oficina / docs Public

Implement live Fichas contract preparation and issuer-only signing pilot

Paul Campbell pushed by paul@keymail.dev 02432a4d8ce556a8e7c174d9a009427e0d5487de parent 1f75224
12 files changed, +1,206 −1
  • cmd/docs/main.go +3 −0
  • docs/superpowers/specs/2026-10-25-contract-workflow-design.md +9 −0
  • docs/superpowers/specs/2026-10-26-live-contract-demo.md +133 −0
  • internal/docs/app.go +13 −1
  • internal/docs/contract_actions.go +249 −0
  • internal/docs/contract_concurrency_test.go +178 −0
  • internal/docs/contract_demo.go +308 −0
  • internal/docs/contract_demo_test.go +185 −0
  • internal/docs/contract_view.go +74 −0
  • internal/docs/migrations/0009_contract_demo.sql +9 −0
  • internal/docs/views/contract.css +1 −0
  • internal/docs/views/contract.html +44 −0
diff --git a/cmd/docs/main.go b/cmd/docs/main.go
index 22d2cb1..4f49b10 100644
--- a/cmd/docs/main.go
+++ b/cmd/docs/main.go
@@ -283,6 +283,9 @@ func main() {
// same variable Home itself reads (home origins.go).
Directory: os.Getenv("HOME_DIRECTORY_ORIGIN"),
}
+ if os.Getenv("DOCS_CONTRACT_SOURCE") != "" || os.Getenv("DOCS_CONTRACT_PUBLIC_KEY") != "" || os.Getenv("DOCS_CONTRACT_IMPORTER") != "" || os.Getenv("DOCS_CONTRACT_TEAM") != "" {
+ cfg.ContractDemo = &docs.ContractDemoConfig{Source: os.Getenv("DOCS_CONTRACT_SOURCE"), PublicKey: os.Getenv("DOCS_CONTRACT_PUBLIC_KEY"), Importer: os.Getenv("DOCS_CONTRACT_IMPORTER"), Team: os.Getenv("DOCS_CONTRACT_TEAM")}
+ }
home := docs.HomeConfig{Issuer: os.Getenv("DOCS_HOME_ISSUER"), ConsumerID: os.Getenv("DOCS_HOME_CONSUMER_ID"), KeysBase64: os.Getenv("DOCS_HOME_KEYS_BASE64"), DEKBase64: os.Getenv("DOCS_HOME_DEK_BASE64")}
if home.Issuer != "" || home.ConsumerID != "" || home.KeysBase64 != "" || home.DEKBase64 != "" {
cfg.Home = &home
diff --git a/docs/superpowers/specs/2026-10-25-contract-workflow-design.md b/docs/superpowers/specs/2026-10-25-contract-workflow-design.md
index 7b31d55..a40f874 100644
--- a/docs/superpowers/specs/2026-10-25-contract-workflow-design.md
+++ b/docs/superpowers/specs/2026-10-25-contract-workflow-design.md
@@ -317,3 +317,12 @@ 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.
+
+## Correction and next slice, 2026-10-26
+
+The earlier §6 claim that Home integration is a prerequisite was too broad:
+suite §3 permits paired lone apps. The approved issuer-only demo is specified
+in `2026-10-26-live-contract-demo.md`, consuming suite revision 9 at
+`1d8e22eefca2a1df863b554dd60506de3689e7c4`. It adds a narrowly bounded source
+release and self-signing. It does not enable external recipients or resolve
+discussion 12. Live deployment and browser verification remain separate gates.
diff --git a/docs/superpowers/specs/2026-10-26-live-contract-demo.md b/docs/superpowers/specs/2026-10-26-live-contract-demo.md
new file mode 100644
index 0000000..218e1e6
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-26-live-contract-demo.md
@@ -0,0 +1,133 @@
+# Live Fichas contract demo
+
+Status: approved for implementation by independent GPT-6 review. Author: Codex, 2026-10-26.
+Paul requests an end-to-end demo this session, explicitly using live Fichas,
+and names paul@tito.io for the signature request. This slice supports only
+self-signing by the independently authenticated Docs issuer. It introduces
+no external grants, anonymous agreement routes, or team membership.
+
+## Scope and authority
+
+Fichas remains a lone app. Suite doctrine revision 8 §3 permits paired lone
+apps; Home migration is not a prerequisite (correcting the older workflow
+proposal). Source and destination authenticate independently. Matching an
+explicitly designated importer address constrains delivery, never links
+accounts. Only the configured Fichas owners may release; Card.OwnerID is
+provenance, not release authority. Docs requires full member admission and
+ownership on every route, including PDF, evidence and signature confirmation.
+
+Consumes suite doctrine revision 9 and its self-signing release annex at
+`1d8e22eefca2a1df863b554dd60506de3689e7c4`, adopted after independent
+GPT-6 review and passing CI. It does not resolve external sharing discussion 12.
+
+## One demo, one importer
+
+Both apps have optional configuration: fixed HTTPS peer origins and the
+same explicitly designated importer address. Fichas has a dedicated Ed25519
+release seed; Docs pins its public key. No automatic DNS discovery or
+generic sibling credentials. Deployment pairs these actual instances in the
+same operator's account; configuration is trusted, never request-supplied.
+Disable all new routes unless complete configuration validates at boot.
+Pairing additionally requires the same explicit team binding for custom
+origins; operator/account equality alone is insufficient. For this deployment
+the trusted binding is the existing oficina standalone team, explicitly
+recorded with both origins; standard team-labelled origins must match labels.
+
+The Docs workspace has a dedicated template editor, separate from the CRDT
+editor until old native clients preserve fields. Plain paragraphs and named
+field placeholders compile into the existing structural renderer; no HTML,
+expressions or recursive expansion. Templates are locally authored for this
+workflow with no imported/transitive sources. Field chips and a preview make
+bindings visible. Source keys remain stable. Date and EUR fee are explicitly
+typed manual inputs; unsupported source types refuse, never coerce silently.
+
+## Handoff
+
+1. An own-origin POST in Docs creates an encrypted, owner-scoped preparation
+ with a random UUID and a separate 256-bit browser-binding cookie. The
+ stored cookie hash binds this browser in addition to its signed-in owner.
+ A plain link takes the user to the configured Fichas contract page with
+ only the preparation UUID in the URL. It is not a bearer credential.
+2. Fichas requires its real admitted session. The user chooses one live card
+ and the individual text/date fields to release. No notes or call entries
+ are preselected. It displays exact values, revision, fixed Docs destination,
+ designated importer, purpose and expiry before a same-origin approval POST.
+3. The POST checks the submitted revision against a transactional reread,
+ refuses changes, and signs only those displayed selected values. The
+ preceding review signs a ten-minute confirmation digest covering the
+ exact selection, definitions, types, values, revision, actor and flow;
+ approval verifies that digest against a transactional reread. A changed
+ field definition or submitted selection therefore refuses too. The
+ envelope contains v1, source, destination, purpose, importer, source actor,
+ card ID/revision, preparation UUID, unique release UUID, timestamps and
+ typed stable fields. It is capped at 64 KiB, 32 fields, 8 KiB per value.
+ Issue authorisation expires after 30 minutes; this is irrevocable for
+ that window. Later card edits do not modify the released copy.
+ Docs requires expiry minus issue time to be at most 30 minutes and
+ issue time no more than 60 seconds in the future. Preview identity binds
+ release ID, template contents and manual inputs as well as PDF digest.
+4. A Fichas page submits the signed envelope to the fixed Docs receipt URL.
+ Only that page adds the exact destination to form-action. The receipt
+ route alone accepts cross-origin POST, with exact source Origin and
+ signature checks, strict bounded JSON and audience/purpose checks. It
+ parks bytes against the existing preparation; creates no document, grant
+ or agreement; and redirects to an owner-authenticated review GET.
+5. The review GET and own-origin commit POST require the original browser
+ cookie plus original owner. Signed importer must match current verified
+ address. One release and one preparation can bind only once. The commit
+ uses only the stored envelope, never substituted form values. Signing in
+ again resumes the URL but never substitutes a different person/browser.
+
+All copies and personal fields are encrypted with Docs' content encryption
+under a new record purpose. IDs, owner IDs, state and times are structural
+metadata, as in existing storage. No values/tokens in logs or URLs. All
+responses are no-store and no-referrer. Expiry is enforced on every access;
+expired unissued payloads are erased opportunistically. Backup erasure is
+not claimed; the live demo uses the existing instance backup trust model.
+After issuance, its seven-day retention replaces pending-source expiry;
+the frozen provenance remains part of that issued record.
+
+## Preview, issue, verify, sign
+
+Editing the template/inputs creates a fresh structural template and real PDF.
+Store the resolved paragraphs, exact PDF, SHA-256 and renderer version as one
+encrypted payload. The accessible reading view escapes the same resolved
+tree, not a second merge. A changed form demands a new preview. Issue POST
+binds to the stored preview digest and freezes it, before release expiry.
+One preparation yields one agreement; retries cannot mint another.
+
+The only recipient is the current verified Docs issuer address; the
+configuration and session must agree. Issue sends a fresh one-time random
+verification code by real configured mail to that address, not a link that
+grants document access. Store only its hash, bound to agreement/digest, with
+15-minute expiry and at most five guesses. A GET never consumes it. Successful
+verification is an own-origin POST, then a separate consent POST signs.
+Codes carry 128 random bits, rendered as 32 hexadecimal characters. Verification
+success lasts no longer than the original 15-minute challenge expiry, belongs
+to the same admitted issuer/agreement/digest, and is invalidated by resend.
+Attempt counts, challenge generation, verification and resend update the same
+versioned record atomically. Concurrent stale operations cannot restore codes.
+Consent names the immutable digest; evidence records issuer, timestamp,
+verification time, consent version/text and digest. Sign/void are conditional
+atomic transitions; completed records never reopen. An issued agreement
+expires after 24 hours. Re-send is rate-limited and invalidates the old code.
+Email failure is shown as delivery failure, separately from issued state;
+the owner may retry. No exactly-once delivery claim.
+
+All issued and completed demo records expire after seven days, including
+artifact/evidence routes. UI discloses that retention and offers download.
+Owner may void an unsigned agreement; terminal records cannot be signed.
+No automatic email to any customer or any address except the authenticated
+issuer. This proves address control and affirmative acceptance, not corporate
+authority, qualified signatures, or PDF certificate signing.
+
+## Evidence required
+
+Actual middleware tests: wrong origin, signature, audience, importer, browser,
+owner and expiry; replay; edited-source revision; cross-origin commit; missing
+values; template unchanged; digest-bound immutable issue; delivery failures;
+verification attempts/expiry; GET scanners; sign/void race; stranger PDF and
+evidence refusal; restart persistence. Browser demonstration must use real
+Fichas login and selected live record, real PDF, real email and consent.
+Exercise no-JS forms and narrow screen. Run independent whole-branch review
+and each repo's gate. Canary validation precedes enabling live source release.
diff --git a/internal/docs/app.go b/internal/docs/app.go
index a261e7b..c98b50c 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -42,6 +42,8 @@ import (
// Config configures New.
type Config struct {
+ ContractDemo *ContractDemoConfig
+
Home *HomeConfig
// Directory is the hub directory origin ($HOME_DIRECTORY_ORIGIN): the
// app switcher's "All apps". Empty means no switcher.
@@ -581,6 +583,10 @@ func New(cfg Config) (*App, error) {
} else {
h.remembered = home.navigation.returnPath
}
+ contracts, err := newContractDemo(h, cfg.ContractDemo, mailer, cipher)
+ if err != nil {
+ return nil, err
+ }
r := chi.NewRouter()
// Every route that is not a route is the 404 page for a browser, and a
// page GET to a POST-only path is too (errors.go).
@@ -592,7 +598,10 @@ func New(cfg Config) (*App, error) {
// Referer evidence; GET/HEAD/OPTIONS pass untouched, so this does
// nothing to "/" or "/d/{sqid}" and everything to "/documents",
// "/signin" and "/signout".
- r.Use(homeCSRF(cfg.Origin, home))
+ r.Use(contractReceiptCSRF(homeCSRF(cfg.Origin, home), contracts))
+ if contracts != nil {
+ r.Post("/contracts/receive", contracts.receipt)
+ }
r.Post("/native/request", native.ServeHTTP)
r.Post("/native/exchange", native.ServeHTTP)
r.Get("/native/start", native.ServeHTTP)
@@ -694,6 +703,9 @@ func New(cfg Config) (*App, error) {
home.mountAccount(r)
}
}
+ if contracts != nil {
+ contracts.mount(r)
+ }
r.Get("/", h.list)
r.Post("/documents", h.create)
// Title search for the jump-to palette (search.go). Inside
diff --git a/internal/docs/contract_actions.go b/internal/docs/contract_actions.go
new file mode 100644
index 0000000..7da203a
--- /dev/null
+++ b/internal/docs/contract_actions.go
@@ -0,0 +1,249 @@
+package docs
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "net/http"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/docs/internal/contract"
+ "github.com/carlosframework/docs/internal/export"
+ json "github.com/go-json-experiment/json"
+)
+
+var contractFieldKey = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
+var contractToken = regexp.MustCompile(`\{\{([a-z][a-z0-9_]{0,63})\}\}`)
+var contractMoney = regexp.MustCompile(`^[0-9]{1,12}\.[0-9]{2}$`)
+
+const contractConsent = "I have reviewed this agreement and agree to sign it electronically in my own name."
+
+func demoPreview(s *contractState) error {
+ if s.Release == nil || len(s.Body) > 16384 || len(s.Title) > 256 || strings.TrimSpace(s.Title) == "" || !contractMoney.MatchString(s.Fee) {
+ return errContract
+ }
+ minor, e := strconv.ParseInt(strings.ReplaceAll(s.Fee, ".", ""), 10, 64)
+ if e != nil {
+ return errContract
+ }
+ defs := map[string]contract.Field{"start_date": {Key: "start_date", Label: "Start date", Kind: contract.Date}, "fee": {Key: "fee", Label: "Fee", Kind: contract.Money, Currency: "EUR"}}
+ values := map[string]contract.Value{"start_date": {Kind: contract.Date, Text: s.Date}, "fee": {Kind: contract.Money, MinorUnits: minor, Currency: "EUR"}}
+ for _, f := range s.Release.Fields {
+ defs[f.Key] = contract.Field{Key: f.Key, Label: f.Label, Kind: contract.Kind(f.Kind)}
+ values[f.Key] = contract.Value{Kind: contract.Kind(f.Kind), Text: f.Value}
+ }
+ t := contract.Template{Version: 1, Title: s.Title, Root: contract.Node{Type: "doc"}}
+ used := map[string]bool{}
+ supplied := map[string]contract.Value{}
+ for _, line := range strings.Split(strings.ReplaceAll(s.Body, "\r\n", "\n"), "\n") {
+ p := contract.Node{Type: "paragraph"}
+ pos := 0
+ for _, m := range contractToken.FindAllStringSubmatchIndex(line, -1) {
+ if m[0] > pos {
+ p.Content = append(p.Content, contract.Node{Type: "text", Text: line[pos:m[0]]})
+ }
+ key := line[m[2]:m[3]]
+ f, ok := defs[key]
+ if !ok {
+ return errContract
+ }
+ p.Content = append(p.Content, contract.Node{Type: "merge_field", Attrs: contract.Attrs{Key: key}})
+ if !used[key] {
+ t.Fields = append(t.Fields, f)
+ supplied[key] = values[key]
+ used[key] = true
+ }
+ pos = m[1]
+ }
+ if pos < len(line) {
+ p.Content = append(p.Content, contract.Node{Type: "text", Text: line[pos:]})
+ }
+ // Malformed placeholders are errors, never literal clauses unnoticed by issuer.
+ remaining := contractToken.ReplaceAllString(line, "")
+ if strings.Contains(remaining, "{{") || strings.Contains(remaining, "}}") {
+ return errContract
+ }
+ t.Root.Content = append(t.Root.Content, p)
+ }
+ p, e := contract.Render(t, supplied, contract.ISOFormat)
+ if e != nil {
+ return e
+ }
+ s.Renderer = p.Renderer
+ s.PDF = p.PDF
+ s.Digest = hex.EncodeToString(p.SHA256[:])
+ s.Paragraphs = nil
+ var plain func(export.Node) string
+ plain = func(n export.Node) string {
+ if n.Type == "hard_break" {
+ return "\n"
+ }
+ out := n.Text
+ for _, c := range n.Content {
+ out += plain(c)
+ }
+ return out
+ }
+ for _, n := range p.Document.Root.Content {
+ s.Paragraphs = append(s.Paragraphs, plain(n))
+ }
+ identity, _ := json.Marshal([]string{s.Release.ID, s.Title, s.Body, s.Date, s.Fee, s.Digest, p.Renderer})
+ sum := sha256.Sum256(identity)
+ s.PreviewID = hex.EncodeToString(sum[:])
+ s.Stage = "preview"
+ return nil
+}
+func (d *contractDemo) action(w http.ResponseWriter, r *http.Request) {
+ contractHeaders(w)
+ r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
+ if r.ParseForm() != nil {
+ contractFail(w, r)
+ return
+ }
+ row, s, e := d.read(r)
+ if e != nil {
+ http.NotFound(w, r)
+ return
+ }
+ action := r.PathValue("action") // chi does not populate PathValue on all versions.
+ if action == "" {
+ parts := strings.Split(r.URL.Path, "/")
+ action = parts[len(parts)-1]
+ }
+ now := time.Now().Unix()
+ expires := row.Expires
+ sendCode := ""
+ switch action {
+ case "commit":
+ if s.Stage != "received" || !d.browser(r, s) || s.Release == nil || s.Release.Expires <= now {
+ contractFail(w, r)
+ return
+ }
+ s.Stage = "editing"
+ case "preview":
+ if s.Stage != "editing" && s.Stage != "preview" {
+ contractFail(w, r)
+ return
+ }
+ s.Title = r.PostForm.Get("title")
+ s.Body = r.PostForm.Get("body")
+ s.Date = r.PostForm.Get("date")
+ s.Fee = r.PostForm.Get("fee")
+ if e = demoPreview(&s); e != nil {
+ s.Stage = "editing"
+ s.PDF = nil
+ s.PreviewID = ""
+ d.page(w, row, s, "Changes were not saved. Check the field names, date and fee. Every field in the template must be selected in Fichas; use a fee such as 1250.00.")
+ return
+ }
+ case "issue":
+ if s.Stage != "preview" || s.Release == nil || s.Release.Expires <= now || r.PostForm.Get("preview") != s.PreviewID || len(s.PDF) == 0 {
+ contractFail(w, r)
+ return
+ }
+ s.Stage = "issued"
+ s.Issued = now
+ expires = now + 7*86400
+ sendCode = contractRandom(16)
+ setDemoChallenge(&s, sendCode, now)
+ case "resend":
+ if s.Stage != "issued" || now >= s.Issued+86400 || now-s.LastSent < 60 {
+ contractFail(w, r)
+ return
+ }
+ sendCode = contractRandom(16)
+ setDemoChallenge(&s, sendCode, now)
+ case "verify":
+ if s.Stage != "issued" || now >= s.Issued+86400 || s.ChallengeExpires <= now || s.Attempts >= 5 || s.Verified != 0 {
+ contractFail(w, r)
+ return
+ }
+ s.Attempts++
+ if contractHash(strings.ToLower(strings.TrimSpace(r.PostForm.Get("code")))+":"+row.ID+":"+s.Digest) == s.ChallengeHash {
+ s.Verified = now
+ s.ChallengeHash = ""
+ }
+ case "sign":
+ if s.Stage != "issued" || s.Verified == 0 || s.ChallengeExpires <= now || now >= s.Issued+86400 || r.PostForm.Get("digest") != s.Digest || r.PostForm.Get("consent") != "yes" {
+ contractFail(w, r)
+ return
+ }
+ s.Stage = "completed"
+ s.Signed = now
+ s.Consent = contractConsent
+ s.ChallengeHash = ""
+ case "void":
+ if s.Stage != "issued" {
+ contractFail(w, r)
+ return
+ }
+ s.Stage = "voided"
+ s.ChallengeHash = ""
+ s.Verified = 0
+ default:
+ http.NotFound(w, r)
+ return
+ }
+ if sendCode != "" {
+ s.ChallengeHash = contractHash(sendCode + ":" + row.ID + ":" + s.Digest)
+ }
+ if e = d.save(r, row, s, expires); e != nil {
+ contractFail(w, r)
+ return
+ }
+ if sendCode != "" {
+ // Commit the new challenge before sending; a timeout means delivery is
+ // uncertain and the visible state never claims successful verification.
+ e = d.mail.Send(r.Context(), s.Address, "Review and sign your Oficina agreement", "Your agreement is ready for your review.\n\nOpen "+d.h.origin+"/contracts/"+row.ID+" and sign in as "+s.Address+".\n\nVerification code: "+sendCode+"\n\nThis code expires in 15 minutes. Entering it verifies your address; signing is a separate action.\n\nThis pilot supports signing your own agreement only. Demo records are available for seven days.")
+ row2, s2, readErr := d.read(r)
+ if readErr == nil && s2.ChallengeHash == s.ChallengeHash {
+ if e == nil {
+ s2.Delivery = "sent"
+ } else {
+ s2.Delivery = "failed"
+ }
+ _ = d.save(r, row2, s2, row2.Expires)
+ }
+ }
+ http.Redirect(w, r, "/contracts/"+row.ID, http.StatusSeeOther)
+}
+func setDemoChallenge(s *contractState, code string, now int64) {
+ // The caller hashes the code with the record ID and immutable PDF digest before saving.
+ s.ChallengeHash = ""
+ s.ChallengeExpires = now + 900
+ s.LastSent = now
+ s.Attempts = 0
+ s.Verified = 0
+ s.Delivery = "pending"
+}
+func (d *contractDemo) pdf(w http.ResponseWriter, r *http.Request) {
+ row, s, e := d.read(r)
+ _ = row
+ if e != nil || len(s.PDF) == 0 || s.Stage == "voided" || (s.Stage == "issued" && time.Now().Unix() >= s.Issued+86400) {
+ http.NotFound(w, r)
+ return
+ }
+ contractHeaders(w)
+ w.Header().Set("Content-Type", "application/pdf")
+ w.Header().Set("Content-Disposition", `inline; filename="agreement.pdf"`)
+ w.Write(s.PDF)
+}
+func (d *contractDemo) evidence(w http.ResponseWriter, r *http.Request) {
+ row, s, e := d.read(r)
+ if e != nil || s.Stage != "completed" {
+ http.NotFound(w, r)
+ return
+ }
+ evidence := map[string]any{"version": 1, "agreement": row.ID, "title": s.Title, "sha256": s.Digest, "signer": s.Address, "issued_at": time.Unix(s.Issued, 0).UTC(), "verified_at": time.Unix(s.Verified, 0).UTC(), "signed_at": time.Unix(s.Signed, 0).UTC(), "consent_version": 1, "consent": s.Consent, "source": s.Release.Source, "source_card": s.Release.Card, "source_revision": s.Release.Revision, "release": s.Release.ID, "assurance": "Email address control and affirmative issuer-only electronic acceptance. No PDF certificate signature."}
+ raw, e := json.Marshal(evidence)
+ if e != nil {
+ contractFail(w, r)
+ return
+ }
+ contractHeaders(w)
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Disposition", `attachment; filename="signature-evidence.json"`)
+ w.Write(raw)
+}
diff --git a/internal/docs/contract_concurrency_test.go b/internal/docs/contract_concurrency_test.go
new file mode 100644
index 0000000..3705a93
--- /dev/null
+++ b/internal/docs/contract_concurrency_test.go
@@ -0,0 +1,178 @@
+package docs
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "errors"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+type contractFailingMail struct{}
+
+func (contractFailingMail) Send(_ context.Context, _ string, subject string, _ string) error {
+ if strings.Contains(subject, "agreement") {
+ return errors.New("test delivery failed")
+ }
+ return nil
+}
+
+func TestContractChallengeRacesExpiryAndRestart(t *testing.T) {
+ pub, _, _ := ed25519.GenerateKey(rand.Reader)
+ c := &ContractDemoConfig{Source: "https://fichas.example.com", Importer: "owner@example.com", Team: "test", PublicKey: base64.StdEncoding.EncodeToString(pub)}
+ cfg := Config{DBPath: filepath.Join(t.TempDir(), "contracts.db"), Env: "development", Origin: "https://docs.example.com", AllowedAddresses: c.Importer, ContractDemo: c, Mailer: contractFailingMail{}}
+ app, e := New(cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer func() { app.Close() }()
+ cookies := app.TestRequest(t, c.Importer, "GET", "/contracts", nil).Cookies()
+ owner := app.TestPerson(t, c.Importer)
+ cipher, _ := newContentCipher("", "development")
+ demo, _ := newContractDemo(app.handlers, c, app.mailRecorder, cipher)
+ makeRow := func(s contractState) contractRow {
+ row := contractRow{ID: uuid.NewString(), OwnerID: owner, Version: 1, Expires: time.Now().Unix() + 7*86400}
+ s.Address = c.Importer
+ s.Digest = "immutable-digest"
+ s.PDF = []byte("immutable-pdf")
+ if s.ChallengeHash != "" {
+ s.ChallengeHash = contractHash(s.ChallengeHash + ":" + row.ID + ":" + s.Digest)
+ }
+ if e := demo.seal(&row, s); e != nil {
+ t.Fatal(e)
+ }
+ if e := app.store.db.Create(&row).Error; e != nil {
+ t.Fatal(e)
+ }
+ return row
+ }
+ call := func(row contractRow, action string, f url.Values) *httptest.ResponseRecorder {
+ r := httptest.NewRequest("POST", "/contracts/"+row.ID+"/"+action, strings.NewReader(f.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.Header.Set("Sec-Fetch-Site", "same-origin")
+ for _, cookie := range cookies {
+ r.AddCookie(cookie)
+ }
+ w := httptest.NewRecorder()
+ app.Handler().ServeHTTP(w, r)
+ return w
+ }
+ load := func(row contractRow) contractState {
+ if e := app.store.db.First(&row, "id = ?", row.ID).Error; e != nil {
+ t.Fatal(e)
+ }
+ s, e := demo.open(row)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return s
+ }
+ now := time.Now().Unix()
+ issued := func() contractState {
+ return contractState{Stage: "issued", Issued: now, Verified: now, ChallengeExpires: now + 900, LastSent: now - 61, ChallengeHash: "test-code"}
+ }
+ // Actual conflicting HTTP terminal transitions: only one can succeed.
+ row := makeRow(issued())
+ start := make(chan struct{})
+ out := make(chan int, 2)
+ var wg sync.WaitGroup
+ for _, action := range []string{"sign", "void"} {
+ wg.Add(1)
+ go func(action string) {
+ defer wg.Done()
+ <-start
+ out <- call(row, action, url.Values{"digest": {"immutable-digest"}, "consent": {"yes"}}).Code
+ }(action)
+ }
+ close(start)
+ wg.Wait()
+ close(out)
+ success := 0
+ for code := range out {
+ if code == 303 {
+ success++
+ }
+ }
+ if success != 1 {
+ t.Fatalf("terminal winners %d", success)
+ }
+ final := load(row)
+ if final.Stage != "completed" && final.Stage != "voided" {
+ t.Fatal("no terminal state")
+ }
+ // Concurrent verify/resend cannot restore a verification for the prior generation.
+ s := issued()
+ s.Verified = 0
+ row = makeRow(s)
+ start = make(chan struct{})
+ wg = sync.WaitGroup{}
+ for _, action := range []string{"verify", "resend"} {
+ wg.Add(1)
+ go func(action string) { defer wg.Done(); <-start; call(row, action, url.Values{"code": {"test-code"}}) }(action)
+ }
+ close(start)
+ wg.Wait()
+ final = load(row)
+ if final.LastSent > now-61 && final.Verified != 0 {
+ t.Fatal("resend resurrected stale verification")
+ }
+ // Five wrong attempts exhaust the challenge, including a subsequent correct code.
+ s = issued()
+ s.Verified = 0
+ row = makeRow(s)
+ for i := 0; i < 5; i++ {
+ if w := call(row, "verify", url.Values{"code": {"wrong"}}); w.Code != 303 {
+ t.Fatalf("guess %d: %d", i, w.Code)
+ }
+ }
+ if w := call(row, "verify", url.Values{"code": {"test-code"}}); w.Code < 400 {
+ t.Fatal("exhausted challenge accepted")
+ }
+ s = issued()
+ s.ChallengeExpires = now - 1
+ row = makeRow(s)
+ if w := call(row, "sign", url.Values{"digest": {"immutable-digest"}, "consent": {"yes"}}); w.Code < 400 {
+ t.Fatal("stale verified challenge accepted")
+ }
+ s = issued()
+ s.Issued = now - 86401
+ row = makeRow(s)
+ if w := call(row, "resend", nil); w.Code < 400 {
+ t.Fatal("expired agreement renewed")
+ }
+ // SMTP refusal persists distinctly from issuance; a restart keeps that state.
+ s = issued()
+ s.Stage = "preview"
+ s.PreviewID = "reviewed"
+ s.Release = &contractRelease{Expires: now + 1800}
+ s.Issued = 0
+ row = makeRow(s)
+ if w := call(row, "issue", url.Values{"preview": {"reviewed"}}); w.Code != 303 {
+ t.Fatalf("issue failure path %d", w.Code)
+ }
+ final = load(row)
+ if final.Stage != "issued" || final.Delivery != "failed" {
+ t.Fatalf("delivery %s / %s", final.Stage, final.Delivery)
+ }
+ if e = app.Close(); e != nil {
+ t.Fatal(e)
+ }
+ app, e = New(cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ demo, _ = newContractDemo(app.handlers, c, app.mailRecorder, cipher)
+ final = load(row)
+ if final.Delivery != "failed" || final.Stage != "issued" || string(final.PDF) != "immutable-pdf" {
+ t.Fatal("restart lost immutable issue")
+ }
+}
diff --git a/internal/docs/contract_demo.go b/internal/docs/contract_demo.go
new file mode 100644
index 0000000..87945d9
--- /dev/null
+++ b/internal/docs/contract_demo.go
@@ -0,0 +1,308 @@
+package docs
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/mail"
+ "github.com/go-chi/chi/v5"
+ json "github.com/go-json-experiment/json"
+ "github.com/google/uuid"
+)
+
+// ContractDemoConfig is an explicitly paired, issuer-only pilot. It never
+// authorises external signing or derives team membership from an email.
+type ContractDemoConfig struct{ Source, Importer, Team, PublicKey string }
+type contractDemo struct {
+ h *handlers
+ cfg ContractDemoConfig
+ key ed25519.PublicKey
+ mail mail.Sender
+ cipher *contentCipher
+}
+type releasedField struct {
+ Key string `json:"key"`
+ Label string `json:"label"`
+ Kind string `json:"kind"`
+ Value string `json:"value"`
+}
+type contractRelease struct {
+ Version int `json:"version"`
+ Source string `json:"source"`
+ Destination string `json:"destination"`
+ Team string `json:"team"`
+ Purpose string `json:"purpose"`
+ Importer string `json:"importer"`
+ Actor string `json:"actor"`
+ Flow string `json:"flow"`
+ ID string `json:"id"`
+ Card int64 `json:"card"`
+ Revision int64 `json:"revision"`
+ Issued int64 `json:"issued"`
+ Expires int64 `json:"expires"`
+ Fields []releasedField `json:"fields"`
+}
+type contractRow struct {
+ ID string `gorm:"primaryKey"`
+ OwnerID int64
+ Version int64
+ Payload []byte
+ Expires int64
+}
+
+func (contractRow) TableName() string { return "contract_demo_records" }
+
+type contractState struct {
+ Renderer string
+
+ ReleaseBytes, ReleaseSignature []byte
+
+ Stage, Browser, Address, Title, Body, Date, Fee, Digest, PreviewID string
+ Release *contractRelease
+ PDF []byte
+ Paragraphs []string
+ Issued, Verified, ChallengeExpires, LastSent int64
+ ChallengeHash string
+ Attempts int
+ Delivery string
+ Signed int64
+ Consent string
+}
+
+const contractPurpose = "oficina.contract.self-sign.v1"
+const contractCookie = "docs_contract_browser"
+
+var errContract = errors.New("contract demo: request refused")
+
+func contractOrigin(s string) bool {
+ u, e := url.Parse(s)
+ return e == nil && u.Scheme == "https" && u.Host != "" && u.User == nil && u.Path == "" && u.RawQuery == "" && u.Fragment == "" && !u.ForceQuery
+}
+func newContractDemo(h *handlers, c *ContractDemoConfig, m mail.Sender, cipher *contentCipher) (*contractDemo, error) {
+ if c == nil {
+ return nil, nil
+ }
+ key, e := base64.StdEncoding.DecodeString(c.PublicKey)
+ if e != nil || len(key) != ed25519.PublicKeySize || !contractOrigin(c.Source) || !contractOrigin(h.origin) || c.Source == h.origin || !contractTeam(c.Source, c.Team) || !contractTeam(h.origin, c.Team) || c.Team == "" || len(c.Team) > 64 || c.Importer == "" || c.Importer != subjectOf(c.Importer) || !strings.Contains(c.Importer, "@") || h.homeEnabled || h.store.team != nil || !mail.IsConfigured(m) {
+ return nil, errContract
+ }
+ return &contractDemo{h: h, cfg: *c, key: key, mail: m, cipher: cipher}, nil
+}
+func contractRandom(n int) string {
+ b := make([]byte, n)
+ if _, e := rand.Read(b); e != nil {
+ panic(e)
+ }
+ return hex.EncodeToString(b)
+}
+func contractHash(s string) string { b := sha256.Sum256([]byte(s)); return hex.EncodeToString(b[:]) }
+func (d *contractDemo) actor(r *http.Request) (int64, error) {
+ a, e := d.h.actor(r)
+ if e != nil || !d.h.member(r) || a.VerifiedAddress == nil || *a.VerifiedAddress != d.cfg.Importer {
+ return 0, errContract
+ }
+ return a.PersonID, nil
+}
+func (d *contractDemo) seal(row *contractRow, s contractState) error {
+ raw, e := json.Marshal(s)
+ if e != nil {
+ return e
+ }
+ row.Payload, e = d.cipher.seal(4, row.ID, row.Version, 1, raw)
+ return e
+}
+func (d *contractDemo) open(row contractRow) (contractState, error) {
+ var s contractState
+ raw, e := d.cipher.open(4, row.ID, row.Version, 1, row.Payload)
+ if e != nil {
+ return s, e
+ }
+ e = json.Unmarshal(raw, &s)
+ return s, e
+}
+func (d *contractDemo) read(r *http.Request) (contractRow, contractState, error) {
+ var row contractRow
+ var s contractState
+ owner, e := d.actor(r)
+ if e != nil {
+ return row, s, e
+ }
+ e = d.h.store.db.WithContext(r.Context()).Where("id = ? AND owner_id = ?", chi.URLParam(r, "id"), owner).First(&row).Error
+ if e != nil {
+ return row, s, e
+ }
+ if row.Expires <= time.Now().Unix() {
+ d.h.store.db.WithContext(r.Context()).Where("id = ? AND owner_id = ? AND expires <= ?", row.ID, owner, time.Now().Unix()).Delete(&contractRow{})
+ return row, s, errContract
+ }
+ s, e = d.open(row)
+ return row, s, e
+}
+func (d *contractDemo) save(r *http.Request, row contractRow, s contractState, expires int64) error {
+ old := row.Version
+ row.Version++
+ row.Expires = expires
+ if e := d.seal(&row, s); e != nil {
+ return e
+ }
+ q := d.h.store.db.WithContext(r.Context()).Model(&contractRow{}).Where("id = ? AND owner_id = ? AND version = ?", row.ID, row.OwnerID, old).Updates(map[string]any{"version": row.Version, "payload": row.Payload, "expires": expires})
+ if q.Error != nil {
+ return q.Error
+ }
+ if q.RowsAffected != 1 {
+ return errContract
+ }
+ return nil
+}
+func (d *contractDemo) browser(r *http.Request, s contractState) bool {
+ cs := r.CookiesNamed(contractCookie)
+ return len(cs) == 1 && contractHash(cs[0].Value) == s.Browser
+}
+func (d *contractDemo) mount(r chi.Router) {
+ r.Get("/contracts/style.css", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/css; charset=utf-8")
+ w.Write(contractCSS)
+ })
+ r.Get("/contracts", d.home)
+ r.Post("/contracts/start", d.start)
+ r.Get("/contracts/{id}", d.show)
+ r.Post("/contracts/{id}/{action}", d.action)
+ r.Get("/contracts/{id}/document.pdf", d.pdf)
+ r.Get("/contracts/{id}/evidence.json", d.evidence)
+}
+func contractHeaders(w http.ResponseWriter) {
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Referrer-Policy", "no-referrer")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+}
+func contractFail(w http.ResponseWriter, r *http.Request) {
+ contractHeaders(w)
+ http.Error(w, "This contract request is unavailable or has changed. Return to Contracts and try again.", http.StatusConflict)
+}
+func (d *contractDemo) start(w http.ResponseWriter, r *http.Request) {
+ owner, e := d.actor(r)
+ if e != nil {
+ http.NotFound(w, r)
+ return
+ }
+ // At most 20 live preparations per owner bounds anonymous receipt storage.
+ var count int64
+ d.h.store.db.Model(&contractRow{}).Where("owner_id = ? AND expires > ?", owner, time.Now().Unix()).Count(&count)
+ if count >= 20 {
+ contractFail(w, r)
+ return
+ }
+ secret := contractRandom(32)
+ row := contractRow{ID: uuid.NewString(), OwnerID: owner, Version: 1, Expires: time.Now().Add(30 * time.Minute).Unix()}
+ s := contractState{Stage: "connecting", Browser: contractHash(secret), Address: d.cfg.Importer, Title: "Service agreement", Date: time.Now().Format("2006-01-02"), Fee: "1250.00", Body: "Service agreement\n\nThis agreement is prepared for {{f_name}}.\n\nThe services begin on {{start_date}}. The agreed fee is {{fee}}.\n\nThe provider will deliver the services described and agreed by both parties.\n\nPrepared for review and acceptance by the issuer."}
+ if d.seal(&row, s) != nil || d.h.store.db.Create(&row).Error != nil {
+ contractFail(w, r)
+ return
+ }
+ http.SetCookie(w, &http.Cookie{Name: contractCookie, Value: secret, Path: "/contracts/" + row.ID, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: 1800})
+ http.Redirect(w, r, "/contracts/"+row.ID, http.StatusSeeOther)
+}
+func (d *contractDemo) receipt(w http.ResponseWriter, r *http.Request) {
+ contractHeaders(w)
+ if r.Method != "POST" || r.Header.Get("Origin") != d.cfg.Source {
+ http.NotFound(w, r)
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, 128<<10)
+ if r.ParseForm() != nil {
+ contractFail(w, r)
+ return
+ }
+ raw, e := base64.RawURLEncoding.DecodeString(r.PostForm.Get("payload"))
+ sig, se := base64.RawURLEncoding.DecodeString(r.PostForm.Get("signature"))
+ if e != nil || se != nil || len(raw) > 64<<10 || !ed25519.Verify(d.key, raw, sig) {
+ contractFail(w, r)
+ return
+ }
+ var rel contractRelease
+ if json.Unmarshal(raw, &rel, json.RejectUnknownMembers(true)) != nil {
+ contractFail(w, r)
+ return
+ }
+ now := time.Now().Unix()
+ if rel.Version != 1 || rel.Source != d.cfg.Source || rel.Destination != d.h.origin || rel.Team != d.cfg.Team || rel.Importer != d.cfg.Importer || rel.Purpose != contractPurpose || rel.Expires <= now || rel.Issued > now+60 || rel.Expires-rel.Issued > 1800 || rel.Expires <= rel.Issued || rel.Card < 1 || rel.Revision < 1 || len(rel.Fields) == 0 || len(rel.Fields) > 32 {
+ contractFail(w, r)
+ return
+ }
+ if _, e = uuid.Parse(rel.ID); e != nil {
+ contractFail(w, r)
+ return
+ }
+ if _, e = uuid.Parse(rel.Flow); e != nil {
+ contractFail(w, r)
+ return
+ }
+ seen := map[string]bool{}
+ for _, f := range rel.Fields {
+ if seen[f.Key] || !contractFieldKey.MatchString(f.Key) || f.Key == "fee" || f.Key == "start_date" || len(f.Value) > 8192 || len(f.Label) > 256 || (f.Kind != "text" && f.Kind != "date") {
+ contractFail(w, r)
+ return
+ }
+ seen[f.Key] = true
+ }
+ var row contractRow
+ if d.h.store.db.Where("id = ? AND expires > ?", rel.Flow, now).First(&row).Error != nil {
+ contractFail(w, r)
+ return
+ }
+ s, e := d.open(row)
+ if e != nil || s.Stage != "connecting" || s.Release != nil || s.Address != rel.Importer {
+ contractFail(w, r)
+ return
+ }
+ s.Release = &rel
+ s.ReleaseBytes = raw
+ s.ReleaseSignature = sig
+ s.Stage = "received"
+ // The flow ID is signed and fixed: each release can target only its one row.
+ expires := row.Expires
+ if rel.Expires < expires {
+ expires = rel.Expires
+ }
+ if d.save(r, row, s, expires) != nil {
+ contractFail(w, r)
+ return
+ }
+ http.Redirect(w, r, "/contracts/"+row.ID, http.StatusSeeOther)
+}
+
+// Only this signed, origin-checked receipt bypasses ordinary same-origin CSRF.
+func contractReceiptCSRF(protect func(http.Handler) http.Handler, d *contractDemo) func(http.Handler) http.Handler {
+ return func(next http.Handler) http.Handler {
+ checked := protect(next)
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if d != nil && r.Method == "POST" && r.URL.Path == "/contracts/receive" {
+ d.receipt(w, r)
+ return
+ }
+ checked.ServeHTTP(w, r)
+ })
+ }
+}
+
+// Standard team-labelled suite hosts must agree with the explicit binding.
+// Standalone/custom hosts are paired by the trusted deployment configuration.
+func contractTeam(origin, team string) bool {
+ u, e := url.Parse(origin)
+ if e != nil {
+ return false
+ }
+ parts := strings.Split(u.Hostname(), ".")
+ if strings.HasSuffix(u.Hostname(), ".oficina.works") && len(parts) >= 4 {
+ return len(parts) == 4 && parts[0] == team
+ }
+ return true
+}
diff --git a/internal/docs/contract_demo_test.go b/internal/docs/contract_demo_test.go
new file mode 100644
index 0000000..77efc39
--- /dev/null
+++ b/internal/docs/contract_demo_test.go
@@ -0,0 +1,185 @@
+package docs
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ json "github.com/go-json-experiment/json"
+ "github.com/google/uuid"
+)
+
+func TestContractLiveFlowAndBoundaries(t *testing.T) {
+ pub, key, _ := ed25519.GenerateKey(rand.Reader)
+ cfg := &ContractDemoConfig{Source: "https://fichas.example.com", Importer: "issuer@example.com", Team: "test-team", PublicKey: base64.StdEncoding.EncodeToString(pub)}
+ app, e := NewForTestWith(t, Config{Origin: "https://docs.example.com", AllowedAddresses: "issuer@example.com,stranger@example.com", ContractDemo: cfg})
+ if e != nil {
+ t.Fatal(e)
+ }
+ auth := app.TestRequest(t, cfg.Importer, "GET", "/contracts", nil).Cookies()
+ request := func(method, path string, form url.Values, cookies []*http.Cookie, origin string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(method, path, strings.NewReader(form.Encode()))
+ for _, c := range cookies {
+ req.AddCookie(c)
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", origin)
+ if origin == cfg.Source {
+ req.Header.Set("Sec-Fetch-Site", "cross-site")
+ } else if origin == "https://docs.example.com" {
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ } else {
+ req.Header.Set("Sec-Fetch-Site", "cross-site")
+ }
+ rec := httptest.NewRecorder()
+ app.Handler().ServeHTTP(rec, req)
+ return rec
+ }
+ own := func(method, path string, form url.Values) *httptest.ResponseRecorder {
+ return request(method, path, form, auth, "https://docs.example.com")
+ }
+ start := own("POST", "/contracts/start", nil)
+ if start.Code != 303 {
+ t.Fatalf("start %d: %s", start.Code, start.Body)
+ }
+ path := start.Header().Get("Location")
+ id := strings.TrimPrefix(path, "/contracts/")
+ auth = append(auth, start.Result().Cookies()...)
+ if got := own("GET", path, nil); got.Code != 200 || !strings.Contains(got.Body.String(), "Choose a customer") {
+ t.Fatalf("connect %d %s", got.Code, got.Body)
+ }
+ now := time.Now().Unix()
+ rel := contractRelease{Version: 1, Source: cfg.Source, Destination: "https://docs.example.com", Team: cfg.Team, Purpose: contractPurpose, Importer: cfg.Importer, Actor: "source-owner@example.com", Flow: id, ID: uuid.NewString(), Card: 1, Revision: 3, Issued: now, Expires: now + 1800, Fields: []releasedField{{"f_name", "Name", "text", "Acme <script> Workshops"}}}
+ envelope := func(r contractRelease) url.Values {
+ raw, _ := json.Marshal(r)
+ return url.Values{"payload": {base64.RawURLEncoding.EncodeToString(raw)}, "signature": {base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, raw))}}
+ }
+ for _, tc := range []struct {
+ name string
+ edit func(*contractRelease)
+ }{{"audience", func(r *contractRelease) { r.Destination = "https://elsewhere.example.com" }}, {"importer", func(r *contractRelease) { r.Importer = "stranger@example.com" }}, {"expiry", func(r *contractRelease) { r.Expires = now - 1 }}, {"future", func(r *contractRelease) { r.Issued = now + 120 }}, {"long release", func(r *contractRelease) { r.Expires = now + 1801 }}, {"team", func(r *contractRelease) { r.Team = "other" }}} {
+ t.Run(tc.name, func(t *testing.T) {
+ bad := rel
+ tc.edit(&bad)
+ if rec := request("POST", "/contracts/receive", envelope(bad), nil, cfg.Source); rec.Code < 400 {
+ t.Fatal("accepted invalid release")
+ }
+ })
+ }
+ if rec := request("POST", "/contracts/receive", envelope(rel), nil, "https://evil.example.com"); rec.Code < 400 {
+ t.Fatal("foreign origin accepted")
+ }
+ bad := envelope(rel)
+ bad.Set("signature", base64.RawURLEncoding.EncodeToString(make([]byte, 64)))
+ if rec := request("POST", "/contracts/receive", bad, nil, cfg.Source); rec.Code < 400 {
+ t.Fatal("bad signature")
+ }
+ if rec := request("POST", "/contracts/receive", envelope(rel), nil, cfg.Source); rec.Code != 303 {
+ t.Fatalf("receipt %d %s", rec.Code, rec.Body)
+ }
+ if rec := request("POST", "/contracts/receive", envelope(rel), nil, cfg.Source); rec.Code < 400 {
+ t.Fatal("replay")
+ }
+ if rec := request("POST", path+"/commit", nil, auth, cfg.Source); rec.Code != 403 {
+ t.Fatalf("cross-origin commit %d", rec.Code)
+ }
+ if rec := request("POST", path+"/commit", nil, auth[:1], "https://docs.example.com"); rec.Code < 400 {
+ t.Fatal("missing browser binding")
+ }
+ if rec := own("POST", path+"/commit", nil); rec.Code != 303 {
+ t.Fatalf("commit %d %s", rec.Code, rec.Body)
+ }
+ form := url.Values{"title": {"Consulting agreement"}, "body": {"Prepared for {{f_name}}\nFee: {{fee}}\nStarts {{start_date}}"}, "fee": {"1250.50"}, "date": {"2028-02-29"}}
+ if rec := own("POST", path+"/preview", form); rec.Code != 303 {
+ t.Fatalf("preview %d %s", rec.Code, rec.Body)
+ }
+ page := own("GET", path, nil)
+ if !strings.Contains(page.Body.String(), "Acme &lt;script&gt; Workshops") {
+ t.Fatal("accessible content absent or unescaped")
+ }
+ preview := regexp.MustCompile(`name="preview" value="([a-f0-9]+)"`).FindStringSubmatch(page.Body.String())
+ if len(preview) != 2 {
+ t.Fatal("preview identity missing")
+ }
+ original := own("GET", path+"/document.pdf", nil)
+ if !bytes.HasPrefix(original.Body.Bytes(), []byte("%PDF-")) {
+ t.Fatal("not actual PDF")
+ }
+ if rec := own("POST", path+"/issue", url.Values{"preview": {"wrong"}}); rec.Code < 400 {
+ t.Fatal("wrong preview accepted")
+ }
+ if rec := own("POST", path+"/issue", url.Values{"preview": {preview[1]}}); rec.Code != 303 {
+ t.Fatalf("issue %d %s", rec.Code, rec.Body)
+ }
+ app.mailRecorder.mu.Lock()
+ body, to := app.mailRecorder.lastBody, app.mailRecorder.lastTo
+ app.mailRecorder.mu.Unlock()
+ code := regexp.MustCompile(`Verification code: ([a-f0-9]{32})`).FindStringSubmatch(body)
+ if len(code) != 2 || to != cfg.Importer {
+ t.Fatal("real mail adapter not called for fixed issuer")
+ }
+ if rec := own("POST", path+"/issue", url.Values{"preview": {preview[1]}}); rec.Code < 400 {
+ t.Fatal("duplicate issue accepted")
+ }
+ if rec := own("POST", path+"/preview", form); rec.Code < 400 {
+ t.Fatal("issued payload editable")
+ }
+ if rec := own("GET", path+"/verify?code="+code[1], nil); rec.Code < 400 {
+ t.Fatal("GET verification")
+ }
+ if rec := own("POST", path+"/verify", url.Values{"code": {code[1]}}); rec.Code != 303 {
+ t.Fatalf("verify %d", rec.Code)
+ }
+ page = own("GET", path, nil)
+ digest := regexp.MustCompile(`name="digest" value="([a-f0-9]+)"`).FindStringSubmatch(page.Body.String())
+ if len(digest) != 2 {
+ t.Fatal("consent not available after verification")
+ }
+ if rec := own("POST", path+"/sign", url.Values{"digest": {digest[1]}, "consent": {"yes"}}); rec.Code != 303 {
+ t.Fatalf("sign %d %s", rec.Code, rec.Body)
+ }
+ if rec := own("POST", path+"/void", nil); rec.Code < 400 {
+ t.Fatal("completed record reopened")
+ }
+ if got := own("GET", path+"/document.pdf", nil); !bytes.Equal(got.Body.Bytes(), original.Body.Bytes()) {
+ t.Fatal("issued PDF mutated")
+ }
+ if got := own("GET", path+"/evidence.json", nil); got.Code != 200 || !strings.Contains(got.Body.String(), digest[1]) {
+ t.Fatal("evidence not bound")
+ }
+ stranger := app.TestRequest(t, "stranger@example.com", "GET", path+"/document.pdf", nil).Cookies()
+ for _, suffix := range []string{"", "/document.pdf", "/evidence.json"} {
+ if rec := request("GET", path+suffix, nil, stranger, "https://docs.example.com"); rec.Code != 404 {
+ t.Fatalf("stranger %s got %d", suffix, rec.Code)
+ }
+ }
+ var row contractRow
+ if e = app.store.db.First(&row, "id = ?", id).Error; e != nil {
+ t.Fatal(e)
+ }
+ if bytes.Contains(row.Payload, []byte("Acme")) || bytes.Contains(row.Payload, []byte(code[1])) {
+ t.Fatal("plaintext stored")
+ }
+ // Optimistic state changes ensure competing sign/void/resend writers have one winner.
+ cipher, _ := newContentCipher("", "development")
+ demo, _ := newContractDemo(app.handlers, cfg, app.mailRecorder, cipher)
+ state, e := demo.open(row)
+ if e != nil {
+ t.Fatal(e)
+ }
+ req := httptest.NewRequest("POST", path, nil)
+ if e = demo.save(req, row, state, row.Expires); e != nil {
+ t.Fatal(e)
+ }
+ if e = demo.save(req, row, state, row.Expires); e == nil {
+ t.Fatal("stale writer accepted")
+ }
+}
diff --git a/internal/docs/contract_view.go b/internal/docs/contract_view.go
new file mode 100644
index 0000000..eab380a
--- /dev/null
+++ b/internal/docs/contract_view.go
@@ -0,0 +1,74 @@
+package docs
+
+import (
+ "bytes"
+ _ "embed"
+ "html/template"
+ "net/http"
+ "time"
+)
+
+//go:embed views/contract.html
+var contractPage string
+
+//go:embed views/contract.css
+var contractCSS []byte
+var contractView = template.Must(template.New("contract").Funcs(template.FuncMap{"when": func(v int64) string { return time.Unix(v, 0).UTC().Format("2 January 2006 at 15:04 UTC") }, "token": func(k string) string { return "{{" + k + "}}" }}).Parse(contractPage))
+
+type contractViewData struct {
+ ID, Error, Source, Connect string
+ State contractState
+ Home bool
+ Expired bool
+ Retention int64
+ Records []contractSummary
+}
+type contractSummary struct{ ID, Title, Stage string }
+
+func (d *contractDemo) home(w http.ResponseWriter, r *http.Request) {
+ owner, e := d.actor(r)
+ if e != nil {
+ http.NotFound(w, r)
+ return
+ }
+ var rows []contractRow
+ if d.h.store.db.Where("owner_id = ? AND expires > ?", owner, time.Now().Unix()).Order("expires desc").Limit(20).Find(&rows).Error != nil {
+ contractFail(w, r)
+ return
+ }
+ v := contractViewData{Home: true, Source: d.cfg.Source, State: contractState{Address: d.cfg.Importer}}
+ for _, row := range rows {
+ if s, e := d.open(row); e == nil {
+ v.Records = append(v.Records, contractSummary{row.ID, s.Title, s.Stage})
+ }
+ }
+ d.render(w, v)
+}
+func (d *contractDemo) show(w http.ResponseWriter, r *http.Request) {
+ row, s, e := d.read(r)
+ if e != nil {
+ http.NotFound(w, r)
+ return
+ }
+ if (s.Stage == "connecting" || s.Stage == "received") && !d.browser(r, s) {
+ http.NotFound(w, r)
+ return
+ }
+ if s.Stage == "issued" && s.ChallengeExpires <= time.Now().Unix() {
+ s.Verified = 0
+ }
+ d.page(w, row, s, "")
+}
+func (d *contractDemo) page(w http.ResponseWriter, row contractRow, s contractState, message string) {
+ d.render(w, contractViewData{ID: row.ID, State: s, Error: message, Source: d.cfg.Source, Connect: d.cfg.Source + "/contracts/prepare?flow=" + row.ID, Retention: row.Expires, Expired: s.Stage == "issued" && time.Now().Unix() >= s.Issued+86400})
+}
+func (d *contractDemo) render(w http.ResponseWriter, v contractViewData) {
+ var buf bytes.Buffer
+ if e := contractView.Execute(&buf, v); e != nil {
+ http.Error(w, "The contract page could not be shown.", 500)
+ return
+ }
+ contractHeaders(w)
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Write(buf.Bytes())
+}
diff --git a/internal/docs/migrations/0009_contract_demo.sql b/internal/docs/migrations/0009_contract_demo.sql
new file mode 100644
index 0000000..a162f48
--- /dev/null
+++ b/internal/docs/migrations/0009_contract_demo.sql
@@ -0,0 +1,9 @@
+-- Encrypted pilot state; no customer values, addresses or tokens in columns.
+CREATE TABLE contract_demo_records (
+ id TEXT PRIMARY KEY NOT NULL,
+ owner_id INTEGER NOT NULL REFERENCES people(id),
+ version INTEGER NOT NULL,
+ payload BLOB NOT NULL,
+ expires INTEGER NOT NULL
+);
+CREATE INDEX contract_demo_owner ON contract_demo_records(owner_id);
diff --git a/internal/docs/views/contract.css b/internal/docs/views/contract.css
new file mode 100644
index 0000000..0a16290
--- /dev/null
+++ b/internal/docs/views/contract.css
@@ -0,0 +1 @@
+:root{font:16px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#25352f;background:#f6f5ef;color-scheme:light}*{box-sizing:border-box}body{margin:0}a{color:#245b46;text-underline-offset:4px}button,input,textarea{font:inherit}.bar{display:flex;align-items:center;gap:32px;padding:22px 5vw;border-bottom:1px solid #dddcd3}.bar a{text-decoration:none}.brand{font-size:21px}.bar>span{margin-left:auto;font-size:13px;color:#68716a}main{max-width:1120px;margin:64px auto;padding:0 36px 60px}h1{font-size:clamp(32px,4.7vw,58px);font-weight:550;line-height:1.12;letter-spacing:-1.8px;margin:18px 0 25px}h2{font-size:20px;font-weight:600}.eyebrow{font-size:11px;letter-spacing:2px;font-weight:650;color:#65756b}.intro{font-size:19px;color:#5c6a61;line-height:1.65;margin:0 0 30px}.button,button{display:inline-block;border:1px solid transparent;border-radius:7px;padding:12px 21px;text-decoration:none;cursor:pointer;font-weight:550}.primary{background:#245b46;color:#fff}.primary:hover{background:#194532}.secondary{background:transparent;border-color:#c6cec7;color:#315443}form{margin:22px 0}.note{margin-top:45px;padding:22px;background:#eceee5;border-radius:9px;max-width:750px;font-size:14px}.note p{margin-bottom:0}.hint,small{color:#5e6c63;font-size:13px;display:block}.recent{margin-top:60px;max-width:750px}.record{display:flex;justify-content:space-between;padding:18px 0;border-bottom:1px solid #d9ded5;text-decoration:none}.record span{font-size:13px}.steps{display:flex;gap:32px;border-bottom:1px solid #d9ded5;padding-bottom:18px;margin-bottom:42px;color:#607165;font-size:13px}.workspace{display:grid;grid-template-columns:minmax(0,2.3fr) minmax(220px,1fr);gap:42px}.workspace form{margin-top:0}label{display:block;font-size:14px;font-weight:600;margin:20px 0 7px}input,textarea{display:block;width:100%;border:1px solid #c6cfc5;border-radius:5px;padding:11px 12px;background:#fffefa;color:#243c2d}textarea{font-family:Georgia,serif;font-size:17px;line-height:1.65;resize:vertical}.twocol{display:grid;grid-template-columns:1fr 1fr;gap:20px}form>.primary{margin-top:18px}.fields{padding:18px 24px;background:#eceee5;border-radius:9px;align-self:start}.fields h2{font-size:15px}.field{border-bottom:1px solid #d2d8cc;padding:13px 0}.field strong{font-size:13px;display:block}.field p{font-size:14px;margin:5px 0}.fields code{display:block;font-size:12px;margin:7px 0;color:#315745}.preview{margin-top:45px;padding-top:25px;border-top:1px solid #d4d9cf}.preview-head{display:flex;align-items:center;justify-content:space-between;gap:15px}.paper{background:#fffefa;box-shadow:0 3px 18px #273d2310;border:1px solid #e0e0d6;padding:55px 65px;max-width:800px;font:18px/1.7 Georgia,serif;margin:20px 0 32px;white-space:pre-wrap;overflow-wrap:anywhere}.paper p{min-height:1em;margin:0 0 1em}.facts{display:grid;grid-template-columns:160px 1fr;gap:14px 22px;max-width:750px;padding:22px 0}.facts dt{font-size:13px;color:#617064}.facts dd{margin:0;white-space:pre-wrap}.check{display:flex;gap:12px;align-items:flex-start;max-width:650px}.check input{width:auto;margin-top:6px;accent-color:#245b46}.error{padding:16px;background:#f8e6dd;color:#773c22;border:1px solid #d9bcb0}details{margin:22px 0;font-size:14px}summary{cursor:pointer}.downloads{display:flex;gap:12px;flex-wrap:wrap}footer{margin-top:60px;border-top:1px solid #d9ded5;padding-top:15px;font-size:12px;color:#617064}.digest{overflow-wrap:anywhere}.skip{position:absolute;left:-9999px}.skip:focus{left:12px;top:8px;background:white;padding:8px}a:focus-visible,button:focus-visible,input:focus-visible,textarea:focus-visible{outline:3px solid #b38e36;outline-offset:3px}@media(max-width:700px){main{margin-top:35px;padding:0 20px 45px}.bar{padding:16px 20px;gap:18px}.bar>span{display:none}.workspace{grid-template-columns:1fr}.fields{order:-1}.steps{gap:15px;font-size:11px}.paper{padding:25px}.facts{grid-template-columns:1fr;gap:4px}.facts dd{margin-bottom:14px}.preview-head{display:block}}
diff --git a/internal/docs/views/contract.html b/internal/docs/views/contract.html
new file mode 100644
index 0000000..2895e7c
--- /dev/null
+++ b/internal/docs/views/contract.html
@@ -0,0 +1,44 @@
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{{if .Home}}Contracts{{else}}{{.State.Title}}{{end}} · Oficina Docs</title><link rel="stylesheet" href="/contracts/style.css"></head><body>
+<a class="skip" href="#main">Skip to content</a>
+<header class="bar"><a href="/" class="brand">Oficina <strong>Docs</strong></a><a href="/contracts">Contracts</a><span>{{.State.Address}}</span></header>
+<main id="main">
+{{if .Home}}
+<div class="eyebrow">FROM FIRST DRAFT TO SIGNED AGREEMENT</div><h1>Your next agreement,<br>already personal.</h1><p class="intro">Write the terms. Bring in a customer from Fichas.<br>Review the document, then sign it in Oficina.</p>
+<form method="post" action="/contracts/start"><button class="primary">Prepare a contract <span aria-hidden="true">→</span></button></form>
+<section class="recent"><h2>Your contracts</h2>{{range .Records}}<a class="record" href="/contracts/{{.ID}}"><strong>{{.Title}}</strong><span>{{.Stage}} →</span></a>{{else}}<p>Your first agreement starts here.</p>{{end}}</section>
+<aside class="note"><strong>Live pilot · self-signing</strong><p>Connect to live Fichas and sign as {{.State.Address}}. External recipients are not enabled. Issued agreements and evidence are available here for seven days; download a copy to keep it. Encrypted backups follow the existing backup policy.</p></aside>
+{{else}}
+<nav class="steps" aria-label="Contract progress"><span>1 · Customer</span><span>2 · Terms & preview</span><span>3 · Review & sign</span></nav>
+{{if .Error}}<p class="error" role="alert">{{.Error}}</p>{{end}}
+{{if eq .State.Stage "connecting"}}
+<div class="eyebrow">START WITH YOUR CUSTOMER</div><h1>Bring the details<br>from Fichas.</h1><p class="intro">Choose one live customer and exactly which fields to use. You’ll review the details before they reach this contract.</p><a class="button primary" href="{{.Connect}}">Choose a customer in Fichas →</a><p class="hint">Sign in to Fichas if asked, then return using its Continue button. This preparation expires in 30 minutes.</p>
+{{else if eq .State.Stage "received"}}
+<div class="eyebrow">CUSTOMER DETAILS</div><h1>Ready to make it personal.</h1><p>These are the fields you approved in Fichas. Only these details will be used.</p>
+<dl class="facts">{{range .State.Release.Fields}}<dt>{{.Label}}</dt><dd>{{.Value}}</dd>{{end}}</dl>
+<form method="post" action="/contracts/{{.ID}}/commit"><button class="primary">Use these details →</button></form><p class="hint">Source revision {{.State.Release.Revision}} · release authorised by {{.State.Release.Actor}}. Editing the Fichas card won’t change this approved copy.</p>
+{{else if or (eq .State.Stage "editing") (eq .State.Stage "preview")}}
+<div class="eyebrow">THE TERMS, IN YOUR WORDS</div><h1>{{if eq .State.Stage "preview"}}Review your agreement.{{else}}Make the template yours.{{end}}</h1>
+<div class="workspace"><section><form method="post" action="/contracts/{{.ID}}/preview">
+<label for="title">Document title</label><input id="title" name="title" maxlength="256" required value="{{.State.Title}}">
+<div class="twocol"><div><label for="date">Start date</label><input id="date" name="date" type="date" required value="{{.State.Date}}"></div><div><label for="fee">Fee · EUR</label><input id="fee" name="fee" inputmode="decimal" pattern="[0-9]{1,12}\.[0-9]{2}" required value="{{.State.Fee}}"><small>Use two decimal places, e.g. 1250.00.</small></div></div>
+<label for="body">Template</label><p id="field-help" class="hint">Place a field name where its value belongs. Fields are resolved as plain text.</p><textarea id="body" name="body" rows="17" maxlength="16384" aria-describedby="field-help" required>{{.State.Body}}</textarea><button class="primary">{{if eq .State.Stage "preview"}}Update preview{{else}}Preview agreement{{end}} →</button></form></section>
+<aside class="fields"><h2>Fields from Fichas</h2>{{range .State.Release.Fields}}<div class="field"><strong>{{.Label}}</strong><code>{{token .Key}}</code><p>{{.Value}}</p></div>{{end}}<h2>Contract details</h2><code>{{token "start_date"}}</code><code>{{token "fee"}}</code><p class="hint">This template belongs to this preparation. Changing these terms never edits your Fichas card.</p></aside></div>
+{{if eq .State.Stage "preview"}}<section class="preview"><div class="preview-head"><h2>The document you’ll sign</h2><a href="/contracts/{{.ID}}/document.pdf" target="_blank" rel="noopener">Open actual PDF ↗</a></div><article class="paper" aria-label="Agreement reading view">{{range .State.Paragraphs}}<p>{{.}}</p>{{end}}</article>
+<form method="post" action="/contracts/{{.ID}}/issue"><input type="hidden" name="preview" value="{{.State.PreviewID}}"><p>Ready? Freeze this version and email a verification code to <strong>{{.State.Address}}</strong>. Signing is a separate step.</p><button class="primary">Send to myself for signature →</button></form><p class="hint">Only the saved preview is issued. If you edit the form above, choose Update preview first.</p></section>{{end}}
+{{else if eq .State.Stage "issued"}}
+<div class="eyebrow">{{if .Expired}}SIGNING WINDOW CLOSED{{else}}YOUR AGREEMENT IS READY{{end}}</div><h1>{{if .Expired}}This request has expired.{{else if .State.Verified}}One final confirmation.{{else}}Check your email.{{end}}</h1>
+{{if .Expired}}<p>The 24-hour signing window has ended. Prepare a new agreement to continue.</p>{{else}}
+<p>The document is frozen. <a href="/contracts/{{.ID}}/document.pdf" target="_blank" rel="noopener">Review the PDF ↗</a></p>
+<article class="paper" aria-label="Agreement reading view">{{range .State.Paragraphs}}<p>{{.}}</p>{{end}}</article>
+{{if .State.Verified}}<form method="post" action="/contracts/{{.ID}}/sign"><input type="hidden" name="digest" value="{{.State.Digest}}"><label class="check"><input type="checkbox" name="consent" value="yes" required><span>I have reviewed this agreement and agree to sign it electronically in my own name.</span></label><p>Signing as <strong>{{.State.Address}}</strong>.</p><button class="primary">Sign agreement</button></form>{{else}}
+<p>{{if eq .State.Delivery "sent"}}We sent a verification code to{{else if eq .State.Delivery "failed"}}Email delivery failed. Retry sending the code to{{else}}Email delivery is pending or uncertain. Check the inbox for{{end}} <strong>{{.State.Address}}</strong>.</p>
+<form method="post" action="/contracts/{{.ID}}/verify"><label for="code">Verification code</label><input id="code" name="code" autocomplete="one-time-code" spellcheck="false" maxlength="32" minlength="32" required><small>Paste the 32-character code from the email. It expires after 15 minutes. {{.State.Attempts}} of 5 attempts used.</small><button class="primary">Verify my email →</button></form>{{end}}
+<form method="post" action="/contracts/{{.ID}}/resend"><button class="secondary">Send a new code</button><small>Available once per minute. This replaces any previous code or verification.</small></form>
+<details><summary>Withdraw this signing request</summary><p>This permanently closes the unsigned request.</p><form method="post" action="/contracts/{{.ID}}/void"><button class="secondary">Withdraw request</button></form></details>{{end}}
+{{else if eq .State.Stage "completed"}}
+<div class="eyebrow">AGREEMENT COMPLETED</div><h1>Signed. And all together.</h1><p class="intro">{{.State.Title}}<br>Accepted by {{.State.Address}}</p><dl class="facts"><dt>Signed</dt><dd>{{when .State.Signed}}</dd><dt>Verification</dt><dd>Email address verified before signing</dd></dl>
+<div class="downloads"><a class="button primary" href="/contracts/{{.ID}}/document.pdf">Download original agreement</a><a class="button secondary" href="/contracts/{{.ID}}/evidence.json">Download signing evidence</a></div><p class="hint">The original PDF is preserved unchanged. The evidence records your affirmative acceptance and its exact document digest; this is not a PDF certificate signature.</p>
+{{else if eq .State.Stage "voided"}}<div class="eyebrow">REQUEST WITHDRAWN</div><h1>This agreement is closed.</h1><p>It can no longer be signed. Prepare a new agreement if you need to continue.</p>{{end}}
+{{if .State.Issued}}<footer><p>Demo records available until {{when .Retention}}. Download completed records to keep them. Existing encrypted backups may retain data under the app’s backup policy.</p><details><summary>Document identity</summary><code class="digest">{{.State.Digest}}</code></details></footer>{{end}}
+{{end}}
+</main></body></html>