carlos / platform Public

Improve demo claim account choice and browser progress

Show native account cards with plan capacity hints and preserve confirmed selections through fresh authentication. Poll a cookie-scoped SQL-only status door and show the resulting app with accurate old-address guidance.

Cover account states, status capability isolation, CSP, keyboard selection, resume, automatic progress, and polling failure recovery in targeted Go and Chromium tests.
codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev f20880abcb56fd397dbfe7bb8a6e635f91aaf906 parent 4c41cb9
13 files changed, +824 −62
  • internal/console/apidemo.go +1 −0
  • internal/console/demo_claim_browser_test.go +1 −1
  • internal/console/demo_claim_choice_test.go +362 −0
  • internal/console/demo_claim_copy.go +33 −10
  • internal/console/demo_claim_page.go +104 −13
  • internal/console/demo_claim_ready_test.go +1 −1
  • internal/console/demo_claim_resume_browser_test.go +61 −3
  • internal/console/demo_claim_resume_test.go +2 −2
  • internal/console/demo_claim_review_test.go +2 −2
  • internal/console/demo_claim_status_page.go +56 −0
  • internal/console/static/demo_claim.js +57 −0
  • internal/console/templates/demo_claim.html +62 −13
  • internal/console/testdata/demo_claim_resume_browser.mjs +82 −17

Intent

Human

<paseo-system version="1" kind="agent-message" source-agent-id="32157efb-ed29-443f-b428-8c9e3320fa50" message-id="173a78aa-5486-432c-b4eb-78558b1f24d4"> From platform-f6: departures 1-3 are fine. On room: don&apos;t show raw counts that make 2-of-3 look full. Each card says &apos;Has room&apos; or, for an account that can&apos;t take it, &apos;Full&apos; with the numbers in the plan&apos;s own words (e.g. &apos;Full: 3 of 3 running things used&apos;); use the same &apos;running things&apos; term the plans and pricing copy use, via Luna. Paul may still ask for numbers on every card; I&apos;ll relay if so. </paseo-system>

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

diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go
index 62b3a697f..ccd8efee2 100644
--- a/internal/console/apidemo.go
+++ b/internal/console/apidemo.go
@@ -286,6 +286,7 @@ func (s *Server) registerDemoRoutes() {
s.registerRoute("POST /api/box/demo-claims/{operationID}/snapshot", s.handleDemoClaimSnapshot)
s.registerRoute("POST /api/box/demo-claims/{operationID}/ack", s.handleDemoClaimAck)
s.registerRoute("GET /demo/claim", s.handleDemoClaimPage)
+ s.registerRoute("GET /demo/claim/status", s.handleDemoClaimBrowserStatus)
s.registerRoute("POST /demo/claim/intent", s.handleDemoClaimBrowserIntent)
s.registerRoute("POST /demo/claim/prove", s.handleDemoClaimBrowserProof)
s.registerRoute("POST /demo/claim/select", s.handleDemoClaimBrowserSelect)
diff --git a/internal/console/demo_claim_browser_test.go b/internal/console/demo_claim_browser_test.go
index 6c923af4f..e32dc4174 100644
--- a/internal/console/demo_claim_browser_test.go
+++ b/internal/console/demo_claim_browser_test.go
@@ -321,7 +321,7 @@ func TestDemoClaimBrowserStatus(t *testing.T) {
if w.Code != 200 {
t.Fatalf("%s status: %d", phase, w.Code)
}
- if phase == "done" && (!strings.Contains(w.Body.String(), op.Target.Host) || !strings.Contains(w.Body.String(), op.Target.App) || !strings.Contains(w.Body.String(), op.Target.Sqid) || !strings.Contains(w.Body.String(), "carlos auth login --console "+s.cfg.Origin)) {
+ if phase == "done" && (!strings.Contains(w.Body.String(), op.Target.Host) || !strings.Contains(w.Body.String(), op.Target.App) || !strings.Contains(w.Body.String(), "carlos auth login --console "+s.cfg.Origin)) {
t.Fatalf("result missing: %s", w.Body.String())
}
}
diff --git a/internal/console/demo_claim_choice_test.go b/internal/console/demo_claim_choice_test.go
new file mode 100644
index 000000000..ad80bcebf
--- /dev/null
+++ b/internal/console/demo_claim_choice_test.go
@@ -0,0 +1,362 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "regexp"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestDemoClaimChoiceRendering(t *testing.T) {
+ for _, n := range []int{0, 1, 3} {
+ t.Run(fmt.Sprint(n), func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ b := newClaimBrowser(t, s, token)
+ b.login("shop@example.com", MethodEmail, true)
+ for i := 0; i < n; i++ {
+ claimAccount(t, s, int64(501+i), "shop@example.com", RoleOwner)
+ }
+ s.cfg.AppsDomain = "apps.example.com"
+ d, err := s.store.LookupDemoToken(t.Context(), token)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := b.request("GET", "/demo/claim", nil).Body.String()
+ for _, want := range []string{d.Name, d.Host, "Its saved data comes with it", "a permanent address on apps.example.com"} {
+ if !strings.Contains(body, want) {
+ t.Errorf("missing %q", want)
+ }
+ }
+ if strings.Contains(body, "<select") {
+ t.Error("old select remains")
+ }
+ if n == 0 && !strings.Contains(body, `name="create" value="1"`) {
+ t.Error("missing new account path")
+ }
+ if n == 1 && (!strings.Contains(body, "This goes into shop") || !strings.Contains(body, `type="hidden" name="accountId"`) || strings.Contains(body, `type="radio"`)) {
+ t.Error("single account is not implicit")
+ }
+ if n > 1 && (strings.Count(body, `type="radio"`) != n || !strings.Contains(body, "<fieldset") || !strings.Contains(body, "<legend>")) {
+ t.Error("missing native radio group")
+ }
+ text := regexp.MustCompile(`<[^>]*>`).ReplaceAllString(body, "")
+ accts, _ := s.store.AccountsFor("shop@example.com")
+ for _, a := range accts {
+ if strings.Contains(text, a.Sqid) {
+ t.Errorf("sqid visible: %s", a.Sqid)
+ }
+ }
+ if strings.Contains(body, "apps and instances") {
+ t.Error("plans off must omit room")
+ }
+ })
+ }
+}
+
+func TestDemoClaimStatusDoor(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ raw, _ := randomToken()
+ if err := s.store.attachDemoClaimBrowser(t.Context(), raw, claimFlow{Hash: op.FlowHash, ExpiresAt: time.Now().Add(time.Minute)}); err != nil {
+ t.Fatal(err)
+ }
+ s.demoClaimTestEnabled = false
+ s.cfg.Demo.ClaimEnabled = false
+ s.cfg.Releases = claimNoRemoteStore{}
+ request := func(cookie, path, site string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest("GET", path, nil)
+ r.Header.Set("Sec-Fetch-Site", site)
+ if cookie != "" {
+ r.AddCookie(&http.Cookie{Name: demoClaimBrowserCookie, Value: cookie})
+ }
+ w := httptest.NewRecorder()
+ s.mux.ServeHTTP(w, r)
+ return w
+ }
+ for _, tc := range []struct {
+ phase, state string
+ step int
+ }{{"reserved", "claiming", 1}, {"freezing", "claiming", 1}, {"copying", "claiming", 1}, {"verifying", "claiming", 2}, {"committed", "claiming", 2}, {"done", "claimed", 3}, {"aborted", "aborted", 0}} {
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase=? WHERE id=?`, tc.phase, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ w := request(raw, "/demo/claim/status", "same-origin")
+ var got map[string]any
+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &got) != nil {
+ t.Fatalf("%s: %d %s", tc.phase, w.Code, w.Body)
+ }
+ if got["state"] != tc.state || got["step"] != float64(tc.step) {
+ t.Errorf("%s: %v", tc.phase, got)
+ }
+ want := 2
+ if tc.phase == "done" {
+ want = 3
+ if got["url"] != "https://"+op.Target.Host {
+ t.Error("missing app URL")
+ }
+ }
+ if len(got) != want || w.Header().Get("Cache-Control") != "no-store" {
+ t.Errorf("unexpected payload or cache: %v", got)
+ }
+ }
+ for _, tc := range []struct {
+ cookie, path, site string
+ code int
+ }{{"", "/demo/claim/status", "same-origin", 401}, {"wrong", "/demo/claim/status", "same-origin", 401}, {raw, "/demo/claim/status?operationId=other", "same-origin", 400}, {raw, "/demo/claim/status", "cross-site", 403}, {raw, "/demo/claim/status", "same-site", 403}} {
+ if w := request(tc.cookie, tc.path, tc.site); w.Code != tc.code {
+ t.Errorf("%s %s: %d want %d", tc.path, tc.site, w.Code, tc.code)
+ }
+ }
+ // An operation alone is not sufficient: the cookie must have been
+ // promoted to status purpose and both lifetimes must still be valid.
+ for _, q := range []string{
+ `UPDATE demo_claim_browsers SET purpose='demo-claim-browser'`,
+ `UPDATE demo_claim_browsers SET purpose='demo-claim-status',expires_at=1`,
+ `UPDATE demo_claim_browsers SET expires_at=9999999999`,
+ } {
+ if _, err := s.store.db.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(q, "9999999999") {
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET source_expires_at=1`); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if w := request(raw, "/demo/claim/status", "same-origin"); w.Code != 401 {
+ t.Errorf("expired or wrong-purpose capability accepted: %d", w.Code)
+ }
+ }
+
+}
+
+func TestDemoClaimSharedChromeUnchanged(t *testing.T) {
+ b, err := os.ReadFile("templates/console_chrome.html")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := fmt.Sprintf("%x", sha256.Sum256(b)); got != "555292d40296be5866bec0de6af1d8c5c7121de21b30d1618f2ed2078bd991de" {
+ t.Fatal("shared chrome changed", got)
+ }
+}
+
+// Any accidental remote operation panics, including a newly added Store method.
+type claimNoRemoteStore struct{ release.Store }
+
+type claimRoomStore struct {
+ release.Store
+ calls atomic.Int32
+ fail bool
+}
+
+func (s *claimRoomStore) List(ctx context.Context, prefix string) ([]string, error) {
+ s.calls.Add(1)
+ if s.fail {
+ return nil, errors.New("count unavailable")
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func TestDemoClaimChoiceRoom(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ role string
+ instances int
+ plans, fail bool
+ reason string
+ }{
+ {"fits exactly", RoleOwner, 0, true, false, ""},
+ {"needs two slots", RoleMember, 1, true, false, demoClaimAtLimit},
+ {"role", "viewer", 0, true, false, demoClaimRoleDenied},
+ {"plans off", RoleOwner, 1, false, false, ""},
+ {"count failed", RoleOwner, 1, true, true, ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ b := newClaimBrowser(t, s, token)
+ b.login("shop@example.com", MethodEmail, true)
+ a := claimChoiceAccount(t, s, 501, "shop@example.com", tc.role)
+ if _, err := s.store.CreateAppIn(a.ID, "shop", "shop@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < tc.instances; i++ {
+ if _, err := s.cfg.Releases.Put(t.Context(), provision.RecordKey(a.Sqid, "shop", fmt.Sprintf("shop%d.example.com", i)), []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if tc.plans {
+ s.cfg.PlanCatalog = examplePlanCatalog(t)
+ }
+ spy := &claimRoomStore{Store: s.cfg.Releases, fail: tc.fail}
+ s.cfg.Releases = spy
+ w := b.request("GET", "/demo/claim", nil)
+ body := w.Body.String()
+ if w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ if tc.reason != "" {
+ if !strings.Contains(body, tc.reason) || !strings.Contains(body, `value="`+a.Sqid+`" disabled`) || strings.Contains(body, `action="/demo/claim/select"`) {
+ t.Error("ineligible account not disabled with its reason")
+ }
+ } else if !strings.Contains(body, `type="hidden" name="accountId" value="`+a.Sqid+`"`) {
+ t.Error("eligible account lost")
+ }
+ if tc.plans && !tc.fail {
+ want := fmt.Sprintf(demoClaimRoom, 1+tc.instances, 3)
+ if !strings.Contains(body, want) || !strings.Contains(body, ">Free<") {
+ t.Errorf("missing plan or room %q", want)
+ }
+ if isPlanCap(s.checkRunningThings(t.Context(), a, 2)) != (tc.instances == 1) {
+ t.Error("hint differs from reservation")
+ }
+ } else if strings.Contains(body, "apps and instances") {
+ t.Error("unavailable count rendered")
+ }
+ if !tc.plans && spy.calls.Load() != 0 {
+ t.Error("plans off read store")
+ }
+ // HEAD renders no capacity hint and does not count.
+ spy.calls.Store(0)
+ b.request("HEAD", "/demo/claim", nil)
+ if spy.calls.Load() != 0 {
+ t.Error("HEAD counted")
+ }
+ b.session = ""
+ spy.calls.Store(0)
+ b.request("GET", "/demo/claim", nil)
+ if spy.calls.Load() != 0 {
+ t.Error("signed out counted")
+ }
+ b.login("shop@example.com", MethodEmail, true)
+ b.cookie = "missing"
+ spy.calls.Store(0)
+ b.request("GET", "/demo/claim", nil)
+ if spy.calls.Load() != 0 {
+ t.Error("missing intent counted")
+ }
+ })
+ }
+}
+
+func TestDemoClaimChoiceSingleWithIneligible(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ b := newClaimBrowser(t, s, token)
+ b.login("shop@example.com", MethodEmail, true)
+ a := claimAccount(t, s, 501, "shop@example.com", RoleMember)
+ d := claimChoiceAccount(t, s, 502, "shop@example.com", "viewer")
+ body := b.request("GET", "/demo/claim", nil).Body.String()
+ for _, want := range []string{`type="hidden" name="accountId" value="` + a.Sqid + `"`, `type="radio" name="accountId" value="` + d.Sqid + `" disabled`, "This goes into shop", "Keep in shop", demoClaimRoleDenied} {
+ if !strings.Contains(body, want) {
+ t.Errorf("missing %q", want)
+ }
+ }
+ if strings.Count(body, `type="radio"`) != 1 {
+ t.Error("eligible single account has a choice UI")
+ }
+}
+
+func TestDemoClaimChoiceCSP(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ b := newClaimBrowser(t, s, token)
+ w := b.request("GET", "/demo/claim", nil)
+ body := w.Body.String()
+ styles := regexp.MustCompile(`(?s)<style>(.*?)</style>`).FindAllStringSubmatch(body, -1)
+ hashes := []string{}
+ for _, style := range styles {
+ sum := sha256.Sum256([]byte(style[1]))
+ hashes = append(hashes, "'sha256-"+base64.StdEncoding.EncodeToString(sum[:])+"'")
+ }
+ formAction := "'self'"
+ if origin := s.km.Origin(); origin != "" {
+ formAction += " " + origin
+ }
+ want := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src " + strings.Join(hashes, " ") + "; form-action " + formAction + "; frame-ancestors 'none'; base-uri 'none'"
+ if w.Header().Get("Content-Security-Policy") != want {
+ t.Fatalf("policy changed: %s", w.Header().Get("Content-Security-Policy"))
+ }
+ if strings.Contains(body, ` style="`) || strings.Count(body, "<script") != 1 {
+ t.Error("inline style or extra script")
+ }
+}
+
+func TestDemoClaimStatusDoorCredentials(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ b := newClaimBrowser(t, s, token)
+ send := func(path, cookie, origin, site string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest("GET", path, nil)
+ r.Header.Set("Origin", origin)
+ r.Header.Set("Sec-Fetch-Site", site)
+ r.AddCookie(&http.Cookie{Name: demoClaimBrowserCookie, Value: cookie})
+ w := httptest.NewRecorder()
+ s.mux.ServeHTTP(w, r)
+ return w
+ }
+ if w := send("/demo/claim/status", b.cookie, "", "same-origin"); w.Code != 401 {
+ t.Fatal("intent cookie authorized status", w.Code)
+ }
+ if w := send("/demo/claim/status", b.cookie, "https://other.example.com", "same-origin"); w.Code != 403 {
+ t.Fatal("foreign origin authorized", w.Code)
+ }
+ if w := send("/demo/claim/status", b.cookie, "", ""); w.Code != 403 {
+ t.Fatal("missing origin evidence authorized", w.Code)
+ }
+ other := newClaimBrowser(t, s, token)
+ b.login("shop@example.com", MethodEmail, true)
+ if w := b.post("/demo/claim/select", url.Values{"create": {"1"}}); w.Code != 303 {
+ t.Fatal(w.Code, w.Body)
+ }
+ // Cookie-only and cookie-as-Bearer never authorize an agent endpoint.
+ for _, bearer := range []bool{false, true} {
+ for _, path := range []string{"/api/demo/claims", "/api/demo/claims/verify", "/api/demo/claims/select", "/api/demo/claims/status"} {
+ method := "POST"
+ if strings.HasSuffix(path, "/status") {
+ method = "GET"
+ }
+ payload, _ := json.Marshal(map[string]string{"flowToken": b.cookie, "claimToken": b.cookie, "email": "shop@example.com"})
+ if path != "/api/demo/claims" {
+ payload, _ = json.Marshal(map[string]string{"flowToken": b.cookie})
+ if strings.HasSuffix(path, "/verify") {
+ payload, _ = json.Marshal(map[string]string{"flowToken": b.cookie, "code": "000000"})
+ }
+ }
+ r := httptest.NewRequest(method, path, bytes.NewReader(payload))
+ r.Header.Set("Content-Type", "application/json")
+ r.AddCookie(&http.Cookie{Name: demoClaimBrowserCookie, Value: b.cookie})
+ if bearer {
+ r.Header.Set("Authorization", "Bearer "+b.cookie)
+ }
+ w := httptest.NewRecorder()
+ s.mux.ServeHTTP(w, r)
+ if w.Code != 401 {
+ t.Errorf("agent %s bearer=%v: %d", path, bearer, w.Code)
+ }
+ }
+ }
+ // A valid cookie for an unrelated live intent cannot read this operation.
+ if w := send("/demo/claim/status", other.cookie, "", "same-origin"); w.Code != 401 {
+ t.Fatal("other intent read operation", w.Code)
+ }
+}
+
+func claimChoiceAccount(t *testing.T, s *Server, id int64, person, role string) *Account {
+ t.Helper()
+ a := claimAccount(t, s, id, person, RoleMember)
+ if _, err := s.store.db.Exec(`UPDATE memberships SET role=? WHERE account_id=? AND address=?`, role, id, person); err != nil {
+ t.Fatal(err)
+ }
+ a.Role = role
+ return a
+}
diff --git a/internal/console/demo_claim_copy.go b/internal/console/demo_claim_copy.go
index dcab12abe..6d2acf0ce 100644
--- a/internal/console/demo_claim_copy.go
+++ b/internal/console/demo_claim_copy.go
@@ -55,22 +55,16 @@ const (
demoClaimEmailSent = "Check your email for a code or confirmation link."
// CLAIM-KEYMAIL: ordinary sign-in action.
demoClaimSignin = "Sign in to continue"
- // CLAIM-ACCOUNT: account selector label.
- demoClaimAccountLabel = "Account"
// CLAIM-ACCOUNT: empty picker choice.
demoClaimChooseAccount = "Choose an account"
- // CLAIM-ACCOUNT: zero membership confirmation.
- demoClaimNewAccount = "Create a personal account and keep this demo in it. Your plan limits apply."
+ // CLAIM-ACCOUNT-NEW: zero membership confirmation.
+ demoClaimNewAccount = "We will create a personal account and keep this demo in it."
// CLAIM-ACCOUNT: explicit claim action.
demoClaimConfirm = "Keep this demo"
- // CLAIM-RESULT: in-progress status.
- demoClaimWorking = "Your demo is being copied. Reload this page to check its progress."
// CLAIM-RESULT: reload action.
demoClaimReload = "Check progress"
// CLAIM-RESULT: completed claim.
demoClaimComplete = "Your demo is now a permanent app."
- // CLAIM-RESULT: result app label.
- demoClaimAppLabel = "App"
// CLAIM-RESULT: result URL label.
demoClaimURLLabel = "Open app"
// CLAIM-RESULT: next workflow.
@@ -82,11 +76,40 @@ const (
const (
// CLAIM-ERROR-BACK: return from a browser form refusal.
demoClaimBack = "Back to your claim"
- // CLAIM-ACCOUNT-NONE: memberships exist but none allow app creation.
- demoClaimNoEligibleAccount = "You cannot create apps in any of your accounts. Ask an account owner for access."
+ // CLAIM-ACCOUNT-NONE: memberships exist but none can take the claim.
+ demoClaimNoEligibleAccount = "None of your accounts can take this demo right now."
// CLAIM-ACCOUNT-CAP: plan cap refusal during browser reservation.
demoClaimAccountCap = "This account has reached its plan limit. Choose another account or free up capacity."
)
// CLAIM-RESUME-SUBMITTING: the previously confirmed selection is being posted.
const demoClaimResuming = "Keeping your demo in the account you chose…"
+
+const (
+ // CLAIM-UNAVAILABLE-ACCOUNTS: the disabled account list.
+ demoClaimUnavailableAccounts = "Unavailable accounts"
+ // CLAIM-SAVED: what the person keeps.
+ demoClaimSaved = "Its saved data comes with it."
+ // CLAIM-PERMANENT: domain only; the eventual name may need a suffix.
+ demoClaimPermanent = "It gets a permanent address on %s."
+ // CLAIM-DESTINATION: the only eligible account.
+ demoClaimDestination = "This goes into %s"
+ // CLAIM-KEEP-IN: action after choosing an account.
+ demoClaimKeepIn = "Keep in %s"
+ // CLAIM-ROOM: the same unit as the catalog cap.
+ demoClaimRoom = "%d of %d apps and instances in use"
+ // CLAIM-ROLE-DENIED: membership cannot create apps.
+ demoClaimRoleDenied = "Your role cannot create apps in this account."
+ // CLAIM-AT-LIMIT: a claim requires both an app and an instance.
+ demoClaimAtLimit = "At its limit. This demo needs room for 2 apps and instances."
+ // CLAIM-STEP-COPYING: first progress step.
+ demoClaimCopying = "Copying your data"
+ // CLAIM-STEP-STARTING: second progress step.
+ demoClaimStarting = "Starting your app"
+ // CLAIM-STEP-DONE: final progress step.
+ demoClaimDone = "Done"
+ // CLAIM-POLL-FAILED: repeated status failures, with a reload link.
+ demoClaimPollFailed = "Progress could not be checked. Reload to try again."
+ // 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 expiry."
+)
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index bddaa542e..ea40c871c 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -2,6 +2,7 @@ package console
import (
"bytes"
+ "context"
"crypto/sha256"
"crypto/subtle"
"database/sql"
@@ -33,13 +34,17 @@ var demoClaimStyleHash = func() string {
}()
type demoClaimPageData struct {
- AutoSubmit bool
- SelectedAccount string
- Chrome page
- Copy map[string]string
- Nonce, CSRF, Address, State, AccountID, App, URL, Error string
- Accounts []Account
- CanClaim, HasIntent, EmailPending bool
+ AutoSubmit bool
+ SelectedAccount string
+ Chrome page
+ Copy map[string]string
+ Nonce, CSRF, Address, State, App, URL, Error string
+ Accounts []demoClaimAccountChoice
+ Single *demoClaimAccountChoice
+ Eligible int
+ DemoName, DemoHost, Permanent string
+ Step int
+ CanClaim, HasIntent, EmailPending bool
}
func demoClaimPageHeaders(w http.ResponseWriter, keymailOrigin string) {
@@ -124,10 +129,9 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
if err == nil {
if op, opErr := s.store.demoClaimOpForFlow(r.Context(), hash); opErr == nil {
setDemoClaimCookie(w, cookie, demoClaimResultExpiry(op))
- p.State = "claiming"
+ p.State, p.Step = demoClaimProgressStep(op.Phase)
if op.Phase == "done" {
p.State = "claimed"
- p.AccountID = op.Target.Sqid
p.App = op.Target.App
p.URL = "https://" + op.Target.Host
}
@@ -138,6 +142,13 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return
} else if f, ferr := s.store.demoClaimFlowByHash(r.Context(), hash, time.Now()); ferr == nil {
+ d, derr := s.store.demoByID(r.Context(), f.DemoID)
+ if derr != nil {
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ return
+ }
+ p.DemoName, p.DemoHost = d.Name, d.Host
+ p.Permanent = fmt.Sprintf(demoClaimPermanent, s.cfg.AppsDomain)
p.HasIntent = true
p.State = "proof"
p.CanClaim = s.demoClaimEnabled()
@@ -150,6 +161,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
if f.Person != "" && f.Person != address {
p.State = "missing"
p.HasIntent = false
+ p.DemoName, p.DemoHost, p.Permanent = "", "", ""
p.CanClaim = false
} else {
var accounts []Account
@@ -159,18 +171,29 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
return
}
for _, a := range accounts {
- if demoClaimCanCreate(a) {
+ choice := s.demoClaimAccountView(r.Context(), a, r.Method == http.MethodGet)
+ p.Accounts = append(p.Accounts, choice)
+ if choice.Reason == "" {
+ p.Eligible++
if resume && !selection.Create && selection.Account == a.Sqid {
p.AutoSubmit = p.CanClaim
p.SelectedAccount = a.Sqid
}
- p.Accounts = append(p.Accounts, a)
+ }
+ }
+ if p.Eligible == 1 {
+ for i := range p.Accounts {
+ if p.Accounts[i].Reason == "" {
+ p.Single = &p.Accounts[i]
+ p.Copy["destination"] = fmt.Sprintf(demoClaimDestination, p.Single.Name)
+ p.Copy["confirm"] = p.Single.Button
+ }
}
}
if resume && selection.Create && len(accounts) == 0 {
p.AutoSubmit = p.CanClaim
}
- if len(accounts) > 0 && len(p.Accounts) == 0 {
+ if len(accounts) > 0 && p.Eligible == 0 {
p.State, p.CanClaim = "no_accounts", false
}
}
@@ -499,7 +522,37 @@ func (s *Server) demoClaimSessionIdentity(raw, person string) (string, string, b
}
func demoClaimBrowserCopy() map[string]string {
- return map[string]string{"resuming": demoClaimResuming, "back": demoClaimBack, "noAccounts": demoClaimNoEligibleAccount, "title": demoClaimPageTitle, "missing": demoClaimIntentExpired, "failed": demoClaimExchangeFailed, "noscript": demoClaimNeedsScript, "identity": demoClaimIdentityLabel, "email": demoClaimEmailLabel, "continue": demoClaimEmailContinue, "code": demoClaimCodeLabel, "prove": demoClaimCodeConfirm, "sent": demoClaimEmailSent, "signin": demoClaimSignin, "account": demoClaimAccountLabel, "choose": demoClaimChooseAccount, "new": demoClaimNewAccount, "confirm": demoClaimConfirm, "working": demoClaimWorking, "reload": demoClaimReload, "complete": demoClaimComplete, "app": demoClaimAppLabel, "url": demoClaimURLLabel, "aborted": demoClaimAborted, "disabled": demoClaimUnavailable}
+ return map[string]string{
+ "unavailableAccounts": demoClaimUnavailableAccounts,
+ "saved": demoClaimSaved,
+ "oldAddress": demoClaimOldAddress,
+ "copying": demoClaimCopying,
+ "starting": demoClaimStarting,
+ "done": demoClaimDone,
+ "pollFailed": demoClaimPollFailed,
+ "resuming": demoClaimResuming,
+ "back": demoClaimBack,
+ "noAccounts": demoClaimNoEligibleAccount,
+ "title": demoClaimPageTitle,
+ "missing": demoClaimIntentExpired,
+ "failed": demoClaimExchangeFailed,
+ "noscript": demoClaimNeedsScript,
+ "identity": demoClaimIdentityLabel,
+ "email": demoClaimEmailLabel,
+ "continue": demoClaimEmailContinue,
+ "code": demoClaimCodeLabel,
+ "prove": demoClaimCodeConfirm,
+ "sent": demoClaimEmailSent,
+ "signin": demoClaimSignin,
+ "choose": demoClaimChooseAccount,
+ "new": demoClaimNewAccount,
+ "confirm": demoClaimConfirm,
+ "reload": demoClaimReload,
+ "complete": demoClaimComplete,
+ "url": demoClaimURLLabel,
+ "aborted": demoClaimAborted,
+ "disabled": demoClaimUnavailable,
+ }
}
func demoClaimCanCreate(a Account) bool { return a.Role == RoleOwner || a.Role == RoleMember }
@@ -538,3 +591,41 @@ func (s *Server) continueDemoClaimKeymail(w http.ResponseWriter, r *http.Request
}
s.continueKeymailSignin(w, r, flow, "/demo/claim")
}
+
+// Room is a GET-only hint. Reservation still checks under its account lock.
+type demoClaimAccountChoice struct {
+ Sqid, Name, Plan, Room, Reason, Button string
+}
+
+func (s *Server) demoClaimAccountView(ctx context.Context, a Account, count bool) demoClaimAccountChoice {
+ c := demoClaimAccountChoice{Sqid: a.Sqid, Name: a.Name, Button: fmt.Sprintf(demoClaimKeepIn, a.Name)}
+ if !demoClaimCanCreate(a) {
+ c.Reason = demoClaimRoleDenied
+ }
+ if cat := s.cfg.PlanCatalog; cat != nil {
+ name := cat.DefaultPlan
+ row, err := s.store.AccountPlan(a.ID)
+ if err == nil {
+ if row != nil {
+ name = row.Plan
+ }
+ c.Plan = planLabel(name)
+ }
+ }
+ if !count {
+ return c
+ }
+ limits, err := s.EffectiveLimits(&a)
+ if err != nil || limits == nil {
+ return c
+ }
+ n, err := s.runningThings(ctx, &a)
+ if err != nil {
+ return c
+ }
+ c.Room = fmt.Sprintf(demoClaimRoom, n, limits.RunningThings)
+ if n+2 > limits.RunningThings && c.Reason == "" {
+ c.Reason = demoClaimAtLimit
+ }
+ return c
+}
diff --git a/internal/console/demo_claim_ready_test.go b/internal/console/demo_claim_ready_test.go
index 86dc74d49..0d192b4d3 100644
--- a/internal/console/demo_claim_ready_test.go
+++ b/internal/console/demo_claim_ready_test.go
@@ -124,7 +124,7 @@ func TestDemoClaimRecoveryRoutes(t *testing.T) {
s.mux = http.NewServeMux()
s.claimEntries = claimInventory{}
s.registerDemoRoutes()
- for _, route := range []struct{ method, path string }{{"GET", "/api/demo/claims/status"}, {"GET", "/demo/claim"}, {"POST", "/api/box/demo-claims/AAAAAAAAAAAAAAAAAAAAAA/pickup"}, {"POST", "/api/box/demo-claims/AAAAAAAAAAAAAAAAAAAAAA/snapshot"}, {"POST", "/api/box/demo-claims/AAAAAAAAAAAAAAAAAAAAAA/ack"}, {"POST", "/api/box/demo-retirements/ack"}, {"GET", demoBuildStreamPath}} {
+ for _, route := range []struct{ method, path string }{{"GET", "/api/demo/claims/status"}, {"GET", "/demo/claim"}, {"GET", "/demo/claim/status"}, {"POST", "/api/box/demo-claims/AAAAAAAAAAAAAAAAAAAAAA/pickup"}, {"POST", "/api/box/demo-claims/AAAAAAAAAAAAAAAAAAAAAA/snapshot"}, {"POST", "/api/box/demo-claims/AAAAAAAAAAAAAAAAAAAAAA/ack"}, {"POST", "/api/box/demo-retirements/ack"}, {"GET", demoBuildStreamPath}} {
r := httptest.NewRequest(route.method, route.path, nil)
if _, p := s.mux.Handler(r); p == "" {
t.Fatalf("missing recovery route %s", route.path)
diff --git a/internal/console/demo_claim_resume_browser_test.go b/internal/console/demo_claim_resume_browser_test.go
index e719702f5..4c2c2b13e 100644
--- a/internal/console/demo_claim_resume_browser_test.go
+++ b/internal/console/demo_claim_resume_browser_test.go
@@ -2,11 +2,13 @@ package console
import (
"context"
+ "encoding/json"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
+ "sync/atomic"
"testing"
"time"
)
@@ -23,7 +25,39 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) {
s, _, token := claimTestServer(t)
fk := claimStepUpStub(t, s)
s.registerRoute("GET /static/{hash}/{file...}", s.handleStatic)
+ var polls, mode atomic.Int32
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/demo/claim" && r.URL.Query().Has("testProgress") {
+ polls.Store(0)
+ mode.Store(1)
+ if r.URL.Query().Get("testProgress") == "abort" {
+ mode.Store(2)
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase='copying'`); err != nil {
+ t.Error(err)
+ }
+ }
+ if r.URL.Path == "/demo/claim/status" {
+ n := polls.Add(1)
+ if mode.Load() == 1 {
+ if n%2 == 1 {
+ jsonError(w, 503, demoClaimUnavailable)
+ } else {
+ demoClaimReply(w, 200, map[string]any{"state": "<img src=x onerror=alert(1)>", "step": 2})
+ }
+ return
+ }
+ phase := "verifying"
+ if n >= 4 {
+ phase = "done"
+ }
+ if mode.Load() == 2 {
+ phase = "aborted"
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase=?`, phase); err != nil {
+ t.Error(err)
+ }
+ }
if strings.HasPrefix(r.URL.Path, "/auth/") {
if _, err := r.Cookie(browserClaimCookieName); err == nil {
t.Error("claim cookie reached auth path")
@@ -47,11 +81,35 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) {
s.km.origin = ts.URL
b := newClaimBrowser(t, s, token)
b.login("claimant@example.com", MethodKeymail, false)
- claimAccount(t, s, 501, "claimant@example.com", RoleOwner)
+ first := claimAccount(t, s, 501, "claimant@example.com", RoleOwner)
+ if _, err := s.store.db.Exec(`UPDATE accounts SET name='Shop team' WHERE id=?`, first.ID); err != nil {
+ t.Fatal(err)
+ }
+ claimChoiceAccount(t, s, 503, "claimant@example.com", "viewer")
a := claimAccount(t, s, 502, "claimant@example.com", RoleOwner)
- ctx, cancel := context.WithTimeout(t.Context(), 45*time.Second)
+ if _, err := s.store.db.Exec(`UPDATE accounts SET name='Personal projects' WHERE id=?`, a.ID); err != nil {
+ t.Fatal(err)
+ }
+ s.cfg.PlanCatalog = examplePlanCatalog(t)
+ if _, err := s.store.SetAccountPlan(a.ID, "personal", nil, 0, PlanSourceSponsored, nil, "test", "ops@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+
+ // A second real flow renders the one-account state without changing the
+ // multi-account flow used for the keyboard and fresh-auth round trip.
+ single, _, singleToken := claimTestServer(t)
+ single.registerRoute("GET /static/{hash}/{file...}", single.handleStatic)
+ singleServer := httptest.NewServer(single.mux)
+ defer singleServer.Close()
+ single.cfg.Origin = singleServer.URL
+ one := newClaimBrowser(t, single, singleToken)
+ one.login("shop@example.com", MethodEmail, true)
+ claimAccount(t, single, 601, "shop@example.com", RoleOwner)
+ single.cfg.PlanCatalog = examplePlanCatalog(t)
+ singleArgs, _ := json.Marshal(map[string]string{"target": singleServer.URL, "session": one.session, "cookie": one.cookie})
+ ctx, cancel := context.WithTimeout(t.Context(), 90*time.Second)
defer cancel()
- cmd := exec.CommandContext(ctx, node, "testdata/demo_claim_resume_browser.mjs", chromium, t.TempDir(), ts.URL, b.session, b.cookie, a.Sqid, os.Getenv("CARLOS_DEMO_CLAIM_SCREENSHOTS"))
+ cmd := exec.CommandContext(ctx, node, "testdata/demo_claim_resume_browser.mjs", chromium, t.TempDir(), ts.URL, b.session, b.cookie, a.Sqid, os.Getenv("CARLOS_DEMO_CLAIM_SCREENSHOTS"), string(singleArgs))
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("headless: %v %s", err, output)
diff --git a/internal/console/demo_claim_resume_test.go b/internal/console/demo_claim_resume_test.go
index 55f2c8ab3..8d02f2430 100644
--- a/internal/console/demo_claim_resume_test.go
+++ b/internal/console/demo_claim_resume_test.go
@@ -83,7 +83,7 @@ func TestDemoClaimSelectStepUpRoundTrip(t *testing.T) {
t.Fatal("resume must consume stash without claiming")
}
w = b.request("GET", "/demo/claim", nil)
- if !strings.Contains(w.Body.String(), `data-auto-submit`) || !strings.Contains(w.Body.String(), `value="`+a.Sqid+`" selected`) {
+ if !strings.Contains(w.Body.String(), `data-auto-submit`) || !strings.Contains(w.Body.String(), `value="`+a.Sqid+`" checked`) {
t.Fatalf("selected account was not resumed: %s", w.Body)
}
if claimBrowserCount(t, s, "demo_claim_ops") != 0 {
@@ -104,7 +104,7 @@ func TestDemoClaimSelectStepUpRoundTrip(t *testing.T) {
t.Fatalf("wrong destination: %+v %v", op, err)
}
w = b.request("GET", "/demo/claim", nil)
- if !strings.Contains(w.Body.String(), demoClaimWorking) {
+ if !strings.Contains(w.Body.String(), demoClaimCopying) {
t.Fatal("no claiming state")
}
b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}})
diff --git a/internal/console/demo_claim_review_test.go b/internal/console/demo_claim_review_test.go
index e0649f8d4..f45f9ecc3 100644
--- a/internal/console/demo_claim_review_test.go
+++ b/internal/console/demo_claim_review_test.go
@@ -237,8 +237,8 @@ func TestDemoClaimBrowserPickerPermission(t *testing.T) {
t.Fatal(err)
}
w := b.request("GET", "/demo/claim", nil)
- if strings.Contains(w.Body.String(), denied.Sqid) || !strings.Contains(w.Body.String(), allowed.Sqid) {
- t.Error("picker includes a role that cannot create apps")
+ if !strings.Contains(w.Body.String(), `value="`+denied.Sqid+`" disabled`) || !strings.Contains(w.Body.String(), allowed.Sqid) {
+ t.Error("picker must show the denied role disabled")
}
if w = b.post("/demo/claim/select", url.Values{"accountId": {denied.Sqid}}); w.Code != 404 {
t.Fatal("forbidden membership accepted")
diff --git a/internal/console/demo_claim_status_page.go b/internal/console/demo_claim_status_page.go
new file mode 100644
index 000000000..7caa821e8
--- /dev/null
+++ b/internal/console/demo_claim_status_page.go
@@ -0,0 +1,56 @@
+package console
+
+import (
+ "net/http"
+ "time"
+)
+
+// The browser's status capability names exactly one operation. It cannot
+// select work, prove identity, or authorize any agent endpoint. SQL only.
+func (s *Server) handleDemoClaimBrowserStatus(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ if !s.demoClaimOrigin(r) || (r.Header.Get("Origin") == "" && r.Header.Get("Sec-Fetch-Site") != "same-origin") {
+ jsonError(w, http.StatusForbidden, demoClaimWrongSite)
+ return
+ }
+ if r.URL.RawQuery != "" {
+ jsonError(w, http.StatusBadRequest, demoClaimBadRequest)
+ return
+ }
+ if s.cfg.HostClaim || s.store.claimGated() {
+ jsonError(w, http.StatusServiceUnavailable, demoClaimUnavailable)
+ return
+ }
+ raw := demoClaimCookie(r)
+ var hash string
+ now := time.Now().Unix()
+ err := s.store.db.QueryRowContext(r.Context(), `SELECT flow_hash FROM demo_claim_browsers WHERE hash=? AND purpose=? AND expires_at>?`, hashToken(raw), demoClaimBrowserStatusPurpose, now).Scan(&hash)
+ if raw == "" || err != nil {
+ jsonError(w, http.StatusUnauthorized, demoClaimIntentExpired)
+ return
+ }
+ op, err := s.store.demoClaimOpForFlow(r.Context(), hash)
+ if err != nil || !demoClaimResultExpiry(op).After(time.Now()) {
+ jsonError(w, http.StatusUnauthorized, demoClaimIntentExpired)
+ return
+ }
+ state, step := demoClaimProgressStep(op.Phase)
+ body := map[string]any{"state": state, "step": step}
+ if state == "claimed" {
+ body["url"] = "https://" + op.Target.Host
+ }
+ demoClaimReply(w, http.StatusOK, body)
+}
+
+func demoClaimProgressStep(phase string) (string, int) {
+ switch phase {
+ case "verifying", "committed":
+ return "claiming", 2
+ case "done":
+ return "claimed", 3
+ case "aborted":
+ return "aborted", 0
+ default:
+ return "claiming", 1
+ }
+}
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js
index 1fc375de6..d0211ab72 100644
--- a/internal/console/static/demo_claim.js
+++ b/internal/console/static/demo_claim.js
@@ -9,6 +9,63 @@
}
});
}
+ const choice = document.querySelector('form[action="/demo/claim/select"]');
+ if (choice) {
+ const radios = choice.querySelectorAll('input[type="radio"]:not(:disabled)');
+ const button = choice.querySelector('button[type="submit"]');
+ const update = () => {
+ const selected = choice.querySelector('input[type="radio"]:checked:not(:disabled)');
+ button.disabled = !selected;
+ button.textContent = selected ? selected.dataset.button : button.dataset.neutral;
+ };
+ if (radios.length) {
+ choice.addEventListener("change", update);
+ update();
+ }
+ }
+ const progress = document.getElementById("claim-progress");
+ if (progress && !token) {
+ const status = document.getElementById("claim-status");
+ const reload = document.getElementById("claim-reload");
+ const labels = ["", progress.dataset.copying, progress.dataset.starting, progress.dataset.done];
+ let failures = 0;
+ reload.hidden = true;
+ const poll = async () => {
+ try {
+ const response = await fetch("/demo/claim/status", {
+ credentials: "same-origin", mode: "same-origin", cache: "no-store",
+ signal: AbortSignal.timeout(10000)
+ });
+ if (!response.ok) throw new Error();
+ const result = await response.json();
+ if (result.state === "aborted" && result.step === 0) {
+ for (const step of progress.querySelectorAll("[data-step]")) step.removeAttribute("aria-current");
+ status.textContent = progress.dataset.aborted;
+ return;
+ }
+ if (!((result.state === "claiming" && [1, 2].includes(result.step)) ||
+ (result.state === "claimed" && result.step === 3))) throw new Error();
+ for (const step of progress.querySelectorAll("[data-step]")) {
+ if (Number(step.dataset.step) === result.step) step.setAttribute("aria-current", "step");
+ else step.removeAttribute("aria-current");
+ }
+ status.textContent = labels[result.step];
+ if (result.state === "claimed") {
+ location.replace("/demo/claim");
+ return;
+ }
+ failures = 0;
+ } catch (_) {
+ if (++failures >= 3) {
+ status.textContent = progress.dataset.pollFailed;
+ reload.hidden = false;
+ return;
+ }
+ }
+ setTimeout(poll, 3000);
+ };
+ setTimeout(poll, 3000);
+ }
if (!token) {
const selection = document.querySelector("form[data-auto-submit]");
if (selection) {
diff --git a/internal/console/templates/demo_claim.html b/internal/console/templates/demo_claim.html
index 93bc684a1..fc85359ac 100644
--- a/internal/console/templates/demo_claim.html
+++ b/internal/console/templates/demo_claim.html
@@ -5,40 +5,84 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="referrer" content="origin">
<title>{{.Copy.title}}</title>
-<style>{{template "console_styles" .}}</style>
+<style>{{template "console_styles" .}}
+#claim { max-width: 38rem; overflow-wrap: anywhere; }
+#claim .claim-summary { margin: 0 0 2rem; }
+#claim .claim-summary strong, #claim .claim-summary a { display: block; }
+#claim .claim-summary p { margin: 0.5rem 0 0; }
+#claim fieldset { border: 0; min-width: 0; margin: 1.5rem 0; }
+#claim legend { font-weight: 600; margin-bottom: 0.75rem; }
+#claim .claim-card { display: flex; align-items: flex-start; gap: 0.75rem; border: 1px solid var(--rule); border-radius: var(--rst-radius-sm); padding: 1rem; margin: 0 0 0.65rem; cursor: pointer; }
+#claim .claim-card:has(:checked) { background: var(--accent-soft); border-color: var(--accent); }
+#claim .claim-card:has(:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; }
+#claim .claim-card:has(:disabled) { color: var(--muted); background: var(--rst-surface-2); cursor: not-allowed; }
+#claim .claim-card input { flex: none; width: 1.1rem; height: 1.1rem; margin-top: 0.25rem; accent-color: var(--accent); }
+#claim .claim-card strong, #claim .claim-card span span { display: block; }
+#claim .claim-detail { color: var(--muted); font-size: 0.9rem; }
+#claim .claim-single { margin: 1.5rem 0; }
+#claim .claim-single p { margin-bottom: 0.35rem; }
+#claim .claim-unavailable { font-size: 0.9rem; }
+#claim button, #claim .btn { box-shadow: none; }
+#claim button[type=submit] { margin-top: 0.5rem; }
+#claim .claim-steps { list-style: decimal; padding-left: 1.6rem; margin: 1.5rem 0; }
+#claim .claim-steps li { padding: 0.6rem 0 0.6rem 0.4rem; color: var(--muted); }
+#claim .claim-steps [aria-current=step] { color: var(--ink); font-weight: 600; }
+#claim .claim-steps [aria-current=step]::marker { color: var(--accent); }
+@media (prefers-reduced-motion: reduce) { #claim button, #claim .btn { transition: none; } }
+#claim .claim-result { margin: 1.5rem 0; }
+#claim .claim-result .btn { display: inline-block; padding: 0.65rem 1.25rem; }
+</style>
</head>
<body>
{{template "console_header" .Chrome}}
<main id="claim" data-failed="{{.Copy.failed}}">
<h1>{{.Copy.title}}</h1>
+{{if .DemoName}}<div class="claim-summary">
+<strong>{{.DemoName}}</strong><a href="https://{{.DemoHost}}" rel="noreferrer">{{.DemoHost}}</a>
+<p>{{.Copy.saved}} {{.Permanent}}</p>
+</div>{{end}}
{{if .Error}}<p role="alert">{{.Error}}</p><p><a href="/demo/claim">{{.Copy.back}}</a></p>{{end}}
-{{if eq .State "no_accounts"}}<p>{{.Copy.noAccounts}}</p>{{end}}
+{{if eq .State "no_accounts"}}<p>{{.Copy.noAccounts}}</p>
+<fieldset class="claim-unavailable"><legend>{{.Copy.unavailableAccounts}}</legend>{{range .Accounts}}{{template "claim_card" .}}{{end}}</fieldset>{{end}}
<input type="hidden" name="nonce" value="{{.Nonce}}">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<p id="claim-error" role="alert" tabindex="-1" hidden></p>
{{if eq .State "missing"}}<p>{{.Copy.missing}}</p>{{end}}
{{if eq .State "disabled"}}<p>{{.Copy.disabled}}</p>{{end}}
-{{if eq .State "claiming"}}<p role="status">{{.Copy.working}}</p><a href="/demo/claim">{{.Copy.reload}}</a>{{end}}
+{{if eq .State "claiming"}}
+<div id="claim-progress" data-copying="{{.Copy.copying}}" data-starting="{{.Copy.starting}}" data-done="{{.Copy.done}}" data-aborted="{{.Copy.aborted}}" data-poll-failed="{{.Copy.pollFailed}}">
+<ol class="claim-steps">
+<li data-step="1"{{if eq .Step 1}} aria-current="step"{{end}}>{{.Copy.copying}}</li>
+<li data-step="2"{{if eq .Step 2}} aria-current="step"{{end}}>{{.Copy.starting}}</li>
+<li data-step="3"{{if eq .Step 3}} aria-current="step"{{end}}>{{.Copy.done}}</li>
+</ol>
+<p id="claim-status" role="status" aria-live="polite">{{if eq .Step 2}}{{.Copy.starting}}{{else}}{{.Copy.copying}}{{end}}</p>
+<a id="claim-reload" href="/demo/claim">{{.Copy.reload}}</a>
+</div>{{end}}
{{if eq .State "aborted"}}<p>{{.Copy.aborted}}</p>{{end}}
{{if eq .State "claimed"}}
<p role="status">{{.Copy.complete}}</p>
-<dl><dt>{{.Copy.account}}</dt><dd>{{.AccountID}}</dd><dt>{{.Copy.app}}</dt><dd>{{.App}}</dd></dl>
-<p><a href="{{.URL}}" rel="noreferrer">{{.Copy.url}}</a></p><p>{{.Copy.next}}</p>
+<p class="claim-result"><a class="btn" href="{{.URL}}" rel="noreferrer">{{.Copy.url}}</a></p>
+<p><strong>{{.App}}</strong></p><p>{{.Copy.oldAddress}}</p><p>{{.Copy.next}}</p>
{{end}}
{{if and .HasIntent .CanClaim}}
{{if .Address}}
<p>{{.Copy.identity}} <strong>{{.Address}}</strong></p>
<form method="post" action="/demo/claim/select"{{if .AutoSubmit}} data-auto-submit{{end}}>
<input type="hidden" name="nonce" value="{{.Nonce}}"><input type="hidden" name="csrf" value="{{.CSRF}}">
-{{if .Accounts}}
-<label for="account">{{.Copy.account}}</label>
-<select id="account" name="accountId" required>
-{{if gt (len .Accounts) 1}}<option value=""{{if not .SelectedAccount}} selected{{end}} disabled>{{.Copy.choose}}</option>{{end}}
-{{range .Accounts}}<option value="{{.Sqid}}"{{if eq .Sqid $.SelectedAccount}} selected{{end}}>{{.Name}} ({{.Sqid}})</option>{{end}}
-</select>
+{{if .Single}}
+<div class="claim-single"><p><strong>{{.Copy.destination}}</strong></p>{{with .Single.Plan}}<p class="claim-detail">{{.}}</p>{{end}}{{with .Single.Room}}<p class="claim-detail">{{.}}</p>{{end}}</div>
+<input type="hidden" name="accountId" value="{{.Single.Sqid}}">
+{{if gt (len .Accounts) 1}}<fieldset class="claim-unavailable"><legend>{{.Copy.unavailableAccounts}}</legend>{{range .Accounts}}{{if .Reason}}{{template "claim_card" .}}{{end}}{{end}}</fieldset>{{end}}
+{{else if .Accounts}}
+<fieldset><legend>{{.Copy.choose}}</legend>
+{{range .Accounts}}
+<label class="claim-card"><input type="radio" name="accountId" value="{{.Sqid}}"{{if eq .Sqid $.SelectedAccount}} checked{{end}}{{if .Reason}} disabled{{else}} required{{end}} data-button="{{.Button}}">
+<span><strong>{{.Name}}</strong>{{with .Plan}}<span class="claim-detail">{{.}}</span>{{end}}{{with .Room}}<span class="claim-detail">{{.}}</span>{{end}}{{with .Reason}}<span>{{.}}</span>{{end}}</span></label>
+{{end}}</fieldset>
{{else}}<p>{{.Copy.new}}</p><input type="hidden" name="create" value="1">{{end}}
<p id="claim-resuming" role="status" hidden>{{.Copy.resuming}}</p>
-<button type="submit">{{.Copy.confirm}}</button>
+<button type="submit" data-neutral="{{.Copy.confirm}}">{{.Copy.confirm}}</button>
</form>
{{else}}
<form method="post" action="/demo/claim/prove">
@@ -57,8 +101,13 @@
<p><a href="/?next=%2Fdemo%2Fclaim">{{.Copy.signin}}</a></p>
{{end}}
{{end}}
-<noscript><p>{{.Copy.noscript}}</p></noscript>
+{{if eq .State "missing"}}<noscript><p>{{.Copy.noscript}}</p></noscript>{{end}}
</main>
<script src="{{asset "demo_claim.js"}}"></script>
</body>
</html>
+
+{{define "claim_card"}}
+<label class="claim-card"><input type="radio" name="accountId" value="{{.Sqid}}" disabled>
+<span><strong>{{.Name}}</strong>{{with .Plan}}<span class="claim-detail">{{.}}</span>{{end}}{{with .Room}}<span class="claim-detail">{{.}}</span>{{end}}<span>{{.Reason}}</span></span></label>
+{{end}}
diff --git a/internal/console/testdata/demo_claim_resume_browser.mjs b/internal/console/testdata/demo_claim_resume_browser.mjs
index 37411e6a2..2102f2521 100644
--- a/internal/console/testdata/demo_claim_resume_browser.mjs
+++ b/internal/console/testdata/demo_claim_resume_browser.mjs
@@ -2,7 +2,7 @@ import {spawn} from 'node:child_process';
import assert from 'node:assert/strict';
import {writeFile} from 'node:fs/promises';
-const [binary, profile, target, sessionToken, flowCookie, account, screenshots] = process.argv.slice(2);
+const [binary, profile, target, sessionToken, flowCookie, account, screenshots, singleJSON] = 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',
@@ -10,7 +10,7 @@ const chrome = spawn(binary, ['--headless', '--no-sandbox', '--disable-gpu',
'--user-data-dir=' + profile], {stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe']});
let sequence = 0, buffered = '', session;
const pending = new Map();
-let security = [];
+let security = [], statusRequests = 0;
const submissions = [];
chrome.stdio[4].on('data', bytes => {
@@ -19,6 +19,7 @@ chrome.stdio[4].on('data', bytes => {
while ((end = buffered.indexOf('\0')) !== -1) {
const message = JSON.parse(buffered.slice(0, end));
buffered = buffered.slice(end + 1);
+ if (message.method === 'Network.requestWillBeSent' && new URL(message.params.request.url).pathname === '/demo/claim/status') statusRequests++;
if (message.method === 'Log.entryAdded' && message.params.entry.source === 'security') security.push(message.params.entry.text);
if (message.method === 'Runtime.bindingCalled' && message.params.name === 'claimSubmitted') submissions.push(JSON.parse(message.params.payload));
const resolve = pending.get(message.id);
@@ -49,7 +50,21 @@ async function key(key, code, number) {
await call('Input.dispatchKeyEvent', {type:key === 'Enter' ? 'keyDown' : 'rawKeyDown', key, code, windowsVirtualKeyCode:number, ...(key === 'Enter' ? {text:'\r', unmodifiedText:'\r'} : {})});
await call('Input.dispatchKeyEvent', {type:'keyUp', key, code, windowsVirtualKeyCode:number});
}
-const timer = setTimeout(() => { chrome.kill('SIGKILL'); process.exitCode = 1; }, 35000);
+async function capture(state) {
+ for (const width of [360,1100]) {
+ await call('Emulation.setDeviceMetricsOverride',{width,height:900,deviceScaleFactor:1,mobile:false});
+ for (const scheme of ['light','dark']) {
+ await call('Emulation.setEmulatedMedia',{features:[{name:'prefers-color-scheme',value:scheme},{name:'prefers-reduced-motion',value:'reduce'}]});
+ await new Promise(r=>setTimeout(r,150));
+ assert.equal(await evaluate('document.documentElement.scrollWidth <= innerWidth'),true,state+' overflows at '+width);
+ if (screenshots) {
+ const shot=await call('Page.captureScreenshot',{format:'png',captureBeyondViewport:true});
+ await writeFile(screenshots+'/'+state+'-'+scheme+'-'+width+'.png',Buffer.from(shot.data,'base64'));
+ }
+ }
+ }
+}
+const timer = setTimeout(() => { chrome.kill('SIGKILL'); process.exitCode = 1; }, 85000);
try {
const created = await call('Target.createTarget', {url:'about:blank'}, false);
session = (await call('Target.attachToTarget', {targetId:created.targetId, flatten:true}, false)).sessionId;
@@ -70,19 +85,30 @@ try {
}));
});
`});
+ const single = JSON.parse(singleJSON);
+ await call('Network.setCookies', {cookies:[
+ {name:'carlos_console_session',value:single.session,url:single.target,path:'/',httpOnly:true,sameSite:'Lax'},
+ {name:'carlos_demo_claim_flow',value:single.cookie,url:single.target,path:'/demo/claim',httpOnly:true,secure:true,sameSite:'Lax'}
+ ]});
+ await call('Page.navigate',{url:single.target+'/demo/claim'});
+ await until('document.readyState === "complete" && !!document.querySelector("#claim input[type=hidden][name=accountId]")');
+ assert.equal(await evaluate('document.querySelectorAll("#claim input[type=radio]").length'),0);
+ assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").textContent'),'Keep in shop');
+ await capture('one');
await call('Network.setCookies', {cookies:[
{name:'carlos_console_session',value:sessionToken,url:target,path:'/',httpOnly:true,sameSite:'Lax'},
{name:'carlos_demo_claim_flow',value:flowCookie,url:target,path:'/demo/claim',httpOnly:true,secure:true,sameSite:'Lax'}
]});
await call('Network.setBlockedURLs', {urls:['*demo_claim.js*']});
await call('Page.navigate', {url:target+'/demo/claim'});
- await until('document.readyState === "complete" && !!document.querySelector("select[name=accountId]")');
+ await until('document.readyState === "complete" && !!document.querySelector("input[type=radio][name=accountId]")');
assert.equal(await evaluate('document.querySelector("button[type=submit]").disabled'),false,'script failure disabled the manual fallback');
assert.equal(await evaluate('document.querySelector("form").getBoundingClientRect().height > 0'),true,'script failure hid the form');
+ assert.equal(await evaluate('document.querySelector("#claim form").checkValidity()'),false,'native required radio missing');
await call('Network.setBlockedURLs', {urls:[]});
await call('Page.navigate', {url:target+'/demo/claim?csp=before'});
- await until('!!document.querySelector("select[name=accountId]")');
- await evaluate(`document.querySelector('select').value = ${JSON.stringify(account)}; document.querySelector('form[action="/demo/claim/select"]').requestSubmit()`);
+ await until('document.readyState === "complete" && !!document.querySelector("input[type=radio][name=accountId]")');
+ await evaluate(`document.querySelector('input[value='+${JSON.stringify(account)}+']').click(); document.querySelector('form[action="/demo/claim/select"]').requestSubmit()`);
for (let i=0; i<50 && !security.some(s=>s.includes('form-action')); i++) await new Promise(r=>setTimeout(r,100));
assert(security.some(s=>s.includes('form-action')), 'Chromium did not reproduce redirect CSP block: '+JSON.stringify(security));
assert.equal(await evaluate('location.origin'), target);
@@ -90,17 +116,22 @@ try {
security = [];
submissions.length = 0;
await call('Page.navigate', {url:target+'/demo/claim'});
- await until('!!document.querySelector("select[name=accountId]")');
- await evaluate(`document.querySelector('select').value = ${JSON.stringify(account)}`);
+ await until('document.readyState === "complete" && !!document.querySelector("input[type=radio][name=accountId]")');
+ assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").disabled'),true);
+ assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").textContent'),'Keep this demo');
+ await evaluate('document.querySelector("#claim input[type=radio]:not(:disabled)").focus()');
+ await key(' ', 'Space', 32);
+ await until('!!document.querySelector("#claim input[type=radio]:checked")');
+ const firstLabel = await evaluate('document.querySelector("#claim button[type=submit]").textContent');
+ await key('ArrowDown','ArrowDown',40);
+ assert.notEqual(await evaluate('document.querySelector("#claim button[type=submit]").textContent'), firstLabel);
+ assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").disabled'),false);
+ assert.equal(await evaluate('!!document.querySelector("#claim input:disabled:checked")'),false);
+ assert.equal(await evaluate('getComputedStyle(document.activeElement.closest("label")).outlineStyle'),'solid');
+ await evaluate(`document.querySelector('input[value='+${JSON.stringify(account)}+']').click()`);
assert.equal(await evaluate('document.querySelectorAll("script").length'),1);
- if (screenshots) {
- for (const scheme of ['light','dark']) {
- await call('Emulation.setEmulatedMedia',{features:[{name:'prefers-color-scheme',value:scheme}]});
- await new Promise(r=>setTimeout(r,150));
- const shot = await call('Page.captureScreenshot',{format:'png',captureBeyondViewport:true});
- await writeFile(screenshots+'/'+scheme+'.png',Buffer.from(shot.data,'base64'));
- }
- }
+ assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").textContent'), 'Keep in Personal projects');
+ await capture('many');
await evaluate(`const button = document.querySelector('form[action="/demo/claim/select"] button'); button.click(); button.click()`);
await until(`!!document.querySelector("p[role=status]") && !document.querySelector('form[action="/demo/claim/select"]')`);
assert.equal(await evaluate('location.pathname'),'/demo/claim');
@@ -110,7 +141,41 @@ try {
{disabled:true,visible:true,auto:false,account},
{disabled:true,visible:true,auto:true,account}
],'manual and automatic submissions must disable the button, retain the form and preserve the selected account');
- process.stdout.write('after: redirect, callback, JS auto-submit, claiming state; no CSP violations\n');
+ process.stdout.write('after: keyboard choice, redirect, callback, JS auto-submit; no CSP violations\n');
+ await until('document.querySelector("li[aria-current=step]")?.dataset.step === "2"');
+ assert.equal(await evaluate('document.getElementById("claim-status").textContent'),'Starting your app');
+ await capture('progress');
+ await until('!!document.querySelector(".claim-result a")');
+ await capture('done');
+ assert.equal(await evaluate('document.querySelector(".claim-result a").textContent'),'Open app');
+ assert.equal(security.length,0,JSON.stringify(security));
+ process.stdout.write('progress: polled to step 2 and done automatically; no CSP violations\n');
+ const requestsAtDone=statusRequests;
+ await new Promise(r=>setTimeout(r,3500));
+ assert.equal(statusRequests,requestsAtDone,'done kept polling');
+ await call('Page.navigate',{url:target+'/demo/claim?testProgress=fail'});
+ await until('!!document.getElementById("claim-progress")');
+ const beforeFailure=statusRequests;
+ await until('document.getElementById("claim-reload")?.hidden === false');
+ assert.equal(statusRequests-beforeFailure,3,'did not stop after three failures');
+ assert.equal(await evaluate('document.getElementById("claim-status").textContent'),await evaluate('document.getElementById("claim-progress").dataset.pollFailed'));
+ assert.equal(await evaluate('document.querySelectorAll("#claim img").length'),0,'untrusted status rendered markup');
+ await new Promise(r=>setTimeout(r,3500));
+ assert.equal(statusRequests-beforeFailure,3,'failure fallback kept polling');
+ await call('Network.setBlockedURLs',{urls:['*demo_claim.js*']});
+ await call('Page.navigate',{url:target+'/demo/claim'});
+ await until('document.readyState === "complete" && !!document.getElementById("claim-reload")');
+ assert.equal(await evaluate('document.getElementById("claim-reload").getBoundingClientRect().height > 0'),true,'no-script reload link hidden');
+ await call('Network.setBlockedURLs',{urls:[]});
+ await call('Page.navigate',{url:target+'/demo/claim?testProgress=abort'});
+ await until('!!document.getElementById("claim-progress")');
+ const beforeAbort=statusRequests;
+ await until('document.getElementById("claim-status")?.textContent === document.getElementById("claim-progress")?.dataset.aborted');
+ assert.equal(await evaluate('document.querySelectorAll("[aria-current=step]").length'),0);
+ await new Promise(r=>setTimeout(r,3500));
+ assert.equal(statusRequests-beforeAbort,1,'aborted kept polling');
+ assert.equal(security.length,0,JSON.stringify(security));
+ process.stdout.write('fallback: stopped after three failures, retained no-script reload, stopped on abort; no CSP violations\n');
} finally {
clearTimeout(timer);
const closed = new Promise(resolve => chrome.once('exit',resolve));