// SPDX-License-Identifier: AGPL-3.0-or-later package auth import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "strconv" "strings" "time" ) // FileTokens issues short-lived tokens that let and download links // load attachments: browsers cannot send the Authorization header there, and // putting the session token in a URL would leak it into logs and history. // A file token only identifies the user; every download still checks their // rights to the page. type FileTokens struct { key []byte ttl time.Duration now func() time.Time } // NewFileTokens signs tokens with a key derived from secret. func NewFileTokens(secret string, ttl time.Duration) *FileTokens { sum := sha256.Sum256([]byte("docwell-file-token:" + secret)) return &FileTokens{key: sum[:], ttl: ttl, now: time.Now} } func (f *FileTokens) sign(payload string) string { mac := hmac.New(sha256.New, f.key) mac.Write([]byte(payload)) return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) } // Issue returns a token for userID and when it expires. func (f *FileTokens) Issue(userID string) (string, time.Time) { exp := f.now().Add(f.ttl).Truncate(time.Second) payload := userID + "." + strconv.FormatInt(exp.Unix(), 10) return payload + "." + f.sign(payload), exp } // Parse returns the user a valid, unexpired token was issued to. func (f *FileTokens) Parse(token string) (string, error) { i := strings.LastIndexByte(token, '.') if i < 0 { return "", ErrUnauthorized } payload, sig := token[:i], token[i+1:] if !hmac.Equal([]byte(sig), []byte(f.sign(payload))) { return "", ErrUnauthorized } userID, expStr, ok := strings.Cut(payload, ".") exp, err := strconv.ParseInt(expStr, 10, 64) if !ok || err != nil || userID == "" || f.now().Unix() > exp { return "", ErrUnauthorized } return userID, nil }