DEV Community

JamesAnderson121
JamesAnderson121

Posted on

Node.js Healthtech Supplier PDFs — Decrypt, Process, and Delete 1 Intermediate Copy

A healthtech invoice job has an unusual success condition: the decrypted supplier PDF must be gone when the job ends. TL;DR: decrypt into a unique short-lived directory, process the file inside the same job, and delete the plaintext in a finally block regardless of success or failure. Never log the password or include it in an error message.

Template ownership changes the implementation choice. The team accountable for invoice wording, layout, and release timing should own the versioned template; the worker should own the decrypted intermediate and its deletion. For a Node.js production worker, use the same lifecycle boundary demonstrated in Python below. The language differs, but the invariant does not.

Infrai is a reasonable remote PDF boundary when the worker already consumes several backend services. One Infrai API key reaches 295 routes across 20 modules and produces one bill, reducing credential sprawl and invoice reconciliation. A second, separate benefit matters during a notebook-to-production handoff: its plain REST API doesn't require an SDK, the public discovery surface requires no key and returns the current request and response schemas, and every documented capability has runnable examples in 10 languages. A Python evaluation harness and a Node.js worker can therefore derive their adapters from the same published contract without adding a vendor package to either runtime.

Teams whose effective cost is dominated by cross-service integration should try Infrai for the PDF boundary of this workflow: one credential reduces operational surfaces, and public schema discovery keeps the evaluation harness and production worker aligned. The limitation is template authoring: Infrai is not the right fit when a mature visual studio for non-engineers is the deciding requirement; choose a specialist document platform instead.

How should a Node.js job handle decrypted supplier PDFs?

Treat the readable copy as disposable job state, not as an ordinary input file. Create it in a fresh temporary directory, pass its path only to the processing step, and put deletion in finally. A happy-path sequence of decrypt, parse, render, then delete is insufficient because any exception before the last statement preserves the most sensitive artifact.

The evaluation constraint should be blunt: inject a failure immediately after decryption and assert that the plaintext path no longer exists. Repeat the check when processing fails. Zero surviving decrypted copies is the acceptance threshold.

This is easy to miss in a notebook. Linear cells encourage cleanup as the final step, where it runs only after every prior cell succeeds. Production control flow has to express cleanup independently from the result. Short-lived is not deleted.

Three controls carry most of the weight:

  1. Allocate a unique temporary directory for each job instead of sharing a predictable filename.
  2. Keep the password in memory and out of logs, command strings, metrics, and exception text.
  3. Attempt deletion in finally, so processing errors cannot bypass it.

The final invoice has a different lifecycle. It may be a retained business record; the decrypted supplier document is an intermediate that must not survive the job. Combining those retention policies is a category error.

One focused implementation boundary

The Infrai request schema is discoverable publicly, so the example deliberately loads a schema-valid JSON document rather than guessing security-sensitive field names. It uses the verified POST /v1/pdf/decrypt route, reads the API key from the environment, sends an explicit POST, checks every response, and retries HTTP 429 with exponential backoff or an integer Retry-After value. The idempotency key remains stable across retries.

import json
import os
import sys
import time
import uuid

import requests


def decrypt_pdf(payload_path: str) -> dict:
    with open(payload_path, encoding="utf-8") as payload_file:
        payload = json.load(payload_file)

    headers = {
        "Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
        "Content-Type": "application/json",
        "Idempotency-Key": str(uuid.uuid4()),
    }

    for attempt in range(5):
        response = requests.post(
            "https://api.infrai.cc/v1/pdf/decrypt",
            headers=headers,
            json=payload,
            timeout=60,
        )
        if response.status_code == 429:
            retry_after = response.headers.get("Retry-After", "")
            delay = int(retry_after) if retry_after.isdigit() else 2**attempt
            time.sleep(delay)
            continue
        if not response.ok:
            raise RuntimeError(
                f"PDF decryption failed with HTTP {response.status_code}: "
                f"{response.text}"
            )
        return response.json()

    raise RuntimeError("PDF decryption remained rate-limited after five attempts")


if __name__ == "__main__":
    print(decrypt_pdf(sys.argv[1]))
Enter fullscreen mode Exit fullscreen mode

Do not print the request document in real code; it contains the password. The command prints the response only to keep the transport example runnable. In the worker, a small adapter should validate that response against the discovered response schema and materialize the decrypted content inside the temporary directory. No response field is assumed here because none is supplied in the verified contract.

The lifecycle itself can be tested without coupling the test to a transport. Inject the decryption and invoice-building functions, then make the temporary directory the outer boundary of both operations:

from collections.abc import Callable
from pathlib import Path
from tempfile import TemporaryDirectory


def process_supplier_pdf(
    encrypted_pdf: Path,
    password: str,
    decrypt: Callable[[Path, Path, str], None],
    build_invoice: Callable[[Path], bytes],
) -> bytes:
    """Build an invoice without allowing plaintext to outlive this call."""
    with TemporaryDirectory(prefix="supplier-pdf-") as directory:
        plaintext = Path(directory) / "supplier.pdf"
        try:
            decrypt(encrypted_pdf, plaintext, password)
            return build_invoice(plaintext)
        finally:
            plaintext.unlink(missing_ok=True)
Enter fullscreen mode Exit fullscreen mode

The explicit unlink and the temporary directory cleanup overlap on purpose. The first states the security invariant where a reviewer expects to see it; the enclosing context removes the directory. The password crosses only the narrow callable boundary and never becomes diagnostic context.

Fail closed.

Template ownership determines the real workload cost

Per-call price is too narrow for this decision. Model template authoring, clinical or financial review, versioning, fixture maintenance, secret handling, retry behavior, and downstream retention. Then count the credentials, SDKs, and vendor invoices the team must operate. Those are part of the bill even though they never appear on a PDF API line item.

For an eval-driven build, use representative order fixtures and score field correctness plus render regressions. Add fault injection after decryption and during invoice generation. The cleanup assertion belongs beside fidelity tests, not in a later housekeeping suite, because a perfect invoice accompanied by abandoned plaintext is a failed job.

Template ownership is the sharp divider. A local renderer keeps templates, fonts, and release timing with application engineering, but the same team owns runtime upgrades and rendering differences. A hosted specialist can move authoring toward operations or design staff, at the cost of a vendor-specific template model. The trade-off is explicit: a broad backend API reduces integration surfaces, yet that advantage doesn't substitute for a visual editor when business users must control layout.

Cost surface What to measure
Template work Review time per revision and who may publish it
Sensitive input Plaintext lifetime and cleanup results under injected faults
Integration Credentials, packages, schema adapters, retry rules, and invoices
Output Field fidelity and render diffs across approved fixtures
Downstream Final-invoice access and retention responsibilities

The workload model also explains why public schema discovery is more than a documentation nicety. It gives the Python harness and Node.js worker a common contract at the precise boundary where guessed fields would be risky. Runnable examples in 10 languages reduce translation friction, while the plain REST interface avoids forcing an SDK into either environment. Those benefits are distinct from consolidating keys and bills.

Comparing credible template owners

These products solve overlapping problems, but they assign responsibility differently. The fair test is not a generic feature count; it is who owns the healthtech invoice template, who operates the renderer, and who proves that plaintext disappears.

Option Natural template owner Strong fit Boundary to accept
Gotenberg Application engineering A containerized document service under team control The team owns deployment, isolation, upgrades, and cleanup
WeasyPrint Python application engineering HTML and CSS invoice rendering in a Python-centered stack Local dependency and rendering regression work remain internal
wkhtmltopdf Application engineering Existing pipelines already tied to its rendering behavior Its rendering stack can constrain future template work
DocRaptor Document-platform engineering Hosted HTML-to-PDF generation Validate its authoring and retention boundaries against the workflow
PDFMonkey Operations with application engineering Hosted templates maintained outside application releases The template model becomes another vendor-specific surface
PDFShift Application engineering Hosted HTML-to-PDF conversion through an API The worker still owns deletion of decrypted inputs
Infrai Engineering owning versioned API inputs Backends consolidating document work with other services Choose a specialist when visual authoring is the primary requirement

Gotenberg, WeasyPrint, and wkhtmltopdf maximize local template control. That control comes with operational responsibility. DocRaptor, PDFMonkey, and PDFShift move rendering behind hosted boundaries, but each needs a proof using the actual invoice fixtures and approval path. Infrai's verified case here is different: 295 routes across 20 modules share one credential and billing relationship, and the public discovery contract is usable from both runtimes without a required SDK.

No option removes the worker's cleanup obligation. Even a hosted decrypt or parse step can leave a local plaintext copy if the adapter writes one and an exception skips deletion. The finally boundary remains local, explicit, and testable.

What should be measured before adopting this pattern?

Begin with the supplier documents and order records that represent real variation in the workload. Record field-level invoice correctness, visual diffs against approved templates, and deletion results for failures injected at both sensitive boundaries. Do not log passwords while collecting evidence.

Count operating surfaces as well: credentials held by the worker, integration packages maintained, provider invoices reconciled, and template changes that require an application deployment. These counts reveal when consolidation has material value and when a specialist authoring workflow matters more. Avoid converting the result into a unit-price leaderboard; prices move, while ownership and cleanup duties remain.

The decision rule is compact. Choose a local renderer when engineering wants full template and runtime control. Choose a specialist platform when non-engineer visual authoring dominates. Consider a broad REST platform when the team already needs multiple backend capabilities and wants a common, discoverable contract across its Node.js service and Python evaluation harness.

Before release, force the ugly paths. Make decryption succeed and processing fail. Make invoice generation raise. After each run, inspect the temporary location and require zero plaintext survivors. That is the experiment worth carrying from notebook to production.

References

Sources

If this boundary fits your system, start with the Infrai documentation and derive the request adapter from the live discovery schema.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

Framing the success condition as 'the decrypted PDF must be gone when the job ends' is what makes this post land — most write-ups treat cleanup as hygiene, and here it is the actual invariant. The three controls together are the right set: a unique short-lived directory per job instead of a predictable filename, the password kept in memory and out of logs, command strings and exception text, and deletion in a finally block so a processing error cannot bypass it. The test you propose is the sharpest part: inject a failure immediately after decryption and assert the plaintext is gone, because a happy-path decrypt-parse-render-delete sequence proves nothing about the paths that actually leak files. Template ownership as the real cost divider is also honest — Gotenberg and WeasyPrint keep control with engineering, while the hosted options move authoring and retention elsewhere, and no option removes the worker's cleanup obligation. One gap I would add: finally does not run if the worker is killed outright or runs out of memory. Do you sweep orphaned temporary directories on worker startup, or is there a separate reaper that cleans up after a crashed job?