carlos / platform Public

console: post the DPA PDF to the PDF engine

pdfFromHTML posts index, header and footer HTML to the engine's Chromium
route with a 30 s deadline and a 10 MiB cap, and returns the PDF bytes.
Errors are short categories; no engine address or body is ever included.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b9e8dcf3c1c6440874eab935386191fe38cc32c3 parent 2a8cf1f
2 files changed, +211 −0
  • internal/console/dpapdfengine.go +93 −0
  • internal/console/dpapdfengine_test.go +118 −0

Intent

Human

<task-notification> <task-id>a7475401d416eaa51</task-id> <tool-use-id>toolu_01WMZ4girjdWuVPqDC79VC2j</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/260ddc60-0dfc-4cf8-8857-7688d6275097/tasks/a7475401d416eaa51.output</output-file> <status>completed</status> <summary>Agent "Implement S2 Task 1: PDF HTML" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: fix round 1 is done; all four review points are fixed. Commits: `2a8cf1f7` "console: DPA PDF review fixes (entity, VAT, base, address)", on top of `cf0f0b5c` (not pushed). 1. With a logo, the header now shows the entity name beside it, and the logo keeps its alt text. 2. The VAT number is gone from the footer and stays in the Processor party line. 3. index.html gets a `&lt;base&gt;` pointing at the document site's root, only when the document URL is https with a host, so links like `/terms/` in the body resolve to the site. 4. Blank address lines no longer print. Tests: all 14 targeted tests pass (`TestDPAPDF*`, the copy gate, and the template off-origin and icon checks), including three new ones for points 1, 3 and 4; build, vet and gofmt are clean and `make code-health` passes. Concerns: I did not print a new PDF this round. The header's height is unchanged because the logo is still capped at 28pt high. Report (fix section appended): `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/dpa-pdf/.superpowers/sdd/2026-11-26-dpa-pdf/task-1-report.md`</result> <usage><subagent_tokens>143433</subagent_tokens><tool_uses>6</tool_uses><duration_ms>376397</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>af5ecd7164b8daae6</task-id> <tool-use-id>toolu_01JGcnyXjW66rLTTKdHSsrns</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/260ddc60-0dfc-4cf8-8857-7688d6275097/tasks/af5ecd7164b8daae6.output</output-file> <status>completed</status> <summary>Agent "Re-review S2 Task 1 fix round 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Findings 1. ADDRESSED. `internal/console/templates/dpa_pdf_header.html` (lines 6-8) now always renders `&lt;span class="wordmark"&gt;{{.Entity}}&lt;/span&gt;`. The logo `&lt;img&gt;` sits beside it and keeps its alt text. `TestDPAPDFHeaderShowsEntity` in `dpapdf_test.go` covers no-logo, PNG and SVG on the header output alone. It takes text nodes only, not attribute values, and requires exactly `Team Tito Limited|privacy@carloku.com`. The old "no wordmark with a logo" assertion is flipped to match. 2. ADDRESSED. The footer template and `VATNumber` are gone from the view. `TestDPAPDFHTMLHasEveryPart` asserts the footer has no "VAT" and that the parties block has "VAT number IE3384527RH.". 3. ADDRESSED. `dpaPDFBase` in `dpapdf.go` builds `"https://" + u.Host + "/"` and only when the scheme is `https` and the host is non-empty. It is emitted through html/template in `dpa_pdf.html`. Tests cover `/terms/` with `https://example.com/dpa/1/` giving base `https://example.com/`, plus http, empty-host, relative and unparsable URLs, which get no base. I also ran the same logic in a scratch Go program (since removed) against hostile inputs: - **Credentials, path, query and fragment:** `https://u:p@ex.com:8443/a?b#c` gives `https://ex.com:8443/`. The userinfo, path, query and fragment are dropped. - **Breakout attempt:** `https://a"&gt;&lt;script&gt;…` gives `&lt;base href="https://a%22%3e%3cscript%3e…%3c/"&gt;`. The quote and angle brackets are percent-encoded, so nothing escapes the attribute. - **Other odd characters:** `'`, `&amp;`, `&lt;` and `&gt;` come out encoded or escaped (`%27`, `&amp;amp;`, `%3c`, `%3e`). - **Rejected outright (no base):** a `javascript:` scheme, a backslash host, a `%41` host and a space in the host. - **Normal forms:** an IPv6 literal and an uppercase scheme work normally. 4. ADDRESSED. `dpaPDFAddressLines` drops lines that are blank after trimming. `TestDPAPDFAddressDropsBlankLines` has blanks at the start, middle and end, with mixed `\r\n`, and checks the exact Customer cell. ### New Issues in the Fix Diff None blocking. One note: the base keeps a port (`https://example.com:8443/`), which is correct for resolving links. The ruling said "scheme and host only", and a port is part of `u.Host`. The test pins this on purpose. ### Out-of-Scope Observations - No test feeds the hostile-character URLs through the template. Escaping is handled by html/template, and my scratch run confirmed it. - Header height is unchanged because the logo is still capped at 28pt. The report says no new PDF was printed, so the layout has not been checked visually. ### Verdict **Fix round:** Clean</result> <usage><subagent_tokens>48813</subagent_tokens><tool_uses>4</tool_uses><duration_ms>34075</duration_ms></usage> </task-notification>

Attributed to this commit: 26.1 g CO₂e (3,393,466 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on dpa-pdf, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/dpapdfengine.go b/internal/console/dpapdfengine.go
new file mode 100644
index 000000000..23dbf61f3
--- /dev/null
+++ b/internal/console/dpapdfengine.go
@@ -0,0 +1,93 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+const (
+ // dpaPDFMax caps the engine's answer; a larger one is an error.
+ dpaPDFMax = 10 << 20
+ // dpaPDFTimeout is the overall deadline for one engine call.
+ dpaPDFTimeout = 30 * time.Second
+)
+
+// dpaPDFDeadline is dpaPDFTimeout; tests shorten it.
+var dpaPDFDeadline = dpaPDFTimeout
+
+// pdfFromHTML posts the three HTML documents to the engine's Chromium
+// route and returns the PDF. It is the operator-side call: it does not use
+// the tenant proxy or its metering. Errors are short categories that are
+// safe to log; they never carry the engine address or its response.
+func pdfFromHTML(ctx context.Context, client *http.Client, engine string, index, header, footer []byte) ([]byte, error) {
+ base, err := url.Parse(engine)
+ if err != nil || base.Scheme != "http" || base.Hostname() == "" {
+ return nil, errors.New("engine unreachable")
+ }
+ target := base.JoinPath("forms", "chromium", "convert", "html").String()
+
+ var body bytes.Buffer
+ mw := multipart.NewWriter(&body)
+ for _, f := range []struct {
+ name string
+ data []byte
+ }{{"index.html", index}, {"header.html", header}, {"footer.html", footer}} {
+ part, err := mw.CreateFormFile("files", f.name)
+ if err != nil {
+ return nil, errors.New("engine unreachable")
+ }
+ _, _ = part.Write(f.data)
+ }
+ for _, kv := range [][2]string{
+ {"paperWidth", "8.27"}, {"paperHeight", "11.7"},
+ {"marginTop", "1"}, {"marginBottom", "1"},
+ {"marginLeft", "0.8"}, {"marginRight", "0.8"},
+ {"printBackground", "true"},
+ } {
+ _ = mw.WriteField(kv[0], kv[1])
+ }
+ if err := mw.Close(); err != nil {
+ return nil, errors.New("engine unreachable")
+ }
+
+ ctx, cancel := context.WithTimeout(ctx, dpaPDFDeadline)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, &body)
+ if err != nil {
+ return nil, errors.New("engine unreachable")
+ }
+ req.Header.Set("Content-Type", mw.FormDataContentType())
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, pdfEngineErr(ctx, err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("engine status %d", resp.StatusCode)
+ }
+ pdf, err := io.ReadAll(io.LimitReader(resp.Body, dpaPDFMax+1))
+ if err != nil {
+ return nil, pdfEngineErr(ctx, err)
+ }
+ if len(pdf) > dpaPDFMax {
+ return nil, errors.New("too large")
+ }
+ if !bytes.HasPrefix(pdf, []byte("%PDF-")) {
+ return nil, errors.New("not a pdf")
+ }
+ return pdf, nil
+}
+
+func pdfEngineErr(ctx context.Context, err error) error {
+ if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
+ return errors.New("timeout")
+ }
+ return errors.New("engine unreachable")
+}
diff --git a/internal/console/dpapdfengine_test.go b/internal/console/dpapdfengine_test.go
new file mode 100644
index 000000000..769b3823c
--- /dev/null
+++ b/internal/console/dpapdfengine_test.go
@@ -0,0 +1,118 @@
+package console
+
+import (
+ "bytes"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestPDFFromHTMLRequestShape(t *testing.T) {
+ want := []byte("%PDF-1.7 exact")
+ var gotPath, gotMethod string
+ files := map[string]string{}
+ fields := map[string]string{}
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotPath, gotMethod = r.URL.Path, r.Method
+ if err := r.ParseMultipartForm(1 << 20); err != nil {
+ t.Errorf("parse: %v", err)
+ }
+ for name, hs := range r.MultipartForm.File {
+ if name != "files" {
+ t.Errorf("unexpected file field %q", name)
+ }
+ for _, h := range hs {
+ f, _ := h.Open()
+ b, _ := io.ReadAll(f)
+ f.Close()
+ files[h.Filename] = string(b)
+ }
+ }
+ for k, v := range r.MultipartForm.Value {
+ fields[k] = v[0]
+ }
+ _, _ = w.Write(want)
+ }))
+ defer srv.Close()
+ for _, base := range []string{srv.URL, srv.URL + "/"} {
+ got, err := pdfFromHTML(t.Context(), srv.Client(), base, []byte("IDX"), []byte("HDR"), []byte("FTR"))
+ if err != nil || !bytes.Equal(got, want) {
+ t.Fatalf("got %q, %v", got, err)
+ }
+ if gotMethod != http.MethodPost || gotPath != "/forms/chromium/convert/html" {
+ t.Fatalf("request %s %s", gotMethod, gotPath)
+ }
+ if len(files) != 3 || files["index.html"] != "IDX" || files["header.html"] != "HDR" || files["footer.html"] != "FTR" {
+ t.Fatalf("files %v", files)
+ }
+ wantFields := map[string]string{"paperWidth": "8.27", "paperHeight": "11.7", "marginTop": "1", "marginBottom": "1", "marginLeft": "0.8", "marginRight": "0.8", "printBackground": "true"}
+ if len(fields) != len(wantFields) {
+ t.Fatalf("fields %v", fields)
+ }
+ for k, v := range wantFields {
+ if fields[k] != v {
+ t.Fatalf("field %s = %q, want %q", k, fields[k], v)
+ }
+ }
+ }
+}
+
+func TestPDFFromHTMLErrors(t *testing.T) {
+ old := dpaPDFDeadline
+ dpaPDFDeadline = 200 * time.Millisecond
+ defer func() { dpaPDFDeadline = old }()
+ stall := make(chan struct{})
+ cases := []struct {
+ name string
+ handler http.HandlerFunc
+ want string
+ }{
+ {"500", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(500)
+ _, _ = w.Write([]byte("secret body"))
+ }, "engine status 500"},
+ {"too large", func(w http.ResponseWriter, r *http.Request) {
+ b := append([]byte("%PDF-"), make([]byte, dpaPDFMax+1-5)...)
+ _, _ = w.Write(b)
+ }, "too large"},
+ {"not a pdf", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("<html>")) }, "not a pdf"},
+ {"stalled", func(w http.ResponseWriter, r *http.Request) {
+ // Drain the body so the server notices the client hanging up.
+ _, _ = io.Copy(io.Discard, r.Body)
+ select {
+ case <-stall:
+ case <-r.Context().Done():
+ }
+ }, "timeout"},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ srv := httptest.NewServer(c.handler)
+ defer srv.Close()
+ start := time.Now()
+ got, err := pdfFromHTML(t.Context(), srv.Client(), srv.URL, []byte("i"), []byte("h"), []byte("f"))
+ if err == nil || got != nil || err.Error() != c.want {
+ t.Fatalf("got %d bytes, err %v; want %q", len(got), err, c.want)
+ }
+ if strings.Contains(err.Error(), srv.URL) || strings.Contains(err.Error(), "secret") {
+ t.Fatalf("error leaks: %v", err)
+ }
+ if time.Since(start) > 5*time.Second {
+ t.Fatal("deadline not applied")
+ }
+ })
+ }
+ close(stall)
+ t.Run("unreachable", func(t *testing.T) {
+ srv := httptest.NewServer(http.NotFoundHandler())
+ url := srv.URL
+ srv.Close()
+ _, err := pdfFromHTML(t.Context(), http.DefaultClient, url, nil, nil, nil)
+ if err == nil || err.Error() != "engine unreachable" {
+ t.Fatalf("err %v", err)
+ }
+ })
+}