Streamd v0.2.0: rename, modules panel, stable/beta channels
All checks were successful
release / build-and-upload (push) Successful in 7m5s

- 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
This commit is contained in:
404errordeveloper 2026-10-10 15:58:26 +02:00
parent 066e018749
commit da8e1123ec
140 changed files with 2949 additions and 851 deletions

View file

@ -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 # Triggers:
# git tag v1.2.3 && git push origin v1.2.3 # 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-<pre> → 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 # Requires a Forgejo Actions runner registered against this instance
# (label must match runs-on below — default act_runner often uses "docker"). # (label must match runs-on below — default act_runner often uses "docker").
@ -23,6 +32,35 @@ jobs:
with: with:
fetch-depth: 0 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 - name: Setup Go
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
@ -37,44 +75,94 @@ jobs:
./scripts/build-release.sh "${{ github.ref_name }}" ./scripts/build-release.sh "${{ github.ref_name }}"
ls -la dist/release 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 <<EOF
Multi-platform **Streamd** host CLI + on-device MITM (\`proxy-android-arm64\`).
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 |
| \`streamd-windows-arm64.exe\` | Windows ARM64 |
| \`streamd-linux-amd64\` | Linux x86_64 |
| \`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 |
Always-latest URLs (no version pin):
- Stable: \`…/releases/download/stable/<asset>\`
- Beta: \`…/releases/download/beta/<asset>\`
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 <<EOF
Rolling **${CHANNEL}** channel for Streamd.
Currently points at **${TAG}**.
Prefer versioned tags for pinned installs; use this channel for always-latest downloads.
\`\`\`text
…/releases/download/${CHANNEL}/streamd-linux-amd64
…/releases/download/${CHANNEL}/streamd-windows-amd64.exe
…/releases/download/${CHANNEL}/proxy-android-arm64
\`\`\`
EOF
- name: Upload versioned Forgejo release
uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2 uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2
with: with:
direction: upload direction: upload
# Defaults to this runner's Forgejo URL when omitted.
url: https://git.nulldrm.com url: https://git.nulldrm.com
repo: ${{ github.repository }} repo: ${{ github.repository }}
# Built-in job token (write:repository). Override with a PAT secret if needed.
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ github.ref_name }} tag: ${{ github.ref_name }}
sha: ${{ github.sha }} sha: ${{ github.sha }}
release-dir: dist/release release-dir: dist/release
title: ${{ github.ref_name }} title: ${{ steps.meta.outputs.title }}
prerelease: ${{ steps.meta.outputs.prerelease }}
override: true override: true
release-notes: | release-notes-file: /tmp/release-notes.md
Multi-platform `drm` host CLI + on-device MITM (`proxy-android-arm64`).
| Asset | Platform | - name: Upload rolling channel release (stable / beta)
|---|---| uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2
| `drm-windows-amd64.exe` | Windows x86_64 | with:
| `drm-windows-arm64.exe` | Windows ARM64 | direction: upload
| `drm-linux-amd64` | Linux x86_64 | url: https://git.nulldrm.com
| `drm-linux-arm64` | Linux ARM64 | repo: ${{ github.repository }}
| `drm-darwin-amd64` | macOS Intel | token: ${{ secrets.GITHUB_TOKEN }}
| `drm-darwin-arm64` | macOS Apple Silicon | tag: ${{ steps.meta.outputs.channel }}
| `proxy-android-arm64` | On-device MITM (push with `drm proxy`) | sha: ${{ github.sha }}
| `SHA256SUMS.txt` | Checksums | release-dir: dist/release
title: ${{ steps.meta.outputs.channel }} ← ${{ github.ref_name }}
Built with `CGO_ENABLED=0` via `scripts/build-release.sh`. prerelease: ${{ steps.meta.outputs.prerelease }}
Phone capture still needs Magisk + `drm proxy install-ca --reinject`. override: true
release-notes-file: /tmp/channel-notes.md
- name: Announce on Telegram - name: Announce on Telegram
env: env:
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
# Private DM chat (@error404developer). Override via secret if needed.
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }} TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
RELEASE_TAG: ${{ github.ref_name }} RELEASE_TAG: ${{ github.ref_name }}
RELEASE_KIND: host RELEASE_KIND: host
RELEASE_CHANNEL: ${{ steps.meta.outputs.channel }}
RELEASE_URL: https://git.nulldrm.com/${{ github.repository }}/releases/tag/${{ github.ref_name }} RELEASE_URL: https://git.nulldrm.com/${{ github.repository }}/releases/tag/${{ github.ref_name }}
run: | run: |
if [ -z "$TELEGRAM_BOT_TOKEN" ]; then if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
@ -84,5 +172,10 @@ jobs:
# Null DRM Telegram group → Releases topic (t.me/c/3721978702/16). # Null DRM Telegram group → Releases topic (t.me/c/3721978702/16).
export TELEGRAM_CHAT_ID="-1003721978702" export TELEGRAM_CHAT_ID="-1003721978702"
export TELEGRAM_MESSAGE_THREAD_ID="16" export TELEGRAM_MESSAGE_THREAD_ID="16"
if [ "${{ steps.meta.outputs.channel }}" = "beta" ]; then
export RELEASE_TITLE="Streamd ${{ github.ref_name }} (beta)"
else
export RELEASE_TITLE="Streamd ${{ github.ref_name }}"
fi
chmod +x scripts/notify-telegram.sh chmod +x scripts/notify-telegram.sh
./scripts/notify-telegram.sh "${{ github.ref_name }}" ./scripts/notify-telegram.sh "${{ github.ref_name }}"

108
README.md
View file

@ -1,9 +1,9 @@
# 🔓 Null DRM # 📺 Streamd
**Next-generation open-source DRM decryption for Android streaming apps.** **Next-generation open-source DRM decryption for Android streaming apps.**
Capture live sessions from phones (BBC iPlayer, RTÉ, TG4, ITVX, Channel 4, …), pull manifests Capture live sessions from phones (BBC iPlayer, RTÉ, TG4, ITVX, Channel 4, …), pull manifests
and licenses through a transparent MITM, and restream. One host binary — **`drm`** — and licenses through a transparent MITM, and restream. One host binary — **`streamd`** —
plus drop-in providers under **`modules/`**. plus drop-in providers under **`modules/`**.
📦 Releases: [git.nulldrm.com](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases) 📦 Releases: [git.nulldrm.com](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases)
@ -30,7 +30,7 @@ traffic.
## 🖥️ streamd dashboard ## 🖥️ streamd dashboard
Run `drm serve`, open the panel in a browser, manage streams and API keys: Run `streamd serve`, open the panel in a browser, manage streams and API keys:
<p align="center"> <p align="center">
<img src="docs/images/streamd/dashboard.jpg" alt="streamd Dashboard — overview, live Channel 4, HLS link" width="720" /> <img src="docs/images/streamd/dashboard.jpg" alt="streamd Dashboard — overview, live Channel 4, HLS link" width="720" />
@ -64,15 +64,55 @@ Server setup guide: [docs/streamd-server-setup.md](docs/streamd-server-setup.md)
### 1️⃣ Download ### 1️⃣ Download
From the latest **`v*`** release grab your host binary (e.g. `drm-windows-amd64.exe`) Host binaries ship on two rolling channels (always the newest build — no version pin):
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`). | 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 ```text
Null-DRM/ Streamd/
drm.exe # or ./drm on Linux/macOS streamd.exe # or ./streamd on Linux/macOS (drm.exe also shipped as a compat copy)
bin/proxy-android-arm64 # optional; also embedded in release drm bin/proxy-android-arm64 # optional; also embedded in the release binary
modules/ modules/ # or upload zips in the streamd Modules page
bbc/ # unzip bbc.zip here bbc/ # unzip bbc.zip here
rte/ rte/
tg4/ tg4/
@ -81,7 +121,7 @@ Null-DRM/
outputs/ # created on first run 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 ### 2️⃣ Prerequisites
@ -99,14 +139,14 @@ Unzip into `modules/<name>/`. Edit **`module.yaml`** — fill sensitive fields o
almost nothing extra. almost nothing extra.
```bash ```bash
drm modules streamd modules
# or: drm --modules-dir D:\mods modules # or: streamd --modules-dir D:\mods modules
``` ```
### 4️⃣ Phone CA (once per device / CA) ### 4️⃣ Phone CA (once per device / CA)
```bash ```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 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 ```bash
# BBC + NordVPN UK on the phone (transparent MITM; --channel auto-plays) # BBC + NordVPN UK on the phone (transparent MITM; --channel auto-plays)
drm capture --app bbc --channel bbcone --wait 120 streamd capture --app bbc --channel bbcone --wait 120
drm capture --app bbc --channel s4c --wait 120 streamd capture --app bbc --channel s4c --wait 120
# ITVX (UK VPN; Live tab autoplay) # 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 # Channel 4 — one channel, or every Live channel
drm capture --app c4 --channel channel4 --wait 90 streamd capture --app c4 --channel channel4 --wait 90
drm capture --app c4 --all --wait 90 streamd capture --app c4 --all --wait 90
# Grab every channel for any module # 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) # RTE / TG4 (keys via --wvd when needed)
drm capture --app rte --channel rteone --wvd data/device.wvd streamd capture --app rte --channel rteone --wvd data/device.wvd
drm capture --app tg4 --channel ioi --wvd data/device.wvd streamd capture --app tg4 --channel ioi --wvd data/device.wvd
# Catalog only (no phone) — TG4 # 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/<app>/<stamp>/` (and `latest/`). 📁 Results land in `outputs/<app>/<stamp>/` (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 ### 6️⃣ Clean the phone after a run
```bash ```bash
drm proxy reset streamd proxy reset
``` ```
Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fresh. 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 ## 🧾 Command cheat sheet
```text ```text
drm [--modules-dir DIR] <command> … streamd [--modules-dir DIR] <command> …
drm modules streamd modules
drm capture --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S] streamd capture --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S]
drm catalog --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list] streamd catalog --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list]
drm proxy install-ca [--reinject] | reset [--keep-captures] streamd proxy install-ca [--reinject] | reset [--keep-captures]
| transparent --package PKG [--mitm-host HOST] | transparent --package PKG [--mitm-host HOST]
| start | stop | push | discover | pull | start | stop | push | discover | pull
drm serve [--bind …] [--data …] [--token …] streamd serve [--bind …] [--data …] [--token …]
drm agent run|status|devices|enqueue|cancel [--config …] 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). 🎯 `--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 ```bash
git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official.git git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official.git
cd Null-DRM-Official 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 # Host release: .\scripts\build-release.ps1 -Version v0.1.1
# Modules: .\scripts\build-modules-release.ps1 -Version modules-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 ## 💚 Support the project
If Null DRM saves you time, donations keep development going: If Streamd saves you time, donations keep development going:
| Coin | Address | | Coin | Address |
|------|---------| |------|---------|

View file

@ -1,6 +1,6 @@
# agent # 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 ```text
apps/agent/ apps/agent/
@ -26,30 +26,33 @@ expire by themselves if the agent dies.
```bash ```bash
# terminal 1 — control plane # 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) # terminal 2 — agent (operator API key from streamd Settings → API keys)
export STREAMD_API_KEY=ndk_… export STREAMD_API_KEY=ndk_…
# or legacy: export STREAMD_TOKEN=… # or legacy: export STREAMD_TOKEN=…
./bin/drm agent run --config apps/agent/agent.yaml ./bin/streamd agent run --config apps/agent/agent.yaml
``` ```
```bash ```bash
./bin/drm agent status ./bin/streamd agent status
./bin/drm agent devices ./bin/streamd agent devices
./bin/drm agent enqueue --stream tg4-ioi --reason manual ./bin/streamd agent enqueue --stream tg4-ioi --reason manual
./bin/drm agent cancel --job 3 ./bin/streamd agent cancel --job 3
``` ```
App modules are discovered under `modules/`. The agent drives whichever module a With `sync_modules: true` (default in the sample config), the agent **pulls**
stream names and contains no provider logic. provider modules from the streamd Modules page into `<data_dir>/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 ## Config
`agent.yaml` — `streamd_url`, **`api_key`** (preferred) or `token` (alias), or `agent.yaml` — `streamd_url`, **`api_key`** (preferred) or `token` (alias), or
env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`, env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
`max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device), `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 `<data_dir>/modules`), `modules_sync_interval_sec`, `modules_prune`.
Create the key in the streamd dashboard (role **operator**). The legacy shared Create the key in the streamd dashboard (role **operator**). The legacy shared
`--token` / `STREAMD_TOKEN` still works but is meant for migration only. `--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 ## Build
```bash ```bash
go -C apps/cli build -o ../../bin/drm . go -C apps/cli build -o ../../bin/streamd .
# cross-compile # 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)** **Full guide: [docs/streamd.md](../../docs/streamd.md)**

View file

@ -14,10 +14,11 @@ workers: 1 # concurrent ADB jobs
max_attempts: 5 max_attempts: 5
capture_wait_sec: 180 capture_wait_sec: 180
devices: [] # empty = all adb "device" serials; never installs apps devices: [] # empty = all adb "device" serials; never installs apps
# Push local modules/<name>/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 sync_modules: true
# modules_dir: modules # optional override (default: repo modules/) # modules_dir: # optional; default <data_dir>/modules
# modules_sync_interval_sec: 300 # 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 # Required for key fetch. Relative paths resolve from the repo root
# (DRM-Decryption/), not from C:\Users\admin\Programming\. # (DRM-Decryption/), not from C:\Users\admin\Programming\.
wvd: wvd:

View file

@ -12,14 +12,15 @@ import (
"syscall" "syscall"
"text/tabwriter" "text/tabwriter"
"drmdecryption/apps/agent/internal/client" "streamd/apps/agent/internal/client"
"drmdecryption/apps/agent/internal/config" "streamd/apps/agent/internal/config"
"drmdecryption/apps/agent/internal/device" "streamd/apps/agent/internal/device"
"drmdecryption/apps/agent/internal/modsync" "streamd/apps/agent/internal/modsync"
"drmdecryption/apps/agent/internal/poller" "streamd/apps/agent/internal/poller"
"drmdecryption/apps/agent/internal/queue" "streamd/apps/agent/internal/queue"
"drmdecryption/apps/agent/internal/worker" "streamd/apps/agent/internal/worker"
"drmdecryption/apps/agent/internal/wsclient" "streamd/apps/agent/internal/wsclient"
"streamd/modhost"
) )
// Run dispatches an agent subcommand. args[0] is the subcommand name. // 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) 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 { if cfg.SyncModules {
ms := &modsync.Syncer{ ms = &modsync.Syncer{
API: api, API: api,
ModulesDir: cfg.ModulesDir, ModulesDir: cfg.ModulesDir,
Interval: cfg.ModulesSyncInterval(), Interval: cfg.ModulesSyncInterval(),
Prune: cfg.ModulesPrune,
Log: log.Default(), Log: log.Default(),
} }
go ms.Loop(stop) 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()) 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() go ws.Loop()
for i := 0; i < cfg.Workers; i++ { for i := 0; i < cfg.Workers; i++ {

View file

@ -1,12 +1,12 @@
module drmdecryption/apps/agent module streamd/apps/agent
go 1.25.0 go 1.25.0
require ( require (
drmdecryption v0.0.0
github.com/gorilla/websocket v1.5.3 github.com/gorilla/websocket v1.5.3
gopkg.in/yaml.v3 v3.0.1 gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.34.5 modernc.org/sqlite v1.34.5
streamd v0.0.0
) )
require ( require (
@ -15,11 +15,10 @@ require (
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // 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 golang.org/x/sys v0.42.0 // indirect
modernc.org/libc v1.55.3 // indirect modernc.org/libc v1.55.3 // indirect
modernc.org/mathutil v1.6.0 // indirect modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.8.0 // indirect modernc.org/memory v1.8.0 // indirect
) )
replace drmdecryption => ../pkg replace streamd => ../pkg

View file

@ -1,7 +1,5 @@
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= 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/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 h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= 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= 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/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 h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= 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 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 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= 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/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 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc= 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 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 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 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View file

@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"os"
"strings" "strings"
"time" "time"
) )
@ -183,6 +184,10 @@ type ModuleInfo struct {
Name string `json:"name"` Name string `json:"name"`
HasYAML bool `json:"has_yaml"` HasYAML bool `json:"has_yaml"`
YAMLSHA256 string `json:"yaml_sha256,omitempty"` 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) { func (c *Client) ListModules() ([]ModuleInfo, error) {
@ -199,30 +204,64 @@ func (c *Client) ListModules() ([]ModuleInfo, error) {
return wrap.Modules, nil return wrap.Modules, nil
} }
// PutModuleYAML uploads raw module.yaml bytes for name (Content-Type text/yaml). // GetModuleYAML downloads raw module.yaml bytes for name.
func (c *Client) PutModuleYAML(name string, yamlBytes []byte) error { func (c *Client) GetModuleYAML(name string) ([]byte, error) {
req, err := http.NewRequest(http.MethodPut, c.BaseURL+"/api/modules/"+name, bytes.NewReader(yamlBytes)) 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 { if err != nil {
return err return err
} }
req.Header.Set("Content-Type", "text/yaml")
c.setHeaders(req) c.setHeaders(req)
resp, err := c.HTTP.Do(req) resp, err := c.HTTP.Do(req)
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode >= 300 { 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) { func (c *Client) setHeaders(req *http.Request) {
ua := c.UserAgent ua := c.UserAgent
if ua == "" { if ua == "" {
ua = "drm-agent/" + Version ua = "streamd-agent/" + Version
} }
req.Header.Set("User-Agent", ua) req.Header.Set("User-Agent", ua)
if c.Token != "" { if c.Token != "" {

View file

@ -7,7 +7,7 @@ import (
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"drmdecryption/repo" "streamd/repo"
) )
type Config struct { type Config struct {
@ -27,10 +27,11 @@ type Config struct {
WVD string `yaml:"wvd"` // path to .wvd device file (required for key fetch) WVD string `yaml:"wvd"` // path to .wvd device file (required for key fetch)
UserAgent string `yaml:"user_agent"` UserAgent string `yaml:"user_agent"`
AgentID string `yaml:"agent_id"` AgentID string `yaml:"agent_id"`
// SyncModules pushes local modules/<name>/module.yaml to streamd when missing/stale. // SyncModules pulls modules from streamd into the local cache when missing/stale.
SyncModules bool `yaml:"sync_modules"` SyncModules bool `yaml:"sync_modules"`
ModulesDir string `yaml:"modules_dir"` // empty = repo modules/ ModulesDir string `yaml:"modules_dir"` // empty = <data_dir>/modules
ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"` 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 // OnDemandPriority lets a capture that streamd pushed — a viewer waking
// an on-demand stream, or a scheduled event about to start — jump ahead // an on-demand stream, or a scheduled event about to start — jump ahead
// of routine refreshes in the queue. // of routine refreshes in the queue.
@ -124,7 +125,9 @@ func applyDefaults(cfg Config, root string) Config {
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) { if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
cfg.WVD = filepath.Join(root, 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) cfg.ModulesDir = filepath.Join(root, cfg.ModulesDir)
} }
if cfg.ModulesSyncIntervalSec <= 0 { if cfg.ModulesSyncIntervalSec <= 0 {

View file

@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"sync" "sync"
"drmdecryption/adb" "streamd/adb"
) )
// Pool tracks free/busy ADB devices. Never installs apps. // Pool tracks free/busy ADB devices. Never installs apps.

View file

@ -1,26 +1,32 @@
// Package modsync pushes local modules/<name>/module.yaml to streamd // Package modsync pulls provider modules from streamd into a local cache.
// when the remote copy is missing or the SHA-256 differs. // 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 package modsync
import ( import (
"archive/zip"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"fmt"
"io"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"strings" "strings"
"time" "time"
"drmdecryption/apps/agent/internal/client" "streamd/apps/agent/internal/client"
"drmdecryption/modhost" "streamd/modhost"
"drmdecryption/repo" "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 { type Syncer struct {
API *client.Client API *client.Client
ModulesDir string // empty = modhost.ModulesDir(repo.Root()) ModulesDir string // empty = <data_dir>/modules resolved by caller, or modhost default
Interval time.Duration Interval time.Duration
Prune bool // remove local modules absent from the panel
Log *log.Logger Log *log.Logger
} }
@ -31,15 +37,10 @@ func (s *Syncer) modulesDir() string {
return modhost.ModulesDir(repo.Root()) 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 { func (s *Syncer) Once() error {
dir := s.modulesDir() dir := s.modulesDir()
ents, err := os.ReadDir(dir) if err := os.MkdirAll(dir, 0o755); err != nil {
if err != nil {
if os.IsNotExist(err) {
s.logf("modules sync: no local dir %s", dir)
return nil
}
return err return err
} }
@ -47,42 +48,139 @@ func (s *Syncer) Once() error {
if err != nil { if err != nil {
return err return err
} }
byName := make(map[string]client.ModuleInfo, len(remote)) seen := map[string]struct{}{}
for _, m := range remote { 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 { for _, e := range ents {
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") { if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
continue continue
} }
name := e.Name() if _, ok := keep[e.Name()]; ok {
yamlPath := filepath.Join(dir, name, "module.yaml")
raw, err := os.ReadFile(yamlPath)
if err != nil {
if os.IsNotExist(err) {
continue continue
} }
s.logf("modules sync: read %s: %v", yamlPath, err) path := filepath.Join(dir, e.Name())
if err := os.RemoveAll(path); err != nil {
s.logf("modules sync: prune %s: %v", e.Name(), err)
continue continue
} }
sum := sha256.Sum256(raw) s.logf("modules sync: pruned %s", e.Name())
localSHA := hex.EncodeToString(sum[:])
rm, ok := byName[name]
if ok && rm.HasYAML && strings.EqualFold(rm.YAMLSHA256, localSHA) {
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)
}
}
return nil
} }
// Loop runs Once immediately, then on Interval until stop closes. // 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...) 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
}

View file

@ -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)
}
}

View file

@ -6,8 +6,8 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/apps/agent/internal/client" "streamd/apps/agent/internal/client"
"drmdecryption/apps/agent/internal/queue" "streamd/apps/agent/internal/queue"
) )
type Poller struct { type Poller struct {

View file

@ -7,14 +7,14 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/modhost" "streamd/modhost"
"drmdecryption/phonecap" "streamd/phonecap"
"drmdecryption/repo" "streamd/repo"
"drmdecryption/apps/agent/internal/client" "streamd/apps/agent/internal/client"
"drmdecryption/apps/agent/internal/device" "streamd/apps/agent/internal/device"
"drmdecryption/apps/agent/internal/poller" "streamd/apps/agent/internal/poller"
"drmdecryption/apps/agent/internal/queue" "streamd/apps/agent/internal/queue"
) )
type Worker struct { type Worker struct {

View file

@ -11,7 +11,7 @@ import (
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"drmdecryption/apps/agent/internal/client" "streamd/apps/agent/internal/client"
) )
// Message is one push from streamd. // 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 // OnStreamChanged is called when a stream was edited, so the agent can
// re-poll instead of waiting out its interval. // re-poll instead of waiting out its interval.
OnStreamChanged func(name, reason string) 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{} stop chan struct{}
} }
@ -111,7 +114,7 @@ func (c *Client) session() error {
if c.AgentID != "" { if c.AgentID != "" {
hdr.Set("X-Agent-ID", 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} dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
conn, resp, err := dialer.Dial(u.String(), hdr) conn, resp, err := dialer.Dial(u.String(), hdr)
if err != nil { if err != nil {
@ -190,6 +193,11 @@ func (c *Client) handle(msg Message) {
if c.OnStreamChanged != nil { if c.OnStreamChanged != nil {
c.OnStreamChanged(msg.StreamName, msg.Reason) 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)
}
} }
} }

View file

@ -1,6 +1,6 @@
# capture # 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 ```text
apps/capture/ apps/capture/
@ -8,17 +8,17 @@ apps/capture/
``` ```
```bash ```bash
./bin/drm capture # passive: play anything ./bin/streamd capture # passive: play anything
./bin/drm capture --app rte # launch, navigate by hand ./bin/streamd capture --app rte # launch, navigate by hand
./bin/drm capture --app rte --channel rteone --auto-play \ ./bin/streamd capture --app rte --channel rteone --auto-play \
--wvd data/device.wvd # fully automated --wvd data/device.wvd # fully automated
``` ```
Writes `outputs/<app>/<stamp>/` plus `latest/`. App modules are compiled in, so Writes `outputs/<app>/<stamp>/` 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, **Full guide: [docs/capture.md](../../docs/capture.md)** — device setup, flags,
discovering a new app, and troubleshooting. discovering a new app, and troubleshooting.
The catalog lookup that used to be a separate `tg4info` binary is now the 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`).

View file

@ -12,16 +12,16 @@ import (
"time" "time"
"unicode" "unicode"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/app" "streamd/app"
"drmdecryption/modcfg" "streamd/modcfg"
"drmdecryption/modhost" "streamd/modhost"
"drmdecryption/phonecap" "streamd/phonecap"
"drmdecryption/repo" "streamd/repo"
) )
// Run performs one capture. Providers live under modules/<name>/ and are built // Run performs one capture. Providers live under modules/<name>/ 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 { func Run(args []string) error {
args = normalizeArgs(args) args = normalizeArgs(args)

View file

@ -1,13 +1,9 @@
module drmdecryption/apps/capture module streamd/apps/capture
go 1.25.0 go 1.25.0
require drmdecryption v0.0.0 require streamd v0.0.0
require ( require gopkg.in/yaml.v3 v3.0.1 // indirect
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
)
replace drmdecryption => ../pkg replace streamd => ../pkg

View file

@ -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 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 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 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View file

@ -4,7 +4,7 @@ import (
"strings" "strings"
"testing" "testing"
"drmdecryption/apps/capture/capturecmd" "streamd/apps/capture/capturecmd"
) )
func TestCaptureRejectsChannelAsApp(t *testing.T) { func TestCaptureRejectsChannelAsApp(t *testing.T) {

View file

@ -11,9 +11,9 @@ import (
"sort" "sort"
"strings" "strings"
"drmdecryption/modhost" "streamd/modhost"
"drmdecryption/repo" "streamd/repo"
"drmdecryption/session" "streamd/session"
) )
// Run performs a catalog lookup for one channel. // Run performs a catalog lookup for one channel.

View file

@ -1,13 +1,13 @@
module drmdecryption/apps/cli module streamd/apps/cli
go 1.25.0 go 1.25.0
require ( require (
drmdecryption v0.0.0 streamd v0.0.0
drmdecryption/apps/agent v0.0.0 streamd/apps/agent v0.0.0
drmdecryption/apps/capture v0.0.0 streamd/apps/capture v0.0.0
drmdecryption/apps/proxy v0.0.0 streamd/apps/proxy v0.0.0
drmdecryption/apps/streamd v0.0.0 streamd/apps/streamd v0.0.0
) )
require ( require (
@ -26,9 +26,9 @@ require (
) )
replace ( replace (
drmdecryption => ../pkg streamd => ../pkg
drmdecryption/apps/agent => ../agent streamd/apps/agent => ../agent
drmdecryption/apps/capture => ../capture streamd/apps/capture => ../capture
drmdecryption/apps/proxy => ../proxy streamd/apps/proxy => ../proxy
drmdecryption/apps/streamd => ../streamd streamd/apps/streamd => ../streamd
) )

View file

@ -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 // catalog lookups, the always-on agent, the streamd control plane and the
// on-device MITM. Providers live under modules/<name>/ and are discovered, // on-device MITM. Providers live under modules/<name>/ and are discovered,
// built, and executed by the host — they are not linked into this binary. // 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 package main
import ( import (
@ -13,14 +14,14 @@ import (
"os" "os"
"strings" "strings"
"drmdecryption/apps/agent/agentcmd" "streamd/apps/agent/agentcmd"
"drmdecryption/apps/capture/capturecmd" "streamd/apps/capture/capturecmd"
"drmdecryption/apps/cli/catalogcmd" "streamd/apps/cli/catalogcmd"
"drmdecryption/apps/cli/modulescmd" "streamd/apps/cli/modulescmd"
"drmdecryption/apps/proxy/proxyctlcmd" "streamd/apps/proxy/proxyctlcmd"
"drmdecryption/apps/streamd/servecmd" "streamd/apps/streamd/servecmd"
"drmdecryption/bootstrap" "streamd/bootstrap"
"drmdecryption/modhost" "streamd/modhost"
) )
func main() { func main() {
@ -39,12 +40,12 @@ func main() {
os.Exit(1) os.Exit(1)
} }
} else if err := modhost.ApplyEnvModulesDir(); err != nil { } 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) os.Exit(1)
} }
// Materialise apps/, bin/, modules/, outputs/, … next to this exe when // 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 cmd != "help" && cmd != "-h" && cmd != "--help" {
if err := bootstrap.EnsureAndLogFor(cmd); err != nil { if err := bootstrap.EnsureAndLogFor(cmd); err != nil {
fmt.Fprintln(os.Stderr, "[!] bootstrap:", err) fmt.Fprintln(os.Stderr, "[!] bootstrap:", err)
@ -102,23 +103,25 @@ func peelGlobalFlags(args []string) (modulesDir string, rest []string) {
} }
func usage() { func usage() {
fmt.Fprint(os.Stderr, `drm — DRM capture / restream toolchain fmt.Fprint(os.Stderr, `streamd — capture / restream toolchain
Usage: Usage:
drm [--modules-dir DIR] modules streamd [--modules-dir DIR] modules
drm [--modules-dir DIR] capture --app NAME [--channel ID | --all] [--wvd PATH] streamd [--modules-dir DIR] capture --app NAME [--channel ID | --all] [--wvd PATH]
drm [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json] streamd [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json]
drm agent run|status|devices|enqueue|cancel [--config …] streamd agent run|status|devices|enqueue|cancel [--config …]
drm serve [--bind …] [--data …] [--token …] streamd serve [--bind …] [--data …] [--token …]
drm proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent streamd proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
Global flags: Global flags:
--modules-dir DIR provider folder (default: <install>/modules, or $DRM_MODULES_DIR) --modules-dir DIR provider folder (default: <install>/modules, or $STREAMD_MODULES_DIR)
Providers live under modules/<name>/ (Go source + module-publish.yaml). Providers live under modules/<name>/ (Go source + module-publish.yaml).
Local module.yaml holds secrets and is never published; release zips ship 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. 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. Run any subcommand with --help for its own flags.
`) `)
} }

View file

@ -9,8 +9,8 @@ import (
"sort" "sort"
"text/tabwriter" "text/tabwriter"
"drmdecryption/modhost" "streamd/modhost"
"drmdecryption/repo" "streamd/repo"
) )
// Run prints external modules under modules/. // Run prints external modules under modules/.

View file

@ -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. there is no plugin loading and no modules directory to point a binary at.
```text ```text
apps/modules/ Go module: drmdecryption/modules apps/modules/ Go module: streamd/modules
go.mod replace drmdecryption => ../pkg go.mod replace streamd => ../pkg
all/all.go blank-imports every module — the link point all/all.go blank-imports every module — the link point
provider/ shared base: values loading, channel aliases, durations provider/ shared base: values loading, channel aliases, durations
<name>/*.go TRACKED: the app's logic <name>/*.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: mechanical defaults (timeouts, DASH timescales, card geometry) live in code:
```bash ```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 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` 1. Create `apps/modules/myapp/` with `config.go` and `myapp.go`
2. Register from `init()`: `appreg.Register(Name, New)` and 2. Register from `init()`: `appreg.Register(Name, New)` and
`appreg.RegisterFlags(bindFlags)` `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 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, **Authoring guide: [docs/modules.md](../../docs/modules.md)** — the full contract,
`uiflow` reference, optional capability interfaces, and a checklist. `uiflow` reference, optional capability interfaces, and a checklist.
@ -59,9 +59,9 @@ export TG4_POLICY_KEY=BCpkAD... # same thing
## Run ## Run
```bash ```bash
./bin/drm modules # what is compiled in ./bin/streamd modules # what is compiled in
./bin/drm capture --app rte --channel rteone --auto-play ./bin/streamd capture --app rte --channel rteone --auto-play
./bin/drm capture --app bbc --channel bbcone # transparent MITM; play on phone; MPD only ./bin/streamd 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/streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
./bin/drm agent run --config apps/agent/agent.yaml ./bin/streamd agent run --config apps/agent/agent.yaml
``` ```

View file

@ -4,7 +4,7 @@
package all package all
import ( import (
_ "drmdecryption/modules/bbc" _ "streamd/modules/bbc"
_ "drmdecryption/modules/rte" _ "streamd/modules/rte"
_ "drmdecryption/modules/tg4" _ "streamd/modules/tg4"
) )

View file

@ -4,7 +4,7 @@ import (
"flag" "flag"
"testing" "testing"
appreg "drmdecryption/app" appreg "streamd/app"
) )
// Every module must be constructible with no module.yaml present — a fresh clone // Every module must be constructible with no module.yaml present — a fresh clone

View file

@ -9,12 +9,12 @@ import (
"os" "os"
"time" "time"
"drmdecryption/adb" "streamd/adb"
appreg "drmdecryption/app" appreg "streamd/app"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/modules/provider" "streamd/modules/provider"
"drmdecryption/mpd" "streamd/mpd"
"drmdecryption/uiflow" "streamd/uiflow"
) )
func init() { func init() {

View file

@ -3,11 +3,11 @@ package bbc
import ( import (
"testing" "testing"
appreg "drmdecryption/app" appreg "streamd/app"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/modcfg" "streamd/modcfg"
"drmdecryption/modules/provider" "streamd/modules/provider"
"drmdecryption/mpd" "streamd/mpd"
) )
var ( var (

View file

@ -4,8 +4,8 @@ import (
"regexp" "regexp"
"time" "time"
"drmdecryption/modcfg" "streamd/modcfg"
"drmdecryption/modules/provider" "streamd/modules/provider"
) )
// Name is the module id (--app bbc). // Name is the module id (--app bbc).

View file

@ -6,8 +6,8 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/uiflow" "streamd/uiflow"
) )
// openExplorePage taps the Explore bottom-nav tab and waits for the channel rail. // openExplorePage taps the Explore bottom-nav tab and waits for the channel rail.

View file

@ -9,12 +9,12 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
appreg "drmdecryption/app" appreg "streamd/app"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/modules/provider" "streamd/modules/provider"
"drmdecryption/mpd" "streamd/mpd"
"drmdecryption/uiflow" "streamd/uiflow"
) )
func init() { func init() {

View file

@ -3,8 +3,8 @@ package c4
import ( import (
"time" "time"
"drmdecryption/modcfg" "streamd/modcfg"
"drmdecryption/modules/provider" "streamd/modules/provider"
) )
// Name is the module id (--app c4). // Name is the module id (--app c4).

View file

@ -6,8 +6,8 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/uiflow" "streamd/uiflow"
) )
func (a *App) openLiveTab(c *adb.Client) error { func (a *App) openLiveTab(c *adb.Client) error {

View file

@ -1,9 +1,9 @@
module drmdecryption/modules module streamd/modules
go 1.25.0 go 1.25.0
require drmdecryption v0.0.0 require streamd v0.0.0
require gopkg.in/yaml.v3 v3.0.1 // indirect require gopkg.in/yaml.v3 v3.0.1 // indirect
replace drmdecryption => ../pkg replace streamd => ../pkg

View file

@ -3,8 +3,8 @@ package itv
import ( import (
"time" "time"
"drmdecryption/modcfg" "streamd/modcfg"
"drmdecryption/modules/provider" "streamd/modules/provider"
) )
// Name is the module id (--app itv). // Name is the module id (--app itv).

View file

@ -10,12 +10,12 @@ import (
"os" "os"
"time" "time"
"drmdecryption/adb" "streamd/adb"
appreg "drmdecryption/app" appreg "streamd/app"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/modules/provider" "streamd/modules/provider"
"drmdecryption/mpd" "streamd/mpd"
"drmdecryption/uiflow" "streamd/uiflow"
) )
func init() { func init() {

View file

@ -6,8 +6,8 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/uiflow" "streamd/uiflow"
) )
// openLiveTab taps bottom-nav Live. Accessibility desc is obfuscated as "Lyve"; // openLiveTab taps bottom-nav Live. Accessibility desc is obfuscated as "Lyve";

View file

@ -3,8 +3,8 @@ package my5
import ( import (
"time" "time"
"drmdecryption/modcfg" "streamd/modcfg"
"drmdecryption/modules/provider" "streamd/modules/provider"
) )
// Name is the module id (--app my5). // Name is the module id (--app my5).

View file

@ -9,12 +9,12 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
appreg "drmdecryption/app" appreg "streamd/app"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/modules/provider" "streamd/modules/provider"
"drmdecryption/mpd" "streamd/mpd"
"drmdecryption/uiflow" "streamd/uiflow"
) )
func init() { func init() {

View file

@ -6,8 +6,8 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/uiflow" "streamd/uiflow"
) )
func (a *App) appFocused(c *adb.Client) bool { func (a *App) appFocused(c *adb.Client) bool {

View file

@ -10,10 +10,10 @@ import (
"sort" "sort"
"strings" "strings"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/modcfg" "streamd/modcfg"
"drmdecryption/phonecap" "streamd/phonecap"
"drmdecryption/repo" "streamd/repo"
) )
// Common is the part of a module.yaml that every module has. Modules embed it in // 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 } func (b *Base) ConfigLoaded() bool { return b.cfg.Loaded }
// ProxyBin resolves the on-device MITM binary. Empty means “auto” (caller uses // 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 { func (b *Base) ProxyBin() string {
if b.common.ProxyBin != "" { if b.common.ProxyBin != "" {
return modcfg.Resolve(b.common.ProxyBin) return modcfg.Resolve(b.common.ProxyBin)

View file

@ -3,9 +3,9 @@ package rte
import ( import (
"time" "time"
"drmdecryption/modcfg" "streamd/modcfg"
"drmdecryption/modules/provider" "streamd/modules/provider"
"drmdecryption/mpd" "streamd/mpd"
) )
// Name is the module id (--app rte). // Name is the module id (--app rte).

View file

@ -12,7 +12,7 @@ import (
"strings" "strings"
"testing" "testing"
"drmdecryption/mpd" "streamd/mpd"
) )
// The rewriter must publish a usable manifest from the KID alone — this is the // The rewriter must publish a usable manifest from the KID alone — this is the

View file

@ -6,7 +6,7 @@ import (
"strings" "strings"
"sync" "sync"
"drmdecryption/mpd" "streamd/mpd"
) )
func init() { func init() {

View file

@ -9,12 +9,12 @@ import (
"fmt" "fmt"
"time" "time"
"drmdecryption/adb" "streamd/adb"
appreg "drmdecryption/app" appreg "streamd/app"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/modules/provider" "streamd/modules/provider"
"drmdecryption/mpd" "streamd/mpd"
"drmdecryption/uiflow" "streamd/uiflow"
) )
func init() { func init() {

View file

@ -4,8 +4,8 @@ import (
"strings" "strings"
"testing" "testing"
appreg "drmdecryption/app" appreg "streamd/app"
"drmdecryption/mpd" "streamd/mpd"
) )
// Compile-time proof the plugin satisfies every interface the host expects. // Compile-time proof the plugin satisfies every interface the host expects.

View file

@ -5,8 +5,8 @@ import (
"regexp" "regexp"
"time" "time"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/uiflow" "streamd/uiflow"
) )
// openLiveTab taps the bottom-nav Live tab and waits for channel chips. // openLiveTab taps the bottom-nav Live tab and waits for channel chips.

View file

@ -6,9 +6,9 @@ import (
"net/http" "net/http"
"strings" "strings"
appreg "drmdecryption/app" appreg "streamd/app"
"drmdecryption/brightcove" "streamd/brightcove"
"drmdecryption/session" "streamd/session"
) )
// playbackConfig is the app's remote config blob. It is decoded generically: the // playbackConfig is the app's remote config blob. It is decoded generically: the

View file

@ -3,9 +3,9 @@ package tg4
import ( import (
"time" "time"
"drmdecryption/modcfg" "streamd/modcfg"
"drmdecryption/modules/provider" "streamd/modules/provider"
"drmdecryption/uiflow" "streamd/uiflow"
) )
// Name is the module id (--app tg4). // Name is the module id (--app tg4).

View file

@ -5,10 +5,10 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"drmdecryption/brightcove" "streamd/brightcove"
"drmdecryption/repo" "streamd/repo"
"drmdecryption/session" "streamd/session"
"drmdecryption/wvkey" "streamd/wvkey"
) )
// EnrichWithKeys fetches the HLS master, extracts the Widevine PSSH and resolves // EnrichWithKeys fetches the HLS master, extracts the Widevine PSSH and resolves

View file

@ -5,8 +5,8 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/uiflow" "streamd/uiflow"
) )
// openLivePage navigates to the Live page: if a menu entry is visible tap it, // openLivePage navigates to the Live page: if a menu entry is visible tap it,

View file

@ -10,12 +10,12 @@ import (
"fmt" "fmt"
"time" "time"
"drmdecryption/adb" "streamd/adb"
appreg "drmdecryption/app" appreg "streamd/app"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/modules/provider" "streamd/modules/provider"
"drmdecryption/mpd" "streamd/mpd"
"drmdecryption/uiflow" "streamd/uiflow"
) )
func init() { func init() {

View file

@ -3,9 +3,9 @@ package tg4
import ( import (
"testing" "testing"
appreg "drmdecryption/app" appreg "streamd/app"
"drmdecryption/modcfg" "streamd/modcfg"
"drmdecryption/modules/provider" "streamd/modules/provider"
) )
// Compile-time proof the plugin satisfies every interface the host expects. // Compile-time proof the plugin satisfies every interface the host expects.

View file

@ -1,10 +1,10 @@
# pkg — shared Go libraries # pkg — shared Go libraries
Imported by `apps/capture`, `apps/agent`, `apps/streamd`, `apps/proxy`, `apps/cli` 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 ```go
replace drmdecryption => ../pkg replace streamd => ../pkg
``` ```
## Packages ## Packages
@ -34,4 +34,4 @@ provider values live in that module's gitignored `module.yaml`.
go -C apps/pkg test ./... 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`.

View file

@ -6,10 +6,10 @@ import (
"sort" "sort"
"sync" "sync"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/mpd" "streamd/mpd"
"drmdecryption/session" "streamd/session"
) )
// Channel is a named live target inside an app (e.g. rteone). // Channel is a named live target inside an app (e.g. rteone).

View file

@ -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. // so a single downloaded binary can create apps/, bin/, outputs/, etc. on first run.
package bootstrap package bootstrap
@ -17,7 +17,7 @@ var embedded embed.FS
const minProxyBytes = 100_000 // stub ELF is tiny; real proxy-android-arm64 is ~9MB const minProxyBytes = 100_000 // stub ELF is tiny; real proxy-android-arm64 is ~9MB
// InstallRoot is the directory that should contain apps/, bin/, outputs/. // 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) { func InstallRoot() (string, error) {
exe, err := os.Executable() exe, err := os.Executable()
if err != nil { if err != nil {
@ -91,27 +91,34 @@ func Ensure(root string) (created []string, err error) {
return created, err return created, err
} }
// If drm is not already under bin/, copy/link a drm.exe there for 1:1 layout. // If streamd is not already under bin/, copy it there for 1:1 layout.
if err := ensureBinDrm(root); err != nil { // Also keep a drm.exe compat copy for one release when missing.
if err := ensureBinHost(root); err != nil {
return created, err return created, err
} }
return created, nil return created, nil
} }
func ensureBinDrm(root string) error { func ensureBinHost(root string) error {
exe, err := os.Executable() exe, err := os.Executable()
if err != nil { if err != nil {
return nil return nil
} }
exe, _ = filepath.EvalSymlinks(exe) exe, _ = filepath.EvalSymlinks(exe)
dest := filepath.Join(root, "bin", "drm.exe") if err := copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe")); err != nil {
if sameFile(exe, dest) { return err
}
return copyExeIfMissing(exe, filepath.Join(root, "bin", "drm.exe"))
}
func copyExeIfMissing(src, dest string) error {
if sameFile(src, dest) {
return nil return nil
} }
if st, err := os.Stat(dest); err == nil && !st.IsDir() { if st, err := os.Stat(dest); err == nil && !st.IsDir() {
return nil return nil
} }
data, err := os.ReadFile(exe) data, err := os.ReadFile(src)
if err != nil { if err != nil {
return err return err
} }
@ -154,7 +161,7 @@ func EnsureAndLogFor(cmd string) error {
} }
proxy := filepath.Join(root, "bin", "proxy-android-arm64") proxy := filepath.Join(root, "bin", "proxy-android-arm64")
if st, err := os.Stat(proxy); err != nil || st.Size() < minProxyBytes { 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. // Providers live under modules/; only warn when the command needs them.
needsModules := cmd == "" || cmd == "modules" || cmd == "capture" || cmd == "catalog" || cmd == "agent" || cmd == "serve" needsModules := cmd == "" || cmd == "modules" || cmd == "capture" || cmd == "catalog" || cmd == "agent" || cmd == "serve"

View file

@ -1,14 +1,14 @@
# Null DRM # Streamd
Host binary **`drm`** + providers under **`modules/`**. Host binary **`streamd`** + providers under **`modules/`**.
## Quick start ## 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/<name>/` and edit `module.yaml` (secrets only). 2. Unzip providers into `modules/<name>/` and edit `module.yaml` (secrets only).
3. `drm proxy install-ca --reinject` 3. `streamd proxy install-ca --reinject`
4. `drm capture --app bbc --channel bbcone --wait 120` 4. `streamd capture --app bbc --channel bbcone --wait 120`
5. `drm proxy reset` when finished. 5. `streamd proxy reset` when finished.
```text ```text
drm modules drm modules
@ -17,6 +17,6 @@ drm catalog --app NAME --channel ID [--keys] [--json]
drm proxy install-ca --reinject | reset | transparent --package PKG 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 Full docs: https://git.nulldrm.com/nulldrm/Null-DRM-Official

View file

@ -1,4 +1,4 @@
module drmdecryption module streamd
go 1.25.0 go 1.25.0

View file

@ -1,6 +1,6 @@
# External modules # 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/ modules/

View file

@ -1,4 +1,4 @@
module drmdecryption module streamd
go 1.25.0 go 1.25.0

View file

@ -9,7 +9,7 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
) )
// Hints tell the waiter which fields / log tags mean a capture is complete. // Hints tell the waiter which fields / log tags mean a capture is complete.

View file

@ -1,4 +1,4 @@
module drmdecryption module streamd
go 1.25.0 go 1.25.0

View file

@ -15,8 +15,8 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"drmdecryption/modhost" "streamd/modhost"
"drmdecryption/repo" "streamd/repo"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )

View file

@ -13,7 +13,7 @@ type Module struct {
Dir string // absolute path to modules/<name> Dir string // absolute path to modules/<name>
} }
// 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 { func ModulesDir(root string) string {
return EffectiveModulesDir(root) return EffectiveModulesDir(root)
} }

View file

@ -1,8 +1,8 @@
// Package modhost discovers, builds, and runs external provider modules that // Package modhost discovers, builds, and runs external provider modules that
// live under modules/<name>/ (Go source + module.yaml), outside drm.exe. // live under modules/<name>/ (Go source + module.yaml), outside streamd.
package modhost package modhost
import "drmdecryption/capture" import "streamd/capture"
// ProtocolVersion is bumped when describe/launch/autoplay CLI contract changes. // ProtocolVersion is bumped when describe/launch/autoplay CLI contract changes.
const ProtocolVersion = 1 const ProtocolVersion = 1

View file

@ -6,11 +6,11 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/app" "streamd/app"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/mpd" "streamd/mpd"
"drmdecryption/session" "streamd/session"
) )
// RemoteApp implements app.App by calling an external module binary. // RemoteApp implements app.App by calling an external module binary.

View file

@ -5,7 +5,7 @@ import (
"path/filepath" "path/filepath"
"sync" "sync"
"drmdecryption/repo" "streamd/repo"
) )
var ( var (
@ -13,7 +13,7 @@ var (
modulesDirOV string // absolute path override for the modules directory 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. // Empty clears the override. Relative paths are resolved against the process cwd.
func SetModulesDir(dir string) error { func SetModulesDir(dir string) error {
rootMu.Lock() rootMu.Lock()
@ -38,7 +38,7 @@ func ModulesDirOverride() string {
} }
// EffectiveModulesDir is the directory that Discover/Open scan. // EffectiveModulesDir is the directory that Discover/Open scan.
// Prefer --modules-dir / DRM_MODULES_DIR; else <root>/modules. // Prefer --modules-dir / STREAMD_MODULES_DIR / DRM_MODULES_DIR; else <root>/modules.
func EffectiveModulesDir(root string) string { func EffectiveModulesDir(root string) string {
if ov := ModulesDirOverride(); ov != "" { if ov := ModulesDirOverride(); ov != "" {
return ov return ov
@ -49,12 +49,16 @@ func EffectiveModulesDir(root string) string {
return filepath.Join(root, "modules") 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 { func ApplyEnvModulesDir() error {
if ModulesDirOverride() != "" { if ModulesDirOverride() != "" {
return nil return nil
} }
v := os.Getenv("DRM_MODULES_DIR") v := os.Getenv("STREAMD_MODULES_DIR")
if v == "" {
v = os.Getenv("DRM_MODULES_DIR")
}
if v == "" { if v == "" {
return nil return nil
} }

View file

@ -12,13 +12,13 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/app" "streamd/app"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/proxy" "streamd/proxy"
"drmdecryption/repo" "streamd/repo"
"drmdecryption/session" "streamd/session"
"drmdecryption/wvkey" "streamd/wvkey"
) )
// DefaultCAHash is the subject hash of the bundled MITM CA, used when an app // DefaultCAHash is the subject hash of the bundled MITM CA, used when an app

View file

@ -6,15 +6,15 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/repo" "streamd/repo"
) )
//go:embed embedded/tproxy_iptables.sh //go:embed embedded/tproxy_iptables.sh
var embeddedTProxyScript []byte var embeddedTProxyScript []byte
// ensureTProxyScript pushes the iptables helper to the phone. // 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/. // so a portable release zip does not need apps/proxy/device/.
func ensureTProxyScript(c *adb.Client) error { func ensureTProxyScript(c *adb.Client) error {
candidates := []string{ candidates := []string{

View file

@ -17,8 +17,8 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/repo" "streamd/repo"
) )
const ( const (
@ -225,7 +225,7 @@ func PushAndStart(c *adb.Client, localBin string, extraArgs ...string) error {
} }
// FindLocalBin returns the on-device MITM binary. // 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 { func FindLocalBin(root string) string {
if root == "" { if root == "" {
root = repo.Root() root = repo.Root()
@ -322,11 +322,11 @@ func generateMITMCA(certPath, keyPath string) error {
return err return err
} }
// Unique CN so Android subject_hash_old differs per install (filename HASH.0). // 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{ tmpl := &x509.Certificate{
SerialNumber: serial, SerialNumber: serial,
Subject: pkix.Name{ Subject: pkix.Name{
Organization: []string{"Null DRM MITM CA"}, Organization: []string{"Streamd MITM CA"},
CommonName: cn, CommonName: cn,
}, },
NotBefore: time.Now().Add(-time.Hour), NotBefore: time.Now().Add(-time.Hour),

View file

@ -11,7 +11,7 @@ import (
// //
// Search order: // Search order:
// 1. Walk up from the current working directory // 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 { func Root() string {
if root := findRoot(wd()); root != "" { if root := findRoot(wd()); root != "" {
return root return root

View file

@ -10,7 +10,7 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/adb" "streamd/adb"
) )
// Pick selects among several matching nodes. // Pick selects among several matching nodes.

View file

@ -5,7 +5,7 @@ license URLs, manifests and auth headers.
```text ```text
apps/proxy/ 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) device/ linux/arm64 MITM source (module: appproxy)
rteproxy-ca.crt MITM CA (subject hash 6c3578b4) rteproxy-ca.crt MITM CA (subject hash 6c3578b4)
``` ```
@ -17,8 +17,8 @@ working.
## Build ## Build
```bash ```bash
go -C apps/cli build -o ../../bin/drm . # host CLI go -C apps/cli build -o ../../bin/streamd . # host CLI
./bin/drm proxy build # cross-compile the device binary ./bin/streamd proxy build # cross-compile the device binary
``` ```
`proxy build` compiles `device/` for linux/arm64 into `proxy build` compiles `device/` for linux/arm64 into
@ -28,20 +28,20 @@ go -C apps/cli build -o ../../bin/drm . # host CLI
```bash ```bash
# trust the MITM CA (needs Magisk; mounts into the system store) # trust the MITM CA (needs Magisk; mounts into the system store)
./bin/drm proxy install-ca --reinject ./bin/streamd proxy install-ca --reinject
./bin/drm proxy reinject-ca # mount only, CA already pushed ./bin/streamd proxy reinject-ca # mount only, CA already pushed
# structured capture proxy # structured capture proxy
./bin/drm proxy start --install-ca --reinject ./bin/streamd proxy start --install-ca --reinject
./bin/drm proxy stop ./bin/streamd proxy stop
# record everything while you explore an unknown app # record everything while you explore an unknown app
./bin/drm proxy discover --install-ca --reinject ./bin/streamd proxy discover --install-ca --reinject
./bin/drm proxy discover --force-stop <package> # so it inherits the CA mount ./bin/streamd proxy discover --force-stop <package> # so it inherits the CA mount
# pull artifacts without re-running, and release the phone # pull artifacts without re-running, and release the phone
./bin/drm proxy pull ./bin/streamd proxy pull
./bin/drm proxy clear-proxy ./bin/streamd proxy clear-proxy
``` ```
Always clear the proxy when done, or the phone keeps pointing at a dead listener. 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 ```bash
# leave UK VPN connected on the phone, then: # 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 # 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 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`, 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 ## Artifacts

View file

@ -1,7 +1,7 @@
module drmdecryption/apps/proxy module streamd/apps/proxy
go 1.25.0 go 1.25.0
require drmdecryption v0.0.0 require streamd v0.0.0
replace drmdecryption => ../pkg replace streamd => ../pkg

View file

@ -18,9 +18,9 @@ import (
"syscall" "syscall"
"time" "time"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/proxy" "streamd/proxy"
"drmdecryption/repo" "streamd/repo"
) )
// Run dispatches a proxy subcommand. args[0] is the subcommand name. // 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 { 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, "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) fmt.Fprintf(os.Stderr, "Missing: %s\n", deviceDir)
os.Exit(1) os.Exit(1)
} }

View file

@ -1,7 +1,7 @@
# streamd # streamd
Control plane: REST API, SQLite, dashboard and media supervisor. Hosted by the Control plane: REST API, SQLite, dashboard and media supervisor. Hosted by the
single binary as `drm serve`. single binary as `streamd serve`.
```text ```text
apps/streamd/ apps/streamd/
@ -17,7 +17,7 @@ apps/streamd/
## Run ## Run
```bash ```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 `--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any

View file

@ -1,14 +1,14 @@
module drmdecryption/apps/streamd module streamd/apps/streamd
go 1.25.0 go 1.25.0
require ( require (
drmdecryption v0.0.0
github.com/gorilla/websocket v1.5.3 github.com/gorilla/websocket v1.5.3
modernc.org/sqlite v1.34.5 modernc.org/sqlite v1.34.5
streamd v0.0.0
) )
replace drmdecryption => ../pkg replace streamd => ../pkg
require ( require (
github.com/dustin/go-humanize v1.0.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect

View file

@ -10,10 +10,11 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/apps/streamd/internal/auth" "streamd/apps/streamd/internal/auth"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/deps" "streamd/apps/streamd/internal/deps"
"drmdecryption/apps/streamd/internal/httpx" "streamd/apps/streamd/internal/httpx"
"streamd/apps/streamd/internal/modstore"
) )
type Supervisor interface { type Supervisor interface {
@ -56,6 +57,10 @@ type Handler struct {
Deps deps.Status Deps deps.Status
WWWRoot string // data/www — used to report variant playlist health WWWRoot string // data/www — used to report variant playlist health
LogRoot string // data/logs — source for the log tail endpoints LogRoot string // data/logs — source for the log tail endpoints
DataDir string // streamd --data root
Modules *modstore.Store
// ModulesNotify is set when the hub supports module change pushes.
ModulesNotify ModulesNotifier
Log *slog.Logger Log *slog.Logger
} }

View file

@ -3,10 +3,10 @@ package api
import ( import (
"net/http" "net/http"
"drmdecryption/apps/streamd/internal/auth" "streamd/apps/streamd/internal/auth"
"drmdecryption/modhost" "streamd/modhost"
"drmdecryption/mpd" "streamd/mpd"
"drmdecryption/repo" "streamd/repo"
) )
// appInfo describes one modules/<name>/ provider to the dashboard, so the UI // appInfo describes one modules/<name>/ provider to the dashboard, so the UI
@ -16,6 +16,7 @@ type appInfo struct {
Channels []channelInfo `json:"channels"` Channels []channelInfo `json:"channels"`
Rewriter string `json:"rewriter"` Rewriter string `json:"rewriter"`
HasConfig bool `json:"has_config"` HasConfig bool `json:"has_config"`
Error string `json:"error,omitempty"`
} }
type channelInfo struct { type channelInfo struct {
@ -23,7 +24,9 @@ type channelInfo struct {
Label string `json:"label"` 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) { func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet { if r.Method != http.MethodGet {
writeErr(w, http.StatusMethodNotAllowed, "method not allowed") writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
@ -33,13 +36,27 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
return return
} }
out := []appInfo{} out := []appInfo{}
listed, err := modhost.ListAll(repo.Root()) mods, err := modhost.Discover(repo.Root())
if err != nil { if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error()) writeErr(w, http.StatusInternalServerError, err.Error())
return return
} }
for _, L := range listed { for _, m := range mods {
d := L.Desc 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"} info := appInfo{Name: d.Name, Channels: []channelInfo{}, Rewriter: "none"}
for _, ch := range d.Channels { for _, ch := range d.Channels {
info.Channels = append(info.Channels, channelInfo{ID: ch.ID, Label: ch.Label}) info.Channels = append(info.Channels, channelInfo{ID: ch.ID, Label: ch.Label})

View file

@ -11,9 +11,9 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/apps/streamd/internal/auth" "streamd/apps/streamd/internal/auth"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
"drmdecryption/mpd" "streamd/mpd"
) )
// MountControl adds the bulk, duplicate, probe, settings and schedule routes. // MountControl adds the bulk, duplicate, probe, settings and schedule routes.

View file

@ -10,9 +10,9 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/apps/streamd/internal/auth" "streamd/apps/streamd/internal/auth"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/logfile" "streamd/apps/streamd/internal/logfile"
) )
// logSources maps a caller-supplied source name to the log file suffix the // logSources maps a caller-supplied source name to the log file suffix the

View file

@ -1,93 +1,160 @@
package api package api
import ( import (
"crypto/sha256"
"encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
"io" "io"
"net/http" "net/http"
"os"
"path/filepath" "path/filepath"
"regexp"
"strings" "strings"
"time"
"drmdecryption/apps/streamd/internal/auth" "streamd/apps/streamd/internal/auth"
"drmdecryption/modhost" "streamd/apps/streamd/internal/modstore"
"drmdecryption/repo"
) )
// moduleInfo is one modules/<name>/ entry for agent sync. // ModulesNotifier pushes module change events to agents and the dashboard.
type moduleInfo struct { type ModulesNotifier interface {
Name string `json:"name"` NotifyModulesChanged(name, reason string)
HasYAML bool `json:"has_yaml"`
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
} }
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) { func (h *Handler) modules(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/api/modules") path := strings.TrimPrefix(r.URL.Path, "/api/modules")
path = strings.Trim(path, "/") path = strings.Trim(path, "/")
// Module metadata describes the provider plugins installed on this host, switch {
// so even reading it needs a principal. case path == "" && r.Method == http.MethodGet:
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
return return
} }
switch {
case path == "" && r.Method == http.MethodGet:
h.listModules(w, r) h.listModules(w, r)
case path == "upload" && r.Method == http.MethodPost:
h.uploadModule(w, r)
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodGet: case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodGet:
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
return
}
h.getModule(w, r, path) h.getModule(w, r, path)
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodPut: case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodPut:
h.putModule(w, r, path) 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: default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed") writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
} }
} }
func (h *Handler) listModules(w http.ResponseWriter, r *http.Request) { func (h *Handler) listModules(w http.ResponseWriter, r *http.Request) {
root := repo.Root() list, err := h.modStore().List()
dir := modhost.ModulesDir(root)
ents, err := os.ReadDir(dir)
if err != nil { if err != nil {
if os.IsNotExist(err) {
writeJSON(w, http.StatusOK, map[string]any{"modules": []moduleInfo{}})
return
}
writeErr(w, http.StatusInternalServerError, err.Error()) writeErr(w, http.StatusInternalServerError, err.Error())
return return
} }
out := []moduleInfo{} writeJSON(w, http.StatusOK, map[string]any{"modules": list})
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})
} }
func (h *Handler) getModule(w http.ResponseWriter, r *http.Request, name string) { 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") writeErr(w, http.StatusBadRequest, "invalid module name")
return return
} }
info := moduleYAMLInfo(filepath.Join(modhost.ModulesDir(repo.Root()), name), name) info := h.modStore().Info(name)
writeJSON(w, http.StatusOK, info) 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) { 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) p, ok := auth.Guard(w, r, auth.RoleOperator)
if !ok { if !ok {
return return
} }
if !moduleNameRe.MatchString(name) { if !modstore.NameRe.MatchString(name) {
writeErr(w, http.StatusBadRequest, "invalid module name") writeErr(w, http.StatusBadRequest, "invalid module name")
return return
} }
@ -104,47 +171,84 @@ func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string)
writeErr(w, http.StatusBadRequest, err.Error()) writeErr(w, http.StatusBadRequest, err.Error())
return 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 return
} }
modDir := filepath.Join(modhost.ModulesDir(repo.Root()), name) h.audit(r, p, http.StatusOK, "updated module.yaml for "+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.logger().Info("module.yaml updated", "module", name, "by", p.Actor(), "sha256", info.YAMLSHA256) 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{ writeJSON(w, http.StatusOK, map[string]any{
"ok": true, "ok": true,
"module": info, "module": info,
}) })
} }
func moduleYAMLInfo(modDir, name string) moduleInfo { func (h *Handler) deleteModule(w http.ResponseWriter, r *http.Request, name string) {
info := moduleInfo{Name: name} p, ok := auth.Guard(w, r, auth.RoleOperator)
b, err := os.ReadFile(filepath.Join(modDir, "module.yaml")) if !ok {
if err != nil { return
return info
} }
sum := sha256.Sum256(b) if !modstore.NameRe.MatchString(name) {
info.HasYAML = true writeErr(w, http.StatusBadRequest, "invalid module name")
info.YAMLSHA256 = hex.EncodeToString(sum[:]) return
return info }
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":"..."}. // extractModuleYAML accepts raw YAML or JSON {"yaml":"..."}.
@ -163,7 +267,6 @@ func extractModuleYAML(contentType string, body []byte) ([]byte, error) {
} }
return []byte(wrap.YAML), nil return []byte(wrap.YAML), nil
default: default:
// text/yaml, application/x-yaml, or bare body
return body, nil return body, nil
} }
} }

View file

@ -6,7 +6,7 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
) )
// stalePlaylistS is how old a playlist may get before the output counts as // stalePlaylistS is how old a playlist may get before the output counts as

View file

@ -8,7 +8,7 @@ import (
"testing" "testing"
"time" "time"
"drmdecryption/apps/streamd/internal/httpx" "streamd/apps/streamd/internal/httpx"
_ "modernc.org/sqlite" _ "modernc.org/sqlite"
) )

View file

@ -11,7 +11,7 @@ import (
"sync" "sync"
"time" "time"
"drmdecryption/apps/streamd/internal/httpx" "streamd/apps/streamd/internal/httpx"
) )
// Handler serves the auth routes: login/logout/me, user administration, API // Handler serves the auth routes: login/logout/me, user administration, API

View file

@ -8,7 +8,7 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/apps/streamd/internal/httpx" "streamd/apps/streamd/internal/httpx"
) )
const ( const (

View file

@ -14,7 +14,7 @@ import (
"strings" "strings"
"time" "time"
"drmdecryption/repo" "streamd/repo"
) )
// Status is the resolved path for each tool after Ensure. // Status is the resolved path for each tool after Ensure.
@ -202,7 +202,7 @@ func httpGet(url string) (*http.Response, error) {
if err != nil { if err != nil {
return nil, err 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) return client.Do(req)
} }

View file

@ -17,10 +17,10 @@ import (
"sync" "sync"
"time" "time"
"drmdecryption/apps/streamd/internal/auth" "streamd/apps/streamd/internal/auth"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/httpx" "streamd/apps/streamd/internal/httpx"
"drmdecryption/apps/streamd/internal/tsfanout" "streamd/apps/streamd/internal/tsfanout"
) )
// Supervisor is the subset of the media supervisor the gate needs. // Supervisor is the subset of the media supervisor the gate needs.

View file

@ -11,9 +11,9 @@ import (
"testing" "testing"
"time" "time"
"drmdecryption/apps/streamd/internal/auth" "streamd/apps/streamd/internal/auth"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/tsfanout" "streamd/apps/streamd/internal/tsfanout"
) )
// fakeSup records what the gate asked for, and can pretend a stream comes up. // fakeSup records what the gate asked for, and can pretend a stream comes up.

View file

@ -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 <data>/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/<arch>/<name> or .bin/<name>.
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()
}

View file

@ -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)
}
}

View file

@ -6,7 +6,7 @@ import (
"log/slog" "log/slog"
"time" "time"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
) )
// Supervisor is the subset of the media supervisor the scheduler needs. // Supervisor is the subset of the media supervisor the scheduler needs.

View file

@ -3,10 +3,10 @@ package supervisor
import ( import (
"strings" "strings"
"drmdecryption/app" "streamd/app"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
"drmdecryption/modhost" "streamd/modhost"
"drmdecryption/repo" "streamd/repo"
) )
// streamSettings are the downloader and packager knobs for one stream. They // streamSettings are the downloader and packager knobs for one stream. They

View file

@ -3,11 +3,11 @@ package supervisor
import ( import (
"testing" "testing"
"drmdecryption/adb" "streamd/adb"
"drmdecryption/app" "streamd/app"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
"drmdecryption/capture" "streamd/capture"
"drmdecryption/mpd" "streamd/mpd"
) )
// fakeApp stands in for a compiled-in app module: the supervisor must take its // fakeApp stands in for a compiled-in app module: the supervisor must take its

View file

@ -10,7 +10,7 @@ import (
"testing" "testing"
"time" "time"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
) )
// These tests run the real ffmpeg against the real generated command line. // These tests run the real ffmpeg against the real generated command line.

View file

@ -14,10 +14,10 @@ import (
"sync" "sync"
"time" "time"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/logfile" "streamd/apps/streamd/internal/logfile"
"drmdecryption/apps/streamd/internal/tsfanout" "streamd/apps/streamd/internal/tsfanout"
"drmdecryption/mpd" "streamd/mpd"
) )
// Media runs N_m3u8DL-RE plus one ffmpeg packager per variant, publishing into // Media runs N_m3u8DL-RE plus one ffmpeg packager per variant, publishing into

View file

@ -6,7 +6,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
) )
// Packager defaults. These were literals in the ffmpeg command line before // Packager defaults. These were literals in the ffmpeg command line before

View file

@ -4,7 +4,7 @@ import (
"strings" "strings"
"testing" "testing"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
) )
// quote and backslash as values, so the test source stays readable where it // quote and backslash as values, so the test source stays readable where it

View file

@ -5,7 +5,7 @@ import (
"sync" "sync"
"time" "time"
"drmdecryption/apps/streamd/internal/db" "streamd/apps/streamd/internal/db"
) )
// Stub marks streams as starting/stopped without spawning media workers. // Stub marks streams as starting/stopped without spawning media workers.

Some files were not shown because too many files have changed in this diff Show more