// Package api expose les fichiers en REST/JSON. // // GET /api/me session, fournisseurs et réglages publics (sans authentification) // GET /api/list?path=dir[&details=1] contenu d'un dossier (details : vue Galerie) // GET /api/search?q=texte[&tag=t][&fav=true][&details=1] recherche (noms, tags, texte des fichiers) // GET /api/tags tags utilisés et nombre d'éléments // POST /api/meta/favorite {"paths":[...],"favorite":true} favoris // POST /api/meta/tags {"paths":[...],"add":[...],"remove":[...]} tags // POST /api/meta/icon {"paths":[...],"icon":"server"} icône de dossiers ("" : défaut) // GET /api/file?path=a/b.pdf[&inline=1] téléchargement (Range, ETag) ; inline : affichage dans le navigateur si sûr // GET /api/preview?path=a/b.md aperçu en lecture seule (liste blanche, texte plafonné ; voir preview.go) // PUT /api/file?path=a/b.pdf[&conflict=fail|overwrite|rename][&mtime=ms] dépôt en flux // POST /api/folder {"path":"a/b"} création de dossier // POST /api/move {"from":"x","to":"y"} renommage / déplacement // POST /api/move-many {"paths":[...],"dir":"d"} déplacement multiple // POST /api/copy {"from":"x","to":"y"} duplication (fichier ou dossier) // DELETE /api/entry?path=x[&recursive=true] mise à la poubelle (suppression définitive // dans .poubelle ; path=.poubelle : la vide) // POST /api/trash/restore {"paths":[...]} restauration depuis la poubelle // GET /api/thumb?path=x miniature d'une image // GET /api/zip?path=x / POST (formulaire paths=[...]) archive ZIP en flux // GET /api/hash?path=x empreinte SHA-256 d'un fichier // GET /api/history?path=x versions d'un fichier // GET /api/history/version?path=x&id=v contenu d'une version // POST /api/history/snapshot {"path"} version du contenu courant // POST /api/history/restore {"path","id"} restauration // GET /api/shares[?path=x] liens de partage (d'un élément ou tous) // POST /api/shares {"path","days","password"} nouveau lien (days 0 : sans expiration) // DELETE /api/shares?id=x révocation d'un lien // POST /api/shares/revoke-all révocation de tous les liens (administrateur) // GET /api/public/{jeton}[?sub=d] lien de partage (sans authentification) // POST /api/public/{jeton}/unlock mot de passe d'un lien protégé // GET /api/public/{jeton}/file|zip|thumb|preview contenu d'un lien de partage // GET /api/settings / PUT paramètres (écriture : administrateur) // GET /api/admin/s3 / PUT, POST /api/admin/s3/test racine S3 (administrateur) // GET /api/logo / PUT (image/png) / DELETE logo 64x64 // POST /api/account/password changement du mot de passe (compte local) // PATCH /api/account nom et e-mail (compte local) // GET|POST /api/admin/users, PATCH|DELETE /api/admin/users/{id} comptes (administrateur) // // Les chemins sont vus par l'utilisateur connecté (storage.Space) : l'arborescence // commune, plus ".perso/..." (son espace personnel), ".favoris" (ses favoris, // liens symboliques vers les originaux ; DELETE .favoris/x retire le lien) et // ".poubelle" (éléments supprimés, de l'arborescence commune et de son espace). package api import ( "encoding/json" "errors" "io" "log/slog" "net/http" "strings" "time" "github.com/vblogio/upandown/internal/auth" "github.com/vblogio/upandown/internal/storage" ) // Handler regroupe les routes de l'API. type Handler struct { Store *storage.Store // arborescence commune : paramètres, logo Spaces *storage.Spaces // fichiers : arborescence commune, espaces personnels, favoris Auth *auth.Auth // nil : pas d'authentification intégrée Accounts *auth.Accounts // nil : pas de comptes (AUTH_MODE=none) MaxJSON int64 // taille maximale d'un corps JSON (octets) // PreviewMaxText : si > 0, remplace le plafond de texte des paramètres (tests). PreviewMaxText int64 Mode string // none, local, oidc ou both OIDCName string // libellé du bouton de connexion OIDC Version string // SecureCookies : cookies de déverrouillage des liens marqués Secure même // en HTTP direct (URL publique en https). SecureCookies bool // OnUserRemoved est appelé après la suppression d'un compte (jetons à révoquer). OnUserRemoved func(id string) unlocks *auth.Limiter } // Init prépare les limiteurs internes ; à appeler avant Register. func (h *Handler) Init() *Handler { if h.MaxJSON == 0 { h.MaxJSON = 1 << 20 } h.unlocks = auth.NewLimiter(10, 15*time.Minute) return h } // userID identifie l'utilisateur d'une requête : identifiant de son compte, // ou LocalUser sans authentification intégrée. func userID(r *http.Request) string { if u := auth.UserFrom(r.Context()); u != nil && u.ID != "" { return u.ID } return storage.LocalUser } // UserID est la fonction d'identification utilisée aussi par les jetons. func UserID(r *http.Request) string { return userID(r) } // isAdmin : sans authentification intégrée (AUTH_MODE=none), tout le monde // administre, le contrôle d'accès étant alors celui du reverse proxy. Sinon, // il faut une session de rôle administrateur. func (h *Handler) isAdmin(r *http.Request) bool { if h.Mode == "none" { return true } u := auth.UserFrom(r.Context()) return u != nil && u.Role == auth.RoleAdmin } // space renvoie la vue de l'utilisateur de la requête (espace personnel et favoris). func (h *Handler) space(w http.ResponseWriter, r *http.Request) (*storage.Space, bool) { u, err := h.Spaces.For(userID(r), h.isAdmin(r)) if err != nil { fail(w, err) return nil, false } return u, true } // admin refuse les requêtes des non-administrateurs. func (h *Handler) admin(w http.ResponseWriter, r *http.Request) bool { if !h.isAdmin(r) { writeErr(w, http.StatusForbidden, "réservé aux administrateurs") return false } return true } // Register enregistre les routes sur mux (motifs Go 1.22+). func (h *Handler) Register(mux *http.ServeMux) { mux.HandleFunc("GET /api/me", h.me) mux.HandleFunc("GET /api/list", h.list) mux.HandleFunc("GET /api/search", h.search) mux.HandleFunc("GET /api/tags", h.tags) mux.HandleFunc("POST /api/meta/favorite", h.setFavorite) mux.HandleFunc("POST /api/meta/tags", h.editTags) mux.HandleFunc("POST /api/meta/icon", h.setIcon) mux.HandleFunc("GET /api/file", h.download) mux.HandleFunc("GET /api/preview", h.preview) mux.HandleFunc("PUT /api/file", h.upload) mux.HandleFunc("POST /api/folder", h.mkdir) mux.HandleFunc("POST /api/move", h.move) mux.HandleFunc("POST /api/move-many", h.moveMany) mux.HandleFunc("POST /api/copy", h.copy) mux.HandleFunc("DELETE /api/entry", h.delete) mux.HandleFunc("POST /api/trash/restore", h.restoreTrash) mux.HandleFunc("GET /api/thumb", h.thumb) mux.HandleFunc("GET /api/zip", h.zip) mux.HandleFunc("POST /api/zip", h.zip) mux.HandleFunc("GET /api/hash", h.hash) mux.HandleFunc("GET /api/history", h.history) mux.HandleFunc("GET /api/history/version", h.readVersion) mux.HandleFunc("POST /api/history/snapshot", h.snapshot) mux.HandleFunc("POST /api/history/restore", h.restore) mux.HandleFunc("GET /api/shares", h.shares) mux.HandleFunc("POST /api/shares", h.createShare) mux.HandleFunc("DELETE /api/shares", h.revokeShare) mux.HandleFunc("POST /api/shares/revoke-all", h.revokeAllShares) mux.HandleFunc("GET /api/public/{token}", h.publicInfo) mux.HandleFunc("POST /api/public/{token}/unlock", h.publicUnlock) mux.HandleFunc("GET /api/public/{token}/file", h.publicFile) mux.HandleFunc("GET /api/public/{token}/zip", h.publicZip) mux.HandleFunc("GET /api/public/{token}/thumb", h.publicThumb) mux.HandleFunc("GET /api/public/{token}/preview", h.publicPreview) mux.HandleFunc("GET /api/settings", h.readSettings) mux.HandleFunc("PUT /api/settings", h.writeSettings) mux.HandleFunc("GET /api/logo", h.readLogo) mux.HandleFunc("PUT /api/logo", h.writeLogo) mux.HandleFunc("DELETE /api/logo", h.deleteLogo) mux.HandleFunc("GET /api/admin/s3", h.adminS3) mux.HandleFunc("PUT /api/admin/s3", h.adminSaveS3) mux.HandleFunc("POST /api/admin/s3/test", h.adminTestS3) if h.Accounts != nil { mux.HandleFunc("POST /api/account/password", h.changePassword) mux.HandleFunc("PATCH /api/account", h.patchAccount) mux.HandleFunc("GET /api/admin/users", h.adminUsers) mux.HandleFunc("POST /api/admin/users", h.adminCreateUser) mux.HandleFunc("PATCH /api/admin/users/{id}", h.adminPatchUser) mux.HandleFunc("DELETE /api/admin/users/{id}", h.adminDeleteUser) } mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusNotFound, "route inconnue") }) } func writeJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } func writeErr(w http.ResponseWriter, status int, msg string) { writeJSON(w, status, map[string]string{"error": msg}) } // fail traduit une erreur du Store en code HTTP. func fail(w http.ResponseWriter, err error) { var tooBig *http.MaxBytesError switch { case errors.Is(err, storage.ErrNotFound): writeErr(w, http.StatusNotFound, err.Error()) case errors.Is(err, storage.ErrExists), errors.Is(err, storage.ErrNotEmpty): writeErr(w, http.StatusConflict, err.Error()) case errors.Is(err, storage.ErrConflict): writeErr(w, http.StatusPreconditionFailed, err.Error()) case errors.Is(err, storage.ErrInvalidPath), errors.Is(err, storage.ErrInvalidImage): writeErr(w, http.StatusBadRequest, err.Error()) case errors.Is(err, storage.ErrForbidden): writeErr(w, http.StatusForbidden, err.Error()) case errors.Is(err, storage.ErrQuota): writeErr(w, http.StatusInsufficientStorage, err.Error()) case errors.Is(err, storage.ErrTooLarge), errors.As(err, &tooBig): writeErr(w, http.StatusRequestEntityTooLarge, "fichier trop volumineux") default: slog.Error("erreur interne", "err", err) writeErr(w, http.StatusInternalServerError, "erreur interne") } } func (h *Handler) readBody(w http.ResponseWriter, r *http.Request) ([]byte, error) { return io.ReadAll(http.MaxBytesReader(w, r.Body, h.MaxJSON)) } func (h *Handler) decode(w http.ResponseWriter, r *http.Request, v any) bool { b, err := h.readBody(w, r) if err == nil { err = json.Unmarshal(b, v) } if err != nil { writeErr(w, http.StatusBadRequest, "requête JSON invalide") return false } return true } func wantDetails(r *http.Request) bool { v := r.URL.Query().Get("details") return v == "1" || v == "true" } func secure(r *http.Request) bool { return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") }