Compare commits

..

9 commits

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
404errordeveloper
066e018749 streamd: preview quality picker, dashboard polish, C4 wrap keys
All checks were successful
release / build-and-upload (push) Successful in 6m18s
modules-release / build-and-upload (push) Successful in 5m18s
- Preview player can select FHD/HD/SD (or ABR master) from publish links
- Embed dashboard screenshots in README; Linux streamd+agent setup guide
- C4 Widevine wrap license mode + require --wvd; prefer Widevine PSSH
- Channel 4 and My5 modules; streamd auth, variants, schedules, HLS gate
2026-10-09 20:57:43 +02:00
404errordeveloper
b3955bd81e Route Telegram release announces to the group Releases topic.
Send host/modules release messages to chat -1003721978702 topic 16
instead of the maintainer DM.
2026-10-09 17:45:45 +02:00
404errordeveloper
2e43e6c3fa Add ITVX module, transparent mitm_hosts, and DM Telegram announces.
All checks were successful
release / build-and-upload (push) Successful in 6m21s
Wire module mitm_hosts into StartTransparent for ITVX capture, ship the
itv provider stub with Live-list autoplay, refresh the README, and send
Forgejo release announces to private chat 7314901602.
2026-10-09 17:35:53 +02:00
404errordeveloper
3cb259c9b6 streamd: copyable m3u8 links + FHD/HD/SD output variants
Some checks failed
release / build-and-upload (push) Failing after 3m33s
- WebUI Copy button for absolute m3u8 URLs (no player)
- Per-stream variants ladder; HD/SD live-transcoded as sibling HLS
- variants_json in DB/API; supervisor spawns scaled ffmpeg packagers
2026-10-09 01:12:32 +02:00
236 changed files with 29569 additions and 1990 deletions

View file

@ -54,6 +54,9 @@ jobs:
| `bbc.zip` | BBC iPlayer CLI + `module.yaml` (universal) | | `bbc.zip` | BBC iPlayer CLI + `module.yaml` (universal) |
| `rte.zip` | RTÉ Player CLI + `module.yaml` template | | `rte.zip` | RTÉ Player CLI + `module.yaml` template |
| `tg4.zip` | TG4 CLI + `module.yaml` template | | `tg4.zip` | TG4 CLI + `module.yaml` template |
| `itv.zip` | ITVX CLI stub + `module.yaml` template |
| `c4.zip` | Channel 4 CLI + `module.yaml` template |
| `my5.zip` | Channel 5 (My5) CLI + `module.yaml` template |
| `SHA256SUMS-modules.txt` | Checksums | | `SHA256SUMS-modules.txt` | Checksums |
Unpack each zip into `modules/<name>/` (e.g. `bbc.zip` → `modules/bbc/`). Unpack each zip into `modules/<name>/` (e.g. `bbc.zip` → `modules/bbc/`).
@ -65,14 +68,18 @@ jobs:
- 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: modules RELEASE_KIND: modules
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" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
echo "[!] TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID secrets missing — skip announce" echo "[!] TELEGRAM_BOT_TOKEN secret missing — skip announce"
exit 0 exit 0
fi fi
# Null DRM Telegram group → Releases topic (t.me/c/3721978702/16).
export TELEGRAM_CHAT_ID="-1003721978702"
export TELEGRAM_MESSAGE_THREAD_ID="16"
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 }}"

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,36 +75,83 @@ 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:
@ -74,11 +159,20 @@ jobs:
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" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
echo "[!] TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID secrets missing — skip announce" echo "[!] TELEGRAM_BOT_TOKEN secret missing — skip announce"
exit 0 exit 0
fi fi
# Null DRM Telegram group → Releases topic (t.me/c/3721978702/16).
export TELEGRAM_CHAT_ID="-1003721978702"
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/**

234
README.md
View file

@ -1,136 +1,254 @@
# Null DRM # 📺 Streamd
Capture live sessions from Android streaming apps (BBC iPlayer, RTÉ, TG4, …) and **Next-generation open-source DRM decryption for Android streaming apps.**
restream them. The host is a single binary — **`drm`** — plus drop-in providers
under **`modules/`**.
Releases: [git.nulldrm.com](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases) Capture live sessions from phones (BBC iPlayer, RTÉ, TG4, ITVX, Channel 4, …), pull manifests
Docs: [docs/](docs/) and licenses through a transparent MITM, and restream. One host binary — **`streamd`** —
plus drop-in providers under **`modules/`**.
📦 Releases: [git.nulldrm.com](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases)
📚 Docs: [docs/](docs/)
--- ---
## Quick start (binaries) ## ✨ What it does
### 1. Download Each provider is a **module** that can launch the app, auto-play a channel like a
user would, and capture the stream metadata over HTTPS MITM. When a module does
not exist yet, you can still run discover / transparent capture and inspect raw
traffic.
From the latest **`v*`** release, grab your host binary (e.g. `drm-windows-amd64.exe`) | Module | App | Notes |
and `proxy-android-arm64`. From a **`modules-v*`** release, grab the module zips you need |--------|-----|--------|
(`bbc.zip`, `rte.zip`, `tg4.zip`). | 📺 `bbc` | BBC iPlayer | Transparent MITM; UK VPN on phone |
| 🇮🇪 `rte` | RTÉ Player | Irish egress; ModularDRM keys |
| 🟢 `tg4` | TG4 | Catalog + phone capture |
| 🟣 `itv` | ITVX | Transparent MITM; UK VPN; Live list autoplay |
| 🟧 `c4` | Channel 4 | Transparent MITM; UK VPN; Live TV grab-all |
---
## 🖥️ streamd dashboard
Run `streamd serve`, open the panel in a browser, manage streams and API keys:
<p align="center">
<img src="docs/images/streamd/dashboard.jpg" alt="streamd Dashboard — overview, live Channel 4, HLS link" width="720" />
</p>
<p align="center"><em>Dashboard — health, live streams, and play links</em></p>
<p align="center">
<img src="docs/images/streamd/streams.jpg" alt="streamd Streams list" width="720" />
</p>
<p align="center"><em>Streams — list, filters, start / stop / restart</em></p>
<p align="center">
<img src="docs/images/streamd/stream-detail.jpg" alt="streamd stream detail with in-browser player" width="720" />
</p>
<p align="center"><em>Stream detail — credentials, variants, and preview player</em></p>
<p align="center">
<img src="docs/images/streamd/people-keys.jpg" alt="streamd People and API keys" width="720" />
</p>
<p align="center"><em>People &amp; keys — accounts and agent API keys</em></p>
Server setup guide: [docs/streamd-server-setup.md](docs/streamd-server-setup.md) · full reference: [docs/streamd.md](docs/streamd.md)
---
## 🚀 Quick start
### 1️⃣ Download
Host binaries ship on two rolling channels (always the newest build — no version pin):
| Channel | Tag | When to use |
|---------|-----|-------------|
| **Stable** | [`stable`](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/tag/stable) | Everyday installs |
| **Beta** | [`beta`](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/tag/beta) | Try pre-releases (`vX.Y.Z-beta.N`) |
Provider zips still come from **`modules-v*`** releases (`bbc.zip`, `rte.zip`, …).
Pick **one** host binary block for your machine, then run `chmod +x streamd` on Linux/macOS.
**Linux Intel / AMD 64-bit (stable)**
```bash
curl -fL -o streamd \
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-amd64"
chmod +x streamd
```
**Linux ARM 64-bit (stable)** — Raspberry Pi 4+, many cloud ARM VMs
```bash
curl -fL -o streamd \
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-arm64"
chmod +x streamd
```
**Beta channel (Linux Intel / AMD 64-bit pre-release)**
```bash
curl -fL -o streamd \
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/beta/streamd-linux-amd64"
chmod +x streamd
```
**Windows Intel / AMD 64-bit (stable, PowerShell)**
```powershell
Invoke-WebRequest -Uri "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-windows-amd64.exe" -OutFile streamd.exe
```
Other stable assets: `streamd-windows-arm64.exe`, `streamd-darwin-amd64`, `streamd-darwin-arm64`,
`proxy-android-arm64`. For beta, swap `/download/stable/` → `/download/beta/` in any URL.
Pinned install: swap `stable` / `beta` for a concrete tag such as `v0.1.5` or `v0.2.0-beta.1`.
```text ```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/
itv/
data/ # your .wvd, optional data/ # your .wvd, optional
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
| Need | Why | | Need | Why |
|---|---| |------|-----|
| **adb** on `PATH` | phone capture | | 📱 **adb** on `PATH` | phone capture |
| Rooted Android (Magisk) | system CA for HTTPS MITM | | 🔐 Rooted Android (Magisk) | system CA for HTTPS MITM |
| **`.wvd`** in `data/` | Widevine keys (RTE/TG4; BBC mobile streams are clear) | | 🔑 **`.wvd`** in `data/` | Widevine keys (RTE/TG4/ITV; BBC mobile is often clear) |
| Python 3.10+ + `.venv` | only if you fetch keys with `wvkey.py` | | 🐍 Python 3.10+ + `.venv` | only if you fetch keys with `wvkey.py` |
### 3. Install a provider ### 3️⃣ Install a provider
Unzip into `modules/<name>/`. Edit **`module.yaml`** — fill sensitive fields only Unzip into `modules/<name>/`. Edit **`module.yaml`** — fill sensitive fields only
(RTE license URL / KIDs; TG4 account + policy key + video ids). BBC needs almost (RTE license URL / KIDs; TG4 account + policy key + video ids). BBC / ITVX need
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
``` ```
### 5. Capture ### 5️⃣ 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)
streamd capture --app itv --channel itv1 --wait 90
# Channel 4 — one channel, or every Live channel
streamd capture --app c4 --channel channel4 --wait 90
streamd capture --app c4 --all --wait 90
# Grab every channel for any module
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: `outputs/<app>/<stamp>/` (and `latest/`). 📁 Results land in `outputs/<app>/<stamp>/` (and `latest/`).
### 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.
--- ---
## 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 | start | stop | push | discover | pull | transparent --package PKG [--mitm-host HOST]
drm serve [--bind …] [--data …] [--token …] | start | stop | push | discover | pull
drm agent run|status|devices|enqueue|cancel [--config …] streamd serve [--bind …] [--data …] [--token …]
streamd agent run|status|devices|enqueue|cancel [--config …]
``` ```
Global: `--modules-dir DIR` or `$DRM_MODULES_DIR` (default: `./modules`). 🌍 Global: `--modules-dir DIR` or `$STREAMD_MODULES_DIR` (default: `./modules`).
`--channel` implies interactive auto-play (Explore → channel → Watch live for BBC). 🎯 `--channel` implies interactive auto-play (provider-specific Live UI flow).
--- ---
## Config: publish vs local ## ⚙️ Config: publish vs local
| File | In git / zips? | Purpose | | File | In git / zips? | Purpose |
|---|---|---| |------|----------------|---------|
| `module-publish.yaml` | git only | Universal package, channels, UI | | `module-publish.yaml` | git only | Universal package, channels, UI |
| `module.yaml` | zips yes / git no | Secrets + overlays; release zips ship publish renamed | | `module.yaml` | zips yes / git no | Secrets + overlays; release zips ship publish renamed |
Release module assets are `bbc.zip` / `rte.zip` / `tg4.zip` with `module.yaml` only Release module assets are `bbc.zip` / `rte.zip` / `tg4.zip` / `itv.zip` / `c4.zip` / `my5.zip`
(no `module-publish.yaml` inside the zip). with `module.yaml` only (no `module-publish.yaml` inside the zip).
--- ---
## Building from source (optional) ## 🛠️ Building from source *(optional)*
```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
``` ```
More detail: [docs/quickstart.md](docs/quickstart.md), [docs/architecture.md](docs/architecture.md), More detail: [docs/quickstart.md](docs/quickstart.md) · [docs/architecture.md](docs/architecture.md) · [docs/providers/bbc.md](docs/providers/bbc.md)
[docs/providers/bbc.md](docs/providers/bbc.md).
## Scope ---
## 💚 Support the project
If Streamd saves you time, donations keep development going:
| Coin | Address |
|------|---------|
| ⟠ **ETH** | `0xa6314ce4deaa8329abba301802e3f511b3fa80a6` |
| Ł **LTC** | `ltc1qpm26uccjgn4gx5pqxwzvs89mdp9hcshx9xj5a6` |
| ₿ **BTC** | `bc1qzr70ur76jhm5gjsuqelzqaskumpkhkk2ewjgha` |
Thank you 🙏
---
## ⚖️ Scope
Only for services you are authorised to access, with content you have the right Only for services you are authorised to access, with content you have the right
to decrypt. to decrypt.

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,38 +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 --token SECRET ./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
# terminal 2 — agent # terminal 2 — agent in the background (Linux / macOS / Windows)
export STREAMD_TOKEN=SECRET export STREAMD_API_KEY=ndk_…
./bin/drm agent run --config apps/agent/agent.yaml ./bin/streamd agent start --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 compiled into the binary, so there is no `modules_dir` to set. The With `sync_modules: true` (default in the sample config), the agent **pulls**
agent drives whichever module a 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`, `token` (or `STREAMD_TOKEN`), `poll_interval_sec`, `agent.yaml` — `streamd_url`, **`api_key`** (preferred) or `token` (alias), or
`workers`, `max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
device), `wvd`, `user_agent`, `agent_id`, `data_dir`. `max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device),
`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`.
`wvd` must be set or key fetches fail. Create the key in the streamd dashboard (role **operator**). The legacy shared
`--token` / `STREAMD_TOKEN` still works but is meant for migration only.
`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

@ -1,8 +1,11 @@
# Always-on credentials agent (apps/agent → bin/agent.exe) # Always-on credentials agent (apps/agent → bin/agent.exe)
# Default path: apps/agent/agent.yaml # Default path: apps/agent/agent.yaml
streamd_url: http://185.18.221.132:8083 streamd_url: http://localhost:8083
# Must match streamd --token / STREAMD_TOKEN (mutating API: claim, credentials, modules). # Paste an operator API key from streamd → People & keys → New API key.
token: "SECRET" # The dashboard shows the secret once — copy it into api_key (not the name).
# api_key: "<paste-secret-here>"
# token: is a legacy alias for the same field (or set STREAMD_API_KEY / STREAMD_TOKEN).
token: "REPLACE_WITH_API_KEY_SECRET"
# Stable id across restarts (default = hostname). Required for reclaim after crash. # Stable id across restarts (default = hostname). Required for reclaim after crash.
# agent_id: my-agent # agent_id: my-agent
poll_interval_sec: 30 poll_interval_sec: 30
@ -11,10 +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
# wvd: data/device.wvd # path to .wvd (required for key fetch) # modules_prune: false # delete local modules absent from the panel
# Exponential retry delays (1m, 2m, 4m…). Default false — lone agents retry ASAP.
# 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.
`) `)
} }
@ -82,6 +102,14 @@ func loadCfg(sub string, args []string) (config.Config, *flag.FlagSet) {
return cfg, fs return cfg, fs
} }
// newAPI builds the streamd client with this agent's identity attached, so
// audit rows in streamd name the agent and not just its API key.
func newAPI(cfg config.Config) *client.Client {
c := client.New(cfg.StreamdURL, cfg.Token)
c.AgentID = cfg.AgentID
return c
}
func openQueue(cfg config.Config) *queue.Store { func openQueue(cfg config.Config) *queue.Store {
q, err := queue.Open(cfg.DataDir) q, err := queue.Open(cfg.DataDir)
if err != nil { if err != nil {
@ -92,10 +120,34 @@ func openQueue(cfg config.Config) *queue.Store {
func runCmd(sub string, args []string) { func runCmd(sub string, args []string) {
cfg, _ := loadCfg(sub, args) cfg, _ := loadCfg(sub, args)
api := client.New(cfg.StreamdURL, cfg.Token) api := newAPI(cfg)
if err := api.Health(); err != nil { if err := api.Health(); err != nil {
log.Fatalf("streamd unreachable at %s: %v", cfg.StreamdURL, err) log.Fatalf("streamd unreachable at %s: %v", cfg.StreamdURL, err)
} }
// Health says the server is up; /api/me says our credential actually
// works. Without this a missing or revoked key failed silently on every
// poll instead of once, loudly, at startup.
me, err := api.Me()
if err != nil {
log.Fatalf("streamd rejected this agent at %s: %v", cfg.StreamdURL, err)
}
if me.Role != "operator" && me.Role != "admin" {
log.Fatalf("this agent's credential has role %q, but capturing needs at least `operator` — "+
"create an operator API key in the streamd dashboard", 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()
@ -104,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{})
@ -117,18 +179,60 @@ 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())
// streamd pushes a capture request when a viewer wakes an on-demand
// stream or a scheduled event is about to start. Reacting here is what
// makes those responsive instead of up to one poll interval late.
ws.OnCapture = func(streamID int64, name, app, channel, reason string) {
if cfg.PushedCapturesArePriority() {
p.EnqueueNow(streamID, name, app, channel, reason)
return
}
if j, added, err := q.EnqueueIfIdle(streamID, name, app, channel, reason, cfg.MaxAttempts); err != nil {
log.Printf("pushed capture for %s failed: %v", name, err)
} else if added {
log.Printf("enqueued job=%d stream=%s reason=%s (pushed by streamd)", j.ID, name, reason)
}
}
// A stream was edited: re-poll now rather than waiting out the interval.
ws.OnStreamChanged = func(name, reason string) {
go func() {
if err := p.Once(); err != nil {
log.Printf("re-poll after change to %s: %v", name, err)
}
}()
}
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++ {
@ -142,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)
@ -162,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)
@ -211,7 +317,7 @@ func enqueueCmd(args []string) {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
api := client.New(cfg.StreamdURL, cfg.Token) api := newAPI(cfg)
streams, err := api.ListStreams() streams, err := api.ListStreams()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)

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

@ -3,42 +3,93 @@ package client
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"os"
"strings" "strings"
"time" "time"
) )
// Version is reported in the User-Agent so streamd's audit log can tell
// agent builds apart.
const Version = "2.0"
type Client struct { type Client struct {
BaseURL string BaseURL string
Token string Token string
HTTP *http.Client HTTP *http.Client
UserAgent string UserAgent string
// AgentID is sent as X-Agent-ID so streamd can attribute audit rows to
// this agent rather than just to the API key it shares.
AgentID string
} }
// ErrUnauthorized is returned when streamd rejects this agent's credential.
// It is checked by the worker so a bad key does not burn job attempts.
var ErrUnauthorized = errors.New("unauthorized")
func New(baseURL, token string) *Client { func New(baseURL, token string) *Client {
return &Client{ return &Client{
BaseURL: strings.TrimRight(baseURL, "/"), BaseURL: strings.TrimRight(baseURL, "/"),
Token: token, Token: token,
HTTP: &http.Client{Timeout: 30 * time.Second}, HTTP: &http.Client{Timeout: 30 * time.Second},
UserAgent: "drm-agent/1.0", UserAgent: "drm-agent/" + Version,
} }
} }
// Stream is one row of GET /api/streams.
//
// Note there is no Key field. streamd redacts credentials from this response,
// and the agent only ever writes keys, never reads them. Decisions that used
// to be made here by inspecting the key are now made server-side and arrive
// as NeedsCapture / KeyValid / DRMRequired.
type Stream struct { type Stream struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Title string `json:"title"` Title string `json:"title"`
App string `json:"app"` App string `json:"app"`
Channel string `json:"channel"` Channel string `json:"channel"`
Tags string `json:"tags"`
MPD string `json:"mpd"` MPD string `json:"mpd"`
Key string `json:"key"`
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
Health string `json:"health"` Health string `json:"health"`
LastError string `json:"last_error"` LastError string `json:"last_error"`
PlaylistAgeS float64 `json:"playlist_age_s"` PlaylistAgeS float64 `json:"playlist_age_s"`
ClaimedBy string `json:"claimed_by"` ClaimedBy string `json:"claimed_by"`
// Credential state, without the credentials.
HasKey bool `json:"has_key"`
KeyValid bool `json:"key_valid"`
DRMRequired bool `json:"drm_required"`
// NeedsCapture is streamd's verdict on whether to refresh credentials.
// This is the field the poller acts on.
NeedsCapture bool `json:"needs_capture"`
OnDemand bool `json:"on_demand"`
Public bool `json:"public"`
Outputs []Output `json:"outputs"`
}
// Output is one configured publish format, shown by `agent status`.
type Output struct {
ID string `json:"id"`
Label string `json:"label"`
Format string `json:"format"`
Enabled bool `json:"enabled"`
}
// EnabledOutputs is a short label list for display, e.g. "HLS, DASH".
func (s Stream) EnabledOutputs() string {
var on []string
for _, o := range s.Outputs {
if o.Enabled {
on = append(on, o.Label)
}
}
return strings.Join(on, ",")
} }
type Credentials struct { type Credentials struct {
@ -49,11 +100,34 @@ type Credentials struct {
PID string `json:"pid,omitempty"` PID string `json:"pid,omitempty"`
} }
// Identity is the answer from GET /api/me.
type Identity struct {
Name string `json:"name"`
Role string `json:"role"`
ActorKind string `json:"actor_kind"`
AgentID string `json:"agent_id,omitempty"`
}
func (c *Client) Health() error { func (c *Client) Health() error {
_, err := c.do(http.MethodGet, "/api/health", nil) _, err := c.do(http.MethodGet, "/api/health", nil)
return err return err
} }
// Me verifies this agent's credential and reports the role it was granted.
// Called at startup so a missing, wrong or revoked key fails loudly instead
// of silently failing every poll.
func (c *Client) Me() (Identity, error) {
body, err := c.do(http.MethodGet, "/api/me", nil)
if err != nil {
return Identity{}, err
}
var id Identity
if err := json.Unmarshal(body, &id); err != nil {
return Identity{}, err
}
return id, nil
}
func (c *Client) ListStreams() ([]Stream, error) { func (c *Client) ListStreams() ([]Stream, error) {
body, err := c.do(http.MethodGet, "/api/streams", nil) body, err := c.do(http.MethodGet, "/api/streams", nil)
if err != nil { if err != nil {
@ -85,11 +159,35 @@ func (c *Client) PostCredentials(id int64, cred Credentials) error {
return err return err
} }
// Capture event kinds reported back to streamd, so a failing phone capture
// shows up on the stream's timeline in the dashboard instead of only in this
// agent's console.
const (
EventCaptureStarted = "capture_started"
EventCaptureOK = "capture_ok"
EventCaptureFailed = "capture_failed"
)
// PostEvent records an agent-authored event against a stream. Failures are
// the caller's to ignore: losing a timeline entry must never fail a capture.
func (c *Client) PostEvent(streamID int64, kind, message string, detail map[string]any) error {
payload := map[string]any{"kind": kind, "message": message}
if len(detail) > 0 {
payload["detail"] = detail
}
_, err := c.do(http.MethodPost, fmt.Sprintf("/api/streams/%d/events", streamID), payload)
return err
}
// ModuleInfo is one modules/<name>/ entry from GET /api/modules. // ModuleInfo is one modules/<name>/ entry from GET /api/modules.
type ModuleInfo struct { 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) {
@ -106,27 +204,72 @@ 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)
req.Header.Set("User-Agent", c.UserAgent)
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
}
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(resp.Body)
if resp.StatusCode >= 300 { if resp.StatusCode >= 300 {
return fmt.Errorf("PUT /api/modules/%s: %s — %s", name, resp.Status, strings.TrimSpace(string(body))) body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
return c.statusError(http.MethodGet, "/api/modules/"+name+"/package", resp, body)
}
tmp := destPath + ".partial"
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
if err != nil {
return err
}
_, copyErr := io.Copy(f, io.LimitReader(resp.Body, 100<<20))
closeErr := f.Close()
if copyErr != nil {
_ = os.Remove(tmp)
return copyErr
}
if closeErr != nil {
_ = os.Remove(tmp)
return closeErr
}
_ = os.Remove(destPath)
return os.Rename(tmp, destPath)
}
func (c *Client) setHeaders(req *http.Request) {
ua := c.UserAgent
if ua == "" {
ua = "streamd-agent/" + Version
}
req.Header.Set("User-Agent", ua)
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
}
if c.AgentID != "" {
req.Header.Set("X-Agent-ID", c.AgentID)
} }
return nil
} }
func (c *Client) do(method, path string, payload any) ([]byte, error) { func (c *Client) do(method, path string, payload any) ([]byte, error) {
@ -145,18 +288,53 @@ func (c *Client) do(method, path string, payload any) ([]byte, error) {
if payload != nil { if payload != nil {
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
} }
req.Header.Set("User-Agent", c.UserAgent) c.setHeaders(req)
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
}
resp, err := c.HTTP.Do(req) resp, err := c.HTTP.Do(req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body) body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
if resp.StatusCode >= 300 { if resp.StatusCode >= 300 {
return nil, fmt.Errorf("%s %s: %s — %s", method, path, resp.Status, strings.TrimSpace(string(body))) return nil, c.statusError(method, path, resp, body)
} }
return body, nil return body, nil
} }
// statusError turns an HTTP failure into something actionable. A 401 or 403
// used to surface as a bare status line, which left an operator guessing why
// a working agent had gone quiet.
func (c *Client) statusError(method, path string, resp *http.Response, body []byte) error {
msg := strings.TrimSpace(string(body))
if parsed := errorField(body); parsed != "" {
msg = parsed
}
switch resp.StatusCode {
case http.StatusUnauthorized:
hint := "streamd rejected this agent's credential"
if c.Token == "" {
hint = "streamd requires a credential and none is configured"
}
return fmt.Errorf("%w: %s %s — %s. Set `token:` (or `api_key:`) in apps/agent/agent.yaml, "+
"or STREAMD_TOKEN, to an API key created in the streamd dashboard under "+
"Settings -> API keys (role: operator). Server said: %s",
ErrUnauthorized, method, path, hint, msg)
case http.StatusForbidden:
return fmt.Errorf("%w: %s %s — this agent's API key lacks the needed role; "+
"it must be at least `operator`. Server said: %s", ErrUnauthorized, method, path, msg)
case http.StatusTooManyRequests:
return fmt.Errorf("%s %s: rate limited by streamd (retry-after %s) — %s",
method, path, resp.Header.Get("Retry-After"), msg)
}
return fmt.Errorf("%s %s: %s — %s", method, path, resp.Status, msg)
}
func errorField(body []byte) string {
var wrap struct {
Error string `json:"error"`
}
if json.Unmarshal(body, &wrap) == nil {
return strings.TrimSpace(wrap.Error)
}
return ""
}

View file

@ -7,12 +7,16 @@ import (
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"drmdecryption/repo" "streamd/repo"
) )
type Config struct { type Config struct {
StreamdURL string `yaml:"streamd_url"` StreamdURL string `yaml:"streamd_url"`
// Token is this agent's streamd credential. It is now an API key created
// in the dashboard (Settings -> API keys, role operator) rather than the
// one shared secret; `api_key` is a clearer alias for the same field.
Token string `yaml:"token"` Token string `yaml:"token"`
APIKey string `yaml:"api_key"`
PollIntervalSec int `yaml:"poll_interval_sec"` PollIntervalSec int `yaml:"poll_interval_sec"`
DataDir string `yaml:"data_dir"` DataDir string `yaml:"data_dir"`
Workers int `yaml:"workers"` Workers int `yaml:"workers"`
@ -23,10 +27,37 @@ 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
// an on-demand stream, or a scheduled event about to start — jump ahead
// of routine refreshes in the queue.
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.
// Defaults to true: somebody is waiting on them.
func (c Config) PushedCapturesArePriority() bool {
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 {
@ -72,9 +103,15 @@ func applyDefaults(cfg Config, root string) Config {
if cfg.StreamdURL == "" { if cfg.StreamdURL == "" {
cfg.StreamdURL = "http://127.0.0.1:8083" cfg.StreamdURL = "http://127.0.0.1:8083"
} }
if cfg.Token == "" {
cfg.Token = cfg.APIKey
}
if cfg.Token == "" { if cfg.Token == "" {
cfg.Token = os.Getenv("STREAMD_TOKEN") cfg.Token = os.Getenv("STREAMD_TOKEN")
} }
if cfg.Token == "" {
cfg.Token = os.Getenv("STREAMD_API_KEY")
}
if cfg.PollIntervalSec <= 0 { if cfg.PollIntervalSec <= 0 {
cfg.PollIntervalSec = 30 cfg.PollIntervalSec = 30
} }
@ -104,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,15 +4,15 @@ 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.
type Pool struct { type Pool struct {
mu sync.Mutex mu sync.Mutex
adbBin string adbBin string
allow map[string]bool // empty allow = all serials allow map[string]bool // empty allow = all serials
busy map[string]string // serial → job label busy map[string]string // serial → job label
} }
func New(adbBin string, allowlist []string) *Pool { func New(adbBin string, allowlist []string) *Pool {

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
}
s.logf("modules sync: read %s: %v", yamlPath, err)
continue continue
} }
sum := sha256.Sum256(raw) path := filepath.Join(dir, e.Name())
localSHA := hex.EncodeToString(sum[:]) if err := os.RemoveAll(path); err != nil {
rm, ok := byName[name] s.logf("modules sync: prune %s: %v", e.Name(), err)
if ok && rm.HasYAML && strings.EqualFold(rm.YAMLSHA256, localSHA) {
continue continue
} }
if err := s.API.PutModuleYAML(name, raw); err != nil { s.logf("modules sync: pruned %s", e.Name())
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 {
@ -51,6 +51,27 @@ func (p *Poller) Once() error {
return nil return nil
} }
// EnqueueNow is the entry point for a capture streamd has pushed over the
// websocket, for a viewer waking an on-demand stream or a scheduled event
// about to start. It jumps ahead of routine refreshes because somebody is
// waiting on it.
func (p *Poller) EnqueueNow(streamID int64, name, app, channel, reason string) {
if reason == "" {
reason = "requested"
}
j, added, err := p.Queue.EnqueueIfIdlePriority(
streamID, name, app, channel, reason, p.MaxAttempts, queue.PriorityInteractive)
switch {
case err != nil:
p.logf("push capture for stream %s failed: %v", name, err)
case added:
p.logf("enqueued job=%d stream=%s reason=%s (pushed by streamd, priority)", j.ID, name, reason)
default:
// Already queued or running: EnqueueIfIdlePriority promoted it.
p.logf("push capture for stream %s: a job is already pending (promoted)", name)
}
}
func (p *Poller) Loop(stop <-chan struct{}) { func (p *Poller) Loop(stop <-chan struct{}) {
t := time.NewTicker(p.Interval) t := time.NewTicker(p.Interval)
defer t.Stop() defer t.Stop()
@ -67,11 +88,24 @@ func (p *Poller) Loop(stop <-chan struct{}) {
} }
} }
// needsRefresh decides whether a stream wants fresh credentials.
//
// The verdict comes from streamd, not from inspecting the key: credentials are
// redacted out of the stream list, so a local "is the key empty?" test would
// see every stream as broken and queue a capture for all of them forever.
// streamd also knows things this agent does not — whether the stream is clear
// rather than encrypted, whether it is an idle on-demand stream, and whether
// it is still inside its start-up window.
func needsRefresh(st client.Stream) string { func needsRefresh(st client.Stream) string {
if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" { if !st.NeedsCapture {
return "missing_credentials" return ""
} }
if !validKeyPair(st.Key) { switch {
case strings.TrimSpace(st.MPD) == "":
return "missing_credentials"
case st.DRMRequired && !st.HasKey:
return "missing_credentials"
case st.DRMRequired && !st.KeyValid:
return "invalid_credentials" return "invalid_credentials"
} }
h := strings.ToLower(strings.TrimSpace(st.Health)) h := strings.ToLower(strings.TrimSpace(st.Health))
@ -79,27 +113,44 @@ func needsRefresh(st client.Stream) string {
case "down", "error", "failed": case "down", "error", "failed":
return "down" return "down"
} }
return "" return "stale"
} }
// validKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID ignored). // ValidKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID
func validKeyPair(key string) bool { // ignored). The authoritative check lives in streamd; this copy exists only
parts := strings.SplitN(strings.TrimSpace(key), ":", 2) // to sanity-check what a worker is about to POST.
if len(parts) != 2 { func ValidKeyPair(key string) bool {
return false for _, line := range splitKeyLines(key) {
} kid, k, ok := strings.Cut(line, ":")
hexOnly := func(s string) string { if !ok || len(hexOnly(kid)) != 32 || len(hexOnly(k)) != 32 {
var b strings.Builder return false
for _, r := range s {
switch {
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
b.WriteRune(r)
}
} }
return b.String()
} }
kid, k := hexOnly(parts[0]), hexOnly(parts[1]) return len(splitKeyLines(key)) > 0
return len(kid) == 32 && len(k) == 32 }
// splitKeyLines mirrors how streamd and the packager split a key field, so a
// multi-KID capture is not mistaken for a malformed one.
func splitKeyLines(raw string) []string {
raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
var out []string
for _, line := range strings.Split(raw, "\n") {
if line = strings.TrimSpace(line); line != "" {
out = append(out, line)
}
}
return out
}
func hexOnly(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()
} }
func (p *Poller) logf(format string, args ...any) { func (p *Poller) logf(format string, args ...any) {

View file

@ -2,6 +2,7 @@ package queue
import ( import (
"database/sql" "database/sql"
"errors"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
@ -100,24 +101,56 @@ func parseTime(s string) time.Time {
return t return t
} }
// EnqueueIfIdle inserts a job unless one is already queued/running for the stream. // Job priorities. ClaimNext orders by priority ascending, so a lower number
// runs sooner.
const (
// PriorityInteractive is for a capture a viewer or a schedule is actively
// waiting on, pushed by streamd over the agent websocket.
PriorityInteractive = 10
// PriorityRoutine is a background refresh found by polling.
PriorityRoutine = 100
)
// EnqueueIfIdle inserts a routine job unless one is already queued/running
// for the stream.
func (s *Store) EnqueueIfIdle(streamID int64, name, app, channel, reason string, maxAttempts int) (Job, bool, error) { func (s *Store) EnqueueIfIdle(streamID int64, name, app, channel, reason string, maxAttempts int) (Job, bool, error) {
var existing int return s.EnqueueIfIdlePriority(streamID, name, app, channel, reason, maxAttempts, PriorityRoutine)
}
// EnqueueIfIdlePriority is EnqueueIfIdle with an explicit priority. A job that
// someone is waiting on is enqueued ahead of routine refreshes; if a routine
// job for the same stream is already queued, its priority is raised instead of
// adding a duplicate.
func (s *Store) EnqueueIfIdlePriority(streamID int64, name, app, channel, reason string, maxAttempts, priority int) (Job, bool, error) {
var existingID int64
var existingPriority int
err := s.DB.QueryRow(` err := s.DB.QueryRow(`
SELECT COUNT(1) FROM jobs WHERE stream_id=? AND status IN ('queued','running')`, streamID).Scan(&existing) SELECT id, priority FROM jobs
if err != nil { WHERE stream_id=? AND status IN ('queued','running')
return Job{}, false, err ORDER BY id LIMIT 1`, streamID).Scan(&existingID, &existingPriority)
} switch {
if existing > 0 { case err == nil:
// Already pending. Promote it when this request is more urgent, and
// clear any backoff so it runs now rather than after the delay.
if priority < existingPriority {
_, _ = s.DB.Exec(
`UPDATE jobs SET priority=?, reason=?, not_before='' WHERE id=? AND status='queued'`,
priority, reason, existingID)
}
return Job{}, false, nil return Job{}, false, nil
case !errors.Is(err, sql.ErrNoRows):
return Job{}, false, err
} }
if maxAttempts <= 0 { if maxAttempts <= 0 {
maxAttempts = 5 maxAttempts = 5
} }
if priority <= 0 {
priority = PriorityRoutine
}
res, err := s.DB.Exec(` res, err := s.DB.Exec(`
INSERT INTO jobs(stream_id,stream_name,app,channel,reason,status,priority,attempts,max_attempts,created_at,not_before) INSERT INTO jobs(stream_id,stream_name,app,channel,reason,status,priority,attempts,max_attempts,created_at,not_before)
VALUES(?,?,?,?,?,'queued',100,0,?,?,?)`, VALUES(?,?,?,?,?,'queued',?,0,?,?,?)`,
streamID, name, app, channel, reason, maxAttempts, now(), now()) streamID, name, app, channel, reason, priority, maxAttempts, now(), now())
if err != nil { if err != nil {
return Job{}, false, err return Job{}, false, err
} }
@ -199,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
@ -219,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(`
@ -230,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

@ -1,18 +1,20 @@
package worker package worker
import ( import (
"errors"
"fmt" "fmt"
"log" "log"
"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/queue" "streamd/apps/agent/internal/poller"
"streamd/apps/agent/internal/queue"
) )
type Worker struct { type Worker struct {
@ -25,7 +27,10 @@ type Worker struct {
Python string Python string
WVD string WVD string
UserAgent string UserAgent string
Log *log.Logger // JobBackoff enables exponential delays between failed capture attempts.
// When false (default), failed jobs are re-queued immediately.
JobBackoff bool
Log *log.Logger
lastDelayLog time.Time lastDelayLog time.Time
} }
@ -65,11 +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.Queue.MarkFailed(job.ID, err.Error(), false) w.event(job, client.EventCaptureFailed, err.Error(),
map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
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)
@ -80,6 +92,11 @@ func isAuthErr(err error) bool {
if err == nil { if err == nil {
return false return false
} }
// The client now returns a typed error with an actionable message; the
// substring check stays as a fallback for errors raised elsewhere.
if errors.Is(err, client.ErrUnauthorized) {
return true
}
s := strings.ToLower(err.Error()) s := strings.ToLower(err.Error())
return strings.Contains(s, "401") || strings.Contains(s, "unauthorized") return strings.Contains(s, "401") || strings.Contains(s, "unauthorized")
} }
@ -98,6 +115,10 @@ func (w *Worker) runJob(job queue.Job) error {
return err return err
} }
label := fmt.Sprintf("job-%d:%s", job.ID, job.StreamName) label := fmt.Sprintf("job-%d:%s", job.ID, job.StreamName)
// Tell streamd a capture is under way, so the stream's timeline in the
// dashboard shows it rather than just an unexplained "down".
w.event(job, client.EventCaptureStarted,
fmt.Sprintf("capture started on %s (%s)", w.AgentID, job.Reason), nil)
c, serial, err := w.Pool.Acquire(a.Package(), label) c, serial, err := w.Pool.Acquire(a.Package(), label)
if err != nil { if err != nil {
return err return err
@ -106,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) }()
@ -127,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,
@ -137,9 +171,41 @@ 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.
w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
"device": serial,
"has_key": strings.TrimSpace(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
// failing a capture over, so errors are logged and dropped.
func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {
if w.API == nil || job.StreamID == 0 {
return
}
if detail == nil {
detail = map[string]any{}
}
detail["agent_id"] = w.AgentID
detail["job_id"] = job.ID
if err := w.API.PostEvent(job.StreamID, kind, message, detail); err != nil {
w.logf("job=%d: could not report %s to streamd: %v", job.ID, kind, err)
}
}
func (w *Worker) logf(format string, args ...any) { func (w *Worker) logf(format string, args ...any) {
prefix := fmt.Sprintf("worker/%d: ", w.ID) prefix := fmt.Sprintf("worker/%d: ", w.ID)
if w.Log != nil { if w.Log != nil {

View file

@ -10,16 +10,42 @@ import (
"time" "time"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"streamd/apps/agent/internal/client"
) )
// Message is one push from streamd.
type Message struct {
Type string `json:"type"`
OK bool `json:"ok"`
Error string `json:"error"`
Message string `json:"message"`
StreamID int64 `json:"stream_id"`
StreamName string `json:"stream_name"`
App string `json:"app"`
Channel string `json:"channel"`
Reason string `json:"reason"`
}
// Client keeps a streamd /ws/agent connection alive and sends heartbeats // Client keeps a streamd /ws/agent connection alive and sends heartbeats
// so claims auto-renew; on disconnect streamd releases this agent's claims. // so claims auto-renew; on disconnect streamd releases this agent's claims.
// It also carries pushes from streamd: a capture a viewer or a schedule is
// waiting on, which would otherwise not be noticed until the next poll.
type Client struct { type Client struct {
BaseURL string BaseURL string
Token string Token string
AgentID string AgentID string
Log *log.Logger Log *log.Logger
// OnCapture is called when streamd asks for credentials now.
OnCapture func(streamID int64, name, app, channel, reason string)
// OnStreamChanged is called when a stream was edited, so the agent can
// re-poll instead of waiting out its interval.
OnStreamChanged func(name, reason string)
// OnModulesChanged is called when the panel uploaded/edited/deleted a
// module, so the agent can pull without waiting for the sync interval.
OnModulesChanged func(name, reason string)
stop chan struct{} stop chan struct{}
} }
@ -47,7 +73,8 @@ func (c *Client) Loop() {
return return
default: default:
} }
if err := c.session(); err != nil { err := c.session()
if err != nil {
c.Log.Printf("ws: session ended: %v — retry in %s", err, backoff) c.Log.Printf("ws: session ended: %v — retry in %s", err, backoff)
} }
select { select {
@ -75,18 +102,29 @@ func (c *Client) session() error {
u.Path = "/ws/agent" u.Path = "/ws/agent"
q := u.Query() q := u.Query()
q.Set("agent_id", c.AgentID) q.Set("agent_id", c.AgentID)
if c.Token != "" { // The token is deliberately NOT put in the query string. It used to be,
q.Set("token", c.Token) // which wrote the shared secret into every reverse proxy access log.
} // streamd authenticates the handshake from the Authorization header below.
u.RawQuery = q.Encode() u.RawQuery = q.Encode()
hdr := http.Header{} hdr := http.Header{}
if c.Token != "" { if c.Token != "" {
hdr.Set("Authorization", "Bearer "+c.Token) hdr.Set("Authorization", "Bearer "+c.Token)
} }
if c.AgentID != "" {
hdr.Set("X-Agent-ID", c.AgentID)
}
hdr.Set("User-Agent", "streamd-agent/"+client.Version)
dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second} dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
conn, _, err := dialer.Dial(u.String(), hdr) conn, resp, err := dialer.Dial(u.String(), hdr)
if err != nil { if err != nil {
if resp != nil {
switch resp.StatusCode {
case http.StatusUnauthorized, http.StatusForbidden:
return fmt.Errorf("dial: %w (streamd rejected this agent's API key for /ws/agent; "+
"it needs at least the operator role)", err)
}
}
return fmt.Errorf("dial: %w", err) return fmt.Errorf("dial: %w", err)
} }
defer conn.Close() defer conn.Close()
@ -107,14 +145,11 @@ func (c *Client) session() error {
return return
} }
_ = conn.SetReadDeadline(time.Now().Add(60 * time.Second)) _ = conn.SetReadDeadline(time.Now().Add(60 * time.Second))
var msg map[string]any var msg Message
if json.Unmarshal(data, &msg) == nil { if json.Unmarshal(data, &msg) != nil {
if t, _ := msg["type"].(string); t == "heartbeat_ack" { continue
if ok, _ := msg["ok"].(bool); !ok {
c.Log.Printf("ws: heartbeat nack: %v", msg["error"])
}
}
} }
c.handle(msg)
} }
}() }()
@ -139,6 +174,33 @@ func (c *Client) session() error {
} }
} }
func (c *Client) handle(msg Message) {
switch strings.ToLower(msg.Type) {
case "heartbeat_ack":
if !msg.OK {
c.Log.Printf("ws: heartbeat nack: %s", msg.Error)
}
case "capture_requested":
if msg.StreamID == 0 {
return
}
c.Log.Printf("ws: streamd requested a capture for stream=%s reason=%s",
msg.StreamName, msg.Reason)
if c.OnCapture != nil {
c.OnCapture(msg.StreamID, msg.StreamName, msg.App, msg.Channel, msg.Reason)
}
case "stream_changed":
if c.OnStreamChanged != nil {
c.OnStreamChanged(msg.StreamName, msg.Reason)
}
case "modules_changed":
c.Log.Printf("ws: modules changed module=%s reason=%s", msg.StreamName, msg.Reason)
if c.OnModulesChanged != nil {
c.OnModulesChanged(msg.StreamName, msg.Reason)
}
}
}
func (c *Client) writeHeartbeat(conn *websocket.Conn) error { func (c *Client) writeHeartbeat(conn *websocket.Conn) error {
_ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) _ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
return conn.WriteJSON(map[string]string{ return conn.WriteJSON(map[string]string{

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

@ -3,22 +3,25 @@
package capturecmd package capturecmd
import ( import (
"encoding/json"
"flag" "flag"
"fmt" "fmt"
"os"
"path/filepath"
"strings" "strings"
"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)
@ -32,16 +35,17 @@ func Run(args []string) error {
fs := flag.NewFlagSet("capture", flag.ContinueOnError) fs := flag.NewFlagSet("capture", flag.ContinueOnError)
appName := fs.String("app", "", "app module under modules/<name>/. Empty = passive MITM, no launch/auto-play") appName := fs.String("app", "", "app module under modules/<name>/. Empty = passive MITM, no launch/auto-play")
channel := fs.String("channel", "", "channel id for --auto-play") channel := fs.String("channel", "", "channel id for --auto-play")
autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (implied when --channel is set)") allChannels := fs.Bool("all", false, "capture every channel declared by the module (grab-all)")
waitSec := fs.Int("wait", 180, "seconds to wait for license/mpd capture") autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (implied when --channel / --all is set)")
waitSec := fs.Int("wait", 180, "seconds to wait for license/mpd capture (per channel with --all)")
python := fs.String("python", "", "python for wvkey.py (default: .venv)") python := fs.String("python", "", "python for wvkey.py (default: .venv)")
wvd := fs.String("wvd", "", "path to .wvd device file (required for key fetch)") wvd := fs.String("wvd", "", "path to .wvd device file (required by some apps e.g. c4; MPD-only if omitted)")
userAgent := fs.String("user-agent", "", "optional User-Agent for license requests") userAgent := fs.String("user-agent", "", "optional User-Agent for license requests")
serial := fs.String("serial", "", "adb device serial (default: sole/USB selected device)") serial := fs.String("serial", "", "adb device serial (default: sole/USB selected device)")
closeApp := fs.Bool("close", true, "force-stop --app when capture finishes (ignored in passive mode)") closeApp := fs.Bool("close", true, "force-stop --app when capture finishes (ignored in passive mode)")
keyMode := fs.String("key-mode", "", "override the app's key mode: modulardrm | raw | none") keyMode := fs.String("key-mode", "", "override the app's key mode: modulardrm | raw | wrap | none")
fs.Usage = func() { fs.Usage = func() {
fmt.Fprintf(fs.Output(), "capture — one-shot phone MITM capture\n\nUsage:\n capture --app <%s> [--channel ID] [--auto-play] [--wvd PATH]\n capture (passive: play anything on the phone)\n\nExample (BBC + NordVPN UK):\n capture --app bbc --channel bbcone --wait 120\n\nFlags:\n", appChoices) fmt.Fprintf(fs.Output(), "capture — one-shot phone MITM capture\n\nUsage:\n capture --app <%s> [--channel ID | --all] [--auto-play] [--wvd PATH]\n capture (passive: play anything on the phone)\n\nExamples:\n capture --app bbc --channel bbcone --wait 120\n capture --app c4 --channel film4 --wvd data/device.wvd\n capture --app c4 --all --wvd data/device.wvd --wait 90\n\nFlags:\n", appChoices)
fs.PrintDefaults() fs.PrintDefaults()
} }
@ -60,6 +64,9 @@ func Run(args []string) error {
// No --app: passive MITM — the operator plays whatever they want and we dump // No --app: passive MITM — the operator plays whatever they want and we dump
// whatever DRM traffic appears. // whatever DRM traffic appears.
if strings.TrimSpace(*appName) == "" { if strings.TrimSpace(*appName) == "" {
if *allChannels {
return fmt.Errorf("--all requires --app")
}
_, err := phonecap.RunPassive(phonecap.Options{ _, err := phonecap.RunPassive(phonecap.Options{
Client: c, Client: c,
Python: *python, Python: *python,
@ -76,7 +83,26 @@ func Run(args []string) error {
if err != nil { if err != nil {
return modhost.FormatUnknown(root, *appName) return modhost.FormatUnknown(root, *appName)
} }
if needsWVD(a) && strings.TrimSpace(*wvd) == "" {
return fmt.Errorf("%s requires --wvd PATH (Widevine device file) — encrypted capture cannot be MPD-only", a.Name())
}
channelID := strings.TrimSpace(*channel) channelID := strings.TrimSpace(*channel)
if *allChannels && channelID != "" {
return fmt.Errorf("use either --channel or --all, not both")
}
if *allChannels {
return runAll(root, a, c, phonecap.Options{
App: a,
Client: c,
Python: *python,
WVD: *wvd,
UserAgent: *userAgent,
Wait: time.Duration(*waitSec) * time.Second,
CloseApp: *closeApp,
KeyMode: *keyMode,
ClearProxy: true,
})
}
// --channel implies interactive auto-play (Explore → channel → Watch live). // --channel implies interactive auto-play (Explore → channel → Watch live).
doAutoPlay := *autoPlay || channelID != "" doAutoPlay := *autoPlay || channelID != ""
if *autoPlay && channelID == "" { if *autoPlay && channelID == "" {
@ -102,6 +128,106 @@ func Run(args []string) error {
return err return err
} }
type channelResult struct {
Channel string `json:"channel"`
Label string `json:"label"`
OK bool `json:"ok"`
MPD string `json:"mpd,omitempty"`
LicenseURL string `json:"license_url,omitempty"`
Key string `json:"key,omitempty"`
Path string `json:"path,omitempty"`
Error string `json:"error,omitempty"`
}
func runAll(root string, a app.App, c *adb.Client, base phonecap.Options) error {
chs := a.Channels()
if len(chs) == 0 {
return fmt.Errorf("no channels configured for %s (%s)", a.Name(), knownChannels(a))
}
fmt.Printf("[*] Grab-all %s — %d channel(s)\n", a.Name(), len(chs))
results := make([]channelResult, 0, len(chs))
okN := 0
for i, ch := range chs {
fmt.Printf("\n======== [%d/%d] %s (%s) ========\n", i+1, len(chs), ch.Label, ch.ID)
opt := base
opt.Channel = ch.ID
opt.NoAutoPlay = false
opt.App = a
opt.Client = c
res, err := phonecap.Run(opt)
row := channelResult{
Channel: ch.ID,
Label: ch.Label,
}
if err != nil {
row.Error = err.Error()
fmt.Fprintf(os.Stderr, "[!] %s: %v\n", ch.ID, err)
} else {
row.OK = res.MPD != ""
row.MPD = res.MPD
row.LicenseURL = res.Session.LicenseURL
row.Key = res.Key
row.Path = res.Path
if row.OK {
okN++
} else {
row.Error = "no mpd"
}
}
results = append(results, row)
if i+1 < len(chs) {
// Let iptables / appproxy fully release before the next transparent start.
time.Sleep(4 * time.Second)
}
}
stamp := time.Now().Format("20060102-150405")
batchDir := filepath.Join(root, "outputs", a.Name(), "all-"+stamp)
_ = os.MkdirAll(batchDir, 0o755)
summaryPath := filepath.Join(batchDir, "SUMMARY.json")
if b, err := json.MarshalIndent(results, "", " "); err == nil {
_ = os.WriteFile(summaryPath, b, 0o644)
}
printAllSummary(a.Name(), results, okN, summaryPath)
if okN == 0 {
return fmt.Errorf("grab-all %s: 0/%d channels captured", a.Name(), len(chs))
}
if okN < len(chs) {
return fmt.Errorf("grab-all %s: %d/%d channels captured (see %s)", a.Name(), okN, len(chs), summaryPath)
}
return nil
}
func printAllSummary(appName string, results []channelResult, okN int, summaryPath string) {
fmt.Println()
fmt.Println("========== GRAB-ALL SUMMARY ==========")
fmt.Printf("app: %s ok: %d/%d\n", appName, okN, len(results))
fmt.Println("--------------------------------------")
fmt.Printf("%-12s %-14s %-6s %s\n", "ID", "LABEL", "OK", "MPD / ERROR")
for _, r := range results {
status := "no"
if r.OK {
status = "yes"
}
detail := r.Error
if r.OK {
detail = trimURL(r.MPD, 72)
}
fmt.Printf("%-12s %-14s %-6s %s\n", r.Channel, r.Label, status, detail)
}
fmt.Println("--------------------------------------")
fmt.Println("summary:", summaryPath)
fmt.Println("======================================")
}
func trimURL(s string, n int) string {
s = strings.TrimSpace(s)
if len(s) <= n {
return s
}
return s[:n] + "…"
}
// normalizeArgs rewrites Unicode dashes Word/Terminal often insert (— – −) // normalizeArgs rewrites Unicode dashes Word/Terminal often insert (— – −)
// into ASCII - so `--app` is not silently dropped as a positional token. // into ASCII - so `--app` is not silently dropped as a positional token.
func normalizeArgs(args []string) []string { func normalizeArgs(args []string) []string {
@ -130,6 +256,13 @@ func normalizeArgs(args []string) []string {
return out return out
} }
func needsWVD(a app.App) bool {
if rw, ok := a.(app.RequireWVD); ok {
return rw.RequireWVD()
}
return false
}
// knownChannels describes what the operator can pick, or where to declare it when // knownChannels describes what the operator can pick, or where to declare it when
// the module has no local values file yet. // the module has no local values file yet.
func knownChannels(a app.App) string { func knownChannels(a app.App) string {

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,22 +1,26 @@
// 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.
package main package main
import ( import (
// The scheduler resolves IANA zone names so a weekly event stays at its
// local wall-clock time. Windows ships no zone database, so embed one.
_ "time/tzdata"
"fmt" "fmt"
"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() {
@ -35,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)
@ -98,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] [--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
@ -23,9 +23,9 @@ func TestAllModulesRegisterAndConstruct(t *testing.T) {
t.Errorf("%s: Name() = %q", n, a.Name()) t.Errorf("%s: Name() = %q", n, a.Name())
} }
switch a.KeyMode() { switch a.KeyMode() {
case "raw", "modulardrm", "none": case "raw", "modulardrm", "wrap", "none":
default: default:
t.Errorf("%s: KeyMode() = %q, want raw, modulardrm, or none", n, a.KeyMode()) t.Errorf("%s: KeyMode() = %q, want raw, modulardrm, wrap, or none", n, a.KeyMode())
} }
if a.CAHash() == "" { if a.CAHash() == "" {
t.Errorf("%s: CAHash() empty", n) t.Errorf("%s: CAHash() empty", n)
@ -39,6 +39,12 @@ func TestAllModulesRegisterAndConstruct(t *testing.T) {
if a.CaptureHints().RemoteLog == "" { if a.CaptureHints().RemoteLog == "" {
t.Errorf("%s: CaptureHints has no remote log", n) t.Errorf("%s: CaptureHints has no remote log", n)
} }
if n == "c4" {
rw, ok := a.(appreg.RequireWVD)
if !ok || !rw.RequireWVD() {
t.Errorf("c4 must RequireWVD() so capture refuses MPD-only runs")
}
}
} }
} }

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.

148
apps/modules/c4/c4.go Normal file
View file

@ -0,0 +1,148 @@
// Package c4 is the Channel 4 (All 4) Live TV provider module.
// Live list rows use content-desc "Select to watch Channel Four" / "E Four" / etc.
package c4
import (
"flag"
"fmt"
"os"
"strings"
"time"
"streamd/adb"
appreg "streamd/app"
"streamd/capture"
"streamd/modules/provider"
"streamd/mpd"
"streamd/uiflow"
)
func init() {
appreg.Register(Name, New)
appreg.RegisterFlags(bindFlags)
}
func bindFlags(fs *flag.FlagSet) {
fs.StringVar(&flags.packageName, Name+".package", "", "override "+Name+" android package id")
fs.StringVar(&flags.caHash, Name+".ca-hash", "", "override "+Name+" MITM CA subject hash")
fs.StringVar(&flags.proxyBin, Name+".proxy-bin", "", "override "+Name+" on-device MITM binary")
}
// App is the Channel 4 plugin.
type App struct {
*provider.Base
cfg Config
}
// New constructs the plugin from module.yaml + flags + env.
func New() (appreg.App, error) {
cfg, res, err := loadConfig()
if err != nil {
return nil, err
}
labels := make(map[string]string, len(cfg.Channels))
for id, ch := range cfg.Channels {
labels[id] = ch.Label
}
return &App{Base: provider.New(Name, cfg.Common, labels, res), cfg: cfg}, nil
}
// KeyMode: Channel 4 / RedBee needs the phone's JSON license POST (token +
// challenge). Capture stores that body; wvkey --mode wrap re-issues it.
func (a *App) KeyMode() string { return "wrap" }
// RequireWVD: C4 live is always encrypted — refuse MPD-only captures.
func (a *App) RequireWVD() bool { return true }
// CaptureHints: need the DASH MPD and the phone's RedBee license POST body
// (token + challenge). MPD alone is not enough for keys.
func (a *App) CaptureHints() capture.Hints {
return a.Hints("mpd", "license_body")
}
// CaptureHintsFor prefers the simulcast path for this live channel so a
// neighbouring Auto-play / prefetch MPD does not win the Wait score race.
func (a *App) CaptureHintsFor(channel string) capture.Hints {
h := a.CaptureHints()
id, err := a.Resolve(channel)
if err != nil {
id = strings.ToLower(strings.TrimSpace(channel))
}
prefer := map[string]string{
"channel4": "channel(c4)",
"e4": "channel(e4)",
"more4": "channel(m4)",
"film4": "channel(f4)",
"fourseven": "channel(4s)",
}
if p, ok := prefer[id]; ok {
h.PreferURLContains = []string{p}
}
return h
}
// UseTransparentMITM: UK VPN on-device conflicts with Wi‑Fi http_proxy.
func (a *App) UseTransparentMITM() bool { return true }
func (a *App) MPDRewriter() mpd.Rewriter { return mpd.Passthrough{} }
func (a *App) Channels() []appreg.Channel {
out := make([]appreg.Channel, 0, len(a.cfg.Channels))
for _, id := range a.ChannelIDs() {
out = append(out, appreg.Channel{ID: id, Label: a.Label(id)})
}
return out
}
// Launch cold-starts Channel 4.
func (a *App) Launch(c *adb.Client) error {
c.EnsureAwake()
fmt.Printf("[*] Launching %s (%s)…\n", Name, a.Package())
c.ForceStop(a.Package())
time.Sleep(400 * time.Millisecond)
if err := uiflow.MonkeyLaunch(c, a.Package()); err != nil {
return err
}
time.Sleep(time.Duration(a.cfg.Timeouts.LaunchSettle))
c.DismissShadeIfFocused()
if err := uiflow.WaitUI(c, a.CacheDir(), uiflow.Match{
DescContains: a.cfg.UI.LaunchDescContains,
TextContains: a.cfg.UI.LaunchDescContains,
}, time.Duration(a.cfg.Timeouts.LaunchWaitUI)); err != nil {
fmt.Fprintf(os.Stderr, "[!] launch UI wait: %v — continue and play manually\n", err)
}
return nil
}
// AutoPlay opens Live TV, scrolls to the channel card, and taps Select to watch.
func (a *App) AutoPlay(c *adb.Client, channel string) error {
id, err := a.Resolve(channel)
if err != nil {
return err
}
ch := a.cfg.Channels[id]
fmt.Printf("[*] Auto-play %s…\n", a.Label(id))
c.DismissShadeIfFocused()
if err := a.openLiveTab(c); err != nil {
return fmt.Errorf("Live TV tab: %w", err)
}
if err := a.tapChannelCard(c, ch); err != nil {
return fmt.Errorf("channel play %s: %w", a.Label(id), err)
}
return uiflow.WaitPlayback(c, a.CacheDir(), a.Package(), uiflow.PlaybackOpts{
Timeout: time.Duration(a.cfg.Timeouts.Playback),
SoftFail: true,
OrDescContains: []string{
"Pause",
"Unmute",
"Cast",
},
})
}
func (a *App) VideoSelect() string { return "for=best" }
func (a *App) AudioSelect() string { return "for=best" }
func (a *App) RewriterName() string { return "none" }
func (a *App) LiveWaitSeconds() int { return 2 }
func (a *App) TSReadyBytes() int64 { return 256 << 10 }

116
apps/modules/c4/config.go Normal file
View file

@ -0,0 +1,116 @@
package c4
import (
"time"
"streamd/modcfg"
"streamd/modules/provider"
)
// Name is the module id (--app c4).
const Name = "c4"
// Channel is one Channel 4 Live TV target.
type Channel struct {
Label string `yaml:"label"`
ChipDesc []string `yaml:"chip_desc"`
PlayDesc []string `yaml:"play_desc"`
}
// Config is modules/c4/module.yaml (preferred) or apps/modules/c4/module.yaml.
type Config struct {
provider.Common `yaml:",inline"`
Channels map[string]Channel `yaml:"channels"`
Timeouts Timeouts `yaml:"timeouts"`
UI UI `yaml:"ui"`
}
type Timeouts struct {
LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
LaunchSettle provider.Duration `yaml:"launch_settle"`
LiveNav provider.Duration `yaml:"live_nav"`
ChannelFind provider.Duration `yaml:"channel_find"`
AfterChannel provider.Duration `yaml:"after_channel"`
WatchLive provider.Duration `yaml:"watch_live"`
Playback provider.Duration `yaml:"playback"`
}
type UI struct {
LaunchDescContains []string `yaml:"launch_desc_contains"`
LiveTab []string `yaml:"live_tab"`
LiveTabDescRE []string `yaml:"live_tab_desc_re"`
LiveTabTextRE []string `yaml:"live_tab_text_re"`
WatchLive []string `yaml:"watch_live"`
PlaybackDescContains []string `yaml:"playback_desc_contains"`
ChannelScrollMax int `yaml:"channel_scroll_max"`
}
func (c Config) withDefaults() Config {
t := &c.Timeouts
t.LaunchWaitUI = provider.Duration(t.LaunchWaitUI.D(30 * time.Second))
t.LaunchSettle = provider.Duration(t.LaunchSettle.D(5 * time.Second))
t.LiveNav = provider.Duration(t.LiveNav.D(20 * time.Second))
t.ChannelFind = provider.Duration(t.ChannelFind.D(45 * time.Second))
t.AfterChannel = provider.Duration(t.AfterChannel.D(2 * time.Second))
t.WatchLive = provider.Duration(t.WatchLive.D(20 * time.Second))
t.Playback = provider.Duration(t.Playback.D(45 * time.Second))
u := &c.UI
if len(u.LaunchDescContains) == 0 {
u.LaunchDescContains = []string{"Home", "Live TV", "My Shows", "Downloads", "Search"}
}
if len(u.LiveTab) == 0 {
u.LiveTab = []string{"Live TV"}
}
if len(u.LiveTabDescRE) == 0 {
u.LiveTabDescRE = []string{`(?i)^Live TV$`}
}
if len(u.LiveTabTextRE) == 0 {
u.LiveTabTextRE = []string{`(?i)^Live TV$`}
}
if len(u.WatchLive) == 0 {
u.WatchLive = []string{"Select to watch", "Play Episode", "Restart"}
}
if len(u.PlaybackDescContains) == 0 {
u.PlaybackDescContains = []string{"Pause", "Unmute", "Cast", "Subtitles"}
}
if u.ChannelScrollMax <= 0 {
u.ChannelScrollMax = 10
}
if c.Package == "" {
c.Package = "com.channel4.ondemand"
}
if c.Channels == nil {
c.Channels = map[string]Channel{}
}
return c
}
func loadConfig() (Config, modcfg.Result, error) {
var cfg Config
res, err := modcfg.Load(Name, &cfg)
if err != nil {
return cfg, res, err
}
cfg = cfg.withDefaults()
if v := modcfg.Env(Name, "package"); v != "" {
cfg.Package = v
}
if flags.packageName != "" {
cfg.Package = flags.packageName
}
if flags.caHash != "" {
cfg.CAHash = flags.caHash
}
if flags.proxyBin != "" {
cfg.ProxyBin = flags.proxyBin
}
return cfg, res, nil
}
var flags struct {
packageName string
caHash string
proxyBin string
}

View file

@ -0,0 +1,84 @@
# Channel 4 (All 4) — published universal values (renamed to module.yaml in release zips).
# Live cards: content-desc "Select to watch Channel Four" / "E Four" / "More Four" / …
package: com.channel4.ondemand
proxy_bin: bin/proxy-android-arm64
# SENSITIVE — set in local module.yaml:
# license_url: "https://c4.eme.lp.aws.redbeemedia.com/wvlicenceproxy-service/widevine/acquire"
# Transparent mode only MITMs open.live by default. Force C4 playlist / license hosts.
mitm_hosts:
- c4assets.com
- olsp.live.dash.c4assets.com
- stream.c4assets.com
- channel4.com
- api.channel4.com
- c4.eme.lp.aws.redbeemedia.com
- redbeemedia.com
- all4nav.channel4.com
score:
hosts:
- c4assets.com
- olsp.live.dash.c4assets.com
- stream.c4assets.com
- channel4.com
- api.channel4.com
- redbeemedia.com
- akamaized.net
deny:
- google-analytics
- googletagmanager
- doubleclick
- scorecardresearch
- facebook.com
- crashlytics
- appsflyer
- optimizely
aliases:
c4: channel4
four: channel4
ch4: channel4
channel: channel4
e: e4
more: more4
film: film4
"4seven": fourseven
seven: fourseven
channels:
channel4:
label: Channel Four
chip_desc: ["(?i)Select to watch\\s+Channel Four"]
e4:
label: E Four
chip_desc: ["(?i)Select to watch\\s+E Four"]
more4:
label: More Four
chip_desc: ["(?i)Select to watch\\s+More Four"]
film4:
label: Film Four
chip_desc: ["(?i)Select to watch\\s+Film Four"]
fourseven:
label: Four Seven
chip_desc: ["(?i)Select to watch\\s+Four Seven"]
ui:
launch_desc_contains: ["Home", "Live TV", "My Shows", "Downloads", "Search"]
live_tab: ["Live TV"]
live_tab_desc_re: ["(?i)^Live TV$"]
live_tab_text_re: ["(?i)^Live TV$"]
watch_live: ["Select to watch", "Play Episode"]
playback_desc_contains: ["Pause", "Unmute", "Cast"]
channel_scroll_max: 16
timeouts:
launch_wait_ui: 30s
launch_settle: 5s
live_nav: 20s
channel_find: 45s
after_channel: 2s
watch_live: 20s
playback: 45s

175
apps/modules/c4/steps.go Normal file
View file

@ -0,0 +1,175 @@
package c4
import (
"fmt"
"regexp"
"strings"
"time"
"streamd/adb"
"streamd/uiflow"
)
func (a *App) openLiveTab(c *adb.Client) error {
c.DismissShadeIfFocused()
if nodes, err := c.DumpUI(a.CacheDir()); err == nil && a.onLiveTab(nodes) {
fmt.Println("[*] already on Live TV")
return nil
}
fmt.Println("[*] open Live TV…")
descRE := a.cfg.UI.LiveTabDescRE
if len(descRE) == 0 {
descRE = []string{`(?i)^Live TV$`}
}
textRE := a.cfg.UI.LiveTabTextRE
if len(textRE) == 0 {
textRE = []string{`(?i)^Live TV$`}
}
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
DescRE: descRE,
TextRE: textRE,
DescContains: a.cfg.UI.LiveTab,
TextContains: a.cfg.UI.LiveTab,
Pick: uiflow.PickFirst,
}, time.Duration(a.cfg.Timeouts.LiveNav)); err != nil {
return fmt.Errorf("live tab: %w", err)
}
time.Sleep(1500 * time.Millisecond)
deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveNav))
for time.Now().Before(deadline) {
nodes, err := c.DumpUI(a.CacheDir())
if err == nil && a.onLiveTab(nodes) {
fmt.Println("[*] Live TV ready")
a.disableLiveAutoPlay(c)
return nil
}
time.Sleep(700 * time.Millisecond)
}
return fmt.Errorf("Live TV did not open")
}
// disableLiveAutoPlay turns off the Live TV "Auto-play" toggle so the app does
// not advance to the next channel while we wait for MITM.
func (a *App) disableLiveAutoPlay(c *adb.Client) {
nodes, err := c.DumpUI(a.CacheDir())
if err != nil {
return
}
for _, n := range nodes {
d := strings.ToLower(strings.TrimSpace(n.Desc))
t := strings.ToLower(strings.TrimSpace(n.Text))
if d != "auto-play" && t != "auto-play" {
continue
}
if n.Selected || n.Checked {
fmt.Println("[*] disable Live Auto-play")
_ = c.Tap(n.CX(), n.CY())
time.Sleep(500 * time.Millisecond)
return
}
// State may not be exposed — leave alone when already off / unknown.
fmt.Println("[*] Live Auto-play control present (left as-is)")
return
}
}
func (a *App) onLiveTab(nodes []adb.Node) bool {
for _, n := range nodes {
d := strings.ToLower(n.Desc)
if strings.Contains(d, "select to watch") {
return true
}
if strings.Contains(d, "now showing on") {
return true
}
if strings.EqualFold(n.Desc, "Live TV, heading") || strings.EqualFold(n.Text, "On now") {
return true
}
}
return false
}
// tapChannelCard scrolls the Live list for "Select to watch {Label}" and taps it.
func (a *App) tapChannelCard(c *adb.Client, ch Channel) error {
pats := ch.ChipDesc
if len(pats) == 0 {
pats = []string{`(?i)Select to watch\s+` + regexp.QuoteMeta(ch.Label)}
}
chipRE := uiflow.CompileRes(pats)
fmt.Printf("[*] find Live card for %s…\n", ch.Label)
row, err := a.findChannelCard(c, chipRE)
if err != nil {
return err
}
fmt.Printf("[*] tap %q @ %d,%d\n", trimDesc(row.Desc, 60), row.CX(), row.CY())
if err := c.Tap(row.CX(), row.CY()); err != nil {
return err
}
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
return nil
}
func (a *App) findChannelCard(c *adb.Client, chipRE []*regexp.Regexp) (*adb.Node, error) {
scrollMax := a.cfg.UI.ChannelScrollMax
if scrollMax <= 0 {
scrollMax = 10
}
// Prefer starting near the top so Channel Four / E4 are reachable.
_ = c.Swipe(540, 1100, 540, 1900, 250)
time.Sleep(400 * time.Millisecond)
for attempt := 0; attempt <= scrollMax; attempt++ {
nodes, err := c.DumpUI(a.CacheDir())
if err != nil {
return nil, err
}
var best *adb.Node
for i := range nodes {
n := &nodes[i]
hay := n.Desc
if hay == "" {
hay = n.Text
}
if hay == "" {
continue
}
// Skip cards clipped into the bottom nav (false taps).
if n.Y2 > 2100 || n.CY() > 2050 {
continue
}
for _, p := range chipRE {
if !p.MatchString(hay) {
continue
}
// Prefer the explicit "Select to watch" control when present.
if strings.Contains(strings.ToLower(hay), "select to watch") {
return n, nil
}
if best == nil {
best = n
}
}
}
if best != nil {
return best, nil
}
if attempt == scrollMax {
break
}
fmt.Printf("[*] scroll Live list (%d/%d)…\n", attempt+1, scrollMax)
_ = c.Swipe(540, 1950, 540, 900, 320)
time.Sleep(700 * time.Millisecond)
}
return nil, fmt.Errorf("channel card not found")
}
func trimDesc(s string, n int) string {
s = strings.TrimSpace(s)
if len(s) <= n {
return s
}
return s[:n] + "…"
}

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

116
apps/modules/itv/config.go Normal file
View file

@ -0,0 +1,116 @@
package itv
import (
"time"
"streamd/modcfg"
"streamd/modules/provider"
)
// Name is the module id (--app itv).
const Name = "itv"
// Channel is one live ITVX target.
type Channel struct {
Label string `yaml:"label"`
ChipDesc []string `yaml:"chip_desc"`
PlayDesc []string `yaml:"play_desc"`
}
// Config is modules/itv/module.yaml (preferred) or apps/modules/itv/module.yaml.
type Config struct {
provider.Common `yaml:",inline"`
Channels map[string]Channel `yaml:"channels"`
Timeouts Timeouts `yaml:"timeouts"`
UI UI `yaml:"ui"`
}
type Timeouts struct {
LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
LaunchSettle provider.Duration `yaml:"launch_settle"`
LiveNav provider.Duration `yaml:"live_nav"`
ChannelFind provider.Duration `yaml:"channel_find"`
AfterChannel provider.Duration `yaml:"after_channel"`
WatchLive provider.Duration `yaml:"watch_live"`
Playback provider.Duration `yaml:"playback"`
}
type UI struct {
LaunchDescContains []string `yaml:"launch_desc_contains"`
LiveTab []string `yaml:"live_tab"`
LiveTabDescRE []string `yaml:"live_tab_desc_re"`
LiveTabTextRE []string `yaml:"live_tab_text_re"`
WatchLive []string `yaml:"watch_live"`
PlaybackDescContains []string `yaml:"playback_desc_contains"`
ChannelScrollMax int `yaml:"channel_scroll_max"`
}
func (c Config) withDefaults() Config {
t := &c.Timeouts
t.LaunchWaitUI = provider.Duration(t.LaunchWaitUI.D(30 * time.Second))
t.LaunchSettle = provider.Duration(t.LaunchSettle.D(5 * time.Second))
t.LiveNav = provider.Duration(t.LiveNav.D(20 * time.Second))
t.ChannelFind = provider.Duration(t.ChannelFind.D(45 * time.Second))
t.AfterChannel = provider.Duration(t.AfterChannel.D(3 * time.Second))
t.WatchLive = provider.Duration(t.WatchLive.D(20 * time.Second))
t.Playback = provider.Duration(t.Playback.D(60 * time.Second))
u := &c.UI
if len(u.LaunchDescContains) == 0 {
u.LaunchDescContains = []string{"Home", "Live", "Categories", "My List", "ITVX"}
}
if len(u.LiveTab) == 0 {
u.LiveTab = []string{"Lyve", "Live"}
}
if len(u.LiveTabDescRE) == 0 {
u.LiveTabDescRE = []string{"^Lyve$"}
}
if len(u.LiveTabTextRE) == 0 {
u.LiveTabTextRE = []string{"^Live$"}
}
if len(u.WatchLive) == 0 {
u.WatchLive = []string{"WATCH LIVE", "Watch live", "Watch Live"}
}
if len(u.PlaybackDescContains) == 0 {
u.PlaybackDescContains = []string{"Pause", "pause", "Seek", "Player"}
}
if u.ChannelScrollMax <= 0 {
u.ChannelScrollMax = 12
}
if c.Package == "" {
c.Package = "air.ITVMobilePlayer"
}
if c.Channels == nil {
c.Channels = map[string]Channel{}
}
return c
}
func loadConfig() (Config, modcfg.Result, error) {
var cfg Config
res, err := modcfg.Load(Name, &cfg)
if err != nil {
return cfg, res, err
}
cfg = cfg.withDefaults()
if v := modcfg.Env(Name, "package"); v != "" {
cfg.Package = v
}
if flags.packageName != "" {
cfg.Package = flags.packageName
}
if flags.caHash != "" {
cfg.CAHash = flags.caHash
}
if flags.proxyBin != "" {
cfg.ProxyBin = flags.proxyBin
}
return cfg, res, nil
}
var flags struct {
packageName string
caHash string
proxyBin string
}

124
apps/modules/itv/itv.go Normal file
View file

@ -0,0 +1,124 @@
// Package itv is a stub ITVX provider module.
// Launch works; AutoPlay opens the Live tab and taps a channel chip when
// content-desc matches. Capture scoring targets ITV CDN / license hosts.
// Full Live navigation and catalog may need tuning against a UK-geo session.
package itv
import (
"flag"
"fmt"
"os"
"time"
"streamd/adb"
appreg "streamd/app"
"streamd/capture"
"streamd/modules/provider"
"streamd/mpd"
"streamd/uiflow"
)
func init() {
appreg.Register(Name, New)
appreg.RegisterFlags(bindFlags)
}
func bindFlags(fs *flag.FlagSet) {
fs.StringVar(&flags.packageName, Name+".package", "", "override "+Name+" android package id")
fs.StringVar(&flags.caHash, Name+".ca-hash", "", "override "+Name+" MITM CA subject hash")
fs.StringVar(&flags.proxyBin, Name+".proxy-bin", "", "override "+Name+" on-device MITM binary")
}
// App is the ITVX plugin.
type App struct {
*provider.Base
cfg Config
}
// New constructs the plugin from module.yaml + flags + env.
func New() (appreg.App, error) {
cfg, res, err := loadConfig()
if err != nil {
return nil, err
}
labels := make(map[string]string, len(cfg.Channels))
for id, ch := range cfg.Channels {
labels[id] = ch.Label
}
return &App{Base: provider.New(Name, cfg.Common, labels, res), cfg: cfg}, nil
}
// KeyMode: ITVX live typically uses a raw Widevine license response.
func (a *App) KeyMode() string { return "raw" }
// CaptureHints: transparent MITM yields the DAR MPD URL (+ Irdeto license_url).
// PSSH is often absent from the outer YoSpace/CSM MPD; require mpd only for now.
func (a *App) CaptureHints() capture.Hints {
return a.Hints("mpd")
}
// UseTransparentMITM: UK VPN on-device conflicts with Wi‑Fi http_proxy.
func (a *App) UseTransparentMITM() bool { return true }
// MPDRewriter: passthrough until a DAI rewriter is needed.
func (a *App) MPDRewriter() mpd.Rewriter { return mpd.Passthrough{} }
func (a *App) Channels() []appreg.Channel {
out := make([]appreg.Channel, 0, len(a.cfg.Channels))
for _, id := range a.ChannelIDs() {
out = append(out, appreg.Channel{ID: id, Label: a.Label(id)})
}
return out
}
// Launch cold-starts ITVX.
func (a *App) Launch(c *adb.Client) error {
c.EnsureAwake()
fmt.Printf("[*] Launching %s (%s)…\n", Name, a.Package())
c.ForceStop(a.Package())
time.Sleep(400 * time.Millisecond)
if err := uiflow.MonkeyLaunch(c, a.Package()); err != nil {
return err
}
time.Sleep(time.Duration(a.cfg.Timeouts.LaunchSettle))
c.DismissShadeIfFocused()
if err := uiflow.WaitUI(c, a.CacheDir(), uiflow.Match{
DescContains: a.cfg.UI.LaunchDescContains,
}, time.Duration(a.cfg.Timeouts.LaunchWaitUI)); err != nil {
fmt.Fprintf(os.Stderr, "[!] launch UI wait: %v — continue and play manually\n", err)
}
return nil
}
// AutoPlay opens Live, scrolls to the channel row, and taps WATCH LIVE.
// Failures return an error so batch capture can report which channel broke.
func (a *App) AutoPlay(c *adb.Client, channel string) error {
id, err := a.Resolve(channel)
if err != nil {
return err
}
ch := a.cfg.Channels[id]
fmt.Printf("[*] Auto-play %s…\n", a.Label(id))
c.DismissShadeIfFocused()
if err := a.openLiveTab(c); err != nil {
return fmt.Errorf("Live tab: %w", err)
}
if err := a.tapChipThenPlay(c, ch); err != nil {
return fmt.Errorf("channel play %s: %w", a.Label(id), err)
}
return uiflow.WaitPlayback(c, a.CacheDir(), a.Package(), uiflow.PlaybackOpts{
Timeout: time.Duration(a.cfg.Timeouts.Playback),
SoftFail: true,
OrDescContains: []string{
"on full screen",
"Unmute",
},
})
}
func (a *App) VideoSelect() string { return "for=best" }
func (a *App) AudioSelect() string { return "for=best" }
func (a *App) RewriterName() string { return "none" }
func (a *App) LiveWaitSeconds() int { return 2 }
func (a *App) TSReadyBytes() int64 { return 256 << 10 }

View file

@ -0,0 +1,90 @@
# ITVX — published universal values (renamed to module.yaml in release zips).
# Fill secrets in local module.yaml: license_url, origins, kids (never commit that file).
# Stub: Live UI matchers are best-effort; tune after a UK-geo phone session.
package: air.ITVMobilePlayer
proxy_bin: bin/proxy-android-arm64
# SENSITIVE — set in local module.yaml:
# license_url: "https://…"
# Transparent mode only MITMs open.live by default. Force decrypt of ITVX
# playlist / license / simulcast hosts observed in phone traffic (suffix match).
# Segment CDNs (akamai.content) stay passthrough so playback is less likely to break.
mitm_hosts:
- play.dar.itv.com
- itvpnp.live.ott.irdeto.com
- simulcast.itv.com
- secure.pes.itv.com
- cpt.itv.com
- tom.itv.com
score:
hosts:
- play.dar.itv.com
- itvpnp.live.ott.irdeto.com
- simulcast.itv.com
- content.itv.com
- itv.com
- itvstatic.com
- irdeto.com
deny:
- google-analytics
- googletagmanager
- doubleclick
- scorecardresearch
- facebook.com
- crashlytics
- launchdarkly
- 2cnt.net
- appsflyer
aliases:
one: itv1
itv: itv1
two: itv2
three: itv3
four: itv4
be: itvbe
citv: itvxkids
channels:
itv1:
label: ITV1
# Live list rows: "Expand ITV1 info button" / "Collapse ITV1 info button"
chip_desc: ["(?i)(Expand|Collapse)\\s+ITV1\\s+info button"]
play_desc: ["(?i)^WATCH LIVE$", "(?i)Watch\\s+ITV1\\s+on full screen"]
itv2:
label: ITV2
chip_desc: ["(?i)(Expand|Collapse)\\s+ITV2\\s+info button"]
play_desc: ["(?i)^WATCH LIVE$", "(?i)Watch\\s+ITV2\\s+on full screen"]
itv3:
label: ITV3
chip_desc: ["(?i)(Expand|Collapse)\\s+ITV3\\s+info button"]
play_desc: ["(?i)^WATCH LIVE$", "(?i)Watch\\s+ITV3\\s+on full screen"]
itv4:
label: ITV4
chip_desc: ["(?i)(Expand|Collapse)\\s+ITV4\\s+info button"]
play_desc: ["(?i)^WATCH LIVE$", "(?i)Watch\\s+ITV4\\s+on full screen"]
itvbe:
label: ITVBe
chip_desc: ["(?i)(Expand|Collapse)\\s+ITVBe\\s+info button"]
play_desc: ["(?i)^WATCH LIVE$", "(?i)Watch\\s+ITVBe\\s+on full screen"]
ui:
launch_desc_contains: ["Home", "Lyve", "Live", "Categories", "ITVX"]
live_tab: ["Lyve", "Live"]
live_tab_desc_re: ["^Lyve$"]
live_tab_text_re: ["^Live$"]
watch_live: ["WATCH LIVE", "Watch live", "Watch Live"]
playback_desc_contains: ["Unmute", "on full screen", "Pause"]
channel_scroll_max: 14
timeouts:
launch_wait_ui: 30s
launch_settle: 5s
live_nav: 20s
channel_find: 45s
after_channel: 3s
watch_live: 20s
playback: 60s

153
apps/modules/itv/steps.go Normal file
View file

@ -0,0 +1,153 @@
package itv
import (
"fmt"
"regexp"
"strings"
"time"
"streamd/adb"
"streamd/uiflow"
)
// openLiveTab taps bottom-nav Live. Accessibility desc is obfuscated as "Lyve";
// the visible label is still "Live". Prefer the nav item over "Space Live" rows.
func (a *App) openLiveTab(c *adb.Client) error {
c.DismissShadeIfFocused()
if nodes, err := c.DumpUI(a.CacheDir()); err == nil && a.onLiveTab(nodes) {
fmt.Println("[*] already on Live tab")
return nil
}
fmt.Println("[*] open Live tab…")
descRE := a.cfg.UI.LiveTabDescRE
if len(descRE) == 0 {
descRE = []string{"^Lyve$"}
}
textRE := a.cfg.UI.LiveTabTextRE
if len(textRE) == 0 {
textRE = []string{"^Live$"}
}
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
DescRE: descRE,
TextRE: textRE,
Pick: uiflow.PickFirst,
}, time.Duration(a.cfg.Timeouts.LiveNav)); err != nil {
// Fallback: substring match from publish YAML.
if err2 := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
DescContains: a.cfg.UI.LiveTab,
TextContains: a.cfg.UI.LiveTab,
Pick: uiflow.PickFirst,
}, 8*time.Second); err2 != nil {
return fmt.Errorf("live tab: %w", err)
}
}
time.Sleep(1500 * time.Millisecond)
deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveNav))
for time.Now().Before(deadline) {
nodes, err := c.DumpUI(a.CacheDir())
if err == nil && a.onLiveTab(nodes) {
fmt.Println("[*] Live tab ready")
return nil
}
time.Sleep(700 * time.Millisecond)
}
return fmt.Errorf("Live tab did not open")
}
func (a *App) onLiveTab(nodes []adb.Node) bool {
for _, n := range nodes {
d := strings.ToLower(n.Desc)
if strings.HasPrefix(d, "expand ") && strings.Contains(d, " info button") {
return true
}
if strings.HasPrefix(d, "collapse ") && strings.Contains(d, " info button") {
return true
}
if strings.HasPrefix(d, "watch ") && strings.Contains(d, " on full screen") {
return true
}
}
return false
}
// tapChipThenPlay scrolls the Live channel list for Expand/Collapse {label}
// info button, taps the row, then taps WATCH LIVE / Watch {label} on full screen.
func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error {
pats := ch.ChipDesc
if len(pats) == 0 {
pats = []string{`(?i)(Expand|Collapse)\s+` + regexp.QuoteMeta(ch.Label) + `\s+info button`}
}
chipRE := uiflow.CompileRes(pats)
fmt.Printf("[*] find Live row for %s…\n", ch.Label)
row, err := a.findChannelRow(c, chipRE)
if err != nil {
return err
}
// Chevron nodes are often not clickable; tap mid-row to the left of the button.
x := 540
if row.X1 > 0 && row.X1 < 400 {
x = row.CX()
}
y := row.CY()
fmt.Printf("[*] tap channel row %q @ %d,%d\n", row.Desc, x, y)
if err := c.Tap(x, y); err != nil {
return err
}
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
playRE := ch.PlayDesc
if len(playRE) == 0 {
playRE = []string{
`(?i)^WATCH LIVE$`,
`(?i)^Watch\s+` + regexp.QuoteMeta(ch.Label) + `\s+on full screen$`,
}
}
fmt.Println("[*] tap Watch live…")
// Prefer the list "WATCH LIVE" text button for the selected row.
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
TextRE: playRE,
DescRE: playRE,
Pick: uiflow.PickFirst,
}, time.Duration(a.cfg.Timeouts.WatchLive)); err != nil {
return fmt.Errorf("watch live: %w", err)
}
return nil
}
func (a *App) findChannelRow(c *adb.Client, chipRE []*regexp.Regexp) (*adb.Node, error) {
scrollMax := a.cfg.UI.ChannelScrollMax
if scrollMax <= 0 {
scrollMax = 12
}
// Prefer scrolling down from the top so ITV1/ITV2 are reachable.
_ = c.Swipe(540, 1200, 540, 1900, 250)
time.Sleep(400 * time.Millisecond)
for attempt := 0; attempt <= scrollMax; attempt++ {
nodes, err := c.DumpUI(a.CacheDir())
if err != nil {
return nil, err
}
for i := range nodes {
n := &nodes[i]
if n.Desc == "" {
continue
}
for _, p := range chipRE {
if p.MatchString(n.Desc) {
return n, nil
}
}
}
if attempt == scrollMax {
break
}
fmt.Printf("[*] scroll Live list (%d/%d)…\n", attempt+1, scrollMax)
_ = c.Swipe(540, 1950, 540, 1100, 320)
time.Sleep(700 * time.Millisecond)
}
return nil, fmt.Errorf("channel row not found")
}

133
apps/modules/my5/config.go Normal file
View file

@ -0,0 +1,133 @@
package my5
import (
"time"
"streamd/modcfg"
"streamd/modules/provider"
)
// Name is the module id (--app my5).
const Name = "my5"
// Channel is one My5 / Channel 5 Live TV target.
// Logos in the Live TV rail have no accessibility text, so selection uses
// logo_index (0-based order in the left channel-logo recycler).
type Channel struct {
Label string `yaml:"label"`
LogoIndex int `yaml:"logo_index"`
ChipDesc []string `yaml:"chip_desc"` // unused; kept for YAML parity with other modules
PlayDesc []string `yaml:"play_desc"`
}
// Config is modules/my5/module.yaml (preferred) or apps/modules/my5/module.yaml.
type Config struct {
provider.Common `yaml:",inline"`
Channels map[string]Channel `yaml:"channels"`
Timeouts Timeouts `yaml:"timeouts"`
UI UI `yaml:"ui"`
}
type Timeouts struct {
LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
LaunchSettle provider.Duration `yaml:"launch_settle"`
LiveNav provider.Duration `yaml:"live_nav"`
ChannelFind provider.Duration `yaml:"channel_find"`
AfterChannel provider.Duration `yaml:"after_channel"`
WatchLive provider.Duration `yaml:"watch_live"`
Playback provider.Duration `yaml:"playback"`
}
type UI struct {
LaunchDescContains []string `yaml:"launch_desc_contains"`
LiveTab []string `yaml:"live_tab"`
LiveTabDescRE []string `yaml:"live_tab_desc_re"`
LiveTabTextRE []string `yaml:"live_tab_text_re"`
WatchLive []string `yaml:"watch_live"`
PlaybackDescContains []string `yaml:"playback_desc_contains"`
ChannelScrollMax int `yaml:"channel_scroll_max"`
// LogoMaxX: ImageViews with X1 below this are treated as channel logos.
LogoMaxX int `yaml:"logo_max_x"`
// LogoMinY / LogoMaxY: vertical band of the logos recycler (excludes player + nav).
LogoMinY int `yaml:"logo_min_y"`
LogoMaxY int `yaml:"logo_max_y"`
}
func (c Config) withDefaults() Config {
t := &c.Timeouts
t.LaunchWaitUI = provider.Duration(t.LaunchWaitUI.D(30 * time.Second))
t.LaunchSettle = provider.Duration(t.LaunchSettle.D(5 * time.Second))
t.LiveNav = provider.Duration(t.LiveNav.D(20 * time.Second))
t.ChannelFind = provider.Duration(t.ChannelFind.D(45 * time.Second))
t.AfterChannel = provider.Duration(t.AfterChannel.D(2 * time.Second))
t.WatchLive = provider.Duration(t.WatchLive.D(20 * time.Second))
t.Playback = provider.Duration(t.Playback.D(45 * time.Second))
u := &c.UI
if len(u.LaunchDescContains) == 0 {
u.LaunchDescContains = []string{"Home", "Live TV", "Search", "More", "Milkshake"}
}
if len(u.LiveTab) == 0 {
u.LiveTab = []string{"Live TV"}
}
if len(u.LiveTabDescRE) == 0 {
u.LiveTabDescRE = []string{`(?i)^Live TV$`}
}
if len(u.LiveTabTextRE) == 0 {
u.LiveTabTextRE = []string{`(?i)^Live TV$`}
}
if len(u.WatchLive) == 0 {
u.WatchLive = []string{"Play", "Watch"}
}
if len(u.PlaybackDescContains) == 0 {
u.PlaybackDescContains = []string{"Pause", "Unmute", "Cast", "Subtitles"}
}
if u.ChannelScrollMax <= 0 {
u.ChannelScrollMax = 20
}
if u.LogoMaxX <= 0 {
u.LogoMaxX = 230
}
if u.LogoMinY <= 0 {
u.LogoMinY = 700
}
if u.LogoMaxY <= 0 {
u.LogoMaxY = 2100
}
if c.Package == "" {
c.Package = "com.mobileiq.demand5"
}
if c.Channels == nil {
c.Channels = map[string]Channel{}
}
return c
}
func loadConfig() (Config, modcfg.Result, error) {
var cfg Config
res, err := modcfg.Load(Name, &cfg)
if err != nil {
return cfg, res, err
}
cfg = cfg.withDefaults()
if v := modcfg.Env(Name, "package"); v != "" {
cfg.Package = v
}
if flags.packageName != "" {
cfg.Package = flags.packageName
}
if flags.caHash != "" {
cfg.CAHash = flags.caHash
}
if flags.proxyBin != "" {
cfg.ProxyBin = flags.proxyBin
}
return cfg, res, nil
}
var flags struct {
packageName string
caHash string
proxyBin string
}

View file

@ -0,0 +1,118 @@
# Channel 5 (My5 / "5") — published universal values (renamed to module.yaml in release zips).
# Live TV left-rail logos have no accessibility text; selection uses logo_index (0-based).
package: com.mobileiq.demand5
proxy_bin: bin/proxy-android-arm64
# SENSITIVE — set in local module.yaml after capture:
# license_url: "https://cassie.channel5.com/api/v2/licences/widevine/…"
# Transparent mode only MITMs open.live by default. Force My5 playlist / license hosts.
mitm_hosts:
- channel5.com
- corona.channel5.com
- cassie.channel5.com
- cassie-auth.channel5.com
- hwdash.channel5.com
- c5apps.channel5.com
score:
hosts:
- channel5.com
- corona.channel5.com
- cassie.channel5.com
- cassie-auth.channel5.com
- hwdash.channel5.com
- akamaized.net
- akadash
deny:
- google-analytics
- googletagmanager
- doubleclick
- scorecardresearch
- facebook.com
- crashlytics
- appsflyer
- optimizely
- kantarmedia
aliases:
c5: channel5
five: channel5
ch5: channel5
channel: channel5
my5: channel5
usa: 5usa
star: 5star
action: 5action
select: 5select
cops: 5cops
christmas: 5christmas
drama: 5drama
crime: 5crime
interceptors: policeinterceptors
pi: policeinterceptors
channels:
# Linear Freeview/Freely channels (logo rail order observed on moto g56).
channel5:
label: Channel 5
logo_index: 0
5usa:
label: 5USA
logo_index: 1
5star:
label: 5STAR
logo_index: 2
5action:
label: 5ACTION
logo_index: 3
5select:
label: 5SELECT
logo_index: 4
# FAST / box-set live rails (indices from Live TV scroll; may shift with seasons).
policeinterceptors:
label: Police Interceptors
logo_index: 5
5cops:
label: 5 Cops
logo_index: 6
5christmas:
label: 5 Christmas
logo_index: 7
5drama:
label: 5 Drama
logo_index: 8
bargainbrits:
label: Bargain Loving Brits
logo_index: 9
casualty247:
label: Casualty 24/7
logo_index: 10
rogueclaimers:
label: Rogue Claimers
logo_index: 11
5crime:
label: 5 Crime
logo_index: 12
ui:
launch_desc_contains: ["Home", "Live TV", "Search", "More", "Milkshake"]
live_tab: ["Live TV"]
live_tab_desc_re: ["(?i)^Live TV$"]
live_tab_text_re: ["(?i)^Live TV$"]
watch_live: ["Play", "Watch"]
playback_desc_contains: ["Pause", "Unmute", "Cast"]
channel_scroll_max: 20
logo_max_x: 230
logo_min_y: 700
logo_max_y: 2100
timeouts:
launch_wait_ui: 30s
launch_settle: 5s
live_nav: 20s
channel_find: 45s
after_channel: 2s
watch_live: 20s
playback: 45s

160
apps/modules/my5/my5.go Normal file
View file

@ -0,0 +1,160 @@
// Package my5 is the Channel 5 (My5 / "5") Live TV provider module.
// Live TV uses a left-rail of channel logos (no content-desc); selection is by logo_index.
package my5
import (
"flag"
"fmt"
"os"
"strings"
"time"
"streamd/adb"
appreg "streamd/app"
"streamd/capture"
"streamd/modules/provider"
"streamd/mpd"
"streamd/uiflow"
)
func init() {
appreg.Register(Name, New)
appreg.RegisterFlags(bindFlags)
}
func bindFlags(fs *flag.FlagSet) {
fs.StringVar(&flags.packageName, Name+".package", "", "override "+Name+" android package id")
fs.StringVar(&flags.caHash, Name+".ca-hash", "", "override "+Name+" MITM CA subject hash")
fs.StringVar(&flags.proxyBin, Name+".proxy-bin", "", "override "+Name+" on-device MITM binary")
}
// App is the My5 plugin.
type App struct {
*provider.Base
cfg Config
}
// New constructs the plugin from module.yaml + flags + env.
func New() (appreg.App, error) {
cfg, res, err := loadConfig()
if err != nil {
return nil, err
}
labels := make(map[string]string, len(cfg.Channels))
for id, ch := range cfg.Channels {
labels[id] = ch.Label
}
return &App{Base: provider.New(Name, cfg.Common, labels, res), cfg: cfg}, nil
}
// KeyMode: My5 live uses a raw Widevine license response (Cassie).
func (a *App) KeyMode() string { return "raw" }
// CaptureHints: transparent MITM should yield the DASH MPD (+ license_url).
func (a *App) CaptureHints() capture.Hints {
return a.Hints("mpd")
}
// CaptureHintsFor prefers URL substrings for this live channel when known.
func (a *App) CaptureHintsFor(channel string) capture.Hints {
h := a.CaptureHints()
id, err := a.Resolve(channel)
if err != nil {
id = strings.ToLower(strings.TrimSpace(channel))
}
// Prefer patterns filled after first successful captures; safe no-ops until then.
prefer := map[string][]string{
"channel5": {"channel5", "c5-", "/c5"},
"5usa": {"5usa", "usa"},
"5star": {"5star", "star"},
"5action": {"5action", "action"},
"5select": {"5select", "select"},
}
if p, ok := prefer[id]; ok {
h.PreferURLContains = p
}
return h
}
// UseTransparentMITM: UK VPN on-device conflicts with Wi‑Fi http_proxy.
func (a *App) UseTransparentMITM() bool { return true }
func (a *App) MPDRewriter() mpd.Rewriter { return mpd.Passthrough{} }
func (a *App) Channels() []appreg.Channel {
out := make([]appreg.Channel, 0, len(a.cfg.Channels))
for _, id := range a.ChannelIDs() {
out = append(out, appreg.Channel{ID: id, Label: a.Label(id)})
}
return out
}
// Launch cold-starts My5 and dismisses common first-run prompts.
func (a *App) Launch(c *adb.Client) error {
c.EnsureAwake()
fmt.Printf("[*] Launching %s (%s)…\n", Name, a.Package())
c.ForceStop(a.Package())
time.Sleep(400 * time.Millisecond)
if err := uiflow.MonkeyLaunch(c, a.Package()); err != nil {
return err
}
time.Sleep(time.Duration(a.cfg.Timeouts.LaunchSettle))
c.DismissShadeIfFocused()
a.dismissOnboarding(c)
if err := uiflow.WaitUI(c, a.CacheDir(), uiflow.Match{
DescContains: a.cfg.UI.LaunchDescContains,
TextContains: a.cfg.UI.LaunchDescContains,
}, time.Duration(a.cfg.Timeouts.LaunchWaitUI)); err != nil {
fmt.Fprintf(os.Stderr, "[!] launch UI wait: %v — continue and play manually\n", err)
}
return nil
}
// AutoPlay opens Live TV, taps the channel logo by index, then the Now EPG cell.
func (a *App) AutoPlay(c *adb.Client, channel string) error {
id, err := a.Resolve(channel)
if err != nil {
return err
}
ch := a.cfg.Channels[id]
fmt.Printf("[*] Auto-play %s (logo %d)…\n", a.Label(id), ch.LogoIndex)
c.EnsureAwake()
c.DismissShadeIfFocused()
// Capture host normally Launch()s first; still start the app if we landed on the launcher.
if !a.appFocused(c) {
if err := a.Launch(c); err != nil {
return err
}
}
a.dismissOnboarding(c)
if err := a.openLiveTab(c); err != nil {
return fmt.Errorf("Live TV tab: %w", err)
}
if err := a.tapChannelLogo(c, ch); err != nil {
return fmt.Errorf("channel logo %s: %w", a.Label(id), err)
}
if err := a.tapNowCell(c, ch); err != nil {
fmt.Fprintf(os.Stderr, "[!] Now cell tap: %v — relying on embedded player\n", err)
}
return uiflow.WaitPlayback(c, a.CacheDir(), a.Package(), uiflow.PlaybackOpts{
Timeout: time.Duration(a.cfg.Timeouts.Playback),
SoftFail: true,
OrDescContains: []string{
"Pause",
"Unmute",
"Cast",
},
OrResourceContains: []string{
"c5player",
"video_view",
"video_player",
},
})
}
func (a *App) VideoSelect() string { return "for=best" }
func (a *App) AudioSelect() string { return "for=best" }
func (a *App) RewriterName() string { return "none" }
func (a *App) LiveWaitSeconds() int { return 2 }
func (a *App) TSReadyBytes() int64 { return 256 << 10 }

265
apps/modules/my5/steps.go Normal file
View file

@ -0,0 +1,265 @@
package my5
import (
"fmt"
"sort"
"strings"
"time"
"streamd/adb"
"streamd/uiflow"
)
func (a *App) appFocused(c *adb.Client) bool {
out, err := c.Shell("dumpsys", "window")
if err != nil {
return false
}
pkg := a.Package()
for _, line := range strings.Split(out, "\n") {
if strings.Contains(line, "mCurrentFocus") && strings.Contains(line, pkg) {
return true
}
}
return false
}
func (a *App) dismissOnboarding(c *adb.Client) {
deadline := time.Now().Add(8 * time.Second)
for time.Now().Before(deadline) {
nodes, err := c.DumpUI(a.CacheDir())
if err != nil {
return
}
for _, n := range nodes {
t := strings.TrimSpace(n.Text)
switch {
case strings.EqualFold(t, "Not now"),
strings.EqualFold(t, "Just browse"),
strings.EqualFold(t, "Skip register"):
fmt.Printf("[*] dismiss %q\n", t)
_ = c.Tap(n.CX(), n.CY())
time.Sleep(800 * time.Millisecond)
goto next
}
}
return
next:
}
}
func (a *App) openLiveTab(c *adb.Client) error {
c.DismissShadeIfFocused()
if nodes, err := c.DumpUI(a.CacheDir()); err == nil && a.onLiveTab(nodes) {
fmt.Println("[*] already on Live TV")
return nil
}
fmt.Println("[*] open Live TV…")
descRE := a.cfg.UI.LiveTabDescRE
if len(descRE) == 0 {
descRE = []string{`(?i)^Live TV$`}
}
textRE := a.cfg.UI.LiveTabTextRE
if len(textRE) == 0 {
textRE = []string{`(?i)^Live TV$`}
}
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
DescRE: descRE,
TextRE: textRE,
DescContains: a.cfg.UI.LiveTab,
TextContains: a.cfg.UI.LiveTab,
Pick: uiflow.PickFirst,
}, time.Duration(a.cfg.Timeouts.LiveNav)); err != nil {
return fmt.Errorf("live tab: %w", err)
}
time.Sleep(1500 * time.Millisecond)
deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveNav))
for time.Now().Before(deadline) {
nodes, err := c.DumpUI(a.CacheDir())
if err == nil && a.onLiveTab(nodes) {
fmt.Println("[*] Live TV ready")
return nil
}
time.Sleep(700 * time.Millisecond)
}
return fmt.Errorf("Live TV did not open")
}
func (a *App) onLiveTab(nodes []adb.Node) bool {
for _, n := range nodes {
id := strings.ToLower(n.ResourceID)
if strings.Contains(id, "tv_guide_channel_logos") ||
strings.Contains(id, "tv_guide_epg") ||
strings.Contains(id, "tv_guide_player") ||
strings.Contains(id, "tv_guide_navigation") && n.Selected {
return true
}
if strings.EqualFold(n.Text, "Now") && strings.Contains(id, "tv_guide_header_now") {
return true
}
}
return false
}
func (a *App) logoNodes(nodes []adb.Node) []adb.Node {
maxX := a.cfg.UI.LogoMaxX
minY := a.cfg.UI.LogoMinY
maxY := a.cfg.UI.LogoMaxY
var out []adb.Node
for _, n := range nodes {
if !strings.Contains(n.Class, "ImageView") {
continue
}
// Channel logos in the Live rail have empty resource-id; EPG thumbs do not.
if strings.TrimSpace(n.ResourceID) != "" {
continue
}
if n.X1 >= maxX || n.Y1 < minY || n.Y1 >= maxY {
continue
}
// Skip tiny icons / nav glyphs.
if (n.Y2-n.Y1) < 120 || (n.X2-n.X1) < 120 {
continue
}
if !n.Clickable {
continue
}
out = append(out, n)
}
sort.Slice(out, func(i, j int) bool {
if out[i].Y1 == out[j].Y1 {
return out[i].X1 < out[j].X1
}
return out[i].Y1 < out[j].Y1
})
return out
}
// tapChannelLogo scrolls the left logo rail from the top by logo_index rows, then taps.
func (a *App) tapChannelLogo(c *adb.Client, ch Channel) error {
want := ch.LogoIndex
if want < 0 {
return fmt.Errorf("logo_index must be >= 0")
}
fmt.Printf("[*] find logo index %d (%s)…\n", want, ch.Label)
// Scroll to the top of the logo rail.
for i := 0; i < 8; i++ {
_ = c.Swipe(118, 1000, 118, 1950, 250)
time.Sleep(280 * time.Millisecond)
}
time.Sleep(400 * time.Millisecond)
nodes, err := c.DumpUI(a.CacheDir())
if err != nil {
return err
}
logos := a.logoNodes(nodes)
if len(logos) == 0 {
return fmt.Errorf("no channel logos visible")
}
rowH := logos[0].Y2 - logos[0].Y1
if rowH < 120 {
rowH = 205
}
// Gap between rows is small; step ≈ row height + ~10px from observed layout.
step := rowH + 10
// Bring target near the top by single-row swipes, then tap it in-view.
for i := 0; i < want; i++ {
_ = c.Swipe(118, 1200, 118, 1200-step, 220)
time.Sleep(350 * time.Millisecond)
}
time.Sleep(400 * time.Millisecond)
nodes, err = c.DumpUI(a.CacheDir())
if err != nil {
return err
}
logos = a.logoNodes(nodes)
if len(logos) == 0 {
return fmt.Errorf("no channel logos after scroll to index %d", want)
}
var n adb.Node
if want == 0 {
n = logos[0]
} else {
// After want single-row swipes from top, the target is the first fully
// visible logo (previous rows scrolled off). Prefer logos[0] when fully
// on-screen; otherwise logos[1] if the top one is clipped.
n = logos[0]
if n.Y1 < a.cfg.UI.LogoMinY+5 && len(logos) > 1 {
n = logos[1]
}
}
if n.CY() >= 2050 || n.Y2 > a.cfg.UI.LogoMaxY {
return fmt.Errorf("logo index %d clipped into nav", want)
}
fmt.Printf("[*] tap logo %d @ %d,%d\n", want, n.CX(), n.CY())
if err := c.Tap(n.CX(), n.CY()); err != nil {
return err
}
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
return nil
}
func abs(v int) int {
if v < 0 {
return -v
}
return v
}
// tapNowCell taps the "Now" EPG cell aligned with the selected logo row.
// After tapChannelLogo scrolls the target to the top of the rail, align to logos[0].
func (a *App) tapNowCell(c *adb.Client, ch Channel) error {
_ = ch
nodes, err := c.DumpUI(a.CacheDir())
if err != nil {
return err
}
logos := a.logoNodes(nodes)
if len(logos) == 0 {
return fmt.Errorf("no logos after select")
}
logo := &logos[0]
if logo.Y1 < a.cfg.UI.LogoMinY+5 && len(logos) > 1 {
logo = &logos[1]
}
var best *adb.Node
bestDist := 1 << 30
for i := range nodes {
n := &nodes[i]
id := strings.ToLower(n.ResourceID)
if !strings.Contains(id, "epg_now_view") {
continue
}
d := abs(n.CY() - logo.CY())
if d < bestDist {
bestDist = d
best = n
}
}
if best == nil {
// Fallback: tap embedded player surface.
for i := range nodes {
n := &nodes[i]
id := strings.ToLower(n.ResourceID)
if strings.Contains(id, "video_view") || strings.Contains(id, "c5player") {
fmt.Printf("[*] tap player @ %d,%d\n", n.CX(), n.CY())
return c.Tap(n.CX(), n.CY())
}
}
return fmt.Errorf("Now cell not found")
}
fmt.Printf("[*] tap Now cell @ %d,%d\n", best.CX(), best.CY())
if err := c.Tap(best.CX(), best.CY()); err != nil {
return err
}
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
return nil
}

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
@ -25,6 +25,9 @@ type Common struct {
CAHash string `yaml:"ca_hash"` CAHash string `yaml:"ca_hash"`
Aliases map[string]string `yaml:"aliases"` Aliases map[string]string `yaml:"aliases"`
Score capture.ScoreCfg `yaml:"score"` Score capture.ScoreCfg `yaml:"score"`
// MitmHosts are forced into transparent MITM via -mitm-host (suffix match).
// Transparent mode otherwise passthroughs everything except open.live.bbc.co.uk.
MitmHosts []string `yaml:"mitm_hosts"`
} }
// Base implements the boilerplate half of app.App. // Base implements the boilerplate half of app.App.
@ -54,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)
@ -94,6 +97,18 @@ func (b *Base) Score() capture.ScoreCfg {
return capture.DefaultScoreCfg().Merge(b.common.Score) return capture.DefaultScoreCfg().Merge(b.common.Score)
} }
// MitmHosts returns hosts the transparent MITM must decrypt (empty = BBC open.live only).
func (b *Base) MitmHosts() []string {
out := make([]string, 0, len(b.common.MitmHosts))
for _, h := range b.common.MitmHosts {
h = strings.TrimSpace(strings.ToLower(h))
if h != "" {
out = append(out, h)
}
}
return out
}
// Hints returns device-layout hints with this module's scoring applied. // Hints returns device-layout hints with this module's scoring applied.
func (b *Base) Hints(require ...string) capture.Hints { func (b *Base) Hints(require ...string) capture.Hints {
h := capture.DefaultHints() h := capture.DefaultHints()

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

@ -219,6 +219,8 @@ type Node struct {
Class string Class string
ResourceID string ResourceID string
Clickable bool Clickable bool
Selected bool
Checked bool
X1, Y1 int X1, Y1 int
X2, Y2 int X2, Y2 int
} }
@ -260,6 +262,8 @@ func parseNodes(xml string) []Node {
Class: attr("class"), Class: attr("class"),
ResourceID: attr("resource-id"), ResourceID: attr("resource-id"),
Clickable: attr("clickable") == "true", Clickable: attr("clickable") == "true",
Selected: attr("selected") == "true",
Checked: attr("checked") == "true",
X1: x1, Y1: y1, X2: x2, Y2: y2, X1: x1, Y1: y1, X2: x2, Y2: y2,
}) })
} }

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).
@ -83,6 +83,25 @@ type TransparentMITM interface {
UseTransparentMITM() bool UseTransparentMITM() bool
} }
// MitmHostList is implemented by apps that need extra -mitm-host entries in
// transparent mode (default MITM is only open.live.bbc.co.uk).
type MitmHostList interface {
MitmHosts() []string
}
// ChannelCaptureHints lets a module bias Wait scoring for a specific channel
// (e.g. prefer channel(e4) MPD when capturing E4 while neighbours prefetch).
type ChannelCaptureHints interface {
CaptureHintsFor(channel string) capture.Hints
}
// RequireWVD is implemented by apps that refuse MPD-only captures. When true,
// `drm capture --app …` must pass --wvd; phonecap will not soft-save a session
// without keys.
type RequireWVD interface {
RequireWVD() bool
}
var ( var (
mu sync.RWMutex mu sync.RWMutex
registry = map[string]func() (App, error){} registry = map[string]func() (App, error){}

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.
@ -24,6 +24,9 @@ type Hints struct {
// Score ranks candidate manifest URLs. Zero value falls back to // Score ranks candidate manifest URLs. Zero value falls back to
// DefaultScoreCfg, which has no provider hosts. // DefaultScoreCfg, which has no provider hosts.
Score ScoreCfg Score ScoreCfg
// PreferURLContains boosts MPDs whose URL contains any of these substrings
// (e.g. channel(e4) for Channel 4 Live). Used when an app prefetches neighbours.
PreferURLContains []string
} }
// RemoteCapPaths are the on-device locations the MITM may persist its capture // RemoteCapPaths are the on-device locations the MITM may persist its capture
@ -59,10 +62,23 @@ func DefaultPassiveHints() Hints {
// score applies the hints' URL scoring, defaulting when unset. // score applies the hints' URL scoring, defaulting when unset.
func (h Hints) score(u string) int { func (h Hints) score(u string) int {
var sc int
if len(h.Score.Deny) == 0 && len(h.Score.Hosts) == 0 { if len(h.Score.Deny) == 0 && len(h.Score.Hosts) == 0 {
return DefaultScoreCfg().Score(u) sc = DefaultScoreCfg().Score(u)
} else {
sc = h.Score.Score(u)
} }
return h.Score.Score(u) if sc <= 0 || len(h.PreferURLContains) == 0 {
return sc
}
low := strings.ToLower(u)
for _, p := range h.PreferURLContains {
p = strings.ToLower(strings.TrimSpace(p))
if p != "" && strings.Contains(low, p) {
return sc + 1000
}
}
return sc
} }
// Data is the merged capture payload before key fetch. // Data is the merged capture payload before key fetch.
@ -70,6 +86,25 @@ type Data map[string]string
func (d Data) Get(k string) string { return d[k] } func (d Data) Get(k string) string { return d[k] }
// preferSatisfied is true when no PreferURLContains is set, or the chosen MPD
// matches one of the preferred substrings.
func preferSatisfied(cap Data, hints Hints) bool {
if len(hints.PreferURLContains) == 0 {
return true
}
mpd := strings.ToLower(strings.TrimSpace(cap["mpd"]))
if mpd == "" {
return false
}
for _, p := range hints.PreferURLContains {
p = strings.ToLower(strings.TrimSpace(p))
if p != "" && strings.Contains(mpd, p) {
return true
}
}
return false
}
// Wait pulls device JSON + local mirrored log until required fields exist. // Wait pulls device JSON + local mirrored log until required fields exist.
func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout time.Duration) (Data, error) { func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout time.Duration) (Data, error) {
deadline := time.Now().Add(timeout) deadline := time.Now().Add(timeout)
@ -104,7 +139,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
enrichFromProxyLog(cap, logText, hints) enrichFromProxyLog(cap, logText, hints)
if hints.BestEffort { if hints.BestEffort {
if hasUseful(cap, hints) { if hasUseful(cap, hints) && preferSatisfied(cap, hints) {
_ = os.WriteFile(localCap, mustJSON(cap), 0o644) _ = os.WriteFile(localCap, mustJSON(cap), 0o644)
return cap, nil return cap, nil
} }
@ -116,7 +151,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
break break
} }
} }
if !missing { if !missing && preferSatisfied(cap, hints) {
_ = os.WriteFile(localCap, mustJSON(cap), 0o644) _ = os.WriteFile(localCap, mustJSON(cap), 0o644)
return cap, nil return cap, nil
} }
@ -125,7 +160,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
have := []string{} have := []string{}
keys := hints.Require keys := hints.Require
if hints.BestEffort { if hints.BestEffort {
keys = []string{"mpd", "license_url", "pssh", "auth", "pid"} keys = []string{"mpd", "license_url", "pssh", "auth", "pid", "license_body"}
} }
for _, k := range keys { for _, k := range keys {
if cap[k] != "" { if cap[k] != "" {
@ -225,7 +260,8 @@ func enrichFromProxyLog(cap Data, logText string, hints Hints) {
if sc <= 0 { if sc <= 0 {
return return
} }
if sc > bestScore { // Prefer higher score; on a tie keep the later URL (last stream played).
if sc > bestScore || (sc == bestScore && sc > 0) {
bestScore = sc bestScore = sc
bestMPD = u bestMPD = u
} }

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
@ -22,12 +22,16 @@ type Describe struct {
KeyMode string `json:"key_mode"` KeyMode string `json:"key_mode"`
ProxyBin string `json:"proxy_bin,omitempty"` ProxyBin string `json:"proxy_bin,omitempty"`
CAHash string `json:"ca_hash,omitempty"` CAHash string `json:"ca_hash,omitempty"`
TransparentMITM bool `json:"transparent_mitm"` TransparentMITM bool `json:"transparent_mitm"`
Rewriter string `json:"rewriter,omitempty"` MitmHosts []string `json:"mitm_hosts,omitempty"`
Channels []Channel `json:"channels"` Rewriter string `json:"rewriter,omitempty"`
Require []string `json:"require,omitempty"` Channels []Channel `json:"channels"`
Score capture.ScoreCfg `json:"score,omitempty"` Require []string `json:"require,omitempty"`
HasCatalog bool `json:"has_catalog"` Score capture.ScoreCfg `json:"score,omitempty"`
ValuesPath string `json:"values_path,omitempty"` // ChannelMPDPrefer maps channel id → URL substrings that must win Wait scoring.
ValuesLoaded bool `json:"values_loaded"` ChannelMPDPrefer map[string][]string `json:"channel_mpd_prefer,omitempty"`
HasCatalog bool `json:"has_catalog"`
RequireWVD bool `json:"require_wvd,omitempty"`
ValuesPath string `json:"values_path,omitempty"`
ValuesLoaded bool `json:"values_loaded"`
} }

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.
@ -82,6 +82,41 @@ func (r *RemoteApp) MPDRewriter() mpd.Rewriter {
func (r *RemoteApp) UseTransparentMITM() bool { return r.Desc.TransparentMITM } func (r *RemoteApp) UseTransparentMITM() bool { return r.Desc.TransparentMITM }
func (r *RemoteApp) RequireWVD() bool { return r.Desc.RequireWVD }
func (r *RemoteApp) MitmHosts() []string {
out := make([]string, 0, len(r.Desc.MitmHosts))
for _, h := range r.Desc.MitmHosts {
h = strings.TrimSpace(strings.ToLower(h))
if h != "" {
out = append(out, h)
}
}
return out
}
func (r *RemoteApp) CaptureHintsFor(channel string) capture.Hints {
h := r.CaptureHints()
if len(r.Desc.ChannelMPDPrefer) == 0 {
return h
}
id := strings.ToLower(strings.TrimSpace(channel))
if prefs, ok := r.Desc.ChannelMPDPrefer[id]; ok && len(prefs) > 0 {
h.PreferURLContains = append([]string{}, prefs...)
return h
}
// Alias / label fallback: match prefer keys against known channel ids only.
for _, ch := range r.Desc.Channels {
if strings.EqualFold(ch.ID, id) || strings.EqualFold(ch.Label, id) {
if prefs, ok := r.Desc.ChannelMPDPrefer[ch.ID]; ok && len(prefs) > 0 {
h.PreferURLContains = append([]string{}, prefs...)
}
break
}
}
return h
}
func (r *RemoteApp) RewriterName() string { func (r *RemoteApp) RewriterName() string {
if r.Desc.Rewriter == "" { if r.Desc.Rewriter == "" {
return "none" return "none"
@ -115,10 +150,13 @@ func (r *RemoteApp) ValuesPath() string {
// Ensure RemoteApp satisfies the interfaces capture / catalog use. // Ensure RemoteApp satisfies the interfaces capture / catalog use.
var ( var (
_ app.App = (*RemoteApp)(nil) _ app.App = (*RemoteApp)(nil)
_ app.TransparentMITM = (*RemoteApp)(nil) _ app.TransparentMITM = (*RemoteApp)(nil)
_ app.StreamDefaults = (*RemoteApp)(nil) _ app.RequireWVD = (*RemoteApp)(nil)
_ app.Catalog = (*RemoteApp)(nil) _ app.MitmHostList = (*RemoteApp)(nil)
_ app.ChannelCaptureHints = (*RemoteApp)(nil)
_ app.StreamDefaults = (*RemoteApp)(nil)
_ app.Catalog = (*RemoteApp)(nil)
) )
func (r *RemoteApp) VideoSelect() string { return "" } func (r *RemoteApp) VideoSelect() string { return "" }

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
@ -199,17 +199,28 @@ func Run(opt Options) (res Result, err error) {
proxyBin, caHash := resolveProxy(a, root) proxyBin, caHash := resolveProxy(a, root)
hints := a.CaptureHints() hints := a.CaptureHints()
if chHints, ok := a.(app.ChannelCaptureHints); ok && strings.TrimSpace(opt.Channel) != "" {
hints = chHints.CaptureHintsFor(opt.Channel)
}
useTProxy := false useTProxy := false
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
if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false); err != nil { var mitmHosts []string
if mh, ok := a.(app.MitmHostList); ok {
mitmHosts = mh.MitmHosts()
}
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)
@ -231,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 == "" {
@ -253,80 +253,168 @@ func Run(opt Options) (res Result, err error) {
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop) go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
defer close(stop) defer close(stop)
need := hints.Require
if len(need) == 0 {
need = []string{"manifest"}
}
fmt.Printf("[*] Waiting for %s…\n", strings.Join(need, " + "))
fmt.Println(" watch:", localLog)
capData, err := capture.Wait(c, hints, localLog, localCap, opt.Wait)
if err != nil {
return res, err
}
licenseURL := first(capData.Get("license_url"), a.LicenseURL())
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode)) keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
if keyMode == "" || keyMode == "auto" { if keyMode == "" || keyMode == "auto" {
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode())) keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
} }
// Brightcove/HLS: proxy often captures license + master URL but not PSSH. needsKeys := keyMode != "none" && keyMode != "clear"
// Skip for clear/MPD-only apps (KeyMode none).
if keyMode != "none" && keyMode != "clear" { // DRM apps: wait up to 90s for Widevine traffic, then force-stop and retry
if strings.TrimSpace(capData.Get("pssh")) == "" && strings.TrimSpace(capData.Get("mpd")) != "" { // (max 3). Clear / MPD-only apps keep a single wait of opt.Wait.
if pssh, err := extractHLSPSSH(capData.Get("mpd")); err == nil && pssh != "" { attempts := 1
capData["pssh"] = pssh waitPer := opt.Wait
} else if err != nil { if needsKeys {
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err) attempts = 3
} waitPer = 90 * time.Second
if opt.Wait > 0 && opt.Wait < waitPer {
waitPer = opt.Wait
} }
} }
mpdURL := strings.TrimSpace(capData.Get("mpd")) need := hints.Require
// Console: always surface the MPD we will use (BBC clear streams only need this). if len(need) == 0 {
fmt.Println() need = []string{"manifest"}
fmt.Println("========== MPD ==========")
if mpdURL != "" {
fmt.Println(mpdURL)
} else {
fmt.Println("(none)")
} }
fmt.Println("=========================")
fmt.Println() var (
fmt.Println("[+] Capture:") capData capture.Data
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh"} { licenseURL string
v := capData.Get(k) mpdURL string
if k == "license_url" { key string
v = first(v, licenseURL) lastErr error
)
for attempt := 1; attempt <= attempts; attempt++ {
if attempt > 1 {
fmt.Printf("[*] Widevine attempt %d/%d — closing app and retrying…\n", attempt, attempts)
c.ForceStop(a.Package())
time.Sleep(800 * time.Millisecond)
} }
if v == "" {
// Fresh local mirrors each attempt so we do not reuse a prior MPD/PSSH.
_ = os.WriteFile(localLog, nil, 0o644)
_ = os.Remove(localCap)
if err := a.Launch(c); err != nil {
lastErr = fmt.Errorf("launch: %w", err)
continue continue
} }
label := k if !opt.NoAutoPlay {
if k == "license_url" { if err := a.AutoPlay(c, opt.Channel); err != nil {
label = "license" 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.Println(" ", label+":", trim(v, 120))
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("========== MPD ==========")
if mpdURL != "" {
fmt.Println(mpdURL)
} else {
fmt.Println("(none)")
}
fmt.Println("=========================")
fmt.Println()
fmt.Println("[+] Capture:")
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
v := capData.Get(k)
if k == "license_url" {
v = first(v, licenseURL)
}
if v == "" {
continue
}
label := k
switch k {
case "license_url":
label = "license"
case "license_body":
label = "license_body"
v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
}
fmt.Println(" ", label+":", trim(v, 120))
}
if !needsKeys {
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
lastErr = nil
break
}
k, kerr := fetchKey(opt, root, capData, licenseURL)
if kerr != nil {
lastErr = kerr
// 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")
if softOK {
if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
c.ForceStop(a.Package())
continue
}
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
key = ""
lastErr = nil
break
}
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", " | "))
lastErr = nil
break
} }
key := "" if lastErr != nil {
if keyMode == "none" || keyMode == "clear" { if needsKeys {
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)") return res, fmt.Errorf("widevine capture failed after %d attempt(s): %w", attempts, lastErr)
} else {
var kerr error
key, kerr = fetchKey(opt, root, capData, licenseURL)
if kerr != nil {
return res, kerr
} }
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | ")) 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{
Channel: opt.Channel, Channel: opt.Channel,
PSSH: capData.Get("pssh"), PSSH: capData.Get("pssh"),
Auth: capData.Get("auth"), Auth: capData.Get("auth"),
PID: capData.Get("pid"), PID: capData.Get("pid"),
Key: key, Key: key,
MPD: mpdURL, MPD: mpdURL,
LicenseURL: licenseURL, LicenseURL: licenseURL,
LicenseBody: capData.Get("license_body"),
} }
path, err := session.Write(root, a.Name(), sess) path, err := session.Write(root, a.Name(), sess)
if err != nil { if err != nil {
@ -343,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)
@ -373,22 +517,25 @@ 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"),
PID: cap.Get("pid"), PID: cap.Get("pid"),
LicenseURL: licenseURL, LicenseURL: licenseURL,
UserAgent: opt.UserAgent, UserAgent: opt.UserAgent,
WrapJSON: cap.Get("license_body"),
} }
mode := strings.ToLower(strings.TrimSpace(opt.KeyMode)) mode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
if mode == "" || mode == "auto" { if mode == "" || mode == "auto" {
@ -399,6 +546,11 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
} }
} }
} }
// RedBee / wrapped JSON: if the phone posted a license body, prefer wrap
// even when the module still says raw (migration safety).
if mode == "raw" && strings.TrimSpace(wopt.WrapJSON) != "" {
mode = "wrap"
}
switch mode { switch mode {
case "raw": case "raw":
// Brightcove returns multiple CONTENT keys; NRE needs all of them. // Brightcove returns multiple CONTENT keys; NRE needs all of them.
@ -407,11 +559,22 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
return "", err return "", err
} }
return strings.Join(keys, "\n"), nil return strings.Join(keys, "\n"), nil
case "wrap":
keys, err := wvkey.FetchWrapAll(wopt)
if err != nil {
return "", err
}
return strings.Join(keys, "\n"), nil
default: default:
return wvkey.Fetch(wopt) return wvkey.Fetch(wopt)
} }
} }
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) != "" {
@ -449,6 +612,62 @@ func extractHLSPSSH(masterURL string) (string, error) {
return "", fmt.Errorf("no Widevine PSSH in HLS master") return "", fmt.Errorf("no Widevine PSSH in HLS master")
} }
// PlayReady system id fragment inside a base64 PSSH box.
const playReadyPSSHFrag = "AAAAAmgTweZhAQoarkuZb4IhflQ"
// Widevine system id fragment inside a base64 PSSH box.
const widevinePSSHFrag = "AAAAA7e+LqXnWSs6jyCfc1R0h7Q"
func isPlayReadyPSSH(b64 string) bool {
return strings.Contains(b64, playReadyPSSHFrag) && !strings.Contains(b64, widevinePSSHFrag)
}
func extractWidevinePSSHFromMPD(mpdURL string) (string, error) {
resp, err := http.Get(mpdURL)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return "", fmt.Errorf("HTTP %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return "", err
}
mpd := string(body)
lower := strings.ToLower(mpd)
const (
wvUUID = "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
openTag = "<cenc:pssh"
closeTag = "</cenc:pssh>"
)
searchFrom := 0
for {
i := strings.Index(lower[searchFrom:], openTag)
if i < 0 {
break
}
i += searchFrom
j := strings.Index(mpd[i:], ">")
k := strings.Index(lower[i:], closeTag)
if j < 0 || k < 0 || k <= j {
break
}
val := strings.TrimSpace(mpd[i+j+1 : i+k])
windowStart := i - 400
if windowStart < 0 {
windowStart = 0
}
window := lower[windowStart : i+j]
if strings.Contains(window, wvUUID) || strings.Contains(val, widevinePSSHFrag) {
return val, nil
}
searchFrom = i + k + len(closeTag)
}
return "", fmt.Errorf("no Widevine cenc:pssh in MPD")
}
func trim(s string, n int) string { func trim(s string, n int) string {
if len(s) <= n { if len(s) <= n {
return s return s

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),
@ -478,11 +478,17 @@ const (
// StartTransparent pushes appproxy in -transparent mode (no Wi‑Fi http_proxy), // StartTransparent pushes appproxy in -transparent mode (no Wi‑Fi http_proxy),
// installs iptables UID REDIRECT for pkg, and writes captures under remoteDir. // installs iptables UID REDIRECT for pkg, and writes captures under remoteDir.
func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool) error { // mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent
// mode otherwise only MITMs open.live.bbc.co.uk.
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)
@ -518,6 +524,20 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
_, _ = c.Shell("mkdir", "-p", remoteDir) _, _ = c.Shell("mkdir", "-p", remoteDir)
_, _ = c.Shell("rm", "-f", remoteDir+"/cap.json", remoteDir+"/traffic.jsonl", remoteDir+"/appproxy.log") _, _ = c.Shell("rm", "-f", remoteDir+"/cap.json", remoteDir+"/traffic.jsonl", remoteDir+"/appproxy.log")
mitmFlags := ""
seen := map[string]bool{}
for _, h := range mitmHosts {
h = strings.TrimSpace(strings.ToLower(h))
if h == "" || seen[h] || !safeMitmHost(h) {
continue
}
seen[h] = true
mitmFlags += " -mitm-host " + h
}
if mitmFlags != "" {
fmt.Printf("[*] Force MITM hosts:%s\n", mitmFlags)
}
starter := "#!/system/bin/sh\n" + starter := "#!/system/bin/sh\n" +
"mkdir -p '" + remoteDir + "'\n" + "mkdir -p '" + remoteDir + "'\n" +
"exec " + RemoteBin + "exec " + RemoteBin +
@ -529,6 +549,7 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
" -dns 1.1.1.1,1.0.0.1,8.8.8.8" + " -dns 1.1.1.1,1.0.0.1,8.8.8.8" +
" -log-all" + " -log-all" +
" -v" + " -v" +
mitmFlags +
"\n" "\n"
tmp := filepath.Join(os.TempDir(), "start_appproxy_tproxy.sh") tmp := filepath.Join(os.TempDir(), "start_appproxy_tproxy.sh")
if err := os.WriteFile(tmp, []byte(starter), 0o755); err != nil { if err := os.WriteFile(tmp, []byte(starter), 0o755); err != nil {
@ -597,6 +618,20 @@ func StopTransparent(c *adb.Client) {
fmt.Println("[*] transparent capture stopped") fmt.Println("[*] transparent capture stopped")
} }
// safeMitmHost allows only hostname characters so flags stay shell-safe.
func safeMitmHost(h string) bool {
if h == "" || len(h) > 253 {
return false
}
for _, r := range h {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '.' || r == '-' {
continue
}
return false
}
return true
}
// ResetOptions controls drm proxy reset. // ResetOptions controls drm proxy reset.
type ResetOptions struct { type ResetOptions struct {
KeepCaptures bool // leave /data/local/tmp/capture/ KeepCaptures bool // leave /data/local/tmp/capture/

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

@ -22,6 +22,9 @@ type Session struct {
KeyHex string `json:"key_hex,omitempty"` KeyHex string `json:"key_hex,omitempty"`
MPD string `json:"mpd,omitempty"` MPD string `json:"mpd,omitempty"`
LicenseURL string `json:"license_url,omitempty"` LicenseURL string `json:"license_url,omitempty"`
// LicenseBody is the phone's JSON license POST (RedBee wrap). Used to
// re-issue with a local CDM challenge.
LicenseBody string `json:"license_body,omitempty"`
} }
// Write creates outputs/<app>/<stamp>/session.json (+ field txt files + latest). // Write creates outputs/<app>/<stamp>/session.json (+ field txt files + latest).
@ -51,11 +54,12 @@ func Write(root, app string, s Session) (string, error) {
return "", err return "", err
} }
fields := map[string]string{ fields := map[string]string{
"pssh": s.PSSH, "pssh": s.PSSH,
"auth": s.Auth, "auth": s.Auth,
"pid": s.PID, "pid": s.PID,
"key": s.Key, "key": s.Key,
"mpd": s.MPD, "mpd": s.MPD,
"license_body": s.LicenseBody,
} }
for name, val := range fields { for name, val := range fields {
if val == "" { if val == "" {

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

@ -19,11 +19,13 @@ type Options struct {
PID string PID string
LicenseURL string LicenseURL string
UserAgent string UserAgent string
// WrapJSON is a captured phone license POST body (RedBee / wrapped Widevine).
WrapJSON string
} }
// Fetch runs wvkey.py --quiet (ModularDrm) and returns the first KID:KEY line. // Fetch runs wvkey.py --quiet (ModularDrm) and returns the first KID:KEY line.
func Fetch(opt Options) (string, error) { func Fetch(opt Options) (string, error) {
lines, err := run(opt, false, false) lines, err := run(opt, "modulardrm", false)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -35,7 +37,7 @@ func Fetch(opt Options) (string, error) {
// FetchRaw runs wvkey.py --mode raw (Brightcove / octet-stream license). // FetchRaw runs wvkey.py --mode raw (Brightcove / octet-stream license).
func FetchRaw(opt Options) (string, error) { func FetchRaw(opt Options) (string, error) {
lines, err := run(opt, true, false) lines, err := run(opt, "raw", false)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -47,18 +49,30 @@ func FetchRaw(opt Options) (string, error) {
// FetchRawAll returns every CONTENT key from a raw license response. // FetchRawAll returns every CONTENT key from a raw license response.
func FetchRawAll(opt Options) ([]string, error) { func FetchRawAll(opt Options) ([]string, error) {
return run(opt, true, true) return run(opt, "raw", true)
} }
func run(opt Options, raw, all bool) ([]string, error) { // FetchWrapAll re-POSTs a captured JSON license body with a local CDM challenge.
py := opt.Python func FetchWrapAll(opt Options) ([]string, error) {
if py == "" { return run(opt, "wrap", true)
py = findPython() }
}
func run(opt Options, mode string, all bool) ([]string, error) {
py := resolvePython(opt.Python)
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")
} }
@ -73,12 +87,19 @@ func run(opt Options, raw, all bool) ([]string, error) {
"--wvd", opt.WVD, "--wvd", opt.WVD,
"--pssh", opt.PSSH, "--pssh", opt.PSSH,
"--license-url", opt.LicenseURL, "--license-url", opt.LicenseURL,
"--mode", mode,
"--quiet", "--quiet",
} }
if raw { switch mode {
args = append(args, "--mode", "raw") case "raw":
} else { // no extra fields
args = append(args, "--mode", "modulardrm", "--auth", opt.Auth, "--pid", opt.PID) case "wrap":
if strings.TrimSpace(opt.WrapJSON) == "" {
return nil, fmt.Errorf("wvkey wrap mode requires a captured license_body from the phone (playback must start so RedBee gets a token)")
}
args = append(args, "--wrap-json", opt.WrapJSON)
default:
args = append(args, "--auth", opt.Auth, "--pid", opt.PID)
} }
if all { if all {
args = append(args, "--all") args = append(args, "--all")
@ -106,12 +127,30 @@ func run(opt Options, raw, 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

@ -44,8 +44,11 @@ type capture struct {
LicenseURL string `json:"license_url,omitempty"` LicenseURL string `json:"license_url,omitempty"`
Auth string `json:"auth,omitempty"` Auth string `json:"auth,omitempty"`
PID string `json:"pid,omitempty"` PID string `json:"pid,omitempty"`
// LicenseBody is the raw JSON POST body from the phone's license request
// (RedBee / wrapped Widevine). Used to re-issue with a local CDM challenge.
LicenseBody string `json:"license_body,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"` UpdatedAt string `json:"updated_at,omitempty"`
PSSH string `json:"pssh,omitempty"` // first short Widevine PSSH seen in an MPD body PSSH string `json:"pssh,omitempty"` // Widevine cenc:pssh from an MPD body
} }
type licenseBody struct { type licenseBody struct {
@ -324,6 +327,7 @@ func main() {
if json.Unmarshal(body, &lb) == nil { if json.Unmarshal(body, &lb) == nil {
pid = lb.GetWidevineLicense.ReleasePID pid = lb.GetWidevineLicense.ReleasePID
} }
bodyStr := string(body)
cap.set(func(c *capture) { cap.set(func(c *capture) {
c.LicenseURL = url c.LicenseURL = url
if auth != "" { if auth != "" {
@ -332,10 +336,19 @@ func main() {
if pid != "" { if pid != "" {
c.PID = pid c.PID = pid
} }
// Keep JSON license wrappers (RedBee / wrapped Widevine) so the
// host can swap in a local CDM challenge and re-POST.
if len(body) > 0 && (strings.HasPrefix(strings.TrimSpace(bodyStr), "{") ||
strings.Contains(strings.ToLower(req.Header.Get("Content-Type")), "json")) {
c.LicenseBody = bodyStr
}
}) })
if *verbose { if *verbose {
log.Printf("[LIC] pid=%s auth=%s", pid, trim(auth, 40)) log.Printf("[LIC] pid=%s auth=%s body=%d", pid, trim(auth, 40), len(body))
log.Printf(" %s", trim(url, 120)) log.Printf(" %s", trim(url, 120))
if len(body) > 0 {
log.Printf(" body: %s", trim(bodyStr, 200))
}
} }
if *logAll { if *logAll {
traffic.write(map[string]any{ traffic.write(map[string]any{
@ -348,7 +361,7 @@ func main() {
"authorization": trim(auth, 200), "authorization": trim(auth, 200),
"pid": pid, "pid": pid,
"body_len": len(body), "body_len": len(body),
"body_head": trim(string(body), 240), "body_head": trim(bodyStr, 240),
}) })
} }
} }
@ -1205,34 +1218,74 @@ func trim(s string, n int) string {
return s[:n] + "…" return s[:n] + "…"
} }
// Prefer the short Widevine PSSH (AAAASnBzc2g…) over the giant PlayReady blob. // Prefer a Widevine cenc:pssh (system id edef8ba9-…) over PlayReady / Marlin.
// Channel 4 MPDs list PlayReady first; taking "any cenc:pssh" yields a useless blob.
func firstShortPSSH(mpd string) string { func firstShortPSSH(mpd string) string {
const marker = "AAAASnBzc2g" const (
idx := strings.Index(mpd, marker) wvUUID = "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
if idx < 0 { wvUUIDBare = "edef8ba979d64acea3c827dcd51d21ed"
// any cenc:pssh content openTag = "<cenc:pssh"
const open = "<cenc:pssh" closeTag = "</cenc:pssh>"
i := strings.Index(mpd, open) )
lower := strings.ToLower(mpd)
searchFrom := 0
for {
i := strings.Index(lower[searchFrom:], openTag)
if i < 0 { if i < 0 {
return "" break
} }
i += searchFrom
j := strings.Index(mpd[i:], ">") j := strings.Index(mpd[i:], ">")
k := strings.Index(mpd[i:], "</cenc:pssh>") k := strings.Index(lower[i:], closeTag)
if j < 0 || k < 0 || k <= j { if j < 0 || k < 0 || k <= j {
return "" break
} }
return strings.TrimSpace(mpd[i+j+1 : i+k]) val := strings.TrimSpace(mpd[i+j+1 : i+k])
} // Prefer the Widevine ContentProtection block: UUID appears just before
end := idx // this pssh, or the decoded box itself starts with the Widevine system id.
for end < len(mpd) { windowStart := i - 400
c := mpd[end] if windowStart < 0 {
if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=' { windowStart = 0
end++
continue
} }
break window := lower[windowStart : i+j]
if strings.Contains(window, wvUUID) || strings.Contains(window, wvUUIDBare) || looksLikeWidevinePSSH(val) {
return val
}
searchFrom = i + k + len(closeTag)
} }
return mpd[idx:end] // Fallback: legacy short BBC-style marker, then first cenc:pssh.
const marker = "AAAASnBzc2g"
if idx := strings.Index(mpd, marker); idx >= 0 {
end := idx
for end < len(mpd) {
c := mpd[end]
if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=' {
end++
continue
}
break
}
return mpd[idx:end]
}
i := strings.Index(lower, openTag)
if i < 0 {
return ""
}
j := strings.Index(mpd[i:], ">")
k := strings.Index(lower[i:], closeTag)
if j < 0 || k < 0 || k <= j {
return ""
}
return strings.TrimSpace(mpd[i+j+1 : i+k])
}
// looksLikeWidevinePSSH reports whether a base64 PSSH box uses the Widevine system id.
func looksLikeWidevinePSSH(b64 string) bool {
// Widevine system id bytes as they appear after base64 of a typical PSSH header.
// Full decode is avoided here to keep the on-device binary dependency-free;
// the standard Widevine UUID base64 fragment inside PSSH boxes is stable.
const wvFrag = "AAAAA7e+LqXnWSs6jyCfc1R0h7Q" // edef8ba9-79d6-4ace-a3c8-27dcd51d21ed
return strings.Contains(b64, wvFrag)
} }
func loadOrCreateCA(certPath, keyPath string) (*tls.Certificate, error) { func loadOrCreateCA(certPath, keyPath string) (*tls.Certificate, error) {

View file

@ -19,10 +19,13 @@ uid_for_package() {
echo "$uid" echo "$uid"
} }
# -w waits for the xtables lock (needed when grab-all restarts transparent MITM quickly).
IPT="iptables -w 5"
stop_rules() { stop_rules() {
iptables -t nat -D OUTPUT -j "$CHAIN" 2>/dev/null || true $IPT -t nat -D OUTPUT -j "$CHAIN" 2>/dev/null || true
iptables -t nat -F "$CHAIN" 2>/dev/null || true $IPT -t nat -F "$CHAIN" 2>/dev/null || true
iptables -t nat -X "$CHAIN" 2>/dev/null || true $IPT -t nat -X "$CHAIN" 2>/dev/null || true
echo "STOPPED" echo "STOPPED"
} }
@ -41,17 +44,17 @@ start_rules() {
fi fi
stop_rules >/dev/null stop_rules >/dev/null
iptables -t nat -N "$CHAIN" $IPT -t nat -N "$CHAIN"
# Never redirect the mitm itself (loop). # Never redirect the mitm itself (loop).
if [ -n "$proxy_uid" ]; then if [ -n "$proxy_uid" ]; then
iptables -t nat -A "$CHAIN" -m owner --uid-owner "$proxy_uid" -j RETURN $IPT -t nat -A "$CHAIN" -m owner --uid-owner "$proxy_uid" -j RETURN
fi fi
# Skip localhost / link-local. # Skip localhost / link-local.
iptables -t nat -A "$CHAIN" -d 127.0.0.0/8 -j RETURN $IPT -t nat -A "$CHAIN" -d 127.0.0.0/8 -j RETURN
iptables -t nat -A "$CHAIN" -d 10.0.0.0/8 -j RETURN 2>/dev/null || true $IPT -t nat -A "$CHAIN" -d 10.0.0.0/8 -j RETURN 2>/dev/null || true
# Redirect only the target app's HTTPS. # Redirect only the target app's HTTPS.
iptables -t nat -A "$CHAIN" -p tcp -m owner --uid-owner "$uid" --dport 443 -j REDIRECT --to-ports "$port" $IPT -t nat -A "$CHAIN" -p tcp -m owner --uid-owner "$uid" --dport 443 -j REDIRECT --to-ports "$port"
iptables -t nat -A OUTPUT -j "$CHAIN" $IPT -t nat -A OUTPUT -j "$CHAIN"
echo "STARTED pkg=$pkg uid=$uid port=$port proxy_uid=${proxy_uid:-unknown}" echo "STARTED pkg=$pkg uid=$uid port=$port proxy_uid=${proxy_uid:-unknown}"
} }

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)
} }
@ -258,6 +258,14 @@ func clearProxyCmd(args []string) {
proxy.ClearHTTPProxy(c) proxy.ClearHTTPProxy(c)
} }
type stringList []string
func (s *stringList) String() string { return strings.Join(*s, ",") }
func (s *stringList) Set(v string) error {
*s = append(*s, v)
return nil
}
func transparentCmd(args []string) { func transparentCmd(args []string) {
fs := flag.NewFlagSet("transparent", flag.ExitOnError) fs := flag.NewFlagSet("transparent", flag.ExitOnError)
pkg := fs.String("package", "", "app package to redirect (e.g. bbc.iplayer.android)") pkg := fs.String("package", "", "app package to redirect (e.g. bbc.iplayer.android)")
@ -266,6 +274,8 @@ func transparentCmd(args []string) {
reinject := fs.Bool("reinject", false, "Magisk-reinject CA before start (slow; CA usually already mounted)") reinject := fs.Bool("reinject", false, "Magisk-reinject CA before start (slow; CA usually already mounted)")
port := fs.String("port", "8080", "transparent listen port on device") port := fs.String("port", "8080", "transparent listen port on device")
noTail := fs.Bool("no-tail", false, "start only; do not wait / pull on Ctrl+C") noTail := fs.Bool("no-tail", false, "start only; do not wait / pull on Ctrl+C")
var mitmHosts stringList
fs.Var(&mitmHosts, "mitm-host", "force MITM for this host (repeatable; e.g. play.dar.itv.com)")
c := clientFrom(fs, args) c := clientFrom(fs, args)
if err := c.EnsureDevice(); err != nil { if err := c.EnsureDevice(); err != nil {
fatal(err) fatal(err)
@ -286,7 +296,7 @@ func transparentCmd(args []string) {
remoteDir := "/data/local/tmp/capture/" + *pkg remoteDir := "/data/local/tmp/capture/" + *pkg
fmt.Printf("[*] Transparent capture for %s → %s\n", *pkg, remoteDir) fmt.Printf("[*] Transparent capture for %s → %s\n", *pkg, remoteDir)
if err := proxy.StartTransparent(c, local, *pkg, *port, remoteDir, *reinject); err != nil { if err := proxy.StartTransparent(c, local, *pkg, *port, remoteDir, *reinject, mitmHosts...); err != nil {
fatal(err) fatal(err)
} }
fmt.Println("[+] running. Leave UK VPN ON. Open the app and play.") fmt.Println("[+] running. Leave UK VPN ON. Open the app and play.")

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