oficina / calendar Public

Clone
git clone https://amadan.net/oficina/calendar

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package calendar
4
5// The smart door in a real Chromium, served through rastrillo's production
6// stack with Home configured, so the door offers Continue with Oficina ID.
7// Every state, the widest included (a long remembered address, Keymail,
8// the confirm step, the Keymail continuation, the refusal, team mode's
9// removal, signed out), reflows at 320px (WCAG 1.4.10), every control on
10// the card is a 24px target on its smaller axis (2.5.8), and the Oficina ID
11// button draws its glyph. The page is put in the light scheme through the
12// DevTools protocol, whatever the machine's (this Mac is dark).
13//
14// TMPDIR=/tmp go test -tags browser -run SmartDoorInABrowser ./internal/calendar/
15//
16// CALENDAR_SIGNIN_SHOTS=<dir> also writes a screenshot of each state there.
17
18import (
19 "context"
20 "io"
21 "log/slog"
22 "net/http"
23 "net/http/httptest"
24 "net/url"
25 "os"
26 "path/filepath"
27 "strings"
28 "sync"
29 "testing"
30 "time"
31
32 "amadan.net/oficina/estilo.git/chrome"
33 "amadan.net/oficina/estilo.git/sky"
34 "amadan.net/rastrillo/rastrillo"
35 rauth "amadan.net/rastrillo/rastrillo/auth"
36 "amadan.net/rastrillo/rastrillo/harness"
37 "amadan.net/rastrillo/rastrillo/lastsignin"
38 "github.com/chromedp/cdproto/cdp"
39 "github.com/chromedp/cdproto/emulation"
40 "github.com/chromedp/chromedp"
41)
42
43// continuePreviewPath draws the Keymail continuation in preview (no meta
44// refresh, the link goes nowhere), so its layout can be measured without a
45// Keymail server.
46const continuePreviewPath = "/__test/continue"
47
48func TestSmartDoorInABrowser(t *testing.T) {
49 host := strings.TrimPrefix(homeTestOrigin, "https://")
50 f := newHomeRouterFixture(t)
51 team := newTeamFixture(t)
52 served := func(a *App) http.Handler {
53 h, closeServed, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}))
54 if err != nil {
55 t.Fatal(err)
56 }
57 t.Cleanup(func() { _ = closeServed() })
58 return h
59 }
60 homeServed, teamServed := served(f.app), served(team.app)
61 var (
62 mu sync.Mutex
63 inject []*http.Cookie
64 onTeam bool
65 )
66 rig := harness.New(t, func(string) http.Handler {
67 // connect answers only its own origin's host; the browser is on
68 // the rig's. The case's cookies are added here, since the
69 // remembered and session cookies are __Host- and Secure.
70 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
71 r.Host = host
72 mu.Lock()
73 for _, c := range inject {
74 r.AddCookie(c)
75 }
76 team := onTeam
77 mu.Unlock()
78 if r.URL.Path == continuePreviewPath {
79 st := rauth.SigninState{Step: rauth.StepContinue, ContinueURL: "https://keymail.example.com/oauth/authorize"}
80 screen := chrome.SignInScreen{Icon: doorIcon(), App: "Calendar", Sky: sky.For(r.Host), State: st, Preview: true}
81 title, _ := signinTitle(screen)
82 pd := f.app.h.page(r, "", signinView{Screen: &screen})
83 pd.WholeTitle = title
84 renderStatus(w, "signin", http.StatusOK, pd)
85 return
86 }
87 if team {
88 teamServed.ServeHTTP(w, r)
89 return
90 }
91 homeServed.ServeHTTP(w, r)
92 })
93 })
94 remembered := func(rec lastsignin.Record) func() []*http.Cookie {
95 return func() []*http.Cookie {
96 w := httptest.NewRecorder()
97 f.app.auth.RememberJar().Remember(w, rec)
98 return w.Result().Cookies()
99 }
100 }
101 long := "someone.with.a.rather.long.name@a-team-with-a-long-domain.example.com"
102 // A session the signed-in routes refuse, minted afresh for each load:
103 // the door ends it, as the next page would.
104 refused := func() []*http.Cookie {
105 g := f.fresh()
106 g.session(t, "nobody-here@example.test", "magiclink", time.Now())
107 return append(remembered(lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: long})(), g.sessionCookie())
108 }
109
110 // An emailed link's confirm step.
111 homeRedirect(t, f.do(http.MethodPost, "/signin", "address=alice%40example.test"))
112 f.app.signinMail.wait()
113 confirm, err := linkPath(magicLinkPattern.FindString(f.app.mailRecorder.last()))
114 if err != nil {
115 t.Fatal(err)
116 }
117
118 type measure struct {
119 Light, Door bool
120 Overflow int
121 Small []string
122 GlyphW, GlyphH float64
123 Heading, Text string
124 }
125 const script = `(() => {
126 const card = document.querySelector('[estilo-signin]');
127 const small = [];
128 for (const el of card ? card.querySelectorAll('a, button, input:not([type=hidden])') : []) {
129 const r = el.getBoundingClientRect();
130 if (Math.min(r.width, r.height) < 24) small.push(el.outerHTML.slice(0, 80) + ' ' + r.width + 'x' + r.height);
131 }
132 const glyph = card && card.querySelector('a[href^="/signin/oficina"] svg');
133 const g = glyph ? glyph.getBoundingClientRect() : {width: 0, height: 0};
134 const h = card && card.querySelector('h1');
135 return {
136 Light: matchMedia('(prefers-color-scheme: light)').matches,
137 Door: !!card,
138 Overflow: document.documentElement.scrollWidth - innerWidth,
139 Small: small,
140 GlyphW: g.width, GlyphH: g.height,
141 Heading: h ? h.textContent : '',
142 Text: card ? card.textContent : '',
143 };
144 })()`
145 light := chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
146 _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{
147 Features: []*emulation.MediaFeature{{Name: "prefers-color-scheme", Value: "light"}},
148 })
149 return err
150 })
151 shots := os.Getenv("CALENDAR_SIGNIN_SHOTS")
152 for _, c := range []struct {
153 name, path, heading string
154 cookies func() []*http.Cookie
155 glyph, team bool
156 says string
157 }{
158 {name: "first visit", path: "/signin", heading: "Sign in to Calendar", glyph: true},
159 {name: "from a page", path: "/signin?return_to=" + url.QueryEscape("/day/2026-09-10"), heading: "Sign in to Calendar", glyph: true},
160 {name: "other ways", path: "/signin?ways=1", heading: "Other ways to sign in"},
161 {name: "other ways remembered", path: "/signin?ways=1&way=oficina", heading: "Other ways to sign in",
162 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: long})},
163 {name: "email", path: "/signin?way=email", heading: "Sign in to Calendar"},
164 {name: "continue as", path: "/signin", heading: "Sign in to Calendar",
165 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: long})},
166 {name: "keymail", path: "/signin", heading: "Sign in to Calendar",
167 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodKeymail, Address: long})},
168 {name: "email only", path: "/signin/local", heading: "Sign in to Calendar"},
169 {name: "problem", path: "/signin?err=rate", heading: "Sign in to Calendar"},
170 {name: "refusal", path: "/signin", heading: "Sign in to Calendar", cookies: refused, says: signinRefusal},
171 {name: "removed", path: "/signin?err=removed", heading: "Sign in to Calendar", team: true,
172 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: long}), says: signinRemoved},
173 {name: "step-up", path: "/signin?reauth=1", heading: "Sign in to Calendar"},
174 {name: "sent", path: "/signin?sent=1", heading: "Check your email"},
175 {name: "confirm", path: confirm, heading: "Sign in to Calendar"},
176 {name: "continuation", path: continuePreviewPath, heading: "Signing you in"}, // rastrillo v0.45.0 never names Keymail
177 {name: "signed out", path: "/signed-out", heading: "You’re signed out"},
178 } {
179 for _, width := range []int64{320, 1280} {
180 mu.Lock()
181 inject, onTeam = nil, c.team
182 if c.cookies != nil {
183 inject = c.cookies()
184 }
185 mu.Unlock()
186 ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second)
187 var m measure
188 err := chromedp.Do(ctx,
189 light,
190 chromedp.EmulateViewport(width, 900),
191 chromedp.Navigate(rig.Origin+c.path),
192 chromedp.WaitVisible(chromedp.CSS("[estilo-signin] h1")),
193 harness.Into(&m, chromedp.Evaluate[measure](script)),
194 )
195 if err == nil && shots != "" {
196 var shot []byte
197 shot, err = chromedp.Run(ctx, chromedp.CaptureScreenshot())
198 if err == nil {
199 name := strings.ReplaceAll(c.name, " ", "-") + "-" + map[int64]string{320: "phone", 1280: "desk"}[width] + ".png"
200 err = os.WriteFile(filepath.Join(shots, name), shot, 0o644)
201 }
202 }
203 cancel()
204 if err != nil {
205 t.Fatalf("%s at %dpx: %v", c.name, width, err)
206 }
207 if !m.Light {
208 t.Fatal("the page is not in the light scheme")
209 }
210 if !m.Door || m.Heading != c.heading {
211 t.Errorf("%s at %dpx: door=%v heading %q, want %q", c.name, width, m.Door, m.Heading, c.heading)
212 }
213 if c.says != "" && !strings.Contains(m.Text, c.says) {
214 t.Errorf("%s at %dpx does not say %q:\n%s", c.name, width, c.says, m.Text)
215 }
216 if m.Overflow > 0 {
217 t.Errorf("%s at %dpx scrolls sideways by %dpx", c.name, width, m.Overflow)
218 }
219 if len(m.Small) > 0 {
220 t.Errorf("%s at %dpx: targets under 24px: %q", c.name, width, m.Small)
221 }
222 if c.glyph && (m.GlyphW < 12 || m.GlyphH < 12) {
223 t.Errorf("%s at %dpx: the Oficina glyph is %vx%v", c.name, width, m.GlyphW, m.GlyphH)
224 }
225 }
226 }
227}
228