oficina / sheets Public

Oficina ID native slice A in Sheets: NativeExchange, members choose, 7-day native sessions

The Sheets server half of the native Oficina ID path (spec §7, §8),
modelled on Docs 9de84e4: home/connect + handoff repinned to e03a01a;
Admit through the team roster; MintNativeSession; the choose page and
the native exchange mounted; every Home-session check uses IsHomeDerived;
native sessions refused after 7 days in teamIdentify. A native session
can never approve the older browser sign-in (nativeApprover), so it
cannot mint itself a fresh-clock copy past the 7-day limit.

Reviewed by Claude Fable (b942939 APPROVE AFTER FIXES; d37b269 APPROVE).
Hub CI passed at d37b269. Not deployed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 2bee0974c71dcd9b2d026ba5bfbd2810848fa454 parent 60a0f3d
16 files changed, +536 −23
  • go.mod +2 −2
  • go.sum +4 −0
  • internal/sheets/chrome.go +1 −1
  • internal/sheets/errors_test.go +1 −0
  • internal/sheets/home.go +45 −8
  • internal/sheets/home_native_approval_test.go +80 −0
  • internal/sheets/home_native_test.go +276 −0
  • internal/sheets/home_routes.go +10 −0
  • internal/sheets/members.go +2 −1
  • internal/sheets/native.go +23 −1
  • internal/sheets/page.go +2 −2
  • internal/sheets/team_access.go +11 −3
  • internal/sheets/team_access_test.go +14 −2
  • internal/sheets/team_fixture_test.go +32 −0
  • internal/sheets/team_home_only.go +22 −2
  • internal/sheets/templates/home_link.html +11 −1

CI passed — run details

CI log
amadan: .amadan/timeout: this job's budget is 15m0s (this runner allows up to 30m0s)
=== vet ===
CGO_ENABLED=0 go vet ./...
go: downloading amadan.net/oficina/home/connect v0.0.0-20261114110939-e03a01a1881c
go: downloading amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c
CGO_ENABLED=0 go vet -tags browser ./internal/sheets/
=== fmt ===
=== build ===
CGO_ENABLED=0 go build ./...
=== migrations ===
go tool rastrillo migration check
rastrillo migration check: models and migrations agree
=== go-test ===
CGO_ENABLED=0 go test -count=1 ./...
?   	amadan.net/oficina/sheets/cmd/sheets	[no test files]
?   	amadan.net/oficina/sheets/cmd/sheets-contract	[no test files]
ok  	amadan.net/oficina/sheets/internal/guardstest	0.162s
ok  	amadan.net/oficina/sheets/internal/sheets	14.971s
ok  	amadan.net/oficina/sheets/internal/sheets/calc	0.013s
ok  	amadan.net/oficina/sheets/internal/sheets/format	0.003s
?   	amadan.net/oficina/sheets/internal/sheets/keymailtest	[no test files]
ok  	amadan.net/oficina/sheets/internal/sheets/live	0.053s
ok  	amadan.net/oficina/sheets/internal/sheets/seal	0.002s
ok  	amadan.net/oficina/sheets/internal/sheets/sealtest	0.002s
ok  	amadan.net/oficina/sheets/internal/sheets/store	6.046s
ok  	amadan.net/oficina/sheets/internal/sheets/teamstate	0.114s
ok  	amadan.net/oficina/sheets/internal/sheets/xlsx	4.536s
?   	amadan.net/oficina/sheets/tools/gencorpus	[no test files]
=== race ===
go test -race -count=1 ./internal/sheets/store/... ./internal/sheets/live/...
ok  	amadan.net/oficina/sheets/internal/sheets/store	71.643s
ok  	amadan.net/oficina/sheets/internal/sheets/live	1.065s
diff --git a/go.mod b/go.mod
index 1f5eaab..86ce079 100644
--- a/go.mod
+++ b/go.mod
@@ -5,9 +5,9 @@ go 1.25.0
require (
amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000
amadan.net/oficina/estilo.git v0.0.0-20261101213957-7a19588e736f
- amadan.net/oficina/home/connect v0.0.0-20261110233753-14c83d71b992
+ amadan.net/oficina/home/connect v0.0.0-20261114110939-e03a01a1881c
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816
- amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d
+ amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c
amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2
amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2
amadan.net/rastrillo/rastrillo v0.27.1
diff --git a/go.sum b/go.sum
index 621ec9b..5268b81 100644
--- a/go.sum
+++ b/go.sum
@@ -4,10 +4,14 @@ amadan.net/oficina/estilo.git v0.0.0-20261101213957-7a19588e736f h1:SxWyFCGQwmxh
amadan.net/oficina/estilo.git v0.0.0-20261101213957-7a19588e736f/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
amadan.net/oficina/home/connect v0.0.0-20261110233753-14c83d71b992 h1:pyAvFStnIR6D/MSfMYpRQG+Lete8eYCF10nBdjtBbhA=
amadan.net/oficina/home/connect v0.0.0-20261110233753-14c83d71b992/go.mod h1:7tsJ//7X4o5QkD068WoUGVDxj/e3ygZ2adF+PHhvBxE=
+amadan.net/oficina/home/connect v0.0.0-20261114110939-e03a01a1881c h1:BffZtW5vfqVCTcVlbNbFhpTTrcBE1eKCo8IZZL0RXEs=
+amadan.net/oficina/home/connect v0.0.0-20261114110939-e03a01a1881c/go.mod h1:xbo+sWUk6NL0sbjWw/2BNlI/4ex899zprJRUp+cr/Xo=
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0MxNxN9ZWVc3lul1QHkNjNUCO56kXpe/Fw3I=
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0=
amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d h1:8RTZkLQnyxvH2g0RMovhN/m2LN9D8qb+kBfqdBeqq+s=
amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
+amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c h1:KxjjyIlEu3hY1G6l26IrI2PRcogOscpTeydRgNzimbA=
+amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 h1:yKUTS0nOiVw7ktHpTin0bCcUDLFjmMjpW6CsHIZzZKk=
amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg=
amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 h1:0PQiRUkC+9cbTHE67Y4/SmW1sPH1NNWNwTceNFyMjTY=
diff --git a/internal/sheets/chrome.go b/internal/sheets/chrome.go
index 50a4519..cbab0d0 100644
--- a/internal/sheets/chrome.go
+++ b/internal/sheets/chrome.go
@@ -221,7 +221,7 @@ func (a *App) offersHomeLink(r *http.Request, address string) bool {
return false
}
s, ok := a.homeSessions.From(r)
- if !ok || s.Method == connect.HomeMethod {
+ if !ok || connect.IsHomeDerived(s.Method) {
return false
}
id, err := a.localMemberID(r.Context(), address)
diff --git a/internal/sheets/errors_test.go b/internal/sheets/errors_test.go
index 24dcd8c..122b26f 100644
--- a/internal/sheets/errors_test.go
+++ b/internal/sheets/errors_test.go
@@ -172,6 +172,7 @@ func TestEveryPlainTextErrorIsClassified(t *testing.T) {
"home.go:App.homeLocalComplete": {2, "Home link completion refusals (R3: moves with home/connect)"},
"home.go:App.rejectDisabledHome": {1, "shared session guard for pages and fetches (R3)"},
"jobpages.go:App.renderJobFragment": {2, "the job page's polled fragment, not a page"},
+ "native.go:App.nativeApprover": {1, "refuses a native session at rastrillo/native's device approval; no browser holds one"},
"team_access.go:App.teamRequire": {2, "team mode's session guard, homeRequire's twin: a page GET redirects to /signin"},
}
got := httpErrorSites(t)
diff --git a/internal/sheets/home.go b/internal/sheets/home.go
index ef2d605..c3c676a 100644
--- a/internal/sheets/home.go
+++ b/internal/sheets/home.go
@@ -60,8 +60,25 @@ func (a *App) ConfigureHome(raw *connect.Credentials) error {
a.renderSignedOut(w, r, status)
return
}
- p := connect.PageFor(r, state, label, func(k string) string { return homeCopy[k] })
- a.render(w, r, "home_link", titled(p.Title), status, p)
+ view := homeLinkView{PageData: connect.PageFor(r, state, label, func(k string) string { return homeCopy[k] })}
+ if state == "choose" {
+ // A roster member with no account here yet (Home spec
+ // 2026-11-14-oficina-id-native.md §8): connect an existing
+ // email account, or continue with Oficina ID as someone new.
+ // connect's Page knows no "choose", so the page is built here.
+ if form, ok := connect.ChoiceFor(r); ok {
+ view.Title, view.Body = homeCopy["choose_title"], homeCopy["choose_body"]
+ view.Choice = &homeChoice{Action: form.Action, Token: form.Token,
+ ConnectLabel: homeCopy["choose_connect_action"], NewLabel: homeCopy["choose_new_action"]}
+ } else {
+ // No live choice to offer: "failed", with the way on to
+ // connecting an account, as Docs' home_render.go does.
+ view.PageData = connect.PageFor(r, "failed", label, func(k string) string { return homeCopy[k] })
+ view.Action, view.ActionLabel = "/account/home", homeCopy["menu_action"]
+ status = http.StatusForbidden
+ }
+ }
+ a.render(w, r, "home_link", titled(view.Title), status, view)
}
cfg := connect.Config{DB: d, Origin: a.origin, Issuer: settings.Issuer, ConsumerID: settings.ConsumerID, Namespace: homeNamespace, Keys: settings.Keys, DEK: settings.DEK, SessionCookie: sess.CookieName(), ReadSession: read,
MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error {
@@ -76,11 +93,19 @@ func (a *App) ConfigureHome(raw *connect.Credentials) error {
}
label, err := a.homePerson(ctx, d, id)
return connect.Person{ID: id, Label: label}, err
- }, Render: render}
+ }, Render: render,
+ // The native app's session (connect.NativeExchange, Home spec
+ // 2026-11-14-oficina-id-native.md §7): the same store and cookie
+ // name, minted without a cookie and handed back in the answer. The
+ // store's own 30-day lifetime outlasts connect's 7-day limit.
+ MintNativeSession: func(_ context.Context, s connect.Session) (string, error) {
+ return sess.Mint(sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime})
+ }}
if a.teamSettings != nil {
- // Team mode only: with both hooks nil connect is exactly what it
- // was (team_home_only.go).
- cfg.HomeOnly, cfg.Unlinked = a.teamHomeOnly(d), a.teamUnlinked(d)
+ // Team mode only: with all three hooks nil connect is exactly what
+ // it was, and refuses a Home subject with no link as "unknown"
+ // (team_home_only.go).
+ cfg.Admit, cfg.HomeOnly, cfg.Unlinked = a.teamAdmit, a.teamHomeOnly(d), a.teamUnlinked(d)
}
bridge, err := connect.New(cfg)
if err != nil {
@@ -146,7 +171,7 @@ func (a *App) localMemberID(ctx context.Context, address string) (int64, error)
func (a *App) homeRequire(next http.Handler) http.Handler {
return a.homeSessions.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, ok := a.homeSessions.From(r)
- if ok && session.Method == connect.HomeMethod {
+ if ok && connect.IsHomeDerived(session.Method) {
if _, err := a.home.ResolveSession(r); errors.Is(err, linkstore.ErrStorage) {
w.Header().Set("Cache-Control", "no-store")
http.Error(w, "Sign-in unavailable.", http.StatusServiceUnavailable)
@@ -208,7 +233,7 @@ func (a *App) renderHomeOAuth(w http.ResponseWriter, r *http.Request, destinatio
func (a *App) rejectDisabledHome(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if s, ok := sessions.Current(r); ok && s.Method == connect.HomeMethod {
+ if s, ok := sessions.Current(r); ok && connect.IsHomeDerived(s.Method) {
w.Header().Set("Cache-Control", "no-store")
http.Error(w, "Sign in first.", http.StatusForbidden)
return
@@ -217,6 +242,18 @@ func (a *App) rejectDisabledHome(next http.Handler) http.Handler {
})
}
+// homeLinkView is the account-connection page: connect's page, or the
+// member choice's two buttons when Choice is set. Both buttons POST
+// connect.ChoosePath with the form token, inside the app-wide CSRF check.
+type homeLinkView struct {
+ connect.PageData
+ Choice *homeChoice
+}
+
+type homeChoice struct {
+ Action, Token, ConnectLabel, NewLabel string
+}
+
// homeOAuthView is the Keymail continuation page's data: Home's page (for
// its meta refresh) and the door card around the way on.
type homeOAuthView struct {
diff --git a/internal/sheets/home_native_approval_test.go b/internal/sheets/home_native_approval_test.go
new file mode 100644
index 0000000..28c753d
--- /dev/null
+++ b/internal/sheets/home_native_approval_test.go
@@ -0,0 +1,80 @@
+package sheets
+
+import (
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// The native exchange with rastrillo/native's browser approval mounted, as
+// main mounts both: POST /native/oficina-id still reaches connect ahead of
+// the /native/* wildcard, and a native session can never approve another
+// device. The approval mints a copy with a fresh creation time, so a
+// native session approving itself would outlive its seven days (Fable,
+// sheets b942939).
+func TestNativeSessionCannotApproveTheBrowserSignIn(t *testing.T) {
+ f := newHomeFixture(t)
+ if err := f.app.ConfigureNative(); err != nil {
+ t.Fatal(err)
+ }
+ f.local(t, signedInAddress)
+ f.link(t, "pr_linked")
+ local := f.jar[f.app.homeSessions.CookieName()]
+ f.jar = map[string]*http.Cookie{}
+
+ rec, answer := f.nativeExchange(t, "pr_linked", nil)
+ if rec.Code != http.StatusOK || answer.State != "ok" {
+ t.Fatalf("Oficina ID exchange with native routes mounted = %d %s", rec.Code, rec.Body.String())
+ }
+ native := &http.Cookie{Name: answer.Name, Value: answer.Value}
+
+ // rastrillo/native's browser approval, at this instance's origin.
+ post := func(path string, body any, cookie *http.Cookie) *httptest.ResponseRecorder {
+ var reader *strings.Reader
+ r := httptest.NewRequest("POST", testOrigin+path, nil)
+ if body != nil {
+ data, _ := json.Marshal(body)
+ reader = strings.NewReader(string(data))
+ r = httptest.NewRequest("POST", testOrigin+path, reader)
+ r.Header.Set("Content-Type", "application/json")
+ }
+ r.Header.Set("Origin", testOrigin)
+ if cookie != nil {
+ r.AddCookie(cookie)
+ }
+ w := httptest.NewRecorder()
+ f.app.Router().ServeHTTP(w, r)
+ return w
+ }
+ request := func() (string, string) {
+ verifier := randomProof(t)
+ sum := sha256.Sum256([]byte(verifier))
+ rec := post("/native/request", map[string]string{"challenge": base64.RawURLEncoding.EncodeToString(sum[:])}, nil)
+ var out struct{ ID string }
+ if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &out) != nil || out.ID == "" {
+ t.Fatalf("POST /native/request = %d %s", rec.Code, rec.Body.String())
+ }
+ return out.ID, verifier
+ }
+
+ id, verifier := request()
+ if approve := post("/native/authorize?id="+id, nil, native); approve.Code == http.StatusOK || strings.Contains(approve.Body.String(), "is signed in") {
+ t.Fatalf("a native session approved a device: %d %s", approve.Code, approve.Body.String())
+ }
+ if ex := post("/native/exchange", map[string]string{"id": id, "verifier": verifier}, nil); ex.Code == http.StatusOK {
+ t.Fatalf("exchange after a native session's approval = %d %s", ex.Code, ex.Body.String())
+ }
+
+ // A browser's own session still approves, as before.
+ id, verifier = request()
+ if approve := post("/native/authorize?id="+id, nil, local); approve.Code != http.StatusOK {
+ t.Fatalf("a browser session's approval = %d %s", approve.Code, approve.Body.String())
+ }
+ if ex := post("/native/exchange", map[string]string{"id": id, "verifier": verifier}, nil); ex.Code != http.StatusOK {
+ t.Fatalf("exchange after a browser approval = %d %s", ex.Code, ex.Body.String())
+ }
+}
diff --git a/internal/sheets/home_native_test.go b/internal/sheets/home_native_test.go
new file mode 100644
index 0000000..4ce3831
--- /dev/null
+++ b/internal/sheets/home_native_test.go
@@ -0,0 +1,276 @@
+package sheets
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json"
+ "html"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+// The native app's Oficina ID sign-in (Home spec
+// 2026-11-14-oficina-id-native.md §7, §8): POST /native/oficina-id trades
+// an assertion Home made for the app's verifier for a Sheets session, with
+// no browser and no cookie. Driven through the router, as main mounts it.
+
+type nativeAnswer struct {
+ State string `json:"state"`
+ Name string `json:"name"`
+ Value string `json:"value"`
+ ExpiresAt int64 `json:"expires_at"`
+}
+
+// nativeExchange posts what the native app posts: JSON, no Origin, no
+// Sec-Fetch-Site, no cookies.
+func (f *homeFixture) nativeExchange(t *testing.T, subject string, extra map[string]string) (*httptest.ResponseRecorder, nativeAnswer) {
+ t.Helper()
+ raw := make([]byte, 32)
+ if _, err := rand.Read(raw); err != nil {
+ t.Fatal(err)
+ }
+ verifier := base64.RawURLEncoding.EncodeToString(raw)
+ challenge, _ := handoff.NativeChallenge(verifier)
+ nonce, _ := handoff.NativeNonce(challenge)
+ now := time.Now().Unix()
+ id, _ := assertion.RandomID()
+ token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: homeTestIssuer, Audience: testOrigin, Subject: subject, KeyID: "key", ID: id, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 120, AuthTime: now - 60})
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := map[string]string{"assertion": token, "verifier": verifier}
+ for k, v := range extra {
+ body[k] = v
+ }
+ encoded, _ := json.Marshal(body)
+ r := httptest.NewRequest("POST", testOrigin+connect.NativeExchangePath, bytes.NewReader(encoded))
+ r.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ f.app.Router().ServeHTTP(rec, r)
+ if len(rec.Result().Cookies()) != 0 {
+ t.Fatal("the native exchange set a cookie")
+ }
+ var answer nativeAnswer
+ if err := json.Unmarshal(rec.Body.Bytes(), &answer); err != nil {
+ t.Fatalf("answer %d %q: %v", rec.Code, rec.Body.String(), err)
+ }
+ return rec, answer
+}
+
+// nativeList is the native app's sheet list (SheetsWorkspace's GET
+// /sheets as JSON), with the minted session.
+func (f *homeFixture) nativeList(t *testing.T, a nativeAnswer) *httptest.ResponseRecorder {
+ t.Helper()
+ r := httptest.NewRequest("GET", testOrigin+"/sheets", nil)
+ r.Header.Set("Accept", "application/json")
+ r.AddCookie(&http.Cookie{Name: a.Name, Value: a.Value})
+ rec := httptest.NewRecorder()
+ f.app.Router().ServeHTTP(rec, r)
+ return rec
+}
+
+// age backdates the minted session's creation, as seven days would.
+func (f *homeFixture) age(t *testing.T, a nativeAnswer, by time.Duration) {
+ t.Helper()
+ old := time.Now().Add(-by).UTC().Format(time.RFC3339)
+ if err := f.app.db.Exec("UPDATE sessions SET created_at=? WHERE token_hash=?", old, sessions.HashToken(a.Value)).Error; err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestNativeOficinaIDOpensALinkedAccount(t *testing.T) {
+ f := newHomeFixture(t)
+ member := f.local(t, signedInAddress)
+ if _, err := f.app.createSheet(nil, "Linked workbook", member); err != nil {
+ t.Fatal(err)
+ }
+ f.link(t, "pr_linked")
+ f.jar = map[string]*http.Cookie{}
+
+ rec, answer := f.nativeExchange(t, "pr_linked", nil)
+ if rec.Code != http.StatusOK || answer.State != "ok" || answer.Name != f.app.homeSessions.CookieName() || answer.Value == "" {
+ t.Fatalf("exchange = %d %s", rec.Code, rec.Body.String())
+ }
+ r := httptest.NewRequest("GET", testOrigin+"/", nil)
+ r.AddCookie(&http.Cookie{Name: answer.Name, Value: answer.Value})
+ if s, ok := f.app.homeSessions.From(r); !ok || s.Method != connect.NativeMethod || s.Subject != "pr_linked" {
+ t.Fatalf("minted %+v", s)
+ }
+ if list := f.nativeList(t, answer); list.Code != http.StatusOK || !strings.Contains(list.Body.String(), "Linked workbook") {
+ t.Fatalf("native list = %d %s", list.Code, list.Body.String())
+ }
+
+ // Outside team mode a subject with no account here is unknown, and the
+ // same whatever it sends.
+ for _, extra := range []map[string]string{nil, {"choice": "new"}} {
+ if rec, _ := f.nativeExchange(t, "pr_stranger", extra); rec.Code != http.StatusForbidden || rec.Body.String() != `{"state":"unknown"}` {
+ t.Fatalf("stranger = %d %s", rec.Code, rec.Body.String())
+ }
+ }
+}
+
+// Seven days after it was minted, however recently used, the native
+// session opens nothing: the app re-mints long before (§7).
+func TestNativeSessionEndsAfterSevenDays(t *testing.T) {
+ f := newHomeFixture(t)
+ f.local(t, signedInAddress)
+ f.link(t, "pr_linked")
+ _, answer := f.nativeExchange(t, "pr_linked", nil)
+ if f.nativeList(t, answer).Code != http.StatusOK {
+ t.Fatal("a fresh native session was refused")
+ }
+ f.age(t, answer, connect.NativeLifetime+time.Hour)
+ if r := f.nativeList(t, answer); r.Code == http.StatusOK {
+ t.Fatalf("a native session older than seven days opened the list: %s", r.Body.String())
+ }
+}
+
+// The exchange is not a browser route: a browser's Origin, or a form, is
+// refused by the exchange itself, not waved through the CSRF check.
+func TestNativeExchangeRefusesABrowser(t *testing.T) {
+ f := newHomeFixture(t)
+ serve := func(r *http.Request) *httptest.ResponseRecorder {
+ rec := httptest.NewRecorder()
+ f.app.Router().ServeHTTP(rec, r)
+ return rec
+ }
+ r := httptest.NewRequest("POST", testOrigin+connect.NativeExchangePath, strings.NewReader(`{"assertion":"x","verifier":"y"}`))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Origin", testOrigin)
+ if rec := serve(r); rec.Code != http.StatusBadRequest || rec.Body.String() != `{"state":"invalid"}` {
+ t.Fatalf("browser POST = %d %s", rec.Code, rec.Body.String())
+ }
+ r = httptest.NewRequest("POST", testOrigin+connect.NativeExchangePath, strings.NewReader(url.Values{"assertion": {"x"}}.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if rec := serve(r); rec.Code != http.StatusBadRequest {
+ t.Fatalf("form POST = %d", rec.Code)
+ }
+}
+
+// In team mode a roster member with no member here chooses: 409 and
+// nothing made, then choice "new" makes the Home-only member and signs in.
+// Non-members get the identical unknown; an undecidable roster is a 503.
+func TestTeamNativeMemberChooses(t *testing.T) {
+ f := newTeamFixture(t)
+ teamSheet(t, f, "Team plan")
+ b := teamSubject('b')
+ f.dir.Set(b, "member")
+ rec, answer := f.nativeExchange(t, b, nil)
+ if rec.Code != http.StatusConflict || answer.State != "choose" {
+ t.Fatalf("member with no member here = %d %s", rec.Code, rec.Body.String())
+ }
+ var addressless int64
+ f.app.db.Model(&Member{}).Where("address IS NULL").Count(&addressless)
+ if addressless != 0 {
+ t.Fatal("409 made a member")
+ }
+ rec, answer = f.nativeExchange(t, b, map[string]string{"choice": "new"})
+ if rec.Code != http.StatusOK || answer.State != "ok" {
+ t.Fatalf("choice new = %d %s", rec.Code, rec.Body.String())
+ }
+ if list := f.nativeList(t, answer); list.Code != http.StatusOK || !strings.Contains(list.Body.String(), "Team plan") {
+ t.Fatalf("native list = %d %s", list.Code, list.Body.String())
+ }
+ // Now linked: no choice asked again.
+ if rec, again := f.nativeExchange(t, b, nil); rec.Code != http.StatusOK || again.State != "ok" {
+ t.Fatalf("second exchange = %d %s", rec.Code, rec.Body.String())
+ }
+ for _, extra := range []map[string]string{nil, {"choice": "new"}} {
+ if rec, _ := f.nativeExchange(t, teamSubject('z'), extra); rec.Code != http.StatusForbidden || rec.Body.String() != `{"state":"unknown"}` {
+ t.Fatalf("non-member = %d %s", rec.Code, rec.Body.String())
+ }
+ }
+ f.dir.Set(teamSubject('c'), "member")
+ f.expired(t)
+ if rec, _ := f.nativeExchange(t, teamSubject('c'), map[string]string{"choice": "new"}); rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("undecidable roster = %d %s", rec.Code, rec.Body.String())
+ }
+}
+
+// Team mode resolves a session by its subject (teamIdentify), not through
+// ResolveSession, so it must refuse a native session past seven days too.
+func TestTeamNativeSessionEndsAfterSevenDays(t *testing.T) {
+ f := newTeamFixture(t)
+ b := teamSubject('b')
+ f.dir.Set(b, "member")
+ _, answer := f.nativeExchange(t, b, map[string]string{"choice": "new"})
+ if f.nativeList(t, answer).Code != http.StatusOK {
+ t.Fatal("a fresh native session was refused")
+ }
+ f.age(t, answer, connect.NativeLifetime+time.Hour)
+ if r := f.nativeList(t, answer); r.Code == http.StatusOK {
+ t.Fatalf("a native session older than seven days opened the list: %s", r.Body.String())
+ }
+}
+
+// The browser half of the member choice: "Connect my existing account"
+// resumes local sign-in and linking; "I'm new here" is refused while any
+// app session is present; a cross-origin POST is stopped.
+func TestTeamMemberChoicePage(t *testing.T) {
+ f := newTeamFixture(t)
+ a := teamSubject('a')
+ f.dir.Set(a, "member")
+ if fin := f.signInHomeChoosing(t, a); fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != connect.ChoosePath {
+ t.Fatalf("member sign-in = %d %q", fin.Code, fin.Header().Get("Location"))
+ }
+ page := f.get(t, connect.ChoosePath)
+ body := page.Body.String()
+ for _, want := range []string{homeCopy["choose_title"], "Connect my existing account", `value="connect"`, `value="new"`} {
+ if !strings.Contains(body, want) && !strings.Contains(body, strings.ReplaceAll(want, "’", "&rsquo;")) {
+ t.Fatalf("choose page lacks %q: %s", want, body)
+ }
+ }
+ if connected := f.choose(t, "connect"); connected.Code != http.StatusSeeOther || !strings.HasPrefix(connected.Header().Get("Location"), "/signin/local") {
+ t.Fatalf("connect = %d %q", connected.Code, connected.Header().Get("Location"))
+ }
+
+ // "I'm new here" with an app session present is refused.
+ if fin := f.signInHomeChoosing(t, a); fin.Header().Get("Location") != connect.ChoosePath {
+ t.Fatalf("member sign-in again = %q", fin.Header().Get("Location"))
+ }
+ f.local(t, "local@example.com")
+ if rec := f.choose(t, "new"); rec.Code != http.StatusForbidden {
+ t.Fatalf("I'm new here over a live app session = %d %q, want 403", rec.Code, rec.Header().Get("Location"))
+ }
+ var made int64
+ f.app.db.Model(&Member{}).Where("address IS NULL").Count(&made)
+ if made != 0 {
+ t.Fatalf("Home-only members = %d after a refused choice, want 0", made)
+ }
+
+ // A POST from another origin never reaches the choice, even carrying
+ // the page's real form token and the proof cookie.
+ f.jar = map[string]*http.Cookie{}
+ f.signInHomeChoosing(t, a)
+ token := regexp.MustCompile(`name="token" value="([^"]+)"`).FindStringSubmatch(f.get(t, connect.ChoosePath).Body.String())
+ if token == nil {
+ t.Fatal("no form token on the choose page")
+ }
+ r := httptest.NewRequest("POST", testOrigin+connect.ChoosePath, strings.NewReader(url.Values{"choice": {"new"}, "token": {html.UnescapeString(token[1])}}.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.Header.Set("Origin", "https://evil.example")
+ for _, c := range f.jar {
+ r.AddCookie(c)
+ }
+ rec := httptest.NewRecorder()
+ f.app.Router().ServeHTTP(rec, r)
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("cross-origin choose POST = %d", rec.Code)
+ }
+ var addressless int64
+ f.app.db.Model(&Member{}).Where("address IS NULL").Count(&addressless)
+ if addressless != 0 {
+ t.Fatalf("Home-only members = %d, want 0: no choice of new went through", addressless)
+ }
+}
diff --git a/internal/sheets/home_routes.go b/internal/sheets/home_routes.go
index ba99562..68e9c03 100644
--- a/internal/sheets/home_routes.go
+++ b/internal/sheets/home_routes.go
@@ -18,6 +18,16 @@ func (a *App) mountAuth(r chi.Router) {
r.Get("/account/home/confirm", a.home.ConfirmPage)
r.Post("/account/home/confirm", a.homeRoutes.ConfirmPost)
r.Get("/signed-out", a.homeRoutes.SignedOut)
+ // The member choice (team mode; connect answers 404 without the
+ // team hooks): no session yet, and the POST inside the app-wide
+ // CSRF check like any form (connect also demands this Origin).
+ r.Get(connect.ChoosePath, a.home.ChoosePage)
+ r.Post(connect.ChoosePath, a.home.ChoosePost)
+ // The native app's Oficina ID exchange (Home spec
+ // 2026-11-14-oficina-id-native.md §7). connect's Middleware lets
+ // this one path past the CSRF check: it refuses anything a browser
+ // sends.
+ r.Post(connect.NativeExchangePath, a.home.NativeExchange)
} else {
r.Get("/signin", a.handleSignin)
r.Get("/signed-out", a.handleSignedOut)
diff --git a/internal/sheets/members.go b/internal/sheets/members.go
index 71eb082..42248d9 100644
--- a/internal/sheets/members.go
+++ b/internal/sheets/members.go
@@ -5,6 +5,7 @@ import (
"net/http"
"strings"
+ "amadan.net/oficina/home/connect"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
@@ -100,7 +101,7 @@ func (a *App) actor(r *http.Request) (Member, bool) {
}
if a.home != nil {
s, ok := a.homeSessions.From(r)
- if ok && s.Method == "home-assertion" {
+ if ok && connect.IsHomeDerived(s.Method) {
p, err := a.home.ResolveSession(r)
if err != nil {
return Member{}, false
diff --git a/internal/sheets/native.go b/internal/sheets/native.go
index 1947650..6c76931 100644
--- a/internal/sheets/native.go
+++ b/internal/sheets/native.go
@@ -5,6 +5,7 @@ import (
"net/http"
"strings"
+ "amadan.net/oficina/home/connect"
nativeauth "amadan.net/rastrillo/native/server"
"amadan.net/rastrillo/rastrillo/sessions"
@@ -28,9 +29,30 @@ func (a *App) ConfigureNative() error {
if err != nil {
return err
}
- a.native = nativeauth.New(s, a.origin, "Sheets", a.requireSession)
+ a.native = nativeauth.New(s, a.origin, "Sheets", a.nativeApprover)
return nil
}
+
+// nativeApprover is the guard rastrillo/native's browser approval runs
+// before approving a device (/native/authorize) and again on the approved
+// cookie before minting its session (/native/exchange): the app's own
+// guard, but never for a native or native-web session. The exchange mints a
+// copy that keeps the method with a fresh creation time, and connect's
+// seven-day limit counts from that, so a native session approving another
+// would renew itself for ever (Fable, sheets b942939). A native session
+// signs in with Oficina ID again instead.
+func (a *App) nativeApprover(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if a.homeSessions != nil {
+ if s, ok := a.homeSessions.From(r); ok && (s.Method == connect.NativeMethod || s.Method == connect.NativeWebMethod) {
+ w.Header().Set("Cache-Control", "no-store")
+ http.Error(w, "Sign in first.", http.StatusForbidden)
+ return
+ }
+ }
+ a.requireSession(next).ServeHTTP(w, r)
+ })
+}
func wantsNative(r *http.Request) bool {
return strings.Contains(r.Header.Get("Accept"), "application/json")
}
diff --git a/internal/sheets/page.go b/internal/sheets/page.go
index 5ba79a2..2200d5e 100644
--- a/internal/sheets/page.go
+++ b/internal/sheets/page.go
@@ -67,7 +67,7 @@ func (a *App) identity(r *http.Request) (string, bool) {
if !ok {
return "", false
}
- if s.Method == connect.HomeMethod {
+ if connect.IsHomeDerived(s.Method) {
// In team mode this resolves a Home-only member too (connect's
// HomeOnly hook): signed in, with no address.
p, err := a.home.ResolveSession(r)
@@ -78,7 +78,7 @@ func (a *App) identity(r *http.Request) (string, bool) {
return "", false
}
id, ok := a.auth.SessionFrom(r)
- if !ok || string(id.Method) == connect.HomeMethod {
+ if !ok || connect.IsHomeDerived(string(id.Method)) {
return "", false
}
return id.Address, true
diff --git a/internal/sheets/team_access.go b/internal/sheets/team_access.go
index 9307061..9400f9e 100644
--- a/internal/sheets/team_access.go
+++ b/internal/sheets/team_access.go
@@ -28,6 +28,7 @@ import (
"net/http"
"net/url"
"strconv"
+ "time"
"amadan.net/oficina/home/connect"
"amadan.net/oficina/home/connect/linkstore"
@@ -117,8 +118,15 @@ func (a *App) homeMemberID(ctx context.Context, subject string) (int64, error) {
// subject the roster knows them by ("" when there is none: a local
// account with no link, which is no team standing).
func (a *App) teamIdentify(ctx context.Context, s sessions.Session) (Member, string, error) {
- switch s.Method {
- case connect.HomeMethod:
+ switch {
+ case connect.IsHomeDerived(s.Method):
+ // A browser, native or native-web sign-in through Home. The two
+ // native kinds end seven days after they were minted, however
+ // recently used (connect.Expired); this resolves by subject, not
+ // through ResolveSession, so it refuses what ResolveSession would.
+ if connect.Expired(connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, time.Now()) {
+ return Member{}, "", errNoIdentity
+ }
id, err := a.homeMemberID(ctx, s.Subject)
if err != nil {
if errors.Is(err, errTeamUnavailable) {
@@ -131,7 +139,7 @@ func (a *App) teamIdentify(ctx context.Context, s sessions.Session) (Member, str
return Member{}, "", errTeamUnavailable
}
return m, s.Subject, nil
- case "magiclink", "keymail":
+ case s.Method == "magiclink" || s.Method == "keymail":
// A local session was admitted at sign-in (Admits). Its member is
// created on first sight exactly as actor() always has.
m, err := a.memberFor(s.Subject)
diff --git a/internal/sheets/team_access_test.go b/internal/sheets/team_access_test.go
index aab97d9..cb0ff17 100644
--- a/internal/sheets/team_access_test.go
+++ b/internal/sheets/team_access_test.go
@@ -1,6 +1,7 @@
package sheets
import (
+ "amadan.net/oficina/home/connect"
"net/http"
"net/http/httptest"
"net/url"
@@ -46,8 +47,19 @@ func TestTeamRemovalRevokesAHomeOnlyMembersExistingSession(t *testing.T) {
a := teamSubject('a')
f.dir.Set(a, "member")
- if fin := f.signInHome(t, a); fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != "/sheets" {
- t.Fatalf("roster member's Home sign-in = %d %q", fin.Code, fin.Body.String())
+ // Asked to choose first (Home spec 2026-11-14-oficina-id-native.md
+ // §8); "I'm new here" lands on the default path, as connect's choice
+ // keeps no return path.
+ if fin := f.signInHomeChoosing(t, a); fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != connect.ChoosePath {
+ t.Fatalf("roster member's Home sign-in = %d %q, want the choice", fin.Code, fin.Header().Get("Location"))
+ }
+ var before int64
+ f.app.db.Model(&Member{}).Where("address IS NULL").Count(&before)
+ if before != 0 {
+ t.Fatalf("Home-only members = %d before the choice, want 0: nothing is made until they choose", before)
+ }
+ if fin := f.choose(t, "new"); fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != "/" {
+ t.Fatalf("I'm new here = %d %q", fin.Code, fin.Header().Get("Location"))
}
var addressless int64
f.app.db.Model(&Member{}).Where("address IS NULL").Count(&addressless)
diff --git a/internal/sheets/team_fixture_test.go b/internal/sheets/team_fixture_test.go
index 8149848..2b8fe9a 100644
--- a/internal/sheets/team_fixture_test.go
+++ b/internal/sheets/team_fixture_test.go
@@ -1,11 +1,15 @@
package sheets
import (
+ "html"
"net/http"
"net/http/httptest"
+ "net/url"
+ "regexp"
"testing"
"time"
+ "amadan.net/oficina/home/connect"
"amadan.net/oficina/home/roster"
"amadan.net/oficina/home/teammode"
"amadan.net/oficina/home/teammode/teammodetest"
@@ -88,13 +92,41 @@ func newTeamApp(t *testing.T, directory string, owners ...string) *teamFixture {
// signInHome runs a full Home exchange for subject from a clean jar, and
// returns the finish response.
+//
+// A roster member with no member here yet is asked to choose (Home spec
+// 2026-11-14-oficina-id-native.md §8); signInHome answers "I'm new here",
+// as a new member would, and returns that answer. signInHomeChoosing
+// stops at the choice.
func (f *teamFixture) signInHome(t *testing.T, subject string) *httptest.ResponseRecorder {
+ t.Helper()
+ fin := f.signInHomeChoosing(t, subject)
+ if fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != connect.ChoosePath {
+ return fin
+ }
+ return f.choose(t, "new")
+}
+
+func (f *teamFixture) signInHomeChoosing(t *testing.T, subject string) *httptest.ResponseRecorder {
t.Helper()
f.jar = map[string]*http.Cookie{}
start := f.request(t, "GET", "/auth/start?return_to=%2Fsheets", nil, false)
return f.exchange(t, start, subject)
}
+// choose reads the choice page's form token and posts choice with it.
+func (f *teamFixture) choose(t *testing.T, choice string) *httptest.ResponseRecorder {
+ t.Helper()
+ page := f.get(t, connect.ChoosePath)
+ if page.Code != http.StatusOK {
+ t.Fatalf("choose page = %d %s", page.Code, page.Body.String())
+ }
+ m := regexp.MustCompile(`name="token" value="([^"]+)"`).FindStringSubmatch(page.Body.String())
+ if m == nil {
+ t.Fatalf("choose page has no form token: %s", page.Body.String())
+ }
+ return f.request(t, "POST", connect.ChoosePath, url.Values{"choice": {choice}, "token": {html.UnescapeString(m[1])}}, false)
+}
+
// refreshed steps the roster clock past the refresh point and waits for
// the refresh, so the next request sees the directory's current list.
func (f *teamFixture) refreshed(t *testing.T) {
diff --git a/internal/sheets/team_home_only.go b/internal/sheets/team_home_only.go
index fce41cf..16561c5 100644
--- a/internal/sheets/team_home_only.go
+++ b/internal/sheets/team_home_only.go
@@ -23,6 +23,25 @@ import (
"amadan.net/oficina/sheets/internal/sheets/teamstate"
)
+// teamAdmit is connect's Admit, the roster decision taken first (Home spec
+// 2026-11-14-oficina-id-native.md §8) for a subject with neither a link
+// nor a Home-only member: Runtime.AdmitUnlinked, which allocates nothing
+// and never asks whether Sheets has local accounts. A Member is asked to
+// choose (connect's choose page, or 409 natively); a stranger is
+// connect's "unknown"; an undecidable roster is a 503.
+func (a *App) teamAdmit(ctx context.Context, issuer, subject string) error {
+ if a.team == nil {
+ return errTeamUnavailable
+ }
+ switch err := a.team.AdmitUnlinked(ctx, issuer, subject); {
+ case err == nil:
+ return nil
+ case errors.Is(err, teammode.ErrNotMember):
+ return connect.ErrNoPerson
+ }
+ return errTeamUnavailable
+}
+
// teamHomeOnly is connect's HomeOnly: the addressless member Unlinked
// gave a subject, read and never created.
func (a *App) teamHomeOnly(d *sql.DB) func(context.Context, string, string) (connect.Person, error) {
@@ -38,8 +57,9 @@ func (a *App) teamHomeOnly(d *sql.DB) func(context.Context, string, string) (con
}
}
-// teamUnlinked is connect's Unlinked, asked only when nobody is signed in
-// and the subject has neither a link nor a Home-only member: an
+// teamUnlinked is connect's Unlinked, asked only after a Member chose "I'm
+// new here" with nobody signed in, for a subject with neither a link nor
+// a Home-only member (connect rechecks teamAdmit first): an
// addressless member for a subject the roster says is a Member now, with
// the lease on that answer still valid (Runtime.AdmitUnlinked). A
// stranger is connect's "unknown"; an undecidable roster is a 503.
diff --git a/internal/sheets/templates/home_link.html b/internal/sheets/templates/home_link.html
index db66ed9..7f3cc4b 100644
--- a/internal/sheets/templates/home_link.html
+++ b/internal/sheets/templates/home_link.html
@@ -1 +1,11 @@
-{{define "content"}}{{template "home-connect" .Data}}{{end}}
+{{define "content"}}{{with .Data}}{{if .Choice}}
+<header rst-page-header><div rst-page-header-titles><h1>{{.Title}}</h1></div></header>
+<div rst-box>
+ <p>{{.Body}}</p>
+ {{- /* The member choice (Home spec 2026-11-14-oficina-id-native.md §8):
+ two POSTs carrying the proof's form token, neither the default. */}}
+ <div rst-form-foot>
+ <form method="post" action="{{.Choice.Action}}"><input type="hidden" name="token" value="{{.Choice.Token}}"><button rst-btn="primary" type="submit" name="choice" value="connect">{{.Choice.ConnectLabel}}</button></form>
+ <form method="post" action="{{.Choice.Action}}"><input type="hidden" name="token" value="{{.Choice.Token}}"><button rst-btn="ghost" type="submit" name="choice" value="new">{{.Choice.NewLabel}}</button></form></div>
+</div>
+{{else}}{{template "home-connect" .PageData}}{{end}}{{end}}{{end}}