| 1 | package sheets |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/home/connect" |
| 13 | "amadan.net/oficina/home/connect/linkstore" |
| 14 | "amadan.net/oficina/home/handoff/seal" |
| 15 | "amadan.net/rastrillo/rastrillo/csrf" |
| 16 | "amadan.net/rastrillo/rastrillo/sessions" |
| 17 | ) |
| 18 | |
| 19 | var errHome = errors.New("sheets: Home connection unavailable") |
| 20 | |
| 21 | // homeLandingPath is where connect lands a local sign-in that resumes no |
| 22 | // link (RoutesConfig.LocalLandingPath): the list. |
| 23 | const homeLandingPath = "/sheets" |
| 24 | |
| 25 | // homeNamespace is Sheets' Home storage namespace: connect's link and |
| 26 | // handoff sealing, and in team mode the roster evidence and the team |
| 27 | // sign-in's handoff store, which must open connect's pending rows. |
| 28 | const homeNamespace = "oficina/sheets" |
| 29 | |
| 30 | // ConfigureHome runs after local auth is attached and before serving requests. |
| 31 | func (a *App) ConfigureHome(raw *connect.Credentials) error { |
| 32 | settings, err := connect.DecodeCredentials(raw, a.origin) |
| 33 | if err != nil { |
| 34 | return errHome |
| 35 | } |
| 36 | if settings == nil { |
| 37 | return nil |
| 38 | } |
| 39 | if a.db == nil || a.auth == nil { |
| 40 | return errHome |
| 41 | } |
| 42 | d, err := a.db.DB() |
| 43 | if err != nil { |
| 44 | return errHome |
| 45 | } |
| 46 | sess, err := sessions.New(sessions.Config{DB: d, Origin: a.origin, SigninPath: "/signin"}) |
| 47 | if err != nil || sess.CookieName() != a.auth.SessionCookie() { |
| 48 | return errHome |
| 49 | } |
| 50 | read := func(r *http.Request) (*connect.Session, error) { |
| 51 | s, ok := sess.From(r) |
| 52 | if !ok { |
| 53 | return nil, nil |
| 54 | } |
| 55 | return &connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, nil |
| 56 | } |
| 57 | render := func(w http.ResponseWriter, r *http.Request, state, label string, status int) { |
| 58 | w.Header().Set("Cache-Control", "no-store") |
| 59 | if state == "signedout" { |
| 60 | // The suite's signed-out page (spec §9.2), not connect's |
| 61 | // "Sign in with Home" one. |
| 62 | a.renderSignedOut(w, r, status) |
| 63 | return |
| 64 | } |
| 65 | view := homeLinkView{PageData: connect.PageFor(r, state, label, func(k string) string { return homeCopy[k] })} |
| 66 | if state == "choose" { |
| 67 | // A roster member with no account here yet (Home spec |
| 68 | // 2026-11-14-oficina-id-native.md §8): connect an existing |
| 69 | // email account, or continue with Oficina ID as someone new. |
| 70 | // connect's Page knows no "choose", so the page is built here. |
| 71 | if form, ok := connect.ChoiceFor(r); ok { |
| 72 | view.Title, view.Body = homeCopy["choose_title"], homeCopy["choose_body"] |
| 73 | view.Choice = &homeChoice{Action: form.Action, Token: form.Token, |
| 74 | ConnectLabel: homeCopy["choose_connect_action"], NewLabel: homeCopy["choose_new_action"]} |
| 75 | } else { |
| 76 | // No live choice to offer: "failed", with the way on to |
| 77 | // connecting an account, as Docs' home_render.go does. |
| 78 | view.PageData = connect.PageFor(r, "failed", label, func(k string) string { return homeCopy[k] }) |
| 79 | view.Action, view.ActionLabel = "/account/home", homeCopy["menu_action"] |
| 80 | status = http.StatusForbidden |
| 81 | } |
| 82 | } |
| 83 | a.render(w, r, "home_link", titled(view.Title), status, view) |
| 84 | } |
| 85 | sealer, err := seal.New(settings.DEK, homeNamespace) |
| 86 | if err != nil { |
| 87 | return errHome |
| 88 | } |
| 89 | cfg := connect.Config{DB: d, Origin: a.origin, Issuer: settings.Issuer, ConsumerID: settings.ConsumerID, Namespace: homeNamespace, Keys: settings.Keys, DEK: settings.DEK, SessionCookie: sess.CookieName(), ReadSession: read, |
| 90 | MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error { |
| 91 | if err := sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}); err != nil { |
| 92 | return err |
| 93 | } |
| 94 | a.rememberOficina(w, r) |
| 95 | return nil |
| 96 | }, |
| 97 | LookupPerson: a.homePerson, |
| 98 | LookupLocalSession: func(ctx context.Context, s connect.Session) (connect.Person, error) { |
| 99 | var id int64 |
| 100 | address := strings.ToLower(strings.TrimSpace(s.Subject)) |
| 101 | if err := d.QueryRowContext(ctx, "SELECT id FROM members WHERE address=?", address).Scan(&id); err != nil { |
| 102 | return connect.Person{}, err |
| 103 | } |
| 104 | label, err := a.homePerson(ctx, d, id) |
| 105 | return connect.Person{ID: id, Label: label}, err |
| 106 | }, Render: render, |
| 107 | // The native app's session (connect.NativeExchange, Home spec |
| 108 | // 2026-11-14-oficina-id-native.md §7): the same store and cookie |
| 109 | // name, minted without a cookie and handed back in the answer. The |
| 110 | // store's own 30-day lifetime outlasts connect's 7-day limit. |
| 111 | MintNativeSession: func(_ context.Context, s connect.Session) (string, error) { |
| 112 | return sess.Mint(sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}) |
| 113 | }} |
| 114 | if a.teamSettings != nil { |
| 115 | // Team mode only: with all three hooks nil connect is exactly what |
| 116 | // it was, and refuses a Home subject with no link as "unknown" |
| 117 | // (team_home_only.go). |
| 118 | cfg.Admit, cfg.HomeOnly, cfg.Unlinked = a.teamAdmit, a.teamHomeOnly(d), a.teamUnlinked(d) |
| 119 | } |
| 120 | bridge, err := connect.New(cfg) |
| 121 | if err != nil { |
| 122 | return errHome |
| 123 | } |
| 124 | routes, err := connect.NewRoutes(bridge, connect.RoutesConfig{LocalLandingPath: homeLandingPath, Namespace: homeNamespace, Origin: a.origin, Issuer: settings.Issuer, SessionCookie: sess.CookieName(), DEK: settings.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.signinDoor, Protect: csrf.Protect(a.origin), Render: render, FormPolicy: connect.FormPolicy(settings.Issuer), ForgetPath: signinForgetPath}) |
| 125 | if err != nil { |
| 126 | return errHome |
| 127 | } |
| 128 | a.home, a.homeRoutes, a.homeSessions = bridge, routes, sess |
| 129 | a.returns = &returnMemory{sealer: sealer, origin: a.origin, now: time.Now} |
| 130 | a.homeCreds = settings |
| 131 | a.directory = settings.Directory |
| 132 | return a.configureDashboard(settings) |
| 133 | } |
| 134 | |
| 135 | // The same current admission rule as Admits, using the link transaction's q. |
| 136 | func (a *App) homePerson(ctx context.Context, q linkstore.Queryer, id int64) (string, error) { |
| 137 | var address string |
| 138 | if id <= 0 { |
| 139 | return "", sql.ErrNoRows |
| 140 | } |
| 141 | if err := q.QueryRowContext(ctx, "SELECT address FROM members WHERE id=?", id).Scan(&address); err != nil { |
| 142 | return "", err |
| 143 | } |
| 144 | if address == "" { |
| 145 | return "", sql.ErrNoRows |
| 146 | } |
| 147 | // Team mode: a link names who somebody is, not whether they may |
| 148 | // enter. The roster and the shares decide that on every request |
| 149 | // (team_access.go), so a linked team member needs neither a place |
| 150 | // on SHEETS_OWNERS nor a grant to resolve. |
| 151 | if a.team != nil { |
| 152 | return address, nil |
| 153 | } |
| 154 | if a.admit != nil && a.admit(address) { |
| 155 | return address, nil |
| 156 | } |
| 157 | var count int |
| 158 | err := q.QueryRowContext(ctx, `SELECT COUNT(*) FROM grants JOIN sheets ON sheets.id=grants.sheet_id WHERE grants.member_id=? AND sheets.deleted_at IS NULL AND sheets.filling_since IS NULL`, id).Scan(&count) |
| 159 | if err != nil { |
| 160 | return "", err |
| 161 | } |
| 162 | if count == 0 { |
| 163 | return "", sql.ErrNoRows |
| 164 | } |
| 165 | return address, nil |
| 166 | } |
| 167 | |
| 168 | // localMemberID is the member a local session's address names, read |
| 169 | // without creating one: the person ID Home links are stored against. |
| 170 | func (a *App) localMemberID(ctx context.Context, address string) (int64, error) { |
| 171 | if a.db == nil { |
| 172 | return 0, errNoDB |
| 173 | } |
| 174 | var id int64 |
| 175 | address = strings.ToLower(strings.TrimSpace(address)) |
| 176 | if err := a.db.WithContext(ctx).Raw("SELECT id FROM members WHERE address=?", address).Row().Scan(&id); err != nil { |
| 177 | return 0, err |
| 178 | } |
| 179 | return id, nil |
| 180 | } |
| 181 | |
| 182 | func (a *App) homeRequire(next http.Handler) http.Handler { |
| 183 | return a.homeSessions.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 184 | session, ok := a.homeSessions.From(r) |
| 185 | if ok && connect.IsHomeDerived(session.Method) { |
| 186 | if _, err := a.home.ResolveSession(r); errors.Is(err, linkstore.ErrStorage) { |
| 187 | w.Header().Set("Cache-Control", "no-store") |
| 188 | http.Error(w, "Sign-in unavailable.", http.StatusServiceUnavailable) |
| 189 | return |
| 190 | } |
| 191 | } |
| 192 | address, admitted := a.identity(r) |
| 193 | if !ok || !admitted || !a.Admits(address) { |
| 194 | if ok { |
| 195 | a.homeSessions.SignOut(w, r) |
| 196 | } |
| 197 | w.Header().Set("Cache-Control", "no-store") |
| 198 | if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| 199 | http.Redirect(w, r, "/signin?return_to="+url.QueryEscape(r.URL.RequestURI()), http.StatusSeeOther) |
| 200 | } else { |
| 201 | http.Error(w, "Sign in first.", http.StatusForbidden) |
| 202 | } |
| 203 | return |
| 204 | } |
| 205 | // Jobs use an already resolved local address so local and Home sessions have |
| 206 | // the same owner. The bridge always rereads the actual cookie-backed session. |
| 207 | session.Subject = address |
| 208 | next.ServeHTTP(w, sessions.WithSession(r, session)) |
| 209 | })) |
| 210 | } |
| 211 | |
| 212 | func (a *App) homeLocalComplete(w http.ResponseWriter, r *http.Request) { |
| 213 | s, ok := a.homeSessions.From(r) |
| 214 | if !ok { |
| 215 | a.homeRoutes.LocalComplete(w, r) |
| 216 | return |
| 217 | } |
| 218 | _, fresh := connect.FreshLocal(connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, time.Now()) |
| 219 | if !fresh || !a.Admits(s.Subject) { |
| 220 | http.Error(w, "Sign in first.", http.StatusForbidden) |
| 221 | return |
| 222 | } |
| 223 | // Only an independently verified local sign-in may create its local member. |
| 224 | // Home assertions and lookup hooks never pass through this completion handler. |
| 225 | if _, err := a.memberFor(s.Subject); err != nil { |
| 226 | http.Error(w, "Sign-in unavailable.", http.StatusServiceUnavailable) |
| 227 | return |
| 228 | } |
| 229 | // connect resumes a link from here, or goes to /account/home; otherwise |
| 230 | // it lands on LocalLandingPath, and Sheets lands on the page the |
| 231 | // sign-in began from instead (signin_return.go), once. |
| 232 | result := &bufferedResponse{header: make(http.Header)} |
| 233 | a.homeRoutes.LocalComplete(result, r) |
| 234 | if result.status == http.StatusSeeOther && result.header.Get("Location") == homeLandingPath { |
| 235 | if kept := a.returns.path(r); kept != "/" { |
| 236 | result.header.Set("Location", kept) |
| 237 | } |
| 238 | setReturnCookie(result, "", -1) |
| 239 | } |
| 240 | result.replay(w) |
| 241 | } |
| 242 | |
| 243 | func (a *App) rejectDisabledHome(next http.Handler) http.Handler { |
| 244 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 245 | if s, ok := sessions.Current(r); ok && connect.IsHomeDerived(s.Method) { |
| 246 | w.Header().Set("Cache-Control", "no-store") |
| 247 | http.Error(w, "Sign in first.", http.StatusForbidden) |
| 248 | return |
| 249 | } |
| 250 | next.ServeHTTP(w, r) |
| 251 | }) |
| 252 | } |
| 253 | |
| 254 | // homeLinkView is the account-connection page: connect's page, or the |
| 255 | // member choice's two buttons when Choice is set. Both buttons POST |
| 256 | // connect.ChoosePath with the form token, inside the app-wide CSRF check. |
| 257 | type homeLinkView struct { |
| 258 | connect.PageData |
| 259 | Choice *homeChoice |
| 260 | } |
| 261 | |
| 262 | type homeChoice struct { |
| 263 | Action, Token, ConnectLabel, NewLabel string |
| 264 | } |
| 265 | |