oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "embed"
5 "encoding/base64"
6 "net/http"
7 "strings"
8 "time"
9
10 "amadan.net/rastrillo/rastrillo/passkey"
11 "amadan.net/rastrillo/rastrillo/webauthn"
12)
13
14//go:embed static/passkey.js static/tokens.css static/assertion.js
15var staticFS embed.FS
16
17// confirmPath is where Home's own pending half-session (id_recovery.go,
18// id_passkey.go) sends a first-factor-verified caller who still has a
19// passkey to assert. Home's, not rastrillo's: since rastrillo v0.27.1
20// the half-session lives in rastrillo/secondfactor, whose confirm page
21// defaults to /signin/confirm, and Home wires neither it nor passkey's
22// Gate.
23const confirmPath = "/passkey/confirm"
24
25// Code generation and enrollment share a freshness window, so a person who
26// just enrolled can save codes immediately. Recovery sessions may read the
27// count, but must replace their passkey and sign in with it before generating.
28const codesFreshness = enrolFreshness
29
30// Adding a passkey needs recent authentication: a stolen thirty-day cookie
31// must not become a permanent credential. Recovery uses explicit replacement.
32const enrolFreshness = 10 * time.Minute
33
34// passkeyConfig is the config the app builds.
35//
36// It is returned rather than inlined so a test can assert on what the
37// APP configures instead of on a literal it wrote itself — an RP-ID
38// guard that declares its own config asserts a constant against itself.
39// Home builds no passkey.Handlers (TestHomeNeverMountsFrameworkSignin),
40// so the App retains this value for that purpose alone.
41//
42// LegacyRPID is deliberately empty. It exists for an instance that has
43// changed hostname, so passkeys enrolled under the old name still
44// assert; this app has had exactly one credential origin, and naming a
45// legacy RP that was never used would widen what assertions are accepted
46// for no benefit. It is accepted for assertions only — never for
47// registration — which is what makes it a quiet way to widen the RP ID
48// rather than an obvious one.
49func passkeyConfig(a *App) passkey.Config {
50 return passkey.Config{
51 Sessions: a.sessions,
52 DB: a.db.Writer(),
53 Origin: a.origins.Credential,
54 Logger: a.logger,
55 }
56}
57
58// pageData is what every passkey page needs: the values the glue reads
59// off <body> to run a ceremony.
60//
61// UserName is the person ref, NOT the address. This app does not hold
62// the address, so it has none to give a passkey. And the credential
63// origin renders no account-authored string (§4) but one: since ruling
64// 26, the door (door.go) may show back the address Home sealed into this
65// browser's own cookie, as text and as a form field's value on a no-store
66// page. That carve-out is the door's alone. A passkey page, and the user name
67// a ceremony writes into a password manager, still withhold the address:
68// the cookie is not evidence of who owns a passkey. A person ref reads
69// poorly in a password manager; that is the cost of §0, and it is
70// accepted rather than worked around.
71func (a *App) passkeyPageData(subject string, extra map[string]any) map[string]any {
72 data := map[string]any{
73 "RPID": a.credentialHost,
74 "LegacyRPID": a.passkeyCfg.LegacyRPID,
75 "UserID": base64.RawURLEncoding.EncodeToString([]byte(subject)),
76 "UserName": subject,
77 }
78 for k, v := range extra {
79 data[k] = v
80 }
81 return data
82}
83
84// handlePasskeyConfirm is the Gate's landing page: the ceremony button
85// and the recovery form on one screen.
86//
87// The recovery form is a plain POST and works with script off, which is
88// the point — recovery is exactly the moment WebAuthn is not working.
89func (a *App) handlePasskeyConfirm(w http.ResponseWriter, r *http.Request) {
90 a.render(w, r, http.StatusOK, "passkey_confirm.html", a.passkeyPageData("", map[string]any{
91 "RecoveryFailed": r.URL.Query().Get("recovery") == "failed",
92 }))
93}
94
95// handlePasskeyEnrol offers the optional second factor to a signed-in
96// person.
97func (a *App) handlePasskeyEnrol(w http.ResponseWriter, r *http.Request) {
98 sess, ok := a.sessions.From(r)
99 if !ok {
100 http.Redirect(w, r, "/signin", http.StatusSeeOther)
101 return
102 }
103 if !idFreshSession(sess, enrolFreshness, time.Now()) {
104 http.Redirect(w, r, "/signin?force=1&return_to=%2Fpasskey%2Fenrol", http.StatusSeeOther)
105 return
106 }
107 if strings.Contains(sess.Method, "recovery") {
108 http.Redirect(w, r, "/passkey/replace", http.StatusSeeOther)
109 return
110 }
111 a.render(w, r, http.StatusOK, "passkey_enrol.html", a.passkeyPageData(sess.Subject, nil))
112}
113
114// handleRecoveryCodesPage shows how many codes are left, and the form
115// that replaces them.
116//
117// Regenerating is a POST, not a GET. The plan's route list named only a
118// GET, but minting ten codes and invalidating the previous ten is a
119// state change, and this whole step exists on the principle that a GET
120// does not change state — a link prefetcher would otherwise silently
121// invalidate somebody's recovery codes.
122func (a *App) handleRecoveryCodesPage(w http.ResponseWriter, r *http.Request) {
123 sess, ok := a.sessions.From(r)
124 if !ok {
125 http.Redirect(w, r, "/signin", http.StatusSeeOther)
126 return
127 }
128 remaining, err := a.recoveryCodesRemaining(sess.Subject)
129 if err != nil {
130 a.logger.Error("count recovery codes", "person", sess.Subject, "err", err)
131 a.serverError(w, r)
132 return
133 }
134 a.render(w, r, http.StatusOK, "recovery_codes.html", map[string]any{"Remaining": remaining, "ReturnTo": credentialReturn(r.URL.Query().Get("return_to"))})
135}
136
137// handleRegenerateRecoveryCodes mints a fresh set and shows it once.
138func (a *App) handleRegenerateRecoveryCodes(w http.ResponseWriter, r *http.Request) {
139 sess, ok := a.sessions.From(r)
140 if !ok {
141 http.Redirect(w, r, "/signin", http.StatusSeeOther)
142 return
143 }
144 tx, now, err := a.idTransaction(r.Context())
145 if err != nil {
146 a.serverError(w, r)
147 return
148 }
149 defer tx.Rollback()
150 live, _, err := a.idSession(tx, r, now)
151 if err != nil || live.Subject != sess.Subject || strings.Contains(live.Method, "recovery") || !idFreshSession(live, codesFreshness, time.Unix(now, 0)) {
152 a.signinFailed(w, r)
153 return
154 }
155 var enrolled int
156 if tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", sess.Subject).Scan(&enrolled) != nil {
157 a.serverError(w, r)
158 return
159 }
160 if enrolled == 0 {
161 http.Redirect(w, r, "/passkey/enrol", http.StatusSeeOther)
162 return
163 }
164 codes, err := generateIDCodes(tx, sess.Subject, now)
165 if err == nil {
166 err = tx.Commit()
167 }
168 if err != nil {
169 a.logger.Error("regenerate recovery codes", "person", sess.Subject, "err", err)
170 a.serverError(w, r)
171 return
172 }
173 a.render(w, r, http.StatusOK, "recovery_codes.html", map[string]any{"Codes": codes, "ReturnTo": credentialReturn(r.FormValue("return_to"))})
174}
175
176// serveAsset serves one of the two script files.
177//
178// Stable and unfingerprinted on purpose: the scriptless sweep's
179// allowlist has to name them.
180//
181// The Content-Type is set explicitly even though Go's mime table already
182// maps .mjs. A wrong MIME type makes a browser refuse a module silently,
183// which is the worst way for this to fail.
184func serveAsset(body []byte, contentType string) http.HandlerFunc {
185 version := contentVersion(body)
186 etag := `"` + version + `"`
187 return func(w http.ResponseWriter, r *http.Request) {
188 w.Header().Set("Content-Type", contentType)
189 w.Header().Set("ETag", etag)
190 // A URL carrying this body's version can never serve anything
191 // else, so the browser keeps it for a year without asking. Any
192 // other request — the bare path, a stale version — revalidates,
193 // and the ETag makes that a 304 rather than the bytes again.
194 if r.URL.Query().Get("v") == version {
195 w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
196 } else {
197 w.Header().Set("Cache-Control", "no-cache")
198 }
199 if etagMatches(r.Header.Get("If-None-Match"), etag) {
200 w.WriteHeader(http.StatusNotModified)
201 return
202 }
203 w.WriteHeader(http.StatusOK)
204 w.Write(body)
205 }
206}
207
208func staticAsset(name string) []byte {
209 b, err := staticFS.ReadFile("static/" + name)
210 if err != nil {
211 // Embedded above; unreachable unless the build is broken.
212 panic(err)
213 }
214 return b
215}
216
217func webauthnJS() []byte { return webauthn.JS() }
218
219// signinJS is the door's passkey module, rastrillo's own: it runs the
220// passkey door and the email field's autofill (conditional UI) against
221// the direct ceremony, whose finish answers {"ok":true,"to":…}.
222func signinJS() []byte { return passkey.JS() }
223