| 1 | package slides |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net/http" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/home/connect" |
| 13 | "amadan.net/oficina/home/connect/linkstore" |
| 14 | "amadan.net/oficina/home/handoff" |
| 15 | "amadan.net/rastrillo/rastrillo" |
| 16 | "amadan.net/rastrillo/rastrillo/csrf" |
| 17 | "amadan.net/rastrillo/rastrillo/migrate" |
| 18 | "amadan.net/rastrillo/rastrillo/sessions" |
| 19 | "gorm.io/gorm" |
| 20 | ) |
| 21 | |
| 22 | var homeSchema = migrate.Merge(migrate.MustFromFS(handoff.Migrations, "home_handoff"), migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace)) |
| 23 | var errHomeIdentity = errors.New("slides: Home identity refused") |
| 24 | |
| 25 | func neutralSession(s sessions.Session) connect.Session { |
| 26 | return connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At} |
| 27 | } |
| 28 | |
| 29 | func (a *app) initHome(c *connect.DecodedCredentials) error { |
| 30 | if c == nil { |
| 31 | return nil |
| 32 | } |
| 33 | sess, err := sessions.New(sessions.Config{DB: a.db.Writer(), Origin: a.cfg.Origin, Logger: a.logger}) |
| 34 | if err != nil { |
| 35 | return err |
| 36 | } |
| 37 | a.homeSessions = sess |
| 38 | read := func(r *http.Request) (*connect.Session, error) { |
| 39 | s, ok := sess.From(r) |
| 40 | if !ok { |
| 41 | return nil, nil |
| 42 | } |
| 43 | n := neutralSession(s) |
| 44 | return &n, nil |
| 45 | } |
| 46 | cfg := connect.Config{DB: a.db.Writer(), Origin: a.cfg.Origin, Issuer: c.Issuer, ConsumerID: c.ConsumerID, Namespace: homeNamespace, SessionCookie: sess.CookieName(), Keys: c.Keys, DEK: c.DEK, ReadSession: read, |
| 47 | MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error { |
| 48 | if err := sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}); err != nil { |
| 49 | return err |
| 50 | } |
| 51 | a.rememberOficina(w, r) |
| 52 | return nil |
| 53 | }, |
| 54 | LookupLocalSession: func(ctx context.Context, s connect.Session) (connect.Person, error) { |
| 55 | if s.Method != "magiclink" && s.Method != "keymail" { |
| 56 | return connect.Person{}, errHomeIdentity |
| 57 | } |
| 58 | var u User |
| 59 | if err := a.db.G.WithContext(ctx).Where("email = ?", normalizeAddress(s.Subject)).Take(&u).Error; err != nil { |
| 60 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 61 | return connect.Person{}, sql.ErrNoRows |
| 62 | } |
| 63 | return connect.Person{}, err |
| 64 | } |
| 65 | // Team mode: a link names who somebody is, not whether they |
| 66 | // may enter. The roster decides that on every request |
| 67 | // (team_access.go), so a linked person needs no place on |
| 68 | // SLIDES_ALLOWED_ADDRESSES to resolve. |
| 69 | if a.teamOn == nil && !a.allowed.allows(u.Email) { |
| 70 | return connect.Person{}, sql.ErrNoRows |
| 71 | } |
| 72 | return connect.Person{ID: u.ID, Label: u.Email}, nil |
| 73 | }, LookupPerson: func(ctx context.Context, q linkstore.Queryer, id int64) (string, error) { |
| 74 | var email string |
| 75 | if err := q.QueryRowContext(ctx, "SELECT email FROM users WHERE id = ?", id).Scan(&email); err != nil { |
| 76 | return "", err |
| 77 | } |
| 78 | if a.teamOn == nil && !a.allowed.allows(email) { |
| 79 | return "", sql.ErrNoRows |
| 80 | } |
| 81 | return email, nil |
| 82 | }, Render: a.renderHome} |
| 83 | if a.teamOn != nil { |
| 84 | // Team mode only: with all three hooks nil connect is exactly what |
| 85 | // it was, and refuses a Home subject with no link as "unknown" |
| 86 | // (team_home_only.go). With them, a roster Member with no account |
| 87 | // here is asked to choose (connect.ChoosePath). |
| 88 | cfg.Admit, cfg.HomeOnly, cfg.Unlinked = a.teamAdmit, a.teamHomeOnly(a.db.Writer()), a.teamUnlinked(a.db.Writer()) |
| 89 | } |
| 90 | b, err := connect.New(cfg) |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | a.home = b |
| 95 | a.homeIssuer = c.Issuer |
| 96 | a.directory = c.Directory |
| 97 | if err := a.configureDashboard(c); err != nil { |
| 98 | return err |
| 99 | } |
| 100 | // LocalSignin is the door connect's SigninDoor and SigninLocal hand to |
| 101 | // (signin.go); ForgetPath puts "Forget me on this device" on the |
| 102 | // signed-out page. A local sign-in lands on LocalLandingPath, "/", |
| 103 | // which homeLocalComplete replaces with the page it began from. |
| 104 | a.homeRoutes, err = connect.NewRoutes(b, connect.RoutesConfig{LocalLandingPath: homeLandingPath, Namespace: homeNamespace, Origin: a.cfg.Origin, Issuer: c.Issuer, DEK: c.DEK, SessionCookie: sess.CookieName(), ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.signinDoor, Protect: csrf.Protect(a.cfg.Origin), Render: a.renderHome, FormPolicy: connect.FormPolicy(c.Issuer), ForgetPath: signinForgetPath}) |
| 105 | return err |
| 106 | } |
| 107 | |
| 108 | // homeLandingPath is where connect lands a local sign-in that resumes no |
| 109 | // link (RoutesConfig.LocalLandingPath): the deck list. |
| 110 | const homeLandingPath = "/" |
| 111 | |
| 112 | // homeLinkView is the account-connection pages' data: connect's page |
| 113 | // under this app's own bar, or the member choice's two buttons when |
| 114 | // Choice is set. Both buttons POST connect.ChoosePath with the form |
| 115 | // token, inside the app-wide CSRF check. |
| 116 | type homeLinkView struct { |
| 117 | shell |
| 118 | connect.PageData |
| 119 | Choice *homeChoice |
| 120 | } |
| 121 | |
| 122 | type homeChoice struct { |
| 123 | Action, Token, ConnectLabel, NewLabel string |
| 124 | } |
| 125 | |
| 126 | // renderHome renders connect's account-connection pages, and the |
| 127 | // signed-out page Sign out lands on, in this app's layout and bar. |
| 128 | // |
| 129 | // Referrer-Policy is strict-origin, not no-referrer (shared chrome spec |
| 130 | // §9.5): these pages show the account menu once somebody is signed in, |
| 131 | // and its Sign out chains to id.*/signout, which admits the hop by the |
| 132 | // Referer's origin. strict-origin still sends no path or query. |
| 133 | func (a *app) renderHome(w http.ResponseWriter, r *http.Request, state, label string, status int) { |
| 134 | w.Header().Set("Cache-Control", "no-store") |
| 135 | w.Header().Set("Referrer-Policy", "strict-origin") |
| 136 | if state == "signedout" { |
| 137 | // The same signed-out page standalone mode shows (auth.go), so |
| 138 | // Sign out lands on one page whichever way the person signed in. |
| 139 | a.renderSignedOut(w, r, status) |
| 140 | return |
| 141 | } |
| 142 | t := func(key string) string { return rastrillo.T(r, "slides.home."+key) } |
| 143 | view := homeLinkView{PageData: connect.PageFor(r, state, label, t)} |
| 144 | if state == "choose" { |
| 145 | // A roster member with no account here yet (Home spec |
| 146 | // 2026-11-14-oficina-id-native.md §8): connect an existing email |
| 147 | // account, or continue with Oficina ID as someone new. connect's |
| 148 | // Page knows no "choose", so the page is built here. |
| 149 | if form, ok := connect.ChoiceFor(r); ok { |
| 150 | view.Title, view.Body = t("choose_title"), t("choose_body") |
| 151 | view.Choice = &homeChoice{Action: form.Action, Token: form.Token, |
| 152 | ConnectLabel: t("choose_connect_action"), NewLabel: t("choose_new_action")} |
| 153 | } else { |
| 154 | // No live choice to offer: "failed", with the way on to |
| 155 | // connecting an account, as Docs and Sheets do. |
| 156 | view.PageData = connect.PageFor(r, "failed", label, t) |
| 157 | view.Action, view.ActionLabel = "/account/home", t("menu_action") |
| 158 | status = http.StatusForbidden |
| 159 | } |
| 160 | } |
| 161 | view.shell = a.publicShell(r, titled(view.Title)) |
| 162 | var buf bytes.Buffer |
| 163 | if err := pages["home_link"].ExecuteTemplate(&buf, "layout", view); err != nil { |
| 164 | a.logger.Error("slides: render Home account page", "err", err) |
| 165 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| 166 | return |
| 167 | } |
| 168 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 169 | w.WriteHeader(status) |
| 170 | buf.WriteTo(w) |
| 171 | } |
| 172 | func (a *app) homeUser(r *http.Request, s sessions.Session) (User, error) { |
| 173 | if a.home == nil || s.Method != connect.HomeMethod { |
| 174 | return User{}, errHomeIdentity |
| 175 | } |
| 176 | person, err := a.home.Resolve(r.Context(), s.Subject) |
| 177 | if err != nil { |
| 178 | return User{}, err |
| 179 | } |
| 180 | var u User |
| 181 | if err := a.db.G.WithContext(r.Context()).Where("id = ?", person.ID).Take(&u).Error; err != nil { |
| 182 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 183 | return User{}, linkstore.ErrRefused |
| 184 | } |
| 185 | return User{}, fmt.Errorf("%w: %v", linkstore.ErrStorage, err) |
| 186 | } |
| 187 | if a.team == nil && !a.allowed.allows(u.Email) { |
| 188 | return User{}, linkstore.ErrRefused |
| 189 | } |
| 190 | return u, nil |
| 191 | } |
| 192 | |
| 193 | func (a *app) revokeHome(w http.ResponseWriter, r *http.Request, subject string) { |
| 194 | var u User |
| 195 | if a.team == nil && a.home != nil && a.db.G.WithContext(r.Context()).Raw("SELECT u.* FROM users u JOIN home_identity_links l ON l.person_id=u.id WHERE l.issuer=? AND l.subject=?", a.cfg.Home.Issuer, subject).Scan(&u).Error == nil && u.ID != 0 && !a.allowed.allows(u.Email) { |
| 196 | a.offboard(w, r, u.Email) |
| 197 | return |
| 198 | } |
| 199 | if err := a.db.G.WithContext(r.Context()).Exec("DELETE FROM sessions WHERE method=? AND subject=?", connect.HomeMethod, subject).Error; err != nil { |
| 200 | a.logger.Error("slides: revoke Home session", "err", err) |
| 201 | } |
| 202 | if a.homeSessions != nil { |
| 203 | a.homeSessions.SignOut(w, r) |
| 204 | } |
| 205 | if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| 206 | http.Redirect(w, r, "/signin?err=removed", http.StatusSeeOther) |
| 207 | } else { |
| 208 | w.WriteHeader(http.StatusForbidden) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | type exportSessionKey struct{} |
| 213 | |
| 214 | func (a *app) exportPrincipal(r *http.Request) *http.Request { |
| 215 | s, ok := sessions.Current(r) |
| 216 | if ok && a.team != nil { |
| 217 | // Team mode: every session keys its jobs on the user, since a |
| 218 | // Home-only user has no address (teamJobOwner). |
| 219 | u, _, err := a.teamIdentify(r.Context(), s) |
| 220 | if err != nil { |
| 221 | return r |
| 222 | } |
| 223 | original := s |
| 224 | s.Subject = teamJobOwner(u.ID) |
| 225 | return sessions.WithSession(r.WithContext(context.WithValue(r.Context(), exportSessionKey{}, original)), s) |
| 226 | } |
| 227 | if !ok || s.Method != connect.HomeMethod { |
| 228 | return r |
| 229 | } |
| 230 | u, err := a.homeUser(r, s) |
| 231 | if err != nil { |
| 232 | return r |
| 233 | } |
| 234 | original := s |
| 235 | s.Subject = u.Email |
| 236 | return sessions.WithSession(r.WithContext(context.WithValue(r.Context(), exportSessionKey{}, original)), s) |
| 237 | } |
| 238 | func restoreExportPrincipal(r *http.Request) *http.Request { |
| 239 | if s, ok := r.Context().Value(exportSessionKey{}).(sessions.Session); ok { |
| 240 | return sessions.WithSession(r, s) |
| 241 | } |
| 242 | return r |
| 243 | } |
| 244 | |
| 245 | // homeLocalComplete is GET /auth/local/complete with Home configured: where |
| 246 | // a local sign-in lands. After an Oficina assertion Slides had no link for, |
| 247 | // connect resumes the link from here, and that needs the person's users |
| 248 | // row. A first-ever local sign-in has none yet (currentUser creates it on |
| 249 | // the first page), so the resume fell to /account/home, which answered 403 |
| 250 | // (Astra's review of #23). A fresh, admitted local session gets its row |
| 251 | // here first, exactly as currentUser would make it, sample deck included; |
| 252 | // any other request is passed on untouched. Failing costs only the |
| 253 | // shortcut: the sign-in itself has already succeeded. |
| 254 | // |
| 255 | // connect then resumes a link from here, or goes to /account/home; |
| 256 | // otherwise it lands on LocalLandingPath, "/", and Slides lands on the |
| 257 | // page the sign-in began from instead (signin_return.go), once. |
| 258 | func (a *app) homeLocalComplete(w http.ResponseWriter, r *http.Request) { |
| 259 | if s, ok := a.homeSessions.From(r); ok && (s.Method == "magiclink" || s.Method == "keymail") && a.allowed.allows(s.Subject) { |
| 260 | if _, fresh := connect.FreshLocal(neutralSession(s), time.Now()); fresh { |
| 261 | u, created, err := ensureUser(r.Context(), a.db.G, s.Subject) |
| 262 | switch { |
| 263 | case err != nil: |
| 264 | a.logger.Error("slides: create user before resuming a Home link", "err", err) |
| 265 | case created && a.team != nil: |
| 266 | // Team mode: a local account made here has no link yet, |
| 267 | // so it is a guest, and guests create nothing; no sample |
| 268 | // deck (team_access.go's teamIdentify says the same). |
| 269 | case created: |
| 270 | if has, err := hasDeck(r.Context(), a.db.G, u); err != nil { |
| 271 | a.logger.Error("slides: check for an existing deck before seeding", "user", u.ID, "err", err) |
| 272 | } else if !has { |
| 273 | a.seedSampleDeckFor(r.Context(), u) |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | result := &bufferedResponse{header: make(http.Header)} |
| 279 | a.homeRoutes.LocalComplete(result, r) |
| 280 | if result.status == http.StatusSeeOther && result.header.Get("Location") == homeLandingPath { |
| 281 | if kept, ok := a.rememberedReturn(r); ok { |
| 282 | result.header.Set("Location", kept) |
| 283 | } |
| 284 | a.forgetReturn(result) |
| 285 | } |
| 286 | result.replay(w) |
| 287 | } |
| 288 | |