TL;DR: Treat a parsed table of contents as untrusted evidence, convert its chapter starts into half-open page intervals, validate the entire interval set before copying a single page, and bind every output segment to the signing audit record with a cryptographic digest. In a Node.js document-bundle worker, the useful page is not "split failed." It is "a contract segment reached signing with a missing, duplicated, or reordered source page," because that names the integrity failure an operator can act on. The page fires after a multiplayer game's publisher agreement has been assembled into separate commercial, data-processing, and territory schedules for server-side signature. The on-call sees a bundle ID, the source digest, the parsed chapter starts, the emitted page intervals, the signer job ID, and the first violated invariant. No contract text belongs in the alert. The immediate action is to quarantine that bundle, prevent signature dispatch, and compare the immutable source manifest with the segment manifest. That is the answer before the implementation detail: derive ranges once, prove that they form an ordered, non-overlapping partition of the intended pages, then split. Parsing and page copying are separate trust boundaries. A parser can produce plausible headings while being wrong by one page; a PDF library can copy exactly the pages it was asked to copy while the request itself is wrong. What should page the on-call? The page should fire on an integrity invariant at the last reversible point, before a segment enters the signature workflow. Dashboard symptoms such as a queue growing, a worker slowing down, or a parser returning fewer headings are useful context, but none answers the first operational question: what contract is at risk, and what stopped it from being signed incorrectly? For each bundle, the worker should emit one structured completion event containing the source document digest, source page count, normalized table-of-contents entries, derived intervals, output digests, parser identity and version, and a correlation ID shared with the signing service. Store access-controlled identifiers rather than player, studio, or signatory names. The event is part of the evidence chain, so append it; do not silently rewrite it after a retry. I would make these conditions hard failures: a start page below the permitted first page, a start beyond the source page count, duplicate or descending starts, an empty interval, overlap, a gap where full coverage is required, a copied-page count different from the interval length, or an output digest absent from the audit record. A repeated delivery with the same idempotency key but a different source digest is also a hard failure. Stop there. A warning is appropriate when the parsed contents omit an optional appendix that policy allows the worker to leave attached to the preceding chapter. That policy must be explicit and versioned; otherwise "optional" becomes the place where pages disappear without waking anyone. How should Nodejs split PDF chapter ranges from parsed contents? PDF page indexes in many programmatic representations are zero-based, while printed page labels and table-of-contents entries are often one-based and may use Roman numerals or custom labels. ISO 32000-2 defines the document format, but a visual page label is not permission to treat a parsed number as a physical page index. Normalize at one boundary and retain both values in the manifest: declaredPage from the parser and pageIndex used for copying. Assume the parser produced three trusted candidates after title normalization and policy filtering: Chapter Declared start Internal start Derived interval Commercial terms 3 2 [2, 8) Data processing 9 8 [8, 13) Territory schedule 14 13 [13, 18) For a source with 18 physical pages, each interval begins at one normalized start and ends at the next; the final interval ends at the source page count. Half-open intervals make the arithmetic inspectable: interval length is end - start, adjacent chapters meet when one end equals the next start, and page 8 cannot accidentally appear in both first and second outputs. The cover and contents occupy indexes 0 and 1, so policy must say whether they become a separate preface, are attached to the first segment, or remain outside the signing packet. There is no universally correct choice. Hiding the choice is incorrect. In Node.js, represent these values as integers and reject unsafe, fractional, string-coerced, negative, or non-finite input before range construction. Sort only if the parser contract explicitly permits unordered entries; otherwise descending input is evidence of a parser failure, and sorting it would erase the symptom. First validate chapter identity and starts. Then derive all ends. Then validate global coverage. Only after those passes should the PDF adapter allocate output documents and copy pages. This sequencing matters because partial success is awkward evidence. If two chapter files are written and the third range fails validation, cleanup may remove the files but cannot necessarily remove object-store events, queue messages, or logs already observed by other systems. Building a complete plan in memory keeps the failure on the reversible side of the boundary. Preserve a signing-grade audit trail A signature proves something about the bytes presented to the signing operation; it does not, by itself, prove that the correct chapter pages were selected from the source bundle. The audit trail must connect those two claims. Record a digest of the received source, a canonical representation of the split plan, a digest of every emitted segment, the policy version, the actor or workload identity that authorized processing, timestamps, and the signing result. RFC 8785 is relevant when the manifest itself is JSON and must have a repeatable byte representation before hashing. Keep content and evidence separate. The segment contains contract pages. The audit event contains identifiers, digests, range metadata, outcomes, and correlation fields. This reduces exposure in alerts and logs while leaving enough information to establish that output segment territory-schedule came from source indexes 13 through 17 under a named policy. Access to both stores should be controlled, and retention should follow the contract and legal policy rather than an arbitrary logging default. Retries deserve suspicion: a worker retry should use the same immutable source digest and split-plan digest, write to a deterministic staging identity, and compare any existing result before publishing. If the bytes already present have the expected digest, the worker can report an idempotent completion; if they differ, quarantine the bundle, because overwriting would destroy the most useful clue. Server-side signing adds another boundary: the signing service should accept segment digests or return signed-artifact digests that the orchestrator verifies and appends to the same correlation chain. Do not mark the bundle complete merely because every downstream request returned success. Completion means the expected set of chapter identities exists, each signed result maps to one approved input digest, and the final manifest satisfies the same coverage policy used before splitting. Work backward to the earlier signal The late alert is a signed-packet integrity mismatch. The earlier signal should be a pre-sign validation rejection, grouped by invariant rather than by exception text. Counters for duplicate_start, range_out_of_bounds, coverage_gap, copied_count_mismatch, and digest_conflict expose whether the fault is in parsing, policy, copying, or retry handling. A distribution of bundle page counts and chapter counts may help capacity work, but it is not a substitute for those invariants. Instrument the stages as a trace: ingest, parse, normalize, plan, validate, copy, persist, sign, and verify. Each span carries the bundle correlation ID and digests appropriate to that boundary, never raw contract text. The completion event should also include elapsed time by stage and retry count, so an operator can distinguish a malformed table of contents from storage latency without opening several dashboards and guessing. Tests should be built around failure shapes. Use generated fixtures for one-page chapters, adjacent starts, a chapter beginning on the final page, covers outside the signed range, duplicate starts, descending starts, starts equal to zero, starts beyond the document, and malformed files. Property tests can assert that accepted intervals are ordered, non-empty, non-overlapping, and cover exactly the policy-approved page set. Integration tests then reopen every emitted PDF, count its pages, calculate its digest, and verify the manifest before exercising the signing stub. Deployment needs a shadow phase when the parser, normalization policy, or PDF engine changes. Produce and compare plans without dispatching the shadow outputs for signature. A difference is not automatically a defect, but it needs classification before rollout because a parser improvement can legitimately change chapter recognition while still changing the bytes a signatory receives. Pin the parser and PDF engine versions in the event so a later investigation can reproduce the decision path. Set thresholds by consequence, not dashboard neatness Page immediately when an invalid plan is about to cross into signing, when an already published segment conflicts with its recorded digest, or when verification finds that the signed output set does not match the approved input set. Those are low-volume, high-consequence conditions. Route individual malformed uploads to a review queue with a visible status; page only when the safety barrier fails, quarantines cannot be written, or the rejection rate crosses a documented baseline over a sustained window. The exact window and threshold must come from observed traffic and an error budget, not an invented universal percentage. The trade-off is blunt. A threshold that pages on every rejected contents parse teaches the on-call to distrust the alert, especially when a safe quarantine already protected the signing boundary. A threshold that waits for a broad error-rate spike can miss one high-value contract whose chapters were rearranged. Keep the integrity page event-driven and immediate; aggregate the parser-quality signal for operational review. One asks for intervention. The other asks for engineering work. The final decision rule is narrow: no segment may be signed unless its pages are accounted for by a validated plan and its digest is joined to an append-only audit event. Everything else, including parser confidence, throughput, and queue depth, helps explain that rule or forecast pressure on it. It does not replace it. Further reading ISO 32000-2, Portable Document Format: https://www.iso.org/standard/75839.html RFC 8785, JSON Canonicalization Scheme: https://www.rfc-editor.org/rfc/rfc8785 RFC 3161, Time-Stamp Protocol: https://www.rfc-editor.org/rfc/rfc3161 NIST SP 800-92, Guide to Computer Security Log Management: https://csrc.nist.gov/pubs/sp/800/92/final OWASP Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
Nodejs PDF Chapter Split: Validated Ranges for Game Contract Signing
Full Article
Original Source
Read the full article at Dev →KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.