The smart door: rastrillo's one-way sign-in screen in estilo's door
Home spec 2026-11-19-smart-door.md, step 6, Docs first; home/connect
MIGRATING.md's step-6 checklist.
- rastrillo auth: SigninScreen and SigninOneWay on, SigninPath
connect.SigninPath, Forget mounted at /signin/forget. The door is
estilo-signin-screen over auth.SigninState (HideBrand is estilo's),
for every state: the door, the chooser, Sent, the Keymail
continuation and RenderConfirm's confirm step.
- With Home: GET /signin at Routes.SigninDoor, /signin/local at
Routes.SigninLocal, /signin/oficina at Routes.SigninOficina, the first
and last behind Docs' admission check (admitted plus withoutCookie).
The door offers Continue with Oficina ID (chrome.OficinaGlyph) where
connect.OficinaHref says it may. /signin no longer hops to id.*.
- The refusal moves into the screen's app-problem slot, with the field.
Docs' own sign-in error strings and its Keymail continuation go:
rastrillo's screen covers them.
- MintHomeSession remembers Oficina ID with the address of the person
connect resolved (connect.MintedPerson), or none.
- Signed out: "Forget me on this device" (estilo Forgetting). With Home
the form chains, after Docs' Forget, to {issuer}/forget?return=
<origin>/signed-out.
- POST /signin keeps the return Docs' way: remembered in Docs' sealed
return memory and taken off Begin's form, so a local sign-in still
lands on /auth/local/complete (connect's resume point), and put back
on Begin's redirect to the door.
- The door's <title> is rastrillo's for its state (it names Docs).
- Tests follow: rastrillo's copy, /signin/local?reauth=1 for the link
step-up, the Keymail continuation on the door, a stray Keymail
callback leaving the attempt alone, and rastrillo v0.31's minified
vendored assets (estilo's theme and busy shim sit at vendored paths).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
24 files changed,
+567
−456
go.mod+2 −2internal/docs/app.go+10 −3internal/docs/auth.go+128 −101internal/docs/auth_allowlist_test.go+24 −1internal/docs/auth_keymail_test.go+28 −3internal/docs/auth_navigation.go+53 −83internal/docs/auth_navigation_test.go+44 −77internal/docs/auth_test.go+19 −16internal/docs/chrome.go+8 −2internal/docs/chrome_test.go+8 −3internal/docs/handlers.go+11 −3internal/docs/home_connect.go+61 −47internal/docs/home_connect_linked_test.go+12 −1internal/docs/home_render.go+14 −3internal/docs/home_router_integration_test.go+9 −5internal/docs/render.go+24 −24internal/docs/signin_confirm_test.go+4 −4internal/docs/signin_door_test.go+16 −11internal/docs/signin_loop_test.go+33 −11internal/docs/signin_return.go+13 −24internal/docs/team_router_test.go+1 −1internal/docs/theme_assets_test.go+32 −2internal/docs/views/layout.html+1 −1internal/docs/views/signin.html+12 −28
Intent
diff --git a/go.mod b/go.mod| index 508bf83..89d930e 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -20,8 +20,8 @@ require ( |
| github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 |
| github.com/go-text/typesetting v0.3.6-0.20261020210405-a4cf8f401e16 |
| github.com/google/uuid v1.6.0 |
| - github.com/keymaildev/signin v0.1.1 |
| github.com/modelcontextprotocol/go-sdk v1.8.0 |
| + github.com/tdewolff/minify/v2 v2.24.19 |
| github.com/tetratelabs/wazero v1.12.0 |
| golang.org/x/image v0.23.0 |
| golang.org/x/oauth2 v0.35.0 |
| @@ -40,13 +40,13 @@ require ( |
| github.com/google/jsonschema-go v0.4.3 // indirect |
| github.com/jinzhu/inflection v1.0.0 // indirect |
| github.com/jinzhu/now v1.1.5 // indirect |
| + github.com/keymaildev/signin v0.1.1 // indirect |
| github.com/mattn/go-isatty v0.0.20 // indirect |
| github.com/ncruces/go-strftime v1.0.0 // indirect |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect |
| github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect |
| github.com/segmentio/asm v1.1.3 // indirect |
| github.com/segmentio/encoding v0.5.4 // indirect |
| - github.com/tdewolff/minify/v2 v2.24.19 // indirect |
| github.com/tdewolff/parse/v2 v2.8.16 // indirect |
| github.com/yosida95/uritemplate/v3 v3.0.2 // indirect |
| github.com/zalando/go-keyring v0.2.8 // indirect |
diff --git a/internal/docs/app.go b/internal/docs/app.go| index 3594fda..ffa9eef 100644 |
| --- a/internal/docs/app.go |
| +++ b/internal/docs/app.go |
| @@ -645,10 +645,12 @@ func New(cfg Config) (*App, error) { |
| return nil, err |
| } |
| } |
| + h.auth = authPlugin |
| if home == nil { |
| - h.remembered = standalone.returnPath |
| + h.rememberReturn = standalone.rememberReturn |
| } else { |
| - h.remembered = home.returns.returnPath |
| + h.rememberReturn = home.returns.rememberReturn |
| + h.homeIssuer = home.issuer |
| } |
| r := chi.NewRouter() |
| // Every route that is not a route is the 404 page for a browser, and a |
| @@ -671,7 +673,7 @@ func New(cfg Config) (*App, error) { |
| // static assets that page (and the shell around it) needs to |
| // render at all. |
| if home == nil { |
| - r.Get("/signin", h.standaloneSignin(standalone)) |
| + r.Get("/signin", h.standaloneSignin) |
| r.Get(localLinkCompletePath, standalone.completeStandalone) |
| r.Get("/signed-out", h.signedOut) |
| } else { |
| @@ -682,6 +684,11 @@ func New(cfg Config) (*App, error) { |
| // the menu was open cannot turn the click into a sign-in loop. |
| r.Post("/appearance", chrome.HandleAppearance) |
| r.Post("/signin", h.beginSignin(authPlugin.Begin)) |
| + // "Use a different email" on the door and "Forget me on this device" |
| + // on the signed-out page: a same-origin POST, inside the app-wide CSRF |
| + // check like any form. With Home, the signed-out page's chains on to |
| + // Oficina ID's own Forget (auth.go's forget). |
| + r.Post(signinForgetPath, h.forget(authPlugin.Forget)) |
| // An emailed link opens GET /auth/verify, which only draws the |
| // confirm door (h.confirmSignin); its Sign in button POSTs the token |
| // back, and the POST spends it. Without the POST nobody signs in by |
diff --git a/internal/docs/auth.go b/internal/docs/auth.go| index 682cfb7..d48f6da 100644 |
| --- a/internal/docs/auth.go |
| +++ b/internal/docs/auth.go |
| @@ -18,6 +18,7 @@ import ( |
| "amadan.net/oficina/estilo.git/sky" |
| "amadan.net/oficina/home/connect" |
| rauth "amadan.net/rastrillo/rastrillo/auth" |
| + "amadan.net/rastrillo/rastrillo/lastsignin" |
| "amadan.net/rastrillo/rastrillo/mail" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| @@ -421,6 +422,14 @@ func newAuthPlugin(cfg Config, writer *sql.DB, instanceKey string, mailer mail.S |
| // the page they came from (signin_return.go), since Verify itself can |
| // only land on one fixed path. |
| return rauth.New(rauth.Config{ |
| + // The smart door (Home spec 2026-11-19-smart-door.md): rastrillo's |
| + // screen, one way in per page. Every outcome, chooser link and |
| + // Forget lands on /signin, which with Home configured is connect's |
| + // SigninDoor (home/connect MIGRATING.md, step 6). |
| + SigninScreen: true, |
| + SigninOneWay: true, |
| + SigninPath: connect.SigninPath, |
| + ForgetPath: signinForgetPath, |
| SignedInPath: localLinkCompletePath, |
| DB: writer, |
| Origin: cfg.Origin, |
| @@ -439,121 +448,139 @@ func newAuthPlugin(cfg Config, writer *sql.DB, instanceKey string, mailer mail.S |
| }) |
| } |
| -// signinPage is GET /signin's view data. rauth.Auth's own handlers |
| -// (Begin, Callback, Verify) never render a page themselves — SKILL.md |
| -// §5/magic-links.md: "the sign-in page stays yours" — they report |
| -// outcomes by redirecting back here with a query this handler reads. |
| -// |
| -// Exactly one of Form, Sent, Confirm and ContinueURL is set: the form |
| -// (estilo's estilo-signin), the check-your-email state that replaces it |
| -// (estilo-signin-sent), the emailed link's confirm step |
| -// (auth_navigation.go), or the Keymail continuation (auth_navigation.go). |
| -type signinPage struct { |
| - Frame Frame |
| - Form *chrome.SignIn |
| - Sent *chrome.SignInNotice |
| - Confirm *signinConfirm |
| - ContinueURL string |
| - SubmitLabel string |
| - // Door heads the continuation and confirm cards (Icon, App, Sky), so |
| - // the moment between the form and Keymail, and the page an emailed |
| - // link opens, look like the same door. |
| - Door chrome.SignInNotice |
| -} |
| +// signinForgetPath is where rastrillo auth's Forget is mounted (app.go): |
| +// "Use a different email" on the door, and "Forget me on this device" on |
| +// the signed-out page. It is auth's own default, named here because the |
| +// signed-out page and connect's RoutesConfig.ForgetPath must agree with it. |
| +const signinForgetPath = "/signin/forget" |
| -// signinAgainPath is where "Use a different address" goes: the local |
| -// form, which with Home configured is /signin/local (plain /signin starts |
| -// a Home exchange). |
| -func (h *handlers) signinAgainPath() string { |
| - if h.homeEnabled { |
| - return "/signin/local" |
| - } |
| - return "/signin" |
| -} |
| +// oficinaChain is the hidden field the signed-out page's Forget form posts |
| +// (chain=oficina) when Home is configured: after forgetting this browser |
| +// here, Docs sends it on to Oficina ID's own Forget (forget, below). The |
| +// door's "Use a different email" posts to the same Forget without it, and |
| +// stays on the door. |
| +const oficinaChain = "oficina" |
| -// signinAgainHref is "Use a different address": the form again, carrying |
| -// the page this sign-in was started from (spec §9.2: "keeping the |
| -// return"). A bare /signin is a fresh start, which remembers the list, so |
| -// the deep link would be lost (review finding, Astra, #65). |
| -func (h *handlers) signinAgainHref(r *http.Request) string { |
| - href := h.signinAgainPath() |
| - if h.remembered != nil { |
| - if path := h.remembered(r); path != "/" { |
| - href += "?return_to=" + url.QueryEscape(path) |
| - } |
| - } |
| - return href |
| +// signinPage is the view data of the sign-in door (views/signin.html): |
| +// rastrillo's sign-in screen (its ui "signin" partial, fed by |
| +// auth.SigninState) drawn inside estilo's door by estilo-signin-screen. |
| +// Every state is that one template: the door, the chooser ("Other ways to |
| +// sign in"), Sent, the Keymail continuation and the confirm step an |
| +// emailed link opens. |
| +type signinPage struct { |
| + Frame Frame |
| + Screen chrome.SignInScreen |
| } |
| -// signin serves GET /signin — the form itself, and the landing spot |
| -// for every outcome rauth.Auth's handlers redirect back to |
| -// (?sent=1, ?err=rate|address|expired|keymail|1, ?force=1). rate, |
| -// address and expired each get their own copy below; keymail and 1 |
| -// (a raw Begin failure logged server-side, and Verify's own "unknown, |
| -// used and expired alike" — its own doc comment says rauth.Auth |
| -// refuses to be more specific than that, so there is nothing this |
| -// page could add by drawing a finer distinction of its own) share the |
| -// switch's default branch, docs.signin.error.unknown — never |
| -// docs.error.generic (fix round 1 on Task 3): every outcome on this |
| -// one page means the same operational thing, "sign-in did not |
| -// complete, ask for a new link," and docs.error.generic is authored |
| -// for a render failure with nowhere styled to land, not for this |
| -// page's own ordinary, recoverable outcomes. |
| +// signin is the sign-in door (the smart-door spec in Home, |
| +// docs/superpowers/specs/2026-11-19-smart-door.md): GET /signin, and with |
| +// Home configured GET /signin/local too (connect's SigninDoor and |
| +// SigninLocal hand both here), the landing spot for every outcome |
| +// rastrillo's handlers redirect back with, Config.RenderConfirm's confirm |
| +// step, and Config.Refused's refusal. |
| // |
| -// An address error goes in the field's own error slot (the form sets |
| -// novalidate, so the browser's bubble never shows); every other error is |
| -// a negative callout above the form (spec §9.2). |
| +// rastrillo decides what the door shows from the query and this browser's |
| +// cookies (SigninState: the way in it used last, Sent, problems, the |
| +// chooser), with SigninOneWay drawing one way in per page. Docs adds what |
| +// only it knows: Oficina ID where connect says the door may offer it |
| +// (OficinaHref is "" on /signin/local, on a step-up and anywhere else), |
| +// and the refusal, which only someone who has just verified the address |
| +// reaches (refusedHere), in the screen's app-problem slot with the email |
| +// field. |
| func (h *handlers) signin(w http.ResponseWriter, r *http.Request) { |
| - q := r.URL.Query() |
| - icon := brand.Path("docs") |
| - data := signinPage{} |
| - var page string |
| - if q.Get("sent") == "1" { |
| - sent := chrome.SignInNotice{Icon: icon, App: "Docs", Sky: sky.For(r.Host)}.Sent(h.signinAgainHref(r)) |
| - data.Sent, page = &sent, sent.Page() |
| - } else { |
| - form := &chrome.SignIn{ |
| - Icon: icon, |
| - App: "Docs", |
| - Sky: sky.For(r.Host), |
| - Action: "/signin", |
| - } |
| - page = form.Page() |
| - if q.Get("force") != "" { |
| - form.Hidden = []chrome.Hidden{{Name: "force", Value: "1"}} |
| - } |
| - switch q.Get("err") { |
| - case "": |
| - // nothing to report |
| - case "rate": |
| - form.Error = rastrillo.T(r, "docs.signin.error.rate") |
| - case "address": |
| - form.AddressError = rastrillo.T(r, "docs.signin.error.address") |
| - case "expired": |
| - form.Error = rastrillo.T(r, "docs.signin.error.expired") |
| - default: |
| - form.Error = rastrillo.T(r, "docs.signin.error.unknown") |
| - } |
| - if refusedHere(r) { |
| - // Keymail or a link verified the address and the allowlist |
| - // does not hold it, in this very response (Config.Refused, |
| - // auth_navigation.go's refused). |
| - // Never from the query. The form is the way on. |
| - form.Error = rastrillo.T(r, "docs.signin.error.refused") |
| + st := h.auth.SigninState(r) |
| + if st.Unavailable { |
| + // Under a base path or on a direct host the hub signs people in, |
| + // estilo-signin-screen draws nothing, and every route rastrillo's |
| + // door names answers 404 there. So does the door. |
| + h.notFound(w, r) |
| + return |
| + } |
| + if href := connect.OficinaHref(r); href != "" { |
| + st.Federated = &rauth.FederatedDoor{ |
| + Provider: lastsignin.ProviderOficina, |
| + Href: href, |
| + Label: rastrillo.T(r, "docs.signin.oficina_id"), |
| + Icon: chrome.OficinaGlyph, |
| } |
| - data.Form = form |
| } |
| - data.Frame = h.frame(r, frameOptions{titleParts: []string{page}, signinPage: true}) |
| + if refusedHere(r) { |
| + // Keymail or a link verified the address and the allowlist does |
| + // not hold it, in this very response (Config.Refused, |
| + // auth_navigation.go's signinRefused). Never from the query. |
| + st.AppProblem = &rauth.AppProblem{Text: rastrillo.T(r, "docs.signin.error.refused"), Ask: true} |
| + } |
| + h.rememberSigninReturn(w, r) |
| + h.auth.PrepareSigninResponse(w, st) |
| + data := signinPage{Screen: chrome.SignInScreen{Icon: brand.Path("docs"), App: "Docs", Sky: sky.For(r.Host), State: st}} |
| + title, err := h.render.signinTitle(data.Screen) |
| + if err != nil { |
| + h.logger.Error("docs: render signin title", "err", err) |
| + h.fail(w, r, http.StatusInternalServerError, failStatus) |
| + return |
| + } |
| + data.Frame = h.frame(r, frameOptions{title: title, signinPage: true}) |
| if err := h.render.page(w, r, "signin", data); err != nil { |
| h.logger.Error("docs: render signin", "err", err) |
| h.fail(w, r, http.StatusInternalServerError, failStatus) |
| } |
| } |
| -// signedOut is GET /signed-out, where Sign out lands: "You’re signed out", |
| -// and a Sign in button (spec §9.2). With Home configured it is the same |
| -// page (connect's SignedOut, drawn by home_connect.go's render), which is |
| -// why it takes the path to sign in at. |
| +// rememberSigninReturn keeps the page a sign-in began from in Docs' own |
| +// sealed return memory (home_return.go), read at /auth/local/complete, |
| +// when the door is opened afresh: a plain GET of /signin or /signin/local |
| +// that is not one of the email flow's outcomes. A plain door remembers |
| +// the list, so a page remembered by an earlier, abandoned attempt never |
| +// wins over the one being made now. The chooser's links carry return_to, |
| +// so moving between ways keeps it. The confirm step and a refusal are |
| +// drawn on /auth/*, and remember nothing. |
| +func (h *handlers) rememberSigninReturn(w http.ResponseWriter, r *http.Request) { |
| + if h.rememberReturn == nil || r.Method != http.MethodGet || signinOutcome(r) || |
| + (r.URL.Path != connect.SigninPath && r.URL.Path != connect.SigninLocalPath) { |
| + return |
| + } |
| + path, ok := requestedReturn(r) |
| + if !ok { |
| + path = "/" |
| + } |
| + h.rememberReturn(w, path) |
| +} |
| + |
| +// forget is POST /signin/forget, rastrillo auth's Forget: "Use a |
| +// different email" on the door, and "Forget me on this device" on the |
| +// signed-out page. Each host remembers for itself, so with Home configured |
| +// the signed-out page's form (chain=oficina) goes on to Oficina ID's own |
| +// Forget once this one has answered, with Docs' signed-out page as the way |
| +// back: {issuer}/forget?return=<origin>/signed-out. id.oficina.works asks |
| +// "Forget me on Oficina ID too?" and returns only to a registered |
| +// consumer's exact /signed-out. Anything but Forget's own redirect (a |
| +// cross-origin refusal, a wrong method) is passed on as it is. |
| +func (h *handlers) forget(forget http.HandlerFunc) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + if h.homeIssuer == "" { |
| + forget(w, r) |
| + return |
| + } |
| + result := &signinResponse{header: make(http.Header)} |
| + forget(result, r) |
| + if result.status == http.StatusSeeOther && r.PostFormValue("chain") == oficinaChain { |
| + result.header.Set("Location", oficinaForgetURL(h.homeIssuer, h.origin)) |
| + } |
| + result.replay(w) |
| + } |
| +} |
| + |
| +// oficinaForgetURL is Oficina ID's Forget, returning to this origin's |
| +// signed-out page (Home's internal/home/door.go, forgetChainReturn). |
| +func oficinaForgetURL(issuer, origin string) string { |
| + back := strings.TrimSuffix(origin, "/") + "/signed-out" |
| + return strings.TrimSuffix(issuer, "/") + "/forget?" + url.Values{"return": {back}}.Encode() |
| +} |
| + |
| +// signedOut is GET /signed-out without Home, where Sign out lands: "You’re |
| +// signed out", a Sign in button and "Forget me on this device" (spec |
| +// §9.2; the smart-door spec's "Signed out"). With Home configured the page |
| +// is connect's SignedOut, drawn by the same renderer (home_render.go). |
| func (h *handlers) signedOut(w http.ResponseWriter, r *http.Request) { |
| h.render.homeLink(w, r, "signedout", "", http.StatusOK) |
| } |
diff --git a/internal/docs/auth_allowlist_test.go b/internal/docs/auth_allowlist_test.go| index d29f6b3..d4dd2a9 100644 |
| --- a/internal/docs/auth_allowlist_test.go |
| +++ b/internal/docs/auth_allowlist_test.go |
| @@ -7,6 +7,8 @@ import ( |
| "net/http/httptest" |
| "net/url" |
| "path/filepath" |
| + "regexp" |
| + "sort" |
| "strings" |
| "testing" |
| ) |
| @@ -134,9 +136,15 @@ func TestSigninResponseIdenticalForNonPermittedAddress(t *testing.T) { |
| if got, want := nonPermitted.Code, permitted.Code; got != want { |
| t.Errorf("status differs: non-permitted=%d permitted=%d", got, want) |
| } |
| - if got, want := nonPermitted.Header().Get("Location"), permitted.Header().Get("Location"); got != want { |
| + // The sign-in screen (SigninScreen) names each attempt with a fresh |
| + // random id, so the two Locations differ there and only there; and both |
| + // answers set the same cookies, the attempt's among them. |
| + if got, want := attemptMasked(nonPermitted.Header().Get("Location")), attemptMasked(permitted.Header().Get("Location")); got != want || !strings.Contains(want, "attempt=*") { |
| t.Errorf("Location differs: non-permitted=%q permitted=%q", got, want) |
| } |
| + if got, want := cookieNames(nonPermitted), cookieNames(permitted); got != want { |
| + t.Errorf("cookies differ: non-permitted=%q permitted=%q", got, want) |
| + } |
| if got, want := nonPermitted.Header().Get("Content-Type"), permitted.Header().Get("Content-Type"); got != want { |
| t.Errorf("Content-Type differs: non-permitted=%q permitted=%q", got, want) |
| } |
| @@ -273,3 +281,18 @@ func TestNewRefusesMissingAllowlistOutsideDevelopment(t *testing.T) { |
| t.Fatal("New must refuse to start outside development with no allowlist configured") |
| } |
| } |
| + |
| +// attemptMasked is a sign-in Location with its random attempt id masked. |
| +func attemptMasked(location string) string { |
| + return regexp.MustCompile(`attempt=[^&]+`).ReplaceAllString(location, "attempt=*") |
| +} |
| + |
| +// cookieNames is the sorted names of the cookies a response sets. |
| +func cookieNames(rec *httptest.ResponseRecorder) string { |
| + var names []string |
| + for _, c := range rec.Result().Cookies() { |
| + names = append(names, c.Name) |
| + } |
| + sort.Strings(names) |
| + return strings.Join(names, ",") |
| +} |
diff --git a/internal/docs/auth_keymail_test.go b/internal/docs/auth_keymail_test.go| index ee9883c..8b53a73 100644 |
| --- a/internal/docs/auth_keymail_test.go |
| +++ b/internal/docs/auth_keymail_test.go |
| @@ -169,7 +169,7 @@ func keymailOAuthChild(t *testing.T) { |
| t.Fatalf("actual classifier lookup count=%d, status=%d", lookups, rec.Code) |
| } |
| if !tc.detected { |
| - if rec.Code != 303 || rec.Header().Get("Location") != "/signin?sent=1" { |
| + if rec.Code != 303 || !regexp.MustCompile(`^/signin\?sent=1&attempt=[A-Za-z0-9_-]+$`).MatchString(rec.Header().Get("Location")) { |
| t.Fatalf("mail start: %d %s", rec.Code, rec.Header().Get("Location")) |
| } |
| app.signinMail.wait() |
| @@ -185,8 +185,20 @@ func keymailOAuthChild(t *testing.T) { |
| } |
| return |
| } |
| - if rec.Code != 200 || rec.Header().Get("Location") != "" { |
| - t.Fatalf("OAuth continuation: %d", rec.Code) |
| + // The sign-in screen keeps a Keymail start on the door, so |
| + // form-action stays 'self': Begin answers with the door's |
| + // continuation (?continue=), whose page leaves for Keymail by |
| + // a meta refresh and a link, and discloses no referrer. |
| + continuation := rec.Header().Get("Location") |
| + if rec.Code != 303 || !strings.HasPrefix(continuation, "/signin?continue=") { |
| + t.Fatalf("OAuth start: %d %q, want the door's continuation", rec.Code, continuation) |
| + } |
| + rec = request("GET", continuation, "") |
| + if rec.Code != 200 || rec.Header().Get("Location") != "" || rec.Header().Get("Referrer-Policy") != "no-referrer" || rec.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("OAuth continuation: %d %q %q", rec.Code, rec.Header().Get("Referrer-Policy"), rec.Header().Get("Cache-Control")) |
| + } |
| + if !strings.Contains(rec.Body.String(), `http-equiv="refresh"`) || !strings.Contains(rec.Body.String(), "estilo-door") { |
| + t.Fatal("the continuation is not the door, leaving for Keymail") |
| } |
| var target *url.URL |
| for _, m := range regexp.MustCompile(`href="([^"]+)"`).FindAllStringSubmatch(rec.Body.String(), -1) { |
| @@ -260,6 +272,19 @@ func keymailOAuthChild(t *testing.T) { |
| if got != want { |
| t.Fatalf("token exchanges=%d want%d", got, want) |
| } |
| + // A callback with another attempt's state is answered Expired and |
| + // leaves this browser's attempt alone (rastrillo's sign-in screen: |
| + // a late callback from another tab must not throw away a newer |
| + // attempt), so this attempt's own callback still completes it, once. |
| + if tc.badState { |
| + request("GET", "/auth/callback?"+url.Values{"state": {q.Get("state")}, "code": {"one-code"}}.Encode(), "") |
| + mu.Lock() |
| + got = exchanges |
| + mu.Unlock() |
| + if want = 1; got != want { |
| + t.Fatalf("the attempt's own callback after a stray one: token exchanges=%d want%d", got, want) |
| + } |
| + } |
| // Pending state is cleared after callback: replay cannot reach exchange. |
| request("GET", "/auth/callback?"+url.Values{"state": {q.Get("state")}, "code": {"one-code"}}.Encode(), "") |
| mu.Lock() |
diff --git a/internal/docs/auth_navigation.go b/internal/docs/auth_navigation.go| index d8af473..2b6cb1a 100644 |
| --- a/internal/docs/auth_navigation.go |
| +++ b/internal/docs/auth_navigation.go |
| @@ -1,81 +1,67 @@ |
| package docs |
| import ( |
| - "amadan.net/oficina/estilo.git/brand" |
| - "amadan.net/oficina/estilo.git/chrome" |
| - "amadan.net/oficina/estilo.git/sky" |
| "bytes" |
| "context" |
| "net/http" |
| "net/url" |
| - "strings" |
| - "amadan.net/rastrillo/rastrillo" |
| rauth "amadan.net/rastrillo/rastrillo/auth" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| ) |
| -// End the POST with a document before navigating to an identity provider. |
| -// Safari applies form-action to a redirect chain, including intermediate GETs. |
| -// The continuation keeps the original CSP and works without JavaScript. |
| +// beginSignin is POST /signin, rastrillo's Begin, with the destination kept |
| +// Docs' way. |
| +// |
| +// The door's forms post return_to (the screen's ReturnTo), and rastrillo |
| +// would carry it across the mail or Keymail round trip and land the new |
| +// session there itself. Docs lands every local sign-in on |
| +// /auth/local/complete instead (localLinkCompletePath): connect resumes a |
| +// pending account link from there, which is why its README requires the |
| +// local plugin's successful return to be that path, and only then does |
| +// Docs send the person to the page they came from, from its own sealed |
| +// return memory. So the posted return_to is remembered there and taken off |
| +// the form before Begin reads it, and put back on Begin's redirect to the |
| +// door (a problem, Sent, the Keymail continuation), so the next form there |
| +// posts it again and the chooser's links keep it. |
| +// |
| +// With SigninScreen on, Begin never answers with a redirect off this |
| +// origin: a Keymail address continues on the door (?continue=), whose |
| +// meta refresh leaves for Keymail, so form-action stays 'self'. |
| func (h *handlers) beginSignin(next http.HandlerFunc) http.HandlerFunc { |
| return func(w http.ResponseWriter, r *http.Request) { |
| - result := &signinResponse{header: make(http.Header)} |
| - next(result, r) |
| - destination := result.header.Get("Location") |
| - external := destination != "" && !strings.HasPrefix(destination, "/") |
| - if result.status == http.StatusSeeOther && external { |
| - if !keymailDestination(destination, h.origin) { |
| - h.fail(w, r, http.StatusBadGateway, failStatus) |
| - return |
| - } |
| - for _, cookie := range result.header.Values("Set-Cookie") { |
| - w.Header().Add("Set-Cookie", cookie) |
| - } |
| - w.Header().Set("Cache-Control", "no-store") |
| - w.Header().Set("Referrer-Policy", "no-referrer") |
| - data := signinPage{ |
| - Frame: h.frame(r, frameOptions{titleParts: []string{chrome.SignIn{}.Page()}, signinPage: true}), |
| - SubmitLabel: rastrillo.T(r, "docs.signin.keymail"), |
| - ContinueURL: destination, |
| - Door: chrome.SignInNotice{Icon: brand.Path("docs"), App: "Docs", Sky: sky.For(r.Host)}, |
| - } |
| - if err := h.render.page(w, r, "signin", data); err != nil { |
| - h.logger.Error("docs: render Keymail continuation", "err", err) |
| - h.fail(w, r, http.StatusInternalServerError, failStatus) |
| - } |
| - return |
| + to := "" |
| + if r.ParseForm() == nil { |
| + to = sessions.SafeReturnTo(r.PostForm.Get("return_to"), "") |
| + r.PostForm.Del("return_to") |
| + r.Form.Del("return_to") |
| } |
| - for name, values := range result.header { |
| - for _, value := range values { |
| - w.Header().Add(name, value) |
| - } |
| + if to != "" && h.rememberReturn != nil { |
| + h.rememberReturn(w, to) |
| } |
| - if result.status == 0 { |
| - result.status = http.StatusOK |
| + result := &signinResponse{header: make(http.Header)} |
| + next(result, r) |
| + if to != "" && result.status == http.StatusSeeOther { |
| + result.header.Set("Location", withReturnTo(result.header.Get("Location"), to)) |
| } |
| - w.WriteHeader(result.status) |
| - _, _ = w.Write(result.body.Bytes()) |
| + result.replay(w) |
| } |
| } |
| -// The destination comes only from the identity plugin's server-generated |
| -// redirect, never from return_to or another submitted URL. |
| -func keymailDestination(destination, origin string) bool { |
| - u, err := url.Parse(destination) |
| - if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Fragment != "" || u.Path != "/oauth/authorize" || u.RawPath != "" { |
| - return false |
| +// withReturnTo puts return_to on a redirect to the door, and leaves any |
| +// other Location as it is. |
| +func withReturnTo(location, to string) string { |
| + u, err := url.Parse(location) |
| + if err != nil || u.Scheme != "" || u.Host != "" || u.Path != "/signin" { |
| + return location |
| } |
| - q, err := url.ParseQuery(u.RawQuery) |
| - if err != nil { |
| - return false |
| + q := u.Query() |
| + if q.Has("return_to") { |
| + return location |
| } |
| - for _, key := range []string{"client_id", "redirect_uri", "scope", "code_challenge_method", "state", "code_challenge"} { |
| - if len(q[key]) != 1 || q.Get(key) == "" { |
| - return false |
| - } |
| - } |
| - origin = strings.TrimSuffix(origin, "/") |
| - return q.Get("client_id") == origin && q.Get("redirect_uri") == origin+"/auth/callback" && q.Get("scope") == "identify" && q.Get("code_challenge_method") == "S256" |
| + q.Set("return_to", to) |
| + u.RawQuery = q.Encode() |
| + return u.String() |
| } |
| type signinResponse struct { |
| @@ -122,8 +108,8 @@ type signinDoor struct { |
| // signinRefused is Config.Refused: Keymail or an emailed link verified |
| // an address the allowlist does not hold. It answers with the door, in a |
| // 403, with the refusal marked on the request context (refusedHere), so |
| -// the form is the way on. rastrillo has already set any cookies the |
| -// attempt clears. |
| +// the door draws it in the screen's app-problem slot with the email |
| +// field. rastrillo has already set any cookies the attempt clears. |
| // |
| // Rendered, not redirected to ?err=refused: a query parameter is |
| // something anybody can type, and the sentence means "you proved this |
| @@ -135,31 +121,15 @@ func (h *handlers) signinRefused(w http.ResponseWriter, r *http.Request) { |
| r.WithContext(context.WithValue(r.Context(), refusedKey{}, true))) |
| } |
| -// signinConfirm is the emailed link's confirm step: the door with one |
| -// Sign in button that POSTs the token back to /auth/verify, where |
| -// rastrillo spends it. The GET spends nothing, so a mail scanner that |
| -// fetches every link cannot sign anybody in. |
| -type signinConfirm struct { |
| - Heading, Submit string |
| - Action, Token string |
| -} |
| - |
| -// confirmSignin is Config.RenderConfirm. rastrillo has already set |
| -// no-store, Referrer-Policy strict-origin (the page's URL is a live |
| +// confirmSignin is Config.RenderConfirm, the page an emailed link opens |
| +// (GET /auth/verify): the door, whose SigninState answers StepConfirm on |
| +// this request alone, with one Sign in button that POSTs the token back, |
| +// where rastrillo spends it. The GET spends nothing, so a mail scanner |
| +// that fetches every link cannot sign anybody in. rastrillo has already |
| +// set no-store, Referrer-Policy strict-origin (the page's URL is a live |
| // credential) and the framing refusals; nothing here may loosen them. |
| -// The words are estilo's door copy: the heading and the button are the |
| -// form's own "Sign in", so the step reads as the door, not a new page. |
| -func (h *handlers) confirmSignin(w http.ResponseWriter, r *http.Request, d rauth.ConfirmPageData) { |
| - door := chrome.SignIn{} |
| - data := signinPage{ |
| - Frame: h.frame(r, frameOptions{titleParts: []string{door.Page()}, signinPage: true}), |
| - Confirm: &signinConfirm{Heading: door.Heading(), Submit: door.Submit(), Action: d.Action, Token: d.Token}, |
| - Door: chrome.SignInNotice{Icon: brand.Path("docs"), App: "Docs", Sky: sky.For(r.Host)}, |
| - } |
| - if err := h.render.page(w, r, "signin", data); err != nil { |
| - h.logger.Error("docs: render sign-in confirm", "err", err) |
| - h.fail(w, r, http.StatusInternalServerError, failStatus) |
| - } |
| +func (h *handlers) confirmSignin(w http.ResponseWriter, r *http.Request, _ rauth.ConfirmPageData) { |
| + h.signin(w, r) |
| } |
| // refusedKey marks a request signinRefused is answering with the door. |
diff --git a/internal/docs/auth_navigation_test.go b/internal/docs/auth_navigation_test.go| index 9288162..cb51ae0 100644 |
| --- a/internal/docs/auth_navigation_test.go |
| +++ b/internal/docs/auth_navigation_test.go |
| @@ -1,92 +1,59 @@ |
| package docs |
| import ( |
| - "encoding/json" |
| - "html" |
| "net/http" |
| "net/http/httptest" |
| "net/url" |
| - "os" |
| - "path/filepath" |
| "strings" |
| "testing" |
| - |
| - "github.com/keymaildev/signin" |
| ) |
| -func TestKeymailContinuation(t *testing.T) { |
| +// The door's forms post return_to, and beginSignin keeps it Docs' way: in |
| +// the sealed return memory read at /auth/local/complete, off the form Begin |
| +// reads (so rastrillo lands the session on localLinkCompletePath, where |
| +// connect resumes a pending link), and back on Begin's redirect to the door. |
| +func TestBeginSigninKeepsTheReturnDocsWay(t *testing.T) { |
| app := newAllowlistedTestApp(t, "alice@example.test") |
| - app.handlers.origin = "https://docs.example.test" |
| - destination := (&signin.Keymail{Base: "https://keymail.example.test", Origin: app.handlers.origin}).AuthorizeURL("state", "challenge", true) |
| - handler := app.handlers.beginSignin(func(w http.ResponseWriter, r *http.Request) { |
| - http.SetCookie(w, &http.Cookie{Name: "__Host-pending", Value: "opaque", Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| - http.Redirect(w, r, destination, http.StatusSeeOther) |
| - }) |
| - rec := httptest.NewRecorder() |
| - policy := homeFormPolicy("https://home.example.test") |
| - rec.Header().Set("Content-Security-Policy", policy) |
| - handler(rec, httptest.NewRequest("POST", "/signin", nil)) |
| - if rec.Code != 200 || rec.Header().Get("Location") != "" { |
| - t.Fatalf("status=%d location=%q", rec.Code, rec.Header().Get("Location")) |
| - } |
| - if rec.Header().Get("Content-Security-Policy") != policy { |
| - t.Fatal("CSP changed") |
| - } |
| - if rec.Header().Get("Cache-Control") != "no-store" || rec.Header().Get("Referrer-Policy") != "no-referrer" { |
| - t.Fatal("continuation must not cache or disclose the referring URL") |
| - } |
| - cookies := rec.Result().Cookies() |
| - if len(cookies) != 1 || cookies[0].Name != "__Host-pending" || cookies[0].Value != "opaque" || !cookies[0].Secure || !cookies[0].HttpOnly || cookies[0].SameSite != http.SameSiteLaxMode { |
| - t.Fatalf("lost pending cookie: %v", cookies) |
| - } |
| - body := html.UnescapeString(rec.Body.String()) |
| - for _, part := range []string{`http-equiv="refresh"`, `content="0;url=` + destination + `"`, `href="` + destination + `"`} { |
| - if !strings.Contains(body, part) { |
| - t.Fatalf("missing continuation component %q", part) |
| - } |
| - } |
| - if strings.Contains(body, `action="/signin"`) { |
| - t.Fatal("continuation rendered another sign-in form") |
| - } |
| - // It is the door's card on the sky, not a bare page. |
| - for _, part := range []string{"estilo-door", "estilo-sky-layer", "<span>Docs</span>"} { |
| - if !strings.Contains(body, part) { |
| - t.Fatalf("continuation is not the door: lacks %q", part) |
| - } |
| - } |
| - if dir := os.Getenv("DOCS_OAUTH_BROWSER_FIXTURE"); dir != "" { |
| - if err := os.MkdirAll(dir, 0700); err != nil { |
| - t.Fatal(err) |
| - } |
| - data, err := json.Marshal(map[string]any{"body": rec.Body.String(), "headers": rec.Header(), "destination": destination}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.WriteFile(filepath.Join(dir, "continuation.json"), data, 0600); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| -} |
| - |
| -func TestKeymailDestinationRefusals(t *testing.T) { |
| - origin := "https://docs.example.test" |
| - valid := (&signin.Keymail{Base: "https://keymail.example.test", Origin: origin}).AuthorizeURL("state", "challenge", false) |
| - for _, target := range []string{ |
| - "javascript:alert(1)", "//keymail.example.test/oauth/authorize", strings.Replace(valid, "https:", "http:", 1), |
| - strings.Replace(valid, "keymail.example.test", "user@keymail.example.test", 1), valid + "#fragment", valid + "&state=duplicate", |
| - strings.Replace(valid, "/oauth/authorize", "/other", 1), strings.ReplaceAll(valid, url.QueryEscape(origin), url.QueryEscape("https://foreign.example.test")), |
| - strings.Replace(valid, "S256", "plain", 1), |
| + for _, tc := range []struct { |
| + name, posted, location, want string |
| + remembered bool |
| + }{ |
| + {name: "sent", posted: "/d/abc", location: "/signin?sent=1&attempt=x", want: "/signin?attempt=x&return_to=%2Fd%2Fabc&sent=1", remembered: true}, |
| + {name: "problem", posted: "/d/abc?x=1", location: "/signin?err=rate", want: "/signin?err=rate&return_to=%2Fd%2Fabc%3Fx%3D1", remembered: true}, |
| + {name: "continuation", posted: "/d/abc", location: "/signin?continue=id", want: "/signin?continue=id&return_to=%2Fd%2Fabc", remembered: true}, |
| + {name: "already carried", posted: "/d/abc", location: "/signin?err=rate&return_to=%2Fother", want: "/signin?err=rate&return_to=%2Fother", remembered: true}, |
| + {name: "elsewhere", posted: "/d/abc", location: "/auth/local/complete", want: "/auth/local/complete", remembered: true}, |
| + {name: "off-site", posted: "//evil.example/x", location: "/signin?sent=1", want: "/signin?sent=1"}, |
| + {name: "none", posted: "", location: "/signin?sent=1", want: "/signin?sent=1"}, |
| } { |
| - if keymailDestination(target, origin) { |
| - t.Fatalf("accepted %q", target) |
| - } |
| - } |
| - app := newAllowlistedTestApp(t, "alice@example.test") |
| - app.handlers.origin = origin |
| - rec := httptest.NewRecorder() |
| - app.handlers.beginSignin(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "https://foreign.example.test", 303) })(rec, httptest.NewRequest("POST", "/signin", nil)) |
| - if rec.Code != 502 || rec.Header().Get("Location") != "" { |
| - t.Fatalf("invalid redirect status=%d location=%q", rec.Code, rec.Header().Get("Location")) |
| + t.Run(tc.name, func(t *testing.T) { |
| + seen := "unset" |
| + next := func(w http.ResponseWriter, r *http.Request) { |
| + seen = r.PostFormValue("return_to") + r.FormValue("return_to") |
| + http.Redirect(w, r, tc.location, http.StatusSeeOther) |
| + } |
| + form := url.Values{"address": {"alice@example.test"}} |
| + if tc.posted != "" { |
| + form.Set("return_to", tc.posted) |
| + } |
| + req := httptest.NewRequest("POST", "/signin", strings.NewReader(form.Encode())) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + rec := httptest.NewRecorder() |
| + app.handlers.beginSignin(next)(rec, req) |
| + if seen != "" { |
| + t.Fatalf("Begin read return_to %q; it must land on /auth/local/complete", seen) |
| + } |
| + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != tc.want { |
| + t.Fatalf("redirect %d %q, want %q", rec.Code, rec.Header().Get("Location"), tc.want) |
| + } |
| + remembered := false |
| + for _, c := range rec.Result().Cookies() { |
| + remembered = remembered || c.Name == homeReturnCookie && c.MaxAge > 0 |
| + } |
| + if remembered != tc.remembered { |
| + t.Fatalf("return remembered = %v, want %v", remembered, tc.remembered) |
| + } |
| + }) |
| } |
| } |
diff --git a/internal/docs/auth_test.go b/internal/docs/auth_test.go| index e2d404a..c4b5acb 100644 |
| --- a/internal/docs/auth_test.go |
| +++ b/internal/docs/auth_test.go |
| @@ -1,6 +1,7 @@ |
| package docs_test |
| import ( |
| + "html" |
| "net/http" |
| "net/http/httptest" |
| "strings" |
| @@ -115,10 +116,10 @@ func TestSignInPageRendersSignedOut(t *testing.T) { |
| t.Fatalf("GET /signin: status %d, want 200", rec.Code) |
| } |
| body := rec.Body.String() |
| - if !strings.Contains(body, `<label rst-field-label for="estilo-signin-address">Email address</label>`) { |
| + if !strings.Contains(body, `<label rst-field-label for="rst-signin-email">Email</label>`) { |
| t.Error("email input has no persistent associated translated label") |
| } |
| - if !strings.Contains(body, `type="email" id="estilo-signin-address" name="address" required autofocus autocomplete="email"`) { |
| + if !strings.Contains(body, `type="email" id="rst-signin-email" name="address" required autofocus autocomplete="email"`) { |
| t.Error("label target must remain the required, focused email input with email autocomplete") |
| } |
| @@ -238,17 +239,12 @@ func TestSecondClickOfTheSameMagicLinkOffersRecovery(t *testing.T) { |
| signinReq := httptest.NewRequest(http.MethodGet, loc, nil) |
| signinRec := httptest.NewRecorder() |
| app.Handler().ServeHTTP(signinRec, signinReq) |
| - // NewForTest's app.Handler() never wires rastrillo.Options.BaseCatalog/ |
| - // Locales — only cmd/docs/main.go does, for real serving — so |
| - // rastrillo.T falls back to returning its key verbatim here |
| - // (render.go's own doc comment on Locales: "documented, harmless"). |
| - // That makes the raw catalog key the correct, precise thing to |
| - // assert on in this handler-level test: it pins exactly which |
| - // branch of signin's switch ran, without depending on the English |
| - // copy's exact wording. |
| - body := signinRec.Body.String() |
| - if !strings.Contains(body, "docs.signin.error.expired") { |
| - t.Errorf("signin page after a second click did not resolve docs.signin.error.expired; body: %s", body) |
| + // The words are rastrillo's sign-in screen's (the smart door), from its |
| + // own English catalog: the expired problem, with the email field to |
| + // send a new link. |
| + body := html.UnescapeString(signinRec.Body.String()) |
| + if !strings.Contains(body, "That link has expired or was already used. Send a new one.") || !strings.Contains(body, `name="address"`) { |
| + t.Errorf("signin page after a second click does not say the link expired, with the field; body: %s", body) |
| } |
| if strings.Contains(body, "docs.error.generic") { |
| t.Errorf("signin page after a second click fell back to the app-wide docs.error.generic instead of the sign-in-specific expired copy") |
| @@ -279,9 +275,16 @@ func TestSigninUnrecognizedErrorUsesSigninSpecificFallback(t *testing.T) { |
| req := httptest.NewRequest(http.MethodGet, "/signin?err="+errParam, nil) |
| rec := httptest.NewRecorder() |
| app.Handler().ServeHTTP(rec, req) |
| - body := rec.Body.String() |
| - if !strings.Contains(body, "docs.signin.error.unknown") { |
| - t.Errorf("err=%q: signin page did not resolve docs.signin.error.unknown; body: %s", errParam, body) |
| + // rastrillo's screen answers keymail with its own problem, and any |
| + // other err (a raw Begin failure, or one nobody has written yet) |
| + // with its generic sign-in problem, never Docs' app-wide string. |
| + body := html.UnescapeString(rec.Body.String()) |
| + want := "Something went wrong. Try again." |
| + if errParam == "keymail" { |
| + want = "Keymail couldn't confirm it's you." |
| + } |
| + if !strings.Contains(body, want) || !strings.Contains(body, `name="address"`) { |
| + t.Errorf("err=%q: signin page does not say %q with the field; body: %s", errParam, want, body) |
| } |
| if strings.Contains(body, "docs.error.generic") { |
| t.Errorf("err=%q: signin page fell back to the app-wide docs.error.generic instead of the sign-in-specific fallback", errParam) |
diff --git a/internal/docs/chrome.go b/internal/docs/chrome.go| index 60696e9..aeeeae2 100644 |
| --- a/internal/docs/chrome.go |
| +++ b/internal/docs/chrome.go |
| @@ -28,7 +28,11 @@ import ( |
| type Frame struct { |
| Chrome chrome.Bar |
| TitleParts []string |
| - Theme string |
| + // Title, when set, is the whole <title>, which then does not add the |
| + // app's name: the sign-in door's title is rastrillo's, and it already |
| + // names Docs ("Sign in to Docs"). |
| + Title string |
| + Theme string |
| } |
| // frameOptions describes one page's chrome. The zero value is a plain |
| @@ -36,6 +40,8 @@ type Frame struct { |
| type frameOptions struct { |
| // titleParts precede "Docs" in <title>, most specific first. |
| titleParts []string |
| + // title replaces the whole <title> (Frame.Title). |
| + title string |
| // context is the open object's title; edit replaces it with the |
| // editable title when the person may rename. |
| context string |
| @@ -92,7 +98,7 @@ func (h *handlers) frame(r *http.Request, o frameOptions) Frame { |
| default: |
| bar.SignIn = &chrome.Link{Href: "/signin?return_to=" + url.QueryEscape(returnTarget(r)), Label: rastrillo.T(r, "docs.chrome.signin")} |
| } |
| - return Frame{Chrome: bar, TitleParts: o.titleParts, Theme: chrome.ThemeAttr(chrome.Appearance(r))} |
| + return Frame{Chrome: bar, TitleParts: o.titleParts, Title: o.title, Theme: chrome.ThemeAttr(chrome.Appearance(r))} |
| } |
| // returnTarget is where a person should come back to: this page, if it |
diff --git a/internal/docs/chrome_test.go b/internal/docs/chrome_test.go| index 24da549..21ba79a 100644 |
| --- a/internal/docs/chrome_test.go |
| +++ b/internal/docs/chrome_test.go |
| @@ -41,7 +41,10 @@ func titleOf(body string) string { |
| } |
| // Every page's <title> is "{part} · {part} · Docs", built by the layout |
| -// alone (spec §10): the root is just the app's name. |
| +// alone (spec §10): the root is just the app's name. The sign-in door is |
| +// the one exception: its title is rastrillo's for the state it shows |
| +// (estilo-signin-screen-title), which already names Docs, so that the tab |
| +// and the heading always say the same thing. |
| func TestPageTitlesFollowTheSuitePattern(t *testing.T) { |
| app, _ := docs.NewForTest(t) |
| alice := signInCookies(t, app, "alice@example.com") |
| @@ -56,8 +59,10 @@ func TestPageTitlesFollowTheSuitePattern(t *testing.T) { |
| {"search", "/?q=min", alice, "“min” · docs.app.name"}, |
| {"document", "/d/" + sqid, alice, "Minutes · docs.app.name"}, |
| {"share", "/d/" + sqid + "/share", alice, "docs.share.title · Minutes · docs.app.name"}, |
| - {"sign in", "/signin", nil, "Sign in · docs.app.name"}, |
| - {"sent", "/signin?sent=1", nil, "Check your email · docs.app.name"}, |
| + {"sign in", "/signin", nil, "Sign in to Docs"}, |
| + {"other ways", "/signin?ways=1", nil, "Other ways to sign in to Docs"}, |
| + {"problem", "/signin?err=rate", nil, "Problem signing in to Docs"}, |
| + {"sent", "/signin?sent=1", nil, "Check your email to sign in to Docs"}, |
| {"signed out", "/signed-out", nil, "Signed out · docs.app.name"}, |
| } |
| for _, c := range cases { |
diff --git a/internal/docs/handlers.go b/internal/docs/handlers.go| index a44e270..9f613ab 100644 |
| --- a/internal/docs/handlers.go |
| +++ b/internal/docs/handlers.go |
| @@ -22,6 +22,7 @@ import ( |
| estilomenu "amadan.net/oficina/estilo.git/menu" |
| "amadan.net/oficina/estilo.git/savestatus" |
| "amadan.net/rastrillo/rastrillo" |
| + rauth "amadan.net/rastrillo/rastrillo/auth" |
| "github.com/carlosframework/docs/internal/core" |
| "github.com/carlosframework/docs/internal/export" |
| @@ -114,9 +115,16 @@ type handlers struct { |
| // switcher's "All apps", empty when none is configured. |
| peek func(*http.Request) (string, bool) |
| directory string |
| - // remembered is the page a sign-in in progress will return to |
| - // (signin_return.go), "/" when none. |
| - remembered func(*http.Request) string |
| + // auth is rastrillo's sign-in plugin: the door reads SigninState from |
| + // it and writes PrepareSigninResponse through it (auth.go's signin). |
| + auth *rauth.Auth |
| + // rememberReturn keeps the page a sign-in began from for the local |
| + // landing (signin_return.go, home_return.go): Home's return memory, or |
| + // the standalone one. |
| + rememberReturn func(http.ResponseWriter, string) bool |
| + // homeIssuer is Home's issuer when Home is configured, "" otherwise: |
| + // where the signed-out page's Forget chains to (auth.go's forget). |
| + homeIssuer string |
| } |
| // listPage is GET /'s view data (spec §6.4). Title and the group |
diff --git a/internal/docs/home_connect.go b/internal/docs/home_connect.go| index c9c5388..517b19c 100644 |
| --- a/internal/docs/home_connect.go |
| +++ b/internal/docs/home_connect.go |
| @@ -11,10 +11,13 @@ package docs |
| // request; the hooks only decide who a Home subject is). |
| // |
| // What stays Docs' own, and why: |
| -// - GET /signin skips the form only for a session the signed-in routes |
| -// would admit (h.handlers.admitted), not merely one that exists, or a |
| -// guest whose last share was revoked loops between / and /signin |
| -// (Astra, #65). |
| +// - GET /signin and /signin/oficina skip the door only for a session the |
| +// signed-in routes would admit (h.handlers.admitted), not merely one |
| +// that exists, or a guest whose last share was revoked loops between / |
| +// and /signin (Astra, #65). |
| +// - The sign-in door is Docs' (auth.go's signin), and so is remembering a |
| +// Home sign-in as Oficina ID (rememberOficina): connect imports no |
| +// lastsignin. |
| // - A local sign-in lands on the page it began from (spec §9.4). connect |
| // lands it on LocalLandingPath, so Docs keeps its own sealed return |
| // memory (home_return.go) beside connect's and substitutes it there. |
| @@ -26,7 +29,6 @@ import ( |
| "encoding/base64" |
| "errors" |
| "net/http" |
| - "net/url" |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/connect/linkstore" |
| @@ -36,6 +38,7 @@ import ( |
| "amadan.net/rastrillo/rastrillo" |
| rauth "amadan.net/rastrillo/rastrillo/auth" |
| "amadan.net/rastrillo/rastrillo/csrf" |
| + "amadan.net/rastrillo/rastrillo/lastsignin" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "github.com/carlosframework/docs/internal/docs/principalstore" |
| "github.com/go-chi/chi/v5" |
| @@ -69,6 +72,9 @@ type homeRoutes struct { |
| team *teamRuntime |
| // handlers is set by mount; render reads it. |
| handlers *handlers |
| + // jar is rastrillo auth's remembered way in (auth.RememberJar), set by |
| + // mount: a Home sign-in is remembered here, as Oficina ID. |
| + jar *lastsignin.Jar |
| } |
| // newHome builds connect's Bridge over Docs' people and sessions. New calls |
| @@ -97,7 +103,11 @@ func newHome(settings *homeSettings, origin string, db *sql.DB, store *Store, te |
| Keys: settings.keys, DEK: settings.dek, SessionCookie: h.sessionCookie, |
| ReadSession: h.readSession, |
| MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error { |
| - return sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}) |
| + if err := sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}); err != nil { |
| + return err |
| + } |
| + h.rememberOficina(w, r) |
| + return nil |
| }, |
| // The native app's session (connect.NativeExchange): the same |
| // store and cookie name, minted without a cookie and handed back |
| @@ -132,14 +142,35 @@ func (h *homeRoutes) mount(handlers *handlers, auth *rauth.Auth) error { |
| LocalLandingPath: "/", Namespace: homeNamespace, Origin: h.origin, Issuer: h.issuer, SessionCookie: h.sessionCookie, |
| FormPolicy: homeFormPolicy(h.issuer), DEK: h.dek, ReadSession: h.readSession, SignOut: h.sessions.SignOut, |
| LocalSignin: handlers.signin, Protect: csrf.Protect(h.origin), Render: h.render, |
| + ForgetPath: signinForgetPath, |
| }) |
| if err != nil { |
| return errHomeConfig |
| } |
| - h.routes, h.handlers = routes, handlers |
| + h.routes, h.handlers, h.jar = routes, handlers, auth.RememberJar() |
| return nil |
| } |
| +// rememberOficina is the smart door's memory of a Home sign-in, written in |
| +// MintHomeSession once the session is stored, so it is written only where |
| +// connect turns a Home sign-in into a session here (a finished exchange, |
| +// "I'm new here"), never on link, choose, unknown or failed. The record is |
| +// Oficina ID, with the address of the person connect resolved for this |
| +// very sign-in (connect.MintedPerson), or none for a Home-only person. |
| +// Nothing is carried over from the record it replaces: that address could |
| +// be somebody else's. Remembering is a convenience, and Remember fails |
| +// silently, so it can never fail the sign-in. |
| +func (h *homeRoutes) rememberOficina(w http.ResponseWriter, r *http.Request) { |
| + if h.jar == nil { |
| + return |
| + } |
| + address := "" |
| + if p, ok := connect.MintedPerson(r); ok { |
| + address = p.Label |
| + } |
| + h.jar.Remember(w, lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: address}) |
| +} |
| + |
| // readSession is the actual cookie-backed session, never a supplied one. |
| func (h *homeRoutes) readSession(r *http.Request) (*connect.Session, error) { |
| s, ok := h.sessions.From(r) |
| @@ -278,10 +309,17 @@ func (h *homeRoutes) render(w http.ResponseWriter, r *http.Request, state, label |
| h.handlers.render.homeLinkBack(w, r, state, label, back, status) |
| } |
| +// mountPublic mounts the sign-in door's three routes (home/connect |
| +// MIGRATING.md, step 6): /signin is always the door, offering Continue |
| +// with Oficina ID; /signin/local is the door with email as the one way in, |
| +// where connect sends people Oficina ID cannot help; /signin/oficina |
| +// starts the Home exchange. connect hands both door routes to Docs' door |
| +// (RoutesConfig.LocalSignin, handlers.signin). |
| func (h *homeRoutes) mountPublic(r chi.Router) { |
| - r.Get("/signin", h.signin) |
| + r.Get(connect.SigninPath, h.admittedOnly(h.routes.SigninDoor)) |
| + r.Get(connect.SigninLocalPath, h.routes.SigninLocal) |
| + r.Get(connect.SigninOficinaPath, h.admittedOnly(h.routes.SigninOficina)) |
| r.Get("/signed-out", h.routes.SignedOut) |
| - r.Get("/signin/local", h.handlers.signin) |
| r.Get(localLinkCompletePath, h.localComplete) |
| r.Get(handoff.StartPath, h.bridge.Start) |
| r.Post(handoff.CallbackPath, h.bridge.Callback) |
| @@ -308,44 +346,19 @@ func (h *homeRoutes) mountAccount(r chi.Router) { |
| r.Post("/account/home/confirm", h.routes.ConfirmPost) |
| } |
| -// signin is GET /signin with Home configured. |
| -func (h *homeRoutes) signin(w http.ResponseWriter, r *http.Request) { |
| - q, err := url.ParseQuery(r.URL.RawQuery) |
| - if err != nil { |
| - h.render(w, r, "failed", "", http.StatusBadRequest) |
| - return |
| - } |
| - // These are outcomes from the existing local email flow. Keep its form |
| - // available even when the browser already has a Home session. |
| - if q.Has("sent") || q.Has("err") || q.Has("force") { |
| - h.handlers.signin(w, r) |
| - return |
| - } |
| - // Already signed in to Docs: straight back, with no form and no new |
| - // Home exchange (spec §9.2). Admitted, not merely holding a session: a |
| - // refused identity must be able to reach sign-in, or the guard and |
| - // this shortcut redirect to each other forever (h.handlers.admitted). |
| - _, signedIn := h.sessions.From(r) |
| - if signedIn && h.handlers.admitted(r) { |
| - alreadySignedIn(w, r) |
| - return |
| - } |
| - path, ok := requestedReturn(r) |
| - if !ok { |
| - path = "/" |
| - } |
| - if !h.returns.rememberReturn(w, path) { |
| - h.render(w, r, "failed", "", http.StatusServiceUnavailable) |
| - return |
| - } |
| - // connect remembers the page for the link flow and starts the Home |
| - // exchange. Its own shortcut skips to the page for any live session, |
| - // which for a session admission refuses is the loop above, so it is |
| - // not shown that one. |
| - if signedIn { |
| - r = withoutCookie(r, h.sessionCookie) |
| +// admittedOnly runs connect's SigninDoor or SigninOficina for a browser |
| +// whose session the signed-in routes would admit, and as signed out for |
| +// any other. Both take any live session cookie as signed in and send it |
| +// straight to the page; a session admission refuses (a guest whose last |
| +// share was revoked, a removed member) would then loop between that page |
| +// and /signin forever (Astra, #65), so they are not shown that cookie. |
| +func (h *homeRoutes) admittedOnly(next http.HandlerFunc) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + if _, signedIn := h.sessions.From(r); signedIn && !h.handlers.admitted(r) { |
| + r = withoutCookie(r, h.sessionCookie) |
| + } |
| + next(w, r) |
| } |
| - h.routes.SigninOficina(w, r) |
| } |
| // localComplete is where a local sign-in lands. connect resumes a link from |
| @@ -437,7 +450,8 @@ func homeCookie(r *http.Request, name string) (value string, present, valid bool |
| } |
| // withoutCookie is r, as seen by a handler that must not see the named |
| -// cookie. Only Docs' /signin uses it, on connect's Signin. |
| +// cookie. Only admittedOnly uses it, on connect's SigninDoor and |
| +// SigninOficina. |
| func withoutCookie(r *http.Request, name string) *http.Request { |
| c := r.Clone(r.Context()) |
| c.Header.Del("Cookie") |
diff --git a/internal/docs/home_connect_linked_test.go b/internal/docs/home_connect_linked_test.go| index f27f631..e159adf 100644 |
| --- a/internal/docs/home_connect_linked_test.go |
| +++ b/internal/docs/home_connect_linked_test.go |
| @@ -1,6 +1,7 @@ |
| package docs |
| import ( |
| + "html" |
| "net/http/httptest" |
| "net/url" |
| "strings" |
| @@ -141,7 +142,17 @@ func TestHomeLocalSignInReturnsToTheDeepLink(t *testing.T) { |
| deep := routerRedirect(t, owner.do("POST", "/documents", "title=Minutes"), "") + "?view=1" |
| b := f.browser() |
| signin := routerRedirect(t, b.do("GET", deep, ""), "/signin?return_to="+url.QueryEscape(deep)) |
| - routerRedirect(t, b.do("GET", signin, ""), "/auth/start?return_to="+url.QueryEscape(deep)) |
| + // /signin is the door now (Home spec 2026-11-19-smart-door.md), and |
| + // Continue with Oficina ID carries the deep link to /signin/oficina. |
| + door := b.do("GET", signin, "") |
| + oficina := "/signin/oficina?return_to=" + url.QueryEscape(deep) |
| + if door.Code != 200 || !strings.Contains(door.Body.String(), `href="`+html.EscapeString(oficina)+`"`) { |
| + t.Fatalf("the door does not offer Oficina ID with the deep link (%d)", door.Code) |
| + } |
| + if b.cookies[homeReturnCookie] == nil { |
| + t.Fatal("the door did not remember the deep link for the local landing") |
| + } |
| + routerRedirect(t, b.do("GET", oficina, ""), "/auth/start?return_to="+url.QueryEscape(deep)) |
| if b.cookies[homeReturnCookie] == nil || b.cookies[connectReturnCookie] == nil { |
| t.Fatal("the deep link was not remembered for both landings") |
| } |
diff --git a/internal/docs/home_render.go b/internal/docs/home_render.go| index 228a8a4..4b961f7 100644 |
| --- a/internal/docs/home_render.go |
| +++ b/internal/docs/home_render.go |
| @@ -46,9 +46,20 @@ func (rd *renderer) homeLinkBack(w http.ResponseWriter, r *http.Request, state, |
| page.Action = "/signin/local" |
| page.ActionLabel = rastrillo.T(r, key+"local_action") |
| case "signedout": |
| - // The signed-out page (spec §9.2), in the door's words, with Sign |
| - // in going back through Home when it is configured. |
| - notice := chrome.SignInNotice{Icon: brand.Path("docs"), App: "Docs", Sky: sky.For(r.Host)}.SignedOut("/signin") |
| + // The signed-out page (spec §9.2), in the door's words: Sign in, |
| + // then the quiet "Forget me on this device" (the smart-door spec's |
| + // "Signed out"), a POST to rastrillo auth's Forget. With Home |
| + // configured the page is connect's SignedOut, which carries that |
| + // path (RoutesConfig.ForgetPath) for PageFor, and the form also |
| + // asks Docs to go on to Oficina ID's own Forget once this one has |
| + // answered (auth.go's forget). Standalone, it is Docs' own path. |
| + p := connect.PageFor(r, "signedout", "") |
| + forget, chain := p.ForgetAction, []chrome.Hidden{{Name: "chain", Value: oficinaChain}} |
| + if forget == "" { |
| + forget, chain = signinForgetPath, nil |
| + } |
| + notice := chrome.SignInNotice{Icon: brand.Path("docs"), App: "Docs", Sky: sky.For(r.Host)}. |
| + SignedOut(p.Action).Forgetting(forget, "", chain...) |
| page.SignedOut, page.Title = ¬ice, notice.Page() |
| case "choose": |
| // A roster member with no account here yet (Home spec |
diff --git a/internal/docs/home_router_integration_test.go b/internal/docs/home_router_integration_test.go| index 278b4c1..6e0d70e 100644 |
| --- a/internal/docs/home_router_integration_test.go |
| +++ b/internal/docs/home_router_integration_test.go |
| @@ -263,7 +263,11 @@ func TestHomeRouterExistingAccountRoundTripPreservesOwnedAndSharedContent(t *tes |
| if err != nil || parsed.Path != "/signin" || parsed.Query().Get("return_to") != resource { |
| t.Fatal("unsigned document lost original destination") |
| } |
| - start := routerRedirect(t, b.do("GET", signin, ""), "") |
| + // The door, then Continue with Oficina ID, which keeps the resource. |
| + if door := b.do("GET", signin, ""); door.Code != 200 { |
| + t.Fatal("the door did not render", door.Code) |
| + } |
| + start := routerRedirect(t, b.do("GET", "/signin/oficina?return_to="+url.QueryEscape(resource), ""), "") |
| nonce := b.start(t, start, "") |
| unknown := b.exchange(t, nonce, "opaque-alice", time.Now().Add(-time.Hour)) |
| if unknown.Code != 403 || !strings.Contains(unknown.Body.String(), "/signin/local") { |
| @@ -308,8 +312,8 @@ func TestHomeRouterExistingAccountRoundTripPreservesOwnedAndSharedContent(t *tes |
| if oldRec.Code != 303 { |
| t.Fatal("actual signout did not revoke old session") |
| } |
| - signin = routerRedirect(t, b.do("GET", resource, ""), "") |
| - start = routerRedirect(t, b.do("GET", signin, ""), "") |
| + routerRedirect(t, b.do("GET", resource, ""), "") |
| + start = routerRedirect(t, b.do("GET", "/signin/oficina?return_to="+url.QueryEscape(resource), ""), "") |
| nonce = b.start(t, start, "") |
| originalAuth := time.Now().Add(-2 * time.Hour).Truncate(time.Second) |
| routerRedirect(t, b.exchange(t, nonce, "opaque-alice", originalAuth), resource) |
| @@ -441,11 +445,11 @@ func TestHomeRouterStaleLocalGestureRestartsWithoutResumingProof(t *testing.T) { |
| if _, err := f.app.db.Writer().Exec(`UPDATE sessions SET created_at=? WHERE token_hash=?`, time.Now().Add(-6*time.Minute).UTC().Format(time.RFC3339), sessions.HashToken(oldSession.Value)); err != nil { |
| t.Fatal(err) |
| } |
| - routerRedirect(t, b.do("GET", "/account/home", ""), "/signin/local") |
| + routerRedirect(t, b.do("GET", "/account/home", ""), "/signin/local?reauth=1") |
| if b.cookies[localLinkNavigationCookie] == nil || b.cookies[homeInitCookie] != nil || b.cookies[homeProofCookie] != nil { |
| t.Fatal("stale local restart retained link browser proof") |
| } |
| - if rec := b.do("GET", "/signin/local", ""); rec.Code != 200 { |
| + if rec := b.do("GET", "/signin/local?reauth=1", ""); rec.Code != 200 { |
| t.Fatal("signed-in stale visitor could not see local signin") |
| } |
| path := b.localLink(t, "alice@example.com") |
diff --git a/internal/docs/render.go b/internal/docs/render.go| index 5786c5d..abde83f 100644 |
| --- a/internal/docs/render.go |
| +++ b/internal/docs/render.go |
| @@ -6,9 +6,11 @@ import ( |
| "bytes" |
| "embed" |
| "fmt" |
| + "html" |
| "html/template" |
| "io/fs" |
| "net/http" |
| + "strings" |
| "testing/fstest" |
| "amadan.net/oficina/estilo.git/base" |
| @@ -406,30 +408,15 @@ var Catalog = rastrillo.Catalog{ |
| "docs.import.report.line_break_split": "Line breaks became new paragraphs: {count}.", |
| "docs.import.report.page_break_split": "Page and column breaks became new paragraphs: {count}.", |
| - // docs.signin.* — GET /signin (auth.go's signin handler): the |
| - // form itself, and every outcome rastrillo/auth's own handlers |
| - // redirect back here with (?sent=1, |
| - // ?err=rate|address|expired|keymail|1). docs.signin.error.unknown |
| - // is that switch's own default: branch (fix round 1 on Task 3): |
| - // every one of these outcomes means the same operational thing on |
| - // this one page — sign-in did not complete, ask for a new link — |
| - // so its fallback must not borrow docs.error.generic ("Something |
| - // went wrong."), an app-wide string written for a render failure |
| - // with nowhere else to land, not for this page's own normal, |
| - // recoverable outcomes. See auth.go's signin handler for why no |
| - // finer distinction between ?err=keymail and ?err=1 is drawn |
| - // either (rastrillo/auth's own handlers already refuse to be an |
| - // oracle between "wrong" and "unknown"). |
| - // |
| - // The door's own words (heading, label, help, submit, the sent state |
| - // and the signed-out page) are estilo's chrome.English, not keys here: |
| - // one copy set for the suite. What stays is this app's: the outcome |
| - // errors, and the Keymail continuation's button. |
| - "docs.signin.keymail": "Continue to Keymail", |
| - "docs.signin.error.rate": "Too many attempts. Wait a few minutes, then try again.", |
| - "docs.signin.error.address": "That doesn’t look like an email address.", |
| - "docs.signin.error.expired": "That link has expired or was already used. Enter your email to get a new one.", |
| - "docs.signin.error.unknown": "We couldn’t sign you in. Enter your email to get a new link.", |
| + // docs.signin.* — the sign-in door (auth.go's signin). The door's own |
| + // words, every outcome rastrillo's handlers redirect back with |
| + // (?sent=1, ?err=rate|address|expired|keymail|1) and the Keymail |
| + // continuation are rastrillo's sign-in screen copy |
| + // (rastrillo.ui.signin_*), and the signed-out page is estilo's |
| + // chrome.English. What stays is what only Docs knows: the refusal |
| + // (Config.Refused, the screen's app-problem slot), and the name of the |
| + // federated door, which rastrillo draws as "Continue with {name}". |
| + "docs.signin.oficina_id": "Oficina ID", |
| "docs.signin.error.refused": "That address can’t sign in to Docs. Use a different address, or ask whoever runs this team to add it.", |
| // docs.signout.label is the sign-out control's text — both its |
| @@ -789,6 +776,19 @@ func (rd *renderer) pageStatus(w http.ResponseWriter, r *http.Request, name stri |
| return writeGuardedBody(w, r, status, buf.Bytes()) |
| } |
| +// signinTitle is the sign-in door's <title>: estilo's |
| +// estilo-signin-screen-title, which is rastrillo's signin-title for the |
| +// same state, so the tab and the heading always say the same thing. The |
| +// template writes escaped text, and the layout escapes the title again, |
| +// so it is unescaped here. |
| +func (rd *renderer) signinTitle(screen chrome.SignInScreen) (string, error) { |
| + title, err := rd.fragment("signin", "estilo-signin-screen-title", screen) |
| + if err != nil { |
| + return "", err |
| + } |
| + return strings.TrimSpace(html.UnescapeString(string(title))), nil |
| +} |
| + |
| // fragment renders one named template of a page's set into markup the |
| // page's data carries on: the editor's menu bar and undo/redo pair go into |
| // estilo's bar slots (chrome.Bar.Menubar and Lead), which take trusted |
diff --git a/internal/docs/signin_confirm_test.go b/internal/docs/signin_confirm_test.go| index 2f09ec8..3fdbd3d 100644 |
| --- a/internal/docs/signin_confirm_test.go |
| +++ b/internal/docs/signin_confirm_test.go |
| @@ -40,10 +40,10 @@ func readConfirmDoor(t *testing.T, rec *httptest.ResponseRecorder) confirmDoor { |
| } |
| } |
| // The app's chrome: the door (estilo), Docs' own mark and name, the |
| - // shell's bar. Not rastrillo's plain English fallback page. |
| - // (Tests run without the catalog loaded, so the app's own name in the |
| - // tab title is its key; the door's words are estilo's English.) |
| - for _, want := range []string{"estilo-door", "estilo-signin", "<span>Docs</span>", "estilo-bar", "<title>Sign in · ", "<h1>Sign in</h1>"} { |
| + // shell's bar, and rastrillo's sign-in screen inside it (the smart |
| + // door), whose title and heading say the same thing. Not rastrillo's |
| + // plain English fallback page. |
| + for _, want := range []string{"estilo-door", "estilo-signin-screen", "<span>Docs</span>", "estilo-bar", "<title>Sign in to Docs</title>", `<h1 id="rst-signin-heading">Sign in to Docs</h1>`} { |
| if !strings.Contains(body, want) { |
| t.Errorf("confirm page lacks %q: not Docs' sign-in door", want) |
| } |
diff --git a/internal/docs/signin_door_test.go b/internal/docs/signin_door_test.go| index 1b87d6c..21dbd23 100644 |
| --- a/internal/docs/signin_door_test.go |
| +++ b/internal/docs/signin_door_test.go |
| @@ -32,7 +32,7 @@ func TestSignInPageIsTheDoor(t *testing.T) { |
| if !regexp.MustCompile(`<img estilo-sky-layer="placeholder"[^>]*src="data:image/png;base64,`).MatchString(body) { |
| t.Error("sign-in page has no inline sky placeholder") |
| } |
| - layer := regexp.MustCompile(`<img estilo-sky-layer="[a-z]+"[^>]*src="(/static/estilo/sky/v1/[^"]+)"`).FindStringSubmatch(body) |
| + layer := regexp.MustCompile(`<img estilo-sky-layer="[a-z]+"[^>]*src="(/static/estilo/sky/v[0-9]+/[^"]+)"`).FindStringSubmatch(body) |
| if layer == nil { |
| t.Fatal("sign-in page links no served sky layer") |
| } |
| @@ -44,10 +44,12 @@ func TestSignInPageIsTheDoor(t *testing.T) { |
| } |
| } |
| -// The door's words are the suite's, with this app's English catalog |
| -// wired the way cmd/docs/main.go wires it: the submit reads "Sign in" |
| -// (Paul, 2026-10-01, never "Email me a link"), the help and sent copy are |
| -// the door's one set, and the three tab titles are "<Page> · Docs". |
| +// The door's words, with this app's English catalog wired the way |
| +// cmd/docs/main.go wires it. The door itself is rastrillo's sign-in screen |
| +// (the smart door, Home spec 2026-11-19-smart-door.md), in its approved |
| +// copy: the email field's submit is "Continue", the tab title says what |
| +// the heading says, and Sent keeps "Use a different email". The signed-out |
| +// page is estilo's, with "Forget me on this device" under Sign in. |
| func TestSignInDoorCopyIsTheSuites(t *testing.T) { |
| app, err := NewForTest(t) |
| if err != nil { |
| @@ -79,18 +81,21 @@ func TestSignInDoorCopyIsTheSuites(t *testing.T) { |
| path, title string |
| want []string |
| }{ |
| - {"/signin", "Sign in · Docs", []string{ |
| - `>Sign in</button>`, |
| - "We’ll email you a link that signs you in. It works once and expires in 15 minutes.", |
| + {"/signin", "Sign in to Docs", []string{ |
| + `<h1 id="rst-signin-heading">Sign in to Docs</h1>`, |
| + `>Email</label>`, |
| + `>Continue</button>`, |
| }}, |
| - {"/signin?sent=1", "Check your email · Docs", []string{ |
| - "If that address can sign in here, we’ve sent it a link. It works once and expires in 15 minutes.", |
| - `>Use a different address</a>`, |
| + {"/signin?sent=1", "Check your email to sign in to Docs", []string{ |
| + "We sent a link to your inbox. The link works once and expires soon.", |
| + "<span>Use a different email</span>", |
| }}, |
| {"/signed-out", "Signed out · Docs", []string{ |
| "You’re signed out", |
| "You’ve signed out of Docs on this device.", |
| `href="/signin">Sign in</a>`, |
| + `action="/signin/forget"`, |
| + ">Forget me on this device</button>", |
| }}, |
| } |
| for _, c := range cases { |
diff --git a/internal/docs/signin_loop_test.go b/internal/docs/signin_loop_test.go| index cc7d4c1..c7236a7 100644 |
| --- a/internal/docs/signin_loop_test.go |
| +++ b/internal/docs/signin_loop_test.go |
| @@ -1,8 +1,10 @@ |
| package docs |
| import ( |
| + "html" |
| "net/http" |
| "net/http/httptest" |
| + "net/url" |
| "regexp" |
| "strings" |
| "testing" |
| @@ -91,14 +93,16 @@ func TestARevokedGuestIsNotBouncedBetweenTheListAndSignIn(t *testing.T) { |
| if signin.Code != http.StatusOK { |
| t.Fatalf("GET %s: %d to %q — the list and sign-in redirect to each other", list.Header().Get("Location"), signin.Code, signin.Header().Get("Location")) |
| } |
| - if !strings.Contains(signin.Body.String(), `<form rst-form estilo-signin-form`) { |
| + if !strings.Contains(signin.Body.String(), `<form rst-signin-form method="post" action="/signin"`) { |
| t.Fatal("the revoked guest is not offered a way to sign in as someone else") |
| } |
| } |
| // Review finding (Astra, #65): "Use a different address" on the sent page |
| // went to a bare /signin, which a fresh start treats as "remember the |
| -// list", so the deep link was lost. The retry keeps the remembered page. |
| +// list", so the deep link was lost. The retry keeps the remembered page: |
| +// on the smart door it is "Use a different email", a POST to Forget that |
| +// carries return_to back to the door. |
| func TestUseADifferentAddressKeepsTheDeepLink(t *testing.T) { |
| app, _ := NewForTest(t) |
| owner := newBrowser(t, app) |
| @@ -108,16 +112,25 @@ func TestUseADifferentAddressKeepsTheDeepLink(t *testing.T) { |
| b := newBrowser(t, app) |
| signin := b.do("GET", deep, "").Header().Get("Location") |
| - b.do("GET", signin, "") |
| - sent := b.do("POST", "/signin", "address=typo@example.com") |
| + door := b.do("GET", signin, "") |
| + if !strings.Contains(door.Body.String(), `name="return_to" value="`+html.EscapeString(deep)+`"`) { |
| + t.Fatalf("the door's form does not post the deep link %q", deep) |
| + } |
| + sent := b.do("POST", "/signin", url.Values{"address": {"typo@example.com"}, "return_to": {deep}}.Encode()) |
| sentPage := b.do("GET", sent.Header().Get("Location"), "") |
| - m := regexp.MustCompile(`<p><a href="([^"]+)">Use a different address</a></p>`).FindStringSubmatch(sentPage.Body.String()) |
| - if m == nil { |
| - t.Fatalf("no \"Use a different address\" link on the sent page (%d)", sentPage.Code) |
| + m := regexp.MustCompile(`(?s)<form rst-signin-form method="post" action="(/signin/forget)">(.*?)</form>`).FindStringSubmatch(sentPage.Body.String()) |
| + if m == nil || !strings.Contains(m[2], "Use a different email") { |
| + t.Fatalf("no \"Use a different email\" on the sent page (%d)", sentPage.Code) |
| + } |
| + if !strings.Contains(m[2], `name="return_to" value="`+html.EscapeString(deep)+`"`) { |
| + t.Fatalf("\"Use a different email\" does not keep the deep link: %s", m[2]) |
| + } |
| + again := b.do("POST", m[1], url.Values{"return_to": {deep}}.Encode()) |
| + if again.Code != http.StatusSeeOther { |
| + t.Fatalf("POST %s: %d", m[1], again.Code) |
| } |
| - again := strings.ReplaceAll(m[1], "&", "&") |
| - if rec := b.do("GET", again, ""); rec.Code != http.StatusOK { |
| - t.Fatalf("GET %s: %d", again, rec.Code) |
| + if rec := b.do("GET", again.Header().Get("Location"), ""); rec.Code != http.StatusOK { |
| + t.Fatalf("GET %s: %d", again.Header().Get("Location"), rec.Code) |
| } |
| // The right address this time, in the same browser. |
| link, err := app.TestSignIn(t, "alice@example.com") |
| @@ -128,7 +141,7 @@ func TestUseADifferentAddressKeepsTheDeepLink(t *testing.T) { |
| b.do("POST", verifyPath, verifyForm) |
| landed := b.do("GET", localLinkCompletePath, "") |
| if landed.Header().Get("Location") != deep { |
| - t.Fatalf("after \"Use a different address\" (%s) the sign-in landed on %q, want %q", again, landed.Header().Get("Location"), deep) |
| + t.Fatalf("after \"Use a different email\" the sign-in landed on %q, want %q", landed.Header().Get("Location"), deep) |
| } |
| } |
| @@ -159,4 +172,13 @@ func TestARevokedGuestIsNotBouncedThroughHomeSignIn(t *testing.T) { |
| if next.Code == http.StatusSeeOther && next.Header().Get("Location") == "/" { |
| t.Fatal("Home's /signin sent a refused session straight back to / — the two redirect to each other") |
| } |
| + // The door: carol signed in by email here, so that is its one way in, |
| + // and Oficina ID is among the other ways. |
| + if next.Code != http.StatusOK || !strings.Contains(next.Body.String(), "<bdi>carol@example.com</bdi>") || !strings.Contains(next.Body.String(), `href="/signin?way=email&ways=1"`) { |
| + t.Fatalf("a refused session is not shown the door: %d", next.Code) |
| + } |
| + // Continue with Oficina ID has the same shortcut, and the same check. |
| + if rec := carol.do("GET", "/signin/oficina", ""); rec.Code == http.StatusSeeOther && rec.Header().Get("Location") == "/" { |
| + t.Fatal("/signin/oficina sent a refused session straight back to /") |
| + } |
| } |
diff --git a/internal/docs/signin_return.go b/internal/docs/signin_return.go| index c4d6427..8fa4212 100644 |
| --- a/internal/docs/signin_return.go |
| +++ b/internal/docs/signin_return.go |
| @@ -68,11 +68,14 @@ func requestedReturn(r *http.Request) (string, bool) { |
| return values[0], true |
| } |
| -// signinOutcome reports whether GET /signin is showing an outcome of the |
| -// email flow (?sent, ?err, ?force) rather than starting one. |
| +// signinOutcome reports whether GET /signin names a state of the door |
| +// rather than opening it afresh: an outcome of the email flow (?sent, |
| +// ?err, ?force), the Keymail continuation (?continue) or a step-up |
| +// (?reauth). connect's SigninDoor draws the same five for a signed-in |
| +// browser too (its doorStates), and so does standalone Docs. |
| func signinOutcome(r *http.Request) bool { |
| q := r.URL.Query() |
| - return q.Has("sent") || q.Has("err") || q.Has("force") |
| + return q.Has("sent") || q.Has("err") || q.Has("force") || q.Has("continue") || q.Has("reauth") |
| } |
| // alreadySignedIn sends a signed-in GET /signin back where it came |
| @@ -107,28 +110,14 @@ func (h *handlers) admitted(r *http.Request) bool { |
| } |
| // standaloneSignin is GET /signin without Home: already signed in (and |
| -// admitted) goes back; a return_to is remembered for the landing; then |
| -// the form. |
| -func (h *handlers) standaloneSignin(n *returnMemory) http.HandlerFunc { |
| - return func(w http.ResponseWriter, r *http.Request) { |
| - if !signinOutcome(r) && h.admitted(r) { |
| - alreadySignedIn(w, r) |
| - return |
| - } |
| - // Starting a sign-in remembers where to come back to, and a plain |
| - // /signin remembers the list: a page remembered by an earlier, |
| - // abandoned attempt must not win over the one being made now. The |
| - // email flow's own outcomes (?sent, ?err) leave it alone. Home's |
| - // /signin does the same (home_connect.go). |
| - if !signinOutcome(r) { |
| - path, ok := requestedReturn(r) |
| - if !ok { |
| - path = "/" |
| - } |
| - n.rememberReturn(w, path) |
| - } |
| - h.signin(w, r) |
| +// admitted) goes back; otherwise the door, which remembers a return_to |
| +// for the landing (auth.go's rememberSigninReturn). |
| +func (h *handlers) standaloneSignin(w http.ResponseWriter, r *http.Request) { |
| + if !signinOutcome(r) && h.admitted(r) { |
| + alreadySignedIn(w, r) |
| + return |
| } |
| + h.signin(w, r) |
| } |
| // completeStandalone is the standalone SignedInPath: land on the |
diff --git a/internal/docs/team_router_test.go b/internal/docs/team_router_test.go| index 7a47f60..ce2b5f3 100644 |
| --- a/internal/docs/team_router_test.go |
| +++ b/internal/docs/team_router_test.go |
| @@ -349,7 +349,7 @@ func TestTeamRouterHomeOnlyFirstEntryAndConflict(t *testing.T) { |
| if _, e = f.app.store.team.principals.Resolve(t.Context(), bridgeIssuer, teamSubject('z')); !errors.Is(e, principalstore.ErrRefused) { |
| t.Fatal("nonmember allocated principal", e) |
| } |
| - if r = b.do("GET", "/account/home", ""); r.Code != 303 || r.Header().Get("Location") != "/signin/local" { |
| + if r = b.do("GET", "/account/home", ""); r.Code != 303 || r.Header().Get("Location") != "/signin/local?reauth=1" { |
| t.Fatal("addressless account cannot begin explicit local reauthentication", r.Code, r.Header().Get("Location")) |
| } |
| } |
diff --git a/internal/docs/theme_assets_test.go b/internal/docs/theme_assets_test.go| index 0afc830..65d4bb2 100644 |
| --- a/internal/docs/theme_assets_test.go |
| +++ b/internal/docs/theme_assets_test.go |
| @@ -15,6 +15,9 @@ import ( |
| "amadan.net/oficina/estilo.git/theme" |
| "amadan.net/rastrillo/rastrillo/ui" |
| + "github.com/tdewolff/minify/v2" |
| + mincss "github.com/tdewolff/minify/v2/css" |
| + minjs "github.com/tdewolff/minify/v2/js" |
| ) |
| func TestSharedThemeAssetFingerprintAndCache(t *testing.T) { |
| @@ -37,14 +40,15 @@ func TestSharedThemeAssetFingerprintAndCache(t *testing.T) { |
| }{ |
| {"theme", docsTheme}, {"tokens", ui.TokensCSS()}, |
| } { |
| - sum := sha256.Sum256(item.data) |
| + served := servedAs("static/"+item.name+".css", item.data) |
| + sum := sha256.Sum256(served) |
| hashed := fmt.Sprintf("/static/%s.%x.css", item.name, sum[:8]) |
| if !strings.Contains(page.Body.String(), `href="`+hashed+`"`) { |
| t.Fatalf("missing selected %s fingerprint", item.name) |
| } |
| for _, path := range []string{hashed, "/static/" + item.name + ".css", "/static/" + item.name + ".0000000000000000.css"} { |
| res := serve(app, httptest.NewRequest(http.MethodGet, path, nil)) |
| - if res.Code != http.StatusOK || !bytes.Equal(res.Body.Bytes(), item.data) { |
| + if res.Code != http.StatusOK || !bytes.Equal(res.Body.Bytes(), served) { |
| t.Fatalf("%s asset response mismatch status%d", item.name, res.Code) |
| } |
| if !strings.HasPrefix(res.Header().Get("Content-Type"), "text/css") { |
| @@ -71,6 +75,7 @@ func TestBusyRuleIsLinkedAndServed(t *testing.T) { |
| } |
| page := serve(app, httptest.NewRequest(http.MethodGet, "/signin", nil)).Body.String() |
| for name, body := range map[string][]byte{"static/estilo/busy.css": busy.CSS(), "static/rastrillo.js": busy.ShimJS(), "static/estilo/busy.js": busy.JS()} { |
| + body = servedAs(name, body) |
| sum := sha256.Sum256(body) |
| hashed := "/" + strings.TrimSuffix(name, path.Ext(name)) + fmt.Sprintf(".%x", sum[:8]) + path.Ext(name) |
| if !strings.Contains(page, `"`+hashed+`"`) { |
| @@ -97,3 +102,28 @@ func TestBusyRuleIsLinkedAndServed(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// servedAs is what rastrillo.Assets sends for name (rastrillo v0.31's |
| +// "pages download less"): a file at one of the framework's vendored |
| +// paths (static/tokens.css, static/theme.css, static/rastrillo.js and the |
| +// rest) is minified, by rastrillo's own settings, mirrored here; any other |
| +// file is served as written. Docs puts estilo's theme and busy shim at two |
| +// of those paths, so they are minified too. |
| +func servedAs(name string, body []byte) []byte { |
| + vendored := map[string]bool{"static/tokens.css": true, "static/theme.css": true, "static/shell.css": true, "static/rastrillo.js": true} |
| + if !vendored[name] { |
| + return body |
| + } |
| + m := minify.New() |
| + m.AddFunc("text/css", mincss.Minify) |
| + m.Add("text/javascript", &minjs.Minifier{KeepVarNames: true}) |
| + mediaType := "text/css" |
| + if path.Ext(name) == ".js" { |
| + mediaType = "text/javascript" |
| + } |
| + var out bytes.Buffer |
| + if err := m.Minify(mediaType, &out, bytes.NewReader(body)); err != nil || out.Len() == 0 { |
| + return body |
| + } |
| + return out.Bytes() |
| +} |
diff --git a/internal/docs/views/layout.html b/internal/docs/views/layout.html| index 8c288f4..beddbd7 100644 |
| --- a/internal/docs/views/layout.html |
| +++ b/internal/docs/views/layout.html |
| @@ -16,7 +16,7 @@ |
| <head> |
| <meta charset="utf-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1"> |
| -<title>{{range .Frame.TitleParts}}{{.}} · {{end}}{{.Frame.Chrome.App.Name}}</title> |
| +<title>{{with .Frame.Title}}{{.}}{{else}}{{range .Frame.TitleParts}}{{.}} · {{end}}{{.Frame.Chrome.App.Name}}{{end}}</title> |
| {{block "pagehead" .}}{{end}} |
| <link rel="stylesheet" href="{{asset "static/tokens.css"}}"> |
| <link rel="stylesheet" href="{{asset "static/estilo/busy.css"}}"> |
diff --git a/internal/docs/views/signin.html b/internal/docs/views/signin.html| index 678d98a..07eab76 100644 |
| --- a/internal/docs/views/signin.html |
| +++ b/internal/docs/views/signin.html |
| @@ -1,30 +1,14 @@ |
| -{{/* signin — GET /signin (auth.go's signin handler): estilo's sign-in |
| - form, the check-your-email state that replaces it, the Keymail |
| - continuation (auth_navigation.go), which needs its meta refresh, or |
| - the confirm step an emailed link opens (GET /auth/verify, |
| - auth_navigation.go's confirmSignin): one Sign in button that POSTs |
| - the token back, because a GET must spend nothing. |
| - |
| - rastrillo/auth's own handlers never render this page themselves |
| - (magic-links.md: "the sign-in page stays yours"). Begin, Callback and |
| - Verify report outcomes by redirecting back here with ?sent=1 or |
| - ?err=…, which auth.go resolves into the data below; the confirm step |
| - and a refusal call back into it (Config.RenderConfirm, Config.Refused). |
| +{{/* signin — the sign-in door (auth.go's signin): rastrillo's sign-in |
| + screen, its ui "signin" partial fed by auth.SigninState, drawn inside |
| + estilo's door (the sky, and Docs' mark and name at the card's head) by |
| + estilo-signin-screen. One way in per page (SigninOneWay): the way this |
| + browser used last, or Continue with Oficina ID, then "Other ways to sign |
| + in". Every state is this one template: the door, the chooser, Sent, the |
| + Keymail continuation (its meta refresh is in the card), and the confirm |
| + step an emailed link opens (GET /auth/verify, Config.RenderConfirm), |
| + whose one Sign in button POSTs the token back because a GET must spend |
| + nothing. |
| The bar shows the brand only: no account, no Sign in (chrome.go's |
| - signinPage). It used to be hidden outright, because the rastrillo |
| - shell could not be emptied, and the front door had no name on it. */}} |
| -{{define "content"}} |
| -{{- if .ContinueURL}} |
| -<meta http-equiv="refresh" content="0;url={{.ContinueURL}}"> |
| -{{template "estilo-door-open" .Door}}<p><a rst-btn="primary" href="{{.ContinueURL}}">{{.SubmitLabel}}</a></p>{{template "estilo-door-close"}} |
| -{{- else if .Confirm}}{{template "estilo-door-open" .Door}} |
| - <h1>{{.Confirm.Heading}}</h1> |
| - <form rst-form method="post" action="{{.Confirm.Action}}"> |
| - <input type="hidden" name="token" value="{{.Confirm.Token}}"> |
| - <div rst-form-foot><button rst-btn="primary" type="submit" autofocus>{{.Confirm.Submit}}</button></div> |
| - </form> |
| -{{template "estilo-door-close"}} |
| -{{- else if .Sent}}{{template "estilo-signin-sent" .Sent}} |
| -{{- else}}{{template "estilo-signin" .Form}}{{end}} |
| -{{end}} |
| + signinPage). */}} |
| +{{define "content"}}{{template "estilo-signin-screen" .Screen}}{{end}} |