| 1 | package slides |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/estilo.git/sky" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/estilo.git/brand" |
| 11 | "amadan.net/oficina/estilo.git/chrome" |
| 12 | "amadan.net/oficina/estilo.git/theme" |
| 13 | "amadan.net/oficina/home/connect" |
| 14 | "amadan.net/oficina/home/handoff" |
| 15 | "amadan.net/oficina/home/teammode" |
| 16 | "amadan.net/oficina/slides/internal/slides/core" |
| 17 | "amadan.net/oficina/slides/internal/slides/live" |
| 18 | "amadan.net/oficina/slides/internal/slides/present" |
| 19 | rauth "amadan.net/rastrillo/rastrillo/auth" |
| 20 | "amadan.net/rastrillo/rastrillo/csrf" |
| 21 | "amadan.net/rastrillo/rastrillo/db" |
| 22 | "amadan.net/rastrillo/rastrillo/jobs" |
| 23 | "amadan.net/rastrillo/rastrillo/migrate" |
| 24 | "amadan.net/rastrillo/rastrillo/sessions" |
| 25 | "github.com/go-chi/chi/v5" |
| 26 | ) |
| 27 | |
| 28 | // New wires the whole app: schema, sign-in, router, static files. It |
| 29 | // returns a *http.ServeMux because rastrillo.Options.Mux is typed that |
| 30 | // way — the chi router mounts inside it. |
| 31 | // |
| 32 | // It is SKILL.md §1's app.go shape with one change: the origin and |
| 33 | // logger arguments the scaffold took have grown into Config (config.go), |
| 34 | // because sign-in needs four more settings and each of them is a |
| 35 | // startup refusal when it is missing outside development. Every one of |
| 36 | // those refusals happens before the database is touched, so a |
| 37 | // misconfigured instance never reaches the point of serving a request. |
| 38 | // |
| 39 | // The database handle is the caller's (cmd/slides/main.go's db.Open), |
| 40 | // not one this opens: SKILL.md §1's Resolve/Serve split depends on |
| 41 | // exactly one connection to the file. |
| 42 | // |
| 43 | // The second return value is the built *app, unexported so callers |
| 44 | // outside this package can only ever hold one (via :=) and call its |
| 45 | // exported methods — today, just Close, which releases the deck core's |
| 46 | // runtime. Returning it is what lets cmd/slides/main.go and the test |
| 47 | // harness release that resource on shutdown without this package |
| 48 | // exposing anything more of the app than it already did. |
| 49 | func New(d *db.DB, cfg Config) (*http.ServeMux, *app, error) { |
| 50 | a, authPlugin, err := newApp(d, cfg) |
| 51 | if err != nil { |
| 52 | return nil, nil, err |
| 53 | } |
| 54 | |
| 55 | r := chi.NewRouter() |
| 56 | // App-wide, from day one: every state-changing route added below |
| 57 | // is born covered. Origin-checking, not tokens — nothing to mint |
| 58 | // or forget in a form. a.cfg.Origin, not the caller's cfg.Origin: |
| 59 | // what this protects has to be the origin the app resolved. |
| 60 | if a.homeRoutes != nil { |
| 61 | r.Use(a.homeRoutes.Middleware) |
| 62 | } else { |
| 63 | r.Use(csrf.Protect(a.cfg.Origin)) |
| 64 | } |
| 65 | |
| 66 | // A panic anywhere in the router is the 500 page with the viewer's |
| 67 | // own chrome (errors.go); an unknown address is the 404 page, not |
| 68 | // chi's plain text; a GET of a POST-only path is that 404 too. |
| 69 | r.Use(a.recoverToErrorPage) |
| 70 | r.NotFound(a.routeNotFound) |
| 71 | r.MethodNotAllowed(a.methodNotAllowed(r)) |
| 72 | |
| 73 | if a.dashboard != nil { |
| 74 | r.Handle("/api/oficina/dashboard", a.dashboard) |
| 75 | } |
| 76 | // Team mode's readiness probe (team_answers.go), unauthenticated: |
| 77 | // {"team_mode":false} with team mode off, as Docs' and Sheets' are |
| 78 | // (Paul's ruling on oficina/sheets #52, deviation 5). |
| 79 | r.Get(teammode.ProbePath, a.teamProbe) |
| 80 | r.Get("/help/open-source", a.credits) |
| 81 | // The account menu's Appearance (estilo chrome). Inside the app-wide |
| 82 | // CSRF check above and outside the session group below: a session |
| 83 | // that expired mid-page must not turn the click into a sign-in loop. |
| 84 | r.Post("/appearance", chrome.HandleAppearance) |
| 85 | |
| 86 | // Unauthenticated: the front door and rauth's handlers. The sign-in |
| 87 | // page has to be reachable signed out or nobody could ever get in. |
| 88 | // |
| 89 | // Verify answers GET with the confirm door (renderConfirm), which |
| 90 | // spends nothing, and POST with the redemption, so it is mounted for |
| 91 | // both methods in both modes, wrapped alike: without the POST, the |
| 92 | // door's Sign in button gets a 405 and nobody signs in. A verified |
| 93 | // address that is not admitted is answered by rauth's Refused hook |
| 94 | // (refused), inside Callback and Verify. |
| 95 | // |
| 96 | // The sign-in door is rastrillo's screen in estilo's door (signin.go). |
| 97 | // POST /signin is Begin through beginSignin, which keeps the page the |
| 98 | // sign-in began from in the return memory (signin_return.go), and |
| 99 | // nothing else. POST /signin/forget is auth's Forget: "Use a different |
| 100 | // email" on the door and "Forget me on this device" on the signed-out |
| 101 | // page, a same-origin POST inside the app-wide CSRF check like any form. |
| 102 | begin := a.beginSignin(authPlugin.Begin) |
| 103 | if a.homeRoutes == nil { |
| 104 | r.Get(signinPath, a.standaloneSignin) |
| 105 | r.Post(signinPath, begin) |
| 106 | r.Get("/auth/callback", authPlugin.Callback) |
| 107 | r.Get("/auth/verify", authPlugin.Verify) |
| 108 | r.Post("/auth/verify", authPlugin.Verify) |
| 109 | r.Get(landedPath, a.landed) |
| 110 | r.Post("/signout", a.standaloneSignout(authPlugin.Signout)) |
| 111 | r.Get("/signed-out", a.signedOut) |
| 112 | } else { |
| 113 | h := a.homeRoutes |
| 114 | // The sign-in door's three routes (home/connect MIGRATING.md, step |
| 115 | // 6): /signin is always the door, offering Continue with Oficina |
| 116 | // ID; /signin/local is the door with email as the one way in, |
| 117 | // where connect sends people Oficina ID cannot help; |
| 118 | // /signin/oficina starts the Home exchange. connect hands both |
| 119 | // door routes to Slides' door (RoutesConfig.LocalSignin, |
| 120 | // signinDoor). All three sit behind Slides' admission check |
| 121 | // (admittedOnly). |
| 122 | r.Get(connect.SigninPath, a.admittedOnly(h.SigninDoor)) |
| 123 | r.Get(connect.SigninLocalPath, h.LocalGuard(a.admittedOnly(h.SigninLocal))) |
| 124 | r.Get(connect.SigninOficinaPath, a.admittedOnly(h.SigninOficina)) |
| 125 | r.Post(signinPath, h.LocalGuard(begin)) |
| 126 | r.Get("/auth/callback", h.LocalGuard(authPlugin.Callback)) |
| 127 | r.Get("/auth/verify", h.LocalGuard(authPlugin.Verify)) |
| 128 | r.Post("/auth/verify", h.LocalGuard(authPlugin.Verify)) |
| 129 | r.Post("/signout", a.homeSignout) |
| 130 | r.Get("/signed-out", h.SignedOut) |
| 131 | r.Get(connect.LocalCompletePath, a.homeLocalComplete) |
| 132 | r.Get(handoff.StartPath, a.home.Start) |
| 133 | r.Post(handoff.CallbackPath, a.home.Callback) |
| 134 | r.Get(handoff.FinishPath, a.home.Finish) |
| 135 | r.Get("/account/home", h.Account) |
| 136 | r.Post("/account/home", h.LinkStart) |
| 137 | r.Get("/account/home/confirm", a.home.ConfirmPage) |
| 138 | r.Post("/account/home/confirm", h.ConfirmPost) |
| 139 | // The member choice (team mode; connect answers 404 without the |
| 140 | // team hooks): no session yet, and the POST inside the app-wide |
| 141 | // CSRF check like any form (connect also demands this Origin). |
| 142 | r.Get(connect.ChoosePath, a.home.ChoosePage) |
| 143 | r.Post(connect.ChoosePath, a.home.ChoosePost) |
| 144 | } |
| 145 | r.Post(signinForgetPath, a.forget) |
| 146 | |
| 147 | // The share link, and the one screen this app serves to somebody |
| 148 | // with no session at all (spec §5). Outside the group below on |
| 149 | // purpose: the token IS the capability, so requiring a session |
| 150 | // would defeat the whole feature. It is still inside the chi |
| 151 | // router, so csrf.Protect and every other app-wide middleware |
| 152 | // covers it. |
| 153 | r.Get("/s/{token}", a.sharedDeck) |
| 154 | // The pictures on that page, behind the same capability and no |
| 155 | // other: the renderer writes their src as /s/{token}/assets/{ref} |
| 156 | // (assets.go's own comment says why this is three routes rather |
| 157 | // than one). |
| 158 | r.Get("/s/{token}/assets/{ref}", a.sharedAsset) |
| 159 | // And its uploaded fonts, the same way (deckfonts.go). |
| 160 | r.Get("/s/{token}/fonts/{ref}", a.sharedFont) |
| 161 | // And its scenes' code, sealed (scenes.go). |
| 162 | r.Get("/s/{token}/scenes/{id}/{ref}", a.sharedScene) |
| 163 | // And the thumbnails, for the same reason (thumbs.go). |
| 164 | r.Get("/s/{token}/slides/{file}", a.sharedSlideThumb) |
| 165 | // And the presentation stream, when the link's deck is being |
| 166 | // presented and its holder chose to follow along (share.go's |
| 167 | // sharedStream, spec §3.4). Here rather than on /p/{session} for |
| 168 | // the reason presentation.go's own comment gives: an audience |
| 169 | // stays behind the capability it arrived with, so revoking the |
| 170 | // link ends the follow. |
| 171 | r.Get("/s/{token}/stream", a.sharedStream) |
| 172 | |
| 173 | // Presenting (presentation.go, spec §3.4). Outside the group for |
| 174 | // the share link's reason and then some: the projector has no |
| 175 | // session, the phone in the presenter's hand has no session, and |
| 176 | // the audience following along has no session. Each screen carries |
| 177 | // its own capability — the session sqid to watch, the remote token |
| 178 | // to drive — and answers 404 to anything else. |
| 179 | r.Get("/p/{session}", a.presentSurface) |
| 180 | r.Get("/p/{session}/notes", a.presenterNotes) |
| 181 | r.Get("/p/{session}/stream", a.presentStream) |
| 182 | r.Get("/p/{session}/talk", a.presentTalk) |
| 183 | r.Get("/p/{session}/remote", a.remote) |
| 184 | r.Get("/p/{session}/assets/{ref}", a.presentAsset) |
| 185 | r.Get("/p/{session}/fonts/{ref}", a.presentFont) |
| 186 | r.Get("/p/{session}/scenes/{id}/{ref}", a.presentScene) |
| 187 | r.Get("/p/{session}/slides/{file}", a.presentSlideThumb) |
| 188 | r.Post("/p/{session}/command", a.presentCommand) |
| 189 | // Pairing a phone from the presenter window's menu: the signed-in |
| 190 | // presenter only, so it is a capability screen by its cookie. |
| 191 | r.Post("/p/{session}/pair", a.presentPair) |
| 192 | // The phone's way in: a scanned QR carries the code and the key, |
| 193 | // a typed code gets a form asking for the key. |
| 194 | r.Get("/r/{code}", a.remotePair) |
| 195 | |
| 196 | // Everything else needs a real, signed-in person (SKILL.md §5). A |
| 197 | // signed-out GET/HEAD redirects to /signin; anything else 403s. |
| 198 | r.Group(func(r chi.Router) { |
| 199 | r.Use(a.requireSession(authPlugin.RequireSession)) |
| 200 | r.Get("/", a.decks) |
| 201 | // One screen, one job (SKILL.md §7): the list links to a page |
| 202 | // for creating, and that page is the only place a deck is made. |
| 203 | r.Get("/decks/new", a.newDeck) |
| 204 | r.Post("/decks", a.createDeck) |
| 205 | // /d/{sqid} is the deck's own short URL — short because it is |
| 206 | // what a person pastes into a chat window. Bare, it opens the |
| 207 | // editor, as a document's address does in Docs; with a query |
| 208 | // (?slide=N, which every link inside it carries) it is the |
| 209 | // viewer (viewer.go's showDeck). |
| 210 | r.Get("/d/{sqid}", a.showDeck) |
| 211 | // Every slide's notes on one page — the crib sheet somebody |
| 212 | // presents from with scripts off (spec §8). |
| 213 | r.Get("/d/{sqid}/notes", a.deckNotes) |
| 214 | // Live sync (live.go, spec §3.3). All four are the deck's |
| 215 | // readers-and-writers — deckFor's audience, not the owner's |
| 216 | // alone — because a team deck is edited by the team. |
| 217 | // |
| 218 | // Inside the group and therefore inside csrf.Protect, unlike |
| 219 | // the drive API: these are made by a browser, which sends the |
| 220 | // same-origin evidence csrf.Protect looks for. |
| 221 | r.Get("/d/{sqid}/updates", a.updatesGet) |
| 222 | r.Post("/d/{sqid}/updates", a.updatesPost) |
| 223 | r.Get("/d/{sqid}/stream", a.deckStream) |
| 224 | r.Post("/d/{sqid}/presence", a.deckPresence) |
| 225 | // The editor (editor.go, spec §3.1): deckFor's audience, like |
| 226 | // the live-sync routes it drives — a team deck is edited by the |
| 227 | // team. The slide HTML its stage and strip fetch is the |
| 228 | // session-cookie twin of the API's own. |
| 229 | r.Get("/d/{sqid}/edit", a.deckEditor) |
| 230 | r.Get("/d/{sqid}/slides/{file}", a.deckSlide) |
| 231 | // Images (assets.go, spec §2.7). Sign, register, serve — the |
| 232 | // deck's readers-and-writers, like the live-sync routes: a team |
| 233 | // deck is illustrated by the team. The PUT is the development |
| 234 | // receiving end for a store that cannot presign (blobs.Dir) and |
| 235 | // refuses itself on one that can. |
| 236 | r.Post("/d/{sqid}/uploads", a.signUpload) |
| 237 | r.Put("/d/{sqid}/uploads/{ref}", a.putUpload) |
| 238 | // A clip's staged video, back to the person who staged it, so |
| 239 | // their browser can draw its poster (clips.go). |
| 240 | r.Get("/d/{sqid}/uploads/{ref}", a.stagedVideo) |
| 241 | r.Post("/d/{sqid}/assets", a.registerAsset) |
| 242 | r.Get("/d/{sqid}/assets/{ref}", a.deckAsset) |
| 243 | // Fonts (deckfonts.go): a family from the signed-in person's own |
| 244 | // library recorded for a deck they can edit, and the deck's |
| 245 | // fonts served to its readers, as its pictures are. |
| 246 | r.Post("/d/{sqid}/fonts", a.pickDeckFont) |
| 247 | r.Get("/d/{sqid}/fonts/{ref}", a.deckFont) |
| 248 | // Scenes (scenes.go): a scene's code, sealed, to the deck's |
| 249 | // readers as its pictures are; and the code panel's preview of |
| 250 | // unsaved code, sealed the same way and never stored. A bundle |
| 251 | // goes in through the uploads and assets routes above. |
| 252 | r.Get("/d/{sqid}/scenes/{id}/{ref}", a.deckScene) |
| 253 | r.Post("/d/{sqid}/scenes/preview", a.previewScene) |
| 254 | // Who changed a scene's code, named (editor.go). |
| 255 | r.Get("/d/{sqid}/scene-authors", a.deckSceneAuthors) |
| 256 | // Exporting to PDF (exports.go, spec §4.3). deckFor's audience, |
| 257 | // like presenting: anybody who can read the deck can take a |
| 258 | // copy of it away. The status page, its fragment and its SSE |
| 259 | // stream are inside this group because rastrillo/jobs answers |
| 260 | // them to the session's owner and nobody else. |
| 261 | r.Get("/d/{sqid}/export", a.exportForm) |
| 262 | r.Post("/d/{sqid}/export", a.startExport) |
| 263 | // One route for the status page and the file: chi matches whole |
| 264 | // segments, so {id} and {id}.pdf cannot both be patterns (see |
| 265 | // exportJobRoute). |
| 266 | r.Get("/d/{sqid}/export/{id}", a.exportJobRoute) |
| 267 | r.Get("/d/{sqid}/export/{id}/fragment", a.exportFragment) |
| 268 | r.Get("/d/{sqid}/export/{id}/events", a.exportEvents) |
| 269 | // Presenting starts here and nowhere else: anybody who can |
| 270 | // open the deck can read it to a room, so this is deckFor's |
| 271 | // audience rather than the owner's alone. |
| 272 | r.Post("/d/{sqid}/present", a.startPresenting) |
| 273 | // The editor's assistant (assist.go): a proposal, never a write. |
| 274 | // It answers ops the browser applies through its own commit, so |
| 275 | // the change is the person's, one undo step, saved through the |
| 276 | // queue like a keystroke. With SLIDES_AI off it answers a |
| 277 | // signed-in person the 404 an unknown path does. |
| 278 | r.Post("/d/{sqid}/assist", a.assistDeck) |
| 279 | // Sharing is the owner's, all four of these (share.go says |
| 280 | // why a team member who can read the deck still cannot mint a |
| 281 | // link to it). Who can open the deck is here too, as general |
| 282 | // access is under Share in Docs. |
| 283 | r.Get("/d/{sqid}/share", a.deckShare) |
| 284 | r.Post("/d/{sqid}/share", a.mintShareLink) |
| 285 | r.Post("/d/{sqid}/share/access", a.saveDeckAccess) |
| 286 | r.Post("/d/{sqid}/share/{id}/revoke", a.revokeShareLink) |
| 287 | // A follow-along code's link (qrlink.go): a share link made as |
| 288 | // the form above makes one, answered as JSON to the editor. |
| 289 | r.Post("/d/{sqid}/qr-link", a.qrLink) |
| 290 | // The deck's title and theme as a form: the editor's inspector |
| 291 | // is where they are changed, and this page is that for somebody |
| 292 | // with scripts off (the editor's <noscript> links it). |
| 293 | r.Get("/d/{sqid}/settings", a.deckSettings) |
| 294 | r.Post("/d/{sqid}/settings", a.saveDeckSettings) |
| 295 | // Deleting gets its own URL and its own page, never a modal |
| 296 | // and never a button on the settings form (AGENTS.md's |
| 297 | // destructive-action convention). The GET changes nothing. |
| 298 | r.Get("/d/{sqid}/delete", a.confirmDeleteDeck) |
| 299 | r.Post("/d/{sqid}/delete", a.deleteDeck) |
| 300 | // Agent tokens (agents.go, spec §7.1). A person's own, like |
| 301 | // their decks: minting one is handing a program the ability to |
| 302 | // write everything they can write. |
| 303 | r.Get("/agents", a.agents) |
| 304 | r.Post("/agents", a.createAgent) |
| 305 | r.Post("/agents/{id}/revoke", a.revokeAgent) |
| 306 | // A person's own fonts (library.go). Deleting gets its own page, |
| 307 | // like a deck's. |
| 308 | r.Get("/fonts", a.fonts) |
| 309 | r.Post("/fonts", a.uploadFonts) |
| 310 | r.Get("/fonts/files/{ref}", a.libraryFile) |
| 311 | r.Get("/fonts/delete", a.confirmDeleteFont) |
| 312 | r.Post("/fonts/delete", a.deleteFont) |
| 313 | }) |
| 314 | |
| 315 | mux := http.NewServeMux() |
| 316 | // The app serves its own static files — the framework never does. |
| 317 | // They are embedded (render.go) and fingerprinted: templates link |
| 318 | // them via {{asset ...}}, which returns a content-hashed URL the |
| 319 | // handler serves cacheable-forever. Mounted outside the chi router |
| 320 | // so the sign-in page can load its stylesheet signed out. |
| 321 | mux.HandleFunc("GET /static/credits.css", serveCreditsCSS) |
| 322 | // The suite's app icons (the bar's brand, the switcher's tiles), |
| 323 | // served from estilo rather than vendored. |
| 324 | mux.Handle("GET "+brand.Prefix, brand.Handler()) |
| 325 | // estilo's retired v1 Onest files, kept answering so a page cached |
| 326 | // before the chrome moved to the system face (estilo AGENTS.md row 9) |
| 327 | // still resolves its stylesheet. No page links them. |
| 328 | mux.Handle("GET "+theme.FontPrefix, theme.FontHandler()) |
| 329 | // The sky behind the sign-in door: a closed set of SVGs, public. |
| 330 | mux.Handle("GET "+sky.Prefix, sky.Handler()) |
| 331 | mux.Handle("GET /static/", assets.Handler()) |
| 332 | // The drive surface (api.go, spec §7), mounted HERE rather than in |
| 333 | // the chi router above, and this is the one deliberate exception in |
| 334 | // the whole app's routing. |
| 335 | // |
| 336 | // csrf.Protect refuses a POST that carries no Sec-Fetch-Site, no |
| 337 | // Origin and no Referer (csrf.SameOrigin's last clause), which is |
| 338 | // precisely what an agent's HTTP client sends: it is not a browser |
| 339 | // and has no such evidence to offer. Inside the chi router, every |
| 340 | // write over the API would be a 403 with an HTML body. |
| 341 | // |
| 342 | // Nothing is given up by moving it out. The API's whole gate is an |
| 343 | // `Authorization: Bearer` header, and a browser never attaches one |
| 344 | // on its own — so no page on any origin can make a request this |
| 345 | // surface will authenticate, which is what CSRF is an attack on. |
| 346 | // api.go's package comment says the same thing at length, and |
| 347 | // docs/api.md says it to the person reading the API. |
| 348 | if a.agent != nil { |
| 349 | mux.Handle("/api/v1/operations", a.agent) |
| 350 | mux.Handle("/api/v1/operations/", a.agent) |
| 351 | } |
| 352 | mux.Handle(apiPrefix+"/", a.apiRouter()) |
| 353 | mux.Handle("/", r) |
| 354 | return mux, a, nil |
| 355 | } |
| 356 | |
| 357 | // newApp is everything New does before the router: resolve the config |
| 358 | // fail-closed, apply the schema, build the sign-in plugin. |
| 359 | // |
| 360 | // Separate from New so this package's own tests can assert on the |
| 361 | // resolved *app — that a.cfg carries the origin the app is really |
| 362 | // protecting rather than the empty string a development caller passed |
| 363 | // in (config_test.go). New's own *app return is unexported, so a |
| 364 | // caller outside this package can hold one and Close it but never |
| 365 | // spell its type or read a.cfg; only a package-internal test can. |
| 366 | func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) { |
| 367 | // Fail closed, loudly, and before anything opens: Origin, |
| 368 | // InstanceKey, Mailer and AllowedAddresses each decide whether |
| 369 | // sign-in is safe, and each may default only when Env is exactly |
| 370 | // "development" (config.go's package comment). |
| 371 | cfg, list, err := resolve(cfg) |
| 372 | if err != nil { |
| 373 | return nil, nil, err |
| 374 | } |
| 375 | logger := cfg.Logger |
| 376 | // The assistant's client, built before anything opens so a key or |
| 377 | // base it cannot use is a startup refusal (config_ai.go). |
| 378 | var assistOn *assistant |
| 379 | if cfg.AI.On { |
| 380 | client, err := newAssistClient(cfg.AI) |
| 381 | if err != nil { |
| 382 | return nil, nil, fmt.Errorf("%w: %w", errAIConfig, err) |
| 383 | } |
| 384 | assistOn = newAssistant(client, cfg.AI.Models) |
| 385 | } |
| 386 | |
| 387 | // Apply BootSchema, not Schema: BootSchema is everything this |
| 388 | // app needs at boot (its own migrations plus sessions' and auth's), |
| 389 | // while Schema (migrations.go) stays just this app's own so the |
| 390 | // generator and its check never see a subsystem's tables and try |
| 391 | // to drop them. |
| 392 | homeConfig, err := connect.DecodeCredentials(cfg.Home, cfg.Origin) |
| 393 | if err != nil { |
| 394 | return nil, nil, err |
| 395 | } |
| 396 | if err := validateAgentConfig(cfg.AgentIssuer, cfg.AgentTeam, cfg.Origin, cfg.Home); err != nil { |
| 397 | return nil, nil, err |
| 398 | } |
| 399 | boot := BootSchema |
| 400 | if homeConfig != nil { |
| 401 | boot = migrate.Merge(BootSchema, homeSchema) |
| 402 | } |
| 403 | // Team mode (team_config.go): the configuration is verified against |
| 404 | // the Home credentials just decoded, and the marker read, before |
| 405 | // anything migrates. Off, this is one sqlite_master read and boot |
| 406 | // is unchanged; an activated database without the same binding |
| 407 | // refuses here. |
| 408 | team, err := teamSettings(cfg.Team, homeConfig, cfg.Origin) |
| 409 | if err != nil { |
| 410 | return nil, nil, err |
| 411 | } |
| 412 | if team != nil && cfg.AgentIssuer != "" && cfg.AgentTeam != team.Bindings().Team { |
| 413 | return nil, nil, errAgentConfig |
| 414 | } |
| 415 | boot, err = teamBootSchema(context.Background(), d.Writer(), team, boot) |
| 416 | if err != nil { |
| 417 | return nil, nil, err |
| 418 | } |
| 419 | migrated, err := migrate.Apply(context.Background(), d, boot) |
| 420 | if err != nil { |
| 421 | return nil, nil, err |
| 422 | } |
| 423 | // One line per boot. Result exists so this can be logged, and |
| 424 | // until something does, a fleet-wide adoption — every database |
| 425 | // stamped, no DDL run, exactly once, never again — produces no |
| 426 | // output at all, which is the last event you want to be silent. |
| 427 | logger.Info("migrate", "applied", migrated.Applied, |
| 428 | "skipped", migrated.Skipped, "adopted", migrated.Adopted) |
| 429 | |
| 430 | // The sign-in mailer: links are queued and sent after the response, |
| 431 | // to permitted addresses only (mailqueue.go). Closed by app.Close. |
| 432 | mailer := newMailQueue(cfg.Mailer, list.allows, nil, logger) |
| 433 | // a exists before the plugin so rauth can hold its Refused and |
| 434 | // RenderConfirm pages; it is filled in below, once everything it |
| 435 | // carries has been built. |
| 436 | a := &app{} |
| 437 | authPlugin, err := newAuthPlugin(cfg, d.Writer(), list, mailer, a) |
| 438 | if err != nil { |
| 439 | mailer.close() |
| 440 | return nil, nil, err |
| 441 | } |
| 442 | returnSeal, err := newReturnSealer(cfg.InstanceKey) |
| 443 | if err != nil { |
| 444 | mailer.close() |
| 445 | return nil, nil, err |
| 446 | } |
| 447 | |
| 448 | // One Runtime for the process: it owns the compiled wasm module, |
| 449 | // which is expensive to build and cheap to instantiate, and every |
| 450 | // deck opened gets its own instance from it (decks.go's openDeck). |
| 451 | // Built here rather than lazily on first use so a module that will |
| 452 | // not compile — a stale or truncated .wasm — is a startup refusal |
| 453 | // like every other one in this function, not a 500 on whichever |
| 454 | // request happens to open the first deck. |
| 455 | rt, err := core.New(context.Background()) |
| 456 | if err != nil { |
| 457 | mailer.close() |
| 458 | return nil, nil, err |
| 459 | } |
| 460 | |
| 461 | *a = app{ |
| 462 | db: d, |
| 463 | logger: logger, |
| 464 | cfg: cfg, |
| 465 | allowed: list, |
| 466 | returnSeal: returnSeal, |
| 467 | returnNow: time.Now, |
| 468 | core: rt, |
| 469 | auth: authPlugin, |
| 470 | mail: mailer, |
| 471 | hub: present.New(), |
| 472 | live: live.New(), |
| 473 | jobs: jobs.New(logger), |
| 474 | exports: newExportStore(), |
| 475 | pdf: &pdfRuntime{}, |
| 476 | teamOn: team, |
| 477 | assist: assistOn, |
| 478 | } |
| 479 | |
| 480 | // The optional session read behind every page outside the signed-in |
| 481 | // group (chrome.go's optionalViewer). The same table and cookie as |
| 482 | // rauth's own store. |
| 483 | sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, Logger: logger}) |
| 484 | if err != nil { |
| 485 | rt.Close(context.Background()) |
| 486 | mailer.close() |
| 487 | return nil, nil, err |
| 488 | } |
| 489 | a.sessions = sess |
| 490 | |
| 491 | if err := a.initHome(homeConfig); err != nil { |
| 492 | rt.Close(context.Background()) |
| 493 | mailer.close() |
| 494 | return nil, nil, err |
| 495 | } |
| 496 | if err := a.configureTeam(team, homeConfig); err != nil { |
| 497 | rt.Close(context.Background()) |
| 498 | mailer.close() |
| 499 | return nil, nil, err |
| 500 | } |
| 501 | |
| 502 | if err := a.configureAgentAccess(); err != nil { |
| 503 | a.Close() |
| 504 | return nil, nil, err |
| 505 | } |
| 506 | |
| 507 | // The export's status page, its polled fragment and its SSE stream |
| 508 | // (exports.go). rastrillo/jobs owns the lifecycle and the |
| 509 | // owner-only lookup; the two renderers are this app's, so the page |
| 510 | // is the app's own shell with the app's own words in it. |
| 511 | pages, err := jobs.NewHandlers(jobs.Config{ |
| 512 | Jobs: a.jobs, |
| 513 | Render: a.renderExportPage, |
| 514 | RenderFragment: a.renderExportFragment, |
| 515 | }) |
| 516 | if err != nil { |
| 517 | rt.Close(context.Background()) |
| 518 | mailer.close() |
| 519 | return nil, nil, err |
| 520 | } |
| 521 | a.jobPages = pages |
| 522 | return a, authPlugin, nil |
| 523 | } |
| 524 | |