console: dpaInForce decides each account's DPA version
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
internal/console/dpainforce.go+71 −0internal/console/dpainforce_test.go+87 −0
Intent
<task-notification> <task-id>a7398fc31ded810d4</task-id> <tool-use-id>toolu_01AK8jBmtUP7VqpG3UDqXCd8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/260ddc60-0dfc-4cf8-8857-7688d6275097/tasks/a7398fc31ded810d4.output</output-file> <status>completed</status> <summary>Agent "Implement Task 1: store tables" 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: DONE Commit: e5d666e1 "console: end the DPA acceptance when an account is reaped" - `ReapAccount` in `internal/console/store.go` now calls `endDPA(tx, ...)` before commit, in the same transaction. - There is no third tombstoning path. Only `DeleteAccount` (`ownership.go`) and `ReapAccount` write `accounts.deleted_at`. - New `TestEndDPAOnAccountReap` checks that `LiveDPA` is nil, `LiveDPAs` is empty and `ended_at` is set after a reap. - The two tests that ignored errors from `PublishLegalDocument` and `SetLetterhead` now fail on them, through a shared helper. Test: `go test ./internal/console -run 'TestEndDPA|TestDPAAcceptanceOneLivePerAccount|TestLegal|TestLetterhead|TestReap' -count=1` gave `ok ... 13.045s`. `go vet` and `gofmt` are clean. Concern: the stale `.git/packed-refs.lock` error appeared again during the commit. The commit landed anyway (HEAD is e5d666e1). The lock isn't mine, so I left it. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/dpa-and-retention/.superpowers/sdd/2026-11-25-dpa-acceptance/task-1-report.md</result> <usage><subagent_tokens>92142</subagent_tokens><tool_uses>3</tool_uses><duration_ms>80093</duration_ms></usage> </task-notification>
<task-notification> <task-id>a11675be247fbd163</task-id> <tool-use-id>toolu_0192eSp58zyPDHj6Pf7Nk7yV</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/260ddc60-0dfc-4cf8-8857-7688d6275097/tasks/a11675be247fbd163.output</output-file> <status>completed</status> <summary>Agent "Re-review 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/store.go:1946-1953`: `ReapAccount` now calls `endDPA(tx, accountID, now)` right after the `UPDATE accounts SET deleted_at` and before `tx.Commit()`. That is the same transaction, and an error from `endDPA` returns without committing. - Covering test: `TestEndDPAOnAccountReap`, added in `internal/console/legal_store_test.go`. It reaps an account with a live acceptance, then checks that `LiveDPA` returns nil, `LiveDPAs` is empty, and `ended_at` equals the reap time. - The report names the command, which includes `-run 'TestEndDPA|…'`, and shows its output: `ok … 13.045s`. - "Any other path": my grep of `internal/console` for non-test writes to `accounts.deleted_at` found only `ownership.go:968` (`DeleteAccount`, which already calls `endDPA` per the report) and `store.go:1946` (`ReapAccount`). `platform_store.go:737` only updates `name`, and every other `deleted_at` write hits `apps`. The implementer's claim holds. 2. ADDRESSED. The new helper `legalTestDocAndLetterhead` (`legal_store_test.go`, near the end of the file) calls `t.Fatal` on errors from both `PublishLegalDocument` and `SetLetterhead`. `TestDPAAcceptanceOneLivePerAccount` and `TestEndDPAOnAccountDelete` now use it. The new reap test uses it too. ### New Issues in the Fix Diff None. `time` is still used in the test file, so the imports are fine. ### Out-of-Scope Observations - The report says the full `internal/console` suite has never run to completion. That was already disclosed and is unchanged by this fix. - I did not re-run any tests. The report's output shows a targeted run only. ### Verdict **Fix round:** Clean</result> <usage><subagent_tokens>43511</subagent_tokens><tool_uses>1</tool_uses><duration_ms>28001</duration_ms></usage> </task-notification>
<task-notification> <task-id>a3e0ffa5d47958a27</task-id> <tool-use-id>toolu_013zj95dCXP4QQwkRfwg3Kdr</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/260ddc60-0dfc-4cf8-8857-7688d6275097/tasks/a3e0ffa5d47958a27.output</output-file> <status>completed</status> <summary>Agent "Review Task 2 (spec + quality)" 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>### Spec Compliance - ❌ Issues found: the fetch half and the alert-client refactor match the brief and the rulings. `canonicalAgreement` does not meet the global constraint "Anything else refuses the publish". A tag left open at the end of the fragment can carry any element and attributes, and the check accepts it. See Critical 1. - ✅ Interfaces match the brief: - `newGuardedHTTPClient(refused, timeout)` is at alertdial.go:166. - `newAlertHTTPClient` now just returns `newGuardedHTTPClient(refused, alertSendTimeout)` (alertdial.go:159-160). Only the three timeout fields became the parameter, so the alert client behaves exactly as before. - `fetchLegalText` is at legalfetch.go:44 and `canonicalAgreement` at legalfetch.go:99. `legalFetchMax = 2 << 20` and the 10 s timeout are set. - ✅ Every test the brief names exists (legalfetch_test.go:24, 35, 55, 73, 107, 120). The refuse table covers all six required inputs and six more. - ⚠️ Cannot verify from the diff: - That the alert dial tests pass. The report says so; per the brief I did not re-run the suite. - How Task 3 shows the error strings. `shortToken` replaces control characters but does not HTML-escape (legalfetch.go:147). An error like `link javascript:<script>…` is safe only if it is rendered through html/template. Nothing renders the agreement or these errors yet: `canonicalAgreement` has no callers outside its own files. - Note: the branch tip has moved past 2fa579b7 (it is now e5d666e1), so the fix below lands on top of later tasks. ### Strengths - SSRF boundary, all checked against alertdial.go: - The address check runs at dial time on the resolved IP, after `Unmap()` (alertdial.go:177), so DNS rebinding and IPv4-mapped IPv6 addresses are caught. - `refusedAddr` (alertdial.go:136-150) refuses NAT64, IPv4-compatible, 6to4, Teredo, site-local, CGNAT/Tailscale and both metadata addresses. IPv6 zones fall under link-local. - Proxy settings from the environment are ignored (`Proxy: nil`, alertdial.go:185). - Redirects are not followed (alertdial.go:195), so a 302 comes back as "status 302". - Response headers are capped at 16 KiB (alertdial.go:193). - `Client.Timeout` covers reading the body, so a slow body hits the 10 s limit. - The `LimitReader(…, max+1)` (legalfetch.go:62) applies after transparent gzip decompression, so a compression bomb is also held to 2 MiB. - The URL is refused before any dial unless it is https with a host and no opaque part (legalfetch.go:46). Client errors are reduced to categories and never carry the URL (legalfetch.go:73-86; the test at legalfetch_test.go:100). - Tokenizer cases I ran through a copy of `canonicalAgreement` against x/net v0.62.0, all handled correctly: - Refused: `&#106;avascript:`, `&#x2F;&#x2F;evil` (decodes to `//evil`), `/&#x5c;evil` (`/\evil`), `/&Tab;/evil` (`/?/evil`). - Refused: `<p/onclick=x>`, `<p =onclick=x>`, `<a href="/x"onclick=y>` (no space before the second attribute), `<a href="/x" / onclick=y>`, NUL inside tag or attribute names. - Refused as comment: `<![CDATA[…]]>`, `<?xml?>`, `<!`. - Refused: `<svg>`. - Duplicate `href` / `HREF`: the tokenizer keeps the first, as browsers do, so the second value never matters. - Tag and attribute names are lowercased before the allow-list lookup. - Refusing whitespace, control characters and backslash anywhere in an href (legalfetch.go:136) is a sound extra hardening. ### Issues #### Critical (Must Fix) 1. **A tag left open at the end of the fragment is accepted, and it becomes a live tag once the page continues after it** (legalfetch.go:103-107). - What happens: when the input ends inside a tag, x/net/html silently discards that tag and returns `ErrorToken` with `io.EOF`. `canonicalAgreement` then returns nil. - Probe results: `<p>Terms</p><img src=x onerror=alert(1)` and `<p>Terms</p><script ` both return nil. - In the page: the fragment is rendered unescaped and template markup always follows it. A browser keeps reading the open tag into that markup until the next `>`. Putting the fragment inside `<div>` with `"\n</section>\n<form method=\"post\">"` after it gave: - `<img src="x" onerror="alert(1)" <="" section=""/>`, which is stored XSS on the customer page. - `<script <="" section="">`, which swallows the acceptance form. - Why it matters: this breaks the XSS boundary and the "stored bytes = what was checked" guarantee. The SHA-256 then identifies text that renders differently from what was validated. - Fix: add up `len(z.Raw())` over every token and refuse with a short error such as `"unclosed tag"` if the total is less than `len(b)` at EOF. Add table cases for: - `<p>x</p><img src=x onerror=y` - `<p>x</p><a href="/x" onclick=` - `<p>x</p><a href="/x` - `<p>x</p><scr` #### Important (Should Fix) - None beyond Critical 1. #### Minor (Nice to Have) 1. **Unbalanced elements are accepted** (legalfetch.go:113-130). Examples: `<a href="https://x">open` with no `</a>`, or a stray `</section>`. In the page, the first turns all following template content into a link to the operator's host; the second closes the template's own open elements. It is not script, and the rulings do not require balanced tags. Since the fix for Critical 1 already walks every token, a simple stack check would make "renders as checked" fully true. 2. **Some error categories are blurred** (legalfetch.go:73-86). `context.Canceled` reports as "connect failed". `"invalid url"` (legalfetch.go:51) cannot happen after the parse succeeds. These are cosmetic. 3. **`shortToken` lets Unicode bidi and format characters through** (legalfetch.go:147-162). U+202E is one example; it can reorder how an error reads on the operator's screen. Mapping `unicode.Is(unicode.Cf, r)` to `?` would close this. ### Assessment **Task quality:** Needs fixes **Reasoning:** The fetch side is solid: dial-time refusal, no proxy, no redirects, size and time limits, and errors that never carry the URL. The canonical check, though, accepts any tag left open at the end of the fragment, and I showed `<img … onerror=…>` becoming a live tag once template markup follows it. That is the XSS hole the check exists to close.</result> <usage><subagent_tokens>69960</subagent_tokens><tool_uses>14</tool_uses><duration_ms>401655</duration_ms></usage> </task-notification>
Attributed to this commit: 12.9 g CO₂e (1,600,589 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on dpa-and-retention, 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/dpainforce.go b/internal/console/dpainforce.go| new file mode 100644 |
| index 000000000..d53fd6e7f |
| --- /dev/null |
| +++ b/internal/console/dpainforce.go |
| @@ -0,0 +1,71 @@ |
| +package console |
| + |
| +import "time" |
| + |
| +// dpaNoticePeriod is how long a notice must have been delivered before a |
| +// version that needs notice applies to an account (spec §3.5). |
| +const dpaNoticePeriod = 30 * 24 * time.Hour |
| + |
| +// noticeLookup returns when the notice for a document was first delivered |
| +// to at least one owner of the account, or nil if it has not been. |
| +type noticeLookup func(documentID, accountID int64) (deliveredAt *time.Time) |
| + |
| +// dpaQualifies reports whether a later document d has taken effect for the |
| +// account: effective by now, and either no notice is needed or the notice |
| +// was delivered at least 30 days ago. |
| +func dpaQualifies(d LegalDocument, accountID int64, notified noticeLookup, now time.Time) bool { |
| + if d.EffectiveAt == nil || d.EffectiveAt.After(now) { |
| + return false |
| + } |
| + if !d.NeedsNotice { |
| + return true |
| + } |
| + if notified == nil { |
| + return false |
| + } |
| + deliveredAt := notified(d.ID, accountID) |
| + return deliveredAt != nil && !deliveredAt.After(now.Add(-dpaNoticePeriod)) |
| +} |
| + |
| +// dpaInForce returns the DPA version in force for an account that accepted |
| +// accepted: the newest dpa document at or after the accepted one that is |
| +// the accepted one or qualifies (spec §3.5). docs may be in any order. If |
| +// the accepted document is missing from docs and nothing later qualifies, |
| +// it returns a zero document carrying the accepted ID. |
| +func dpaInForce(accepted DPAAcceptance, docs []LegalDocument, notified noticeLookup, now time.Time) LegalDocument { |
| + best := LegalDocument{ID: accepted.DocumentID} |
| + for _, d := range docs { |
| + if d.Kind != "dpa" || d.ID < accepted.DocumentID { |
| + continue |
| + } |
| + if d.ID == accepted.DocumentID { |
| + if best.ID == accepted.DocumentID { |
| + best = d |
| + } |
| + continue |
| + } |
| + if d.ID > best.ID && dpaQualifies(d, accepted.AccountID, notified, now) { |
| + best = d |
| + } |
| + } |
| + return best |
| +} |
| + |
| +// dpaPending returns the newest dpa document after the accepted one that |
| +// does not apply yet, for the pane's "applies from" line, or nil. |
| +func dpaPending(accepted DPAAcceptance, docs []LegalDocument, notified noticeLookup, now time.Time) *LegalDocument { |
| + var pending *LegalDocument |
| + for i := range docs { |
| + d := docs[i] |
| + if d.Kind != "dpa" || d.ID <= accepted.DocumentID { |
| + continue |
| + } |
| + if dpaQualifies(d, accepted.AccountID, notified, now) { |
| + continue |
| + } |
| + if pending == nil || d.ID > pending.ID { |
| + pending = &d |
| + } |
| + } |
| + return pending |
| +} |
diff --git a/internal/console/dpainforce_test.go b/internal/console/dpainforce_test.go| new file mode 100644 |
| index 000000000..3730f9d8a |
| --- /dev/null |
| +++ b/internal/console/dpainforce_test.go |
| @@ -0,0 +1,87 @@ |
| +package console |
| + |
| +import ( |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestDPAInForce(t *testing.T) { |
| + now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) |
| + past := now.Add(-48 * time.Hour) |
| + future := now.Add(48 * time.Hour) |
| + ago := func(d time.Duration) *time.Time { v := now.Add(-d); return &v } |
| + day := 24 * time.Hour |
| + |
| + doc := func(id int64, eff *time.Time, notice bool) LegalDocument { |
| + return LegalDocument{ID: id, Kind: "dpa", Version: "v", EffectiveAt: eff, NeedsNotice: notice} |
| + } |
| + pp := func(t time.Time) *time.Time { return &t } |
| + |
| + delivered := func(m map[int64]*time.Time) noticeLookup { |
| + return func(documentID, accountID int64) *time.Time { return m[documentID] } |
| + } |
| + |
| + tests := []struct { |
| + name string |
| + acceptedDoc int64 |
| + docs []LegalDocument |
| + notified noticeLookup |
| + wantInForce int64 |
| + wantPending int64 // 0 means nil |
| + }{ |
| + {"accepted is newest", 1, []LegalDocument{doc(1, pp(past), true)}, nil, 1, 0}, |
| + {"later, no notice needed, effective passed", 1, |
| + []LegalDocument{doc(1, pp(past), false), doc(2, pp(past), false)}, nil, 2, 0}, |
| + {"later needs notice, none delivered", 1, |
| + []LegalDocument{doc(1, pp(past), true), doc(2, pp(past), true)}, delivered(nil), 1, 2}, |
| + {"nil lookup counts as none delivered", 1, |
| + []LegalDocument{doc(1, pp(past), true), doc(2, pp(past), true)}, nil, 1, 2}, |
| + {"delivered 29 days ago", 1, |
| + []LegalDocument{doc(1, pp(past), true), doc(2, pp(past), true)}, |
| + delivered(map[int64]*time.Time{2: ago(29 * day)}), 1, 2}, |
| + {"delivered exactly 30 days ago, effective passed", 1, |
| + []LegalDocument{doc(1, pp(past), true), doc(2, pp(past), true)}, |
| + delivered(map[int64]*time.Time{2: ago(30 * day)}), 2, 0}, |
| + {"delivered 30 days ago, effective in future", 1, |
| + []LegalDocument{doc(1, pp(past), true), doc(2, pp(future), true)}, |
| + delivered(map[int64]*time.Time{2: ago(30 * day)}), 1, 2}, |
| + {"three versions, only v2 qualifies", 1, |
| + []LegalDocument{doc(1, pp(past), true), doc(2, pp(past), false), doc(3, pp(future), false)}, |
| + nil, 2, 3}, |
| + {"three versions out of order, only v2 qualifies", 1, |
| + []LegalDocument{doc(3, pp(future), false), doc(1, pp(past), true), doc(2, pp(past), false)}, |
| + nil, 2, 3}, |
| + {"accepted v2 during v2's notice period", 2, |
| + []LegalDocument{doc(1, pp(past), true), doc(2, pp(past), true)}, nil, 2, 0}, |
| + {"earlier documents are ignored", 2, |
| + []LegalDocument{doc(1, pp(past), false), doc(2, pp(past), true)}, nil, 2, 0}, |
| + {"nil effective_at never qualifies", 1, |
| + []LegalDocument{doc(1, pp(past), false), doc(2, nil, false)}, nil, 1, 2}, |
| + {"other kinds are ignored", 1, |
| + []LegalDocument{doc(1, pp(past), false), |
| + {ID: 2, Kind: "terms", EffectiveAt: pp(past)}}, nil, 1, 0}, |
| + {"accepted document missing, later qualifies", 5, |
| + []LegalDocument{doc(6, pp(past), false), doc(7, pp(future), false)}, nil, 6, 7}, |
| + {"accepted document missing, none qualifies", 5, |
| + []LegalDocument{doc(6, pp(future), false)}, nil, 5, 6}, |
| + {"accepted document missing, no later documents", 5, nil, nil, 5, 0}, |
| + } |
| + for _, tc := range tests { |
| + t.Run(tc.name, func(t *testing.T) { |
| + acc := DPAAcceptance{AccountID: 9, DocumentID: tc.acceptedDoc} |
| + got := dpaInForce(acc, tc.docs, tc.notified, now) |
| + if got.ID != tc.wantInForce { |
| + t.Errorf("dpaInForce ID = %d, want %d", got.ID, tc.wantInForce) |
| + } |
| + pend := dpaPending(acc, tc.docs, tc.notified, now) |
| + switch { |
| + case tc.wantPending == 0 && pend != nil: |
| + t.Errorf("dpaPending = %d, want nil", pend.ID) |
| + case tc.wantPending != 0 && pend == nil: |
| + t.Errorf("dpaPending = nil, want %d", tc.wantPending) |
| + case pend != nil && pend.ID != tc.wantPending: |
| + t.Errorf("dpaPending ID = %d, want %d", pend.ID, tc.wantPending) |
| + } |
| + }) |
| + } |
| +} |