oficina / home Public

Oficina ID native: directory exchange, teams and the zero-teams help

Human

Prompt

Implement the Home (id.oficina.works) half of slice A of the approved Oficina ID native spec. Paul approved the spec and building on 2026-11-14.

Read first: native-levelup/BRIEF.md (own worktree from fresh origin/main, repo AGENTS.md, amadan workflow, agent account, never -as-human, pinned-toolchain make gates, no deploys, do not merge). Then in the Home repo: docs/superpowers/specs/2026-11-14-oficina-id-native.md (binding; slice table §14), 2026-11-13-oficina-id-slice-1.md (binding base), Home AGENTS.md.

Scope — slice A, Home side only (another agent does connect/NativeExchange/choose page/IsHomeDerived in parallel on its own branch; a third does the Swift client; coordinate only through the spec's wire formats, and if the spec is ambiguous about a wire detail, pick the reading most consistent with it, write it into a short "wire notes" section of your branch description, and flag it):
- the native grant + device-key proof (§3), persistent replay table, per-grant rate limit, server Date for clock offset;
- email code start/resend/verify with every limit in §4 (per-(address, device key) caps, daily cap, returning-key exemption by end_reason, per-IP-bucket live starts, 503 when full, shared email budget with the web, sealed addresses, no codes/addresses in logs; Keymail addresses get the code in slice A);
- native passkey sign-in (§5): passkey/begin, passkey/finish against RP id.oficina.works, plus the static /.well-known/apple-app-site-association with webcredentials for the five App IDs 9U4A84C4WK.works.oficina.{calls,docs,sheets,calendar,memoria} (no applinks);
- assert with the shared mintPolicy (empty in slice A), native nonce derivation;
- signout, "Sign out all devices" on the web, replacement revoking every grant, first passkey enrolment (native or web) revoking passkey-less grants;
- directory teams listing + zero-teams help;
- every slice-A gate in §13 that belongs to Home, as tests.
Not in scope: A2 (multiple identities UI, Devices page, Keymail sheet), B (native recovery/enrolment), C–E.

Process: small reviewable commits; make ci green; push; describe the branch on the hub with tasks; stop for review. Report: branch, tip, what's done vs deferred, gate output, wire notes, open questions.

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

The directory (oficina.works) as a native consumer: POST /native/oficina-id {assertion, verifier} verifies the assertion against the pinned keys for the directory audience, recomputes the native nonce from the verifier, reserves the jti in the same oficina_handoff_replay ledger the browser callback uses, and returns a seven-day home-assertion-native session token in the body, no cookie. GET /api/native/teams lists the person's teams with live instances of the five native apps from Store.AgentChoices ([] for none, no-store, native sessions only, browsers refused). POST /native/signout ends that native session. GET /help/teams is the zero-teams help page (help text only while Alta is blocked).
Agent notes
Exchange answer shape follows rastrillo/native's /native/exchange: {name, value, expires_at}. target and choice are accepted and ignored: the directory links nobody and allocates nothing. The connect agent's NativeExchange is the instance side; this is the directory's own, because the directory is a handoff consumer, not a connect.Bridge.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ca1f32ac191c623361f06b9dfc94a7cff0e20683 parent 507810f
4 files changed, +344 −0
  • internal/home/directory.go +6 −0
  • internal/home/directory_native.go +190 −0
  • internal/home/directory_native_test.go +141 −0
  • internal/home/templates/directory_no_teams.html +7 −0
diff --git a/internal/home/directory.go b/internal/home/directory.go
index 8d68b98..a949e5b 100644
--- a/internal/home/directory.go
+++ b/internal/home/directory.go
@@ -107,6 +107,10 @@ func (a *App) directoryRouter() http.Handler {
// The credential origin's member-resolution receipt arrives here as a
// cross-origin POST, with its own exact Origin check (team_page.go).
r.Post(teamResolvedPath, a.handleTeamResolved)
+ // The native exchange and sign-out (directory_native.go) refuse every
+ // browser evidence header instead.
+ r.Post(nativeExchangePath, a.directoryNativeExchange)
+ r.Post(nativeDirectorySignout, a.directoryNativeSignout)
r.Group(func(r chi.Router) {
r.Use(csrf.Protect(a.origins.Directory))
for _, chooser := range a.directory.choosers {
@@ -116,6 +120,8 @@ func (a *App) directoryRouter() http.Handler {
r.Get(handoff.StartPath, a.consumer.Start)
r.Get(a.fresh.StartPath(), a.fresh.Start)
r.Get(handoff.FinishPath, a.consumer.Finish)
+ r.Get(nativeTeamsPath, a.directoryNativeTeams)
+ r.Get(noTeamsHelpPath, a.handleNoTeamsHelp)
r.Get("/signin", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, handoff.StartPath, http.StatusSeeOther)
})
diff --git a/internal/home/directory_native.go b/internal/home/directory_native.go
new file mode 100644
index 0000000..c73a8ce
--- /dev/null
+++ b/internal/home/directory_native.go
@@ -0,0 +1,190 @@
+package home
+
+import (
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/hex"
+ "errors"
+ "net/http"
+ "time"
+
+ "amadan.net/oficina/home/internal/home/directorydata"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+// The directory's half of native sign-in (§9). The directory is a consumer
+// like any team instance: the app asks the credential origin for an
+// assertion with aud = the directory, redeems it here for a directory
+// session, and reads its teams with that session. Nothing here renders, sets
+// a cookie, or answers a browser.
+const (
+ nativeExchangePath = "/native/oficina-id"
+ nativeTeamsPath = "/api/native/teams"
+ nativeDirectorySignout = "/native/signout"
+ noTeamsHelpPath = "/help/teams"
+
+ // nativeSessionMethod marks a session minted for a native app. It lives
+ // seven days, absolute (§7); the app re-mints after a day and on a 401.
+ nativeSessionMethod = "home-assertion-native"
+ nativeSessionLife = 7 * day
+)
+
+// nativeTeamApps are the native apps; the list is filtered to them (§9).
+var nativeTeamApps = map[string]bool{"calls": true, "docs": true, "sheets": true, "calendar": true, "memoria": true}
+
+// directoryNativeExchange is POST /native/oficina-id {assertion, verifier}.
+// It verifies the assertion against the pinned keys with the exact issuer
+// and the directory as audience, recomputes the native nonce from the
+// verifier, reserves the jti, and mints a seven-day directory session whose
+// token goes back in the body, never in a cookie. target and choice are
+// accepted for the shape instances share and ignored: the directory links
+// nobody and allocates nothing, so a person ref is the whole answer.
+func (a *App) directoryNativeExchange(w http.ResponseWriter, r *http.Request) {
+ body, ok := nativeIntake(w, r)
+ if !ok {
+ return
+ }
+ var in struct {
+ Assertion string `json:"assertion"`
+ Verifier string `json:"verifier"`
+ Target string `json:"target,omitzero"`
+ Choice string `json:"choice,omitzero"`
+ }
+ if !decodeNative(body, &in) {
+ nativeFail(w, http.StatusBadRequest, "request")
+ return
+ }
+ verifierRaw, ok := decodeB64(in.Verifier, 32)
+ if !ok {
+ nativeFail(w, http.StatusBadRequest, "request")
+ return
+ }
+ v, err := assertion.NewVerifier(a.origins.Credential, a.origins.Directory, a.runtime.keys)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ now := time.Now()
+ claims, err := v.Verify(in.Assertion, now)
+ challenge := sha256.Sum256(verifierRaw)
+ if err != nil || subtle.ConstantTimeCompare([]byte(claims.Nonce), []byte(nativeNonce(challenge[:]))) != 1 || !ValidPersonRef(claims.Subject) {
+ nativeUnauthorized(w, "assertion")
+ return
+ }
+ tx, err := a.db.Writer().BeginTx(r.Context(), nil)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ defer tx.Rollback()
+ // The same replay ledger, and the same key for it, as the browser
+ // callback (handoff.Store): one jti is redeemable once, by either door.
+ jti := sha256.Sum256([]byte(claims.Issuer + "\x00" + claims.ID))
+ res, err := tx.Exec("INSERT INTO oficina_handoff_replay(jti_hash,expires_at) VALUES(?,?) ON CONFLICT DO NOTHING", hex.EncodeToString(jti[:]), claims.ExpiresAt)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if n, err := res.RowsAffected(); err != nil || n != 1 {
+ nativeUnauthorized(w, "replay")
+ return
+ }
+ token, hash, err := sessions.NewToken()
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ expires := now.Unix() + nativeSessionLife
+ if _, err = tx.Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)",
+ hash, claims.Subject, nativeSessionMethod, time.Unix(claims.AuthTime, 0).UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339), time.Unix(expires, 0).UTC().Format(time.RFC3339)); err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if tx.Commit() != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ nativeReply(w, http.StatusOK, map[string]any{"name": a.sessions.CookieName(), "value": token, "expires_at": expires})
+}
+
+type nativeTeamApp struct {
+ App string `json:"app"`
+ Origin string `json:"origin"`
+ ConsumerID string `json:"consumer_id"`
+}
+type nativeTeam struct {
+ SQID string `json:"sqid"`
+ Label string `json:"label"`
+ Name string `json:"name"`
+ Role string `json:"role"`
+ Apps []nativeTeamApp `json:"apps"`
+}
+
+// directoryNativeTeams is GET /api/native/teams: the person's teams with
+// live instances of the five native apps, from Store.AgentChoices. Zero
+// teams is an empty list, never an error; the app then shows its help and
+// may link noTeamsHelpPath.
+func (a *App) directoryNativeTeams(w http.ResponseWriter, r *http.Request) {
+ if _, ok := r.Header["Origin"]; ok {
+ nativeFail(w, http.StatusForbidden, "browser")
+ return
+ }
+ if _, ok := r.Header["Sec-Fetch-Site"]; ok {
+ nativeFail(w, http.StatusForbidden, "browser")
+ return
+ }
+ s, ok := sessions.Current(r)
+ if !ok || s.Method != nativeSessionMethod {
+ nativeUnauthorized(w, "session")
+ return
+ }
+ choices, err := a.directory.store.AgentChoices(r.Context(), s.Subject)
+ if errors.Is(err, directorydata.ErrInvalid) {
+ nativeUnauthorized(w, "session")
+ return
+ }
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ teams := []nativeTeam{}
+ for _, c := range choices {
+ if !nativeTeamApps[c.App] {
+ continue
+ }
+ if len(teams) == 0 || teams[len(teams)-1].SQID != c.SQID {
+ teams = append(teams, nativeTeam{SQID: c.SQID, Label: c.Label, Name: c.Name, Role: c.Role, Apps: []nativeTeamApp{}})
+ }
+ last := &teams[len(teams)-1]
+ last.Apps = append(last.Apps, nativeTeamApp{App: c.App, Origin: c.Origin, ConsumerID: c.ConsumerID})
+ }
+ nativeReply(w, http.StatusOK, teams)
+}
+
+// directoryNativeSignout is POST /native/signout {}: the app's directory
+// session ends (§10 step 3). Outside csrf.Protect, because a native call
+// carries no origin evidence; it refuses any that a browser would send, and
+// it can end only a native session.
+func (a *App) directoryNativeSignout(w http.ResponseWriter, r *http.Request) {
+ body, ok := nativeIntake(w, r)
+ if !ok {
+ return
+ }
+ var in struct{}
+ if !decodeNative(body, &in) {
+ nativeFail(w, http.StatusBadRequest, "request")
+ return
+ }
+ if token := cookieValue(r, a.sessions.CookieName()); token != "" {
+ if _, err := a.db.Writer().ExecContext(r.Context(), "DELETE FROM sessions WHERE token_hash=? AND method=?", sessions.HashToken(token), nativeSessionMethod); err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ }
+ nativeReply(w, http.StatusOK, map[string]string{})
+}
+
+func (a *App) handleNoTeamsHelp(w http.ResponseWriter, r *http.Request) {
+ a.render(w, r, http.StatusOK, "directory_no_teams.html", nil)
+}
diff --git a/internal/home/directory_native_test.go b/internal/home/directory_native_test.go
new file mode 100644
index 0000000..cac7033
--- /dev/null
+++ b/internal/home/directory_native_test.go
@@ -0,0 +1,141 @@
+package home
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+// directoryCall is a native app's request to the directory.
+func directoryCall(t *testing.T, f chooserFixture, method, path, body string, cookie *http.Cookie, headers map[string]string) *httptest.ResponseRecorder {
+ t.Helper()
+ r := httptest.NewRequest(method, directoryOrigin+path, strings.NewReader(body))
+ if body != "" {
+ r.Header.Set("Content-Type", "application/json")
+ }
+ if cookie != nil {
+ r.AddCookie(cookie)
+ }
+ for k, v := range headers {
+ r.Header.Set(k, v)
+ }
+ w := httptest.NewRecorder()
+ f.p.directory.Router().ServeHTTP(w, r)
+ return w
+}
+
+func exchangeBody(assertion, verifier string) string {
+ b, _ := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier})
+ return string(b)
+}
+
+// §9: assert for the directory, exchange it with the verifier, read the
+// teams. Zero teams is an empty list.
+func TestNativeDirectoryTeams(t *testing.T) {
+ f := newMountedChooser(t)
+ cred := f.p.credential
+ d := newDevice(t)
+ grant, _ := d.signInByCode(t, cred, "teams@example.invalid")
+ var person string
+ cred.db.Writer().QueryRow("SELECT person_ref FROM home_id_grants").Scan(&person)
+
+ mint := func(seed byte) (string, string) {
+ verifier, challenge := verifierFor(seed)
+ w := d.assert(t, cred, grant, directoryOrigin, challenge)
+ if w.Code != 200 {
+ t.Fatal("assert", w.Code, w.Body.String())
+ }
+ return decodeReply(t, w)["assertion"].(string), verifier
+ }
+ token, verifier := mint(10)
+ // A wrong verifier, a browser and a non-JSON body are refused.
+ wrongVerifier, _ := verifierFor(11)
+ if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, wrongVerifier), nil, nil); w.Code != 401 {
+ t.Fatal("wrong verifier", w.Code)
+ }
+ if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, map[string]string{"Origin": directoryOrigin}); w.Code != 403 {
+ t.Fatal("a browser exchanged", w.Code)
+ }
+ w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, nil)
+ if w.Code != 200 || len(w.Result().Cookies()) != 0 {
+ t.Fatal("exchange", w.Code, w.Body.String(), w.Header())
+ }
+ out := decodeReply(t, w)
+ cookie := &http.Cookie{Name: out["name"].(string), Value: out["value"].(string)}
+ if exp := int64(out["expires_at"].(float64)); exp > time.Now().Unix()+7*day || exp < time.Now().Unix()+7*day-60 {
+ t.Fatal("native directory session is not seven days", exp)
+ }
+ // The same assertion twice is a replay.
+ if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, nil); w.Code != 401 {
+ t.Fatal("replayed exchange", w.Code)
+ }
+
+ w = directoryCall(t, f, "GET", nativeTeamsPath, "", cookie, nil)
+ if w.Code != 200 || strings.TrimSpace(w.Body.String()) != "[]" || w.Header().Get("Cache-Control") != "no-store" {
+ t.Fatal("zero teams", w.Code, w.Body.String())
+ }
+ f.team(t, "AAA111", "blue", "Blue team", person)
+ f.team(t, "BBB222", "green", "Not yours", chooserOther)
+ w = directoryCall(t, f, "GET", nativeTeamsPath, "", cookie, nil)
+ var teams []nativeTeam
+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &teams) != nil || len(teams) != 1 {
+ t.Fatal("teams", w.Code, w.Body.String())
+ }
+ tm := teams[0]
+ if tm.SQID != "AAA111" || tm.Label != "blue" || tm.Name != "Blue team" || tm.Role != "member" || len(tm.Apps) != 1 || tm.Apps[0] != (nativeTeamApp{"docs", "https://blue.docs.oficina.works", "blue-docs"}) {
+ t.Fatalf("team %+v", tm)
+ }
+ // A browser cannot read it, nor a browser session.
+ if w := directoryCall(t, f, "GET", nativeTeamsPath, "", cookie, map[string]string{"Sec-Fetch-Site": "same-origin"}); w.Code != 403 {
+ t.Fatal("a browser read teams", w.Code)
+ }
+ if w := directoryCall(t, f, "GET", nativeTeamsPath, "", f.session(t, person), nil); w.Code != 401 {
+ t.Fatal("a browser session read the native list", w.Code)
+ }
+ if w := directoryCall(t, f, "GET", nativeTeamsPath, "", nil, nil); w.Code != 401 {
+ t.Fatal("anonymous teams", w.Code)
+ }
+ // Sign-out ends the native directory session, and only that.
+ if w := directoryCall(t, f, "POST", nativeDirectorySignout, "{}", cookie, nil); w.Code != 200 {
+ t.Fatal("directory signout", w.Code)
+ }
+ if w := directoryCall(t, f, "GET", nativeTeamsPath, "", cookie, nil); w.Code != 401 {
+ t.Fatal("a signed-out session read teams", w.Code)
+ }
+}
+
+// §12: the exchange accepts only native nonces. An assertion minted through
+// /authorize, with a browser's nonce, does not redeem here.
+func TestNativeDirectoryRefusesBrowserNonce(t *testing.T) {
+ f := newMountedChooser(t)
+ session := signInFully(t, f.p.credential, "web@example.invalid")
+ _, intent := f.p.start(t)
+ token, _ := f.p.mint(t, intent, session)
+ for seed := byte(0); seed < 4; seed++ {
+ verifier, _ := verifierFor(seed)
+ if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, nil); w.Code == 200 {
+ t.Fatal("a browser assertion redeemed natively")
+ }
+ }
+ // An assertion for another audience fails too.
+ d := newDevice(t)
+ grant, _ := d.signInByCode(t, f.p.credential, "aud@example.invalid")
+ verifier, challenge := verifierFor(20)
+ w := d.assert(t, f.p.credential, grant, "https://blue.docs.oficina.works", challenge)
+ if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(decodeReply(t, w)["assertion"].(string), verifier), nil, nil); w.Code != 401 {
+ t.Fatal("swapped audience redeemed", w.Code)
+ }
+}
+
+// The zero-teams help (§9, Paul's ruling H): help text only while Alta is
+// blocked.
+func TestNativeDirectoryNoTeamsHelp(t *testing.T) {
+ f := newMountedChooser(t)
+ w := directoryCall(t, f, "GET", noTeamsHelpPath, "", nil, nil)
+ if w.Code != 200 || !strings.Contains(w.Body.String(), "not on a team yet") || strings.Contains(w.Body.String(), "Create a team") {
+ t.Fatal("help", w.Code)
+ }
+}
diff --git a/internal/home/templates/directory_no_teams.html b/internal/home/templates/directory_no_teams.html
new file mode 100644
index 0000000..7c0a420
--- /dev/null
+++ b/internal/home/templates/directory_no_teams.html
@@ -0,0 +1,7 @@
+{{define "title"}}Not on a team yet · Oficina{{end}}
+{{define "content"}}
+<h1>You're not on a team yet</h1>
+<p>The Oficina apps open a team's documents, sheets, calendars and calls. Your Oficina ID isn't on a team yet, so there is nothing for them to open.</p>
+<p>Ask the owner of your team to add the email address you signed in with. Then open the app again, and your team appears.</p>
+<p><a href="/">Back to Oficina</a></p>
+{{end}}