Compare commits

..

5 commits
v0.1.5 ... main

Author SHA1 Message Date
404errordeveloper
5b6f38c9cf streamd v0.2.3: fix NRE Spectre crash under daemon (Linux PTY)
All checks were successful
release / build-and-upload (push) Successful in 6m56s
Wrap N_m3u8DL-RE with util-linux script so Spectre gets a real TTY; drop
subtitles; pin COLUMNS/LINES; kill process group on stop. Fixes immediate
'downloader exited before any media arrived' on serve start.
2026-10-10 19:54:41 +02:00
404errordeveloper
a091922efa streamd v0.2.2: session uptimes, egress DNS, Support, agent/Widevine
All checks were successful
release / build-and-upload (push) Successful in 7m2s
Dashboard Live uptimes + Recent runs from stream_sessions; overview.recent_sessions.
WireGuard netns resolv.conf + missing-deps WARN. Support donations card.
Agent start/stop/update, job_backoff default off, wvkey ensure/venv, phonecap retries,
modhost YAML enrich, DRM SetCredentials requires keys.
2026-10-10 19:26:39 +02:00
404errordeveloper
3ae1dd58b3 docs: add Streamd v0.2.1 release notes
All checks were successful
release / build-and-upload (push) Successful in 7m5s
Serve lifecycle, WireGuard/SOCKS egress, module panel fixes; streamd-* assets only.
2026-10-10 18:26:02 +02:00
404errordeveloper
8fc7e4c0b8 streamd: serve start/stop/update, streamd.yaml, egress, module panel fixes
- Add streamd serve start|stop|restart|status|update with auto-written streamd.yaml
- Panel modules: STREAMD_MODULES_DIR for describe, YAML channel fallback, textarea value fix
- Per-stream WireGuard/SOCKS egress profiles + Settings UI
- Drop drm-* from release builds; track streamd-bg.sh / streamd-update.sh wrappers
- Docs: streamd-server-setup lifecycle and update flow
2026-10-10 18:05:51 +02:00
404errordeveloper
da8e1123ec 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
2026-10-10 15:58:26 +02:00
193 changed files with 9527 additions and 1172 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 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,91 @@ 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).
| 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 |
| \`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 +169,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 }}"

4
.gitignore vendored
View file

@ -218,7 +218,7 @@ apps/proxy/proxy-android-arm64
apps/proxy/rteproxy-android-arm64 apps/proxy/rteproxy-android-arm64
# local / VPS deploy + operator scripts (test stuff; keep out of git) # local / VPS deploy + operator scripts (test stuff; keep out of git)
deploy/ deploy/
# Ignore local scripts, but keep the release builders tracked for Forgejo Actions. # Ignore local scripts, but keep release builders + server helpers tracked.
scripts/* scripts/*
!scripts/build-release.sh !scripts/build-release.sh
!scripts/build-release.ps1 !scripts/build-release.ps1
@ -226,6 +226,8 @@ scripts/*
!scripts/build-modules-release.ps1 !scripts/build-modules-release.ps1
!scripts/notify-telegram.sh !scripts/notify-telegram.sh
!scripts/notify-telegram.ps1 !scripts/notify-telegram.ps1
!scripts/streamd-bg.sh
!scripts/streamd-update.sh
# Shared library packages under apps/modules/ (imported by external module CLIs). # Shared library packages under apps/modules/ (imported by external module CLIs).
# module.yaml stays local; module-publish.yaml is the tracked universal template. # module.yaml stays local; module-publish.yaml is the tracked universal template.
apps/modules/** apps/modules/**

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
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,43 +26,54 @@ 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 in the background (Linux / macOS / Windows)
export STREAMD_API_KEY=ndk_… export STREAMD_API_KEY=ndk_…
# or legacy: export STREAMD_TOKEN=… ./bin/streamd agent start --config apps/agent/agent.yaml
./bin/drm agent run --config apps/agent/agent.yaml ./bin/streamd agent status --config apps/agent/agent.yaml
# foreground debug: ./bin/streamd agent run --config apps/agent/agent.yaml
# stop / restart: ./bin/streamd agent stop|restart --config …
# self-update: ./bin/streamd agent update [--beta] [--tag vX.Y.Z]
``` ```
```bash ```bash
./bin/drm agent status ./bin/streamd agent devices
./bin/drm agent devices ./bin/streamd agent enqueue --stream tg4-ioi --reason manual
./bin/drm agent enqueue --stream tg4-ioi --reason manual ./bin/streamd agent cancel --job 3
./bin/drm 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`,
`job_backoff` (default false — exponential delays only when several agents
share work), plus daemon fields `log_file`, `pid_file`, `channel`, `asset`,
`keep_old` for `agent start|stop|update`.
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.
`wvd` must be set or key fetches fail. `wvd` must be set or key fetches fail. On first `agent start`/`run`, streamd
bootstraps `apps/wvkey/` and creates `<install>/.venv` with `pywidevine` using
the system Python (Windows, Linux, or macOS) so Widevine key fetch works without
a hand-made venv.
## 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,12 +14,23 @@ 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
# Required for key fetch. Relative paths resolve from the repo root # modules_prune: false # delete local modules absent from the panel
# (DRM-Decryption/), not from C:\Users\admin\Programming\. # Exponential retry delays (1m, 2m, 4m…). Default false — lone agents retry ASAP.
wvd: # Set true only when several agents share the same streams.
# job_backoff: false
# Background daemon (streamd agent start|stop|update):
# log_file: agent.log
# pid_file: agent.pid
# channel: stable # or beta — used by agent update
# asset: # optional streamd-* override
# keep_old: 10
# Required for key fetch. Relative paths resolve from the install/repo root.
# Agent auto-creates .venv + installs pywidevine on first run (Win/Linux/macOS).
# python: # optional override; default = <root>/.venv/…
wvd: data/device.wvd
# user_agent: "" # optional license-request User-Agent # user_agent: "" # optional license-request User-Agent

View file

@ -9,17 +9,21 @@ import (
"os" "os"
"os/signal" "os/signal"
"strconv" "strconv"
"strings"
"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"
"streamd/repo"
"streamd/wvkey"
) )
// Run dispatches an agent subcommand. args[0] is the subcommand name. // Run dispatches an agent subcommand. args[0] is the subcommand name.
@ -35,6 +39,14 @@ func Run(args []string) error {
switch sub { switch sub {
case "run": case "run":
runCmd(sub, rest) runCmd(sub, rest)
case "start":
return startDaemonCmd(rest)
case "stop":
return stopDaemonCmd(rest)
case "restart":
return restartDaemonCmd(rest)
case "update":
return updateDaemonCmd(rest)
case "status": case "status":
statusCmd(sub, rest) statusCmd(sub, rest)
case "devices": case "devices":
@ -57,8 +69,13 @@ func Usage() {
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB) fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
Usage: Usage:
agent run [--config apps/agent/agent.yaml] agent start [--config agent.yaml] # background (pid + log)
agent status [--config ...] agent stop [--config ...]
agent restart [--config ...]
agent status [--config ...] # process + recent jobs
agent update [--config ...] [--beta] [--tag vX.Y.Z] [--no-restart]
agent run [--config ...] # foreground (debug)
agent devices [--config ...] agent devices [--config ...]
agent enqueue --stream NAME [--reason manual] [--config ...] agent enqueue --stream NAME [--reason manual] [--config ...]
agent cancel --job ID [--config ...] agent cancel --job ID [--config ...]
@ -67,6 +84,9 @@ Polls streamd for enabled streams that are down / missing credentials,
enqueues jobs, claims a free phone that already has the app, captures enqueues jobs, claims a free phone that already has the app, captures
via MITM, POSTs credentials, then force-stops the app. via MITM, POSTs credentials, then force-stops the app.
Job retries default to immediate (job_backoff: false). Set job_backoff: true
in agent.yaml for exponential delays when several agents share work.
Does not install apps. Does not run NRE/ffmpeg. Does not install apps. Does not run NRE/ffmpeg.
`) `)
} }
@ -116,6 +136,18 @@ func runCmd(sub string, args []string) {
"create an operator API key in the streamd dashboard", me.Role) "create an operator API key in the streamd dashboard", me.Role)
} }
log.Printf("authenticated to streamd as %q (role %s)", me.Name, me.Role) log.Printf("authenticated to streamd as %q (role %s)", me.Name, me.Role)
// Widevine keys need apps/wvkey + a local .venv (pywidevine). Create them
// once per install root so Windows / Linux / macOS agents all work.
if rt, err := wvkey.EnsureRuntime(repo.Root()); err != nil {
log.Fatalf("widevine helper: %v", err)
} else {
log.Printf("widevine helper ready python=%s script=%s", rt.Python, rt.Script)
if strings.TrimSpace(cfg.Python) == "" {
cfg.Python = rt.Python
}
}
q := openQueue(cfg) q := openQueue(cfg)
defer q.Close() defer q.Close()
@ -124,6 +156,16 @@ func runCmd(sub string, args []string) {
} else if n > 0 { } else if n > 0 {
log.Printf("re-queued %d stuck running job(s) from previous run", n) log.Printf("re-queued %d stuck running job(s) from previous run", n)
} }
if n, err := q.ClearAllBackoffs(); err != nil {
log.Printf("clear backoffs: %v", err)
} else if n > 0 {
log.Printf("cleared backoff on %d queued job(s) — runnable now", n)
}
if cfg.JobBackoffEnabled() {
log.Printf("job_backoff=true (exponential delays after failures)")
} else {
log.Printf("job_backoff=false (retry failed captures immediately)")
}
pool := device.New("", cfg.Devices) pool := device.New("", cfg.Devices)
stop := make(chan struct{}) stop := make(chan struct{})
@ -137,15 +179,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 +223,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++ {
@ -184,6 +246,7 @@ func runCmd(sub string, args []string) {
Python: cfg.Python, Python: cfg.Python,
WVD: cfg.WVD, WVD: cfg.WVD,
UserAgent: cfg.UserAgent, UserAgent: cfg.UserAgent,
JobBackoff: cfg.JobBackoffEnabled(),
Log: log.Default(), Log: log.Default(),
} }
go w.Loop(stop) go w.Loop(stop)
@ -204,6 +267,7 @@ func runCmd(sub string, args []string) {
func statusCmd(sub string, args []string) { func statusCmd(sub string, args []string) {
cfg, _ := loadCfg(sub, args) cfg, _ := loadCfg(sub, args)
printDaemonStatus(cfg)
q := openQueue(cfg) q := openQueue(cfg)
defer q.Close() defer q.Close()
jobs, err := q.ListRecent(40) jobs, err := q.ListRecent(40)

View file

@ -0,0 +1,177 @@
package agentcmd
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"streamd/apps/agent/internal/config"
"streamd/repo"
)
func readPID(pidFile string) (int, error) {
b, err := os.ReadFile(pidFile)
if err != nil {
return 0, err
}
return strconv.Atoi(strings.TrimSpace(string(b)))
}
func writePID(pidFile string, pid int) error {
if err := os.MkdirAll(filepath.Dir(pidFile), 0o755); err != nil {
return err
}
return os.WriteFile(pidFile, []byte(strconv.Itoa(pid)+"\n"), 0o644)
}
func removePID(pidFile string) { _ = os.Remove(pidFile) }
func runningPID(cfg config.Config) (int, bool) {
pid, err := readPID(cfg.PIDFile)
if err != nil || pid <= 0 {
return 0, false
}
if !signalAlive(pid) {
removePID(cfg.PIDFile)
return pid, false
}
return pid, true
}
func printDaemonStatus(cfg config.Config) {
fmt.Printf("config: %s\n", cfgPathHint(cfg))
fmt.Printf("pid: %s\n", cfg.PIDFile)
fmt.Printf("log: %s\n", cfg.LogFile)
if pid, ok := runningPID(cfg); ok {
fmt.Printf("agent: running pid=%d\n", pid)
} else {
fmt.Println("agent: stopped")
}
}
func cfgPathHint(cfg config.Config) string {
// Best-effort: show data dir; exact yaml path was already resolved by Load.
return cfg.DataDir
}
func startDaemonCmd(args []string) error {
cfg, cfgFile := loadCfgWithPath("start", args)
if pid, ok := runningPID(cfg); ok {
fmt.Printf("agent already running (pid %d)\n", pid)
return nil
}
exe, err := os.Executable()
if err != nil {
return err
}
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
exe = resolved
}
runArgs := []string{"agent", "run"}
if cfgFile != "" {
runArgs = append(runArgs, "--config", cfgFile)
}
cmd := exec.Command(exe, runArgs...)
if err := os.MkdirAll(filepath.Dir(cfg.LogFile), 0o755); err != nil {
return err
}
logF, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return err
}
cmd.Stdout = logF
cmd.Stderr = logF
cmd.Stdin = nil
detachProcess(cmd)
if err := cmd.Start(); err != nil {
_ = logF.Close()
return fmt.Errorf("start agent: %w", err)
}
pid := cmd.Process.Pid
_ = cmd.Process.Release()
_ = logF.Close()
if err := writePID(cfg.PIDFile, pid); err != nil {
return err
}
time.Sleep(400 * time.Millisecond)
if !signalAlive(pid) {
removePID(cfg.PIDFile)
return fmt.Errorf("agent exited immediately — see %s", cfg.LogFile)
}
fmt.Printf("agent started pid=%d\n", pid)
fmt.Printf("logs: %s\n", cfg.LogFile)
return nil
}
func stopDaemonCmd(args []string) error {
cfg, _ := loadCfgWithPath("stop", args)
pid, err := readPID(cfg.PIDFile)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("agent is not running")
return nil
}
return err
}
if !signalAlive(pid) {
removePID(cfg.PIDFile)
fmt.Println("agent is not running (stale pid file removed)")
return nil
}
if err := signalTerminate(pid); err != nil {
return fmt.Errorf("stop pid %d: %w", pid, err)
}
deadline := time.Now().Add(8 * time.Second)
for time.Now().Before(deadline) {
if !signalAlive(pid) {
removePID(cfg.PIDFile)
fmt.Printf("agent stopped (was pid %d)\n", pid)
return nil
}
time.Sleep(200 * time.Millisecond)
}
_ = signalKill(pid)
time.Sleep(200 * time.Millisecond)
removePID(cfg.PIDFile)
fmt.Printf("agent killed (pid %d)\n", pid)
return nil
}
func restartDaemonCmd(args []string) error {
_ = stopDaemonCmd(args)
return startDaemonCmd(args)
}
// loadCfgWithPath returns config and the resolved --config path (may be empty).
func loadCfgWithPath(sub string, args []string) (config.Config, string) {
fs := flag.NewFlagSet(sub, flag.ExitOnError)
cfgPath := fs.String("config", "", "path to agent.yaml")
_ = fs.Parse(args)
path := strings.TrimSpace(*cfgPath)
cfg, err := config.Load(path)
if err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
if path == "" {
// Mirror config.Load default discovery for daemon child argv.
path = defaultConfigPath()
} else if !filepath.IsAbs(path) {
abs, err := filepath.Abs(path)
if err == nil {
path = abs
}
}
return cfg, path
}
// defaultConfigPath matches config.Load("") discovery so the background child
// reopens the same yaml the parent resolved.
func defaultConfigPath() string {
return filepath.Join(repo.Root(), "apps", "agent", "agent.yaml")
}

View file

@ -0,0 +1,37 @@
//go:build unix
package agentcmd
import (
"os"
"os/exec"
"syscall"
)
func detachProcess(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
}
func signalAlive(pid int) bool {
p, err := os.FindProcess(pid)
if err != nil {
return false
}
return p.Signal(syscall.Signal(0)) == nil
}
func signalTerminate(pid int) error {
p, err := os.FindProcess(pid)
if err != nil {
return err
}
return p.Signal(syscall.SIGTERM)
}
func signalKill(pid int) error {
p, err := os.FindProcess(pid)
if err != nil {
return err
}
return p.Signal(syscall.SIGKILL)
}

View file

@ -0,0 +1,46 @@
//go:build windows
package agentcmd
import (
"os"
"os/exec"
"syscall"
"golang.org/x/sys/windows"
)
func detachProcess(cmd *exec.Cmd) {
// CREATE_NEW_PROCESS_GROUP so stop can target the child; keep stdio so
// stdout/stderr still reach the log file opened by the parent.
cmd.SysProcAttr = &syscall.SysProcAttr{
CreationFlags: windows.CREATE_NEW_PROCESS_GROUP,
}
}
func signalAlive(pid int) bool {
// On Windows, FindProcess always succeeds; use OpenProcess exit code instead.
h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
if err != nil {
return false
}
defer windows.CloseHandle(h)
var code uint32
if err := windows.GetExitCodeProcess(h, &code); err != nil {
return false
}
const stillActive = 259 // STILL_ACTIVE
return code == stillActive
}
func signalTerminate(pid int) error {
p, err := os.FindProcess(pid)
if err != nil {
return err
}
return p.Kill()
}
func signalKill(pid int) error {
return signalTerminate(pid)
}

View file

@ -0,0 +1,282 @@
package agentcmd
import (
"flag"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
"streamd/apps/agent/internal/config"
"streamd/repo"
)
const (
releaseBaseURL = "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download"
defaultChannel = "stable"
)
// errUpdateDeferred means the binary swap finishes after process exit (Windows self-update).
var errUpdateDeferred = fmt.Errorf("update deferred until process exit")
func defaultAssetName() string {
switch runtime.GOOS {
case "linux":
switch runtime.GOARCH {
case "amd64":
return "streamd-linux-amd64"
case "arm64":
return "streamd-linux-arm64"
}
case "darwin":
switch runtime.GOARCH {
case "amd64":
return "streamd-darwin-amd64"
case "arm64":
return "streamd-darwin-arm64"
}
case "windows":
switch runtime.GOARCH {
case "amd64":
return "streamd-windows-amd64.exe"
case "arm64":
return "streamd-windows-arm64.exe"
}
}
return ""
}
func updateURL(base, ref, asset string) string {
base = strings.TrimRight(base, "/")
return fmt.Sprintf("%s/%s/%s", base, ref, asset)
}
func updateDaemonCmd(args []string) error {
fs := flag.NewFlagSet("update", flag.ExitOnError)
cfgPath := fs.String("config", "", "path to agent.yaml")
beta := fs.Bool("beta", false, "use beta channel")
tag := fs.String("tag", "", "pin to release tag (e.g. v0.2.1)")
noRestart := fs.Bool("no-restart", false, "install only; do not start agent")
keep := fs.Int("keep", -1, "archived binaries to keep under old/ (-1 = config)")
_ = fs.Parse(args)
path := strings.TrimSpace(*cfgPath)
cfg, err := config.Load(path)
if err != nil {
return err
}
if path == "" {
path = defaultConfigPath()
} else if !filepath.IsAbs(path) {
if abs, err := filepath.Abs(path); err == nil {
path = abs
}
}
channel := cfg.Channel
if channel == "" {
channel = defaultChannel
}
if *beta {
channel = "beta"
}
ref := channel
if strings.TrimSpace(*tag) != "" {
ref = strings.TrimSpace(*tag)
}
asset := cfg.Asset
if asset == "" {
asset = defaultAssetName()
}
if asset == "" {
return fmt.Errorf("unsupported platform %s/%s — set asset: in agent.yaml", runtime.GOOS, runtime.GOARCH)
}
keepN := 10
if cfg.KeepOld != nil {
keepN = *cfg.KeepOld
}
if *keep >= 0 {
keepN = *keep
}
installRoot := repo.Root()
url := updateURL(releaseBaseURL, ref, asset)
fmt.Printf("agent update: downloading %s\n", url)
tmp, err := downloadToTemp(installRoot, url)
if err != nil {
return err
}
defer os.Remove(tmp)
if err := smokeTestBinary(tmp); err != nil {
return err
}
exe, err := os.Executable()
if err != nil {
return err
}
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
exe = resolved
}
target := exe
wantName := "streamd"
if runtime.GOOS == "windows" {
wantName = "streamd.exe"
}
// Prefer well-known names in the install / Downloads tree.
for _, candidate := range []string{
filepath.Join(installRoot, wantName),
filepath.Join(installRoot, "streamd-windows-amd64.exe"),
filepath.Join(installRoot, "streamd-linux-amd64"),
filepath.Join(installRoot, "bin", wantName),
} {
if st, err := os.Stat(candidate); err == nil && !st.IsDir() {
target = candidate
break
}
}
// If the running exe is already a streamd binary in this tree, prefer it.
if strings.Contains(strings.ToLower(filepath.Base(exe)), "streamd") {
if st, err := os.Stat(exe); err == nil && !st.IsDir() {
target = exe
}
}
if _, ok := runningPID(cfg); ok {
fmt.Println("agent update: stopping running agent…")
if err := stopDaemonCmd([]string{"--config", path}); err != nil {
return err
}
}
oldDir := filepath.Join(filepath.Dir(target), "old")
if err := os.MkdirAll(oldDir, 0o755); err != nil {
return err
}
stamp := time.Now().UTC().Format("20060102T150405Z")
archive := filepath.Join(oldDir, "streamd."+stamp)
if runtime.GOOS == "windows" {
archive += ".exe"
}
if _, err := os.Stat(archive); err == nil {
archive += "." + fmt.Sprint(os.Getpid())
}
if *noRestart {
_ = os.Setenv("STREAMD_UPDATE_RESTART", "0")
} else {
_ = os.Setenv("STREAMD_UPDATE_RESTART", "1")
_ = os.Setenv("STREAMD_UPDATE_AGENT_CONFIG", path)
}
if err := replaceBinary(target, tmp, archive); err != nil {
if err == errUpdateDeferred {
return nil // helper finishes after exit; treat as success for CLI
}
return err
}
fmt.Printf("agent update: archived previous → %s\n", archive)
fmt.Printf("agent update: installed %s (%s)\n", target, ref)
pruneOldBinaries(oldDir, keepN)
if *noRestart {
fmt.Println("agent update: done (--no-restart). Start with: streamd agent start")
return nil
}
fmt.Println("agent update: starting…")
return startDaemonCmd([]string{"--config", path})
}
func downloadToTemp(dir, url string) (string, error) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
f, err := os.CreateTemp(dir, ".streamd-download-*")
if err != nil {
return "", err
}
path := f.Name()
resp, err := http.Get(url)
if err != nil {
_ = f.Close()
_ = os.Remove(path)
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
_ = f.Close()
_ = os.Remove(path)
return "", fmt.Errorf("download %s: HTTP %s", url, resp.Status)
}
n, err := io.Copy(f, resp.Body)
closeErr := f.Close()
if err != nil {
_ = os.Remove(path)
return "", err
}
if closeErr != nil {
_ = os.Remove(path)
return "", closeErr
}
if n < 1024 {
_ = os.Remove(path)
return "", fmt.Errorf("download too small (%d bytes) — check URL %s", n, url)
}
head, _ := os.ReadFile(path)
if len(head) > 32 {
h := strings.ToLower(string(head[:32]))
if strings.Contains(h, "<!doctype") || strings.Contains(h, "<html") {
_ = os.Remove(path)
return "", fmt.Errorf("download looks like HTML, not a binary: %s", url)
}
}
_ = os.Chmod(path, 0o755)
return path, nil
}
func smokeTestBinary(path string) error {
cmd := exec.Command(path, "help")
out, err := cmd.CombinedOutput()
text := string(out)
if err != nil {
if !strings.Contains(text, "serve") && !strings.Contains(text, "agent") && !strings.Contains(text, "streamd") {
return fmt.Errorf("new binary failed smoke test: %w\n%s", err, out)
}
}
return nil
}
func pruneOldBinaries(oldDir string, keep int) {
if keep <= 0 {
return
}
ents, err := os.ReadDir(oldDir)
if err != nil {
return
}
var names []string
for _, e := range ents {
if e.IsDir() {
continue
}
n := e.Name()
if strings.HasPrefix(n, "streamd.") {
names = append(names, n)
}
}
sort.Strings(names)
if len(names) <= keep {
return
}
for _, n := range names[:len(names)-keep] {
_ = os.Remove(filepath.Join(oldDir, n))
fmt.Printf("agent update: pruned %s\n", filepath.Join(oldDir, n))
}
}

View file

@ -0,0 +1,21 @@
//go:build unix
package agentcmd
import (
"fmt"
"os"
)
// replaceBinary moves the live binary to archive, then moves next into place.
func replaceBinary(target, next, archive string) error {
if err := os.Rename(target, archive); err != nil {
return fmt.Errorf("archive current binary: %w", err)
}
if err := os.Rename(next, target); err != nil {
_ = os.Rename(archive, target)
return fmt.Errorf("install new binary: %w", err)
}
_ = os.Chmod(target, 0o755)
return nil
}

View file

@ -0,0 +1,125 @@
//go:build windows
package agentcmd
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"time"
)
// replaceBinary on Windows cannot overwrite the running updater exe. Strategy:
// 1. Move target → archive when target is not our own running image.
// 2. If target is us, write next beside as *.new and spawn a helper cmd that
// waits for this PID to exit, then swaps and optionally starts the agent.
func replaceBinary(target, next, archive string) error {
self, _ := os.Executable()
if resolved, err := filepath.EvalSymlinks(self); err == nil {
self = resolved
}
same, _ := sameFile(self, target)
if !same {
if err := os.Rename(target, archive); err != nil {
if err2 := copyFile(target, archive); err2 != nil {
return fmt.Errorf("archive current binary: %v / %w", err, err2)
}
_ = os.Remove(target)
}
if err := os.Rename(next, target); err != nil {
if err2 := copyFile(next, target); err2 != nil {
_ = os.Rename(archive, target)
return fmt.Errorf("install new binary: %v / %w", err, err2)
}
_ = os.Remove(next)
}
return nil
}
newPath := target + ".new"
_ = os.Remove(newPath)
if err := os.Rename(next, newPath); err != nil {
if err2 := copyFile(next, newPath); err2 != nil {
return fmt.Errorf("stage new binary: %v / %w", err, err2)
}
_ = os.Remove(next)
}
helper := filepath.Join(filepath.Dir(target), "streamd-agent-update-finish.cmd")
pid := os.Getpid()
startLine := ""
if os.Getenv("STREAMD_UPDATE_RESTART") != "0" {
cfg := os.Getenv("STREAMD_UPDATE_AGENT_CONFIG")
if cfg != "" {
startLine = fmt.Sprintf("\"%s\" agent start --config \"%s\"\r\n", escapeCmd(target), escapeCmd(cfg))
} else {
startLine = fmt.Sprintf("\"%s\" agent start\r\n", escapeCmd(target))
}
}
script := fmt.Sprintf(""+
"@echo off\r\n"+
":wait\r\n"+
"timeout /t 1 /nobreak >nul\r\n"+
"tasklist /FI \"PID eq %d\" 2>nul | find \"%d\" >nul\r\n"+
"if not errorlevel 1 goto wait\r\n"+
"move /Y \"%s\" \"%s\"\r\n"+
"move /Y \"%s\" \"%s\"\r\n"+
"%s"+
"del \"%%~f0\"\r\n",
pid, pid,
escapeCmd(target), escapeCmd(archive),
escapeCmd(newPath), escapeCmd(target),
startLine,
)
if err := os.WriteFile(helper, []byte(script), 0o644); err != nil {
return err
}
cmd := exec.Command("cmd.exe", "/C", helper)
cmd.Stdout = nil
cmd.Stderr = nil
detachProcess(cmd)
if err := cmd.Start(); err != nil {
return fmt.Errorf("start update helper: %w", err)
}
_ = cmd.Process.Release()
fmt.Println("agent update: scheduled file swap after this process exits")
fmt.Println("agent update: agent will restart automatically in 1–2s")
time.Sleep(300 * time.Millisecond)
return errUpdateDeferred
}
func escapeCmd(p string) string {
return p
}
func sameFile(a, b string) (bool, error) {
absA, err := filepath.Abs(a)
if err != nil {
return false, err
}
absB, err := filepath.Abs(b)
if err != nil {
return false, err
}
return filepath.Clean(absA) == filepath.Clean(absB), nil
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
if err != nil {
return err
}
_, copyErr := out.ReadFrom(in)
closeErr := out.Close()
if copyErr != nil {
return copyErr
}
return closeErr
}

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,14 +27,25 @@ 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.
OnDemandPriority *bool `yaml:"ondemand_priority"` OnDemandPriority *bool `yaml:"ondemand_priority"`
// JobBackoff enables exponential retry delays after a failed capture
// (1m, 2m, 4m, 8m…). Default off — a single agent should retry ASAP.
// Set job_backoff: true when several agents share the same streams.
JobBackoff *bool `yaml:"job_backoff"`
// Daemon / update (streamd agent start|stop|update)
LogFile string `yaml:"log_file"` // default agent.log next to config / install root
PIDFile string `yaml:"pid_file"` // default agent.pid
Channel string `yaml:"channel"` // stable|beta for agent update
Asset string `yaml:"asset"` // optional streamd-* asset override
KeepOld *int `yaml:"keep_old"` // archived binaries under old/ (default 10)
} }
// PushedCapturesArePriority reports whether pushed captures jump the queue. // PushedCapturesArePriority reports whether pushed captures jump the queue.
@ -43,6 +54,12 @@ func (c Config) PushedCapturesArePriority() bool {
return c.OnDemandPriority == nil || *c.OnDemandPriority return c.OnDemandPriority == nil || *c.OnDemandPriority
} }
// JobBackoffEnabled is the exponential multi-agent retry delay.
// Defaults to false so a lone agent retries immediately after a failure.
func (c Config) JobBackoffEnabled() bool {
return c.JobBackoff != nil && *c.JobBackoff
}
func (c Config) PollInterval() time.Duration { func (c Config) PollInterval() time.Duration {
if c.PollIntervalSec <= 0 { if c.PollIntervalSec <= 0 {
return 30 * time.Second return 30 * time.Second
@ -124,12 +141,36 @@ 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.Python != "" && !filepath.IsAbs(cfg.Python) {
cfg.Python = filepath.Join(root, cfg.Python)
}
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 {
cfg.ModulesSyncIntervalSec = 300 cfg.ModulesSyncIntervalSec = 300
} }
if cfg.LogFile == "" {
cfg.LogFile = "agent.log"
}
if !filepath.IsAbs(cfg.LogFile) {
cfg.LogFile = filepath.Join(root, cfg.LogFile)
}
if cfg.PIDFile == "" {
cfg.PIDFile = "agent.pid"
}
if !filepath.IsAbs(cfg.PIDFile) {
cfg.PIDFile = filepath.Join(root, cfg.PIDFile)
}
if cfg.Channel == "" {
cfg.Channel = "stable"
}
if cfg.KeepOld == nil {
k := 10
cfg.KeepOld = &k
}
return cfg return cfg
} }

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

@ -232,17 +232,18 @@ func (s *Store) MarkOK(id int64) error {
return err return err
} }
// MarkFailed increments attempts. Re-queues with backoff unless maxed out. // MarkFailed increments attempts. Re-queues unless maxed out.
// waitingDevice=true keeps status queued without burning an attempt. // waitingDevice=true keeps status queued without burning an attempt.
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error { // backoff is how long to wait before the job is runnable again (0 = immediate).
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool, backoff time.Duration) error {
j, err := s.Get(id) j, err := s.Get(id)
if err != nil { if err != nil {
return err return err
} }
if waitingDevice { if waitingDevice {
_, err = s.DB.Exec(` _, err = s.DB.Exec(`
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='' WHERE id=?`, UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`,
msg, id) msg, now(), id)
return err return err
} }
attempts := j.Attempts + 1 attempts := j.Attempts + 1
@ -252,9 +253,8 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i
attempts, msg, now(), id) attempts, msg, now(), id)
return err return err
} }
backoff := time.Duration(1<<uint(min(attempts, 4))) * time.Minute if backoff < 0 {
if backoff > 15*time.Minute { backoff = 0
backoff = 15 * time.Minute
} }
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339) nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
_, err = s.DB.Exec(` _, err = s.DB.Exec(`
@ -263,6 +263,29 @@ UPDATE jobs SET status='queued', attempts=?, last_error=?, not_before=?, device_
return err return err
} }
// ExponentialBackoff is the old multi-agent delay: 1m, 2m, 4m, 8m (cap 15m).
func ExponentialBackoff(attempts int) time.Duration {
if attempts < 1 {
attempts = 1
}
d := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
if d > 15*time.Minute {
d = 15 * time.Minute
}
return d
}
// ClearAllBackoffs makes every queued job runnable now (e.g. agent restart
// after fixing modules, or when job_backoff is disabled).
func (s *Store) ClearAllBackoffs() (int, error) {
res, err := s.DB.Exec(`UPDATE jobs SET not_before=? WHERE status='queued'`, now())
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
return int(n), nil
}
func min(a, b int) int { func min(a, b int) int {
if a < b { if a < b {
return a return a

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 {
@ -27,6 +27,9 @@ type Worker struct {
Python string Python string
WVD string WVD string
UserAgent string UserAgent string
// JobBackoff enables exponential delays between failed capture attempts.
// When false (default), failed jobs are re-queued immediately.
JobBackoff bool
Log *log.Logger Log *log.Logger
lastDelayLog time.Time lastDelayLog time.Time
@ -67,13 +70,18 @@ func (w *Worker) tick() {
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) { if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
// Config/environment issues — do not burn attempts or multi-minute backoff. // Config/environment issues — do not burn attempts or multi-minute backoff.
w.logf("job=%d waiting: %v", job.ID, err) w.logf("job=%d waiting: %v", job.ID, err)
_ = w.Queue.MarkFailed(job.ID, err.Error(), true) _ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
return return
} }
w.logf("job=%d failed: %v", job.ID, err) w.logf("job=%d failed: %v", job.ID, err)
w.event(job, client.EventCaptureFailed, err.Error(), w.event(job, client.EventCaptureFailed, err.Error(),
map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts}) map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
_ = w.Queue.MarkFailed(job.ID, err.Error(), false) backoff := time.Duration(0)
if w.JobBackoff {
backoff = queue.ExponentialBackoff(job.Attempts + 1)
w.logf("job=%d re-queue in %s (job_backoff=true)", job.ID, backoff)
}
_ = w.Queue.MarkFailed(job.ID, err.Error(), false, backoff)
return return
} }
_ = w.Queue.MarkOK(job.ID) _ = w.Queue.MarkOK(job.ID)
@ -119,8 +127,8 @@ func (w *Worker) runJob(job queue.Job) error {
_ = w.Queue.SetDevice(job.ID, serial) _ = w.Queue.SetDevice(job.ID, serial)
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package()) w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
// Short TTL; /ws/agent heartbeats renew while this process is alive. // Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil { if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
return fmt.Errorf("streamd claim: %w", err) return fmt.Errorf("streamd claim: %w", err)
} }
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }() defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
@ -140,6 +148,19 @@ func (w *Worker) runJob(job queue.Job) error {
return err return err
} }
needsKeys := true
if km := strings.ToLower(strings.TrimSpace(a.KeyMode())); km == "none" || km == "clear" {
needsKeys = false
}
hasKey := poller.ValidKeyPair(res.Key)
if needsKeys && !hasKey {
return fmt.Errorf("refusing to post credentials without valid Widevine key (got mpd=%q key_empty=%v)",
trimURL(res.MPD), strings.TrimSpace(res.Key) == "")
}
if strings.TrimSpace(res.MPD) == "" {
return fmt.Errorf("refusing to post credentials without mpd")
}
cred := client.Credentials{ cred := client.Credentials{
MPD: res.MPD, MPD: res.MPD,
Key: res.Key, Key: res.Key,
@ -150,15 +171,25 @@ func (w *Worker) runJob(job queue.Job) error {
if err := w.API.PostCredentials(job.StreamID, cred); err != nil { if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
return fmt.Errorf("post credentials: %w", err) return fmt.Errorf("post credentials: %w", err)
} }
w.logf("job=%d posted credentials to streamd has_key=%v key_valid=%v mpd=%s",
job.ID, strings.TrimSpace(res.Key) != "", hasKey, trimURL(res.MPD))
// Report what was captured, never the key itself. // Report what was captured, never the key itself.
w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{ w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
"device": serial, "device": serial,
"has_key": strings.TrimSpace(res.Key) != "", "has_key": strings.TrimSpace(res.Key) != "",
"key_valid": poller.ValidKeyPair(res.Key), "key_valid": hasKey,
}) })
return nil return nil
} }
func trimURL(s string) string {
s = strings.TrimSpace(s)
if len(s) <= 96 {
return s
}
return s[:96] + "…"
}
// event posts a stream event to streamd. A timeline entry is never worth // event posts a stream event to streamd. A timeline entry is never worth
// failing a capture over, so errors are logged and dropped. // failing a capture over, so errors are logged and dropped.
func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) { func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {

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,4 +1,4 @@
// 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.
@ -13,14 +13,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 +39,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,18 +102,19 @@ 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 start|stop|restart|status|update|run [flags]
drm proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent streamd serve [--bind …] [--data …] # foreground (same as run)
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

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,30 @@ 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 { 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") return copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe"))
if sameFile(exe, dest) { }
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 +157,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

@ -0,0 +1,6 @@
# Dependencies for wvkey.py (the only Python in the project).
# Install into a venv at the repo root:
# python -m venv .venv
# .venv/bin/pip install -r apps/wvkey/requirements.txt
pywidevine==1.9.0
requests==2.34.2

View file

@ -0,0 +1,367 @@
#!/usr/bin/env python3
"""Thin Widevine CDM helper for the Go capture tooling.
Prints a single CONTENT key as KID:KEY on stdout (no banners) when --quiet.
Exit code 0 on success.
Example:
.venv/Scripts/python.exe wvkey.py \\
--wvd path/to/device.wvd \\
--pssh 'AAAA…' \\
--license-url 'https://…' \\
--auth 'Basic …' \\
--pid 'xxxx' \\
--quiet
"""
from __future__ import annotations
import argparse
import base64
import json
import sys
from pathlib import Path
import requests
from pywidevine.cdm import Cdm
from pywidevine.device import Device
from pywidevine.pssh import PSSH
def fetch_content_keys_modulardrm(
*,
wvd: Path,
pssh_b64: str,
auth: str,
release_pid: str,
license_url: str,
user_agent: str,
) -> list[str]:
"""RTE / thePlatform ModularDrm (JSON challenge wrapper)."""
device = Device.load(str(wvd))
cdm = Cdm.from_device(device)
session_id = cdm.open()
try:
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
challenge_b64 = base64.b64encode(challenge).decode("utf-8")
payload = {
"getWidevineLicense": {
"releasePid": release_pid,
"widevineChallenge": challenge_b64,
}
}
headers = {
"Accept-Encoding": "gzip",
"Authorization": auth,
"Content-Type": "application/json; charset=utf-8",
}
if user_agent:
headers["User-Agent"] = user_agent
response = requests.post(license_url, json=payload, headers=headers, timeout=30)
data = response.json()
if data.get("isException"):
raise RuntimeError(data.get("description") or "license server exception")
license_b64 = (
data.get("getWidevineLicenseResponse", {}).get("license")
or data.get("license")
)
if not license_b64:
raise RuntimeError("no license in response: " + json.dumps(data)[:1500])
cdm.parse_license(session_id, base64.b64decode(license_b64))
keys = [
f"{key.kid.hex}:{key.key.hex()}"
for key in cdm.get_keys(session_id)
if key.type == "CONTENT"
]
finally:
cdm.close(session_id)
if not keys:
raise RuntimeError("no CONTENT keys")
return keys
def fetch_content_keys_raw(
*,
wvd: Path,
pssh_b64: str,
license_url: str,
user_agent: str,
) -> list[str]:
"""Brightcove / generic Widevine: POST raw challenge, parse raw license body."""
device = Device.load(str(wvd))
cdm = Cdm.from_device(device)
session_id = cdm.open()
try:
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
headers = {
"Content-Type": "application/octet-stream",
"Accept": "*/*",
}
if user_agent:
headers["User-Agent"] = user_agent
response = requests.post(
license_url, data=challenge, headers=headers, timeout=30
)
if response.status_code >= 400:
raise RuntimeError(
f"license HTTP {response.status_code}: {response.text[:500]!r}"
)
body = response.content
if not body:
raise RuntimeError("empty license response body")
# Some servers wrap base64 text; try raw first, then b64.
try:
cdm.parse_license(session_id, body)
except Exception:
try:
cdm.parse_license(session_id, base64.b64decode(body))
except Exception as exc:
raise RuntimeError(
f"parse_license failed ({len(body)} bytes): {exc}"
) from exc
keys = [
f"{key.kid.hex}:{key.key.hex()}"
for key in cdm.get_keys(session_id)
if key.type == "CONTENT"
]
finally:
cdm.close(session_id)
if not keys:
raise RuntimeError("no CONTENT keys")
return keys
_CHALLENGE_KEYS = (
"request",
"licenseRequest",
"license_request",
"widevineChallenge",
"widevine_challenge",
"challenge",
"payload",
"rawLicenseRequestBase64",
"message",
"drm_info",
)
def _replace_challenge(obj, challenge_b64: str, challenge_bytes: bytes) -> bool:
"""Replace the Widevine challenge field inside a captured JSON license body."""
if isinstance(obj, dict):
for key in _CHALLENGE_KEYS:
if key not in obj:
continue
val = obj[key]
if key == "drm_info" and isinstance(val, list):
obj[key] = list(challenge_bytes)
return True
if isinstance(val, str) and len(val) >= 8:
obj[key] = challenge_b64
return True
if isinstance(val, dict) and _replace_challenge(val, challenge_b64, challenge_bytes):
return True
for val in obj.values():
if _replace_challenge(val, challenge_b64, challenge_bytes):
return True
elif isinstance(obj, list):
for item in obj:
if _replace_challenge(item, challenge_b64, challenge_bytes):
return True
return False
def _license_bytes_from_response(response: requests.Response) -> bytes:
body = response.content
if not body:
raise RuntimeError("empty license response body")
# Prefer JSON wrappers used by RedBee / ModularDrm-style proxies.
try:
data = response.json()
except Exception:
data = None
if isinstance(data, dict):
for path in (
("license",),
("licenseResponse",),
("license_response",),
("payload",),
("message",),
("getWidevineLicenseResponse", "license"),
("status", "license"),
):
cur: object = data
ok = True
for key in path:
if not isinstance(cur, dict) or key not in cur:
ok = False
break
cur = cur[key]
if ok and isinstance(cur, str) and cur:
try:
return base64.b64decode(cur)
except Exception:
return cur.encode("utf-8")
# Some LSP responses nest the blob under status.success payload.
if data.get("status", {}).get("success") is False:
raise RuntimeError("license LSP error: " + json.dumps(data)[:500])
return body
def fetch_content_keys_wrap(
*,
wvd: Path,
pssh_b64: str,
license_url: str,
wrap_json: str,
user_agent: str,
) -> list[str]:
"""Re-POST a captured JSON license body with a fresh local CDM challenge.
Used by Channel 4 / RedBee (wvlicenceproxy-service) which reject raw
octet-stream (HTTP 415) and need the phone's token fields intact.
"""
try:
template = json.loads(wrap_json)
except Exception as exc:
raise RuntimeError(f"wrap-json is not valid JSON: {exc}") from exc
device = Device.load(str(wvd))
cdm = Cdm.from_device(device)
session_id = cdm.open()
try:
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
challenge_b64 = base64.b64encode(challenge).decode("utf-8")
if not _replace_challenge(template, challenge_b64, challenge):
raise RuntimeError(
"wrap-json has no recognisable challenge field "
f"(tried {', '.join(_CHALLENGE_KEYS)})"
)
headers = {
"Content-Type": "application/json",
"Accept": "application/json, */*",
}
if user_agent:
headers["User-Agent"] = user_agent
response = requests.post(
license_url, json=template, headers=headers, timeout=30
)
if response.status_code >= 400:
raise RuntimeError(
f"license HTTP {response.status_code}: {response.text[:500]!r}"
)
license_bytes = _license_bytes_from_response(response)
try:
cdm.parse_license(session_id, license_bytes)
except Exception:
try:
cdm.parse_license(session_id, base64.b64decode(license_bytes))
except Exception as exc:
raise RuntimeError(
f"parse_license failed ({len(license_bytes)} bytes): {exc}"
) from exc
keys = [
f"{key.kid.hex}:{key.key.hex()}"
for key in cdm.get_keys(session_id)
if key.type == "CONTENT"
]
finally:
cdm.close(session_id)
if not keys:
raise RuntimeError("no CONTENT keys")
return keys
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(description="Widevine CDM helper → KID:KEY")
p.add_argument("--wvd", type=Path, required=True, help="Path to .wvd device file")
p.add_argument("--pssh", required=True, help="Base64 PSSH box")
p.add_argument(
"--mode",
choices=("modulardrm", "raw", "wrap"),
default="modulardrm",
help="modulardrm=RTE JSON; raw=octet-stream; wrap=captured JSON body",
)
p.add_argument("--auth", default="", help="Authorization header (modulardrm)")
p.add_argument("--pid", default="", help="releasePid (modulardrm)")
p.add_argument(
"--wrap-json",
default="",
help="Captured phone license POST JSON (wrap mode)",
)
p.add_argument(
"--license-url",
required=True,
help="Widevine license server URL",
)
p.add_argument(
"--user-agent",
default="",
help="Optional User-Agent for the license request",
)
p.add_argument(
"--quiet",
action="store_true",
help="Print only KID:KEY lines (for Go tooling)",
)
p.add_argument(
"--all",
action="store_true",
help="Print every CONTENT key (default: first only)",
)
args = p.parse_args(argv)
if not args.wvd.is_file():
print(f"[!] missing WVD: {args.wvd}", file=sys.stderr)
return 2
try:
if args.mode == "raw":
keys = fetch_content_keys_raw(
wvd=args.wvd,
pssh_b64=args.pssh,
license_url=args.license_url,
user_agent=args.user_agent,
)
elif args.mode == "wrap":
if not args.wrap_json.strip():
print(
"[!] --wrap-json required for wrap mode "
"(phone must complete a license POST during capture)",
file=sys.stderr,
)
return 2
keys = fetch_content_keys_wrap(
wvd=args.wvd,
pssh_b64=args.pssh,
license_url=args.license_url,
wrap_json=args.wrap_json,
user_agent=args.user_agent,
)
else:
if not args.auth or not args.pid:
print("[!] --auth and --pid required for modulardrm mode", file=sys.stderr)
return 2
keys = fetch_content_keys_modulardrm(
wvd=args.wvd,
pssh_b64=args.pssh,
auth=args.auth,
release_pid=args.pid,
license_url=args.license_url,
user_agent=args.user_agent,
)
except Exception as exc:
print(f"[!] {exc}", file=sys.stderr)
return 1
out = keys if args.all else keys[:1]
if not args.quiet:
print("[+] Keys:", file=sys.stderr)
for pair in out:
print(f"--key {pair}", file=sys.stderr)
for pair in out:
print(pair)
return 0
if __name__ == "__main__":
raise SystemExit(main())

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,13 +15,14 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"drmdecryption/modhost" "streamd/modhost"
"drmdecryption/repo" "streamd/repo"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
// Dir returns the directory holding a module's values. // Dir returns the directory holding a module's values.
// Prefers the active modules dir (see modhost / --modules-dir); falls back to // Prefers the active modules dir (see modhost / --modules-dir); then the
// directory beside a panel/release binary (<mod>/.bin/<name>); then
// apps/modules/<name>/ for older checkouts. // apps/modules/<name>/ for older checkouts.
func Dir(name string) string { func Dir(name string) string {
preferred := filepath.Join(modhost.ModulesDir(""), name) preferred := filepath.Join(modhost.ModulesDir(""), name)
@ -31,6 +32,9 @@ func Dir(name string) string {
if modhost.ModulesDirOverride() != "" { if modhost.ModulesDirOverride() != "" {
return preferred return preferred
} }
if beside := dirBesideExecutable(name); beside != "" {
return beside
}
root := repo.Root() root := repo.Root()
if _, err := os.Stat(filepath.Join(root, "modules")); err == nil { if _, err := os.Stat(filepath.Join(root, "modules")); err == nil {
return filepath.Join(root, "modules", name) return filepath.Join(root, "modules", name)
@ -38,6 +42,43 @@ func Dir(name string) string {
return filepath.Join(root, "apps", "modules", name) return filepath.Join(root, "apps", "modules", name)
} }
// dirBesideExecutable finds module.yaml next to a panel/release binary layout:
// <modDir>/.bin/<name>[.exe]
// <modDir>/.bin/<goos>-<goarch>/<name>[.exe]
func dirBesideExecutable(name string) string {
exe, err := os.Executable()
if err != nil {
return ""
}
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
exe = resolved
}
base := strings.TrimSuffix(filepath.Base(exe), ".exe")
if !strings.EqualFold(base, name) {
return ""
}
binDir := filepath.Dir(exe)
candidates := []string{}
if strings.EqualFold(filepath.Base(binDir), ".bin") {
candidates = append(candidates, filepath.Dir(binDir))
}
parent := filepath.Dir(binDir)
if strings.EqualFold(filepath.Base(parent), ".bin") {
candidates = append(candidates, filepath.Dir(parent))
}
for _, dir := range candidates {
if fileExists(filepath.Join(dir, "module.yaml")) || fileExists(filepath.Join(dir, "module-publish.yaml")) {
return dir
}
}
return ""
}
func fileExists(p string) bool {
st, err := os.Stat(p)
return err == nil && !st.IsDir()
}
// Path returns the preferred values file path (module.yaml). // Path returns the preferred values file path (module.yaml).
func Path(name string) string { func Path(name string) string {
return filepath.Join(Dir(name), "module.yaml") return filepath.Join(Dir(name), "module.yaml")

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

@ -9,9 +9,39 @@ import (
"strings" "strings"
) )
// prepareModuleCmd sets STREAMD_MODULES_DIR so child module binaries load
// panel-store module.yaml. Module builds that call EffectiveModulesDir (or
// ApplyEnvModulesDir) honour this; /api/apps also falls back to parsing the
// panel module.yaml when describe returns no channels.
func prepareModuleCmd(cmd *exec.Cmd) {
ov := ModulesDirOverride()
if ov == "" {
return
}
cmd.Env = append(withoutEnvKeys(os.Environ(), "STREAMD_MODULES_DIR", "DRM_MODULES_DIR"),
"STREAMD_MODULES_DIR="+ov)
}
func withoutEnvKeys(env []string, keys ...string) []string {
drop := map[string]struct{}{}
for _, k := range keys {
drop[strings.ToUpper(k)] = struct{}{}
}
out := make([]string, 0, len(env))
for _, e := range env {
key, _, _ := strings.Cut(e, "=")
if _, skip := drop[strings.ToUpper(key)]; skip {
continue
}
out = append(out, e)
}
return out
}
// Run executes the module binary with args, inheriting stdout/stderr. // Run executes the module binary with args, inheriting stdout/stderr.
func Run(bin string, args ...string) error { func Run(bin string, args ...string) error {
cmd := exec.Command(bin, args...) cmd := exec.Command(bin, args...)
prepareModuleCmd(cmd)
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin cmd.Stdin = os.Stdin
@ -24,6 +54,7 @@ func Run(bin string, args ...string) error {
// RunOutput executes the module binary and returns combined stdout. // RunOutput executes the module binary and returns combined stdout.
func RunOutput(bin string, args ...string) (string, error) { func RunOutput(bin string, args ...string) (string, error) {
cmd := exec.Command(bin, args...) cmd := exec.Command(bin, args...)
prepareModuleCmd(cmd)
var stdout, stderr bytes.Buffer var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout cmd.Stdout = &stdout
cmd.Stderr = &stderr cmd.Stderr = &stderr
@ -74,5 +105,9 @@ func Load(root, name string) (Module, string, Describe, error) {
if d.Name == "" { if d.Name == "" {
d.Name = m.Name d.Name = m.Name
} }
// Older panel binaries may not load module.yaml from STREAMD_MODULES_DIR /
// exe-adjacent layout, leaving package empty (breaks transparent MITM —
// iptables then treats the listen port as the package name).
enrichDescribeFromYAML(&d, m.Dir)
return m, bin, d, nil return m, bin, d, nil
} }

View file

@ -0,0 +1,31 @@
package modhost
import (
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestPrepareModuleCmdSetsEnv(t *testing.T) {
t.Cleanup(func() { _ = SetModulesDir("") })
ov := filepath.Join(t.TempDir(), "modules")
if err := os.MkdirAll(ov, 0o755); err != nil {
t.Fatal(err)
}
if err := SetModulesDir(ov); err != nil {
t.Fatal(err)
}
cmd := exec.Command("true")
prepareModuleCmd(cmd)
found := false
for _, e := range cmd.Env {
if e == "STREAMD_MODULES_DIR="+ov {
found = true
break
}
}
if !found {
t.Fatalf("STREAMD_MODULES_DIR missing in env: %v", cmd.Env)
}
}

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

@ -3,9 +3,10 @@ package modhost
import ( import (
"os" "os"
"path/filepath" "path/filepath"
"strings"
"sync" "sync"
"drmdecryption/repo" "streamd/repo"
) )
var ( var (
@ -13,7 +14,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()
@ -37,24 +38,45 @@ func ModulesDirOverride() string {
return modulesDirOV return modulesDirOV
} }
// envModulesDir returns STREAMD_MODULES_DIR (preferred) or DRM_MODULES_DIR.
func envModulesDir() string {
v := strings.TrimSpace(os.Getenv("STREAMD_MODULES_DIR"))
if v == "" {
v = strings.TrimSpace(os.Getenv("DRM_MODULES_DIR"))
}
if v == "" {
return ""
}
if abs, err := filepath.Abs(v); err == nil {
return abs
}
return v
}
// EffectiveModulesDir is the directory that Discover/Open scan. // EffectiveModulesDir is the directory that Discover/Open scan.
// Prefer --modules-dir / DRM_MODULES_DIR; else <root>/modules. // Prefer --modules-dir, then STREAMD_MODULES_DIR / DRM_MODULES_DIR, else <root>/modules.
// Module binaries read the env here directly so they honour the panel store even
// when they never call ApplyEnvModulesDir.
func EffectiveModulesDir(root string) string { func EffectiveModulesDir(root string) string {
if ov := ModulesDirOverride(); ov != "" { if ov := ModulesDirOverride(); ov != "" {
return ov return ov
} }
if v := envModulesDir(); v != "" {
return v
}
if root == "" { if root == "" {
root = repo.Root() root = repo.Root()
} }
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 := envModulesDir()
if v == "" { if v == "" {
return nil return nil
} }

View file

@ -0,0 +1,39 @@
package modhost
import (
"os"
"path/filepath"
"testing"
)
func TestEffectiveModulesDirEnv(t *testing.T) {
t.Cleanup(func() {
_ = SetModulesDir("")
_ = os.Unsetenv("STREAMD_MODULES_DIR")
_ = os.Unsetenv("DRM_MODULES_DIR")
})
_ = SetModulesDir("")
_ = os.Unsetenv("STREAMD_MODULES_DIR")
_ = os.Unsetenv("DRM_MODULES_DIR")
dir := t.TempDir()
t.Setenv("STREAMD_MODULES_DIR", dir)
got := EffectiveModulesDir("")
want, _ := filepath.Abs(dir)
if got != want {
t.Fatalf("env modules dir: got %q want %q", got, want)
}
override := filepath.Join(t.TempDir(), "override")
if err := os.MkdirAll(override, 0o755); err != nil {
t.Fatal(err)
}
if err := SetModulesDir(override); err != nil {
t.Fatal(err)
}
got = EffectiveModulesDir("")
want, _ = filepath.Abs(override)
if got != want {
t.Fatalf("flag overrides env: got %q want %q", got, want)
}
}

View file

@ -0,0 +1,77 @@
package modhost
import (
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
)
// enrichDescribeFromYAML fills gaps left by older module binaries that do not
// load panel/agent module.yaml (empty package breaks transparent MITM).
func enrichDescribeFromYAML(d *Describe, modDir string) {
if d == nil || strings.TrimSpace(modDir) == "" {
return
}
raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml"))
if err != nil {
raw, err = os.ReadFile(filepath.Join(modDir, "module-publish.yaml"))
if err != nil {
return
}
}
var doc struct {
Package string `yaml:"package"`
LicenseURL string `yaml:"license_url"`
KeyMode string `yaml:"key_mode"`
ProxyBin string `yaml:"proxy_bin"`
CAHash string `yaml:"ca_hash"`
TransparentMITM *bool `yaml:"transparent_mitm"`
RequireWVD *bool `yaml:"require_wvd"`
Rewriter string `yaml:"rewriter"`
Channels map[string]struct {
Label string `yaml:"label"`
} `yaml:"channels"`
}
if err := yaml.Unmarshal(raw, &doc); err != nil {
return
}
if strings.TrimSpace(d.Package) == "" && strings.TrimSpace(doc.Package) != "" {
d.Package = strings.TrimSpace(doc.Package)
}
if strings.TrimSpace(d.LicenseURL) == "" && strings.TrimSpace(doc.LicenseURL) != "" {
d.LicenseURL = strings.TrimSpace(doc.LicenseURL)
}
if strings.TrimSpace(d.KeyMode) == "" && strings.TrimSpace(doc.KeyMode) != "" {
d.KeyMode = strings.TrimSpace(doc.KeyMode)
}
if strings.TrimSpace(d.ProxyBin) == "" && strings.TrimSpace(doc.ProxyBin) != "" {
d.ProxyBin = strings.TrimSpace(doc.ProxyBin)
}
if strings.TrimSpace(d.CAHash) == "" && strings.TrimSpace(doc.CAHash) != "" {
d.CAHash = strings.TrimSpace(doc.CAHash)
}
if strings.TrimSpace(d.Rewriter) == "" && strings.TrimSpace(doc.Rewriter) != "" {
d.Rewriter = strings.TrimSpace(doc.Rewriter)
}
if !d.TransparentMITM && doc.TransparentMITM != nil {
d.TransparentMITM = *doc.TransparentMITM
}
if !d.RequireWVD && doc.RequireWVD != nil {
d.RequireWVD = *doc.RequireWVD
}
if len(d.Channels) == 0 && len(doc.Channels) > 0 {
for id, ch := range doc.Channels {
label := strings.TrimSpace(ch.Label)
if label == "" {
label = id
}
d.Channels = append(d.Channels, Channel{ID: id, Label: label})
}
}
if !d.ValuesLoaded {
d.ValuesLoaded = true
d.ValuesPath = filepath.Join(modDir, "module.yaml")
}
}

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
@ -206,17 +206,21 @@ func Run(opt Options) (res Result, err error) {
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() { if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
useTProxy = true useTProxy = true
} }
pkgName := strings.TrimSpace(a.Package())
if useTProxy && pkgName == "" {
return res, fmt.Errorf("module %q has empty package — fix module.yaml package: (or re-pull modules); transparent MITM cannot install iptables UID rules", a.Name())
}
if useTProxy { if useTProxy {
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working. // Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key. // StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
proxy.ClearHTTPProxy(c) proxy.ClearHTTPProxy(c)
remoteDir := "/data/local/tmp/capture/" + a.Package() remoteDir := "/data/local/tmp/capture/" + pkgName
var mitmHosts []string var mitmHosts []string
if mh, ok := a.(app.MitmHostList); ok { if mh, ok := a.(app.MitmHostList); ok {
mitmHosts = mh.MitmHosts() mitmHosts = mh.MitmHosts()
} }
if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false, mitmHosts...); err != nil { if err := proxy.StartTransparent(c, proxyBin, pkgName, "8080", remoteDir, false, mitmHosts...); err != nil {
return res, fmt.Errorf("transparent MITM start: %w", err) return res, fmt.Errorf("transparent MITM start: %w", err)
} }
defer proxy.StopTransparent(c) defer proxy.StopTransparent(c)
@ -238,17 +242,6 @@ func Run(opt Options) (res Result, err error) {
proxy.ReinjectCA(c, caHash) proxy.ReinjectCA(c, caHash)
} }
if err := a.Launch(c); err != nil {
return res, fmt.Errorf("launch: %w", err)
}
if !opt.NoAutoPlay {
if err := a.AutoPlay(c, opt.Channel); err != nil {
return res, fmt.Errorf("auto-play: %w", err)
}
} else {
fmt.Println("[*] Open the channel on the phone and wait for playback…")
}
_ = os.MkdirAll(filepath.Join(root, ".cache"), 0o755) _ = os.MkdirAll(filepath.Join(root, ".cache"), 0o755)
serialTag := c.Serial serialTag := c.Serial
if serialTag == "" { if serialTag == "" {
@ -256,57 +249,86 @@ func Run(opt Options) (res Result, err error) {
} }
localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log") localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log")
localCap := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+"_cap.json") localCap := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+"_cap.json")
// Fresh local mirrors each run so grab-all does not reuse a prior channel's MPD.
_ = os.WriteFile(localLog, nil, 0o644)
_ = os.Remove(localCap)
stop := make(chan struct{}) stop := make(chan struct{})
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop) go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
defer close(stop) defer close(stop)
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
if keyMode == "" || keyMode == "auto" {
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
}
needsKeys := keyMode != "none" && keyMode != "clear"
// DRM apps: wait up to 90s for Widevine traffic, then force-stop and retry
// (max 3). Clear / MPD-only apps keep a single wait of opt.Wait.
attempts := 1
waitPer := opt.Wait
if needsKeys {
attempts = 3
waitPer = 90 * time.Second
if opt.Wait > 0 && opt.Wait < waitPer {
waitPer = opt.Wait
}
}
need := hints.Require need := hints.Require
if len(need) == 0 { if len(need) == 0 {
need = []string{"manifest"} need = []string{"manifest"}
} }
fmt.Printf("[*] Waiting for %s…\n", strings.Join(need, " + "))
fmt.Println(" watch:", localLog) var (
capData, err := capture.Wait(c, hints, localLog, localCap, opt.Wait) capData capture.Data
if err != nil { licenseURL string
return res, err mpdURL string
} key string
licenseURL := first(capData.Get("license_url"), a.LicenseURL()) lastErr error
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode)) )
if keyMode == "" || keyMode == "auto" {
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode())) for attempt := 1; attempt <= attempts; attempt++ {
} if attempt > 1 {
// Brightcove/HLS: proxy often captures license + master URL but not PSSH. fmt.Printf("[*] Widevine attempt %d/%d — closing app and retrying…\n", attempt, attempts)
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob. c.ForceStop(a.Package())
// Skip for clear/MPD-only apps (KeyMode none). time.Sleep(800 * time.Millisecond)
if keyMode != "none" && keyMode != "clear" {
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
curPSSH := strings.TrimSpace(capData.Get("pssh"))
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
if needPSSH && mpdForPSSH != "" {
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
if curPSSH != "" && curPSSH != pssh {
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
}
capData["pssh"] = pssh
} else if err != nil && curPSSH == "" {
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
}
} else if curPSSH == "" {
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
capData["pssh"] = pssh
} else if err != nil {
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
}
}
}
} }
mpdURL := strings.TrimSpace(capData.Get("mpd")) // Fresh local mirrors each attempt so we do not reuse a prior MPD/PSSH.
// Console: always surface the MPD we will use (BBC clear streams only need this). _ = os.WriteFile(localLog, nil, 0o644)
_ = os.Remove(localCap)
if err := a.Launch(c); err != nil {
lastErr = fmt.Errorf("launch: %w", err)
continue
}
if !opt.NoAutoPlay {
if err := a.AutoPlay(c, opt.Channel); err != nil {
lastErr = fmt.Errorf("auto-play: %w", err)
c.ForceStop(a.Package())
continue
}
} else {
fmt.Println("[*] Open the channel on the phone and wait for playback…")
}
fmt.Printf("[*] Waiting for %s (attempt %d/%d, timeout %s)…\n",
strings.Join(need, " + "), attempt, attempts, waitPer.Round(time.Second))
fmt.Println(" watch:", localLog)
cap, err := capture.Wait(c, hints, localLog, localCap, waitPer)
if err != nil {
lastErr = err
fmt.Fprintf(os.Stderr, "[!] capture wait failed: %v\n", err)
c.ForceStop(a.Package())
continue
}
capData = cap
licenseURL = first(capData.Get("license_url"), a.LicenseURL())
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
if needsKeys {
enrichWidevinePSSH(capData)
}
mpdURL = strings.TrimSpace(capData.Get("mpd"))
fmt.Println() fmt.Println()
fmt.Println("========== MPD ==========") fmt.Println("========== MPD ==========")
if mpdURL != "" { if mpdURL != "" {
@ -336,27 +358,52 @@ func Run(opt Options) (res Result, err error) {
fmt.Println(" ", label+":", trim(v, 120)) fmt.Println(" ", label+":", trim(v, 120))
} }
key := "" if !needsKeys {
if keyMode == "none" || keyMode == "clear" {
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)") fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
} else { lastErr = nil
var kerr error break
key, kerr = fetchKey(opt, root, capData, licenseURL) }
k, kerr := fetchKey(opt, root, capData, licenseURL)
if kerr != nil { if kerr != nil {
// Allow MPD-only sessions when no .wvd was passed (grab-all / first pass), lastErr = kerr
// unless the app requires keys (e.g. c4). // Missing --wvd on a manual grab-all can soft-save MPD-only; agents
// always pass WVD so this path is for interactive capture only.
softOK := strings.Contains(kerr.Error(), "requires --wvd") softOK := strings.Contains(kerr.Error(), "requires --wvd")
if softOK { if softOK {
if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() { if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
return res, kerr c.ForceStop(a.Package())
continue
} }
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr) fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
} else { key = ""
return res, kerr lastErr = nil
break
} }
} else { fmt.Fprintf(os.Stderr, "[!] key fetch failed (attempt %d/%d): %v\n", attempt, attempts, kerr)
c.ForceStop(a.Package())
continue
}
if strings.TrimSpace(k) == "" || !looksLikeKey(k) {
lastErr = fmt.Errorf("wvkey returned no usable KID:KEY")
fmt.Fprintf(os.Stderr, "[!] %v (attempt %d/%d)\n", lastErr, attempt, attempts)
c.ForceStop(a.Package())
continue
}
key = k
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | ")) fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
lastErr = nil
break
} }
if lastErr != nil {
if needsKeys {
return res, fmt.Errorf("widevine capture failed after %d attempt(s): %w", attempts, lastErr)
}
return res, lastErr
}
if needsKeys && (strings.TrimSpace(key) == "" || !looksLikeKey(key)) {
return res, fmt.Errorf("refusing to save capture without Widevine keys (mpd alone is not enough)")
} }
sess := session.Session{ sess := session.Session{
@ -384,6 +431,62 @@ func Run(opt Options) (res Result, err error) {
return res, nil return res, nil
} }
func enrichWidevinePSSH(capData capture.Data) {
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
curPSSH := strings.TrimSpace(capData.Get("pssh"))
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
if !needPSSH || mpdForPSSH == "" {
return
}
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
if curPSSH != "" && curPSSH != pssh {
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
}
capData["pssh"] = pssh
} else if err != nil && curPSSH == "" {
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
}
return
}
if curPSSH == "" {
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
capData["pssh"] = pssh
} else if err != nil {
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
}
}
}
func looksLikeKey(raw string) bool {
raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
for _, line := range strings.Split(raw, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
kid, k, ok := strings.Cut(line, ":")
if !ok {
continue
}
if len(hexDigits(kid)) == 32 && len(hexDigits(k)) == 32 {
return true
}
}
return false
}
func hexDigits(s string) string {
var b strings.Builder
for _, r := range s {
switch {
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
b.WriteRune(r)
}
}
return b.String()
}
// ClearProxyLater clears http_proxy (exported for agent defer helpers). // ClearProxyLater clears http_proxy (exported for agent defer helpers).
func ClearProxyLater(c *adb.Client) { func ClearProxyLater(c *adb.Client) {
proxy.ClearHTTPProxy(c) proxy.ClearHTTPProxy(c)
@ -414,16 +517,18 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
if strings.TrimSpace(opt.WVD) == "" { if strings.TrimSpace(opt.WVD) == "" {
return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)") return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)")
} }
py := opt.Python // Ensure apps/wvkey + .venv/pywidevine exist on Windows/Linux/macOS.
if py == "" { rt, err := wvkey.EnsureRuntime(root)
py = filepath.Join(root, ".venv", "Scripts", "python.exe") if err != nil {
if _, err := os.Stat(py); err != nil { return "", err
py = filepath.Join(root, ".venv", "bin", "python")
} }
py := rt.Python
if p := strings.TrimSpace(opt.Python); p != "" && fileExistsPath(p) {
py = p
} }
wopt := wvkey.Options{ wopt := wvkey.Options{
Python: py, Python: py,
Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"), Script: rt.Script,
WVD: opt.WVD, WVD: opt.WVD,
PSSH: cap.Get("pssh"), PSSH: cap.Get("pssh"),
Auth: cap.Get("auth"), Auth: cap.Get("auth"),
@ -465,6 +570,11 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
} }
} }
func fileExistsPath(path string) bool {
st, err := os.Stat(path)
return err == nil && !st.IsDir()
}
func first(vals ...string) string { func first(vals ...string) string {
for _, v := range vals { for _, v := range vals {
if strings.TrimSpace(v) != "" { if strings.TrimSpace(v) != "" {

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),
@ -481,10 +481,14 @@ const (
// mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent // mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent
// mode otherwise only MITMs open.live.bbc.co.uk. // mode otherwise only MITMs open.live.bbc.co.uk.
func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool, mitmHosts ...string) error { func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool, mitmHosts ...string) error {
pkg = strings.TrimSpace(pkg)
if pkg == "" {
return fmt.Errorf("transparent MITM requires Android package name (module.yaml package: is empty — re-pull/rebuild the module)")
}
if port == "" { if port == "" {
port = "8080" port = "8080"
} }
if remoteDir == "" { if remoteDir == "" || strings.HasSuffix(remoteDir, "/capture/") || strings.HasSuffix(remoteDir, `\capture\`) {
remoteDir = RemoteCaptureRoot + "/" + pkg remoteDir = RemoteCaptureRoot + "/" + pkg
} }
stopProxy(c) stopProxy(c)

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.

172
apps/pkg/wvkey/ensure.go Normal file
View file

@ -0,0 +1,172 @@
package wvkey
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
// Runtime is a resolved Python + wvkey.py pair ready for Fetch*.
type Runtime struct {
Python string
Script string
}
// ScriptPath returns <root>/apps/wvkey/wvkey.py.
func ScriptPath(root string) string {
return filepath.Join(root, "apps", "wvkey", "wvkey.py")
}
// VenvPython returns the platform venv interpreter under root, if present.
func VenvPython(root string) string {
candidates := []string{
filepath.Join(root, ".venv", "Scripts", "python.exe"),
filepath.Join(root, ".venv", "bin", "python"),
filepath.Join(root, ".venv", "bin", "python3"),
}
for _, c := range candidates {
if fileExists(c) {
return c
}
}
return ""
}
// EnsureRuntime makes sure wvkey.py exists and a usable Python with
// pywidevine is available under root (creating .venv when needed).
// Works on Windows, Linux, and macOS.
func EnsureRuntime(root string) (Runtime, error) {
var zero Runtime
if root == "" {
return zero, fmt.Errorf("wvkey: install root required")
}
script := ScriptPath(root)
if !fileExists(script) {
return zero, fmt.Errorf("wvkey script missing at %s — re-run streamd so bootstrap can materialise apps/wvkey/", script)
}
req := filepath.Join(root, "apps", "wvkey", "requirements.txt")
if py := VenvPython(root); py != "" {
if hasPywidevine(py) {
return Runtime{Python: py, Script: script}, nil
}
if err := pipInstall(py, req); err != nil {
return zero, err
}
if !hasPywidevine(py) {
return zero, fmt.Errorf("wvkey: installed requirements but pywidevine still missing in %s", py)
}
return Runtime{Python: py, Script: script}, nil
}
base, err := findSystemPython()
if err != nil {
return zero, err
}
venvDir := filepath.Join(root, ".venv")
fmt.Fprintf(os.Stderr, "agent: creating Widevine venv at %s …\n", venvDir)
if err := createVenv(base, venvDir); err != nil {
return zero, err
}
py := VenvPython(root)
if py == "" {
return zero, fmt.Errorf("wvkey: venv created at %s but no python binary found", venvDir)
}
if err := pipInstall(py, req); err != nil {
return zero, err
}
if !hasPywidevine(py) {
return zero, fmt.Errorf("wvkey: pywidevine missing after pip install (%s)", py)
}
fmt.Fprintf(os.Stderr, "agent: Widevine helper ready (%s)\n", py)
return Runtime{Python: py, Script: script}, nil
}
// FindPython prefers an existing install-root venv, then PATH helpers.
func FindPython(root string) string {
if root != "" {
if py := VenvPython(root); py != "" {
return py
}
}
return findPython()
}
func fileExists(path string) bool {
st, err := os.Stat(path)
return err == nil && !st.IsDir()
}
func hasPywidevine(py string) bool {
cmd := exec.Command(py, "-c", "import pywidevine")
return cmd.Run() == nil
}
func pipInstall(py, requirements string) error {
if !fileExists(requirements) {
return fmt.Errorf("wvkey: requirements missing at %s", requirements)
}
fmt.Fprintf(os.Stderr, "agent: pip install -r %s …\n", requirements)
cmd := exec.Command(py, "-m", "pip", "install", "-r", requirements)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("wvkey: pip install failed: %w\n%s", err, strings.TrimSpace(string(out)))
}
return nil
}
func createVenv(basePython, venvDir string) error {
cmd := exec.Command(basePython, "-m", "venv", venvDir)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("wvkey: python -m venv %s failed: %w\n%s", venvDir, err, strings.TrimSpace(string(out)))
}
return nil
}
func findSystemPython() (string, error) {
var names []string
switch runtime.GOOS {
case "windows":
// Prefer the py launcher (real install) over the Store stub named "python".
names = []string{"py", "python3", "python"}
default:
names = []string{"python3", "python"}
}
for _, name := range names {
if name == "py" {
// `py -3` on Windows
if p, err := exec.LookPath("py"); err == nil {
cmd := exec.Command(p, "-3", "-c", "import sys; print(sys.executable)")
out, err := cmd.Output()
if err == nil {
exe := strings.TrimSpace(string(out))
if fileExists(exe) {
return exe, nil
}
}
}
continue
}
if p, err := exec.LookPath(name); err == nil {
// Skip the WindowsApps Store alias stub when it cannot run -m venv.
if runtime.GOOS == "windows" && strings.Contains(strings.ToLower(p), `windowsapps`) {
cmd := exec.Command(p, "-c", "import sys; print(sys.executable)")
out, err := cmd.Output()
if err != nil {
continue
}
exe := strings.TrimSpace(string(out))
if !fileExists(exe) || strings.Contains(strings.ToLower(exe), `windowsapps`) {
continue
}
return exe, nil
}
return p, nil
}
}
return "", fmt.Errorf("wvkey: no system Python found — install Python 3.10+ (Windows/macOS/Linux) so the agent can create .venv for Widevine keys")
}

View file

@ -58,14 +58,21 @@ func FetchWrapAll(opt Options) ([]string, error) {
} }
func run(opt Options, mode string, all bool) ([]string, error) { func run(opt Options, mode string, all bool) ([]string, error) {
py := opt.Python py := resolvePython(opt.Python)
if py == "" {
py = findPython()
}
script := opt.Script script := opt.Script
if script == "" { if script == "" {
return nil, fmt.Errorf("wvkey script path required") return nil, fmt.Errorf("wvkey script path required")
} }
if !fileExists(script) {
return nil, fmt.Errorf("wvkey script not found: %s", script)
}
if !fileExists(py) {
// Bare names like "python3" are OK via LookPath inside resolvePython;
// absolute/relative paths must exist.
if filepath.IsAbs(py) || strings.Contains(py, string(os.PathSeparator)) || strings.Contains(py, "/") {
return nil, fmt.Errorf("wvkey python not found: %s (run agent once to auto-create .venv, or set python: in agent.yaml)", py)
}
}
if strings.TrimSpace(opt.WVD) == "" { if strings.TrimSpace(opt.WVD) == "" {
return nil, fmt.Errorf("wvkey --wvd path required") return nil, fmt.Errorf("wvkey --wvd path required")
} }
@ -120,12 +127,30 @@ func run(opt Options, mode string, all bool) ([]string, error) {
return out, nil return out, nil
} }
// resolvePython uses an explicit path only when the file exists; otherwise
// discovers a usable interpreter. Passing a missing absolute path used to make
// exec fail with a confusing "not found in %PATH%" on Windows.
func resolvePython(explicit string) string {
if strings.TrimSpace(explicit) != "" {
if st, err := os.Stat(explicit); err == nil && !st.IsDir() {
return explicit
}
if !strings.Contains(explicit, string(os.PathSeparator)) && !strings.Contains(explicit, "/") {
if p, err := exec.LookPath(explicit); err == nil {
return p
}
}
}
return findPython()
}
func findPython() string { func findPython() string {
candidates := []string{ candidates := []string{
filepath.Join(".venv", "Scripts", "python.exe"), filepath.Join(".venv", "Scripts", "python.exe"),
filepath.Join(".venv", "bin", "python"), filepath.Join(".venv", "bin", "python"),
"python3", "python3",
"python", "python",
"py",
} }
for _, c := range candidates { for _, c := range candidates {
if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) { if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) {

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,9 @@ 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 is optional: reuses existing .cache/streamd (cwd or next to the binary)
# or set STREAMD_DATA / pass --data explicitly
``` ```
`--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any `--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any

View file

@ -1,14 +1,15 @@
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
gopkg.in/yaml.v3 v3.0.1
) )
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
@ -17,6 +18,7 @@ require (
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
golang.org/x/sys v0.42.0 // indirect golang.org/x/sys v0.42.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.55.3 // indirect modernc.org/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

View file

@ -19,6 +19,9 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/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=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=

View file

@ -10,10 +10,12 @@ 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/egress"
"streamd/apps/streamd/internal/httpx"
"streamd/apps/streamd/internal/modstore"
) )
type Supervisor interface { type Supervisor interface {
@ -56,6 +58,11 @@ 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
Egress *egress.Manager
Log *slog.Logger Log *slog.Logger
} }
@ -65,6 +72,7 @@ func (h *Handler) Mount(mux *http.ServeMux) {
mux.HandleFunc("/api/streams/", h.streamAction) mux.HandleFunc("/api/streams/", h.streamAction)
mux.HandleFunc("/api/overview", h.overview) mux.HandleFunc("/api/overview", h.overview)
h.MountControl(mux) h.MountControl(mux)
h.MountEgress(mux)
mux.HandleFunc("/api/apps", h.apps) mux.HandleFunc("/api/apps", h.apps)
mux.HandleFunc("/api/modules", h.modules) mux.HandleFunc("/api/modules", h.modules)
mux.HandleFunc("/api/modules/", h.modules) mux.HandleFunc("/api/modules/", h.modules)
@ -534,6 +542,7 @@ func changeNote(before, after db.Stream, in db.PatchStream) string {
add("key", in.Key != nil && before.Key != after.Key) add("key", in.Key != nil && before.Key != after.Key)
add("headers", in.HeadersJSON != nil && before.HeadersJSON != after.HeadersJSON) add("headers", in.HeadersJSON != nil && before.HeadersJSON != after.HeadersJSON)
add("proxy", in.Proxy != nil && before.Proxy != after.Proxy) add("proxy", in.Proxy != nil && before.Proxy != after.Proxy)
add("egress", in.Egress != nil && before.Egress != after.Egress)
add("variants", before.VariantsJSON != after.VariantsJSON) add("variants", before.VariantsJSON != after.VariantsJSON)
add("outputs", before.OutputsJSON != after.OutputsJSON) add("outputs", before.OutputsJSON != after.OutputsJSON)
add("settings", before.SettingsJSON != after.SettingsJSON) add("settings", before.SettingsJSON != after.SettingsJSON)
@ -565,6 +574,9 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) { if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) {
return true return true
} }
if in.Egress != nil && strings.TrimSpace(before.Egress) != strings.TrimSpace(after.Egress) {
return true
}
if in.VariantsJSON != nil || len(in.Variants) > 0 { if in.VariantsJSON != nil || len(in.Variants) > 0 {
if strings.TrimSpace(before.VariantsJSON) != strings.TrimSpace(after.VariantsJSON) { if strings.TrimSpace(before.VariantsJSON) != strings.TrimSpace(after.VariantsJSON) {
return true return true

View file

@ -2,11 +2,15 @@ package api
import ( import (
"net/http" "net/http"
"sort"
"drmdecryption/apps/streamd/internal/auth" "gopkg.in/yaml.v3"
"drmdecryption/modhost"
"drmdecryption/mpd" "streamd/apps/streamd/internal/auth"
"drmdecryption/repo" "streamd/apps/streamd/internal/modstore"
"streamd/modhost"
"streamd/mpd"
"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 +20,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 +28,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,21 +40,43 @@ 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 {
info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}
h.fillChannelsFromStore(&info, m.Name)
out = append(out, info)
h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
continue
}
d, err := modhost.RunDescribe(bin)
if err != nil {
info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}
h.fillChannelsFromStore(&info, m.Name)
out = append(out, info)
h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
continue
}
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})
} }
info.HasConfig = len(info.Channels) > 0
if d.Rewriter != "" { if d.Rewriter != "" {
info.Rewriter = d.Rewriter info.Rewriter = d.Rewriter
} }
// Older module binaries may not see the panel store; fill from module.yaml.
if len(info.Channels) == 0 {
h.fillChannelsFromStore(&info, m.Name)
}
info.HasConfig = len(info.Channels) > 0
out = append(out, info) out = append(out, info)
} }
writeJSON(w, http.StatusOK, map[string]any{ writeJSON(w, http.StatusOK, map[string]any{
@ -55,3 +84,53 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
"rewriters": mpd.Names(), "rewriters": mpd.Names(),
}) })
} }
func (h *Handler) fillChannelsFromStore(info *appInfo, name string) {
if h == nil || h.Modules == nil || info == nil {
return
}
chans := channelsFromStoreYAML(h.Modules, name)
if len(chans) == 0 {
return
}
info.Channels = chans
info.HasConfig = true
if info.Error != "" {
// Soft: yaml channels recovered even though describe failed.
info.Error = ""
}
}
// channelsFromStoreYAML reads channels from the panel module.yaml when describe
// returns none (common with uploaded binaries that resolve values via cwd).
func channelsFromStoreYAML(store *modstore.Store, name string) []channelInfo {
if store == nil {
return nil
}
raw, err := store.ReadYAML(name)
if err != nil || len(raw) == 0 {
return nil
}
var doc struct {
Channels map[string]struct {
Label string `yaml:"label"`
} `yaml:"channels"`
}
if err := yaml.Unmarshal(raw, &doc); err != nil || len(doc.Channels) == 0 {
return nil
}
ids := make([]string, 0, len(doc.Channels))
for id := range doc.Channels {
ids = append(ids, id)
}
sort.Strings(ids)
out := make([]channelInfo, 0, len(ids))
for _, id := range ids {
label := doc.Channels[id].Label
if label == "" {
label = id
}
out = append(out, channelInfo{ID: id, Label: label})
}
return out
}

View file

@ -0,0 +1,45 @@
package api
import (
"os"
"path/filepath"
"testing"
"streamd/apps/streamd/internal/modstore"
)
func TestChannelsFromStoreYAML(t *testing.T) {
root := t.TempDir()
store := modstore.New(root)
modDir := filepath.Join(root, "rte")
if err := os.MkdirAll(modDir, 0o755); err != nil {
t.Fatal(err)
}
yaml := []byte(`package: air.RTE
channels:
rteone:
label: RTE One
rtetwo:
label: RTE 2
`)
if err := os.WriteFile(filepath.Join(modDir, "module.yaml"), yaml, 0o644); err != nil {
t.Fatal(err)
}
chans := channelsFromStoreYAML(store, "rte")
if len(chans) != 2 {
t.Fatalf("got %d channels: %+v", len(chans), chans)
}
if chans[0].ID != "rteone" || chans[0].Label != "RTE One" {
t.Fatalf("first channel: %+v", chans[0])
}
if chans[1].ID != "rtetwo" {
t.Fatalf("second channel: %+v", chans[1])
}
}
func TestChannelsFromStoreYAMLMissing(t *testing.T) {
store := modstore.New(t.TempDir())
if chans := channelsFromStoreYAML(store, "nope"); chans != nil {
t.Fatalf("expected nil, got %+v", chans)
}
}

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.
@ -162,6 +162,7 @@ func (h *Handler) duplicate(w http.ResponseWriter, r *http.Request, id int64) {
Key: src.Key, Key: src.Key,
HeadersJSON: src.HeadersJSON, HeadersJSON: src.HeadersJSON,
Proxy: src.Proxy, Proxy: src.Proxy,
Egress: src.Egress,
VideoSelect: src.VideoSelect, VideoSelect: src.VideoSelect,
AudioSelect: src.AudioSelect, AudioSelect: src.AudioSelect,
Rewriter: src.Rewriter, Rewriter: src.Rewriter,
@ -271,9 +272,19 @@ func (h *Handler) doProbe(ctx context.Context, st db.Stream, target string) prob
start := time.Now() start := time.Now()
client := &http.Client{Timeout: 20 * time.Second} client := &http.Client{Timeout: 20 * time.Second}
// Fetch through the stream's own proxy, so a geo-restricted origin is // Fetch through the stream's effective proxy (explicit or named egress),
// probed the same way the downloader would reach it. // so a geo-restricted origin is probed the same way the downloader would.
if proxy := strings.TrimSpace(st.Proxy); proxy != "" { proxy := strings.TrimSpace(st.Proxy)
if h.Egress != nil {
if p, err := h.Egress.ResolveProxy(st); err == nil {
proxy = p
} else if strings.TrimSpace(st.Egress) != "" && proxy == "" {
res.Error = "egress: " + err.Error()
res.Summary = "egress profile could not be brought up"
return res
}
}
if proxy != "" {
if c, err := httpClientWithProxy(proxy); err == nil { if c, err := httpClientWithProxy(proxy); err == nil {
client = c client = c
} else { } else {

View file

@ -0,0 +1,254 @@
package api
import (
"database/sql"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"streamd/apps/streamd/internal/auth"
"streamd/apps/streamd/internal/db"
)
// MountEgress registers /api/egress routes.
func (h *Handler) MountEgress(mux *http.ServeMux) {
mux.HandleFunc("/api/egress", h.egressRoot)
mux.HandleFunc("/api/egress/", h.egressAction)
}
func (h *Handler) egressRoot(w http.ResponseWriter, r *http.Request) {
if h.Egress == nil {
writeErr(w, http.StatusServiceUnavailable, "egress manager not configured")
return
}
switch r.Method {
case http.MethodGet:
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
return
}
list, err := h.Store.ListEgressProfiles()
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
for i := range list {
h.Egress.Enrich(&list[i])
}
writeJSON(w, http.StatusOK, map[string]any{"profiles": list})
case http.MethodPost:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
var in db.CreateEgressProfile
if err := readJSON(r, &in); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
prof, err := h.Store.CreateEgressProfile(in)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.Egress.Enrich(&prof)
h.audit(r, p, http.StatusOK, "create egress "+prof.Name)
writeJSON(w, http.StatusOK, prof)
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
func (h *Handler) egressAction(w http.ResponseWriter, r *http.Request) {
if h.Egress == nil {
writeErr(w, http.StatusServiceUnavailable, "egress manager not configured")
return
}
path := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/egress/"), "/")
if path == "" {
h.egressRoot(w, r)
return
}
parts := strings.Split(path, "/")
name := db.Slug(parts[0])
if name == "" {
writeErr(w, http.StatusBadRequest, "invalid name")
return
}
action := ""
if len(parts) > 1 {
action = strings.ToLower(parts[1])
}
switch {
case action == "" && r.Method == http.MethodGet:
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
return
}
prof, err := h.Egress.Status(name)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
writeErr(w, http.StatusNotFound, "not found")
return
}
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, prof)
case action == "" && r.Method == http.MethodPut:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
h.putEgress(w, r, p, name)
case action == "" && r.Method == http.MethodDelete:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
prof, err := h.Store.GetEgressProfileByName(name)
if err != nil {
writeErr(w, http.StatusNotFound, "not found")
return
}
_ = h.Egress.Down(name)
if err := h.Store.DeleteEgressProfile(prof.ID); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
_ = h.Egress.RemoveFiles(name)
h.audit(r, p, http.StatusOK, "delete egress "+name)
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
case action == "up" && r.Method == http.MethodPost:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
if err := h.Egress.EnsureUp(name); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
prof, _ := h.Egress.Status(name)
h.audit(r, p, http.StatusOK, "egress up "+name)
writeJSON(w, http.StatusOK, prof)
case action == "down" && r.Method == http.MethodPost:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
if err := h.Egress.Down(name); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
prof, _ := h.Egress.Status(name)
h.audit(r, p, http.StatusOK, "egress down "+name)
writeJSON(w, http.StatusOK, prof)
case action == "test" && r.Method == http.MethodPost:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
out, err := h.Egress.TestDial(name)
if err != nil {
if out == nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.audit(r, p, http.StatusOK, "egress test "+name+" fail")
writeJSON(w, http.StatusOK, out)
return
}
h.audit(r, p, http.StatusOK, "egress test "+name)
writeJSON(w, http.StatusOK, out)
case action == "conf" && r.Method == http.MethodPut:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
_ = r.Body.Close()
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
contents := string(body)
ct := r.Header.Get("Content-Type")
if strings.Contains(ct, "json") || strings.HasPrefix(strings.TrimSpace(contents), "{") {
var in struct {
Conf string `json:"conf"`
}
if err := json.Unmarshal(body, &in); err != nil || strings.TrimSpace(in.Conf) == "" {
writeErr(w, http.StatusBadRequest, "conf required")
return
}
contents = in.Conf
}
if strings.TrimSpace(contents) == "" {
writeErr(w, http.StatusBadRequest, "empty conf")
return
}
if _, err := h.Store.GetEgressProfileByName(name); err != nil {
writeErr(w, http.StatusNotFound, "not found")
return
}
if err := h.Egress.WriteConf(name, contents); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
prof, _ := h.Egress.Status(name)
h.audit(r, p, http.StatusOK, "egress conf "+name)
writeJSON(w, http.StatusOK, prof)
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
func (h *Handler) putEgress(w http.ResponseWriter, r *http.Request, p *auth.Principal, name string) {
prof, err := h.Store.GetEgressProfileByName(name)
if err != nil {
writeErr(w, http.StatusNotFound, "not found")
return
}
var in struct {
Enabled *bool `json:"enabled"`
SocksURL *string `json:"socks_url"`
Kind *string `json:"kind"`
Conf *string `json:"conf"`
}
if err := readJSON(r, &in); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
upd, err := h.Store.UpdateEgressProfile(prof.ID, db.UpdateEgressProfile{
Enabled: in.Enabled, SocksURL: in.SocksURL, Kind: in.Kind,
})
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if in.Conf != nil && strings.TrimSpace(*in.Conf) != "" {
if err := h.Egress.WriteConf(name, *in.Conf); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
}
h.Egress.Enrich(&upd)
if in.Enabled != nil && *in.Enabled {
_ = h.Egress.EnsureUp(name)
upd, _ = h.Egress.Status(name)
}
if in.Enabled != nil && !*in.Enabled {
_ = h.Egress.Down(name)
upd, _ = h.Egress.Status(name)
}
h.audit(r, p, http.StatusOK, "update egress "+name)
writeJSON(w, http.StatusOK, upd)
}

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