carlos / platform Public

console: explain spent demo claim links

Preserve spent token hashes and retirement reasons atomically, retaining
minimal claim receipts through cleanup. Return specific unauthorized
reasons for browser intent, agent claim start, and demo updates using the
approved copy.

Cover each clearing path, refusal gate, migration, rollback, retention,
and expired-link Chromium behavior. Targeted Demo/Claim tests pass in
shards after serial timeouts; console vet and census checks pass.
codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev d1d84e19368d2a824a15214e8c06781929b9867b parent 35d551b
14 files changed, +528 −20
  • docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-CLAIM-SPENT-LINK.md +20 −0
  • docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-CLAIM-SPENT-LINK.md +6 −0
  • internal/console/apidemo.go +23 −1
  • internal/console/demo_claim_auth.go +5 −1
  • internal/console/demo_claim_copy.go +11 −0
  • internal/console/demo_claim_page.go +10 −1
  • internal/console/demo_claim_transfer.go +2 −2
  • internal/console/demo_expiry.go +5 −1
  • internal/console/demo_expiry_test.go +2 −3
  • internal/console/demo_spent_token_test.go +362 −0
  • internal/console/demo_store.go +52 −3
  • internal/console/static/demo_claim.js +18 −6
  • internal/console/templates/demo_claim.html +1 −1
  • internal/console/testdata/demo_claim_browser.mjs +11 −1

Intent

Human

<paseo-system version="1" kind="agent-message" source-agent-id="32157efb-ed29-443f-b428-8c9e3320fa50" message-id="fdacf727-ed20-4af4-8edf-db474a79d901"> From platform-f6: Paul (2026-11-07) saw a blank gap before the email prompt appeared when opening the claim link. That gap is demo_claim.js posting /demo/claim/intent and then location.replace(&quot;/demo/claim&quot;) reloading the page. Paul&apos;s rule: if there&apos;s a loading delay, show a loader, and show it for AT LEAST 650 ms (no flash of a spinner). Do it in the same follow-up as the expired/already-kept messages: - When the page has a claim token in the URL fragment, the very first paint shows a loading state (&quot;Opening your demo…&quot;, Luna to finalise) with an accessible spinner (role=status, aria-live polite, prefers-reduced-motion respected), not an empty page. Render it so it shows before any script work (e.g. the template&apos;s initial markup when JS is on, hidden for noscript), and the script keeps it until both the intent response and the reload are done, with a minimum on-screen time of 650 ms measured from when it first showed. - Apply the same rule to every wait on the claim page: after Continue (email), after the code, after &quot;Keep in …&quot; while the step-up and selection run, and the progress steps. - Keep the CSP posture (only the embedded script; no inline script or style beyond what the console layout already allows). Tests for the 650 ms minimum with a fake clock. Screenshot the loader in light and dark at 390 px. Send to this session when it&apos;s on dev. Don&apos;t redeploy while a claim is in flight (Paul may be claiming plucky-lotus-49). </paseo-system>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="32157efb-ed29-443f-b428-8c9e3320fa50" message-id="ec03c0a2-8556-4a5f-87b6-eb3d2b8c4add"> From platform-f6: Paul is claiming plucky-lotus-49 RIGHT NOW (his page shows the progress steps at &quot;1. Copying your data&quot;). This is the first real claim on a box. 0. Watch his claim operation now (demo_claim_ops phase, box journal, deadlines). If it stalls or fails, send this session the phase, the error and what Paul should do, within minutes. Do not redeploy anything while it is in flight. When it finishes, run verify.sh and send this session the result. 1. Paul had to sign in with Keymail TWICE. It must be once. Root-cause it from evidence (the stash/step-up rows and journal for his session): likely the browser sign-in is followed immediately by requireFreshAuth&apos;s step-up, which should accept an authentication that just happened in this same flow (recent auth_time from the sign-in itself) instead of sending him to Keymail again. Fix without weakening step-up anywhere else; Opus review (security gate). 2. Paul: the progress page &quot;needs to be much more magical and animated&quot;. Redesign it with the frontend-design / impeccable skills, as part of the claim page work: a lively, delightful sequence, not a plain numbered list. Ideas to weigh: the demo&apos;s own name and new address front and centre; smooth step transitions with an animated indicator per step; a sense of motion while data copies (real numbers if the status door can cheaply give them, e.g. size copied, otherwise honest indeterminate motion); a celebratory reveal of the new app&apos;s address at the end with a big &quot;Open your app&quot; button; all CSS animations from the console stylesheet (no inline script/style; CSP unchanged); prefers-reduced-motion gets a calm version; the 650 ms minimum for any loader still applies. Screenshots plus a short screen recording (light and dark, 390 px and desktop) to this session before it goes to dev. Luna for any new wording. Same branch discipline as before. </paseo-system>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="32157efb-ed29-443f-b428-8c9e3320fa50" message-id="595510c2-ce50-4df7-9cc0-97fc18b83e79"> From platform-f6: Paul&apos;s claim of plucky-lotus-49 COMPLETED (done page shows https://plucky-lotus-49.bac.dev.oncarlos.com). Run verify.sh now and send this session the result. Then: Paul wants the claim journey much more &apos;tada&apos;, and a UX mockup pass of the whole flow first. So PAUSE the visual work (progress redesign, loader look, done page look) until mockups are approved; keep going only on the functional fixes: (a) one Keymail sign-in, not two (root cause + fix + Opus review), (b) plain &apos;This demo has expired&apos; / &apos;already kept&apos; messages. The 650 ms loader rule will come back with the approved design. </paseo-system>

Attributed to this commit: 9.82 g CO₂e (989,348 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on demo-claim-spent-link, 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/docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-CLAIM-SPENT-LINK.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-CLAIM-SPENT-LINK.md
new file mode 100644
index 000000000..8e1584ce4
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-CLAIM-SPENT-LINK.md
@@ -0,0 +1,20 @@
+You are the copy-review gate itself for this set. Paul delegated copy review to you on 2026-10-25; your verdicts ARE the review. Do NOT run the copy-review skill or start any server. Do not edit any file. You are writing a review report into your final answer.
+
+Context: a person opens a private link to keep a temporary demo app that an AI agent built for them. Demos last 24 hours. These are the messages when the link can no longer be used. They show on a web page, and the same text goes back to the person's agent in a JSON error. Audience: a person, often not technical.
+
+Facts:
+- Expired: the demo's 24 hours ended and it is deleted. Nothing can be recovered. The next step is to ask their agent to build it again, which makes a new demo with a new link.
+- Already kept: someone already kept this demo as a permanent app in a console account. If it was them, it is in their console account. The link can't be used again.
+- Taken down: the platform operator removed it. Nothing can be recovered.
+- Unknown: the link is wrong or incomplete, for example cut off when copied. They should copy the whole link again from where their agent gave it.
+
+House rules: plain words, short sentences, no marketing tone, no exclamation marks, no em or en dashes used as dashes, sentence case, full stops on sentences. Do not name the product.
+
+Answer with one markdown table, `| key | new | why |`, `unchanged` in why if kept. Nothing else.
+
+| key | Draft |
+|---|---|
+| demoClaimExpired | This demo has expired. Its 24 hours ended and it has been deleted. Ask your agent to build it again for a new link. |
+| demoClaimAlreadyKept | This demo has already been kept as a permanent app. If you kept it, you will find it in your console account. |
+| demoClaimTakenDown | This demo was taken down and cannot be kept. |
+| demoClaimLinkBroken | This link does not work. Copy the whole link again from where your agent gave it to you. |
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-CLAIM-SPENT-LINK.md b/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-CLAIM-SPENT-LINK.md
new file mode 100644
index 000000000..dc7063f32
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-CLAIM-SPENT-LINK.md
@@ -0,0 +1,6 @@
+| key | new | why |
+|---|---|---|
+| demoClaimExpired | This demo has expired and been deleted. Nothing can be recovered. Ask your agent to build it again. The new demo will have a new link. | Says what happened and gives the next step. |
+| demoClaimAlreadyKept | Someone has already kept this demo as a permanent app. If that was you, you can find it in your console account. This link can no longer be used. | Clarifies that someone else may have kept it and the link is no longer usable. |
+| demoClaimTakenDown | The platform operator took down this demo. Nothing can be recovered. | Says who removed it and makes clear it cannot be recovered. |
+| demoClaimLinkBroken | This link is wrong or incomplete. Copy the whole link again from where your agent gave it to you. | Names likely causes and keeps the instruction clear. |
\ No newline at end of file
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go
index ccd8efee2..2447d9547 100644
--- a/internal/console/apidemo.go
+++ b/internal/console/apidemo.go
@@ -291,6 +291,28 @@ func (s *Server) registerDemoRoutes() {
s.registerRoute("POST /demo/claim/prove", s.handleDemoClaimBrowserProof)
s.registerRoute("POST /demo/claim/select", s.handleDemoClaimBrowserSelect)
}
+func demoTokenRefusal(err error) (reason, message string) {
+ switch {
+ case errors.Is(err, ErrDemoExpired):
+ return "expired", demoClaimExpired
+ case errors.Is(err, ErrDemoKept):
+ return "kept", demoClaimAlreadyKept
+ case errors.Is(err, ErrDemoTakenDown):
+ return "taken-down", demoClaimTakenDown
+ default:
+ return "invalid", demoClaimLinkBroken
+ }
+}
+
+func demoTokenError(w http.ResponseWriter, err error) {
+ if !errors.Is(err, ErrDemoToken) {
+ demoError(w, err)
+ return
+ }
+ reason, message := demoTokenRefusal(err)
+ demoClaimReply(w, http.StatusUnauthorized, map[string]string{"error": message, "reason": reason})
+}
+
func demoError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, ErrDemoCreateLimit):
@@ -356,7 +378,7 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) {
}
row, lookupErr := s.store.LookupDemoToken(r.Context(), parts[1])
if lookupErr != nil {
- demoError(w, lookupErr)
+ demoTokenError(w, lookupErr)
return
}
if row.ActiveJobID != "" {
diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go
index 95b2a58e1..7cbc31008 100644
--- a/internal/console/demo_claim_auth.go
+++ b/internal/console/demo_claim_auth.go
@@ -142,7 +142,11 @@ func (s *Server) handleDemoClaimStart(w http.ResponseWriter, r *http.Request) {
}
d, err := s.store.LookupDemoToken(r.Context(), fields["claimToken"])
if err != nil {
- demoError(w, ErrDemoToken)
+ if errors.Is(err, ErrDemoToken) {
+ demoTokenError(w, err)
+ } else {
+ demoError(w, ErrDemoToken)
+ }
return
}
now := time.Now()
diff --git a/internal/console/demo_claim_copy.go b/internal/console/demo_claim_copy.go
index 5dfe6db9e..af9b54c53 100644
--- a/internal/console/demo_claim_copy.go
+++ b/internal/console/demo_claim_copy.go
@@ -129,3 +129,14 @@ const (
// CLAIM-OLD-ADDRESS: notice lifetime, without a redirect promise.
demoClaimOldAddress = "The old address shows a short notice with a link to this app until the demo's original 24 hours end."
)
+
+const (
+ // CLAIM-LINK-EXPIRED
+ demoClaimExpired = "This demo has expired and been deleted. Nothing can be recovered. Ask your agent to build it again. The new demo will have a new link."
+ // CLAIM-LINK-KEPT
+ demoClaimAlreadyKept = "Someone has already kept this demo as a permanent app. If that was you, you can find it in your console account. This link can no longer be used."
+ // CLAIM-LINK-TAKEN-DOWN
+ demoClaimTakenDown = "The platform operator took down this demo. Nothing can be recovered."
+ // CLAIM-LINK-BROKEN
+ demoClaimLinkBroken = "This link is wrong or incomplete. Copy the whole link again from where your agent gave it to you."
+)
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index af2b13b1f..1ae9a883e 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -271,7 +271,12 @@ func (s *Server) handleDemoClaimBrowserIntent(w http.ResponseWriter, r *http.Req
}
d, err := s.store.LookupDemoToken(r.Context(), r.PostForm.Get("claimToken"))
if err != nil {
- demoError(w, ErrDemoToken)
+ if errors.Is(err, ErrDemoToken) {
+ reason, _ := demoTokenRefusal(err)
+ demoClaimReply(w, http.StatusUnauthorized, map[string]string{"reason": reason})
+ } else {
+ demoError(w, ErrDemoToken)
+ }
return
}
if !s.limits.submit(s.clientIP(r)) {
@@ -525,6 +530,10 @@ func (s *Server) demoClaimSessionIdentity(raw, person string) (string, string, b
func demoClaimBrowserCopy() map[string]string {
return map[string]string{
+ "expired": demoClaimExpired,
+ "kept": demoClaimAlreadyKept,
+ "takenDown": demoClaimTakenDown,
+ "invalid": demoClaimLinkBroken,
"unavailableAccounts": demoClaimUnavailableAccounts,
"saved": demoClaimSaved,
"oldAddress": demoClaimOldAddress,
diff --git a/internal/console/demo_claim_transfer.go b/internal/console/demo_claim_transfer.go
index e8d4074b0..f4640f8f5 100644
--- a/internal/console/demo_claim_transfer.go
+++ b/internal/console/demo_claim_transfer.go
@@ -677,7 +677,7 @@ func (s *Server) commitDemoClaim(ctx context.Context, op claimOp) error {
}{
{`INSERT INTO demo_claim_commits(operation_id,demo_id,committed_at) VALUES(?,?,?)`, []any{op.ID, op.DemoID, time.Now().Unix()}},
{`UPDATE demo_claim_ops SET phase='committed' WHERE id=?`, []any{op.ID}},
- {`UPDATE demo_apps SET claim_token_hash=NULL WHERE demo_id=?`, []any{op.DemoID}},
+ {`UPDATE demo_apps SET spent_token_hash=claim_token_hash,claim_token_hash=NULL WHERE demo_id=?`, []any{op.DemoID}},
{`DELETE FROM demo_claim_flows WHERE demo_id=?`, []any{op.DemoID}},
{`INSERT INTO demo_moved_notices(demo_id,host,target_host,expires_at) VALUES(?,?,?,?)`, []any{op.DemoID, d.Host, op.Target.Host, op.SourceExpiresAt}},
{`INSERT INTO demo_claim_outbox(operation_id,step) VALUES(?,'open'),(?,'moved'),(?,'retire')`, []any{op.ID, op.ID, op.ID}},
@@ -1080,7 +1080,7 @@ func (s *Server) pruneDemoClaims(ctx context.Context, now time.Time) error {
{`UPDATE demo_claim_ops SET flow_hash='' WHERE source_expires_at<=? AND flow_hash!=''`, now.Add(-24 * time.Hour).Unix()},
{`DELETE FROM demo_claim_flows WHERE hash NOT IN (SELECT flow_hash FROM demo_claim_ops WHERE flow_hash!='') AND expires_at<=?`, now.Unix()},
{`DELETE FROM demo_claim_progress WHERE operation_id IN (SELECT o.id FROM demo_claim_ops o JOIN demo_apps d ON d.demo_id=o.demo_id WHERE o.phase IN ('done','aborted') AND d.purged_at>0 AND d.purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()},
- {`DELETE FROM demo_claim_commits WHERE operation_id IN (SELECT o.id FROM demo_claim_ops o JOIN demo_apps d ON d.demo_id=o.demo_id WHERE o.phase IN ('done','aborted') AND d.purged_at>0 AND d.purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()},
+ {`DELETE FROM demo_claim_commits WHERE NOT EXISTS(SELECT 1 FROM demo_apps d WHERE d.demo_id=demo_claim_commits.demo_id AND d.spent_token_hash IS NOT NULL) AND operation_id IN (SELECT o.id FROM demo_claim_ops o JOIN demo_apps d ON d.demo_id=o.demo_id WHERE o.phase IN ('done','aborted') AND d.purged_at>0 AND d.purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()},
{`DELETE FROM demo_claim_ops WHERE phase IN ('done','aborted') AND demo_id IN (SELECT demo_id FROM demo_apps WHERE purged_at>0 AND purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()},
} {
if _, err = tx.ExecContext(ctx, q.sql, q.arg); err != nil {
diff --git a/internal/console/demo_expiry.go b/internal/console/demo_expiry.go
index 3cc77f116..18522e24f 100644
--- a/internal/console/demo_expiry.go
+++ b/internal/console/demo_expiry.go
@@ -210,7 +210,11 @@ func (s *Server) retireDemoLocked(ctx context.Context, d DemoRow, now time.Time,
if _, err = tx.ExecContext(ctx, `INSERT INTO demo_retirements(demo_id,wire,acknowledged,initialized_clean,fenced_at) VALUES(?,?,?,?,?)`, d.ID, r.Wire, d.AssignedBox == "", d.AssignedBox == "", r.FencedAt); err != nil {
return err
}
- if _, err = tx.ExecContext(ctx, `UPDATE demo_apps SET state='retiring',generation=generation+1,claim_token_hash=NULL,active_job_id='' WHERE demo_id=? AND state='anonymous'`, d.ID); err != nil {
+ spentReason := reason
+ if reason == "claimed" {
+ spentReason = ""
+ }
+ if _, err = tx.ExecContext(ctx, `UPDATE demo_apps SET state='retiring',generation=generation+1,spent_token_hash=coalesce(spent_token_hash,claim_token_hash),spent_reason=CASE WHEN spent_token_hash IS NULL THEN ? ELSE spent_reason END,claim_token_hash=NULL,active_job_id='' WHERE demo_id=? AND state='anonymous'`, spentReason, d.ID); err != nil {
return err
}
if _, err = tx.ExecContext(ctx, `UPDATE demo_jobs SET state='failed',publish_stage='retired' WHERE demo_id=?`, d.ID); err != nil {
diff --git a/internal/console/demo_expiry_test.go b/internal/console/demo_expiry_test.go
index d702f189c..335c6b099 100644
--- a/internal/console/demo_expiry_test.go
+++ b/internal/console/demo_expiry_test.go
@@ -3,7 +3,6 @@ package console
import (
"bytes"
"context"
- "database/sql"
"errors"
"net/http/httptest"
"strings"
@@ -126,8 +125,8 @@ func TestDemoPurgeRecovery(t *testing.T) {
if err = s.store.WipeDemoAbuse(t.Context(), now.Add(8*24*time.Hour)); err != nil {
t.Fatal(err)
}
- if _, err = s.store.demoByID(t.Context(), d.ID); !errors.Is(err, sql.ErrNoRows) {
- t.Fatalf("history retained: %v", err)
+ if row, err := s.store.demoByID(t.Context(), d.ID); err != nil || row.CreatingIP != "" || row.Client != "" || row.PurgedAt == 0 {
+ t.Fatalf("spent tombstone lost or abuse history retained: %+v %v", row, err)
}
in := demoTestAdmission(t, s.cfg.Demo)
in.AccountSqid = d.AccountSqid
diff --git a/internal/console/demo_spent_token_test.go b/internal/console/demo_spent_token_test.go
new file mode 100644
index 000000000..71272da28
--- /dev/null
+++ b/internal/console/demo_spent_token_test.go
@@ -0,0 +1,362 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestDemoSpentTokenSurfaces(t *testing.T) {
+ for _, state := range []string{"expired", "expired-live", "kept", "taken-down", "invalid", "malformed"} {
+ t.Run(state, func(t *testing.T) {
+ s, m, token := claimTestServer(t)
+ d, err := s.store.LookupDemoToken(t.Context(), token)
+ if err != nil {
+ t.Fatal(err)
+ }
+ flow, w := claimStart(t, s, token, "spent@example.com", "")
+ if w.Code != 202 {
+ t.Fatalf("start: %d %s", w.Code, w.Body)
+ }
+ code, _ := claimMail(t, s, m)
+ selectionToken, err := randomToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ life, err := s.store.AppLife(d.AccountID, d.App)
+ if err != nil {
+ t.Fatal(err)
+ }
+ selection, err := s.store.createDemoClaimFlow(t.Context(), selectionToken, "select@example.com", d, *life, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ selection, err = s.proveDemoClaim(t.Context(), selection, MethodEmail, selection.Address, "192.0.2.10", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ acct := claimAccount(t, s, 501, selection.Person, RoleOwner)
+ reason := state
+ switch state {
+ case "expired", "taken-down":
+ retirement := "operator"
+ now := time.Now()
+ if state == "expired" {
+ retirement = "expired"
+ now = time.Unix(d.CreatedAt+86400, 0)
+ }
+ if err := s.retireDemoLocked(t.Context(), d, now, retirement); err != nil {
+ t.Fatal(err)
+ }
+ case "expired-live":
+ reason = "expired"
+ if _, err := s.store.db.Exec(`UPDATE apps SET expires_at=1 WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ case "kept":
+ if _, err := s.store.db.Exec(`INSERT INTO demo_claim_commits(operation_id,demo_id,committed_at) VALUES('test',?,?); UPDATE demo_apps SET spent_token_hash=claim_token_hash,claim_token_hash=NULL WHERE demo_id=?`, d.ID, time.Now().Unix(), d.ID); err != nil {
+ t.Fatal(err)
+ }
+ case "invalid":
+ if token[0] == 'A' {
+ token = "B" + token[1:]
+ } else {
+ token = "A" + token[1:]
+ }
+ case "malformed":
+ reason = "invalid"
+ token += "="
+ }
+ row, err := s.store.LookupDemoToken(t.Context(), token)
+ typed := map[string]error{"expired": ErrDemoExpired, "kept": ErrDemoKept, "taken-down": ErrDemoTakenDown, "invalid": ErrDemoToken}
+ if !errors.Is(err, typed[reason]) {
+ t.Errorf("wrong typed error: %v", err)
+ }
+ if !errors.Is(err, ErrDemoToken) || row != (DemoRow{}) {
+ t.Fatalf("lookup authorized: %+v %v", row, err)
+ }
+ check := func(surface string, w *httptest.ResponseRecorder) {
+ t.Helper()
+ var got map[string]string
+ if w.Code != 401 || json.Unmarshal(w.Body.Bytes(), &got) != nil || got["reason"] != reason {
+ t.Errorf("%s: %d %s; want %s", surface, w.Code, w.Body, reason)
+ return
+ }
+ if surface == "intent" {
+ if len(got) != 1 {
+ t.Errorf("intent exposed more than reason: %v", got)
+ }
+ } else {
+ messages := map[string]string{"expired": demoClaimExpired, "kept": demoClaimAlreadyKept, "taken-down": demoClaimTakenDown, "invalid": demoClaimLinkBroken}
+ if got["error"] != messages[reason] {
+ t.Errorf("%s message: %q", surface, got["error"])
+ }
+ }
+ }
+ b := &claimBrowser{t: t, s: s}
+ b.request("GET", "/demo/claim", nil)
+ check("intent", b.post("/demo/claim/intent", url.Values{"claimToken": {token}}))
+ _, w = claimStart(t, s, token, "other@example.com", "")
+ check("start", w)
+ check("update", demoRequest(s, "Bearer "+token, "192.0.2.10").ResponseRecorder)
+ if state != "invalid" && state != "malformed" {
+ if w := claimVerify(s, flow, code); w.Code < 400 {
+ t.Fatalf("old flow verified: %d", w.Code)
+ }
+ if _, err := s.store.demoClaimFlow(t.Context(), flow, time.Now()); !errors.Is(err, ErrDemoToken) {
+ t.Fatalf("old flow accepted: %v", err)
+ }
+ if w := claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": selectionToken, "accountId": acct.Sqid}); w.Code != 401 {
+ t.Fatalf("old proved flow selected: %d %s", w.Code, w.Body)
+ }
+ if state != "kept" {
+ if err := s.store.SpendDemoUpdate(t.Context(), d.ID, time.Now()); !errors.Is(err, ErrDemoToken) {
+ t.Fatalf("update gate accepted: %v", err)
+ }
+ }
+ }
+ if w := claimVerify(s, token, code); w.Code != 401 {
+ t.Fatalf("spent token authorized verify: %d %s", w.Code, w.Body)
+ }
+ if w := claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": token, "accountId": acct.Sqid}); w.Code != 401 {
+ t.Fatalf("spent token authorized select: %d %s", w.Code, w.Body)
+ }
+ r := httptest.NewRequest("GET", "/api/demo/claims/status", nil)
+ r.Header.Set("Authorization", "Bearer "+token)
+ status := httptest.NewRecorder()
+ s.mux.ServeHTTP(status, r)
+ if status.Code != 401 {
+ t.Fatalf("spent token authorized status: %d", status.Code)
+ }
+ })
+ }
+}
+
+func TestDemoSpentTokenClearingPaths(t *testing.T) {
+ for _, reason := range []string{"expired", "operator", "claimed"} {
+ t.Run(reason, func(t *testing.T) {
+ var s *Server
+ var d DemoRow
+ var token string
+ if reason == "claimed" {
+ server, op, data := claimTransferFixture(t)
+ s = server
+ d, _ = s.store.demoByID(t.Context(), op.DemoID)
+ token, _ = randomToken()
+ raw, _ := base64.RawURLEncoding.DecodeString(token)
+ hash := sha256.Sum256(raw)
+ if _, err := s.store.db.Exec(`UPDATE demo_apps SET claim_token_hash=? WHERE demo_id=?`, hash[:], d.ID); err != nil {
+ t.Fatal(err)
+ }
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ } else {
+ s, _, token = claimTestServer(t)
+ d, _ = s.store.LookupDemoToken(t.Context(), token)
+ now := time.Now()
+ if reason == "expired" {
+ now = time.Unix(d.CreatedAt+86400, 0)
+ }
+ if err := s.retireDemoLocked(t.Context(), d, now, reason); err != nil {
+ t.Fatal(err)
+ }
+ }
+ raw, _ := base64.RawURLEncoding.DecodeString(token)
+ hash := sha256.Sum256(raw)
+ check := func() {
+ t.Helper()
+ var live, spent []byte
+ if err := s.store.db.QueryRow(`SELECT claim_token_hash,spent_token_hash FROM demo_apps WHERE demo_id=?`, d.ID).Scan(&live, &spent); err != nil {
+ t.Fatal(err)
+ }
+ if len(live) != 0 || !bytes.Equal(spent, hash[:]) {
+ t.Fatal("spent hash lost or live token retained")
+ }
+ want := map[string]error{"expired": ErrDemoExpired, "operator": ErrDemoTakenDown, "claimed": ErrDemoKept}[reason]
+ if _, err := s.store.LookupDemoToken(t.Context(), token); !errors.Is(err, want) || !errors.Is(err, ErrDemoToken) {
+ t.Fatalf("spent token reason lost: %v", err)
+ }
+ }
+ check()
+ if reason == "claimed" {
+ retirement, err := s.demoRetirement(t.Context(), d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = s.completeDemoRetirement(t.Context(), d.Fleet+"/"+d.AssignedBox, retirement.Wire); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.retireDemoLocked(t.Context(), d, time.Now().Add(48*time.Hour), reason); err != nil {
+ t.Fatal(err)
+ }
+ check()
+ purged, err := s.store.demoByID(t.Context(), d.ID)
+ if err != nil || purged.PurgedAt == 0 {
+ t.Fatalf("purge did not complete: %+v %v", purged, err)
+ }
+ future := time.Now().Add(30 * 24 * time.Hour)
+ if err := s.pruneDemoClaims(t.Context(), future); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.store.WipeDemoAbuse(t.Context(), future); err != nil {
+ t.Fatal(err)
+ }
+ check()
+ retained, err := s.store.demoByID(t.Context(), d.ID)
+ if err != nil || retained.CreatingIP != "" || retained.Client != "" || retained.SourceSHA256 != ([32]byte{}) {
+ t.Fatalf("abuse metadata retained: %+v %v", retained, err)
+ }
+ if reason == "claimed" {
+ var commits, ops int
+ if err := s.store.db.QueryRow(`SELECT (SELECT count(*) FROM demo_claim_commits WHERE demo_id=?),(SELECT count(*) FROM demo_claim_ops WHERE demo_id=?)`, d.ID, d.ID).Scan(&commits, &ops); err != nil || commits != 1 || ops != 0 {
+ t.Fatalf("durable commit or operation pruning: commits=%d ops=%d %v", commits, ops, err)
+ }
+ }
+ })
+ }
+}
+
+func TestDemoSpentTokenMigration(t *testing.T) {
+ st, _ := demoTestStore(t)
+ // Recreate the pre-migration shape while retaining an admitted demo.
+ in := demoTestAdmission(t, demoTestConfig(t))
+ if _, err := st.ReserveDemo(t.Context(), in); err != nil {
+ t.Fatal(err)
+ }
+ for _, q := range []string{`DROP INDEX IF EXISTS demo_apps_spent_token`, `ALTER TABLE demo_apps DROP COLUMN spent_token_hash`, `ALTER TABLE demo_apps DROP COLUMN spent_reason`} {
+ if _, err := st.db.Exec(q); err != nil && !strings.Contains(err.Error(), "no such column") {
+ t.Fatal(err)
+ }
+ }
+ for i := 0; i < 2; i++ {
+ if err := st.migrateDemo(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var live, spent []byte
+ var reason string
+ if err := st.db.QueryRow(`SELECT claim_token_hash,spent_token_hash,spent_reason FROM demo_apps WHERE demo_id=?`, in.Identity.ID).Scan(&live, &spent, &reason); err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(live, in.Identity.TokenHash[:]) || spent != nil || reason != "" {
+ t.Fatal("migration changed live credential")
+ }
+ if _, err := st.LookupDemoToken(t.Context(), in.Identity.Token); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDemoSpentTokenBrowserHeadless(t *testing.T) {
+ chromium, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("no installed Chromium")
+ }
+ node, err := exec.LookPath("node")
+ if err != nil {
+ t.Skip("no installed node")
+ }
+ s, _, token := claimTestServer(t)
+ d, err := s.store.LookupDemoToken(t.Context(), token)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = s.retireDemoLocked(t.Context(), d, time.Unix(d.CreatedAt+86400, 0), "expired"); err != nil {
+ t.Fatal(err)
+ }
+ s.registerRoute("GET /static/{hash}/{file...}", s.handleStatic)
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.Contains(r.URL.String(), token) || strings.Contains(r.Header.Get("Referer"), token) {
+ t.Error("token leaked in URL or referrer")
+ }
+ s.mux.ServeHTTP(w, r)
+ }))
+ defer ts.Close()
+ s.cfg.Origin = ts.URL
+ ctx, cancel := context.WithTimeout(t.Context(), 40*time.Second)
+ defer cancel()
+ expected := "This demo has expired and been deleted. Nothing can be recovered. Ask your agent to build it again. The new demo will have a new link."
+ cmd := exec.CommandContext(ctx, node, "testdata/demo_claim_browser.mjs", chromium, t.TempDir(), ts.URL+"/demo/claim#"+token, "", expected)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("headless: %v %s", err, output)
+ }
+ t.Log(strings.TrimSpace(string(output)))
+}
+
+func TestDemoSpentTokenDecode(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ d, err := s.store.LookupDemoToken(t.Context(), token)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = s.retireDemoLocked(t.Context(), d, time.Now(), "operator"); err != nil {
+ t.Fatal(err)
+ }
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
+ noncanonical := token[:42] + string(alphabet[strings.IndexByte(alphabet, token[42])|1])
+ for _, bad := range []string{"", token + "=", token[:42], "!" + token[1:], noncanonical, base64.RawURLEncoding.EncodeToString(make([]byte, 33)), d.ID, d.Name, d.Host} {
+ row, err := s.store.LookupDemoToken(t.Context(), bad)
+ if err != ErrDemoToken || row != (DemoRow{}) {
+ t.Errorf("malformed or non-token lookup: %+v %v", row, err)
+ }
+ }
+}
+
+func TestDemoSpentTokenAtomicClearing(t *testing.T) {
+ for _, reason := range []string{"expired", "operator", "claimed"} {
+ t.Run(reason, func(t *testing.T) {
+ var s *Server
+ var d DemoRow
+ var clear func() error
+ if reason == "claimed" {
+ server, op, data := claimTransferFixture(t)
+ s = server
+ d, _ = s.store.demoByID(t.Context(), op.DemoID)
+ claimToVerify(t, s, op, data)
+ if _, err := s.store.db.Exec(`CREATE TRIGGER fail_after_spend BEFORE INSERT ON demo_claim_outbox BEGIN SELECT RAISE(ABORT,'injected'); END`); err != nil {
+ t.Fatal(err)
+ }
+ clear = func() error { return s.advanceDemoClaim(t.Context(), op.ID) }
+ } else {
+ server, _, token := claimTestServer(t)
+ s = server
+ d, _ = s.store.LookupDemoToken(t.Context(), token)
+ if _, err := s.store.db.Exec(`CREATE TRIGGER fail_after_spend BEFORE UPDATE ON demo_serving BEGIN SELECT RAISE(ABORT,'injected'); END`); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if reason == "expired" {
+ now = time.Unix(d.CreatedAt+86400, 0)
+ }
+ clear = func() error { return s.retireDemoLocked(t.Context(), d, now, reason) }
+ }
+ var before []byte
+ if err := s.store.db.QueryRow(`SELECT claim_token_hash FROM demo_apps WHERE demo_id=?`, d.ID).Scan(&before); err != nil {
+ t.Fatal(err)
+ }
+ if err := clear(); err == nil {
+ t.Fatal("missing injected failure")
+ }
+ var live, spent []byte
+ var spentReason string
+ var receipts int
+ if err := s.store.db.QueryRow(`SELECT claim_token_hash,spent_token_hash,spent_reason,(SELECT count(*) FROM demo_claim_commits WHERE demo_id=d.demo_id) FROM demo_apps d WHERE demo_id=?`, d.ID).Scan(&live, &spent, &spentReason, &receipts); err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(live, before) || len(spent) != 0 || spentReason != "" || receipts != 0 {
+ t.Fatal("partial credential spend survived rollback")
+ }
+ })
+ }
+}
diff --git a/internal/console/demo_store.go b/internal/console/demo_store.go
index 5c0761316..75b157f1e 100644
--- a/internal/console/demo_store.go
+++ b/internal/console/demo_store.go
@@ -9,6 +9,7 @@ import (
"database/sql"
"encoding/base64"
"errors"
+ "fmt"
"strings"
"time"
@@ -19,6 +20,9 @@ var (
ErrDemoCreateLimit = errors.New("demo: create budget exhausted")
ErrDemoLiveLimit = errors.New("demo: live ceiling reached")
ErrDemoToken = errors.New("demo: unavailable credential")
+ ErrDemoExpired = fmt.Errorf("%w: expired", ErrDemoToken)
+ ErrDemoKept = fmt.Errorf("%w: kept", ErrDemoToken)
+ ErrDemoTakenDown = fmt.Errorf("%w: taken down", ErrDemoToken)
ErrDemoUpdateLimit = errors.New("demo: update budget exhausted")
ErrDemoBusy = errors.New("demo: job already active")
ErrDemoNameTaken = errors.New("demo: name already reserved")
@@ -72,6 +76,17 @@ CREATE TABLE IF NOT EXISTS demo_retirements(demo_id TEXT PRIMARY KEY, wire BLOB
if err != nil {
return err
}
+ for _, stmt := range []string{
+ `ALTER TABLE demo_apps ADD COLUMN spent_token_hash BLOB CHECK(spent_token_hash IS NULL OR length(spent_token_hash)=32)`,
+ `ALTER TABLE demo_apps ADD COLUMN spent_reason TEXT NOT NULL DEFAULT '' CHECK(spent_reason IN ('','expired','operator'))`,
+ } {
+ if _, err := s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ return err
+ }
+ }
+ if _, err := s.db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS demo_apps_spent_token ON demo_apps(spent_token_hash)`); err != nil {
+ return err
+ }
salt := make([]byte, 32)
if _, err := rand.Read(salt); err != nil {
return err
@@ -321,7 +336,7 @@ func (s *Store) LookupDemoToken(ctx context.Context, token string) (DemoRow, err
var stored []byte
err = s.db.QueryRowContext(ctx, `SELECT demo_id,claim_token_hash FROM demo_apps WHERE claim_token_hash=?`, hash[:]).Scan(&id, &stored)
if errors.Is(err, sql.ErrNoRows) {
- return DemoRow{}, ErrDemoToken
+ return DemoRow{}, s.spentDemoTokenError(ctx, hash[:])
}
if err != nil {
return DemoRow{}, err
@@ -338,10 +353,44 @@ func (s *Store) LookupDemoToken(ctx context.Context, token string) (DemoRow, err
return DemoRow{}, err
}
if !demoLifeValid(row, life, time.Now()) {
+ if row.State == "anonymous" && life != nil && life.DemoID == row.ID && life.ExpiresAt > 0 && life.ExpiresAt <= time.Now().Unix() {
+ return DemoRow{}, ErrDemoExpired
+ }
return DemoRow{}, ErrDemoToken
}
return row, nil
}
+
+// Spent hashes explain a refusal only; this path never returns a demo row.
+func (s *Store) spentDemoTokenError(ctx context.Context, hash []byte) error {
+ var stored []byte
+ var reason string
+ var committed bool
+ err := s.db.QueryRowContext(ctx, `SELECT spent_token_hash,spent_reason,
+ EXISTS(SELECT 1 FROM demo_claim_commits c WHERE c.demo_id=d.demo_id)
+ FROM demo_apps d WHERE spent_token_hash=?`, hash).Scan(&stored, &reason, &committed)
+ if errors.Is(err, sql.ErrNoRows) {
+ return ErrDemoToken
+ }
+ if err != nil {
+ return err
+ }
+ if subtle.ConstantTimeCompare(hash, stored) != 1 {
+ return ErrDemoToken
+ }
+ if committed {
+ return ErrDemoKept
+ }
+ switch reason {
+ case "expired":
+ return ErrDemoExpired
+ case "operator":
+ return ErrDemoTakenDown
+ default:
+ return ErrDemoToken
+ }
+}
+
func demoLifeValid(row DemoRow, life *AppLife, now time.Time) bool {
return life != nil && life.DemoID == row.ID && life.Lifetime != "" && life.DeletedAt == 0 && !life.Restoring && life.ExpiresAt > now.Unix() && row.State == "anonymous" && row.PurgedAt == 0
}
@@ -435,7 +484,7 @@ func (s *Server) withDemoLocked(ctx context.Context, id string, fn func(DemoRow,
}
// WipeDemoAbuse removes identifying metadata seven days after confirmed purge.
-// Purged history lasts seven days; the minimal host tombstone is permanent.
+// Abuse history lasts seven days; spent hashes and host tombstones are permanent.
// The existing expiry pass calls this even with admission disabled.
func (s *Store) WipeDemoAbuse(ctx context.Context, now time.Time) error {
tx, err := s.db.BeginTx(ctx, nil)
@@ -460,7 +509,7 @@ func (s *Store) WipeDemoAbuse(ctx context.Context, now time.Time) error {
if _, err = tx.ExecContext(ctx, `DELETE FROM demo_caps WHERE demo_id IN (`+expired+`)`, cutoff); err != nil {
return err
}
- if _, err = tx.ExecContext(ctx, `DELETE FROM demo_apps WHERE demo_id IN (`+expired+`)`, cutoff); err != nil {
+ if _, err = tx.ExecContext(ctx, `DELETE FROM demo_apps WHERE spent_token_hash IS NULL AND demo_id IN (`+expired+`)`, cutoff); err != nil {
return err
}
return tx.Commit()
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js
index 98debaa3c..601701da1 100644
--- a/internal/console/static/demo_claim.js
+++ b/internal/console/static/demo_claim.js
@@ -114,21 +114,33 @@
csrf: document.querySelector('input[name="csrf"]').value
});
token = "";
+ const showError = reason => {
+ const copy = document.getElementById("claim").dataset;
+ const messages = new Map([
+ ["expired", copy.expired], ["kept", copy.kept],
+ ["taken-down", copy.takenDown], ["invalid", copy.invalid]
+ ]);
+ const error = document.getElementById("claim-error");
+ error.textContent = messages.get(reason) || copy.failed;
+ error.hidden = false;
+ error.focus();
+ };
fetch("/demo/claim/intent", {
method: "POST",
credentials: "same-origin",
mode: "same-origin",
cache: "no-store",
body: form
- }).then(response => {
+ }).then(async response => {
form.delete("claimToken");
- if (!response.ok) throw new Error();
+ if (!response.ok) {
+ const result = await response.json();
+ showError(result?.reason);
+ return;
+ }
location.replace("/demo/claim");
}).catch(() => {
form.delete("claimToken");
- const error = document.getElementById("claim-error");
- error.textContent = document.getElementById("claim").dataset.failed;
- error.hidden = false;
- error.focus();
+ showError();
});
})();
diff --git a/internal/console/templates/demo_claim.html b/internal/console/templates/demo_claim.html
index fd7296ae6..eb5da8d26 100644
--- a/internal/console/templates/demo_claim.html
+++ b/internal/console/templates/demo_claim.html
@@ -47,7 +47,7 @@
</head>
<body>
{{template "console_header" .Chrome}}
-<main id="claim" data-failed="{{.Copy.failed}}">
+<main id="claim" data-failed="{{.Copy.failed}}" data-expired="{{.Copy.expired}}" data-kept="{{.Copy.kept}}" data-taken-down="{{.Copy.takenDown}}" data-invalid="{{.Copy.invalid}}">
<h1>{{if eq .State "claimed"}}{{.Copy.complete}}{{else}}{{.Copy.title}}{{end}}</h1>
{{if .DemoName}}<div class="claim-summary">
<strong>{{.DemoName}}</strong><a href="https://{{.DemoHost}}" rel="noreferrer">{{.DemoHost}}</a>
diff --git a/internal/console/testdata/demo_claim_browser.mjs b/internal/console/testdata/demo_claim_browser.mjs
index 55b6e992d..8e19f87b2 100644
--- a/internal/console/testdata/demo_claim_browser.mjs
+++ b/internal/console/testdata/demo_claim_browser.mjs
@@ -2,7 +2,7 @@ import {spawn} from 'node:child_process';
import assert from 'node:assert/strict';
import {captureClaim, watchClaimCSP} from './demo_claim_layout.mjs';
-const [binary, profile, target, screenshots] = process.argv.slice(2);
+const [binary, profile, target, screenshots, expectedError] = process.argv.slice(2);
const chrome = spawn(binary, ['--headless', '--no-sandbox', '--disable-gpu',
'--disable-dev-shm-usage', '--disable-background-networking', '--disable-component-update',
'--disable-default-apps', '--disable-extensions', '--disable-sync', '--no-proxy-server',
@@ -51,6 +51,15 @@ try {
await call('Page.enable');
await call('Page.addScriptToEvaluateOnNewDocument', {source:watchClaimCSP});
await call('Page.navigate', {url:target});
+ if (expectedError) {
+ await until('location.hash === "" && document.getElementById("claim-error")?.hidden === false');
+ assert.equal(await evaluate('document.getElementById("claim-error").textContent'), expectedError);
+ assert.equal(await evaluate('document.activeElement.id'), 'claim-error');
+ assert.deepEqual(await evaluate('window.claimCSPViolations'), []);
+ const history = await call('Page.getNavigationHistory');
+ assert(history.entries.every(entry => !entry.url.includes('#')));
+ process.stdout.write('expired message, fragment cleared, zero CSP violations passed\n');
+ } else {
await until('location.hash === "" && !!document.getElementById("email")');
await captureClaim(call, evaluate, screenshots, 'email', [360, 390, 1100]);
const history = await call('Page.getNavigationHistory');
@@ -100,6 +109,7 @@ try {
assert.deepEqual(await evaluate('window.claimCSPViolations'), []);
process.stdout.write('email/code mobile layouts, secondary email and code submissions, CSP passed\n');
process.stdout.write('fragment_cleared post_exchange keyboard_email_submit passed\n');
+ }
} finally {
clearTimeout(timer);
const closed = new Promise(resolve => chrome.once('exit', resolve));