| 1 | package calls |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | |
| 11 | "amadan.net/oficina/estilo.git/chrome" |
| 12 | "amadan.net/oficina/home/connect" |
| 13 | "amadan.net/oficina/home/roster" |
| 14 | rauth "amadan.net/rastrillo/rastrillo/auth" |
| 15 | "amadan.net/rastrillo/rastrillo/sessions" |
| 16 | "github.com/keymaildev/signin" |
| 17 | ) |
| 18 | |
| 19 | // signinPath is the sign-in door (connect.SigninPath): every outcome of |
| 20 | // the email flow, every chooser link and Forget's way back land here. |
| 21 | const signinPath = connect.SigninPath |
| 22 | |
| 23 | // newAuthPlugin wires rastrillo/auth. Authorize is Calls' one departure |
| 24 | // from Docs (spec §3.2): an address is admitted at the emailed link when |
| 25 | // it is on the allowlist, or when it holds an unexpired pending-join row |
| 26 | // whose link is still live. The row was written before the mail went |
| 27 | // out, so the click is admitted in whichever browser it lands. |
| 28 | func (a *app) newAuthPlugin(writer *sql.DB) (*rauth.Auth, error) { |
| 29 | landing := "/continue" |
| 30 | if a.cfg.home != nil { |
| 31 | landing = "/auth/local/complete" |
| 32 | } |
| 33 | return rauth.New(rauth.Config{ |
| 34 | DB: writer, |
| 35 | Origin: a.cfg.Origin, |
| 36 | InstanceKey: a.cfg.instanceKey, |
| 37 | Mailer: a.signinMail, |
| 38 | Subject: chrome.EmailSubject("Calls"), |
| 39 | Authorize: a.authorize, |
| 40 | // A verified address authorize refuses gets the door, with the |
| 41 | // refusal on it, in auth's own 403 (refused). |
| 42 | Refused: a.refused, |
| 43 | // GET /auth/verify spends nothing: it opens the door with one |
| 44 | // Sign in button that POSTs the link back, so a mail scanner's |
| 45 | // fetch cannot spend it (renderConfirm). |
| 46 | RenderConfirm: a.renderConfirm, |
| 47 | // No proof-of-work on the sign-in form. Calls never had one: |
| 48 | // gateBegin's syntax check, mayRequestLink's budgets (ruling 12) |
| 49 | // and mailQueue's admission check are what stand between a |
| 50 | // stranger and the mailer, and the door is estilo's form, which |
| 51 | // renders no pow challenge. ProofOff keeps today's behaviour; |
| 52 | // wiring a pow.Guard is a decision of its own (schema, assets, a |
| 53 | // form that needs JavaScript). |
| 54 | ProofOff: true, |
| 55 | // The smart door (Home spec 2026-11-19-smart-door.md, step 6): |
| 56 | // rastrillo's screen, one way in per page. Every outcome, chooser |
| 57 | // link and Forget lands on /signin, which with Home configured is |
| 58 | // connect's SigninDoor, offering Continue with Oficina ID |
| 59 | // (home/connect MIGRATING.md, item 3). |
| 60 | SigninScreen: true, |
| 61 | SigninOneWay: true, |
| 62 | SigninPath: signinPath, |
| 63 | ForgetPath: signinForgetPath, |
| 64 | SignedInPath: landing, |
| 65 | Logger: a.logger, |
| 66 | KeymailServers: a.cfg.KeymailServers, |
| 67 | }) |
| 68 | } |
| 69 | |
| 70 | func (a *app) authorize(address string) bool { |
| 71 | if a.allowNow().allows(address) { |
| 72 | return true |
| 73 | } |
| 74 | live, err := a.store.pendingLive(context.Background(), address) |
| 75 | if err != nil { |
| 76 | a.logger.Error("calls: authorize: pending lookup", "err", err) |
| 77 | return false |
| 78 | } |
| 79 | return live |
| 80 | } |
| 81 | |
| 82 | // gateBegin sits in front of rastrillo's Begin, which it reaches for |
| 83 | // EVERY well-formed address, so whether an address signs in at Keymail |
| 84 | // or by emailed link depends on its domain alone, never on membership. |
| 85 | // |
| 86 | // - A Keymail address (keymail.dev itself, or a domain delegating to |
| 87 | // Keymail with a `_keymail` TXT record) goes to Keymail, member or |
| 88 | // not. With SigninScreen on, Begin continues on the door |
| 89 | // (/signin?continue=), whose meta refresh leaves for Keymail, so |
| 90 | // form-action stays 'self' (Safari applies it to a form's whole |
| 91 | // redirect chain). Admission is rastrillo's Authorize after Keymail |
| 92 | // has verified the address (a member, or a guest holding a live |
| 93 | // pending-join row), and its refusal is the door saying so (refused). |
| 94 | // - Any other address is answered ?sent=1, and a link is mailed only |
| 95 | // when mayRequestLink allowed it for this request (ruling 12's |
| 96 | // budgets included) and authorize admits the address. mailQueue |
| 97 | // decides that after the response, in a worker, so not even the |
| 98 | // response time differs (signin_mail.go). |
| 99 | // |
| 100 | // Begin's own answers (sent, a malformed address, the rate budget, a |
| 101 | // failure of its own) are passed on as they are: none of them depends on |
| 102 | // who the address is, because Authorize runs in the mail worker, not in |
| 103 | // Begin. Membership of a specific address is not a secret Calls keeps at |
| 104 | // this form (spec §3.2), but the choice of ceremony must still not |
| 105 | // depend on it: it used to set force=1 for a permitted address only, |
| 106 | // which kept Keymail out of Calls altogether (Paul, 2026-10-06: "I do |
| 107 | // want it to use keymail"). force now arrives only from the door |
| 108 | // rastrillo lands a failed Keymail exchange on (?force=1&err=keymail), |
| 109 | // and asks for an emailed link instead. |
| 110 | // |
| 111 | // Until the smart door, a wrapper (sameAnswer, Slides' shape) rewrote |
| 112 | // every Begin problem but address and rate to ?sent=1. It hid nothing a |
| 113 | // member could not already tell, and it dropped what the door now needs |
| 114 | // on the way back: force, a step-up's reauth=1, return_to and Sent's |
| 115 | // attempt. Slides deleted its copy on review (Fable on oficina/slides |
| 116 | // #49); this is the same deletion. |
| 117 | func (a *app) gateBegin(next http.HandlerFunc) http.HandlerFunc { |
| 118 | return func(w http.ResponseWriter, r *http.Request) { |
| 119 | _ = r.ParseForm() |
| 120 | if a.team != nil && !a.teamJoinCookieStands(w, r) { |
| 121 | return |
| 122 | } |
| 123 | address := r.FormValue("address") |
| 124 | // Syntax first, before mayRequestLink writes a pending row for a |
| 125 | // cookie holder: a string that is not an email address is no |
| 126 | // address to keep. Whether a string is an email address says |
| 127 | // nothing about who is on the team, so this answer is no oracle. |
| 128 | // It is keymail's own check, the one Begin would make, and it |
| 129 | // lands where Begin's would (badAddress). |
| 130 | if _, _, err := signin.SplitAddress(strings.TrimSpace(address)); err != nil { |
| 131 | http.Redirect(w, r, badAddress(r), http.StatusSeeOther) |
| 132 | return |
| 133 | } |
| 134 | may := a.mayRequestLink(w, r, address) |
| 135 | next(w, r.WithContext(context.WithValue(r.Context(), mayMailKey{}, may))) |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // badAddress is the door's answer to a malformed address, in Begin's own |
| 140 | // shape (rastrillo's problemURL): ?err=address, keeping a failed |
| 141 | // Keymail's force=1 and a step-up's reauth=1. return_to is put back by |
| 142 | // beginSignin, which took it off the form. |
| 143 | func badAddress(r *http.Request) string { |
| 144 | q := url.Values{"err": {"address"}} |
| 145 | if r.PostFormValue("force") != "" { |
| 146 | q.Set("force", "1") |
| 147 | } |
| 148 | if r.PostFormValue("reauth") == "1" { |
| 149 | q.Set("reauth", "1") |
| 150 | } |
| 151 | return signinPath + "?" + q.Encode() |
| 152 | } |
| 153 | |
| 154 | // mayMailKey carries gateBegin's mayRequestLink answer to mailQueue, |
| 155 | // through Begin, on the request context. |
| 156 | type mayMailKey struct{} |
| 157 | |
| 158 | // mayRequestLink decides whether a link may be mailed (ruling 12). A |
| 159 | // member address always may. Any other address may only when the |
| 160 | // browser carries a valid pending-join cookie for a live link, within |
| 161 | // two budgets: five attempts per link and ten across all links per |
| 162 | // fifteen minutes. |
| 163 | // |
| 164 | // It runs on the response path, so its WORK must not depend on who the |
| 165 | // address is (Astra on #25, round 3, P1: over budget, a member wrote a |
| 166 | // pending row while an outsider wrote a log line and returned — |
| 167 | // 0.4–0.65 ms against 77–78 ms). Whoever the address names, a live |
| 168 | // cookie costs the same: the link lookup, and the pending_joins row, |
| 169 | // written for an over-budget outsider too. Only the in-memory budget |
| 170 | // counters, charged for outsiders as before, differ. Nothing is logged |
| 171 | // here: an over-budget attempt is counted (overBudget) and the hourly |
| 172 | // sweep reports the count. |
| 173 | // |
| 174 | // The row an over-budget outsider gets admits nothing new by mail: the |
| 175 | // answer this returns still says no, so no link is sent (the budgets are |
| 176 | // about mail). It does let a Keymail sign-in through that link's guest |
| 177 | // path, which the budgets never governed. |
| 178 | func (a *app) mayRequestLink(w http.ResponseWriter, r *http.Request, address string) bool { |
| 179 | address = normalizeAddress(address) |
| 180 | member := a.allowNow().allows(address) |
| 181 | ck, hasCookie := a.readJoinCookie(r) |
| 182 | if !hasCookie { |
| 183 | return member |
| 184 | } |
| 185 | link, m, live, err := a.store.liveLinkByHash(r.Context(), ck.TokenHash) |
| 186 | if err != nil { |
| 187 | a.logger.Error("calls: link for cookie", "err", err) |
| 188 | return member |
| 189 | } |
| 190 | if !live { |
| 191 | return member |
| 192 | } |
| 193 | if a.team != nil && a.hostAccess(r.Context(), m).State() != roster.Member { |
| 194 | // Team mode: a link whose host does not stand now admits nobody |
| 195 | // new, so it is answered as a dead link is (team_host.go). The |
| 196 | // work does not depend on the address. |
| 197 | return member |
| 198 | } |
| 199 | may := true |
| 200 | if !member { |
| 201 | now := a.store.now() |
| 202 | // The per-link budget is consulted first: a link already over |
| 203 | // its own budget must not keep charging the shared pool. |
| 204 | if !a.linkBudget.allow(ck.TokenHash, now) || !a.outsiderBudget.allow("all", now) { |
| 205 | a.overBudget.Add(1) |
| 206 | may = false |
| 207 | } |
| 208 | } |
| 209 | if address == "" { |
| 210 | return member |
| 211 | } |
| 212 | if err := a.store.writePending(r.Context(), address, link); err != nil { |
| 213 | a.logger.Error("calls: write pending join", "err", err) |
| 214 | return member |
| 215 | } |
| 216 | return may |
| 217 | } |
| 218 | |
| 219 | type personCtxKey struct{} |
| 220 | |
| 221 | // requirePerson runs behind RequireSession: it maps the session subject |
| 222 | // (the verified address; sessions.UserID would return 0, false) to a |
| 223 | // persons row, creating it on first sign-in. |
| 224 | func (a *app) requirePerson(next http.Handler) http.Handler { |
| 225 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 226 | s, ok := sessions.Current(r) |
| 227 | if !ok || s.Subject == "" { |
| 228 | a.logger.Error("calls: session with no subject reached requirePerson", "path", r.URL.Path) |
| 229 | a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| 230 | return |
| 231 | } |
| 232 | if a.team != nil { |
| 233 | // Team mode: the roster's standing, asked once and carried on |
| 234 | // the request (team_access.go). |
| 235 | a.teamRequirePerson(w, r, s, next) |
| 236 | return |
| 237 | } |
| 238 | p, err := a.personForSession(r.Context(), s) |
| 239 | if errors.Is(err, errHomeRemoved) { |
| 240 | // A Home identity that is definitely no longer admitted: end |
| 241 | // the session and say so, rather than a 404 whose "Sign in" |
| 242 | // would pass straight back through the same live session |
| 243 | // (the loop Astra found in Docs #65 and Sheets #39). |
| 244 | a.endRemovedSession(w, r) |
| 245 | return |
| 246 | } |
| 247 | if errors.Is(err, errHomeUnavailable) { |
| 248 | // Storage, not identity: a retryable 503, never the 404 below, |
| 249 | // which the sign-in door's admission probe would read as a |
| 250 | // refusal and answer by ending the session |
| 251 | // (signin_admission.go). Team mode already answers so. |
| 252 | a.homeUnavailable(w, r) |
| 253 | return |
| 254 | } |
| 255 | if errors.Is(err, errHomeIdentity) { |
| 256 | a.notFound(w, r) |
| 257 | return |
| 258 | } |
| 259 | if err != nil { |
| 260 | a.logger.Error("calls: ensure person", "err", err) |
| 261 | a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| 262 | return |
| 263 | } |
| 264 | next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), personCtxKey{}, p))) |
| 265 | }) |
| 266 | } |
| 267 | |
| 268 | func currentPerson(r *http.Request) (Person, bool) { |
| 269 | p, ok := r.Context().Value(personCtxKey{}).(Person) |
| 270 | return p, ok |
| 271 | } |
| 272 | |
| 273 | // requireMember is spec §2.5's first row: current member standing. |
| 274 | func (a *app) requireMember(next http.Handler) http.Handler { |
| 275 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 276 | if a.team != nil { |
| 277 | a.requireTeamMember(w, r, next) |
| 278 | return |
| 279 | } |
| 280 | p, ok := currentPerson(r) |
| 281 | if !ok || !a.isMember(p) { |
| 282 | a.notFound(w, r) |
| 283 | return |
| 284 | } |
| 285 | next.ServeHTTP(w, r) |
| 286 | }) |
| 287 | } |
| 288 | |
| 289 | // signinAgain is the door with a problem (extra, "err=removed"), |
| 290 | // keeping whatever page the person was on their way to: the remembered |
| 291 | // page, as return_to, so the door's next form posts it again. |
| 292 | func (a *app) signinAgain(r *http.Request, extra string) string { |
| 293 | q := url.Values{} |
| 294 | if ret, ok := a.rememberedReturn(r); ok { |
| 295 | q.Set("return_to", ret) |
| 296 | } |
| 297 | out := signinPath + "?" + extra |
| 298 | if enc := q.Encode(); enc != "" { |
| 299 | out += "&" + enc |
| 300 | } |
| 301 | return out |
| 302 | } |
| 303 | |
| 304 | // continueSignedIn is SignedInPath. Task 6 adds the pending-join branch |
| 305 | // in front; this slice's first version routes members to the list and |
| 306 | // everyone else to /welcome. |
| 307 | func (a *app) continueSignedIn(w http.ResponseWriter, r *http.Request) { |
| 308 | p, ok := currentPerson(r) |
| 309 | if !ok { |
| 310 | a.ErrorPage(w, r, http.StatusInternalServerError, "") |
| 311 | return |
| 312 | } |
| 313 | if dest, handled := a.continuePending(w, r, p); handled { |
| 314 | if dest == "" { |
| 315 | // Team mode answered it (a retryable 503). |
| 316 | return |
| 317 | } |
| 318 | http.Redirect(w, r, dest, http.StatusSeeOther) |
| 319 | return |
| 320 | } |
| 321 | // The invitation a join cookie names, when no pending join answered |
| 322 | // for it: an Oficina ID sign-in from the join cookie's door lands here |
| 323 | // (signin_admission.go's oficinaJoinLanding). |
| 324 | if a.continueInvitation(w, r) { |
| 325 | return |
| 326 | } |
| 327 | // Where the person was going when they were asked to sign in |
| 328 | // (signin_return.go), spent either way. |
| 329 | ret, remembered := a.rememberedReturn(r) |
| 330 | a.forgetReturn(w) |
| 331 | if remembered { |
| 332 | http.Redirect(w, r, ret, http.StatusSeeOther) |
| 333 | return |
| 334 | } |
| 335 | // In team mode Unknown goes to the list too, which says it is |
| 336 | // partial; only a definite non-member is sent to /welcome. |
| 337 | if a.memberState(r.Context(), p) != roster.NotMember { |
| 338 | http.Redirect(w, r, "/", http.StatusSeeOther) |
| 339 | return |
| 340 | } |
| 341 | http.Redirect(w, r, "/welcome", http.StatusSeeOther) |
| 342 | } |
| 343 | |
| 344 | // continuePending is /continue's first branch (spec §3.2): the most |
| 345 | // recent unexpired pending row for this person, re-checked against its |
| 346 | // link and meeting in one transaction with the grant, then deleted. |
| 347 | func (a *app) continuePending(w http.ResponseWriter, r *http.Request, p Person) (string, bool) { |
| 348 | a.clearJoinCookie(w) |
| 349 | pend, ok, err := a.store.latestPending(r.Context(), p.Email) |
| 350 | if err != nil { |
| 351 | a.logger.Error("calls: latest pending", "err", err) |
| 352 | return "", false |
| 353 | } |
| 354 | if !ok { |
| 355 | return "", false |
| 356 | } |
| 357 | if a.team != nil { |
| 358 | return a.teamContinuePending(w, r, p, pend) |
| 359 | } |
| 360 | dest, err := a.store.consumePending(r.Context(), p, pend, a.isMember(p)) |
| 361 | if err != nil { |
| 362 | a.logger.Error("calls: consume pending", "err", err) |
| 363 | return "", false |
| 364 | } |
| 365 | return dest, dest != "" |
| 366 | } |
| 367 | |
| 368 | func (a *app) welcome(w http.ResponseWriter, r *http.Request) { |
| 369 | p, _ := currentPerson(r) |
| 370 | render(w, "welcome", a.page(r, titled("You’re signed in"), map[string]any{"Email": p.shown()})) |
| 371 | } |
| 372 | |