| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "net/http" |
| 7 | "net/url" |
| 8 | "strings" |
| 9 | |
| 10 | "amadan.net/oficina/estilo.git/brand" |
| 11 | "amadan.net/oficina/estilo.git/chrome" |
| 12 | "amadan.net/oficina/estilo.git/sky" |
| 13 | "amadan.net/oficina/estilo.git/theme" |
| 14 | |
| 15 | "github.com/go-chi/chi/v5" |
| 16 | |
| 17 | "amadan.net/oficina/home/connect" |
| 18 | "amadan.net/rastrillo/rastrillo/auth" |
| 19 | "amadan.net/rastrillo/rastrillo/db" |
| 20 | "amadan.net/rastrillo/rastrillo/migrate" |
| 21 | "amadan.net/rastrillo/rastrillo/sessions" |
| 22 | |
| 23 | "amadan.net/oficina/memoria/internal/memoria/index" |
| 24 | "amadan.net/oficina/memoria/internal/memoria/seal" |
| 25 | ) |
| 26 | |
| 27 | // App wires the whole app: schema, sealing, index, router, static files. |
| 28 | // |
| 29 | // The order matters. Migrations first, then the index is filled from the |
| 30 | // sealed rows — the index lives only in memory (see internal/memoria/index |
| 31 | // for why), so a boot that skipped the rebuild would serve an empty |
| 32 | // corpus and call it "nothing matched". |
| 33 | func App(d *db.DB, origin string, sealer *seal.Sealer, logger *slog.Logger) (*http.ServeMux, *app, error) { |
| 34 | return AppWith(d, Config{Origin: origin, Sealer: sealer}, logger) |
| 35 | } |
| 36 | |
| 37 | // AppWith is App from the whole configuration, which is what main calls: |
| 38 | // team mode is decided here, before anything migrates. |
| 39 | // |
| 40 | // With the five MEMORIA_TEAM_* variables set, the provisioning record is |
| 41 | // verified against cfg's Home credentials and origin, and the marker is |
| 42 | // read, before migrate.Apply runs: a database already activated in team |
| 43 | // mode refuses to boot without the same binding (team_config.go). With |
| 44 | // them unset, and a database never activated, this is App exactly as it |
| 45 | // was — BootSchema, applied the same way. |
| 46 | func AppWith(d *db.DB, cfg Config, logger *slog.Logger) (*http.ServeMux, *app, error) { |
| 47 | origin, sealer := cfg.Origin, cfg.Sealer |
| 48 | settings, err := teamSettings(cfg.Team, cfg.Home, origin) |
| 49 | if err != nil { |
| 50 | return nil, nil, err |
| 51 | } |
| 52 | schema, err := teamBootSchema(context.Background(), d.Writer(), settings, BootSchema) |
| 53 | if err != nil { |
| 54 | return nil, nil, err |
| 55 | } |
| 56 | migrated, err := migrate.Apply(context.Background(), d, schema) |
| 57 | if err != nil { |
| 58 | return nil, nil, err |
| 59 | } |
| 60 | logger.Info("migrate", "applied", migrated.Applied, |
| 61 | "skipped", migrated.Skipped, "adopted", migrated.Adopted) |
| 62 | |
| 63 | ix, err := index.Open() |
| 64 | if err != nil { |
| 65 | return nil, nil, err |
| 66 | } |
| 67 | |
| 68 | // Custody starts nil and stays nil until UseSiblings supplies one. |
| 69 | // nil withholds every sibling passage rather than rendering it, so |
| 70 | // the un-wired state is the closed one — slice 0 stores nothing owned |
| 71 | // by anybody else, which makes nil correct rather than a gap. See |
| 72 | // Store.custody, and UseSiblings for why this is a setter. |
| 73 | store := NewStore(d, sealer, ix, nil) |
| 74 | indexed, err := store.Rebuild(context.Background()) |
| 75 | if err != nil { |
| 76 | // A failed rebuild is fatal, not a warning. Serving with a |
| 77 | // partly-filled index means every search silently under-reports, |
| 78 | // which is the plausible-empty-list failure this codebase treats |
| 79 | // as the worst available. |
| 80 | return nil, nil, err |
| 81 | } |
| 82 | logger.Info("index rebuilt", "passages", indexed) |
| 83 | |
| 84 | // Reclaim runs that were in flight when the process last stopped. |
| 85 | // |
| 86 | // Sound by construction rather than by timeout: a process that has |
| 87 | // just started cannot be running a sync, so anything still marked |
| 88 | // in flight was killed by the platform sleeping the app. Without |
| 89 | // this the connector wedges permanently on its NORMAL path — the |
| 90 | // goroutine dies without writing, the row stays "fetching", and |
| 91 | // every later sync is refused as already running. |
| 92 | reclaimed, err := store.ReclaimRuns(context.Background()) |
| 93 | if err != nil { |
| 94 | return nil, nil, err |
| 95 | } |
| 96 | if reclaimed > 0 { |
| 97 | logger.Info("reclaimed interrupted syncs", "runs", reclaimed) |
| 98 | } |
| 99 | |
| 100 | a := &app{db: d, logger: logger, store: store, syncer: NewSyncer(store, logger), origin: origin} |
| 101 | if settings != nil { |
| 102 | a.teamWiring = &teamWiring{settings: settings, transport: cfg.teamTransport, clock: cfg.teamClock} |
| 103 | // Every person-made write is guarded from here on, before the |
| 104 | // runtime exists: a write that arrives without a request's |
| 105 | // standing is refused rather than let through (team_guard.go). |
| 106 | store.team = true |
| 107 | } |
| 108 | |
| 109 | if err := a.wireNative(origin); err != nil { |
| 110 | return nil, nil, err |
| 111 | } |
| 112 | r := chi.NewRouter() |
| 113 | // Outermost, so a panic anywhere in the router is the 500 page with a |
| 114 | // reference. The page reads the session itself (admissionOf), so it |
| 115 | // shows the viewer's own chrome however deep the panic was. |
| 116 | r.Use(a.recoverToErrorPage) |
| 117 | r.Use(a.native.Resume) |
| 118 | r.Use(a.homeMiddleware(origin)) |
| 119 | // Unknown routes, and a GET of a POST-only path, are the 404 page (a |
| 120 | // browser) or plain text (anything else). They were Go's plain |
| 121 | // "404 page not found" in the browser's monospace. |
| 122 | r.NotFound(a.routeNotFound) |
| 123 | r.MethodNotAllowed(a.methodNotAllowed(r)) |
| 124 | |
| 125 | r.Post("/native/request", a.native.ServeHTTP) |
| 126 | r.Post("/native/exchange", a.native.ServeHTTP) |
| 127 | r.Get("/native/start", a.native.ServeHTTP) |
| 128 | // The approval page is the native kit's, styled by one inline |
| 129 | // <style>: allowed by its hash on this route alone (native.go). |
| 130 | r.Get("/native/authorize", nativeApprovalCSP(a.native.ServeHTTP)) |
| 131 | r.Post("/native/authorize", nativeApprovalCSP(a.native.ServeHTTP)) |
| 132 | |
| 133 | // Appearance (estilo chrome §8.3): inside the app-wide CSRF check |
| 134 | // (homeMiddleware) and OUTSIDE the session gate, so a session that |
| 135 | // expired mid-page cannot turn the click into a sign-in loop. It sets |
| 136 | // one host-only preference cookie and redirects to a SafeReturn path. |
| 137 | r.Post("/appearance", chrome.HandleAppearance) |
| 138 | |
| 139 | // Public: the sign-in door and auth's own callbacks. The door is |
| 140 | // rastrillo's screen in estilo's door (signin.go). With Home its three |
| 141 | // routes (home/connect MIGRATING.md, step 6): /signin is always the |
| 142 | // door, offering Continue with Oficina ID; /signin/local is the door |
| 143 | // with email as the one way in, where connect sends people Oficina ID |
| 144 | // cannot help; /signin/oficina starts the Home exchange. All three sit |
| 145 | // behind the admission check (signin_admission.go's admittedOnly), |
| 146 | // which asks requireSession's question of a live web sign-in first. |
| 147 | // Standalone, /signin is the email door and the other two answer 404. |
| 148 | // Literals, so the route gate can read them; TestDoorRoutesAreConnects |
| 149 | // keeps them equal to connect's SigninPath, SigninLocalPath, |
| 150 | // SigninOficinaPath and ChoosePath, and to auth's Forget. |
| 151 | r.Get("/signin", a.signinRoute) |
| 152 | r.Get("/signin/local", a.signinLocalRoute) |
| 153 | r.Get("/signin/oficina", a.signinOficinaRoute) |
| 154 | // "Use a different email" on the door and "Forget me on this device" |
| 155 | // on the signed-out page: a same-origin POST, inside the CSRF check |
| 156 | // (homeMiddleware) like any form, and auth's own. With Home, the |
| 157 | // signed-out page's chains on to Oficina ID's own Forget (signin.go's |
| 158 | // forget). |
| 159 | r.Post("/signin/forget", a.forget) |
| 160 | // The member choice (team mode; connect answers 404 without the team |
| 161 | // hooks): no session yet, and the POST inside the CSRF check like any |
| 162 | // form (connect also demands this Origin). Standalone, 404. |
| 163 | r.Get("/account/home/choose", func(w http.ResponseWriter, r *http.Request) { |
| 164 | if a.home == nil { |
| 165 | a.routeNotFound(w, r) |
| 166 | return |
| 167 | } |
| 168 | a.home.bridge.ChoosePage(w, r) |
| 169 | }) |
| 170 | r.Post("/account/home/choose", func(w http.ResponseWriter, r *http.Request) { |
| 171 | if a.home == nil { |
| 172 | a.routeNotFound(w, r) |
| 173 | return |
| 174 | } |
| 175 | a.spentOnMint(a.home.bridge.ChoosePost)(w, r) |
| 176 | }) |
| 177 | // Where Sign out lands, standalone and with Home alike: connect's |
| 178 | // SignedOut with Home (which puts the Forget path on the page), |
| 179 | // Memoria's own standalone. Never a 404 in either mode. |
| 180 | r.Get("/signed-out", a.signedOut) |
| 181 | // The Open source page is public, and it says nothing about the team. |
| 182 | // The sign-in page no longer links to it (Paul, 2026-11-19, superseding |
| 183 | // spec §8.4's link). It still shows the viewer's own chrome when |
| 184 | // somebody is signed in. |
| 185 | r.Get("/help/open-source", a.credits) |
| 186 | r.With(a.requireSession).Get("/account/home", func(w http.ResponseWriter, r *http.Request) { |
| 187 | if a.home == nil { |
| 188 | a.routeNotFound(w, r) |
| 189 | return |
| 190 | } |
| 191 | a.homeAccount(w, r) |
| 192 | }) |
| 193 | r.With(a.requireSession).Post("/account/home", func(w http.ResponseWriter, r *http.Request) { |
| 194 | if a.home == nil { |
| 195 | a.routeNotFound(w, r) |
| 196 | return |
| 197 | } |
| 198 | a.home.routes.LinkStart(w, r) |
| 199 | }) |
| 200 | r.With(a.requireSession).Get("/account/home/confirm", func(w http.ResponseWriter, r *http.Request) { |
| 201 | if a.home == nil { |
| 202 | a.routeNotFound(w, r) |
| 203 | return |
| 204 | } |
| 205 | a.home.bridge.ConfirmPage(w, r) |
| 206 | }) |
| 207 | r.With(a.requireSession).Post("/account/home/confirm", func(w http.ResponseWriter, r *http.Request) { |
| 208 | if a.home == nil { |
| 209 | a.routeNotFound(w, r) |
| 210 | return |
| 211 | } |
| 212 | a.home.routes.ConfirmPost(w, r) |
| 213 | }) |
| 214 | |
| 215 | // Everything else requires a session. memoria holds the team's work |
| 216 | // in one place, so there is no anonymous surface at all — not even a |
| 217 | // landing page. §4.3: admission is not authorization, but it is the |
| 218 | // door. |
| 219 | r.Group(func(r chi.Router) { |
| 220 | r.Use(a.requireSession) |
| 221 | // In team mode each route says what it needs of the roster: |
| 222 | // the three list pages render partial under Unknown standing, |
| 223 | // and everything else needs Member (team_access.go). Outside |
| 224 | // team mode both are no gate at all. |
| 225 | list, member := a.standing(needListing), a.standing(needMember) |
| 226 | r.With(member).Get("/api/native/session", a.nativeSession) |
| 227 | r.With(member).Post("/api/native/search", a.nativeSearch) |
| 228 | r.With(member).Post("/api/native/notes", a.nativeNote) |
| 229 | r.With(list).Get("/", a.index) |
| 230 | r.With(member).Get("/add", a.addContent) |
| 231 | r.With(list).Get("/documents", a.documents) |
| 232 | r.With(list).Get("/search", a.searchResults) |
| 233 | r.With(member).Get("/suggest", a.suggest) |
| 234 | r.With(member).Post("/documents", a.createDocument) |
| 235 | r.With(member).Get("/documents/{id}", a.showDocument) |
| 236 | r.With(member).Get("/documents/{id}/delete", a.confirmDelete) |
| 237 | r.With(member).Post("/documents/{id}/delete", a.deleteDocument) |
| 238 | r.With(member).Get("/facts/correct", a.correctFacts) |
| 239 | r.With(member).Post("/facts/correct", a.saveCorrection) |
| 240 | r.With(list).Get("/reports", a.reports) |
| 241 | r.With(member).Get("/answer", a.answer) |
| 242 | r.With(member).Post("/answer/feedback", a.saveFeedback) |
| 243 | r.With(member).Get("/answer/feedback/{id}", a.feedbackPage) |
| 244 | r.With(member).Post("/answer/feedback/{id}", a.saveFeedbackNote) |
| 245 | r.With(member).Post("/answer/feedback/{id}/delete", a.deleteFeedback) |
| 246 | r.With(member).Post("/reports/{id}/delete", a.deleteReport) |
| 247 | |
| 248 | // Connector routes sit INSIDE this group, so they inherit |
| 249 | // csrf.Protect and requireSession. A route mounted on the outer |
| 250 | // mux (as /static/ is) would bypass both. |
| 251 | r.Group(func(r chi.Router) { |
| 252 | r.Use(a.requireOwner) |
| 253 | r.Get("/connectors", a.connectors) |
| 254 | r.Get("/connectors/notion", a.notionConnector) |
| 255 | r.Post("/connectors/notion", a.saveNotionConnector) |
| 256 | r.Post("/connectors/notion/sync", a.startNotionSync) |
| 257 | r.Post("/connectors/notion/disconnect", a.disconnectNotion) |
| 258 | }) |
| 259 | }) |
| 260 | |
| 261 | mux := http.NewServeMux() |
| 262 | // Team mode's readiness probe, public and no-store: {"team_mode":false} |
| 263 | // with team mode off, the only thing a non-team instance gains |
| 264 | // (team_config.go). |
| 265 | mux.HandleFunc("GET /api/team", a.teamProbe) |
| 266 | mux.HandleFunc("GET /static/credits.css", serveCreditsCSS) |
| 267 | mux.Handle("GET /static/", assets.Handler()) |
| 268 | // estilo's retired v1 Onest files, kept answering so a page cached |
| 269 | // before the chrome moved to the system face (estilo AGENTS.md row 9) |
| 270 | // still resolves its stylesheet. No page links them. A literal, so the |
| 271 | // route gate can read it; TestFontRouteIsEstilosPrefix keeps it equal |
| 272 | // to theme.FontPrefix. |
| 273 | mux.Handle("GET /static/estilo/fonts/v1/", theme.FontHandler()) |
| 274 | // The sign-in door's sky (estilo sky), under its versioned prefix: |
| 275 | // public artwork, served before any session gate like the font. A |
| 276 | // literal for the same reason; TestSkyRouteIsEstilosPrefix keeps it |
| 277 | // equal to sky.Prefix. |
| 278 | mux.Handle("GET /static/estilo/sky/v3/", sky.Handler()) |
| 279 | // The app switcher's tile icons (estilo brand), public and |
| 280 | // sessionless like the sky. A literal for the same reason; |
| 281 | // TestBrandRouteIsEstilosPrefix keeps it equal to brand.Prefix. |
| 282 | mux.Handle("GET /static/estilo/brand/", brand.Handler()) |
| 283 | mux.Handle("/", r) |
| 284 | return mux, a, nil |
| 285 | } |
| 286 | |
| 287 | // MountAuth adds auth's routes. Separate from App because auth needs the |
| 288 | // admission gate and App builds the router; the caller wires both. |
| 289 | func (a *app) MountAuth(mux *http.ServeMux, origin string) { |
| 290 | r := chi.NewRouter() |
| 291 | r.Use(a.homeMiddleware(origin)) |
| 292 | // Guarded, not bare: the classifier inside Begin dials the submitted |
| 293 | // address's domain before Authorize runs. beginGuard says why. And |
| 294 | // the destination is kept Memoria's way: signinBegin says why. |
| 295 | r.Post("/auth/begin", a.signinBegin(origin, a.auth.Begin)) |
| 296 | // Verify answers GET with the confirm door (renderConfirm), which |
| 297 | // spends nothing, and POST with the redemption, so it is mounted for |
| 298 | // both methods in both modes: without the POST the door's Sign in |
| 299 | // button gets a 405 and nobody signs in. The path is baked into every |
| 300 | // emailed link. A verified address that is not admitted is answered |
| 301 | // by auth's Refused hook (app.refused), inside Callback and Verify. |
| 302 | if a.home == nil { |
| 303 | r.Get("/auth/callback", a.auth.Callback) |
| 304 | r.Get("/auth/verify", a.auth.Verify) |
| 305 | r.Post("/auth/verify", a.auth.Verify) |
| 306 | // Where a verified link lands (NewAuth's SignedInPath), and on to |
| 307 | // the page the person was heading for (return.go). |
| 308 | r.Get("/auth/landed", a.landed) |
| 309 | r.Post("/signout", a.standaloneSignout(a.auth.Signout)) |
| 310 | } else { |
| 311 | r.Get("/auth/callback", a.home.routes.LocalGuard(a.auth.Callback)) |
| 312 | r.Get("/auth/verify", a.home.routes.LocalGuard(a.auth.Verify)) |
| 313 | r.Post("/auth/verify", a.home.routes.LocalGuard(a.auth.Verify)) |
| 314 | // Chains to id.*'s /signout (a 307), which ends the Oficina |
| 315 | // session too and returns the browser to /signed-out (§9.5). |
| 316 | r.Post("/signout", a.homeSignout) |
| 317 | r.Get("/auth/start", a.home.bridge.Start) |
| 318 | r.Post("/auth/assertion", a.home.bridge.Callback) |
| 319 | // A finished exchange spends a page a local sign-in kept, as every |
| 320 | // landing does (spentOnMint). |
| 321 | r.Get("/auth/finish", a.spentOnMint(a.home.bridge.Finish)) |
| 322 | r.Get("/auth/local/complete", a.landedAfter(a.localComplete)) |
| 323 | } |
| 324 | mux.Handle("/auth/", r) |
| 325 | mux.Handle("POST /signout", r) |
| 326 | } |
| 327 | |
| 328 | // requireSession is auth.RequireSession, and it FAILS CLOSED. |
| 329 | // |
| 330 | // An earlier version fell through when auth was nil, so that tests could |
| 331 | // reach the routes without a mailer and a magic-link round trip. Sheets |
| 332 | // carries that seam and it is defensible there. Here it was not, for a |
| 333 | // reason a code review found: the safety argument rested on a test named |
| 334 | // TestProductionRefusesToStartWithoutSignin, and **that test did not |
| 335 | // exist** — the name survived a rename and lived on only in comments. So |
| 336 | // deleting main.go's UseAuth call compiled, left the suite green, and |
| 337 | // served every route unauthenticated. |
| 338 | // |
| 339 | // A seam whose guard is imaginary is a hole. Tests now build the app |
| 340 | // through AppForTest, which says what it is doing in its name. |
| 341 | func (a *app) requireSession(next http.Handler) http.Handler { |
| 342 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 343 | if a.allowUnauthenticated { |
| 344 | next.ServeHTTP(w, r) |
| 345 | return |
| 346 | } |
| 347 | if a.auth == nil { |
| 348 | a.logger.Error("no sign-in configured; refusing every request") |
| 349 | http.Error(w, "sign-in is not configured", http.StatusInternalServerError) |
| 350 | return |
| 351 | } |
| 352 | // Team mode configured and no roster runtime (WireHome never ran, |
| 353 | // or ran without Home): closed, never the owners list. |
| 354 | if a.teamMode() && a.team == nil { |
| 355 | a.logger.Error("team mode is configured but the roster is not; refusing every request") |
| 356 | http.Error(w, "sign-in is not configured", http.StatusInternalServerError) |
| 357 | return |
| 358 | } |
| 359 | // A signed-out page request goes to /signin WITH the page it asked |
| 360 | // for (spec §9.4): rastrillo's own refusal sends a bare /signin, so |
| 361 | // a document link opened signed out landed on the index. Anything |
| 362 | // else keeps rastrillo's answer below (a POST still gets its 403). |
| 363 | // Both modes: with Home, connect's Signin keeps a safe return_to |
| 364 | // through the exchange (feat/home-consumer added the Home half; |
| 365 | // a.sess reads the same cookie and table as Home's sessions). |
| 366 | if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| 367 | if _, ok := a.sess.From(r); !ok { |
| 368 | w.Header().Set("Cache-Control", "no-store") |
| 369 | http.Redirect(w, r, signinPath+"?return_to="+url.QueryEscape(r.URL.RequestURI()), http.StatusSeeOther) |
| 370 | return |
| 371 | } |
| 372 | } |
| 373 | guarded := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 374 | if a.teamMode() { |
| 375 | // The roster decides who this is for, on every request |
| 376 | // (team_access.go). |
| 377 | a.teamSession(w, r, next) |
| 378 | return |
| 379 | } |
| 380 | address, ok := a.identity(r) |
| 381 | if !ok || !a.Admit(address) { |
| 382 | // Still closed. What changes is what a REMOVED person is |
| 383 | // told: their session is ended and the sign-in page says |
| 384 | // why, where they used to meet a 404 on every page for |
| 385 | // thirty days. |
| 386 | switch _, st := a.admissionOf(r); { |
| 387 | case st == removed: |
| 388 | a.offboard(w, r) |
| 389 | return |
| 390 | case st == unresolved && a.home != nil: |
| 391 | // A Home link that could not be read now (storage, |
| 392 | // not identity): a retryable 503, never the 404 |
| 393 | // below, which the sign-in door's admission probe |
| 394 | // would read as a refusal (homeUnavailable). |
| 395 | a.homeUnavailable(w, r) |
| 396 | return |
| 397 | } |
| 398 | a.errorPage(w, r, http.StatusNotFound, kindRoute, "") |
| 399 | return |
| 400 | } |
| 401 | next.ServeHTTP(w, r) |
| 402 | }) |
| 403 | a.auth.RequireSession(guarded).ServeHTTP(w, r) |
| 404 | }) |
| 405 | } |
| 406 | |
| 407 | // requireOwner guards the connector routes. |
| 408 | // |
| 409 | // "Owner" is Config.Owners, and IN SLICE 0 THAT IS THE ENTIRE ADMITTED |
| 410 | // SET — MEMORIA_OWNERS is the admission list, so this is currently |
| 411 | // equivalent to requireSession. It is written as its own middleware |
| 412 | // anyway, and this comment says the equivalence out loud, because an |
| 413 | // earlier draft described the connector pages as "owners only" as though |
| 414 | // that were a restriction. Naming a gate for a distinction the app does |
| 415 | // not have is how a guard that guards nothing gets shipped. |
| 416 | // |
| 417 | // It fails CLOSED: no identity, or an empty owner list, refuses. |
| 418 | // |
| 419 | // Slice 1 replaces the owners list with S7 and there will be no list to |
| 420 | // check. These routes then need an owner predicate from wherever |
| 421 | // membership lives, or they lose their guard — recorded in the spec's |
| 422 | // open items, not left to be discovered. |
| 423 | // |
| 424 | // In team mode the owner is the roster's owner role, asked on every |
| 425 | // request: members search and read the team's memory, and only owners |
| 426 | // manage what feeds it (team_access.go's needOwner). MEMORIA_OWNERS then |
| 427 | // admits a local sign-in and nothing more. |
| 428 | func (a *app) requireOwner(next http.Handler) http.Handler { |
| 429 | owners := a.standing(needOwner)(next) |
| 430 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 431 | if a.teamMode() { |
| 432 | owners.ServeHTTP(w, r) |
| 433 | return |
| 434 | } |
| 435 | addr, ok := a.identity(r) |
| 436 | if !ok || !a.isOwner(addr) { |
| 437 | // 404, not 403: AGENTS.md's rule, and a 403 would confirm |
| 438 | // the route exists to someone who may not use it. The same |
| 439 | // page as an unknown address, so it confirms nothing either. |
| 440 | a.errorPage(w, r, http.StatusNotFound, kindRoute, "") |
| 441 | return |
| 442 | } |
| 443 | next.ServeHTTP(w, r) |
| 444 | }) |
| 445 | } |
| 446 | |
| 447 | // identity is the signed-in address, or false. |
| 448 | func (a *app) identity(r *http.Request) (string, bool) { |
| 449 | if a.testIdentity != "" { |
| 450 | return a.testIdentity, true |
| 451 | } |
| 452 | if s, ok := sessions.Current(r); ok && s.Method == connect.HomeMethod { |
| 453 | if a.home == nil { |
| 454 | return "", false |
| 455 | } |
| 456 | person, err := a.home.bridge.Resolve(r.Context(), s.Subject) |
| 457 | if err != nil { |
| 458 | return "", false |
| 459 | } |
| 460 | return person.Label, a.Admit(person.Label) |
| 461 | } |
| 462 | if s, ok := sessions.Current(r); ok && s.Method != "magiclink" && s.Method != "keymail" { |
| 463 | return "", false |
| 464 | } |
| 465 | id, ok := auth.From(r) |
| 466 | if !ok { |
| 467 | return "", false |
| 468 | } |
| 469 | return strings.ToLower(strings.TrimSpace(id.Address)), true |
| 470 | } |
| 471 | |
| 472 | func (a *app) isOwner(addr string) bool { |
| 473 | if len(a.owners) == 0 { |
| 474 | return false |
| 475 | } |
| 476 | for _, o := range a.owners { |
| 477 | if o == addr { |
| 478 | return true |
| 479 | } |
| 480 | } |
| 481 | return false |
| 482 | } |
| 483 | |
| 484 | // UseSiblings supplies the apps of record memoria may ask about |
| 485 | // passages. Called by main from Config. |
| 486 | // |
| 487 | // A setter, in the shape UseAuth already has here, and with the same |
| 488 | // hazard: production can forget to call it. What makes that survivable is |
| 489 | // which way the omission fails — a store with no custody withholds every |
| 490 | // sibling passage and says so on the page, where UseAuth's omission |
| 491 | // served every route unauthenticated. The failure is loud and visible to |
| 492 | // the first reader, not silent. |
| 493 | func (a *app) UseSiblings(c Custody) { a.store.custody = c } |
| 494 | |
| 495 | // WarmSiblings starts §6.5's wake poll and returns immediately. |
| 496 | // |
| 497 | // **Asynchronous on purpose, and gate 24 is written around that.** A |
| 498 | // synchronous warm-up would make the first request wait for three sibling |
| 499 | // wakes, which puts the latency back on the reader and undoes the whole |
| 500 | // point; an assertion that it finishes "before the first query" is either |
| 501 | // that, or a race between goroutines. So the gate asserts UNPROMPTED |
| 502 | // PRESENCE instead — every fixture is polled within a stated few seconds |
| 503 | // of boot, with no query issued at all — and the claim is that the poll |
| 504 | // happens on its own rather than that it wins a race. |
| 505 | // |
| 506 | // context.WithoutCancel: the poll outlives the request context that |
| 507 | // happened to be current, because it belongs to the process's wake and |
| 508 | // not to anybody's request. |
| 509 | func (a *app) WarmSiblings(ctx context.Context) { |
| 510 | s, ok := a.store.custody.(*Siblings) |
| 511 | if !ok || s == nil { |
| 512 | // No siblings configured (slice 0), or a Custody that is not the |
| 513 | // production roster. Nothing to warm, and not an error. |
| 514 | return |
| 515 | } |
| 516 | go s.Warm(context.WithoutCancel(ctx), a.store, a.logger) |
| 517 | } |
| 518 | |
| 519 | // SetOwners supplies the owner list. Called by main from Config. |
| 520 | func (a *app) SetOwners(owners []string) { a.owners = owners } |
| 521 | |
| 522 | // Store exposes the store, for gates that must inspect it. |
| 523 | func (a *app) Store() *Store { return a.store } |
| 524 | |
| 525 | // Syncer exposes the syncer, so a test can drive a run against a fake. |
| 526 | func (a *app) Syncer() *Syncer { return a.syncer } |
| 527 | |
| 528 | // AsPerson sets the identity AppForTest presents, so a gate can check |
| 529 | // that a non-owner is refused. Test seam only; production never sets it. |
| 530 | func (a *app) AsPerson(addr string) { a.testIdentity = addr } |
| 531 | |
| 532 | // AppForTest builds the app with a stub session so tests can exercise the |
| 533 | // routes. It is exported, obvious, and takes a testing marker so it |
| 534 | // cannot be reached from production by accident: cmd/memoria does not |
| 535 | // import testing. |
| 536 | func AppForTest(d *db.DB, origin string, sealer *seal.Sealer, logger *slog.Logger) (*http.ServeMux, *app, error) { |
| 537 | mux, a, err := App(d, origin, sealer, logger) |
| 538 | if err != nil { |
| 539 | return nil, nil, err |
| 540 | } |
| 541 | a.allowUnauthenticated = true |
| 542 | // An identity, and an owner list containing it. |
| 543 | // |
| 544 | // AppForTest used to bypass RequireSession entirely, which left no |
| 545 | // identity in the request context — so a gate on "is this person an |
| 546 | // owner" could not have been written at all, only asserted. Found by |
| 547 | // a design review. |
| 548 | a.testIdentity = TestOwner |
| 549 | a.owners = []string{TestOwner} |
| 550 | return mux, a, nil |
| 551 | } |
| 552 | |
| 553 | // TestOwner is the address AppForTest signs in as. |
| 554 | const TestOwner = "owner@test" |
| 555 | |