package connect import ( "context" "crypto/hmac" "crypto/sha256" "encoding/base64" "errors" "io" "mime" "net/http" "net/url" "amadan.net/oficina/home/connect/linkstore" ) // ChoosePath is the member choice page (Home spec // 2026-11-14-oficina-id-native.md §8). Mount ChoosePage at GET and // ChoosePost at POST, outside the session guards: the person choosing has // no session here. ChoosePost is an ordinary same-origin form, so it stays // inside the app's CSRF middleware as well as checking Origin itself. const ChoosePath = "/account/home/choose" const homeChoiceCookie = "__Host-oficina-home-choice" const choiceCookieLifetime = 600 // ChoicePage is the choose page's form: both buttons POST Action with the // field "choice" ("connect" or "new") and the hidden field "token". type ChoicePage struct { Action, Token string } type choiceKey struct{} // ChoiceFor is the form for the choose page being rendered: Render is // called with state "choose" and a request carrying it. The labels are the // app's ("choose_title", "choose_body", "choose_connect_action" and // "choose_new_action" in English). func ChoiceFor(r *http.Request) (ChoicePage, bool) { p, ok := r.Context().Value(choiceKey{}).(ChoicePage) return p, ok } // formKey is the choice form's HMAC key, derived from the storage key and // bound to this origin, so a token is good for one proof on one instance. func formKey(dek []byte, origin string) []byte { m := hmac.New(sha256.New, dek) m.Write([]byte("oficina-connect/choice-form/v1\x00" + origin)) return m.Sum(nil) } func (b *Bridge) choiceToken(secret string) string { m := hmac.New(sha256.New, b.formKey) m.Write([]byte(secret)) return base64.RawURLEncoding.EncodeToString(m.Sum(nil)) } // ChoosePage is GET /account/home/choose: "Welcome to the team", with // "Connect my existing account" and "I'm new here — continue with Oficina // ID". It consumes nothing; it needs the live, browser-bound proof that a // Member's finish left. func (b *Bridge) ChoosePage(w http.ResponseWriter, r *http.Request) { if !b.guard(w, r, http.MethodGet, ChoosePath) { return } if b.admit == nil { b.fail(w, r, http.StatusNotFound) return } secret, present, ok := homeCookie(r, homeChoiceCookie) if !present || !ok { b.fail(w, r, http.StatusForbidden) return } switch err := b.links.ChoiceLive(r.Context(), secret, b.now()); { case errors.Is(err, linkstore.ErrRefused): setHomeCookie(w, homeChoiceCookie, "", -1) b.fail(w, r, http.StatusForbidden) return case err != nil: b.fail(w, r, http.StatusServiceUnavailable) return } page := ChoicePage{Action: ChoosePath, Token: b.choiceToken(secret)} b.render(w, r.WithContext(context.WithValue(r.Context(), choiceKey{}, page)), "choose", "", http.StatusOK) } // ChoosePost is the choice. Its form token is an HMAC of the proof cookie // and it requires this exact origin in Origin. "connect" consumes the proof // and goes to local sign-in with the link-resuming marker, so the person // lands on slice 1's linking. "new" refuses while any app session is // present; otherwise it consumes the proof in its own short transaction // and then, with no transaction open, re-checks Admit and that the subject // still has no person, allocates through Unlinked, resolves and mints. A // consumed proof that yields no session means signing in again. func (b *Bridge) ChoosePost(w http.ResponseWriter, r *http.Request) { if !b.guard(w, r, http.MethodPost, ChoosePath) { return } if b.admit == nil { b.fail(w, r, http.StatusNotFound) return } origins := r.Header.Values("Origin") if len(origins) != 1 || origins[0] != b.origin { b.fail(w, r, http.StatusForbidden) return } media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil || media != "application/x-www-form-urlencoded" { b.fail(w, r, http.StatusBadRequest) return } body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1024)) if err != nil { b.fail(w, r, http.StatusBadRequest) return } form, err := url.ParseQuery(string(body)) if err != nil || len(form) != 2 || len(form["choice"]) != 1 || len(form["token"]) != 1 { b.fail(w, r, http.StatusBadRequest) return } secret, present, ok := homeCookie(r, homeChoiceCookie) if !present || !ok || !hmac.Equal([]byte(form["token"][0]), []byte(b.choiceToken(secret))) { b.fail(w, r, http.StatusForbidden) return } choice := form["choice"][0] if choice != "connect" && choice != "new" { b.fail(w, r, http.StatusBadRequest) return } if choice == "new" && cookieCount(r, b.sessionCookie) != 0 { // Allocation is reachable only with no app session at all, as at // finish; the proof stays for a choice made without one. b.fail(w, r, http.StatusForbidden) return } taken, err := b.links.TakeChoice(r.Context(), secret, b.now()) switch { case errors.Is(err, linkstore.ErrRefused): setHomeCookie(w, homeChoiceCookie, "", -1) b.fail(w, r, http.StatusForbidden) return case err != nil: // Nothing was consumed: the same proof may be tried again. b.fail(w, r, http.StatusServiceUnavailable) return } setHomeCookie(w, homeChoiceCookie, "", -1) if choice == "connect" { if b.rememberUnknown != nil { b.rememberUnknown(w) } http.Redirect(w, r, SigninLocalPath, http.StatusSeeOther) return } person, err := b.chooseNew(r.Context(), taken.Subject) if errors.Is(err, linkstore.ErrRefused) { if b.rememberUnknown != nil { b.rememberUnknown(w) } b.render(w, r, "unknown", "", http.StatusForbidden) return } if err != nil || person.ID <= 0 { b.fail(w, r, http.StatusServiceUnavailable) return } if err := b.mint(w, r, Session{Subject: taken.Subject, Method: HomeMethod, AuthTime: taken.AuthTime}, person); err != nil { b.fail(w, r, http.StatusServiceUnavailable) return } http.Redirect(w, r, "/", http.StatusSeeOther) } // chooseNew is "I'm new here" for a subject, after its proof or its native // request: a person found now (a link or a racing choice) is used as is; // otherwise Admit again, then allocate. ErrRefused is "unknown", ErrStorage // "cannot decide now". It holds no transaction across any hook. func (b *Bridge) chooseNew(ctx context.Context, subject string) (Person, error) { if p, err := b.Resolve(ctx, subject); !errors.Is(err, linkstore.ErrRefused) { return p, err } switch err := b.admit(ctx, b.issuer, subject); { case errors.Is(err, ErrNoPerson): return Person{}, linkstore.ErrRefused case err != nil: return Person{}, linkstore.ErrStorage } return b.allocate(ctx, subject) } // allocate is Unlinked followed by a fresh resolution (spec §7 step 4): the // person is whoever the subject resolves to afterwards, so a hook that // refused because a racing choice created the person still signs this one // in, and a refusal with nobody found is "unknown", or "cannot decide now" // when either step could not read. func (b *Bridge) allocate(ctx context.Context, subject string) (Person, error) { _, hookErr := homeOnlyPerson(b.unlinked(ctx, b.issuer, subject)) p, err := b.Resolve(ctx, subject) switch { case err == nil: return p, nil case errors.Is(hookErr, linkstore.ErrStorage) || errors.Is(err, linkstore.ErrStorage): return Person{}, linkstore.ErrStorage } return Person{}, linkstore.ErrRefused }