| 1 | // auth.go is sign-in: rastrillo/auth's plugin, the allowlist that gates |
| 2 | // who is mailed and who is admitted, and the mapping from a verified |
| 3 | // address to this app's own users row. |
| 4 | // |
| 5 | // Per spec §6.1 a single instance signs people in itself, with no |
| 6 | // password and no credential enrolled here. How an address proves |
| 7 | // itself depends on its domain alone, through rastrillo/auth's |
| 8 | // classification: an address whose domain runs Keymail (keymail.dev |
| 9 | // itself, or a domain delegating through a `_keymail` TXT record) |
| 10 | // signs in at Keymail, where its passkey lives; every other address is |
| 11 | // emailed a single-use link. Paul ruled on 2026-10-06 that Slides uses |
| 12 | // Keymail. Never a passkey enrolled at this instance: its relying party |
| 13 | // id would derive from this host, so a person on three team instances |
| 14 | // would hold three credentials for one app. Keymail keeps the |
| 15 | // credential at Keymail's own origin, and a magic link enrols nothing. |
| 16 | // |
| 17 | // Admission is a separate question from the ceremony, asked at two |
| 18 | // places that cannot be observed from the form: the mail worker |
| 19 | // (mailQueue — a non-permitted address is never mailed) and |
| 20 | // rauth's Authorize, after Keymail or the link has verified the |
| 21 | // address. Neither changes what POST /signin answers (see the note on |
| 22 | // POST /signin, below). |
| 23 | // |
| 24 | // This file is a port of oficina/docs' internal/docs/auth.go, adapted |
| 25 | // to rastrillo v0.26.0 and to Config.AllowedAddresses being a slice |
| 26 | // rather than a comma-separated string. Spec §6.1 names the second copy |
| 27 | // as the extraction trigger: the next app to need this should get it |
| 28 | // from rastrillo, not from a third copy. |
| 29 | package slides |
| 30 | |
| 31 | import ( |
| 32 | "bytes" |
| 33 | "context" |
| 34 | "crypto/sha256" |
| 35 | "database/sql" |
| 36 | "encoding/base64" |
| 37 | "encoding/json" |
| 38 | "errors" |
| 39 | "fmt" |
| 40 | "log/slog" |
| 41 | "math" |
| 42 | "net/http" |
| 43 | "net/url" |
| 44 | "strings" |
| 45 | "time" |
| 46 | |
| 47 | "amadan.net/oficina/estilo.git/chrome" |
| 48 | "amadan.net/oficina/home/connect" |
| 49 | "amadan.net/oficina/home/connect/linkstore" |
| 50 | "amadan.net/oficina/home/handoff" |
| 51 | "amadan.net/oficina/home/handoff/seal" |
| 52 | "amadan.net/oficina/slides/internal/slides/present" |
| 53 | rauth "amadan.net/rastrillo/rastrillo/auth" |
| 54 | "amadan.net/rastrillo/rastrillo/mail" |
| 55 | "amadan.net/rastrillo/rastrillo/sessions" |
| 56 | "gorm.io/gorm" |
| 57 | "gorm.io/gorm/clause" |
| 58 | ) |
| 59 | |
| 60 | // signinPath is where the sign-in door lives: connect's SigninPath, which |
| 61 | // newAuthPlugin passes as rauth's SigninPath, so every outcome rauth |
| 62 | // redirects back with lands on the door app.go mounts. |
| 63 | const signinPath = connect.SigninPath |
| 64 | |
| 65 | // devInstanceKey is resolveInstanceKey's fallback when Env is |
| 66 | // development and Config.InstanceKey is empty. It is not a secret: it |
| 67 | // is a fixed, public string, exactly as dangerous — and exactly as |
| 68 | // acceptable — as rastrillo/auth's own refused empty key would be, |
| 69 | // except spelled out here instead of left implicit, and it never seals |
| 70 | // anything outside a throwaway development database. |
| 71 | const devInstanceKey = "slides-development-instance-key-not-a-secret" |
| 72 | |
| 73 | // resolveInstanceKey applies Config.InstanceKey's fail-closed rule: |
| 74 | // non-empty always wins; empty is fine only in development; anywhere |
| 75 | // else it is a startup refusal. |
| 76 | func resolveInstanceKey(cfg Config) (string, error) { |
| 77 | if key := strings.TrimSpace(cfg.InstanceKey); key != "" { |
| 78 | return key, nil |
| 79 | } |
| 80 | if cfg.development() { |
| 81 | return devInstanceKey, nil |
| 82 | } |
| 83 | return "", fmt.Errorf("slides: Config.InstanceKey is empty and Env is %q, not %q — refusing to start with no seal for the sign-in link's pending blob; set $SLIDES_INSTANCE_KEY", cfg.Env, EnvDevelopment) |
| 84 | } |
| 85 | |
| 86 | // resolveMailer applies Config.Mailer's fail-closed rule: an explicit |
| 87 | // Mailer always wins; nil falls back to rastrillo/mail's logging sender |
| 88 | // in development, and is a startup refusal anywhere else. |
| 89 | func resolveMailer(cfg Config, logger *slog.Logger) (mail.Sender, error) { |
| 90 | if cfg.Mailer != nil { |
| 91 | return cfg.Mailer, nil |
| 92 | } |
| 93 | if !cfg.development() { |
| 94 | return nil, fmt.Errorf("slides: mail is not configured and Env is %q, not %q — refusing to start: a sign-in that cannot send its link is not sign-in. Switch the app to CARLOS mail submission (the agent then sets $CARLOS_MAIL=submit), run `carlos email enable` for this app and let $CARLOS_SMTP_HOST supply the relay, or set $SLIDES_SMTP_HOST and $SLIDES_SMTP_FROM", cfg.Env, EnvDevelopment) |
| 95 | } |
| 96 | // mail.Logged labels every send loudly itself — see its own doc |
| 97 | // comment. Never reached outside development. |
| 98 | return mail.Logged(logger), nil |
| 99 | } |
| 100 | |
| 101 | // normalizeAddress puts address into the one form the allowlist |
| 102 | // compares and the users table stores: trimmed, lowercased. Shared by |
| 103 | // the allowlist and by ensureUser so the two can never drift into |
| 104 | // comparing differently-normalized forms of the same address. |
| 105 | func normalizeAddress(address string) string { |
| 106 | return strings.ToLower(strings.TrimSpace(address)) |
| 107 | } |
| 108 | |
| 109 | // allowlist is Config.AllowedAddresses, parsed and normalized. |
| 110 | // |
| 111 | // A nil addrs map means "admit every address" — resolveAllowlist's |
| 112 | // development-only default, spelled out here rather than left as an |
| 113 | // accidental nil. A non-nil one means "admit nothing but exactly this |
| 114 | // set"; resolveAllowlist returns a non-nil-but-empty map only in team |
| 115 | // mode (admit nobody locally: the roster decides, and Home signs people |
| 116 | // in), since an empty parse outside development is otherwise a refusal |
| 117 | // rather than a value. |
| 118 | type allowlist struct { |
| 119 | addrs map[string]struct{} |
| 120 | } |
| 121 | |
| 122 | // allows reports whether address may sign in. |
| 123 | func (a allowlist) allows(address string) bool { |
| 124 | if a.addrs == nil { |
| 125 | return true |
| 126 | } |
| 127 | _, ok := a.addrs[normalizeAddress(address)] |
| 128 | return ok |
| 129 | } |
| 130 | |
| 131 | // resolveAllowlist applies Config.AllowedAddresses' fail-closed rule. |
| 132 | // See that field's own doc comment for why an empty list outside |
| 133 | // development is a refusal rather than "admit nobody". |
| 134 | func resolveAllowlist(cfg Config) (allowlist, error) { |
| 135 | addrs := make(map[string]struct{}) |
| 136 | for _, addr := range cfg.AllowedAddresses { |
| 137 | if addr = normalizeAddress(addr); addr != "" { |
| 138 | addrs[addr] = struct{}{} |
| 139 | } |
| 140 | } |
| 141 | if len(addrs) > 0 { |
| 142 | return allowlist{addrs: addrs}, nil |
| 143 | } |
| 144 | if cfg.Team != nil { |
| 145 | // Team mode: the roster decides standing, and the list is only |
| 146 | // local sign-in's admission. Empty admits nobody locally, in |
| 147 | // every Env: a team instance never takes the development |
| 148 | // default that admits everyone. |
| 149 | return allowlist{addrs: addrs}, nil |
| 150 | } |
| 151 | if cfg.development() { |
| 152 | return allowlist{}, nil // addrs stays nil: admit everyone |
| 153 | } |
| 154 | return allowlist{}, fmt.Errorf("slides: Config.AllowedAddresses is empty and Env is %q, not %q — refusing to start with no allowlist: an instance admitting nobody is indistinguishable from one working correctly, since every POST /signin answers the same 303 either way; set $SLIDES_ALLOWED_ADDRESSES", cfg.Env, EnvDevelopment) |
| 155 | } |
| 156 | |
| 157 | // POST /signin is rauth.Auth.Begin for EVERY address, permitted or not |
| 158 | // (through beginSignin, signin_return.go, which only keeps the page), |
| 159 | // so what the form answers depends on the address's domain and never on |
| 160 | // the allowlist. That is the whole guarantee, and any difference at all |
| 161 | // would turn this endpoint into a membership oracle, letting anyone learn |
| 162 | // who this instance admits by watching how its answers differ. |
| 163 | // |
| 164 | // Every address therefore takes the same road through Begin: the same |
| 165 | // per-IP and per-address budgets, the same classification, the same |
| 166 | // ceremony. |
| 167 | // |
| 168 | // - A Keymail address — permitted or not — goes to Keymail. With |
| 169 | // SigninScreen on, Begin continues on the door (/signin?continue=), |
| 170 | // whose meta refresh leaves for Keymail, never a 303 off this origin |
| 171 | // (Safari applies form-action to the whole redirect chain of a form |
| 172 | // POST, and ours is 'self'). Whether the address may sign in here is |
| 173 | // asked only after Keymail has verified it, by rauth's Authorize, and |
| 174 | // a refusal is the sign-in door saying so (refused, rauth's Refused |
| 175 | // hook) — told only to somebody who has just proved they hold the |
| 176 | // address. |
| 177 | // - Any other address is answered `303 /signin?sent=1&attempt=…`, and a |
| 178 | // link is mailed only if it is permitted: mailQueue drops the rest, |
| 179 | // after the response, so not even its timing differs (mailqueue.go). |
| 180 | // So this instance's sending identity is no open relay for whatever |
| 181 | // a stranger types, which is why a gate exists at all |
| 182 | // (rauth.Config.Authorize alone runs only after a link was mailed |
| 183 | // and clicked). |
| 184 | // |
| 185 | // force=1 is passed through as the form sent it: only the recovery form |
| 186 | // carries it (a failed Keymail exchange lands on `?force=1&err=keymail`), |
| 187 | // and it selects an emailed link over Keymail, so a person whose Keymail |
| 188 | // failed is never stuck. |
| 189 | // |
| 190 | // No outcome of Begin depends on admission: both kinds of address spend |
| 191 | // the same budgets and parse the same way, and the send that only a |
| 192 | // permitted address reaches happens in mailQueue's worker, after the |
| 193 | // response, where its failures are logged rather than answered. So |
| 194 | // Begin's own problems (?err=rate, ?err=address) are answered as they |
| 195 | // are, the same for an address on the list and one off it. Slides used to |
| 196 | // rewrite them as Sent (sameAnswer), which told a mistyped address "We |
| 197 | // sent a link" and dropped force=1 after a failed Keymail; it was removed |
| 198 | // with the smart door. |
| 199 | |
| 200 | // refused is rauth's Refused hook: Keymail or an emailed link verified |
| 201 | // the address and the allowlist does not hold it. It answers with the |
| 202 | // sign-in door, the refusal in the screen's app-problem slot with the |
| 203 | // email field, in a 403 — no session is minted, and rauth has already |
| 204 | // ended the attempt and set any cookies it clears. |
| 205 | // |
| 206 | // Rendered, not redirected to ?err=refused: a query parameter is |
| 207 | // something anybody can type, and then the sentence that means "you |
| 208 | // proved this address and it is not admitted" could be shown to anybody |
| 209 | // about nothing (Astra on #20, round 3). Only this hook can say it, and |
| 210 | // rauth calls it only after the address is proved, so it is no oracle. |
| 211 | func (a *app) refused(w http.ResponseWriter, r *http.Request, _ rauth.Identity) { |
| 212 | a.signinDoorStatus(w, withRefusal(r), http.StatusForbidden) |
| 213 | } |
| 214 | |
| 215 | // renderConfirm is rauth's RenderConfirm: the page an emailed link opens |
| 216 | // on (GET /auth/verify), the door, whose SigninState answers StepConfirm |
| 217 | // on this request alone, with one Sign in button that POSTs the token |
| 218 | // back, where rauth spends it. The GET spends nothing, so a mail-security |
| 219 | // scanner that fetches every link in an inbound message cannot spend this |
| 220 | // one (#64). rauth has already set no-store, Referrer-Policy: |
| 221 | // strict-origin (the URL is a live credential) and the framing refusals; |
| 222 | // nothing here replaces them. |
| 223 | func (a *app) renderConfirm(w http.ResponseWriter, r *http.Request, _ rauth.ConfirmPageData) { |
| 224 | a.signinDoor(w, r) |
| 225 | } |
| 226 | |
| 227 | // newAuthPlugin wires rastrillo/auth per SKILL.md §5: exactly one *Auth |
| 228 | // per process (the rate limiter's budget lives on the value, so a plugin |
| 229 | // per request would silently have no rate limiting at all), Origin as |
| 230 | // both the emailed link's base and the cookie decision, InstanceKey and |
| 231 | // Mailer already resolved and fail-closed above. |
| 232 | // |
| 233 | // Authorize is list.allows as well as mailQueue — two checks |
| 234 | // defending two different things: mailQueue stops the mail, |
| 235 | // Authorize stops a session being minted for a non-permitted address, |
| 236 | // whether Keymail verified it or a link was somehow issued for it |
| 237 | // (mailed before the allowlist changed, say). SecondFactor stays nil, |
| 238 | // per this file's package comment. |
| 239 | // |
| 240 | // cfg must be the resolved Config (config.go's resolve), not a |
| 241 | // caller's raw one: Origin, InstanceKey and Mailer are all required |
| 242 | // here and all three may have been filled in by a development default. |
| 243 | // |
| 244 | // SigninPath is passed explicitly even though signinPath is already |
| 245 | // rauth's own zero-value default. rauth redirects every outcome to its |
| 246 | // copy of that literal and app.go mounts the page at ours; saying it |
| 247 | // once, out loud, is what keeps the two from drifting silently if |
| 248 | // either default ever changes. |
| 249 | // |
| 250 | // a supplies the two pages rauth asks of the app: the door a verified |
| 251 | // but refused address is shown (app.refused) and the door an emailed |
| 252 | // link opens on (app.renderConfirm). Only their method values are taken |
| 253 | // here; newApp fills the rest of *a in after this returns. |
| 254 | func newAuthPlugin(cfg Config, writer *sql.DB, list allowlist, mailer *mailQueue, a *app) (*rauth.Auth, error) { |
| 255 | signedInPath := landedPath |
| 256 | if cfg.Home != nil { |
| 257 | signedInPath = connect.LocalCompletePath |
| 258 | } |
| 259 | return rauth.New(rauth.Config{ |
| 260 | SignedInPath: signedInPath, |
| 261 | DB: writer, |
| 262 | Origin: cfg.Origin, |
| 263 | InstanceKey: cfg.InstanceKey, |
| 264 | Mailer: mailer, |
| 265 | Subject: chrome.EmailSubject("Slides"), |
| 266 | Authorize: list.allows, |
| 267 | // A verified address the allowlist does not hold gets the door, |
| 268 | // with the refusal on it, in rauth's own 403 (app.refused). |
| 269 | Refused: a.refused, |
| 270 | // GET /auth/verify spends nothing: it opens the door with one |
| 271 | // Sign in button that POSTs the link back, so a mail scanner's |
| 272 | // fetch cannot spend it (app.renderConfirm). |
| 273 | RenderConfirm: a.renderConfirm, |
| 274 | // No proof-of-work on the sign-in form. Slides never had one: |
| 275 | // rauth's per-IP and per-address budgets and mailQueue's |
| 276 | // allowlist check are what stand between a stranger and the |
| 277 | // mailer. ProofOff keeps today's behaviour; wiring a pow.Guard |
| 278 | // is a decision of its own (schema, assets, a form that needs |
| 279 | // JavaScript, which the door works without). |
| 280 | ProofOff: true, |
| 281 | // The smart door (Home spec 2026-11-19-smart-door.md): rastrillo's |
| 282 | // screen, one way in per page. Every outcome, chooser link and |
| 283 | // Forget lands on /signin, which with Home configured is connect's |
| 284 | // SigninDoor (home/connect MIGRATING.md, step 6). |
| 285 | SigninScreen: true, |
| 286 | SigninOneWay: true, |
| 287 | SigninPath: connect.SigninPath, |
| 288 | ForgetPath: signinForgetPath, |
| 289 | // Nil in every deployment (Config.KeymailServers). |
| 290 | KeymailServers: cfg.KeymailServers, |
| 291 | Logger: cfg.Logger, |
| 292 | }) |
| 293 | } |
| 294 | |
| 295 | // presenceColours is the palette ensureUser assigns from — spec §3.2's |
| 296 | // coloured cursor and block outline. Six, so a small team rarely |
| 297 | // collides, and never the only carrier of who is who: the name rides |
| 298 | // beside the colour everywhere it is drawn. |
| 299 | var presenceColours = []string{ |
| 300 | "#2f6f4f", "#8a4b2a", "#3a4f8a", "#7a2f5f", "#4a5a2a", "#2a5f7a", |
| 301 | } |
| 302 | |
| 303 | // ensureUser maps a verified address to this app's own users row, |
| 304 | // creating it on first sign-in. It is the mapping SKILL.md §5 insists |
| 305 | // on: under rastrillo/auth the session Subject is the email, so |
| 306 | // sessions.UserID answers (0, false) and scoping on it would file every |
| 307 | // deck under user_id = 0. |
| 308 | // |
| 309 | // Read first, and only write when the read came back empty. This runs |
| 310 | // on every authenticated request — currentUser calls it before any |
| 311 | // handler does its own work — and SQLite has one writer: an |
| 312 | // unconditional upsert here would open a write transaction per page |
| 313 | // view, serialising every reader in the app behind a statement whose |
| 314 | // answer is almost always "this row already exists". The read goes to |
| 315 | // the reader pool (db.Open routes per statement), so the steady state |
| 316 | // costs one indexed SELECT and no lock at all. |
| 317 | // |
| 318 | // The write, when it happens, is still ON CONFLICT DO NOTHING on the |
| 319 | // unique Email index rather than a bare INSERT: the read above is not a |
| 320 | // lock, so two requests arriving together on a person's very first |
| 321 | // sign-in can both miss and both try to insert. DO NOTHING makes the |
| 322 | // loser a no-op instead of an error, and the read-back below gives both |
| 323 | // of them the same row. |
| 324 | // The second return says whether THIS call created the row — what |
| 325 | // makes a first sign-in distinguishable from every later request, and |
| 326 | // so where the sample deck is seeded (sample.go). It is read off the |
| 327 | // insert's own RowsAffected rather than off "we took the insert path", |
| 328 | // because DO NOTHING means both racing requests take that path and only |
| 329 | // one of them writes. |
| 330 | func ensureUser(ctx context.Context, g *gorm.DB, address string) (User, bool, error) { |
| 331 | email := normalizeAddress(address) |
| 332 | if email == "" { |
| 333 | return User{}, false, errors.New("slides: cannot map an empty address to a user") |
| 334 | } |
| 335 | |
| 336 | var found User |
| 337 | err := g.WithContext(ctx).Where("email = ?", email).Take(&found).Error |
| 338 | switch { |
| 339 | case err == nil: |
| 340 | return found, false, nil |
| 341 | case !errors.Is(err, gorm.ErrRecordNotFound): |
| 342 | return User{}, false, fmt.Errorf("slides: load user %q: %w", email, err) |
| 343 | } |
| 344 | |
| 345 | // First sight of this address: create the row, then read it back |
| 346 | // rather than trusting the insert's own return — DO NOTHING leaves |
| 347 | // ID at zero when a concurrent request won the race. |
| 348 | created := User{Email: email, Colour: colourFor(email)} |
| 349 | res := g.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&created) |
| 350 | if res.Error != nil { |
| 351 | return User{}, false, fmt.Errorf("slides: create user %q: %w", email, res.Error) |
| 352 | } |
| 353 | if err := g.WithContext(ctx).Where("email = ?", email).Take(&found).Error; err != nil { |
| 354 | return User{}, false, fmt.Errorf("slides: load user %q: %w", email, err) |
| 355 | } |
| 356 | return found, res.RowsAffected == 1, nil |
| 357 | } |
| 358 | |
| 359 | // colourFor picks a stable presence colour for an address: the same |
| 360 | // person gets the same colour on every instance and after every |
| 361 | // restart, which is what makes a colour worth recognising at all. |
| 362 | func colourFor(email string) string { |
| 363 | var sum uint32 |
| 364 | for _, b := range []byte(email) { |
| 365 | sum = sum*31 + uint32(b) |
| 366 | } |
| 367 | return presenceColours[int(sum%uint32(len(presenceColours)))] |
| 368 | } |
| 369 | |
| 370 | // currentUser is the users row for whoever is signed in on r, created |
| 371 | // on first sight. Past RequireSession the second return is always true; |
| 372 | // it is false for a signed-out request, or when the row could not be |
| 373 | // read (logged, never surfaced as a half-signed-in page). |
| 374 | // |
| 375 | // It is also where a first sign-in seeds the sample deck (sample.go) — |
| 376 | // right beside the insert that makes the row, because "the users row |
| 377 | // was just created" is the only place in the app that knows a person is |
| 378 | // new. The seed is guarded by a second check for a deck this person |
| 379 | // already owns, so no arrangement of races or restores can produce two |
| 380 | // welcome decks, and a failure to build one never stops a sign-in. |
| 381 | // |
| 382 | // sessions.Current(r).Subject, never sessions.UserID — see ensureUser. |
| 383 | // |
| 384 | // IT IS ALSO THE ADMISSION RECHECK (spec §6.1, codex 6). The allowlist |
| 385 | // used to gate only the minting of a session: past that, a session was |
| 386 | // good until it expired, and rastrillo's RequireSession asks nothing |
| 387 | // about admission. So taking an address out of |
| 388 | // SLIDES_ALLOWED_ADDRESSES and restarting left every browser that |
| 389 | // person was already signed in on working exactly as before — the one |
| 390 | // control this instance has for saying "not any more" did not say it. |
| 391 | // |
| 392 | // It takes the ResponseWriter for that reason: the honest answer to a |
| 393 | // session whose address is no longer admitted is to end it, here, |
| 394 | // rather than to let the request through or to fail it as an internal |
| 395 | // error. offboard does the rest. |
| 396 | func (a *app) currentUser(w http.ResponseWriter, r *http.Request) (User, sessionOutcome) { |
| 397 | s, ok := sessions.Current(r) |
| 398 | if !ok || s.Subject == "" { |
| 399 | return User{}, sessionNone |
| 400 | } |
| 401 | if a.team != nil { |
| 402 | // Team mode: the roster replaces the allowlist recheck below. |
| 403 | // The user comes back carrying their standing, asked of the |
| 404 | // roster on this request (team_access.go). |
| 405 | return a.teamCurrentUser(w, r, s) |
| 406 | } |
| 407 | if s.Method == connect.HomeMethod { |
| 408 | u, err := a.homeUser(r, s) |
| 409 | if err != nil { |
| 410 | if errors.Is(err, linkstore.ErrRefused) || errors.Is(err, errHomeIdentity) { |
| 411 | a.revokeHome(w, r, s.Subject) |
| 412 | return User{}, sessionOffboarded |
| 413 | } |
| 414 | a.logger.Error("slides: resolve Home user", "err", err) |
| 415 | return User{}, sessionNone |
| 416 | } |
| 417 | return u, sessionOK |
| 418 | } |
| 419 | if !a.allowed.allows(s.Subject) { |
| 420 | a.offboard(w, r, s.Subject) |
| 421 | return User{}, sessionOffboarded |
| 422 | } |
| 423 | u, created, err := ensureUser(r.Context(), a.db.G, s.Subject) |
| 424 | if err != nil { |
| 425 | a.logger.Error("slides: resolve current user", "err", err) |
| 426 | return User{}, sessionNone |
| 427 | } |
| 428 | if created { |
| 429 | if has, err := hasDeck(r.Context(), a.db.G, u); err != nil { |
| 430 | a.logger.Error("slides: check for an existing deck before seeding", "user", u.ID, "err", err) |
| 431 | } else if !has { |
| 432 | a.seedSampleDeckFor(r.Context(), u) |
| 433 | } |
| 434 | } |
| 435 | return u, sessionOK |
| 436 | } |
| 437 | |
| 438 | // sessionOutcome is what currentUser concluded about a request, and it |
| 439 | // is three answers rather than two because one of them means "this |
| 440 | // request has already been answered". |
| 441 | type sessionOutcome int |
| 442 | |
| 443 | const ( |
| 444 | // sessionOK: there is a person, and the second return of |
| 445 | // currentUser is their row. |
| 446 | sessionOK sessionOutcome = iota |
| 447 | // sessionNone: no session, or the row could not be read. Never |
| 448 | // reached past RequireSession, and a bug if it is — the caller |
| 449 | // renders its own 500. |
| 450 | sessionNone |
| 451 | // sessionOffboarded: there was a session, and its address is no |
| 452 | // longer on the allowlist. offboard has ended it and written the |
| 453 | // answer; the caller must write nothing more. |
| 454 | sessionOffboarded |
| 455 | ) |
| 456 | |
| 457 | // offboard is what happens to somebody whose address is no longer on |
| 458 | // the allowlist and who still has a live session — spec §6.1's |
| 459 | // offboarding rule (codex 6). |
| 460 | // |
| 461 | // Three things, in this order, and the order is the point: |
| 462 | // |
| 463 | // - Every session for that address is DELETED, not just this |
| 464 | // request's, and not just the cookie. A cleared cookie leaves the |
| 465 | // token in the sessions table and valid, so a browser holding a |
| 466 | // copy — a second tab restored from history, a phone — would carry |
| 467 | // on. Real revocation, and for every device at once, because |
| 468 | // offboarding is about the person and not about the browser they |
| 469 | // happen to be using. |
| 470 | // - Every presentation they had running is ENDED. A live session is |
| 471 | // a public URL that reads the deck out, so leaving one up would |
| 472 | // leave a removed person's talk readable by whoever has the |
| 473 | // address. Their share links are NOT revoked: a share link belongs |
| 474 | // to the deck, the deck belongs to the team, and revoking the |
| 475 | // team's links because one member left would be an outage the |
| 476 | // departure did not call for. The share page is where a link goes |
| 477 | // away, deliberately by somebody who still has access. |
| 478 | // - The cookie is cleared and the person is told, in words, on the |
| 479 | // sign-in page. `?err=removed` rather than a silent redirect, |
| 480 | // because "your access to this instance was removed" is a |
| 481 | // different fact from "you are signed out" and a person who is not |
| 482 | // told the first will simply ask for another link. |
| 483 | // |
| 484 | // A page request gets the redirect; anything else gets a 403, which is |
| 485 | // rauth's own split (refuseSession) and the only one that makes sense |
| 486 | // for a fetch or a form POST. |
| 487 | func (a *app) offboard(w http.ResponseWriter, r *http.Request, address string) { |
| 488 | email := normalizeAddress(address) |
| 489 | if a.home != nil { |
| 490 | if err := a.db.G.WithContext(r.Context()).Exec("DELETE FROM sessions WHERE method = ? AND subject IN (SELECT l.subject FROM home_identity_links l JOIN users u ON u.id=l.person_id WHERE u.email=?)", connect.HomeMethod, email).Error; err != nil { |
| 491 | a.logger.Error("slides: revoke linked Home sessions", "err", err) |
| 492 | } |
| 493 | } |
| 494 | a.logger.Warn("slides: a signed-in address is no longer admitted; ending its sessions", |
| 495 | "address", email) |
| 496 | |
| 497 | // rastrillo/sessions owns this table and offers no "revoke every |
| 498 | // session for a subject", so the statement is written here. The |
| 499 | // subject IS the address under rastrillo/auth (SKILL.md §5), which |
| 500 | // is what makes one statement enough. |
| 501 | if err := a.db.G.WithContext(r.Context()). |
| 502 | Exec("DELETE FROM sessions WHERE subject = ?", email).Error; err != nil { |
| 503 | a.logger.Error("slides: revoke the sessions of a removed address", "err", err) |
| 504 | } |
| 505 | |
| 506 | var u User |
| 507 | if err := a.db.G.WithContext(r.Context()). |
| 508 | Where("email = ?", email).Take(&u).Error; err == nil { |
| 509 | a.endPresentationsOf(r, actorFor(u)) |
| 510 | } else if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 511 | a.logger.Error("slides: load a removed address's user row", "err", err) |
| 512 | } |
| 513 | |
| 514 | if a.auth != nil { |
| 515 | http.SetCookie(w, &http.Cookie{ |
| 516 | Name: a.auth.SessionCookie(), Value: "", Path: "/", |
| 517 | MaxAge: -1, HttpOnly: true, |
| 518 | SameSite: http.SameSiteLaxMode, |
| 519 | Secure: strings.HasPrefix(a.cfg.Origin, "https://"), |
| 520 | }) |
| 521 | } |
| 522 | if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| 523 | http.Redirect(w, r, signinPath+"?err=removed", http.StatusSeeOther) |
| 524 | return |
| 525 | } |
| 526 | http.Error(w, "this address is no longer admitted here", http.StatusForbidden) |
| 527 | } |
| 528 | |
| 529 | // endPresentationsOf closes every live talk one actor still has open. |
| 530 | // Best effort and logged: it is part of offboarding, and a failure to |
| 531 | // end a talk must not stop the sign-out that is the main event. |
| 532 | func (a *app) endPresentationsOf(r *http.Request, actor string) { |
| 533 | var live []Presentation |
| 534 | if err := a.db.G.WithContext(r.Context()). |
| 535 | Where("actor = ? AND ended_at IS NULL", actor).Find(&live).Error; err != nil { |
| 536 | a.logger.Error("slides: list a removed actor's presentations", "actor", actor, "err", err) |
| 537 | return |
| 538 | } |
| 539 | if len(live) == 0 { |
| 540 | return |
| 541 | } |
| 542 | now := time.Now().UTC() |
| 543 | if err := a.db.G.WithContext(r.Context()).Model(&Presentation{}). |
| 544 | Where("actor = ? AND ended_at IS NULL", actor). |
| 545 | Update("ended_at", now).Error; err != nil { |
| 546 | a.logger.Error("slides: end a removed actor's presentations", "actor", actor, "err", err) |
| 547 | return |
| 548 | } |
| 549 | // Every projector, phone and follower watching one of them, told at |
| 550 | // once — the same event the End button publishes. |
| 551 | for _, p := range live { |
| 552 | a.hub.Publish(p.Sqid, present.Event{Ended: true}) |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | // requireSession is rastrillo/auth's RequireSession with return_to |
| 557 | // (spec §9.4): its refusal sends a page request to a bare /signin and |
| 558 | // drops the path, so a signed-out visit to a deck link used to land on |
| 559 | // the deck list after sign-in. A signed-out GET or HEAD is answered here |
| 560 | // with 303 /signin?return_to=<the page>; everything else goes to the |
| 561 | // guard as before (a POST still gets its 403). |
| 562 | func (a *app) requireSession(guard func(http.Handler) http.Handler) func(http.Handler) http.Handler { |
| 563 | return func(next http.Handler) http.Handler { |
| 564 | guarded := guard(next) |
| 565 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 566 | if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| 567 | if _, ok := a.sessions.From(r); !ok { |
| 568 | w.Header().Set("Cache-Control", "no-store") |
| 569 | http.Redirect(w, r, signinPath+"?return_to="+url.QueryEscape(r.URL.RequestURI()), http.StatusSeeOther) |
| 570 | return |
| 571 | } |
| 572 | } |
| 573 | guarded.ServeHTTP(w, r) |
| 574 | }) |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | // landedPath is rastrillo/auth's SignedInPath in standalone mode: where a |
| 579 | // verified magic link lands, which then goes on to the remembered page. |
| 580 | const landedPath = "/auth/landed" |
| 581 | |
| 582 | // landed serves GET /auth/landed: the remembered return_to, or the deck |
| 583 | // list. The cookie is spent either way. |
| 584 | func (a *app) landed(w http.ResponseWriter, r *http.Request) { |
| 585 | dest := "/" |
| 586 | if ret, ok := a.rememberedReturn(r); ok { |
| 587 | dest = ret |
| 588 | } |
| 589 | a.forgetReturn(w) |
| 590 | w.Header().Set("Cache-Control", "no-store") |
| 591 | http.Redirect(w, r, dest, http.StatusSeeOther) |
| 592 | } |
| 593 | |
| 594 | // returnCookieName is the remembered return_to. Host-only, and |
| 595 | // __Host- prefixed wherever the origin is https. |
| 596 | func (a *app) returnCookieName() string { |
| 597 | if a.secure() { |
| 598 | return "__Host-slides_return" |
| 599 | } |
| 600 | return "slides_return" |
| 601 | } |
| 602 | |
| 603 | func (a *app) secure() bool { return strings.HasPrefix(a.cfg.Origin, "https://") } |
| 604 | |
| 605 | // returnCookieAge is how long a remembered page lasts: a link opened |
| 606 | // after ten minutes, or in another browser, lands on the deck list. |
| 607 | const returnCookieAge int64 = 600 |
| 608 | const returnCookieLimit = 4096 |
| 609 | |
| 610 | type returnIntent struct { |
| 611 | Path string `json:"path"` |
| 612 | Issued int64 `json:"issued"` |
| 613 | Expires int64 `json:"expires"` |
| 614 | } |
| 615 | |
| 616 | // newReturnSealer keeps the cookie independent from any other encrypted |
| 617 | // value. The raw instance key need not be exactly 32 bytes; its domain-bound |
| 618 | // hash is. A changed key invalidates old return cookies, which is safe. |
| 619 | func newReturnSealer(instanceKey string) (*seal.Sealer, error) { |
| 620 | key := sha256.Sum256([]byte("oficina/slides return v1\x00" + instanceKey)) |
| 621 | return seal.New(key[:], "oficina/slides") |
| 622 | } |
| 623 | |
| 624 | func (a *app) returnPurpose() string { return "slides.return.v1:" + a.cfg.Origin } |
| 625 | |
| 626 | // rememberReturn keeps path in the return memory, or "/" when it is not |
| 627 | // one safe local path, or is the signed-out page, which would land a |
| 628 | // fresh sign-in on "You're signed out". Remembering "/" rather than |
| 629 | // nothing is what keeps a page an earlier, abandoned attempt remembered |
| 630 | // from winning over this one. |
| 631 | func (a *app) rememberReturn(w http.ResponseWriter, path string) { |
| 632 | if a.returnSeal == nil || a.returnNow == nil { |
| 633 | return |
| 634 | } |
| 635 | if !handoff.SafePath(path) || signedOutPage(path) { |
| 636 | path = "/" |
| 637 | } |
| 638 | now := a.returnNow().Unix() |
| 639 | if now <= 0 || now > math.MaxInt64-returnCookieAge { |
| 640 | return |
| 641 | } |
| 642 | raw, err := json.Marshal(returnIntent{Path: path, Issued: now, Expires: now + returnCookieAge}) |
| 643 | if err != nil { |
| 644 | return |
| 645 | } |
| 646 | sealed, err := a.returnSeal.Seal(a.returnPurpose(), raw) |
| 647 | if err != nil { |
| 648 | return |
| 649 | } |
| 650 | value := base64.RawURLEncoding.EncodeToString(sealed) |
| 651 | if len(value) > returnCookieLimit { |
| 652 | return |
| 653 | } |
| 654 | http.SetCookie(w, &http.Cookie{ |
| 655 | Name: a.returnCookieName(), Value: value, Path: "/", |
| 656 | MaxAge: int(returnCookieAge), HttpOnly: true, Secure: a.secure(), |
| 657 | SameSite: http.SameSiteLaxMode, |
| 658 | }) |
| 659 | } |
| 660 | |
| 661 | func (a *app) forgetReturn(w http.ResponseWriter) { |
| 662 | http.SetCookie(w, &http.Cookie{ |
| 663 | Name: a.returnCookieName(), Value: "", Path: "/", |
| 664 | MaxAge: -1, HttpOnly: true, Secure: a.secure(), |
| 665 | SameSite: http.SameSiteLaxMode, |
| 666 | }) |
| 667 | } |
| 668 | |
| 669 | // rememberedReturn reads the remembered page back, validated again: the |
| 670 | // cookie is a request header like any other, and the value is only ever |
| 671 | // a same-origin path (handoff.SafePath, which also refuses /signin and |
| 672 | // /auth/*, so this can never loop). |
| 673 | func (a *app) rememberedReturn(r *http.Request) (string, bool) { |
| 674 | if a.returnSeal == nil || a.returnNow == nil { |
| 675 | return "", false |
| 676 | } |
| 677 | count := 0 |
| 678 | for _, c := range r.Cookies() { |
| 679 | if c.Name == a.returnCookieName() { |
| 680 | count++ |
| 681 | } |
| 682 | } |
| 683 | if count != 1 { |
| 684 | return "", false |
| 685 | } |
| 686 | c, err := r.Cookie(a.returnCookieName()) |
| 687 | if err != nil { |
| 688 | return "", false |
| 689 | } |
| 690 | if c.Value == "" || len(c.Value) > returnCookieLimit { |
| 691 | return "", false |
| 692 | } |
| 693 | sealed, err := base64.RawURLEncoding.Strict().DecodeString(c.Value) |
| 694 | if err != nil || base64.RawURLEncoding.EncodeToString(sealed) != c.Value { |
| 695 | return "", false |
| 696 | } |
| 697 | raw, err := a.returnSeal.Open(a.returnPurpose(), sealed) |
| 698 | if err != nil || len(raw) > returnCookieLimit { |
| 699 | return "", false |
| 700 | } |
| 701 | var intent returnIntent |
| 702 | if json.Unmarshal(raw, &intent) != nil { |
| 703 | return "", false |
| 704 | } |
| 705 | canonical, _ := json.Marshal(intent) |
| 706 | now := a.returnNow().Unix() |
| 707 | if !bytes.Equal(raw, canonical) || intent.Issued <= 0 || intent.Issued > now || intent.Expires <= now || intent.Expires <= intent.Issued || intent.Expires-intent.Issued > returnCookieAge || !handoff.SafePath(intent.Path) { |
| 708 | return "", false |
| 709 | } |
| 710 | return intent.Path, true |
| 711 | } |
| 712 | |
| 713 | // signedOutPage reports whether path is /signed-out, with or without a |
| 714 | // query or fragment. |
| 715 | func signedOutPage(path string) bool { |
| 716 | u, err := url.Parse(path) |
| 717 | return err != nil || u.Path == "/signed-out" |
| 718 | } |
| 719 | |
| 720 | // safeReturn is the request's return_to, when there is exactly one and |
| 721 | // it is a same-origin path (handoff.SafePath: no scheme, no host, no |
| 722 | // "//", no control characters, not /signin or /auth/*). |
| 723 | func safeReturn(q url.Values) (string, bool) { |
| 724 | values, ok := q["return_to"] |
| 725 | if !ok || len(values) != 1 || !handoff.SafePath(values[0]) { |
| 726 | return "", false |
| 727 | } |
| 728 | return values[0], true |
| 729 | } |
| 730 | |
| 731 | // signedOutAfter wraps rastrillo/auth's Signout, which ends the session |
| 732 | // and redirects to the sign-in form: a page that, with no word about |
| 733 | // what just happened, read like an error (polish audit, sign-on). The |
| 734 | // redirect goes to /signed-out instead, which says so. |
| 735 | func signedOutAfter(signout http.HandlerFunc) http.HandlerFunc { |
| 736 | return func(w http.ResponseWriter, r *http.Request) { |
| 737 | signout(&toSignedOut{ResponseWriter: w}, r) |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | // toSignedOut rewrites Signout's Location, at the last moment a header is |
| 742 | // still settable: http.Redirect sets Location and then calls |
| 743 | // WriteHeader, so intercepting the second sees the first. |
| 744 | type toSignedOut struct{ http.ResponseWriter } |
| 745 | |
| 746 | func (t *toSignedOut) WriteHeader(status int) { |
| 747 | if t.Header().Get("Location") == signinPath { |
| 748 | t.Header().Set("Location", "/signed-out") |
| 749 | } |
| 750 | t.ResponseWriter.WriteHeader(status) |
| 751 | } |
| 752 | |