oficina / home Public

connect: the smart door's routes and the signed-out Forget (smart-door step 4)

Home spec 2026-11-19-smart-door.md, "Routes, and every state the door
must answer", step 4.

- /signin always renders the door. Routes.Signin, whose query dispatch
  sent a bare /signin straight to Home, is deleted; Routes.SigninDoor
  hands every request to the app's door (RoutesConfig.LocalSignin),
  keeping only the signed-in shortcut (shared-chrome §9.4), which a
  door state (sent, err, force, reauth, continue) skips.
- /signin/local is Routes.SigninLocal: the same door, email only. connect
  sends unknown, failed, link-resume and choose-declined people there,
  so it never offers Oficina ID, which would loop.
- GET /signin/oficina?return_to=... is Routes.SigninOficina, "Continue
  with Oficina ID": today's rememberReturn plus handoff.StartPath, with
  return_to validated as before (one SafePath value, else "/").
  OficinaHref(r) is the href for the app's auth.FederatedDoor, and "" on
  /signin/local, on any step-up and on any door connect did not hand over.
- Reauth offers local ways only: a reauth reaching /signin/oficina goes to
  /signin/local, and the link flow's step-up already lands there.
- The signed-out page: RoutesConfig.ForgetPath (optional, a clean local
  path) puts "Forget me on this device" on it as PageData.ForgetAction, a
  plain same-origin POST that csrf.SameOrigin admits. PageData is now
  connect's own struct (same fields as estilo's homeconnect.PageData,
  plus ForgetAction) rather than an alias. Signout still chains to
  {Issuer}/signout.
- MintHomeSession is where an app remembers the federated way in;
  connect imports no lastsignin (tested). MintedPerson(r) is the person
  connect resolved, on the minting request only, so the app records that
  address, or none, and never carries one over.

Paths are constants now: SigninPath, SigninLocalPath, SigninOficinaPath.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 106d1084c741548aaaa3ecb1cfc3279d56a7c7ea parent 5e5ebe5
11 files changed, +796 −123
  • connect/README.md +65 −10
  • connect/api.go +41 −1
  • connect/bridge.go +1 −1
  • connect/choose.go +2 −2
  • connect/derived_test.go +7 −2
  • connect/door.go +157 −0
  • connect/door_test.go +456 −0
  • connect/navigation.go +1 −1
  • connect/routes.go +37 −32
  • connect/routes_test.go +0 −69
  • connect/view.go +29 −5
diff --git a/connect/README.md b/connect/README.md
index 6297ca9..24d106e 100644
--- a/connect/README.md
+++ b/connect/README.md
@@ -51,7 +51,8 @@ existing behavior in the app's local authentication path.
narrow callback exception to your app's CSRF middleware. Mount its methods
alongside `Bridge.Start`, `Callback`, `Finish` and `ConfirmPage`. The local
plugin's successful return must be `LocalCompletePath`. Its pending cookie must
-be `__Host-rastrillo_pending`, and the local entry is `/signin/local`.
+be `__Host-rastrillo_pending`, and the local entry is `/signin/local`
+(`Routes.SigninLocal`; see "The sign-in door" below).
Mount exactly `Bridge.Callback` at `POST /auth/assertion`: this path alone bypasses
CSRF protection because the bridge verifies its browser-bound assertion.
`LocalLandingPath` optionally sets a validated local destination after ordinary
@@ -60,15 +61,6 @@ inside the app's existing Estilo layout; all paths work without JavaScript.
Apps with additional content-security directives must supply their existing
policy with the validated Home issuer added to `form-action`.
-`Routes.Signin` sends a person who already has a live session straight to the
-validated `return_to` (or `/`) instead of starting another exchange. `Routes.Signout`
-ends the app session and then answers `307` to `{Issuer}/signout`, which ends the
-Home sign-in session too and returns the browser to the app's `/signed-out`. Home
-admits that hop only from an origin registered in its `HOME_CONSUMERS`, by
-`Referer` when the browser nulls `Origin`, so a page showing Sign out must not send
-`Referrer-Policy: no-referrer` (use `strict-origin`), and a custom policy must keep
-the issuer in `form-action`.
-
Offer "Connect your Oficina account" in the account menu only when
`Bridge.Linked` reports no stored link for the signed-in local person, however
the session signed in: one indexed lookup per render. Render the shared pages
@@ -87,6 +79,69 @@ then ends the POST with a no-store continuation page so Safari does not apply
form-action to Keymail's redirect chain. It does not discover or trust arbitrary
request-provided destinations. Keep the existing local plugin callback route.
+## The sign-in door
+
+Three GET routes (Home spec `2026-11-19-smart-door.md`, "Routes, and every
+state the door must answer"):
+
+- `SigninPath` (`/signin`) at `Routes.SigninDoor`: **always the door**, which
+ the app draws in its `RoutesConfig.LocalSignin`. It never starts a Home
+ exchange. A browser with a live session goes straight to the validated
+ `return_to` (or `/`), unless the query names a state of the door (`sent`,
+ `err`, `force`, `reauth`, `continue`).
+- `SigninLocalPath` (`/signin/local`) at `Routes.SigninLocal`: the same door
+ with **email as the one way in**. connect sends people here when Oficina ID
+ cannot help them: unknown, failed, a link to resume, "Connect my existing
+ account", and a session too old to link. It has no signed-in shortcut.
+- `SigninOficinaPath` (`/signin/oficina?return_to=…`) at `Routes.SigninOficina`:
+ "Continue with Oficina ID". It remembers the validated `return_to` in the
+ sealed return cookie and redirects to `handoff.StartPath`. A live session
+ goes straight to the page instead; a `reauth` is sent to `/signin/local`.
+
+In the door, `OficinaHref(r)` is the href for rastrillo's
+`auth.FederatedDoor.Href`. It is `""` on `/signin/local`, on any step-up
+(`reauth` in the query), and on any request that did not come through
+`SigninDoor`. Set no `FederatedDoor` then: a step-up offers local ways only,
+because linking needs `FreshLocal`, which no Home sign-in gives.
+
+```go
+st := app.auth.SigninState(r) // app.auth is the app's *rauth.Auth
+if href := connect.OficinaHref(r); href != "" {
+ st.Federated = &rauth.FederatedDoor{Provider: lastsignin.ProviderOficina,
+ Href: href, Label: "Oficina ID", Icon: chrome.OficinaGlyph}
+}
+```
+
+`SigninDoor` and `SigninOficina` read the session cookie and nothing else. An
+app whose signed-in routes refuse some live sessions must end or hide such a
+session first, or `/signin` and the refusing page redirect to each other.
+
+**Remembering Oficina ID** is the app's job, in `Config.MintHomeSession`.
+connect imports no `lastsignin`, so it forces no rastrillo version on you.
+After storing the session, call `RememberJar().Remember` with
+`lastsignin.MethodFederated`, `ProviderOficina` and the address of
+`connect.MintedPerson(r)` (empty for a Home-only person). Never carry an
+address over from the record already in the jar. connect calls the hook only
+where a Home sign-in becomes a session (a finished exchange, and "I'm new
+here"), never on link, choose, unknown or failed.
+
+**Signed out.** Set `RoutesConfig.ForgetPath` to where you mounted rastrillo
+auth's `Forget`. `PageFor(r, "signedout", …)` on the request `Routes.SignedOut`
+renders then carries it as `PageData.ForgetAction`. Draw it with estilo's
+`estilo-signed-out`: `chrome.SignInNotice{…}.SignedOut(p.Action).Forgetting(p.ForgetAction, "")`.
+It is a plain same-origin POST, which `csrf.SameOrigin` admits, so it stays
+inside `Middleware`'s CSRF check with no token. It forgets this host only;
+id.oficina.works keeps and forgets its own record.
+
+## Signing out
+
+`Routes.Signout` ends the app session and then answers `307` to `{Issuer}/signout`, which ends the
+Home sign-in session too and returns the browser to the app's `/signed-out`. Home
+admits that hop only from an origin registered in its `HOME_CONSUMERS`, by
+`Referer` when the browser nulls `Origin`, so a page showing Sign out must not send
+`Referrer-Policy: no-referrer` (use `strict-origin`), and a custom policy must keep
+the issuer in `form-action`.
+
## Home-only people (team mode)
`Config.Admit`, `Config.Unlinked` and `Config.HomeOnly` are optional and set
diff --git a/connect/api.go b/connect/api.go
index 8dbd217..fec56f1 100644
--- a/connect/api.go
+++ b/connect/api.go
@@ -74,7 +74,31 @@ type Config struct {
Keys map[string][]byte
DEK []byte
// ReadSession must resolve the actual verified session, never a supplied subject.
- ReadSession func(*http.Request) (*Session, error)
+ ReadSession func(*http.Request) (*Session, error)
+ // MintHomeSession stores the browser session for a Home sign-in
+ // (Method HomeMethod, the assertion's AuthTime) and sets its cookie.
+ // It is called only where a Home sign-in becomes a session: a finished
+ // exchange (Finish) and a Member's "I'm new here" (ChoosePost). Never
+ // for linking, the choose page, "unknown" or "failed".
+ //
+ // That makes it the one place an app remembers "Continue with Oficina
+ // ID" for its smart door (Home spec 2026-11-19-smart-door.md, "The
+ // cookie"), and connect leaves it to the app: connect imports no
+ // lastsignin, so it forces no rastrillo version on its consumers.
+ // Once the session is stored, the app records the federated way in
+ // with the address of the person who just signed in, or with none:
+ //
+ // p, _ := connect.MintedPerson(r)
+ // auth.RememberJar().Remember(w, lastsignin.Record{
+ // Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina,
+ // Address: p.Label, // "" for a Home-only person
+ // })
+ //
+ // MintedPerson is the person connect resolved for this sign-in. Never
+ // carry an address over from the record already in the jar: it may be
+ // somebody else's. A failure to remember must not fail the sign-in.
+ // NativeExchange mints through MintNativeSession, never this hook, and
+ // a native client has no browser jar to remember in.
MintHomeSession func(http.ResponseWriter, *http.Request, Session) error
// Both lookup hooks must read current existing, admitted local accounts.
// They never create accounts or infer a Home link from an email address.
@@ -136,6 +160,22 @@ type Config struct {
MintNativeSession func(ctx context.Context, s Session) (string, error)
}
+// MintedPerson is the person a Home sign-in resolved to, on the request
+// MintHomeSession is called with, and false on any other request. Label is
+// their canonical verified local address, or "" for a Home-only person.
+func MintedPerson(r *http.Request) (Person, bool) {
+ p, ok := r.Context().Value(mintedKey{}).(Person)
+ return p, ok
+}
+
+type mintedKey struct{}
+
+// mint is MintHomeSession for person, who must be the one connect resolved
+// for this sign-in.
+func (b *Bridge) mint(w http.ResponseWriter, r *http.Request, s Session, person Person) error {
+ return b.mintSession(w, r.WithContext(context.WithValue(r.Context(), mintedKey{}, person)), s)
+}
+
// ErrNoPerson is what a Config.Unlinked or Config.HomeOnly hook returns for
// "no person here for this subject", as distinct from a storage failure.
var ErrNoPerson = errors.New("home connect: no person for this subject")
diff --git a/connect/bridge.go b/connect/bridge.go
index c0f5a2b..b44abad 100644
--- a/connect/bridge.go
+++ b/connect/bridge.go
@@ -264,7 +264,7 @@ func (b *Bridge) complete(w http.ResponseWriter, r *http.Request, claims asserti
return rejectHome(r, "failed", http.StatusForbidden)
}
}
- if err := b.mintSession(w, r, Session{Subject: claims.Subject, Method: HomeMethod, AuthTime: time.Unix(claims.AuthTime, 0)}); err != nil {
+ if err := b.mint(w, r, Session{Subject: claims.Subject, Method: HomeMethod, AuthTime: time.Unix(claims.AuthTime, 0)}, arriving); err != nil {
return errHomeBridge
}
return nil
diff --git a/connect/choose.go b/connect/choose.go
index b905394..0054972 100644
--- a/connect/choose.go
+++ b/connect/choose.go
@@ -153,7 +153,7 @@ func (b *Bridge) ChoosePost(w http.ResponseWriter, r *http.Request) {
if b.rememberUnknown != nil {
b.rememberUnknown(w)
}
- http.Redirect(w, r, "/signin/local", http.StatusSeeOther)
+ http.Redirect(w, r, SigninLocalPath, http.StatusSeeOther)
return
}
person, err := b.chooseNew(r.Context(), taken.Subject)
@@ -168,7 +168,7 @@ func (b *Bridge) ChoosePost(w http.ResponseWriter, r *http.Request) {
b.fail(w, r, http.StatusServiceUnavailable)
return
}
- if err := b.mintSession(w, r, Session{Subject: taken.Subject, Method: HomeMethod, AuthTime: taken.AuthTime}); err != nil {
+ if err := b.mint(w, r, Session{Subject: taken.Subject, Method: HomeMethod, AuthTime: taken.AuthTime}, person); err != nil {
b.fail(w, r, http.StatusServiceUnavailable)
return
}
diff --git a/connect/derived_test.go b/connect/derived_test.go
index 8b68ff4..c6cf684 100644
--- a/connect/derived_test.go
+++ b/connect/derived_test.go
@@ -58,10 +58,15 @@ func TestNativeSessionResolvesUntilSevenDays(t *testing.T) {
}
routes := f.routes(t)
w := httptest.NewRecorder()
- routes.Signin(w, bridgeRequest(http.MethodGet, "/signin?return_to=%2Fd%2Fx", []*http.Cookie{cookie}))
+ routes.SigninOficina(w, bridgeRequest(http.MethodGet, "/signin/oficina?return_to=%2Fd%2Fx", []*http.Cookie{cookie}))
if w.Code != 303 || w.Header().Get("Location") != "/d/x" {
t.Fatalf("a live native session is not signed in: %d %q", w.Code, w.Header().Get("Location"))
}
+ w = httptest.NewRecorder()
+ routes.SigninDoor(w, bridgeRequest(http.MethodGet, "/signin?return_to=%2Fd%2Fx", []*http.Cookie{cookie}))
+ if w.Code != 303 || w.Header().Get("Location") != "/d/x" {
+ t.Fatalf("the door kept a live native session: %d %q", w.Code, w.Header().Get("Location"))
+ }
s := f.sessions.values[token]
s.At = time.Now().Add(-NativeLifetime - time.Minute)
@@ -70,7 +75,7 @@ func TestNativeSessionResolvesUntilSevenDays(t *testing.T) {
t.Fatal("a native session resolved after seven days")
}
w = httptest.NewRecorder()
- routes.Signin(w, bridgeRequest(http.MethodGet, "/signin?return_to=%2Fd%2Fx", []*http.Cookie{cookie}))
+ routes.SigninOficina(w, bridgeRequest(http.MethodGet, "/signin/oficina?return_to=%2Fd%2Fx", []*http.Cookie{cookie}))
if w.Header().Get("Location") == "/d/x" {
t.Fatal("an expired native session counted as signed in")
}
diff --git a/connect/door.go b/connect/door.go
new file mode 100644
index 0000000..1741b5c
--- /dev/null
+++ b/connect/door.go
@@ -0,0 +1,157 @@
+package connect
+
+import (
+ "context"
+ "net/http"
+ "net/url"
+
+ "amadan.net/oficina/home/handoff"
+)
+
+// The sign-in door's three routes (Home spec 2026-11-19-smart-door.md,
+// "Routes, and every state the door must answer"). Mount them with GET:
+//
+// - SigninPath at Routes.SigninDoor: the door, always. The app draws it.
+// - SigninLocalPath at Routes.SigninLocal: the door with email as the one
+// way in. connect sends people here when Oficina ID cannot help them
+// (unknown, failed, a link to resume, "Connect my existing account", a
+// step-up for linking), so it never offers Oficina ID, which would loop.
+// - SigninOficinaPath at Routes.SigninOficina: "Continue with Oficina ID",
+// which starts the Home exchange.
+const (
+ SigninPath = "/signin"
+ SigninLocalPath = "/signin/local"
+ SigninOficinaPath = "/signin/oficina"
+)
+
+// doorKey marks a request connect's door routes handed to the app's door
+// (RoutesConfig.LocalSignin), with whether that door may offer Oficina ID.
+type doorKey struct{}
+
+type doorOffer struct{ oficina bool }
+
+// OficinaHref is the href of "Continue with Oficina ID" on the door being
+// drawn for r: the app's auth.FederatedDoor.Href. It is SigninOficinaPath,
+// with r's return_to when that is one safe local path (rastrillo's
+// SigninState.FederatedHref sets the page's own return_to on it again).
+//
+// It is "" whenever the door must not offer Oficina ID, and the app then
+// sets no FederatedDoor at all:
+// - on SigninLocalPath, where offering it would loop;
+// - on a step-up (any reauth in the query). A live id.* session hands back
+// an old auth_time, and linking needs FreshLocal, which only a local
+// sign-in gives, so a step-up offers local ways only;
+// - on any request that did not come through Routes.SigninDoor, so a door
+// drawn from somewhere else offers nothing it was not told to.
+func OficinaHref(r *http.Request) string {
+ offer, ok := r.Context().Value(doorKey{}).(doorOffer)
+ if !ok || !offer.oficina {
+ return ""
+ }
+ q, err := url.ParseQuery(r.URL.RawQuery)
+ if err != nil || q.Has("reauth") {
+ return ""
+ }
+ if path, ok := requestedReturn(q); ok {
+ return SigninOficinaPath + "?" + url.Values{"return_to": {path}}.Encode()
+ }
+ return SigninOficinaPath
+}
+
+// requestedReturn is the query's return_to when it is exactly one safe local
+// path: connect's rule for every destination it is handed.
+func requestedReturn(q url.Values) (string, bool) {
+ values, ok := q["return_to"]
+ if !ok || len(values) != 1 || !handoff.SafePath(values[0]) {
+ return "", false
+ }
+ return values[0], true
+}
+
+// doorStates are the query keys that name a state of the door itself: a
+// link sent, a problem, a failed Keymail's force, a step-up, a Keymail
+// continuation. Each is drawn even for a browser with a live session, as
+// the sent, err and force states always were; a step-up in particular is
+// asked of somebody who is signed in.
+var doorStates = []string{"sent", "err", "force", "reauth", "continue"}
+
+// SigninDoor is GET SigninPath: the door, always. It never starts a Home
+// exchange; "Continue with Oficina ID" does that (SigninOficina), and the
+// app's door offers it where OficinaHref says it may.
+//
+// A browser already signed in here (spec shared-chrome §9.4) goes straight
+// to the validated return_to, or "/", unless the query names a state of the
+// door (doorStates). Otherwise the request is handed to
+// RoutesConfig.LocalSignin, the app's door.
+func (h *Routes) SigninDoor(w http.ResponseWriter, r *http.Request) {
+ q, err := url.ParseQuery(r.URL.RawQuery)
+ if err != nil {
+ h.bridge.fail(w, r, http.StatusBadRequest)
+ return
+ }
+ state := false
+ for _, key := range doorStates {
+ state = state || q.Has(key)
+ }
+ if !state && h.signedIn(r) {
+ h.alreadySignedIn(w, r, q)
+ return
+ }
+ h.cfg.LocalSignin(w, r.WithContext(context.WithValue(r.Context(), doorKey{}, doorOffer{oficina: true})))
+}
+
+// SigninLocal is GET SigninLocalPath: the app's door with email as the one
+// way in (OficinaHref is ""). It has no signed-in shortcut: a signed-in
+// person whose local sign-in is too old to link is sent here to sign in
+// again (Routes.Account).
+func (h *Routes) SigninLocal(w http.ResponseWriter, r *http.Request) {
+ h.cfg.LocalSignin(w, r.WithContext(context.WithValue(r.Context(), doorKey{}, doorOffer{oficina: false})))
+}
+
+// SigninOficina is GET SigninOficinaPath?return_to=…: "Continue with
+// Oficina ID". It remembers the validated return_to (or "/") in the sealed
+// return cookie and starts the Home exchange (handoff.StartPath). A browser
+// already signed in here goes straight to that page instead, as SigninDoor
+// does. A step-up never reaches Home: any reauth in the query is sent to
+// SigninLocalPath with it, because linking needs a fresh local sign-in.
+func (h *Routes) SigninOficina(w http.ResponseWriter, r *http.Request) {
+ q, err := url.ParseQuery(r.URL.RawQuery)
+ if err != nil {
+ h.bridge.fail(w, r, http.StatusBadRequest)
+ return
+ }
+ path, ok := requestedReturn(q)
+ if !ok {
+ path = "/"
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ if q.Has("reauth") {
+ local := url.Values{"reauth": {"1"}}
+ if ok {
+ local.Set("return_to", path)
+ }
+ http.Redirect(w, r, SigninLocalPath+"?"+local.Encode(), http.StatusSeeOther)
+ return
+ }
+ if h.signedIn(r) {
+ h.alreadySignedIn(w, r, q)
+ return
+ }
+ if !h.navigation.rememberReturn(w, path) {
+ h.bridge.fail(w, r, http.StatusServiceUnavailable)
+ return
+ }
+ http.Redirect(w, r, handoff.StartPath+"?"+url.Values{"return_to": {path}}.Encode(), http.StatusSeeOther)
+}
+
+// alreadySignedIn sends a signed-in browser where it was headed, with no
+// door and no second exchange. SafePath refuses /signin and /auth/*, so
+// this cannot loop.
+func (h *Routes) alreadySignedIn(w http.ResponseWriter, r *http.Request, q url.Values) {
+ path, ok := requestedReturn(q)
+ if !ok {
+ path = "/"
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ http.Redirect(w, r, path, http.StatusSeeOther)
+}
diff --git a/connect/door_test.go b/connect/door_test.go
new file mode 100644
index 0000000..907699c
--- /dev/null
+++ b/connect/door_test.go
@@ -0,0 +1,456 @@
+package connect
+
+import (
+ "bytes"
+ "html/template"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/rastrillo/rastrillo/csrf"
+)
+
+// doorFixture is Routes over navigationFixture's sealer, with a session
+// reader that knows "verified" (a live Home sign-in), "guest" (a Calls
+// guest, a session but not a sign-in) and "revoked" (no session). The
+// app's door (LocalSignin) answers 299 and records what connect told it.
+type doorFixture struct {
+ h *Routes
+ calls int
+ href string
+ path string
+}
+
+func newDoorFixture(t *testing.T) *doorFixture {
+ t.Helper()
+ _, n := navigationFixture(t)
+ f := &doorFixture{}
+ f.h = &Routes{bridge: &Bridge{now: time.Now, render: func(w http.ResponseWriter, r *http.Request, state, label string, status int) { w.WriteHeader(status) }}, navigation: n, cfg: RoutesConfig{Origin: navigationOrigin, SessionCookie: "__Host-rastrillo_session", ReadSession: func(r *http.Request) (*Session, error) {
+ c, err := r.Cookie("__Host-rastrillo_session")
+ if err != nil || (c.Value != "verified" && c.Value != "guest") {
+ return nil, nil
+ }
+ method := HomeMethod
+ if c.Value == "guest" {
+ method = "guest"
+ }
+ return &Session{Subject: "pr_live", Method: method, At: time.Now()}, nil
+ }}}
+ f.h.cfg.LocalSignin = func(w http.ResponseWriter, r *http.Request) {
+ f.calls++
+ f.href, f.path = OficinaHref(r), r.URL.Path
+ w.WriteHeader(299)
+ }
+ return f
+}
+
+func (f *doorFixture) get(handler http.HandlerFunc, target string, cookies ...*http.Cookie) *httptest.ResponseRecorder {
+ f.href, f.path = "unset", ""
+ r := httptest.NewRequest(http.MethodGet, navigationOrigin+target, nil)
+ for _, c := range cookies {
+ r.AddCookie(c)
+ }
+ w := httptest.NewRecorder()
+ handler(w, r)
+ return w
+}
+
+var (
+ liveSession = &http.Cookie{Name: "__Host-rastrillo_session", Value: "verified"}
+ staleSession = &http.Cookie{Name: "__Host-rastrillo_session", Value: "revoked"}
+ guestSession = &http.Cookie{Name: "__Host-rastrillo_session", Value: "guest"}
+)
+
+// TestBareSigninRendersTheDoor is the smart door's first route: GET /signin
+// always renders the door, and never starts a Home exchange. Before, a bare
+// /signin went straight to id.oficina.works (connect's query dispatch), so
+// nobody could pick email from it. Nothing is remembered and no cookie is
+// set: the exchange, and its return cookie, belong to /signin/oficina.
+func TestBareSigninRendersTheDoor(t *testing.T) {
+ f := newDoorFixture(t)
+ for _, tc := range []struct {
+ target string
+ cookies []*http.Cookie
+ href string
+ }{
+ {"/signin", nil, SigninOficinaPath},
+ {"/signin?return_to=%2Fd%2F42%3Fview%3Dcompact", nil, "/signin/oficina?return_to=%2Fd%2F42%3Fview%3Dcompact"},
+ // A stale cookie, an ambiguous pair or a Calls guest is not signed
+ // in: the door, as for nobody.
+ {"/signin?return_to=%2Fd%2F42", []*http.Cookie{staleSession}, "/signin/oficina?return_to=%2Fd%2F42"},
+ {"/signin?return_to=%2Fd%2F42", []*http.Cookie{liveSession, liveSession}, "/signin/oficina?return_to=%2Fd%2F42"},
+ {"/signin?return_to=%2Fd%2F42", []*http.Cookie{guestSession}, "/signin/oficina?return_to=%2Fd%2F42"},
+ // The chooser and a picked way are the door's own pages.
+ {"/signin?ways=1&way=oficina", nil, SigninOficinaPath},
+ {"/signin?way=email&return_to=%2Fd%2F1", nil, "/signin/oficina?return_to=%2Fd%2F1"},
+ // A return_to connect would not follow is left off, as the exchange
+ // would land on "/" anyway.
+ {"/signin?return_to=https%3A%2F%2Fevil.example%2F", nil, SigninOficinaPath},
+ {"/signin?return_to=%2F%2Fevil.example", nil, SigninOficinaPath},
+ {"/signin?return_to=%2Fsignin", nil, SigninOficinaPath},
+ {"/signin?return_to=%2Fa&return_to=%2Fb", nil, SigninOficinaPath},
+ } {
+ calls := f.calls
+ w := f.get(f.h.SigninDoor, tc.target, tc.cookies...)
+ if w.Code != 299 || f.calls != calls+1 {
+ t.Fatalf("%s: %d %q, want the door", tc.target, w.Code, w.Header().Get("Location"))
+ }
+ if f.href != tc.href {
+ t.Fatalf("%s: Oficina href %q, want %q", tc.target, f.href, tc.href)
+ }
+ if len(w.Result().Cookies()) != 0 {
+ t.Fatalf("%s: the door set a cookie", tc.target)
+ }
+ }
+}
+
+// TestSigninWhenAlreadySignedIn is spec shared-chrome §9.4, kept on the
+// door: a live session goes straight to the validated return_to, or /,
+// with no door and no exchange. A query naming a state of the door (a
+// sent link, a problem, Keymail's force, a step-up, a continuation) is
+// drawn even then.
+func TestSigninWhenAlreadySignedIn(t *testing.T) {
+ f := newDoorFixture(t)
+ for _, tc := range []struct{ query, want string }{
+ {"?return_to=%2Fd%2F42%3Fview%3Dcompact", "/d/42?view=compact"},
+ {"", "/"},
+ {"?return_to=https%3A%2F%2Fevil.example%2F", "/"},
+ {"?return_to=%2F%2Fevil.example", "/"},
+ {"?return_to=%2Fsignin", "/"},
+ {"?return_to=%2Fa&return_to=%2Fb", "/"},
+ } {
+ for _, route := range []struct {
+ path string
+ handler http.HandlerFunc
+ }{{SigninPath, f.h.SigninDoor}, {SigninOficinaPath, f.h.SigninOficina}} {
+ w := f.get(route.handler, route.path+tc.query, liveSession)
+ if w.Code != 303 || w.Header().Get("Location") != tc.want {
+ t.Fatalf("%s%s: %d %q", route.path, tc.query, w.Code, w.Header().Get("Location"))
+ }
+ if w.Header().Get("Cache-Control") != "no-store" || len(w.Result().Cookies()) != 0 {
+ t.Fatalf("%s%s: cacheable, or set a cookie", route.path, tc.query)
+ }
+ }
+ }
+ for _, query := range []string{"?force=1", "?err=removed", "?err=rate", "?sent=1&attempt=x", "?reauth=1", "?continue=abc"} {
+ calls := f.calls
+ if w := f.get(f.h.SigninDoor, SigninPath+query, liveSession); w.Code != 299 || f.calls != calls+1 {
+ t.Fatalf("%s with a live session: %d, want the door", query, w.Code)
+ }
+ }
+ if w := f.get(f.h.SigninDoor, "/signin?%zz", nil...); w.Code != 400 {
+ t.Fatal("a malformed query reached the door", w.Code)
+ }
+}
+
+// TestSigninLocalIsEmailOnly: /signin/local is where connect sends people
+// Oficina ID could not help (unknown, failed, a link to resume, "Connect my
+// existing account", a step-up to link). Its door must never offer Oficina
+// ID, or those people would loop through Home and back. It has no
+// signed-in shortcut either: a signed-in person too stale to link is sent
+// here precisely to sign in again.
+func TestSigninLocalIsEmailOnly(t *testing.T) {
+ f := newDoorFixture(t)
+ for _, target := range []string{"/signin/local", "/signin/local?return_to=%2Fd%2F42", "/signin/local?way=oficina", "/signin/local?ways=1"} {
+ for _, cookies := range [][]*http.Cookie{nil, {liveSession}} {
+ calls := f.calls
+ w := f.get(f.h.SigninLocal, target, cookies...)
+ if w.Code != 299 || f.calls != calls+1 || f.path != SigninLocalPath {
+ t.Fatalf("%s (%d cookies): %d %q, want the door", target, len(cookies), w.Code, w.Header().Get("Location"))
+ }
+ if f.href != "" {
+ t.Fatalf("%s offered Oficina ID: %q", target, f.href)
+ }
+ }
+ }
+ // Every flow that ends locally ends here.
+ for state, want := range map[string]string{"unknown": SigninLocalPath, "failed": SigninLocalPath, "anything": SigninLocalPath, "signedout": SigninPath} {
+ if got := Page(state, "").Action; got != want {
+ t.Errorf("%s leads to %q, want %q", state, got, want)
+ }
+ }
+}
+
+// TestOficinaHrefOnlyWhereTheDoorMayOfferIt: the href exists only on a
+// request connect's /signin handed to the app, and never on a step-up.
+func TestOficinaHrefOnlyWhereTheDoorMayOfferIt(t *testing.T) {
+ if got := OficinaHref(httptest.NewRequest(http.MethodGet, navigationOrigin+"/signin", nil)); got != "" {
+ t.Fatalf("a door connect did not hand over offers Oficina ID: %q", got)
+ }
+ f := newDoorFixture(t)
+ for _, query := range []string{"?reauth=1", "?reauth=1&return_to=%2Fd%2F42", "?reauth=0", "?reauth=1&way=oficina", "?ways=1&reauth=1"} {
+ f.get(f.h.SigninDoor, SigninPath+query)
+ if f.href != "" {
+ t.Fatalf("%s: a step-up offered Oficina ID: %q", query, f.href)
+ }
+ }
+}
+
+// TestSigninOficinaStartsTheExchange is "Continue with Oficina ID": the
+// sealed return cookie remembers the page, and the browser goes to
+// handoff.StartPath with it. A return_to connect would not follow is "/".
+func TestSigninOficinaStartsTheExchange(t *testing.T) {
+ f := newDoorFixture(t)
+ for _, tc := range []struct {
+ query string
+ cookies []*http.Cookie
+ want string
+ }{
+ {"?return_to=%2Fd%2F42%3Fview%3Dcompact", nil, "/d/42?view=compact"},
+ {"", nil, "/"},
+ {"?return_to=https%3A%2F%2Fevil.example%2F", nil, "/"},
+ {"?return_to=%2F%2Fevil.example", nil, "/"},
+ {"?return_to=%2Fsignin", nil, "/"},
+ {"?return_to=%2Fauth%2Fstart", nil, "/"},
+ {"?return_to=%2Fa&return_to=%2Fb", nil, "/"},
+ {"?return_to=javascript%3Aalert(1)", nil, "/"},
+ {"?return_to=%2Fd%2F42", []*http.Cookie{staleSession}, "/d/42"},
+ {"?return_to=%2Fd%2F42", []*http.Cookie{liveSession, liveSession}, "/d/42"},
+ {"?return_to=%2Fd%2F42", []*http.Cookie{guestSession}, "/d/42"},
+ } {
+ w := f.get(f.h.SigninOficina, SigninOficinaPath+tc.query, tc.cookies...)
+ start := handoff.StartPath + "?" + url.Values{"return_to": {tc.want}}.Encode()
+ if w.Code != 303 || w.Header().Get("Location") != start {
+ t.Fatalf("%s: %d %q", tc.query, w.Code, w.Header().Get("Location"))
+ }
+ if w.Header().Get("Cache-Control") != "no-store" {
+ t.Fatalf("%s: cacheable", tc.query)
+ }
+ var remembered *http.Cookie
+ for _, c := range w.Result().Cookies() {
+ if c.Name == homeReturnCookie {
+ remembered = c
+ }
+ }
+ if remembered == nil || remembered.MaxAge <= 0 || !remembered.Secure || !remembered.HttpOnly {
+ t.Fatalf("%s: the page was not remembered", tc.query)
+ }
+ back := httptest.NewRequest(http.MethodGet, navigationOrigin+"/auth/finish", nil)
+ back.AddCookie(remembered)
+ if got := f.h.navigation.returnPath(back); got != tc.want {
+ t.Fatalf("%s: remembered %q, want %q", tc.query, got, tc.want)
+ }
+ if f.calls != 0 {
+ t.Fatal("Continue with Oficina ID drew the door")
+ }
+ }
+ if w := f.get(f.h.SigninOficina, SigninOficinaPath+"?%zz"); w.Code != 400 || w.Header().Get("Location") != "" {
+ t.Fatal("a malformed query started an exchange", w.Code)
+ }
+ // Failing to remember is a 503, never an exchange that forgets the page.
+ f.h.navigation.now = func() time.Time { return time.Unix(0, 0) }
+ if w := f.get(f.h.SigninOficina, SigninOficinaPath+"?return_to=%2Fd%2F42"); w.Code != 503 || w.Header().Get("Location") != "" {
+ t.Fatal("an unremembered return started the exchange", w.Code)
+ }
+}
+
+// TestStepUpNeverReachesHome is the spec's reauth rule: a step-up offers
+// local ways only. Linking needs FreshLocal, which no Home sign-in gives,
+// and a live id.* session would hand back an old auth_time. So a reauth
+// that reaches /signin/oficina anyway goes to the local door, keeping it.
+func TestStepUpNeverReachesHome(t *testing.T) {
+ f := newDoorFixture(t)
+ for _, tc := range []struct{ query, want string }{
+ {"?reauth=1&return_to=%2Fd%2F42", "/signin/local?reauth=1&return_to=%2Fd%2F42"},
+ {"?reauth=1", "/signin/local?reauth=1"},
+ {"?reauth=yes&return_to=%2F%2Fevil.example", "/signin/local?reauth=1"},
+ } {
+ for _, cookies := range [][]*http.Cookie{nil, {liveSession}} {
+ w := f.get(f.h.SigninOficina, SigninOficinaPath+tc.query, cookies...)
+ if w.Code != 303 || w.Header().Get("Location") != tc.want || len(w.Result().Cookies()) != 0 {
+ t.Fatalf("%s: %d %q", tc.query, w.Code, w.Header().Get("Location"))
+ }
+ }
+ }
+ // The link flow's own step-up: a session too old to link goes to the
+ // local door, which offers no Oficina ID.
+ _, n := navigationFixture(t)
+ f.h.navigation = n
+ w := httptest.NewRecorder()
+ n.Begin(w, httptest.NewRequest(http.MethodGet, navigationOrigin+"/account/home", nil))
+ if w.Code != 303 || w.Header().Get("Location") != SigninLocalPath {
+ t.Fatalf("link step-up: %d %q", w.Code, w.Header().Get("Location"))
+ }
+ f.get(f.h.SigninLocal, w.Header().Get("Location"), liveSession)
+ if f.href != "" {
+ t.Fatal("the link step-up offered Oficina ID")
+ }
+ if _, fresh := FreshLocal(Session{Subject: "pr_x", Method: HomeMethod, AuthTime: time.Now()}, time.Now()); fresh {
+ t.Fatal("a Home sign-in counted as a fresh local one")
+ }
+}
+
+// TestSignedOutOffersForget: with ForgetPath, the signed-out page carries a
+// second form, "Forget me on this device", posting to the app's Forget.
+// Without it there is none, as before. It is a plain same-origin form, so
+// the app's csrf.Protect admits it from this origin, refuses it from any
+// other, and Middleware exempts nothing for it.
+func TestSignedOutOffersForget(t *testing.T) {
+ f := newBridgeFixture(t)
+ for _, forget := range []string{"", "/signin/forget", "/auth/forget"} {
+ var got PageData
+ cfg := RoutesConfig{Namespace: "oficina/docs", Origin: bridgeOrigin, Issuer: bridgeIssuer, SessionCookie: f.sessions.cookie, DEK: bytes.Repeat([]byte{41}, 32), ForgetPath: forget,
+ ReadSession: func(*http.Request) (*Session, error) { return nil, nil },
+ SignOut: func(http.ResponseWriter, *http.Request) {}, LocalSignin: func(http.ResponseWriter, *http.Request) {},
+ Protect: csrf.Protect(bridgeOrigin),
+ Render: func(w http.ResponseWriter, r *http.Request, state, label string, status int) {
+ got = PageFor(r, state, label)
+ w.WriteHeader(status)
+ }}
+ h, err := NewRoutes(f.b, cfg)
+ if err != nil {
+ t.Fatal(forget, err)
+ }
+ w := httptest.NewRecorder()
+ h.SignedOut(w, bridgeRequest(http.MethodGet, "/signed-out", nil))
+ if w.Code != 200 || got.Title != "You’re signed out" || got.Action != SigninPath || got.ForgetAction != forget {
+ t.Fatalf("ForgetPath %q: %d %+v", forget, w.Code, got)
+ }
+ if forget == "" {
+ continue
+ }
+ reached := 0
+ handler := h.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached++; w.WriteHeader(303) }))
+ for _, tc := range []struct {
+ header, value string
+ want int
+ }{{"Origin", bridgeOrigin, 303}, {"Sec-Fetch-Site", "same-origin", 303}, {"Origin", "https://evil.example", 403}, {"Sec-Fetch-Site", "cross-site", 403}, {"", "", 403}} {
+ r := httptest.NewRequest(http.MethodPost, bridgeOrigin+forget, strings.NewReader(""))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if tc.header != "" {
+ r.Header.Set(tc.header, tc.value)
+ }
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, r)
+ if w.Code != tc.want {
+ t.Fatalf("Forget POST with %s %q: %d, want %d", tc.header, tc.value, w.Code, tc.want)
+ }
+ }
+ if reached != 2 {
+ t.Fatal("Forget reached past the same-origin check", reached)
+ }
+ }
+ // Only the page Routes.SignedOut draws carries it.
+ r := bridgeRequest(http.MethodGet, "/signed-out", nil)
+ if Page("signedout", "").ForgetAction != "" || PageFor(r, "signedout", "").ForgetAction != "" {
+ t.Fatal("Forget offered without the signed-out route")
+ }
+ // The Home-derived sign-out still chains to id.* (TestSignoutChainsToTheIssuer).
+}
+
+// TestForgetPathMustBeLocal: a form action that could leave the origin, or
+// carry a query, is refused at boot rather than drawn.
+func TestForgetPathMustBeLocal(t *testing.T) {
+ f := newBridgeFixture(t)
+ for _, bad := range []string{"signin/forget", "//evil.example/forget", "https://evil.example/forget", "/forget?x=1", "/forget#x", "/a/../forget", "/a\\forget", "/a%2Fforget", "/forget/", "/a//forget", "javascript:alert(1)"} {
+ _, err := NewRoutes(f.b, RoutesConfig{Namespace: "oficina/docs", Origin: bridgeOrigin, Issuer: bridgeIssuer, SessionCookie: f.sessions.cookie, DEK: bytes.Repeat([]byte{41}, 32), ForgetPath: bad,
+ ReadSession: func(*http.Request) (*Session, error) { return nil, nil }, SignOut: func(http.ResponseWriter, *http.Request) {}, LocalSignin: func(http.ResponseWriter, *http.Request) {},
+ Protect: func(next http.Handler) http.Handler { return next }, Render: f.b.render})
+ if err == nil {
+ t.Errorf("ForgetPath %q accepted", bad)
+ }
+ }
+}
+
+// TestPageDataStillDrawsTheSharedTemplate: PageData stopped being an alias
+// of estilo's homeconnect.PageData when it gained ForgetAction. Its shared
+// fields keep their names, so estilo's home-connect template draws it.
+func TestPageDataStillDrawsTheSharedTemplate(t *testing.T) {
+ view := template.Must(template.ParseFS(Templates(), "templates/*.html"))
+ var out bytes.Buffer
+ if err := view.ExecuteTemplate(&out, "home-connect", Page("confirm", "person@example.test")); err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{English["confirm_title"], `action="/account/home/confirm"`, "<bdi>person@example.test</bdi>", English["cancel_action"]} {
+ if !strings.Contains(out.String(), want) {
+ t.Fatalf("missing %q in %s", want, out.String())
+ }
+ }
+ // And a struct embedding it, as Slides and Sheets do.
+ type appView struct{ PageData }
+ out.Reset()
+ if err := view.ExecuteTemplate(&out, "home-connect", appView{Page("start", "")}); err != nil || !strings.Contains(out.String(), English["start_title"]) {
+ t.Fatal("an embedding view no longer draws", err)
+ }
+}
+
+// TestMintedPersonIsWhoJustSignedIn: MintHomeSession is where an app
+// remembers "Continue with Oficina ID" (the smart door's federated record),
+// with the address of the person who just signed in, or none. connect hands
+// it that person on the minting request only: the linked local account, or
+// a Home-only person with no address. Never on link, choose or unknown.
+func TestMintedPersonIsWhoJustSignedIn(t *testing.T) {
+ type mint struct {
+ person Person
+ ok bool
+ }
+ watch := func(f *bridgeFixture) *[]mint {
+ var seen []mint
+ inner := f.b.mintSession
+ f.b.mintSession = func(w http.ResponseWriter, r *http.Request, s Session) error {
+ p, ok := MintedPerson(r)
+ seen = append(seen, mint{p, ok})
+ return inner(w, r, s)
+ }
+ return &seen
+ }
+
+ f := newBridgeFixture(t)
+ seen := watch(f)
+ local := f.local(t, "one@example.com", "magiclink", time.Time{})
+ f.link(t, local, "opaque-subject-one")
+ if len(*seen) != 0 {
+ t.Fatal("linking minted a Home session")
+ }
+ unknown := f.finishAs(t, "opaque-subject-nobody", nil)
+ if unknown.Code != 403 || len(*seen) != 0 {
+ t.Fatal("an unknown subject minted", unknown.Code)
+ }
+ if w := f.finishAs(t, "opaque-subject-one", nil); w.Code != 303 {
+ t.Fatalf("ordinary finish=%d", w.Code)
+ }
+ var id int64
+ if err := f.db.QueryRow("SELECT id FROM people WHERE email='one@example.com'").Scan(&id); err != nil {
+ t.Fatal(err)
+ }
+ if len(*seen) != 1 || !(*seen)[0].ok || (*seen)[0].person != (Person{ID: id, Label: "one@example.com"}) {
+ t.Fatalf("minted with %+v", *seen)
+ }
+ if _, ok := MintedPerson(bridgeRequest(http.MethodGet, "/", nil)); ok {
+ t.Fatal("a person on a request that minted nothing")
+ }
+
+ team, _ := newHomeOnlyFixture(t)
+ seen = watch(team)
+ finish := team.finishAs(t, "pr_member", nil)
+ if len(*seen) != 0 {
+ t.Fatal("the choose page minted")
+ }
+ if _, w := team.choose(t, finish, "new", nil); w.Code != 303 {
+ t.Fatalf("choose new=%d", w.Code)
+ }
+ if len(*seen) != 1 || !(*seen)[0].ok || (*seen)[0].person.ID <= 1000 || (*seen)[0].person.Label != "" {
+ t.Fatalf("a new member minted with %+v", *seen)
+ }
+}
+
+// TestConnectImportsNoLastsignin: remembering the way in is each app's job
+// (MintHomeSession), so connect never forces a rastrillo minor on its
+// consumers by importing lastsignin, directly or through auth.
+func TestConnectImportsNoLastsignin(t *testing.T) {
+ out, err := exec.Command("go", "list", "-deps", "./...").Output()
+ if err != nil {
+ t.Skip("go list unavailable:", err)
+ }
+ for _, dep := range strings.Fields(string(out)) {
+ switch dep {
+ case "amadan.net/rastrillo/rastrillo/lastsignin", "amadan.net/rastrillo/rastrillo/auth":
+ t.Errorf("connect depends on %s", dep)
+ }
+ }
+}
diff --git a/connect/navigation.go b/connect/navigation.go
index bae5b39..94a9b85 100644
--- a/connect/navigation.go
+++ b/connect/navigation.go
@@ -107,7 +107,7 @@ func (n *localLinkNavigation) Begin(w http.ResponseWriter, r *http.Request) {
return
}
localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime))
- http.Redirect(w, r, "/signin/local", http.StatusSeeOther)
+ http.Redirect(w, r, SigninLocalPath, http.StatusSeeOther)
}
var (
diff --git a/connect/routes.go b/connect/routes.go
index 42eb5b1..8caba53 100644
--- a/connect/routes.go
+++ b/connect/routes.go
@@ -1,10 +1,12 @@
package connect
import (
+ "context"
"crypto/sha256"
"errors"
"net/http"
"net/url"
+ "path"
"strings"
"amadan.net/oficina/home/handoff"
@@ -23,6 +25,14 @@ type RoutesConfig struct {
LocalSignin http.HandlerFunc
Protect func(http.Handler) http.Handler
Render func(http.ResponseWriter, *http.Request, string, string, int)
+ // ForgetPath is optional: where the app mounted rastrillo auth's
+ // Forget (auth.Config.ForgetPath, "/signin/forget" by default). With it
+ // set, the signed-out page offers "Forget me on this device", a POST
+ // there (PageData.ForgetAction). It must be an absolute local path with
+ // no query. The form is a plain same-origin POST with no token, so it
+ // passes csrf.SameOrigin (Protect, and Forget's own check) and needs no
+ // exemption in Middleware. Empty offers none, as before.
+ ForgetPath string
}
type Routes struct {
@@ -32,6 +42,9 @@ type Routes struct {
}
func NewRoutes(b *Bridge, c RoutesConfig) (*Routes, error) {
+ if c.ForgetPath != "" && !localPath(c.ForgetPath) {
+ return nil, errors.New("home connect: invalid routes")
+ }
if (c.LocalLandingPath != "" && !handoff.SafePath(c.LocalLandingPath)) || b == nil || c.ReadSession == nil || c.SignOut == nil || c.LocalSignin == nil || c.Protect == nil || c.Render == nil || c.Origin != b.origin || c.Issuer != b.issuer || c.SessionCookie != b.sessionCookie || c.Namespace != b.namespace || sha256.Sum256(c.DEK) != b.keyHash {
return nil, errors.New("home connect: invalid routes")
}
@@ -50,6 +63,16 @@ func NewRoutes(b *Bridge, c RoutesConfig) (*Routes, error) {
return &Routes{bridge: b, navigation: n, cfg: c}, nil
}
+// localPath is a path on this origin, with nothing a form action could take
+// elsewhere: absolute, no scheme or host, no query or fragment, clean.
+func localPath(p string) bool {
+ u, err := url.Parse(p)
+ return err == nil && u.Scheme == "" && u.Host == "" && u.User == nil && u.RawQuery == "" && u.Fragment == "" && !u.ForceQuery &&
+ u.Path == p && strings.HasPrefix(p, "/") && !strings.HasPrefix(p, "//") && !strings.ContainsAny(p, "\\\x00") && path.Clean(p) == p
+}
+
+type forgetKey struct{}
+
func cookieCount(r *http.Request, name string) int {
n := 0
for _, c := range r.Cookies() {
@@ -102,44 +125,19 @@ func (h *Routes) LocalGuard(next http.HandlerFunc) http.HandlerFunc {
}
}
-func (h *Routes) Signin(w http.ResponseWriter, r *http.Request) {
- q, err := url.ParseQuery(r.URL.RawQuery)
- if err != nil {
- h.bridge.fail(w, r, http.StatusBadRequest)
- return
- }
- if q.Has("sent") || q.Has("err") || q.Has("force") {
- h.cfg.LocalSignin(w, r)
- return
- }
- path := "/"
- if values, ok := q["return_to"]; ok && len(values) == 1 && handoff.SafePath(values[0]) {
- path = values[0]
- }
- // Already signed in: go where the person was headed, with no form and
- // no second exchange (spec shared-chrome §9.4). SafePath refuses
- // /signin and /auth/*, so this cannot loop.
- if h.signedIn(r) {
- w.Header().Set("Cache-Control", "no-store")
- http.Redirect(w, r, path, http.StatusSeeOther)
- return
- }
- if !h.navigation.rememberReturn(w, path) {
- h.bridge.fail(w, r, http.StatusServiceUnavailable)
- return
- }
- w.Header().Set("Cache-Control", "no-store")
- http.Redirect(w, r, handoff.StartPath+"?"+url.Values{"return_to": {path}}.Encode(), http.StatusSeeOther)
-}
-
// signedIn reports a live, signed-in app session: exactly one session
// cookie, which ReadSession resolves to a person who signed in, through
// Home (IsHomeDerived and not Expired) or a local link (magiclink,
// keymail). An ambiguous pair or a revoked cookie is not one, and neither
// is any other method: Calls' anonymous per-meeting guests ("guest") are
// sessions but not sign-ins, and sending one to the root instead of the
-// exchange ends on a 404 (the #74 review, finding 3). An unknown method falls back to the
-// exchange, which is what /signin did before this check existed.
+// door ends on a 404 (the #74 review, finding 3). An unknown method gets the
+// door (SigninDoor) or the exchange (SigninOficina), as if signed out.
+//
+// It reads the session cookie and nothing else. An app whose signed-in
+// routes refuse some live sessions (a removed member, a revoked share) must
+// end or hide such a session before SigninDoor or SigninOficina, or the two
+// redirect to each other forever (Astra on Docs #65, Sheets #39).
func (h *Routes) signedIn(r *http.Request) bool {
if cookieCount(r, h.cfg.SessionCookie) != 1 {
return false
@@ -154,7 +152,14 @@ func (h *Routes) signedIn(r *http.Request) bool {
return s.Method == "magiclink" || s.Method == "keymail"
}
+// SignedOut is GET /signed-out, where Signout lands: Render with state
+// "signedout". With RoutesConfig.ForgetPath set, PageFor on that request
+// carries it as PageData.ForgetAction, the page's second form, "Forget me
+// on this device".
func (h *Routes) SignedOut(w http.ResponseWriter, r *http.Request) {
+ if h.cfg.ForgetPath != "" {
+ r = r.WithContext(context.WithValue(r.Context(), forgetKey{}, h.cfg.ForgetPath))
+ }
h.cfg.Render(w, r, "signedout", "", http.StatusOK)
}
func (h *Routes) LocalComplete(w http.ResponseWriter, r *http.Request) { h.navigation.Complete(w, r) }
diff --git a/connect/routes_test.go b/connect/routes_test.go
index 9b0b27d..03775c5 100644
--- a/connect/routes_test.go
+++ b/connect/routes_test.go
@@ -7,7 +7,6 @@ import (
"net/http/httptest"
"strings"
"testing"
- "time"
)
func TestRouteGuardExemptsOnlyCallbackAndPreservesPolicy(t *testing.T) {
@@ -122,74 +121,6 @@ func assertSignoutCleared(t *testing.T, w *httptest.ResponseRecorder) {
}
}
-// TestSigninWhenAlreadySignedIn is spec shared-chrome §9.4: GET /signin
-// with a live session goes straight to the validated return_to, or /,
-// instead of starting another assertion exchange. Without a session, or
-// with an explicit local state (sent, err, force), nothing changes.
-func TestSigninWhenAlreadySignedIn(t *testing.T) {
- _, n := navigationFixture(t)
- locals := 0
- h := &Routes{bridge: &Bridge{now: time.Now, render: func(w http.ResponseWriter, r *http.Request, state, label string, status int) { w.WriteHeader(status) }}, navigation: n, cfg: RoutesConfig{Origin: navigationOrigin, SessionCookie: "__Host-rastrillo_session", ReadSession: func(r *http.Request) (*Session, error) {
- c, err := r.Cookie("__Host-rastrillo_session")
- if err != nil || (c.Value != "verified" && c.Value != "guest") {
- return nil, nil
- }
- method := HomeMethod
- if c.Value == "guest" {
- method = "guest"
- }
- return &Session{Subject: "pr_live", Method: method, At: time.Now()}, nil
- }}}
- h.cfg.LocalSignin = func(w http.ResponseWriter, r *http.Request) { locals++; w.WriteHeader(299) }
- live := &http.Cookie{Name: "__Host-rastrillo_session", Value: "verified"}
- stale := &http.Cookie{Name: "__Host-rastrillo_session", Value: "revoked"}
- for _, tc := range []struct {
- query string
- cookies []*http.Cookie
- code int
- want string
- }{
- {"?return_to=%2Fd%2F42%3Fview%3Dcompact", []*http.Cookie{live}, 303, "/d/42?view=compact"},
- {"", []*http.Cookie{live}, 303, "/"},
- {"?return_to=https%3A%2F%2Fevil.example%2F", []*http.Cookie{live}, 303, "/"},
- {"?return_to=%2F%2Fevil.example", []*http.Cookie{live}, 303, "/"},
- {"?return_to=%2Fsignin", []*http.Cookie{live}, 303, "/"},
- {"?return_to=%2Fa&return_to=%2Fb", []*http.Cookie{live}, 303, "/"},
- // No session, a stale one, or an ambiguous pair: start the exchange.
- {"?return_to=%2Fd%2F42", nil, 303, handoff.StartPath + "?return_to=%2Fd%2F42"},
- {"?return_to=%2Fd%2F42", []*http.Cookie{stale}, 303, handoff.StartPath + "?return_to=%2Fd%2F42"},
- {"?return_to=%2Fd%2F42", []*http.Cookie{live, live}, 303, handoff.StartPath + "?return_to=%2Fd%2F42"},
- // A Calls guest (an anonymous, per-meeting session) is not signed
- // in for this purpose: it still starts the exchange, as before,
- // rather than bouncing to a root that 404s for guests.
- {"?return_to=%2Fd%2F42", []*http.Cookie{{Name: "__Host-rastrillo_session", Value: "guest"}}, 303, handoff.StartPath + "?return_to=%2Fd%2F42"},
- {"", []*http.Cookie{{Name: "__Host-rastrillo_session", Value: "guest"}}, 303, handoff.StartPath + "?return_to=%2F"},
- // Explicit local states still reach the local page.
- {"?force=1", []*http.Cookie{live}, 299, ""},
- {"?err=removed", []*http.Cookie{live}, 299, ""},
- {"?sent=1", []*http.Cookie{live}, 299, ""},
- } {
- r := httptest.NewRequest("GET", navigationOrigin+"/signin"+tc.query, nil)
- for _, c := range tc.cookies {
- r.AddCookie(c)
- }
- w := httptest.NewRecorder()
- h.Signin(w, r)
- if w.Code != tc.code || w.Header().Get("Location") != tc.want {
- t.Fatalf("%q with %d cookies: %d %q", tc.query, len(tc.cookies), w.Code, w.Header().Get("Location"))
- }
- if tc.code == 303 && w.Header().Get("Cache-Control") != "no-store" {
- t.Fatalf("%q: cacheable", tc.query)
- }
- if tc.code == 303 && !strings.HasPrefix(tc.want, handoff.StartPath) && len(w.Result().Cookies()) != 0 {
- t.Fatalf("%q: a signed-in redirect set a cookie", tc.query)
- }
- }
- if locals != 3 {
- t.Fatal("local states", locals)
- }
-}
-
func TestStaleSessionStillRefusesAndOffersExplicitLocalRecovery(t *testing.T) {
f := newBridgeFixture(t)
templates := template.Must(template.ParseFS(Templates(), "templates/*.html"))
diff --git a/connect/view.go b/connect/view.go
index 611c4aa..ce59f34 100644
--- a/connect/view.go
+++ b/connect/view.go
@@ -10,15 +10,39 @@ import (
func Templates() embed.FS { return homeconnect.Templates() }
-type PageData = homeconnect.PageData
+// PageData is a connect page's data: estilo's homeconnect.PageData, whose
+// home-connect template draws it, plus ForgetAction for the signed-out page.
+// It was an alias of homeconnect.PageData until the smart door (Home spec
+// 2026-11-19-smart-door.md); the shared fields keep their names, so a
+// template or an embedding struct reads it as before.
+type PageData struct {
+ Title, Body, Address, Action, ActionLabel, CancelLabel string
+ PostAction bool
+ // ForgetAction is the signed-out page's second form, "Forget me on this
+ // device": a POST with no fields to the app's rastrillo auth Forget
+ // (RoutesConfig.ForgetPath), which forgets how this browser last signed
+ // in here, for a shared computer. "" draws none. Set by PageFor on the
+ // request Routes.SignedOut renders, never by Page. Draw it with estilo's
+ // estilo-signed-out:
+ //
+ // chrome.SignInNotice{…}.SignedOut(p.Action).Forgetting(p.ForgetAction, "")
+ //
+ // which supplies the label. It forgets this host only: each host keeps
+ // its own record, and id.oficina.works offers its own Forget.
+ ForgetAction string
+}
// PageFor is Page for the request being answered. On "Accounts connected"
-// its way back is the page the link began from, where Page's is "/".
+// its way back is the page the link began from, where Page's is "/". On the
+// signed-out page Routes.SignedOut renders, it carries ForgetAction.
func PageFor(r *http.Request, state, label string, translate ...func(string) string) PageData {
p := Page(state, label, translate...)
if back, ok := r.Context().Value(successReturnKey{}).(string); ok && state == "success" && handoff.SafePath(back) {
p.Action = back
}
+ if forget, ok := r.Context().Value(forgetKey{}).(string); ok && state == "signedout" && localPath(forget) {
+ p.ForgetAction = forget
+ }
return p
}
@@ -38,17 +62,17 @@ func Page(state, label string, translate ...func(string) string) PageData {
p.PostAction = true
p.ActionLabel = t("confirm_action")
case "unknown":
- p.Action = "/signin/local"
+ p.Action = SigninLocalPath
p.ActionLabel = t("local_action")
case "signedout":
- p.Action = "/signin"
+ p.Action = SigninPath
p.ActionLabel = t("signedout_action")
case "success":
p.Action = "/"
p.ActionLabel = t("documents_action")
default:
state = "failed"
- p.Action = "/signin/local"
+ p.Action = SigninLocalPath
p.ActionLabel = t("local_action")
}
p.Title = t(state + "_title")