package api import ( "errors" "net/http" "time" "github.com/vblogio/upandown/internal/storage" ) // Liens de partage publics : /s/ dans l'interface, /api/public/ // pour les données. Rien d'autre n'est accessible sans authentification : ni // l'explorateur, ni les chemins réels (les entrées sont décrites relativement // à l'élément partagé). const unlockCookiePrefix = "ud_share_" type publicEntry struct { Name string `json:"name"` IsDir bool `json:"isDir"` Size int64 `json:"size"` ModTime time.Time `json:"modTime"` } type publicInfo struct { Title string `json:"title"` Logo string `json:"logo,omitempty"` Protected bool `json:"protected,omitempty"` // mot de passe requis (rien d'autre n'est révélé) Name string `json:"name,omitempty"` IsDir bool `json:"isDir"` Size int64 `json:"size"` ModTime time.Time `json:"modTime"` Sub string `json:"sub,omitempty"` // dossier affiché, relatif à l'élément partagé Entries []publicEntry `json:"entries,omitempty"` Expires *time.Time `json:"expires,omitempty"` } // shared résout le lien de la requête et vérifie le déverrouillage s'il est // protégé par un mot de passe. func (h *Handler) shared(w http.ResponseWriter, r *http.Request) (storage.Share, *storage.Store, bool, bool) { w.Header().Set("Cache-Control", "no-store") w.Header().Set("X-Robots-Tag", "noindex, nofollow") sh, st, err := h.Spaces.ResolveShare(r.PathValue("token")) if err != nil { if errors.Is(err, storage.ErrNotFound) { writeErr(w, http.StatusNotFound, "lien invalide, expiré ou révoqué") } else { fail(w, err) } return sh, nil, false, false } unlocked := true if sh.Protected { want, err := st.UnlockCookie(sh) c, cerr := r.Cookie(unlockCookiePrefix + sh.ID) unlocked = err == nil && cerr == nil && c.Value == want } return sh, st, unlocked, true } // sharedItem renvoie le Store et le chemin de l'élément visé (sub : sous-chemin // demandé), en refusant l'accès tant que le lien n'est pas déverrouillé. func (h *Handler) sharedItem(w http.ResponseWriter, r *http.Request) (storage.Share, *storage.Store, string, string, bool) { sh, st, unlocked, ok := h.shared(w, r) if !ok { return sh, nil, "", "", false } if !unlocked { writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "mot de passe requis", "code": "password"}) return sh, nil, "", "", false } sub := r.URL.Query().Get("sub") full, err := storage.SharedPath(sh, sub) if err != nil { fail(w, err) return sh, nil, "", "", false } return sh, st, full, sub, true } func (h *Handler) branding(info *publicInfo) { if st, err := h.Store.ReadSettings(); err == nil { info.Title, info.Logo = st.Title, st.Logo } } func (h *Handler) publicInfo(w http.ResponseWriter, r *http.Request) { sh, st, unlocked, ok := h.shared(w, r) if !ok { return } var info publicInfo h.branding(&info) if !unlocked { info.Protected = true writeJSON(w, http.StatusOK, info) return } sub := r.URL.Query().Get("sub") full, err := storage.SharedPath(sh, sub) if err != nil { fail(w, err) return } e, err := st.Stat(full) if err != nil { fail(w, err) return } info.Name, info.IsDir, info.Size, info.ModTime, info.Sub, info.Expires = e.Name, e.IsDir, e.Size, e.ModTime, sub, sh.Expires if sub == "" { info.Name = baseName(sh.Path) } if e.IsDir { es, err := st.List(full) if err != nil { fail(w, err) return } info.Entries = make([]publicEntry, 0, len(es)) for _, x := range es { info.Entries = append(info.Entries, publicEntry{Name: x.Name, IsDir: x.IsDir, Size: x.Size, ModTime: x.ModTime}) } } writeJSON(w, http.StatusOK, info) } func baseName(p string) string { for i := len(p) - 1; i >= 0; i-- { if p[i] == '/' { return p[i+1:] } } return p } // publicUnlock vérifie le mot de passe d'un lien protégé et pose le cookie de // déverrouillage (12 h). func (h *Handler) publicUnlock(w http.ResponseWriter, r *http.Request) { sh, st, _, ok := h.shared(w, r) if !ok { return } var req struct { Password string `json:"password"` } if !h.decode(w, r, &req) { return } key := sh.ID + "|" + r.RemoteAddr if !h.unlocks.Allowed(key) { w.Header().Set("Retry-After", "900") writeErr(w, http.StatusTooManyRequests, "trop de tentatives : réessayer dans quelques minutes") return } if !sh.CheckPassword(req.Password) { h.unlocks.Fail(key) writeErr(w, http.StatusForbidden, "mot de passe incorrect") return } h.unlocks.Reset(key) v, err := st.UnlockCookie(sh) if err != nil { fail(w, err) return } http.SetCookie(w, &http.Cookie{ Name: unlockCookiePrefix + sh.ID, Value: v, Path: "/", MaxAge: int((12 * time.Hour).Seconds()), HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: secure(r) || h.SecureCookies, }) w.WriteHeader(http.StatusNoContent) } func (h *Handler) publicFile(w http.ResponseWriter, r *http.Request) { sh, st, full, _, ok := h.sharedItem(w, r) if !ok { return } f, fi, err := st.Open(full) if err != nil { fail(w, err) return } defer f.Close() inline := r.URL.Query().Get("inline") == "1" if !inline && r.Header.Get("Range") == "" { st.CountDownload(sh.ID) } serveFile(w, r, f, fi, fi.Name(), inline) } func (h *Handler) publicZip(w http.ResponseWriter, r *http.Request) { sh, st, full, _, ok := h.sharedItem(w, r) if !ok { return } item, err := st.SharedZipItem(full) if err != nil { fail(w, err) return } st.CountDownload(sh.ID) w.Header().Set("Content-Type", "application/zip") w.Header().Set("Content-Disposition", contentDisposition(false, item.Name+".zip")) if err := storage.WriteZip(w, []storage.ZipItem{item}); err != nil { panic(http.ErrAbortHandler) } } func (h *Handler) publicThumb(w http.ResponseWriter, r *http.Request) { _, st, full, _, ok := h.sharedItem(w, r) if !ok { return } data, typ, mod, err := st.Thumb(full) if err != nil { fail(w, err) return } // Réponse protégée : pas de cache partagé. writeThumb(w, data, typ, mod) }