package calls // The door's admission check (home/connect MIGRATING.md, step 6, item 2): // before /signin, /signin/local or /signin/oficina may treat a live session // as signed in, the gate every signed-in page runs is asked about it, on a // probe. A session it refuses gets the door with the refusal (or the // removal) and is ended; one it cannot decide on is left alone. And the // smart door's memory of an Oficina ID sign-in, written only for a session // that gate admits. // // What the door judges, and what it never touches: // // - A web sign-in (an emailed link, Keymail, a Home sign-in) is judged, // as the old /signin checks (signin, teamSignin) judged it. // - A guest's session (method "guest", minted by joining a call by name) // is never judged, refused, remembered or ended here: the door is drawn // for it as for anybody signed out, because signing in is what a guest // at the door is asking to do, and the cookie is left as it is. // connect's SigninDoor reads a guest as signed out for the same reason. // - The native apps hold sessions of their own: native_auth.go mints the // app its own session row, a copy of the browser's, and callscore // never follows a redirect, so the app's cookie never reaches a door. // The door only ever ends the one session the browser presented // (refusedSession), so no native session is refused or ended by it. import ( "context" "net/http" "net/url" "amadan.net/oficina/home/connect" "amadan.net/rastrillo/rastrillo/lastsignin" ) // signinRoute is GET /signin: the door. With Home, connect's SigninDoor // behind the admission check; standalone, standaloneSignin. // // The join cookie (joincookie.go: an invitation this browser followed) // opens the door on the email way, whatever the browser used last, with // Oficina ID under Other ways (Paul's ruling, 2026-11-22, #46). An // outsider is let in by the pending join the emailed link proves (spec // §3.2); a member may use either, and an Oficina ID sign-in lands back on // the invitation (oficinaJoinLanding). Before the smart door this was a // call straight to the local form, email only. func (a *app) signinRoute(w http.ResponseWriter, r *http.Request) { if a.home == nil { a.standaloneSignin(w, r) return } if _, pending := a.readJoinCookie(r); pending { r = withJoining(r) } a.homeDoor(a.home.routes.SigninDoor)(w, r) } // oficinaJoinLanding is GET /signin/oficina while a join cookie is live: // the Home exchange lands on /continue, as an emailed link does, instead // of the page return_to named, so the sign-in goes on into the invitation // the cookie names (continueInvitation). /continue is a fixed local path, // and the invitation is read from the sealed cookie by its hash, so no // destination or token is taken from the request. A step-up is left to // SigninOficina, which sends it to the email-only door. func (a *app) oficinaJoinLanding(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() if _, pending := a.readJoinCookie(r); pending && !q.Has("reauth") { q.Set("return_to", "/continue") r = r.Clone(r.Context()) r.URL.RawQuery = q.Encode() r.RequestURI = r.URL.RequestURI() } next(w, r) } } // homeDoor is one of connect's three door routes as Calls mounts it: under // Home's session middleware, which clears a cookie whose session is // definitively gone (and leaves it on a storage failure), so a stale cookie // cannot stand in the way of the exchange (connect's Start refuses a // session cookie that does not resolve); then the admission check. func (a *app) homeDoor(next http.HandlerFunc) http.HandlerFunc { return a.home.sessions.Middleware(a.admittedOnly(next)).ServeHTTP } // standaloneSignin is GET /signin without Home: somebody already signed in // and admitted never sees the door (spec shared-chrome §9.4) unless the // query names one of its states, and goes to a safe return_to or "/". A // session the signed-in routes refuse gets the door with the refusal, as // with Home (admittedOnly). Standalone Calls has only email, so the door is // the email way. func (a *app) standaloneSignin(w http.ResponseWriter, r *http.Request) { if ad := a.admission(r, false); ad.signedIn { if !ad.admitted { r = a.refusedSession(w, r, ad.removed) } else if !signinOutcome(r) { alreadySignedIn(w, r) return } } a.signinDoor(w, r) } // admittedOnly runs connect's SigninDoor, SigninLocal or SigninOficina for // a browser whose session the signed-in routes would admit, and as signed // out for any other. SigninDoor and SigninOficina take any live session // cookie as signed in and send it straight to the page; a session the // signed-in routes refuse (a Home link to a deleted person, an address no // longer a member, somebody the roster says is off the team) would then go // round /signin, the page, the refusal and back (Astra on Docs #65, Sheets // #39), so they are not shown that cookie. SigninLocal is wrapped too, for // the refusals that land there. func (a *app) admittedOnly(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if ad := a.admission(r, false); ad.signedIn && !ad.admitted { r = withoutCookie(a.refusedSession(w, r, ad.removed), a.sessionCookie()) } next(w, r) } } // refusedSession answers for a session the probe refused: it is ended and // its cookie cleared on this response, so a reload is plainly signed out // rather than a dead cookie over the plain door; a remembered Oficina ID is // forgotten, because offered again it would sign the same refused person // in and send them back here; and the door is marked to say why: the // refusal, or for a session the signed-in routes end as removed the // removal, in the screen's app-problem slot with the email field. A // remembered email way is kept: it is no loop. func (a *app) refusedSession(w http.ResponseWriter, r *http.Request, removed bool) *http.Request { a.nativeAuth.sessions.SignOut(w, r) w.Header().Set("Cache-Control", "no-store") jar := a.auth.RememberJar() if rec, res := jar.Read(r); res == lastsignin.Valid && rec.Method == lastsignin.MethodFederated { jar.Clear(w) } if removed { return withRemoval(r) } return withRefusal(r) } // admissionResult is what the probe found: whether r holds a web sign-in // at all, whether the signed-in routes let it in, and whether they ended it // as removed (endRemovedSession). type admissionResult struct { signedIn, admitted, removed bool } // admission runs the gate every signed-in page runs (rastrillo auth's // RequireSession, then requirePerson: identity, a Home link and whether // it still resolves to a member, or in team mode the roster) around a // probe GET / whose answer is thrown away. A session is not enough: a // Home link to a person who has gone still holds a valid one. The probe // ends nothing itself (endRemovedSession skips its sign-out under it): // the door's caller does, for a session it decides to refuse. // // requireMember is not part of it: in Calls a signed-in non-member is no // refusal but a guest-like participant, who lands on /welcome and joins // calls through their invitations, and the old /signin checks never asked // it either. // // A gate that cannot decide (a 5xx: storage or the roster unavailable) // counts as admitted unless strict: the door must not tell somebody they // cannot sign in, nor sign them out, because a read failed, and nothing is // remembered on one. func (a *app) admission(r *http.Request, strict bool) admissionResult { probe := r.Clone(context.WithValue(r.Context(), probingKey{}, true)) probe.Method = http.MethodGet probe.URL = &url.URL{Path: "/"} probe.RequestURI = "/" probe.Body = http.NoBody // The session is read from the probe's own cookie, never from the // context a middleware filled: admittedAs asks about a session minted // on this very response. s, ok := a.nativeAuth.sessions.From(probe) if !ok || !doorJudges(s.Method) { // Signed out, or a session that is not a web sign-in (a guest): // the door is drawn, and nothing is refused or ended. return admissionResult{} } reached := false gate := a.auth.RequireSession(a.requirePerson(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true }))) rec := &bufferedResponse{header: make(http.Header)} gate.ServeHTTP(rec, probe) undecided := rec.status >= http.StatusInternalServerError return admissionResult{ signedIn: true, admitted: reached || (!strict && undecided), removed: !reached && rec.status == http.StatusSeeOther && removedRedirect(rec.header.Get("Location")), } } // doorJudges reports whether the door's probe judges a session by method: // the three requirePerson speaks for as a sign-in (an emailed link, // Keymail, a Home sign-in on the web), as signin and teamSignin did. A // guest is never judged by the door. func doorJudges(method string) bool { return method == connect.HomeMethod || method == "magiclink" || method == "keymail" } // removedRedirect reports whether location is endRemovedSession's: the // door with err=removed. func removedRedirect(location string) bool { u, err := url.Parse(location) return err == nil && u.Path == signinPath && u.Query().Get("err") == "removed" } // probingKey marks the admission probe's request, so the gate it runs // answers without ending anything (endRemovedSession). type probingKey struct{} // probing reports whether ctx is the admission probe's. func probing(ctx context.Context) bool { v, _ := ctx.Value(probingKey{}).(bool) return v } // withoutCookie is r, as seen by a handler that must not see the named // cookie. Only admittedOnly and admittedAs use it. func withoutCookie(r *http.Request, name string) *http.Request { c := r.Clone(r.Context()) c.Header.Del("Cookie") for _, cookie := range r.Cookies() { if cookie.Name != name { c.AddCookie(cookie) } } return c } // sessionCookie is the session cookie's name: auth's, Home's and the // native hand-off's are the same table and the same cookie. func (a *app) sessionCookie() string { return a.auth.SessionCookie() } // rememberOficina is the smart door's memory of a Home sign-in, written in // MintHomeSession once the session is stored, so it is written only where // connect turns a Home sign-in into a session here (a finished exchange, // "I'm new here"), never on link, choose, unknown or failed. The record is // Oficina ID, with the address of the person connect resolved for this // very sign-in (connect.MintedPerson), or none for a Home-only member. // Nothing is carried over from the record it replaces: that address could // be somebody else's. Remembering is a convenience, and Remember fails // silently, so it can never fail the sign-in. // // Only for a session the signed-in routes admit, asked of the session just // minted (admittedAs) and strictly: connect mints for any linked person, // and a record for a refused one would offer Oficina ID again, round a // loop of sign-in, refusal and door (Fable on Docs #139, A2). func (a *app) rememberOficina(w http.ResponseWriter, r *http.Request) { if a.auth == nil || a.home == nil || a.nativeAuth == nil { return } if !a.admission(a.admittedAs(w, r), true).admitted { return } address := "" if p, ok := connect.MintedPerson(r); ok { address = p.Label } a.auth.RememberJar().Remember(w, lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: address}) } // admittedAs is r as the session MintHomeSession just set on w would send // it: the request's own cookies, with that session's in place of any other. func (a *app) admittedAs(w http.ResponseWriter, r *http.Request) *http.Request { name := a.sessionCookie() var minted *http.Cookie for _, c := range (&http.Response{Header: w.Header()}).Cookies() { if c.Name == name && c.MaxAge >= 0 && c.Value != "" { minted = c } } probe := withoutCookie(r, name) if minted != nil { probe.AddCookie(&http.Cookie{Name: minted.Name, Value: minted.Value}) } return probe } // signinOutcome reports whether GET /signin names a state of the door // rather than opening it afresh: an outcome of the email flow (?sent, // ?err, ?force), the Keymail continuation (?continue) or a step-up // (?reauth). connect's SigninDoor draws the same five for a signed-in // browser too (its doorStates). func signinOutcome(r *http.Request) bool { q := r.URL.Query() return q.Has("sent") || q.Has("err") || q.Has("force") || q.Has("continue") || q.Has("reauth") } // alreadySignedIn sends a signed-in GET /signin back where it came from, // with no door: 303 to a safe return_to, or "/". func alreadySignedIn(w http.ResponseWriter, r *http.Request) { target := "/" if path, ok := requestedReturn(r); ok { target = path } w.Header().Set("Cache-Control", "no-store") http.Redirect(w, r, target, http.StatusSeeOther) } // chooseJoinLanding is the member choice's POST while a join cookie is // live: connect lands "I'm new here" on "/", whatever the exchange was // started for, so that one redirect goes to /continue instead, which // follows the invitation (continueInvitation), as oficinaJoinLanding does // for every other Oficina ID sign-in. Any other answer is passed on. func (a *app) chooseJoinLanding(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if _, pending := a.readJoinCookie(r); !pending { next(w, r) return } result := &bufferedResponse{header: make(http.Header)} next(result, r) if result.status == http.StatusSeeOther && result.header.Get("Location") == "/" { result.header.Set("Location", "/continue") } result.replay(w) } }