Skip to content

Example: sign a PDF on the server ​

A record the server produced should say so in a way anyone can check. In this example the server's copy of the form carries a sealed layout: the form's components with a signature block at the foot, and signature settings that say how the record is sealed. The page delivers the envelope, and the endpoint validates it with the sandbox program, then has the PDF program render the layout and prepare a PAdES signature. The program never sees the key: it hands back the bytes to sign, the server signs them with its own key, and the program embeds the value. The page then sends the file back to a second endpoint for the server's verdict on it.

The page ​

There is no server behind these docs. The result under the code is answered by a stand-in in the browser that runs the same programs, from the same built files, over the same form. The endpoint files further down are what a real server runs.

The stand-in signs for real. When the example loads, it makes its own throwaway key pair in the browser and a self-signed certificate for "Intake service (demo)", and signs with those. The key never leaves the page, and a reload makes a new pair. No PDF viewer trusts the certificate, so a viewer will say the signer is unknown. A real server signs with its own certificate and keeps its key to itself, in a file, a hardware token or a key service.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Customer intake</title>
    <link rel="stylesheet" href="/datum/datum-form.css">
    <script type="module" src="/datum/datum-form.js"></script>
    <style>#record { width: 100%; height: 640px; border: 1px solid #c8ccd0; }</style>
  </head>
  <body>
    <datum-form id="intake" src="/forms/customer-intake.json" language-switcher></datum-form>

    <!-- Where the PDF the server answers with lands: offered as a file and shown in the page. -->
    <p><a id="save" hidden download="customer-intake-signed.pdf">Save the signed PDF</a></p>
    <pre id="verdict" hidden></pre>
    <iframe id="record" title="The sealed record" hidden></iframe>

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

      // The endpoint validates before anything else; a 422 carries codes, which these word.
      form.messages = {
        required: {
          default: "This field is required.",
          locales: { "fr-CA": "Ce champ est requis." }
        }
      };

      form.addEventListener("datum-submit", ({ detail }) => {
        if (!detail.accepted) return; // the form shows its own validation errors
        detail.waitUntil(deliver(detail));
      });

      // Deliver the envelope. What comes back is the record as a PDF, sealed with the server's own
      // certificate as the layout declares, which a PDF viewer's signature panel can check.
      async function deliver(detail) {
        try {
          const response = await fetch("/api/submissions/sign", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify(detail.submission)
          });
          if (response.status === 422) {
            // { errors: [{ field, code }] }: the server's verdict, worded by the messages above.
            const { errors } = await response.json();
            form.setErrors(errors.map((e) => ({ componentId: e.field ?? undefined, code: e.code })));
            return;
          }
          if (!response.ok) throw new Error(response.statusText);
          const pdf = await response.blob();
          // The bytes as an address the page can show and offer: an iframe draws a PDF in place.
          const url = URL.createObjectURL(pdf);
          Object.assign(document.getElementById("record"), { src: url, hidden: false });
          Object.assign(document.getElementById("save"), { href: url, hidden: false });
          // Back to the server for its verdict: the signature checked, the signer known to be itself.
          const verdict = await fetch("/api/submissions/verify", { method: "POST", headers: { "content-type": "application/pdf" }, body: pdf });
          Object.assign(document.getElementById("verdict"), { textContent: JSON.stringify(await verdict.json(), null, 2), hidden: false });
        } catch {
          form.setErrors([{ code: "delivery.failed", message: "The form could not be sent. Try again." }]);
        }
      }
    </script>
  </body>
</html>
ResultThis page, running. Addresses under /forms//api/ are answered by the example.
What the page did

Nothing yet.

Fill in a name and submit. The signed PDF appears under the form with a link to save it, and the verdict of /api/submissions/verify above it: the signature field, the signer, and whether the digest, the certificate binding and the signature value check out, whether the signature covers the whole file and whether the signer is this server. Save the file and open it in a PDF viewer to see the signature panel; the viewer reports the signer as unknown, which is right for a certificate made a moment ago in your browser.

What the server keeps ​

The page loads the plain form. The server's copy of the definition is the same form with the sealed layout sealed-record added: customer-intake-sealed.json. Its signature settings are:

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

The layout ends in a pdf-signature block named server-signature, which is where the visible signature goes. See Signing for every key of the signature block.

The endpoint ​

Each file is complete. Its first lines say what to install, how to fetch the engine, a WASM build of a JavaScript engine (qjs-wasi.wasm), from its release page, and how to make a self-signed certificate to try with. Beside it the server keeps both programs from the bundle folder, its copy of the form at forms/customer-intake.json (the one with the sealed layout), the fonts at fonts/, and its key and certificate chain at keys/signer.key.pem and keys/signer.cert.pem.

Python (FastAPI) ​

python
# main.py — the endpoint the page delivers to: the submission validated, rendered as a PDF, and signed.
#   pip install fastapi uvicorn wasmtime cryptography
#   curl -LO https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
#   the signing key, a self-signed certificate to try with (production uses the organisation's):
#   mkdir -p keys
#   openssl req -x509 -newkey rsa:2048 -nodes -sha256 -days 3650 -subj "/CN=Intake service/O=Datum" \
#       -keyout keys/signer.key.pem -out keys/signer.cert.pem
#   uvicorn main:app
#
# The PDF is signed the way ISO 32000 and PAdES ask — a signature field, /ByteRange, a CMS
# SignedData — by datum-pdf-program.js, the kernel behind the browser's PDF button, in a QuickJS of
# this process's own. The kernel never sees the key: it prepares the bytes to sign, this process
# signs them with its platform crypto, the kernel embeds the value. Any viewer validates the
# result; the verify endpoint below is how this server tells its own sealed records apart.
import base64
import json
import math
import tempfile
import threading
import time
import urllib.request
import uuid
from datetime import datetime, timezone
from pathlib import Path

from cryptography import x509
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, padding
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response
from wasmtime import Config, Engine, ExitTrap, Linker, Module, Store, Trap, WasiConfig

FORM = json.loads(Path("forms/customer-intake.json").read_text())


# The journey the answers were given through, from this server's own copy of the form: the
# envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
# kernel work the path out again from the values, as the browser did: an answer on a page the
# path skipped is judged hidden, and a form field one of the journey's own fields fills or works
# out counts as asked on that page. None named, or one the form does not have: null, and the
# answers are judged as the whole form, which asks for every required field.
def journey_of(submission: dict):
    named = (submission.get("journey") or {}).get("id")
    return next((j for j in FORM.get("journey", {}).get("journeys", []) if j["id"] == named), None)


# The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, compiled
# once and shared. Every request runs it afresh in a store of its own, so requests need no lock.
config = Config()
config.epoch_interruption = True  # the time budget: a run past its deadline traps
engine = Engine(config)
QJS = Module.from_file(engine, "qjs-wasi.wasm")
linker = Linker(engine)
linker.define_wasi()

# The clock every budget is kept by, one for all the runs at once: a tick every 50 ms; a run's
# deadline is its budget in ticks, plus one for the tick already under way when it started. The
# epoch it advances is the engine's, shared by every store on it, so no run may bump it for
# itself: a timer of the run's own, fired when its budget was spent, would advance the epoch under
# every other run in flight too, and cut short one that had set its deadline a tick earlier — a
# wrong verdict for a submission that was never judged. One clock, and no run can touch another.
TICK = 0.05


def clock() -> None:
    while True:
        time.sleep(TICK)
        engine.increment_epoch()


threading.Thread(target=clock, daemon=True).start()


class SandboxError(Exception):
    """A run that ended without an outcome: a limit cut it off, or a program or rule module would not load."""


def qjs(argv: list, request: str, seconds: float, memory: int) -> str:
    # One run: this directory mounted read-only as /app (the programs), the request on stdin, the
    # answer on stdout — all the run can reach; wasmtime hands it nothing else. The limits are
    # wasmtime's, at the browser's profile: the budget in seconds, the memory in bytes. Runaway
    # recursion exhausts the instance's own stack and traps, which ends the run too.
    out, err = [], []
    with tempfile.NamedTemporaryFile("w", suffix=".json") as stdin:
        stdin.write(request)
        stdin.flush()
        store = Store(engine)
        store.set_limits(memory_size=memory)
        store.set_epoch_deadline(math.ceil(seconds / TICK) + 1)
        wasi = WasiConfig()
        wasi.argv = ["qjs", "--std", *argv]  # --std: the std module, which reads stdin
        wasi.preopen_dir(".", "/app", fs_mutable=False)
        wasi.stdin_file = stdin.name
        wasi.stdout_custom = out.append
        wasi.stderr_custom = err.append
        store.set_wasi(wasi)
        try:
            linker.instantiate(store, QJS).exports(store)["_start"](store)
        except ExitTrap as exit:  # a throw: qjs printed it to stderr and exited 1
            if exit.code != 0:
                raise SandboxError(b"".join(err).decode().strip()) from exit
        except Trap as trap:  # "interrupt": the budget; "stack_overflow": the recursion
            raise SandboxError(f"{trap.trap_code}") from trap
    return b"".join(out).decode().rstrip("\n")


# Validation first, so the PDF prints the sanitized values: what the form defines, nothing else.
VALIDATE = ["-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));"]

# The PDF program, under the document profile; __datum_pdf's promise settles before qjs exits.
# Signing needs a program that lists "signature" in its capabilities.
RENDER = ["-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));"]


# The fonts to embed: the signature's appearance is drawn with the first of them.
def font(id, family, weight, file):
    data = base64.b64encode(Path("fonts", file).read_bytes()).decode("ascii")
    return {"id": id, "family": family, "weight": weight, "style": "normal", "data": data}


FONTS = [font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf")]

# What the Country select shows, resolved here: the program never fetches a data source.
COUNTRIES = [{"value": "CA", "label": "Canada"}, {"value": "US", "label": "United States"}, {"value": "MX", "label": "Mexico"}]

# The server's key and certificate chain. The key stays in this process; the chain rides with the
# request (DER, base64, the signer's certificate first) and ends up in the PDF for any viewer to check.
KEY = serialization.load_pem_private_key(Path("keys/signer.key.pem").read_bytes(), password=None)
CHAIN = x509.load_pem_x509_certificates(Path("keys/signer.cert.pem").read_bytes())
CERTIFICATES = [base64.b64encode(cert.public_bytes(serialization.Encoding.DER)).decode("ascii") for cert in CHAIN]

# The layout says how the record is sealed — which signature block, certified or not, the reason —
# and the request may override any of it. None keeps the layout's say (certify, no changes).
CERTIFY = None

# A timestamp authority (RFC 3161), for a signature that proves when it was made by a third party's
# clock (PAdES-B-T). Empty: none. With a URL, the kernel builds the request, this process posts it,
# and the token goes into the signature; give the layout "timestamp": true so the placeholder has room.
TSA_URL = ""

app = FastAPI()


# The one cryptographic step this server keeps for itself: the DER attributes the kernel prepared,
# signed with the key. An HSM or a cloud KMS signs the same bytes (or "toBeSignedDigest", their SHA-256).
def sign_bytes(data: bytes) -> bytes:
    if isinstance(KEY, ec.EllipticCurvePrivateKey):
        return KEY.sign(data, ec.ECDSA(hashes.SHA256()))
    return KEY.sign(data, padding.PKCS1v15(), hashes.SHA256())


def verify_bytes(public_key_der: bytes, data: bytes, signature: bytes) -> bool:
    key = serialization.load_der_public_key(public_key_der)
    try:
        if isinstance(key, ec.EllipticCurvePublicKey):
            key.verify(signature, data, ec.ECDSA(hashes.SHA256()))
        else:
            key.verify(signature, data, padding.PKCS1v15(), hashes.SHA256())
        return True
    except InvalidSignature:
        return False


@app.post("/api/submissions/sign")
def submit(envelope: dict):
    submission = envelope["submission"]
    locale = submission.get("locale", "en")
    # The journey, if the answers came through one: the path is worked out again from the values (see journey_of).
    context = {"formId": FORM["id"], "form": FORM["root"], "values": submission["values"], "locale": locale, "journey": journey_of(submission), "optionSnapshot": {"countries": COUNTRIES}}
    outcome = json.loads(qjs(VALIDATE, json.dumps(context), 0.25, 32 * 1024 * 1024))
    if outcome["errors"]:  # 422 with codes and fields, never text; the page's messages word them
        errors = [{"field": e.get("componentId"), "code": e["code"]} for e in outcome["errors"]]
        return JSONResponse(status_code=422, content={"errors": errors})
    # The record, rendered and prepared for signing in one call: the layout's signature settings
    # plus these certificates. The answer's "bytes" carry the placeholder; "signing" says what to sign.
    signature = {"certificates": CERTIFICATES}
    if CERTIFY is not None:
        signature["certify"] = CERTIFY
    prepared = render({
        "abi": "4.0.0",
        "op": "document",
        "form": FORM["root"],
        "pdf": FORM["pdf"],  # the sealed layout, as designed in the builder's PDF mode
        "values": outcome["values"],
        "locale": locale,
        "optionSnapshot": {"country": COUNTRIES},
        "fonts": FONTS,
        "signature": signature,
        # The only time and identity the program ever sees; the signature's /M is this instant.
        "env": {"createdAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"), "documentId": str(uuid.uuid4())},
    })
    if not prepared["ok"]:  # {"code": "signature" | "font" | "layout" | "internal", "message": ...}
        return JSONResponse(status_code=500, content={"error": prepared["error"]})
    handoff = prepared["signing"]
    value = sign_bytes(base64.b64decode(handoff["toBeSigned"]))
    signing = {"certificates": CERTIFICATES, "value": base64.b64encode(value).decode("ascii"), "toBeSignedDigest": handoff["toBeSignedDigest"]}
    if TSA_URL:
        signing["timestamp"] = {"token": timestamp(value)}
    completed = render({"abi": "4.0.0", "op": "complete", "pdf": {"data": prepared["bytes"]}, "signing": signing})
    if not completed["ok"]:
        return JSONResponse(status_code=500, content={"error": completed["error"]})
    return Response(
        content=base64.b64decode(completed["bytes"]),
        media_type="application/pdf",
        headers={
            "Content-Disposition": 'attachment; filename="customer-intake-signed.pdf"',
            "X-Page-Count": str(prepared["pageCount"]),
            "X-Signed-By": CHAIN[0].subject.rfc4514_string(),
            "X-Signature-Field": completed["field"],
            "X-Timestamped": "true" if completed["timestamped"] else "false",
        },
    )


# A signed PDF back for a verdict: which signatures it carries, whether each still matches the
# bytes, whether the value checks out under the signer's key, and whether the signer is this server.
@app.post("/api/submissions/verify")
async def verify(request: Request):
    pdf = base64.b64encode(await request.body()).decode("ascii")
    report = render({"abi": "4.0.0", "op": "verify", "pdf": {"data": pdf}})
    if not report["ok"]:
        return JSONResponse(status_code=400, content={"error": report["error"]})
    verdicts = []
    for sig in report["signatures"]:
        signer = sig["signer"]
        valid = bool(signer) and verify_bytes(base64.b64decode(signer["publicKey"]), base64.b64decode(sig["toBeVerified"]), base64.b64decode(sig["signature"]))
        verdicts.append({
            "field": sig["field"],
            "signer": signer["subject"] if signer else None,
            "signingTime": sig["signingTime"],
            "digestMatches": sig["digestMatches"],  # the file still hashes to what was signed
            "certificateMatches": sig["certificateMatches"],  # the signed attributes name this certificate
            "signatureValid": valid,  # the value checks out under the signer's public key
            "coversDocument": sig["coversDocument"],  # nothing was appended after this signature
            "trusted": bool(signer) and signer["certificate"] == CERTIFICATES[0],  # the signer is this server
            "certification": sig["certification"],
            "timestamp": sig.get("timestamp"),
        })
    # The files the signature sealed, by digest: what a record's JSON must hash to.
    return {"signatures": verdicts, "attachments": report["attachments"]}


def timestamp(value: bytes) -> str:
    tsq = render({"abi": "4.0.0", "op": "timestampRequest", "signature": base64.b64encode(value).decode("ascii")})["request"]
    request = urllib.request.Request(TSA_URL, data=base64.b64decode(tsq), headers={"Content-Type": "application/timestamp-query"})
    with urllib.request.urlopen(request, timeout=10) as response:
        return base64.b64encode(response.read()).decode("ascii")


def render(request: dict) -> dict:
    return json.loads(qjs(RENDER, json.dumps(request), 15, 256 * 1024 * 1024))

Java (Spring Boot) ​

java
// Application.java — the endpoint the page delivers to: the submission validated, rendered as a PDF, and signed.
//   pom.xml beside it: Spring Boot, and Endive with its Maven plugin, which compiles the engine in.
//   curl -Lo src/main/resources/qjs-wasi.wasm https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
//   mvn spring-boot:run
//
//   the signing key, a self-signed certificate to try with (production uses the organisation's):
//   mkdir -p keys
//   openssl req -x509 -newkey rsa:2048 -nodes -sha256 -days 3650 -subj "/CN=Intake service/O=Datum" \
//       -keyout keys/signer.key.pem -out keys/signer.cert.pem
// The PDF is signed the way ISO 32000 and PAdES ask — a signature field, /ByteRange, a CMS
// SignedData — by datum-pdf-program.js, the kernel behind the browser's PDF button, in a QuickJS of
// this process's own. The kernel never sees the key: it prepares the bytes to sign, this process
// signs them with java.security, the kernel embeds the value. Any viewer validates the result;
// the verify endpoint below is how this server tells its own sealed records apart.
package datum;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import run.endive.runtime.ImportValues;
import run.endive.wasi.WasiExitException;
import run.endive.wasi.WasiOptions;
import run.endive.wasi.WasiPreview1;
import run.endive.wasm.types.MemoryLimits;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.node.ObjectNode;

@SpringBootApplication
@RestController
public class Application {

    static final JsonMapper JSON = JsonMapper.shared();
    static final JsonNode FORM = JSON.readTree(text("forms/customer-intake.json"));

    // The journey the answers were given through, from this server's own copy of the form: the
    // envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
    // kernel work the path out again from the values, as the browser did: an answer on a page the
    // path skipped is judged hidden, and a form field one of the journey's own fields fills or works
    // out counts as asked on that page. None named, or one the form does not have: null, and the
    // answers are judged as the whole form, which asks for every required field.
    static JsonNode journeyOf(JsonNode submission) {
        for (JsonNode journey : FORM.path("journey").path("journeys")) {
            if (journey.path("id").equals(submission.path("journey").path("id"))) {
                return journey;
            }
        }
        return null;  // set as JSON null: no journey
    }

    // The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, compiled once,
    // at build time, by Endive's plugin (see pom.xml) into the class Qjs — native code where the platform
    // has it, JVM bytecode where not. Every request runs it afresh in an instance of its own, so requests
    // need no lock. The module's own initial memory, which a limit must keep.
    static final int QJS_PAGES = Qjs.load().memorySection().get().getMemory(0).limits().initialPages();

    // What a run can reach: one in-memory directory holding the two programs, and nothing else — not this
    // directory, not the disk. Endive mounts any java.nio path, and Jimfs makes one.
    static final Path APP = programs();

    static Path programs() {
        try {
            var app = Files.createDirectories(Jimfs.newFileSystem(Configuration.unix()).getPath("/app"));
            for (var name : List.of("datum-sandbox-program.js", "datum-pdf-program.js")) {
                Files.copy(Path.of(name), app.resolve(name));
            }
            return app;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    static {
        // A JVM's first runs are slow until its JIT has compiled the runner's own setup, several times
        // over what they settle to: pay for that at start, not on the first requests.
        for (int i = 0; i < 3; i++) {
            try {
                qjs(List.of("-e", "0"), "", 30, 32 * 1024 * 1024);
            } catch (SandboxException ignored) {
                // the budget is wide; a failure here shows on the first request instead
            }
        }
    }

    /** A run that ended without an outcome: a limit cut it off, or a program or rule module would not load. */
    static class SandboxException extends Exception {
        SandboxException(String message) {
            super(message);
        }
    }

    static String qjs(List<String> argv, String request, double seconds, int memory) throws SandboxException {
        // One run: the programs mounted as /app, the request on stdin, the answer on stdout — all the run can
        // reach; Endive hands it nothing else. The limits are Endive's, at the browser's profile: the budget in
        // seconds — past it the run is interrupted, native or bytecode — and the memory in bytes. The budget
        // is this run's alone, a Future of its own cancelled at the timeout, so a run past it interrupts no
        // other: there is no engine-wide clock here, as there is under wasmtime (see main.py). Runaway
        // recursion exhausts the instance's own stack and traps, which ends the run too.
        var out = new ByteArrayOutputStream();
        var err = new ByteArrayOutputStream();
        var args = new ArrayList<>(List.of("qjs", "--std"));  // --std: the std module, which reads stdin
        args.addAll(argv);
        var options = WasiOptions.builder()
                .withArguments(args)
                .withDirectory("/app", APP)
                .withStdin(new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8)))
                .withStdout(out)
                .withStderr(err)
                .build();
        var worker = Executors.newSingleThreadExecutor();
        try (var wasi = WasiPreview1.builder().withOptions(options).build()) {
            var imports = ImportValues.builder().addFunction(wasi.toHostFunctions()).build();
            var run = worker.submit(() -> {
                // Building the instance runs _start: qjs's main, through to its exit.
                try (var instance = Qjs.builder()
                        .withImportValues(imports)
                        .withMemoryLimits(new MemoryLimits(QJS_PAGES, memory / 65536))
                        .build()) {
                    return null;
                }
            });
            try {
                run.get((long) (seconds * 1000), TimeUnit.MILLISECONDS);
            } catch (TimeoutException budget) {
                run.cancel(true);  // the interrupt that ends the run
                throw new SandboxException("interrupt");
            }
        } catch (ExecutionException failed) {
            var cause = failed.getCause();
            if (cause instanceof WasiExitException exit) {  // a throw: qjs printed it to stderr and exited 1
                if (exit.exitCode() != 0) {
                    throw new SandboxException(err.toString(StandardCharsets.UTF_8).strip());
                }
            } else {  // a trap: "call stack exhausted", "out of bounds memory access"
                throw new SandboxException(cause.getMessage());
            }
        } catch (InterruptedException interrupted) {
            Thread.currentThread().interrupt();
            throw new SandboxException("interrupted");
        } finally {
            worker.shutdownNow();
        }
        return out.toString(StandardCharsets.UTF_8).stripTrailing();
    }

    static String text(String file) {
        try {
            return Files.readString(Path.of(file));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    // Validation first, so the PDF prints the sanitized values: what the form defines, nothing else.
    static final List<String> VALIDATE = List.of("-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));");

    // The PDF program, under the document profile; __datum_pdf's promise settles before qjs exits.
    // Signing needs a program that lists "signature" in its capabilities.
    static final List<String> RENDER = List.of("-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));");

    // The fonts to embed: the signature's appearance is drawn with the first of them.
    static Map<String, Object> font(String id, String family, int weight, String file) {
        return Map.of("id", id, "family", family, "weight", weight, "style", "normal", "data", base64("fonts/" + file));
    }

    static final List<Map<String, Object>> FONTS = List.of(font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf"));

    // What the Country select shows, resolved here: the program never fetches a data source.
    static final List<Map<String, String>> COUNTRIES = List.of(
            Map.of("value", "CA", "label", "Canada"), Map.of("value", "US", "label", "United States"), Map.of("value", "MX", "label", "Mexico"));

    // The instant as the program takes it, to the second: the same request gives the same bytes.
    static final DateTimeFormatter CREATED_AT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'.000Z'").withZone(ZoneOffset.UTC);

    // The server's key and certificate chain. The key stays in this process; the chain rides with the
    // request (DER, base64, the signer's certificate first) and ends up in the PDF for any viewer to check.
    static final PrivateKey KEY = privateKey("keys/signer.key.pem");
    static final List<X509Certificate> CHAIN = certificates("keys/signer.cert.pem");
    static final List<String> CERTIFICATES = CHAIN.stream().map(Application::encoded).toList();

    // The layout says how the record is sealed — which signature block, certified or not, the reason —
    // and the request may override any of it. Null keeps the layout's say (certify, no changes).
    static final Object CERTIFY = null;

    // A timestamp authority (RFC 3161), for a signature that proves when it was made by a third party's
    // clock (PAdES-B-T). Empty: none. With a URL, the kernel builds the request, this process posts it,
    // and the token goes into the signature; give the layout "timestamp": true so the placeholder has room.
    static final String TSA_URL = "";

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    record FieldError(String field, String code) {}

    @PostMapping("/api/submissions/sign")
    public ResponseEntity<?> submit(@RequestBody JsonNode envelope) throws Exception {
        var submission = envelope.path("submission");
        var locale = submission.path("locale").asString("en");
        var context = JSON.createObjectNode()
                .put("formId", FORM.path("id").asString())
                .set("form", FORM.path("root"))
                .set("values", submission.path("values"))
                .put("locale", locale)
                .set("optionSnapshot", JSON.valueToTree(Map.of("countries", COUNTRIES)))  // the lists a choice's data source holds, by source id
                .set("journey", journeyOf(submission));  // the path, worked out again from the values (see journeyOf)
        var outcome = JSON.readTree(qjs(VALIDATE, JSON.writeValueAsString(context), 5, 32 * 1024 * 1024));
        if (!outcome.path("errors").isEmpty()) {  // 422 with codes and fields, never text; the page's messages word them
            var errors = new ArrayList<FieldError>();
            for (JsonNode e : outcome.path("errors")) {
                errors.add(new FieldError(e.path("componentId").asString(null), e.path("code").asString()));
            }
            return ResponseEntity.status(422).body(Map.of("errors", errors));
        }
        // The record, rendered and prepared for signing in one call: the layout's signature settings
        // plus these certificates. The answer's "bytes" carry the placeholder; "signing" says what to sign.
        var signature = new LinkedHashMap<String, Object>();
        signature.put("certificates", CERTIFICATES);
        if (CERTIFY != null) {
            signature.put("certify", CERTIFY);
        }
        var prepared = render(JSON.createObjectNode()
                .put("abi", "4.0.0")
                .put("op", "document")
                .set("form", FORM.path("root"))
                .set("pdf", FORM.path("pdf"))  // the sealed layout, as designed in the builder's PDF mode
                .set("values", outcome.path("values"))
                .put("locale", locale)
                .set("optionSnapshot", JSON.valueToTree(Map.of("country", COUNTRIES)))
                .set("fonts", JSON.valueToTree(FONTS))
                .set("signature", JSON.valueToTree(signature))
                // The only time and identity the program ever sees; the signature's /M is this instant.
                .set("env", JSON.valueToTree(Map.of("createdAt", CREATED_AT.format(Instant.now()), "documentId", UUID.randomUUID().toString()))));
        if (!prepared.path("ok").asBoolean()) {  // {"code": "signature" | "font" | "layout" | "internal", "message": ...}
            return ResponseEntity.status(500).body(Map.of("error", prepared.path("error")));
        }
        var handoff = prepared.path("signing");
        var value = signBytes(Base64.getDecoder().decode(handoff.path("toBeSigned").asString()));
        var signing = JSON.createObjectNode()
                .set("certificates", JSON.valueToTree(CERTIFICATES))
                .put("value", Base64.getEncoder().encodeToString(value))
                .put("toBeSignedDigest", handoff.path("toBeSignedDigest").asString());
        if (!TSA_URL.isEmpty()) {
            signing.set("timestamp", JSON.valueToTree(Map.of("token", timestamp(value))));
        }
        var completed = render(JSON.createObjectNode()
                .put("abi", "4.0.0")
                .put("op", "complete")
                .set("pdf", JSON.valueToTree(Map.of("data", prepared.path("bytes").asString())))
                .set("signing", signing));
        if (!completed.path("ok").asBoolean()) {
            return ResponseEntity.status(500).body(Map.of("error", completed.path("error")));
        }
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"customer-intake-signed.pdf\"")
                .header("X-Page-Count", String.valueOf(prepared.path("pageCount").asInt()))
                .header("X-Signed-By", CHAIN.get(0).getSubjectX500Principal().getName())
                .header("X-Signature-Field", completed.path("field").asString())
                .header("X-Timestamped", String.valueOf(completed.path("timestamped").asBoolean()))
                .body(Base64.getDecoder().decode(completed.path("bytes").asString()));
    }

    // A signed PDF back for a verdict: which signatures it carries, whether each still matches the
    // bytes, whether the value checks out under the signer's key, and whether the signer is this server.
    @PostMapping(value = "/api/submissions/verify", consumes = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<?> verify(@RequestBody byte[] pdf) throws Exception {
        var report = render(JSON.createObjectNode()
                .put("abi", "4.0.0")
                .put("op", "verify")
                .set("pdf", JSON.valueToTree(Map.of("data", Base64.getEncoder().encodeToString(pdf)))));
        if (!report.path("ok").asBoolean()) {
            return ResponseEntity.status(400).body(Map.of("error", report.path("error")));
        }
        var verdicts = new ArrayList<Map<String, Object>>();
        for (JsonNode sig : report.path("signatures")) {
            var signer = sig.path("signer");
            var known = !signer.isNull() && !signer.isMissingNode();
            var decoder = Base64.getDecoder();
            var valid = known && verifyBytes(decoder.decode(signer.path("publicKey").asString()), decoder.decode(sig.path("toBeVerified").asString()), decoder.decode(sig.path("signature").asString()));
            var verdict = new LinkedHashMap<String, Object>();
            verdict.put("field", sig.path("field").asString());
            verdict.put("signer", known ? signer.path("subject").asString() : null);
            verdict.put("signingTime", sig.path("signingTime").asString(null));
            verdict.put("digestMatches", sig.path("digestMatches").asBoolean());  // the file still hashes to what was signed
            verdict.put("certificateMatches", sig.path("certificateMatches").asBoolean());  // the signed attributes name this certificate
            verdict.put("signatureValid", valid);  // the value checks out under the signer's public key
            verdict.put("coversDocument", sig.path("coversDocument").asBoolean());  // nothing was appended after this signature
            verdict.put("trusted", known && CERTIFICATES.get(0).equals(signer.path("certificate").asString()));  // the signer is this server
            verdict.put("certification", sig.path("certification"));
            verdict.put("timestamp", sig.path("timestamp"));
            verdicts.add(verdict);
        }
        // The files the signature sealed, by digest: what a record's JSON must hash to.
        return ResponseEntity.ok(Map.of("signatures", verdicts, "attachments", report.path("attachments")));
    }

    // The one cryptographic step this server keeps for itself: the DER attributes the kernel prepared,
    // signed with the key. An HSM or a cloud KMS signs the same bytes (or "toBeSignedDigest", their SHA-256).
    static byte[] signBytes(byte[] data) throws Exception {
        var signature = Signature.getInstance(KEY.getAlgorithm().equals("EC") ? "SHA256withECDSA" : "SHA256withRSA");
        signature.initSign(KEY);
        signature.update(data);
        return signature.sign();
    }

    static boolean verifyBytes(byte[] spki, byte[] data, byte[] value) throws Exception {
        PublicKey key;
        try {
            key = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(spki));
        } catch (Exception notRsa) {
            key = KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(spki));
        }
        var signature = Signature.getInstance(key.getAlgorithm().equals("EC") ? "SHA256withECDSA" : "SHA256withRSA");
        signature.initVerify(key);
        signature.update(data);
        return signature.verify(value);
    }

    static String timestamp(byte[] value) throws Exception {
        var tsq = render(JSON.createObjectNode().put("abi", "4.0.0").put("op", "timestampRequest").put("signature", Base64.getEncoder().encodeToString(value)));
        var request = HttpRequest.newBuilder(URI.create(TSA_URL))
                .header("Content-Type", "application/timestamp-query")
                .POST(HttpRequest.BodyPublishers.ofByteArray(Base64.getDecoder().decode(tsq.path("request").asString())))
                .build();
        var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofByteArray());
        return Base64.getEncoder().encodeToString(response.body());
    }

    static PrivateKey privateKey(String file) {
        var pem = text(file).replaceAll("-----[A-Z ]+-----", "").replaceAll("\\s", "");
        var spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(pem));
        try {
            return KeyFactory.getInstance("RSA").generatePrivate(spec);
        } catch (Exception notRsa) {
            try {
                return KeyFactory.getInstance("EC").generatePrivate(spec);
            } catch (Exception e) {
                throw new IllegalStateException("the signing key is neither RSA nor EC", e);
            }
        }
    }

    static List<X509Certificate> certificates(String file) {
        try {
            var factory = CertificateFactory.getInstance("X.509");
            return factory.generateCertificates(new ByteArrayInputStream(Files.readAllBytes(Path.of(file)))).stream().map(X509Certificate.class::cast).toList();
        } catch (Exception e) {
            throw new IllegalStateException("the certificate chain could not be read", e);
        }
    }

    static String encoded(X509Certificate certificate) {
        try {
            return Base64.getEncoder().encodeToString(certificate.getEncoded());
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    static JsonNode render(ObjectNode request) throws SandboxException {
        return JSON.readTree(qjs(RENDER, JSON.writeValueAsString(request), 15, 256 * 1024 * 1024));
    }

    static String base64(String file) {
        try {
            return Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of(file)));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
xml
<!-- pom.xml — beside Application.java. Spring Boot for the endpoint; Endive, the Bytecode Alliance's
     WebAssembly runtime for the JVM, for the engine: its Maven plugin compiles qjs-wasi.wasm at build
     time — to native code through Redline (Cranelift, the code generator behind wasmtime) for the six
     platforms it knows, and to JVM bytecode as the fallback for any other — into the class datum.Qjs,
     packaged in the jar. No native library to install, no JNI: the jar runs wherever a JDK does. Redline
     is experimental in Endive 1.1.0; the bytecode runs the same program the same way, more slowly. -->
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.1.1</version>
  </parent>
  <groupId>example</groupId>
  <artifactId>intake</artifactId>
  <version>1.0.0</version>
  <properties>
    <!-- The native runner uses the Panama FFM API, so Java 25; on 17 to 24, redline-runner-jffi-experimental instead. -->
    <java.version>25</java.version>
    <endive.version>1.1.0</endive.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>
    <!-- Endive: the WASI layer (stdin, stdout, the mount) and the runner for the native code. -->
    <dependency>
      <groupId>run.endive</groupId>
      <artifactId>wasi</artifactId>
      <version>${endive.version}</version>
    </dependency>
    <dependency>
      <groupId>run.endive</groupId>
      <artifactId>redline-runner-experimental</artifactId>
      <version>${endive.version}</version>
    </dependency>
    <!-- An in-memory file system: the one directory a run is given. -->
    <dependency>
      <groupId>com.google.jimfs</groupId>
      <artifactId>jimfs</artifactId>
      <version>1.3.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <!-- The native runner is a restricted API: without this the JDK warns at the first run. -->
          <jvmArguments>--enable-native-access=ALL-UNNAMED</jvmArguments>
        </configuration>
      </plugin>
      <plugin>
        <groupId>run.endive</groupId>
        <artifactId>endive-compiler-maven-plugin</artifactId>
        <version>${endive.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <name>datum.Qjs</name>
              <wasmFile>src/main/resources/qjs-wasi.wasm</wasmFile>
              <redlineExperimental>true</redlineExperimental>
              <!-- QuickJS's interpreter loop, JS_CallInternal, is too big for one JVM method: the bytecode
                   fallback interprets that one function. The native code has no such limit. -->
              <interpreterFallback>WARN</interpreterFallback>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

C# (ASP.NET Core) ​

csharp
// Program.cs — the endpoint the page delivers to: the submission validated, rendered as a PDF, and signed.
//   intake.csproj beside it: ASP.NET Core, and Wasmtime, the .NET embedding of wasmtime.
//   curl -LO https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
//   dotnet run
//
//   the signing key, a self-signed certificate to try with (production uses the organisation's):
//   mkdir -p keys
//   openssl req -x509 -newkey rsa:2048 -nodes -sha256 -days 3650 -subj "/CN=Intake service/O=Datum" \
//       -keyout keys/signer.key.pem -out keys/signer.cert.pem
// The PDF is signed the way ISO 32000 and PAdES ask — a signature field, /ByteRange, a CMS
// SignedData — by datum-pdf-program.js, the kernel behind the browser's PDF button, in a QuickJS of
// this process's own. The kernel never sees the key: it prepares the bytes to sign, this process
// signs them with System.Security.Cryptography, the kernel embeds the value. Any viewer validates
// the result; the verify endpoint below is how this server tells its own sealed records apart.
using System.Text.Json;
using System.Text.Json.Nodes;
using Wasmtime;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

var form = JsonNode.Parse(File.ReadAllText("forms/customer-intake.json"))!;

// The journey the answers were given through, from this server's own copy of the form: the
// envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
// kernel work the path out again from the values, as the browser did: an answer on a page the
// path skipped is judged hidden, and a form field one of the journey's own fields fills or works
// out counts as asked on that page. None named, or one the form does not have: null, and the
// answers are judged as the whole form, which asks for every required field.
JsonNode? JourneyOf(JsonNode submission) =>
    form["journey"]?["journeys"]?.AsArray().FirstOrDefault(journey => (string?)journey!["id"] == (string?)submission["journey"]?["id"]);

// The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, compiled
// once, now, and shared (the Sandbox class below). Every request runs it afresh in a store of its
// own, so requests need no lock.
var sandbox = new Sandbox();

// Validation first, so the PDF prints the sanitized values: what the form defines, nothing else.
string[] validate = ["-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));"];

// The PDF program, under the document profile; __datum_pdf's promise settles before qjs exits.
// Signing needs a program that lists "signature" in its capabilities.
string[] render = ["-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));"];

// The fonts to embed: the signature's appearance is drawn with the first of them.
static object Font(string id, string family, int weight, string file) =>
    new { id, family, weight, style = "normal", data = Convert.ToBase64String(File.ReadAllBytes(Path.Combine("fonts", file))) };

object[] fonts = [Font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), Font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf")];

// What the Country select shows, resolved here: the program never fetches a data source.
object[] countries = [new { value = "CA", label = "Canada" }, new { value = "US", label = "United States" }, new { value = "MX", label = "Mexico" }];

// The server's key and certificate chain. The key stays in this process; the chain rides with the
// request (DER, base64, the signer's certificate first) and ends up in the PDF for any viewer to check.
var signer = X509Certificate2.CreateFromPemFile("keys/signer.cert.pem", "keys/signer.key.pem");
var chain = new X509Certificate2Collection();
chain.ImportFromPemFile("keys/signer.cert.pem");
string[] certificates = [.. chain.Select(certificate => Convert.ToBase64String(certificate.RawData))];

// The layout says how the record is sealed — which signature block, certified or not, the reason —
// and the request may override any of it. Null keeps the layout's say (certify, no changes).
object? certify = null;

// A timestamp authority (RFC 3161), for a signature that proves when it was made by a third party's
// clock (PAdES-B-T). Empty: none. With a URL, the kernel builds the request, this process posts it,
// and the token goes into the signature; give the layout "timestamp": true so the placeholder has room.
var tsaUrl = "";

var app = WebApplication.CreateBuilder(args).Build();

app.MapPost("/api/submissions/sign", async (JsonNode envelope, HttpContext http) =>
{
    var submission = envelope["submission"]!;
    var locale = (string?)submission["locale"] ?? "en";
    // The journey, if the answers came through one: the path is worked out again from the values (see JourneyOf).
    var context = JsonSerializer.Serialize(new { formId = form["id"], form = form["root"], values = submission["values"], locale, journey = JourneyOf(submission), optionSnapshot = new { countries } });
    var outcome = JsonNode.Parse(sandbox.Run(validate, context, 0.25, 32 * 1024 * 1024))!;
    if (outcome["errors"]!.AsArray().Count > 0)  // 422 with codes and fields, never text; the page's messages word them
    {
        var errors = outcome["errors"]!.AsArray().Select(e => new { field = (string?)e!["componentId"], code = (string?)e["code"] });
        return Results.Json(new { errors }, statusCode: 422);
    }
    // The record, rendered and prepared for signing in one call: the layout's signature settings
    // plus these certificates. The answer's "bytes" carry the placeholder; "signing" says what to sign.
    var signature = new Dictionary<string, object?> { ["certificates"] = certificates };
    if (certify is not null)
    {
        signature["certify"] = certify;
    }
    var prepared = Render(new Dictionary<string, object?>
    {
        ["abi"] = "4.0.0",
        ["op"] = "document",
        ["form"] = form["root"],
        ["pdf"] = form["pdf"],  // the sealed layout, as designed in the builder's PDF mode
        ["values"] = outcome["values"],
        ["locale"] = locale,
        ["optionSnapshot"] = new { country = countries },
        ["fonts"] = fonts,
        ["signature"] = signature,
        // The only time and identity the program ever sees; the signature's /M is this instant.
        ["env"] = new { createdAt = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'.000Z'"), documentId = Guid.NewGuid().ToString() }
    });
    if (!(bool)prepared["ok"]!)  // {"code": "signature" | "font" | "layout" | "internal", "message": ...}
    {
        return Results.Json(new { error = prepared["error"] }, statusCode: 500);
    }
    var handoff = prepared["signing"]!;
    var value = SignBytes(Convert.FromBase64String((string)handoff["toBeSigned"]!));
    var signing = new Dictionary<string, object?>
    {
        ["certificates"] = certificates,
        ["value"] = Convert.ToBase64String(value),
        ["toBeSignedDigest"] = (string)handoff["toBeSignedDigest"]!
    };
    if (tsaUrl != "")
    {
        signing["timestamp"] = new { token = await Timestamp(value) };
    }
    var completed = Render(new Dictionary<string, object?> { ["abi"] = "4.0.0", ["op"] = "complete", ["pdf"] = new { data = (string)prepared["bytes"]! }, ["signing"] = signing });
    if (!(bool)completed["ok"]!)
    {
        return Results.Json(new { error = completed["error"] }, statusCode: 500);
    }
    http.Response.Headers["X-Page-Count"] = ((int)prepared["pageCount"]!).ToString();
    http.Response.Headers["X-Signed-By"] = signer.SubjectName.Name;
    http.Response.Headers["X-Signature-Field"] = (string)completed["field"]!;
    http.Response.Headers["X-Timestamped"] = ((bool)completed["timestamped"]!).ToString().ToLowerInvariant();
    return Results.File(Convert.FromBase64String((string)completed["bytes"]!), "application/pdf", "customer-intake-signed.pdf");
});

// A signed PDF back for a verdict: which signatures it carries, whether each still matches the
// bytes, whether the value checks out under the signer's key, and whether the signer is this server.
app.MapPost("/api/submissions/verify", async (HttpRequest request) =>
{
    using var body = new MemoryStream();
    await request.Body.CopyToAsync(body);
    var report = Render(new Dictionary<string, object?> { ["abi"] = "4.0.0", ["op"] = "verify", ["pdf"] = new { data = Convert.ToBase64String(body.ToArray()) } });
    if (!(bool)report["ok"]!)
    {
        return Results.Json(new { error = report["error"] }, statusCode: 400);
    }
    var verdicts = report["signatures"]!.AsArray().Select(sig =>
    {
        var signer = sig!["signer"];
        var valid = signer is not null && VerifyBytes(Convert.FromBase64String((string)signer["publicKey"]!), Convert.FromBase64String((string)sig["toBeVerified"]!), Convert.FromBase64String((string)sig["signature"]!));
        return new
        {
            field = (string)sig["field"]!,
            signer = signer is null ? null : (string?)signer["subject"],
            signingTime = (string?)sig["signingTime"],
            digestMatches = (bool)sig["digestMatches"]!,  // the file still hashes to what was signed
            certificateMatches = (bool)sig["certificateMatches"]!,  // the signed attributes name this certificate
            signatureValid = valid,  // the value checks out under the signer's public key
            coversDocument = (bool)sig["coversDocument"]!,  // nothing was appended after this signature
            trusted = signer is not null && (string?)signer["certificate"] == certificates[0],  // the signer is this server
            certification = sig["certification"],
            timestamp = sig["timestamp"]
        };
    });
    // The files the signature sealed, by digest: what a record's JSON must hash to.
    return Results.Json(new { signatures = verdicts, attachments = report["attachments"] });
});

app.Run();

// The one cryptographic step this server keeps for itself: the DER attributes the kernel prepared,
// signed with the key. An HSM or a cloud KMS signs the same bytes (or "toBeSignedDigest", their SHA-256).
byte[] SignBytes(byte[] data)
{
    using var ecdsa = signer.GetECDsaPrivateKey();
    if (ecdsa is not null)
    {
        return ecdsa.SignData(data, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
    }
    using var rsa = signer.GetRSAPrivateKey()!;
    return rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}

bool VerifyBytes(byte[] spki, byte[] data, byte[] value)
{
    try
    {
        using var rsa = RSA.Create();
        rsa.ImportSubjectPublicKeyInfo(spki, out _);
        return rsa.VerifyData(data, value, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
    }
    catch (CryptographicException)
    {
        using var ecdsa = ECDsa.Create();
        ecdsa.ImportSubjectPublicKeyInfo(spki, out _);
        return ecdsa.VerifyData(data, value, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
    }
}

async Task<string> Timestamp(byte[] value)
{
    var tsq = Render(new Dictionary<string, object?> { ["abi"] = "4.0.0", ["op"] = "timestampRequest", ["signature"] = Convert.ToBase64String(value) });
    using var client = new HttpClient();
    var content = new ByteArrayContent(Convert.FromBase64String((string)tsq["request"]!));
    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/timestamp-query");
    var response = await client.PostAsync(tsaUrl, content);
    response.EnsureSuccessStatusCode();
    return Convert.ToBase64String(await response.Content.ReadAsByteArrayAsync());
}

JsonNode Render(Dictionary<string, object?> request) =>
    JsonNode.Parse(sandbox.Run(render, JsonSerializer.Serialize(request), 15, 256 * 1024 * 1024))!;

/// <summary>A run that ended without an outcome: a limit cut it off, or a program or rule module would not load.</summary>
class SandboxException(string message) : Exception(message);

/// <summary>The engine, compiled once as the process starts, and one run of it per request.</summary>
class Sandbox
{
    readonly Engine engine = new(new Config().WithEpochInterruption(true));  // the time budget: a run past its deadline traps
    readonly Module qjs;
    readonly Linker linker;

    // The clock every budget is kept by, one for all the runs at once: a tick every 50 ms; a run's
    // deadline is its budget in ticks, plus one for the tick already under way when it started. The
    // epoch it advances is the engine's, shared by every store on it, so no run may bump it for
    // itself: a timer of the run's own, fired when its budget was spent, would advance the epoch under
    // every other run in flight too, and cut short one that had set its deadline a tick earlier — a
    // wrong verdict for a submission that was never judged. One clock, and no run can touch another.
    static readonly TimeSpan Tick = TimeSpan.FromSeconds(0.05);
    readonly Timer clock;

    public Sandbox()
    {
        qjs = Module.FromFile(engine, "qjs-wasi.wasm");
        linker = new Linker(engine);
        linker.DefineWasi();
        clock = new Timer(_ => engine.IncrementEpoch(), null, Tick, Tick);
    }

    public string Run(string[] argv, string request, double seconds, long memory)
    {
        // One run: this directory mounted read-only as /app (the programs), the request on stdin, the
        // answer on stdout — all the run can reach; wasmtime hands it nothing else. The limits are
        // wasmtime's, at the browser's profile: the budget in seconds, the memory in bytes. Runaway
        // recursion exhausts the instance's own stack and traps, which ends the run too. WASI's
        // standard streams are files here: the request goes in as one, the answer comes back as one.
        var stdin = Path.GetTempFileName();
        var stdout = Path.GetTempFileName();
        var stderr = Path.GetTempFileName();
        try
        {
            File.WriteAllText(stdin, request);
            string[] args = ["qjs", "--std", .. argv];  // --std: the std module, which reads stdin
            using var store = new Store(engine);
            store.SetLimits(memorySize: memory);
            store.SetEpochDeadline((ulong)Math.Ceiling(seconds / Tick.TotalSeconds) + 1);
            store.SetWasiConfiguration(new WasiConfiguration()
                .WithArgs(args)
                .WithPreopenedDirectory(".", "/app", WasiDirectoryPermissions.Read, WasiFilePermissions.Read)
                .WithStandardInput(stdin)
                .WithStandardOutput(stdout)
                .WithStandardError(stderr));
            try
            {
                linker.Instantiate(store, qjs).GetFunction("_start")!.Invoke();
            }
            catch (WasmtimeException exit) when (exit.ExitCode is int code)  // a throw: qjs printed it to stderr and exited 1
            {
                if (code != 0)
                {
                    throw new SandboxException(File.ReadAllText(stderr).Trim());
                }
            }
            catch (TrapException trap)  // Interrupt: the budget; StackOverflow: the recursion
            {
                throw new SandboxException(trap.Type.ToString());
            }
            return File.ReadAllText(stdout).TrimEnd('\n');
        }
        finally
        {
            File.Delete(stdin);
            File.Delete(stdout);
            File.Delete(stderr);
        }
    }
}
xml
<!-- intake.csproj — beside Program.cs. ASP.NET Core for the endpoint; Wasmtime, the Bytecode Alliance's
     .NET embedding of wasmtime, for the engine: the runtime main.py runs under, as a NuGet package that
     carries its native library for Windows, macOS and Linux on x64 and arm64. Nothing else to install. -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Wasmtime" Version="44.0.0" />
  </ItemGroup>
</Project>

Node.js (Express) ​

js
// main.mjs — the endpoint the page delivers to: the submission validated, rendered as a PDF, and signed.
//   qjs.mjs beside it: the engine, one process per run — Node 22 or later, nothing to install for it.
//   npm install express
//   curl -LO https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
//   node main.mjs
//
//   the signing key, a self-signed certificate to try with (production uses the organisation's):
//   mkdir -p keys
//   openssl req -x509 -newkey rsa:2048 -nodes -sha256 -days 3650 -subj "/CN=Intake service/O=Datum" \
//       -keyout keys/signer.key.pem -out keys/signer.cert.pem
// The PDF is signed the way ISO 32000 and PAdES ask — a signature field, /ByteRange, a CMS
// SignedData — by datum-pdf-program.js, the kernel behind the browser's PDF button, in a QuickJS of
// this process's own. The kernel never sees the key: it prepares the bytes to sign, this process
// signs them with node:crypto, the kernel embeds the value. Any viewer validates the result; the
// verify endpoint below is how this server tells its own sealed records apart.
import { spawn } from "node:child_process";
import { X509Certificate, createPrivateKey, createPublicKey, randomUUID, sign, verify } from "node:crypto";
import { copyFileSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";

import express from "express";

const FORM = JSON.parse(readFileSync("forms/customer-intake.json", "utf8"));

// The journey the answers were given through, from this server's own copy of the form: the
// envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
// kernel work the path out again from the values, as the browser did: an answer on a page the
// path skipped is judged hidden, and a form field one of the journey's own fields fills or works
// out counts as asked on that page. None named, or one the form does not have: null, and the
// answers are judged as the whole form, which asks for every required field.
const journeyOf = (submission) => FORM.journey?.journeys?.find((journey) => journey.id === submission.journey?.id) ?? null;

// The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, on V8 with
// node:wasi (qjs.mjs) — nothing to install. Every request runs it in a process of its own, so requests
// need no lock and share nothing: V8 has no store to hang a limit on, as wasmtime has, so the
// operating system draws the line instead, and the flag and the timeout below are that process's.
const RUNNER = fileURLToPath(new URL("qjs.mjs", import.meta.url));

// What a run can reach: one directory holding the two programs, and nothing else — not this
// directory, not the disk. Node's WASI mounts a directory read-write and does not promise the
// sandbox wasmtime's does, so a run is started in a directory of its own with nothing else in it.
const APP = programs();

function programs() {
  const app = mkdtempSync(join(tmpdir(), "datum-"));
  for (const name of ["datum-sandbox-program.js", "datum-pdf-program.js"]) {
    copyFileSync(name, join(app, name));
  }
  // Gone with the process: at its exit, and on the signals that would otherwise end it without one.
  process.on("exit", () => rmSync(app, { recursive: true, force: true }));
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => process.exit());
  return app;
}

/** A run that ended without an outcome: a limit cut it off, or a program or rule module would not load. */
class SandboxError extends Error {}

function qjs(argv, request, seconds, memory) {
  // One run: a process started in the programs' directory, which it mounts as /app, the request on
  // its stdin, the answer on its stdout — all the run can reach; the runner hands it nothing else.
  // The limits are the process's, at the browser's profile: the memory in bytes, as the pages V8
  // lets the module's memory grow to, and the budget in seconds, a timeout that ends the process —
  // this run's alone, so a run past it interrupts no other: there is no engine-wide clock here, as
  // there is under wasmtime (see main.py). The budget counts the process's own start and the
  // module's compilation, a fifth of a second: it is a bound on a runaway rule, not a latency to
  // meet. Runaway recursion ends the run too: QuickJS's own stack check throws, and V8 traps the
  // instance's stack if it does not.
  return new Promise((resolve, reject) => {
    const flags = ["--wasm-max-mem-pages=" + memory / 65536, "--disable-warning=ExperimentalWarning"];
    const run = spawn(process.execPath, [...flags, RUNNER, ...argv], { cwd: APP, timeout: seconds * 1000 });
    const out = [];
    const err = [];
    run.stdout.on("data", (chunk) => out.push(chunk));
    run.stderr.on("data", (chunk) => err.push(chunk));
    run.stdin.on("error", () => {});  // a run that ended before reading its request: what ended it is on stderr
    run.stdin.end(request);
    run.on("error", reject);
    run.on("close", (code, signal) => {
      if (signal !== null) {  // the budget: the timeout ended the process
        reject(new SandboxError("interrupt"));
      } else if (code !== 0) {  // a throw: qjs printed it to stderr and exited 1
        reject(new SandboxError(Buffer.concat(err).toString().trim()));
      } else {
        resolve(Buffer.concat(out).toString().trimEnd());
      }
    });
  });
}

// Validation first, so the PDF prints the sanitized values: what the form defines, nothing else.
const VALIDATE = ["-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));"];

// The PDF program, under the document profile; __datum_pdf's promise settles before qjs exits.
// Signing needs a program that lists "signature" in its capabilities.
const RENDER = ["-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));"];

// The fonts to embed: the signature's appearance is drawn with the first of them.
function font(id, family, weight, file) {
  return { id, family, weight, style: "normal", data: readFileSync(join("fonts", file)).toString("base64") };
}

const FONTS = [font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf")];

// What the Country select shows, resolved here: the program never fetches a data source.
const COUNTRIES = [{ value: "CA", label: "Canada" }, { value: "US", label: "United States" }, { value: "MX", label: "Mexico" }];

// The server's key and certificate chain. The key stays in this process; the chain rides with the
// request (DER, base64, the signer's certificate first) and ends up in the PDF for any viewer to check.
const KEY = createPrivateKey(readFileSync("keys/signer.key.pem"));
const CHAIN = readFileSync("keys/signer.cert.pem", "utf8").split(/(?<=-----END CERTIFICATE-----)/).map((pem) => pem.trim()).filter(Boolean).map((pem) => new X509Certificate(pem));
const CERTIFICATES = CHAIN.map((certificate) => certificate.raw.toString("base64"));

// The layout says how the record is sealed — which signature block, certified or not, the reason —
// and the request may override any of it. Undefined keeps the layout's say (certify, no changes).
const CERTIFY = undefined;

// A timestamp authority (RFC 3161), for a signature that proves when it was made by a third party's
// clock (PAdES-B-T). Empty: none. With a URL, the kernel builds the request, this process posts it,
// and the token goes into the signature; give the layout "timestamp": true so the placeholder has room.
const TSA_URL = "";

const app = express();
app.use(express.json());

app.post("/api/submissions/sign", async (req, res) => {
  const { submission } = req.body;
  const locale = submission.locale ?? "en";
  // The journey, if the answers came through one: the path is worked out again from the values (see journeyOf).
  const context = { formId: FORM.id, form: FORM.root, values: submission.values, locale, journey: journeyOf(submission), optionSnapshot: { countries: COUNTRIES } };
  const outcome = JSON.parse(await qjs(VALIDATE, JSON.stringify(context), 5, 32 * 1024 * 1024));
  if (outcome.errors.length > 0) {  // 422 with codes and fields, never text; the page's messages word them
    const errors = outcome.errors.map((e) => ({ field: e.componentId ?? null, code: e.code }));
    return res.status(422).json({ errors });
  }
  // The record, rendered and prepared for signing in one call: the layout's signature settings
  // plus these certificates. The answer's "bytes" carry the placeholder; "signing" says what to sign.
  const prepared = await render({
    abi: "4.0.0",
    op: "document",
    form: FORM.root,
    pdf: FORM.pdf,  // the sealed layout, as designed in the builder's PDF mode
    values: outcome.values,
    locale,
    optionSnapshot: { country: COUNTRIES },
    fonts: FONTS,
    signature: { certificates: CERTIFICATES, ...(CERTIFY === undefined ? {} : { certify: CERTIFY }) },
    // The only time and identity the program ever sees; the signature's /M is this instant.
    env: { createdAt: new Date().toISOString(), documentId: randomUUID() }
  });
  if (!prepared.ok) {  // {"code": "signature" | "font" | "layout" | "internal", "message": ...}
    return res.status(500).json({ error: prepared.error });
  }
  const handoff = prepared.signing;
  const value = signBytes(Buffer.from(handoff.toBeSigned, "base64"));
  const signing = { certificates: CERTIFICATES, value: value.toString("base64"), toBeSignedDigest: handoff.toBeSignedDigest };
  if (TSA_URL) {
    signing.timestamp = { token: await timestamp(value) };
  }
  const completed = await render({ abi: "4.0.0", op: "complete", pdf: { data: prepared.bytes }, signing });
  if (!completed.ok) {
    return res.status(500).json({ error: completed.error });
  }
  res.set({
    "Content-Type": "application/pdf",
    "Content-Disposition": 'attachment; filename="customer-intake-signed.pdf"',
    "X-Page-Count": String(prepared.pageCount),
    "X-Signed-By": CHAIN[0].subject.replace(/\n/g, ", "),
    "X-Signature-Field": completed.field,
    "X-Timestamped": String(completed.timestamped)
  });
  res.send(Buffer.from(completed.bytes, "base64"));
});

// A signed PDF back for a verdict: which signatures it carries, whether each still matches the
// bytes, whether the value checks out under the signer's key, and whether the signer is this server.
app.post("/api/submissions/verify", express.raw({ type: "application/pdf", limit: "64mb" }), async (req, res) => {
  const report = await render({ abi: "4.0.0", op: "verify", pdf: { data: req.body.toString("base64") } });
  if (!report.ok) {
    return res.status(400).json({ error: report.error });
  }
  const verdicts = report.signatures.map((sig) => ({
    field: sig.field,
    signer: sig.signer?.subject ?? null,
    signingTime: sig.signingTime,
    digestMatches: sig.digestMatches,  // the file still hashes to what was signed
    certificateMatches: sig.certificateMatches,  // the signed attributes name this certificate
    signatureValid: Boolean(sig.signer) && verifyBytes(Buffer.from(sig.signer.publicKey, "base64"), Buffer.from(sig.toBeVerified, "base64"), Buffer.from(sig.signature, "base64")),  // the value checks out under the signer's public key
    coversDocument: sig.coversDocument,  // nothing was appended after this signature
    trusted: sig.signer?.certificate === CERTIFICATES[0],  // the signer is this server
    certification: sig.certification,
    timestamp: sig.timestamp ?? null
  }));
  // The files the signature sealed, by digest: what a record's JSON must hash to.
  res.json({ signatures: verdicts, attachments: report.attachments });
});

app.listen(8000);

// The one cryptographic step this server keeps for itself: the DER attributes the kernel prepared,
// signed with the key. An HSM or a cloud KMS signs the same bytes (or "toBeSignedDigest", their SHA-256).
function signBytes(data) {
  return sign("sha256", data, KEY);  // RSA PKCS#1 v1.5, or ECDSA as DER — both as the kernel takes them
}

function verifyBytes(spki, data, value) {
  return verify("sha256", data, createPublicKey({ key: spki, format: "der", type: "spki" }), value);
}

async function timestamp(value) {
  const tsq = await render({ abi: "4.0.0", op: "timestampRequest", signature: value.toString("base64") });
  const response = await fetch(TSA_URL, { method: "POST", headers: { "content-type": "application/timestamp-query" }, body: Buffer.from(tsq.request, "base64") });
  if (!response.ok) throw new Error(`the timestamp authority answered ${response.status}`);
  return Buffer.from(await response.arrayBuffer()).toString("base64");
}

async function render(request) {
  return JSON.parse(await qjs(RENDER, JSON.stringify(request), 15, 256 * 1024 * 1024));
}
js
// qjs.mjs — one run of the engine, in a process of its own: qjs-wasi.wasm, QuickJS-ng's own
// WebAssembly build from its release page, on V8, with node:wasi for its system interface — nothing
// to install beside Node 22. The endpoint (main.mjs) starts one of these per request:
//   node --wasm-max-mem-pages=<pages> --disable-warning=ExperimentalWarning qjs.mjs <qjs arguments>
// The request comes in on stdin and the answer goes out on stdout; the directory the process was
// started in is mounted as /app, all the run can reach. The flag is the memory the module may grow
// to, per process. The warning silenced is node:wasi's own, that it is still marked experimental,
// so that stderr is the run's alone.
import { readFileSync } from "node:fs";
import { WASI } from "node:wasi";

const wasi = new WASI({
  version: "preview1",
  args: ["qjs", "--std", ...process.argv.slice(2)],  // --std: the std module, which reads stdin
  preopens: { "/app": "." },
  returnOnExit: true  // qjs's exit code comes back from start() below, and becomes this process's
});
const qjs = await WebAssembly.compile(readFileSync(new URL("qjs-wasi.wasm", import.meta.url)));
const instance = await WebAssembly.instantiate(qjs, wasi.getImportObject());
process.exitCode = wasi.start(instance);

What to notice ​

  • Two calls to the program. The document operation renders the record and prepares it in one call: the signature field, the /ByteRange placeholder, and the signed attributes in signing.toBeSigned. The complete operation embeds the signature value. Between them is the one step the server keeps for itself.
  • The key stays with the server. The server signs toBeSigned with its platform's crypto. A hardware token or a key service can sign the same bytes, or toBeSignedDigest, their SHA-256, instead. Only the certificates go into the request.
  • The layout says how, the server may override. CERTIFY left empty keeps the layout's certification, which allows no further change. Set it to false for an approval signature, or to formFilling to allow form filling after the seal.
  • A timestamp, if you want one. With TSA_URL set, the program builds an RFC 3161 request, the server posts it to the authority, and the token goes into the signature. Give the layout "timestamp": true so the placeholder has room for it.
  • Verifying is the program's and the server's. The verify operation checks each signature's structure, digest and certificate binding. The server checks the signature value under the signer's public key, and calls a signer it knows trusted only when the certificate is its own.

Next ​

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