ZDDC/zddc/internal/handler/directory.go
ZDDC fb13ff4fd8
All checks were successful
Notify chart dev on beta cut / notify-chart-dev (push) Successful in 5s
feat(browse): generic directory listing tool — default at folder URLs
A new HTML tool — browse — that lists the contents of any directory.
Designed for ZDDC archives but no ZDDC-specific filtering; just a
straight folder browser with expand/collapse, sort, and name filter.

Modes (auto-detected at page load):
  - Online: when served by zddc-server at a folder URL, queries
    the same URL with Accept: application/json to load the listing
    and renders it. Auto-served as the default at any directory
    under ZDDC_ROOT without an index.html (replacing the previous
    minimal-HTML stub from directory.go).
  - Local: 'Select Directory' button uses FileSystemAccessAPI to
    pick any folder on disk; works in Chromium-based browsers.

Features (Phase 1 — what's in this commit):
  - Tree view with lazy-loaded folders (children fetched on first
    expand).
  - Sort by name / size / extension / date (column header click).
  - Filter by name substring (toolbar input).
  - File click opens in a new tab — for server-backed pages,
    routes through zddc-server's normal handler so .archive
    redirects + apps cascade overrides + ACL all apply.

Phase 2 deferred:
  - ZIP files inline expansion (treat archive entries as virtual
    children).
  - File preview popup (reuse shared/preview-lib.js).
  - Extension multi-select filter.

Wiring:
  - browse/ added to top-level ./build's per-tool list, embed
    block, versions.txt, and the lockstep release commit + tag set.
    All seven tools (archive, transmittal, classifier, mdedit,
    landing, form, browse) advance together on stable cuts.
  - shared/build-lib.sh: browse added to ZDDC_RELEASE_TOOLS and
    verify_channel_links's per-tool loop.
  - zddc/internal/apps/embed.go: //go:embed browse.html +
    EmbeddedBytes("browse") case.
  - zddc/internal/apps/availability.go: browse available at every
    directory (same as archive).
  - zddc/internal/apps/handler.go: MatchAppHTML routes
    /<dir>/browse.html → 'browse'.
  - zddc/internal/handler/directory.go: when a directory request
    arrives with Accept: text/html and no index.html exists,
    serve the embedded browse.html bytes (with a JSON-fallback
    if the embedded slot is empty during bootstrap).
2026-05-03 19:56:51 -05:00

114 lines
3.7 KiB
Go

package handler
import (
"encoding/json"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"codeberg.org/VARASYS/ZDDC/zddc/internal/apps"
"codeberg.org/VARASYS/ZDDC/zddc/internal/config"
appfs "codeberg.org/VARASYS/ZDDC/zddc/internal/fs"
"codeberg.org/VARASYS/ZDDC/zddc/internal/zddc"
)
// safeJoin joins fsRoot and relPath, then verifies the result is under fsRoot.
// Returns ("", false) if relPath would escape fsRoot.
func safeJoin(fsRoot, relPath string) (string, bool) {
abs := filepath.Join(fsRoot, filepath.FromSlash(relPath))
if !strings.HasPrefix(abs, fsRoot+string(filepath.Separator)) && abs != fsRoot {
return "", false
}
return abs, true
}
// ServeDirectory handles a request for a directory path.
// If Accept: application/json → return Caddy-compatible JSON listing.
// Otherwise → return minimal HTML.
func ServeDirectory(cfg config.Config, w http.ResponseWriter, r *http.Request) {
urlPath := r.URL.Path
if !strings.HasSuffix(urlPath, "/") {
http.Redirect(w, r, urlPath+"/", http.StatusMovedPermanently)
return
}
email := EmailFromContext(r)
// Compute relative dir path (no leading or trailing slash)
dirPath := strings.TrimPrefix(urlPath, "/")
dirPath = strings.TrimSuffix(dirPath, "/")
// ACL check on this directory itself
absDir, ok := safeJoin(cfg.Root, dirPath)
if !ok {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
chain, err := zddc.EffectivePolicy(cfg.Root, absDir)
if err != nil {
slog.Warn("ACL policy error", "path", absDir, "err", err)
}
if !zddc.AllowedWithChain(chain, email) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
accept := r.Header.Get("Accept")
// For HTML requests, serve index.html if present (landing page convention)
if !strings.Contains(accept, "application/json") {
indexPath := filepath.Join(absDir, "index.html")
if info, err := os.Stat(indexPath); err == nil && !info.IsDir() {
ServeFile(w, r, indexPath)
return
}
}
// Build base URL for listing entries
baseURL := urlPath // relative URLs suffice for JSON listings
entries, err := appfs.ListDirectory(cfg.Root, dirPath, email, baseURL)
if err != nil {
if os.IsNotExist(err) {
http.Error(w, "Not Found", http.StatusNotFound)
} else {
slog.Error("listing directory", "path", dirPath, "err", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
return
}
if strings.Contains(accept, "application/json") {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-cache")
if err := json.NewEncoder(w).Encode(entries); err != nil {
slog.Error("encoding directory listing", "err", err)
}
return
}
// Browser HTML fallback: serve the embedded `browse` tool. It's a
// single-file SPA whose autoDetectServerMode loads the JSON listing
// for the current directory and renders it as a sortable, filterable
// tree. Same bytes that get served at /<dir>/browse.html — but at
// the bare directory URL too, so any zddc-served folder presents a
// usable file browser to anyone who navigates to it.
body := apps.EmbeddedBytes("browse")
if len(body) == 0 {
// Bootstrap state: a fresh build hasn't populated browse.html
// into the embed yet. Fall through to JSON for clients that
// will still parse it.
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-cache")
if err := json.NewEncoder(w).Encode(entries); err != nil {
slog.Error("encoding directory listing (no-embed fallback)", "err", err)
}
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("X-ZDDC-Source", "embedded:browse")
w.Header().Set("Cache-Control", "public, max-age=300, must-revalidate")
_, _ = w.Write(body)
}