oficina / home Public

connect: menu reads the stored link; an unknown arrival resumes linking

Four fixes to connecting an Oficina account, shared by every app on
home/connect.

- Bridge.Linked reports whether the local person has a stored link, one
  lookup on the UNIQUE (issuer, person_id) index. Apps offered "Connect
  your Oficina account" to every session that had not signed in through
  Home, so a linked person who used the app's own email link was still
  offered it.
- An assertion with no link here used to end at "Sign in, then connect
  from the account menu". It now leaves the existing sealed, ten-minute
  navigation marker (action link-resume, no identity in it). The next
  fresh local sign-in begins the link exactly as the Connect button
  does, so it still needs a fresh Home assertion bound to that session
  and the explicit confirm POST. An expired marker is ignored.
- The confirm POST ends on GET /account/home/confirm?connected=1, which
  says "Accounts connected", shown only once the link is stored.
  PageFor gives that page a way back to where the link began.
- Copy: the confirm step asks its own question, and the unknown state
  says what signing in will do.

The connect module now requires the estilo branch whose homeconnect
template puts the two buttons in one row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 08bbcf31e4839c459b5991f8e8c7116b9663d03f parent ba81936
13 files changed, +453 −36
  • connect/README.md +10 −0
  • connect/api.go +9 −0
  • connect/bridge.go +7 −0
  • connect/bridge_test.go +20 −3
  • connect/go.mod +1 −1
  • connect/go.sum +2 −2
  • connect/link_handlers.go +89 −7
  • connect/linked_test.go +199 −0
  • connect/linkstore/store.go +19 −0
  • connect/navigation.go +70 −18
  • connect/navigation_test.go +2 −2
  • connect/routes.go +2 −0
  • connect/view.go +23 −3

CI cancelled — superseded by a newer push — run details

diff --git a/connect/README.md b/connect/README.md
index 02d4491..c258ad4 100644
--- a/connect/README.md
+++ b/connect/README.md
@@ -69,6 +69,16 @@ admits that hop only from an origin registered in its `HOME_CONSUMERS`, by
`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
+with `PageFor(r, ...)` so "Accounts connected" leads back to the page the link
+began from. An assertion with no link here leaves a sealed, ten-minute
+navigation marker: the next fresh local sign-in begins the link at once and
+lands, after Home's freshness check, on the confirm step. An expired marker is
+ignored. The confirm POST ends on `GET /account/home/confirm?connected=1`,
+which shows "Accounts connected" only to a person whose link is stored.
+
Wrap the trusted local plugin's Begin handler with `OAuthContinuation` when it
can redirect to Keymail. Render the supplied destination with `OAuthPage` and the
shared `home-oauth-head` and `home-oauth` templates inside your existing layout.
diff --git a/connect/api.go b/connect/api.go
index 91aee15..17f7f94 100644
--- a/connect/api.go
+++ b/connect/api.go
@@ -48,6 +48,15 @@ func (b *Bridge) Resolve(ctx context.Context, subject string) (Person, error) {
id, label, err := b.links.Resolve(ctx, b.issuer, subject)
return Person{ID: id, Label: label}, err
}
+
+// Linked reports whether the local person already has a stored link to an
+// Oficina identity. The account menu offers "Connect your Oficina account"
+// only when it does not, however this session signed in: someone linked who
+// signed in with the app's own email link is still linked. One indexed
+// lookup; an error means "unknown", and callers should offer nothing.
+func (b *Bridge) Linked(ctx context.Context, person int64) (bool, error) {
+ return b.links.Linked(ctx, person)
+}
func (b *Bridge) ResolveSession(r *http.Request) (Person, error) {
session, err := b.actualSession(r)
if err != nil || session == nil {
diff --git a/connect/bridge.go b/connect/bridge.go
index 245a441..40deb82 100644
--- a/connect/bridge.go
+++ b/connect/bridge.go
@@ -33,6 +33,10 @@ type Bridge struct {
mintSession func(http.ResponseWriter, *http.Request, Session) error
localPerson func(context.Context, Session) (Person, error)
render func(http.ResponseWriter, *http.Request, string, string, int)
+ // rememberUnknown is set by NewRoutes: an assertion with no link here
+ // leaves the sealed navigation marker that resumes linking after the
+ // person signs in locally.
+ rememberUnknown func(http.ResponseWriter)
}
type homeFinishKey struct{}
type homeFinishResult struct {
@@ -207,6 +211,9 @@ func (b *Bridge) complete(w http.ResponseWriter, r *http.Request, claims asserti
}
id, _, err := b.links.Resolve(r.Context(), claims.Issuer, claims.Subject)
if errors.Is(err, linkstore.ErrRefused) {
+ if b.rememberUnknown != nil {
+ b.rememberUnknown(w)
+ }
return rejectHome(r, "unknown", http.StatusForbidden)
}
if err != nil {
diff --git a/connect/bridge_test.go b/connect/bridge_test.go
index ffa0569..c97ff6a 100644
--- a/connect/bridge_test.go
+++ b/connect/bridge_test.go
@@ -236,8 +236,8 @@ func (f *bridgeFixture) link(t *testing.T, local *http.Cookie, subject string) {
}
w := httptest.NewRecorder()
f.b.ConfirmPost(w, bridgeRequest(http.MethodPost, "/account/home/confirm", cookies))
- if w.Code != 303 || w.Header().Get("Location") != "/" {
- t.Fatalf("confirm=%d", w.Code)
+ if w.Code != 303 || w.Header().Get("Location") != connectedURL("/") {
+ t.Fatalf("confirm=%d %q", w.Code, w.Header().Get("Location"))
}
bridgeNoSession(t, f.b, w)
}
@@ -479,9 +479,26 @@ func TestHomeBridgeReturnPathCallbackRemainsSafe(t *testing.T) {
proof, cookies := f.linkProof(t, local, "opaque")
w := httptest.NewRecorder()
f.b.ConfirmPost(w, bridgeRequest(http.MethodPost, "/account/home/confirm", append(cookies, proof)))
- if w.Code != 303 || w.Header().Get("Location") != tc.want {
+ if w.Code != 303 || w.Header().Get("Location") != connectedURL(tc.want) {
t.Fatalf("return location=%q status=%d", w.Header().Get("Location"), w.Code)
}
+ // The success page's way back is that same safe path, even
+ // when the query is hand-edited to something else.
+ var back string
+ f.b.render = func(w http.ResponseWriter, r *http.Request, state, label string, status int) {
+ back = PageFor(r, state, label).Action
+ w.WriteHeader(status)
+ }
+ for location, want := range map[string]string{w.Header().Get("Location"): tc.want, connectedURL(tc.input): "/"} {
+ if tc.input == tc.want {
+ want = tc.want
+ }
+ done := httptest.NewRecorder()
+ f.b.ConfirmPage(done, bridgeRequest(http.MethodGet, location, []*http.Cookie{local}))
+ if done.Code != 200 || back != want {
+ t.Fatalf("%s: success way back=%q status=%d want %q", location, back, done.Code, want)
+ }
+ }
})
}
}
diff --git a/connect/go.mod b/connect/go.mod
index de1fbd8..e6dac3e 100644
--- a/connect/go.mod
+++ b/connect/go.mod
@@ -3,7 +3,7 @@ module amadan.net/oficina/home/connect
go 1.25.0
require (
- amadan.net/oficina/estilo.git v0.0.0-20260909234655-dec3908b237c
+ amadan.net/oficina/estilo.git v0.0.0-20261024215431-0b375d59ca32
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2
diff --git a/connect/go.sum b/connect/go.sum
index db96826..acebc8e 100644
--- a/connect/go.sum
+++ b/connect/go.sum
@@ -1,5 +1,5 @@
-amadan.net/oficina/estilo.git v0.0.0-20260909234655-dec3908b237c h1:LgE7WLm6zMG/qZScoAHb4X2gguzorctB4XGjPYavXts=
-amadan.net/oficina/estilo.git v0.0.0-20260909234655-dec3908b237c/go.mod h1:0R45/vCUAT+kpS7S6K/ZxBdE8f7YxFN4HT3HyDJ3nPY=
+amadan.net/oficina/estilo.git v0.0.0-20261024215431-0b375d59ca32 h1:YJhvKpW6eTejjvXRbb+CHrgmF6Pms7N2q2/73dbm3iA=
+amadan.net/oficina/estilo.git v0.0.0-20261024215431-0b375d59ca32/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM=
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd h1:jlFSt95M1ontOg+VePU+kIJpChtWqDQAbnmlxqCnbgc=
diff --git a/connect/link_handlers.go b/connect/link_handlers.go
index bdbd5f1..ac8999b 100644
--- a/connect/link_handlers.go
+++ b/connect/link_handlers.go
@@ -1,8 +1,11 @@
package connect
import (
+ "context"
"errors"
"net/http"
+ "net/url"
+ "strings"
"amadan.net/oficina/home/connect/linkstore"
"amadan.net/oficina/home/handoff"
@@ -30,18 +33,37 @@ func (b *Bridge) LinkStart(w http.ResponseWriter, r *http.Request) {
if !b.guard(w, r, http.MethodPost, "/account/home") {
return
}
+ if status, err := b.startLink(w, r); err != nil {
+ if status == 0 {
+ b.linkFailure(w, r, err)
+ } else {
+ b.fail(w, r, status)
+ }
+ }
+}
+
+// resumeLink is LinkStart for a person who just signed in locally after an
+// Oficina assertion with no link arrived: the same checks, the same flow.
+// It reports false having written nothing when the link cannot begin.
+func (b *Bridge) resumeLink(w http.ResponseWriter, r *http.Request) bool {
+ _, err := b.startLink(w, r)
+ return err == nil
+}
+
+// startLink begins a link for the actual fresh local session and sends the
+// browser to the Home freshness check. It writes nothing unless it succeeds;
+// on failure it returns the status to show, or 0 for linkFailure's.
+func (b *Bridge) startLink(w http.ResponseWriter, r *http.Request) (int, error) {
for _, name := range []string{homeInitCookie, homeProofCookie} {
if _, _, ok := homeCookie(r, name); !ok {
- b.fail(w, r, http.StatusBadRequest)
- return
+ return http.StatusBadRequest, errIdentityRefused
}
}
local, _, err := b.localBinding(r)
// The reviewed local reauthentication continuation is wired separately.
// Stale local authentication cannot begin or reuse a linking initiation.
if err != nil {
- b.fail(w, r, http.StatusForbidden)
- return
+ return http.StatusForbidden, err
}
path := "/"
if b.returnPath != nil {
@@ -51,14 +73,32 @@ func (b *Bridge) LinkStart(w http.ResponseWriter, r *http.Request) {
}
secret, err := b.links.Start(r.Context(), local, path, b.now())
if err != nil {
- b.linkFailure(w, r, err)
- return
+ return 0, err
}
setHomeCookie(w, homeInitCookie, secret, 300)
setHomeCookie(w, homeProofCookie, "", -1)
http.Redirect(w, r, "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm", http.StatusSeeOther)
+ return 0, nil
}
+
+// connectedQuery marks the confirm page's GET after a successful confirm.
+// It shows "Accounts connected" only to a person whose link is stored, so
+// a crafted URL can show nothing that is not already true. return_to is
+// the page the link began from, revalidated before it becomes the page's
+// way back.
+const connectedQuery = "connected"
+
+type successReturnKey struct{}
+
+func connectedURL(path string) string {
+ return "/account/home/confirm?" + url.Values{connectedQuery: {"1"}, "return_to": {path}}.Encode()
+}
+
func (b *Bridge) ConfirmPage(w http.ResponseWriter, r *http.Request) {
+ if q, err := url.ParseQuery(r.URL.RawQuery); err == nil && q.Has(connectedQuery) {
+ b.connectedPage(w, r, q)
+ return
+ }
if !b.guard(w, r, http.MethodGet, "/account/home/confirm") {
return
}
@@ -103,7 +143,49 @@ func (b *Bridge) ConfirmPost(w http.ResponseWriter, r *http.Request) {
b.linkFailure(w, r, err)
return
}
- http.Redirect(w, r, pending.ReturnPath, http.StatusSeeOther)
+ // Say that it worked (Paul, 2026-10-24: landing back on the page with
+ // nothing changed left him unable to tell). A GET, so a reload repeats
+ // the page rather than the POST.
+ http.Redirect(w, r, connectedURL(pending.ReturnPath), http.StatusSeeOther)
+}
+
+// connectedPage is "Accounts connected", for the signed-in person whose
+// account now has a stored link.
+func (b *Bridge) connectedPage(w http.ResponseWriter, r *http.Request, q url.Values) {
+ w.Header().Set("Cache-Control", "no-store")
+ if r.Host != strings.TrimPrefix(b.origin, "https://") || r.URL.Path != "/account/home/confirm" {
+ b.fail(w, r, http.StatusNotFound)
+ return
+ }
+ if r.Method != http.MethodGet {
+ w.Header().Set("Allow", http.MethodGet)
+ b.fail(w, r, http.StatusMethodNotAllowed)
+ return
+ }
+ session, err := b.actualSession(r)
+ if err != nil || session == nil {
+ b.fail(w, r, http.StatusForbidden)
+ return
+ }
+ person, err := b.existingPerson(r, *session)
+ if err != nil {
+ b.fail(w, r, http.StatusForbidden)
+ return
+ }
+ linked, err := b.links.Linked(r.Context(), person.ID)
+ if err != nil {
+ b.fail(w, r, http.StatusServiceUnavailable)
+ return
+ }
+ if !linked {
+ b.fail(w, r, http.StatusForbidden)
+ return
+ }
+ back := "/"
+ if v, ok := q["return_to"]; ok && len(v) == 1 && handoff.SafePath(v[0]) {
+ back = v[0]
+ }
+ b.render(w, r.WithContext(context.WithValue(r.Context(), successReturnKey{}, back)), "success", person.Label, http.StatusOK)
}
func (b *Bridge) linkFailure(w http.ResponseWriter, r *http.Request, err error) {
status := http.StatusServiceUnavailable
diff --git a/connect/linked_test.go b/connect/linked_test.go
new file mode 100644
index 0000000..b545941
--- /dev/null
+++ b/connect/linked_test.go
@@ -0,0 +1,199 @@
+package connect
+
+import (
+ "bytes"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+ "time"
+)
+
+func (f *bridgeFixture) personID(t *testing.T, address string) int64 {
+ t.Helper()
+ var id int64
+ if err := f.db.QueryRow("SELECT id FROM people WHERE email=?", address).Scan(&id); err != nil {
+ t.Fatal(err)
+ }
+ return id
+}
+
+// routes wires NewRoutes over the fixture's bridge, as an app does, so the
+// navigation marker and the bridge share their hooks.
+func (f *bridgeFixture) routes(t *testing.T) *Routes {
+ t.Helper()
+ h, err := NewRoutes(f.b, RoutesConfig{Namespace: "oficina/docs", Origin: bridgeOrigin, Issuer: bridgeIssuer, SessionCookie: f.sessions.cookie, DEK: bytes.Repeat([]byte{41}, 32),
+ ReadSession: func(r *http.Request) (*Session, error) {
+ s, ok := f.sessions.From(r)
+ if !ok {
+ return nil, nil
+ }
+ return &s, 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.Fatal(err)
+ }
+ return h
+}
+
+// TestLinkedIsTheStoredLinkNotTheSessionMethod is the menu bug: someone
+// linked who signs in with the app's own email link is still linked.
+func TestLinkedIsTheStoredLinkNotTheSessionMethod(t *testing.T) {
+ f := newBridgeFixture(t)
+ local := f.local(t, "one@example.com", "magiclink", time.Time{})
+ f.local(t, "two@example.com", "magiclink", time.Time{})
+ one, two := f.personID(t, "one@example.com"), f.personID(t, "two@example.com")
+ ctx := t.Context()
+ if linked, err := f.b.Linked(ctx, one); err != nil || linked {
+ t.Fatal("unlinked person reported linked", linked, err)
+ }
+ f.link(t, local, "opaque-one")
+ if linked, err := f.b.Linked(ctx, one); err != nil || !linked {
+ t.Fatal("linked person reported unlinked", linked, err)
+ }
+ if linked, err := f.b.Linked(ctx, two); err != nil || linked {
+ t.Fatal("another person's link leaked", linked, err)
+ }
+ if linked, err := f.b.Linked(ctx, 0); err != nil || linked {
+ t.Fatal("no person reported linked", linked, err)
+ }
+}
+
+// TestConfirmEndsOnAccountsConnected: after "Connect accounts" the person
+// sees that it worked, on a GET, and only once the link is stored.
+func TestConfirmEndsOnAccountsConnected(t *testing.T) {
+ f := newBridgeFixture(t)
+ local := f.local(t, "one@example.com", "magiclink", time.Time{})
+ proof, cookies := f.linkProof(t, local, "opaque-one")
+ w := httptest.NewRecorder()
+ f.b.ConfirmPost(w, bridgeRequest(http.MethodPost, "/account/home/confirm", append(cookies, proof)))
+ if w.Code != 303 || w.Header().Get("Location") != connectedURL("/") {
+ t.Fatalf("confirm=%d %q", w.Code, w.Header().Get("Location"))
+ }
+ var links int
+ if err := f.db.QueryRow("SELECT COUNT(*) FROM home_identity_links WHERE subject='opaque-one' AND person_id=?", f.personID(t, "one@example.com")).Scan(&links); err != nil || links != 1 {
+ t.Fatal("confirm did not store the link", links, err)
+ }
+ done := httptest.NewRecorder()
+ f.b.ConfirmPage(done, bridgeRequest(http.MethodGet, connectedURL("/"), []*http.Cookie{local}))
+ if done.Code != 200 || done.Body.String() != "success" {
+ t.Fatalf("connected page=%d %q", done.Code, done.Body.String())
+ }
+ other := f.local(t, "two@example.com", "magiclink", time.Time{})
+ crafted := httptest.NewRecorder()
+ f.b.ConfirmPage(crafted, bridgeRequest(http.MethodGet, connectedURL("/"), []*http.Cookie{other}))
+ if crafted.Code != 403 || crafted.Body.String() == "success" {
+ t.Fatalf("unlinked person shown success: %d", crafted.Code)
+ }
+ anonymous := httptest.NewRecorder()
+ f.b.ConfirmPage(anonymous, bridgeRequest(http.MethodGet, connectedURL("/"), nil))
+ if anonymous.Code != 403 {
+ t.Fatalf("signed-out success page=%d", anonymous.Code)
+ }
+}
+
+// unknownArrival runs an ordinary exchange for a subject with no link and
+// returns the navigation marker it left.
+func (f *bridgeFixture) unknownArrival(t *testing.T, subject string) *http.Cookie {
+ t.Helper()
+ pending, nonce := f.start(t, nil, "/d/existing")
+ inbox := f.callback(t, subject, nonce, time.Now().Add(-time.Hour))
+ w := httptest.NewRecorder()
+ f.b.Finish(w, bridgeRequest(http.MethodGet, "/auth/finish", []*http.Cookie{pending, inbox}))
+ if w.Code != 403 || w.Body.String() != "unknown" {
+ t.Fatalf("unknown arrival=%d %q", w.Code, w.Body.String())
+ }
+ bridgeNoSession(t, f.b, w)
+ return bridgeCookie(t, w, localLinkNavigationCookie)
+}
+
+// TestUnknownAssertionResumesLinkAfterLocalSignIn: an Oficina assertion
+// with no link, then a local sign-in, lands on the confirm step for a
+// fresh Oficina assertion, with no menu to hunt for. Every existing rule
+// still holds: fresh local auth, a fresh Home assertion bound to this
+// session, and an explicit confirm before anything is stored.
+func TestUnknownAssertionResumesLinkAfterLocalSignIn(t *testing.T) {
+ f := newBridgeFixture(t)
+ h := f.routes(t)
+ marker := f.unknownArrival(t, "opaque-one")
+ local := f.local(t, "one@example.com", "magiclink", time.Time{})
+ w := httptest.NewRecorder()
+ h.LocalComplete(w, bridgeRequest(http.MethodGet, LocalCompletePath, []*http.Cookie{marker, local}))
+ if w.Code != 303 || w.Header().Get("Location") != "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm" {
+ t.Fatalf("local sign-in did not resume the link: %d %q", w.Code, w.Header().Get("Location"))
+ }
+ init := bridgeCookie(t, w, homeInitCookie)
+ cookies := []*http.Cookie{local, init}
+ start := httptest.NewRecorder()
+ f.b.Start(start, bridgeRequest(http.MethodGet, w.Header().Get("Location"), cookies))
+ target, _ := url.Parse(start.Header().Get("Location"))
+ if start.Code != 303 || target.Query().Get("max_age") != "300" {
+ t.Fatal("resumed link did not ask Oficina for fresh authentication", start.Code)
+ }
+ pending := bridgeCookie(t, start, "__Host-oficina-assertion-pending")
+ inbox := f.callback(t, "opaque-one", target.Query().Get("nonce"), time.Now().Add(-30*time.Second))
+ finish := httptest.NewRecorder()
+ f.b.Finish(finish, bridgeRequest(http.MethodGet, "/auth/finish", append(cookies, pending, inbox)))
+ if finish.Code != 303 || finish.Header().Get("Location") != "/account/home/confirm" {
+ t.Fatalf("finish=%d %q", finish.Code, finish.Header().Get("Location"))
+ }
+ proof := bridgeCookie(t, finish, homeProofCookie)
+ var links int
+ if err := f.db.QueryRow("SELECT COUNT(*) FROM home_identity_links").Scan(&links); err != nil || links != 0 {
+ t.Fatal("linked before the explicit confirm", links, err)
+ }
+ page := httptest.NewRecorder()
+ f.b.ConfirmPage(page, bridgeRequest(http.MethodGet, "/account/home/confirm", []*http.Cookie{local, proof}))
+ if page.Code != 200 || page.Body.String() != "confirm" {
+ t.Fatalf("confirm page=%d %q", page.Code, page.Body.String())
+ }
+ post := httptest.NewRecorder()
+ f.b.ConfirmPost(post, bridgeRequest(http.MethodPost, "/account/home/confirm", []*http.Cookie{local, proof}))
+ if post.Code != 303 {
+ t.Fatalf("confirm=%d", post.Code)
+ }
+ if id, err := f.b.Resolve(t.Context(), "opaque-one"); err != nil || id.ID != f.personID(t, "one@example.com") {
+ t.Fatal("resumed link not stored", id, err)
+ }
+}
+
+// TestUnknownMarkerExpiresToTheMenuPath: a remembered arrival older than
+// the marker's lifetime is ignored, and the person lands as from any sign
+// in, with the menu item still on offer. A stale local sign-in never
+// resumes, and the menu's own marker still goes to the Connect page.
+func TestUnknownMarkerExpiresToTheMenuPath(t *testing.T) {
+ f := newBridgeFixture(t)
+ h := f.routes(t)
+ marker := f.unknownArrival(t, "opaque-one")
+ local := f.local(t, "one@example.com", "magiclink", time.Time{})
+ later := time.Now().Add(time.Duration(localLinkNavigationLifetime+1) * time.Second)
+ h.navigation.now = func() time.Time { return later }
+ w := httptest.NewRecorder()
+ h.LocalComplete(w, bridgeRequest(http.MethodGet, LocalCompletePath, []*http.Cookie{marker, local}))
+ if w.Code != 303 || w.Header().Get("Location") != "/" {
+ t.Fatalf("expired marker still resumed: %d %q", w.Code, w.Header().Get("Location"))
+ }
+ for _, c := range w.Result().Cookies() {
+ if c.Name == homeInitCookie && c.MaxAge > 0 {
+ t.Fatal("expired marker began a link")
+ }
+ }
+ h.navigation.now = time.Now
+ stale := f.local(t, "one@example.com", "keymail", time.Now().Add(-10*time.Minute))
+ w = httptest.NewRecorder()
+ h.LocalComplete(w, bridgeRequest(http.MethodGet, LocalCompletePath, []*http.Cookie{f.unknownArrival(t, "opaque-one"), stale}))
+ if w.Header().Get("Location") != "/" {
+ t.Fatalf("stale local sign-in resumed: %q", w.Header().Get("Location"))
+ }
+ begin := httptest.NewRecorder()
+ h.navigation.Begin(begin, bridgeRequest(http.MethodGet, "/account/home", nil))
+ w = httptest.NewRecorder()
+ h.LocalComplete(w, bridgeRequest(http.MethodGet, LocalCompletePath, []*http.Cookie{bridgeCookie(t, begin, localLinkNavigationCookie), local}))
+ if w.Header().Get("Location") != "/account/home" {
+ t.Fatalf("menu marker changed: %q", w.Header().Get("Location"))
+ }
+}
diff --git a/connect/linkstore/store.go b/connect/linkstore/store.go
index 544c1ff..e0422ca 100644
--- a/connect/linkstore/store.go
+++ b/connect/linkstore/store.go
@@ -203,6 +203,25 @@ func (s *Store) Resolve(ctx context.Context, issuer, subject string) (int64, str
return id, address, nil
}
+// Linked reports whether the person has a stored link to an identity at
+// this issuer, whichever way the current session signed in. It is one
+// lookup on the UNIQUE (issuer, person_id) index, cheap enough for every
+// page that draws the account menu.
+func (s *Store) Linked(ctx context.Context, person int64) (bool, error) {
+ if person <= 0 {
+ return false, nil
+ }
+ var one int
+ err := s.db.QueryRowContext(ctx, "SELECT 1 FROM home_identity_links WHERE issuer = ? AND person_id = ?", s.issuer, person).Scan(&one)
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ if err != nil {
+ return false, ErrStorage
+ }
+ return true, nil
+}
+
func safePath(v string) string {
if handoff.SafePath(v) {
return v
diff --git a/connect/navigation.go b/connect/navigation.go
index c3adc89..bae5b39 100644
--- a/connect/navigation.go
+++ b/connect/navigation.go
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/base64"
"encoding/json"
+ "errors"
"math"
"net/http"
"net/url"
@@ -33,8 +34,22 @@ type localLinkNavigation struct {
fail func(http.ResponseWriter, *http.Request, int)
origin, host string
now func() time.Time
+ // resume begins the link for the actual fresh local session and
+ // redirects to the Home freshness check, or reports false having
+ // written nothing (Bridge.resumeLink).
+ resume func(http.ResponseWriter, *http.Request) bool
}
+// The marker's two actions. linkStart is the account menu's: after local
+// sign-in, show the Connect page. linkResume is remembered when an Oficina
+// assertion arrived that this app has no link for: after local sign-in,
+// begin the link at once, so the person lands on the confirm step rather
+// than hunting for the menu item.
+const (
+ linkStart = "link-start"
+ linkResume = "link-resume"
+)
+
func newLocalLinkNavigation(sealer handoff.Sealer, c RoutesConfig) *localLinkNavigation {
u, err := url.Parse(c.Origin)
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || sealer == nil || c.ReadSession == nil {
@@ -82,27 +97,54 @@ func (n *localLinkNavigation) Begin(w http.ResponseWriter, r *http.Request) {
}
localNavigationCookie(w, homeInitCookie, "", -1)
localNavigationCookie(w, homeProofCookie, "", -1)
- now := n.now().Unix()
- if now <= 0 || now > math.MaxInt64-localLinkNavigationLifetime {
+ encoded, err := n.seal(linkStart)
+ if errors.Is(err, errNavigationClock) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
- payload, _ := json.Marshal(localLinkMarker{Version: 1, Action: "link-start", Issued: now, Expires: now + localLinkNavigationLifetime})
- sealed, err := n.sealer.Seal(n.purpose(), payload)
if err != nil {
n.fail(w, r, http.StatusServiceUnavailable)
return
}
+ localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime))
+ http.Redirect(w, r, "/signin/local", http.StatusSeeOther)
+}
+
+var (
+ errNavigationClock = errors.New("home connect: navigation clock unusable")
+ errNavigationSeal = errors.New("home connect: navigation marker unavailable")
+)
+
+// seal returns the encoded marker for action.
+func (n *localLinkNavigation) seal(action string) (string, error) {
+ now := n.now().Unix()
+ if now <= 0 || now > math.MaxInt64-localLinkNavigationLifetime {
+ return "", errNavigationClock
+ }
+ payload, _ := json.Marshal(localLinkMarker{Version: 1, Action: action, Issued: now, Expires: now + localLinkNavigationLifetime})
+ sealed, err := n.sealer.Seal(n.purpose(), payload)
+ if err != nil {
+ return "", errNavigationSeal
+ }
encoded := base64.RawURLEncoding.EncodeToString(sealed)
if len(encoded) > localLinkNavigationLimit {
- n.fail(w, r, http.StatusServiceUnavailable)
- return
+ return "", errNavigationSeal
}
- localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime))
- http.Redirect(w, r, "/signin/local", http.StatusSeeOther)
+ return encoded, nil
}
-func (n *localLinkNavigation) marker(r *http.Request, now int64) bool {
+// rememberUnknown records, in the same sealed short-lived marker, that an
+// Oficina assertion arrived with no link here. It carries no identity: the
+// link is still bound to a fresh Home assertion and an explicit confirm, as
+// from the menu. Failing to seal costs only the shortcut.
+func (n *localLinkNavigation) rememberUnknown(w http.ResponseWriter) {
+ if encoded, err := n.seal(linkResume); err == nil {
+ localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime))
+ }
+}
+
+// marker returns the action of the one valid, unexpired marker, or "".
+func (n *localLinkNavigation) marker(r *http.Request, now int64) string {
value := ""
count := 0
for _, c := range r.Cookies() {
@@ -112,32 +154,39 @@ func (n *localLinkNavigation) marker(r *http.Request, now int64) bool {
}
}
if count != 1 || value == "" || len(value) > localLinkNavigationLimit {
- return false
+ return ""
}
sealed, err := base64.RawURLEncoding.Strict().DecodeString(value)
if err != nil || base64.RawURLEncoding.EncodeToString(sealed) != value {
- return false
+ return ""
}
payload, err := n.sealer.Open(n.purpose(), sealed)
if err != nil || len(payload) > localLinkNavigationLimit {
- return false
+ return ""
}
var marker localLinkMarker
if json.Unmarshal(payload, &marker) != nil {
- return false
+ return ""
}
// Only this helper writes the payload. Exact re-encoding excludes duplicate
// and unknown fields, alternate numbers, and any trailing JSON value.
canonical, _ := json.Marshal(marker)
if !bytes.Equal(payload, canonical) {
- return false
+ return ""
+ }
+ if marker.Version == 1 && (marker.Action == linkStart || marker.Action == linkResume) && marker.Issued > 0 && marker.Issued <= now && now < marker.Expires && marker.Expires > marker.Issued && marker.Expires-marker.Issued <= localLinkNavigationLifetime {
+ return marker.Action
}
- return marker.Version == 1 && marker.Action == "link-start" && marker.Issued > 0 && marker.Issued <= now && now < marker.Expires && marker.Expires > marker.Issued && marker.Expires-marker.Issued <= localLinkNavigationLifetime
+ return ""
}
// Complete reads the newly presented session after local verification. It
-// cannot initiate or confirm linking, and never treats a Home mint as local
-// proof. A copied marker can at most repeat navigation to the same page.
+// never confirms a link, and never treats a Home mint as local proof. With
+// a remembered unknown assertion it begins one, exactly as the Connect
+// button would, which is bound to this fresh session and still needs a
+// fresh Home assertion and an explicit same-origin confirm. A copied marker
+// can at most repeat that navigation. An expired marker is ignored: the
+// person lands as from any sign-in, with the menu item still on offer.
func (n *localLinkNavigation) Complete(w http.ResponseWriter, r *http.Request) {
localNavigationCookie(w, localLinkNavigationCookie, "", -1)
if !n.guard(w, r, localLinkCompletePath) {
@@ -145,7 +194,7 @@ func (n *localLinkNavigation) Complete(w http.ResponseWriter, r *http.Request) {
}
now := n.now()
target := n.landingPath
- if n.marker(r, now.Unix()) {
+ if action := n.marker(r, now.Unix()); action != "" {
count := 0
for _, c := range r.Cookies() {
if c.Name == n.sessionCookie {
@@ -155,6 +204,9 @@ func (n *localLinkNavigation) Complete(w http.ResponseWriter, r *http.Request) {
if count == 1 {
if session, err := n.readSession(r); err == nil && session != nil {
if _, fresh := FreshLocal(*session, now); fresh {
+ if action == linkResume && n.resume != nil && n.resume(w, r) {
+ return
+ }
target = "/account/home"
}
}
diff --git a/connect/navigation_test.go b/connect/navigation_test.go
index 5f9d42f..f87707d 100644
--- a/connect/navigation_test.go
+++ b/connect/navigation_test.go
@@ -82,12 +82,12 @@ func TestNavigationPurposeIsolationAndFixedAction(t *testing.T) {
r.AddCookie(c)
}
}
- if !n.marker(r, n.now().Unix()) {
+ if n.marker(r, n.now().Unix()) != linkStart {
t.Fatal("valid marker refused")
}
other := *n
other.namespace = "oficina/calls"
- if other.marker(r, n.now().Unix()) {
+ if other.marker(r, n.now().Unix()) != "" {
t.Fatal("cross-app marker accepted")
}
for _, target := range []string{navigationOrigin + "/account/home?return_to=https://bad.test", "https://bad.test/account/home"} {
diff --git a/connect/routes.go b/connect/routes.go
index 038b21f..a3ef883 100644
--- a/connect/routes.go
+++ b/connect/routes.go
@@ -44,7 +44,9 @@ func NewRoutes(b *Bridge, c RoutesConfig) (*Routes, error) {
return nil, errors.New("home connect: invalid navigation")
}
n.now = b.now
+ n.resume = b.resumeLink
b.returnPath = n.returnPath
+ b.rememberUnknown = n.rememberUnknown
return &Routes{bridge: b, navigation: n, cfg: c}, nil
}
diff --git a/connect/view.go b/connect/view.go
index c7736a2..d4bcfb8 100644
--- a/connect/view.go
+++ b/connect/view.go
@@ -1,14 +1,27 @@
package connect
import (
- "amadan.net/oficina/estilo.git/homeconnect"
"embed"
+ "net/http"
+
+ "amadan.net/oficina/estilo.git/homeconnect"
+ "amadan.net/oficina/home/handoff"
)
func Templates() embed.FS { return homeconnect.Templates() }
type PageData = homeconnect.PageData
+// 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 "/".
+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
+ }
+ return p
+}
+
func Page(state, label string, translate ...func(string) string) PageData {
t := func(k string) string { return English[k] }
if len(translate) > 0 && translate[0] != nil {
@@ -50,10 +63,17 @@ func Page(state, label string, translate ...func(string) string) PageData {
// never names the hub: the account is "your Oficina account" (Paul,
// 2026-09-23), worded as Docs' approved docs.home.* strings are. The
// signed-out state speaks the door's words (estilo chrome.English).
+//
+// The confirm step must not read as the start page reloaded (Paul,
+// 2026-10-24): it has its own question for a title and says the Oficina
+// half is already done. The assertion carries an opaque subject and no
+// address, so the Oficina account cannot be named, only the local one.
+// The unknown state says what signing in will do, because it now does it:
+// local sign-in resumes the link (localLinkNavigation.Complete).
var English = map[string]string{
"signedout_title": "You’re signed out", "signedout_body": "You can sign in again with your Oficina account.", "signedout_action": "Sign in",
"start_title": "Connect your Oficina account", "start_body": "Use your Oficina account to sign in to this account. Your content and sharing settings stay as they are.", "start_action": "Connect", "cancel_action": "Back",
- "confirm_title": "Confirm account connection", "confirm_body": "Connect the account below to the Oficina account you just signed in to.", "confirm_action": "Connect accounts",
- "unknown_title": "Oficina account not connected", "unknown_body": "Sign in to your existing account, then connect your Oficina account from the account menu.", "local_action": "Sign in to your existing account",
+ "confirm_title": "Connect these two accounts?", "confirm_body": "Your Oficina account is confirmed. Connect it to the account below, and you can sign in to that account with Oficina from now on.", "confirm_action": "Connect accounts",
+ "unknown_title": "Oficina account not connected", "unknown_body": "Sign in to your existing account once to connect it to your Oficina account.", "local_action": "Sign in to your existing account",
"failed_title": "Could not connect accounts", "failed_body": "Return to the app and start again.", "success_title": "Accounts connected", "success_body": "You can now use your Oficina account to sign in to this account.", "documents_action": "Back to the app", "menu_action": "Connect your Oficina account",
}