oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package setup
2
3import (
4 "crypto/aes"
5 "crypto/cipher"
6 "crypto/sha256"
7 "encoding/base64"
8 "encoding/json"
9 "net/http"
10 "strings"
11 "time"
12)
13
14const inviteCookieName = "__Secure-equipo_invite"
15const inviteCookieLifetime = 15 * time.Minute
16
17type inviteCookie struct {
18 Secret string
19 Expires int64
20}
21
22func validInviteID(id string) bool {
23 return len(id) > 0 && len(id) <= 128 && strings.IndexFunc(id, func(c rune) bool {
24 return !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '-')
25 }) == -1
26}
27func (h *Handler) cookieCipher() (cipher.AEAD, error) {
28 if h.Key == "" {
29 return nil, h.Invalid
30 }
31 key := sha256.Sum256([]byte("equipo-invite-cookie\x00" + h.Key))
32 block, err := aes.NewCipher(key[:])
33 if err != nil {
34 return nil, err
35 }
36 return cipher.NewGCMWithRandomNonce(block)
37}
38func (h *Handler) issueCookie(w http.ResponseWriter, id, secret string) error {
39 aead, err := h.cookieCipher()
40 if err != nil {
41 return err
42 }
43 expires := h.Now().Add(inviteCookieLifetime)
44 raw, err := json.Marshal(inviteCookie{Secret: secret, Expires: expires.Unix()})
45 if err != nil {
46 return err
47 }
48 sealed := aead.Seal(nil, nil, raw, []byte(id))
49 http.SetCookie(w, &http.Cookie{Name: inviteCookieName, Value: base64.RawURLEncoding.EncodeToString(sealed), Path: "/invites/" + id, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: int(inviteCookieLifetime.Seconds()), Expires: expires})
50 return nil
51}
52func (h *Handler) cookieSecret(r *http.Request, id string) (string, error) {
53 c, err := r.Cookie(inviteCookieName)
54 if err != nil || !validInviteID(id) {
55 return "", h.Invalid
56 }
57 raw, err := base64.RawURLEncoding.DecodeString(c.Value)
58 if err != nil {
59 return "", h.Invalid
60 }
61 aead, err := h.cookieCipher()
62 if err != nil {
63 return "", err
64 }
65 raw, err = aead.Open(nil, nil, raw, []byte(id))
66 if err != nil {
67 return "", h.Invalid
68 }
69 var value inviteCookie
70 if json.Unmarshal(raw, &value) != nil || value.Secret == "" {
71 return "", h.Invalid
72 }
73 if h.Now().Unix() >= value.Expires {
74 return "", h.Expired
75 }
76 return value.Secret, nil
77}
78