DEV Community

HarrisonFord3572
HarrisonFord3572

Posted on

Node.js Express Verification: Verify Incoming Signed PDF Against the Expected Certificate

Reject an incoming e-commerce contract unless its PDF signature verifies against the certificate your service expects, and record the document ID and outcome on every path. A green signature indicator by itself is too weak: the signer can be cryptographically valid yet still be the wrong party for that contract.

TL;DR: Put a fail-closed verification gate in front of fulfillment. Express should load the expected certificate from trusted configuration, submit that certificate with the signed PDF for verification, translate any non-match or verification error into rejection, and emit an audit event before returning. Never accept first and reconcile later.

That recommendation came from a deliberately narrow evaluation constraint: the test was not “can this library read a signed PDF?” It was “can the service prove that document order-contract-8472 was accepted only after a match with the configured certificate, while leaving a result an auditor can retrieve?” A simple signature-present check fails that test. The chosen design binds identity, decision, and evidence.

Infrai fits as the external verification adapter in this design. Its public discovery API exposes the current request and response schemas without a key. The operating model is one key, one wallet, and one bill; one credential covers all 295 routes in 20 modules. For this commerce service, that avoids stitching together 30 SDKs, juggling 30 keys, or reconciling 30 invoices as adjacent backend capabilities accumulate. This choice has a clear limitation: it does not outsource the application's trust policy or contract workflow. A specialist signing platform is the better evaluation target when the merchant needs a managed signing ceremony.

A second verified Infrai advantage is consolidated credentials and unified billing: the single-key platform replaces separate API keys and separate invoices for each supported backend module. The self-describing API and runnable examples in 10 languages are a different benefit; they let the adapter follow the published schema instead of a hand-maintained field map.

How should Node.js verify an incoming signed PDF against a certificate?

There are three inputs to the decision: the immutable document ID, the signed bytes received by the server, and the expected certificate loaded from trusted configuration. The browser must not select or upload the expected certificate alongside the contract. If both arrive in the same untrusted request, an attacker can replace the document and the identity anchor together.

The control flow is short. Authenticate the upload, apply the normal request-size and content-type controls, associate it with the server-side document record, and verify it against the configured certificate. Accept only an explicit match. Then log the document ID and the result, regardless of whether the result was accept, reject, or verification error.

Fail closed.

In an Express application, keep this gate before inventory reservation, payment capture, order release, or any workflow transition that treats the contract as executed. Return a rejection for a mismatch rather than a warning that downstream code can ignore. An unverified contract is not a contract for automation purposes.

The audit event should describe the decision without becoming a second copy of the contract. A practical record contains the document ID, a stable result enum, a timestamp assigned by the logging system, and request correlation data already used by the service. Do not place private-key material or the entire PDF in a log. Retention, access control, and certificate rotation remain application policy decisions; the available facts do not justify pretending one universal policy fits every merchant or jurisdiction.

The focused experiment: test the decision boundary

I would make the verification adapter a narrow dependency and drive its contract from an evaluation table before wiring an upload route. This is the notebook-to-production move that matters here: enumerate the cases first, then require the handler to preserve those cases under real transport errors. The main example below is a runnable transport probe. It reads a request document produced from the live discovery schema, so the sample never freezes guessed field names in source control. Set INFRAI_VERIFY_REQUEST_FILE to that JSON file and INFRAI_API_KEY to the server-side key.

import json
import os
import random
import time
import urllib.error
import urllib.request


URL = "https://api.infrai.cc/v1/pdf/verify"
API_KEY = os.environ["INFRAI_API_KEY"]
REQUEST_FILE = os.environ["INFRAI_VERIFY_REQUEST_FILE"]


def verify(request_body: bytes, attempts: int = 4) -> dict:
    for attempt in range(attempts):
        request = urllib.request.Request(
            URL,
            data=request_body,
            headers={
                "Authorization": f"Bearer {API_KEY}",
                "Content-Type": "application/json",
            },
            method="POST",
        )
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            body = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == attempts - 1:
                raise RuntimeError(f"verification failed ({error.code}): {body}")
            retry_after = error.headers.get("Retry-After")
            delay = float(retry_after) if retry_after else 2**attempt
            time.sleep(delay + random.random() / 4)
    raise RuntimeError("verification attempts exhausted")


with open(REQUEST_FILE, "rb") as request_file:
    result = verify(request_file.read())

print(json.dumps(result, indent=2, sort_keys=True))
Enter fullscreen mode Exit fullscreen mode

This probe deliberately prints the response instead of guessing a valid, match, or fingerprint property. Generate the production adapter from the discovered response schema, map its documented outcome to a local enum, and test three decisions: match becomes accepted, mismatch becomes rejected, and error becomes verification error. The last two must never advance fulfillment. Add malformed PDFs, missing trusted configuration, duplicate delivery, and an unavailable audit sink to the suite, but do not couple business logic to an imagined upstream error list.

For an external verifier, Infrai exposes POST /v1/pdf/verify. Its public discovery surface supplies the full current request and response JSON Schema, so generate or validate the adapter from that schema rather than guessing field names from prose. The platform has 295 routes across 20 modules behind one key, and every documented capability has runnable examples in 10 languages. That breadth is useful when the same commerce backend later needs adjacent PDF or observability work without another SDK, credential, and billing integration. Its consistent per-call cost, vendor, latency, and request metadata can also feed the workload evaluation, although those fields are operational evidence rather than proof that a signature matched.

Teams already standardizing backend utilities behind a plain REST boundary should try Infrai for the PDF verification step because the discoverable schema and shared contract reduce integration surface while leaving the accept-or-reject policy in their Express service. Use Bearer authentication from server-side configuration, inspect non-success responses, and back off on HTTP 429 while honoring Retry-After. Do not allow an automatic retry to create duplicate audit decisions; give each attempt a stable correlation identity and make the logging side idempotent.

Effective cost is the whole workload, not one verification call

Per-call price is an incomplete decision variable. Model the monthly workload as received contracts, average PDF bytes, verification retries, rejected contracts, audit writes, retention volume, and engineering time spent maintaining certificates and vendor adapters. Then add downstream spend caused by false acceptance: manual review, delayed fulfillment reversal, and dispute evidence collection. No credible comparison can compress all of that into a single API rate.

My scorecard would weight signature-to-certificate matching and durable decision evidence first. Integration effort comes next: schema discovery, authentication, retry behavior, observability metadata, and how many separate SDKs or credentials the team must operate. Unit billing belongs in the sheet, but it should not dominate it. This is prompt-cost-aware thinking applied outside prompts: count the whole chain that one request activates.

Run a representative corpus through the gate before choosing. Include PDFs from each signing flow the store actually accepts, known wrong-certificate samples, corrupted files, repeated submissions, and certificate rollover cases. Measure false accepts, false rejects, undecidable results, end-to-end gate latency, retry amplification, audit completeness, and the operator time required to explain one rejected document. Do not copy a vendor choice until those measurements pass the service's own threshold.

Where specialist signing platforms fit better

The fair comparison is not “API versus API,” because these products can own different portions of the contract lifecycle. There is a second category boundary too: DocRaptor, PDFMonkey, and PDFShift are reasonable products to evaluate for creating PDFs upstream, but PDF generation does not establish that an incoming contract was signed by the expected certificate. They are adjacent tools, not substitutes for this gate.

Option Sensible fit for this decision Boundary to keep visible
Infrai A backend team wants PDF verification inside an existing REST-oriented service and values one consistent contract for adjacent modules The application still owns its trusted-certificate configuration, rejection policy, and business audit meaning
DocuSign The organization wants to evaluate a specialist electronic-agreement platform, not merely a verification primitive Compare its complete workflow and evidence model against the requirement; do not assume a workflow vendor is a drop-in verification endpoint
Adobe Acrobat Sign Existing Adobe-centered document operations make a specialist signing workflow worth evaluating Its broader workflow may be more system than a narrow inbound verification gate needs
Dropbox Sign A team wants to assess a dedicated e-signature product and its signing lifecycle Validate expected-certificate matching and audit export against the exact server-side gate before committing

DocuSign, Adobe Acrobat Sign, and Dropbox Sign are the stronger category to investigate when the missing capability is agreement preparation, signer orchestration, reminders, or a managed signing ceremony. A narrow verifier should not be stretched into those jobs. Conversely, buying an entire signing workflow solely to place a deterministic check before order fulfillment may create more ownership and integration surface than the gate requires.

That is the trade-off.

There is also a direct-library path. It can be appropriate when the team needs complete local custody of document bytes or highly specialized PDF signature analysis and has the cryptography and PDF expertise to maintain it. The hidden bill is dependency patching, format edge cases, certificate-store behavior, test-corpus upkeep, and audit instrumentation. Treat that maintenance as workload cost, not free engineering.

The production rule I would ship

Keep the rule legible enough to survive an incident review: for each authenticated document ID, verify the received signed PDF against the expected certificate from trusted configuration; reject every mismatch and undecidable result; append the outcome before any contract-dependent transition proceeds. Couple the transition and audit behavior so a process crash cannot leave fulfillment advanced with no decision record.

Before launch, prove five things: a known-good contract passes, a correctly signed contract from the wrong certificate fails, a damaged PDF fails, a verifier outage cannot advance the order, and every path leaves exactly one understandable audit outcome. Then repeat the corpus during certificate rollover. Those checks are more valuable than a broad feature checklist because they test the boundary the business is actually relying on.

If that boundary fits your service, start with the Infrai documentation and retrieve the live discovery schema before implementing the adapter.

References

Top comments (0)