oficina / docs Public

Merge branch 'feat/contract-workflow' into main

Add bounded contract template rendering
codex agent, operated by paul@keymail.dev 1f75224cd63f92d3372eaaa6323c152e17d57d52 parent 29b6deaparent 2f38033
6 files changed, +1,430 −7
  • docs/superpowers/specs/2026-10-25-contract-workflow-design.md +319 −0
  • docs/superpowers/specs/2026-10-26-contract-rendering-design.md +132 −0
  • internal/contract/contract_test.go +399 −0
  • internal/contract/resolve.go +220 −0
  • internal/contract/template.go +316 −0
  • internal/export/pdf.go +44 −7

CI passed — run details

landed from feat/contract-workflow

diff --git a/docs/superpowers/specs/2026-10-25-contract-workflow-design.md b/docs/superpowers/specs/2026-10-25-contract-workflow-design.md
new file mode 100644
index 0000000..7b31d55
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-contract-workflow-design.md
@@ -0,0 +1,319 @@
+# Contracts: Docs templates, Fichas merge, native signing
+
+Status: **proposal, revision 1, 2026-10-25**. Author: GPT-6 / Codex.
+Not an implementation plan or an approved change to suite authority.
+Independent GPT-6 review accepted this as a scoped discovery/design
+proposal, with four clarifications incorporated below. This is not
+approval to implement issuance or native signing. No application code or
+deployed configuration is changed by this document.
+
+## 1. Outcome and authority
+
+Paul requested a contract authored in Docs, personalised from Fichas, and
+sent for signature. On 2026-10-25 Paul confirmed Fichas is live and asked
+to proceed; when asked about the signing implementation, he chose
+**native signing in Oficina**. The narrower implementation choices below
+are this session's proposals, not decisions attributed to Paul.
+
+The first usable milestone is one customer, one template, and a preview.
+The next is one agreement issued to one external signer and returned to
+the customer's card as completed. Batch issuance follows the working
+single-agreement lifecycle. Suite-wide API, CLI and MCP design remains a
+separate workstream; these operations must eventually be usable by those
+clients without recreating business logic in each transport.
+
+Canonical dependencies, read after fetching on 2026-10-25:
+
+| Source | Revision | Relevant boundary |
+|---|---|---|
+| Suite sharing doctrine | revision 8, `094de9c0733e908c944e958d852cc583f5b78ea5` | §4.1–4.3, §5, §7, §7.1, §11 gates 6b and 7 |
+| Docs | `c6602122601d2dcbfcc24ba9b625dda1852d22bc` on `origin/main` | existing editor, encrypted content, access checks, PDF export, Home bridge; Docs design §14 and §14a |
+| Fichas | `714409257562048ad97fb0fc0b4148acfcce9b4b` on `origin/design/rulings-2026-09-19` | card/field/entry implementation, record revisions, sealed values, standalone admission |
+| Suite producer proposal | `design/producer-protocol`, discussion [10](https://amadan.net/oficina/suite/discussions/10) | proposed producer integration; not an implemented service |
+| External sharing requirement | suite discussion [12](https://amadan.net/oficina/suite/discussions/12) | Paul’s document-scoped isolation requirement; architecture remains unresolved |
+
+Those doctrine sections are cited, not replaced by local paraphrases.
+No new sibling credential, private-item transfer, issuance permission or
+external-signing grant is authorised merely by this draft.
+
+## 2. Verified starting point
+
+The public Fichas `/api/version` returned `7144092`; the Docs endpoint
+returned `v0.1.0-40-gce29703`. These are endpoint observations, not an
+authenticated end-to-end test. Docs main is ahead of the observed release.
+Fichas main is still `fab37e4`, a design-only commit; the live code is on
+the branch above. Feature work must explicitly name its base and cannot
+silently treat that branch as main or merge unrelated work into main.
+
+Fichas has card types, configurable fields/layouts, customer records and
+entries. Its configuration still rejects `FICHAS_SHAPE=suite`. Its mounted
+routes do not implement S2/S3 or a contract handoff. Docs has PDF and
+Markdown export but no template fields, personalised preview, handoff
+receipt/commit, provenance enforcement, agreement store or signing flow.
+An app switcher or Home link is not evidence those integrations exist.
+
+## 3. Product flow
+
+1. In Docs, mark a document as a template and insert named fields. Bind
+ customer fields using stable Fichas field keys, showing their labels.
+ Contract-specific inputs such as a start date are separate from CRM
+ fields. Changing a field label must not break a binding.
+2. From a Fichas customer, choose **Prepare contract**, select a template,
+ and enter any contract-specific values. Selection exposes only templates
+ this person can use. Displaying their titles is itself an authorised read.
+3. Docs shows the resolved contract, customer and template revisions,
+ unresolved fields and explicit formatting errors. A separate preview
+ renders the actual PDF bytes. A preview cannot send invitations.
+4. Once issuance exists, the sender names the signer, reviews those same
+ bytes, and explicitly issues the agreement. A changed source requires a
+ new preview; issue must not silently re-merge against a newer source.
+5. The signer verifies control of their named address, reads the issued
+ document, accepts the displayed signing consent, and confirms signing.
+6. Fichas shows agreement status with a link to Docs. Completed document
+ and evidence are available to authorised participants from Docs.
+
+Prepare/preview is a useful release without issue/sign controls. The first
+release must not display a functioning-looking send button backed by a
+stub or ordinary public document link.
+
+## 4. Ownership and records
+
+**Proposal: Docs owns templates and agreements; Fichas owns customer
+records and references to agreements.** No new app is required for this
+first workflow. An agreement is not an editable Doc with a status flag.
+Its access paths, transitions and immutable payload are separate.
+
+Proposed records, not a migration prescription:
+
+- Template definition: document ID, schema version, field bindings and
+ signer-role anchors. Rendering pins the document content revision and
+ the binding revision together.
+- Preparation: owner/actor, customer reference and revision, template
+ reference and revision, selected values and manual inputs, locale,
+ renderer version, provenance, PDF bytes and digest, expiry. Seal content
+ and personal data under the receiving app's normal content protection.
+- Agreement: preparation reference, exact issued payload and digest,
+ issuer, named recipients/roles, issue timestamp and lifecycle state.
+- Agreement events: attributed transitions with server timestamps,
+ previous state/version, payload digest, and reasons where appropriate.
+- Signing evidence: agreement/payload identity, recipient identity,
+ verification method and time, consent text/version and affirmative
+ action. It must identify what was signed without storing bearer secrets.
+- Delivery outbox: invitation/completion jobs with stable deduplication
+ keys, retry state and delivery outcomes. Delivery is not signing.
+- Fichas reference: Docs instance and agreement ID. Any status projection
+ identifies its last observed revision/time and reports unavailable or
+ stale status honestly. It holds no duplicate PDF.
+
+Reference visibility and status retrieval require agreement access, not
+just access to the customer card. Recipients, agreement titles and state
+must not leak to another card reader. Recheck after team departure or
+participant revocation; an obsolete projection cannot preserve access.
+
+Preparation retention is proposed at 24 hours, to let a sender return the
+next day without making abandoned drafts a permanent copy. Reauthorise
+each access; expiry is not permission to serve a revoked source. Purge
+expired payloads on reads and in scheduled maintenance. Define the backup
+retirement bound before deploying this storage. Issued-record retention,
+withdrawal and deletion are separate decisions required before issuance;
+do not inherit temporary-preparation expiry for signed records.
+
+## 5. Template and rendering contract
+
+Use explicit inline field nodes in the document schema, not global string
+replacement on HTML or a PDF. Field IDs are stable; labels are editable.
+Fields cannot execute expressions, fetch URLs or recursively expand
+values that happen to contain field syntax. Rendering treats values as
+text. Rich-text content is not accepted as a customer field in this slice.
+
+Start with text, date and integer-minor-unit money inputs with an explicit
+currency. Preserve numeric zero; distinguish missing from an empty value.
+Required missing values, removed fields, incompatible types and unsupported
+formatting block successful preview. Optional fields have explicit empty
+behaviour. Date-only values never pass through a timezone conversion.
+Locale and currency are selected once and included in the preparation.
+No conditions, repeating tables or formulas in the first slice.
+
+Preview produces a new resolved representation and leaves the original
+template unchanged. The existing PDF exporter is the initial renderer,
+subject to tests for the supported document subset. Unsupported node
+types and missing glyph substitutions must be visible blocking errors for
+issuance; the existing export route's log-only warning is insufficient.
+
+Persist the PDF being reviewed. Issue freezes those bytes; completion
+preserves them and attaches evidence, rather than regenerating the original
+from a changed renderer/template. If a completion PDF adds a signature
+page, it is a separate derivative with both original and final digests.
+This draft does not claim a PDF certificate signature or any particular
+legal assurance level.
+
+## 6. Cross-app preparation prerequisites
+
+The live standalone instances do not yet satisfy the suite integration
+needed for this workflow. Reuse the Home identity/membership contracts and
+the suite's producer/handoff designs; do not derive trust from matching
+email strings, the shared DNS suffix, or an unrestricted service token.
+
+Before preview is enabled for real customer records, the implementation
+must demonstrate all of the following against the actual app middleware:
+
+- A named identity and membership recognised by both apps, with the
+ configured instances belonging to the same authorised team.
+- The Fichas source authorises the precise record/revision and selected
+ values for the relevant operation. An unavailable source cannot become
+ an empty but apparently successful merge.
+- Docs authorises template use and the resulting preparation. Customer
+ visibility and template visibility are independent checks.
+- A concrete transport for the selected data and provenance that satisfies
+ the cited suite sections, including receipt/commit and sign-in resume.
+ S2 alone is not a data-transfer grant, and the current S3 scope must not
+ be widened to private records for convenience.
+- Source revisions and content are read consistently. Receipt stores
+ bounded, expiring pending state; commit is bound to the same authenticated
+ browser/person and to the exact server-held payload.
+- Every preparation disclosure, including PDF/thumbnail/download and
+ resumed tabs, enforces the source rules. No anonymous preview links.
+
+Choosing the precise source transport is gated on the missing producer and
+identity integration; a naked cross-origin form carrying customer values
+is not a substitute. This proposal therefore does not invent routes or
+declare an implementation-ready wire protocol before those dependencies
+are resolved. A local renderer fixture is useful development work but
+does not pass the integrated-preview milestone.
+
+## 7. Native issuance: required suite decision
+
+The proposed new boundary is **explicit issuance of an independent
+agreement**, distinct from a source-dependent preparation. Once issued,
+editing or deleting a customer card must not mutate the bytes a recipient
+was asked to sign. A participant's access to the issued agreement must not
+require access to CRM notes or the source template.
+
+This needs a reviewed extension to the suite doctrine, specifically §7,
+and must satisfy the external-isolation requirement in suite discussion
+12. The proposal is:
+
+- Require an explicit, auditable authority to issue the template body,
+ selected customer values and every transitive source in their provenance.
+ Permission merely to read or internally use them is not permission to release them
+ independently. The first implementation may restrict issue to owners,
+ but must define what ownership means in both apps and verify it there.
+- Record the approved source revisions, fields, payload digest and named
+ recipients at the issuance boundary. A source change or loss of authority
+ before issuance invalidates preparation and demands a fresh review.
+- Issuance creates recipient-scoped access to this agreement only, hosted
+ by its owning Docs instance. It does not grant team membership, general
+ Docs access, or access to the original customer/template.
+- Subsequent source changes do not invalidate this separately authorised
+ record. Agreement withdrawal, participant access revocation and retention
+ are explicit lifecycle actions, not accidental consequences of editing
+ unrelated records.
+
+These are proposed product semantics, not an exception this app can apply
+unilaterally. **No send/sign implementation may ship before the suite
+extension and the external-isolation design are reviewed.** Merely adding
+a database permission flag does not fulfil discussion 12.
+
+The suite design must define the authoritative issuance point and the
+semantics of a concurrent source update/revocation. Revalidation in one
+app followed by a local transaction in another is not atomic cross-app
+authorisation. Define whether the source supplies a bounded, irrevocable
+release authorisation or a coordinated commit mechanism, including crash,
+timeout and retry behaviour, before prescribing an implementation.
+
+## 8. Signing lifecycle and reliability
+
+First-release proposal: one issuer, one named external signer, one fixed
+document. Email verification identifies control of an address; it is not
+represented as proof of corporate signing authority. Signing is a separate
+affirmative action after verification and document review. Opening an
+email link, a scanner fetch, or rendering a page never signs anything.
+
+Proposed agreement states: `issued`, `completed`, `declined`, `voided`,
+`expired`. Preparations have their own lifecycle. Invitation delivery
+status is independent, so a failed email cannot be mistaken for an
+unissued agreement or a completed one. A completed agreement cannot be
+rewritten or reopened; corrections require a new agreement with a link to
+the previous one. Countersigning and signing order are later slices.
+
+Issue commits an immutable payload, recipient set and delivery outbox job
+atomically. Its idempotency key is scoped to actor and operation and bound
+to the request digest; reuse with different input is a conflict. Network
+retries return the existing result. Delivery retries reuse the invitation
+job; no claim of exactly-once email transport.
+
+Sign/decline/void/expire use a conditional state/version transition. A
+concurrent terminal action has one winner; signature, evidence and state
+commit together. Confirmation binds the recipient and exact payload
+digest; it must fail after withdrawal or expiry. Tokens are expiring,
+purpose-bound and stored only as hashes. Invitation and verified session
+secrets are redacted from logs and referrers. Signing-session and document
+access rules require their own adversarial design review before code.
+
+## 9. Acceptance evidence and sequencing
+
+This is a dependency order for design, not an approved implementation plan.
+
+| Milestone | Evidence required |
+|---|---|
+| Template fields | field nodes survive editing/save/reload; rename preserves binding; missing/type errors are actionable; literal markup remains text; source template unchanged |
+| Integrated preview | real Fichas record through the agreed identity/producer/handoff path; real Docs template; actual PDF; sign-in resume; revoked access, wrong team, replay and expired pending state refused; no customer values in URLs/logs |
+| Issue | suite boundary approved; exact reviewed PDF and source revisions frozen; revalidation failures refuse; double-click/retry yields one agreement; outbox survives restart |
+| Sign | verified named recipient; affirmative consent bound to original digest; scanners do nothing; concurrent sign/void safe; recipient cannot enumerate or access unrelated content |
+| Completion | immutable original and evidence retrievable by intended participants; Fichas link/status correct; outages show stale/unavailable; storage/backup and deletion rules tested |
+
+Browser coverage must include JavaScript disabled for preparation forms,
+handoff confirmation and signing, keyboard navigation, and narrow-screen
+review. Native field-node editing/rendering compatibility must be resolved
+before enabling template editing in clients that cannot preserve the new
+schema. Never silently drop fields in an older client or an export.
+
+The review/signing design must also provide an accessible reading path
+for the exact issued content. Keyboard access to a PDF viewer alone is not
+sufficient: specify reading order and assistive-technology support, and
+how any alternative representation is bound to the reviewed PDF so it
+cannot present different contract terms.
+
+Useful independent implementation work after design review is the typed
+field/renderer layer. The integrated milestone still depends on real
+source authorisation and handoff; unit tests and simulated signing cannot
+be reported as the completed workflow.
+
+## 10. Next design outputs
+
+1. Resolve the suite boundary for independently issued agreements,
+ alongside discussion 12's required isolation mechanism and explicit
+ issued-record retention/access policy.
+2. Specify the authenticated Fichas-to-Docs preview transport against the
+ actual Home and producer implementations. State what source rungs the
+ first release supports; do not claim all cards/templates by default.
+3. Review a concrete document-field schema and rendering compatibility
+ design, then produce the implementation plan for the preview slice.
+4. Review the recipient identity, consent and evidence design before
+ shipping native signing. Keep the wider API/CLI/MCP work separate.
+
+## 11. Independent review record
+
+GPT-6 / Codex, separate `contract_design_review` agent, 2026-10-25:
+acceptable as a scoped discovery/design proposal, not approval to implement
+issuance or signing. No blocking factual error found in inspected fetched
+refs. Clarifications incorporated: issuance authority includes template and
+transitive sources; cross-app revocation race needs an authoritative commit
+boundary; card visibility does not grant agreement-status visibility; PDF
+review needs an accessible equivalent tied to the issued content. The
+reviewer did not repeat live endpoint or discussion-12 checks; those remain
+author-session observations.
+
+## 12. Implementation progress, 2026-10-26
+
+Paul asked to proceed. The first implemented unit is the bounded internal
+template renderer specified in `2026-10-26-contract-rendering-design.md`:
+structural fields, typed values, exact integer money, strict validation,
+PDF fidelity checks, byte/digest output and resource limits. Its independent
+GPT-6 code review approved that scope subject to repository gates.
+
+This is not a user-facing template editor or the integrated Fichas preview.
+The live editor schema remains unchanged to avoid dropping fields in older
+native clients. Source authorisation, handoff, preparation persistence,
+authoring UI and native signing are still required. The first renderer uses
+explicit ISO formatting; locale-specific formatting is not yet supported.
diff --git a/docs/superpowers/specs/2026-10-26-contract-rendering-design.md b/docs/superpowers/specs/2026-10-26-contract-rendering-design.md
new file mode 100644
index 0000000..d9573a7
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-26-contract-rendering-design.md
@@ -0,0 +1,132 @@
+# Contract rendering foundation
+
+Status: implemented on `feat/contract-workflow`, 2026-10-26; independently
+reviewed by GPT-6 / Codex. Repository merge gates remain separate.
+Accepted for implementation with its cumulative-indentation finding
+addressed by the fatal overflow diagnostic below.
+Consumes the 2026-10-25 contract workflow design §5 and §9. Paul asked to
+continue implementation on 2026-10-26. This is the first implementation
+unit; it is not the integrated Fichas preview or the signing workflow.
+
+## Scope
+
+Add `internal/contract`, a pure, bounded renderer for a versioned template
+tree and explicitly supplied typed values. It resolves structural field
+nodes into text, validates that the entire tree is renderable, and renders
+an actual PDF with the existing Docs exporter. It has no HTTP route,
+credential, database, source fetch, or send/sign operation. App handlers
+must authorise and pin their source revisions before calling it later.
+
+Keep this format separate from the live CRDT/editor schema until web and
+native clients can preserve field nodes. Adding a live schema node now
+would allow older clients to discard fields. This package's tests exercise
+real merge and PDF output but are not evidence of an integrated workflow.
+
+## Data contract
+
+`Template` has version 1, a title, a document root and field definitions.
+Nodes use Docs' exported tree vocabulary plus an inline `merge_field`
+node whose `attrs.key` names a definition. A field definition has a stable
+key, display label, kind (`text`, `date`, `money`), optional flag, and a
+currency for money. No expressions or arbitrary HTML. Repeated field
+occurrences use the same value. Definition order must not affect output.
+Reject duplicate definitions, unused definitions and dangling field nodes.
+
+Values are keyed by field key and typed. Missing map entries differ from
+explicit empty text. Required text rejects empty or whitespace-only input;
+optional missing/empty text produces no text. Zero money is a real value.
+Date values are strict calendar dates `YYYY-MM-DD` with no timezone.
+Money is signed int64 minor units plus an explicit ISO currency agreeing
+with its definition. No float conversion, including at int64 limits.
+
+The first supported format is explicitly `iso`: dates are ISO dates and
+money is `EUR 1234.56`, with the currency's standard minor-unit exponent
+(JPY 0, EUR 2, KWD 3). Locale-specific formatting is a later, explicit
+format version. Refuse unsupported formats instead of guessing locale.
+This narrows the initial workflow proposal's locale option deliberately;
+it does not claim localised presentation that is not implemented.
+
+The supported document subset is doc/paragraph/heading/bullet_list/
+ordered_list/list_item/blockquote/code_block/text/hard_break. Enforce the
+parent/child grammar, heading levels 1–6, indentation 0–8, and the existing
+alignment values. Only attributes the renderer actually supports may be
+used on each node. Known font/size marks and strong/em/code are permitted
+on text/fields/breaks; reject unknown or contradictory marks rather than
+quietly discarding their meaning. Link/image/table and unknown nodes are
+errors, not flattened content. Return diagnostics with field key/node path
+and stable code, not submitted field values or PDF/text content.
+
+## Bounds and failure semantics
+
+Bounds are constants with reasons: encoded template 1 MiB; 10,000 tree
+nodes and depth 32; 128 definitions; 64 KiB per value and 1 MiB total
+resolved text. These fit ordinary contracts while bounding recursive and
+repeated-field expansion. Validate UTF-8 and refuse control characters
+other than supported text whitespace. Titles and labels are bounded too.
+Decode a single JSON value strictly, including unknown properties. Typed
+callers go through the same semantic validation as decoded callers.
+
+Independent code review additionally identified quadratic shaping of long
+unbroken runs in the existing PDF exporter. Cap each word at 1,024 UTF-8
+bytes, interactive PDF text at 128 KiB, and PDF output at 100 pages. Refuse
+excess before returning an artifact. Page exhaustion returns no truncated
+PDF; empty paragraphs count toward that budget. Bound expanded node count
+too, including hard breaks introduced for multiline values. These are
+explicit supported-subset limits, not silently truncated inputs.
+
+Merge builds a fresh tree and never mutates the template or input map.
+Values are literal text even when they contain field syntax or markup.
+An error returns no resolved document or PDF. PDF font-substitution reports
+are fatal for this package even though ordinary Docs export is permissive.
+Errors expose codes/coordinates, not the offending characters.
+
+The PDF exporter must also report layout overflow (including cumulative
+quote/list/paragraph indentation). The contract adapter treats that report
+as fatal and returns no preview. Test nested lists/quotes combined with
+maximum paragraph indentation, and single glyphs too wide for the remaining
+line. A successful glyph report alone is not evidence all text fits.
+
+`Preview` returns the resolved document, exact PDF bytes, SHA-256 digest,
+template-format version and renderer-format identifier. It does not claim
+those bytes are persisted, approved, issued, cryptographically signed or
+authorised. A later preparation store must freeze the returned bytes, not
+re-render them on send. An accessible HTML view must escape the resolved
+text; this package does not mint trusted HTML.
+
+## Evidence
+
+Tests cover repeated fields, labels independent from keys, input
+immutability, literal markup, missing/empty/zero, leap dates, currency
+scale/mismatch, int64 bounds, unsupported format/schema/node/mark,
+contradictory formatting, malformed grammar, resource caps, and missing
+glyph refusal. A PDF integration case extracts text from the real output
+and checks substituted contract terms and its digest; it must fail when
+substitution is disabled. Refusal cases must return no preview artifact.
+
+After independent review: implement the types/strict parser, resolver and
+PDF adapter; run the focused tests and adversarial mutation; run repository
+checks and independent branch review before any merge. The next app-level
+unit is template authoring/persistence with client compatibility, followed
+by the authenticated Fichas transport already identified in suite #14.
+
+## Implementation and review record
+
+`internal/contract` implements strict parsing, semantic validation, typed
+resolution and real PDF generation. `export.PDFBounded` adds a page budget
+without capping ordinary export; `Report.LayoutOverflow` lets the contract
+adapter refuse overflow without silently changing ordinary export policy.
+The PDF bytes and SHA-256 digest are returned together. No persistence,
+editor schema change, UI, Fichas source fetch or signing route is exposed.
+
+Independent GPT-6 code review found the unbroken-word shaping issue above;
+limits and adversarial tests addressed it. Final review approved the
+isolated foundation subject to CI/merge gates and independently ran
+`go test ./internal/contract ./internal/export` successfully. The parent
+also ran race-enabled contract tests, extracted the fictional sample's PDF
+text with Poppler, and visually inspected its page. An overlay mutation
+disabling field substitution made the expected-value test fail for missing
+contract terms; no working-tree code was changed by that mutation.
+
+Formatting v1 is ISO, explicitly not locale-specific. This foundation is
+not the completed integrated-preview milestone; the remaining app-level
+work in the workflow design still applies.
diff --git a/internal/contract/contract_test.go b/internal/contract/contract_test.go
new file mode 100644
index 0000000..5f733ae
--- /dev/null
+++ b/internal/contract/contract_test.go
@@ -0,0 +1,399 @@
+package contract_test
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "math"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/docs/internal/contract"
+ "github.com/carlosframework/docs/internal/export"
+)
+
+func field(key string) contract.Node {
+ return contract.Node{Type: "merge_field", Attrs: contract.Attrs{Key: key}}
+}
+
+func template() contract.Template {
+ return contract.Template{Version: 1, Title: "Service agreement", Fields: []contract.Field{
+ {Key: "customer", Label: "Customer name", Kind: contract.Text},
+ {Key: "start", Label: "Start date", Kind: contract.Date},
+ {Key: "fee", Label: "Fee", Kind: contract.Money, Currency: "EUR"},
+ }, Root: contract.Node{Type: "doc", Content: []contract.Node{
+ {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Prepared for "}, field("customer")}},
+ {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Effective "}, field("start")}},
+ {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Fee: "}, field("fee")}},
+ {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Accepted by "}, field("customer")}},
+ }}}
+}
+
+func values() map[string]contract.Value {
+ return map[string]contract.Value{
+ "customer": {Kind: contract.Text, Text: "Acme Workshops"},
+ "start": {Kind: contract.Date, Text: "2028-02-29"},
+ "fee": {Kind: contract.Money, MinorUnits: 125050, Currency: "EUR"},
+ }
+}
+
+func code(t *testing.T, err error, want string) {
+ t.Helper()
+ var d *contract.Diagnostic
+ if !errors.As(err, &d) || d.Code != want {
+ t.Fatalf("error = %v, want code %s", err, want)
+ }
+}
+
+func text(n export.Node) string {
+ s := n.Text
+ for _, c := range n.Content {
+ s += text(c)
+ }
+ return s
+}
+
+func TestResolveSubstitutesStructuralFieldsWithoutChangingInputs(t *testing.T) {
+ t.Parallel()
+ tpl, vals := template(), values()
+ tpl.Root.Content[0].Content[1].Marks = []export.Mark{{Type: "strong"}}
+ before, _ := json.Marshal(tpl)
+ doc, err := contract.Resolve(tpl, vals, contract.ISOFormat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := text(doc.Root)
+ if strings.Count(got, "Acme Workshops") != 2 || !strings.Contains(got, "2028-02-29") || !strings.Contains(got, "EUR 1250.50") {
+ t.Fatal(got)
+ }
+ if doc.Root.Content[0].Content[1].Marks[0].Type != "strong" {
+ t.Fatal("lost field formatting")
+ }
+ // Mutating the returned slices must not edit the template's slices.
+ doc.Root.Content[0].Content[1].Marks[0].Type = "em"
+ doc.Root.Content[0].Content[0].Text = "changed"
+ after, _ := json.Marshal(tpl)
+ if !bytes.Equal(before, after) || !reflect.DeepEqual(vals, values()) {
+ t.Fatal("inputs mutated")
+ }
+ tpl.Fields[0].Label = "Renamed label"
+ again, err := contract.Resolve(tpl, vals, contract.ISOFormat)
+ if err != nil || text(again.Root) != got {
+ t.Fatal("label rename changed binding", err)
+ }
+}
+
+func TestValuesAreLiteralAndZeroIsPresent(t *testing.T) {
+ t.Parallel()
+ v := values()
+ v["customer"] = contract.Value{Kind: contract.Text, Text: `<script>{{fee}}</script>`}
+ v["fee"] = contract.Value{Kind: contract.Money, Currency: "EUR"}
+ doc, err := contract.Resolve(template(), v, contract.ISOFormat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(text(doc.Root), `<script>{{fee}}</script>`) || !strings.Contains(text(doc.Root), "EUR 0.00") {
+ t.Fatal(text(doc.Root))
+ }
+}
+
+func TestMultilineValuesPreserveLineBreaks(t *testing.T) {
+ t.Parallel()
+ v := values()
+ v["customer"] = contract.Value{Kind: contract.Text, Text: "Acme\nWorkshop\n"}
+ doc, err := contract.Resolve(template(), v, contract.ISOFormat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ nodes := doc.Root.Content[0].Content
+ if len(nodes) != 5 || nodes[1].Text != "Acme" || nodes[2].Type != "hard_break" || nodes[3].Text != "Workshop" || nodes[4].Type != "hard_break" {
+ t.Fatalf("lost line breaks: %#v", nodes)
+ }
+ v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("a\n", 6000)}
+ _, err = contract.Resolve(template(), v, contract.ISOFormat)
+ code(t, err, "expanded_node_limit")
+}
+
+func TestMissingEmptyAndWrongValuesRefuseWithoutDocument(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name, key, code string
+ value contract.Value
+ remove bool
+ }{
+ {"absent", "customer", "required_value", contract.Value{}, true},
+ {"empty", "customer", "required_value", contract.Value{Kind: contract.Text}, false},
+ {"space", "customer", "required_value", contract.Value{Kind: contract.Text, Text: " \n "}, false},
+ {"kind", "customer", "value_type", contract.Value{Kind: contract.Date, Text: "2026-01-01"}, false},
+ {"bad leap", "start", "invalid_date", contract.Value{Kind: contract.Date, Text: "2027-02-29"}, false},
+ {"timestamp", "start", "invalid_date", contract.Value{Kind: contract.Date, Text: "2028-02-29T00:00:00Z"}, false},
+ {"year zero", "start", "invalid_date", contract.Value{Kind: contract.Date, Text: "0000-01-01"}, false},
+ {"currency", "fee", "currency_mismatch", contract.Value{Kind: contract.Money, Currency: "GBP"}, false},
+ {"unused money", "customer", "unexpected_money", contract.Value{Kind: contract.Text, Text: "Acme", MinorUnits: 1}, false},
+ {"invalid unicode", "customer", "invalid_value", contract.Value{Kind: contract.Text, Text: "\xff"}, false},
+ {"control", "customer", "invalid_value", contract.Value{Kind: contract.Text, Text: "secret\x00"}, false},
+ {"oversized", "customer", "invalid_value", contract.Value{Kind: contract.Text, Text: strings.Repeat("x", contract.MaxValueBytes+1)}, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ v := values()
+ if tc.remove {
+ delete(v, tc.key)
+ } else {
+ v[tc.key] = tc.value
+ }
+ doc, err := contract.Resolve(template(), v, contract.ISOFormat)
+ code(t, err, tc.code)
+ if !reflect.DeepEqual(doc, export.Document{}) {
+ t.Fatal("partial result returned")
+ }
+ if strings.Contains(err.Error(), "secret") {
+ t.Fatal("error leaked value")
+ }
+ })
+ }
+
+ tpl, v := template(), values()
+ tpl.Fields[0].Optional = true
+ delete(v, "customer")
+ doc, err := contract.Resolve(tpl, v, contract.ISOFormat)
+ if err != nil || len(doc.Root.Content[0].Content) != 1 {
+ t.Fatal("optional missing field", err)
+ }
+ v["customer"] = contract.Value{Kind: contract.Text}
+ if _, err := contract.Resolve(tpl, v, contract.ISOFormat); err != nil {
+ t.Fatal(err)
+ }
+ v["unknown_secret_key"] = contract.Value{Kind: contract.Text}
+ _, err = contract.Resolve(tpl, v, contract.ISOFormat)
+ code(t, err, "unexpected_values")
+ if strings.Contains(err.Error(), "unknown_secret_key") {
+ t.Fatal("untrusted key leaked")
+ }
+}
+
+func TestMoneyUsesExactMinorUnits(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ currency string
+ minor int64
+ want string
+ }{
+ {"EUR", math.MinInt64, "EUR -92233720368547758.08"},
+ {"EUR", math.MaxInt64, "EUR 92233720368547758.07"},
+ {"EUR", -1, "EUR -0.01"}, {"JPY", 100, "JPY 100"},
+ {"KWD", 1, "KWD 0.001"}, {"KWD", 1234567, "KWD 1234.567"},
+ } {
+ t.Run(tc.want, func(t *testing.T) {
+ tpl, v := template(), values()
+ tpl.Fields[2].Currency = tc.currency
+ v["fee"] = contract.Value{Kind: contract.Money, Currency: tc.currency, MinorUnits: tc.minor}
+ doc, err := contract.Resolve(tpl, v, contract.ISOFormat)
+ if err != nil || !strings.Contains(text(doc.Root), tc.want) {
+ t.Fatal(text(doc.Root), err)
+ }
+ })
+ }
+}
+
+func TestTemplateValidation(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ name, code string
+ change func(*contract.Template)
+ }{
+ {"version", "unsupported_version", func(t *contract.Template) { t.Version = 2 }},
+ {"title", "invalid_title", func(t *contract.Template) { t.Title = "\xff" }},
+ {"duplicate", "duplicate_field", func(t *contract.Template) { t.Fields = append(t.Fields, t.Fields[0]) }},
+ {"unused", "unused_field", func(t *contract.Template) {
+ t.Fields = append(t.Fields, contract.Field{Key: "unused", Label: "Unused", Kind: contract.Text})
+ }},
+ {"currency", "invalid_currency", func(t *contract.Template) { t.Fields[2].Currency = "xxx" }},
+ {"unknown", "unknown_field", func(t *contract.Template) { t.Root.Content[0].Content[1].Attrs.Key = "absent" }},
+ {"image", "unsupported_structure", func(t *contract.Template) { t.Root.Content[0].Content[0].Type = "image" }},
+ {"leaf children", "unexpected_children", func(t *contract.Template) { t.Root.Content[0].Content[0].Content = []contract.Node{field("fee")} }},
+ {"no children", "missing_children", func(t *contract.Template) { t.Root.Content = nil }},
+ {"bad heading", "invalid_heading", func(t *contract.Template) { t.Root.Content[0].Type = "heading" }},
+ {"block marks", "unexpected_marks", func(t *contract.Template) { t.Root.Marks = []export.Mark{{Type: "strong"}} }},
+ {"unknown mark", "unsupported_mark", func(t *contract.Template) { t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "link"}} }},
+ {"two sizes", "conflicting_marks", func(t *contract.Template) {
+ t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "size_8"}, {Type: "size_14"}}
+ }},
+ {"two fonts", "conflicting_marks", func(t *contract.Template) {
+ t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "font_sans"}, {Type: "font_mono"}}
+ }},
+ {"code font", "conflicting_marks", func(t *contract.Template) {
+ t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "code"}, {Type: "font_sans"}}
+ }},
+ {"indent", "invalid_indent", func(t *contract.Template) { t.Root.Content[0].Attrs.Indent = 9 }},
+ {"alignment", "invalid_alignment", func(t *contract.Template) { t.Root.Content[0].Attrs.Align = "justify" }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tpl := template()
+ tc.change(&tpl)
+ code(t, tpl.Validate(), tc.code)
+ })
+ }
+ _, err := contract.Resolve(template(), values(), "en-IE")
+ code(t, err, "unsupported_format")
+}
+
+func TestStrictJSON(t *testing.T) {
+ t.Parallel()
+ b, _ := json.Marshal(template())
+ parsed, err := contract.Parse(b)
+ if err != nil || !reflect.DeepEqual(parsed, template()) {
+ t.Fatal(err)
+ }
+ for _, input := range [][]byte{
+ append(append([]byte(nil), b...), []byte(` {}`)...),
+ []byte(strings.Replace(string(b), `"version":1`, `"version":1,"version":1`, 1)),
+ []byte(strings.Replace(string(b), `"version":1`, `"version":1,"unexpected":"secret"`, 1)),
+ []byte(strings.Replace(string(b), `"Service agreement"`, `"\ud800"`, 1)),
+ []byte(strings.Replace(string(b), `"paragraph"`, `"paragraph","attrs":{"surprise":true}`, 1)),
+ } {
+ _, err := contract.Parse(input)
+ code(t, err, "invalid_json")
+ }
+ _, err = contract.Parse(bytes.Repeat([]byte(" "), contract.MaxTemplateBytes+1))
+ code(t, err, "template_too_large")
+}
+
+func TestResourceBounds(t *testing.T) {
+ t.Parallel()
+ tpl := template()
+ for i := 0; i <= contract.MaxDepth; i++ {
+ tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}}
+ }
+ code(t, tpl.Validate(), "tree_limit")
+ tpl = template()
+ tpl.Root.Content = append(tpl.Root.Content, make([]contract.Node, contract.MaxNodes)...)
+ for i := 4; i < len(tpl.Root.Content); i++ {
+ tpl.Root.Content[i] = contract.Node{Type: "paragraph"}
+ }
+ code(t, tpl.Validate(), "tree_limit")
+ tpl = template()
+ for i := 0; i < 20; i++ {
+ tpl.Root.Content[0].Content = append(tpl.Root.Content[0].Content, field("customer"))
+ }
+ v := values()
+ v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("x ", contract.MaxValueBytes/2)}
+ _, err := contract.Resolve(tpl, v, contract.ISOFormat)
+ code(t, err, "expanded_text_limit")
+}
+
+func TestRenderPDF(t *testing.T) {
+ t.Parallel()
+ p, err := contract.Render(template(), values(), contract.ISOFormat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.HasPrefix(p.PDF, []byte("%PDF-")) || !bytes.Contains(p.PDF, []byte("%%EOF")) || p.SHA256 != sha256.Sum256(p.PDF) {
+ t.Fatal("invalid PDF or digest")
+ }
+ if p.TemplateVersion != 1 || p.Renderer == "" {
+ t.Fatal("missing version")
+ }
+ // Optional local QA artifact, always using the fictional fixture above.
+ // The independent pdftotext check is run against these exact output bytes.
+ if path := os.Getenv("CONTRACT_PREVIEW_PDF"); path != "" {
+ if err := os.WriteFile(path, p.PDF, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func TestRenderRefusesLossyPDF(t *testing.T) {
+ t.Parallel()
+ t.Run("missing glyph", func(t *testing.T) {
+ v := values()
+ v["customer"] = contract.Value{Kind: contract.Text, Text: "\U0010ffff"}
+ p, err := contract.Render(template(), v, contract.ISOFormat)
+ code(t, err, "missing_glyphs")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("partial artifact")
+ }
+ })
+ t.Run("nested indentation", func(t *testing.T) {
+ tpl := template()
+ tpl.Root.Content[0].Attrs.Indent = 8
+ for i := 0; i < 20; i++ {
+ tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}}
+ }
+ p, err := contract.Render(tpl, values(), contract.ISOFormat)
+ code(t, err, "layout_overflow")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("partial artifact")
+ }
+ })
+ t.Run("single glyph wider than column", func(t *testing.T) {
+ tpl, v := template(), values()
+ tpl.Root.Content[0].Attrs.Indent = 8
+ tpl.Root.Content[0].Content[1].Marks = []export.Mark{{Type: "size_72"}}
+ v["customer"] = contract.Value{Kind: contract.Text, Text: "W"}
+ for i := 0; i < 14; i++ {
+ tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}}
+ }
+ p, err := contract.Render(tpl, v, contract.ISOFormat)
+ code(t, err, "layout_overflow")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("partial artifact")
+ }
+ })
+}
+
+func TestRenderWorkLimits(t *testing.T) {
+ t.Parallel()
+ for _, literal := range []bool{false, true} {
+ tpl, v := template(), values()
+ long := strings.Repeat("x", contract.MaxWordBytes+1)
+ if literal {
+ tpl.Root.Content[0].Content[0].Text = long
+ } else {
+ v["customer"] = contract.Value{Kind: contract.Text, Text: long}
+ }
+ p, err := contract.Render(tpl, v, contract.ISOFormat)
+ code(t, err, "word_limit")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("partial output")
+ }
+ }
+ tpl, v := template(), values()
+ v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("x ", contract.MaxValueBytes/2)}
+ tpl.Root.Content[0].Content = append(tpl.Root.Content[0].Content, field("customer"))
+ p, err := contract.Render(tpl, v, contract.ISOFormat)
+ code(t, err, "render_text_limit")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("partial output")
+ }
+
+ tpl = template()
+ // Empty paragraphs are real blank lines: byte caps alone cannot bound pages.
+ for i := 0; i < 5000; i++ {
+ tpl.Root.Content = append(tpl.Root.Content, contract.Node{Type: "paragraph"})
+ }
+ p, err = contract.Render(tpl, values(), contract.ISOFormat)
+ code(t, err, "page_limit")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("truncated output")
+ }
+}
+
+func TestLongestWordInNarrowColumn(t *testing.T) {
+ t.Parallel()
+ tpl, v := template(), values()
+ tpl.Root.Content[0].Attrs.Indent = 8
+ // 468pt content - 288pt paragraph indent - 14*12pt quote indent =
+ // 12pt remaining. A regular W fits, but nearly every glyph wraps.
+ for i := 0; i < 14; i++ {
+ tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}}
+ }
+ v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("W", contract.MaxWordBytes)}
+ p, err := contract.Render(tpl, v, contract.ISOFormat)
+ if err != nil || len(p.PDF) == 0 {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/contract/resolve.go b/internal/contract/resolve.go
new file mode 100644
index 0000000..d0c20f8
--- /dev/null
+++ b/internal/contract/resolve.go
@@ -0,0 +1,220 @@
+package contract
+
+import (
+ "crypto/sha256"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/docs/internal/export"
+ "golang.org/x/text/currency"
+)
+
+// Value represents a supplied value, including zero money. Absence is a
+// missing map entry. Text is used for text/date, MinorUnits for money.
+type Value struct {
+ Kind Kind
+ Text string
+ MinorUnits int64
+ Currency string
+}
+
+const ISOFormat = "iso"
+
+func currencyScale(code string) (int, bool) {
+ if len(code) != 3 || code != strings.ToUpper(code) || code == "XXX" || code == "XTS" {
+ return 0, false
+ }
+ u, err := currency.ParseISO(code)
+ if err != nil {
+ return 0, false
+ }
+ scale, _ := currency.Standard.Rounding(u)
+ return scale, true
+}
+
+func formatValue(f Field, v Value, path string) (string, error) {
+ if v.Kind != f.Kind {
+ return "", problem("value_type", path)
+ }
+ if !validText(v.Text, MaxValueBytes) {
+ return "", problem("invalid_value", path)
+ }
+ if wordTooLong(v.Text) {
+ return "", problem("word_limit", path)
+ }
+ if v.Kind != Money && (v.MinorUnits != 0 || v.Currency != "") {
+ return "", problem("unexpected_money", path)
+ }
+ switch v.Kind {
+ case Text:
+ if strings.TrimSpace(v.Text) == "" && !f.Optional {
+ return "", problem("required_value", path)
+ }
+ return v.Text, nil
+ case Date:
+ date, err := time.Parse("2006-01-02", v.Text)
+ if err != nil || date.Year() < 1 || date.Format("2006-01-02") != v.Text {
+ return "", problem("invalid_date", path)
+ }
+ return v.Text, nil
+ case Money:
+ if v.Text != "" || v.Currency != f.Currency {
+ return "", problem("currency_mismatch", path)
+ }
+ scale, _ := currencyScale(f.Currency) // definition already validated
+ digits := strconv.FormatInt(v.MinorUnits, 10)
+ sign := ""
+ if strings.HasPrefix(digits, "-") {
+ sign, digits = "-", digits[1:]
+ }
+ if scale > 0 {
+ if len(digits) <= scale {
+ digits = strings.Repeat("0", scale+1-len(digits)) + digits
+ }
+ digits = digits[:len(digits)-scale] + "." + digits[len(digits)-scale:]
+ }
+ return f.Currency + " " + sign + digits, nil
+ }
+ return "", problem("unsupported_kind", path)
+}
+
+// Resolve validates all input before producing a fresh tree. It never mutates
+// the template or reinterprets a value as field syntax, markup or an expression.
+func Resolve(t Template, values map[string]Value, format string) (export.Document, error) {
+ if format != ISOFormat {
+ return export.Document{}, problem("unsupported_format", "format")
+ }
+ if err := t.Validate(); err != nil {
+ return export.Document{}, err
+ }
+ if len(values) > len(t.Fields) {
+ return export.Document{}, problem("unexpected_values", "values")
+ }
+ resolved := make(map[string]string, len(t.Fields))
+ for i, f := range t.Fields {
+ path := fmt.Sprintf("fields[%d]", i)
+ v, present := values[f.Key]
+ if !present {
+ if !f.Optional {
+ return export.Document{}, problem("required_value", path)
+ }
+ resolved[f.Key] = ""
+ continue
+ }
+ text, err := formatValue(f, v, path)
+ if err != nil {
+ return export.Document{}, err
+ }
+ resolved[f.Key] = text
+ }
+ for key := range values {
+ if _, ok := resolved[key]; !ok {
+ return export.Document{}, problem("unexpected_values", "values")
+ }
+ }
+ remaining := expansionBudget{text: MaxTextBytes - len(t.Title), nodes: MaxNodes}
+ root, err := resolveNode(t.Root, resolved, &remaining)
+ if err != nil {
+ return export.Document{}, err
+ }
+ return export.Document{Title: t.Title, Root: root}, nil
+}
+
+type expansionBudget struct{ text, nodes int }
+
+func resolveNode(n Node, values map[string]string, remaining *expansionBudget) (export.Node, error) {
+ remaining.nodes--
+ if remaining.nodes < 0 {
+ return export.Node{}, problem("expanded_node_limit", "root")
+ }
+ out := export.Node{Type: n.Type, Text: n.Text,
+ Attrs: export.Attrs{Level: n.Attrs.Level, Align: n.Attrs.Align, Indent: n.Attrs.Indent},
+ Marks: append([]export.Mark(nil), n.Marks...)}
+ if n.Type == "merge_field" {
+ out.Type, out.Text = "text", values[n.Attrs.Key]
+ }
+ remaining.text -= len(out.Text)
+ if remaining.text < 0 {
+ return export.Node{}, problem("expanded_text_limit", "root")
+ }
+ for _, child := range n.Content {
+ c, err := resolveNode(child, values, remaining)
+ if err != nil {
+ return export.Node{}, err
+ }
+ // An optional absent field becomes no node, not an invalid empty text.
+ if c.Type == "text" && c.Text == "" {
+ continue
+ }
+ if c.Type == "text" && strings.Contains(c.Text, "\n") {
+ // The exporter treats newlines inside a text run as whitespace.
+ // Explicit breaks preserve multiline values and code-block lines.
+ parts := strings.Split(c.Text, "\n")
+ remaining.nodes -= 2 * (len(parts) - 1)
+ if remaining.nodes < 0 {
+ return export.Node{}, problem("expanded_node_limit", "root")
+ }
+ for i, part := range parts {
+ if i > 0 {
+ out.Content = append(out.Content, export.Node{Type: "hard_break", Marks: append([]export.Mark(nil), c.Marks...)})
+ }
+ if part != "" {
+ run := c
+ run.Text = part
+ run.Marks = append([]export.Mark(nil), c.Marks...)
+ out.Content = append(out.Content, run)
+ }
+ }
+ continue
+ }
+ out.Content = append(out.Content, c)
+ }
+ return out, nil
+}
+
+// Preview is an in-memory rendering, not a persisted or authorised agreement.
+// Persist PDF exactly if it later becomes the subject of a signing operation.
+type Preview struct {
+ Document export.Document
+ PDF []byte
+ SHA256 [32]byte
+ TemplateVersion int
+ Renderer string
+}
+
+// Render refuses output that would substitute glyphs or overflow the page.
+// Errors return the zero Preview, never a partially usable document or PDF.
+func Render(t Template, values map[string]Value, format string) (Preview, error) {
+ doc, err := Resolve(t, values, format)
+ if err != nil {
+ return Preview{}, err
+ }
+ if renderedBytes(doc.Root)+len(doc.Title) > MaxRenderTextBytes {
+ return Preview{}, problem("render_text_limit", "document")
+ }
+ data, report, err := export.PDFBounded(doc, MaxPreviewPages)
+ if errors.Is(err, export.ErrPageLimit) {
+ return Preview{}, problem("page_limit", "document")
+ }
+ if err != nil {
+ return Preview{}, problem("render_failed", "document")
+ }
+ if !report.Empty() {
+ return Preview{}, problem("missing_glyphs", "document")
+ }
+ if report.LayoutOverflow {
+ return Preview{}, problem("layout_overflow", "document")
+ }
+ return Preview{Document: doc, PDF: data, SHA256: sha256.Sum256(data), TemplateVersion: Version, Renderer: "docs-contract-pdf-v1"}, nil
+}
+
+func renderedBytes(n export.Node) int {
+ total := len(n.Text)
+ for _, c := range n.Content {
+ total += renderedBytes(c)
+ }
+ return total
+}
diff --git a/internal/contract/template.go b/internal/contract/template.go
new file mode 100644
index 0000000..6579b3b
--- /dev/null
+++ b/internal/contract/template.go
@@ -0,0 +1,316 @@
+// Package contract resolves versioned contract templates into PDF previews.
+// It performs no source lookup or authorisation and does not issue agreements.
+// Callers must authorise and pin their inputs before invoking it.
+package contract
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/carlosframework/docs/internal/export"
+ "github.com/carlosframework/docs/internal/fonts"
+ json "github.com/go-json-experiment/json"
+)
+
+const (
+ Version = 1
+ // Limits bound decoding, recursive traversal and repeated-field expansion
+ // while leaving room for a substantial contract, without attachments.
+ MaxTemplateBytes = 1 << 20
+ MaxNodes = 10000
+ MaxDepth = 32
+ MaxFields = 128
+ MaxValueBytes = 64 << 10
+ MaxTextBytes = 1 << 20
+ // Titles and field labels are short display metadata, not contract bodies.
+ MaxLabelBytes = 256
+ // The exporter reshapes a word when wrapping it; bounding each word
+ // prevents a long identifier from causing quadratic shaping work.
+ MaxWordBytes = 1024
+ // Rendering is more expensive than structural resolution. These caps
+ // bound an interactive preview to an ordinary contract, not a book.
+ MaxRenderTextBytes = 128 << 10
+ MaxPreviewPages = 100
+)
+
+type Kind string
+
+const (
+ Text Kind = "text"
+ Date Kind = "date"
+ Money Kind = "money"
+)
+
+type Field struct {
+ Key string `json:"key"`
+ Label string `json:"label"`
+ Kind Kind `json:"kind"`
+ Optional bool `json:"optional,omitempty"`
+ Currency string `json:"currency,omitempty"`
+}
+
+// Attrs deliberately names only attributes the contract renderer understands.
+// Key belongs only to merge_field; the others are the Docs export vocabulary.
+type Attrs struct {
+ Level int `json:"level,omitempty"`
+ Align string `json:"align,omitempty"`
+ Indent int `json:"indent,omitempty"`
+ Key string `json:"key,omitempty"`
+}
+
+// Node is a template node, not a change to the live editor/CRDT schema.
+type Node struct {
+ Type string `json:"type"`
+ Attrs Attrs `json:"attrs,omitempty"`
+ Content []Node `json:"content,omitempty"`
+ Text string `json:"text,omitempty"`
+ Marks []export.Mark `json:"marks,omitempty"`
+}
+
+type Template struct {
+ Version int `json:"version"`
+ Title string `json:"title"`
+ Fields []Field `json:"fields"`
+ Root Node `json:"root"`
+}
+
+// Diagnostic contains only a stable code and structural coordinate. Labels,
+// text, raw parser errors and submitted values never enter an error string.
+type Diagnostic struct {
+ Code string
+ Path string
+}
+
+func (e *Diagnostic) Error() string { return "contract: " + e.Code + " at " + e.Path }
+func problem(code, path string) error { return &Diagnostic{Code: code, Path: path} }
+
+// Parse rejects duplicate/unknown JSON properties and invalid Unicode using
+// the same strict decoder already pinned by Docs. Validate also serves typed
+// callers, so decoding is not the only enforcement point.
+func Parse(data []byte) (Template, error) {
+ if len(data) > MaxTemplateBytes {
+ return Template{}, problem("template_too_large", "template")
+ }
+ var t Template
+ if err := json.Unmarshal(data, &t, json.RejectUnknownMembers(true)); err != nil {
+ return Template{}, problem("invalid_json", "template")
+ }
+ if err := t.Validate(); err != nil {
+ return Template{}, err
+ }
+ return t, nil
+}
+
+var keyPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]{0,63}$`)
+
+func validText(s string, max int) bool {
+ if len(s) > max || !utf8.ValidString(s) {
+ return false
+ }
+ for _, r := range s {
+ if (unicode.IsControl(r) && r != '\n' && r != '\t') || unicode.In(r, unicode.Cf) {
+ return false
+ }
+ }
+ return true
+}
+
+func wordTooLong(s string) bool {
+ length := 0
+ for _, r := range s {
+ if r == ' ' || r == '\n' || r == '\t' {
+ length = 0
+ } else {
+ length += utf8.RuneLen(r)
+ }
+ if length > MaxWordBytes {
+ return true
+ }
+ }
+ return false
+}
+
+func (t Template) Validate() error {
+ if t.Version != Version {
+ return problem("unsupported_version", "version")
+ }
+ if !validText(t.Title, MaxLabelBytes) || strings.ContainsAny(t.Title, "\n\t") {
+ return problem("invalid_title", "title")
+ }
+ if len(t.Fields) > MaxFields {
+ return problem("too_many_fields", "fields")
+ }
+ defs := make(map[string]Field, len(t.Fields))
+ for i, f := range t.Fields {
+ path := fmt.Sprintf("fields[%d]", i)
+ if !keyPattern.MatchString(f.Key) || !validText(f.Label, MaxLabelBytes) || strings.TrimSpace(f.Label) == "" {
+ return problem("invalid_field", path)
+ }
+ if _, exists := defs[f.Key]; exists {
+ return problem("duplicate_field", path)
+ }
+ switch f.Kind {
+ case Text, Date:
+ if f.Currency != "" {
+ return problem("unexpected_currency", path)
+ }
+ case Money:
+ if _, ok := currencyScale(f.Currency); !ok {
+ return problem("invalid_currency", path)
+ }
+ default:
+ return problem("unsupported_kind", path)
+ }
+ defs[f.Key] = f
+ }
+ v := validator{defs: defs, used: map[string]bool{}}
+ if err := v.node(t.Root, "", "root", 0); err != nil {
+ return err
+ }
+ for i, f := range t.Fields {
+ if !v.used[f.Key] {
+ return problem("unused_field", fmt.Sprintf("fields[%d]", i))
+ }
+ }
+ // Bound the encoded representation for typed callers too, after bounded
+ // traversal has excluded extreme depth and cyclic slice-backed trees.
+ b, err := json.Marshal(t)
+ if err != nil || len(b) > MaxTemplateBytes {
+ return problem("template_too_large", "template")
+ }
+ return nil
+}
+
+type validator struct {
+ defs map[string]Field
+ used map[string]bool
+ nodes, bytes int
+}
+
+func isBlock(s string) bool {
+ switch s {
+ case "paragraph", "heading", "blockquote", "code_block", "bullet_list", "ordered_list":
+ return true
+ }
+ return false
+}
+
+func childAllowed(parent, child string) bool {
+ switch parent {
+ case "":
+ return child == "doc"
+ case "doc", "blockquote", "list_item":
+ return isBlock(child)
+ case "bullet_list", "ordered_list":
+ return child == "list_item"
+ case "paragraph", "heading":
+ return child == "text" || child == "hard_break" || child == "merge_field"
+ case "code_block":
+ return child == "text"
+ }
+ return false
+}
+
+func (v *validator) node(n Node, parent, path string, depth int) error {
+ v.nodes++
+ if depth > MaxDepth || v.nodes > MaxNodes {
+ return problem("tree_limit", path)
+ }
+ if !childAllowed(parent, n.Type) {
+ return problem("unsupported_structure", path)
+ }
+ inline := n.Type == "text" || n.Type == "hard_break" || n.Type == "merge_field"
+ if inline && len(n.Content) != 0 {
+ return problem("unexpected_children", path)
+ }
+ if !inline && n.Type != "paragraph" && n.Type != "heading" && n.Type != "code_block" && len(n.Content) == 0 {
+ return problem("missing_children", path)
+ }
+ if n.Type == "list_item" && n.Content[0].Type != "paragraph" {
+ return problem("list_item_paragraph", path)
+ }
+ if n.Type != "text" && n.Text != "" {
+ return problem("unexpected_text", path)
+ }
+ if !validText(n.Text, MaxTextBytes) {
+ return problem("invalid_text", path)
+ }
+ if wordTooLong(n.Text) {
+ return problem("word_limit", path)
+ }
+ v.bytes += len(n.Text)
+ if v.bytes > MaxTextBytes {
+ return problem("text_limit", path)
+ }
+ a := n.Attrs
+ if n.Type == "heading" {
+ if a.Level < 1 || a.Level > 6 {
+ return problem("invalid_heading", path)
+ }
+ } else if a.Level != 0 {
+ return problem("unexpected_level", path)
+ }
+ if a.Indent < 0 || a.Indent > export.MaxIndent || (a.Indent != 0 && n.Type != "paragraph" && n.Type != "heading") {
+ return problem("invalid_indent", path)
+ }
+ if a.Align != "" && (n.Type != "paragraph" || (a.Align != "left" && a.Align != "center" && a.Align != "right")) {
+ return problem("invalid_alignment", path)
+ }
+ if n.Type == "merge_field" {
+ if _, ok := v.defs[a.Key]; !ok {
+ return problem("unknown_field", path)
+ }
+ v.used[a.Key] = true
+ } else if a.Key != "" {
+ return problem("unexpected_key", path)
+ }
+ if !inline && len(n.Marks) != 0 {
+ return problem("unexpected_marks", path)
+ }
+ if err := validateMarks(n.Marks, path); err != nil {
+ return err
+ }
+ if parent == "code_block" && len(n.Marks) != 0 {
+ return problem("unexpected_marks", path)
+ }
+ for i, child := range n.Content {
+ if err := v.node(child, n.Type, fmt.Sprintf("%s.content[%d]", path, i), depth+1); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func validateMarks(marks []export.Mark, path string) error {
+ groups := map[string]bool{}
+ for _, m := range marks {
+ group := m.Type
+ switch {
+ case m.Type == "strong" || m.Type == "em" || m.Type == "code":
+ case strings.HasPrefix(m.Type, "font_"):
+ if _, ok := fonts.ByKey(strings.TrimPrefix(m.Type, "font_")); !ok {
+ return problem("unsupported_mark", path)
+ }
+ group = "font"
+ case strings.HasPrefix(m.Type, "size_"):
+ if _, ok := export.SizePt(m.Type); !ok {
+ return problem("unsupported_mark", path)
+ }
+ group = "size"
+ default:
+ return problem("unsupported_mark", path)
+ }
+ if groups[group] {
+ return problem("conflicting_marks", path)
+ }
+ groups[group] = true
+ }
+ // The exporter forces the code family even if a font mark is present.
+ if groups["code"] && groups["font"] {
+ return problem("conflicting_marks", path)
+ }
+ return nil
+}
diff --git a/internal/export/pdf.go b/internal/export/pdf.go
index 1f41c52..6362ed9 100644
--- a/internal/export/pdf.go
+++ b/internal/export/pdf.go
@@ -1,6 +1,7 @@
package export
import (
+ "errors"
"sort"
"strconv"
"strings"
@@ -319,6 +320,10 @@ func Lines(doc Document) []string {
type Report struct {
// MissingRunes is sorted and deduplicated.
MissingRunes []rune
+ // LayoutOverflow reports text beyond its available line width. Ordinary
+ // export remains permissive; contract previews must refuse this report.
+ // Empty retains its existing meaning: no glyph substitutions.
+ LayoutOverflow bool
}
// Empty reports whether the export was fully faithful.
@@ -441,14 +446,34 @@ type blockContext struct {
// PDF lays a document out and returns the file.
func PDF(doc Document) ([]byte, Report, error) {
+ return renderPDF(doc, 0)
+}
+
+// ErrPageLimit means a bounded export did not fit. No truncated PDF is returned.
+var ErrPageLimit = errors.New("pdf: page limit exceeded")
+
+// PDFBounded bounds page allocation for interactive contract previews.
+// Normal exports continue to use PDF without this cap.
+func PDFBounded(doc Document, maxPages int) ([]byte, Report, error) {
+ if maxPages <= 0 {
+ return nil, Report{}, ErrPageLimit
+ }
+ return renderPDF(doc, maxPages)
+}
+
+func renderPDF(doc Document, maxPages int) ([]byte, Report, error) {
l := &layout{
- b: pdf.New(PageWidthPt, PageHeightPt),
- missing: map[rune]bool{},
- shaper: fonts.NewShaper(),
+ b: pdf.New(PageWidthPt, PageHeightPt),
+ missing: map[rune]bool{},
+ shaper: fonts.NewShaper(),
+ stopAfterPage: maxPages,
}
l.b.Title = doc.Title
l.newPage()
l.document(doc)
+ if l.stopped {
+ return nil, l.report(), ErrPageLimit
+ }
out, err := l.b.Bytes()
if err != nil {
@@ -545,9 +570,10 @@ type layout struct {
// once that many are complete. Nothing is drawn or reported after
// stopped is set, so a caller that wants one page pays for one page
// of layout rather than for all of a long document's.
- pages int
- stopAfterPage int
- stopped bool
+ pages int
+ stopAfterPage int
+ stopped bool
+ layoutOverflow bool
missing map[rune]bool
@@ -597,7 +623,7 @@ func (l *layout) newPage() {
}
func (l *layout) report() Report {
- out := Report{}
+ out := Report{LayoutOverflow: l.layoutOverflow}
for r := range l.missing {
out.MissingRunes = append(out.MissingRunes, r)
}
@@ -809,6 +835,9 @@ func (l *layout) paragraph(content []Node, ctx blockContext, lineHeight float64)
}
maxWidth := contentWidthPt - ctx.indent
+ if maxWidth <= 0 {
+ l.layoutOverflow = true
+ }
var line []token
var lineWidth float64
@@ -926,6 +955,14 @@ func (l *layout) drawLine(line []token, ctx blockContext, lineHeight float64) {
// instead would put a right-aligned line's right edge an inch off
// the paper.
x := MarginPt + ctx.indent
+ var measuredWidth float64
+ for _, t := range line {
+ measuredWidth += t.width
+ }
+ // A tiny tolerance absorbs floating-point sums, not a visible glyph.
+ if measuredWidth > contentWidthPt-ctx.indent+0.001 {
+ l.layoutOverflow = true
+ }
if ctx.align != "" {
var lineWidth float64
for _, t := range line {