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 "database/sql"
5 "encoding/base64"
6 "encoding/hex"
7 "encoding/json"
8 "net/http"
9 "time"
10
11 "amadan.net/rastrillo/rastrillo/webauthn"
12)
13
14type directChallenge struct {
15 Challenge string `json:"challenge"`
16 Expires int64 `json:"expires"`
17}
18
19// Anonymous begins allocate only a sealed browser cookie. Replay receipts are
20// written after WebAuthn verification, in the same transaction as session mint.
21func (a *App) idDirectBegin(w http.ResponseWriter, r *http.Request) {
22 challenge, err := webauthn.NewChallenge()
23 if err != nil {
24 idRefuse(w)
25 return
26 }
27 plain, err := json.Marshal(directChallenge{hex.EncodeToString(challenge), time.Now().Unix() + 300})
28 if err != nil {
29 idRefuse(w)
30 return
31 }
32 sealed, err := a.secrets.Sealer.Seal("id.direct", plain)
33 if err != nil {
34 idRefuse(w)
35 return
36 }
37 idCookie(w, ceremonyCookie, base64.RawURLEncoding.EncodeToString(sealed), 300)
38 idJSONReply(w, 200, map[string]any{"challenge": base64.RawURLEncoding.EncodeToString(challenge)})
39}
40func (a *App) idDirectProof(r *http.Request, challenge []byte, now int64) (int64, error) {
41 value := cookieValue(r, ceremonyCookie)
42 sealed, err := base64.RawURLEncoding.Strict().DecodeString(value)
43 if err != nil {
44 return 0, errIDProof
45 }
46 plain, err := a.secrets.Sealer.Open("id.direct", sealed)
47 if err != nil {
48 return 0, errIDProof
49 }
50 var proof directChallenge
51 if json.Unmarshal(plain, &proof) != nil || proof.Challenge != hex.EncodeToString(challenge) || proof.Expires <= now || proof.Expires > now+300 {
52 return 0, errIDProof
53 }
54 return proof.Expires, nil
55}
56func consumeDirect(tx *sql.Tx, challenge []byte, expires, now int64) error {
57 if _, err := tx.Exec("DELETE FROM home_id_direct_used WHERE expires_at<=?", now); err != nil {
58 return errIDProof
59 }
60 if _, err := tx.Exec("INSERT INTO home_id_direct_used VALUES(?,?)", hex.EncodeToString(challenge), expires); err != nil {
61 return errIDProof
62 }
63 return nil
64}
65