oficina / docs Public

Docs: Connect your Oficina account only when it isn't, and finishes itself

The account menu offers Connect only when no Oficina link is stored. A
sign-in through id with an unlinked identity now leads, after one local
sign-in, straight to the confirm step; the card's buttons sit in one
row, the confirm step names the Docs account, and a stored link shows
Accounts connected. Reviewed by GPT-6-Astra via Codex (#79).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from fix/connect-item-when-linked into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c6602122601d2dcbfcc24ba9b625dda1852d22bc parent ce29703
17 files changed, +433 −49
  • internal/docs/app.go +1 −0
  • internal/docs/errors_test.go +2 −2
  • internal/docs/handlers.go +3 −0
  • internal/docs/home_connect_linked_test.go +188 −0
  • internal/docs/home_exchange.go +6 −0
  • internal/docs/home_exchange_test.go +3 −3
  • internal/docs/home_link_handlers.go +87 −7
  • internal/docs/home_local_navigation.go +70 −18
  • internal/docs/home_render.go +9 −0
  • internal/docs/home_router_integration_test.go +12 −6
  • internal/docs/home_routes.go +15 −2
  • internal/docs/linkstore/store.go +19 −0
  • internal/docs/render.go +7 −3
  • internal/docs/team_access_test.go +1 −1
  • internal/docs/team_router_test.go +1 −1
  • internal/docs/team_stream_test.go +3 −3
  • internal/docs/views/home_link.html +6 −3

CI passed — run details

diff --git a/internal/docs/app.go b/internal/docs/app.go
index 27f33b5..6af0fbc 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -511,6 +511,7 @@ func New(cfg Config) (*App, error) {
return nil, err
}
h.homeEnabled = true
+ h.homeLinked = home.bridge.links.Linked
h.peek = func(r *http.Request) (string, bool) {
s, ok := home.bridge.sessions.From(r)
if !ok || s.Subject == "" {
diff --git a/internal/docs/errors_test.go b/internal/docs/errors_test.go
index 5131c2c..cbc62b5 100644
--- a/internal/docs/errors_test.go
+++ b/internal/docs/errors_test.go
@@ -248,8 +248,8 @@ func TestEveryPlainTextErrorIsClassified(t *testing.T) {
"handlers.go:handlers.updatesPost": {7, "the update log, posted by the editor"},
"handlers.go:parseSince": {1, "the update log's cursor"},
"home_local_navigation.go:localLinkNavigation.guard": {1, "405 for a non-GET method"},
- "home_local_navigation.go:localLinkNavigation.Begin": {2, "Home link start, sealing failure (R3: moves with home/connect)"},
- "home_render.go:renderer.homeLink": {1, "the page itself could not render"},
+ "home_local_navigation.go:localLinkNavigation.Begin": {1, "Home link start, sealing failure (R3: moves with home/connect)"},
+ "home_render.go:renderer.homeLinkBack": {1, "the page itself could not render"},
"home_routes.go:homeCSRF": {1, "unknown Host: not a page anyone navigates to"},
"identity.go:identityResolver.middleware": {1, "shared guard in front of page and fetch routes (R3)"},
"identity.go:refuseIdentity": {1, "non-GET refusal; a GET redirects to sign-in"},
diff --git a/internal/docs/handlers.go b/internal/docs/handlers.go
index 8a703d2..e956f4d 100644
--- a/internal/docs/handlers.go
+++ b/internal/docs/handlers.go
@@ -2,6 +2,7 @@ package docs
import (
"amadan.net/oficina/home/roster"
+ "context"
"errors"
"html/template"
"io"
@@ -39,6 +40,8 @@ const maxUpdateBytes = 1 << 20
type handlers struct {
requireCurrent func(http.Handler) http.Handler
homeEnabled bool
+ // homeLinked reports a local person's stored Home link (linkstore.Linked).
+ homeLinked func(context.Context, int64) (bool, error)
render *renderer
logger *slog.Logger
diff --git a/internal/docs/home_connect_linked_test.go b/internal/docs/home_connect_linked_test.go
new file mode 100644
index 0000000..ddd78dc
--- /dev/null
+++ b/internal/docs/home_connect_linked_test.go
@@ -0,0 +1,188 @@
+package docs
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+const connectItem = `href="/account/home"`
+
+func (b *routerBrowser) menuOffersConnect(t *testing.T) bool {
+ t.Helper()
+ rec := b.do("GET", "/", "")
+ if rec.Code != 200 {
+ t.Fatalf("list=%d", rec.Code)
+ }
+ return strings.Contains(rec.Body.String(), connectItem)
+}
+
+// confirmLink posts "Connect accounts" and follows it to the success page.
+func (b *routerBrowser) confirmLink(t *testing.T, back string) {
+ t.Helper()
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL(back))
+ done := b.do("GET", connectedURL(back), "")
+ body := done.Body.String()
+ if done.Code != 200 || !strings.Contains(body, rastrillo.T(httptest.NewRequest("GET", "/", nil), "docs.home.success_title")) || !strings.Contains(body, `href="`+back+`"`) {
+ t.Fatalf("no Accounts connected page leading back to %q: %d\n%s", back, done.Code, body)
+ }
+}
+
+// TestHomeMenuOffersConnectOnlyWithoutAStoredLink is the bug Paul hit as
+// paul@tito.io: signed in with the Docs email link to an account already
+// linked to an Oficina identity, the menu still offered to connect it.
+func TestHomeMenuOffersConnectOnlyWithoutAStoredLink(t *testing.T) {
+ f := newRouterHomeFixture(t)
+ b := f.browser()
+ b.localSignin(t, "alice@example.com")
+ if !b.menuOffersConnect(t) {
+ t.Fatal("signed in locally and not linked: no Connect item")
+ }
+ b.linkProof(t, "opaque-alice", "alice@example.com")
+ b.confirmLink(t, "/")
+ if routerRows(t, f, "docs_identity_links") != 1 {
+ t.Fatal("Connect accounts did not store the link")
+ }
+ if b.menuOffersConnect(t) {
+ t.Fatal("same session, just linked: Connect item still offered")
+ }
+ again := f.browser()
+ again.localSignin(t, "alice@example.com")
+ if again.menuOffersConnect(t) {
+ t.Fatal("signed in locally and linked: Connect item offered")
+ }
+ home := f.browser()
+ nonce := home.start(t, "/auth/start?return_to=%2F", "")
+ routerRedirect(t, home.exchange(t, nonce, "opaque-alice", time.Now().Add(-time.Hour)), "/")
+ if home.menuOffersConnect(t) {
+ t.Fatal("signed in through Home: Connect item offered")
+ }
+ other := f.browser()
+ other.localSignin(t, "bob@example.com")
+ if !other.menuOffersConnect(t) {
+ t.Fatal("another unlinked person lost the Connect item")
+ }
+}
+
+// TestHomeUnknownArrivalResumesLinkAfterLocalSignIn: an Oficina assertion
+// with no link, then signing in to Docs, lands on the confirm step for a
+// fresh Oficina assertion. Nothing to find in the menu, and every rule of
+// the menu path still holds.
+func TestHomeUnknownArrivalResumesLinkAfterLocalSignIn(t *testing.T) {
+ f := newRouterHomeFixture(t)
+ // A brand-new address has no Docs account to connect yet: it lands on
+ // the Connect page, which creates nothing until the person goes on.
+ fresh := f.browser()
+ if rec := fresh.exchange(t, fresh.start(t, "/auth/start?return_to=%2F", ""), "opaque-bob", time.Now().Add(-time.Hour)); rec.Code != 403 {
+ t.Fatal("unknown Bob", rec.Code)
+ }
+ bobPath, bobForm := confirmForm(fresh.localLink(t, "bob@example.com"))
+ routerRedirect(t, fresh.do("POST", bobPath, bobForm), localLinkCompletePath)
+ routerRedirect(t, fresh.do("GET", localLinkCompletePath, ""), "/account/home")
+ if _, err := f.app.store.EnsurePerson(t.Context(), "alice@example.com"); err != nil {
+ t.Fatal(err)
+ }
+ b := f.browser()
+ nonce := b.start(t, "/auth/start?return_to=%2F", "")
+ unknown := b.exchange(t, nonce, "opaque-alice", time.Now().Add(-time.Hour))
+ body := unknown.Body.String()
+ if unknown.Code != 403 || !strings.Contains(body, `href="/signin/local"`) || !strings.Contains(body, "docs.home.unknown_body") || Catalog["docs.home.unknown_body"] != "Sign in to your Docs account once to connect it to your Oficina account." {
+ t.Fatalf("unknown page does not say what signing in will do: %d\n%s", unknown.Code, body)
+ }
+ if b.cookies[localLinkNavigationCookie] == nil || b.cookies[f.sessions.CookieName()] != nil {
+ t.Fatal("unknown arrival not remembered, or it minted a session")
+ }
+ verifyPath, verifyForm := confirmForm(b.localLink(t, "alice@example.com"))
+ routerRedirect(t, b.do("POST", verifyPath, verifyForm), localLinkCompletePath)
+ next := routerRedirect(t, b.do("GET", localLinkCompletePath, ""), "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm")
+ if b.cookies[homeInitCookie] == nil {
+ t.Fatal("resume did not begin the link")
+ }
+ nonce = b.start(t, next, "300")
+ routerRedirect(t, b.exchange(t, nonce, "opaque-alice", time.Now().Add(-time.Minute)), "/account/home/confirm")
+ if routerRows(t, f, "docs_identity_links") != 0 {
+ t.Fatal("linked before the explicit confirm")
+ }
+ confirm := b.do("GET", "/account/home/confirm", "")
+ if confirm.Code != 200 || !strings.Contains(confirm.Body.String(), "alice@example.com") || !strings.Contains(confirm.Body.String(), "docs.home.confirm_title") || Catalog["docs.home.confirm_title"] == Catalog["docs.home.start_title"] {
+ t.Fatalf("confirm step not shown: %d", confirm.Code)
+ }
+ b.confirmLink(t, "/")
+ if routerRows(t, f, "docs_identity_links") != 1 || b.menuOffersConnect(t) {
+ t.Fatal("resumed link not stored, or the menu still offers it")
+ }
+}
+
+// TestLocalNavigationUnknownMarkerExpiresToTheMenuPath: a remembered
+// arrival older than the marker is ignored, and the person lands as from
+// any sign-in, with the menu item still on offer.
+func TestLocalNavigationUnknownMarkerExpiresToTheMenuPath(t *testing.T) {
+ app, n := navigationFixture(t)
+ resumed := 0
+ n.resume = func(w http.ResponseWriter, r *http.Request) bool {
+ resumed++
+ http.Redirect(w, r, "/resumed", http.StatusSeeOther)
+ return true
+ }
+ now := time.Now().Truncate(time.Second)
+ n.now = func() time.Time { return now }
+ remember := httptest.NewRecorder()
+ n.rememberUnknown(remember)
+ var marker *http.Cookie
+ for _, c := range remember.Result().Cookies() {
+ if c.Name == localLinkNavigationCookie && c.MaxAge > 0 {
+ marker = c
+ }
+ }
+ if marker == nil {
+ t.Fatal("unknown arrival not remembered")
+ }
+ session := navigationSession(t, n, sessions.Session{Subject: "local@example.com", Method: "magiclink"})
+ request := func() *http.Request {
+ r := navigationRequest(localLinkCompletePath)
+ r.AddCookie(marker)
+ r.AddCookie(session)
+ return r
+ }
+ assertNavigation(t, n, request(), "/resumed")
+ later := now.Add(time.Duration(localLinkNavigationLifetime) * time.Second)
+ n.now = func() time.Time { return later }
+ // The local sign-in is fresh at the later time too, so only the
+ // marker's own expiry can decide.
+ if _, err := app.db.Writer().Exec(`UPDATE sessions SET created_at=? WHERE token_hash=?`, later.Add(-time.Minute).UTC().Format(time.RFC3339), sessions.HashToken(session.Value)); err != nil {
+ t.Fatal(err)
+ }
+ n.resume = func(w http.ResponseWriter, r *http.Request) bool {
+ resumed++
+ http.Redirect(w, r, "/resumed", http.StatusSeeOther)
+ return true
+ }
+ menu := navigationMarker(t, n)
+ r := navigationRequest(localLinkCompletePath)
+ r.AddCookie(menu)
+ r.AddCookie(session)
+ assertNavigation(t, n, r, "/account/home")
+ assertNavigation(t, n, request(), "/")
+ if resumed != 1 {
+ t.Fatal("expired marker resumed", resumed)
+ }
+}
+
+// TestHomeLinkActionsShareOneRow: Connect and Back to Docs sat stacked
+// flush; they share the door's form-foot row, primary first.
+func TestHomeLinkActionsShareOneRow(t *testing.T) {
+ f := newRouterHomeFixture(t)
+ b := f.browser()
+ b.localSignin(t, "alice@example.com")
+ html := b.do("GET", "/account/home", "").Body.String()
+ row := strings.Index(html, "<div rst-form-foot>")
+ primary, ghost := strings.Index(html, `rst-btn="primary"`), strings.LastIndex(html, `rst-btn="ghost"`)
+ if row < 0 || primary < row || ghost < primary || !strings.Contains(html[row:], "</div>") || row+strings.Index(html[row:], "</div>") < ghost {
+ t.Fatalf("actions are not one row with primary first:\n%s", html)
+ }
+}
diff --git a/internal/docs/home_exchange.go b/internal/docs/home_exchange.go
index a420fad..5bd4f71 100644
--- a/internal/docs/home_exchange.go
+++ b/internal/docs/home_exchange.go
@@ -35,6 +35,9 @@ type homeBridge struct {
now func() time.Time
// returnPath reads separate sealed navigation state; it carries no identity.
returnPath func(*http.Request) string
+ // rememberUnknown leaves the sealed navigation marker that resumes
+ // linking after the person signs in locally (newHomeRoutes).
+ rememberUnknown func(http.ResponseWriter)
}
type homeFinishKey struct{}
type homeFinishResult struct {
@@ -227,6 +230,9 @@ func (b *homeBridge) complete(w http.ResponseWriter, r *http.Request, claims ass
} else {
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/internal/docs/home_exchange_test.go b/internal/docs/home_exchange_test.go
index 72dd595..f60d295 100644
--- a/internal/docs/home_exchange_test.go
+++ b/internal/docs/home_exchange_test.go
@@ -168,8 +168,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)
}
@@ -429,7 +429,7 @@ 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)
}
})
diff --git a/internal/docs/home_link_handlers.go b/internal/docs/home_link_handlers.go
index 1a80321..3eef44c 100644
--- a/internal/docs/home_link_handlers.go
+++ b/internal/docs/home_link_handlers.go
@@ -3,6 +3,8 @@ package docs
import (
"errors"
"net/http"
+ "net/url"
+ "strings"
"amadan.net/oficina/home/handoff"
"github.com/carlosframework/docs/internal/docs/linkstore"
@@ -30,18 +32,37 @@ func (b *homeBridge) 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 *homeBridge) 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 *homeBridge) 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 +72,30 @@ func (b *homeBridge) 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"
+
+func connectedURL(path string) string {
+ return "/account/home/confirm?" + url.Values{connectedQuery: {"1"}, "return_to": {path}}.Encode()
+}
+
func (b *homeBridge) 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 +140,50 @@ func (b *homeBridge) 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 list with
+ // the menu unchanged 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. Its way back is the page the link began
+// from.
+func (b *homeBridge) 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.homeLinkBack(w, r, "success", person.Email, back, http.StatusOK)
}
func (b *homeBridge) linkFailure(w http.ResponseWriter, r *http.Request, err error) {
status := http.StatusServiceUnavailable
diff --git a/internal/docs/home_local_navigation.go b/internal/docs/home_local_navigation.go
index 4dde2d0..f797b5b 100644
--- a/internal/docs/home_local_navigation.go
+++ b/internal/docs/home_local_navigation.go
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/base64"
"encoding/json"
+ "errors"
"math"
"net/http"
"net/url"
@@ -31,8 +32,27 @@ type localLinkNavigation struct {
sess *sessions.Sessions
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 (homeBridge.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 Docs 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"
+)
+
+var (
+ errNavigationClock = errors.New("docs: navigation clock unusable")
+ errNavigationSeal = errors.New("docs: navigation marker unavailable")
+)
+
// newLocalLinkNavigation takes the already validated suite origin and the same
// session store used by local auth. The marker conveys navigation only.
func newLocalLinkNavigation(sealer handoff.Sealer, sess *sessions.Sessions, origin string) *localLinkNavigation {
@@ -73,27 +93,49 @@ func (n *localLinkNavigation) Begin(w http.ResponseWriter, r *http.Request) {
}
localNavigationCookie(w, "__Host-docs-home-init", "", -1)
localNavigationCookie(w, "__Host-docs-home-proof", "", -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 {
http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
return
}
+ localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime))
+ http.Redirect(w, r, "/signin/local", http.StatusSeeOther)
+}
+
+// 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 {
- http.Error(w, rastrillo.T(r, "docs.error.generic"), 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() {
@@ -103,32 +145,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) {
@@ -141,7 +190,7 @@ func (n *localLinkNavigation) Complete(w http.ResponseWriter, r *http.Request) {
// was: LinkStart reads it too, so connecting accounts right after
// signing in still returns to the same document.
target := n.returnPath(r)
- 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.sess.CookieName() {
@@ -151,6 +200,9 @@ func (n *localLinkNavigation) Complete(w http.ResponseWriter, r *http.Request) {
if count == 1 {
if session, ok := n.sess.From(r); ok {
if _, fresh := freshLocalAuthentication(session, now); fresh {
+ if action == linkResume && n.resume != nil && n.resume(w, r) {
+ return
+ }
target = "/account/home"
}
}
diff --git a/internal/docs/home_render.go b/internal/docs/home_render.go
index 8499631..ea89c52 100644
--- a/internal/docs/home_render.go
+++ b/internal/docs/home_render.go
@@ -19,6 +19,12 @@ type homeLinkPage struct {
}
func (rd *renderer) homeLink(w http.ResponseWriter, r *http.Request, state, address string, status int) {
+ rd.homeLinkBack(w, r, state, address, "", status)
+}
+
+// homeLinkBack is homeLink with the success page's way back: the page the
+// link began from, already validated, or "" for the list.
+func (rd *renderer) homeLinkBack(w http.ResponseWriter, r *http.Request, state, address, back string, status int) {
page := homeLinkPage{Address: address}
key := "docs.home."
switch state {
@@ -38,6 +44,9 @@ func (rd *renderer) homeLink(w http.ResponseWriter, r *http.Request, state, addr
page.SignedOut, page.Title = &notice, notice.Page()
case "success":
page.Action = "/"
+ if back != "" {
+ page.Action = back
+ }
page.ActionLabel = rastrillo.T(r, key+"documents_action")
default:
state = "failed"
diff --git a/internal/docs/home_router_integration_test.go b/internal/docs/home_router_integration_test.go
index bc649e4..a86421c 100644
--- a/internal/docs/home_router_integration_test.go
+++ b/internal/docs/home_router_integration_test.go
@@ -269,15 +269,21 @@ func TestHomeRouterExistingAccountRoundTripPreservesOwnedAndSharedContent(t *tes
if routerRows(t, f, "people") != 2 || routerRows(t, f, "documents") != 3 || routerRows(t, f, "docs_identity_links") != 0 || b.cookies[f.sessions.CookieName()] != nil {
t.Fatal("unknown Home subject created an account or session")
}
- // The local link lands on the document this browser was sent to sign
- // in from, not the list (spec §9.4).
- b.localSignin(t, "alice@example.com", resource)
+ // The unknown arrival is remembered, so signing in locally resumes the
+ // link straight away: Home's freshness check, then the confirm step.
+ // The document this browser was sent to sign in from (spec §9.4) is
+ // where "Accounts connected" leads back to.
+ b.localSignin(t, "alice@example.com", "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm")
localCookie := b.cookies[f.sessions.CookieName()].Value
- b.linkProof(t, "opaque-alice", "alice@example.com")
+ nonce = b.start(t, "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm", "300")
+ routerRedirect(t, b.exchange(t, nonce, "opaque-alice", time.Now().Add(-time.Minute)), "/account/home/confirm")
+ if confirm := b.do("GET", "/account/home/confirm", ""); confirm.Code != 200 || !strings.Contains(confirm.Body.String(), "alice@example.com") {
+ t.Fatal("confirmation did not identify local account", confirm.Code)
+ }
if b.cookies[f.sessions.CookieName()].Value != localCookie || routerRows(t, f, "docs_identity_links") != 0 {
t.Fatal("proof replaced local session or linked before confirmation")
}
- routerRedirect(t, b.do("POST", "/account/home/confirm", ""), resource)
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL(resource))
if b.cookies[f.sessions.CookieName()].Value != localCookie || routerRows(t, f, "docs_identity_links") != 1 {
t.Fatal("confirmation failed local session retention")
}
@@ -371,7 +377,7 @@ func TestHomeRouterCSRFGuardsBothLinkMutations(t *testing.T) {
t.Fatal("actual router permitted foreign confirmation or consumed valid proof", rec.Code)
}
}
- routerRedirect(t, b.do("POST", "/account/home/confirm", ""), "/")
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
if routerRows(t, f, "docs_identity_links") != 1 {
t.Fatal("valid same-origin confirmation failed after refusal")
}
diff --git a/internal/docs/home_routes.go b/internal/docs/home_routes.go
index 92f8686..0fe4dac 100644
--- a/internal/docs/home_routes.go
+++ b/internal/docs/home_routes.go
@@ -38,6 +38,8 @@ func newHomeRoutes(settings *homeSettings, origin string, db *sql.DB, auth *raut
return nil, errHomeConfig
}
b.returnPath = navigation.returnPath
+ b.rememberUnknown = navigation.rememberUnknown
+ navigation.resume = b.resumeLink
return &homeRoutes{bridge: b, navigation: navigation, handlers: h, formPolicy: homeFormPolicy(settings.issuer), issuer: settings.issuer}, nil
}
@@ -165,11 +167,22 @@ func (h *homeRoutes) mountAccount(r chi.Router) {
})
}
+// homeLinkLabel is the account menu's "Connect your Oficina account", or ""
+// when there is nothing to connect: offered only to a local person with no
+// stored link, whichever way this session signed in. Before, it was offered
+// to every session that had not come from a Home assertion, so a linked
+// person who used the email link still saw it (Paul, as paul@tito.io).
+// A team instance already resolved the link with the identity; otherwise
+// it is one indexed lookup per menu render. Not knowing offers nothing.
func (h *handlers) homeLinkLabel(r *http.Request) string {
- if !h.homeEnabled {
+ if !h.homeEnabled || h.homeLinked == nil {
return ""
}
- if id, ok := currentIdentity(r); ok && id.Session.Method == homeAssertionMethod {
+ id, ok := currentIdentity(r)
+ if !ok || id.Session.Method == homeAssertionMethod || id.HomeSubject != "" {
+ return ""
+ }
+ if linked, err := h.homeLinked(r.Context(), id.Actor.PersonID); err != nil || linked {
return ""
}
return rastrillo.T(r, "docs.home.menu_action")
diff --git a/internal/docs/linkstore/store.go b/internal/docs/linkstore/store.go
index 3797989..2f469ec 100644
--- a/internal/docs/linkstore/store.go
+++ b/internal/docs/linkstore/store.go
@@ -190,6 +190,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 docs_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/internal/docs/render.go b/internal/docs/render.go
index 0488cb7..d784b3e 100644
--- a/internal/docs/render.go
+++ b/internal/docs/render.go
@@ -35,15 +35,19 @@ var Catalog = rastrillo.Catalog{
// docs.home.* — connecting a Docs account to the suite account. The
// hub is never named ("Home" leaves user copy, spec §10 and §13 Q3):
// the account is "your Oficina account", and the verb stays Connect.
+ // The confirm step asks its own question so it cannot read as the
+ // start page reloaded (Paul, 2026-10-24); the assertion's subject is
+ // opaque, so only the Docs address can be named. The unknown state
+ // says what signing in now does: it resumes the link.
"docs.home.start_title": "Connect your Oficina account",
"docs.home.start_body": "Use your Oficina account to sign in to this Docs account. Your documents and sharing settings stay as they are.",
"docs.home.start_action": "Connect",
"docs.home.cancel_action": "Back to Docs",
- "docs.home.confirm_title": "Confirm account connection",
- "docs.home.confirm_body": "Connect the Docs account below to the Oficina account you just signed in to.",
+ "docs.home.confirm_title": "Connect these two accounts?",
+ "docs.home.confirm_body": "Your Oficina account is confirmed. Connect it to the Docs account below, and you can sign in to Docs with Oficina from now on.",
"docs.home.confirm_action": "Connect accounts",
"docs.home.unknown_title": "Oficina account not connected",
- "docs.home.unknown_body": "Sign in to your existing Docs account, then connect your Oficina account from the account menu.",
+ "docs.home.unknown_body": "Sign in to your Docs account once to connect it to your Oficina account.",
"docs.home.local_action": "Sign in to Docs",
"docs.home.failed_title": "Could not connect accounts",
"docs.home.failed_body": "Return to Docs and start again.",
diff --git a/internal/docs/team_access_test.go b/internal/docs/team_access_test.go
index 3782bb2..3504e61 100644
--- a/internal/docs/team_access_test.go
+++ b/internal/docs/team_access_test.go
@@ -402,7 +402,7 @@ func TestTeamPermissionContentionCannotRecoverIntoPermanentDenial(t *testing.T)
b := f.browser()
b.localSignin(t, "alice@example.com")
b.linkProof(t, teamSubject('a'), "alice@example.com")
- routerRedirect(t, b.do("POST", "/account/home/confirm", ""), "/")
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
session, ok := f.sessions.From(b.request("GET", "/", ""))
if !ok {
t.Fatal("session")
diff --git a/internal/docs/team_router_test.go b/internal/docs/team_router_test.go
index a2db9a0..9b031f7 100644
--- a/internal/docs/team_router_test.go
+++ b/internal/docs/team_router_test.go
@@ -176,7 +176,7 @@ func TestTeamRouterLocalLinkMembershipRemovalAndIndependentGrant(t *testing.T) {
}
cookie := b.cookies[f.sessions.CookieName()].Value
b.linkProof(t, teamSubject('a'), "alice@example.com")
- routerRedirect(t, b.do("POST", "/account/home/confirm", ""), "/")
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
if b.cookies[f.sessions.CookieName()].Value != cookie {
t.Fatal("link rotated local session")
}
diff --git a/internal/docs/team_stream_test.go b/internal/docs/team_stream_test.go
index 86d678a..aeeb6a8 100644
--- a/internal/docs/team_stream_test.go
+++ b/internal/docs/team_stream_test.go
@@ -49,7 +49,7 @@ func TestTeamStreamActualSessionWriterWaitCannotExtendOriginalLease(t *testing.T
b := f.browser()
b.localSignin(t, "alice@example.com")
b.linkProof(t, teamSubject('a'), "alice@example.com")
- routerRedirect(t, b.do("POST", "/account/home/confirm", ""), "/")
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
if r := b.do("GET", "/d/"+f.own.Sqid, ""); r.Code != 200 {
t.Fatal("initial membership unavailable", r.Code)
}
@@ -98,7 +98,7 @@ func TestTeamStreamHealthyPublicationClosesOriginalLeaseAndReconnects(t *testing
b := f.browser()
b.localSignin(t, "alice@example.com")
b.linkProof(t, teamSubject('a'), "alice@example.com")
- routerRedirect(t, b.do("POST", "/account/home/confirm", ""), "/")
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
streamDurations(t, f.app, 30*time.Millisecond, 5*time.Second)
srv := httptest.NewServer(f.app.Handler())
defer srv.Close()
@@ -128,7 +128,7 @@ func TestTeamStreamGuestGrantAndActualSessionRevocation(t *testing.T) {
owner := f.browser()
owner.localSignin(t, "bob@example.com")
owner.linkProof(t, teamSubject('b'), "bob@example.com")
- routerRedirect(t, owner.do("POST", "/account/home/confirm", ""), "/")
+ routerRedirect(t, owner.do("POST", "/account/home/confirm", ""), connectedURL("/"))
streamDurations(t, f.app, 30*time.Millisecond, 5*time.Second)
srv := httptest.NewServer(f.app.Handler())
defer srv.Close()
diff --git a/internal/docs/views/home_link.html b/internal/docs/views/home_link.html
index 17ca43d..886b80c 100644
--- a/internal/docs/views/home_link.html
+++ b/internal/docs/views/home_link.html
@@ -5,9 +5,12 @@
<header rst-page-header><div rst-page-header-titles><h1>{{.Title}}</h1></div></header>
<div rst-box>
<p>{{.Body}}</p>{{if .Address}}<p style="overflow-wrap: anywhere"><strong>{{.Address}}</strong></p>{{end}}
- {{if .PostAction}}<form method="post" action="{{.Action}}"><button rst-btn="primary" type="submit">{{.ActionLabel}}</button></form>
- {{else}}<a rst-btn="primary" href="{{.Action}}">{{.ActionLabel}}</a>{{end}}
- {{if .CancelLabel}}<a rst-btn="ghost" href="/">{{.CancelLabel}}</a>{{end}}
+ {{- /* One row with the door's gap, primary first: rastrillo's form-foot,
+ as estilo's homeconnect lays out the same screens for the other apps. */}}
+ <div rst-form-foot>
+ {{- if .PostAction}}<form method="post" action="{{.Action}}"><button rst-btn="primary" type="submit">{{.ActionLabel}}</button></form>
+ {{- else}}<a rst-btn="primary" href="{{.Action}}">{{.ActionLabel}}</a>{{end}}
+ {{- if .CancelLabel}}<a rst-btn="ghost" href="/">{{.CancelLabel}}</a>{{end}}</div>
</div>
{{- end}}
{{end}}