oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1// Package web is Base's HTTP surface: sign-in, the member gate, Home, People,
2// the Store and Settings.
3package web
4
5import (
6 "context"
7 "database/sql"
8 "embed"
9 "errors"
10 "html/template"
11 "io/fs"
12 "log/slog"
13 "mime"
14 "net/http"
15 "strings"
16 "time"
17
18 "github.com/go-chi/chi/v5"
19
20 "amadan.net/oficina/home/connect"
21 "amadan.net/oficina/home/handoff"
22 "amadan.net/rastrillo/rastrillo/auth"
23 "amadan.net/rastrillo/rastrillo/csrf"
24 "amadan.net/rastrillo/rastrillo/db"
25 "amadan.net/rastrillo/rastrillo/mail"
26 "amadan.net/rastrillo/rastrillo/passkey"
27 "amadan.net/rastrillo/rastrillo/pow"
28 "amadan.net/rastrillo/rastrillo/sessions"
29 "amadan.net/rastrillo/rastrillo/webauthn"
30
31 "amadan.net/oficina/base/internal/config"
32 "amadan.net/oficina/base/internal/equipo"
33 "amadan.net/oficina/base/internal/issuer"
34 "amadan.net/oficina/base/internal/look"
35 "amadan.net/oficina/base/internal/operations"
36 "amadan.net/oficina/base/internal/store"
37)
38
39//go:embed templates/*.html templates/partials/*.html
40var templateFS embed.FS
41
42// Installer installs and uninstalls catalogue apps for this Base;
43// *install.Installer is the real one.
44type Installer interface {
45 // Start claims app's install before it returns, so the next page shows
46 // it installing, and finishes the install in the background.
47 Start(ctx context.Context, app string) error
48 Uninstall(ctx context.Context, app string) error
49}
50
51type app struct {
52 db *sql.DB
53 cfg config.Config
54 inst Installer
55 logger *slog.Logger
56 auth *auth.Auth
57 sess *sessions.Sessions
58 pk *passkey.Handlers
59 pages *look.Renderer
60 mailer mail.Sender
61 // oficina is sign-in with Oficina ID, nil when cfg.Home is.
62 oficina *oficina
63 // ask is "Ask Base anything", nil when cfg.EquipoOrigin is empty.
64 ask *asker
65 // unrecorded are native clients Base couldn't record (ask_caps.go).
66 unrecorded clientsUnrecorded
67}
68
69// App builds Base's router. d is rastrillo's database handle (auth and
70// sessions need it); store functions get d.Writer().
71func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger *slog.Logger) (http.Handler, error) {
72 if mailer == nil {
73 return nil, errors.New("web: a mail sender is required")
74 }
75 if !mail.IsConfigured(mailer) && !cfg.AllowLoggedMail {
76 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)")
77 }
78 if cfg.InstanceKey == "" {
79 return nil, errors.New("web: BASE_INSTANCE_KEY is required")
80 }
81 if logger == nil {
82 logger = slog.Default()
83 }
84 sub, err := fs.Sub(templateFS, "templates")
85 if err != nil {
86 return nil, err
87 }
88 // newKey gives each chat form its own request key when the page is
89 // drawn; startedText says when a job started, as of then.
90 pages, err := look.NewRenderer(sub, template.FuncMap{"newKey": equipo.NewKey, "fileSize": fileSize, "lookupAnswer": lookupMarkdown, "sourceHost": sourceHost,
91 "startedText": func(at *time.Time) string { return startedText(*at, time.Now(), cfg.Timezone) }})
92 if err != nil {
93 return nil, err
94 }
95 a := &app{db: d.Writer(), cfg: cfg, inst: inst, logger: logger, pages: pages, mailer: mailer}
96 if cfg.EquipoOrigin != "" {
97 a.ask = newAsker(cfg.EquipoOrigin, cfg.InstanceKey, cfg.Name, cfg.Timezone)
98 }
99 guard, err := pow.New(pow.Config{InstanceKey: cfg.InstanceKey, Nonces: pow.SQLNonces(d.Writer()), Difficulty: pow.NoProof, MinAge: pow.DefaultMinAge})
100 if err != nil {
101 return nil, err
102 }
103 // With Oficina ID on, /signin leads with Oficina, so the email and
104 // passkey door moves to /signin/local, and a local sign-in lands on
105 // connect's LocalCompletePath, which picks up a link waiting for it.
106 localSignin, signedIn := "/signin", "/"
107 if cfg.Home != nil {
108 localSignin, signedIn = "/signin/local", connect.LocalCompletePath
109 }
110 a.auth, err = auth.New(auth.Config{
111 DB: d.Writer(), Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: mailer, Logger: logger,
112 Proof: guard, KeymailServers: []string{"keymail.dev"}, SigninScreen: true,
113 SigninPath: localSignin, BeginPath: "/auth/begin", ForgetPath: "/auth/forget", SignedInPath: signedIn,
114 Authorize: a.authorize,
115 Refused: func(w http.ResponseWriter, r *http.Request, _ auth.Identity) {
116 http.Redirect(w, r, localSignin+"?refused=1", http.StatusSeeOther)
117 },
118 RenderConfirm: a.renderConfirm,
119 })
120 if err != nil {
121 return nil, err
122 }
123 // Passkeys share auth's sessions: the same table and, built for the same
124 // origin, the same cookie. A passkey signs a member in on its own, through
125 // the same admission check as an emailed link.
126 sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, Logger: logger})
127 if err != nil {
128 return nil, err
129 }
130 a.sess = sess
131 a.pk, err = passkey.New(passkey.Config{
132 Sessions: sess, DB: d.Writer(), Origin: cfg.Origin, Logger: logger,
133 Authorize: a.authorize, SignedInPath: "/", Remember: a.auth.RememberJar(),
134 })
135 if err != nil {
136 return nil, err
137 }
138
139 // Without an assertion key there are no installs to hand off to.
140 var authorize http.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
141 http.Error(w, "unavailable", http.StatusServiceUnavailable)
142 })
143 if cfg.AssertionKey != nil {
144 if authorize, err = issuer.New(d.Writer(), cfg, CurrentMember, signedInAt, logger); err != nil {
145 return nil, err
146 }
147 }
148
149 if cfg.Home != nil {
150 if a.oficina, err = a.newOficina(cfg.Home); err != nil {
151 return nil, err
152 }
153 }
154
155 r := chi.NewRouter()
156 if o := a.oficina; o != nil {
157 // connect's middleware is csrf.Protect with one exception, POST
158 // /auth/assertion, whose signed assertion is its own proof.
159 r.Use(o.routes.Middleware)
160 } else {
161 r.Use(csrf.Protect(cfg.Origin))
162 }
163 r.Get("/static/fonts/*", look.FontHandler().ServeHTTP)
164 r.Get("/static/*", look.Assets.Handler().ServeHTTP)
165 r.Get("/api/team", a.teamProbe)
166 if o := a.oficina; o != nil {
167 r.Get("/signin", a.oficinaSignin)
168 r.Get("/signin/local", a.signin)
169 r.Get("/signed-out", o.routes.SignedOut)
170 r.Get(connect.LocalCompletePath, o.routes.LocalComplete)
171 r.Get(handoff.StartPath, o.bridge.Start)
172 r.Post(handoff.CallbackPath, o.bridge.Callback)
173 r.Get(handoff.FinishPath, o.bridge.Finish)
174 r.With(sess.Require).Get("/account/home", o.routes.Account)
175 r.With(sess.Require).Post("/account/home", o.routes.LinkStart)
176 r.With(sess.Require).Get("/account/home/confirm", o.bridge.ConfirmPage)
177 r.With(sess.Require).Post("/account/home/confirm", a.oficinaConfirm)
178 r.Post("/auth/begin", o.routes.LocalGuard(a.auth.Begin))
179 r.Get("/auth/callback", o.routes.LocalGuard(a.auth.Callback))
180 r.Get("/auth/verify", o.routes.LocalGuard(a.auth.Verify))
181 r.Post("/auth/verify", o.routes.LocalGuard(a.auth.Verify))
182 r.Post("/auth/signout", o.routes.Signout)
183 // The native app's Oficina ID exchange. connect's Middleware lets
184 // this one path past the CSRF check: it refuses anything a browser
185 // sends, and reads and sets no cookies.
186 r.Post(connect.NativeExchangePath, o.bridge.NativeExchange)
187 r.Post("/signout", a.signout)
188 } else {
189 r.Get("/signin", a.signin)
190 r.Post("/auth/begin", a.auth.Begin)
191 r.Get("/auth/callback", a.auth.Callback)
192 r.Get("/auth/verify", a.auth.Verify)
193 r.Post("/auth/verify", a.auth.Verify)
194 r.Post("/auth/signout", a.auth.Signout)
195 }
196 r.Post("/auth/forget", a.auth.Forget)
197 r.Get(webauthnModulePath, serveScript(webauthn.JS()))
198 r.Get(passkeyDoorPath, serveScript(passkey.JS()))
199 r.Post(passkeyDoor.BeginPath, a.pk.DiscoverBegin)
200 r.Post(passkeyDoor.FinishPath, a.pk.DiscoverFinish)
201 r.Group(func(r chi.Router) {
202 r.Use(a.requireMember)
203 if a.ask != nil {
204 r.Use(a.withAskCaps)
205 }
206 r.Get("/", a.home)
207 r.Get("/people", a.people)
208 r.Post("/people", a.invite)
209 r.Get("/store", a.storePage)
210 r.Post("/store/{app}/install", a.storeInstall)
211 r.Get("/store/{app}/uninstall", a.uninstallPage)
212 r.Post("/store/{app}/uninstall", a.storeUninstall)
213 r.Get("/settings", a.settings)
214 r.Post("/settings/appearance", a.settingsAppearance)
215 r.Get("/api/v1/me", a.apiMeRead)
216 r.Get("/api/v1/home", a.apiHomeRead)
217 r.Get("/api/v1/store", a.apiStoreRead)
218 r.Get("/api/v1/people", a.apiPeopleRead)
219 r.Post("/api/v1/store/{app}/install", a.apiStoreInstall)
220 r.Post("/api/v1/store/{app}/uninstall", a.apiStoreUninstall)
221 r.Post("/api/v1/people", a.apiPeopleInvite)
222 r.With(ownSignInOnly).Post(registerBeginPath, a.pk.RegisterBegin)
223 r.With(ownSignInOnly).Post(registerFinishPath, a.pk.RegisterFinish)
224 r.Method(http.MethodGet, "/authorize", authorize)
225 if a.ask != nil {
226 a.askRoutes(r)
227 }
228 })
229 return withOperations(operations.Handler(d.Writer(), cfg), r), nil
230}
231
232// withOperations sends operations.Path and everything under it to ops and
233// the rest to site. ops sits outside site's middleware: no CSRF check (its
234// callers are servers, which send no Origin) and no member gate (the
235// member's host token is its proof, and cookies count for nothing there).
236func withOperations(ops, site http.Handler) http.Handler {
237 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
238 if p := r.URL.Path; p == operations.Path || strings.HasPrefix(p, operations.Path+"/") {
239 ops.ServeHTTP(w, r)
240 return
241 }
242 site.ServeHTTP(w, r)
243 })
244}
245
246// authorize admits a verified address that belongs to a member, and records
247// the member's first sign-in. It runs only after the address has been proved.
248func (a *app) authorize(address string) bool {
249 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
250 defer cancel()
251 m, ok, err := store.MemberByEmail(ctx, a.db, address)
252 if err != nil || !ok {
253 if err != nil {
254 a.logger.Error("sign-in: member lookup", "err", err)
255 }
256 return false
257 }
258 if m.JoinedAt == nil {
259 if err := store.MarkJoined(ctx, a.db, m.ID); err != nil {
260 a.logger.Error("sign-in: mark joined", "err", err)
261 return false
262 }
263 }
264 return true
265}
266
267type ctxKey struct{}
268
269// CurrentMember is the signed-in member behind a request that passed the gate.
270func CurrentMember(r *http.Request) (store.Member, bool) {
271 m, ok := r.Context().Value(ctxKey{}).(store.Member)
272 return m, ok
273}
274
275// requireMember lets through only a session that belongs to a current
276// member, and puts that member on the request. A session from Base's own
277// sign-in names the member's address; one from Oficina ID (a browser's or
278// the native app's) names an Oficina account, which counts only through a
279// stored link to a member who still exists. A signed-out page request goes
280// to /signin; the native app and scripts (apiRequest) hear
281// 401 {"code":"unauthenticated"} instead, for no session or a session that
282// names nobody.
283func (a *app) requireMember(next http.Handler) http.Handler {
284 gate := a.auth.RequireSession
285 if a.oficina != nil {
286 // sessions' own gate, whose sign-in page is /signin, not auth's
287 // /signin/local: a signed-out visitor is offered Oficina first.
288 gate = a.sess.Require
289 }
290 member := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
291 w.Header().Set("Cache-Control", "no-store")
292 s, ok := sessions.Current(r)
293 if !ok {
294 http.Error(w, "forbidden", http.StatusForbidden)
295 return
296 }
297 m, found, err := a.memberFor(r, s)
298 switch {
299 case err != nil:
300 a.logger.Error("member gate", "err", err)
301 http.Error(w, "unavailable", http.StatusServiceUnavailable)
302 case !found && apiRequest(r):
303 unauthenticated(w)
304 case !found:
305 http.Error(w, "forbidden", http.StatusForbidden)
306 default:
307 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, m)))
308 }
309 })
310 paged := gate(member)
311 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
312 if !apiRequest(r) {
313 paged.ServeHTTP(w, r)
314 return
315 }
316 s, ok := a.sess.From(r)
317 if !ok {
318 unauthenticated(w)
319 return
320 }
321 member.ServeHTTP(w, sessions.WithSession(r, s))
322 })
323}
324
325// memberFor is the member behind session s. found is false for a session
326// that names nobody who is a member now.
327func (a *app) memberFor(r *http.Request, s sessions.Session) (m store.Member, found bool, err error) {
328 if connect.IsHomeDerived(s.Method) {
329 // A browser, native or native-to-web sign-in through Oficina. The
330 // native kinds end seven days after they were minted, however
331 // recently used; connect's ResolveSession refuses them too, but
332 // the age is checked here first so no path forgets it.
333 if a.oficina == nil || connect.Expired(connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, time.Now()) {
334 // Without Oficina ID on, one left over from when it was names
335 // an Oficina account, never an address.
336 return store.Member{}, false, nil
337 }
338 return a.oficina.member(r)
339 }
340 return store.MemberByEmail(r.Context(), a.db, s.Subject)
341}
342
343// ownSignInOnly refuses a request whose session came from Oficina ID, in a
344// browser or the native app. A passkey is filed under the session's subject,
345// which for an Oficina session is the Oficina account, not the member's
346// address: a passkey added there could never sign the member in.
347func ownSignInOnly(next http.Handler) http.Handler {
348 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
349 if s, ok := sessions.Current(r); !ok || connect.IsHomeDerived(s.Method) {
350 http.Error(w, "forbidden", http.StatusForbidden)
351 return
352 }
353 next.ServeHTTP(w, r)
354 })
355}
356
357// signout is POST /signout, the native app's sign-out: it ends the session
358// the request carries, whatever its method, and nothing else (Oficina's own
359// sign-out is the app's to do). The app hears 204; a browser form goes to
360// the signed-out page. It is mounted with Oficina ID on, inside the CSRF
361// check like every POST, which the app passes by sending Base's Origin.
362func (a *app) signout(w http.ResponseWriter, r *http.Request) {
363 a.sess.SignOut(w, r)
364 w.Header().Set("Cache-Control", "no-store")
365 if wantsJSON(r) || isJSONBody(r) {
366 w.WriteHeader(http.StatusNoContent)
367 return
368 }
369 http.Redirect(w, r, "/signed-out", http.StatusSeeOther)
370}
371
372// isJSONBody reports whether the request's body is JSON, as the native kit
373// sends it.
374func isJSONBody(r *http.Request) bool {
375 media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
376 return err == nil && media == "application/json"
377}
378
379// signedInAt is when the request's session signed in: the credential's own
380// verification time when the sign-in method records one (Keymail, and
381// Oficina ID, which records when the person last proved who they are at
382// Oficina), else when the session was created, which is the moment a magic
383// link was confirmed.
384func signedInAt(r *http.Request) (time.Time, bool) {
385 s, ok := sessions.Current(r)
386 if !ok {
387 return time.Time{}, false
388 }
389 if !s.AuthTime.IsZero() {
390 return s.AuthTime, true
391 }
392 return s.At, !s.At.IsZero()
393}
394