Backend : token_version (000022, claim tv, 401 si révoqué, bump au password — fin limite V1), quota (000023 idempotente, colonne héritée de 000001, 413 QUOTA_EXCEEDED, GET /users/me/usage), devices (GET + DELETE révocation, EnforceDeviceExists en prod), renames concurrents transparents (baseUpdatedAt + conflicts[] non-fataux, tolérance 2 s). Tests service + handlers + migrations + auth. Mobile : pipeline conflits (DTO + SyncConflictStore + worker + dialogue), baseUpdatedAt prêt, liens 7j par défaut, écran Appareils (+ quota), import classeur unifié (scan/note/dossier), onboarding cercle Famille. Contrat docs/api-v1.md, V3.md (S6 livré).
99 lines
3.3 KiB
Go
99 lines
3.3 KiB
Go
package auth
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"errors"
|
|
"regexp"
|
|
"strconv"
|
|
"time"
|
|
|
|
"aidanwoods.dev/go-paseto"
|
|
)
|
|
|
|
// TokenTTL = 7 jours, sans refresh (V1). À expiration, le client doit
|
|
// re-demander un POST /auth/login.
|
|
const TokenTTL = 7 * 24 * time.Hour
|
|
|
|
var ErrInvalidToken = errors.New("invalid token")
|
|
|
|
var hex32Pattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
|
|
|
|
// Identity est le résultat de Verify : l'utilisateur (sujet du token, autorisant),
|
|
// le device (claim secondaire, porté mais NON autorisant seul) et la version
|
|
// de révocation (claim `tv`, V3 S6 — le middleware la compare à
|
|
// users.token_version).
|
|
type Identity struct {
|
|
UserID string
|
|
DeviceID string
|
|
TokenVersion int
|
|
}
|
|
|
|
// Manager issues and verifies paseto v4-local bearer tokens.
|
|
// Le subject est l'USER (scope des ressources) ; device_id est un claim
|
|
// transporté pour l'idempotence outbox et le nommage des uploads.
|
|
type Manager struct {
|
|
key paseto.V4SymmetricKey
|
|
}
|
|
|
|
func NewManager(secret string) (*Manager, error) {
|
|
sum := sha256.Sum256([]byte(secret))
|
|
key, err := paseto.V4SymmetricKeyFromBytes(sum[:])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Manager{key: key}, nil
|
|
}
|
|
|
|
// Issue émet un token lié à un utilisateur ET à un device (version 0 —
|
|
// compat pré-V3, cf. IssueWithExpiry).
|
|
func (m *Manager) Issue(userID, deviceID string) (string, error) {
|
|
token, _, err := m.IssueWithExpiry(userID, deviceID, 0)
|
|
return token, err
|
|
}
|
|
|
|
// IssueWithExpiry émet un token et retourne son expiration réelle (le `exp`
|
|
// embarqué). Les appelants doivent exposer expiresAt, jamais le recalculer
|
|
// via Now()+TTL (dérive d'horloge, cf. FEEDBACK A7). `tokenVersion` est le
|
|
// compteur de révocation du compte (V3 S6) — bumpé à chaque changement de
|
|
// mot de passe, vérifié par le middleware.
|
|
func (m *Manager) IssueWithExpiry(userID, deviceID string, tokenVersion int) (string, time.Time, error) {
|
|
now := time.Now()
|
|
expiresAt := now.Add(TokenTTL)
|
|
token := paseto.NewToken()
|
|
token.SetIssuedAt(now)
|
|
token.SetNotBefore(now)
|
|
token.SetExpiration(expiresAt)
|
|
token.SetSubject(userID)
|
|
// v1.6.0 : SetString n'expose pas d'erreur (panic si non sérialisable).
|
|
token.SetString("device_id", deviceID)
|
|
token.SetString("tv", strconv.Itoa(tokenVersion))
|
|
return token.V4Encrypt(m.key, nil), expiresAt, nil
|
|
}
|
|
|
|
// Verify décode et contrôle le token, retourne l'identité (user + device +
|
|
// version). Les deux identifiants doivent être 32-hex (cf. docs/api-v1.md) —
|
|
// rejet sinon pour préserver les invariants UNIQUE(device_id,operation_id)/CHECK.
|
|
// `tv` absent (tokens pré-V3) → 0 ; non numérique → rejet.
|
|
func (m *Manager) Verify(signed string) (Identity, error) {
|
|
parsed, err := paseto.NewParserForValidNow().ParseV4Local(m.key, signed, nil)
|
|
if err != nil {
|
|
return Identity{}, ErrInvalidToken
|
|
}
|
|
userID, err := parsed.GetSubject()
|
|
if err != nil || !hex32Pattern.MatchString(userID) {
|
|
return Identity{}, ErrInvalidToken
|
|
}
|
|
deviceID, err := parsed.GetString("device_id")
|
|
if err != nil || !hex32Pattern.MatchString(deviceID) {
|
|
return Identity{}, ErrInvalidToken
|
|
}
|
|
tv := 0
|
|
if raw, err := parsed.GetString("tv"); err == nil && raw != "" {
|
|
tv, err = strconv.Atoi(raw)
|
|
if err != nil || tv < 0 {
|
|
return Identity{}, ErrInvalidToken
|
|
}
|
|
}
|
|
return Identity{UserID: userID, DeviceID: deviceID, TokenVersion: tv}, nil
|
|
}
|