oficina / fichas Public

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

Plain git — no account needed to clone.

Download

Download this file

1package fichas
2
3import (
4 "amadan.net/oficina/estilo.git/chrome"
5 "amadan.net/oficina/estilo.git/sky"
6 "amadan.net/oficina/estilo.git/theme"
7 "amadan.net/oficina/fichas/internal/fichas/locale"
8 "context"
9 "log/slog"
10 "net/http"
11
12 "github.com/go-chi/chi/v5"
13
14 "amadan.net/rastrillo/rastrillo/csrf"
15 "amadan.net/rastrillo/rastrillo/db"
16 "amadan.net/rastrillo/rastrillo/mail"
17 "amadan.net/rastrillo/rastrillo/migrate"
18 "amadan.net/rastrillo/rastrillo/sessions"
19
20 "amadan.net/oficina/suite/server"
21)
22
23// App wires the whole app: schema, router, static files. It returns a
24// *http.ServeMux because rastrillo.Options.Mux is typed that way — the
25// chi router mounts inside it. origin is the app's external origin
26// ("https://app.example.com") — the CSRF check's yardstick, and, once
27// the app grows accounts, sessions.Config.Origin too.
28//
29// Growing the app is SKILL.md's five-file shape: models in models.go,
30// handlers in handlers.go, and — for a multi-user app — the sessions
31// core plus an identity plugin wired right here (examples/notes in the
32// rastrillo repo is the worked example to copy). Adding a subsystem
33// also means adding its Schema to migrations.go's BootSchema — see
34// the comment there.
35func App(d *db.DB, cfg Config, logger *slog.Logger) (*http.ServeMux, *app, error) {
36 // Apply BootSchema, not Schema: BootSchema is everything this
37 // app needs at boot (its own migrations plus any subsystem's),
38 // while Schema (migrations.go) stays just this app's own so the
39 // generator and its check never see a subsystem's tables and try
40 // to drop them.
41 migrated, err := migrate.Apply(context.Background(), d, BootSchema)
42 if err != nil {
43 return nil, nil, err
44 }
45 // One line per boot. Result exists so this can be logged, and
46 // until something does, a fleet-wide adoption — every database
47 // stamped, no DDL run, exactly once, never again — produces no
48 // output at all, which is the last event you want to be silent.
49 logger.Info("migrate", "applied", migrated.Applied,
50 "skipped", migrated.Skipped, "adopted", migrated.Adopted)
51
52 // The seeded catalogue (§4.4) is data, not schema, so it is written
53 // here and not by a migration. Deliberate: a migration cannot seal,
54 // because the DEK is config and arrives after the schema does, and a
55 // migration that wrote labels in the clear would put the catalogue's
56 // words in the durable file — which is the whole thing §4.3 forbids.
57 if err := Seed(d.G, cfg.Sealer); err != nil {
58 return nil, nil, err
59 }
60
61 a := &app{db: d, sealer: cfg.Sealer, cfg: cfg, ix: NewIndex(d.G, cfg.Sealer), logger: logger}
62 // The formats Fichas offers, the team's first (§6.8): what a
63 // reader's Accept-Language is matched against.
64 if a.negotiation, err = locale.Negotiation(cfg.Locale); err != nil {
65 return nil, nil, err
66 }
67
68 a.owners = cfg.Owners
69 // The sessions core auth keeps its sessions in, over the same table
70 // and cookie, so the door can end a refused one (refusedSession).
71 if a.sess, err = sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, SigninPath: signinPath, Logger: logger}); err != nil {
72 return nil, nil, err
73 }
74
75 r := chi.NewRouter()
76 // App-wide, from day one: every state-changing route added below
77 // is born covered. Origin-checking, not tokens — nothing to mint
78 // or forget in a form.
79 r.Use(csrf.Protect(cfg.Origin))
80 // Every page carries the reader's localizer: English words, their
81 // own formats (level-up §6.8).
82 r.Use(a.withFormats)
83 // A path nothing answers is the app's 404 page, not chi's plain text.
84 r.NotFound(notFound)
85
86 // Sign-in is outside the session guard, necessarily: it is how a
87 // session is obtained. The door (signin.go) is rastrillo's screen in
88 // estilo's; Fichas has no Home, so there is no /signin/local or
89 // /signin/oficina, and both answer 404 like any unknown path.
90 r.Get(signinPath, a.signinRoute)
91 // Order matters: the kept page is settled first (beginReturn), then
92 // admission before the classifier can dial (beginGuard), then Begin,
93 // which with the screen on keeps a Keymail continuation on the door
94 // (?continue=) so form-action 'self' stays strict.
95 r.Post(beginPath, a.beginReturn(a.beginGuard(a.authBegin)))
96 // The two landings: the kept page is checked again here
97 // (landingReturn), as at Begin.
98 r.Get("/auth/callback", a.landingReturn(a.authCallback))
99 // The emailed link: GET draws the confirm door, POST spends the token.
100 r.Get("/auth/verify", a.landingReturn(a.authVerify))
101 r.Post("/auth/verify", a.landingReturn(a.authVerify))
102 // "Use a different email", and "Forget me on this device".
103 r.Post(signinForgetPath, a.forget)
104 r.Post("/signout", a.signout)
105 r.Get(signedOutPath, a.signedOut)
106 // Light, dark or system: a per-person preference set by a form in the
107 // account menu, so it works with scripts off. estilo's handler and
108 // cookie; inside the CSRF check above and outside the session guard,
109 // so an expired session cannot turn the click into a sign-in loop.
110 r.Post("/appearance", chrome.HandleAppearance)
111
112 if cfg.ContractRelease != nil {
113 r.Get("/contracts/prepare", a.contractPrepareReturning)
114 }
115 // Everything else requires a session AND admission. Grouped rather
116 // than wrapped per route: a route added below is born guarded, which
117 // is the property memoria lost when a seam let one through.
118 r.Group(func(r chi.Router) {
119 r.Use(a.requireSession)
120 if cfg.ContractRelease != nil {
121
122 r.Post("/contracts/review", a.contractReview)
123 r.Post("/contracts/approve", a.contractApprove)
124 }
125 r.Get("/", func(w http.ResponseWriter, r *http.Request) {
126 if cfg.ContractRelease != nil {
127 if c, e := r.Cookie("fichas_contract_return"); e == nil {
128 http.SetCookie(w, &http.Cookie{Name: "fichas_contract_return", Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
129 if validContractFlow(c.Value) {
130 http.Redirect(w, r, "/contracts/prepare?flow="+c.Value, http.StatusSeeOther)
131 return
132 }
133 }
134 }
135 a.index(w, r)
136 })
137 r.Get("/t/{type}", a.index)
138 r.Get("/t/{type}/fields", a.fieldsPage)
139 r.Get("/t/{type}/fields/new", a.newField)
140 r.Post("/t/{type}/fields", a.createField)
141 r.Post("/t/{type}/view", a.saveView)
142 r.Get("/t/{type}/layout", a.layoutPage)
143 r.Post("/t/{type}/layout", a.saveLayout)
144 r.Get("/fields/{key}/edit", a.editField)
145 r.Post("/fields/{key}", a.updateField)
146 r.Get("/types/new", a.newType)
147 r.Post("/types", a.createType)
148 r.Get("/cards/new", a.newCard)
149 r.Post("/cards", a.createCard)
150 r.Get("/cards/{id}", a.showCard)
151 r.Get("/cards/{id}/edit", a.editCard)
152 r.Post("/cards/{id}", a.updateCard)
153 // Editing in place (level-up §5): one field, Undo and Redo, and
154 // the card's History.
155 r.Post("/cards/{id}/fields/{key}", a.setFieldValue)
156 r.Post("/cards/{id}/undo", a.undoEdit)
157 r.Get("/cards/{id}/history", a.cardHistory)
158 // The rail's fold: a preference cookie, no row, no event.
159 r.Post("/view/rail", a.foldRail)
160 r.Post("/cards/{id}/entries", a.addEntry)
161 // A destructive action gets its own URL, never a modal.
162 r.Get("/cards/{id}/delete", a.confirmDelete)
163 r.Post("/cards/{id}/delete", a.deleteCard)
164 })
165
166 mux := http.NewServeMux()
167 // The app serves its own static files — the framework never does.
168 // They are embedded (render.go) and fingerprinted: templates link
169 // them via {{asset ...}}, which returns a content-hashed URL the
170 // handler serves cacheable-forever.
171 mux.Handle("GET /static/", assets.Handler())
172 // Onest, Calma's typeface, served by estilo under its versioned prefix.
173 mux.Handle("GET "+theme.FontPrefix, theme.FontHandler())
174 // The suite's sky behind the sign-in door, drawn by estilo under its
175 // versioned prefix. Sessionless like the rest of static, and more
176 // specific than GET /static/, so it wins over the app's assets.
177 mux.Handle("GET "+sky.Prefix, sky.Handler())
178 // The suite contract (spec §6.5), only when a consumer is configured:
179 // with none, Handler is nil and /suite/ is an unknown path like any
180 // other. Mounted HERE, on the outer mux, and not on r: outside the
181 // session group, because memoria is not a person and has no session,
182 // and outside r's app-wide csrf.Protect, which would refuse its POST
183 // /suite/s2 — it sends a bearer token and no Origin or Sec-Fetch-Site.
184 // A bearer header is not something a cross-site form can attach, so
185 // the CSRF check has nothing to protect here. Exactly /suite/ is
186 // exempt; every other path still reaches r and its check.
187 if h := server.Handler(&suiteProducer{g: d.G, sealer: cfg.Sealer, admit: a.Admit}, cfg.SuiteConsumers, logger); h != nil {
188 mux.Handle(suitePrefix, h)
189 }
190 mux.Handle("/", r)
191 return mux, a, nil
192}
193
194// suitePrefix is where the suite routes live (suite.RouteS1 and its
195// siblings all sit under it), and the one path exempt from the CSRF check.
196const suitePrefix = "/suite/"
197
198// AppForTest builds the app already signed in as one address.
199//
200// Named for what it does, and the naming is the point. memoria's earlier
201// seam was a nil-auth fall-through inside requireSession whose safety
202// argument rested on a test that did not exist, so deleting the sign-in
203// wiring compiled and left every route open while the suite stayed green.
204// A test that wants an unauthenticated app has to ask for one by a name
205// nobody will mistake for production wiring.
206func AppForTest(d *db.DB, cfg Config, logger *slog.Logger, as string) (*http.ServeMux, error) {
207 mux, a, err := App(d, cfg, logger)
208 if err != nil {
209 return nil, err
210 }
211 a.testIdentity = normaliseAddress(as)
212 a.allowUnauthenticated = true
213 // requireSession still refuses a nil auth, so the test wiring has to
214 // supply one rather than route around the guard.
215 au, err := NewAuth(d.Writer(), AuthEnv{
216 Origin: cfg.Origin,
217 InstanceKey: cfg.InstanceKey,
218 Mailer: mail.Logged(logger),
219 }, logger, a)
220 if err != nil {
221 return nil, err
222 }
223 a.UseAuth(au)
224 return mux, nil
225}
226