| 1 | // Package sheets is the Sheets instance app: one process, one SQLite file, |
| 2 | // one team. |
| 3 | package sheets |
| 4 | |
| 5 | import ( |
| 6 | nativeauth "amadan.net/rastrillo/native/server" |
| 7 | "net/http" |
| 8 | |
| 9 | "amadan.net/oficina/estilo.git/chrome" |
| 10 | "amadan.net/oficina/estilo.git/googleimport" |
| 11 | "amadan.net/oficina/home/connect" |
| 12 | "amadan.net/oficina/home/teammode" |
| 13 | "amadan.net/rastrillo/rastrillo/sessions" |
| 14 | |
| 15 | "amadan.net/rastrillo/rastrillo/auth" |
| 16 | "amadan.net/rastrillo/rastrillo/csrf" |
| 17 | "amadan.net/rastrillo/rastrillo/jobs" |
| 18 | "github.com/go-chi/chi/v5" |
| 19 | "gorm.io/gorm" |
| 20 | |
| 21 | "amadan.net/oficina/sheets/internal/sheets/live" |
| 22 | "amadan.net/oficina/sheets/internal/sheets/seal" |
| 23 | ) |
| 24 | |
| 25 | // Config is everything an App needs. |
| 26 | // |
| 27 | // A struct rather than positional parameters: this grew from two to |
| 28 | // five arguments in one plan, and the fifth — Origin — is a string |
| 29 | // sitting next to another string, which is the shape a call site gets |
| 30 | // silently wrong. |
| 31 | type Config struct { |
| 32 | // DB is the app's GORM handle. Nil only in tests that render pages |
| 33 | // without touching storage. |
| 34 | DB *gorm.DB |
| 35 | |
| 36 | // Auth is the sign-in flow. Nil ONLY in tests: Router then mounts |
| 37 | // none of auth's handlers and the sign-in door answers 404, so a |
| 38 | // nil-auth App can render pages without a database or a mailer. |
| 39 | // Production always passes one — main refuses to boot without the |
| 40 | // configuration auth needs. |
| 41 | Auth *auth.Auth |
| 42 | |
| 43 | // Sealer seals every cell, title and tab name. Nil only in tests |
| 44 | // that never reach a sheet. |
| 45 | Sealer *seal.Sealer |
| 46 | |
| 47 | // Origin is this instance's external origin, scheme included. It is |
| 48 | // the CSRF same-origin check's reference value. |
| 49 | Origin string |
| 50 | |
| 51 | // Admit is the allowlist, the static half of App.Admits. Admits is |
| 52 | // consulted before a link is SENT (admissionMailer) and at |
| 53 | // redemption (auth.Config.Authorize). See handleBegin. |
| 54 | Admit func(string) bool |
| 55 | // Team is team mode's verified configuration (TeamSettings), nil |
| 56 | // unless SHEETS_TEAM_* is set (team_config.go). |
| 57 | Team *teammode.Settings |
| 58 | // GoogleImport is the Google Drive chooser's public configuration |
| 59 | // (googleimport.go); the zero value is off. |
| 60 | GoogleImport googleimport.Config |
| 61 | } |
| 62 | |
| 63 | // App holds the wiring. One per process. |
| 64 | type App struct { |
| 65 | agent http.Handler |
| 66 | dashboard http.Handler |
| 67 | native *nativeauth.Auth |
| 68 | home *connect.Bridge |
| 69 | homeRoutes *connect.Routes |
| 70 | homeSessions *sessions.Sessions |
| 71 | homeCreds *connect.DecodedCredentials // ConfigureHome's, kept for team mode |
| 72 | // returns is the page a local sign-in began from, with Home |
| 73 | // configured (signin_return.go); nil standalone, where rastrillo |
| 74 | // carries it itself. |
| 75 | returns *returnMemory |
| 76 | // team is the roster runtime, nil unless SHEETS_TEAM_* configured |
| 77 | // team mode (team_config.go). Every team-mode branch keys on it. |
| 78 | team *teamRuntime |
| 79 | teamSettings *teammode.Settings |
| 80 | google googleimport.Config |
| 81 | teamTest |
| 82 | db *gorm.DB |
| 83 | auth *auth.Auth |
| 84 | sealer *seal.Sealer |
| 85 | origin string |
| 86 | admit func(string) bool |
| 87 | // directory is the hub directory (HOME_DIRECTORY_ORIGIN), set only |
| 88 | // with Home configured: the app switcher's link. Empty, no switcher. |
| 89 | directory string |
| 90 | |
| 91 | // hub fans every committed edit out to every other open tab. One per |
| 92 | // process, because it holds the live subscriptions: a hub per |
| 93 | // request would fan out to nobody, silently. |
| 94 | hub *live.Hub |
| 95 | |
| 96 | // jobs runs XLSX import off the request (spec §11). One registry |
| 97 | // per process for the same reason as the hub: it holds the running |
| 98 | // goroutines, and a registry per request could never answer for a |
| 99 | // job started by an earlier one. |
| 100 | // |
| 101 | // In-memory and unpersisted, which is the package's own design and |
| 102 | // the right one here: a deploy ends the goroutine, so a persisted |
| 103 | // row would only persist a lie about work that is no longer |
| 104 | // running. |
| 105 | jobs *jobs.Jobs |
| 106 | |
| 107 | // jobPages is the status page, its polled fragment and its event |
| 108 | // stream, over that registry. |
| 109 | jobPages *jobs.Handlers |
| 110 | |
| 111 | // previews holds the sheet list's rendered thumbnails. One per |
| 112 | // process, and in memory only — see previewcache.go for why a |
| 113 | // column would be the wrong place even though the content is safe. |
| 114 | previews *previewCache |
| 115 | } |
| 116 | |
| 117 | // New builds an App. |
| 118 | func New(cfg Config) *App { |
| 119 | a := &App{ |
| 120 | db: cfg.DB, |
| 121 | auth: cfg.Auth, |
| 122 | sealer: cfg.Sealer, |
| 123 | origin: cfg.Origin, |
| 124 | admit: cfg.Admit, |
| 125 | hub: live.NewHub(), |
| 126 | teamSettings: cfg.Team, |
| 127 | google: cfg.GoogleImport, |
| 128 | // nil logger means slog.Default(), which is exactly what main |
| 129 | // passes rastrillo everywhere else. |
| 130 | jobs: jobs.New(nil), |
| 131 | previews: newPreviewCache(), |
| 132 | } |
| 133 | // NewHandlers' only failure is a nil field in a Config this |
| 134 | // function just built, so a failure here is this line being wrong |
| 135 | // and nothing else — the same class of mistake as a template that |
| 136 | // will not parse, and handled the same way (parsePages). Failing at |
| 137 | // construction is louder than failing on the first import. |
| 138 | h, err := jobs.NewHandlers(jobs.Config{ |
| 139 | Jobs: a.jobs, |
| 140 | Render: a.renderJobPage, |
| 141 | RenderFragment: a.renderJobFragment, |
| 142 | }) |
| 143 | if err != nil { |
| 144 | panic("sheets: wiring job handlers: " + err.Error()) |
| 145 | } |
| 146 | a.jobPages = h |
| 147 | // Reclaim imports abandoned by a process that is not coming back. |
| 148 | // Only ones old enough to have no live job under any scheduling — |
| 149 | // two instances CAN overlap (a draining rolling replacement, a |
| 150 | // duplicate start), and a sweep that assumed otherwise would delete |
| 151 | // a running import out from under the person doing it. See |
| 152 | // sweepStaleImports. |
| 153 | a.sweepStaleImports() |
| 154 | return a |
| 155 | } |
| 156 | |
| 157 | // UseAuth attaches the sign-in flow after construction. |
| 158 | // |
| 159 | // It exists because the two are mutually dependent: auth needs an |
| 160 | // admission gate that reads this app's grants table, and the app needs |
| 161 | // auth to read sessions. Building the App first and attaching auth |
| 162 | // second is the smaller of the two knots — the alternative is a gate |
| 163 | // that closes over a database handle nobody else uses. |
| 164 | func (a *App) UseAuth(x *auth.Auth) { a.auth = x } |
| 165 | |
| 166 | // Router returns the mounted handler. |
| 167 | func (a *App) Router() http.Handler { |
| 168 | r := chi.NewRouter() |
| 169 | if a.native != nil { |
| 170 | r.Use(a.nativeResume) |
| 171 | } |
| 172 | |
| 173 | // Origin-checking CSRF, app-wide, on every state-changing method. |
| 174 | // App-wide rather than per-route because the failure mode of |
| 175 | // forgetting one route is silent, and there is no token to mint or |
| 176 | // remember to check. |
| 177 | // |
| 178 | // Skipped entirely when Origin is empty, which only ever happens in |
| 179 | // a test App: a Protect("") would compare every Origin header |
| 180 | // against the empty string and refuse every POST, turning a missing |
| 181 | // test fixture into a wall of 403s that look like an auth bug. |
| 182 | if a.homeRoutes != nil { |
| 183 | r.Use(a.homeRoutes.Middleware) |
| 184 | } else if a.origin != "" { |
| 185 | r.Use(csrf.Protect(a.origin)) |
| 186 | } |
| 187 | |
| 188 | // This /healthz is NOT what answers in a deployed instance: |
| 189 | // rastrillo.Serve registers its own GET /healthz on the outer mux |
| 190 | // (serve.go's buildHandler), and Go 1.22+ http.ServeMux prefers that |
| 191 | // exact pattern over this router's "/" mount, so the outer one wins |
| 192 | // every time in production. It exists here so App's own router is |
| 193 | // testable in isolation (see TestHealthz) and as the seam later |
| 194 | // routes mount alongside. |
| 195 | r.Get("/healthz", func(w http.ResponseWriter, _ *http.Request) { |
| 196 | w.WriteHeader(http.StatusOK) |
| 197 | }) |
| 198 | // Exact "/" only, not a catch-all: every other unknown path is the |
| 199 | // 404 page for a browser and plain text for anything else |
| 200 | // (TestIndexIsNotACatchAll pins both halves). |
| 201 | r.NotFound(a.routeNotFound) |
| 202 | r.MethodNotAllowed(a.methodNotAllowed(r)) |
| 203 | if a.dashboard != nil { |
| 204 | r.Handle("/api/oficina/dashboard", a.dashboard) |
| 205 | } |
| 206 | r.Get("/", a.handleIndex) |
| 207 | a.mountAuth(r) |
| 208 | if a.native != nil { |
| 209 | r.Handle("/native/*", a.native) |
| 210 | } |
| 211 | // Fingerprinted and immutably cached, mounted at the FS's own path |
| 212 | // with no prefix stripped — rastrillo's Assets uses |
| 213 | // http.FileServerFS semantics, where the URL path is "/" plus the |
| 214 | // FS path. |
| 215 | r.Handle("/static/*", staticHandler()) |
| 216 | r.Get(googleScriptPath, serveGoogleScript) |
| 217 | // estilo serves the suite's app icons (the bar's brand). |
| 218 | mountEstilo(r) |
| 219 | // Light/dark is a per-person preference set by a form, so it works |
| 220 | // with scripting off. estilo's handler and cookie; inside the CSRF |
| 221 | // check above and outside the session group, so an expired session |
| 222 | // cannot turn the click into a sign-in loop (spec §8.3). |
| 223 | r.Post("/appearance", chrome.HandleAppearance) |
| 224 | |
| 225 | // A share link is a capability, so this route is deliberately |
| 226 | // OUTSIDE the session group: no account, no member, no directory |
| 227 | // entry (spec §8.3). The token is the entire authorization. |
| 228 | r.Get("/l/{token}", a.handleLinkView) |
| 229 | |
| 230 | // Alta's team-mode readiness probe (team_probe.go): unauthenticated, |
| 231 | // no account data, {"team_mode":false} on an instance not in team |
| 232 | // mode. |
| 233 | r.Get(teamProbePath, a.handleTeamProbe) |
| 234 | |
| 235 | r.Group(func(r chi.Router) { |
| 236 | r.Use(a.requireSession) |
| 237 | // After the guard, so a 500 shows the viewer's own chrome. |
| 238 | r.Use(a.recoverToErrorPage) |
| 239 | r.Get("/api/native/jobs/{id}", a.handleNativeJob) |
| 240 | r.Get("/sheets", a.handleSheetList) |
| 241 | r.Post("/sheets", a.handleSheetCreate) |
| 242 | // Before the {sheetID} pattern below (handlers_import_page.go). |
| 243 | a.importRoutes(r) |
| 244 | r.Get("/sheets/{sheetID}", a.handleSheetPage) |
| 245 | // Rename. The other half of a Create button that no longer |
| 246 | // asks for a name — see handlers_rename.go. |
| 247 | r.Post("/sheets/{sheetID}/rename", a.handleSheetRename) |
| 248 | // The scriptless view. Spec §6 names the grid editor, drag-fill |
| 249 | // and live sync as the only script-required things; everything |
| 250 | // else, including editing any cell, works here. |
| 251 | r.Get("/sheets/{sheetID}/export.xlsx", a.handleExport) |
| 252 | r.Get("/sheets/{sheetID}/table", a.handleTable) |
| 253 | r.Post("/sheets/{sheetID}/table", a.handleTableWrite) |
| 254 | // Sharing. Sheet owners only — see sheetForSharing. |
| 255 | r.Get("/sheets/{sheetID}/share", a.handleShare) |
| 256 | r.Post("/sheets/{sheetID}/share", a.handleShareGrant) |
| 257 | r.Post("/sheets/{sheetID}/share/revoke", a.handleShareRevoke) |
| 258 | r.Post("/sheets/{sheetID}/share/link", a.handleLinkCreate) |
| 259 | r.Post("/sheets/{sheetID}/share/link/revoke", a.handleLinkRevoke) |
| 260 | // History, restore and undo. All three are scriptless, because |
| 261 | // putting something back is exactly the moment somebody wants |
| 262 | // the plainest possible interface. |
| 263 | r.Get("/sheets/{sheetID}/history", a.handleHistory) |
| 264 | r.Post("/sheets/{sheetID}/restore", a.handleRestore) |
| 265 | r.Post("/sheets/{sheetID}/undo", a.handleUndo) |
| 266 | // Comments. Reading needs a viewer's grant; writing needs |
| 267 | // commenter, which is what that role is for. |
| 268 | r.Get("/sheets/{sheetID}/comments", a.handleComments) |
| 269 | r.Post("/sheets/{sheetID}/comments", a.handleCommentAdd) |
| 270 | r.Post("/sheets/{sheetID}/comments/resolve", a.handleCommentResolve) |
| 271 | // Sort and filter. Non-destructive: it reorders what is shown, |
| 272 | // never what is stored — see ViewSpec for why that is a |
| 273 | // constraint and not a preference. |
| 274 | r.Post("/sheets/{sheetID}/view", a.handleViewSave) |
| 275 | |
| 276 | // The grid API answers JSON behind the same session as the pages. |
| 277 | r.Get("/api/sheets/{sheetID}/tabs/{tabID}/cells", a.handleCellsGet) |
| 278 | r.Post("/api/sheets/{sheetID}/tabs/{tabID}/cells", a.handleCellPost) |
| 279 | r.Post("/api/sheets/{sheetID}/tabs/{tabID}/cells/batch", a.handleCellBatchPost) |
| 280 | r.Post("/api/sheets/{sheetID}/tabs/{tabID}/format", a.handleFormatPost) |
| 281 | r.Post("/api/sheets/{sheetID}/tabs/{tabID}/size", a.handleSizePost) |
| 282 | r.Get("/api/sheets/{sheetID}/tabs/{tabID}/stream", a.handleStream) |
| 283 | |
| 284 | // The job status page, its polled fragment and its event |
| 285 | // stream. Inside the session group because jobs.Handlers reads |
| 286 | // the viewer with sessions.Current and answers a job only to |
| 287 | // its owner — mounted outside, every one of them would 404. |
| 288 | // |
| 289 | // The parameter MUST be named "id": rastrillo reads it with |
| 290 | // r.PathValue("id"), which chi populates from its own route |
| 291 | // pattern. A rename here is a silent 404 on every job page, |
| 292 | // which is why TestJobRouteParamIsNamedID pins it. |
| 293 | r.Get("/jobs/{id}", a.jobPages.StatusPage) |
| 294 | r.Get("/jobs/{id}/fragment", a.jobPages.Fragment) |
| 295 | r.Get("/jobs/{id}/events", a.jobPages.Events) |
| 296 | }) |
| 297 | return a.agentRoutes(r) |
| 298 | } |
| 299 | |