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
3// The sign-in door (Home spec 2026-11-19-smart-door.md, step 6; home
4// connect/MIGRATING.md): rastrillo's sign-in screen, its ui "signin"
5// partial fed by auth.SigninState, drawn inside estilo's door by
6// estilo-signin-screen. Its words are rastrillo's approved copy
7// (rastrillo.ui.signin_*), and the signed-out page's are estilo's
8// chrome.English, so every app in the suite says the same thing. Only the
9// refusal is Fichas' (signinRefusal).
10//
11// Fichas has no Home, so its door has one way in, email: "Continue as
12// {address}" when this browser remembers one, else the field, and under
13// it "Use a different email". /signin/local and /signin/oficina, which
14// Home-derived apps mount, are not routes here and answer 404.
15//
16// Every door is drawn signed out: the sign-in pages use the plain layout
17// (render.go), which has no account menu, even for a session the door has
18// just refused.
19
20import (
21 "bytes"
22 "context"
23 "html"
24 "net/http"
25 "net/url"
26 "path"
27 "strings"
28
29 "amadan.net/oficina/estilo.git/chrome"
30 "amadan.net/oficina/estilo.git/sky"
31 "amadan.net/rastrillo/rastrillo/auth"
32)
33
34// signinForgetPath is where rastrillo auth's Forget is mounted (app.go):
35// "Use a different email" on the door, and "Forget me on this device" on
36// the signed-out page. auth's own default, named here because the
37// signed-out page and auth.Config.ForgetPath must agree.
38const signinForgetPath = "/signin/forget"
39
40// signedOutPath is where Sign out lands: "You’re signed out".
41const signedOutPath = "/signed-out"
42
43// appName is the door's name for Fichas: the card's head, the partial's
44// Brand.Name ("Sign in to Fichas") and the tab title.
45const appName = "Fichas"
46
47// signinRefusal is the refusal: a verified address the owners list does
48// not hold (refused), or a session the signed-in routes no longer admit
49// (refusedSession). Drawn in the screen's app-problem slot with the email
50// field. Paul approved the wording for Docs and Sheets (2026-11-21/22):
51// the same sentence with the app's name.
52const signinRefusal = "That email can’t sign in to Fichas. Use a different email, or ask whoever runs this team to add it."
53
54// signinPage is templates/signin.html's data: exactly one of Screen and
55// SignedOut is set. Screen is rastrillo's screen in estilo's door (every
56// sign-in state, the confirm step and the refusal included); SignedOut is
57// the page Sign out lands on.
58type signinPage struct {
59 Screen *chrome.SignInScreen
60 SignedOut *chrome.SignInNotice
61 // Title is the tab title: rastrillo's for the screen's state ("Sign
62 // in to Fichas"), or estilo's "Signed out · Fichas".
63 Title string
64 // Theme is <html data-theme> (themeAttr).
65 Theme string
66}
67
68// doorIcon is Fichas' mark at the head of every door card.
69func doorIcon() string { return assets.Path("static/brand/icon.svg") }
70
71// signinRoute is GET /signin. Somebody already signed in and admitted
72// never sees the door (shared-chrome spec §9.2) unless the query names
73// one of its states, and goes to a safe return_to or "/". A session the
74// signed-in routes refuse is ended here and gets the door with the
75// refusal (refusedSession). One they cannot decide on is left alone.
76func (a *app) signinRoute(w http.ResponseWriter, r *http.Request) {
77 if a.auth == nil {
78 // Closed, as requireSession is: no sign-in is wired, so there is
79 // no door to draw.
80 a.logger.Error("no sign-in configured; refusing the door")
81 http.Error(w, "sign-in is not configured", http.StatusInternalServerError)
82 return
83 }
84 if ad := a.admission(r); ad.signedIn {
85 if !ad.admitted {
86 r = a.refusedSession(w, r)
87 } else if !signinOutcome(r) {
88 alreadySignedIn(w, r)
89 return
90 }
91 }
92 a.signinDoor(w, r, http.StatusOK)
93}
94
95// signinDoor draws the door. rastrillo decides what it shows from the
96// query and this browser's cookies (SigninState: the way in it used last,
97// Sent, problems, the Keymail continuation, the confirm step), with
98// SigninOneWay drawing one way in per page. Fichas adds the refusal, which
99// only someone who has just verified the address, or whose session the
100// signed-in routes no longer admit, reaches.
101func (a *app) signinDoor(w http.ResponseWriter, r *http.Request, status int) {
102 st := a.auth.SigninState(r)
103 if st.Unavailable {
104 // Under a base path or on a direct host the hub signs people in,
105 // and every route rastrillo's door names answers 404 there. So
106 // does the door.
107 notFound(w, r)
108 return
109 }
110 // The confirm step and the Keymail continuation are drawn before
111 // SigninState reads SigninOneWay, so the partial drew them as the
112 // classic door: a square Sign in among the one-way door's pills (the
113 // estilo review's note that Fichas' confirm form had no pill). Marked
114 // one-way, they are the same markup on the one-way door, whose
115 // buttons are Fiesta's pills; neither draws a Forget either way.
116 if st.Step == auth.StepConfirm || st.Step == auth.StepContinue {
117 st.OneWay = true
118 }
119 if refusedHere(r) {
120 st.AppProblem = &auth.AppProblem{Text: signinRefusal, Ask: true}
121 }
122 // The door's forms post this, and the chooser's links carry it: a
123 // page that is no page to come back to is dropped here as well as at
124 // Begin (beginReturn).
125 if !keepableReturn(st.ReturnTo) {
126 st.ReturnTo = ""
127 }
128 a.auth.PrepareSigninResponse(w, st)
129 screen := chrome.SignInScreen{Icon: doorIcon(), App: appName, Sky: sky.For(r.Host), State: st, L: a.readerL(r)}
130 title, err := signinTitle(screen)
131 if err != nil {
132 a.logger.Error("fichas: render the sign-in title", "err", err)
133 ErrorPage(w, r, http.StatusInternalServerError, "")
134 return
135 }
136 w.Header().Set("Cache-Control", "no-store")
137 renderStatus(w, "signin", signinPage{Screen: &screen, Title: title, Theme: themeAttr(r)}, status)
138}
139
140// signinTitle is the door's <title>: estilo's estilo-signin-screen-title,
141// which is rastrillo's signin-title for the same state, so the tab and
142// the heading always say the same thing ("Sign in to Fichas", "Check your
143// email to sign in to Fichas"). The template writes escaped text and the
144// layout escapes the title again, so it is unescaped here.
145func signinTitle(screen chrome.SignInScreen) (string, error) {
146 var b bytes.Buffer
147 if err := pages["signin"].ExecuteTemplate(&b, "estilo-signin-screen-title", screen); err != nil {
148 return "", err
149 }
150 return strings.TrimSpace(html.UnescapeString(b.String())), nil
151}
152
153// renderConfirm is auth's RenderConfirm, the page an emailed link opens on
154// (GET /auth/verify): the door, whose SigninState answers StepConfirm on
155// this request alone, with one Sign in button that POSTs the token back,
156// where auth spends it. The GET spends nothing, so a mail-security scanner
157// that fetches every link cannot sign anybody in. auth has already set
158// no-store, Referrer-Policy strict-origin (the URL is a live credential)
159// and the framing refusals; nothing here loosens them.
160func (a *app) renderConfirm(w http.ResponseWriter, r *http.Request, _ auth.ConfirmPageData) {
161 a.signinDoor(w, r, http.StatusOK)
162}
163
164// refused is auth's Refused hook: Keymail or an emailed link verified the
165// address and the owners list said no. It answers with the door, carrying
166// the refusal, in a 403: no session is minted, and auth has already ended
167// the attempt and spent the kept page.
168//
169// Drawn in this response, never from a query parameter: those are
170// something anybody can type, and the sentence means "you proved this
171// address and it is not admitted". Only this hook can say it, and auth
172// calls it only after the address is proved, so saying it is no
173// owners-list oracle; beginGuard's sameness is about the unproved submit,
174// and is untouched.
175func (a *app) refused(w http.ResponseWriter, r *http.Request, _ auth.Identity) {
176 a.signinDoor(w, withRefusal(r), http.StatusForbidden)
177}
178
179// refusedKey marks a request the door draws with the refusal.
180type refusedKey struct{}
181
182// withRefusal marks r as a refusal the door draws.
183//
184// Only on the plain door: the chooser (?ways=) and a way's own page
185// (?way=) are how a refused person reaches another way in, and a refusal
186// there would draw the field again over them (Fable on Docs #139, N1).
187// Fichas has only email, so nothing links there, but a typed URL is drawn
188// as asked.
189func withRefusal(r *http.Request) *http.Request {
190 if choosing(r) {
191 return r
192 }
193 return r.WithContext(context.WithValue(r.Context(), refusedKey{}, true))
194}
195
196// choosing reports whether r is the chooser or a way's own page.
197func choosing(r *http.Request) bool {
198 q := r.URL.Query()
199 return q.Has("ways") || q.Has("way")
200}
201
202// refusedHere reports whether r is a refusal the door is drawing. Never
203// from the query.
204func refusedHere(r *http.Request) bool {
205 v, _ := r.Context().Value(refusedKey{}).(bool)
206 return v
207}
208
209// signedOut serves GET /signed-out, where Sign out lands, in the door's
210// words: "You’re signed out", Sign in, then the quiet "Forget me on this
211// device" (the smart-door spec's "Signed out"), a POST to rastrillo auth's
212// Forget for a shared computer. Fichas has no Home, so there is no Oficina
213// ID to go on and forget too: the chain to id.* is a Home-derived app's.
214func (a *app) signedOut(w http.ResponseWriter, r *http.Request) {
215 out := chrome.SignInNotice{Icon: doorIcon(), App: appName, Sky: sky.For(r.Host)}.
216 SignedOut(signinPath).Forgetting(signinForgetPath, "")
217 w.Header().Set("Cache-Control", "no-store")
218 renderStatus(w, "signin", signinPage{SignedOut: &out, Title: out.Title(), Theme: themeAttr(r)}, http.StatusOK)
219}
220
221// forget is POST /signin/forget, rastrillo auth's Forget: "Use a
222// different email" on the door, and "Forget me on this device" on the
223// signed-out page. It also forgets a page a sign-in in progress kept: the
224// door that sent the post carries its own return_to, and on a shared
225// computer the kept page is the last person's, not the next one's.
226func (a *app) forget(w http.ResponseWriter, r *http.Request) {
227 if a.auth == nil {
228 http.Error(w, "sign-in is not configured", http.StatusInternalServerError)
229 return
230 }
231 if r.Method == http.MethodPost {
232 a.forgetReturn(w, r)
233 }
234 a.auth.Forget(w, r)
235}
236
237// signout is POST /signout: rastrillo's Sign out (which ends the session
238// and forgets a kept page itself), landing on /signed-out rather than on
239// the bare door, which, with no word about what just happened, read like
240// an error (memoria's polish audit §B5).
241func (a *app) signout(w http.ResponseWriter, r *http.Request) {
242 if a.auth == nil {
243 http.Error(w, "sign-in is not configured", http.StatusInternalServerError)
244 return
245 }
246 a.auth.Signout(&rewriteLocation{ResponseWriter: w, from: signinPath, to: signedOutPath}, r)
247}
248
249// rewriteLocation swaps one Location for another at the last moment a
250// header is still settable.
251type rewriteLocation struct {
252 http.ResponseWriter
253 from, to string
254}
255
256func (rw *rewriteLocation) WriteHeader(status int) {
257 if rw.Header().Get("Location") == rw.from {
258 rw.Header().Set("Location", rw.to)
259 }
260 rw.ResponseWriter.WriteHeader(status)
261}
262
263func (rw *rewriteLocation) Write(b []byte) (int, error) { return rw.ResponseWriter.Write(b) }
264
265// The return memory (shared-chrome spec §9.4) is rastrillo's own: a
266// signed-out page request goes to /signin?return_to=<the page>, the door
267// posts it to Begin, and Begin keeps it in a host-only cookie across the
268// mail or Keymail round trip, which the landing reads back. Fichas adds
269// a check at each end, so what Begin keeps and what a landing reads pass
270// the same test (keepableReturn), and rastrillo supplies the rest:
271//
272// - at Begin (beginReturn): a body that does not parse, or a page that
273// is no page to come back to (/signed-out, the door, auth's own
274// routes, dot segments included), keeps nothing, and a post without
275// return_to forgets the kept page (rastrillo's keepReturnTo,
276// AnswerAsSent included, so owner and stranger alike);
277// - at the landing (landingReturn, on /auth/verify and /auth/callback,
278// the only two ways Fichas mints a session): the request's own
279// return_to is never read, and the kept page is read only when there
280// is exactly one cookie and it passes keepableReturn; otherwise it is
281// cleared and the landing is "/";
282// - every landing spends it, admitted or not (rastrillo's admit);
283// - Sign out clears it (rastrillo's Signout), and so does Forget
284// (forget, above);
285// - there is no /signin/local to overwrite it.
286//
287// What this does not do: tell an expired cookie from a live one.
288// rastrillo's cookie is the bare path with no issue time, so its
289// lifetime is the browser's Max-Age, which Begin sets to the emailed
290// link's own (15 minutes); a cookie a browser sends past it is one
291// somebody wrote by hand, and still passes keepableReturn or not.
292
293// beginReturn is POST /auth/begin, outermost: Begin keeps no page it
294// should not. A body that fails to parse keeps none at all: Go leaves
295// what it parsed before the error in the form, and rastrillo would read
296// a return_to from it. A return_to that is no page to come back to
297// (keepableReturn) is taken off the form, so Begin forgets the kept page
298// instead and the landing is "/".
299func (a *app) beginReturn(next http.HandlerFunc) http.HandlerFunc {
300 return func(w http.ResponseWriter, r *http.Request) {
301 parsed := r.ParseForm() == nil
302 if v := r.PostForm["return_to"]; !parsed || len(v) != 1 || !keepableReturn(v[0]) {
303 if r.PostForm != nil {
304 r.PostForm.Del("return_to")
305 }
306 if r.Form != nil {
307 r.Form.Del("return_to")
308 }
309 }
310 next(w, r)
311 }
312}
313
314// keepableReturn reports whether a return_to names a page a fresh
315// sign-in may land on: a same-origin path, and not the signed-out page
316// ("You’re signed out" straight after signing in), the door, or auth's
317// own routes, with or without a query.
318//
319// The path is judged as a browser would resolve it: backslashes are
320// slashes and dot segments are removed (path.Clean), so /./signed-out,
321// /x/../signed-out and /x\..\signin are refused like the pages they
322// name (Fable on fichas #9). A refused value is refused whole, never
323// rewritten to its cleaned form.
324func keepableReturn(to string) bool {
325 if to == "" || !strings.HasPrefix(to, "/") || strings.HasPrefix(to, "//") || strings.HasPrefix(to, "/\\") {
326 return false
327 }
328 u, err := url.Parse(to)
329 if err != nil || u.Scheme != "" || u.Host != "" {
330 return false
331 }
332 p := path.Clean(strings.ReplaceAll(u.Path, "\\", "/"))
333 return p != signedOutPath && p != signinPath && !strings.HasPrefix(p, signinPath+"/") &&
334 p != "/auth" && !strings.HasPrefix(p, "/auth/")
335}
336
337// landingReturn wraps a landing that may mint a session (/auth/verify,
338// /auth/callback): rastrillo's admit lands on the request's own
339// return_to, else the kept one. The request's own is never Fichas' page
340// to land on: no door posts one there, so it comes off the form and the
341// query, duplicates and all. The kept one is read only when the browser
342// sends exactly one cookie and its page passes keepableReturn; any other
343// is cleared on this response and hidden from admit, so the landing is
344// "/". A cookie is a request header like any other.
345func (a *app) landingReturn(next http.HandlerFunc) http.HandlerFunc {
346 return func(w http.ResponseWriter, r *http.Request) {
347 _ = r.ParseForm()
348 if r.PostForm != nil {
349 r.PostForm.Del("return_to")
350 }
351 if r.Form != nil {
352 r.Form.Del("return_to")
353 }
354 name := a.returnCookieName()
355 var kept []string
356 for _, c := range r.Cookies() {
357 if c.Name == name {
358 kept = append(kept, c.Value)
359 }
360 }
361 if len(kept) > 0 {
362 to, err := url.QueryUnescape(kept[0])
363 if len(kept) != 1 || err != nil || !keepableReturn(to) {
364 a.forgetReturn(w, r)
365 r = withoutCookie(r, name)
366 }
367 }
368 next(w, r)
369 }
370}
371
372// returnCookieName is rastrillo auth's kept-page cookie: rastrillo_return_to,
373// __Host- prefixed on an https origin, as auth names its cookies.
374func (a *app) returnCookieName() string {
375 if strings.HasPrefix(a.cfg.Origin, "https://") {
376 return "__Host-rastrillo_return_to"
377 }
378 return "rastrillo_return_to"
379}
380
381// forgetReturn clears the kept page, if this browser holds one.
382func (a *app) forgetReturn(w http.ResponseWriter, r *http.Request) {
383 name := a.returnCookieName()
384 if _, err := r.Cookie(name); err != nil {
385 return
386 }
387 http.SetCookie(w, &http.Cookie{
388 Name: name, Value: "", Path: "/", MaxAge: -1, HttpOnly: true,
389 Secure: strings.HasPrefix(a.cfg.Origin, "https://"), SameSite: http.SameSiteLaxMode,
390 })
391}
392