| 1 | // Package home is the Oficina suite home app: identity, directory, |
| 2 | // provisioning glue shared by every instance in the suite. See |
| 3 | // AGENTS.md (binding) and |
| 4 | // docs/superpowers/specs/2026-08-30-home-design.md (the design) for |
| 5 | // what this service is and, just as importantly, is not. |
| 6 | // |
| 7 | // §13 step 2 is built: hand-rolled sign-in on keymaildev/signin with the |
| 8 | // Keymail upgrade, passkeys as an optional second factor with recovery |
| 9 | // codes, sealed link state, the person ref and the blind index. The |
| 10 | // front page is still a placeholder (page.go). |
| 11 | // |
| 12 | // Explicit credential and directory roles now exchange browser-bound assertions. |
| 13 | // A directory session establishes identity only. Membership-backed navigation |
| 14 | // does not authorize access to application content. |
| 15 | package home |
| 16 | |
| 17 | import ( |
| 18 | "context" |
| 19 | "errors" |
| 20 | "log/slog" |
| 21 | "net/http" |
| 22 | "strings" |
| 23 | "time" |
| 24 | |
| 25 | "amadan.net/oficina/estilo.git/theme" |
| 26 | "amadan.net/oficina/home/handoff" |
| 27 | "amadan.net/rastrillo/rastrillo/csrf" |
| 28 | "amadan.net/rastrillo/rastrillo/db" |
| 29 | "amadan.net/rastrillo/rastrillo/passkey" |
| 30 | "amadan.net/rastrillo/rastrillo/sessions" |
| 31 | "github.com/go-chi/chi/v5" |
| 32 | "github.com/keymaildev/signin" |
| 33 | ) |
| 34 | |
| 35 | // App holds the wiring. One per process. |
| 36 | // |
| 37 | // It holds the validated Secrets because every value this app persists |
| 38 | // is sealed on the way in, and the database handle because that is what |
| 39 | // it is sealed into. Nothing here reaches for a raw key. |
| 40 | type App struct { |
| 41 | mailboxes mailboxMemory |
| 42 | dash *dashboardState |
| 43 | runtime *Runtime |
| 44 | directory *directoryFeatures |
| 45 | consumer *handoff.Consumer |
| 46 | handoffStore *handoff.Store // the directory's: native exchange and sign-out-all |
| 47 | fresh *handoff.Consumer |
| 48 | op *operatorEndpoint |
| 49 | origins Origins |
| 50 | credentialHost string |
| 51 | directoryHost string |
| 52 | secrets Secrets |
| 53 | db *db.DB |
| 54 | links *linkStore |
| 55 | logger *slog.Logger |
| 56 | renderer *renderer |
| 57 | flow *signin.Flow |
| 58 | sessions *sessions.Sessions |
| 59 | |
| 60 | // door is the door's remembered way in (door.go, ruling 26): a sealed |
| 61 | // cookie on the person's own browser, never anything at rest here. |
| 62 | // Nil on the directory, which newDirectory builds without one and |
| 63 | // which never serves the door. |
| 64 | door *doorMemory |
| 65 | |
| 66 | // signinLimiter is signin.Flow's own limiter, held here so that /resolve |
| 67 | // spends the same per-IP budget sign-in does; resolveLimiter is |
| 68 | // /resolve's per-subject budget (credential). teamWrites is the Team |
| 69 | // page's per-owner budget (directory). |
| 70 | signinLimiter *signin.MemoryLimiter |
| 71 | resolveLimiter *signin.MemoryLimiter |
| 72 | teamWrites *signin.MemoryLimiter |
| 73 | |
| 74 | // passkeyCfg is the passkey config the app builds. Home mounts none |
| 75 | // of passkey's handlers (its ceremonies are its own, id_passkey.go), |
| 76 | // so this is never handed to passkey.New: it is the record the RP-ID |
| 77 | // guard reads, so that guard checks what the app configured rather |
| 78 | // than a literal (TestHomeNeverMountsFrameworkSignin). |
| 79 | passkeyCfg passkey.Config |
| 80 | } |
| 81 | |
| 82 | // New builds an App on validated secrets, and refuses anything less. |
| 83 | // |
| 84 | // Secrets is a value, so a zero one always exists and can always be |
| 85 | // passed; an earlier version of this comment claimed there was "no |
| 86 | // zero-value escape hatch", which was false — New(Secrets{}) compiled |
| 87 | // and ran, and an App with a nil Sealer would persist addresses in the |
| 88 | // clear, the exact failure this step exists to prevent. The claim is now |
| 89 | // true because it is checked rather than asserted. |
| 90 | // |
| 91 | // The checks duplicate LoadSecrets deliberately. LoadSecrets guards the |
| 92 | // boot path; this guards every other way an App can be constructed, |
| 93 | // which is every test and every future caller. |
| 94 | func New(secrets Secrets, d *db.DB, logger *slog.Logger) (*App, error) { |
| 95 | return NewWithOrigins(secrets, d, logger, Origins{Origin, directoryOrigin}) |
| 96 | } |
| 97 | |
| 98 | func NewWithOrigins(secrets Secrets, d *db.DB, logger *slog.Logger, origins Origins) (*App, error) { |
| 99 | if err := origins.validate(); err != nil { |
| 100 | return nil, err |
| 101 | } |
| 102 | if logger == nil { |
| 103 | logger = slog.Default() |
| 104 | } |
| 105 | switch { |
| 106 | case d == nil: |
| 107 | return nil, errors.New("home: no database") |
| 108 | case secrets.Sealer == nil: |
| 109 | return nil, errors.New("home: no Sealer, so nothing would be sealed at rest") |
| 110 | case len(secrets.Pepper) == 0: |
| 111 | return nil, errors.New("home: no pepper, so no address could be found again") |
| 112 | case secrets.SigninKey == ([32]byte{}): |
| 113 | return nil, errors.New("home: signing key is the zero value, which signin.Flow refuses") |
| 114 | case secrets.Mailer == nil: |
| 115 | return nil, errors.New("home: no mailer, so no sign-in link could be sent") |
| 116 | } |
| 117 | links := &linkStore{db: d, sealer: secrets.Sealer, logger: logger} |
| 118 | |
| 119 | rend, err := newRenderer() |
| 120 | if err != nil { |
| 121 | return nil, err |
| 122 | } |
| 123 | |
| 124 | // Exactly one Sessions per process, per the package's own |
| 125 | // instruction. TTL and SigninPath are named rather than defaulted so |
| 126 | // a reader of this file knows what they are without opening |
| 127 | // rastrillo. |
| 128 | sess, err := sessions.New(sessions.Config{ |
| 129 | DB: d.Writer(), |
| 130 | Origin: origins.Credential, |
| 131 | TTL: 30 * 24 * time.Hour, |
| 132 | SigninPath: "/signin", |
| 133 | Logger: logger, |
| 134 | }) |
| 135 | if err != nil { |
| 136 | return nil, err |
| 137 | } |
| 138 | |
| 139 | door, err := newDoorMemory(secrets, origins.Credential) |
| 140 | if err != nil { |
| 141 | return nil, err |
| 142 | } |
| 143 | |
| 144 | a := &App{ |
| 145 | door: door, |
| 146 | origins: origins, |
| 147 | credentialHost: strings.TrimPrefix(origins.Credential, "https://"), |
| 148 | directoryHost: strings.TrimPrefix(origins.Directory, "https://"), |
| 149 | secrets: secrets, |
| 150 | db: d, |
| 151 | links: links, |
| 152 | logger: logger, |
| 153 | renderer: rend, |
| 154 | flow: newFlow(secrets, links, origins.Credential), |
| 155 | sessions: sess, |
| 156 | } |
| 157 | |
| 158 | // The flow's default, made explicit so that /resolve shares its per-IP |
| 159 | // budget (resolve.go). |
| 160 | a.signinLimiter = signin.NewMemoryLimiter(15 * time.Minute) |
| 161 | a.flow.Limiter = blindSigninLimiter{next: a.signinLimiter, pepper: secrets.Pepper} |
| 162 | a.resolveLimiter = signin.NewMemoryLimiter(time.Hour) |
| 163 | |
| 164 | a.passkeyCfg = passkeyConfig(a) |
| 165 | |
| 166 | // Sweep at boot as well as on each put. A process that put a link |
| 167 | // and then restarted before the next one leaves that row behind |
| 168 | // forever otherwise, and this app is not expected to restart often. |
| 169 | // Logged rather than fatal: expired sealed rows are untidy, not |
| 170 | // unsafe, and refusing to boot over housekeeping is the wrong trade. |
| 171 | if err := a.links.sweep(context.Background(), time.Now()); err != nil { |
| 172 | logger.Warn("sweeping expired sign-in links at boot", "err", err) |
| 173 | } |
| 174 | if err := a.sweepNativeAtBoot(context.Background()); err != nil { |
| 175 | logger.Warn("sweeping expired native codes at boot", "err", err) |
| 176 | } |
| 177 | |
| 178 | return a, nil |
| 179 | } |
| 180 | |
| 181 | // Router returns the mounted handler. |
| 182 | func (a *App) Router() http.Handler { |
| 183 | if a.runtime != nil && a.runtime.role == "directory" { |
| 184 | return a.directoryRouter() |
| 185 | } |
| 186 | r := chi.NewRouter() |
| 187 | |
| 188 | r.Use(a.serveKnownHost) |
| 189 | // estilo's error page for a browser, plain text for anything else |
| 190 | // (chrome.go). Unknown hosts never reach these: serveKnownHost answers |
| 191 | // them first, with an empty 404. |
| 192 | r.NotFound(a.notFound) |
| 193 | r.MethodNotAllowed(a.methodNotAllowed) |
| 194 | a.mountCredits(r) |
| 195 | |
| 196 | r.Get("/", func(w http.ResponseWriter, r *http.Request) { |
| 197 | if strings.ToLower(r.Host) == a.credentialHost { |
| 198 | w.Header().Set("Location", a.origins.Directory+"/") |
| 199 | w.WriteHeader(http.StatusSeeOther) |
| 200 | return |
| 201 | } |
| 202 | a.handleIndex(w, r) |
| 203 | }) |
| 204 | // This /healthz is NOT what answers in a deployed instance: |
| 205 | // rastrillo.Serve registers its own GET /healthz on the outer mux |
| 206 | // (serve.go's buildHandler), and Go 1.22+ http.ServeMux prefers that |
| 207 | // exact pattern over this router's "/" mount, so the outer one wins |
| 208 | // every time in production. It exists here so App's own router is |
| 209 | // testable in isolation (see TestHealthz) and as the seam later |
| 210 | // routes mount alongside — mirrors Sheets' internal/sheets/app.go. |
| 211 | r.Get("/healthz", func(w http.ResponseWriter, _ *http.Request) { |
| 212 | w.WriteHeader(http.StatusOK) |
| 213 | }) |
| 214 | |
| 215 | if a.runtime != nil && a.runtime.role == "credential" { |
| 216 | // Outside csrf.Protect on purpose, with its own exact origin |
| 217 | // check: a consumer's sign-out arrives same-site or cross-site, |
| 218 | // never same-origin. GET only renders the "Finish signing out" |
| 219 | // page. See signoutPath. |
| 220 | r.With(a.credentialOnly).Post(signoutPath, a.handleCredentialSignout) |
| 221 | r.With(a.credentialOnly).Get(signoutPath, a.handleCredentialSignoutPage) |
| 222 | r.With(a.credentialOnly).Get("/signed-out", func(w http.ResponseWriter, r *http.Request) { a.render(w, r, 200, "id_signed_out.html", nil) }) |
| 223 | // Oficina ID for the native apps (native.go): JSON only, outside |
| 224 | // csrf.Protect because each refuses any browser evidence header. |
| 225 | a.mountNative(r) |
| 226 | } |
| 227 | |
| 228 | r.Group(func(r chi.Router) { |
| 229 | r.Use(a.credentialOnly) |
| 230 | // POST /signin is an unauthenticated endpoint that sends mail and makes |
| 231 | // outbound DNS and HTTPS calls decided by the submitted address — a |
| 232 | // blind-SSRF surface by design — and csrf.Protect is pure origin |
| 233 | // evidence (Sec-Fetch-Site, then Origin, then Referer) that never |
| 234 | // consults a session, so it works before anybody is signed in. |
| 235 | r.Use(csrf.Protect(a.origins.Credential)) |
| 236 | if a.runtime != nil && a.runtime.role == "credential" { |
| 237 | r.Get("/authorize", a.handleAuthorize) |
| 238 | r.Get("/dashboard/authorize", a.beginDashboard) |
| 239 | r.With(a.sessions.Require).Get("/dashboard/resume", a.authorizeDashboard) |
| 240 | r.With(a.sessions.Require).Get("/authorize/resume", a.handleAssertion) |
| 241 | r.With(a.sessions.Require).Post("/authorize/resume", a.handleAssertion) |
| 242 | // Adding a team member by email (team-members.md §4): only |
| 243 | // with HOME_RESOLVE_KEY configured. |
| 244 | if a.runtime.resolveSigner != nil { |
| 245 | r.Get(resolvePath, a.handleResolve) |
| 246 | r.Post(resolvePath, a.handleResolvePost) |
| 247 | } |
| 248 | if a.op != nil { |
| 249 | r.Get(operatorConfirm, a.handleCredentialConfirm) |
| 250 | r.Post(operatorConfirm, a.handleCredentialConfirmPost) |
| 251 | } |
| 252 | versionAsset("/static/assertion.js", staticAsset("assertion.js")) |
| 253 | r.Get("/static/assertion.js", serveAsset(staticAsset("assertion.js"), "text/javascript; charset=utf-8")) |
| 254 | } |
| 255 | r.Get("/signin", a.handleSigninForm) |
| 256 | r.Post("/signin", a.handleSigninBegin) |
| 257 | r.Get("/signin/sent", a.handleSigninSent) |
| 258 | // Forget (door.go): "Use a different email", and the confirm page |
| 259 | // an app's signed-out page chains to. POSTs behind csrf.Protect. |
| 260 | r.Post(forgetPath, a.handleForget) |
| 261 | r.Get(forgetChainPath, a.handleForgetChainPage) |
| 262 | r.Post(forgetChainPath, a.handleForgetChain) |
| 263 | // GET renders, POST redeems. See handleVerifyForm for why. |
| 264 | r.Get(linkPath, a.handleVerifyForm) |
| 265 | r.Post(linkPath, a.handleVerify) |
| 266 | r.Get(callbackPath, a.handleCallback) |
| 267 | |
| 268 | // The second factor. The ceremony endpoints are JSON POSTs driven by |
| 269 | // static/passkey.js; the recovery POST is a plain form and works |
| 270 | // with script off, because recovery is exactly the moment WebAuthn |
| 271 | // is not working. |
| 272 | r.Get(confirmPath, a.handlePasskeyConfirm) |
| 273 | r.Get("/passkey/replace", a.handleReplacement) |
| 274 | r.Post("/passkey/replace/begin", a.idBegin("replace")) |
| 275 | r.Post("/passkey/replace/finish", a.idFinish("replace")) |
| 276 | r.Get("/passkey/replaced", a.handleReplacementDone) |
| 277 | r.Post("/passkey/notice", a.handleNoticeRetry) |
| 278 | r.Post("/passkey/direct/begin", a.idBegin("direct")) |
| 279 | r.Post("/passkey/direct/finish", a.idFinish("direct")) |
| 280 | r.Post("/passkey/stepup/begin", a.idBegin("stepup")) |
| 281 | r.Post("/passkey/stepup/finish", a.idFinish("stepup")) |
| 282 | r.Post("/passkey/signin/begin", a.idBegin("signin")) |
| 283 | r.Post("/passkey/signin/finish", a.idFinish("signin")) |
| 284 | r.Post("/passkey/signin/recovery", a.idRecovery) |
| 285 | // Enrolling changes who can get in, and there is no operator reset, |
| 286 | // so it wants a recent session rather than merely a valid one — see |
| 287 | // enrolFreshness for the lockout this closes. |
| 288 | r.Group(func(r chi.Router) { |
| 289 | r.Use(a.sessions.RequireFresh(enrolFreshness)) |
| 290 | // Ending every device's grant changes who can get in, so it |
| 291 | // wants a recent session too (§10). |
| 292 | if a.runtime != nil && a.runtime.role == "credential" { |
| 293 | r.Get(signoutAllPath, a.handleSignoutAllPage) |
| 294 | r.Post(signoutAllPath, a.handleSignoutAll) |
| 295 | } |
| 296 | r.Get("/passkey/enrol", a.handlePasskeyEnrol) |
| 297 | r.Post("/passkey/register/begin", a.idBegin("register")) |
| 298 | r.Post("/passkey/register/finish", a.idFinish("register")) |
| 299 | }) |
| 300 | |
| 301 | // The codes page shows ten codes once, so it wants a recent session |
| 302 | // rather than merely a valid one. |
| 303 | r.Group(func(r chi.Router) { |
| 304 | r.Use(a.sessions.RequireFresh(codesFreshness)) |
| 305 | r.Get("/passkey/codes", a.handleRecoveryCodesPage) |
| 306 | r.Post("/passkey/codes", a.handleRegenerateRecoveryCodes) |
| 307 | }) |
| 308 | |
| 309 | // Stable, unfingerprinted paths: Task 7's scriptless allowlist has |
| 310 | // to name them, and a rule that cannot name its subject is not a |
| 311 | // rule. |
| 312 | r.Get("/static/webauthn.mjs", serveAsset(webauthnJS(), "text/javascript; charset=utf-8")) |
| 313 | r.Get("/static/passkey.js", serveAsset(staticAsset("passkey.js"), "text/javascript; charset=utf-8")) |
| 314 | // The door's passkey module: rastrillo's (passkey.JS()), the one |
| 315 | // the signin partial loads on its passkey door and email field. |
| 316 | r.Get(signinModule, serveAsset(signinJS(), "text/javascript; charset=utf-8")) |
| 317 | }) |
| 318 | |
| 319 | // Vendored from rastrillo's ui package, not linked from it: an app |
| 320 | // owns its stylesheet from the moment it lands, and |
| 321 | // `rastrillo doctor --fix` is what reconciles it on an upgrade. |
| 322 | mountCSS(r, "/static/tokens.css", staticAsset("tokens.css")) |
| 323 | mountCSS(r, "/static/theme.css", theme.CSS()) |
| 324 | mountBrand(r) |
| 325 | mountCalma(r) |
| 326 | mountSite(r) |
| 327 | |
| 328 | if a.op == nil { |
| 329 | return r |
| 330 | } |
| 331 | // The operator transport sits outside csrf.Protect and every session |
| 332 | // check (operator_http.go); it refuses any Cookie anyway. |
| 333 | return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 334 | if a.serveOperator(w, req) { |
| 335 | return |
| 336 | } |
| 337 | r.ServeHTTP(w, req) |
| 338 | }) |
| 339 | } |
| 340 | |