carlos / platform Public

Add optional demo terms links and pin approved alert copy

Add configured HTTPS terms links to demo banners and claim pages, plus
independently optional validated abuse email links. Preserve original HTML
and CSP bytes when the new settings are absent or invalid. Encode mailto
recipients so valid punctuation cannot introduce headers or fragments.

Claim, kept and error/progress pages already share demo_claim.html, so the
footer stays within that shared layout. Standalone moved pages and JSON
status responses are unchanged. Alert strings remain byte-for-byte as
approved; record the approval date and pin all nine strings in a test.

Targeted edge and census tests, footer browser checks, vet, formatting,
and Darwin/Windows builds pass. The requested console selection hit the
default ten-minute timeout; its remaining two tests passed separately.
All 197 matching console tests are accounted for: 196 pass, one gated
live-dev test skips. Opus round 1 approves every census unit and envelope,
with no P1 findings. P3 items remain follow-ups; no new review round.

README documentation and startup-warning copy await human copy approval.
This local commit is not ready to land until that documentation is applied.
No push, merge, deployment or real deployment configuration change.
codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev d99a0cff53f42d3c69c4673c2871a0d2a6b15b8f parent 6c2c167
29 files changed, +842 −50
  • cmd/console/demo_footer_env_test.go +22 −0
  • cmd/console/main.go +25 −7
  • docs/superpowers/notes/census-proposal-demo-terms-links.md +23 −0
  • docs/superpowers/notes/demo-terms-links.claims.tsv +3 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-demo-terms-links.md +28 −0
  • docs/superpowers/reviews/demo-terms-links-r1.md +96 −0
  • internal/console/demo_alert_copy.go +2 −2
  • internal/console/demo_alert_copy_test.go +30 −0
  • internal/console/demo_claim_copy.go +7 −0
  • internal/console/demo_claim_footer.go +75 −0
  • internal/console/demo_claim_footer_addresses_test.go +49 −0
  • internal/console/demo_claim_footer_test.go +263 −0
  • internal/console/demo_claim_kept.go +2 −2
  • internal/console/demo_claim_page.go +33 −9
  • internal/console/demo_claim_page_test.go +2 −0
  • internal/console/server.go +4 −0
  • internal/console/templates/demo_claim.html +6 −2
  • internal/console/testdata/demo_claim_layout.mjs +9 −0
  • internal/edge/demo_assets/banner.css +2 −0
  • internal/edge/demo_banner.go +34 −14
  • internal/edge/demo_banner_test.go +11 −11
  • internal/edge/demo_copy.go +1 −0
  • internal/edge/demo_terms_test.go +98 −0
  • internal/edge/demo_traffic.go +1 −1
  • internal/edge/demo_ux_browser_test.go +2 −1
  • internal/edge/edge.go +2 −1
  • internal/edge/testdata/demo_banner_without_terms.html +1 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-demo-terms-links.tsv +10 −0

CI cancelled — superseded by a newer push — run details

diff --git a/cmd/console/demo_footer_env_test.go b/cmd/console/demo_footer_env_test.go
new file mode 100644
index 000000000..213e73869
--- /dev/null
+++ b/cmd/console/demo_footer_env_test.go
@@ -0,0 +1,22 @@
+package main
+
+import "testing"
+
+func TestDemoClaimFooterEnv(t *testing.T) {
+ for _, tc := range []struct{ name, terms, abuse, wantTerms, wantAbuse string }{
+ {"valid", "https://example.com/terms", "abuse@example.com", "https://example.com/terms", "abuse@example.com"},
+ {"unset", "", "", "", ""},
+ {"invalid", "http://example.com/terms", "abuse@example.com?cc=x@example.com", "", ""},
+ {"spaces", " https://example.com/terms\n", "abuse@example.com ", "", ""},
+ {"independent", "http://example.com/terms", "abuse@example.com", "", "abuse@example.com"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ terms, abuse := demoClaimFooterEnv(func(k string) string {
+ return map[string]string{"CARLOS_DEMO_TERMS_URL": tc.terms, "CARLOS_DEMO_ABUSE_ADDRESS": tc.abuse}[k]
+ })
+ if terms != tc.wantTerms || abuse != tc.wantAbuse {
+ t.Fatalf("settings = %q %q; want %q %q", terms, abuse, tc.wantTerms, tc.wantAbuse)
+ }
+ })
+ }
+}
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 8ce8d7810..86184a080 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -483,18 +483,21 @@ func serve() {
if err != nil {
log.Fatal(err)
}
+ demoTermsURL, demoAbuseAddress := demoClaimFooterEnv(os.Getenv)
costScope, err := costScopeFromEnv(os.Getenv)
if err != nil {
log.Fatal(err)
}
cfg := console.Config{
- DemoAlerts: demoAlerts,
- DemoAPIOrigin: os.Getenv("CONSOLE_DEMO_API_ORIGIN"),
- Demo: demoConfig,
- Origin: origin,
- Keymail: envOr("CONSOLE_KEYMAIL", "https://keymail.dev"),
- Registry: envOr("CARLOS_REGISTRY", "/data/registry.db"),
- Releases: rel,
+ DemoAlerts: demoAlerts,
+ DemoAPIOrigin: os.Getenv("CONSOLE_DEMO_API_ORIGIN"),
+ Demo: demoConfig,
+ DemoTermsURL: demoTermsURL,
+ DemoAbuseAddress: demoAbuseAddress,
+ Origin: origin,
+ Keymail: envOr("CONSOLE_KEYMAIL", "https://keymail.dev"),
+ Registry: envOr("CARLOS_REGISTRY", "/data/registry.db"),
+ Releases: rel,
// The deployment bucket's NAME, from the same variable openStore()
// opens it with — /fleet/architecture draws the box -> bucket edge
// from it. Empty on a CARLOS_DEPLOYMENT_DIR deployment, which
@@ -1811,6 +1814,21 @@ func firstLineCapped(err error) string {
return s
}
+// demoClaimFooterEnv reads the two optional claim page footer settings next
+// to the other CARLOS_DEMO_* variables. A value that fails the console's checks
+// is dropped, so the page renders without that item.
+func demoClaimFooterEnv(getenv func(string) string) (terms, abuse string) {
+ terms = getenv("CARLOS_DEMO_TERMS_URL")
+ if terms != "" && !console.ValidDemoTermsURL(terms) {
+ terms = ""
+ }
+ abuse = getenv("CARLOS_DEMO_ABUSE_ADDRESS")
+ if abuse != "" && !console.ValidDemoAbuseAddress(abuse) {
+ abuse = ""
+ }
+ return terms, abuse
+}
+
func envOr(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
diff --git a/docs/superpowers/notes/census-proposal-demo-terms-links.md b/docs/superpowers/notes/census-proposal-demo-terms-links.md
new file mode 100644
index 000000000..791954808
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-demo-terms-links.md
@@ -0,0 +1,23 @@
+# Census approval: demo-terms-links
+
+Ruling `census-ruling-demo-terms-links`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/edge/demo_assets/banner.css` `external` | body | unchanged (1) | Add spacing and wrapping for the optional terms anchor in the compiled-in banner stylesheet; no URL, import, script or runtime read added. |
+| `internal/edge/demo_banner.go` `transformDemoHTMLResponse` | body | unchanged (1) | Pass the configured terms URL through the existing bounded-prefix banner injector; no new reads, response policy and streaming behavior unchanged. |
+| `internal/edge/demo_traffic.go` `Edge.demoProxy` | body | unchanged (2) | Pass the edge's optional terms URL into the resident demo banner transport; no new registry fields or reads, serving and forwarding authority unchanged. |
+
+Envelopes re-pinned: `internal/edge`, `internal/edge/demo_assets`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/edge/demo_assets/banner.css` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-agent-start-demo-2;basis=demo_assets/banner.css:1-31 is the fixed embedded warning layout, referenced by demo_banner.go:22 and served only under the reserved asset path at :91. No external imports, URLs, runtime path or app-selected content; stylesheet bytes are compiled into the edge.;rev3=census-ruling-claim-ux-edge;basis=Restyled the fixed embedded banner layout for a one-line summary with a no-script details element; still compiled-in bytes under the reserved asset path, no imports or URLs.;rev3=census-ruling-claim-countdown;basis=Arrange the warning and remaining time on two rows below 640px, keeping the icon and chevron beside them; no URLs, script, inline style or root inputs added.
+- `internal/edge/demo_banner.go` `transformDemoHTMLResponse`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-agent-start-demo-2;basis=demo_banner.go:212-282 transforms the app HTTP response stream. The new ReadAll at :228 is bounded to 512 bytes of response Body for sniffing, not a filesystem read. HTML is streamed through the bounded-prefix injector; unsupported active types/charsets/encodings refuse and stale representation metadata is removed.;rev3=census-ruling-claim-ux-edge;basis=Passes the route's known demo expiry into the injected banner markup for the hours-left text; same bounded sniff and streaming injector, no new reads.
+- `internal/edge/demo_traffic.go` `Edge.demoProxy`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-agent-start-demo-2;basis=demo_traffic.go:537-558 reads the supplied Route.Host and IsForward to install resident banner or forwarding transports before reload wrappers. No new registry lookup; resident content is transformed once, forwarded representations remain unchanged.;rev3=census-ruling-claim-ux-edge;basis=Reads the existing registry field DemoExpiresAt (already used for serving admission) to give the banner its end time; display only, grants no serving authority.
+
+Seal: `eea13e9a0b04164ea3fc7f8258bd1ab0a613d1e23ffe0cd028bc85058576c248` → `c8e2c7ed3850823a8e379d880738982772b870ad8549238cc02abce24c80eb93`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-demo-terms-links.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/demo-terms-links.claims.tsv b/docs/superpowers/notes/demo-terms-links.claims.tsv
new file mode 100644
index 000000000..4bd441fbc
--- /dev/null
+++ b/docs/superpowers/notes/demo-terms-links.claims.tsv
@@ -0,0 +1,3 @@
+internal/edge/demo_assets/banner.css:external Add spacing and wrapping for the optional terms anchor in the compiled-in banner stylesheet; no URL, import, script or runtime read added.
+internal/edge/demo_banner.go:transformDemoHTMLResponse Pass the configured terms URL through the existing bounded-prefix banner injector; no new reads, response policy and streaming behavior unchanged.
+internal/edge/demo_traffic.go:Edge.demoProxy Pass the edge's optional terms URL into the resident demo banner transport; no new registry fields or reads, serving and forwarding authority unchanged.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-demo-terms-links.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-demo-terms-links.md
new file mode 100644
index 000000000..065869a45
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-demo-terms-links.md
@@ -0,0 +1,28 @@
+# Review brief: demo terms links, round 1 of 3
+
+Repo carlos/platform, branch demo-terms-links. Base origin/main 6c2c167afa9db90137bc405408523b50137f1596 (amadan.net remote). Under review: the final local diff and new source/test files in this worktree. No earlier review rounds. Read AGENTS.md and /home/paulca/.cache/demo-terms-apply/ASTRA-BRIEF.md. No push, merge, release, deploy, live console, external messages or other checkout. Do not write files; report via stdout. Do not spawn any agents. Do not run full suites. This is the local independent review before the coordinator pushes; #280 posting is deferred by the local-only scope.
+
+Authorities: the user's ASTRA-BRIEF; merged docs/superpowers/specs/2026-11-02-agent-start-demo-design.md, relevant banner/claim sections of docs/superpowers/plans/2026-11-04-agent-start-demo-2-edge-protections.md and 2026-11-04-agent-start-demo-3-claim.md. Existing implementation is the baseline.
+
+## Fixed
+
+- Approved strings Demo terms, Report abuse: {abuse address}, all nine alerts are verbatim. Alert switches/thresholds/recipients unchanged.
+- Optional configuration; unset/invalid means no new items and unchanged rendered HTML.
+- No real deployment values or infrastructure changes. Core remains deployment-neutral.
+- Independent footer items, only claim template and its existing shared states. No new auth/claim authority.
+
+## Check
+
+1. Validate and trace edge CARLOS_DEMO_TERMS_URL from startup through proxy and HTML escaping; absolute HTTPS, no userinfo, invalid ignored and one startup log without revealing raw values. Narrow layout and CSP remain safe.
+2. Console CARLOS_DEMO_TERMS_URL / CARLOS_DEMO_ABUSE_ADDRESS configuration, independent omission, email validation and mailto escaping, no URL/HTML injection, exact approved copy, CSP hash matches conditional styles; old page bytes when no footer. Trace kept/status/error paths sharing the existing template; don't widen to other templates.
+3. Nine alert strings unchanged, test pins all nine, approved date comment only.
+4. TDD/baseline fixtures and test coverage meaningful, no accidental unrelated edits.
+5. Census: read docs/superpowers/notes/census-proposal-demo-terms-links.md and claims, overlay, chain. Give explicit approval/rejection per changed unit (banner.css external, transformDemoHTMLResponse, Edge.demoProxy) and both envelopes (internal/edge and internal/edge/demo_assets), with file:line evidence. Read every changed production function within these envelopes and its calls, including newEdge, demoTermsURLFromEnv, validDemoTermsURL and injection helpers. Reject if root can newly open/run/query/follow tenant/app/agent-named state, any safety check is weakened, disposition changes improperly or evidence is insufficient.
+
+## Severity and budget
+
+P1: unsafe, fails compilation/tests or does not work; blocks merge. State scenario and file:line evidence. P2: wrong/missing; fixed without reopening review (census/security changes still checked within same round). P3: clarity/polish, follow-up only. Stop at first round without P1. Max 3 rounds; no fourth without Paul. Name invariant/trust-boundary fault family for each finding. No third fix after two rounds in same fault family.
+
+## Output
+
+Rank findings P1/P2/P3 with evidence and concrete fix. Explicit census unit/envelope verdicts. End exactly with READY (no P1/P2), READY AFTER FIXES (P2 only), or NOT READY (P1). Do not edit files or spawn reviewers/subagents. Do not run full test suites.
diff --git a/docs/superpowers/reviews/demo-terms-links-r1.md b/docs/superpowers/reviews/demo-terms-links-r1.md
new file mode 100644
index 000000000..d2b768719
--- /dev/null
+++ b/docs/superpowers/reviews/demo-terms-links-r1.md
@@ -0,0 +1,96 @@
+# Demo terms links: Opus review, round 1 of 3
+
+Author: Codex (edge and integration), Sonnet (initial console footer), Haiku (alert pin).
+Reviewer: Claude Opus, 2026-11-10. Local working-tree diff against origin/main
+6c2c167afa9db90137bc405408523b50137f1596. No earlier rounds.
+The review stops here because there are no P1 findings. P2 fixes do not reopen it;
+P3 items below are follow-ups only. No production changes followed this review.
+The local-only brief defers posting the census verdict on #280 to the coordinator.
+
+No P1 findings. There are two P2s, both in docs and hygiene; nothing in the code needs reopening.
+
+Tests I ran:
+- Edge banner tests (`Demo|Banner` set): ok.
+- Console footer, alert copy, claim CSP and claim page tests: ok.
+- `cmd/console` `TestDemoClaimFooterEnv`: ok.
+- `internal/provision` `Census|RootRead`: ok. It failed inside the sandbox because the Go cache was read-only for its subprocess, so I reran it with the sandbox off.
+- `go vet` on the three changed packages and `gofmt -l`: clean.
+- darwin and windows builds of the changed packages: ok.
+
+## Findings
+
+**P2-1: neither README nor any other doc mentions the new settings.** Fault family: operator configuration contract.
+- The brief asked for the new variables to be documented next to `CARLOS_DEMO_CONSOLE_URL`. None of `CARLOS_DEMO_TERMS_URL` (edge and console) or `CARLOS_DEMO_ABUSE_ADDRESS` (console) appears outside code and tests.
+- The existing edge setting is documented at `README.md:658`, and the console's `CARLOS_DEMO_*` table is at `README.md:632-642`.
+- Correctly, nothing was added to `hostenv.Optional`: `CARLOS_DEMO_CONSOLE_URL` is a per-box host.env value too.
+- **Fix:**
+ - Add a sentence after `README.md:658`: set `CARLOS_DEMO_TERMS_URL` on demo edges, absolute HTTPS with no credentials; an invalid value is ignored with a log line; restart the edge after changing it.
+ - Add two rows to the table at `README.md:632-642` for the console's `CARLOS_DEMO_TERMS_URL` and `CARLOS_DEMO_ABUSE_ADDRESS`: optional, independent, an invalid value hides only that item.
+ - Use example.com values only.
+
+**P2-2: committing with `git add -A .`, as the brief says, would pick up stray files.** Fault family: commit scope.
+- `.demo-terms-work/` is untracked and not ignored. It holds about 30 PNG screenshots, `demo_alert_copy_mutant.go`, `escape.go` and logs.
+- The sandbox also leaves zero-byte or device placeholders in the worktree (`.bashrc`, `.gitconfig`, `.gitmodules`, `.mcp.json`, `.idea`, `.vscode`, `.zprofile`, `.claude/{agents,settings.json,…}`), and they show up as untracked.
+- **Fix:** move `.demo-terms-work/` out of the worktree. Stage the 17 modified files and 11 new files by path, then check `git diff --cached --stat` before committing.
+
+**P3s (follow-up only)**
+- `internal/edge/demo_copy.go:23`: `BANNER-UX-07` sits before `-06`. Reorder it.
+- `banner.css:81` together with the leading space at `demo_banner.go:47`: the gap between the two links is a space plus `.75em`, and on a narrow screen a wrapped "Demo terms" starts indented. Use the space or the margin, not both.
+- `cmd/console/main.go` `demoClaimFooterEnv` drops invalid values without a log line, while the edge logs once (`demo_banner.go:339`). A matching value-free log would help operators.
+- `ValidDemoTermsURL` exists twice, in `internal/edge/demo_banner.go:329` and `internal/console/demo_claim_footer.go:33`. They are identical now but could drift apart; a shared helper would prevent that.
+
+## The checks you asked for
+
+1. **Edge terms URL: ok.**
+ - Startup: `newEdge` calls `demoTermsURLFromEnv(os.Getenv)` (`edge.go:628`). That accepts only `validDemoTermsURL`: https scheme, a host, no userinfo, not opaque, no backslash, no whitespace or control characters. Otherwise it logs once, without the value, and the field stays empty (`demo_banner.go:329-341`).
+ - Proxy: `demoProxy` passes `e.demoTermsURL` on (`demo_traffic.go:565`), and `transformDemoHTMLResponse` hands it to `demoBannerReader` and then `demoBannerMarkup`.
+ - Markup: `demoBannerMarkup` checks the URL again and escapes it with `html.EscapeString` (`demo_banner.go:45-49`).
+ - With the URL unset or invalid, the banner bytes equal the fixture `testdata/demo_banner_without_terms.html`.
+ - The banner CSP is unchanged.
+ - `serveDemoHTML` has no production caller.
+ - The browser test checks both links fit inside the banner at 390 and 1280 px.
+2. **Console footer: ok.**
+ - The settings are read in `cmd/console/main.go` and checked again at render time in `demoClaimFooter()`.
+ - The terms link and the abuse line are independent: either can show without the other.
+ - The abuse address is a plain address. `AbuseURL` runs it through `url.PathEscape`, so `?` and `#` cannot open headers or a fragment, and a test checks the address round-trips.
+ - `html/template` escapes everything; a test covers it.
+ - The copy is exact: `Demo terms` and `Report abuse: ` followed by the mailto link.
+ - The footer CSS renders only when the footer does (`demo_claim.html:145-147`), so its CSP hash is separate, and the header and the rendered page both read the same server configuration (`demo_claim_page.go:65-85`).
+ - With no footer, the page bytes match the pre-footer digests for the template states, the error page, `GET /demo/claim` and `GET /demo/claim/kept`. I also checked by reading the template: with no footer the output is identical.
+ - The page, error and kept paths all go through `renderDemoClaimPage`. No other template was touched.
+ - `--rule` and `--muted` are existing tokens from `console_chrome.html`.
+3. **Alert copy: ok.** Compared with `origin/main`, the only change to `demo_alert_copy.go` is the two-line comment. `TestDemoAlertCopyPinned` pins all nine strings verbatim.
+4. **Tests: ok.**
+ - The tests mean something: byte baselines, invalid-input tables, a proxy wiring test, mailto round-trips, CSP hash matching, and a layout check on the long-address case (64-character local part, 63-character label).
+ - The only changes outside scope are the mechanical updates to `demoBannerMarkup` callers in tests.
+
+## Census verdicts
+
+**Units**
+
+| Unit | Verdict | Evidence |
+|---|---|---|
+| `internal/edge/demo_assets/banner.css` `external` | **APPROVE** | One rule added (`banner.css:81`). No URL, `@import`, script or runtime read. The file is still compiled in and served under the reserved asset path. |
+| `internal/edge/demo_banner.go` `transformDemoHTMLResponse` | **APPROVE** | The only change is the extra `termsURL` argument passed to `demoBannerReader` (`demo_banner.go:286`). The 512-byte sniff, the type, charset and encoding refusals, and the bounded-prefix streaming are unchanged. No new read. |
+| `internal/edge/demo_traffic.go` `Edge.demoProxy` | **APPROVE** | It sets `termsURL: e.demoTermsURL` from the edge struct (`demo_traffic.go:565`). No new registry field or lookup. The transport choice and the forward/resident split are unchanged. |
+
+**Envelopes**
+
+- **`internal/edge`: APPROVE.** I read every changed function and what it calls:
+ - `newEdge` reads one more variable from the root-owned process environment (`edge.go:628`).
+ - `demoTermsURLFromEnv` and `validDemoTermsURL` are pure checks plus a value-free log.
+ - `demoBannerMarkup`, `demoBannerReader`, `injectDemoBanner`, `serveDemoHTML`, the `demoBannerTransport` field and `RoundTrip` only thread a string through.
+ - `demoUXCopy` gains one map entry.
+
+ None of this opens, runs, queries or follows anything a tenant, app or agent can name. The URL comes only from operator configuration and goes into an `<a href>` in the banner as escaped text. No check is weakened: report-origin validation at `demo_banner.go:31` is untouched.
+- **`internal/edge/demo_assets`: APPROVE.** Only `banner.css` changed, as described for its unit above.
+- **Overlay and chain:** all three units keep their recorded `legacy`/`accepted-legacy` disposition, and the basis text is appended, not replaced. The seal goes from `eea13e9a…` to `c8e2c7ed…`, and the chain line is added to `plan14-root-reads-chain.tsv`. The `Census|RootRead` tests pass. `newEdge` has no census row, which is consistent with it having no read site.
+
+READY AFTER FIXES
+
+## Author disposition after round 1
+
+- P2-1: pending copy approval for the prepared README paragraph. The branch is not ready to land until that documentation is applied.
+- P2-2: task-owned screenshots, mutation source and scratch logs are removed before staging. The sandbox placeholders reported by the reviewer are absent from the actual worktree; none were deleted by pattern. Stage with the user-mandated `git add -A .` after cleanup.
+- P3 items remain follow-ups; no second review round.
+- The full requested console test selection reached Go’s default ten-minute timeout after 194 passes and one live-dev skip. Its last two tests passed in a separate invocation. The test-name inventory confirms all 197 matching tests are accounted for.
diff --git a/internal/console/demo_alert_copy.go b/internal/console/demo_alert_copy.go
index 45a8fe6dd..8280c9d4a 100644
--- a/internal/console/demo_alert_copy.go
+++ b/internal/console/demo_alert_copy.go
@@ -1,7 +1,7 @@
package console
-// Draft operator copy, off by default. Paul reviews these strings before
-// demo alerts are switched on.
+// Operator copy for demo alert email. Paul approved these strings on
+// 2026-11-10 (copy review, no edits). Alerts stay off by default.
const (
demoAlertPassLog = "console: demo alerts: %v"
demoAlertConfigError = "console: invalid demo alert setting %s"
diff --git a/internal/console/demo_alert_copy_test.go b/internal/console/demo_alert_copy_test.go
new file mode 100644
index 000000000..2a236be0e
--- /dev/null
+++ b/internal/console/demo_alert_copy_test.go
@@ -0,0 +1,30 @@
+package console
+
+import "testing"
+
+// TestDemoAlertCopyPinned pins the nine approved demo alert strings, so an
+// edit to any of them fails here instead of drifting silently.
+func TestDemoAlertCopyPinned(t *testing.T) {
+ tests := []struct {
+ name string
+ got string
+ want string
+ }{
+ {"alert.subject", demoAlertSubject, "[carlos] Demo activity needs attention"},
+ {"alert.body", demoAlertBody, "%s\n\nConsole: %s\nCheck demos with carlos system demos status and reports with carlos system demos reports.\nThese counts are signals to investigate, not proof of abuse.\n"},
+ {"budget", demoAlertText["budget"], "%d demo create attempts used at least %d%% of the rolling daily budget of %d."},
+ {"ips", demoAlertText["ips"], "%d demo create attempts came from the busiest %d IP budgets within %s. An IPv6 budget covers a /64."},
+ {"prefix", demoAlertText["prefix"], "%d demo create attempts came from one IPv4 /24 or IPv6 /48 within %s."},
+ {"refusals", demoAlertText["refusals"], "%d demo admissions were refused across the latest %s of minute buckets, including the current partial minute."},
+ {"reports", demoAlertText["reports"], "%d abuse reports arrived in the last hour, more than the threshold of %d."},
+ {"digest.subject", demoAlertDigestSubject, "[carlos] Daily demo abuse reports"},
+ {"digest.body", demoAlertDigestBody, "%d abuse reports arrived since %s (UTC), before %s (UTC).\n\nConsole: %s\nReview them with carlos system demos reports. Resolved reports are included in this count.\n"},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if tc.got != tc.want {
+ t.Errorf("%s drifted:\n got: %q\nwant: %q", tc.name, tc.got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/console/demo_claim_copy.go b/internal/console/demo_claim_copy.go
index 3557dccf2..23086c70c 100644
--- a/internal/console/demo_claim_copy.go
+++ b/internal/console/demo_claim_copy.go
@@ -96,6 +96,13 @@ const (
demoClaimAccountCap = "This account has reached its plan limit. Choose another account or free up capacity."
)
+const (
+ // CLAIM-FOOTER-TERMS: link to the configured demo terms.
+ demoClaimFooterTerms = "Demo terms"
+ // CLAIM-FOOTER-ABUSE: precedes the abuse address, which is a mailto link.
+ demoClaimFooterAbuse = "Report abuse: "
+)
+
// CLAIM-RESUME-SUBMITTING: the previously confirmed selection is being posted.
const demoClaimResuming = "Keeping your demo in the account you chose…"
diff --git a/internal/console/demo_claim_footer.go b/internal/console/demo_claim_footer.go
new file mode 100644
index 000000000..13feb90b1
--- /dev/null
+++ b/internal/console/demo_claim_footer.go
@@ -0,0 +1,75 @@
+package console
+
+import (
+ "net/url"
+ "strings"
+ "unicode"
+)
+
+// The claim page footer shows two optional items: a link to the deployment's
+// demo terms and a mailto link for abuse reports. The deployment configures
+// both (Config.DemoTermsURL, Config.DemoAbuseAddress); the platform names
+// neither. Each item renders only when its value passes the checks below, and
+// with neither the page is byte-for-byte what it was before the footer.
+type demoClaimFooter struct{ TermsURL, Abuse string }
+
+// On reports whether anything renders. The footer's CSS rides on it.
+func (f demoClaimFooter) On() bool { return f.TermsURL != "" || f.Abuse != "" }
+
+// demoClaimFooter validates here, at render time, so a Config built directly
+// (tests, embedders) is held to the same rules as one loaded from the environment.
+func (s *Server) demoClaimFooter() demoClaimFooter {
+ var f demoClaimFooter
+ if ValidDemoTermsURL(s.cfg.DemoTermsURL) {
+ f.TermsURL = s.cfg.DemoTermsURL
+ }
+ if ValidDemoAbuseAddress(s.cfg.DemoAbuseAddress) {
+ f.Abuse = s.cfg.DemoAbuseAddress
+ }
+ return f
+}
+
+// ValidDemoTermsURL accepts an absolute HTTPS URL without credentials.
+func ValidDemoTermsURL(raw string) bool {
+ u, err := url.Parse(raw)
+ return err == nil && u.Scheme == "https" && u.Hostname() != "" && u.User == nil && u.Opaque == "" && !strings.Contains(raw, "\\") && strings.IndexFunc(raw, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) < 0
+}
+
+// AbuseURL encodes the address as a recipient, so punctuation in its local
+// part cannot turn into mailto headers or a fragment.
+func (f demoClaimFooter) AbuseURL() string { return "mailto:" + url.PathEscape(f.Abuse) }
+
+// ValidDemoAbuseAddress accepts a single plain dot-atom address with a DNS
+// hostname. Display names, quoted addresses, whitespace and controls fail.
+func ValidDemoAbuseAddress(s string) bool {
+ if s == "" || len(s) > 254 {
+ return false
+ }
+ local, domain, ok := strings.Cut(s, "@")
+ if !ok || local == "" || domain == "" || len(local) > 64 || strings.Contains(domain, "@") {
+ return false
+ }
+ for i := 0; i < len(local); i++ {
+ if c := local[i]; !mailAlnum(c) && !strings.ContainsRune(".!#$%&'*+-/=?^_`{|}~", rune(c)) {
+ return false
+ }
+ }
+ if local[0] == '.' || local[len(local)-1] == '.' || strings.Contains(local, "..") {
+ return false
+ }
+ for _, label := range strings.Split(domain, ".") {
+ if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
+ return false
+ }
+ for i := 0; i < len(label); i++ {
+ if c := label[i]; !mailAlnum(c) && c != '-' {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+func mailAlnum(c byte) bool {
+ return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'
+}
diff --git a/internal/console/demo_claim_footer_addresses_test.go b/internal/console/demo_claim_footer_addresses_test.go
new file mode 100644
index 000000000..00f4468f7
--- /dev/null
+++ b/internal/console/demo_claim_footer_addresses_test.go
@@ -0,0 +1,49 @@
+package console
+
+import (
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+
+ "golang.org/x/net/html"
+)
+
+func TestDemoClaimFooterPlainEmailEscaping(t *testing.T) {
+ for _, address := range []string{"o'hara&team@example.com", "ops?subject=hello@example.com", "ops#tag@example.com", "ops%tag@example.com"} {
+ t.Run(address, func(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ s.cfg.DemoAbuseAddress = address
+ w := httptest.NewRecorder()
+ s.demoClaimBrowserError(w, 403, demoClaimWrongSite)
+ z := html.NewTokenizer(strings.NewReader(w.Body.String()))
+ found := false
+ for z.Next() != html.ErrorToken {
+ token := z.Token()
+ if token.Type != html.StartTagToken || token.Data != "a" {
+ continue
+ }
+ for _, attr := range token.Attr {
+ if attr.Key != "href" || !strings.HasPrefix(attr.Val, "mailto:") {
+ continue
+ }
+ u, err := url.Parse(attr.Val)
+ if err != nil || u.RawQuery != "" || u.Fragment != "" {
+ t.Fatalf("mailto opens query or fragment: %q (%v)", attr.Val, err)
+ }
+ recipient, err := url.PathUnescape(strings.TrimPrefix(attr.Val, "mailto:"))
+ if err != nil || recipient != address {
+ t.Fatalf("recipient = %q, want %q (%v)", recipient, address, err)
+ }
+ if z.Next() != html.TextToken || z.Token().Data != address {
+ t.Fatal("address text did not round-trip through HTML")
+ }
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("valid plain address was hidden")
+ }
+ })
+ }
+}
diff --git a/internal/console/demo_claim_footer_test.go b/internal/console/demo_claim_footer_test.go
new file mode 100644
index 000000000..5c4754a95
--- /dev/null
+++ b/internal/console/demo_claim_footer_test.go
@@ -0,0 +1,263 @@
+package console
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/base64"
+ "fmt"
+ "net/http/httptest"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+// The digests were taken from the claim page before the footer existed. With
+// neither item configured (or both invalid) the page is these exact bytes.
+const demoClaimFooterBaseStyleHash = "'sha256-0/eCVx0ZVcjLY0c+mSbXxujrLi96B+0QEsMyCIBaADI='"
+
+var demoClaimFooterBaseDigests = map[string]string{
+ "template-zero": "48b65f39722b9f26dfd9e1cc74e99b8d25859993e4af6681e886e8a9b09c923f",
+ "template-missing": "2c793c646d7199bba6a84e4c552992dfc8fd7d17111a108232b93e4fa92ec5a0",
+ "template-error": "1e8177ca639ff61406cfc0bc9db173b6668ac924bf53b875da7a5ef0dd1961ae",
+ "template-claimed": "ab4542a9b912449bbc637595e9f51f653b417940eee103e7970eadb710fd667e",
+ "template-proof": "9ca3d70d40f86bffa5081768630b3524b60548f2e8ffcb26eaf10e0a0c9e6458",
+ "error-page": "f6cd7ee22473fb614b2f247599a1dfe3eac1ce870268ad6332ebafc37fd49a09",
+ "get-claim": "c67a7aa13e23edb1a78fec563c17d74f173fa5153dc4fea3c8a10d128c18395d",
+ "get-kept": "6050a0a0f5516f8209baf8dcf4a6549986f4f97d1f0026889cc8ad5e1b4c5d93",
+}
+
+const (
+ footerTerms = "https://carloku.example/terms/demos/"
+ footerAbuse = "abuse@example.com"
+)
+
+var footerNonceRE = regexp.MustCompile(`(name="(?:nonce|csrf)" value=")[^"]*`)
+
+func footerDigest(b []byte) string { return fmt.Sprintf("%x", sha256.Sum256(b)) }
+
+func footerTemplateCases() map[string]demoClaimPageData {
+ cp := demoClaimBrowserCopy
+ return map[string]demoClaimPageData{
+ "template-zero": {},
+ "template-missing": {Copy: cp(), State: "missing"},
+ "template-error": {Copy: cp(), Error: "Cross-site request blocked."},
+ "template-claimed": {Copy: cp(), State: "claimed", URL: "https://app.example.com"},
+ "template-proof": {Copy: cp(), State: "proof", HasIntent: true, CanClaim: true, EmailPending: true, Address: "a@example.com", Nonce: "n", CSRF: "c"},
+ }
+}
+
+// footerPages renders every page the claim template serves, keyed like the
+// base digests, with the nonces normalised.
+func footerPages(t *testing.T, s *Server) map[string][]byte {
+ t.Helper()
+ out := map[string][]byte{}
+ for name, data := range footerTemplateCases() {
+ var b bytes.Buffer
+ if err := demoClaimPageTemplate.ExecuteTemplate(&b, "demo_claim.html", data); err != nil {
+ t.Fatal(err)
+ }
+ out[name] = b.Bytes()
+ }
+ w := httptest.NewRecorder()
+ s.demoClaimBrowserError(w, 403, demoClaimWrongSite)
+ out["error-page"] = w.Body.Bytes()
+ b := &claimBrowser{t: t, s: s}
+ out["get-claim"] = footerNonceRE.ReplaceAll(b.request("GET", "/demo/claim", nil).Body.Bytes(), []byte("$1X"))
+ out["get-kept"] = footerNonceRE.ReplaceAll(b.request("GET", "/demo/claim/kept", nil).Body.Bytes(), []byte("$1X"))
+ return out
+}
+
+func footerStyleHeaderMatches(t *testing.T, header, body string) {
+ t.Helper()
+ _, rest, _ := strings.Cut(body, "<style>")
+ css, _, _ := strings.Cut(rest, "</style>")
+ sum := sha256.Sum256([]byte(css))
+ if want := "style-src 'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "';"; !strings.Contains(header, want) {
+ t.Errorf("CSP does not carry the hash of the rendered style: %s", header)
+ }
+}
+
+func TestDemoClaimFooterAbsentKeepsOldBytes(t *testing.T) {
+ invalid := []struct{ terms, abuse string }{
+ {"", ""},
+ {"http://carloku.example/terms", "not an address"},
+ {"https://", "a@b@example.com"},
+ {"javascript:alert(1)", "<abuse@example.com>"},
+ {"https://user:pw@carloku.example/terms", "abuse@example.com?cc=x@example.com"},
+ }
+ for _, c := range invalid {
+ s, _, _ := claimTestServer(t)
+ s.cfg.DemoTermsURL, s.cfg.DemoAbuseAddress = c.terms, c.abuse
+ pages := footerPages(t, s)
+ for name, want := range demoClaimFooterBaseDigests {
+ if got := footerDigest(pages[name]); got != want {
+ t.Errorf("%q/%q: %s changed with no valid footer: %s", c.terms, c.abuse, name, got)
+ }
+ }
+ w := httptest.NewRecorder()
+ s.demoClaimBrowserError(w, 403, demoClaimWrongSite)
+ if !strings.Contains(w.Header().Get("Content-Security-Policy"), "style-src "+demoClaimFooterBaseStyleHash+";") {
+ t.Errorf("%q/%q: base style hash changed: %s", c.terms, c.abuse, w.Header().Get("Content-Security-Policy"))
+ }
+ if bytes.Contains(pages["get-claim"], []byte("claim-footer")) {
+ t.Errorf("%q/%q: footer rendered", c.terms, c.abuse)
+ }
+ }
+}
+
+func TestDemoClaimFooterItems(t *testing.T) {
+ termsLink := `<a href="` + footerTerms + `" target="_blank" rel="noopener noreferrer">Demo terms</a>`
+ abuseLine := `Report abuse: <a href="mailto:` + footerAbuse + `">` + footerAbuse + `</a>`
+ for _, c := range []struct {
+ name, terms, abuse string
+ wantTerms, wantAbuse bool
+ }{
+ {"both", footerTerms, footerAbuse, true, true},
+ {"terms only", footerTerms, "", true, false},
+ {"abuse only", "", footerAbuse, false, true},
+ {"terms with invalid abuse", footerTerms, "abuse example.com", true, false},
+ {"abuse with invalid terms", "http://carloku.example/terms", footerAbuse, false, true},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ s.cfg.DemoTermsURL, s.cfg.DemoAbuseAddress = c.terms, c.abuse
+ b := &claimBrowser{t: t, s: s}
+ pages := map[string]*httptest.ResponseRecorder{
+ "claim": b.request("GET", "/demo/claim", nil),
+ "kept": b.request("GET", "/demo/claim/kept", nil),
+ "error": httptest.NewRecorder(),
+ }
+ s.demoClaimBrowserError(pages["error"], 403, demoClaimWrongSite)
+ for name, w := range pages {
+ body := w.Body.String()
+ if got := strings.Contains(body, termsLink); got != c.wantTerms {
+ t.Errorf("%s: terms link present = %v", name, got)
+ }
+ if got := strings.Contains(body, abuseLine); got != c.wantAbuse {
+ t.Errorf("%s: abuse line present = %v", name, got)
+ }
+ if strings.Count(body, `<footer class="claim-footer">`) != 1 || strings.Count(body, "<script") != 1 || strings.Contains(body, " style=") {
+ t.Errorf("%s: want one footer, one script, no inline styles", name)
+ }
+ if i, j := strings.Index(body, `<footer class="claim-footer">`), strings.Index(body, "</main>"); i < 0 || j < i || strings.Index(body, "<main") > i {
+ t.Errorf("%s: footer must sit inside main", name)
+ }
+ if strings.Contains(w.Header().Get("Content-Security-Policy"), demoClaimFooterBaseStyleHash) {
+ t.Errorf("%s: footer styles need their own CSP hash", name)
+ }
+ footerStyleHeaderMatches(t, w.Header().Get("Content-Security-Policy"), body)
+ if !strings.Contains(w.Header().Get("Content-Security-Policy"), "style-src 'sha256-") || strings.Contains(w.Header().Get("Content-Security-Policy"), "unsafe-inline") {
+ t.Errorf("%s: CSP widened: %s", name, w.Header().Get("Content-Security-Policy"))
+ }
+ }
+ })
+ }
+}
+
+func TestDemoClaimFooterPagesEveryState(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ s.cfg.DemoTermsURL, s.cfg.DemoAbuseAddress = footerTerms, footerAbuse
+ for name, body := range footerPages(t, s) {
+ if !bytes.Contains(body, []byte(`Report abuse: <a href="mailto:abuse@example.com">`)) && !strings.HasPrefix(name, "template-") {
+ t.Errorf("%s: no footer", name)
+ }
+ }
+}
+
+func TestDemoClaimFooterEscapesValues(t *testing.T) {
+ // The template escapes on its own, whatever the validators let through.
+ var b bytes.Buffer
+ data := demoClaimPageData{Copy: demoClaimBrowserCopy(), Footer: demoClaimFooter{TermsURL: `https://example.com/t?a=1&b="<x>"`, Abuse: `a"><script>alert(1)</script>@example.com`}}
+ if err := demoClaimPageTemplate.ExecuteTemplate(&b, "demo_claim.html", data); err != nil {
+ t.Fatal(err)
+ }
+ body := b.String()
+ if strings.Contains(body, "<script>alert") || strings.Contains(body, `"<x>"`) || strings.Contains(body, `a"><`) {
+ t.Fatal("configured values reached the page unescaped")
+ }
+ if !strings.Contains(body, `&amp;b=`) {
+ t.Error("ampersand in the URL not escaped")
+ }
+
+ // Through the server, a valid URL carrying & and ' stays inert.
+ s, _, _ := claimTestServer(t)
+ s.cfg.DemoTermsURL = "https://carloku.example/terms?a=1&b='x'"
+ s.cfg.DemoAbuseAddress = footerAbuse
+ w := httptest.NewRecorder()
+ s.demoClaimBrowserError(w, 403, demoClaimWrongSite)
+ _, rest, _ := strings.Cut(w.Body.String(), `<footer class="claim-footer">`)
+ foot, _, _ := strings.Cut(rest, "</footer>")
+ if !strings.Contains(foot, `/terms?a=1&amp;b=%27x%27"`) || strings.Contains(foot, "'") {
+ t.Errorf("URL not escaped in footer: %s", foot)
+ }
+}
+
+func TestDemoClaimFooterTermsURLValidation(t *testing.T) {
+ good := []string{
+ "https://carloku.example/terms/demos/",
+ "https://carloku.example",
+ "https://carloku.example:8443/terms?a=1#top",
+ "https://sub.carloku.example/a%20b",
+ "https://carloku.example/café", "https://carloku.example/<x>", "https://carloku.example/\"", "https://carloku.example/`",
+ "https://carloku.example/" + strings.Repeat("a", 2100),
+ }
+ bad := []string{
+ "", " ", "http://carloku.example/terms", "ftp://carloku.example", "//carloku.example/terms",
+ "/terms", "terms", "mailto:abuse@example.com", "javascript:alert(1)", "data:text/html,x",
+ "https:carloku.example", "https:///terms", "https://", "https://:443/terms",
+ "https://user@carloku.example/", "https://user:pw@carloku.example/", "https://@carloku.example/",
+ "https://carloku.example\\terms", "https://carloku.example/te rms", " https://carloku.example/",
+ "https://carloku.example/\n", "https://carloku.example/\x00", "https://carloku.example/\t",
+ "https://carloku.example/\u00a0", "https://carloku.example/\u2028", "https://carloku.example/%zz",
+ "https://carloku.example:port/",
+ }
+ for _, v := range good {
+ if !ValidDemoTermsURL(v) {
+ t.Errorf("rejected %q", v)
+ }
+ }
+ for _, v := range bad {
+ if ValidDemoTermsURL(v) {
+ t.Errorf("accepted %q", v)
+ }
+ }
+}
+
+func TestDemoClaimFooterAbuseAddressValidation(t *testing.T) {
+ good := []string{"abuse@example.com", "abuse+demo@example.com", "a.b_c-d@sub.example.co.uk", "abuse@localhost", "o'hara&team@example.com", "abuse?cc=x@example.com", "abuse?subject=x@example.com", "abuse%0d@example.com"}
+ bad := []string{
+ "", " ", "abuse", "@example.com", "abuse@", "a@b@example.com", "abuse @example.com", "abuse@exam ple.com",
+ " abuse@example.com", "abuse@example.com ", "abuse@example.com\n", "abuse@example.com\x00",
+ "<abuse@example.com>", "Abuse <abuse@example.com>", "abuse@example.com>", "\"abuse\"@example.com",
+ "abuse@example.com?cc=x@example.com",
+ "abuse@example.com&bcc=x@example.com", "abuse@example.com#x", "abuse,x@example.com",
+ "abuse;x@example.com", "abuse\\@example.com", "abuse@exa_mple.com", "abuse@-example.com", "abuse@example..com",
+ ".abuse@example.com", "abuse.@example.com", "a..b@example.com", "abuse@example.com.", "abuse@[127.0.0.1]",
+ "abuse@exämple.com", "mailto:abuse@example.com", "abuse@example.com\u00a0",
+ strings.Repeat("a", 65) + "@example.com",
+ "a@" + strings.Repeat("b", 64) + ".example.com",
+ "a@" + strings.Repeat("b.", 125) + "com",
+ }
+ for _, v := range good {
+ if !ValidDemoAbuseAddress(v) {
+ t.Errorf("rejected %q", v)
+ }
+ }
+ for _, v := range bad {
+ if ValidDemoAbuseAddress(v) {
+ t.Errorf("accepted %q", v)
+ }
+ }
+}
+
+func TestDemoClaimFooterCopy(t *testing.T) {
+ c := demoClaimBrowserCopy()
+ if c["footerTerms"] != "Demo terms" || c["footerAbuse"] != "Report abuse: " {
+ t.Fatalf("footer copy = %q, %q", c["footerTerms"], c["footerAbuse"])
+ }
+ for _, v := range []string{c["footerTerms"], c["footerAbuse"]} {
+ if strings.ContainsAny(v, "—–") {
+ t.Errorf("dash in copy %q", v)
+ }
+ }
+}
diff --git a/internal/console/demo_claim_kept.go b/internal/console/demo_claim_kept.go
index 48a830ec4..e5fb4400f 100644
--- a/internal/console/demo_claim_kept.go
+++ b/internal/console/demo_claim_kept.go
@@ -31,8 +31,8 @@ func (s *Server) handleDemoClaimKeptPage(w http.ResponseWriter, r *http.Request)
setDemoClaimCookie(w, raw, time.Now().Add(15*time.Minute))
}
_, session, _ := s.session(r)
- demoClaimPageHeaders(w, s.km.Origin())
- _ = demoClaimPageTemplate.ExecuteTemplate(w, "demo_claim.html", demoClaimPageData{Chrome: page{Brand: s.brandName()}, Copy: demoClaimBrowserCopy(), State: "missing", Nonce: demoClaimNonce(raw, session), CSRF: session})
+ s.demoClaimPageHeaders(w, s.km.Origin())
+ _ = s.renderDemoClaimPage(w, demoClaimPageData{Chrome: page{Brand: s.brandName()}, Copy: demoClaimBrowserCopy(), State: "missing", Nonce: demoClaimNonce(raw, session), CSRF: session})
}
func (s *Server) handleDemoClaimKept(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index d118f3846..77b4e04d9 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -10,6 +10,7 @@ import (
"errors"
"fmt"
"html/template"
+ "io"
"net/http"
"net/url"
"strings"
@@ -20,18 +21,27 @@ const demoClaimBrowserCookie = "carlos_demo_claim_flow"
var demoClaimPageTemplate = template.Must(template.New("demo_claim.html").Funcs(template.FuncMap{"asset": assetURL, "icon": icon}).ParseFS(tmplFS, "templates/demo_claim.html", "templates/console_chrome.html", "templates/fiesta.html"))
-var demoClaimStyleHash = func() string {
+// demoClaimStyleHashFor hashes the page's inline style as sent. The footer adds
+// CSS only when it renders, so the two states have two hashes and the CSP
+// carries the one that matches. With no footer the style (and its hash) is
+// exactly the pre-footer one.
+func demoClaimStyleHashFor(p demoClaimPageData) string {
// Hash the style in its HTML context: html/template removes CSS comments
// inside <style>, so the standalone template's bytes are not the sent bytes.
var rendered bytes.Buffer
- if err := demoClaimPageTemplate.ExecuteTemplate(&rendered, "demo_claim.html", demoClaimPageData{}); err != nil {
+ if err := demoClaimPageTemplate.ExecuteTemplate(&rendered, "demo_claim.html", p); err != nil {
panic(err)
}
_, rest, _ := strings.Cut(rendered.String(), "<style>")
css, _, _ := strings.Cut(rest, "</style>")
sum := sha256.Sum256([]byte(css))
return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
-}()
+}
+
+var (
+ demoClaimStyleHash = demoClaimStyleHashFor(demoClaimPageData{})
+ demoClaimFooterStyleHash = demoClaimStyleHashFor(demoClaimPageData{Footer: demoClaimFooter{TermsURL: "https://example.com/"}})
+)
type demoClaimPageData struct {
SourceSteps []claimSourceStep
@@ -49,23 +59,35 @@ type demoClaimPageData struct {
TimeLeft, TimeLeftAccessible, EndTime string
Step int
CanClaim, HasIntent, EmailPending bool
+ Footer demoClaimFooter
}
-func demoClaimPageHeaders(w http.ResponseWriter, keymailOrigin string) {
+func (s *Server) demoClaimPageHeaders(w http.ResponseWriter, keymailOrigin string) {
+ styleHash := demoClaimStyleHash
+ if s.demoClaimFooter().On() {
+ styleHash = demoClaimFooterStyleHash
+ }
formAction := "'self'"
if keymailOrigin != "" {
formAction += " " + keymailOrigin
}
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Referrer-Policy", "origin")
- w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; connect-src 'self'; style-src "+demoClaimStyleHash+"; form-action "+formAction+"; frame-ancestors 'none'; base-uri 'none'")
+ w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; connect-src 'self'; style-src "+styleHash+"; form-action "+formAction+"; frame-ancestors 'none'; base-uri 'none'")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
}
+// renderDemoClaimPage is the one way this flow writes the page, so the footer
+// follows the same configuration that picked the CSP style hash.
+func (s *Server) renderDemoClaimPage(w io.Writer, p demoClaimPageData) error {
+ p.Footer = s.demoClaimFooter()
+ return demoClaimPageTemplate.ExecuteTemplate(w, "demo_claim.html", p)
+}
+
func (s *Server) demoClaimBrowserError(w http.ResponseWriter, status int, message string) {
- demoClaimPageHeaders(w, "")
+ s.demoClaimPageHeaders(w, "")
w.WriteHeader(status)
- _ = demoClaimPageTemplate.ExecuteTemplate(w, "demo_claim.html", demoClaimPageData{Chrome: page{Brand: s.brandName()}, Copy: demoClaimBrowserCopy(), Error: message})
+ _ = s.renderDemoClaimPage(w, demoClaimPageData{Chrome: page{Brand: s.brandName()}, Copy: demoClaimBrowserCopy(), Error: message})
}
func setDemoClaimCookie(w http.ResponseWriter, raw string, expiry time.Time) {
@@ -109,7 +131,7 @@ func (s *Server) attachDemoClaimBrowser(w http.ResponseWriter, r *http.Request,
// A render may read existing work with admission off. It never proves identity,
// chooses an account, or starts a reservation, including on OAuth return.
func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
- demoClaimPageHeaders(w, s.km.Origin())
+ s.demoClaimPageHeaders(w, s.km.Origin())
if s.cfg.HostClaim || s.store.claimGated() {
s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return
@@ -258,7 +280,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
p.Copy["accountsIntro"] = strings.ReplaceAll(demoClaimUX25, "{used}", fmt.Sprint(len(p.Accounts)))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
- if err = demoClaimPageTemplate.ExecuteTemplate(w, "demo_claim.html", p); err != nil {
+ if err = s.renderDemoClaimPage(w, p); err != nil {
return
}
}
@@ -639,6 +661,8 @@ func demoClaimBrowserCopy() map[string]string {
"stopping": demoClaimStopping,
"aborted": demoClaimAborted,
"disabled": demoClaimUnavailable,
+ "footerTerms": demoClaimFooterTerms,
+ "footerAbuse": demoClaimFooterAbuse,
}
}
diff --git a/internal/console/demo_claim_page_test.go b/internal/console/demo_claim_page_test.go
index 2812a34d3..e03855204 100644
--- a/internal/console/demo_claim_page_test.go
+++ b/internal/console/demo_claim_page_test.go
@@ -176,6 +176,8 @@ func TestDemoClaimBrowserHeadless(t *testing.T) {
t.Skip("no installed node for browser protocol")
}
s, m, token := claimTestServer(t)
+ s.cfg.DemoTermsURL = "https://example.com/terms/demos/"
+ s.cfg.DemoAbuseAddress = strings.Repeat("a", 64) + "@" + strings.Repeat("b", 63) + ".example.com"
s.registerRoute(routeDecl{Pattern: "GET /static/{hash}/{file...}"}, s.handleStatic)
var mu sync.Mutex
var leaked bool
diff --git a/internal/console/server.go b/internal/console/server.go
index a9d2c1df9..3b0fc526a 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -539,6 +539,10 @@ type Config struct {
DomainApex zonehost.ApexSource
DomainCatalog *domainreg.Catalog
+ // The claim page footer. Each is optional, validated again where it is
+ // rendered, and invisible when unset or invalid (demo_claim_footer.go).
+ DemoTermsURL, DemoAbuseAddress string
+
HostClaimOps *hostops.Controller
HostClaimRecovery *hostops.Recovery
ClaimMoveRecovery func(context.Context, *hostops.MoveRecoveryGrant) error
diff --git a/internal/console/templates/demo_claim.html b/internal/console/templates/demo_claim.html
index 6428e7768..13788753c 100644
--- a/internal/console/templates/demo_claim.html
+++ b/internal/console/templates/demo_claim.html
@@ -142,7 +142,10 @@
#claim .claim-track i, #claim .claim-burst, #claim.is-celebrating .claim-address .claim-old { display: none; }
#claim.is-celebrating #claim-finished { animation: claim-fade .2s ease both !important; }
}
-</style>
+{{if .Footer.On}}#claim .claim-footer { display: flex; flex-wrap: wrap; gap: 0 1.5rem; margin-top: 3rem; padding-top: 1rem; border-top: 1px solid var(--rule); font-size: .85rem; color: var(--muted); }
+#claim .claim-footer p { min-width: 0; overflow-wrap: anywhere; margin: 0; color: var(--muted); }
+#claim .claim-footer a { display: inline-block; max-width: 100%; padding-block: .6rem; }
+{{end}}</style>
</head>
<body>
{{template "console_header" .Chrome}}
@@ -233,7 +236,8 @@
{{end}}
{{end}}
{{if eq .State "missing"}}<noscript><p>{{.Copy.noscript}}</p></noscript>{{end}}
-</main>
+{{if .Footer.On}}<footer class="claim-footer">{{with .Footer.TermsURL}}<p><a href="{{.}}" target="_blank" rel="noopener noreferrer">{{$.Copy.footerTerms}}</a></p>{{end}}{{with .Footer.Abuse}}<p>{{$.Copy.footerAbuse}}<a href="{{$.Footer.AbuseURL}}">{{.}}</a></p>{{end}}</footer>
+{{end}}</main>
<script src="{{asset "demo_claim.js"}}"></script>
</body>
</html>
diff --git a/internal/console/testdata/demo_claim_layout.mjs b/internal/console/testdata/demo_claim_layout.mjs
index 9fd2ec562..f6091c224 100644
--- a/internal/console/testdata/demo_claim_layout.mjs
+++ b/internal/console/testdata/demo_claim_layout.mjs
@@ -38,6 +38,15 @@ export async function captureClaim(call, evaluate, screenshots, state, widths =
const rect = link.getBoundingClientRect();
if (rect.left < 0 || rect.right > innerWidth || link.scrollWidth > link.clientWidth) problems.push('result address overflows');
}
+ const footer = document.querySelector('.claim-footer');
+ if (footer) {
+ const links = [...footer.querySelectorAll('a')];
+ if (links.length !== 2 || links[0].textContent !== 'Demo terms') problems.push('footer links missing');
+ for (const link of links) {
+ const rect = link.getBoundingClientRect();
+ if (rect.width <= 0 || rect.left < 0 || rect.right > innerWidth || link.scrollWidth > link.clientWidth) problems.push('footer link overflows');
+ }
+ }
const command = document.getElementById('claim-cli-command');
if (command) {
const rect = command.parentElement.getBoundingClientRect();
diff --git a/internal/edge/demo_assets/banner.css b/internal/edge/demo_assets/banner.css
index 129dab10c..e83e60155 100644
--- a/internal/edge/demo_assets/banner.css
+++ b/internal/edge/demo_assets/banner.css
@@ -77,3 +77,5 @@
#carlos-demo-warning .carlos-demo-left { grid-column: 2; grid-row: 2; white-space: normal; }
#carlos-demo-warning .carlos-demo-chevron { grid-column: 3; grid-row: 1 / 3; }
}
+
+#carlos-demo-warning a.carlos-demo-terms { display: inline-block; margin-inline-start: .75em; }
diff --git a/internal/edge/demo_banner.go b/internal/edge/demo_banner.go
index 81a873b74..b49183138 100644
--- a/internal/edge/demo_banner.go
+++ b/internal/edge/demo_banner.go
@@ -7,12 +7,14 @@ import (
"errors"
stdhtml "html"
"io"
+ "log"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
+ "unicode"
"golang.org/x/net/html"
)
@@ -24,7 +26,7 @@ const demoAssetPrefix = "/.carlos/demo/"
var demoBannerCSS string
// reportOrigin comes from edge configuration, never the request or app.
-func demoBannerMarkup(host, reportOrigin string, expiresAt int64) (string, error) {
+func demoBannerMarkup(host, reportOrigin, termsURL string, expiresAt int64) (string, error) {
origin, err := url.Parse(reportOrigin)
if err != nil || origin.Scheme != "https" || origin.Hostname() == "" || origin.User != nil || origin.Opaque != "" || origin.RawQuery != "" || origin.ForceQuery || origin.Fragment != "" || (origin.Path != "" && origin.Path != "/") || strings.ContainsAny(reportOrigin, "\\\r\n\t ") {
return "", errors.New("DEMO-RESPONSE")
@@ -40,13 +42,17 @@ func demoBannerMarkup(host, reportOrigin string, expiresAt int64) (string, error
remaining = ` <span class="carlos-demo-left">` + stdhtml.EscapeString(demoBannerCountdown(seconds)) + `</span>`
details = strings.ReplaceAll(demoUXCopy["BANNER-UX-02"], "{date}", demoNoticeDate(expiresAt))
}
- return `<link rel="stylesheet" href="/.carlos/demo/banner.css"><details id="carlos-demo-warning"><summary><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 4 2.8 19.5h18.4z M12 10v4 M12 17v.01"/></svg><span class="carlos-demo-line">` + stdhtml.EscapeString(summary) + `</span>` + remaining + `<span class="carlos-demo-chevron" aria-hidden="true"></span></summary><div class="carlos-demo-more"><p>` + stdhtml.EscapeString(details) + `</p><p>` + stdhtml.EscapeString(demoUXCopy["BANNER-UX-03"]) + ` <a href="` + stdhtml.EscapeString(origin.String()) + `" target="_blank" rel="noopener noreferrer">` + stdhtml.EscapeString(demoUXCopy["BANNER-UX-04"]) + `</a></p></div></details>`, nil
+ termsLink := ""
+ if validDemoTermsURL(termsURL) {
+ termsLink = ` <a class="carlos-demo-terms" href="` + stdhtml.EscapeString(termsURL) + `" target="_blank" rel="noopener noreferrer">` + stdhtml.EscapeString(demoUXCopy["BANNER-UX-07"]) + `</a>`
+ }
+ return `<link rel="stylesheet" href="/.carlos/demo/banner.css"><details id="carlos-demo-warning"><summary><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 4 2.8 19.5h18.4z M12 10v4 M12 17v.01"/></svg><span class="carlos-demo-line">` + stdhtml.EscapeString(summary) + `</span>` + remaining + `<span class="carlos-demo-chevron" aria-hidden="true"></span></summary><div class="carlos-demo-more"><p>` + stdhtml.EscapeString(details) + `</p><p>` + stdhtml.EscapeString(demoUXCopy["BANNER-UX-03"]) + ` <a href="` + stdhtml.EscapeString(origin.String()) + `" target="_blank" rel="noopener noreferrer">` + stdhtml.EscapeString(demoUXCopy["BANNER-UX-04"]) + `</a>` + termsLink + `</p></div></details>`, nil
}
// demoBannerReader buffers only the prefix. Tokenization finds real body tags
// without reserializing app markup or mistaking script/comment text for tags.
-func demoBannerReader(src io.Reader, host, reportOrigin string, expiresAt int64) (io.Reader, error) {
- markup, err := demoBannerMarkup(host, reportOrigin, expiresAt)
+func demoBannerReader(src io.Reader, host, reportOrigin, termsURL string, expiresAt int64) (io.Reader, error) {
+ markup, err := demoBannerMarkup(host, reportOrigin, termsURL, expiresAt)
if err != nil {
return nil, err
}
@@ -85,8 +91,8 @@ func demoBannerReader(src io.Reader, host, reportOrigin string, expiresAt int64)
return io.MultiReader(bytes.NewReader(b[:insert]), strings.NewReader(markup), bytes.NewReader(b[insert:]), src), nil
}
-func injectDemoBanner(dst io.Writer, src io.Reader, host, reportOrigin string, expiresAt int64) error {
- r, err := demoBannerReader(src, host, reportOrigin, expiresAt)
+func injectDemoBanner(dst io.Writer, src io.Reader, host, reportOrigin, termsURL string, expiresAt int64) error {
+ r, err := demoBannerReader(src, host, reportOrigin, termsURL, expiresAt)
if err != nil {
return err
}
@@ -125,8 +131,8 @@ func (e *Edge) serveDemoAsset(w http.ResponseWriter, r *http.Request) bool {
// Platform pages use the markup directly, outside the app transport. They
// must not pass through the app injector a second time.
-func serveDemoHTML(w http.ResponseWriter, r *http.Request, status int, copyID, host, reportOrigin string) {
- markup, err := demoBannerMarkup(host, reportOrigin, 0)
+func serveDemoHTML(w http.ResponseWriter, r *http.Request, status int, copyID, host, reportOrigin, termsURL string) {
+ markup, err := demoBannerMarkup(host, reportOrigin, termsURL, 0)
message, ok := demoCopy[copyID]
if err != nil || !ok {
serveDemoPlain(w, r, 503, "DEMO-UNAVAILABLE")
@@ -150,9 +156,9 @@ func serveDemoHTML(w http.ResponseWriter, r *http.Request, status int, copyID, h
// the final compressor negotiates the browser's encoding. It grants no
// serving authority and is not installed until Tasks 3/4 supply admission.
type demoBannerTransport struct {
- base http.RoundTripper
- host, reportOrigin string
- expiresAt int64
+ base http.RoundTripper
+ host, reportOrigin, termsURL string
+ expiresAt int64
}
func (t demoBannerTransport) RoundTrip(r *http.Request) (*http.Response, error) {
@@ -198,7 +204,7 @@ func (t demoBannerTransport) RoundTrip(r *http.Request) (*http.Response, error)
return demoBannerRefusal(resp), nil
}
}
- if err := transformDemoHTMLResponse(resp, t.host, t.reportOrigin, t.expiresAt); err != nil {
+ if err := transformDemoHTMLResponse(resp, t.host, t.reportOrigin, t.termsURL, t.expiresAt); err != nil {
return demoBannerRefusal(resp), nil
}
return resp, nil
@@ -226,7 +232,7 @@ func demoBannerRefusal(resp *http.Response) *http.Response {
return resp
}
-func transformDemoHTMLResponse(resp *http.Response, host, reportOrigin string, expiresAt int64) error {
+func transformDemoHTMLResponse(resp *http.Response, host, reportOrigin, termsURL string, expiresAt int64) error {
if resp.StatusCode == 204 || resp.StatusCode == 205 || resp.StatusCode == 304 {
return nil
}
@@ -277,7 +283,7 @@ func transformDemoHTMLResponse(resp *http.Response, host, reportOrigin string, e
default:
return errors.New("DEMO-RESPONSE")
}
- reader, err = demoBannerReader(reader, host, reportOrigin, expiresAt)
+ reader, err = demoBannerReader(reader, host, reportOrigin, termsURL, expiresAt)
if err != nil {
return err
}
@@ -319,3 +325,17 @@ func demoPassiveMediaType(mt string) bool {
func demoNoticeDate(expiresAt int64) string {
return time.Unix(expiresAt, 0).UTC().Format("Mon 2 Jan at 15:04 MST")
}
+
+func validDemoTermsURL(raw string) bool {
+ u, err := url.Parse(raw)
+ return err == nil && u.Scheme == "https" && u.Hostname() != "" && u.User == nil && u.Opaque == "" && !strings.Contains(raw, "\\") && strings.IndexFunc(raw, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) < 0
+}
+
+func demoTermsURLFromEnv(getenv func(string) string) string {
+ raw := getenv("CARLOS_DEMO_TERMS_URL")
+ if raw == "" || validDemoTermsURL(raw) {
+ return raw
+ }
+ log.Print("edge: invalid CARLOS_DEMO_TERMS_URL; ignoring")
+ return ""
+}
diff --git a/internal/edge/demo_banner_test.go b/internal/edge/demo_banner_test.go
index a7b389ade..7b99f07aa 100644
--- a/internal/edge/demo_banner_test.go
+++ b/internal/edge/demo_banner_test.go
@@ -28,10 +28,10 @@ func TestDemoBannerInsertion(t *testing.T) {
} {
t.Run(tt.name, func(t *testing.T) {
var out bytes.Buffer
- if err := injectDemoBanner(&out, strings.NewReader(tt.input), "shop.example.com", "https://console.example.com", 0); err != nil {
+ if err := injectDemoBanner(&out, strings.NewReader(tt.input), "shop.example.com", "https://console.example.com", "", 0); err != nil {
t.Fatal(err)
}
- markup, err := demoBannerMarkup("shop.example.com", "https://console.example.com", 0)
+ markup, err := demoBannerMarkup("shop.example.com", "https://console.example.com", "", 0)
if err != nil {
t.Fatal(err)
}
@@ -47,7 +47,7 @@ func TestDemoBannerInsertion(t *testing.T) {
t.Run("stream", func(t *testing.T) {
src := &demoRepeatingReader{left: 8 << 20}
dst := &demoStreamWitness{source: src}
- if err := injectDemoBanner(dst, io.MultiReader(strings.NewReader("<body>"), src), "shop.example.com", "https://console.example.com", 0); err != nil {
+ if err := injectDemoBanner(dst, io.MultiReader(strings.NewReader("<body>"), src), "shop.example.com", "https://console.example.com", "", 0); err != nil {
t.Fatal(err)
}
if !dst.beforeEOF || src.left != 0 || dst.n < 8<<20 {
@@ -55,12 +55,12 @@ func TestDemoBannerInsertion(t *testing.T) {
}
})
t.Run("reader-error", func(t *testing.T) {
- if err := injectDemoBanner(io.Discard, demoBrokenReader{}, "shop.example.com", "https://console.example.com", 0); err == nil {
+ if err := injectDemoBanner(io.Discard, demoBrokenReader{}, "shop.example.com", "https://console.example.com", "", 0); err == nil {
t.Fatal("read error lost")
}
})
t.Run("writer-error", func(t *testing.T) {
- if err := injectDemoBanner(demoBrokenWriter{}, strings.NewReader("<body>x"), "shop.example.com", "https://console.example.com", 0); err == nil {
+ if err := injectDemoBanner(demoBrokenWriter{}, strings.NewReader("<body>x"), "shop.example.com", "https://console.example.com", "", 0); err == nil {
t.Fatal("write error lost")
}
})
@@ -232,7 +232,7 @@ func TestDemoBannerRepresentations(t *testing.T) {
t.Run("platform", func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "https://shop.example.com/", nil)
- serveDemoHTML(w, r, 503, "DEMO-UNAVAILABLE", "shop.example.com", "https://console.example.com")
+ serveDemoHTML(w, r, 503, "DEMO-UNAVAILABLE", "shop.example.com", "https://console.example.com", "")
if w.Code != 503 || strings.Count(w.Body.String(), `id="carlos-demo-warning"`) != 1 || w.Header().Get("Content-Security-Policy") != demoCSP() {
t.Fatalf("platform response: %+v", w)
}
@@ -273,12 +273,12 @@ func TestDemoBannerAssets(t *testing.T) {
}
func TestDemoBannerReportURL(t *testing.T) {
- markup, err := demoBannerMarkup(`shop.example.com\"><script>`, "https://console.example.com", 0)
+ markup, err := demoBannerMarkup(`shop.example.com\"><script>`, "https://console.example.com", "", 0)
if err != nil || strings.Contains(markup, "<script>") || !strings.Contains(markup, "/demo/report?host=") || !strings.Contains(markup, `target="_blank" rel="noopener noreferrer"`) {
t.Fatalf("escaping/link: %s %v", markup, err)
}
for _, origin := range []string{"", "http://console.example.com", "https://user@console.example.com", "https://console.example.com/path", "https://console.example.com?token=private"} {
- if _, err := demoBannerMarkup("shop.example.com", origin, 0); err == nil {
+ if _, err := demoBannerMarkup("shop.example.com", origin, "", 0); err == nil {
t.Fatalf("bad origin accepted %q", origin)
}
}
@@ -396,7 +396,7 @@ func TestDemoBannerWireCompression(t *testing.T) {
func TestDemoBannerPrefixBound(t *testing.T) {
src := &demoBoundWitness{left: 2 << 20}
- if err := injectDemoBanner(src, src, "shop.example.com", "https://console.example.com", 0); err != nil {
+ if err := injectDemoBanner(src, src, "shop.example.com", "https://console.example.com", "", 0); err != nil {
t.Fatal(err)
}
if src.beforeWrite != demoBannerPrefixLimit || src.left != 0 {
@@ -492,7 +492,7 @@ type demoCloseWitness struct {
func (b *demoCloseWitness) Close() error { b.closed = true; return nil }
func TestDemoReportBannerDestination(t *testing.T) {
- markup, err := demoBannerMarkup("shop.example.com", "https://console.example.com/", 0)
+ markup, err := demoBannerMarkup("shop.example.com", "https://console.example.com/", "", 0)
if err != nil {
t.Fatal(err)
}
@@ -500,7 +500,7 @@ func TestDemoReportBannerDestination(t *testing.T) {
t.Fatalf("link %s", markup)
}
for _, origin := range []string{"", "http://console.example.com", "https://console.example.com/?token=secret", "https://console.example.com/#secret", "https://user:secret@console.example.com", "https://console.example.com/foreign", "https://console.example.com\\@example.com"} {
- if _, err := demoBannerMarkup("shop.example.com", origin, 0); err == nil {
+ if _, err := demoBannerMarkup("shop.example.com", origin, "", 0); err == nil {
t.Fatalf("unsafe origin %q", origin)
}
}
diff --git a/internal/edge/demo_copy.go b/internal/edge/demo_copy.go
index 97d3e1e39..5b369ead9 100644
--- a/internal/edge/demo_copy.go
+++ b/internal/edge/demo_copy.go
@@ -20,6 +20,7 @@ var demoUXCopy = map[string]string{
"BANNER-UX-03": "Don’t enter real passwords or personal details.",
"BANNER-UX-04": "Report abuse",
"BANNER-UX-05": "This app was built by an AI. It is temporary. Do not enter real passwords or sensitive information.",
+ "BANNER-UX-07": "Demo terms",
"BANNER-UX-06": "Made by an AI. Temporary. Don’t enter real passwords. {time}",
"MOVED-UX-01": "This app has moved",
"MOVED-UX-02": "{old address}",
diff --git a/internal/edge/demo_terms_test.go b/internal/edge/demo_terms_test.go
new file mode 100644
index 000000000..6bdfa80f3
--- /dev/null
+++ b/internal/edge/demo_terms_test.go
@@ -0,0 +1,98 @@
+package edge
+
+import (
+ "bytes"
+ "io"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func TestDemoBannerTerms(t *testing.T) {
+ baseline, err := os.ReadFile("testdata/demo_banner_without_terms.html")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct{ name, value, link string }{
+ {"unset", "", ""},
+ {"valid", "https://example.com/terms/demos/", `<a class="carlos-demo-terms" href="https://example.com/terms/demos/" target="_blank" rel="noopener noreferrer">Demo terms</a>`},
+ {"escaping", `https://example.com/terms?q="<yes>"&other='ok'`, `<a class="carlos-demo-terms" href="https://example.com/terms?q=&#34;&lt;yes&gt;&#34;&amp;other=&#39;ok&#39;" target="_blank" rel="noopener noreferrer">Demo terms</a>`},
+ {"http", "http://example.com/terms", ""},
+ {"relative", "/terms", ""},
+ {"protocol-relative", "//example.com/terms", ""},
+ {"javascript", "javascript:alert(1)", ""},
+ {"userinfo", "https://user:pass@example.com/terms", ""},
+ {"empty-userinfo", "https://@example.com/terms", ""},
+ {"hostless", "https:///terms", ""},
+ {"opaque", "https:example.com/terms", ""},
+ {"backslash", `https://example.com\@evil.example/terms`, ""},
+ {"whitespace", "https://example.com/terms x", ""},
+ {"newline", "https://example.com/\nterms", ""},
+ {"unicode-space", "https://example.com/\u00a0terms", ""},
+ {"bad-escape", "https://example.com/%zz", ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("CARLOS_DEMO_TERMS_URL", tc.value)
+ var logs bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&logs)
+ defer log.SetOutput(old)
+ reg, err := registry.Open(t.TempDir() + "/registry.db")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.link == "" && e.demoTermsURL != "" {
+ t.Fatalf("invalid URL accepted: %q", e.demoTermsURL)
+ }
+ markup, err := demoBannerMarkup("shop.example.com", "https://console.example.com", e.demoTermsURL, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.link == "" {
+ if markup != string(baseline) {
+ t.Fatal("unset/invalid terms changed banner bytes")
+ }
+ if tc.value != "" && strings.Count(logs.String(), "CARLOS_DEMO_TERMS_URL") != 1 {
+ t.Fatalf("expected one config warning: %s", logs.String())
+ }
+ } else if !strings.Contains(markup, tc.link) || !strings.Contains(markup, ">Report abuse</a>") {
+ t.Fatalf("missing links: %s", markup)
+ }
+ // Rendering does not trust a directly supplied invalid setting either.
+ direct, err := demoBannerMarkup("shop.example.com", "https://console.example.com", tc.value, 0)
+ if err != nil || direct != markup {
+ t.Fatalf("direct configuration differs: %v", err)
+ }
+ })
+ }
+}
+
+func TestDemoBannerTermsProxy(t *testing.T) {
+ e := &Edge{demoReportOrigin: "https://console.example.com", demoTermsURL: "https://example.com/terms"}
+ proxy := e.demoProxy(&httputil.ReverseProxy{Transport: demoBannerRoundTrip(func(r *http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/html"}}, Body: io.NopCloser(strings.NewReader("<body>app</body>"))}, nil
+ })}, registry.Route{Host: "shop.example.com"})
+ resp, err := proxy.Transport.RoundTrip(httptest.NewRequest("GET", "https://shop.example.com", nil))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(body), `href="https://example.com/terms"`) {
+ t.Fatal("terms URL lost in proxy wiring")
+ }
+}
diff --git a/internal/edge/demo_traffic.go b/internal/edge/demo_traffic.go
index 62b910a0e..d40a27667 100644
--- a/internal/edge/demo_traffic.go
+++ b/internal/edge/demo_traffic.go
@@ -562,7 +562,7 @@ func (e *Edge) demoProxy(p *httputil.ReverseProxy, rt registry.Route) *httputil.
base = http.DefaultTransport
}
if _, wrapped := base.(demoBannerTransport); !wrapped {
- cp.Transport = demoBannerTransport{base: base, host: rt.Host, reportOrigin: e.demoReportOrigin, expiresAt: rt.DemoExpiresAt}
+ cp.Transport = demoBannerTransport{base: base, host: rt.Host, reportOrigin: e.demoReportOrigin, termsURL: e.demoTermsURL, expiresAt: rt.DemoExpiresAt}
}
}
return &cp
diff --git a/internal/edge/demo_ux_browser_test.go b/internal/edge/demo_ux_browser_test.go
index b37320149..36739b683 100644
--- a/internal/edge/demo_ux_browser_test.go
+++ b/internal/edge/demo_ux_browser_test.go
@@ -28,7 +28,7 @@ func TestDemoUXBrowser(t *testing.T) {
if r.URL.Path == "/plain" || r.URL.Path == "/hostile-css" {
w = e.beginDemoResponse(w, r)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
- markup, err := demoBannerMarkup("shop.demos.example.com", "https://console.example.com", time.Now().Add(21*time.Hour).Unix())
+ markup, err := demoBannerMarkup("shop.demos.example.com", "https://console.example.com", "https://example.com/terms/demos/", time.Now().Add(21*time.Hour).Unix())
if err != nil {
t.Error(err)
return
@@ -80,6 +80,7 @@ func TestDemoUXBrowser(t *testing.T) {
cdp.call("Input.dispatchKeyEvent", map[string]any{"type": "keyDown", "text": "\r", "key": "Enter", "code": "Enter", "windowsVirtualKeyCode": 13})
cdp.call("Input.dispatchKeyEvent", map[string]any{"type": "keyUp", "key": "Enter", "code": "Enter", "windowsVirtualKeyCode": 13})
cdp.wait(`document.querySelector('#carlos-demo-warning').open===true`)
+ cdp.check(`(()=>{const b=document.querySelector('#carlos-demo-warning'),r=b.getBoundingClientRect(),links=[...b.querySelectorAll('a')];return links.length===2 && links[1].textContent==='Demo terms' && links.every(a=>{const x=a.getBoundingClientRect();return x.width>0 && x.left>=r.left && x.right<=r.right && x.bottom<=r.bottom && a.target==='_blank' && a.rel==='noopener noreferrer'})})()`)
cdp.check(`(()=>{const b=document.querySelector('#carlos-demo-warning'),r=b.getBoundingClientRect(),a=b.querySelector('a').getBoundingClientRect();return a.width>0 && a.left>=r.left && a.right<=r.right && a.bottom<=r.bottom && document.querySelector('main').getBoundingClientRect().top>=r.bottom})()`)
if page == "plain" {
demoUXScreenshot(t, cdp, fmt.Sprintf("banner-open-%d-%s-%s", width, theme, motion))
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index cdc4e3c40..452afc960 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -128,6 +128,7 @@ type Edge struct {
demoTrafficOnce sync.Once
demoBox string
demoReportOrigin string
+ demoTermsURL string
demoAPIAlias demoAPIAliasConfig
demo demo.Config
demoNames atomic.Pointer[map[string]bool] // includes marked routes refused by reload
@@ -624,7 +625,7 @@ func newEdge(reg *registry.Registry, act Activator, hold localHold) (*Edge, erro
if err != nil {
return nil, err
}
- e := &Edge{demoAPIAlias: demoAPI, demoReportOrigin: os.Getenv("CARLOS_DEMO_CONSOLE_URL"), demo: demoEdgeConfig(), reg: reg, act: act, hold: hold, gate: gate.New(), probers: newProberSet(hold), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
+ e := &Edge{demoAPIAlias: demoAPI, demoReportOrigin: os.Getenv("CARLOS_DEMO_CONSOLE_URL"), demoTermsURL: demoTermsURLFromEnv(os.Getenv), demo: demoEdgeConfig(), reg: reg, act: act, hold: hold, gate: gate.New(), probers: newProberSet(hold), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000),
planLimiter: ratelimit.NewLimiter(time.Now, 100_000), burst: newBurstLimiter(time.Now), notices: newBurstNotices(),
held: newHeldSet(DefaultHeldConfig)}
diff --git a/internal/edge/testdata/demo_banner_without_terms.html b/internal/edge/testdata/demo_banner_without_terms.html
new file mode 100644
index 000000000..64c70a076
--- /dev/null
+++ b/internal/edge/testdata/demo_banner_without_terms.html
@@ -0,0 +1 @@
+<link rel="stylesheet" href="/.carlos/demo/banner.css"><details id="carlos-demo-warning"><summary><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 4 2.8 19.5h18.4z M12 10v4 M12 17v.01"/></svg><span class="carlos-demo-line">Made by an AI. Temporary. Don’t enter real passwords.</span><span class="carlos-demo-chevron" aria-hidden="true"></span></summary><div class="carlos-demo-more"><p>This app was built by an AI. It is temporary. Do not enter real passwords or sensitive information.</p><p>Don’t enter real passwords or personal details. <a href="https://console.example.com/demo/report?host=shop.example.com" target="_blank" rel="noopener noreferrer">Report abuse</a></p></div></details>
\ No newline at end of file
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 58c6ca4d9..e54f43dca 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -160,3 +160,4 @@ plan14-root-reads-held-floor-capability.tsv b60c83f8ba4311222174284420b5327e9200
plan14-root-reads-litestream-unit-restart.tsv e650a3ceb286df4457850d74ded9229d94ed9932057ae5b45b1d6c3d0d843ce2
plan14-root-reads-health-check-no-redirects-845.tsv e650a3ceb286df4457850d74ded9229d94ed9932057ae5b45b1d6c3d0d843ce2
plan14-root-reads-retry-after-503.tsv eea13e9a0b04164ea3fc7f8258bd1ab0a613d1e23ffe0cd028bc85058576c248
+plan14-root-reads-demo-terms-links.tsv c8e2c7ed3850823a8e379d880738982772b870ad8549238cc02abce24c80eb93
diff --git a/internal/provision/testdata/plan14-root-reads-demo-terms-links.tsv b/internal/provision/testdata/plan14-root-reads-demo-terms-links.tsv
new file mode 100644
index 000000000..c9bbf14a6
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-demo-terms-links.tsv
@@ -0,0 +1,10 @@
+# Census overlay demo-terms-links, written by census-propose (#369). census-ruling-demo-terms-links, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-demo-terms-links.md.
+# 3 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy ca231b052f674fba9d0b4b82af150f48978f1c07664f654bd6d74b779c0190f1 internal/edge/demo_assets/banner.css external legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-2;basis=demo_assets/banner.css:1-31 is the fixed embedded warning layout, referenced by demo_banner.go:22 and served only under the reserved asset path at :91. No external imports, URLs, runtime path or app-selected content; stylesheet bytes are compiled into the edge.;rev3=census-ruling-claim-ux-edge;basis=Restyled the fixed embedded banner layout for a one-line summary with a no-script details element; still compiled-in bytes under the reserved asset path, no imports or URLs.;rev3=census-ruling-claim-countdown;basis=Arrange the warning and remaining time on two rows below 640px, keeping the icon and chevron beside them; no URLs, script, inline style or root inputs added.;rev3=census-ruling-demo-terms-links;basis=Add spacing and wrapping for the optional terms anchor in the compiled-in banner stylesheet; no URL, import, script or runtime read added. file:external@0 6dc1f5dcd04d6444ed50ddea52b6d7793da9358bef845b80d61b4caa9bb44d83
+@legacy f66b45ce13816f0f72e5b8753f8c46a731cd31db4d113b56934ee8a478c5ed8e internal/edge/demo_banner.go transformDemoHTMLResponse legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-2;basis=demo_banner.go:212-282 transforms the app HTTP response stream. The new ReadAll at :228 is bounded to 512 bytes of response Body for sniffing, not a filesystem read. HTML is streamed through the bounded-prefix injector; unsupported active types/charsets/encodings refuse and stale representation metadata is removed.;rev3=census-ruling-claim-ux-edge;basis=Passes the route's known demo expiry into the injected banner markup for the hours-left text; same bounded sniff and streaming injector, no new reads.;rev3=census-ruling-demo-terms-links;basis=Pass the configured terms URL through the existing bounded-prefix banner injector; no new reads, response policy and streaming behavior unchanged. file:ReadAll@710 53338a90d119d6baaf5d5f1d6344cf1b6810758f84eb02251a93e2e71371fa5c
+@legacy 302d65559b2992ed2002bd5df246382f92ccff6269d7326789d9f5cde0b9db8b internal/edge/demo_traffic.go Edge.demoProxy legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-2;basis=demo_traffic.go:537-558 reads the supplied Route.Host and IsForward to install resident banner or forwarding transports before reload wrappers. No new registry lookup; resident content is transformed once, forwarded representations remain unchanged.;rev3=census-ruling-claim-ux-edge;basis=Reads the existing registry field DemoExpiresAt (already used for serving admission) to give the banner its end time; display only, grants no serving authority.;rev3=census-ruling-demo-terms-links;basis=Pass the edge's optional terms URL into the resident demo banner transport; no new registry fields or reads, serving and forwarding authority unchanged. registry:DemoExpiresAt@738,registry:Host@658 194562803cadb0f1852400c1c94c7662c2684dc47e45aaa774762a4154fc6eba
+internal/edge/demo_assets/banner.css external legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-2;basis=demo_assets/banner.css:1-31 is the fixed embedded warning layout, referenced by demo_banner.go:22 and served only under the reserved asset path at :91. No external imports, URLs, runtime path or app-selected content; stylesheet bytes are compiled into the edge.;rev3=census-ruling-claim-ux-edge;basis=Restyled the fixed embedded banner layout for a one-line summary with a no-script details element; still compiled-in bytes under the reserved asset path, no imports or URLs.;rev3=census-ruling-claim-countdown;basis=Arrange the warning and remaining time on two rows below 640px, keeping the icon and chevron beside them; no URLs, script, inline style or root inputs added.;rev3=census-ruling-demo-terms-links;basis=Add spacing and wrapping for the optional terms anchor in the compiled-in banner stylesheet; no URL, import, script or runtime read added. file:external@0 6dc1f5dcd04d6444ed50ddea52b6d7793da9358bef845b80d61b4caa9bb44d83
+internal/edge/demo_banner.go transformDemoHTMLResponse legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-2;basis=demo_banner.go:212-282 transforms the app HTTP response stream. The new ReadAll at :228 is bounded to 512 bytes of response Body for sniffing, not a filesystem read. HTML is streamed through the bounded-prefix injector; unsupported active types/charsets/encodings refuse and stale representation metadata is removed.;rev3=census-ruling-claim-ux-edge;basis=Passes the route's known demo expiry into the injected banner markup for the hours-left text; same bounded sniff and streaming injector, no new reads.;rev3=census-ruling-demo-terms-links;basis=Pass the configured terms URL through the existing bounded-prefix banner injector; no new reads, response policy and streaming behavior unchanged. file:ReadAll@710 53338a90d119d6baaf5d5f1d6344cf1b6810758f84eb02251a93e2e71371fa5c
+internal/edge/demo_traffic.go Edge.demoProxy legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-2;basis=demo_traffic.go:537-558 reads the supplied Route.Host and IsForward to install resident banner or forwarding transports before reload wrappers. No new registry lookup; resident content is transformed once, forwarded representations remain unchanged.;rev3=census-ruling-claim-ux-edge;basis=Reads the existing registry field DemoExpiresAt (already used for serving admission) to give the banner its end time; display only, grants no serving authority.;rev3=census-ruling-demo-terms-links;basis=Pass the edge's optional terms URL into the resident demo banner transport; no new registry fields or reads, serving and forwarding authority unchanged. registry:DemoExpiresAt@738,registry:Host@658 194562803cadb0f1852400c1c94c7662c2684dc47e45aaa774762a4154fc6eba
+@coverage internal/edge 6cff8627251da60e6569e51e66bb370b0e499b5bdf3a69e2bd2172163c8415f5
+@coverage internal/edge/demo_assets 02967737050c919dc2edd83ba3d47f6beb03bb812832f73f457a2431da3cee33