// Package web is Base's HTTP surface: sign-in, the member gate, Home, People, // the Store and Settings. package web import ( "context" "database/sql" "embed" "errors" "html/template" "io/fs" "log/slog" "mime" "net/http" "strings" "time" "github.com/go-chi/chi/v5" "amadan.net/oficina/home/connect" "amadan.net/oficina/home/handoff" "amadan.net/rastrillo/rastrillo/auth" "amadan.net/rastrillo/rastrillo/csrf" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/mail" "amadan.net/rastrillo/rastrillo/passkey" "amadan.net/rastrillo/rastrillo/pow" "amadan.net/rastrillo/rastrillo/sessions" "amadan.net/rastrillo/rastrillo/webauthn" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/base/internal/equipo" "amadan.net/oficina/base/internal/issuer" "amadan.net/oficina/base/internal/look" "amadan.net/oficina/base/internal/operations" "amadan.net/oficina/base/internal/store" ) //go:embed templates/*.html templates/partials/*.html var templateFS embed.FS // Installer installs and uninstalls catalogue apps for this Base; // *install.Installer is the real one. type Installer interface { // Start claims app's install before it returns, so the next page shows // it installing, and finishes the install in the background. Start(ctx context.Context, app string) error Uninstall(ctx context.Context, app string) error } type app struct { db *sql.DB cfg config.Config inst Installer logger *slog.Logger auth *auth.Auth sess *sessions.Sessions pk *passkey.Handlers pages *look.Renderer mailer mail.Sender // oficina is sign-in with Oficina ID, nil when cfg.Home is. oficina *oficina // ask is "Ask Base anything", nil when cfg.EquipoOrigin is empty. ask *asker // unrecorded are native clients Base couldn't record (ask_caps.go). unrecorded clientsUnrecorded } // App builds Base's router. d is rastrillo's database handle (auth and // sessions need it); store functions get d.Writer(). func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger *slog.Logger) (http.Handler, error) { if mailer == nil { return nil, errors.New("web: a mail sender is required") } if !mail.IsConfigured(mailer) && !cfg.AllowLoggedMail { return nil, errors.New("web: set CARLOS_SMTP_HOST and CARLOS_SMTP_FROM so Base can email sign-in links (BASE_ALLOW_LOGGED_MAIL=1 only for local runs)") } if cfg.InstanceKey == "" { return nil, errors.New("web: BASE_INSTANCE_KEY is required") } if logger == nil { logger = slog.Default() } sub, err := fs.Sub(templateFS, "templates") if err != nil { return nil, err } // newKey gives each chat form its own request key when the page is // drawn; startedText says when a job started, as of then. pages, err := look.NewRenderer(sub, template.FuncMap{"newKey": equipo.NewKey, "fileSize": fileSize, "lookupAnswer": lookupMarkdown, "sourceHost": sourceHost, "startedText": func(at *time.Time) string { return startedText(*at, time.Now(), cfg.Timezone) }}) if err != nil { return nil, err } a := &app{db: d.Writer(), cfg: cfg, inst: inst, logger: logger, pages: pages, mailer: mailer} if cfg.EquipoOrigin != "" { a.ask = newAsker(cfg.EquipoOrigin, cfg.InstanceKey, cfg.Name, cfg.Timezone) } guard, err := pow.New(pow.Config{InstanceKey: cfg.InstanceKey, Nonces: pow.SQLNonces(d.Writer()), Difficulty: pow.NoProof, MinAge: pow.DefaultMinAge}) if err != nil { return nil, err } // With Oficina ID on, /signin leads with Oficina, so the email and // passkey door moves to /signin/local, and a local sign-in lands on // connect's LocalCompletePath, which picks up a link waiting for it. localSignin, signedIn := "/signin", "/" if cfg.Home != nil { localSignin, signedIn = "/signin/local", connect.LocalCompletePath } a.auth, err = auth.New(auth.Config{ DB: d.Writer(), Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: mailer, Logger: logger, Proof: guard, KeymailServers: []string{"keymail.dev"}, SigninScreen: true, SigninPath: localSignin, BeginPath: "/auth/begin", ForgetPath: "/auth/forget", SignedInPath: signedIn, Authorize: a.authorize, Refused: func(w http.ResponseWriter, r *http.Request, _ auth.Identity) { http.Redirect(w, r, localSignin+"?refused=1", http.StatusSeeOther) }, RenderConfirm: a.renderConfirm, }) if err != nil { return nil, err } // Passkeys share auth's sessions: the same table and, built for the same // origin, the same cookie. A passkey signs a member in on its own, through // the same admission check as an emailed link. sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, Logger: logger}) if err != nil { return nil, err } a.sess = sess a.pk, err = passkey.New(passkey.Config{ Sessions: sess, DB: d.Writer(), Origin: cfg.Origin, Logger: logger, Authorize: a.authorize, SignedInPath: "/", Remember: a.auth.RememberJar(), }) if err != nil { return nil, err } // Without an assertion key there are no installs to hand off to. var authorize http.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.Error(w, "unavailable", http.StatusServiceUnavailable) }) if cfg.AssertionKey != nil { if authorize, err = issuer.New(d.Writer(), cfg, CurrentMember, signedInAt, logger); err != nil { return nil, err } } if cfg.Home != nil { if a.oficina, err = a.newOficina(cfg.Home); err != nil { return nil, err } } r := chi.NewRouter() if o := a.oficina; o != nil { // connect's middleware is csrf.Protect with one exception, POST // /auth/assertion, whose signed assertion is its own proof. r.Use(o.routes.Middleware) } else { r.Use(csrf.Protect(cfg.Origin)) } r.Get("/static/fonts/*", look.FontHandler().ServeHTTP) r.Get("/static/*", look.Assets.Handler().ServeHTTP) r.Get("/api/team", a.teamProbe) if o := a.oficina; o != nil { r.Get("/signin", a.oficinaSignin) r.Get("/signin/local", a.signin) r.Get("/signed-out", o.routes.SignedOut) r.Get(connect.LocalCompletePath, o.routes.LocalComplete) r.Get(handoff.StartPath, o.bridge.Start) r.Post(handoff.CallbackPath, o.bridge.Callback) r.Get(handoff.FinishPath, o.bridge.Finish) r.With(sess.Require).Get("/account/home", o.routes.Account) r.With(sess.Require).Post("/account/home", o.routes.LinkStart) r.With(sess.Require).Get("/account/home/confirm", o.bridge.ConfirmPage) r.With(sess.Require).Post("/account/home/confirm", a.oficinaConfirm) r.Post("/auth/begin", o.routes.LocalGuard(a.auth.Begin)) r.Get("/auth/callback", o.routes.LocalGuard(a.auth.Callback)) r.Get("/auth/verify", o.routes.LocalGuard(a.auth.Verify)) r.Post("/auth/verify", o.routes.LocalGuard(a.auth.Verify)) r.Post("/auth/signout", o.routes.Signout) // The native app's Oficina ID exchange. connect's Middleware lets // this one path past the CSRF check: it refuses anything a browser // sends, and reads and sets no cookies. r.Post(connect.NativeExchangePath, o.bridge.NativeExchange) r.Post("/signout", a.signout) } else { r.Get("/signin", a.signin) r.Post("/auth/begin", a.auth.Begin) r.Get("/auth/callback", a.auth.Callback) r.Get("/auth/verify", a.auth.Verify) r.Post("/auth/verify", a.auth.Verify) r.Post("/auth/signout", a.auth.Signout) } r.Post("/auth/forget", a.auth.Forget) r.Get(webauthnModulePath, serveScript(webauthn.JS())) r.Get(passkeyDoorPath, serveScript(passkey.JS())) r.Post(passkeyDoor.BeginPath, a.pk.DiscoverBegin) r.Post(passkeyDoor.FinishPath, a.pk.DiscoverFinish) r.Group(func(r chi.Router) { r.Use(a.requireMember) if a.ask != nil { r.Use(a.withAskCaps) } r.Get("/", a.home) r.Get("/people", a.people) r.Post("/people", a.invite) r.Get("/store", a.storePage) r.Post("/store/{app}/install", a.storeInstall) r.Get("/store/{app}/uninstall", a.uninstallPage) r.Post("/store/{app}/uninstall", a.storeUninstall) r.Get("/settings", a.settings) r.Post("/settings/appearance", a.settingsAppearance) r.Get("/api/v1/me", a.apiMeRead) r.Get("/api/v1/home", a.apiHomeRead) r.Get("/api/v1/store", a.apiStoreRead) r.Get("/api/v1/people", a.apiPeopleRead) r.Post("/api/v1/store/{app}/install", a.apiStoreInstall) r.Post("/api/v1/store/{app}/uninstall", a.apiStoreUninstall) r.Post("/api/v1/people", a.apiPeopleInvite) r.With(ownSignInOnly).Post(registerBeginPath, a.pk.RegisterBegin) r.With(ownSignInOnly).Post(registerFinishPath, a.pk.RegisterFinish) r.Method(http.MethodGet, "/authorize", authorize) if a.ask != nil { a.askRoutes(r) } }) return withOperations(operations.Handler(d.Writer(), cfg), r), nil } // withOperations sends operations.Path and everything under it to ops and // the rest to site. ops sits outside site's middleware: no CSRF check (its // callers are servers, which send no Origin) and no member gate (the // member's host token is its proof, and cookies count for nothing there). func withOperations(ops, site http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if p := r.URL.Path; p == operations.Path || strings.HasPrefix(p, operations.Path+"/") { ops.ServeHTTP(w, r) return } site.ServeHTTP(w, r) }) } // authorize admits a verified address that belongs to a member, and records // the member's first sign-in. It runs only after the address has been proved. func (a *app) authorize(address string) bool { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() m, ok, err := store.MemberByEmail(ctx, a.db, address) if err != nil || !ok { if err != nil { a.logger.Error("sign-in: member lookup", "err", err) } return false } if m.JoinedAt == nil { if err := store.MarkJoined(ctx, a.db, m.ID); err != nil { a.logger.Error("sign-in: mark joined", "err", err) return false } } return true } type ctxKey struct{} // CurrentMember is the signed-in member behind a request that passed the gate. func CurrentMember(r *http.Request) (store.Member, bool) { m, ok := r.Context().Value(ctxKey{}).(store.Member) return m, ok } // requireMember lets through only a session that belongs to a current // member, and puts that member on the request. A session from Base's own // sign-in names the member's address; one from Oficina ID (a browser's or // the native app's) names an Oficina account, which counts only through a // stored link to a member who still exists. A signed-out page request goes // to /signin; the native app and scripts (apiRequest) hear // 401 {"code":"unauthenticated"} instead, for no session or a session that // names nobody. func (a *app) requireMember(next http.Handler) http.Handler { gate := a.auth.RequireSession if a.oficina != nil { // sessions' own gate, whose sign-in page is /signin, not auth's // /signin/local: a signed-out visitor is offered Oficina first. gate = a.sess.Require } member := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") s, ok := sessions.Current(r) if !ok { http.Error(w, "forbidden", http.StatusForbidden) return } m, found, err := a.memberFor(r, s) switch { case err != nil: a.logger.Error("member gate", "err", err) http.Error(w, "unavailable", http.StatusServiceUnavailable) case !found && apiRequest(r): unauthenticated(w) case !found: http.Error(w, "forbidden", http.StatusForbidden) default: next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, m))) } }) paged := gate(member) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !apiRequest(r) { paged.ServeHTTP(w, r) return } s, ok := a.sess.From(r) if !ok { unauthenticated(w) return } member.ServeHTTP(w, sessions.WithSession(r, s)) }) } // memberFor is the member behind session s. found is false for a session // that names nobody who is a member now. func (a *app) memberFor(r *http.Request, s sessions.Session) (m store.Member, found bool, err error) { if connect.IsHomeDerived(s.Method) { // A browser, native or native-to-web sign-in through Oficina. The // native kinds end seven days after they were minted, however // recently used; connect's ResolveSession refuses them too, but // the age is checked here first so no path forgets it. if a.oficina == nil || connect.Expired(connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, time.Now()) { // Without Oficina ID on, one left over from when it was names // an Oficina account, never an address. return store.Member{}, false, nil } return a.oficina.member(r) } return store.MemberByEmail(r.Context(), a.db, s.Subject) } // ownSignInOnly refuses a request whose session came from Oficina ID, in a // browser or the native app. A passkey is filed under the session's subject, // which for an Oficina session is the Oficina account, not the member's // address: a passkey added there could never sign the member in. func ownSignInOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if s, ok := sessions.Current(r); !ok || connect.IsHomeDerived(s.Method) { http.Error(w, "forbidden", http.StatusForbidden) return } next.ServeHTTP(w, r) }) } // signout is POST /signout, the native app's sign-out: it ends the session // the request carries, whatever its method, and nothing else (Oficina's own // sign-out is the app's to do). The app hears 204; a browser form goes to // the signed-out page. It is mounted with Oficina ID on, inside the CSRF // check like every POST, which the app passes by sending Base's Origin. func (a *app) signout(w http.ResponseWriter, r *http.Request) { a.sess.SignOut(w, r) w.Header().Set("Cache-Control", "no-store") if wantsJSON(r) || isJSONBody(r) { w.WriteHeader(http.StatusNoContent) return } http.Redirect(w, r, "/signed-out", http.StatusSeeOther) } // isJSONBody reports whether the request's body is JSON, as the native kit // sends it. func isJSONBody(r *http.Request) bool { media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) return err == nil && media == "application/json" } // signedInAt is when the request's session signed in: the credential's own // verification time when the sign-in method records one (Keymail, and // Oficina ID, which records when the person last proved who they are at // Oficina), else when the session was created, which is the moment a magic // link was confirmed. func signedInAt(r *http.Request) (time.Time, bool) { s, ok := sessions.Current(r) if !ok { return time.Time{}, false } if !s.AuthTime.IsZero() { return s.AuthTime, true } return s.At, !s.At.IsZero() }