From da8e1123ec4f698cc13d38ed453d55d20e546325 Mon Sep 17 00:00:00 2001 From: 404errordeveloper Date: Sat, 10 Oct 2026 15:58:26 +0200 Subject: [PATCH 1/5] 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 --- .forgejo/workflows/release.yml | 139 +++- README.md | 108 ++- apps/agent/README.md | 27 +- apps/agent/agent.yaml | 5 +- apps/agent/agentcmd/agentcmd.go | 41 +- apps/agent/go.mod | 7 +- apps/agent/go.sum | 6 - apps/agent/internal/client/client.go | 61 +- apps/agent/internal/config/config.go | 11 +- apps/agent/internal/device/pool.go | 2 +- apps/agent/internal/modsync/sync.go | 332 ++++++++-- apps/agent/internal/modsync/sync_test.go | 154 +++++ apps/agent/internal/poller/poller.go | 4 +- apps/agent/internal/worker/worker.go | 14 +- apps/agent/internal/wsclient/wsclient.go | 12 +- apps/capture/README.md | 12 +- apps/capture/capturecmd/capturecmd.go | 14 +- apps/capture/go.mod | 12 +- apps/capture/go.sum | 8 - apps/cli/capture_args_test.go | 2 +- apps/cli/catalogcmd/catalogcmd.go | 6 +- apps/cli/go.mod | 22 +- apps/cli/main.go | 41 +- apps/cli/modulescmd/modulescmd.go | 4 +- apps/modules/README.md | 20 +- apps/modules/all/all.go | 6 +- apps/modules/all/all_test.go | 2 +- apps/modules/bbc/bbc.go | 12 +- apps/modules/bbc/bbc_test.go | 10 +- apps/modules/bbc/config.go | 4 +- apps/modules/bbc/steps.go | 4 +- apps/modules/c4/c4.go | 12 +- apps/modules/c4/config.go | 4 +- apps/modules/c4/steps.go | 4 +- apps/modules/go.mod | 6 +- apps/modules/itv/config.go | 4 +- apps/modules/itv/itv.go | 12 +- apps/modules/itv/steps.go | 4 +- apps/modules/my5/config.go | 4 +- apps/modules/my5/my5.go | 12 +- apps/modules/my5/steps.go | 4 +- apps/modules/provider/provider.go | 10 +- apps/modules/rte/config.go | 6 +- apps/modules/rte/live_test.go | 2 +- apps/modules/rte/mpd.go | 2 +- apps/modules/rte/rte.go | 12 +- apps/modules/rte/rte_test.go | 4 +- apps/modules/rte/steps.go | 4 +- apps/modules/tg4/catalog.go | 6 +- apps/modules/tg4/config.go | 6 +- apps/modules/tg4/keys.go | 8 +- apps/modules/tg4/steps.go | 4 +- apps/modules/tg4/tg4.go | 12 +- apps/modules/tg4/tg4_test.go | 6 +- apps/pkg/README.md | 6 +- apps/pkg/app/app.go | 8 +- apps/pkg/bootstrap/bootstrap.go | 25 +- apps/pkg/bootstrap/embedded/README.md | 14 +- .../pkg/bootstrap/embedded/apps/pkg/pkg.gomod | 2 +- apps/pkg/bootstrap/embedded/modules/README.md | 2 +- apps/pkg/bootstrap/embedded/root-go-mod.txt | 2 +- apps/pkg/capture/capture.go | 2 +- apps/pkg/go.mod | 2 +- apps/pkg/modcfg/modcfg.go | 4 +- apps/pkg/modhost/discover.go | 2 +- apps/pkg/modhost/protocol.go | 4 +- apps/pkg/modhost/remote_app.go | 10 +- apps/pkg/modhost/root.go | 14 +- apps/pkg/phonecap/phonecap.go | 14 +- apps/pkg/proxy/embed.go | 6 +- apps/pkg/proxy/proxy.go | 10 +- apps/pkg/repo/root.go | 2 +- apps/pkg/uiflow/uiflow.go | 2 +- apps/proxy/README.md | 26 +- apps/proxy/go.mod | 6 +- apps/proxy/proxyctlcmd/proxyctlcmd.go | 8 +- apps/streamd/README.md | 4 +- apps/streamd/go.mod | 6 +- apps/streamd/internal/api/api.go | 15 +- apps/streamd/internal/api/apps.go | 33 +- apps/streamd/internal/api/control.go | 6 +- apps/streamd/internal/api/events.go | 6 +- apps/streamd/internal/api/modules.go | 247 +++++-- apps/streamd/internal/api/variants.go | 2 +- apps/streamd/internal/auth/auth_test.go | 2 +- apps/streamd/internal/auth/handlers.go | 2 +- apps/streamd/internal/auth/middleware.go | 2 +- apps/streamd/internal/deps/deps.go | 4 +- apps/streamd/internal/hlsgate/hlsgate.go | 8 +- apps/streamd/internal/hlsgate/hlsgate_test.go | 6 +- apps/streamd/internal/modstore/modstore.go | 622 ++++++++++++++++++ .../internal/modstore/modstore_test.go | 149 +++++ apps/streamd/internal/scheduler/scheduler.go | 2 +- .../internal/supervisor/appdefaults.go | 8 +- .../internal/supervisor/appdefaults_test.go | 10 +- .../supervisor/ffmpeg_integration_test.go | 2 +- apps/streamd/internal/supervisor/media.go | 8 +- apps/streamd/internal/supervisor/outputs.go | 2 +- .../internal/supervisor/outputs_test.go | 2 +- apps/streamd/internal/supervisor/stub.go | 2 +- apps/streamd/internal/supervisor/variants.go | 4 +- apps/streamd/internal/ui/index.html | 6 +- apps/streamd/internal/ui/static/app.css | 42 ++ apps/streamd/internal/ui/static/js/api.js | 39 ++ apps/streamd/internal/ui/static/js/app.js | 6 + apps/streamd/internal/ui/static/js/store.js | 3 + .../internal/ui/static/js/views/modules.js | 310 +++++++++ apps/streamd/internal/ws/hub.go | 20 +- apps/streamd/servecmd/servecmd.go | 64 +- docs/README.md | 4 +- docs/architecture.md | 34 +- docs/capture.md | 36 +- docs/modules.md | 22 +- docs/providers/bbc.md | 8 +- docs/providers/rte.md | 12 +- docs/providers/tg4.md | 16 +- docs/quickstart.md | 38 +- docs/release.md | 54 +- docs/releases/v0.2.0.md | 65 ++ docs/streamd-server-setup.md | 96 +-- docs/streamd.md | 48 +- modules/README.md | 10 +- modules/bbc/go.mod | 10 +- modules/bbc/main.go | 12 +- modules/c4/go.mod | 10 +- modules/c4/main.go | 12 +- modules/itv/go.mod | 10 +- modules/itv/main.go | 12 +- modules/my5/go.mod | 10 +- modules/my5/main.go | 12 +- modules/rte/go.mod | 10 +- modules/rte/main.go | 12 +- modules/tg4/go.mod | 10 +- modules/tg4/main.go | 12 +- scripts/build-modules-release.ps1 | 2 +- scripts/build-release.ps1 | 51 +- scripts/build-release.sh | 37 +- scripts/notify-telegram.ps1 | 22 +- scripts/notify-telegram.sh | 26 +- www/index.html | 22 +- 140 files changed, 2949 insertions(+), 851 deletions(-) create mode 100644 apps/agent/internal/modsync/sync_test.go create mode 100644 apps/streamd/internal/modstore/modstore.go create mode 100644 apps/streamd/internal/modstore/modstore_test.go create mode 100644 apps/streamd/internal/ui/static/js/views/modules.js create mode 100644 docs/releases/v0.2.0.md diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index e9181c7..d534396 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -1,7 +1,16 @@ -# Build multi-platform drm binaries + Android MITM and attach them to a Forgejo release. +# Build multi-platform streamd (+ drm compat) binaries + Android MITM and attach them to a Forgejo release. # -# Trigger: push a version tag -# git tag v1.2.3 && git push origin v1.2.3 +# Triggers: +# Stable: git tag v1.2.3 && git push origin v1.2.3 +# Beta: git tag v1.2.3-beta.1 && git push origin v1.2.3-beta.1 +# +# Each version tag gets its own release. CI also retargets a rolling channel tag: +# vX.Y.Z → release + update `stable` (always-latest download URL) +# vX.Y.Z-
    → prerelease + update `beta`  (always-latest beta URL)
+#
+# Download without pinning a version:
+#   .../releases/download/stable/streamd-linux-amd64
+#   .../releases/download/beta/streamd-linux-amd64
 #
 # Requires a Forgejo Actions runner registered against this instance
 # (label must match runs-on below — default act_runner often uses "docker").
@@ -23,6 +32,35 @@ jobs:
         with:
           fetch-depth: 0
 
+      - name: Classify tag (stable vs beta)
+        id: meta
+        run: |
+          set -euo pipefail
+          TAG="${{ github.ref_name }}"
+          # Strict SemVer: v1.2.3 = stable; v1.2.3-beta.1 / -rc.1 / -alpha.1 = beta channel
+          if echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
+            CHANNEL=stable
+            PRERELEASE=false
+            TITLE="$TAG"
+            NOTES_KIND=stable
+          elif echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+-(beta|rc|alpha)(\.[0-9]+)?$'; then
+            CHANNEL=beta
+            PRERELEASE=true
+            TITLE="$TAG (beta)"
+            NOTES_KIND=beta
+          else
+            echo "Unsupported host tag '$TAG'." >&2
+            echo "Use vX.Y.Z for stable or vX.Y.Z-beta.N / -rc.N / -alpha.N for beta." >&2
+            exit 1
+          fi
+          {
+            echo "channel=$CHANNEL"
+            echo "prerelease=$PRERELEASE"
+            echo "title=$TITLE"
+            echo "notes_kind=$NOTES_KIND"
+          } >> "$GITHUB_OUTPUT"
+          echo "tag=$TAG channel=$CHANNEL prerelease=$PRERELEASE"
+
       - name: Setup Go
         uses: actions/setup-go@v5
         with:
@@ -37,44 +75,94 @@ jobs:
           ./scripts/build-release.sh "${{ github.ref_name }}"
           ls -la dist/release
 
-      - name: Upload to Forgejo release
+      - name: Prepare release notes
+        run: |
+          set -euo pipefail
+          TAG="${{ github.ref_name }}"
+          CHANNEL="${{ steps.meta.outputs.channel }}"
+          NOTES="docs/releases/${TAG}.md"
+          if [ -f "$NOTES" ]; then
+            cp "$NOTES" /tmp/release-notes.md
+            echo "Using $NOTES"
+          else
+            cat > /tmp/release-notes.md <\`
+          - Beta: \`…/releases/download/beta/\`
+
+          Built with \`CGO_ENABLED=0\` via \`scripts/build-release.sh\`.
+          Phone capture still needs Magisk + \`streamd proxy install-ca --reinject\`.
+          EOF
+            echo "No $NOTES — using generic notes"
+          fi
+          cat > /tmp/channel-notes.md <
   streamd Dashboard — overview, live Channel 4, HLS link
@@ -64,15 +64,55 @@ Server setup guide: [docs/streamd-server-setup.md](docs/streamd-server-setup.md)
 
 ### 1️⃣ Download
 
-From the latest **`v*`** release grab your host binary (e.g. `drm-windows-amd64.exe`)
-and `proxy-android-arm64`. From a **`modules-v*`** release grab the zips you need
-(`bbc.zip`, `rte.zip`, `tg4.zip`, `itv.zip`, `c4.zip`, `my5.zip`).
+Host binaries ship on two rolling channels (always the newest build — no version pin):
+
+| Channel | Tag | When to use |
+|---------|-----|-------------|
+| **Stable** | [`stable`](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/tag/stable) | Everyday installs |
+| **Beta** | [`beta`](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/tag/beta) | Try pre-releases (`vX.Y.Z-beta.N`) |
+
+Provider zips still come from **`modules-v*`** releases (`bbc.zip`, `rte.zip`, …).
+Pick **one** host binary block for your machine, then run `chmod +x streamd` on Linux/macOS.
+
+**Linux Intel / AMD 64-bit (stable)**
+
+```bash
+curl -fL -o streamd \
+  "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-amd64"
+chmod +x streamd
+```
+
+**Linux ARM 64-bit (stable)** — Raspberry Pi 4+, many cloud ARM VMs
+
+```bash
+curl -fL -o streamd \
+  "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-arm64"
+chmod +x streamd
+```
+
+**Beta channel (Linux Intel / AMD 64-bit pre-release)**
+
+```bash
+curl -fL -o streamd \
+  "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/beta/streamd-linux-amd64"
+chmod +x streamd
+```
+
+**Windows Intel / AMD 64-bit (stable, PowerShell)**
+
+```powershell
+Invoke-WebRequest -Uri "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-windows-amd64.exe" -OutFile streamd.exe
+```
+
+Other stable assets: `streamd-windows-arm64.exe`, `streamd-darwin-amd64`, `streamd-darwin-arm64`,
+`proxy-android-arm64`. For beta, swap `/download/stable/` → `/download/beta/` in any URL.
+Pinned install: swap `stable` / `beta` for a concrete tag such as `v0.1.5` or `v0.2.0-beta.1`.
 
 ```text
-Null-DRM/
-  drm.exe                 # or ./drm on Linux/macOS
-  bin/proxy-android-arm64 # optional; also embedded in release drm
-  modules/
+Streamd/
+  streamd.exe             # or ./streamd on Linux/macOS (drm.exe also shipped as a compat copy)
+  bin/proxy-android-arm64 # optional; also embedded in the release binary
+  modules/                # or upload zips in the streamd Modules page
     bbc/                  # unzip bbc.zip here
     rte/
     tg4/
@@ -81,7 +121,7 @@ Null-DRM/
   outputs/                # created on first run
 ```
 
-On first run, `drm` creates the install scaffold next to the exe.
+On first run, `streamd` creates the install scaffold next to the exe.
 
 ### 2️⃣ Prerequisites
 
@@ -99,14 +139,14 @@ Unzip into `modules//`. Edit **`module.yaml`** — fill sensitive fields o
 almost nothing extra.
 
 ```bash
-drm modules
-# or: drm --modules-dir D:\mods modules
+streamd modules
+# or: streamd --modules-dir D:\mods modules
 ```
 
 ### 4️⃣ Phone CA (once per device / CA)
 
 ```bash
-drm proxy install-ca --reinject
+streamd proxy install-ca --reinject
 adb shell am force-stop bbc.iplayer.android   # or the app you will capture
 ```
 
@@ -114,25 +154,25 @@ adb shell am force-stop bbc.iplayer.android   # or the app you will capture
 
 ```bash
 # BBC + NordVPN UK on the phone (transparent MITM; --channel auto-plays)
-drm capture --app bbc --channel bbcone --wait 120
-drm capture --app bbc --channel s4c --wait 120
+streamd capture --app bbc --channel bbcone --wait 120
+streamd capture --app bbc --channel s4c --wait 120
 
 # ITVX (UK VPN; Live tab autoplay)
-drm capture --app itv --channel itv1 --wait 90
+streamd capture --app itv --channel itv1 --wait 90
 
 # Channel 4 — one channel, or every Live channel
-drm capture --app c4 --channel channel4 --wait 90
-drm capture --app c4 --all --wait 90
+streamd capture --app c4 --channel channel4 --wait 90
+streamd capture --app c4 --all --wait 90
 
 # Grab every channel for any module
-drm capture --app itv --all --wait 90
+streamd capture --app itv --all --wait 90
 
 # RTE / TG4 (keys via --wvd when needed)
-drm capture --app rte --channel rteone --wvd data/device.wvd
-drm capture --app tg4 --channel ioi --wvd data/device.wvd
+streamd capture --app rte --channel rteone --wvd data/device.wvd
+streamd capture --app tg4 --channel ioi --wvd data/device.wvd
 
 # Catalog only (no phone) — TG4
-drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
+streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
 ```
 
 📁 Results land in `outputs///` (and `latest/`).
@@ -140,7 +180,7 @@ drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
 ### 6️⃣ Clean the phone after a run
 
 ```bash
-drm proxy reset
+streamd proxy reset
 ```
 
 Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fresh.
@@ -150,19 +190,19 @@ Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fr
 ## 🧾 Command cheat sheet
 
 ```text
-drm [--modules-dir DIR]  …
+streamd [--modules-dir DIR]  …
 
-drm modules
-drm capture  --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S]
-drm catalog  --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list]
-drm proxy    install-ca [--reinject] | reset [--keep-captures]
+streamd modules
+streamd capture  --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S]
+streamd catalog  --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list]
+streamd proxy    install-ca [--reinject] | reset [--keep-captures]
              | transparent --package PKG [--mitm-host HOST]
              | start | stop | push | discover | pull
-drm serve    [--bind …] [--data …] [--token …]
-drm agent    run|status|devices|enqueue|cancel [--config …]
+streamd serve    [--bind …] [--data …] [--token …]
+streamd agent    run|status|devices|enqueue|cancel [--config …]
 ```
 
-🌍 Global: `--modules-dir DIR` or `$DRM_MODULES_DIR` (default: `./modules`).
+🌍 Global: `--modules-dir DIR` or `$STREAMD_MODULES_DIR` (default: `./modules`).
 
 🎯 `--channel` implies interactive auto-play (provider-specific Live UI flow).
 
@@ -185,7 +225,7 @@ with `module.yaml` only (no `module-publish.yaml` inside the zip).
 ```bash
 git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official.git
 cd Null-DRM-Official
-go -C apps/cli build -o ../../bin/drm.exe .    # Windows
+go -C apps/cli build -o ../../bin/streamd.exe .    # Windows
 # Host release:  .\scripts\build-release.ps1 -Version v0.1.1
 # Modules:       .\scripts\build-modules-release.ps1 -Version modules-v0.1.1
 ```
@@ -196,7 +236,7 @@ More detail: [docs/quickstart.md](docs/quickstart.md) · [docs/architecture.md](
 
 ## 💚 Support the project
 
-If Null DRM saves you time, donations keep development going:
+If Streamd saves you time, donations keep development going:
 
 | Coin | Address |
 |------|---------|
diff --git a/apps/agent/README.md b/apps/agent/README.md
index 44fe6ae..2f70fe0 100644
--- a/apps/agent/README.md
+++ b/apps/agent/README.md
@@ -1,6 +1,6 @@
 # agent
 
-Always-on credentials refresher, hosted by the single binary as `drm agent`.
+Always-on credentials refresher, hosted by the single binary as `streamd agent`.
 
 ```text
 apps/agent/
@@ -26,30 +26,33 @@ expire by themselves if the agent dies.
 
 ```bash
 # terminal 1 — control plane
-./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd
+./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
 
 # terminal 2 — agent (operator API key from streamd Settings → API keys)
 export STREAMD_API_KEY=ndk_…
 # or legacy: export STREAMD_TOKEN=…
-./bin/drm agent run --config apps/agent/agent.yaml
+./bin/streamd agent run --config apps/agent/agent.yaml
 ```
 
 ```bash
-./bin/drm agent status
-./bin/drm agent devices
-./bin/drm agent enqueue --stream tg4-ioi --reason manual
-./bin/drm agent cancel --job 3
+./bin/streamd agent status
+./bin/streamd agent devices
+./bin/streamd agent enqueue --stream tg4-ioi --reason manual
+./bin/streamd agent cancel --job 3
 ```
 
-App modules are discovered under `modules/`. The agent drives whichever module a
-stream names and contains no provider logic.
+With `sync_modules: true` (default in the sample config), the agent **pulls**
+provider modules from the streamd Modules page into `/modules/`. You do
+not need a hand-maintained `modules/` tree on each agent host. The agent drives
+whichever module a stream names and contains no provider logic.
 
 ## Config
 
 `agent.yaml` — `streamd_url`, **`api_key`** (preferred) or `token` (alias), or
 env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
 `max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device),
-`wvd`, `user_agent`, `agent_id`, `data_dir`.
+`wvd`, `user_agent`, `agent_id`, `data_dir`, `sync_modules`, `modules_dir`
+(default `/modules`), `modules_sync_interval_sec`, `modules_prune`.
 
 Create the key in the streamd dashboard (role **operator**). The legacy shared
 `--token` / `STREAMD_TOKEN` still works but is meant for migration only.
@@ -59,10 +62,10 @@ Create the key in the streamd dashboard (role **operator**). The legacy shared
 ## Build
 
 ```bash
-go -C apps/cli build -o ../../bin/drm .
+go -C apps/cli build -o ../../bin/streamd .
 
 # cross-compile
-GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/drm .
+GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/streamd .
 ```
 
 **Full guide: [docs/streamd.md](../../docs/streamd.md)**
diff --git a/apps/agent/agent.yaml b/apps/agent/agent.yaml
index 0bf5550..0155cb7 100644
--- a/apps/agent/agent.yaml
+++ b/apps/agent/agent.yaml
@@ -14,10 +14,11 @@ workers: 1                     # concurrent ADB jobs
 max_attempts: 5
 capture_wait_sec: 180
 devices: []                    # empty = all adb "device" serials; never installs apps
-# Push local modules//module.yaml to streamd when missing or SHA differs.
+# Pull modules from the streamd panel into the local cache (package.zip + yaml).
 sync_modules: true
-# modules_dir: modules         # optional override (default: repo modules/)
+# modules_dir:                 # optional; default /modules
 # modules_sync_interval_sec: 300
+# modules_prune: false         # delete local modules absent from the panel
 # Required for key fetch. Relative paths resolve from the repo root
 # (DRM-Decryption/), not from C:\Users\admin\Programming\.
 wvd: 
diff --git a/apps/agent/agentcmd/agentcmd.go b/apps/agent/agentcmd/agentcmd.go
index a104e32..60ef0ba 100644
--- a/apps/agent/agentcmd/agentcmd.go
+++ b/apps/agent/agentcmd/agentcmd.go
@@ -12,14 +12,15 @@ import (
 	"syscall"
 	"text/tabwriter"
 
-	"drmdecryption/apps/agent/internal/client"
-	"drmdecryption/apps/agent/internal/config"
-	"drmdecryption/apps/agent/internal/device"
-	"drmdecryption/apps/agent/internal/modsync"
-	"drmdecryption/apps/agent/internal/poller"
-	"drmdecryption/apps/agent/internal/queue"
-	"drmdecryption/apps/agent/internal/worker"
-	"drmdecryption/apps/agent/internal/wsclient"
+	"streamd/apps/agent/internal/client"
+	"streamd/apps/agent/internal/config"
+	"streamd/apps/agent/internal/device"
+	"streamd/apps/agent/internal/modsync"
+	"streamd/apps/agent/internal/poller"
+	"streamd/apps/agent/internal/queue"
+	"streamd/apps/agent/internal/worker"
+	"streamd/apps/agent/internal/wsclient"
+	"streamd/modhost"
 )
 
 // Run dispatches an agent subcommand. args[0] is the subcommand name.
@@ -137,15 +138,25 @@ func runCmd(sub string, args []string) {
 	}
 	go p.Loop(stop)
 
+	// Prefer the panel-synced modules cache for capture jobs.
+	if cfg.ModulesDir != "" {
+		if err := modhost.SetModulesDir(cfg.ModulesDir); err != nil {
+			log.Fatalf("modules dir: %v", err)
+		}
+		log.Printf("modules dir %s", cfg.ModulesDir)
+	}
+
+	var ms *modsync.Syncer
 	if cfg.SyncModules {
-		ms := &modsync.Syncer{
+		ms = &modsync.Syncer{
 			API:        api,
 			ModulesDir: cfg.ModulesDir,
 			Interval:   cfg.ModulesSyncInterval(),
+			Prune:      cfg.ModulesPrune,
 			Log:        log.Default(),
 		}
 		go ms.Loop(stop)
-		log.Printf("modules sync enabled interval=%s", cfg.ModulesSyncInterval())
+		log.Printf("modules pull sync enabled interval=%s dir=%s", cfg.ModulesSyncInterval(), cfg.ModulesDir)
 	}
 
 	ws := wsclient.New(cfg.StreamdURL, cfg.Token, cfg.AgentID, log.Default())
@@ -171,6 +182,16 @@ func runCmd(sub string, args []string) {
 			}
 		}()
 	}
+	ws.OnModulesChanged = func(name, reason string) {
+		if ms == nil {
+			return
+		}
+		go func() {
+			if err := ms.Once(); err != nil {
+				log.Printf("modules sync after change to %s: %v", name, err)
+			}
+		}()
+	}
 	go ws.Loop()
 
 	for i := 0; i < cfg.Workers; i++ {
diff --git a/apps/agent/go.mod b/apps/agent/go.mod
index c3aa50f..c912a7b 100644
--- a/apps/agent/go.mod
+++ b/apps/agent/go.mod
@@ -1,12 +1,12 @@
-module drmdecryption/apps/agent
+module streamd/apps/agent
 
 go 1.25.0
 
 require (
-	drmdecryption v0.0.0
 	github.com/gorilla/websocket v1.5.3
 	gopkg.in/yaml.v3 v3.0.1
 	modernc.org/sqlite v1.34.5
+	streamd v0.0.0
 )
 
 require (
@@ -15,11 +15,10 @@ require (
 	github.com/mattn/go-isatty v0.0.20 // indirect
 	github.com/ncruces/go-strftime v0.1.9 // indirect
 	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
-	go.starlark.net v0.0.0-20260930220527-d7438c5a85ac // indirect
 	golang.org/x/sys v0.42.0 // indirect
 	modernc.org/libc v1.55.3 // indirect
 	modernc.org/mathutil v1.6.0 // indirect
 	modernc.org/memory v1.8.0 // indirect
 )
 
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/agent/go.sum b/apps/agent/go.sum
index 5ef9a1c..58f3755 100644
--- a/apps/agent/go.sum
+++ b/apps/agent/go.sum
@@ -1,7 +1,5 @@
 github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
 github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
-github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
-github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
 github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
 github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
 github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -14,8 +12,6 @@ github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdh
 github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
-go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
-go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
 golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
 golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -23,8 +19,6 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
 golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
 golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
 golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
-google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
-google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
diff --git a/apps/agent/internal/client/client.go b/apps/agent/internal/client/client.go
index 0ddaa5c..ba96c65 100644
--- a/apps/agent/internal/client/client.go
+++ b/apps/agent/internal/client/client.go
@@ -7,6 +7,7 @@ import (
 	"fmt"
 	"io"
 	"net/http"
+	"os"
 	"strings"
 	"time"
 )
@@ -180,9 +181,13 @@ func (c *Client) PostEvent(streamID int64, kind, message string, detail map[stri
 
 // ModuleInfo is one modules// entry from GET /api/modules.
 type ModuleInfo struct {
-	Name       string `json:"name"`
-	HasYAML    bool   `json:"has_yaml"`
-	YAMLSHA256 string `json:"yaml_sha256,omitempty"`
+	Name          string   `json:"name"`
+	HasYAML       bool     `json:"has_yaml"`
+	YAMLSHA256    string   `json:"yaml_sha256,omitempty"`
+	HasPackage    bool     `json:"has_package"`
+	PackageSHA256 string   `json:"package_sha256,omitempty"`
+	Arches        []string `json:"arches,omitempty"`
+	SizeBytes     int64    `json:"size_bytes,omitempty"`
 }
 
 func (c *Client) ListModules() ([]ModuleInfo, error) {
@@ -199,30 +204,64 @@ func (c *Client) ListModules() ([]ModuleInfo, error) {
 	return wrap.Modules, nil
 }
 
-// PutModuleYAML uploads raw module.yaml bytes for name (Content-Type text/yaml).
-func (c *Client) PutModuleYAML(name string, yamlBytes []byte) error {
-	req, err := http.NewRequest(http.MethodPut, c.BaseURL+"/api/modules/"+name, bytes.NewReader(yamlBytes))
+// GetModuleYAML downloads raw module.yaml bytes for name.
+func (c *Client) GetModuleYAML(name string) ([]byte, error) {
+	req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/yaml", nil)
+	if err != nil {
+		return nil, err
+	}
+	c.setHeaders(req)
+	resp, err := c.HTTP.Do(req)
+	if err != nil {
+		return nil, err
+	}
+	defer resp.Body.Close()
+	body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
+	if resp.StatusCode >= 300 {
+		return nil, c.statusError(http.MethodGet, "/api/modules/"+name+"/yaml", resp, body)
+	}
+	return body, nil
+}
+
+// DownloadModulePackage writes the module zip to destPath.
+func (c *Client) DownloadModulePackage(name, destPath string) error {
+	req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/package", nil)
 	if err != nil {
 		return err
 	}
-	req.Header.Set("Content-Type", "text/yaml")
 	c.setHeaders(req)
 	resp, err := c.HTTP.Do(req)
 	if err != nil {
 		return err
 	}
 	defer resp.Body.Close()
-	body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
 	if resp.StatusCode >= 300 {
-		return c.statusError(http.MethodPut, "/api/modules/"+name, resp, body)
+		body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+		return c.statusError(http.MethodGet, "/api/modules/"+name+"/package", resp, body)
 	}
-	return nil
+	tmp := destPath + ".partial"
+	f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
+	if err != nil {
+		return err
+	}
+	_, copyErr := io.Copy(f, io.LimitReader(resp.Body, 100<<20))
+	closeErr := f.Close()
+	if copyErr != nil {
+		_ = os.Remove(tmp)
+		return copyErr
+	}
+	if closeErr != nil {
+		_ = os.Remove(tmp)
+		return closeErr
+	}
+	_ = os.Remove(destPath)
+	return os.Rename(tmp, destPath)
 }
 
 func (c *Client) setHeaders(req *http.Request) {
 	ua := c.UserAgent
 	if ua == "" {
-		ua = "drm-agent/" + Version
+		ua = "streamd-agent/" + Version
 	}
 	req.Header.Set("User-Agent", ua)
 	if c.Token != "" {
diff --git a/apps/agent/internal/config/config.go b/apps/agent/internal/config/config.go
index 2239f5a..65e6c41 100644
--- a/apps/agent/internal/config/config.go
+++ b/apps/agent/internal/config/config.go
@@ -7,7 +7,7 @@ import (
 
 	"gopkg.in/yaml.v3"
 
-	"drmdecryption/repo"
+	"streamd/repo"
 )
 
 type Config struct {
@@ -27,10 +27,11 @@ type Config struct {
 	WVD             string   `yaml:"wvd"` // path to .wvd device file (required for key fetch)
 	UserAgent       string   `yaml:"user_agent"`
 	AgentID         string   `yaml:"agent_id"`
-	// SyncModules pushes local modules//module.yaml to streamd when missing/stale.
+	// SyncModules pulls modules from streamd into the local cache when missing/stale.
 	SyncModules            bool   `yaml:"sync_modules"`
-	ModulesDir             string `yaml:"modules_dir"` // empty = repo modules/
+	ModulesDir             string `yaml:"modules_dir"` // empty = /modules
 	ModulesSyncIntervalSec int    `yaml:"modules_sync_interval_sec"`
+	ModulesPrune           bool   `yaml:"modules_prune"` // remove local modules absent from panel
 	// OnDemandPriority lets a capture that streamd pushed — a viewer waking
 	// an on-demand stream, or a scheduled event about to start — jump ahead
 	// of routine refreshes in the queue.
@@ -124,7 +125,9 @@ func applyDefaults(cfg Config, root string) Config {
 	if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
 		cfg.WVD = filepath.Join(root, cfg.WVD)
 	}
-	if cfg.ModulesDir != "" && !filepath.IsAbs(cfg.ModulesDir) {
+	if cfg.ModulesDir == "" {
+		cfg.ModulesDir = filepath.Join(cfg.DataDir, "modules")
+	} else if !filepath.IsAbs(cfg.ModulesDir) {
 		cfg.ModulesDir = filepath.Join(root, cfg.ModulesDir)
 	}
 	if cfg.ModulesSyncIntervalSec <= 0 {
diff --git a/apps/agent/internal/device/pool.go b/apps/agent/internal/device/pool.go
index a9800b4..5d5eab1 100644
--- a/apps/agent/internal/device/pool.go
+++ b/apps/agent/internal/device/pool.go
@@ -4,7 +4,7 @@ import (
 	"fmt"
 	"sync"
 
-	"drmdecryption/adb"
+	"streamd/adb"
 )
 
 // Pool tracks free/busy ADB devices. Never installs apps.
diff --git a/apps/agent/internal/modsync/sync.go b/apps/agent/internal/modsync/sync.go
index 5563db0..5fa3c0d 100644
--- a/apps/agent/internal/modsync/sync.go
+++ b/apps/agent/internal/modsync/sync.go
@@ -1,26 +1,32 @@
-// Package modsync pushes local modules//module.yaml to streamd
-// when the remote copy is missing or the SHA-256 differs.
+// Package modsync pulls provider modules from streamd into a local cache.
+// The panel is the source of truth: agents download package.zip when the
+// package hash changes, and module.yaml alone when only YAML changed.
 package modsync
 
 import (
+	"archive/zip"
 	"crypto/sha256"
 	"encoding/hex"
+	"fmt"
+	"io"
 	"log"
 	"os"
 	"path/filepath"
+	"runtime"
 	"strings"
 	"time"
 
-	"drmdecryption/apps/agent/internal/client"
-	"drmdecryption/modhost"
-	"drmdecryption/repo"
+	"streamd/apps/agent/internal/client"
+	"streamd/modhost"
+	"streamd/repo"
 )
 
-// Syncer compares local module.yaml files to streamd and PUTs updates.
+// Syncer keeps the local modules cache aligned with streamd.
 type Syncer struct {
 	API        *client.Client
-	ModulesDir string // empty = modhost.ModulesDir(repo.Root())
+	ModulesDir string // empty = /modules resolved by caller, or modhost default
 	Interval   time.Duration
+	Prune      bool // remove local modules absent from the panel
 	Log        *log.Logger
 }
 
@@ -31,15 +37,10 @@ func (s *Syncer) modulesDir() string {
 	return modhost.ModulesDir(repo.Root())
 }
 
-// Once uploads every local module.yaml that is missing or stale on streamd.
+// Once pulls every remote module that is missing or stale locally.
 func (s *Syncer) Once() error {
 	dir := s.modulesDir()
-	ents, err := os.ReadDir(dir)
-	if err != nil {
-		if os.IsNotExist(err) {
-			s.logf("modules sync: no local dir %s", dir)
-			return nil
-		}
+	if err := os.MkdirAll(dir, 0o755); err != nil {
 		return err
 	}
 
@@ -47,42 +48,139 @@ func (s *Syncer) Once() error {
 	if err != nil {
 		return err
 	}
-	byName := make(map[string]client.ModuleInfo, len(remote))
+	seen := map[string]struct{}{}
 	for _, m := range remote {
-		byName[m.Name] = m
+		seen[m.Name] = struct{}{}
+		if err := s.syncOne(dir, m); err != nil {
+			s.logf("modules sync: %s: %v", m.Name, err)
+			continue
+		}
+	}
+	if s.Prune {
+		s.pruneLocal(dir, seen)
+	}
+	return nil
+}
+
+func (s *Syncer) syncOne(dir string, m client.ModuleInfo) error {
+	modDir := filepath.Join(dir, m.Name)
+	localPkg := localSHA(filepath.Join(modDir, "package.sha256"))
+	localYAML := ""
+	if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
+		sum := sha256.Sum256(raw)
+		localYAML = hex.EncodeToString(sum[:])
 	}
 
+	needPackage := m.HasPackage && (localPkg == "" || !strings.EqualFold(localPkg, m.PackageSHA256))
+	needYAML := m.HasYAML && (localYAML == "" || !strings.EqualFold(localYAML, m.YAMLSHA256))
+
+	if !needPackage && !needYAML {
+		return nil
+	}
+
+	if needPackage {
+		if !m.HasPackage {
+			return fmt.Errorf("panel has no package.zip")
+		}
+		if err := s.pullPackage(modDir, m); err != nil {
+			return err
+		}
+		s.logf("modules sync: pulled package %s", m.Name)
+		// Package extract includes yaml; refresh localYAML check.
+		if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
+			sum := sha256.Sum256(raw)
+			localYAML = hex.EncodeToString(sum[:])
+			needYAML = m.HasYAML && !strings.EqualFold(localYAML, m.YAMLSHA256)
+		} else {
+			needYAML = m.HasYAML
+		}
+	}
+
+	if needYAML {
+		raw, err := s.API.GetModuleYAML(m.Name)
+		if err != nil {
+			return err
+		}
+		if err := os.MkdirAll(modDir, 0o755); err != nil {
+			return err
+		}
+		if err := atomicWrite(filepath.Join(modDir, "module.yaml"), raw, 0o644); err != nil {
+			return err
+		}
+		s.logf("modules sync: updated yaml %s", m.Name)
+	}
+	return nil
+}
+
+func (s *Syncer) pullPackage(modDir string, m client.ModuleInfo) error {
+	if err := os.MkdirAll(modDir, 0o755); err != nil {
+		return err
+	}
+	zipPath := filepath.Join(modDir, "package.zip")
+	if err := s.API.DownloadModulePackage(m.Name, zipPath); err != nil {
+		return err
+	}
+	sum, err := fileSHA256(zipPath)
+	if err != nil {
+		return err
+	}
+	if m.PackageSHA256 != "" && !strings.EqualFold(sum, m.PackageSHA256) {
+		return fmt.Errorf("package sha mismatch: got %s want %s", sum, m.PackageSHA256)
+	}
+
+	extractDir := filepath.Join(modDir, ".extract-tmp")
+	_ = os.RemoveAll(extractDir)
+	if err := os.MkdirAll(extractDir, 0o755); err != nil {
+		return err
+	}
+	defer os.RemoveAll(extractDir)
+
+	if err := unzipSafe(zipPath, extractDir); err != nil {
+		return err
+	}
+	// Flatten a single top-level folder (bbc/...) into extractDir root.
+	if err := flattenSingleRoot(extractDir); err != nil {
+		return err
+	}
+	if err := promoteHostBinary(extractDir, m.Name); err != nil {
+		return err
+	}
+
+	// Move extracted contents into modDir (keep package.zip + sha sidecar).
+	ents, err := os.ReadDir(extractDir)
+	if err != nil {
+		return err
+	}
+	for _, e := range ents {
+		src := filepath.Join(extractDir, e.Name())
+		dst := filepath.Join(modDir, e.Name())
+		_ = os.RemoveAll(dst)
+		if err := os.Rename(src, dst); err != nil {
+			return err
+		}
+	}
+	return atomicWrite(filepath.Join(modDir, "package.sha256"), []byte(sum+"\n"), 0o644)
+}
+
+func (s *Syncer) pruneLocal(dir string, keep map[string]struct{}) {
+	ents, err := os.ReadDir(dir)
+	if err != nil {
+		return
+	}
 	for _, e := range ents {
 		if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
 			continue
 		}
-		name := e.Name()
-		yamlPath := filepath.Join(dir, name, "module.yaml")
-		raw, err := os.ReadFile(yamlPath)
-		if err != nil {
-			if os.IsNotExist(err) {
-				continue
-			}
-			s.logf("modules sync: read %s: %v", yamlPath, err)
+		if _, ok := keep[e.Name()]; ok {
 			continue
 		}
-		sum := sha256.Sum256(raw)
-		localSHA := hex.EncodeToString(sum[:])
-		rm, ok := byName[name]
-		if ok && rm.HasYAML && strings.EqualFold(rm.YAMLSHA256, localSHA) {
+		path := filepath.Join(dir, e.Name())
+		if err := os.RemoveAll(path); err != nil {
+			s.logf("modules sync: prune %s: %v", e.Name(), err)
 			continue
 		}
-		if err := s.API.PutModuleYAML(name, raw); err != nil {
-			s.logf("modules sync: PUT %s: %v", name, err)
-			continue
-		}
-		if !ok || !rm.HasYAML {
-			s.logf("modules sync: uploaded %s (new)", name)
-		} else {
-			s.logf("modules sync: updated %s", name)
-		}
+		s.logf("modules sync: pruned %s", e.Name())
 	}
-	return nil
 }
 
 // Loop runs Once immediately, then on Interval until stop closes.
@@ -119,3 +217,161 @@ func (s *Syncer) logf(format string, args ...any) {
 	}
 	log.Printf(format, args...)
 }
+
+func localSHA(path string) string {
+	b, err := os.ReadFile(path)
+	if err != nil {
+		return ""
+	}
+	return strings.TrimSpace(string(b))
+}
+
+func fileSHA256(path string) (string, error) {
+	f, err := os.Open(path)
+	if err != nil {
+		return "", err
+	}
+	defer f.Close()
+	h := sha256.New()
+	if _, err := io.Copy(h, f); err != nil {
+		return "", err
+	}
+	return hex.EncodeToString(h.Sum(nil)), nil
+}
+
+func atomicWrite(path string, data []byte, mode os.FileMode) error {
+	tmp := path + ".tmp"
+	if err := os.WriteFile(tmp, data, mode); err != nil {
+		return err
+	}
+	if err := os.Rename(tmp, path); err != nil {
+		_ = os.Remove(tmp)
+		return err
+	}
+	return nil
+}
+
+func unzipSafe(zipPath, destDir string) error {
+	r, err := zip.OpenReader(zipPath)
+	if err != nil {
+		return err
+	}
+	defer r.Close()
+	absDest, err := filepath.Abs(destDir)
+	if err != nil {
+		return err
+	}
+	for _, f := range r.File {
+		name := strings.ReplaceAll(f.Name, "\\", "/")
+		name = strings.TrimPrefix(name, "./")
+		if name == "" || strings.HasPrefix(name, "__MACOSX/") || strings.HasSuffix(name, ".DS_Store") {
+			continue
+		}
+		if strings.Contains(name, "..") {
+			return fmt.Errorf("zip slip: %s", f.Name)
+		}
+		target := filepath.Join(destDir, filepath.FromSlash(name))
+		absTarget, err := filepath.Abs(target)
+		if err != nil {
+			return err
+		}
+		rel, err := filepath.Rel(absDest, absTarget)
+		if err != nil || strings.HasPrefix(rel, "..") {
+			return fmt.Errorf("zip slip: %s", f.Name)
+		}
+		if f.FileInfo().IsDir() || strings.HasSuffix(name, "/") {
+			if err := os.MkdirAll(target, 0o755); err != nil {
+				return err
+			}
+			continue
+		}
+		if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+			return err
+		}
+		rc, err := f.Open()
+		if err != nil {
+			return err
+		}
+		mode := os.FileMode(0o644)
+		if f.Mode()&0o111 != 0 {
+			mode = 0o755
+		}
+		out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
+		if err != nil {
+			_ = rc.Close()
+			return err
+		}
+		_, copyErr := io.Copy(out, rc)
+		_ = out.Close()
+		_ = rc.Close()
+		if copyErr != nil {
+			return copyErr
+		}
+	}
+	return nil
+}
+
+func flattenSingleRoot(dir string) error {
+	ents, err := os.ReadDir(dir)
+	if err != nil {
+		return err
+	}
+	var dirs []os.DirEntry
+	var files []os.DirEntry
+	for _, e := range ents {
+		if strings.HasPrefix(e.Name(), ".") {
+			continue
+		}
+		if e.IsDir() {
+			dirs = append(dirs, e)
+		} else {
+			files = append(files, e)
+		}
+	}
+	if len(files) > 0 || len(dirs) != 1 {
+		return nil
+	}
+	root := filepath.Join(dir, dirs[0].Name())
+	inner, err := os.ReadDir(root)
+	if err != nil {
+		return err
+	}
+	for _, e := range inner {
+		src := filepath.Join(root, e.Name())
+		dst := filepath.Join(dir, e.Name())
+		if err := os.Rename(src, dst); err != nil {
+			return err
+		}
+	}
+	return os.RemoveAll(root)
+}
+
+func promoteHostBinary(modDir, name string) error {
+	want := name
+	if runtime.GOOS == "windows" {
+		want += ".exe"
+	}
+	dest := filepath.Join(modDir, ".bin", want)
+	if st, err := os.Stat(dest); err == nil && !st.IsDir() {
+		return nil
+	}
+	src := filepath.Join(modDir, ".bin", runtime.GOOS+"-"+runtime.GOARCH, want)
+	in, err := os.Open(src)
+	if err != nil {
+		return nil // soft: host arch may be missing
+	}
+	defer in.Close()
+	if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+		return err
+	}
+	out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
+	if err != nil {
+		return err
+	}
+	_, copyErr := io.Copy(out, in)
+	closeErr := out.Close()
+	if copyErr != nil {
+		return copyErr
+	}
+	return closeErr
+}
diff --git a/apps/agent/internal/modsync/sync_test.go b/apps/agent/internal/modsync/sync_test.go
new file mode 100644
index 0000000..0e5c3bd
--- /dev/null
+++ b/apps/agent/internal/modsync/sync_test.go
@@ -0,0 +1,154 @@
+package modsync
+
+import (
+	"archive/zip"
+	"bytes"
+	"crypto/sha256"
+	"encoding/hex"
+	"encoding/json"
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"path/filepath"
+	"runtime"
+	"strings"
+	"testing"
+
+	"streamd/apps/agent/internal/client"
+)
+
+func TestPullPackageThenYAMLOnly(t *testing.T) {
+	arch := runtime.GOOS + "-" + runtime.GOARCH
+	binName := "demo"
+	if runtime.GOOS == "windows" {
+		binName += ".exe"
+	}
+	zip1 := mustZip(t, map[string][]byte{
+		"module.yaml":                  []byte("package: a\n"),
+		".bin/" + arch + "/" + binName: []byte("bin-v1"),
+	})
+	sum1 := sha256.Sum256(zip1)
+	pkgSHA1 := hex.EncodeToString(sum1[:])
+	yaml1SHA := sha256Hex([]byte("package: a\n"))
+
+	zip2 := mustZip(t, map[string][]byte{
+		"module.yaml":                  []byte("package: a\n"),
+		".bin/" + arch + "/" + binName: []byte("bin-v2"),
+	})
+	sum2 := sha256.Sum256(zip2)
+	pkgSHA2 := hex.EncodeToString(sum2[:])
+
+	yamlEdited := []byte("package: a\nchannels: {}\n")
+	yamlEditedSHA := sha256Hex(yamlEdited)
+
+	state := struct {
+		pkg   []byte
+		pkgSHA string
+		yaml  []byte
+		yamlSHA string
+	}{pkg: zip1, pkgSHA: pkgSHA1, yaml: []byte("package: a\n"), yamlSHA: yaml1SHA}
+
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		switch {
+		case r.URL.Path == "/api/modules" && r.Method == http.MethodGet:
+			_ = json.NewEncoder(w).Encode(map[string]any{
+				"modules": []map[string]any{{
+					"name":            "demo",
+					"has_yaml":        true,
+					"yaml_sha256":     state.yamlSHA,
+					"has_package":     true,
+					"package_sha256":  state.pkgSHA,
+				}},
+			})
+		case r.URL.Path == "/api/modules/demo/package":
+			w.Header().Set("Content-Type", "application/zip")
+			_, _ = w.Write(state.pkg)
+		case r.URL.Path == "/api/modules/demo/yaml":
+			w.Header().Set("Content-Type", "text/yaml")
+			_, _ = w.Write(state.yaml)
+		default:
+			http.NotFound(w, r)
+		}
+	}))
+	defer srv.Close()
+
+	dir := t.TempDir()
+	api := &client.Client{BaseURL: srv.URL, HTTP: srv.Client()}
+	s := &Syncer{API: api, ModulesDir: dir}
+
+	if err := s.Once(); err != nil {
+		t.Fatalf("first sync: %v", err)
+	}
+	if _, err := os.Stat(filepath.Join(dir, "demo", "module.yaml")); err != nil {
+		t.Fatal(err)
+	}
+	promoted := filepath.Join(dir, "demo", ".bin", binName)
+	if b, err := os.ReadFile(promoted); err != nil || string(b) != "bin-v1" {
+		t.Fatalf("promoted binary: %v %q", err, b)
+	}
+
+	// YAML-only change on panel.
+	state.yaml = yamlEdited
+	state.yamlSHA = yamlEditedSHA
+	if err := s.Once(); err != nil {
+		t.Fatalf("yaml sync: %v", err)
+	}
+	raw, _ := os.ReadFile(filepath.Join(dir, "demo", "module.yaml"))
+	if !bytes.Equal(raw, yamlEdited) {
+		t.Fatalf("yaml not updated: %s", raw)
+	}
+	if b, _ := os.ReadFile(promoted); string(b) != "bin-v1" {
+		t.Fatalf("binary should be unchanged after yaml-only sync, got %q", b)
+	}
+
+	// Package change.
+	state.pkg = zip2
+	state.pkgSHA = pkgSHA2
+	state.yaml = []byte("package: a\n")
+	state.yamlSHA = yaml1SHA
+	if err := s.Once(); err != nil {
+		t.Fatalf("package sync: %v", err)
+	}
+	if b, _ := os.ReadFile(promoted); string(b) != "bin-v2" {
+		t.Fatalf("binary not updated: %q", b)
+	}
+}
+
+func mustZip(t *testing.T, files map[string][]byte) []byte {
+	t.Helper()
+	var buf bytes.Buffer
+	zw := zip.NewWriter(&buf)
+	for name, body := range files {
+		w, err := zw.Create(name)
+		if err != nil {
+			t.Fatal(err)
+		}
+		if _, err := w.Write(body); err != nil {
+			t.Fatal(err)
+		}
+	}
+	if err := zw.Close(); err != nil {
+		t.Fatal(err)
+	}
+	return buf.Bytes()
+}
+
+func sha256Hex(b []byte) string {
+	sum := sha256.Sum256(b)
+	return hex.EncodeToString(sum[:])
+}
+
+func TestUnzipSlip(t *testing.T) {
+	dir := t.TempDir()
+	var buf bytes.Buffer
+	zw := zip.NewWriter(&buf)
+	w, _ := zw.Create("../evil")
+	_, _ = w.Write([]byte("x"))
+	_ = zw.Close()
+	zipPath := filepath.Join(dir, "bad.zip")
+	_ = os.WriteFile(zipPath, buf.Bytes(), 0o644)
+	err := unzipSafe(zipPath, filepath.Join(dir, "out"))
+	if err == nil || !strings.Contains(err.Error(), "slip") {
+		t.Fatalf("want zip slip error, got %v", err)
+	}
+}
diff --git a/apps/agent/internal/poller/poller.go b/apps/agent/internal/poller/poller.go
index 2014717..5195e87 100644
--- a/apps/agent/internal/poller/poller.go
+++ b/apps/agent/internal/poller/poller.go
@@ -6,8 +6,8 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/apps/agent/internal/client"
-	"drmdecryption/apps/agent/internal/queue"
+	"streamd/apps/agent/internal/client"
+	"streamd/apps/agent/internal/queue"
 )
 
 type Poller struct {
diff --git a/apps/agent/internal/worker/worker.go b/apps/agent/internal/worker/worker.go
index ea009f4..517ffb7 100644
--- a/apps/agent/internal/worker/worker.go
+++ b/apps/agent/internal/worker/worker.go
@@ -7,14 +7,14 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/modhost"
-	"drmdecryption/phonecap"
-	"drmdecryption/repo"
+	"streamd/modhost"
+	"streamd/phonecap"
+	"streamd/repo"
 
-	"drmdecryption/apps/agent/internal/client"
-	"drmdecryption/apps/agent/internal/device"
-	"drmdecryption/apps/agent/internal/poller"
-	"drmdecryption/apps/agent/internal/queue"
+	"streamd/apps/agent/internal/client"
+	"streamd/apps/agent/internal/device"
+	"streamd/apps/agent/internal/poller"
+	"streamd/apps/agent/internal/queue"
 )
 
 type Worker struct {
diff --git a/apps/agent/internal/wsclient/wsclient.go b/apps/agent/internal/wsclient/wsclient.go
index 05400c7..b37ac6c 100644
--- a/apps/agent/internal/wsclient/wsclient.go
+++ b/apps/agent/internal/wsclient/wsclient.go
@@ -11,7 +11,7 @@ import (
 
 	"github.com/gorilla/websocket"
 
-	"drmdecryption/apps/agent/internal/client"
+	"streamd/apps/agent/internal/client"
 )
 
 // Message is one push from streamd.
@@ -42,6 +42,9 @@ type Client struct {
 	// OnStreamChanged is called when a stream was edited, so the agent can
 	// re-poll instead of waiting out its interval.
 	OnStreamChanged func(name, reason string)
+	// OnModulesChanged is called when the panel uploaded/edited/deleted a
+	// module, so the agent can pull without waiting for the sync interval.
+	OnModulesChanged func(name, reason string)
 
 	stop chan struct{}
 }
@@ -111,7 +114,7 @@ func (c *Client) session() error {
 	if c.AgentID != "" {
 		hdr.Set("X-Agent-ID", c.AgentID)
 	}
-	hdr.Set("User-Agent", "drm-agent/"+client.Version)
+	hdr.Set("User-Agent", "streamd-agent/"+client.Version)
 	dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
 	conn, resp, err := dialer.Dial(u.String(), hdr)
 	if err != nil {
@@ -190,6 +193,11 @@ func (c *Client) handle(msg Message) {
 		if c.OnStreamChanged != nil {
 			c.OnStreamChanged(msg.StreamName, msg.Reason)
 		}
+	case "modules_changed":
+		c.Log.Printf("ws: modules changed module=%s reason=%s", msg.StreamName, msg.Reason)
+		if c.OnModulesChanged != nil {
+			c.OnModulesChanged(msg.StreamName, msg.Reason)
+		}
 	}
 }
 
diff --git a/apps/capture/README.md b/apps/capture/README.md
index 4274d50..f34b0f7 100644
--- a/apps/capture/README.md
+++ b/apps/capture/README.md
@@ -1,6 +1,6 @@
 # capture
 
-One-shot phone MITM capture, hosted by the single binary as `drm capture`.
+One-shot phone MITM capture, hosted by the single binary as `streamd capture`.
 
 ```text
 apps/capture/
@@ -8,17 +8,17 @@ apps/capture/
 ```
 
 ```bash
-./bin/drm capture                                              # passive: play anything
-./bin/drm capture --app rte                                    # launch, navigate by hand
-./bin/drm capture --app rte --channel rteone --auto-play \
+./bin/streamd capture                                              # passive: play anything
+./bin/streamd capture --app rte                                    # launch, navigate by hand
+./bin/streamd capture --app rte --channel rteone --auto-play \
                   --wvd data/device.wvd                        # fully automated
 ```
 
 Writes `outputs///` plus `latest/`. App modules are compiled in, so
-there is no modules directory to point at; `drm modules` lists what is available.
+there is no modules directory to point at; `streamd modules` lists what is available.
 
 **Full guide: [docs/capture.md](../../docs/capture.md)** — device setup, flags,
 discovering a new app, and troubleshooting.
 
 The catalog lookup that used to be a separate `tg4info` binary is now the
-provider-agnostic `drm catalog` (`apps/cli/catalogcmd`).
+provider-agnostic `streamd catalog` (`apps/cli/catalogcmd`).
diff --git a/apps/capture/capturecmd/capturecmd.go b/apps/capture/capturecmd/capturecmd.go
index 8c93c66..c76e01d 100644
--- a/apps/capture/capturecmd/capturecmd.go
+++ b/apps/capture/capturecmd/capturecmd.go
@@ -12,16 +12,16 @@ import (
 	"time"
 	"unicode"
 
-	"drmdecryption/adb"
-	"drmdecryption/app"
-	"drmdecryption/modcfg"
-	"drmdecryption/modhost"
-	"drmdecryption/phonecap"
-	"drmdecryption/repo"
+	"streamd/adb"
+	"streamd/app"
+	"streamd/modcfg"
+	"streamd/modhost"
+	"streamd/phonecap"
+	"streamd/repo"
 )
 
 // Run performs one capture. Providers live under modules// and are built
-// and executed by modhost — they are not linked into drm.exe.
+// and executed by modhost — they are not linked into streamd.
 func Run(args []string) error {
 	args = normalizeArgs(args)
 
diff --git a/apps/capture/go.mod b/apps/capture/go.mod
index af6edc7..e575d3d 100644
--- a/apps/capture/go.mod
+++ b/apps/capture/go.mod
@@ -1,13 +1,9 @@
-module drmdecryption/apps/capture
+module streamd/apps/capture
 
 go 1.25.0
 
-require drmdecryption v0.0.0
+require streamd v0.0.0
 
-require (
-	go.starlark.net v0.0.0-20260930220527-d7438c5a85ac // indirect
-	golang.org/x/sys v0.42.0 // indirect
-	gopkg.in/yaml.v3 v3.0.1 // indirect
-)
+require gopkg.in/yaml.v3 v3.0.1 // indirect
 
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/capture/go.sum b/apps/capture/go.sum
index 908fb03..a62c313 100644
--- a/apps/capture/go.sum
+++ b/apps/capture/go.sum
@@ -1,11 +1,3 @@
-github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
-github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
-go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
-go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
-golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
-golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
-google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
-google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
diff --git a/apps/cli/capture_args_test.go b/apps/cli/capture_args_test.go
index ef8a084..c533f80 100644
--- a/apps/cli/capture_args_test.go
+++ b/apps/cli/capture_args_test.go
@@ -4,7 +4,7 @@ import (
 	"strings"
 	"testing"
 
-	"drmdecryption/apps/capture/capturecmd"
+	"streamd/apps/capture/capturecmd"
 )
 
 func TestCaptureRejectsChannelAsApp(t *testing.T) {
diff --git a/apps/cli/catalogcmd/catalogcmd.go b/apps/cli/catalogcmd/catalogcmd.go
index b45ba90..4f5a782 100644
--- a/apps/cli/catalogcmd/catalogcmd.go
+++ b/apps/cli/catalogcmd/catalogcmd.go
@@ -11,9 +11,9 @@ import (
 	"sort"
 	"strings"
 
-	"drmdecryption/modhost"
-	"drmdecryption/repo"
-	"drmdecryption/session"
+	"streamd/modhost"
+	"streamd/repo"
+	"streamd/session"
 )
 
 // Run performs a catalog lookup for one channel.
diff --git a/apps/cli/go.mod b/apps/cli/go.mod
index 441ed1e..a3df87f 100644
--- a/apps/cli/go.mod
+++ b/apps/cli/go.mod
@@ -1,13 +1,13 @@
-module drmdecryption/apps/cli
+module streamd/apps/cli
 
 go 1.25.0
 
 require (
-	drmdecryption v0.0.0
-	drmdecryption/apps/agent v0.0.0
-	drmdecryption/apps/capture v0.0.0
-	drmdecryption/apps/proxy v0.0.0
-	drmdecryption/apps/streamd v0.0.0
+	streamd v0.0.0
+	streamd/apps/agent v0.0.0
+	streamd/apps/capture v0.0.0
+	streamd/apps/proxy v0.0.0
+	streamd/apps/streamd v0.0.0
 )
 
 require (
@@ -26,9 +26,9 @@ require (
 )
 
 replace (
-	drmdecryption => ../pkg
-	drmdecryption/apps/agent => ../agent
-	drmdecryption/apps/capture => ../capture
-	drmdecryption/apps/proxy => ../proxy
-	drmdecryption/apps/streamd => ../streamd
+	streamd => ../pkg
+	streamd/apps/agent => ../agent
+	streamd/apps/capture => ../capture
+	streamd/apps/proxy => ../proxy
+	streamd/apps/streamd => ../streamd
 )
diff --git a/apps/cli/main.go b/apps/cli/main.go
index 3db10b7..37d6475 100644
--- a/apps/cli/main.go
+++ b/apps/cli/main.go
@@ -1,7 +1,8 @@
-// Command drm is the single entry point for the toolchain: phone capture,
+// Command streamd is the single entry point for the toolchain: phone capture,
 // catalog lookups, the always-on agent, the streamd control plane and the
 // on-device MITM. Providers live under modules// and are discovered,
 // built, and executed by the host — they are not linked into this binary.
+// A drm.exe copy of this binary is still shipped for one release as a compat alias.
 package main
 
 import (
@@ -13,14 +14,14 @@ import (
 	"os"
 	"strings"
 
-	"drmdecryption/apps/agent/agentcmd"
-	"drmdecryption/apps/capture/capturecmd"
-	"drmdecryption/apps/cli/catalogcmd"
-	"drmdecryption/apps/cli/modulescmd"
-	"drmdecryption/apps/proxy/proxyctlcmd"
-	"drmdecryption/apps/streamd/servecmd"
-	"drmdecryption/bootstrap"
-	"drmdecryption/modhost"
+	"streamd/apps/agent/agentcmd"
+	"streamd/apps/capture/capturecmd"
+	"streamd/apps/cli/catalogcmd"
+	"streamd/apps/cli/modulescmd"
+	"streamd/apps/proxy/proxyctlcmd"
+	"streamd/apps/streamd/servecmd"
+	"streamd/bootstrap"
+	"streamd/modhost"
 )
 
 func main() {
@@ -39,12 +40,12 @@ func main() {
 			os.Exit(1)
 		}
 	} else if err := modhost.ApplyEnvModulesDir(); err != nil {
-		fmt.Fprintln(os.Stderr, "[!] DRM_MODULES_DIR:", err)
+		fmt.Fprintln(os.Stderr, "[!] STREAMD_MODULES_DIR / DRM_MODULES_DIR:", err)
 		os.Exit(1)
 	}
 
 	// Materialise apps/, bin/, modules/, outputs/, … next to this exe when
-	// missing so a lone downloaded drm.exe becomes a GitHub-like install tree.
+	// missing so a lone downloaded streamd.exe becomes a usable install tree.
 	if cmd != "help" && cmd != "-h" && cmd != "--help" {
 		if err := bootstrap.EnsureAndLogFor(cmd); err != nil {
 			fmt.Fprintln(os.Stderr, "[!] bootstrap:", err)
@@ -102,23 +103,25 @@ func peelGlobalFlags(args []string) (modulesDir string, rest []string) {
 }
 
 func usage() {
-	fmt.Fprint(os.Stderr, `drm — DRM capture / restream toolchain
+	fmt.Fprint(os.Stderr, `streamd — capture / restream toolchain
 
 Usage:
-  drm [--modules-dir DIR] modules
-  drm [--modules-dir DIR] capture  --app NAME [--channel ID | --all] [--wvd PATH]
-  drm [--modules-dir DIR] catalog  --app NAME --channel ID [--keys] [--json]
-  drm agent    run|status|devices|enqueue|cancel [--config …]
-  drm serve    [--bind …] [--data …] [--token …]
-  drm proxy    build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
+  streamd [--modules-dir DIR] modules
+  streamd [--modules-dir DIR] capture  --app NAME [--channel ID | --all] [--wvd PATH]
+  streamd [--modules-dir DIR] catalog  --app NAME --channel ID [--keys] [--json]
+  streamd agent    run|status|devices|enqueue|cancel [--config …]
+  streamd serve    [--bind …] [--data …] [--token …]
+  streamd proxy    build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
 
 Global flags:
-  --modules-dir DIR   provider folder (default: /modules, or $DRM_MODULES_DIR)
+  --modules-dir DIR   provider folder (default: /modules, or $STREAMD_MODULES_DIR)
 
 Providers live under modules// (Go source + module-publish.yaml).
 Local module.yaml holds secrets and is never published; release zips ship
 module-publish.yaml renamed to module.yaml. The host builds modules on demand.
 
+A drm binary may still be shipped as an identical compatibility copy.
+
 Run any subcommand with --help for its own flags.
 `)
 }
diff --git a/apps/cli/modulescmd/modulescmd.go b/apps/cli/modulescmd/modulescmd.go
index 4f7ee55..5cf2a23 100644
--- a/apps/cli/modulescmd/modulescmd.go
+++ b/apps/cli/modulescmd/modulescmd.go
@@ -9,8 +9,8 @@ import (
 	"sort"
 	"text/tabwriter"
 
-	"drmdecryption/modhost"
-	"drmdecryption/repo"
+	"streamd/modhost"
+	"streamd/repo"
 )
 
 // Run prints external modules under modules/.
diff --git a/apps/modules/README.md b/apps/modules/README.md
index e518fd5..87532fc 100644
--- a/apps/modules/README.md
+++ b/apps/modules/README.md
@@ -4,8 +4,8 @@ One Go package per streaming app. Every module is **compiled into the binary** 
 there is no plugin loading and no modules directory to point a binary at.
 
 ```text
-apps/modules/                 Go module: drmdecryption/modules
-  go.mod                      replace drmdecryption => ../pkg
+apps/modules/                 Go module: streamd/modules
+  go.mod                      replace streamd => ../pkg
   all/all.go                  blank-imports every module — the link point
   provider/                   shared base: values loading, channel aliases, durations
   /*.go                 TRACKED: the app's logic
@@ -37,7 +37,7 @@ Values arrive by **flag → environment → module.yaml → Go default**, and on
 mechanical defaults (timeouts, DASH timescales, card geometry) live in code:
 
 ```bash
-./bin/drm catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
+./bin/streamd catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
 export TG4_POLICY_KEY=BCpkAD...        # same thing
 ```
 
@@ -46,9 +46,9 @@ export TG4_POLICY_KEY=BCpkAD...        # same thing
 1. Create `apps/modules/myapp/` with `config.go` and `myapp.go`
 2. Register from `init()`: `appreg.Register(Name, New)` and
    `appreg.RegisterFlags(bindFlags)`
-3. Add one line to `all/all.go`: `_ "drmdecryption/modules/myapp"`
+3. Add one line to `all/all.go`: `_ "streamd/modules/myapp"`
 4. Create `apps/modules/myapp/module.yaml` with your values
-5. `go -C apps/cli build -o ../../bin/drm .` then `./bin/drm modules`
+5. `go -C apps/cli build -o ../../bin/streamd .` then `./bin/streamd modules`
 
 **Authoring guide: [docs/modules.md](../../docs/modules.md)** — the full contract,
 `uiflow` reference, optional capability interfaces, and a checklist.
@@ -59,9 +59,9 @@ export TG4_POLICY_KEY=BCpkAD...        # same thing
 ## Run
 
 ```bash
-./bin/drm modules                                        # what is compiled in
-./bin/drm capture --app rte --channel rteone --auto-play
-./bin/drm capture --app bbc --channel bbcone   # transparent MITM; play on phone; MPD only
-./bin/drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
-./bin/drm agent run --config apps/agent/agent.yaml
+./bin/streamd modules                                        # what is compiled in
+./bin/streamd capture --app rte --channel rteone --auto-play
+./bin/streamd capture --app bbc --channel bbcone   # transparent MITM; play on phone; MPD only
+./bin/streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
+./bin/streamd agent run --config apps/agent/agent.yaml
 ```
diff --git a/apps/modules/all/all.go b/apps/modules/all/all.go
index 33b94a3..9771be3 100644
--- a/apps/modules/all/all.go
+++ b/apps/modules/all/all.go
@@ -4,7 +4,7 @@
 package all
 
 import (
-	_ "drmdecryption/modules/bbc"
-	_ "drmdecryption/modules/rte"
-	_ "drmdecryption/modules/tg4"
+	_ "streamd/modules/bbc"
+	_ "streamd/modules/rte"
+	_ "streamd/modules/tg4"
 )
diff --git a/apps/modules/all/all_test.go b/apps/modules/all/all_test.go
index 9639faa..f7d2031 100644
--- a/apps/modules/all/all_test.go
+++ b/apps/modules/all/all_test.go
@@ -4,7 +4,7 @@ import (
 	"flag"
 	"testing"
 
-	appreg "drmdecryption/app"
+	appreg "streamd/app"
 )
 
 // Every module must be constructible with no module.yaml present — a fresh clone
diff --git a/apps/modules/bbc/bbc.go b/apps/modules/bbc/bbc.go
index b20424c..50941de 100644
--- a/apps/modules/bbc/bbc.go
+++ b/apps/modules/bbc/bbc.go
@@ -9,12 +9,12 @@ import (
 	"os"
 	"time"
 
-	"drmdecryption/adb"
-	appreg "drmdecryption/app"
-	"drmdecryption/capture"
-	"drmdecryption/modules/provider"
-	"drmdecryption/mpd"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	appreg "streamd/app"
+	"streamd/capture"
+	"streamd/modules/provider"
+	"streamd/mpd"
+	"streamd/uiflow"
 )
 
 func init() {
diff --git a/apps/modules/bbc/bbc_test.go b/apps/modules/bbc/bbc_test.go
index 1ea2bca..fff5490 100644
--- a/apps/modules/bbc/bbc_test.go
+++ b/apps/modules/bbc/bbc_test.go
@@ -3,11 +3,11 @@ package bbc
 import (
 	"testing"
 
-	appreg "drmdecryption/app"
-	"drmdecryption/capture"
-	"drmdecryption/modcfg"
-	"drmdecryption/modules/provider"
-	"drmdecryption/mpd"
+	appreg "streamd/app"
+	"streamd/capture"
+	"streamd/modcfg"
+	"streamd/modules/provider"
+	"streamd/mpd"
 )
 
 var (
diff --git a/apps/modules/bbc/config.go b/apps/modules/bbc/config.go
index 969ad7d..321ad85 100644
--- a/apps/modules/bbc/config.go
+++ b/apps/modules/bbc/config.go
@@ -4,8 +4,8 @@ import (
 	"regexp"
 	"time"
 
-	"drmdecryption/modcfg"
-	"drmdecryption/modules/provider"
+	"streamd/modcfg"
+	"streamd/modules/provider"
 )
 
 // Name is the module id (--app bbc).
diff --git a/apps/modules/bbc/steps.go b/apps/modules/bbc/steps.go
index b0bdb15..df0e1ee 100644
--- a/apps/modules/bbc/steps.go
+++ b/apps/modules/bbc/steps.go
@@ -6,8 +6,8 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	"streamd/uiflow"
 )
 
 // openExplorePage taps the Explore bottom-nav tab and waits for the channel rail.
diff --git a/apps/modules/c4/c4.go b/apps/modules/c4/c4.go
index 4757ef6..f6cea1b 100644
--- a/apps/modules/c4/c4.go
+++ b/apps/modules/c4/c4.go
@@ -9,12 +9,12 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
-	appreg "drmdecryption/app"
-	"drmdecryption/capture"
-	"drmdecryption/modules/provider"
-	"drmdecryption/mpd"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	appreg "streamd/app"
+	"streamd/capture"
+	"streamd/modules/provider"
+	"streamd/mpd"
+	"streamd/uiflow"
 )
 
 func init() {
diff --git a/apps/modules/c4/config.go b/apps/modules/c4/config.go
index fd8d192..8fc767b 100644
--- a/apps/modules/c4/config.go
+++ b/apps/modules/c4/config.go
@@ -3,8 +3,8 @@ package c4
 import (
 	"time"
 
-	"drmdecryption/modcfg"
-	"drmdecryption/modules/provider"
+	"streamd/modcfg"
+	"streamd/modules/provider"
 )
 
 // Name is the module id (--app c4).
diff --git a/apps/modules/c4/steps.go b/apps/modules/c4/steps.go
index fd60461..698016c 100644
--- a/apps/modules/c4/steps.go
+++ b/apps/modules/c4/steps.go
@@ -6,8 +6,8 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	"streamd/uiflow"
 )
 
 func (a *App) openLiveTab(c *adb.Client) error {
diff --git a/apps/modules/go.mod b/apps/modules/go.mod
index 6635e2a..1036caa 100644
--- a/apps/modules/go.mod
+++ b/apps/modules/go.mod
@@ -1,9 +1,9 @@
-module drmdecryption/modules
+module streamd/modules
 
 go 1.25.0
 
-require drmdecryption v0.0.0
+require streamd v0.0.0
 
 require gopkg.in/yaml.v3 v3.0.1 // indirect
 
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/modules/itv/config.go b/apps/modules/itv/config.go
index dde2df8..e2f7d96 100644
--- a/apps/modules/itv/config.go
+++ b/apps/modules/itv/config.go
@@ -3,8 +3,8 @@ package itv
 import (
 	"time"
 
-	"drmdecryption/modcfg"
-	"drmdecryption/modules/provider"
+	"streamd/modcfg"
+	"streamd/modules/provider"
 )
 
 // Name is the module id (--app itv).
diff --git a/apps/modules/itv/itv.go b/apps/modules/itv/itv.go
index 5a34212..bc89ffd 100644
--- a/apps/modules/itv/itv.go
+++ b/apps/modules/itv/itv.go
@@ -10,12 +10,12 @@ import (
 	"os"
 	"time"
 
-	"drmdecryption/adb"
-	appreg "drmdecryption/app"
-	"drmdecryption/capture"
-	"drmdecryption/modules/provider"
-	"drmdecryption/mpd"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	appreg "streamd/app"
+	"streamd/capture"
+	"streamd/modules/provider"
+	"streamd/mpd"
+	"streamd/uiflow"
 )
 
 func init() {
diff --git a/apps/modules/itv/steps.go b/apps/modules/itv/steps.go
index 10cde09..4ac6ac6 100644
--- a/apps/modules/itv/steps.go
+++ b/apps/modules/itv/steps.go
@@ -6,8 +6,8 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	"streamd/uiflow"
 )
 
 // openLiveTab taps bottom-nav Live. Accessibility desc is obfuscated as "Lyve";
diff --git a/apps/modules/my5/config.go b/apps/modules/my5/config.go
index 9b7e6e8..8720d4f 100644
--- a/apps/modules/my5/config.go
+++ b/apps/modules/my5/config.go
@@ -3,8 +3,8 @@ package my5
 import (
 	"time"
 
-	"drmdecryption/modcfg"
-	"drmdecryption/modules/provider"
+	"streamd/modcfg"
+	"streamd/modules/provider"
 )
 
 // Name is the module id (--app my5).
diff --git a/apps/modules/my5/my5.go b/apps/modules/my5/my5.go
index 94c46de..ebd103b 100644
--- a/apps/modules/my5/my5.go
+++ b/apps/modules/my5/my5.go
@@ -9,12 +9,12 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
-	appreg "drmdecryption/app"
-	"drmdecryption/capture"
-	"drmdecryption/modules/provider"
-	"drmdecryption/mpd"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	appreg "streamd/app"
+	"streamd/capture"
+	"streamd/modules/provider"
+	"streamd/mpd"
+	"streamd/uiflow"
 )
 
 func init() {
diff --git a/apps/modules/my5/steps.go b/apps/modules/my5/steps.go
index 9c6c996..f9fd4f7 100644
--- a/apps/modules/my5/steps.go
+++ b/apps/modules/my5/steps.go
@@ -6,8 +6,8 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	"streamd/uiflow"
 )
 
 func (a *App) appFocused(c *adb.Client) bool {
diff --git a/apps/modules/provider/provider.go b/apps/modules/provider/provider.go
index b6e96e2..1b0f919 100644
--- a/apps/modules/provider/provider.go
+++ b/apps/modules/provider/provider.go
@@ -10,10 +10,10 @@ import (
 	"sort"
 	"strings"
 
-	"drmdecryption/capture"
-	"drmdecryption/modcfg"
-	"drmdecryption/phonecap"
-	"drmdecryption/repo"
+	"streamd/capture"
+	"streamd/modcfg"
+	"streamd/phonecap"
+	"streamd/repo"
 )
 
 // Common is the part of a module.yaml that every module has. Modules embed it in
@@ -57,7 +57,7 @@ func (b *Base) ConfigPath() string { return b.cfg.Path }
 func (b *Base) ConfigLoaded() bool { return b.cfg.Loaded }
 
 // ProxyBin resolves the on-device MITM binary. Empty means “auto” (caller uses
-// proxy.FindLocalBin — next to drm.exe, then repo bin/).
+// proxy.FindLocalBin — next to streamd, then repo bin/).
 func (b *Base) ProxyBin() string {
 	if b.common.ProxyBin != "" {
 		return modcfg.Resolve(b.common.ProxyBin)
diff --git a/apps/modules/rte/config.go b/apps/modules/rte/config.go
index 6eb03ce..f01d3db 100644
--- a/apps/modules/rte/config.go
+++ b/apps/modules/rte/config.go
@@ -3,9 +3,9 @@ package rte
 import (
 	"time"
 
-	"drmdecryption/modcfg"
-	"drmdecryption/modules/provider"
-	"drmdecryption/mpd"
+	"streamd/modcfg"
+	"streamd/modules/provider"
+	"streamd/mpd"
 )
 
 // Name is the module id (--app rte).
diff --git a/apps/modules/rte/live_test.go b/apps/modules/rte/live_test.go
index b89e50a..329a1b1 100644
--- a/apps/modules/rte/live_test.go
+++ b/apps/modules/rte/live_test.go
@@ -12,7 +12,7 @@ import (
 	"strings"
 	"testing"
 
-	"drmdecryption/mpd"
+	"streamd/mpd"
 )
 
 // The rewriter must publish a usable manifest from the KID alone — this is the
diff --git a/apps/modules/rte/mpd.go b/apps/modules/rte/mpd.go
index 2d5a31b..6c91a05 100644
--- a/apps/modules/rte/mpd.go
+++ b/apps/modules/rte/mpd.go
@@ -6,7 +6,7 @@ import (
 	"strings"
 	"sync"
 
-	"drmdecryption/mpd"
+	"streamd/mpd"
 )
 
 func init() {
diff --git a/apps/modules/rte/rte.go b/apps/modules/rte/rte.go
index 2f279ff..ec8ec12 100644
--- a/apps/modules/rte/rte.go
+++ b/apps/modules/rte/rte.go
@@ -9,12 +9,12 @@ import (
 	"fmt"
 	"time"
 
-	"drmdecryption/adb"
-	appreg "drmdecryption/app"
-	"drmdecryption/capture"
-	"drmdecryption/modules/provider"
-	"drmdecryption/mpd"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	appreg "streamd/app"
+	"streamd/capture"
+	"streamd/modules/provider"
+	"streamd/mpd"
+	"streamd/uiflow"
 )
 
 func init() {
diff --git a/apps/modules/rte/rte_test.go b/apps/modules/rte/rte_test.go
index eb08cc1..faf3cfd 100644
--- a/apps/modules/rte/rte_test.go
+++ b/apps/modules/rte/rte_test.go
@@ -4,8 +4,8 @@ import (
 	"strings"
 	"testing"
 
-	appreg "drmdecryption/app"
-	"drmdecryption/mpd"
+	appreg "streamd/app"
+	"streamd/mpd"
 )
 
 // Compile-time proof the plugin satisfies every interface the host expects.
diff --git a/apps/modules/rte/steps.go b/apps/modules/rte/steps.go
index 32e1360..584e2d1 100644
--- a/apps/modules/rte/steps.go
+++ b/apps/modules/rte/steps.go
@@ -5,8 +5,8 @@ import (
 	"regexp"
 	"time"
 
-	"drmdecryption/adb"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	"streamd/uiflow"
 )
 
 // openLiveTab taps the bottom-nav Live tab and waits for channel chips.
diff --git a/apps/modules/tg4/catalog.go b/apps/modules/tg4/catalog.go
index a80501d..5afaada 100644
--- a/apps/modules/tg4/catalog.go
+++ b/apps/modules/tg4/catalog.go
@@ -6,9 +6,9 @@ import (
 	"net/http"
 	"strings"
 
-	appreg "drmdecryption/app"
-	"drmdecryption/brightcove"
-	"drmdecryption/session"
+	appreg "streamd/app"
+	"streamd/brightcove"
+	"streamd/session"
 )
 
 // playbackConfig is the app's remote config blob. It is decoded generically: the
diff --git a/apps/modules/tg4/config.go b/apps/modules/tg4/config.go
index 2162ed7..3fef619 100644
--- a/apps/modules/tg4/config.go
+++ b/apps/modules/tg4/config.go
@@ -3,9 +3,9 @@ package tg4
 import (
 	"time"
 
-	"drmdecryption/modcfg"
-	"drmdecryption/modules/provider"
-	"drmdecryption/uiflow"
+	"streamd/modcfg"
+	"streamd/modules/provider"
+	"streamd/uiflow"
 )
 
 // Name is the module id (--app tg4).
diff --git a/apps/modules/tg4/keys.go b/apps/modules/tg4/keys.go
index a14db24..5ec6cd1 100644
--- a/apps/modules/tg4/keys.go
+++ b/apps/modules/tg4/keys.go
@@ -5,10 +5,10 @@ import (
 	"path/filepath"
 	"strings"
 
-	"drmdecryption/brightcove"
-	"drmdecryption/repo"
-	"drmdecryption/session"
-	"drmdecryption/wvkey"
+	"streamd/brightcove"
+	"streamd/repo"
+	"streamd/session"
+	"streamd/wvkey"
 )
 
 // EnrichWithKeys fetches the HLS master, extracts the Widevine PSSH and resolves
diff --git a/apps/modules/tg4/steps.go b/apps/modules/tg4/steps.go
index 3b5040b..b915877 100644
--- a/apps/modules/tg4/steps.go
+++ b/apps/modules/tg4/steps.go
@@ -5,8 +5,8 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	"streamd/uiflow"
 )
 
 // openLivePage navigates to the Live page: if a menu entry is visible tap it,
diff --git a/apps/modules/tg4/tg4.go b/apps/modules/tg4/tg4.go
index 8e20653..d1f1a62 100644
--- a/apps/modules/tg4/tg4.go
+++ b/apps/modules/tg4/tg4.go
@@ -10,12 +10,12 @@ import (
 	"fmt"
 	"time"
 
-	"drmdecryption/adb"
-	appreg "drmdecryption/app"
-	"drmdecryption/capture"
-	"drmdecryption/modules/provider"
-	"drmdecryption/mpd"
-	"drmdecryption/uiflow"
+	"streamd/adb"
+	appreg "streamd/app"
+	"streamd/capture"
+	"streamd/modules/provider"
+	"streamd/mpd"
+	"streamd/uiflow"
 )
 
 func init() {
diff --git a/apps/modules/tg4/tg4_test.go b/apps/modules/tg4/tg4_test.go
index cc16fc6..1e16891 100644
--- a/apps/modules/tg4/tg4_test.go
+++ b/apps/modules/tg4/tg4_test.go
@@ -3,9 +3,9 @@ package tg4
 import (
 	"testing"
 
-	appreg "drmdecryption/app"
-	"drmdecryption/modcfg"
-	"drmdecryption/modules/provider"
+	appreg "streamd/app"
+	"streamd/modcfg"
+	"streamd/modules/provider"
 )
 
 // Compile-time proof the plugin satisfies every interface the host expects.
diff --git a/apps/pkg/README.md b/apps/pkg/README.md
index 05a5413..6d17d2b 100644
--- a/apps/pkg/README.md
+++ b/apps/pkg/README.md
@@ -1,10 +1,10 @@
 # pkg — shared Go libraries
 
 Imported by `apps/capture`, `apps/agent`, `apps/streamd`, `apps/proxy`, `apps/cli`
-and `apps/modules` as module `drmdecryption` via:
+and `apps/modules` as module `streamd` via:
 
 ```go
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
 ```
 
 ## Packages
@@ -34,4 +34,4 @@ provider values live in that module's gitignored `module.yaml`.
 go -C apps/pkg test ./...
 ```
 
-No binary of its own — everything ships in `bin/drm`, built from `apps/cli`.
+No binary of its own — everything ships in `bin/streamd`, built from `apps/cli`.
diff --git a/apps/pkg/app/app.go b/apps/pkg/app/app.go
index 3a180b7..a78b688 100644
--- a/apps/pkg/app/app.go
+++ b/apps/pkg/app/app.go
@@ -6,10 +6,10 @@ import (
 	"sort"
 	"sync"
 
-	"drmdecryption/adb"
-	"drmdecryption/capture"
-	"drmdecryption/mpd"
-	"drmdecryption/session"
+	"streamd/adb"
+	"streamd/capture"
+	"streamd/mpd"
+	"streamd/session"
 )
 
 // Channel is a named live target inside an app (e.g. rteone).
diff --git a/apps/pkg/bootstrap/bootstrap.go b/apps/pkg/bootstrap/bootstrap.go
index 1ec264c..86f4d5d 100644
--- a/apps/pkg/bootstrap/bootstrap.go
+++ b/apps/pkg/bootstrap/bootstrap.go
@@ -1,4 +1,4 @@
-// Package bootstrap materialises a GitHub-like install tree next to drm.exe
+// Package bootstrap materialises a GitHub-like install tree next to streamd
 // so a single downloaded binary can create apps/, bin/, outputs/, etc. on first run.
 package bootstrap
 
@@ -17,7 +17,7 @@ var embedded embed.FS
 const minProxyBytes = 100_000 // stub ELF is tiny; real proxy-android-arm64 is ~9MB
 
 // InstallRoot is the directory that should contain apps/, bin/, outputs/.
-// If drm.exe lives in …/bin/, the parent is the root; otherwise the exe directory.
+// If streamd lives in …/bin/, the parent is the root; otherwise the exe directory.
 func InstallRoot() (string, error) {
 	exe, err := os.Executable()
 	if err != nil {
@@ -91,27 +91,34 @@ func Ensure(root string) (created []string, err error) {
 		return created, err
 	}
 
-	// If drm is not already under bin/, copy/link a drm.exe there for 1:1 layout.
-	if err := ensureBinDrm(root); err != nil {
+	// If streamd is not already under bin/, copy it there for 1:1 layout.
+	// Also keep a drm.exe compat copy for one release when missing.
+	if err := ensureBinHost(root); err != nil {
 		return created, err
 	}
 	return created, nil
 }
 
-func ensureBinDrm(root string) error {
+func ensureBinHost(root string) error {
 	exe, err := os.Executable()
 	if err != nil {
 		return nil
 	}
 	exe, _ = filepath.EvalSymlinks(exe)
-	dest := filepath.Join(root, "bin", "drm.exe")
-	if sameFile(exe, dest) {
+	if err := copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe")); err != nil {
+		return err
+	}
+	return copyExeIfMissing(exe, filepath.Join(root, "bin", "drm.exe"))
+}
+
+func copyExeIfMissing(src, dest string) error {
+	if sameFile(src, dest) {
 		return nil
 	}
 	if st, err := os.Stat(dest); err == nil && !st.IsDir() {
 		return nil
 	}
-	data, err := os.ReadFile(exe)
+	data, err := os.ReadFile(src)
 	if err != nil {
 		return err
 	}
@@ -154,7 +161,7 @@ func EnsureAndLogFor(cmd string) error {
 	}
 	proxy := filepath.Join(root, "bin", "proxy-android-arm64")
 	if st, err := os.Stat(proxy); err != nil || st.Size() < minProxyBytes {
-		fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to drm or use a release build that embeds it\n")
+		fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to streamd or use a release build that embeds it\n")
 	}
 	// Providers live under modules/; only warn when the command needs them.
 	needsModules := cmd == "" || cmd == "modules" || cmd == "capture" || cmd == "catalog" || cmd == "agent" || cmd == "serve"
diff --git a/apps/pkg/bootstrap/embedded/README.md b/apps/pkg/bootstrap/embedded/README.md
index 6773ac9..e4e6cc8 100644
--- a/apps/pkg/bootstrap/embedded/README.md
+++ b/apps/pkg/bootstrap/embedded/README.md
@@ -1,14 +1,14 @@
-# Null DRM
+# Streamd
 
-Host binary **`drm`** + providers under **`modules/`**.
+Host binary **`streamd`** + providers under **`modules/`**.
 
 ## Quick start
 
-1. Download `drm` (`v*` release) and module zips (`modules-v*` release).
+1. Download `streamd` (`v*` release) and module zips (`modules-v*` release).
 2. Unzip providers into `modules//` and edit `module.yaml` (secrets only).
-3. `drm proxy install-ca --reinject`
-4. `drm capture --app bbc --channel bbcone --wait 120`
-5. `drm proxy reset` when finished.
+3. `streamd proxy install-ca --reinject`
+4. `streamd capture --app bbc --channel bbcone --wait 120`
+5. `streamd proxy reset` when finished.
 
 ```text
 drm modules
@@ -17,6 +17,6 @@ drm catalog --app NAME --channel ID [--keys] [--json]
 drm proxy install-ca --reinject | reset | transparent --package PKG
 ```
 
-`--modules-dir DIR` or `$DRM_MODULES_DIR` selects another modules folder.
+`--modules-dir DIR` or `$STREAMD_MODULES_DIR` selects another modules folder.
 
 Full docs: https://git.nulldrm.com/nulldrm/Null-DRM-Official
diff --git a/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod b/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod
index c23f9f3..1b7a669 100644
--- a/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod
+++ b/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod
@@ -1,4 +1,4 @@
-module drmdecryption
+module streamd
 
 go 1.25.0
 
diff --git a/apps/pkg/bootstrap/embedded/modules/README.md b/apps/pkg/bootstrap/embedded/modules/README.md
index edc20ac..8493f8b 100644
--- a/apps/pkg/bootstrap/embedded/modules/README.md
+++ b/apps/pkg/bootstrap/embedded/modules/README.md
@@ -1,6 +1,6 @@
 # External modules
 
-Each subdirectory is a provider the `drm` host discovers, builds, and runs.
+Each subdirectory is a provider the `streamd` host discovers, builds, and runs.
 
 ```
 modules/
diff --git a/apps/pkg/bootstrap/embedded/root-go-mod.txt b/apps/pkg/bootstrap/embedded/root-go-mod.txt
index c23f9f3..1b7a669 100644
--- a/apps/pkg/bootstrap/embedded/root-go-mod.txt
+++ b/apps/pkg/bootstrap/embedded/root-go-mod.txt
@@ -1,4 +1,4 @@
-module drmdecryption
+module streamd
 
 go 1.25.0
 
diff --git a/apps/pkg/capture/capture.go b/apps/pkg/capture/capture.go
index f4e30e4..ef73a54 100644
--- a/apps/pkg/capture/capture.go
+++ b/apps/pkg/capture/capture.go
@@ -9,7 +9,7 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
+	"streamd/adb"
 )
 
 // Hints tell the waiter which fields / log tags mean a capture is complete.
diff --git a/apps/pkg/go.mod b/apps/pkg/go.mod
index c23f9f3..1b7a669 100644
--- a/apps/pkg/go.mod
+++ b/apps/pkg/go.mod
@@ -1,4 +1,4 @@
-module drmdecryption
+module streamd
 
 go 1.25.0
 
diff --git a/apps/pkg/modcfg/modcfg.go b/apps/pkg/modcfg/modcfg.go
index 30b3fa5..371e621 100644
--- a/apps/pkg/modcfg/modcfg.go
+++ b/apps/pkg/modcfg/modcfg.go
@@ -15,8 +15,8 @@ import (
 	"path/filepath"
 	"strings"
 
-	"drmdecryption/modhost"
-	"drmdecryption/repo"
+	"streamd/modhost"
+	"streamd/repo"
 	"gopkg.in/yaml.v3"
 )
 
diff --git a/apps/pkg/modhost/discover.go b/apps/pkg/modhost/discover.go
index 93a90de..efecb85 100644
--- a/apps/pkg/modhost/discover.go
+++ b/apps/pkg/modhost/discover.go
@@ -13,7 +13,7 @@ type Module struct {
 	Dir  string // absolute path to modules/
 }
 
-// ModulesDir returns the modules directory (honours --modules-dir / DRM_MODULES_DIR).
+// ModulesDir returns the modules directory (honours --modules-dir / STREAMD_MODULES_DIR / DRM_MODULES_DIR).
 func ModulesDir(root string) string {
 	return EffectiveModulesDir(root)
 }
diff --git a/apps/pkg/modhost/protocol.go b/apps/pkg/modhost/protocol.go
index 4fbade8..3ac5acc 100644
--- a/apps/pkg/modhost/protocol.go
+++ b/apps/pkg/modhost/protocol.go
@@ -1,8 +1,8 @@
 // Package modhost discovers, builds, and runs external provider modules that
-// live under modules// (Go source + module.yaml), outside drm.exe.
+// live under modules// (Go source + module.yaml), outside streamd.
 package modhost
 
-import "drmdecryption/capture"
+import "streamd/capture"
 
 // ProtocolVersion is bumped when describe/launch/autoplay CLI contract changes.
 const ProtocolVersion = 1
diff --git a/apps/pkg/modhost/remote_app.go b/apps/pkg/modhost/remote_app.go
index 6932567..ac113d5 100644
--- a/apps/pkg/modhost/remote_app.go
+++ b/apps/pkg/modhost/remote_app.go
@@ -6,11 +6,11 @@ import (
 	"path/filepath"
 	"strings"
 
-	"drmdecryption/adb"
-	"drmdecryption/app"
-	"drmdecryption/capture"
-	"drmdecryption/mpd"
-	"drmdecryption/session"
+	"streamd/adb"
+	"streamd/app"
+	"streamd/capture"
+	"streamd/mpd"
+	"streamd/session"
 )
 
 // RemoteApp implements app.App by calling an external module binary.
diff --git a/apps/pkg/modhost/root.go b/apps/pkg/modhost/root.go
index 9133e24..f796db6 100644
--- a/apps/pkg/modhost/root.go
+++ b/apps/pkg/modhost/root.go
@@ -5,7 +5,7 @@ import (
 	"path/filepath"
 	"sync"
 
-	"drmdecryption/repo"
+	"streamd/repo"
 )
 
 var (
@@ -13,7 +13,7 @@ var (
 	modulesDirOV string // absolute path override for the modules directory
 )
 
-// SetModulesDir overrides where providers are discovered (drm --modules-dir).
+// SetModulesDir overrides where providers are discovered (streamd --modules-dir).
 // Empty clears the override. Relative paths are resolved against the process cwd.
 func SetModulesDir(dir string) error {
 	rootMu.Lock()
@@ -38,7 +38,7 @@ func ModulesDirOverride() string {
 }
 
 // EffectiveModulesDir is the directory that Discover/Open scan.
-// Prefer --modules-dir / DRM_MODULES_DIR; else /modules.
+// Prefer --modules-dir / STREAMD_MODULES_DIR / DRM_MODULES_DIR; else /modules.
 func EffectiveModulesDir(root string) string {
 	if ov := ModulesDirOverride(); ov != "" {
 		return ov
@@ -49,12 +49,16 @@ func EffectiveModulesDir(root string) string {
 	return filepath.Join(root, "modules")
 }
 
-// ApplyEnvModulesDir sets the override from DRM_MODULES_DIR when no flag was set.
+// ApplyEnvModulesDir sets the override from STREAMD_MODULES_DIR (preferred) or
+// DRM_MODULES_DIR when no flag was set.
 func ApplyEnvModulesDir() error {
 	if ModulesDirOverride() != "" {
 		return nil
 	}
-	v := os.Getenv("DRM_MODULES_DIR")
+	v := os.Getenv("STREAMD_MODULES_DIR")
+	if v == "" {
+		v = os.Getenv("DRM_MODULES_DIR")
+	}
 	if v == "" {
 		return nil
 	}
diff --git a/apps/pkg/phonecap/phonecap.go b/apps/pkg/phonecap/phonecap.go
index 776335c..2f27ffd 100644
--- a/apps/pkg/phonecap/phonecap.go
+++ b/apps/pkg/phonecap/phonecap.go
@@ -12,13 +12,13 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
-	"drmdecryption/app"
-	"drmdecryption/capture"
-	"drmdecryption/proxy"
-	"drmdecryption/repo"
-	"drmdecryption/session"
-	"drmdecryption/wvkey"
+	"streamd/adb"
+	"streamd/app"
+	"streamd/capture"
+	"streamd/proxy"
+	"streamd/repo"
+	"streamd/session"
+	"streamd/wvkey"
 )
 
 // DefaultCAHash is the subject hash of the bundled MITM CA, used when an app
diff --git a/apps/pkg/proxy/embed.go b/apps/pkg/proxy/embed.go
index 1c985c4..79d0e20 100644
--- a/apps/pkg/proxy/embed.go
+++ b/apps/pkg/proxy/embed.go
@@ -6,15 +6,15 @@ import (
 	"os"
 	"path/filepath"
 
-	"drmdecryption/adb"
-	"drmdecryption/repo"
+	"streamd/adb"
+	"streamd/repo"
 )
 
 //go:embed embedded/tproxy_iptables.sh
 var embeddedTProxyScript []byte
 
 // ensureTProxyScript pushes the iptables helper to the phone.
-// Prefers the source-tree copy; falls back to the copy embedded in drm.exe
+// Prefers the source-tree copy; falls back to the copy embedded in streamd
 // so a portable release zip does not need apps/proxy/device/.
 func ensureTProxyScript(c *adb.Client) error {
 	candidates := []string{
diff --git a/apps/pkg/proxy/proxy.go b/apps/pkg/proxy/proxy.go
index d6be1e2..90d7647 100644
--- a/apps/pkg/proxy/proxy.go
+++ b/apps/pkg/proxy/proxy.go
@@ -17,8 +17,8 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
-	"drmdecryption/repo"
+	"streamd/adb"
+	"streamd/repo"
 )
 
 const (
@@ -225,7 +225,7 @@ func PushAndStart(c *adb.Client, localBin string, extraArgs ...string) error {
 }
 
 // FindLocalBin returns the on-device MITM binary.
-// Search order: next to this drm.exe (release zip layout), then under the repo.
+// Search order: next to this streamd binary (release zip layout), then under the repo.
 func FindLocalBin(root string) string {
 	if root == "" {
 		root = repo.Root()
@@ -322,11 +322,11 @@ func generateMITMCA(certPath, keyPath string) error {
 		return err
 	}
 	// Unique CN so Android subject_hash_old differs per install (filename HASH.0).
-	cn := fmt.Sprintf("Null DRM Capture CA %x", serial.Bytes()[:8])
+	cn := fmt.Sprintf("Streamd Capture CA %x", serial.Bytes()[:8])
 	tmpl := &x509.Certificate{
 		SerialNumber: serial,
 		Subject: pkix.Name{
-			Organization: []string{"Null DRM MITM CA"},
+			Organization: []string{"Streamd MITM CA"},
 			CommonName:   cn,
 		},
 		NotBefore:             time.Now().Add(-time.Hour),
diff --git a/apps/pkg/repo/root.go b/apps/pkg/repo/root.go
index a03ac8a..c218f43 100644
--- a/apps/pkg/repo/root.go
+++ b/apps/pkg/repo/root.go
@@ -11,7 +11,7 @@ import (
 //
 // Search order:
 //  1. Walk up from the current working directory
-//  2. Walk up from drm.exe (if the exe lives in bin/, start at the parent)
+//  2. Walk up from streamd (if the exe lives in bin/, start at the parent)
 func Root() string {
 	if root := findRoot(wd()); root != "" {
 		return root
diff --git a/apps/pkg/uiflow/uiflow.go b/apps/pkg/uiflow/uiflow.go
index de8da07..afde843 100644
--- a/apps/pkg/uiflow/uiflow.go
+++ b/apps/pkg/uiflow/uiflow.go
@@ -10,7 +10,7 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/adb"
+	"streamd/adb"
 )
 
 // Pick selects among several matching nodes.
diff --git a/apps/proxy/README.md b/apps/proxy/README.md
index 38f5e83..1641534 100644
--- a/apps/proxy/README.md
+++ b/apps/proxy/README.md
@@ -5,7 +5,7 @@ license URLs, manifests and auth headers.
 
 ```text
 apps/proxy/
-  proxyctlcmd/      host CLI, hosted by bin/drm as `drm proxy`
+  proxyctlcmd/      host CLI, hosted by bin/streamd as `streamd proxy`
   device/           linux/arm64 MITM source (module: appproxy)
   rteproxy-ca.crt   MITM CA (subject hash 6c3578b4)
 ```
@@ -17,8 +17,8 @@ working.
 ## Build
 
 ```bash
-go -C apps/cli build -o ../../bin/drm .   # host CLI
-./bin/drm proxy build                     # cross-compile the device binary
+go -C apps/cli build -o ../../bin/streamd .   # host CLI
+./bin/streamd proxy build                     # cross-compile the device binary
 ```
 
 `proxy build` compiles `device/` for linux/arm64 into
@@ -28,20 +28,20 @@ go -C apps/cli build -o ../../bin/drm .   # host CLI
 
 ```bash
 # trust the MITM CA (needs Magisk; mounts into the system store)
-./bin/drm proxy install-ca --reinject
-./bin/drm proxy reinject-ca              # mount only, CA already pushed
+./bin/streamd proxy install-ca --reinject
+./bin/streamd proxy reinject-ca              # mount only, CA already pushed
 
 # structured capture proxy
-./bin/drm proxy start --install-ca --reinject
-./bin/drm proxy stop
+./bin/streamd proxy start --install-ca --reinject
+./bin/streamd proxy stop
 
 # record everything while you explore an unknown app
-./bin/drm proxy discover --install-ca --reinject
-./bin/drm proxy discover --force-stop    # so it inherits the CA mount
+./bin/streamd proxy discover --install-ca --reinject
+./bin/streamd proxy discover --force-stop    # so it inherits the CA mount
 
 # pull artifacts without re-running, and release the phone
-./bin/drm proxy pull
-./bin/drm proxy clear-proxy
+./bin/streamd proxy pull
+./bin/streamd proxy clear-proxy
 ```
 
 Always clear the proxy when done, or the phone keeps pointing at a dead listener.
@@ -53,7 +53,7 @@ phone can stay on NordVPN UK; nothing sets `http_proxy`.
 
 ```bash
 # leave UK VPN connected on the phone, then:
-./bin/drm proxy transparent --package bbc.iplayer.android --reinject
+./bin/streamd proxy transparent --package bbc.iplayer.android --reinject
 # open the app / play — Ctrl+C stops iptables and pulls files
 ```
 
@@ -75,7 +75,7 @@ Force-stop the target app once after CA reinject so it inherits the Magisk CA mo
 
 The device binary cannot read an app module's values file, so a module's
 manifest-scoring hosts are passed to it as flags (`--match`, `--score-host`,
-`--score-deny`). `drm capture` does this automatically.
+`--score-deny`). `streamd capture` does this automatically.
 
 ## Artifacts
 
diff --git a/apps/proxy/go.mod b/apps/proxy/go.mod
index 859bedf..0bea3da 100644
--- a/apps/proxy/go.mod
+++ b/apps/proxy/go.mod
@@ -1,7 +1,7 @@
-module drmdecryption/apps/proxy
+module streamd/apps/proxy
 
 go 1.25.0
 
-require drmdecryption v0.0.0
+require streamd v0.0.0
 
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/proxy/proxyctlcmd/proxyctlcmd.go b/apps/proxy/proxyctlcmd/proxyctlcmd.go
index d1864bf..a39ae31 100644
--- a/apps/proxy/proxyctlcmd/proxyctlcmd.go
+++ b/apps/proxy/proxyctlcmd/proxyctlcmd.go
@@ -18,9 +18,9 @@ import (
 	"syscall"
 	"time"
 
-	"drmdecryption/adb"
-	"drmdecryption/proxy"
-	"drmdecryption/repo"
+	"streamd/adb"
+	"streamd/proxy"
+	"streamd/repo"
 )
 
 // Run dispatches a proxy subcommand. args[0] is the subcommand name.
@@ -130,7 +130,7 @@ func buildCmd(args []string) {
 
 	if _, err := os.Stat(deviceDir); err != nil {
 		fmt.Fprintf(os.Stderr, "proxy build needs the full source tree (apps/proxy/device).\n")
-		fmt.Fprintf(os.Stderr, "For a release zip, put proxy-android-arm64 next to drm.exe instead — no Go build required.\n")
+		fmt.Fprintf(os.Stderr, "For a release zip, put proxy-android-arm64 next to streamd instead — no Go build required.\n")
 		fmt.Fprintf(os.Stderr, "Missing: %s\n", deviceDir)
 		os.Exit(1)
 	}
diff --git a/apps/streamd/README.md b/apps/streamd/README.md
index 7efabc8..20dfe6a 100644
--- a/apps/streamd/README.md
+++ b/apps/streamd/README.md
@@ -1,7 +1,7 @@
 # streamd
 
 Control plane: REST API, SQLite, dashboard and media supervisor. Hosted by the
-single binary as `drm serve`.
+single binary as `streamd serve`.
 
 ```text
 apps/streamd/
@@ -17,7 +17,7 @@ apps/streamd/
 ## Run
 
 ```bash
-./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd
+./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
 ```
 
 `--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any
diff --git a/apps/streamd/go.mod b/apps/streamd/go.mod
index 4064060..ec97f71 100644
--- a/apps/streamd/go.mod
+++ b/apps/streamd/go.mod
@@ -1,14 +1,14 @@
-module drmdecryption/apps/streamd
+module streamd/apps/streamd
 
 go 1.25.0
 
 require (
-	drmdecryption v0.0.0
 	github.com/gorilla/websocket v1.5.3
 	modernc.org/sqlite v1.34.5
+	streamd v0.0.0
 )
 
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
 
 require (
 	github.com/dustin/go-humanize v1.0.1 // indirect
diff --git a/apps/streamd/internal/api/api.go b/apps/streamd/internal/api/api.go
index 0ae4089..4408794 100644
--- a/apps/streamd/internal/api/api.go
+++ b/apps/streamd/internal/api/api.go
@@ -10,10 +10,11 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/auth"
-	"drmdecryption/apps/streamd/internal/db"
-	"drmdecryption/apps/streamd/internal/deps"
-	"drmdecryption/apps/streamd/internal/httpx"
+	"streamd/apps/streamd/internal/auth"
+	"streamd/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/deps"
+	"streamd/apps/streamd/internal/httpx"
+	"streamd/apps/streamd/internal/modstore"
 )
 
 type Supervisor interface {
@@ -56,7 +57,11 @@ type Handler struct {
 	Deps       deps.Status
 	WWWRoot    string // data/www — used to report variant playlist health
 	LogRoot    string // data/logs — source for the log tail endpoints
-	Log        *slog.Logger
+	DataDir    string // streamd --data root
+	Modules    *modstore.Store
+	// ModulesNotify is set when the hub supports module change pushes.
+	ModulesNotify ModulesNotifier
+	Log           *slog.Logger
 }
 
 func (h *Handler) Mount(mux *http.ServeMux) {
diff --git a/apps/streamd/internal/api/apps.go b/apps/streamd/internal/api/apps.go
index 179290a..5b61afc 100644
--- a/apps/streamd/internal/api/apps.go
+++ b/apps/streamd/internal/api/apps.go
@@ -3,10 +3,10 @@ package api
 import (
 	"net/http"
 
-	"drmdecryption/apps/streamd/internal/auth"
-	"drmdecryption/modhost"
-	"drmdecryption/mpd"
-	"drmdecryption/repo"
+	"streamd/apps/streamd/internal/auth"
+	"streamd/modhost"
+	"streamd/mpd"
+	"streamd/repo"
 )
 
 // appInfo describes one modules// provider to the dashboard, so the UI
@@ -16,6 +16,7 @@ type appInfo struct {
 	Channels  []channelInfo `json:"channels"`
 	Rewriter  string        `json:"rewriter"`
 	HasConfig bool          `json:"has_config"`
+	Error     string        `json:"error,omitempty"`
 }
 
 type channelInfo struct {
@@ -23,7 +24,9 @@ type channelInfo struct {
 	Label string `json:"label"`
 }
 
-// apps answers GET /api/apps: which providers exist under modules/.
+// apps answers GET /api/apps: which providers exist under the panel modules store.
+// A single module that fails to describe is skipped with an error field rather
+// than failing the whole list (bad uploads must not blank the stream pickers).
 func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
 	if r.Method != http.MethodGet {
 		writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
@@ -33,13 +36,27 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 	out := []appInfo{}
-	listed, err := modhost.ListAll(repo.Root())
+	mods, err := modhost.Discover(repo.Root())
 	if err != nil {
 		writeErr(w, http.StatusInternalServerError, err.Error())
 		return
 	}
-	for _, L := range listed {
-		d := L.Desc
+	for _, m := range mods {
+		bin, err := modhost.EnsureBuilt(m)
+		if err != nil {
+			out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()})
+			h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
+			continue
+		}
+		d, err := modhost.RunDescribe(bin)
+		if err != nil {
+			out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()})
+			h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
+			continue
+		}
+		if d.Name == "" {
+			d.Name = m.Name
+		}
 		info := appInfo{Name: d.Name, Channels: []channelInfo{}, Rewriter: "none"}
 		for _, ch := range d.Channels {
 			info.Channels = append(info.Channels, channelInfo{ID: ch.ID, Label: ch.Label})
diff --git a/apps/streamd/internal/api/control.go b/apps/streamd/internal/api/control.go
index 7cb3723..44fd939 100644
--- a/apps/streamd/internal/api/control.go
+++ b/apps/streamd/internal/api/control.go
@@ -11,9 +11,9 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/auth"
-	"drmdecryption/apps/streamd/internal/db"
-	"drmdecryption/mpd"
+	"streamd/apps/streamd/internal/auth"
+	"streamd/apps/streamd/internal/db"
+	"streamd/mpd"
 )
 
 // MountControl adds the bulk, duplicate, probe, settings and schedule routes.
diff --git a/apps/streamd/internal/api/events.go b/apps/streamd/internal/api/events.go
index 8943dbf..873c006 100644
--- a/apps/streamd/internal/api/events.go
+++ b/apps/streamd/internal/api/events.go
@@ -10,9 +10,9 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/auth"
-	"drmdecryption/apps/streamd/internal/db"
-	"drmdecryption/apps/streamd/internal/logfile"
+	"streamd/apps/streamd/internal/auth"
+	"streamd/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/logfile"
 )
 
 // logSources maps a caller-supplied source name to the log file suffix the
diff --git a/apps/streamd/internal/api/modules.go b/apps/streamd/internal/api/modules.go
index b04a480..f99efa5 100644
--- a/apps/streamd/internal/api/modules.go
+++ b/apps/streamd/internal/api/modules.go
@@ -1,93 +1,160 @@
 package api
 
 import (
-	"crypto/sha256"
-	"encoding/hex"
 	"encoding/json"
 	"errors"
 	"io"
 	"net/http"
-	"os"
 	"path/filepath"
-	"regexp"
 	"strings"
+	"time"
 
-	"drmdecryption/apps/streamd/internal/auth"
-	"drmdecryption/modhost"
-	"drmdecryption/repo"
+	"streamd/apps/streamd/internal/auth"
+	"streamd/apps/streamd/internal/modstore"
 )
 
-// moduleInfo is one modules// entry for agent sync.
-type moduleInfo struct {
-	Name       string `json:"name"`
-	HasYAML    bool   `json:"has_yaml"`
-	YAMLSHA256 string `json:"yaml_sha256,omitempty"`
+// ModulesNotifier pushes module change events to agents and the dashboard.
+type ModulesNotifier interface {
+	NotifyModulesChanged(name, reason string)
 }
 
-var moduleNameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`)
+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, "/")
 
-	// Module metadata describes the provider plugins installed on this host,
-	// so even reading it needs a principal.
-	if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
-		return
-	}
-
 	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) {
-	root := repo.Root()
-	dir := modhost.ModulesDir(root)
-	ents, err := os.ReadDir(dir)
+	list, err := h.modStore().List()
 	if err != nil {
-		if os.IsNotExist(err) {
-			writeJSON(w, http.StatusOK, map[string]any{"modules": []moduleInfo{}})
-			return
-		}
 		writeErr(w, http.StatusInternalServerError, err.Error())
 		return
 	}
-	out := []moduleInfo{}
-	for _, e := range ents {
-		if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
-			continue
-		}
-		info := moduleYAMLInfo(filepath.Join(dir, e.Name()), e.Name())
-		out = append(out, info)
-	}
-	writeJSON(w, http.StatusOK, map[string]any{"modules": out})
+	writeJSON(w, http.StatusOK, map[string]any{"modules": list})
 }
 
 func (h *Handler) getModule(w http.ResponseWriter, r *http.Request, name string) {
-	if !moduleNameRe.MatchString(name) {
+	if !modstore.NameRe.MatchString(name) {
 		writeErr(w, http.StatusBadRequest, "invalid module name")
 		return
 	}
-	info := moduleYAMLInfo(filepath.Join(modhost.ModulesDir(repo.Root()), name), name)
-	writeJSON(w, http.StatusOK, info)
+	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) {
-	// Writing a module.yaml changes how streams are captured on this host:
-	// operator, and recorded.
 	p, ok := auth.Guard(w, r, auth.RoleOperator)
 	if !ok {
 		return
 	}
-	if !moduleNameRe.MatchString(name) {
+	if !modstore.NameRe.MatchString(name) {
 		writeErr(w, http.StatusBadRequest, "invalid module name")
 		return
 	}
@@ -104,47 +171,84 @@ func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string)
 		writeErr(w, http.StatusBadRequest, err.Error())
 		return
 	}
-	if len(strings.TrimSpace(string(yamlBytes))) == 0 {
-		writeErr(w, http.StatusBadRequest, "empty module.yaml")
+
+	info, err := h.modStore().WriteYAML(name, yamlBytes)
+	if err != nil {
+		writeErr(w, http.StatusBadRequest, err.Error())
 		return
 	}
 
-	modDir := filepath.Join(modhost.ModulesDir(repo.Root()), name)
-	if err := os.MkdirAll(modDir, 0o755); err != nil {
-		writeErr(w, http.StatusInternalServerError, err.Error())
-		return
-	}
-	dest := filepath.Join(modDir, "module.yaml")
-	tmp := dest + ".tmp"
-	if err := os.WriteFile(tmp, yamlBytes, 0o644); err != nil {
-		writeErr(w, http.StatusInternalServerError, err.Error())
-		return
-	}
-	if err := os.Rename(tmp, dest); err != nil {
-		_ = os.Remove(tmp)
-		writeErr(w, http.StatusInternalServerError, err.Error())
-		return
-	}
-
-	info := moduleYAMLInfo(modDir, name)
-	h.audit(r, p, http.StatusOK, "uploaded module.yaml for "+name)
+	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 moduleYAMLInfo(modDir, name string) moduleInfo {
-	info := moduleInfo{Name: name}
-	b, err := os.ReadFile(filepath.Join(modDir, "module.yaml"))
-	if err != nil {
-		return info
+func (h *Handler) deleteModule(w http.ResponseWriter, r *http.Request, name string) {
+	p, ok := auth.Guard(w, r, auth.RoleOperator)
+	if !ok {
+		return
 	}
-	sum := sha256.Sum256(b)
-	info.HasYAML = true
-	info.YAMLSHA256 = hex.EncodeToString(sum[:])
-	return info
+	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":"..."}.
@@ -163,7 +267,6 @@ func extractModuleYAML(contentType string, body []byte) ([]byte, error) {
 		}
 		return []byte(wrap.YAML), nil
 	default:
-		// text/yaml, application/x-yaml, or bare body
 		return body, nil
 	}
 }
diff --git a/apps/streamd/internal/api/variants.go b/apps/streamd/internal/api/variants.go
index 69da377..c29db91 100644
--- a/apps/streamd/internal/api/variants.go
+++ b/apps/streamd/internal/api/variants.go
@@ -6,7 +6,7 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/db"
 )
 
 // stalePlaylistS is how old a playlist may get before the output counts as
diff --git a/apps/streamd/internal/auth/auth_test.go b/apps/streamd/internal/auth/auth_test.go
index b4a7df4..cbe85b3 100644
--- a/apps/streamd/internal/auth/auth_test.go
+++ b/apps/streamd/internal/auth/auth_test.go
@@ -8,7 +8,7 @@ import (
 	"testing"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/httpx"
+	"streamd/apps/streamd/internal/httpx"
 
 	_ "modernc.org/sqlite"
 )
diff --git a/apps/streamd/internal/auth/handlers.go b/apps/streamd/internal/auth/handlers.go
index 40290d0..a86d412 100644
--- a/apps/streamd/internal/auth/handlers.go
+++ b/apps/streamd/internal/auth/handlers.go
@@ -11,7 +11,7 @@ import (
 	"sync"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/httpx"
+	"streamd/apps/streamd/internal/httpx"
 )
 
 // Handler serves the auth routes: login/logout/me, user administration, API
diff --git a/apps/streamd/internal/auth/middleware.go b/apps/streamd/internal/auth/middleware.go
index db2e5a1..8d84625 100644
--- a/apps/streamd/internal/auth/middleware.go
+++ b/apps/streamd/internal/auth/middleware.go
@@ -8,7 +8,7 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/httpx"
+	"streamd/apps/streamd/internal/httpx"
 )
 
 const (
diff --git a/apps/streamd/internal/deps/deps.go b/apps/streamd/internal/deps/deps.go
index 7ee72b9..9b449c5 100644
--- a/apps/streamd/internal/deps/deps.go
+++ b/apps/streamd/internal/deps/deps.go
@@ -14,7 +14,7 @@ import (
 	"strings"
 	"time"
 
-	"drmdecryption/repo"
+	"streamd/repo"
 )
 
 // Status is the resolved path for each tool after Ensure.
@@ -202,7 +202,7 @@ func httpGet(url string) (*http.Response, error) {
 	if err != nil {
 		return nil, err
 	}
-	req.Header.Set("User-Agent", "null-drm-streamd/1.0")
+	req.Header.Set("User-Agent", "streamd/1.0")
 	return client.Do(req)
 }
 
diff --git a/apps/streamd/internal/hlsgate/hlsgate.go b/apps/streamd/internal/hlsgate/hlsgate.go
index 0005dbd..264ece4 100644
--- a/apps/streamd/internal/hlsgate/hlsgate.go
+++ b/apps/streamd/internal/hlsgate/hlsgate.go
@@ -17,10 +17,10 @@ import (
 	"sync"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/auth"
-	"drmdecryption/apps/streamd/internal/db"
-	"drmdecryption/apps/streamd/internal/httpx"
-	"drmdecryption/apps/streamd/internal/tsfanout"
+	"streamd/apps/streamd/internal/auth"
+	"streamd/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/httpx"
+	"streamd/apps/streamd/internal/tsfanout"
 )
 
 // Supervisor is the subset of the media supervisor the gate needs.
diff --git a/apps/streamd/internal/hlsgate/hlsgate_test.go b/apps/streamd/internal/hlsgate/hlsgate_test.go
index 01c318b..8fe07ad 100644
--- a/apps/streamd/internal/hlsgate/hlsgate_test.go
+++ b/apps/streamd/internal/hlsgate/hlsgate_test.go
@@ -11,9 +11,9 @@ import (
 	"testing"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/auth"
-	"drmdecryption/apps/streamd/internal/db"
-	"drmdecryption/apps/streamd/internal/tsfanout"
+	"streamd/apps/streamd/internal/auth"
+	"streamd/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/tsfanout"
 )
 
 // fakeSup records what the gate asked for, and can pretend a stream comes up.
diff --git a/apps/streamd/internal/modstore/modstore.go b/apps/streamd/internal/modstore/modstore.go
new file mode 100644
index 0000000..f527d58
--- /dev/null
+++ b/apps/streamd/internal/modstore/modstore.go
@@ -0,0 +1,622 @@
+// Package modstore keeps provider modules under the streamd data directory.
+// Operators upload release-style zips; agents pull package.zip + module.yaml.
+package modstore
+
+import (
+	"archive/zip"
+	"crypto/sha256"
+	"encoding/hex"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+	"regexp"
+	"runtime"
+	"sort"
+	"strings"
+	"time"
+)
+
+const (
+	MaxPackageBytes = 100 << 20 // 100 MiB
+	manifestName    = "manifest.json"
+	packageName     = "package.zip"
+	yamlName        = "module.yaml"
+)
+
+var NameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`)
+
+// Info is one module's metadata for the API and agent sync.
+type Info struct {
+	Name           string   `json:"name"`
+	HasYAML        bool     `json:"has_yaml"`
+	YAMLSHA256     string   `json:"yaml_sha256,omitempty"`
+	HasPackage     bool     `json:"has_package"`
+	PackageSHA256  string   `json:"package_sha256,omitempty"`
+	Arches         []string `json:"arches,omitempty"`
+	SizeBytes      int64    `json:"size_bytes,omitempty"`
+	UploadedAt     string   `json:"uploaded_at,omitempty"`
+	YAMLUpdatedAt  string   `json:"yaml_updated_at,omitempty"`
+}
+
+type Manifest struct {
+	Name          string   `json:"name"`
+	YAMLSHA256    string   `json:"yaml_sha256,omitempty"`
+	PackageSHA256 string   `json:"package_sha256,omitempty"`
+	Arches        []string `json:"arches,omitempty"`
+	SizeBytes     int64    `json:"size_bytes,omitempty"`
+	UploadedAt    string   `json:"uploaded_at,omitempty"`
+	YAMLUpdatedAt string   `json:"yaml_updated_at,omitempty"`
+}
+
+// Store is the on-disk module library under /modules.
+type Store struct {
+	Root string
+}
+
+func New(root string) *Store {
+	return &Store{Root: root}
+}
+
+func (s *Store) modulesDir() string {
+	return s.Root
+}
+
+func (s *Store) modDir(name string) string {
+	return filepath.Join(s.Root, name)
+}
+
+func (s *Store) Ensure() error {
+	return os.MkdirAll(s.Root, 0o755)
+}
+
+// List returns every module directory under the store.
+func (s *Store) List() ([]Info, error) {
+	ents, err := os.ReadDir(s.Root)
+	if err != nil {
+		if os.IsNotExist(err) {
+			return []Info{}, nil
+		}
+		return nil, err
+	}
+	out := make([]Info, 0, len(ents))
+	for _, e := range ents {
+		if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
+			continue
+		}
+		if !NameRe.MatchString(e.Name()) {
+			continue
+		}
+		out = append(out, s.Info(e.Name()))
+	}
+	sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
+	return out, nil
+}
+
+// Info loads manifest + checks for yaml/package files.
+func (s *Store) Info(name string) Info {
+	info := Info{Name: name}
+	if !NameRe.MatchString(name) {
+		return info
+	}
+	dir := s.modDir(name)
+	m, err := s.readManifest(dir)
+	if err == nil {
+		info.YAMLSHA256 = m.YAMLSHA256
+		info.PackageSHA256 = m.PackageSHA256
+		info.Arches = append([]string(nil), m.Arches...)
+		info.SizeBytes = m.SizeBytes
+		info.UploadedAt = m.UploadedAt
+		info.YAMLUpdatedAt = m.YAMLUpdatedAt
+		info.HasYAML = m.YAMLSHA256 != ""
+		info.HasPackage = m.PackageSHA256 != ""
+	}
+	// Prefer live file hashes when present so a hand-edited yaml still shows.
+	if b, err := os.ReadFile(filepath.Join(dir, yamlName)); err == nil {
+		info.HasYAML = true
+		sum := sha256.Sum256(b)
+		info.YAMLSHA256 = hex.EncodeToString(sum[:])
+	}
+	if st, err := os.Stat(filepath.Join(dir, packageName)); err == nil && !st.IsDir() {
+		info.HasPackage = true
+		if info.PackageSHA256 == "" {
+			if sum, err := fileSHA256(filepath.Join(dir, packageName)); err == nil {
+				info.PackageSHA256 = sum
+			}
+		}
+		if info.SizeBytes == 0 {
+			info.SizeBytes = st.Size()
+		}
+	}
+	return info
+}
+
+// ReadYAML returns module.yaml bytes.
+func (s *Store) ReadYAML(name string) ([]byte, error) {
+	if !NameRe.MatchString(name) {
+		return nil, fmt.Errorf("invalid module name")
+	}
+	b, err := os.ReadFile(filepath.Join(s.modDir(name), yamlName))
+	if err != nil {
+		if os.IsNotExist(err) {
+			return nil, fmt.Errorf("module %s: no module.yaml", name)
+		}
+		return nil, err
+	}
+	return b, nil
+}
+
+// WriteYAML atomically replaces module.yaml and updates the manifest.
+func (s *Store) WriteYAML(name string, yamlBytes []byte) (Info, error) {
+	if !NameRe.MatchString(name) {
+		return Info{}, fmt.Errorf("invalid module name")
+	}
+	if len(strings.TrimSpace(string(yamlBytes))) == 0 {
+		return Info{}, fmt.Errorf("empty module.yaml")
+	}
+	dir := s.modDir(name)
+	if err := os.MkdirAll(dir, 0o755); err != nil {
+		return Info{}, err
+	}
+	dest := filepath.Join(dir, yamlName)
+	if err := atomicWrite(dest, yamlBytes, 0o644); err != nil {
+		return Info{}, err
+	}
+	sum := sha256.Sum256(yamlBytes)
+	now := time.Now().UTC().Format(time.RFC3339)
+	m, _ := s.readManifest(dir)
+	m.Name = name
+	m.YAMLSHA256 = hex.EncodeToString(sum[:])
+	m.YAMLUpdatedAt = now
+	if m.UploadedAt == "" {
+		m.UploadedAt = now
+	}
+	if err := s.writeManifest(dir, m); err != nil {
+		return Info{}, err
+	}
+	return s.Info(name), nil
+}
+
+// OpenPackage returns a ReadCloser for package.zip plus size.
+func (s *Store) OpenPackage(name string) (*os.File, int64, error) {
+	if !NameRe.MatchString(name) {
+		return nil, 0, fmt.Errorf("invalid module name")
+	}
+	path := filepath.Join(s.modDir(name), packageName)
+	f, err := os.Open(path)
+	if err != nil {
+		if os.IsNotExist(err) {
+			return nil, 0, fmt.Errorf("module %s: no package.zip", name)
+		}
+		return nil, 0, err
+	}
+	st, err := f.Stat()
+	if err != nil {
+		_ = f.Close()
+		return nil, 0, err
+	}
+	return f, st.Size(), nil
+}
+
+// Delete removes the module directory.
+func (s *Store) Delete(name string) error {
+	if !NameRe.MatchString(name) {
+		return fmt.Errorf("invalid module name")
+	}
+	dir := s.modDir(name)
+	if _, err := os.Stat(dir); err != nil {
+		if os.IsNotExist(err) {
+			return fmt.Errorf("module %s not found", name)
+		}
+		return err
+	}
+	return os.RemoveAll(dir)
+}
+
+// InstallZip stores zipBytes as package.zip, extracts into the module dir,
+// promotes the host-arch binary, and writes the manifest.
+// nameHint may be empty; the zip layout is used to infer the name.
+func (s *Store) InstallZip(zipBytes []byte, nameHint string) (Info, error) {
+	if len(zipBytes) == 0 {
+		return Info{}, fmt.Errorf("empty zip")
+	}
+	if int64(len(zipBytes)) > MaxPackageBytes {
+		return Info{}, fmt.Errorf("zip exceeds %d byte limit", MaxPackageBytes)
+	}
+
+	name, entries, err := inspectZip(zipBytes, nameHint)
+	if err != nil {
+		return Info{}, err
+	}
+	if !NameRe.MatchString(name) {
+		return Info{}, fmt.Errorf("invalid module name %q", name)
+	}
+
+	if err := s.Ensure(); err != nil {
+		return Info{}, err
+	}
+	dir := s.modDir(name)
+	tmpDir, err := os.MkdirTemp(s.Root, "."+name+".tmp-*")
+	if err != nil {
+		return Info{}, err
+	}
+	defer os.RemoveAll(tmpDir)
+
+	if err := extractZipEntries(zipBytes, entries, tmpDir); err != nil {
+		return Info{}, err
+	}
+	if err := promoteHostBinary(tmpDir, name); err != nil {
+		return Info{}, err
+	}
+	yamlPath := filepath.Join(tmpDir, yamlName)
+	if _, err := os.Stat(yamlPath); err != nil {
+		return Info{}, fmt.Errorf("zip missing module.yaml")
+	}
+	arches := detectArches(tmpDir, name)
+	pkgSum := sha256.Sum256(zipBytes)
+	yamlRaw, err := os.ReadFile(yamlPath)
+	if err != nil {
+		return Info{}, err
+	}
+	yamlSum := sha256.Sum256(yamlRaw)
+	now := time.Now().UTC().Format(time.RFC3339)
+	m := Manifest{
+		Name:          name,
+		YAMLSHA256:    hex.EncodeToString(yamlSum[:]),
+		PackageSHA256: hex.EncodeToString(pkgSum[:]),
+		Arches:        arches,
+		SizeBytes:     int64(len(zipBytes)),
+		UploadedAt:    now,
+		YAMLUpdatedAt: now,
+	}
+	if err := s.writeManifest(tmpDir, m); err != nil {
+		return Info{}, err
+	}
+	if err := atomicWrite(filepath.Join(tmpDir, packageName), zipBytes, 0o644); err != nil {
+		return Info{}, err
+	}
+
+	// Replace the live module dir.
+	backup := dir + ".bak"
+	_ = os.RemoveAll(backup)
+	if _, err := os.Stat(dir); err == nil {
+		if err := os.Rename(dir, backup); err != nil {
+			return Info{}, err
+		}
+	}
+	if err := os.Rename(tmpDir, dir); err != nil {
+		_ = os.Rename(backup, dir)
+		return Info{}, err
+	}
+	_ = os.RemoveAll(backup)
+	return s.Info(name), nil
+}
+
+type zipEntry struct {
+	// Rel is the path relative to the module root inside the zip (forward slashes).
+	Rel  string
+	File *zip.File
+}
+
+func inspectZip(zipBytes []byte, nameHint string) (name string, entries []zipEntry, err error) {
+	zr, err := zip.NewReader(newBytesReaderAt(zipBytes), int64(len(zipBytes)))
+	if err != nil {
+		return "", nil, fmt.Errorf("open zip: %w", err)
+	}
+	return inspectZipReader(zr, nameHint)
+}
+
+type bytesReaderAt struct{ b []byte }
+
+func newBytesReaderAt(b []byte) *bytesReaderAt { return &bytesReaderAt{b: b} }
+
+func (r *bytesReaderAt) ReadAt(p []byte, off int64) (int, error) {
+	if off < 0 {
+		return 0, errors.New("negative offset")
+	}
+	if off >= int64(len(r.b)) {
+		return 0, io.EOF
+	}
+	n := copy(p, r.b[off:])
+	if n < len(p) {
+		return n, io.EOF
+	}
+	return n, nil
+}
+
+func inspectZipReader(zr *zip.Reader, nameHint string) (string, []zipEntry, error) {
+	hint := strings.TrimSpace(nameHint)
+	if hint != "" && !NameRe.MatchString(hint) {
+		return "", nil, fmt.Errorf("invalid module name %q", hint)
+	}
+
+	prefix := ""
+	topDirs := map[string]struct{}{}
+	hasRootFile := false
+
+	for _, f := range zr.File {
+		name := strings.ReplaceAll(f.Name, "\\", "/")
+		name = strings.TrimPrefix(name, "./")
+		if name == "" || strings.HasPrefix(name, "__MACOSX/") || strings.HasSuffix(name, ".DS_Store") {
+			continue
+		}
+		parts := strings.Split(name, "/")
+		if len(parts) > 0 && parts[0] != "" {
+			if f.FileInfo().IsDir() || len(parts) > 1 {
+				topDirs[parts[0]] = struct{}{}
+			}
+			if len(parts) == 1 && !f.FileInfo().IsDir() {
+				hasRootFile = true
+			}
+		}
+	}
+
+	switch {
+	case hint != "":
+		prefix = ""
+		// If every entry is under hint/, strip it.
+		allUnder := true
+		for _, f := range zr.File {
+			n := strings.ReplaceAll(f.Name, "\\", "/")
+			n = strings.TrimPrefix(n, "./")
+			if n == "" || strings.HasPrefix(n, "__MACOSX/") {
+				continue
+			}
+			if n != hint && !strings.HasPrefix(n, hint+"/") {
+				allUnder = false
+				break
+			}
+		}
+		if allUnder {
+			prefix = hint + "/"
+		}
+	case hasRootFile:
+		// Flat zip: module.yaml at root. Name must be provided or inferred from binary.
+		prefix = ""
+	case len(topDirs) == 1:
+		for d := range topDirs {
+			prefix = d + "/"
+			if hint == "" {
+				hint = d
+			}
+		}
+	default:
+		return "", nil, fmt.Errorf("cannot infer module name from zip; pass name= or use a single top-level folder")
+	}
+
+	if hint == "" {
+		// Try to infer from .bin// or .bin/.
+		for _, f := range zr.File {
+			n := strings.ReplaceAll(f.Name, "\\", "/")
+			n = strings.TrimPrefix(n, "./")
+			if prefix != "" {
+				if !strings.HasPrefix(n, prefix) {
+					continue
+				}
+				n = strings.TrimPrefix(n, prefix)
+			}
+			base := filepath.Base(n)
+			base = strings.TrimSuffix(base, ".exe")
+			if strings.HasPrefix(n, ".bin/") && NameRe.MatchString(base) && base != ".bin" {
+				hint = base
+				break
+			}
+		}
+	}
+	if hint == "" {
+		return "", nil, fmt.Errorf("cannot infer module name from zip; pass name=")
+	}
+	if !NameRe.MatchString(hint) {
+		return "", nil, fmt.Errorf("invalid module name %q", hint)
+	}
+
+	var entries []zipEntry
+	for _, f := range zr.File {
+		n := strings.ReplaceAll(f.Name, "\\", "/")
+		n = strings.TrimPrefix(n, "./")
+		if n == "" || strings.HasPrefix(n, "__MACOSX/") || strings.HasSuffix(n, ".DS_Store") {
+			continue
+		}
+		rel := n
+		if prefix != "" {
+			if !strings.HasPrefix(n, prefix) {
+				continue
+			}
+			rel = strings.TrimPrefix(n, prefix)
+		}
+		if rel == "" {
+			continue
+		}
+		if strings.Contains(rel, "..") {
+			return "", nil, fmt.Errorf("zip slip: %s", f.Name)
+		}
+		entries = append(entries, zipEntry{Rel: rel, File: f})
+	}
+	if len(entries) == 0 {
+		return "", nil, fmt.Errorf("zip has no files for module %s", hint)
+	}
+	return hint, entries, nil
+}
+
+func extractZipEntries(zipBytes []byte, entries []zipEntry, destDir string) error {
+	_ = zipBytes // entries already hold openable *zip.File from the same buffer
+	for _, e := range entries {
+		target := filepath.Join(destDir, filepath.FromSlash(e.Rel))
+		// Zip-slip: ensure target stays under destDir.
+		if !isUnder(destDir, target) {
+			return fmt.Errorf("zip slip: %s", e.Rel)
+		}
+		if e.File.FileInfo().IsDir() || strings.HasSuffix(e.Rel, "/") {
+			if err := os.MkdirAll(target, 0o755); err != nil {
+				return err
+			}
+			continue
+		}
+		if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+			return err
+		}
+		rc, err := e.File.Open()
+		if err != nil {
+			return err
+		}
+		mode := e.File.Mode()
+		if mode&0o111 != 0 {
+			mode = 0o755
+		} else {
+			mode = 0o644
+		}
+		err = copyToFile(target, rc, mode)
+		_ = rc.Close()
+		if err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+func isUnder(root, path string) bool {
+	absRoot, err1 := filepath.Abs(root)
+	absPath, err2 := filepath.Abs(path)
+	if err1 != nil || err2 != nil {
+		return false
+	}
+	rel, err := filepath.Rel(absRoot, absPath)
+	if err != nil {
+		return false
+	}
+	return rel == "." || (!strings.HasPrefix(rel, "..") && !filepath.IsAbs(rel))
+}
+
+func copyToFile(dest string, r io.Reader, mode os.FileMode) error {
+	tmp := dest + ".partial"
+	f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
+	if err != nil {
+		return err
+	}
+	_, copyErr := io.Copy(f, r)
+	closeErr := f.Close()
+	if copyErr != nil {
+		_ = os.Remove(tmp)
+		return copyErr
+	}
+	if closeErr != nil {
+		_ = os.Remove(tmp)
+		return closeErr
+	}
+	_ = os.Remove(dest)
+	return os.Rename(tmp, dest)
+}
+
+func promoteHostBinary(modDir, name string) error {
+	want := name
+	if runtime.GOOS == "windows" {
+		want += ".exe"
+	}
+	dest := filepath.Join(modDir, ".bin", want)
+	if fileExists(dest) {
+		return nil
+	}
+	archDir := filepath.Join(modDir, ".bin", runtime.GOOS+"-"+runtime.GOARCH)
+	src := filepath.Join(archDir, want)
+	if !fileExists(src) {
+		// Soft: describe may fail later; zip install still succeeds.
+		return nil
+	}
+	if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+		return err
+	}
+	in, err := os.Open(src)
+	if err != nil {
+		return err
+	}
+	defer in.Close()
+	return copyToFile(dest, in, 0o755)
+}
+
+func detectArches(modDir, name string) []string {
+	binRoot := filepath.Join(modDir, ".bin")
+	ents, err := os.ReadDir(binRoot)
+	if err != nil {
+		return nil
+	}
+	seen := map[string]struct{}{}
+	var arches []string
+	add := func(a string) {
+		if _, ok := seen[a]; ok {
+			return
+		}
+		seen[a] = struct{}{}
+		arches = append(arches, a)
+	}
+	for _, e := range ents {
+		if e.IsDir() {
+			sub := e.Name() // e.g. windows-amd64
+			if strings.Contains(sub, "-") {
+				add(sub)
+			}
+			continue
+		}
+		base := strings.TrimSuffix(e.Name(), ".exe")
+		if base == name {
+			add(runtime.GOOS + "-" + runtime.GOARCH)
+		}
+	}
+	sort.Strings(arches)
+	return arches
+}
+
+func (s *Store) readManifest(dir string) (Manifest, error) {
+	var m Manifest
+	b, err := os.ReadFile(filepath.Join(dir, manifestName))
+	if err != nil {
+		return m, err
+	}
+	if err := json.Unmarshal(b, &m); err != nil {
+		return m, err
+	}
+	return m, nil
+}
+
+func (s *Store) writeManifest(dir string, m Manifest) error {
+	b, err := json.MarshalIndent(m, "", "  ")
+	if err != nil {
+		return err
+	}
+	b = append(b, '\n')
+	return atomicWrite(filepath.Join(dir, manifestName), b, 0o644)
+}
+
+func atomicWrite(path string, data []byte, mode os.FileMode) error {
+	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+		return err
+	}
+	tmp := path + ".tmp"
+	if err := os.WriteFile(tmp, data, mode); err != nil {
+		return err
+	}
+	if err := os.Rename(tmp, path); err != nil {
+		_ = os.Remove(tmp)
+		return err
+	}
+	return nil
+}
+
+func fileSHA256(path string) (string, error) {
+	f, err := os.Open(path)
+	if err != nil {
+		return "", err
+	}
+	defer f.Close()
+	h := sha256.New()
+	if _, err := io.Copy(h, f); err != nil {
+		return "", err
+	}
+	return hex.EncodeToString(h.Sum(nil)), nil
+}
+
+func fileExists(p string) bool {
+	st, err := os.Stat(p)
+	return err == nil && !st.IsDir()
+}
diff --git a/apps/streamd/internal/modstore/modstore_test.go b/apps/streamd/internal/modstore/modstore_test.go
new file mode 100644
index 0000000..edb3096
--- /dev/null
+++ b/apps/streamd/internal/modstore/modstore_test.go
@@ -0,0 +1,149 @@
+package modstore
+
+import (
+	"archive/zip"
+	"bytes"
+	"os"
+	"path/filepath"
+	"runtime"
+	"strings"
+	"testing"
+)
+
+func makeZip(t *testing.T, files map[string][]byte) []byte {
+	t.Helper()
+	var buf bytes.Buffer
+	zw := zip.NewWriter(&buf)
+	for name, body := range files {
+		w, err := zw.Create(name)
+		if err != nil {
+			t.Fatal(err)
+		}
+		if _, err := w.Write(body); err != nil {
+			t.Fatal(err)
+		}
+	}
+	if err := zw.Close(); err != nil {
+		t.Fatal(err)
+	}
+	return buf.Bytes()
+}
+
+func TestInstallZipFlatAndYAMLOnly(t *testing.T) {
+	root := t.TempDir()
+	s := New(root)
+
+	arch := runtime.GOOS + "-" + runtime.GOARCH
+	binName := "demo"
+	if runtime.GOOS == "windows" {
+		binName += ".exe"
+	}
+	zipBytes := makeZip(t, map[string][]byte{
+		"module.yaml":                         []byte("package: com.example\nchannels: {}\n"),
+		".bin/" + arch + "/" + binName:        []byte("fake-binary"),
+		".bin/linux-amd64/demo":               []byte("linux-bin"),
+	})
+
+	info, err := s.InstallZip(zipBytes, "demo")
+	if err != nil {
+		t.Fatalf("InstallZip: %v", err)
+	}
+	if info.Name != "demo" || !info.HasYAML || !info.HasPackage {
+		t.Fatalf("info = %+v", info)
+	}
+	if info.PackageSHA256 == "" || info.YAMLSHA256 == "" {
+		t.Fatalf("missing hashes: %+v", info)
+	}
+	pkgHash := info.PackageSHA256
+	yamlHash := info.YAMLSHA256
+
+	// Host binary should be promoted.
+	promoted := filepath.Join(root, "demo", ".bin", binName)
+	if !fileExists(promoted) {
+		t.Fatalf("expected promoted binary at %s", promoted)
+	}
+
+	// YAML-only update must not change package hash.
+	info2, err := s.WriteYAML("demo", []byte("package: com.example\nchannels:\n  one: {label: One}\n"))
+	if err != nil {
+		t.Fatalf("WriteYAML: %v", err)
+	}
+	if info2.PackageSHA256 != pkgHash {
+		t.Fatalf("package hash changed on yaml edit: %s -> %s", pkgHash, info2.PackageSHA256)
+	}
+	if info2.YAMLSHA256 == yamlHash {
+		t.Fatal("yaml hash should change after edit")
+	}
+
+	raw, err := s.ReadYAML("demo")
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !strings.Contains(string(raw), "one:") {
+		t.Fatalf("yaml not updated: %s", raw)
+	}
+
+	f, size, err := s.OpenPackage("demo")
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer f.Close()
+	if size != int64(len(zipBytes)) {
+		t.Fatalf("package size %d want %d", size, len(zipBytes))
+	}
+}
+
+func TestInstallZipTopLevelFolder(t *testing.T) {
+	root := t.TempDir()
+	s := New(root)
+	zipBytes := makeZip(t, map[string][]byte{
+		"bbc/module.yaml":              []byte("package: bbc.iplayer.android\n"),
+		"bbc/.bin/linux-amd64/bbc":     []byte("bin"),
+		"bbc/.bin/windows-amd64/bbc.exe": []byte("winbin"),
+	})
+	info, err := s.InstallZip(zipBytes, "")
+	if err != nil {
+		t.Fatalf("InstallZip: %v", err)
+	}
+	if info.Name != "bbc" {
+		t.Fatalf("name=%q", info.Name)
+	}
+	list, err := s.List()
+	if err != nil || len(list) != 1 || list[0].Name != "bbc" {
+		t.Fatalf("list=%v err=%v", list, err)
+	}
+}
+
+func TestZipSlipRejected(t *testing.T) {
+	root := t.TempDir()
+	s := New(root)
+	var buf bytes.Buffer
+	zw := zip.NewWriter(&buf)
+	w, err := zw.Create("../evil.yaml")
+	if err != nil {
+		t.Fatal(err)
+	}
+	_, _ = w.Write([]byte("x"))
+	_ = zw.Close()
+	_, err = s.InstallZip(buf.Bytes(), "demo")
+	if err == nil {
+		t.Fatal("expected zip-slip error")
+	}
+}
+
+func TestDelete(t *testing.T) {
+	root := t.TempDir()
+	s := New(root)
+	zipBytes := makeZip(t, map[string][]byte{
+		"module.yaml": []byte("package: x\n"),
+	})
+	if _, err := s.InstallZip(zipBytes, "xmod"); err != nil {
+		t.Fatal(err)
+	}
+	if err := s.Delete("xmod"); err != nil {
+		t.Fatal(err)
+	}
+	if _, err := os.Stat(filepath.Join(root, "xmod")); !os.IsNotExist(err) {
+		t.Fatalf("dir still present: %v", err)
+	}
+}
diff --git a/apps/streamd/internal/scheduler/scheduler.go b/apps/streamd/internal/scheduler/scheduler.go
index c8c40cf..fa0b2e2 100644
--- a/apps/streamd/internal/scheduler/scheduler.go
+++ b/apps/streamd/internal/scheduler/scheduler.go
@@ -6,7 +6,7 @@ import (
 	"log/slog"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/db"
 )
 
 // Supervisor is the subset of the media supervisor the scheduler needs.
diff --git a/apps/streamd/internal/supervisor/appdefaults.go b/apps/streamd/internal/supervisor/appdefaults.go
index 24725bd..dd0440a 100644
--- a/apps/streamd/internal/supervisor/appdefaults.go
+++ b/apps/streamd/internal/supervisor/appdefaults.go
@@ -3,10 +3,10 @@ package supervisor
 import (
 	"strings"
 
-	"drmdecryption/app"
-	"drmdecryption/apps/streamd/internal/db"
-	"drmdecryption/modhost"
-	"drmdecryption/repo"
+	"streamd/app"
+	"streamd/apps/streamd/internal/db"
+	"streamd/modhost"
+	"streamd/repo"
 )
 
 // streamSettings are the downloader and packager knobs for one stream. They
diff --git a/apps/streamd/internal/supervisor/appdefaults_test.go b/apps/streamd/internal/supervisor/appdefaults_test.go
index f41eb39..ee1feca 100644
--- a/apps/streamd/internal/supervisor/appdefaults_test.go
+++ b/apps/streamd/internal/supervisor/appdefaults_test.go
@@ -3,11 +3,11 @@ package supervisor
 import (
 	"testing"
 
-	"drmdecryption/adb"
-	"drmdecryption/app"
-	"drmdecryption/apps/streamd/internal/db"
-	"drmdecryption/capture"
-	"drmdecryption/mpd"
+	"streamd/adb"
+	"streamd/app"
+	"streamd/apps/streamd/internal/db"
+	"streamd/capture"
+	"streamd/mpd"
 )
 
 // fakeApp stands in for a compiled-in app module: the supervisor must take its
diff --git a/apps/streamd/internal/supervisor/ffmpeg_integration_test.go b/apps/streamd/internal/supervisor/ffmpeg_integration_test.go
index dcbcf8b..c333c44 100644
--- a/apps/streamd/internal/supervisor/ffmpeg_integration_test.go
+++ b/apps/streamd/internal/supervisor/ffmpeg_integration_test.go
@@ -10,7 +10,7 @@ import (
 	"testing"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/db"
 )
 
 // These tests run the real ffmpeg against the real generated command line.
diff --git a/apps/streamd/internal/supervisor/media.go b/apps/streamd/internal/supervisor/media.go
index cc14d53..91aa7c0 100644
--- a/apps/streamd/internal/supervisor/media.go
+++ b/apps/streamd/internal/supervisor/media.go
@@ -14,10 +14,10 @@ import (
 	"sync"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/db"
-	"drmdecryption/apps/streamd/internal/logfile"
-	"drmdecryption/apps/streamd/internal/tsfanout"
-	"drmdecryption/mpd"
+	"streamd/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/logfile"
+	"streamd/apps/streamd/internal/tsfanout"
+	"streamd/mpd"
 )
 
 // Media runs N_m3u8DL-RE plus one ffmpeg packager per variant, publishing into
diff --git a/apps/streamd/internal/supervisor/outputs.go b/apps/streamd/internal/supervisor/outputs.go
index 12d443f..0a2457e 100644
--- a/apps/streamd/internal/supervisor/outputs.go
+++ b/apps/streamd/internal/supervisor/outputs.go
@@ -6,7 +6,7 @@ import (
 	"strconv"
 	"strings"
 
-	"drmdecryption/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/db"
 )
 
 // Packager defaults. These were literals in the ffmpeg command line before
diff --git a/apps/streamd/internal/supervisor/outputs_test.go b/apps/streamd/internal/supervisor/outputs_test.go
index 76c4000..c4e6a92 100644
--- a/apps/streamd/internal/supervisor/outputs_test.go
+++ b/apps/streamd/internal/supervisor/outputs_test.go
@@ -4,7 +4,7 @@ import (
 	"strings"
 	"testing"
 
-	"drmdecryption/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/db"
 )
 
 // quote and backslash as values, so the test source stays readable where it
diff --git a/apps/streamd/internal/supervisor/stub.go b/apps/streamd/internal/supervisor/stub.go
index 58eef69..609c0ee 100644
--- a/apps/streamd/internal/supervisor/stub.go
+++ b/apps/streamd/internal/supervisor/stub.go
@@ -5,7 +5,7 @@ import (
 	"sync"
 	"time"
 
-	"drmdecryption/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/db"
 )
 
 // Stub marks streams as starting/stopped without spawning media workers.
diff --git a/apps/streamd/internal/supervisor/variants.go b/apps/streamd/internal/supervisor/variants.go
index 324786d..ebf925d 100644
--- a/apps/streamd/internal/supervisor/variants.go
+++ b/apps/streamd/internal/supervisor/variants.go
@@ -9,8 +9,8 @@ import (
 	"sort"
 	"strings"
 
-	"drmdecryption/apps/streamd/internal/db"
-	"drmdecryption/apps/streamd/internal/logfile"
+	"streamd/apps/streamd/internal/db"
+	"streamd/apps/streamd/internal/logfile"
 )
 
 type variantProc struct {
diff --git a/apps/streamd/internal/ui/index.html b/apps/streamd/internal/ui/index.html
index 4121147..c425196 100644
--- a/apps/streamd/internal/ui/index.html
+++ b/apps/streamd/internal/ui/index.html
@@ -26,6 +26,10 @@
           
           Streams
         
+        
+          
+          Modules
+        
         
           
           Schedule
@@ -81,7 +85,7 @@
     

Sign in to streamd

-

Null DRM restream control

+

Streamd control plane

Download $Tag" ) } + $channelLine = "" + if ($Channel) { + $channelLine = $nl + "Rolling channel: $Channel -> $( & $code "$RepoUrl/releases/download/$Channel/streamd-..." )" + } return ( "$Title" + $nl + - "Host CLI ($( & $code 'drm' )) + on-device MITM ($( & $code 'proxy-android-arm64' ))." + $nl + $nl + + "Host CLI ($( & $code 'streamd' ); $( & $code 'drm' ) compat copy) + on-device MITM ($( & $code 'proxy-android-arm64' ))." + + $channelLine + $nl + $nl + "Download $Tag" ) } @@ -83,7 +95,7 @@ if (-not $Body) { if ($env:RELEASE_BODY) { $Body = $env:RELEASE_BODY } else { - $Body = New-TelegramBody -Kind $Kind -Title $Title -Tag $Tag -ReleaseUrl $ReleaseUrl + $Body = New-TelegramBody -Kind $Kind -Title $Title -Tag $Tag -ReleaseUrl $ReleaseUrl -RepoUrl $RepoUrl -Channel $Channel } } diff --git a/scripts/notify-telegram.sh b/scripts/notify-telegram.sh index 91e790c..a509769 100644 --- a/scripts/notify-telegram.sh +++ b/scripts/notify-telegram.sh @@ -49,10 +49,28 @@ fi REPO_URL="${RELEASE_REPO_URL:-https://git.nulldrm.com/nulldrm/Null-DRM-Official}" URL="${RELEASE_URL:-${REPO_URL}/releases/tag/${TAG}}" +CHANNEL="${RELEASE_CHANNEL:-}" +if [[ -z "$CHANNEL" ]]; then + case "$TAG" in + v[0-9]*.[0-9]*.[0-9]) CHANNEL="stable" ;; + v[0-9]*.[0-9]*.[0-9]-*) CHANNEL="beta" ;; + esac +fi + if [[ -n "${RELEASE_TITLE:-}" ]]; then TITLE="$RELEASE_TITLE" +elif [[ "$CHANNEL" == "beta" ]]; then + TITLE="Streamd ${TAG} (beta)" else - TITLE="Null DRM ${TAG}" + TITLE="Streamd ${TAG}" +fi + +CHANNEL_URL="" +CHANNEL_LINE="" +if [[ -n "$CHANNEL" && "$KIND" == "host" ]]; then + CHANNEL_URL="${REPO_URL}/releases/download/${CHANNEL}" + CHANNEL_LINE=" +Rolling channel: ${CHANNEL} -> ${CHANNEL_URL}/streamd-..." fi if [[ -n "${RELEASE_BODY:-}" ]]; then @@ -61,16 +79,16 @@ elif [[ "$KIND" == "modules" ]]; then BODY="${TITLE} Provider module zips: bbc.zip, rte.zip, tg4.zip, itv.zip, c4.zip, my5.zip -Unpack each into modules/<name>/ and edit module.yaml for secrets. +Upload in the streamd Modules page, or unpack into modules/<name>/ and edit module.yaml. Download ${TAG}" else BODY="${TITLE} -Host CLI (drm) + on-device MITM (proxy-android-arm64). +Host CLI (streamd; drm compat copy) + on-device MITM (proxy-android-arm64). +${CHANNEL_LINE} Download ${TAG}" fi - if [[ "${DRY_RUN:-}" == "1" ]]; then echo "DRY_RUN chat=$CHAT thread=${THREAD:-} tag=$TAG kind=$KIND" echo "----" diff --git a/www/index.html b/www/index.html index 8e26ba3..aaf4065 100644 --- a/www/index.html +++ b/www/index.html @@ -63,9 +63,9 @@ - drm capture — rteone + streamd capture — rteone -
PS C:\DRM-Decryption> ./bin/drm capture --app rte --channel rteone --auto-play
+
PS C:\DRM-Decryption> ./bin/streamd capture --app rte --channel rteone --auto-play
 [*] Stopping any old appproxy...
 [*] Pushing appproxy...
 20:30:45 CA cert: /data/local/tmp/appproxy-ca.crt
@@ -191,16 +191,16 @@
 
 
# 1. build the one binary
 git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official
-go -C apps/cli build -o ../../bin/drm .
+go -C apps/cli build -o ../../bin/streamd .
 
 # 2. the CDM helper
 python -m venv .venv && .venv/bin/pip install -r apps/wvkey/requirements.txt
 
 # 3. see which app modules are compiled in
-./bin/drm modules
+./bin/streamd modules
 
 # 4. capture a channel
-./bin/drm capture --app rte --channel rteone --auto-play --wvd data/device.wvd
+./bin/streamd capture --app rte --channel rteone --auto-play --wvd data/device.wvd

A fresh clone ships no account ids, keys or hostnames — module code is public, @@ -227,27 +227,27 @@ python -m venv .venv && .venv/bin/pip install -r apps/wvkey/requirements - drm capture + streamd capture Drives the phone through the on-device proxy and writes a session: manifest, PSSH, keys. - drm catalog + streamd catalog Resolves a channel from a public playback catalogue, no phone involved. - drm serve + streamd serve Control plane: REST API, SQLite, dashboard, and the restream supervisor. - drm agent + streamd agent Polls the control plane, claims a free phone and refreshes dead channels. - drm proxy + streamd proxy Builds and installs the on-device HTTPS proxy, and records unknown apps. - drm modules + streamd modules Lists the app modules this build contains and where each one reads its values. From 8fc7e4c0b885061c6e99114ed5e5f03d01c95c1f Mon Sep 17 00:00:00 2001 From: 404errordeveloper Date: Sat, 10 Oct 2026 18:05:51 +0200 Subject: [PATCH 2/5] streamd: serve start/stop/update, streamd.yaml, egress, module panel fixes - Add streamd serve start|stop|restart|status|update with auto-written streamd.yaml - Panel modules: STREAMD_MODULES_DIR for describe, YAML channel fallback, textarea value fix - Per-stream WireGuard/SOCKS egress profiles + Settings UI - Drop drm-* from release builds; track streamd-bg.sh / streamd-update.sh wrappers - Docs: streamd-server-setup lifecycle and update flow --- .forgejo/workflows/release.yml | 5 +- .gitignore | 4 +- README.md | 2 +- apps/cli/main.go | 6 +- apps/pkg/bootstrap/bootstrap.go | 6 +- apps/pkg/modcfg/modcfg.go | 43 +- apps/pkg/modhost/exec.go | 31 ++ apps/pkg/modhost/exec_test.go | 31 ++ apps/pkg/modhost/root.go | 28 +- apps/pkg/modhost/root_test.go | 39 ++ apps/streamd/README.md | 4 +- apps/streamd/go.mod | 2 + apps/streamd/go.sum | 3 + apps/streamd/internal/api/api.go | 7 + apps/streamd/internal/api/apps.go | 68 ++- apps/streamd/internal/api/apps_test.go | 45 ++ apps/streamd/internal/api/control.go | 17 +- apps/streamd/internal/api/egress.go | 254 +++++++++++ apps/streamd/internal/api/modules.go | 8 + apps/streamd/internal/db/db.go | 32 +- apps/streamd/internal/db/egress.go | 226 ++++++++++ apps/streamd/internal/db/egress_test.go | 117 +++++ apps/streamd/internal/egress/conf.go | 80 ++++ apps/streamd/internal/egress/manager.go | 401 ++++++++++++++++++ apps/streamd/internal/egress/manager_test.go | 100 +++++ apps/streamd/internal/egress/wg_linux.go | 262 ++++++++++++ apps/streamd/internal/egress/wg_stub.go | 19 + apps/streamd/internal/modstore/modstore.go | 62 ++- .../internal/modstore/modstore_test.go | 21 + apps/streamd/internal/supervisor/media.go | 65 ++- apps/streamd/internal/ui/static/js/api.js | 14 + apps/streamd/internal/ui/static/js/util.js | 5 + .../internal/ui/static/js/views/admin.js | 174 ++++++++ .../internal/ui/static/js/views/modules.js | 8 +- .../ui/static/js/views/stream-form.js | 24 +- .../internal/ui/static/js/views/stream.js | 22 +- apps/streamd/servecmd/config.go | 336 +++++++++++++++ apps/streamd/servecmd/config_test.go | 101 +++++ apps/streamd/servecmd/daemon.go | 200 +++++++++ apps/streamd/servecmd/daemon_unix.go | 37 ++ apps/streamd/servecmd/daemon_windows.go | 46 ++ apps/streamd/servecmd/data_dir_test.go | 71 ++++ apps/streamd/servecmd/servecmd.go | 382 ++++++++++++++--- apps/streamd/servecmd/update.go | 243 +++++++++++ apps/streamd/servecmd/update_unix.go | 22 + apps/streamd/servecmd/update_windows.go | 123 ++++++ docs/examples/streamd.yaml | 19 + docs/release.md | 2 +- docs/releases/v0.2.0.md | 5 +- docs/streamd-server-setup.md | 312 +++++++++++--- docs/streamd.md | 23 +- scripts/build-release.ps1 | 15 +- scripts/build-release.sh | 31 +- scripts/notify-telegram.ps1 | 2 +- scripts/notify-telegram.sh | 2 +- scripts/streamd-bg.sh | 69 +++ scripts/streamd-update.sh | 12 + 57 files changed, 4031 insertions(+), 257 deletions(-) create mode 100644 apps/pkg/modhost/exec_test.go create mode 100644 apps/pkg/modhost/root_test.go create mode 100644 apps/streamd/internal/api/apps_test.go create mode 100644 apps/streamd/internal/api/egress.go create mode 100644 apps/streamd/internal/db/egress.go create mode 100644 apps/streamd/internal/db/egress_test.go create mode 100644 apps/streamd/internal/egress/conf.go create mode 100644 apps/streamd/internal/egress/manager.go create mode 100644 apps/streamd/internal/egress/manager_test.go create mode 100644 apps/streamd/internal/egress/wg_linux.go create mode 100644 apps/streamd/internal/egress/wg_stub.go create mode 100644 apps/streamd/servecmd/config.go create mode 100644 apps/streamd/servecmd/config_test.go create mode 100644 apps/streamd/servecmd/daemon.go create mode 100644 apps/streamd/servecmd/daemon_unix.go create mode 100644 apps/streamd/servecmd/daemon_windows.go create mode 100644 apps/streamd/servecmd/data_dir_test.go create mode 100644 apps/streamd/servecmd/update.go create mode 100644 apps/streamd/servecmd/update_unix.go create mode 100644 apps/streamd/servecmd/update_windows.go create mode 100644 docs/examples/streamd.yaml create mode 100644 scripts/streamd-bg.sh create mode 100644 scripts/streamd-update.sh diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index d534396..fc1d1ba 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -1,4 +1,4 @@ -# Build multi-platform streamd (+ drm compat) binaries + Android MITM and attach them to a Forgejo release. +# Build multi-platform streamd binaries + Android MITM and attach them to a Forgejo release. # # Triggers: # Stable: git tag v1.2.3 && git push origin v1.2.3 @@ -90,8 +90,6 @@ jobs: Channel: **${CHANNEL}** (rolling download tag \`${CHANNEL}\` also updated). - Prefer \`streamd-*\`. Matching \`drm-*\` files are identical compatibility copies for this release. - | Asset | Platform | |---|---| | \`streamd-windows-amd64.exe\` | Windows x86_64 | @@ -100,7 +98,6 @@ jobs: | \`streamd-linux-arm64\` | Linux ARM64 | | \`streamd-darwin-amd64\` | macOS Intel | | \`streamd-darwin-arm64\` | macOS Apple Silicon | - | \`drm-*\` | Same bytes as the matching \`streamd-*\` (compat) | | \`proxy-android-arm64\` | On-device MITM (push with \`streamd proxy\`) | | \`SHA256SUMS.txt\` | Checksums | diff --git a/.gitignore b/.gitignore index b91b24c..c8832a5 100644 --- a/.gitignore +++ b/.gitignore @@ -218,7 +218,7 @@ apps/proxy/proxy-android-arm64 apps/proxy/rteproxy-android-arm64 # local / VPS deploy + operator scripts (test stuff; keep out of git) deploy/ -# Ignore local scripts, but keep the release builders tracked for Forgejo Actions. +# Ignore local scripts, but keep release builders + server helpers tracked. scripts/* !scripts/build-release.sh !scripts/build-release.ps1 @@ -226,6 +226,8 @@ scripts/* !scripts/build-modules-release.ps1 !scripts/notify-telegram.sh !scripts/notify-telegram.ps1 +!scripts/streamd-bg.sh +!scripts/streamd-update.sh # Shared library packages under apps/modules/ (imported by external module CLIs). # module.yaml stays local; module-publish.yaml is the tracked universal template. apps/modules/** diff --git a/README.md b/README.md index c12d14d..7867424 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ Pinned install: swap `stable` / `beta` for a concrete tag such as `v0.1.5` or `v ```text Streamd/ - streamd.exe # or ./streamd on Linux/macOS (drm.exe also shipped as a compat copy) + streamd.exe # or ./streamd on Linux/macOS bin/proxy-android-arm64 # optional; also embedded in the release binary modules/ # or upload zips in the streamd Modules page bbc/ # unzip bbc.zip here diff --git a/apps/cli/main.go b/apps/cli/main.go index 37d6475..802c7fb 100644 --- a/apps/cli/main.go +++ b/apps/cli/main.go @@ -2,7 +2,6 @@ // catalog lookups, the always-on agent, the streamd control plane and the // on-device MITM. Providers live under modules// and are discovered, // built, and executed by the host — they are not linked into this binary. -// A drm.exe copy of this binary is still shipped for one release as a compat alias. package main import ( @@ -110,7 +109,8 @@ Usage: streamd [--modules-dir DIR] capture --app NAME [--channel ID | --all] [--wvd PATH] streamd [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json] streamd agent run|status|devices|enqueue|cancel [--config …] - streamd serve [--bind …] [--data …] [--token …] + streamd serve start|stop|restart|status|update|run [flags] + streamd serve [--bind …] [--data …] # foreground (same as run) streamd proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent Global flags: @@ -120,8 +120,6 @@ Providers live under modules// (Go source + module-publish.yaml). Local module.yaml holds secrets and is never published; release zips ship module-publish.yaml renamed to module.yaml. The host builds modules on demand. -A drm binary may still be shipped as an identical compatibility copy. - Run any subcommand with --help for its own flags. `) } diff --git a/apps/pkg/bootstrap/bootstrap.go b/apps/pkg/bootstrap/bootstrap.go index 86f4d5d..52ff36b 100644 --- a/apps/pkg/bootstrap/bootstrap.go +++ b/apps/pkg/bootstrap/bootstrap.go @@ -92,7 +92,6 @@ func Ensure(root string) (created []string, err error) { } // If streamd is not already under bin/, copy it there for 1:1 layout. - // Also keep a drm.exe compat copy for one release when missing. if err := ensureBinHost(root); err != nil { return created, err } @@ -105,10 +104,7 @@ func ensureBinHost(root string) error { return nil } exe, _ = filepath.EvalSymlinks(exe) - if err := copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe")); err != nil { - return err - } - return copyExeIfMissing(exe, filepath.Join(root, "bin", "drm.exe")) + return copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe")) } func copyExeIfMissing(src, dest string) error { diff --git a/apps/pkg/modcfg/modcfg.go b/apps/pkg/modcfg/modcfg.go index 371e621..5868a55 100644 --- a/apps/pkg/modcfg/modcfg.go +++ b/apps/pkg/modcfg/modcfg.go @@ -21,7 +21,8 @@ import ( ) // Dir returns the directory holding a module's values. -// Prefers the active modules dir (see modhost / --modules-dir); falls back to +// Prefers the active modules dir (see modhost / --modules-dir); then the +// directory beside a panel/release binary (/.bin/); then // apps/modules// for older checkouts. func Dir(name string) string { preferred := filepath.Join(modhost.ModulesDir(""), name) @@ -31,6 +32,9 @@ func Dir(name string) string { if modhost.ModulesDirOverride() != "" { return preferred } + if beside := dirBesideExecutable(name); beside != "" { + return beside + } root := repo.Root() if _, err := os.Stat(filepath.Join(root, "modules")); err == nil { return filepath.Join(root, "modules", name) @@ -38,6 +42,43 @@ func Dir(name string) string { return filepath.Join(root, "apps", "modules", name) } +// dirBesideExecutable finds module.yaml next to a panel/release binary layout: +// /.bin/[.exe] +// /.bin/-/[.exe] +func dirBesideExecutable(name string) string { + exe, err := os.Executable() + if err != nil { + return "" + } + if resolved, err := filepath.EvalSymlinks(exe); err == nil { + exe = resolved + } + base := strings.TrimSuffix(filepath.Base(exe), ".exe") + if !strings.EqualFold(base, name) { + return "" + } + binDir := filepath.Dir(exe) + candidates := []string{} + if strings.EqualFold(filepath.Base(binDir), ".bin") { + candidates = append(candidates, filepath.Dir(binDir)) + } + parent := filepath.Dir(binDir) + if strings.EqualFold(filepath.Base(parent), ".bin") { + candidates = append(candidates, filepath.Dir(parent)) + } + for _, dir := range candidates { + if fileExists(filepath.Join(dir, "module.yaml")) || fileExists(filepath.Join(dir, "module-publish.yaml")) { + return dir + } + } + return "" +} + +func fileExists(p string) bool { + st, err := os.Stat(p) + return err == nil && !st.IsDir() +} + // Path returns the preferred values file path (module.yaml). func Path(name string) string { return filepath.Join(Dir(name), "module.yaml") diff --git a/apps/pkg/modhost/exec.go b/apps/pkg/modhost/exec.go index 57d1beb..8b19720 100644 --- a/apps/pkg/modhost/exec.go +++ b/apps/pkg/modhost/exec.go @@ -9,9 +9,39 @@ import ( "strings" ) +// prepareModuleCmd sets STREAMD_MODULES_DIR so child module binaries load +// panel-store module.yaml. Module builds that call EffectiveModulesDir (or +// ApplyEnvModulesDir) honour this; /api/apps also falls back to parsing the +// panel module.yaml when describe returns no channels. +func prepareModuleCmd(cmd *exec.Cmd) { + ov := ModulesDirOverride() + if ov == "" { + return + } + cmd.Env = append(withoutEnvKeys(os.Environ(), "STREAMD_MODULES_DIR", "DRM_MODULES_DIR"), + "STREAMD_MODULES_DIR="+ov) +} + +func withoutEnvKeys(env []string, keys ...string) []string { + drop := map[string]struct{}{} + for _, k := range keys { + drop[strings.ToUpper(k)] = struct{}{} + } + out := make([]string, 0, len(env)) + for _, e := range env { + key, _, _ := strings.Cut(e, "=") + if _, skip := drop[strings.ToUpper(key)]; skip { + continue + } + out = append(out, e) + } + return out +} + // Run executes the module binary with args, inheriting stdout/stderr. func Run(bin string, args ...string) error { cmd := exec.Command(bin, args...) + prepareModuleCmd(cmd) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin @@ -24,6 +54,7 @@ func Run(bin string, args ...string) error { // RunOutput executes the module binary and returns combined stdout. func RunOutput(bin string, args ...string) (string, error) { cmd := exec.Command(bin, args...) + prepareModuleCmd(cmd) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr diff --git a/apps/pkg/modhost/exec_test.go b/apps/pkg/modhost/exec_test.go new file mode 100644 index 0000000..ae7c842 --- /dev/null +++ b/apps/pkg/modhost/exec_test.go @@ -0,0 +1,31 @@ +package modhost + +import ( + "os" + "os/exec" + "path/filepath" + "testing" +) + +func TestPrepareModuleCmdSetsEnv(t *testing.T) { + t.Cleanup(func() { _ = SetModulesDir("") }) + ov := filepath.Join(t.TempDir(), "modules") + if err := os.MkdirAll(ov, 0o755); err != nil { + t.Fatal(err) + } + if err := SetModulesDir(ov); err != nil { + t.Fatal(err) + } + cmd := exec.Command("true") + prepareModuleCmd(cmd) + found := false + for _, e := range cmd.Env { + if e == "STREAMD_MODULES_DIR="+ov { + found = true + break + } + } + if !found { + t.Fatalf("STREAMD_MODULES_DIR missing in env: %v", cmd.Env) + } +} diff --git a/apps/pkg/modhost/root.go b/apps/pkg/modhost/root.go index f796db6..9da5fd3 100644 --- a/apps/pkg/modhost/root.go +++ b/apps/pkg/modhost/root.go @@ -3,6 +3,7 @@ package modhost import ( "os" "path/filepath" + "strings" "sync" "streamd/repo" @@ -37,12 +38,32 @@ func ModulesDirOverride() string { return modulesDirOV } +// envModulesDir returns STREAMD_MODULES_DIR (preferred) or DRM_MODULES_DIR. +func envModulesDir() string { + v := strings.TrimSpace(os.Getenv("STREAMD_MODULES_DIR")) + if v == "" { + v = strings.TrimSpace(os.Getenv("DRM_MODULES_DIR")) + } + if v == "" { + return "" + } + if abs, err := filepath.Abs(v); err == nil { + return abs + } + return v +} + // EffectiveModulesDir is the directory that Discover/Open scan. -// Prefer --modules-dir / STREAMD_MODULES_DIR / DRM_MODULES_DIR; else /modules. +// Prefer --modules-dir, then STREAMD_MODULES_DIR / DRM_MODULES_DIR, else /modules. +// Module binaries read the env here directly so they honour the panel store even +// when they never call ApplyEnvModulesDir. func EffectiveModulesDir(root string) string { if ov := ModulesDirOverride(); ov != "" { return ov } + if v := envModulesDir(); v != "" { + return v + } if root == "" { root = repo.Root() } @@ -55,10 +76,7 @@ func ApplyEnvModulesDir() error { if ModulesDirOverride() != "" { return nil } - v := os.Getenv("STREAMD_MODULES_DIR") - if v == "" { - v = os.Getenv("DRM_MODULES_DIR") - } + v := envModulesDir() if v == "" { return nil } diff --git a/apps/pkg/modhost/root_test.go b/apps/pkg/modhost/root_test.go new file mode 100644 index 0000000..d653914 --- /dev/null +++ b/apps/pkg/modhost/root_test.go @@ -0,0 +1,39 @@ +package modhost + +import ( + "os" + "path/filepath" + "testing" +) + +func TestEffectiveModulesDirEnv(t *testing.T) { + t.Cleanup(func() { + _ = SetModulesDir("") + _ = os.Unsetenv("STREAMD_MODULES_DIR") + _ = os.Unsetenv("DRM_MODULES_DIR") + }) + _ = SetModulesDir("") + _ = os.Unsetenv("STREAMD_MODULES_DIR") + _ = os.Unsetenv("DRM_MODULES_DIR") + + dir := t.TempDir() + t.Setenv("STREAMD_MODULES_DIR", dir) + got := EffectiveModulesDir("") + want, _ := filepath.Abs(dir) + if got != want { + t.Fatalf("env modules dir: got %q want %q", got, want) + } + + override := filepath.Join(t.TempDir(), "override") + if err := os.MkdirAll(override, 0o755); err != nil { + t.Fatal(err) + } + if err := SetModulesDir(override); err != nil { + t.Fatal(err) + } + got = EffectiveModulesDir("") + want, _ = filepath.Abs(override) + if got != want { + t.Fatalf("flag overrides env: got %q want %q", got, want) + } +} diff --git a/apps/streamd/README.md b/apps/streamd/README.md index 20dfe6a..79994a8 100644 --- a/apps/streamd/README.md +++ b/apps/streamd/README.md @@ -17,7 +17,9 @@ apps/streamd/ ## Run ```bash -./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd +./bin/streamd serve --bind 127.0.0.1:8083 +# --data is optional: reuses existing .cache/streamd (cwd or next to the binary) +# or set STREAMD_DATA / pass --data explicitly ``` `--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any diff --git a/apps/streamd/go.mod b/apps/streamd/go.mod index ec97f71..d3a639e 100644 --- a/apps/streamd/go.mod +++ b/apps/streamd/go.mod @@ -6,6 +6,7 @@ require ( github.com/gorilla/websocket v1.5.3 modernc.org/sqlite v1.34.5 streamd v0.0.0 + gopkg.in/yaml.v3 v3.0.1 ) replace streamd => ../pkg @@ -17,6 +18,7 @@ require ( github.com/ncruces/go-strftime v0.1.9 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect golang.org/x/sys v0.42.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect modernc.org/libc v1.55.3 // indirect modernc.org/mathutil v1.6.0 // indirect modernc.org/memory v1.8.0 // indirect diff --git a/apps/streamd/go.sum b/apps/streamd/go.sum index 3dff215..077f977 100644 --- a/apps/streamd/go.sum +++ b/apps/streamd/go.sum @@ -19,6 +19,9 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw= golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= diff --git a/apps/streamd/internal/api/api.go b/apps/streamd/internal/api/api.go index 4408794..bf83790 100644 --- a/apps/streamd/internal/api/api.go +++ b/apps/streamd/internal/api/api.go @@ -13,6 +13,7 @@ import ( "streamd/apps/streamd/internal/auth" "streamd/apps/streamd/internal/db" "streamd/apps/streamd/internal/deps" + "streamd/apps/streamd/internal/egress" "streamd/apps/streamd/internal/httpx" "streamd/apps/streamd/internal/modstore" ) @@ -61,6 +62,7 @@ type Handler struct { Modules *modstore.Store // ModulesNotify is set when the hub supports module change pushes. ModulesNotify ModulesNotifier + Egress *egress.Manager Log *slog.Logger } @@ -70,6 +72,7 @@ func (h *Handler) Mount(mux *http.ServeMux) { mux.HandleFunc("/api/streams/", h.streamAction) mux.HandleFunc("/api/overview", h.overview) h.MountControl(mux) + h.MountEgress(mux) mux.HandleFunc("/api/apps", h.apps) mux.HandleFunc("/api/modules", h.modules) mux.HandleFunc("/api/modules/", h.modules) @@ -539,6 +542,7 @@ func changeNote(before, after db.Stream, in db.PatchStream) string { add("key", in.Key != nil && before.Key != after.Key) add("headers", in.HeadersJSON != nil && before.HeadersJSON != after.HeadersJSON) add("proxy", in.Proxy != nil && before.Proxy != after.Proxy) + add("egress", in.Egress != nil && before.Egress != after.Egress) add("variants", before.VariantsJSON != after.VariantsJSON) add("outputs", before.OutputsJSON != after.OutputsJSON) add("settings", before.SettingsJSON != after.SettingsJSON) @@ -570,6 +574,9 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool { if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) { return true } + if in.Egress != nil && strings.TrimSpace(before.Egress) != strings.TrimSpace(after.Egress) { + return true + } if in.VariantsJSON != nil || len(in.Variants) > 0 { if strings.TrimSpace(before.VariantsJSON) != strings.TrimSpace(after.VariantsJSON) { return true diff --git a/apps/streamd/internal/api/apps.go b/apps/streamd/internal/api/apps.go index 5b61afc..53b146d 100644 --- a/apps/streamd/internal/api/apps.go +++ b/apps/streamd/internal/api/apps.go @@ -2,8 +2,12 @@ package api import ( "net/http" + "sort" + + "gopkg.in/yaml.v3" "streamd/apps/streamd/internal/auth" + "streamd/apps/streamd/internal/modstore" "streamd/modhost" "streamd/mpd" "streamd/repo" @@ -44,13 +48,17 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) { for _, m := range mods { bin, err := modhost.EnsureBuilt(m) if err != nil { - out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}) + info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()} + h.fillChannelsFromStore(&info, m.Name) + out = append(out, info) h.logger().Warn("module describe skipped", "module", m.Name, "err", err) continue } d, err := modhost.RunDescribe(bin) if err != nil { - out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}) + info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()} + h.fillChannelsFromStore(&info, m.Name) + out = append(out, info) h.logger().Warn("module describe skipped", "module", m.Name, "err", err) continue } @@ -61,10 +69,14 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) { for _, ch := range d.Channels { info.Channels = append(info.Channels, channelInfo{ID: ch.ID, Label: ch.Label}) } - info.HasConfig = len(info.Channels) > 0 if d.Rewriter != "" { info.Rewriter = d.Rewriter } + // Older module binaries may not see the panel store; fill from module.yaml. + if len(info.Channels) == 0 { + h.fillChannelsFromStore(&info, m.Name) + } + info.HasConfig = len(info.Channels) > 0 out = append(out, info) } writeJSON(w, http.StatusOK, map[string]any{ @@ -72,3 +84,53 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) { "rewriters": mpd.Names(), }) } + +func (h *Handler) fillChannelsFromStore(info *appInfo, name string) { + if h == nil || h.Modules == nil || info == nil { + return + } + chans := channelsFromStoreYAML(h.Modules, name) + if len(chans) == 0 { + return + } + info.Channels = chans + info.HasConfig = true + if info.Error != "" { + // Soft: yaml channels recovered even though describe failed. + info.Error = "" + } +} + +// channelsFromStoreYAML reads channels from the panel module.yaml when describe +// returns none (common with uploaded binaries that resolve values via cwd). +func channelsFromStoreYAML(store *modstore.Store, name string) []channelInfo { + if store == nil { + return nil + } + raw, err := store.ReadYAML(name) + if err != nil || len(raw) == 0 { + return nil + } + var doc struct { + Channels map[string]struct { + Label string `yaml:"label"` + } `yaml:"channels"` + } + if err := yaml.Unmarshal(raw, &doc); err != nil || len(doc.Channels) == 0 { + return nil + } + ids := make([]string, 0, len(doc.Channels)) + for id := range doc.Channels { + ids = append(ids, id) + } + sort.Strings(ids) + out := make([]channelInfo, 0, len(ids)) + for _, id := range ids { + label := doc.Channels[id].Label + if label == "" { + label = id + } + out = append(out, channelInfo{ID: id, Label: label}) + } + return out +} diff --git a/apps/streamd/internal/api/apps_test.go b/apps/streamd/internal/api/apps_test.go new file mode 100644 index 0000000..2ade1ad --- /dev/null +++ b/apps/streamd/internal/api/apps_test.go @@ -0,0 +1,45 @@ +package api + +import ( + "os" + "path/filepath" + "testing" + + "streamd/apps/streamd/internal/modstore" +) + +func TestChannelsFromStoreYAML(t *testing.T) { + root := t.TempDir() + store := modstore.New(root) + modDir := filepath.Join(root, "rte") + if err := os.MkdirAll(modDir, 0o755); err != nil { + t.Fatal(err) + } + yaml := []byte(`package: air.RTE +channels: + rteone: + label: RTE One + rtetwo: + label: RTE 2 +`) + if err := os.WriteFile(filepath.Join(modDir, "module.yaml"), yaml, 0o644); err != nil { + t.Fatal(err) + } + chans := channelsFromStoreYAML(store, "rte") + if len(chans) != 2 { + t.Fatalf("got %d channels: %+v", len(chans), chans) + } + if chans[0].ID != "rteone" || chans[0].Label != "RTE One" { + t.Fatalf("first channel: %+v", chans[0]) + } + if chans[1].ID != "rtetwo" { + t.Fatalf("second channel: %+v", chans[1]) + } +} + +func TestChannelsFromStoreYAMLMissing(t *testing.T) { + store := modstore.New(t.TempDir()) + if chans := channelsFromStoreYAML(store, "nope"); chans != nil { + t.Fatalf("expected nil, got %+v", chans) + } +} diff --git a/apps/streamd/internal/api/control.go b/apps/streamd/internal/api/control.go index 44fd939..f89db47 100644 --- a/apps/streamd/internal/api/control.go +++ b/apps/streamd/internal/api/control.go @@ -162,6 +162,7 @@ func (h *Handler) duplicate(w http.ResponseWriter, r *http.Request, id int64) { Key: src.Key, HeadersJSON: src.HeadersJSON, Proxy: src.Proxy, + Egress: src.Egress, VideoSelect: src.VideoSelect, AudioSelect: src.AudioSelect, Rewriter: src.Rewriter, @@ -271,9 +272,19 @@ func (h *Handler) doProbe(ctx context.Context, st db.Stream, target string) prob start := time.Now() client := &http.Client{Timeout: 20 * time.Second} - // Fetch through the stream's own proxy, so a geo-restricted origin is - // probed the same way the downloader would reach it. - if proxy := strings.TrimSpace(st.Proxy); proxy != "" { + // Fetch through the stream's effective proxy (explicit or named egress), + // so a geo-restricted origin is probed the same way the downloader would. + proxy := strings.TrimSpace(st.Proxy) + if h.Egress != nil { + if p, err := h.Egress.ResolveProxy(st); err == nil { + proxy = p + } else if strings.TrimSpace(st.Egress) != "" && proxy == "" { + res.Error = "egress: " + err.Error() + res.Summary = "egress profile could not be brought up" + return res + } + } + if proxy != "" { if c, err := httpClientWithProxy(proxy); err == nil { client = c } else { diff --git a/apps/streamd/internal/api/egress.go b/apps/streamd/internal/api/egress.go new file mode 100644 index 0000000..bfda8b9 --- /dev/null +++ b/apps/streamd/internal/api/egress.go @@ -0,0 +1,254 @@ +package api + +import ( + "database/sql" + "encoding/json" + "errors" + "io" + "net/http" + "strings" + + "streamd/apps/streamd/internal/auth" + "streamd/apps/streamd/internal/db" +) + +// MountEgress registers /api/egress routes. +func (h *Handler) MountEgress(mux *http.ServeMux) { + mux.HandleFunc("/api/egress", h.egressRoot) + mux.HandleFunc("/api/egress/", h.egressAction) +} + +func (h *Handler) egressRoot(w http.ResponseWriter, r *http.Request) { + if h.Egress == nil { + writeErr(w, http.StatusServiceUnavailable, "egress manager not configured") + return + } + switch r.Method { + case http.MethodGet: + if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { + return + } + list, err := h.Store.ListEgressProfiles() + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + for i := range list { + h.Egress.Enrich(&list[i]) + } + writeJSON(w, http.StatusOK, map[string]any{"profiles": list}) + case http.MethodPost: + p, ok := auth.Guard(w, r, auth.RoleAdmin) + if !ok { + return + } + var in db.CreateEgressProfile + if err := readJSON(r, &in); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + prof, err := h.Store.CreateEgressProfile(in) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + h.Egress.Enrich(&prof) + h.audit(r, p, http.StatusOK, "create egress "+prof.Name) + writeJSON(w, http.StatusOK, prof) + default: + writeErr(w, http.StatusMethodNotAllowed, "method not allowed") + } +} + +func (h *Handler) egressAction(w http.ResponseWriter, r *http.Request) { + if h.Egress == nil { + writeErr(w, http.StatusServiceUnavailable, "egress manager not configured") + return + } + path := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/egress/"), "/") + if path == "" { + h.egressRoot(w, r) + return + } + parts := strings.Split(path, "/") + name := db.Slug(parts[0]) + if name == "" { + writeErr(w, http.StatusBadRequest, "invalid name") + return + } + action := "" + if len(parts) > 1 { + action = strings.ToLower(parts[1]) + } + + switch { + case action == "" && r.Method == http.MethodGet: + if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { + return + } + prof, err := h.Egress.Status(name) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + writeErr(w, http.StatusNotFound, "not found") + return + } + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + writeJSON(w, http.StatusOK, prof) + + case action == "" && r.Method == http.MethodPut: + p, ok := auth.Guard(w, r, auth.RoleAdmin) + if !ok { + return + } + h.putEgress(w, r, p, name) + + case action == "" && r.Method == http.MethodDelete: + p, ok := auth.Guard(w, r, auth.RoleAdmin) + if !ok { + return + } + prof, err := h.Store.GetEgressProfileByName(name) + if err != nil { + writeErr(w, http.StatusNotFound, "not found") + return + } + _ = h.Egress.Down(name) + if err := h.Store.DeleteEgressProfile(prof.ID); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + _ = h.Egress.RemoveFiles(name) + h.audit(r, p, http.StatusOK, "delete egress "+name) + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) + + case action == "up" && r.Method == http.MethodPost: + p, ok := auth.Guard(w, r, auth.RoleAdmin) + if !ok { + return + } + if err := h.Egress.EnsureUp(name); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + prof, _ := h.Egress.Status(name) + h.audit(r, p, http.StatusOK, "egress up "+name) + writeJSON(w, http.StatusOK, prof) + + case action == "down" && r.Method == http.MethodPost: + p, ok := auth.Guard(w, r, auth.RoleAdmin) + if !ok { + return + } + if err := h.Egress.Down(name); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + prof, _ := h.Egress.Status(name) + h.audit(r, p, http.StatusOK, "egress down "+name) + writeJSON(w, http.StatusOK, prof) + + case action == "test" && r.Method == http.MethodPost: + p, ok := auth.Guard(w, r, auth.RoleAdmin) + if !ok { + return + } + out, err := h.Egress.TestDial(name) + if err != nil { + if out == nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + h.audit(r, p, http.StatusOK, "egress test "+name+" fail") + writeJSON(w, http.StatusOK, out) + return + } + h.audit(r, p, http.StatusOK, "egress test "+name) + writeJSON(w, http.StatusOK, out) + + case action == "conf" && r.Method == http.MethodPut: + p, ok := auth.Guard(w, r, auth.RoleAdmin) + if !ok { + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + _ = r.Body.Close() + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + contents := string(body) + ct := r.Header.Get("Content-Type") + if strings.Contains(ct, "json") || strings.HasPrefix(strings.TrimSpace(contents), "{") { + var in struct { + Conf string `json:"conf"` + } + if err := json.Unmarshal(body, &in); err != nil || strings.TrimSpace(in.Conf) == "" { + writeErr(w, http.StatusBadRequest, "conf required") + return + } + contents = in.Conf + } + if strings.TrimSpace(contents) == "" { + writeErr(w, http.StatusBadRequest, "empty conf") + return + } + if _, err := h.Store.GetEgressProfileByName(name); err != nil { + writeErr(w, http.StatusNotFound, "not found") + return + } + if err := h.Egress.WriteConf(name, contents); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + prof, _ := h.Egress.Status(name) + h.audit(r, p, http.StatusOK, "egress conf "+name) + writeJSON(w, http.StatusOK, prof) + + default: + writeErr(w, http.StatusMethodNotAllowed, "method not allowed") + } +} + +func (h *Handler) putEgress(w http.ResponseWriter, r *http.Request, p *auth.Principal, name string) { + prof, err := h.Store.GetEgressProfileByName(name) + if err != nil { + writeErr(w, http.StatusNotFound, "not found") + return + } + var in struct { + Enabled *bool `json:"enabled"` + SocksURL *string `json:"socks_url"` + Kind *string `json:"kind"` + Conf *string `json:"conf"` + } + if err := readJSON(r, &in); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + upd, err := h.Store.UpdateEgressProfile(prof.ID, db.UpdateEgressProfile{ + Enabled: in.Enabled, SocksURL: in.SocksURL, Kind: in.Kind, + }) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + if in.Conf != nil && strings.TrimSpace(*in.Conf) != "" { + if err := h.Egress.WriteConf(name, *in.Conf); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + } + h.Egress.Enrich(&upd) + if in.Enabled != nil && *in.Enabled { + _ = h.Egress.EnsureUp(name) + upd, _ = h.Egress.Status(name) + } + if in.Enabled != nil && !*in.Enabled { + _ = h.Egress.Down(name) + upd, _ = h.Egress.Status(name) + } + h.audit(r, p, http.StatusOK, "update egress "+name) + writeJSON(w, http.StatusOK, upd) +} diff --git a/apps/streamd/internal/api/modules.go b/apps/streamd/internal/api/modules.go index f99efa5..e5a9de0 100644 --- a/apps/streamd/internal/api/modules.go +++ b/apps/streamd/internal/api/modules.go @@ -222,6 +222,14 @@ func (h *Handler) uploadModule(w http.ResponseWriter, r *http.Request) { return } defer file.Close() + if name == "" && hdr != nil { + // rte.zip → rte (helps flat release zips before binary inference). + base := strings.TrimSuffix(filepath.Base(hdr.Filename), filepath.Ext(hdr.Filename)) + base = strings.ToLower(strings.TrimSpace(base)) + if modstore.NameRe.MatchString(base) { + name = base + } + } if hdr.Size > modstore.MaxPackageBytes { writeErr(w, http.StatusBadRequest, "zip too large") return diff --git a/apps/streamd/internal/db/db.go b/apps/streamd/internal/db/db.go index 522e009..c3a70e4 100644 --- a/apps/streamd/internal/db/db.go +++ b/apps/streamd/internal/db/db.go @@ -41,7 +41,8 @@ type Stream struct { MPD string `json:"mpd"` Key string `json:"key"` HeadersJSON string `json:"headers_json"` - Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE) + Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE) + Egress string `json:"egress"` // named egress profile (wireguard/socks); used when Proxy empty VideoSelect string `json:"video_select"` AudioSelect string `json:"audio_select"` Enabled bool `json:"enabled"` @@ -81,6 +82,7 @@ type Stream struct { HasKey bool `json:"has_key"` HasHeaders bool `json:"has_headers"` HasProxy bool `json:"has_proxy"` + HasEgress bool `json:"has_egress"` KeyValid bool `json:"key_valid"` // DRMRequired is DRMMode resolved: whether this stream needs keys at all. DRMRequired bool `json:"drm_required"` @@ -103,6 +105,7 @@ type CreateStream struct { Key string `json:"key"` HeadersJSON string `json:"headers_json"` Proxy string `json:"proxy"` + Egress string `json:"egress"` VideoSelect string `json:"video_select"` AudioSelect string `json:"audio_select"` Rewriter string `json:"rewriter"` @@ -128,6 +131,7 @@ type PatchStream struct { Key *string `json:"key"` HeadersJSON *string `json:"headers_json"` Proxy *string `json:"proxy"` + Egress *string `json:"egress"` VideoSelect *string `json:"video_select"` AudioSelect *string `json:"audio_select"` Rewriter *string `json:"rewriter"` @@ -230,6 +234,7 @@ CREATE TABLE IF NOT EXISTS agent_claims ( `ALTER TABLE streams ADD COLUMN on_demand INTEGER NOT NULL DEFAULT 0`, `ALTER TABLE streams ADD COLUMN idle_timeout_s INTEGER NOT NULL DEFAULT 300`, `ALTER TABLE streams ADD COLUMN public INTEGER NOT NULL DEFAULT 1`, + `ALTER TABLE streams ADD COLUMN egress TEXT NOT NULL DEFAULT ''`, } { _, _ = s.DB.Exec(stmt) } @@ -239,7 +244,10 @@ CREATE TABLE IF NOT EXISTS agent_claims ( if err := s.migrateSettings(); err != nil { return err } - return s.migrateSchedules() + if err := s.migrateSchedules(); err != nil { + return err + } + return s.migrateEgress() } func now() string { @@ -264,10 +272,13 @@ func slug(name string) string { return out } +// Slug normalises a name the same way stream and egress profile names are stored. +func Slug(name string) string { return slug(name) } + const streamSelect = ` SELECT s.id, s.name, s.title, COALESCE(s.description,''), COALESCE(s.tags,''), s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json, - COALESCE(s.proxy,''), s.video_select, s.audio_select, s.enabled, s.rewriter, + COALESCE(s.proxy,''), COALESCE(s.egress,''), s.video_select, s.audio_select, s.enabled, s.rewriter, COALESCE(s.variants_json,''), COALESCE(s.outputs_json,''), COALESCE(s.settings_json,''), COALESCE(s.drm_mode,'auto'), COALESCE(s.on_demand,0), COALESCE(s.idle_timeout_s,300), COALESCE(s.public,1), @@ -318,7 +329,7 @@ func scanStream(row rowScanner) (Stream, error) { err := row.Scan( &st.ID, &st.Name, &st.Title, &st.Description, &st.Tags, &st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON, - &st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, + &st.Proxy, &st.Egress, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, &st.VariantsJSON, &st.OutputsJSON, &st.SettingsJSON, &st.DRMMode, &onDemand, &st.IdleTimeoutS, &public, &st.CreatedAt, &st.UpdatedAt, @@ -361,6 +372,7 @@ func (st *Stream) fillDerived() { hdr := strings.TrimSpace(st.HeadersJSON) st.HasHeaders = hdr != "" && hdr != "{}" && hdr != "null" st.HasProxy = strings.TrimSpace(st.Proxy) != "" + st.HasEgress = strings.TrimSpace(st.Egress) != "" switch strings.ToLower(strings.TrimSpace(st.DRMMode)) { case DRMYes: st.DRMRequired = true @@ -557,12 +569,13 @@ func (s *Store) CreateStream(in CreateStream) (Stream, error) { } ts := now() res, err := s.DB.Exec(` -INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy, +INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,egress, video_select,audio_select,enabled,rewriter,variants_json,outputs_json, settings_json,drm_mode,on_demand,idle_timeout_s,public,created_at,updated_at) -VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, +VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, name, in.Title, strings.TrimSpace(in.Description), normalizeTags(in.Tags), in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy), + slug(strings.TrimSpace(in.Egress)), in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, outputsJSON, settingsJSON, normalizeDRMMode(in.DRMMode), onDemand, idle, public, ts, ts) if err != nil { @@ -654,6 +667,9 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) { if in.Proxy != nil { cur.Proxy = strings.TrimSpace(*in.Proxy) } + if in.Egress != nil { + cur.Egress = slug(strings.TrimSpace(*in.Egress)) + } if in.VideoSelect != nil { cur.VideoSelect = *in.VideoSelect } @@ -730,11 +746,11 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) { ts := now() _, err = s.DB.Exec(` UPDATE streams SET title=?, description=?, tags=?, app=?, channel=?, mpd=?, key_kid_key=?, - headers_json=?, proxy=?, video_select=?, audio_select=?, enabled=?, rewriter=?, + headers_json=?, proxy=?, egress=?, video_select=?, audio_select=?, enabled=?, rewriter=?, variants_json=?, outputs_json=?, settings_json=?, drm_mode=?, on_demand=?, idle_timeout_s=?, public=?, updated_at=? WHERE id=?`, cur.Title, cur.Description, cur.Tags, cur.App, cur.Channel, cur.MPD, cur.Key, - cur.HeadersJSON, cur.Proxy, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, + cur.HeadersJSON, cur.Proxy, cur.Egress, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, cur.VariantsJSON, cur.OutputsJSON, cur.SettingsJSON, cur.DRMMode, onDemand, cur.IdleTimeoutS, public, ts, id) if err != nil { diff --git a/apps/streamd/internal/db/egress.go b/apps/streamd/internal/db/egress.go new file mode 100644 index 0000000..6371c83 --- /dev/null +++ b/apps/streamd/internal/db/egress.go @@ -0,0 +1,226 @@ +package db + +import ( + "database/sql" + "fmt" + "strings" +) + +const ( + EgressKindWireGuard = "wireguard" + EgressKindSocks = "socks" + + EgressStopped = "stopped" + EgressStarting = "starting" + EgressUp = "up" + EgressDown = "down" + EgressError = "error" +) + +// EgressProfile is a named origin-egress path (WireGuard netns or plain SOCKS). +// Conf blobs live on disk under data/egress//; never in this table. +type EgressProfile struct { + ID int64 `json:"id"` + Name string `json:"name"` + Kind string `json:"kind"` + Enabled bool `json:"enabled"` + ListenPort int `json:"listen_port"` + SocksURL string `json:"socks_url,omitempty"` + Status string `json:"status"` + LastError string `json:"last_error,omitempty"` + EgressIP string `json:"egress_ip,omitempty"` + HasConf bool `json:"has_conf"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +func (s *Store) migrateEgress() error { + _, err := s.DB.Exec(` +CREATE TABLE IF NOT EXISTS egress_profiles ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE, + kind TEXT NOT NULL DEFAULT 'wireguard', + enabled INTEGER NOT NULL DEFAULT 0, + listen_port INTEGER NOT NULL DEFAULT 0, + socks_url TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'stopped', + last_error TEXT NOT NULL DEFAULT '', + egress_ip TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); +`) + return err +} + +type CreateEgressProfile struct { + Name string `json:"name"` + Kind string `json:"kind"` + Enabled *bool `json:"enabled"` + SocksURL string `json:"socks_url"` +} + +type UpdateEgressProfile struct { + Enabled *bool `json:"enabled"` + SocksURL *string `json:"socks_url"` + Kind *string `json:"kind"` +} + +func normalizeEgressKind(k string) (string, error) { + switch strings.ToLower(strings.TrimSpace(k)) { + case "", EgressKindWireGuard: + return EgressKindWireGuard, nil + case EgressKindSocks: + return EgressKindSocks, nil + default: + return "", fmt.Errorf("kind must be %q or %q", EgressKindWireGuard, EgressKindSocks) + } +} + +func (s *Store) ListEgressProfiles() ([]EgressProfile, error) { + rows, err := s.DB.Query(` +SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at +FROM egress_profiles ORDER BY name`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []EgressProfile + for rows.Next() { + p, err := scanEgress(rows) + if err != nil { + return nil, err + } + out = append(out, p) + } + if out == nil { + out = []EgressProfile{} + } + return out, rows.Err() +} + +func (s *Store) GetEgressProfile(id int64) (EgressProfile, error) { + row := s.DB.QueryRow(` +SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at +FROM egress_profiles WHERE id=?`, id) + return scanEgress(row) +} + +func (s *Store) GetEgressProfileByName(name string) (EgressProfile, error) { + name = slug(name) + if name == "" { + return EgressProfile{}, fmt.Errorf("name required") + } + row := s.DB.QueryRow(` +SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at +FROM egress_profiles WHERE name=?`, name) + return scanEgress(row) +} + +func scanEgress(row rowScanner) (EgressProfile, error) { + var p EgressProfile + var enabled int + err := row.Scan( + &p.ID, &p.Name, &p.Kind, &enabled, &p.ListenPort, &p.SocksURL, + &p.Status, &p.LastError, &p.EgressIP, &p.CreatedAt, &p.UpdatedAt, + ) + if err != nil { + return p, err + } + p.Enabled = enabled != 0 + if p.Status == "" { + p.Status = EgressStopped + } + return p, nil +} + +func (s *Store) CreateEgressProfile(in CreateEgressProfile) (EgressProfile, error) { + name := slug(in.Name) + if name == "" { + return EgressProfile{}, fmt.Errorf("name required (slug of letters, digits, hyphens)") + } + kind, err := normalizeEgressKind(in.Kind) + if err != nil { + return EgressProfile{}, err + } + socks := strings.TrimSpace(in.SocksURL) + if kind == EgressKindSocks && socks == "" { + return EgressProfile{}, fmt.Errorf("socks_url required for kind=socks") + } + enabled := 0 + if in.Enabled != nil && *in.Enabled { + enabled = 1 + } + ts := now() + res, err := s.DB.Exec(` +INSERT INTO egress_profiles(name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at) +VALUES(?,?,?,0,?,?, '','',?,?)`, + name, kind, enabled, socks, EgressStopped, ts, ts) + if err != nil { + if strings.Contains(strings.ToLower(err.Error()), "unique") { + return EgressProfile{}, fmt.Errorf("egress profile %q already exists", name) + } + return EgressProfile{}, err + } + id, _ := res.LastInsertId() + return s.GetEgressProfile(id) +} + +func (s *Store) UpdateEgressProfile(id int64, in UpdateEgressProfile) (EgressProfile, error) { + cur, err := s.GetEgressProfile(id) + if err != nil { + return EgressProfile{}, err + } + if in.Enabled != nil { + cur.Enabled = *in.Enabled + } + if in.SocksURL != nil { + cur.SocksURL = strings.TrimSpace(*in.SocksURL) + } + if in.Kind != nil { + kind, err := normalizeEgressKind(*in.Kind) + if err != nil { + return EgressProfile{}, err + } + cur.Kind = kind + } + if cur.Kind == EgressKindSocks && cur.SocksURL == "" { + return EgressProfile{}, fmt.Errorf("socks_url required for kind=socks") + } + enabled := 0 + if cur.Enabled { + enabled = 1 + } + ts := now() + _, err = s.DB.Exec(` +UPDATE egress_profiles SET kind=?, enabled=?, socks_url=?, updated_at=? WHERE id=?`, + cur.Kind, enabled, cur.SocksURL, ts, id) + if err != nil { + return EgressProfile{}, err + } + return s.GetEgressProfile(id) +} + +func (s *Store) DeleteEgressProfile(id int64) error { + res, err := s.DB.Exec(`DELETE FROM egress_profiles WHERE id=?`, id) + if err != nil { + return err + } + n, _ := res.RowsAffected() + if n == 0 { + return sql.ErrNoRows + } + return nil +} + +// SetEgressRuntime updates live status fields without touching config. +func (s *Store) SetEgressRuntime(id int64, status, lastErr, egressIP string, listenPort int) error { + status = strings.TrimSpace(status) + if status == "" { + status = EgressStopped + } + _, err := s.DB.Exec(` +UPDATE egress_profiles SET status=?, last_error=?, egress_ip=?, listen_port=?, updated_at=? WHERE id=?`, + status, strings.TrimSpace(lastErr), strings.TrimSpace(egressIP), listenPort, now(), id) + return err +} diff --git a/apps/streamd/internal/db/egress_test.go b/apps/streamd/internal/db/egress_test.go new file mode 100644 index 0000000..3b6c9c1 --- /dev/null +++ b/apps/streamd/internal/db/egress_test.go @@ -0,0 +1,117 @@ +package db + +import ( + "path/filepath" + "testing" +) + +func TestSlugValidation(t *testing.T) { + for _, c := range []struct { + in, want string + }{ + {"London", "london"}, + {"dublin-1", "dublin-1"}, + {" RTE IE ", "rte-ie"}, + {"!!!", ""}, + {"Wire_Guard", "wire-guard"}, + {"a--b", "a-b"}, + } { + if got := Slug(c.in); got != c.want { + t.Errorf("Slug(%q) = %q want %q", c.in, got, c.want) + } + } +} + +func TestEgressCRUD(t *testing.T) { + dir := t.TempDir() + store, err := Open(filepath.Join(dir, "data")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + + _, err = store.CreateEgressProfile(CreateEgressProfile{Name: "!!!"}) + if err == nil { + t.Fatal("expected empty slug to fail") + } + + on := true + p, err := store.CreateEgressProfile(CreateEgressProfile{ + Name: "London", Kind: "wireguard", Enabled: &on, + }) + if err != nil { + t.Fatal(err) + } + if p.Name != "london" || p.Kind != EgressKindWireGuard || !p.Enabled { + t.Fatalf("create: %+v", p) + } + if p.Status != EgressStopped { + t.Fatalf("status = %q", p.Status) + } + + got, err := store.GetEgressProfileByName("LONDON") + if err != nil || got.ID != p.ID { + t.Fatalf("GetByName: %+v %v", got, err) + } + + off := false + url := "socks5://127.0.0.1:1080" + kind := EgressKindSocks + upd, err := store.UpdateEgressProfile(p.ID, UpdateEgressProfile{ + Enabled: &off, SocksURL: &url, Kind: &kind, + }) + if err != nil { + t.Fatal(err) + } + if upd.Enabled || upd.SocksURL != url || upd.Kind != EgressKindSocks { + t.Fatalf("update: %+v", upd) + } + + if err := store.SetEgressRuntime(p.ID, EgressUp, "", "1.2.3.4", 18080); err != nil { + t.Fatal(err) + } + got, _ = store.GetEgressProfile(p.ID) + if got.Status != EgressUp || got.EgressIP != "1.2.3.4" || got.ListenPort != 18080 { + t.Fatalf("runtime: %+v", got) + } + + list, err := store.ListEgressProfiles() + if err != nil || len(list) != 1 { + t.Fatalf("list: %v %#v", err, list) + } + + if err := store.DeleteEgressProfile(p.ID); err != nil { + t.Fatal(err) + } + if _, err := store.GetEgressProfile(p.ID); err == nil { + t.Fatal("expected missing after delete") + } +} + +func TestStreamEgressField(t *testing.T) { + dir := t.TempDir() + store, err := Open(filepath.Join(dir, "data")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + + st, err := store.CreateStream(CreateStream{Name: "rte1", MPD: "https://x/a.mpd", Egress: "Dublin"}) + if err != nil { + t.Fatal(err) + } + if st.Egress != "dublin" || !st.HasEgress || st.HasProxy { + t.Fatalf("create egress: %+v has_egress=%v has_proxy=%v", st.Egress, st.HasEgress, st.HasProxy) + } + + empty := "" + london := "london" + st, err = store.PatchStream(st.ID, PatchStream{Egress: &london}) + if err != nil || st.Egress != "london" { + t.Fatalf("patch: %+v %v", st, err) + } + st, err = store.PatchStream(st.ID, PatchStream{Egress: &empty}) + if err != nil || st.HasEgress { + t.Fatalf("clear egress: %+v %v", st, err) + } +} diff --git a/apps/streamd/internal/egress/conf.go b/apps/streamd/internal/egress/conf.go new file mode 100644 index 0000000..7e4356b --- /dev/null +++ b/apps/streamd/internal/egress/conf.go @@ -0,0 +1,80 @@ +package egress + +import ( + "bufio" + "strings" +) + +// wgInterfaceAddrs extracts Address= values from the [Interface] section of a +// wg-quick style conf. Private keys are never returned or logged. +func wgInterfaceAddrs(conf string) []string { + var addrs []string + section := "" + sc := bufio.NewScanner(strings.NewReader(conf)) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") { + continue + } + if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + section = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1])) + continue + } + if section != "interface" { + continue + } + key, val, ok := strings.Cut(line, "=") + if !ok { + continue + } + if strings.EqualFold(strings.TrimSpace(key), "Address") { + for _, part := range strings.Split(val, ",") { + if a := strings.TrimSpace(part); a != "" { + addrs = append(addrs, a) + } + } + } + } + return addrs +} + +// wgSetconfBody strips wg-quick-only keys so the result is valid for `wg setconf`. +func wgSetconfBody(conf string) string { + var b strings.Builder + section := "" + sc := bufio.NewScanner(strings.NewReader(conf)) + for sc.Scan() { + raw := sc.Text() + line := strings.TrimSpace(raw) + if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") { + continue + } + if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + section = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1])) + b.WriteString(line) + b.WriteByte('\n') + continue + } + key, _, ok := strings.Cut(line, "=") + if !ok { + continue + } + k := strings.ToLower(strings.TrimSpace(key)) + if section == "interface" { + switch k { + case "privatekey", "listenport", "fwmark": + b.WriteString(line) + b.WriteByte('\n') + } + continue + } + if section == "peer" { + switch k { + case "publickey", "presharedkey", "allowedips", "endpoint", "persistentkeepalive": + b.WriteString(line) + b.WriteByte('\n') + } + } + } + return b.String() +} diff --git a/apps/streamd/internal/egress/manager.go b/apps/streamd/internal/egress/manager.go new file mode 100644 index 0000000..4cb3519 --- /dev/null +++ b/apps/streamd/internal/egress/manager.go @@ -0,0 +1,401 @@ +package egress + +import ( + "fmt" + "io" + "log/slog" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "time" + + "streamd/apps/streamd/internal/db" +) + +const ( + baseListenPort = 18080 + socksPortInNS = 1080 +) + +// Manager brings named egress profiles up and resolves a stream's origin proxy. +type Manager struct { + DataDir string + Store *db.Store + Log *slog.Logger + SocksBin string // microsocks or gost; looked up if empty + + mu sync.Mutex + running map[string]*runState // by profile name +} + +type runState struct { + name string + listenPort int + nsIP string // veth IP inside netns, e.g. 10.255.N.2 + socksCmd *exec.Cmd + forwardLn net.Listener + stopFwd chan struct{} +} + +// New builds a Manager. SocksBin may be empty (auto LookPath). +func New(dataDir string, store *db.Store, log *slog.Logger, socksBin string) *Manager { + if log == nil { + log = slog.Default() + } + return &Manager{ + DataDir: dataDir, + Store: store, + Log: log, + SocksBin: socksBin, + running: map[string]*runState{}, + } +} + +func (m *Manager) logger() *slog.Logger { + if m.Log != nil { + return m.Log + } + return slog.Default() +} + +func (m *Manager) profileDir(name string) string { + return filepath.Join(m.DataDir, "egress", db.Slug(name)) +} + +func (m *Manager) confPath(name string) string { + return filepath.Join(m.profileDir(name), "wg.conf") +} + +// HasConf reports whether a WireGuard conf file exists for name. +func (m *Manager) HasConf(name string) bool { + st, err := os.Stat(m.confPath(name)) + return err == nil && st.Size() > 0 +} + +// WriteConf stores a WireGuard conf on disk (0600). Does not log contents. +func (m *Manager) WriteConf(name, contents string) error { + name = db.Slug(name) + if name == "" { + return fmt.Errorf("name required") + } + dir := m.profileDir(name) + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + path := m.confPath(name) + tmp := path + ".tmp" + if err := os.WriteFile(tmp, []byte(contents), 0o600); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// ReadConf returns the raw conf for admin use. Callers must not log it. +func (m *Manager) ReadConf(name string) (string, error) { + b, err := os.ReadFile(m.confPath(name)) + if err != nil { + return "", err + } + return string(b), nil +} + +// RemoveFiles deletes on-disk conf for a profile (after DB delete). +func (m *Manager) RemoveFiles(name string) error { + name = db.Slug(name) + if name == "" { + return nil + } + return os.RemoveAll(m.profileDir(name)) +} + +// Enrich fills HasConf on profiles (conf is never stored in the DB). +func (m *Manager) Enrich(p *db.EgressProfile) { + if p == nil { + return + } + if p.Kind == db.EgressKindWireGuard { + p.HasConf = m.HasConf(p.Name) + } +} + +// ResolveProxy returns the SOCKS/HTTP proxy URL a stream should use for origin +// fetch. Order: explicit stream.Proxy, then named egress profile, else empty. +func (m *Manager) ResolveProxy(st db.Stream) (string, error) { + if p := strings.TrimSpace(st.Proxy); p != "" { + return p, nil + } + name := strings.TrimSpace(st.Egress) + if name == "" { + return "", nil + } + if err := m.EnsureUp(name); err != nil { + return "", err + } + p, err := m.Store.GetEgressProfileByName(name) + if err != nil { + return "", err + } + switch p.Kind { + case db.EgressKindSocks: + u := strings.TrimSpace(p.SocksURL) + if u == "" { + return "", fmt.Errorf("egress %q has no socks_url", p.Name) + } + return u, nil + default: + if p.ListenPort <= 0 { + return "", fmt.Errorf("egress %q is up but has no listen port", p.Name) + } + return fmt.Sprintf("socks5://127.0.0.1:%d", p.ListenPort), nil + } +} + +// StartEnabled brings up every profile marked enabled. +func (m *Manager) StartEnabled() { + list, err := m.Store.ListEgressProfiles() + if err != nil { + m.logger().Error("list egress profiles", "err", err) + return + } + for _, p := range list { + if !p.Enabled { + continue + } + if err := m.EnsureUp(p.Name); err != nil { + m.logger().Warn("egress start", "name", p.Name, "err", err) + } + } +} + +// StopAll tears down every running profile. +func (m *Manager) StopAll() { + m.mu.Lock() + names := make([]string, 0, len(m.running)) + for n := range m.running { + names = append(names, n) + } + m.mu.Unlock() + for _, n := range names { + _ = m.Down(n) + } +} + +// Status returns the DB row for a profile (with HasConf filled). +func (m *Manager) Status(name string) (db.EgressProfile, error) { + p, err := m.Store.GetEgressProfileByName(name) + if err != nil { + return p, err + } + m.Enrich(&p) + return p, nil +} + +// EnsureUp brings a profile to a usable SOCKS endpoint. +func (m *Manager) EnsureUp(name string) error { + name = db.Slug(name) + if name == "" { + return fmt.Errorf("egress name required") + } + p, err := m.Store.GetEgressProfileByName(name) + if err != nil { + return fmt.Errorf("egress profile %q: %w", name, err) + } + + m.mu.Lock() + if rs, ok := m.running[name]; ok && rs != nil { + m.mu.Unlock() + return nil + } + m.mu.Unlock() + + _ = m.Store.SetEgressRuntime(p.ID, db.EgressStarting, "", p.EgressIP, p.ListenPort) + + switch p.Kind { + case db.EgressKindSocks: + u := strings.TrimSpace(p.SocksURL) + if u == "" { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, "socks_url required", "", 0) + return fmt.Errorf("egress %q: socks_url required", name) + } + m.mu.Lock() + m.running[name] = &runState{name: name} + m.mu.Unlock() + _ = m.Store.SetEgressRuntime(p.ID, db.EgressUp, "", "", 0) + return nil + case db.EgressKindWireGuard: + if runtime.GOOS != "linux" { + msg := "wireguard egress requires Linux" + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0) + return fmt.Errorf("%s", msg) + } + return m.ensureWireGuardUp(p) + default: + msg := fmt.Sprintf("unknown egress kind %q", p.Kind) + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0) + return fmt.Errorf("%s", msg) + } +} + +// Down stops a profile's local SOCKS / netns. +func (m *Manager) Down(name string) error { + name = db.Slug(name) + p, err := m.Store.GetEgressProfileByName(name) + if err != nil { + return err + } + + m.mu.Lock() + rs := m.running[name] + delete(m.running, name) + m.mu.Unlock() + + if rs != nil { + m.stopRun(rs) + } + if p.Kind == db.EgressKindWireGuard && runtime.GOOS == "linux" { + if err := m.teardownWireGuard(name, p.ID); err != nil { + m.logger().Warn("egress teardown", "name", name, "err", err) + } + } + _ = m.Store.SetEgressRuntime(p.ID, db.EgressStopped, "", "", 0) + return nil +} + +func (m *Manager) stopRun(rs *runState) { + if rs.stopFwd != nil { + close(rs.stopFwd) + rs.stopFwd = nil + } + if rs.forwardLn != nil { + _ = rs.forwardLn.Close() + rs.forwardLn = nil + } + if rs.socksCmd != nil && rs.socksCmd.Process != nil { + _ = rs.socksCmd.Process.Kill() + _, _ = rs.socksCmd.Process.Wait() + rs.socksCmd = nil + } +} + +func (m *Manager) findSocksBin() (string, error) { + if m.SocksBin != "" { + return m.SocksBin, nil + } + for _, n := range []string{"microsocks", "gost"} { + if p, err := exec.LookPath(n); err == nil { + m.SocksBin = p + return p, nil + } + } + return "", fmt.Errorf("microsocks (or gost) not found on PATH") +} + +func (m *Manager) allocListenPort(id int64) int { + return baseListenPort + int(id%1000) +} + +func (m *Manager) vethAddrs(id int64) (hostIP, nsIP, subnet string) { + // Unique /30-ish /24 host pair per profile id (1..254). + n := int(id % 200) + if n <= 0 { + n = 1 + } + hostIP = fmt.Sprintf("10.255.%d.1", n) + nsIP = fmt.Sprintf("10.255.%d.2", n) + subnet = fmt.Sprintf("10.255.%d.0/24", n) + return hostIP, nsIP, subnet +} + +func (m *Manager) startLocalForward(listenPort int, destHost string, destPort int) (net.Listener, chan struct{}, error) { + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", listenPort)) + if err != nil { + return nil, nil, err + } + stop := make(chan struct{}) + go func() { + for { + c, err := ln.Accept() + if err != nil { + select { + case <-stop: + return + default: + return + } + } + go proxyTCP(c, fmt.Sprintf("%s:%d", destHost, destPort)) + } + }() + return ln, stop, nil +} + +func proxyTCP(client net.Conn, addr string) { + defer client.Close() + _ = client.SetDeadline(time.Now().Add(60 * time.Second)) + upstream, err := net.DialTimeout("tcp", addr, 15*time.Second) + if err != nil { + return + } + defer upstream.Close() + _ = client.SetDeadline(time.Time{}) + _ = upstream.SetDeadline(time.Time{}) + done := make(chan struct{}, 2) + go func() { _, _ = io.Copy(upstream, client); done <- struct{}{} }() + go func() { _, _ = io.Copy(client, upstream); done <- struct{}{} }() + <-done +} + +// TestDial tries a short TCP connect through the resolved SOCKS endpoint of a +// profile (after EnsureUp). Used by POST /api/egress/:name/test. +func (m *Manager) TestDial(name string) (map[string]any, error) { + if err := m.EnsureUp(name); err != nil { + return nil, err + } + p, err := m.Store.GetEgressProfileByName(name) + if err != nil { + return nil, err + } + var proxyURL string + switch p.Kind { + case db.EgressKindSocks: + proxyURL = strings.TrimSpace(p.SocksURL) + default: + if p.ListenPort <= 0 { + return nil, fmt.Errorf("no listen port") + } + proxyURL = fmt.Sprintf("socks5://127.0.0.1:%d", p.ListenPort) + } + out := map[string]any{ + "ok": true, + "name": p.Name, + "kind": p.Kind, + "proxy_url": proxyURL, + "status": p.Status, + "egress_ip": p.EgressIP, + } + // Dial the local SOCKS port to confirm it accepts TCP. + hostPort := "" + if p.Kind == db.EgressKindWireGuard && p.ListenPort > 0 { + hostPort = fmt.Sprintf("127.0.0.1:%d", p.ListenPort) + } else if u := strings.TrimPrefix(strings.TrimPrefix(proxyURL, "socks5://"), "socks5h://"); u != proxyURL { + if i := strings.LastIndex(u, "@"); i >= 0 { + u = u[i+1:] + } + hostPort = u + } + if hostPort != "" { + c, err := net.DialTimeout("tcp", hostPort, 5*time.Second) + if err != nil { + out["ok"] = false + out["error"] = err.Error() + return out, fmt.Errorf("socks dial: %w", err) + } + _ = c.Close() + out["socks_reachable"] = true + } + return out, nil +} diff --git a/apps/streamd/internal/egress/manager_test.go b/apps/streamd/internal/egress/manager_test.go new file mode 100644 index 0000000..b355237 --- /dev/null +++ b/apps/streamd/internal/egress/manager_test.go @@ -0,0 +1,100 @@ +package egress + +import ( + "path/filepath" + "strings" + "testing" + + "streamd/apps/streamd/internal/db" +) + +func TestResolveProxyOrder(t *testing.T) { + dir := t.TempDir() + store, err := db.Open(filepath.Join(dir, "data")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + + m := New(filepath.Join(dir, "data"), store, nil, "") + + // Neither proxy nor egress. + got, err := m.ResolveProxy(db.Stream{Name: "a"}) + if err != nil || got != "" { + t.Fatalf("empty: got %q err %v", got, err) + } + + // Explicit proxy wins over egress. + got, err = m.ResolveProxy(db.Stream{ + Proxy: "socks5://127.0.0.1:9999", + Egress: "london", + }) + if err != nil || got != "socks5://127.0.0.1:9999" { + t.Fatalf("proxy wins: got %q err %v", got, err) + } + + on := true + _, err = store.CreateEgressProfile(db.CreateEgressProfile{ + Name: "dublin", + Kind: db.EgressKindSocks, + Enabled: &on, + SocksURL: "socks5://10.0.0.5:1080", + }) + if err != nil { + t.Fatal(err) + } + + got, err = m.ResolveProxy(db.Stream{Egress: "dublin"}) + if err != nil || got != "socks5://10.0.0.5:1080" { + t.Fatalf("egress socks: got %q err %v", got, err) + } + + // Missing profile. + _, err = m.ResolveProxy(db.Stream{Egress: "missing"}) + if err == nil { + t.Fatal("expected error for missing profile") + } + + // WireGuard on non-Linux must fail EnsureUp (covered when GOOS != linux). + _, err = store.CreateEgressProfile(db.CreateEgressProfile{ + Name: "london", Kind: db.EgressKindWireGuard, Enabled: &on, + }) + if err != nil { + t.Fatal(err) + } + _, err = m.ResolveProxy(db.Stream{Egress: "london"}) + // On Linux without conf/tools this also errors; on Windows always errors. + if err == nil { + t.Fatal("expected wireguard EnsureUp to fail without a working tunnel") + } +} + +func TestWgConfParse(t *testing.T) { + conf := `[Interface] +PrivateKey = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEE= +Address = 10.64.0.2/32 +Address = fd00::2/128 +DNS = 1.1.1.1 + +[Peer] +PublicKey = BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBEE= +AllowedIPs = 0.0.0.0/0, ::/0 +Endpoint = 203.0.113.1:51820 +` + addrs := wgInterfaceAddrs(conf) + if len(addrs) != 2 || addrs[0] != "10.64.0.2/32" || addrs[1] != "fd00::2/128" { + t.Fatalf("addrs: %#v", addrs) + } + body := wgSetconfBody(conf) + lower := strings.ToLower(body) + if strings.Contains(lower, "address") || strings.Contains(lower, "dns") { + t.Fatalf("setconf body still has wg-quick keys:\n%s", body) + } + if !strings.Contains(body, "PrivateKey") || !strings.Contains(body, "PublicKey") { + t.Fatalf("setconf missing keys:\n%s", body) + } + addrs = wgInterfaceAddrs("[Interface]\nAddress = 10.1.0.2/32, 10.1.0.3/32\n") + if len(addrs) != 2 { + t.Fatalf("combined: %#v", addrs) + } +} diff --git a/apps/streamd/internal/egress/wg_linux.go b/apps/streamd/internal/egress/wg_linux.go new file mode 100644 index 0000000..9985965 --- /dev/null +++ b/apps/streamd/internal/egress/wg_linux.go @@ -0,0 +1,262 @@ +//go:build linux + +package egress + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + "streamd/apps/streamd/internal/db" +) + +func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error { + name := p.Name + confPath := m.confPath(name) + raw, err := os.ReadFile(confPath) + if err != nil { + msg := "wg.conf missing; upload a WireGuard conf first" + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0) + return fmt.Errorf("egress %q: %s", name, msg) + } + addrs := wgInterfaceAddrs(string(raw)) + if len(addrs) == 0 { + msg := "wg.conf has no Interface Address=" + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0) + return fmt.Errorf("egress %q: %s", name, msg) + } + socksBin, err := m.findSocksBin() + if err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + return err + } + if _, err := exec.LookPath("ip"); err != nil { + msg := "ip (iproute2) not found on PATH" + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0) + return fmt.Errorf("%s", msg) + } + if _, err := exec.LookPath("wg"); err != nil { + msg := "wg (wireguard-tools) not found on PATH" + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0) + return fmt.Errorf("%s", msg) + } + + listenPort := p.ListenPort + if listenPort <= 0 { + listenPort = m.allocListenPort(p.ID) + } + hostIP, nsIP, _ := m.vethAddrs(p.ID) + nsName := netnsName(name) + wgDev := wgDevName(name) + hostVeth := hostVethName(name) + nsVeth := "hv0" + + // Tear down any leftover state before bringing up. + _ = m.teardownWireGuard(name, p.ID) + + run := func(args ...string) error { + cmd := exec.Command(args[0], args[1:]...) + out, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("%s: %w (%s)", strings.Join(args, " "), err, strings.TrimSpace(string(out))) + } + return nil + } + nsExec := func(args ...string) error { + full := append([]string{"ip", "netns", "exec", nsName}, args...) + return run(full...) + } + + if err := run("ip", "netns", "add", nsName); err != nil { + // Already exists is fine after a partial teardown. + if !strings.Contains(err.Error(), "File exists") { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + return err + } + } + // Loopback inside ns. + _ = nsExec("ip", "link", "set", "lo", "up") + + if err := run("ip", "link", "add", wgDev, "type", "wireguard"); err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + return err + } + if err := run("ip", "link", "set", wgDev, "netns", nsName); err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = run("ip", "link", "del", wgDev) + return err + } + + setconfPath := filepath.Join(m.profileDir(name), "wg.setconf") + body := wgSetconfBody(string(raw)) + if err := os.WriteFile(setconfPath, []byte(body), 0o600); err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + return err + } + if err := nsExec("wg", "setconf", wgDev, setconfPath); err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + for _, a := range addrs { + if err := nsExec("ip", "address", "add", a, "dev", wgDev); err != nil { + // "File exists" after restart is fine. + if !strings.Contains(err.Error(), "File exists") { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + } + } + if err := nsExec("ip", "link", "set", wgDev, "up"); err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + // Default route only inside the netns — never the host table. + _ = nsExec("ip", "route", "replace", "default", "dev", wgDev) + + if err := run("ip", "link", "add", hostVeth, "type", "veth", "peer", "name", nsVeth); err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + if err := run("ip", "link", "set", nsVeth, "netns", nsName); err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + if err := run("ip", "addr", "add", hostIP+"/24", "dev", hostVeth); err != nil && !strings.Contains(err.Error(), "File exists") { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + if err := run("ip", "link", "set", hostVeth, "up"); err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + if err := nsExec("ip", "addr", "add", nsIP+"/24", "dev", nsVeth); err != nil && !strings.Contains(err.Error(), "File exists") { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + if err := nsExec("ip", "link", "set", nsVeth, "up"); err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + + socksCmd, err := m.startSocksInNS(nsName, socksBin, nsIP) + if err != nil { + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + + ln, stopFwd, err := m.startLocalForward(listenPort, nsIP, socksPortInNS) + if err != nil { + _ = socksCmd.Process.Kill() + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0) + _ = m.teardownWireGuard(name, p.ID) + return err + } + + rs := &runState{ + name: name, + listenPort: listenPort, + nsIP: nsIP, + socksCmd: socksCmd, + forwardLn: ln, + stopFwd: stopFwd, + } + m.mu.Lock() + m.running[name] = rs + m.mu.Unlock() + + egressIP := probeEgressIP(nsName) + _ = m.Store.SetEgressRuntime(p.ID, db.EgressUp, "", egressIP, listenPort) + m.logger().Info("egress up", "name", name, "listen", listenPort, "ns", nsName, "egress_ip", egressIP) + return nil +} + +func (m *Manager) startSocksInNS(nsName, socksBin, bindIP string) (*exec.Cmd, error) { + base := filepath.Base(socksBin) + var cmd *exec.Cmd + switch { + case strings.Contains(base, "gost"): + cmd = exec.Command("ip", "netns", "exec", nsName, socksBin, + "-L", fmt.Sprintf("socks5://%s:%d", bindIP, socksPortInNS)) + default: + // microsocks + cmd = exec.Command("ip", "netns", "exec", nsName, socksBin, + "-i", bindIP, "-p", fmt.Sprintf("%d", socksPortInNS)) + } + cmd.Stdout = nil + cmd.Stderr = nil + if err := cmd.Start(); err != nil { + return nil, fmt.Errorf("start socks in netns: %w", err) + } + // Brief wait so a crash-on-start is visible. + time.Sleep(200 * time.Millisecond) + if cmd.ProcessState != nil && cmd.ProcessState.Exited() { + return nil, fmt.Errorf("socks exited immediately") + } + return cmd, nil +} + +func (m *Manager) teardownWireGuard(name string, _ int64) error { + nsName := netnsName(name) + wgDev := wgDevName(name) + hostVeth := hostVethName(name) + + runQuiet := func(args ...string) { + _ = exec.Command(args[0], args[1:]...).Run() + } + runQuiet("ip", "netns", "exec", nsName, "ip", "link", "del", wgDev) + runQuiet("ip", "link", "del", hostVeth) + runQuiet("ip", "link", "del", wgDev) // if still in init ns + runQuiet("ip", "netns", "del", nsName) + _ = os.Remove(filepath.Join(m.profileDir(name), "wg.setconf")) + return nil +} + +func netnsName(name string) string { + return "streamd-" + name +} + +func wgDevName(name string) string { + // IFNAMSIZ is 15. + s := "wg-" + name + if len(s) > 15 { + s = s[:15] + } + return s +} + +func hostVethName(name string) string { + s := "sv-" + name + if len(s) > 15 { + s = s[:15] + } + return s +} + +func probeEgressIP(nsName string) string { + // Best-effort: ask a public echo over the ns default route. + cmd := exec.Command("ip", "netns", "exec", nsName, + "curl", "-4", "-fsS", "--max-time", "5", "https://ifconfig.me/ip") + out, err := cmd.Output() + if err != nil { + cmd = exec.Command("ip", "netns", "exec", nsName, + "wget", "-qO-", "--timeout=5", "https://ifconfig.me/ip") + out, err = cmd.Output() + if err != nil { + return "" + } + } + return strings.TrimSpace(string(out)) +} diff --git a/apps/streamd/internal/egress/wg_stub.go b/apps/streamd/internal/egress/wg_stub.go new file mode 100644 index 0000000..065d686 --- /dev/null +++ b/apps/streamd/internal/egress/wg_stub.go @@ -0,0 +1,19 @@ +//go:build !linux + +package egress + +import ( + "fmt" + + "streamd/apps/streamd/internal/db" +) + +func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error { + msg := "wireguard egress requires Linux" + _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0) + return fmt.Errorf("%s", msg) +} + +func (m *Manager) teardownWireGuard(name string, id int64) error { + return nil +} diff --git a/apps/streamd/internal/modstore/modstore.go b/apps/streamd/internal/modstore/modstore.go index f527d58..b6acdff 100644 --- a/apps/streamd/internal/modstore/modstore.go +++ b/apps/streamd/internal/modstore/modstore.go @@ -28,6 +28,9 @@ const ( var NameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`) +// archDirRe matches .bin/-/ folder names (never a module name). +var archDirRe = regexp.MustCompile(`^[a-z0-9]+-(amd64|arm64|386|arm)$`) + // Info is one module's metadata for the API and agent sync. type Info struct { Name string `json:"name"` @@ -387,23 +390,7 @@ func inspectZipReader(zr *zip.Reader, nameHint string) (string, []zipEntry, erro } if hint == "" { - // Try to infer from .bin// or .bin/. - for _, f := range zr.File { - n := strings.ReplaceAll(f.Name, "\\", "/") - n = strings.TrimPrefix(n, "./") - if prefix != "" { - if !strings.HasPrefix(n, prefix) { - continue - } - n = strings.TrimPrefix(n, prefix) - } - base := filepath.Base(n) - base = strings.TrimSuffix(base, ".exe") - if strings.HasPrefix(n, ".bin/") && NameRe.MatchString(base) && base != ".bin" { - hint = base - break - } - } + hint = inferNameFromBinEntries(zr, prefix) } if hint == "" { return "", nil, fmt.Errorf("cannot infer module name from zip; pass name=") @@ -476,6 +463,47 @@ func extractZipEntries(zipBytes []byte, entries []zipEntry, destDir string) erro return nil } +// inferNameFromBinEntries picks the module binary basename from +// .bin//[.exe] or .bin/[.exe]. Directory entries and +// arch folder names (linux-amd64, darwin-arm64, …) are skipped — those used +// to be mistaken for the module name on flat release zips. +func inferNameFromBinEntries(zr *zip.Reader, prefix string) string { + var fallback string + for _, f := range zr.File { + if f.FileInfo().IsDir() { + continue + } + n := strings.ReplaceAll(f.Name, "\\", "/") + n = strings.TrimPrefix(n, "./") + if prefix != "" { + if !strings.HasPrefix(n, prefix) { + continue + } + n = strings.TrimPrefix(n, prefix) + } + n = strings.TrimSuffix(n, "/") + if !strings.HasPrefix(n, ".bin/") { + continue + } + rel := strings.TrimPrefix(n, ".bin/") + parts := strings.Split(rel, "/") + base := parts[len(parts)-1] + base = strings.TrimSuffix(base, ".exe") + if !NameRe.MatchString(base) || archDirRe.MatchString(base) { + continue + } + // Prefer .bin// + if len(parts) >= 2 && archDirRe.MatchString(parts[0]) { + return base + } + // .bin/ + if len(parts) == 1 && fallback == "" { + fallback = base + } + } + return fallback +} + func isUnder(root, path string) bool { absRoot, err1 := filepath.Abs(root) absPath, err2 := filepath.Abs(path) diff --git a/apps/streamd/internal/modstore/modstore_test.go b/apps/streamd/internal/modstore/modstore_test.go index edb3096..bcd841c 100644 --- a/apps/streamd/internal/modstore/modstore_test.go +++ b/apps/streamd/internal/modstore/modstore_test.go @@ -29,6 +29,27 @@ func makeZip(t *testing.T, files map[string][]byte) []byte { return buf.Bytes() } +func TestInstallZipInfersNameNotArchDir(t *testing.T) { + // Flat release zips list .bin/darwin-arm64/ before the binary; that arch + // folder must not become the module name. + root := t.TempDir() + s := New(root) + zipBytes := makeZip(t, map[string][]byte{ + "module.yaml": []byte("package: air.RTE\nchannels:\n rteone: {label: One}\n"), + ".bin/": nil, // directory markers via path only + ".bin/darwin-arm64/rte": []byte("mac-bin"), + ".bin/linux-amd64/rte": []byte("linux-bin"), + ".bin/windows-amd64/rte.exe": []byte("win-bin"), + }) + info, err := s.InstallZip(zipBytes, "") + if err != nil { + t.Fatalf("InstallZip: %v", err) + } + if info.Name != "rte" { + t.Fatalf("inferred name=%q want rte", info.Name) + } +} + func TestInstallZipFlatAndYAMLOnly(t *testing.T) { root := t.TempDir() s := New(root) diff --git a/apps/streamd/internal/supervisor/media.go b/apps/streamd/internal/supervisor/media.go index 91aa7c0..a191be2 100644 --- a/apps/streamd/internal/supervisor/media.go +++ b/apps/streamd/internal/supervisor/media.go @@ -37,12 +37,19 @@ type Media struct { // ViewersFn reports the live client count for a stream, for the metrics // series. Optional. ViewersFn func(streamName string) int + // ProxyResolver resolves stream.Proxy / stream.Egress to a SOCKS/HTTP URL. + ProxyResolver ProxyResolver mu sync.Mutex procs map[int64]*streamProc stopMon chan struct{} } +// ProxyResolver turns a stream row into an origin-fetch proxy URL. +type ProxyResolver interface { + ResolveProxy(st db.Stream) (string, error) +} + // Notifier is the subset of the websocket hub the supervisor needs. type Notifier interface { NotifyRuntime(name, health string) @@ -82,15 +89,16 @@ type streamProc struct { // Options for constructing the media supervisor. type Options struct { - Store *db.Store - DataDir string - NRE string - FFmpeg string - MP4Decrypt string - Log *slog.Logger - Fanout *tsfanout.Set - Notifier Notifier - ViewersFn func(streamName string) int + Store *db.Store + DataDir string + NRE string + FFmpeg string + MP4Decrypt string + Log *slog.Logger + Fanout *tsfanout.Set + Notifier Notifier + ViewersFn func(streamName string) int + ProxyResolver ProxyResolver } func NewMedia(opt Options) *Media { @@ -103,17 +111,18 @@ func NewMedia(opt Options) *Media { fan = tsfanout.NewSet(tsfanout.DefaultBufferBytes) } m := &Media{ - Store: opt.Store, - DataDir: opt.DataDir, - NRE: opt.NRE, - FFmpeg: opt.FFmpeg, - MP4Decrypt: opt.MP4Decrypt, - Log: lg, - Fanout: fan, - Notifier: opt.Notifier, - ViewersFn: opt.ViewersFn, - procs: map[int64]*streamProc{}, - stopMon: make(chan struct{}), + Store: opt.Store, + DataDir: opt.DataDir, + NRE: opt.NRE, + FFmpeg: opt.FFmpeg, + MP4Decrypt: opt.MP4Decrypt, + Log: lg, + Fanout: fan, + Notifier: opt.Notifier, + ViewersFn: opt.ViewersFn, + ProxyResolver: opt.ProxyResolver, + procs: map[int64]*streamProc{}, + stopMon: make(chan struct{}), } go m.monitorLoop() return m @@ -143,6 +152,13 @@ func (m *Media) Running(id int64) bool { func (m *Media) logsDir() string { return filepath.Join(m.DataDir, "logs") } +func (m *Media) effectiveProxy(st db.Stream) (string, error) { + if m.ProxyResolver != nil { + return m.ProxyResolver.ResolveProxy(st) + } + return strings.TrimSpace(st.Proxy), nil +} + func (m *Media) Start(id int64) error { st, err := m.Store.GetStream(id) if err != nil { @@ -203,12 +219,17 @@ func (m *Media) Start(id int64) error { saveName := st.Name headers := headerMap(st.HeadersJSON) cfg := settingsFor(st, m.Store.GlobalPackagerSettings()) + originProxy, err := m.effectiveProxy(st) + if err != nil { + m.fail(id, st.Name, "egress: "+err.Error()) + return err + } manifestURL := st.MPD var mpdProxy *mpd.LocalServer // The rewriter is named by the stream row or its app module and looked up in // the mpd registry, so streamd needs no knowledge of any provider. if rw, needed := mpd.Lookup(cfg.Rewriter); needed && strings.TrimSpace(st.MPD) != "" && !cfg.IsHLS { - srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, st.Proxy) + srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, originProxy) if err != nil { m.fail(id, st.Name, "mpd rewrite server: "+err.Error()) return err @@ -246,7 +267,7 @@ func (m *Media) Start(id int64) error { "--mp4-real-time-decryption", ) } - if proxy := strings.TrimSpace(st.Proxy); proxy != "" { + if proxy := strings.TrimSpace(originProxy); proxy != "" { // NRE prefers --custom-proxy over the system proxy when both are set. // The proxy may carry credentials, so it is not logged. nreArgs = append(nreArgs, "--custom-proxy", proxy) diff --git a/apps/streamd/internal/ui/static/js/api.js b/apps/streamd/internal/ui/static/js/api.js index 0c4816d..1329da1 100644 --- a/apps/streamd/internal/ui/static/js/api.js +++ b/apps/streamd/internal/ui/static/js/api.js @@ -117,6 +117,20 @@ export const api = { patchSchedule: (sid, body) => api.patch(`/api/schedules/${sid}`, body), deleteSchedule: (sid) => api.del(`/api/schedules/${sid}`), + // --- egress tunnels --- + egress: () => api.get("/api/egress"), + egressProfiles: () => api.get("/api/egress"), + egressProfile: (name) => api.get(`/api/egress/${encodeURIComponent(name)}`), + createEgress: (body) => api.post("/api/egress", body), + saveEgress: (name, body) => api.put(`/api/egress/${encodeURIComponent(name)}`, body), + updateEgress: (name, body) => api.put(`/api/egress/${encodeURIComponent(name)}`, body), + deleteEgress: (name) => api.del(`/api/egress/${encodeURIComponent(name)}`), + egressUp: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/up`), + egressDown: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/down`), + egressTest: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/test`), + egressConf: (name, conf) => + api.put(`/api/egress/${encodeURIComponent(name)}/conf`, { conf }), + // --- admin --- settings: () => api.get("/api/settings"), saveSettings: (body) => api.put("/api/settings", body), diff --git a/apps/streamd/internal/ui/static/js/util.js b/apps/streamd/internal/ui/static/js/util.js index ccceae2..3b2da13 100644 --- a/apps/streamd/internal/ui/static/js/util.js +++ b/apps/streamd/internal/ui/static/js/util.js @@ -36,6 +36,11 @@ export function el(spec, attrs, ...children) { else if (k === "dataset") Object.assign(node.dataset, v); else if (k === "style" && typeof v === "object") Object.assign(node.style, v); else if (k.startsWith("on") && typeof v === "function") node.addEventListener(k.slice(2), v); + // Form controls: set the live property. setAttribute("value") does not fill + //