demo claims: account cards, live progress and a clear result
The claim page shows what is being kept, accounts as cards with plan and room, a button naming the account, progress that updates by itself through a status-only browser door, and a result with the new address. Squashed from demo-claim-account-ui into main.
15 files changed,
+1,196
−66
docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-CLAIM-ACCOUNT-UI.md+34 −0docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-CLAIM-ACCOUNT-UI.md+22 −0internal/console/apidemo.go+1 −0internal/console/demo_claim_browser_test.go+1 −1internal/console/demo_claim_choice_test.go+537 −0internal/console/demo_claim_copy.go+37 −10internal/console/demo_claim_page.go+112 −15internal/console/demo_claim_ready_test.go+1 −1internal/console/demo_claim_resume_browser_test.go+117 −3internal/console/demo_claim_resume_test.go+2 −2internal/console/demo_claim_review_test.go+2 −2internal/console/demo_claim_status_page.go+60 −0internal/console/static/demo_claim.js+67 −0internal/console/templates/demo_claim.html+64 −15internal/console/testdata/demo_claim_resume_browser.mjs+139 −17
CI passed — run details
diff --git a/docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-CLAIM-ACCOUNT-UI.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-CLAIM-ACCOUNT-UI.md| new file mode 100644 |
| index 000000000..ac0718137 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-CLAIM-ACCOUNT-UI.md |
| @@ -0,0 +1,34 @@ |
| +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. |
| + |
| +The page: a person keeps a temporary 24-hour demo as a permanent app. They choose an account on a page in a web console. Accounts appear as cards. They press a button naming the account, then watch progress steps, then see the result. The audience is a person, often not technical. |
| + |
| +Facts that must stay true: |
| +- The app keeps its data. Its address changes; the exact name can have a suffix, so only the domain is promised before the claim. |
| +- A claim needs room for 2 under the plan: one app plus its instance. The plan copy elsewhere calls them "apps and instances"; keep that term. |
| +- The old address shows a short notice with a link until the demo's original 24 hours end. It does not forward automatically. |
| +- A new personal account is made only if they have none. Plan limits apply; no payment happens here. |
| + |
| +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. Labels, headings and button text have no full stop. Keep %s and %d placeholders, their number and order. Do not name the product. |
| + |
| +Answer with one markdown table, `| key | new | why |`, one row per deck row in deck order, `unchanged` in why when you keep a string. Then a short **Flags** list only if needed. Nothing else. |
| + |
| +## Deck |
| + |
| +| key | Surface | Draft | |
| +|---|---|---| |
| +| demoClaimNewAccount | CLAIM-ACCOUNT-NEW: zero membership confirmation. | We will create a personal account and keep this demo in it. | |
| +| demoClaimNoEligibleAccount | CLAIM-ACCOUNT-NONE: memberships exist but none can take the claim. | None of your accounts can take this demo right now. | |
| +| demoClaimUnavailableAccounts | CLAIM-UNAVAILABLE-ACCOUNTS: the disabled account list. | Unavailable accounts | |
| +| demoClaimSaved | CLAIM-SAVED: what the person keeps. | Its saved data comes with it. | |
| +| demoClaimPermanent | CLAIM-PERMANENT: domain only; the eventual name may need a suffix. | It gets a permanent address on %s. | |
| +| demoClaimDestination | CLAIM-DESTINATION: the only eligible account. | This goes into %s | |
| +| demoClaimKeepIn | CLAIM-KEEP-IN: action after choosing an account. | Keep in %s | |
| +| demoClaimHasRoom | CLAIM-ROOM-AVAILABLE: the account has room for the app and its instance. | Has room | |
| +| demoClaimFull | CLAIM-ROOM-FULL: current use is at or above the catalog cap. | Full: %d of %d apps and instances in use | |
| +| demoClaimNoRoom | CLAIM-ROOM-INSUFFICIENT: one slot remains, but the claim needs two. | Not enough room: %d of %d apps and instances in use. This demo needs room for 2. | |
| +| demoClaimRoleDenied | CLAIM-ROLE-DENIED: membership cannot create apps. | Your role cannot create apps in this account. | |
| +| demoClaimCopying | CLAIM-STEP-COPYING: first progress step. | Copying your data | |
| +| demoClaimStarting | CLAIM-STEP-STARTING: second progress step. | Starting your app | |
| +| demoClaimDone | CLAIM-STEP-DONE: final progress step. | Done | |
| +| demoClaimPollFailed | CLAIM-POLL-FAILED: repeated status failures, with a reload link. | Progress could not be checked. Reload to try again. | |
| +| demoClaimOldAddress | CLAIM-OLD-ADDRESS: notice lifetime, without a redirect promise. | The old address shows a short notice with a link to this app until the demo's original expiry. | |
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-CLAIM-ACCOUNT-UI.md b/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-CLAIM-ACCOUNT-UI.md| new file mode 100644 |
| index 000000000..5eeb04bbe |
| --- /dev/null |
| +++ b/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-CLAIM-ACCOUNT-UI.md |
| @@ -0,0 +1,22 @@ |
| +| key | new | why | |
| +|---|---|---| |
| +| demoClaimNewAccount | We will create a personal account only if you do not have one. We will keep this demo in it. | Makes clear an account is created only when needed. | |
| +| demoClaimNoEligibleAccount | None of your accounts can take this demo right now. | unchanged | |
| +| demoClaimUnavailableAccounts | Unavailable accounts | unchanged | |
| +| demoClaimSaved | Its saved data comes with it. | unchanged | |
| +| demoClaimPermanent | It gets a permanent address on %s. | unchanged | |
| +| demoClaimDestination | This goes into %s. | Adds the required full stop. | |
| +| demoClaimKeepIn | Keep in %s | unchanged | |
| +| demoClaimHasRoom | Has room | unchanged | |
| +| demoClaimFull | Full: %d of %d apps and instances in use | unchanged | |
| +| demoClaimNoRoom | Not enough room: %d of %d apps and instances in use. This demo needs room for one app and its instance. | Clarifies what the two spaces are for. | |
| +| demoClaimRoleDenied | Your role cannot create apps in this account. | unchanged | |
| +| demoClaimCopying | Copying your data | unchanged | |
| +| demoClaimStarting | Starting your app | unchanged | |
| +| demoClaimDone | Done | unchanged | |
| +| demoClaimPollFailed | Progress could not be checked. Reload to try again. | unchanged | |
| +| demoClaimOldAddress | The old address shows a short notice with a link to this app until the demo's original 24 hours end. | States the notice lasts only until the original 24 hours end, without promising a redirect. | |
| +| key | new | why | |
| +|---|---|---| |
| +| demoClaimNewAccount | You don't have an account yet. We will create a personal one and keep this demo in it. | unchanged | |
| +| demoClaimStopping | The claim did not finish. The demo is not serving its pages while we undo the claim. When this finishes, the demo resumes if its 24 hours have not ended. | The draft promises the demo stays paused until undo finishes but omits what happens afterward. The replacement avoids promising that the demo is safe or will return. | |
| \ No newline at end of file |
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..2e64d73aa |
| --- /dev/null |
| +++ b/internal/console/demo_claim_choice_test.go |
| @@ -0,0 +1,537 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "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}, {"aborting", "stopping", 0}, {"future-phase", "claiming", 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) |
| + } |
| + page := request(raw, "/demo/claim", "same-origin").Body.String() |
| + if tc.step == 0 { |
| + if strings.Contains(page, `aria-current="step"`) { |
| + t.Errorf("%s marks a progress step", tc.phase) |
| + } |
| + if tc.state != "aborted" && !strings.Contains(page, `id="claim-progress"`) { |
| + t.Errorf("%s lost polling", tc.phase) |
| + } |
| + } |
| + if tc.state == "stopping" && !strings.Contains(page, "The claim did not finish. The demo is not serving its pages while we undo the claim.") { |
| + t.Error("missing stopping explanation") |
| + } |
| + 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) |
| + } |
| + } |
| + |
| +} |
| + |
| +// 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, room string |
| + }{ |
| + {"fits exactly", RoleOwner, 0, true, false, "", "Has room"}, |
| + {"needs two slots", RoleMember, 1, true, false, "Not enough room: 2 of 3 apps and instances in use. This demo needs room for one app and its instance.", ""}, |
| + {"full", RoleOwner, 2, true, false, "Full: 3 of 3 apps and instances in use", ""}, |
| + {"over limit", RoleOwner, 3, true, false, "Full: 4 of 3 apps and instances in use", ""}, |
| + {"role", "viewer", 0, true, false, demoClaimRoleDenied, ""}, |
| + {"role at limit", "viewer", 2, 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") |
| + } |
| + if !strings.Contains(body, "You are signed in as") || !strings.Contains(body, `<span class="claim-detail">`+tc.reason+"</span>") { |
| + t.Error("no_accounts missing identity or muted reason") |
| + } |
| + } else if !strings.Contains(body, `type="hidden" name="accountId" value="`+a.Sqid+`"`) { |
| + t.Error("eligible account lost") |
| + } |
| + choice := s.demoClaimAccountView(t.Context(), *a, true) |
| + if choice.Room != tc.room || choice.Reason != tc.reason { |
| + t.Errorf("room/reason = %q / %q; want %q / %q", choice.Room, choice.Reason, tc.room, tc.reason) |
| + } |
| + if tc.room != "" && strings.Count(body, ">"+tc.room+"<") != 1 { |
| + t.Errorf("single account must show exactly one %q line", tc.room) |
| + } |
| + if tc.reason == "" || tc.role == "viewer" { |
| + if strings.Contains(body, "apps and instances") { |
| + t.Error("eligible or role-disabled account shows counts") |
| + } |
| + } else if strings.Count(body, tc.reason) != 1 { |
| + t.Error("capacity reason must appear once") |
| + } |
| + if (!tc.plans || tc.role == "viewer") && spy.calls.Load() != 0 { |
| + t.Error("plans off or role-disabled account read store") |
| + } |
| + if tc.plans && !tc.fail && tc.role != "viewer" { |
| + if !strings.Contains(body, ">Free<") { |
| + t.Error("missing plan") |
| + } |
| + if isPlanCap(s.checkRunningThings(t.Context(), a, 2)) != (tc.instances >= 1) { |
| + t.Error("hint differs from reservation") |
| + } |
| + } |
| + // 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 |
| +} |
| + |
| +func TestDemoClaimProgressAndOutcome(t *testing.T) { |
| + for _, state := range []string{"claiming", "claimed"} { |
| + t.Run(state, func(t *testing.T) { |
| + var rendered bytes.Buffer |
| + address := "https://a-long-permanent-app-name.account.apps.example.com" |
| + if err := demoClaimPageTemplate.ExecuteTemplate(&rendered, "demo_claim.html", demoClaimPageData{Copy: demoClaimBrowserCopy(), State: state, Step: 2, URL: address}); err != nil { |
| + t.Fatal(err) |
| + } |
| + body := rendered.String() |
| + if state == "claiming" { |
| + if !strings.Contains(body, `id="claim-status" class="claim-sr-only" role="status" aria-live="polite"`) || !strings.Contains(body, "#claim .claim-sr-only") { |
| + t.Error("live status must use the scoped screen-reader-only class") |
| + } |
| + if !strings.Contains(body, `data-step="2" aria-current="step">Starting your app</li>`) { |
| + t.Error("current step is not marked") |
| + } |
| + } else { |
| + if !strings.Contains(body, "<h1>"+demoClaimComplete+"</h1>") || strings.Count(body, demoClaimComplete) != 1 { |
| + t.Error("outcome must appear once, as the heading") |
| + } |
| + link := regexp.MustCompile(`<a class="btn" href="([^"]+)" rel="noreferrer">([^<]+)</a>`).FindStringSubmatch(body) |
| + if len(link) != 3 || link[1] != address || strings.TrimPrefix(link[2], "https://") != strings.TrimPrefix(address, "https://") { |
| + t.Error("result link must display the permanent address") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type claimBlockingRoomStore struct { |
| + release.Store |
| + calls atomic.Int32 |
| +} |
| + |
| +func (s *claimBlockingRoomStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + s.calls.Add(1) |
| + select { |
| + case <-ctx.Done(): |
| + return nil, ctx.Err() |
| + case <-time.After(3 * time.Second): |
| + return nil, errors.New("test safety timeout") |
| + } |
| +} |
| + |
| +func TestDemoClaimRoomBudget(t *testing.T) { |
| + for _, n := range []int{2, 22} { |
| + 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++ { |
| + a := claimAccount(t, s, int64(501+i), "shop@example.com", RoleOwner) |
| + if _, err := s.store.CreateAppIn(a.ID, "shop", "shop@example.com", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + s.cfg.PlanCatalog = examplePlanCatalog(t) |
| + blocking := &claimBlockingRoomStore{Store: s.cfg.Releases} |
| + counting := &claimRoomStore{Store: s.cfg.Releases} |
| + if n == 2 { |
| + s.cfg.Releases = blocking |
| + } else { |
| + s.cfg.Releases = counting |
| + } |
| + start := time.Now() |
| + w := b.request("GET", "/demo/claim", nil) |
| + elapsed := time.Since(start) |
| + if w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + body := w.Body.String() |
| + if strings.Count(body, ` required`) != n { |
| + t.Error("budget omitted eligible accounts") |
| + } |
| + if n == 2 { |
| + if elapsed > 2700*time.Millisecond { |
| + t.Errorf("page exceeded shared 2s budget: %v", elapsed) |
| + } |
| + if blocking.calls.Load() != 1 { |
| + t.Errorf("counted after deadline: %d", blocking.calls.Load()) |
| + } |
| + if strings.Contains(body, ">Has room<") { |
| + t.Error("unverified room hint") |
| + } |
| + } else { |
| + if counting.calls.Load() != 20 { |
| + t.Errorf("counted %d accounts, want 20", counting.calls.Load()) |
| + } |
| + if strings.Count(body, ">Has room<") != 20 { |
| + t.Error("wrong number of room hints") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimChoiceAdmissionAndExemption(t *testing.T) { |
| + for _, exempt := range []bool{false, true} { |
| + t.Run(fmt.Sprint(exempt), func(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", RoleOwner) |
| + s.cfg.PlanCatalog = examplePlanCatalog(t) |
| + if exempt { |
| + s.store.planExemptID = a.ID |
| + } else { |
| + s.demoClaimTestEnabled = false |
| + s.cfg.Demo.ClaimEnabled = false |
| + } |
| + spy := &claimRoomStore{Store: s.cfg.Releases} |
| + s.cfg.Releases = spy |
| + if _, err := s.store.CreateAppIn(a.ID, "shop", "shop@example.com", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 2; i++ { |
| + if _, err := spy.Put(t.Context(), provision.RecordKey(a.Sqid, "shop", fmt.Sprintf("shop%d.example.com", i)), []byte("{}"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + body := b.request("GET", "/demo/claim", nil).Body.String() |
| + if spy.calls.Load() != 0 { |
| + t.Error("counted unavailable or exempt account") |
| + } |
| + if strings.Contains(body, ">Free<") { |
| + t.Error("false plan label") |
| + } |
| + if !exempt && (!strings.Contains(body, "<p>unavailable</p>") || strings.Contains(body, demoClaimNoEligibleAccount)) { |
| + t.Error("admission-off state replaced by account refusal") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimChoicePrivacy(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", RoleOwner) |
| + if _, err := s.store.db.Exec(`UPDATE accounts SET name='Private account name' WHERE id=?`, a.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + b.session = "" |
| + body := b.request("GET", "/demo/claim", nil).Body.String() |
| + if strings.Contains(body, "Private account name") || strings.Contains(body, a.Sqid) { |
| + t.Error("signed-out account leak") |
| + } |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_flows SET person='someone-else@example.com'`); err != nil { |
| + t.Fatal(err) |
| + } |
| + b.login("shop@example.com", MethodEmail, true) |
| + body = b.request("GET", "/demo/claim", nil).Body.String() |
| + if strings.Contains(body, `<div class="claim-summary">`) || strings.Contains(body, "Private account name") { |
| + t.Error("another person's proved flow revealed summary or accounts") |
| + } |
| +} |
diff --git a/internal/console/demo_claim_copy.go b/internal/console/demo_claim_copy.go| index dcab12abe..d6de609db 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 = "You don't have an account yet. We will create a personal one 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,44 @@ 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-AVAILABLE: the account has room for the app and its instance. |
| + demoClaimHasRoom = "Has room" |
| + // CLAIM-ROOM-FULL: current use is at or above the catalog cap. |
| + demoClaimFull = "Full: %d of %d apps and instances in use" |
| + // CLAIM-ROOM-INSUFFICIENT: one slot remains, but the claim needs two. |
| + demoClaimNoRoom = "Not enough room: %d of %d apps and instances in use. This demo needs room for one app and its instance." |
| + // CLAIM-ROLE-DENIED: membership cannot create apps. |
| + demoClaimRoleDenied = "Your role cannot create apps in this account." |
| + // 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-STOPPING: undoing an unfinished claim. |
| + demoClaimStopping = "The claim did not finish. The demo is not serving its pages while we undo the claim. When this finishes, the demo resumes if its 24 hours have not ended." |
| + // 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 24 hours end." |
| +) |
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go| index bddaa542e..9dee722e5 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,27 +161,41 @@ 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 { |
| + } else if p.CanClaim { |
| var accounts []Account |
| accounts, err = s.store.AccountsFor(address) |
| if err != nil { |
| s.demoClaimBrowserError(w, 503, demoClaimUnavailable) |
| return |
| } |
| - for _, a := range accounts { |
| - if demoClaimCanCreate(a) { |
| + roomCtx, cancelRoom := context.WithTimeout(r.Context(), 2*time.Second) |
| + defer cancelRoom() |
| + for i, a := range accounts { |
| + choice := s.demoClaimAccountView(roomCtx, a, r.Method == http.MethodGet && i < 20) |
| + 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 +524,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, |
| + "stopping": demoClaimStopping, |
| + "aborted": demoClaimAborted, |
| + "disabled": demoClaimUnavailable, |
| + } |
| } |
| func demoClaimCanCreate(a Account) bool { return a.Role == RoleOwner || a.Role == RoleMember } |
| @@ -538,3 +593,45 @@ 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 && !s.store.planExempt(a.ID) { |
| + 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 || c.Reason != "" || ctx.Err() != nil { |
| + return c |
| + } |
| + limits, err := s.EffectiveLimits(&a) |
| + if err != nil || limits == nil { |
| + return c |
| + } |
| + n, err := s.runningThings(ctx, &a) |
| + if err != nil || ctx.Err() != nil { |
| + return c |
| + } |
| + switch { |
| + case n >= limits.RunningThings: |
| + c.Reason = fmt.Sprintf(demoClaimFull, n, limits.RunningThings) |
| + case n+2 > limits.RunningThings: |
| + c.Reason = fmt.Sprintf(demoClaimNoRoom, n, limits.RunningThings) |
| + default: |
| + c.Room = demoClaimHasRoom |
| + } |
| + 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..065f8e69c 100644 |
| --- a/internal/console/demo_claim_resume_browser_test.go |
| +++ b/internal/console/demo_claim_resume_browser_test.go |
| @@ -2,13 +2,18 @@ package console |
| import ( |
| "context" |
| + "encoding/json" |
| + "fmt" |
| "net/http" |
| "net/http/httptest" |
| "os" |
| "os/exec" |
| "strings" |
| + "sync/atomic" |
| "testing" |
| "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| ) |
| func TestDemoClaimSelectStepUpHeadless(t *testing.T) { |
| @@ -23,7 +28,57 @@ 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) |
| + } |
| + phase := "copying" |
| + if r.URL.Query().Get("testProgress") == "stopping" { |
| + mode.Store(3) |
| + phase = "verifying" |
| + } |
| + if r.URL.Query().Get("testProgress") == "unknown" { |
| + mode.Store(4) |
| + phase = "future-phase" |
| + } |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase=?`, phase); 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() == 3 { |
| + phase = "aborting" |
| + if n >= 3 { |
| + phase = "aborted" |
| + } |
| + } |
| + if mode.Load() == 4 { |
| + phase = "future-phase" |
| + } |
| + 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 +102,70 @@ 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(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Query().Has("long") { |
| + if _, err := single.store.db.Exec(`UPDATE accounts SET name=? WHERE id=601`, strings.Repeat("LongAccountName", 10)); err != nil { |
| + t.Error(err) |
| + } |
| + claimAccount(t, single, 602, "shop@example.com", RoleOwner) |
| + host := strings.Repeat("long-demo-", 6) + "." + strings.Repeat("long-domain-", 5) + ".example.com" |
| + if _, err := single.store.db.Exec(`UPDATE demo_apps SET host=?`, host); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + single.mux.ServeHTTP(w, r) |
| + })) |
| + 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) |
| + capacity, _, capacityToken := claimTestServer(t) |
| + capacity.registerRoute("GET /static/{hash}/{file...}", capacity.handleStatic) |
| + capacityServer := httptest.NewServer(capacity.mux) |
| + defer capacityServer.Close() |
| + capacity.cfg.Origin = capacityServer.URL |
| + capacity.cfg.PlanCatalog = examplePlanCatalog(t) |
| + room := newClaimBrowser(t, capacity, capacityToken) |
| + room.login("shop@example.com", MethodEmail, true) |
| + for i, name := range []string{"Full account", "Almost full account"} { |
| + a := claimAccount(t, capacity, int64(701+i), "shop@example.com", RoleOwner) |
| + if _, err := capacity.store.db.Exec(`UPDATE accounts SET name=? WHERE id=?`, name, a.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := capacity.store.CreateAppIn(a.ID, "shop", "shop@example.com", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for j := 0; j < 2-i; j++ { |
| + if _, err := capacity.cfg.Releases.Put(t.Context(), provision.RecordKey(a.Sqid, "shop", fmt.Sprintf("shop%d.example.com", j)), []byte(`{}`), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + singleArgs, _ := json.Marshal(map[string]string{"target": singleServer.URL, "session": one.session, "cookie": one.cookie, |
| + "capacityTarget": capacityServer.URL, "capacitySession": room.session, "capacityCookie": room.cookie}) |
| + ctx, cancel := context.WithTimeout(t.Context(), 120*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..e61ff461d |
| --- /dev/null |
| +++ b/internal/console/demo_claim_status_page.go |
| @@ -0,0 +1,60 @@ |
| +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 "reserved", "freezing", "copying": |
| + return "claiming", 1 |
| + case "aborting": |
| + return "stopping", 0 |
| + case "verifying", "committed": |
| + return "claiming", 2 |
| + case "done": |
| + return "claimed", 3 |
| + case "aborted": |
| + return "aborted", 0 |
| + default: |
| + return "claiming", 0 |
| + } |
| +} |
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js| index 1fc375de6..b1c8f1b34 100644 |
| --- a/internal/console/static/demo_claim.js |
| +++ b/internal/console/static/demo_claim.js |
| @@ -9,6 +9,73 @@ |
| } |
| }); |
| } |
| + 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"]'); |
| + let submitted = false; |
| + choice.addEventListener("submit", () => { submitted = true; }); |
| + const update = () => { |
| + if (submitted) return; |
| + 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.neutral, progress.dataset.copying, progress.dataset.starting, progress.dataset.done]; |
| + const setStatus = text => { |
| + if (status.textContent !== text) status.textContent = text; |
| + }; |
| + 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.classList.remove("claim-sr-only"); |
| + setStatus(progress.dataset.aborted); |
| + return; |
| + } |
| + if (!((result.state === "claiming" && [0, 1, 2].includes(result.step)) || |
| + (result.state === "stopping" && result.step === 0) || |
| + (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.classList.toggle("claim-sr-only", result.step > 0); |
| + setStatus(result.state === "stopping" ? progress.dataset.stopping : labels[result.step]); |
| + if (result.state === "claimed") { |
| + location.replace("/demo/claim"); |
| + return; |
| + } |
| + failures = 0; |
| + } catch (_) { |
| + if (++failures >= 3) { |
| + status.classList.remove("claim-sr-only"); |
| + setStatus(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..1c701b957 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-sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; } |
| +#claim .claim-result { margin: 1.5rem 0; } |
| +#claim .claim-result .btn { display: inline-block; max-width: 100%; white-space: normal; overflow-wrap: anywhere; padding: 0.65rem 1.25rem; } |
| +</style> |
| </head> |
| <body> |
| {{template "console_header" .Chrome}} |
| <main id="claim" data-failed="{{.Copy.failed}}"> |
| -<h1>{{.Copy.title}}</h1> |
| +<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> |
| +<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.identity}} <strong>{{.Address}}</strong></p><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 or (eq .State "claiming") (eq .State "stopping")}} |
| +<div id="claim-progress" data-neutral="{{.Copy.title}}" data-stopping="{{.Copy.stopping}}" 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"{{if gt .Step 0}} class="claim-sr-only"{{end}} role="status" aria-live="polite">{{if eq .State "stopping"}}{{.Copy.stopping}}{{else if eq .Step 2}}{{.Copy.starting}}{{else if eq .Step 1}}{{.Copy.copying}}{{else}}{{.Copy.title}}{{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">{{.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 class="claim-detail">{{.}}</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 class="claim-detail">{{.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..4c08dfecd 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,24 @@ 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 <= document.documentElement.clientWidth'),true,state+' overflows at '+width); |
| + if (state === 'done') { |
| + assert.equal(await evaluate('(() => { const link = document.querySelector(".claim-result a"); const rect = link.getBoundingClientRect(); return rect.left >= 0 && rect.right <= innerWidth && link.scrollWidth <= link.clientWidth; })()'),true,'result address 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; }, 115000); |
| 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 +88,49 @@ 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'); |
| + assert.equal(await evaluate('document.querySelector(".claim-single").innerText.includes("Has room")'),true); |
| + assert.equal(await evaluate('document.querySelector(".claim-single").innerText.includes("apps and instances")'),false); |
| + await capture('one'); |
| + await call('Page.navigate',{url:single.target+'/demo/claim?long=1'}); |
| + await until('document.readyState === "complete" && document.querySelectorAll(".claim-card").length === 2'); |
| + assert.equal(await evaluate('document.querySelector(".claim-card strong").textContent.length > 100'), true); |
| + assert.equal(await evaluate('document.querySelector(".claim-summary a").textContent.length > 100'), true); |
| + await evaluate('document.querySelector(".claim-card input").click()'); |
| + await capture('long-name'); |
| + await call('Network.setCookies', {cookies:[ |
| + {name:'carlos_console_session',value:single.capacitySession,url:single.capacityTarget,path:'/',httpOnly:true,sameSite:'Lax'}, |
| + {name:'carlos_demo_claim_flow',value:single.capacityCookie,url:single.capacityTarget,path:'/demo/claim',httpOnly:true,secure:true,sameSite:'Lax'} |
| + ]}); |
| + await call('Page.navigate',{url:single.capacityTarget+'/demo/claim'}); |
| + await until('document.readyState === "complete" && document.querySelectorAll(".claim-card").length === 2'); |
| + const capacityCards = await evaluate('Array.from(document.querySelectorAll(".claim-card"), card => ({text:card.innerText,disabled:card.querySelector("input").disabled}))'); |
| + assert(capacityCards.every(card=>card.disabled)); |
| + assert(capacityCards.some(card=>card.text.includes('Full: 3 of 3 apps and instances in use'))); |
| + assert(capacityCards.some(card=>card.text.includes('Not enough room: 2 of 3 apps and instances in use. This demo needs room for one app and its instance.'))); |
| + await capture('capacity'); |
| 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 +138,30 @@ 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'); |
| + assert.equal(await evaluate('Array.from(document.querySelectorAll(".claim-card:has(input:not(:disabled))")).every(card => card.innerText.includes("Has room") && !card.innerText.includes("apps and instances"))'),true); |
| + assert.deepEqual(await evaluate('Array.from(document.querySelectorAll(".claim-card:has(input:disabled) .claim-detail")).map(el => el.textContent)'),['Free', 'Your role cannot create apps in this account.']); |
| + await capture('many'); |
| + await evaluate(`const form = document.querySelector('form[action="/demo/claim/select"]'); form.addEventListener('submit', event => event.preventDefault(), {once:true}); form.requestSubmit(); document.querySelector('#claim input[type=radio]:not(:disabled)').click()`); |
| + assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").disabled'),true,'radio change re-enabled submitted button'); |
| + await call('Page.navigate', {url:target+'/demo/claim'}); |
| + await until('document.readyState === "complete" && !!document.querySelector("input[type=radio][name=accountId]")'); |
| + await evaluate(`document.querySelector('input[value='+${JSON.stringify(account)}+']').click()`); |
| + submissions.length = 0; |
| 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 +171,68 @@ 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'); |
| + assert.equal(await evaluate('document.getElementById("claim-status").getAttribute("aria-live")'),'polite'); |
| + assert.equal(await evaluate('getComputedStyle(document.getElementById("claim-status")).clipPath'),'inset(50%)'); |
| + assert.equal(await evaluate('document.querySelector("li[aria-current=step]").getBoundingClientRect().height > 1'),true); |
| + await capture('progress'); |
| + await evaluate('window.liveWrites = 0; new MutationObserver(records => window.liveWrites += records.length).observe(document.getElementById("claim-status"), {childList:true,subtree:true,characterData:true})'); |
| + const repeatedPoll = statusRequests; |
| + await until('document.querySelector("li[aria-current=step]")?.dataset.step === "2"'); |
| + for (let i=0; i<40 && statusRequests === repeatedPoll; i++) await new Promise(r=>setTimeout(r,100)); |
| + await new Promise(r=>setTimeout(r,200)); |
| + assert.equal(await evaluate('window.liveWrites'),0,'unchanged poll rewrote live region'); |
| + await until('!!document.querySelector(".claim-result a")'); |
| + await capture('done'); |
| + assert.equal(await evaluate('document.querySelector(".claim-result a").textContent.replace(/^https:\\/\\//, "")'),await evaluate('document.querySelector(".claim-result a").getAttribute("href").replace(/^https:\\/\\//, "")')); |
| + assert.equal(await evaluate('document.querySelector("#claim h1").textContent'),'Your demo is now a permanent app.'); |
| + assert.equal(await evaluate('document.querySelector("#claim").innerText.split("Your demo is now a permanent app.").length-1'),1); |
| + 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('getComputedStyle(document.getElementById("claim-status")).clipPath'),'none','failure message hidden'); |
| + 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('getComputedStyle(document.getElementById("claim-status")).clipPath'),'none','abort message hidden'); |
| + 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)); |
| + await call('Page.navigate',{url:target+'/demo/claim?testProgress=stopping'}); |
| + await until('document.querySelector("li[aria-current=step]")?.dataset.step === "2"'); |
| + await until('document.getElementById("claim-status")?.textContent === document.getElementById("claim-progress")?.dataset.stopping'); |
| + assert.equal(await evaluate('document.querySelectorAll("[aria-current=step]").length'),0); |
| + assert.equal(await evaluate('getComputedStyle(document.getElementById("claim-status")).clipPath'),'none'); |
| + await capture('stopping'); |
| + await until('document.getElementById("claim-status")?.textContent === document.getElementById("claim-progress")?.dataset.aborted'); |
| + await call('Page.navigate',{url:target+'/demo/claim?testProgress=unknown'}); |
| + await until('!!document.getElementById("claim-progress") && document.querySelectorAll("[aria-current=step]").length === 0'); |
| + const unknownPolls = statusRequests; |
| + await new Promise(r=>setTimeout(r,6500)); |
| + assert(statusRequests >= unknownPolls + 2, 'neutral progress stopped polling'); |
| + assert.equal(await evaluate('document.getElementById("claim-status").textContent'),'Keep your demo'); |
| + assert.equal(await evaluate('document.querySelectorAll("[aria-current=step]").length'),0); |
| + 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)); |