Null-DRM-Official/apps/streamd/internal/api/modules.go
404errordeveloper da8e1123ec
All checks were successful
release / build-and-upload (push) Successful in 7m5s
Streamd v0.2.0: rename, modules panel, stable/beta channels
- Rename product/host binary to streamd (drm compat copy still shipped)
- Go module path streamd; STREAMD_* env aliases; agent UA streamd-agent
- Panel Modules store + agent pull sync (modstore / modsync)
- Rolling stable + beta download tags; README/docs channel curl blocks
- Release notes in docs/releases/v0.2.0.md attached by Forgejo Actions
2026-10-10 15:58:26 +02:00

272 lines
7.6 KiB
Go

package api
import (
"encoding/json"
"errors"
"io"
"net/http"
"path/filepath"
"strings"
"time"
"streamd/apps/streamd/internal/auth"
"streamd/apps/streamd/internal/modstore"
)
// ModulesNotifier pushes module change events to agents and the dashboard.
type ModulesNotifier interface {
NotifyModulesChanged(name, reason string)
}
func (h *Handler) modStore() *modstore.Store {
if h.Modules != nil {
return h.Modules
}
root := filepath.Join(h.DataDir, "modules")
return modstore.New(root)
}
func (h *Handler) notifyModules(name, reason string) {
if h.ModulesNotify != nil {
h.ModulesNotify.NotifyModulesChanged(name, reason)
return
}
// Hub also implements Notifier; prefer the dedicated method when available.
if n, ok := h.Notifier.(ModulesNotifier); ok {
n.NotifyModulesChanged(name, reason)
}
}
func (h *Handler) modules(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/api/modules")
path = strings.Trim(path, "/")
switch {
case path == "" && r.Method == http.MethodGet:
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
return
}
h.listModules(w, r)
case path == "upload" && r.Method == http.MethodPost:
h.uploadModule(w, r)
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodGet:
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
return
}
h.getModule(w, r, path)
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodPut:
h.putModule(w, r, path)
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodDelete:
h.deleteModule(w, r, path)
case strings.HasSuffix(path, "/yaml") && r.Method == http.MethodGet:
name := strings.TrimSuffix(path, "/yaml")
name = strings.Trim(name, "/")
h.getModuleYAML(w, r, name)
case strings.HasSuffix(path, "/package") && r.Method == http.MethodGet:
name := strings.TrimSuffix(path, "/package")
name = strings.Trim(name, "/")
h.getModulePackage(w, r, name)
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
func (h *Handler) listModules(w http.ResponseWriter, r *http.Request) {
list, err := h.modStore().List()
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"modules": list})
}
func (h *Handler) getModule(w http.ResponseWriter, r *http.Request, name string) {
if !modstore.NameRe.MatchString(name) {
writeErr(w, http.StatusBadRequest, "invalid module name")
return
}
info := h.modStore().Info(name)
if !info.HasYAML && !info.HasPackage {
writeErr(w, http.StatusNotFound, "module not found")
return
}
out := map[string]any{"module": info}
if r.URL.Query().Get("include") == "yaml" {
// YAML may hold secrets — operator+.
if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
return
}
raw, err := h.modStore().ReadYAML(name)
if err != nil {
writeErr(w, http.StatusNotFound, err.Error())
return
}
out["yaml"] = string(raw)
}
writeJSON(w, http.StatusOK, out)
}
func (h *Handler) getModuleYAML(w http.ResponseWriter, r *http.Request, name string) {
if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
return
}
if !modstore.NameRe.MatchString(name) {
writeErr(w, http.StatusBadRequest, "invalid module name")
return
}
raw, err := h.modStore().ReadYAML(name)
if err != nil {
writeErr(w, http.StatusNotFound, err.Error())
return
}
w.Header().Set("Content-Type", "text/yaml; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(raw)
}
func (h *Handler) getModulePackage(w http.ResponseWriter, r *http.Request, name string) {
if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
return
}
if !modstore.NameRe.MatchString(name) {
writeErr(w, http.StatusBadRequest, "invalid module name")
return
}
f, _, err := h.modStore().OpenPackage(name)
if err != nil {
writeErr(w, http.StatusNotFound, err.Error())
return
}
defer f.Close()
modTime := time.Time{}
if st, err := f.Stat(); err == nil {
modTime = st.ModTime()
}
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", `attachment; filename="`+name+`.zip"`)
w.Header().Set("X-Content-Type-Options", "nosniff")
http.ServeContent(w, r, name+".zip", modTime, f)
}
func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string) {
p, ok := auth.Guard(w, r, auth.RoleOperator)
if !ok {
return
}
if !modstore.NameRe.MatchString(name) {
writeErr(w, http.StatusBadRequest, "invalid module name")
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 2<<20))
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
yamlBytes, err := extractModuleYAML(r.Header.Get("Content-Type"), body)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
info, err := h.modStore().WriteYAML(name, yamlBytes)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.audit(r, p, http.StatusOK, "updated module.yaml for "+name)
h.logger().Info("module.yaml updated", "module", name, "by", p.Actor(), "sha256", info.YAMLSHA256)
h.notifyModules(name, "yaml_updated")
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"module": info,
})
}
func (h *Handler) deleteModule(w http.ResponseWriter, r *http.Request, name string) {
p, ok := auth.Guard(w, r, auth.RoleOperator)
if !ok {
return
}
if !modstore.NameRe.MatchString(name) {
writeErr(w, http.StatusBadRequest, "invalid module name")
return
}
if err := h.modStore().Delete(name); err != nil {
writeErr(w, http.StatusNotFound, err.Error())
return
}
h.audit(r, p, http.StatusOK, "deleted module "+name)
h.logger().Info("module deleted", "module", name, "by", p.Actor())
h.notifyModules(name, "deleted")
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func (h *Handler) uploadModule(w http.ResponseWriter, r *http.Request) {
p, ok := auth.Guard(w, r, auth.RoleOperator)
if !ok {
return
}
if err := r.ParseMultipartForm(modstore.MaxPackageBytes + (1 << 20)); err != nil {
writeErr(w, http.StatusBadRequest, "multipart: "+err.Error())
return
}
name := strings.TrimSpace(r.FormValue("name"))
file, hdr, err := r.FormFile("file")
if err != nil {
writeErr(w, http.StatusBadRequest, "missing file field")
return
}
defer file.Close()
if hdr.Size > modstore.MaxPackageBytes {
writeErr(w, http.StatusBadRequest, "zip too large")
return
}
raw, err := io.ReadAll(io.LimitReader(file, modstore.MaxPackageBytes+1))
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if int64(len(raw)) > modstore.MaxPackageBytes {
writeErr(w, http.StatusBadRequest, "zip too large")
return
}
info, err := h.modStore().InstallZip(raw, name)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.audit(r, p, http.StatusOK, "uploaded module package "+info.Name)
h.logger().Info("module package uploaded",
"module", info.Name, "by", p.Actor(),
"package_sha256", info.PackageSHA256, "arches", info.Arches)
h.notifyModules(info.Name, "uploaded")
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"module": info,
})
}
// extractModuleYAML accepts raw YAML or JSON {"yaml":"..."}.
func extractModuleYAML(contentType string, body []byte) ([]byte, error) {
ct := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))
switch ct {
case "application/json", "text/json":
var wrap struct {
YAML string `json:"yaml"`
}
if err := json.Unmarshal(body, &wrap); err != nil {
return nil, err
}
if strings.TrimSpace(wrap.YAML) == "" {
return nil, errors.New("empty yaml field")
}
return []byte(wrap.YAML), nil
default:
return body, nil
}
}