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é).
156 lines
5.0 KiB
Go
156 lines
5.0 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
"regexp"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/kazier/backend/pkg/api"
|
|
)
|
|
|
|
var deviceIDPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
|
|
|
|
// Anti-remplissage de POST /devices (FEEDBACK §moyenne) : l'endpoint est
|
|
// public et bon marché (un upsert), donc anonyme et floodable. Limiteur
|
|
// basique en mémoire, N enregistrements / minute / IP → 429 RATE_LIMITED.
|
|
// Budget large (300) : les usages légitimes (1 device = 1 appel) sont très
|
|
// loin du seuil ; la protection vise le flood massif, un WAF frontal fera
|
|
// le reste en prod multi-réplicas.
|
|
// TODO(suivi) : rate-limit distribué + budget global coordonné avec le
|
|
// rate-limit login (cf. handlers/auth.go).
|
|
var (
|
|
devicesRateLimitPerMinute = 300
|
|
devicesRateWindow = time.Minute
|
|
devicesAttemptsMu sync.Mutex
|
|
devicesAttempts = map[string][]time.Time{}
|
|
)
|
|
|
|
// OnDevicesRateLimited est un hook d'observabilité (nil = no-op).
|
|
var OnDevicesRateLimited func(ip string)
|
|
|
|
// ResetDevicesRateLimit vide le compteur (tests uniquement).
|
|
func ResetDevicesRateLimit() {
|
|
devicesAttemptsMu.Lock()
|
|
defer devicesAttemptsMu.Unlock()
|
|
devicesAttempts = map[string][]time.Time{}
|
|
}
|
|
|
|
func devicesRateLimited(ip string, now time.Time) bool {
|
|
devicesAttemptsMu.Lock()
|
|
defer devicesAttemptsMu.Unlock()
|
|
cutoff := now.Add(-devicesRateWindow)
|
|
kept := make([]time.Time, 0, len(devicesAttempts[ip])+1)
|
|
for _, t := range devicesAttempts[ip] {
|
|
if t.After(cutoff) {
|
|
kept = append(kept, t)
|
|
}
|
|
}
|
|
if len(kept) >= devicesRateLimitPerMinute {
|
|
devicesAttempts[ip] = kept
|
|
return true
|
|
}
|
|
devicesAttempts[ip] = append(kept, now)
|
|
return false
|
|
}
|
|
|
|
type DeviceRegisterRequest struct {
|
|
DeviceID string `json:"deviceId"`
|
|
}
|
|
|
|
func DevicesRegister(c *gin.Context) {
|
|
// POST /devices est PUBLIC (sans token) : le device s'enregistre pour
|
|
// exister, puis le client appelle POST /auth/login pour obtenir son
|
|
// token user-first (cf. docs/api-v1.md §2).
|
|
//
|
|
// NOTE rate-limit : limiteur en mémoire ci-dessus (300/min/IP, 429
|
|
// au-delà). Si le budget doit changer, ajuster
|
|
// devicesRateLimitPerMinute + documenter dans docs/api-v1.md.
|
|
//
|
|
// NOTE MarkUser : repository.Devices.MarkUser retourne ErrNotFound quand
|
|
// RowsAffected == 0 (device supprimé entre Exists et UPDATE) ; le login
|
|
// mappe ce cas en 401 indistinguable (cf. handlers/auth.go).
|
|
var req DeviceRegisterRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil || req.DeviceID == "" {
|
|
api.Error(c, 400, "INVALID_REQUEST", "missing deviceId")
|
|
return
|
|
}
|
|
if !deviceIDPattern.MatchString(req.DeviceID) {
|
|
api.Error(c, 400, "INVALID_DEVICE_ID", "deviceId must be 32 lowercase hex chars")
|
|
return
|
|
}
|
|
|
|
if devicesRateLimited(c.ClientIP(), time.Now()) {
|
|
if OnDevicesRateLimited != nil {
|
|
OnDevicesRateLimited(c.ClientIP())
|
|
}
|
|
api.Error(c, http.StatusTooManyRequests, "RATE_LIMITED", "too many device registrations, retry later")
|
|
return
|
|
}
|
|
|
|
if Store == nil || Store.Repository == nil {
|
|
api.Error(c, 503, "SERVICE_UNAVAILABLE", "backend not initialized")
|
|
return
|
|
}
|
|
if err := Store.Repository.Devices.Upsert(req.DeviceID); err != nil {
|
|
api.Error(c, 500, "INTERNAL", "could not persist device")
|
|
return
|
|
}
|
|
|
|
// POST /devices n'émet PLUS de token : de l'identité user-first (V1), le
|
|
// device s'enregistre pour exister, puis le client appelle POST /auth/login
|
|
// avec username/password + device_id pour obtenir son token (cf.
|
|
// docs/api-v1.md §2). Réponse : { deviceId } uniquement.
|
|
api.OK(c, gin.H{"deviceId": req.DeviceID})
|
|
|
|
}
|
|
|
|
// DeviceDTO expose un device du compte (A1 — voir / révoquer).
|
|
type DeviceDTO struct {
|
|
DeviceID string `json:"deviceId"`
|
|
LastSeenAt *int64 `json:"lastSeenAt"`
|
|
}
|
|
|
|
// DevicesList renvoie les devices du compte connecté (`GET /devices`,
|
|
// dernier login = ce compte, les plus récemment vus d'abord).
|
|
func DevicesList(c *gin.Context) {
|
|
if Store == nil || Store.Repository == nil {
|
|
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
|
return
|
|
}
|
|
userID := c.GetString(UserIDKey)
|
|
rows, err := Store.Repository.Devices.ListByUser(userID)
|
|
if err != nil {
|
|
writeError(c, err)
|
|
return
|
|
}
|
|
out := make([]DeviceDTO, 0, len(rows))
|
|
for _, row := range rows {
|
|
out = append(out, DeviceDTO{DeviceID: row.DeviceID, LastSeenAt: row.LastSeenAt})
|
|
}
|
|
api.OK(c, out)
|
|
}
|
|
|
|
// DeviceRevoke révoque un device du compte (`DELETE /devices/:id`, A1 —
|
|
// téléphone perdu). Avec EnforceDeviceExists, ses tokens deviennent 401 et
|
|
// son login est refusé (ré-enregistrement explicite requis). Ligne absente
|
|
// ou d'un autre compte → 404 (pas d'énumération).
|
|
func DeviceRevoke(c *gin.Context) {
|
|
if Store == nil || Store.Repository == nil {
|
|
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
|
return
|
|
}
|
|
userID := c.GetString(UserIDKey)
|
|
id := c.Param("id")
|
|
if !deviceIDPattern.MatchString(id) {
|
|
api.Error(c, http.StatusNotFound, "NOT_FOUND", "device not found")
|
|
return
|
|
}
|
|
if err := Store.Repository.Devices.Revoke(userID, id); err != nil {
|
|
writeError(c, err)
|
|
return
|
|
}
|
|
api.OK(c, gin.H{"id": id})
|
|
}
|