Compare commits

..

No commits in common. "main" and "v0.0.4" have entirely different histories.
main ... v0.0.4

256 changed files with 2142 additions and 34002 deletions

View file

@ -1,85 +0,0 @@
# Build per-module zip assets and attach them to a Forgejo release.
#
# Trigger: push a modules version tag
# git tag modules-v1.0.0 && git push origin modules-v1.0.0
name: modules-release
on:
push:
tags:
- "modules-v*"
jobs:
build-and-upload:
runs-on: docker
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version-file: apps/proxy/device/go.mod
cache: false
- name: Install zip
run: apt-get update && apt-get install -y zip
- name: Build module zips
run: |
chmod +x scripts/build-modules-release.sh
./scripts/build-modules-release.sh "${{ github.ref_name }}"
ls -la dist/release
- name: Upload to Forgejo release
uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2
with:
direction: upload
url: https://git.nulldrm.com
repo: ${{ github.repository }}
token: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ github.ref_name }}
sha: ${{ github.sha }}
release-dir: dist/release
title: ${{ github.ref_name }}
override: true
release-notes: |
External provider modules for Null DRM (`modules-v*` release).
| Asset | Contents |
|---|---|
| `bbc.zip` | BBC iPlayer CLI + `module.yaml` (universal) |
| `rte.zip` | RTÉ Player 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 |
Unpack each zip into `modules/<name>/` (e.g. `bbc.zip` → `modules/bbc/`).
Each zip contains `module.yaml` only (publish template renamed — no
`module-publish.yaml`). Fill sensitive fields in `module.yaml`.
Host `drm` is released separately on `v*` tags.
Phone capture still needs Magisk + `drm proxy install-ca --reinject`.
- name: Announce on Telegram
env:
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
# Private DM chat (@error404developer). Override via secret if needed.
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
RELEASE_TAG: ${{ github.ref_name }}
RELEASE_KIND: modules
RELEASE_URL: https://git.nulldrm.com/${{ github.repository }}/releases/tag/${{ github.ref_name }}
run: |
if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
echo "[!] TELEGRAM_BOT_TOKEN secret missing — skip announce"
exit 0
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
./scripts/notify-telegram.sh "${{ github.ref_name }}"

View file

@ -1,16 +1,7 @@
# Build multi-platform streamd binaries + Android MITM and attach them to a Forgejo release.
# Build multi-platform drm binaries + Android MITM and attach them to a Forgejo release.
#
# Triggers:
# Stable: git tag v1.2.3 && git push origin v1.2.3
# Beta: git tag v1.2.3-beta.1 && git push origin v1.2.3-beta.1
#
# Each version tag gets its own release. CI also retargets a rolling channel tag:
# vX.Y.Z → release + update `stable` (always-latest download URL)
# vX.Y.Z-<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
# Trigger: push a version tag
# git tag v1.2.3 && git push origin v1.2.3
#
# Requires a Forgejo Actions runner registered against this instance
# (label must match runs-on below — default act_runner often uses "docker").
@ -32,42 +23,14 @@ jobs:
with:
fetch-depth: 0
- name: Classify tag (stable vs beta)
id: meta
run: |
set -euo pipefail
TAG="${{ github.ref_name }}"
# Strict SemVer: v1.2.3 = stable; v1.2.3-beta.1 / -rc.1 / -alpha.1 = beta channel
if echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
CHANNEL=stable
PRERELEASE=false
TITLE="$TAG"
NOTES_KIND=stable
elif echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+-(beta|rc|alpha)(\.[0-9]+)?$'; then
CHANNEL=beta
PRERELEASE=true
TITLE="$TAG (beta)"
NOTES_KIND=beta
else
echo "Unsupported host tag '$TAG'." >&2
echo "Use vX.Y.Z for stable or vX.Y.Z-beta.N / -rc.N / -alpha.N for beta." >&2
exit 1
fi
{
echo "channel=$CHANNEL"
echo "prerelease=$PRERELEASE"
echo "title=$TITLE"
echo "notes_kind=$NOTES_KIND"
} >> "$GITHUB_OUTPUT"
echo "tag=$TAG channel=$CHANNEL prerelease=$PRERELEASE"
- name: Setup Go
uses: actions/setup-go@v5
with:
# apps/proxy/device requires the newer toolchain; apps/cli is fine with it.
go-version-file: apps/proxy/device/go.mod
# Forgejo has no Actions cache server; setup-go cache-save hangs without one.
cache: false
cache-dependency-path: |
apps/cli/go.sum
apps/proxy/device/go.sum
- name: Build release artifacts
run: |
@ -75,104 +38,33 @@ jobs:
./scripts/build-release.sh "${{ github.ref_name }}"
ls -la dist/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
- name: Upload to Forgejo release
uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2
with:
direction: upload
# Defaults to this runner's Forgejo URL when omitted.
url: https://git.nulldrm.com
repo: ${{ github.repository }}
# Built-in job token (write:repository). Override with a PAT secret if needed.
token: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ github.ref_name }}
sha: ${{ github.sha }}
release-dir: dist/release
title: ${{ steps.meta.outputs.title }}
prerelease: ${{ steps.meta.outputs.prerelease }}
title: ${{ github.ref_name }}
override: true
release-notes-file: /tmp/release-notes.md
release-notes: |
Multi-platform `drm` host CLI + on-device MITM (`proxy-android-arm64`).
- name: Upload rolling channel release (stable / beta)
uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2
with:
direction: upload
url: https://git.nulldrm.com
repo: ${{ github.repository }}
token: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ steps.meta.outputs.channel }}
sha: ${{ github.sha }}
release-dir: dist/release
title: ${{ steps.meta.outputs.channel }} ← ${{ github.ref_name }}
prerelease: ${{ steps.meta.outputs.prerelease }}
override: true
release-notes-file: /tmp/channel-notes.md
| Asset | Platform |
|---|---|
| `drm-windows-amd64.exe` | Windows x86_64 |
| `drm-windows-arm64.exe` | Windows ARM64 |
| `drm-linux-amd64` | Linux x86_64 |
| `drm-linux-arm64` | Linux ARM64 |
| `drm-darwin-amd64` | macOS Intel |
| `drm-darwin-arm64` | macOS Apple Silicon |
| `proxy-android-arm64` | On-device MITM (push with `drm proxy`) |
| `SHA256SUMS.txt` | Checksums |
- name: Announce on Telegram
env:
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
RELEASE_TAG: ${{ github.ref_name }}
RELEASE_KIND: host
RELEASE_CHANNEL: ${{ steps.meta.outputs.channel }}
RELEASE_URL: https://git.nulldrm.com/${{ github.repository }}/releases/tag/${{ github.ref_name }}
run: |
if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
echo "[!] TELEGRAM_BOT_TOKEN secret missing — skip announce"
exit 0
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
./scripts/notify-telegram.sh "${{ github.ref_name }}"
Built with `CGO_ENABLED=0` via `scripts/build-release.sh`.
Phone capture still needs Magisk + `drm proxy install-ca --reinject`.

26
.gitignore vendored
View file

@ -218,18 +218,14 @@ apps/proxy/proxy-android-arm64
apps/proxy/rteproxy-android-arm64
# local / VPS deploy + operator scripts (test stuff; keep out of git)
deploy/
# Ignore local scripts, but keep release builders + server helpers tracked.
# Ignore local scripts, but keep the release builders tracked for Forgejo Actions.
scripts/*
!scripts/build-release.sh
!scripts/build-release.ps1
!scripts/build-modules-release.sh
!scripts/build-modules-release.ps1
!scripts/notify-telegram.sh
!scripts/notify-telegram.ps1
!scripts/streamd-bg.sh
!scripts/streamd-update.sh
# Shared library packages under apps/modules/ (imported by external module CLIs).
# module.yaml stays local; module-publish.yaml is the tracked universal template.
# phone app modules: the Go packages are tracked and compiled into bin/drm.exe,
# but most module.yaml files (package ids, Brightcove keys, origins, KIDs,
# channel maps) are local only and must never be committed.
# Exception: bbc/module.yaml is public (clear streams; package + channel map only).
apps/modules/**
!apps/modules/README.md
!apps/modules/go.mod
@ -237,17 +233,7 @@ apps/modules/**
!apps/modules/*/
!apps/modules/*/*.go
!apps/modules/*/**/*.go
!apps/modules/*/module-publish.yaml
# External providers under modules/<name>/ — host discovers/builds/runs these.
modules/**/.bin/
modules/**/module.yaml
!modules/README.md
!modules/*/
!modules/*/*.go
!modules/*/go.mod
!modules/*/go.sum
!modules/*/module-publish.yaml
!modules/*/README.md
!apps/modules/bbc/module.yaml
# local forgejo / deploy secrets
**/.env
**/.push-token

356
README.md
View file

@ -1,254 +1,154 @@
# 📺 Streamd
# DRM-Decryption
**Next-generation open-source DRM decryption for Android streaming apps.**
Capture Widevine live sessions from Android streaming apps and restream them.
Capture live sessions from phones (BBC iPlayer, RTÉ, TG4, ITVX, Channel 4, …), pull manifests
and licenses through a transparent MITM, and restream. One host binary — **`streamd`** —
plus drop-in providers under **`modules/`**.
Everything is one Go binary — `drm` — with every app module compiled in. Each
streaming app (RTE, TG4, …) is a Go package under `apps/modules/`; its secrets and
IDs live in a local, gitignored values file that you fill in yourself.
📦 Releases: [git.nulldrm.com](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases)
📚 Docs: [docs/](docs/)
- **[docs/](docs/)** — architecture, module authoring, per-provider setup
- **[docs/quickstart.md](docs/quickstart.md)** — the longer version of what follows
---
## ✨ What it does
## Quick start
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.
| Module | App | Notes |
|--------|-----|--------|
| 📺 `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
Streamd/
streamd.exe # or ./streamd on Linux/macOS
bin/proxy-android-arm64 # optional; also embedded in the release binary
modules/ # or upload zips in the streamd Modules page
bbc/ # unzip bbc.zip here
rte/
tg4/
itv/
data/ # your .wvd, optional
outputs/ # created on first run
```
On first run, `streamd` creates the install scaffold next to the exe.
### 2️⃣ Prerequisites
### 1. Prerequisites
| Need | Why |
|------|-----|
| 📱 **adb** on `PATH` | phone capture |
| 🔐 Rooted Android (Magisk) | system CA for HTTPS MITM |
| 🔑 **`.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` |
|---|---|
| **Go 1.25+** | builds everything |
| **Python 3.10+** | `apps/wvkey/wvkey.py` talks to the Widevine CDM |
| **adb** (platform-tools) on `PATH` | only for phone capture |
| A `.wvd` Widevine device file | only for fetching keys |
### 3️⃣ Install a provider
Phone capture additionally needs a rooted Android device (Magisk) so the MITM CA
can be injected into the system trust store. Catalog lookups need no phone.
Unzip into `modules/<name>/`. Edit **`module.yaml`** — fill sensitive fields only
(RTE license URL / KIDs; TG4 account + policy key + video ids). BBC / ITVX need
almost nothing extra.
```bash
streamd modules
# or: streamd --modules-dir D:\mods modules
```
### 4️⃣ Phone CA (once per device / CA)
```bash
streamd proxy install-ca --reinject
adb shell am force-stop bbc.iplayer.android # or the app you will capture
```
### 5️⃣ Capture
```bash
# BBC + NordVPN UK on the phone (transparent MITM; --channel auto-plays)
streamd capture --app bbc --channel bbcone --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)
streamd capture --app rte --channel rteone --wvd data/device.wvd
streamd capture --app tg4 --channel ioi --wvd data/device.wvd
# Catalog only (no phone) — TG4
streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
```
📁 Results land in `outputs/<app>/<stamp>/` (and `latest/`).
### 6️⃣ Clean the phone after a run
```bash
streamd proxy reset
```
Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fresh.
---
## 🧾 Command cheat sheet
```text
streamd [--modules-dir DIR] <command> …
streamd modules
streamd capture --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S]
streamd catalog --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list]
streamd proxy install-ca [--reinject] | reset [--keep-captures]
| transparent --package PKG [--mitm-host HOST]
| start | stop | push | discover | pull
streamd serve [--bind …] [--data …] [--token …]
streamd agent run|status|devices|enqueue|cancel [--config …]
```
🌍 Global: `--modules-dir DIR` or `$STREAMD_MODULES_DIR` (default: `./modules`).
🎯 `--channel` implies interactive auto-play (provider-specific Live UI flow).
---
## ⚙️ Config: publish vs local
| File | In git / zips? | Purpose |
|------|----------------|---------|
| `module-publish.yaml` | git only | Universal package, channels, UI |
| `module.yaml` | zips yes / git no | Secrets + overlays; release zips ship publish renamed |
Release module assets are `bbc.zip` / `rte.zip` / `tg4.zip` / `itv.zip` / `c4.zip` / `my5.zip`
with `module.yaml` only (no `module-publish.yaml` inside the zip).
---
## 🛠️ Building from source *(optional)*
### 2. Clone and build
```bash
git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official.git
cd Null-DRM-Official
go -C apps/cli build -o ../../bin/streamd.exe . # Windows
# Host release: .\scripts\build-release.ps1 -Version v0.1.1
# Modules: .\scripts\build-modules-release.ps1 -Version modules-v0.1.1
# Linux / macOS
go -C apps/cli build -o ../../bin/drm .
# Windows
go -C apps/cli build -o ../../bin/drm.exe .
```
More detail: [docs/quickstart.md](docs/quickstart.md) · [docs/architecture.md](docs/architecture.md) · [docs/providers/bbc.md](docs/providers/bbc.md)
Check it:
```bash
./bin/drm help
./bin/drm modules # which app modules this build contains
```
`drm modules` works immediately, but channel lists stay empty until you add
values — that is the next step.
### 3. Python CDM helper
```bash
python -m venv .venv
.venv/bin/pip install -r apps/wvkey/requirements.txt # Windows: .venv\Scripts\pip
```
Put your Widevine device file in `data/` (gitignored), e.g. `data/device.wvd`.
### 4. Fill in a module's values
Compiled-in module code carries **no** account IDs, policy keys, video IDs,
license URLs or key IDs. Those go in a gitignored file per module, which you create:
```text
apps/modules/tg4/module.yaml
apps/modules/rte/module.yaml
```
Where each value comes from:
- **[docs/providers/tg4.md](docs/providers/tg4.md)** — Brightcove account ID, policy key, video IDs
- **[docs/providers/rte.md](docs/providers/rte.md)** — license URL, origin hosts, channel KIDs
- **[docs/capture.md](docs/capture.md)** — how to discover all of it for a *new* app
Any value can be passed per-run instead of stored:
```bash
./bin/drm catalog --app tg4 --channel ioi --tg4.policy-key 'BCpkAD...'
TG4_POLICY_KEY='BCpkAD...' ./bin/drm catalog --app tg4 --channel ioi
```
### 5. Run something
```bash
# keys from a public catalog — no phone needed
./bin/drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
# phone capture: launch the app, drive it to a channel, grab license + keys
./bin/drm proxy build # once: cross-compile the on-device MITM
./bin/drm capture --app rte --channel rteone --auto-play --wvd data/device.wvd
# control plane + dashboard on http://127.0.0.1:8083
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET
# always-on refresher: watches streamd, re-captures dead channels
STREAMD_TOKEN=SECRET ./bin/drm agent run --config apps/agent/agent.yaml
```
Results land in `outputs/<app>/<timestamp>/`, with `latest/` kept as a copy.
---
## 💚 Support the project
## Subcommands
If Streamd saves you time, donations keep development going:
| Command | What it does |
|---|---|
| `drm modules` | list compiled-in app modules, their channels and config source |
| `drm capture` | one-shot phone MITM capture → `outputs/<app>/<stamp>/` |
| `drm catalog` | resolve a channel from its public catalog, no phone |
| `drm serve` | streamd: REST API + dashboard + media supervisor |
| `drm agent` | `run` / `status` / `devices` / `enqueue` / `cancel` |
| `drm proxy` | `build` / `push` / `install-ca` / `start` / `stop` / `discover` / `pull` |
| Coin | Address |
|------|---------|
| ⟠ **ETH** | `0xa6314ce4deaa8329abba301802e3f511b3fa80a6` |
| Ł **LTC** | `ltc1qpm26uccjgn4gx5pqxwzvs89mdp9hcshx9xj5a6` |
| ₿ **BTC** | `bc1qzr70ur76jhm5gjsuqelzqaskumpkhkk2ewjgha` |
Run any of them with `--help`.
Thank you 🙏
## Layout
---
```text
apps/cli/ the binary -> bin/drm
apps/modules/ app modules: Go (tracked) + module.yaml (gitignored)
apps/pkg/ shared, provider-neutral libraries
apps/capture/ phone capture command
apps/agent/ always-on key refresher
apps/streamd/ control plane: API, SQLite, dashboard, supervisor
apps/proxy/ MITM host CLI + on-device proxy source
apps/wvkey/ wvkey.py — CDM only
docs/ architecture, authoring, provider setup
data/ secrets: .wvd, CA (gitignored)
outputs/ capture sessions (gitignored)
bin/ built binaries (gitignored)
www/ static site
```
## ⚖️ Scope
## Tests
Only for services you are authorised to access, with content you have the right
to decrypt.
```bash
go -C apps/pkg test ./...
go -C apps/modules test ./...
go -C apps/streamd test ./...
```
Tests that hit a live origin are behind a build tag, so they stay out of the
normal run:
```bash
go -C apps/modules test -tags live ./rte/ -v
```
## Scope
For use only on services you are authorised to access, with content you have the
right to decrypt. [docs/architecture.md](docs/architecture.md) describes what the
system does and where it stops.

View file

@ -1,6 +1,6 @@
# agent
Always-on credentials refresher, hosted by the single binary as `streamd agent`.
Always-on credentials refresher, hosted by the single binary as `drm agent`.
```text
apps/agent/
@ -26,54 +26,38 @@ expire by themselves if the agent dies.
```bash
# terminal 1 — control plane
./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET
# terminal 2 — agent in the background (Linux / macOS / Windows)
export STREAMD_API_KEY=ndk_…
./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]
# terminal 2 — agent
export STREAMD_TOKEN=SECRET
./bin/drm agent run --config apps/agent/agent.yaml
```
```bash
./bin/streamd agent devices
./bin/streamd agent enqueue --stream tg4-ioi --reason manual
./bin/streamd agent cancel --job 3
./bin/drm agent status
./bin/drm agent devices
./bin/drm agent enqueue --stream tg4-ioi --reason manual
./bin/drm agent cancel --job 3
```
With `sync_modules: true` (default in the sample config), the agent **pulls**
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.
App modules are compiled into the binary, so there is no `modules_dir` to set. The
agent drives whichever module a stream names and contains no provider logic.
## Config
`agent.yaml` — `streamd_url`, **`api_key`** (preferred) or `token` (alias), or
env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
`max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device),
`wvd`, `user_agent`, `agent_id`, `data_dir`, `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`.
`agent.yaml` — `streamd_url`, `token` (or `STREAMD_TOKEN`), `poll_interval_sec`,
`workers`, `max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised
device), `wvd`, `user_agent`, `agent_id`, `data_dir`.
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.
`wvd` must be set or key fetches fail.
## Build
```bash
go -C apps/cli build -o ../../bin/streamd .
go -C apps/cli build -o ../../bin/drm .
# cross-compile
GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/streamd .
GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/drm .
```
**Full guide: [docs/streamd.md](../../docs/streamd.md)**

View file

@ -1,11 +1,8 @@
# Always-on credentials agent (apps/agent → bin/agent.exe)
# Default path: apps/agent/agent.yaml
streamd_url: http://localhost:8083
# Paste an operator API key from streamd → People & keys → New API key.
# 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"
streamd_url: http://127.0.0.1:8083
# Must match streamd --token / STREAMD_TOKEN (mutating API: claim, credentials).
token: "SECRET"
# Stable id across restarts (default = hostname). Required for reclaim after crash.
# agent_id: my-agent
poll_interval_sec: 30
@ -14,23 +11,8 @@ workers: 1 # concurrent ADB jobs
max_attempts: 5
capture_wait_sec: 180
devices: [] # empty = all adb "device" serials; never installs apps
# Pull modules from the streamd panel into the local cache (package.zip + yaml).
sync_modules: true
# modules_dir: # optional; default <data_dir>/modules
# modules_sync_interval_sec: 300
# 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
# wvd: data/device.wvd # path to .wvd (required for key fetch)
# user_agent: "" # optional license-request User-Agent
# App modules (rte, tg4, …) are compiled into the binary — there is no
# modules directory to point at. Their local values live in
# apps/modules/<name>/module.yaml; see apps/modules/README.md.

View file

@ -9,21 +9,16 @@ import (
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"text/tabwriter"
"streamd/apps/agent/internal/client"
"streamd/apps/agent/internal/config"
"streamd/apps/agent/internal/device"
"streamd/apps/agent/internal/modsync"
"streamd/apps/agent/internal/poller"
"streamd/apps/agent/internal/queue"
"streamd/apps/agent/internal/worker"
"streamd/apps/agent/internal/wsclient"
"streamd/modhost"
"streamd/repo"
"streamd/wvkey"
"drmdecryption/apps/agent/internal/client"
"drmdecryption/apps/agent/internal/config"
"drmdecryption/apps/agent/internal/device"
"drmdecryption/apps/agent/internal/poller"
"drmdecryption/apps/agent/internal/queue"
"drmdecryption/apps/agent/internal/worker"
"drmdecryption/apps/agent/internal/wsclient"
)
// Run dispatches an agent subcommand. args[0] is the subcommand name.
@ -39,14 +34,6 @@ func Run(args []string) error {
switch sub {
case "run":
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":
statusCmd(sub, rest)
case "devices":
@ -69,13 +56,8 @@ func Usage() {
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
Usage:
agent start [--config agent.yaml] # background (pid + log)
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 run [--config apps/agent/agent.yaml]
agent status [--config ...]
agent devices [--config ...]
agent enqueue --stream NAME [--reason manual] [--config ...]
agent cancel --job ID [--config ...]
@ -84,9 +66,6 @@ Polls streamd for enabled streams that are down / missing credentials,
enqueues jobs, claims a free phone that already has the app, captures
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.
`)
}
@ -102,14 +81,6 @@ func loadCfg(sub string, args []string) (config.Config, *flag.FlagSet) {
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 {
q, err := queue.Open(cfg.DataDir)
if err != nil {
@ -120,34 +91,10 @@ func openQueue(cfg config.Config) *queue.Store {
func runCmd(sub string, args []string) {
cfg, _ := loadCfg(sub, args)
api := newAPI(cfg)
api := client.New(cfg.StreamdURL, cfg.Token)
if err := api.Health(); err != nil {
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)
defer q.Close()
@ -156,16 +103,6 @@ func runCmd(sub string, args []string) {
} else if n > 0 {
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)
stop := make(chan struct{})
@ -179,60 +116,7 @@ func runCmd(sub string, args []string) {
}
go p.Loop(stop)
// Prefer the panel-synced modules cache for capture jobs.
if cfg.ModulesDir != "" {
if err := modhost.SetModulesDir(cfg.ModulesDir); err != nil {
log.Fatalf("modules dir: %v", err)
}
log.Printf("modules dir %s", cfg.ModulesDir)
}
var ms *modsync.Syncer
if cfg.SyncModules {
ms = &modsync.Syncer{
API: api,
ModulesDir: cfg.ModulesDir,
Interval: cfg.ModulesSyncInterval(),
Prune: cfg.ModulesPrune,
Log: log.Default(),
}
go ms.Loop(stop)
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())
// 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()
for i := 0; i < cfg.Workers; i++ {
@ -246,7 +130,6 @@ func runCmd(sub string, args []string) {
Python: cfg.Python,
WVD: cfg.WVD,
UserAgent: cfg.UserAgent,
JobBackoff: cfg.JobBackoffEnabled(),
Log: log.Default(),
}
go w.Loop(stop)
@ -267,7 +150,6 @@ func runCmd(sub string, args []string) {
func statusCmd(sub string, args []string) {
cfg, _ := loadCfg(sub, args)
printDaemonStatus(cfg)
q := openQueue(cfg)
defer q.Close()
jobs, err := q.ListRecent(40)
@ -317,7 +199,7 @@ func enqueueCmd(args []string) {
if err != nil {
log.Fatal(err)
}
api := newAPI(cfg)
api := client.New(cfg.StreamdURL, cfg.Token)
streams, err := api.ListStreams()
if err != nil {
log.Fatal(err)

View file

@ -1,177 +0,0 @@
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

@ -1,37 +0,0 @@
//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

@ -1,46 +0,0 @@
//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

@ -1,282 +0,0 @@
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

@ -1,21 +0,0 @@
//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

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

View file

@ -1,5 +1,7 @@
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@ -12,6 +14,8 @@ github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdh
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@ -19,6 +23,8 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View file

@ -3,93 +3,42 @@ package client
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"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 {
BaseURL string
Token string
HTTP *http.Client
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
BaseURL string
Token string
HTTP *http.Client
UserAgent 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 {
return &Client{
BaseURL: strings.TrimRight(baseURL, "/"),
Token: token,
HTTP: &http.Client{Timeout: 30 * time.Second},
UserAgent: "drm-agent/" + Version,
BaseURL: strings.TrimRight(baseURL, "/"),
Token: token,
HTTP: &http.Client{Timeout: 30 * time.Second},
UserAgent: "drm-agent/1.0",
}
}
// 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 {
ID int64 `json:"id"`
Name string `json:"name"`
Title string `json:"title"`
App string `json:"app"`
Channel string `json:"channel"`
Tags string `json:"tags"`
MPD string `json:"mpd"`
Key string `json:"key"`
Enabled bool `json:"enabled"`
Health string `json:"health"`
LastError string `json:"last_error"`
PlaylistAgeS float64 `json:"playlist_age_s"`
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 {
@ -100,34 +49,11 @@ type Credentials struct {
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 {
_, err := c.do(http.MethodGet, "/api/health", nil)
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) {
body, err := c.do(http.MethodGet, "/api/streams", nil)
if err != nil {
@ -159,119 +85,6 @@ func (c *Client) PostCredentials(id int64, cred Credentials) error {
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.
type ModuleInfo struct {
Name string `json:"name"`
HasYAML bool `json:"has_yaml"`
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
HasPackage bool `json:"has_package"`
PackageSHA256 string `json:"package_sha256,omitempty"`
Arches []string `json:"arches,omitempty"`
SizeBytes int64 `json:"size_bytes,omitempty"`
}
func (c *Client) ListModules() ([]ModuleInfo, error) {
body, err := c.do(http.MethodGet, "/api/modules", nil)
if err != nil {
return nil, err
}
var wrap struct {
Modules []ModuleInfo `json:"modules"`
}
if err := json.Unmarshal(body, &wrap); err != nil {
return nil, err
}
return wrap.Modules, nil
}
// GetModuleYAML downloads raw module.yaml bytes for name.
func (c *Client) GetModuleYAML(name string) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/yaml", nil)
if err != nil {
return nil, err
}
c.setHeaders(req)
resp, err := c.HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
if resp.StatusCode >= 300 {
return nil, c.statusError(http.MethodGet, "/api/modules/"+name+"/yaml", resp, body)
}
return body, nil
}
// DownloadModulePackage writes the module zip to destPath.
func (c *Client) DownloadModulePackage(name, destPath string) error {
req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/package", nil)
if err != nil {
return err
}
c.setHeaders(req)
resp, err := c.HTTP.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
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)
}
}
func (c *Client) do(method, path string, payload any) ([]byte, error) {
var rdr io.Reader
if payload != nil {
@ -288,53 +101,18 @@ func (c *Client) do(method, path string, payload any) ([]byte, error) {
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
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)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 300 {
return nil, c.statusError(method, path, resp, body)
return nil, fmt.Errorf("%s %s: %s — %s", method, path, resp.Status, strings.TrimSpace(string(body)))
}
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,16 +7,12 @@ import (
"gopkg.in/yaml.v3"
"streamd/repo"
"drmdecryption/repo"
)
type Config struct {
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.
StreamdURL string `yaml:"streamd_url"`
Token string `yaml:"token"`
APIKey string `yaml:"api_key"`
PollIntervalSec int `yaml:"poll_interval_sec"`
DataDir string `yaml:"data_dir"`
Workers int `yaml:"workers"`
@ -27,37 +23,6 @@ type Config struct {
WVD string `yaml:"wvd"` // path to .wvd device file (required for key fetch)
UserAgent string `yaml:"user_agent"`
AgentID string `yaml:"agent_id"`
// SyncModules pulls modules from streamd into the local cache when missing/stale.
SyncModules bool `yaml:"sync_modules"`
ModulesDir string `yaml:"modules_dir"` // empty = <data_dir>/modules
ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"`
ModulesPrune bool `yaml:"modules_prune"` // remove local modules absent from panel
// OnDemandPriority lets a capture that streamd pushed — a viewer waking
// an on-demand stream, or a scheduled event about to start — jump ahead
// of routine refreshes in the queue.
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 {
@ -103,15 +68,9 @@ func applyDefaults(cfg Config, root string) Config {
if cfg.StreamdURL == "" {
cfg.StreamdURL = "http://127.0.0.1:8083"
}
if cfg.Token == "" {
cfg.Token = cfg.APIKey
}
if cfg.Token == "" {
cfg.Token = os.Getenv("STREAMD_TOKEN")
}
if cfg.Token == "" {
cfg.Token = os.Getenv("STREAMD_API_KEY")
}
if cfg.PollIntervalSec <= 0 {
cfg.PollIntervalSec = 30
}
@ -141,42 +100,5 @@ func applyDefaults(cfg Config, root string) Config {
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
cfg.WVD = filepath.Join(root, cfg.WVD)
}
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)
}
if cfg.ModulesSyncIntervalSec <= 0 {
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
}
func (c Config) ModulesSyncInterval() time.Duration {
if c.ModulesSyncIntervalSec <= 0 {
return 5 * time.Minute
}
return time.Duration(c.ModulesSyncIntervalSec) * time.Second
}

View file

@ -4,15 +4,15 @@ import (
"fmt"
"sync"
"streamd/adb"
"drmdecryption/adb"
)
// Pool tracks free/busy ADB devices. Never installs apps.
type Pool struct {
mu sync.Mutex
adbBin string
allow map[string]bool // empty allow = all serials
busy map[string]string // serial → job label
mu sync.Mutex
adbBin string
allow map[string]bool // empty allow = all serials
busy map[string]string // serial → job label
}
func New(adbBin string, allowlist []string) *Pool {

View file

@ -1,377 +0,0 @@
// Package modsync pulls provider modules from streamd into a local cache.
// The panel is the source of truth: agents download package.zip when the
// package hash changes, and module.yaml alone when only YAML changed.
package modsync
import (
"archive/zip"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"streamd/apps/agent/internal/client"
"streamd/modhost"
"streamd/repo"
)
// Syncer keeps the local modules cache aligned with streamd.
type Syncer struct {
API *client.Client
ModulesDir string // empty = <data_dir>/modules resolved by caller, or modhost default
Interval time.Duration
Prune bool // remove local modules absent from the panel
Log *log.Logger
}
func (s *Syncer) modulesDir() string {
if strings.TrimSpace(s.ModulesDir) != "" {
return s.ModulesDir
}
return modhost.ModulesDir(repo.Root())
}
// Once pulls every remote module that is missing or stale locally.
func (s *Syncer) Once() error {
dir := s.modulesDir()
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
remote, err := s.API.ListModules()
if err != nil {
return err
}
seen := map[string]struct{}{}
for _, m := range remote {
seen[m.Name] = struct{}{}
if err := s.syncOne(dir, m); err != nil {
s.logf("modules sync: %s: %v", m.Name, err)
continue
}
}
if s.Prune {
s.pruneLocal(dir, seen)
}
return nil
}
func (s *Syncer) syncOne(dir string, m client.ModuleInfo) error {
modDir := filepath.Join(dir, m.Name)
localPkg := localSHA(filepath.Join(modDir, "package.sha256"))
localYAML := ""
if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
sum := sha256.Sum256(raw)
localYAML = hex.EncodeToString(sum[:])
}
needPackage := m.HasPackage && (localPkg == "" || !strings.EqualFold(localPkg, m.PackageSHA256))
needYAML := m.HasYAML && (localYAML == "" || !strings.EqualFold(localYAML, m.YAMLSHA256))
if !needPackage && !needYAML {
return nil
}
if needPackage {
if !m.HasPackage {
return fmt.Errorf("panel has no package.zip")
}
if err := s.pullPackage(modDir, m); err != nil {
return err
}
s.logf("modules sync: pulled package %s", m.Name)
// Package extract includes yaml; refresh localYAML check.
if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
sum := sha256.Sum256(raw)
localYAML = hex.EncodeToString(sum[:])
needYAML = m.HasYAML && !strings.EqualFold(localYAML, m.YAMLSHA256)
} else {
needYAML = m.HasYAML
}
}
if needYAML {
raw, err := s.API.GetModuleYAML(m.Name)
if err != nil {
return err
}
if err := os.MkdirAll(modDir, 0o755); err != nil {
return err
}
if err := atomicWrite(filepath.Join(modDir, "module.yaml"), raw, 0o644); err != nil {
return err
}
s.logf("modules sync: updated yaml %s", m.Name)
}
return nil
}
func (s *Syncer) pullPackage(modDir string, m client.ModuleInfo) error {
if err := os.MkdirAll(modDir, 0o755); err != nil {
return err
}
zipPath := filepath.Join(modDir, "package.zip")
if err := s.API.DownloadModulePackage(m.Name, zipPath); err != nil {
return err
}
sum, err := fileSHA256(zipPath)
if err != nil {
return err
}
if m.PackageSHA256 != "" && !strings.EqualFold(sum, m.PackageSHA256) {
return fmt.Errorf("package sha mismatch: got %s want %s", sum, m.PackageSHA256)
}
extractDir := filepath.Join(modDir, ".extract-tmp")
_ = os.RemoveAll(extractDir)
if err := os.MkdirAll(extractDir, 0o755); err != nil {
return err
}
defer os.RemoveAll(extractDir)
if err := unzipSafe(zipPath, extractDir); err != nil {
return err
}
// Flatten a single top-level folder (bbc/...) into extractDir root.
if err := flattenSingleRoot(extractDir); err != nil {
return err
}
if err := promoteHostBinary(extractDir, m.Name); err != nil {
return err
}
// Move extracted contents into modDir (keep package.zip + sha sidecar).
ents, err := os.ReadDir(extractDir)
if err != nil {
return err
}
for _, e := range ents {
src := filepath.Join(extractDir, e.Name())
dst := filepath.Join(modDir, e.Name())
_ = os.RemoveAll(dst)
if err := os.Rename(src, dst); err != nil {
return err
}
}
return atomicWrite(filepath.Join(modDir, "package.sha256"), []byte(sum+"\n"), 0o644)
}
func (s *Syncer) pruneLocal(dir string, keep map[string]struct{}) {
ents, err := os.ReadDir(dir)
if err != nil {
return
}
for _, e := range ents {
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
continue
}
if _, ok := keep[e.Name()]; ok {
continue
}
path := filepath.Join(dir, e.Name())
if err := os.RemoveAll(path); err != nil {
s.logf("modules sync: prune %s: %v", e.Name(), err)
continue
}
s.logf("modules sync: pruned %s", e.Name())
}
}
// Loop runs Once immediately, then on Interval until stop closes.
func (s *Syncer) Loop(stop <-chan struct{}) {
interval := s.Interval
if interval <= 0 {
interval = 5 * time.Minute
}
_ = s.runLogged()
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-stop:
return
case <-t.C:
_ = s.runLogged()
}
}
}
func (s *Syncer) runLogged() error {
if err := s.Once(); err != nil {
s.logf("modules sync error: %v", err)
return err
}
return nil
}
func (s *Syncer) logf(format string, args ...any) {
if s.Log != nil {
s.Log.Printf(format, args...)
return
}
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

@ -1,154 +0,0 @@
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"
"time"
"streamd/apps/agent/internal/client"
"streamd/apps/agent/internal/queue"
"drmdecryption/apps/agent/internal/client"
"drmdecryption/apps/agent/internal/queue"
)
type Poller struct {
@ -51,27 +51,6 @@ func (p *Poller) Once() error {
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{}) {
t := time.NewTicker(p.Interval)
defer t.Stop()
@ -88,24 +67,11 @@ 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 {
if !st.NeedsCapture {
return ""
if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" {
return "missing_credentials"
}
switch {
case strings.TrimSpace(st.MPD) == "":
return "missing_credentials"
case st.DRMRequired && !st.HasKey:
return "missing_credentials"
case st.DRMRequired && !st.KeyValid:
if !validKeyPair(st.Key) {
return "invalid_credentials"
}
h := strings.ToLower(strings.TrimSpace(st.Health))
@ -113,44 +79,27 @@ func needsRefresh(st client.Stream) string {
case "down", "error", "failed":
return "down"
}
return "stale"
return ""
}
// ValidKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID
// ignored). The authoritative check lives in streamd; this copy exists only
// to sanity-check what a worker is about to POST.
func ValidKeyPair(key string) bool {
for _, line := range splitKeyLines(key) {
kid, k, ok := strings.Cut(line, ":")
if !ok || len(hexOnly(kid)) != 32 || len(hexOnly(k)) != 32 {
return false
}
// validKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID ignored).
func validKeyPair(key string) bool {
parts := strings.SplitN(strings.TrimSpace(key), ":", 2)
if len(parts) != 2 {
return false
}
return len(splitKeyLines(key)) > 0
}
// 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)
hexOnly := func(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()
}
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()
kid, k := hexOnly(parts[0]), hexOnly(parts[1])
return len(kid) == 32 && len(k) == 32
}
func (p *Poller) logf(format string, args ...any) {

View file

@ -2,7 +2,6 @@ package queue
import (
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
@ -101,56 +100,24 @@ func parseTime(s string) time.Time {
return t
}
// 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.
// EnqueueIfIdle inserts a 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) {
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
var existing int
err := s.DB.QueryRow(`
SELECT id, priority FROM jobs
WHERE stream_id=? AND status IN ('queued','running')
ORDER BY id LIMIT 1`, streamID).Scan(&existingID, &existingPriority)
switch {
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
case !errors.Is(err, sql.ErrNoRows):
SELECT COUNT(1) FROM jobs WHERE stream_id=? AND status IN ('queued','running')`, streamID).Scan(&existing)
if err != nil {
return Job{}, false, err
}
if existing > 0 {
return Job{}, false, nil
}
if maxAttempts <= 0 {
maxAttempts = 5
}
if priority <= 0 {
priority = PriorityRoutine
}
res, err := s.DB.Exec(`
INSERT INTO jobs(stream_id,stream_name,app,channel,reason,status,priority,attempts,max_attempts,created_at,not_before)
VALUES(?,?,?,?,?,'queued',?,0,?,?,?)`,
streamID, name, app, channel, reason, priority, maxAttempts, now(), now())
VALUES(?,?,?,?,?,'queued',100,0,?,?,?)`,
streamID, name, app, channel, reason, maxAttempts, now(), now())
if err != nil {
return Job{}, false, err
}
@ -232,18 +199,17 @@ func (s *Store) MarkOK(id int64) error {
return err
}
// MarkFailed increments attempts. Re-queues unless maxed out.
// MarkFailed increments attempts. Re-queues with backoff unless maxed out.
// waitingDevice=true keeps status queued without burning an attempt.
// 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 {
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error {
j, err := s.Get(id)
if err != nil {
return err
}
if waitingDevice {
_, err = s.DB.Exec(`
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`,
msg, now(), id)
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='' WHERE id=?`,
msg, id)
return err
}
attempts := j.Attempts + 1
@ -253,8 +219,9 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i
attempts, msg, now(), id)
return err
}
if backoff < 0 {
backoff = 0
backoff := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
if backoff > 15*time.Minute {
backoff = 15 * time.Minute
}
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
_, err = s.DB.Exec(`
@ -263,29 +230,6 @@ UPDATE jobs SET status='queued', attempts=?, last_error=?, not_before=?, device_
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 {
if a < b {
return a

View file

@ -1,20 +1,17 @@
package worker
import (
"errors"
"fmt"
"log"
"strings"
"time"
"streamd/modhost"
"streamd/phonecap"
"streamd/repo"
"drmdecryption/app"
"drmdecryption/phonecap"
"streamd/apps/agent/internal/client"
"streamd/apps/agent/internal/device"
"streamd/apps/agent/internal/poller"
"streamd/apps/agent/internal/queue"
"drmdecryption/apps/agent/internal/client"
"drmdecryption/apps/agent/internal/device"
"drmdecryption/apps/agent/internal/queue"
)
type Worker struct {
@ -27,10 +24,7 @@ type Worker struct {
Python string
WVD string
UserAgent string
// JobBackoff enables exponential delays between failed capture attempts.
// When false (default), failed jobs are re-queued immediately.
JobBackoff bool
Log *log.Logger
Log *log.Logger
lastDelayLog time.Time
}
@ -70,18 +64,11 @@ func (w *Worker) tick() {
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
// Config/environment issues — do not burn attempts or multi-minute backoff.
w.logf("job=%d waiting: %v", job.ID, err)
_ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
_ = w.Queue.MarkFailed(job.ID, err.Error(), true)
return
}
w.logf("job=%d failed: %v", job.ID, err)
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)
_ = w.Queue.MarkFailed(job.ID, err.Error(), false)
return
}
_ = w.Queue.MarkOK(job.ID)
@ -92,11 +79,6 @@ func isAuthErr(err error) bool {
if err == nil {
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())
return strings.Contains(s, "401") || strings.Contains(s, "unauthorized")
}
@ -106,19 +88,15 @@ func isUnknownAppErr(err error) bool {
return false
}
s := strings.ToLower(err.Error())
return strings.Contains(s, "unknown app") || strings.Contains(s, "unknown module") || strings.Contains(s, "no modules found")
return strings.Contains(s, "unknown app")
}
func (w *Worker) runJob(job queue.Job) error {
a, err := modhost.Open(repo.Root(), job.App)
a, err := app.Get(job.App)
if err != nil {
return err
}
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)
if err != nil {
return err
@ -127,8 +105,8 @@ func (w *Worker) runJob(job queue.Job) error {
_ = w.Queue.SetDevice(job.ID, serial)
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
// Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
// Short TTL; /ws/agent heartbeats renew while this process is alive.
if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil {
return fmt.Errorf("streamd claim: %w", err)
}
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
@ -148,19 +126,6 @@ func (w *Worker) runJob(job queue.Job) error {
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{
MPD: res.MPD,
Key: res.Key,
@ -171,41 +136,9 @@ func (w *Worker) runJob(job queue.Job) error {
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
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
}
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) {
prefix := fmt.Sprintf("worker/%d: ", w.ID)
if w.Log != nil {

View file

@ -10,42 +10,16 @@ import (
"time"
"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
// 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 {
BaseURL string
Token string
AgentID string
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{}
}
@ -73,8 +47,7 @@ func (c *Client) Loop() {
return
default:
}
err := c.session()
if err != nil {
if err := c.session(); err != nil {
c.Log.Printf("ws: session ended: %v — retry in %s", err, backoff)
}
select {
@ -102,29 +75,18 @@ func (c *Client) session() error {
u.Path = "/ws/agent"
q := u.Query()
q.Set("agent_id", c.AgentID)
// The token is deliberately NOT put in the query string. It used to be,
// which wrote the shared secret into every reverse proxy access log.
// streamd authenticates the handshake from the Authorization header below.
if c.Token != "" {
q.Set("token", c.Token)
}
u.RawQuery = q.Encode()
hdr := http.Header{}
if 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}
conn, resp, err := dialer.Dial(u.String(), hdr)
conn, _, err := dialer.Dial(u.String(), hdr)
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)
}
defer conn.Close()
@ -145,11 +107,14 @@ func (c *Client) session() error {
return
}
_ = conn.SetReadDeadline(time.Now().Add(60 * time.Second))
var msg Message
if json.Unmarshal(data, &msg) != nil {
continue
var msg map[string]any
if json.Unmarshal(data, &msg) == nil {
if t, _ := msg["type"].(string); t == "heartbeat_ack" {
if ok, _ := msg["ok"].(bool); !ok {
c.Log.Printf("ws: heartbeat nack: %v", msg["error"])
}
}
}
c.handle(msg)
}
}()
@ -174,33 +139,6 @@ 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 {
_ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
return conn.WriteJSON(map[string]string{

View file

@ -1,6 +1,6 @@
# capture
One-shot phone MITM capture, hosted by the single binary as `streamd capture`.
One-shot phone MITM capture, hosted by the single binary as `drm capture`.
```text
apps/capture/
@ -8,17 +8,17 @@ apps/capture/
```
```bash
./bin/streamd capture # passive: play anything
./bin/streamd capture --app rte # launch, navigate by hand
./bin/streamd capture --app rte --channel rteone --auto-play \
./bin/drm capture # passive: play anything
./bin/drm capture --app rte # launch, navigate by hand
./bin/drm capture --app rte --channel rteone --auto-play \
--wvd data/device.wvd # fully automated
```
Writes `outputs/<app>/<stamp>/` plus `latest/`. App modules are compiled in, so
there is no modules directory to point at; `streamd modules` lists what is available.
there is no modules directory to point at; `drm modules` lists what is available.
**Full guide: [docs/capture.md](../../docs/capture.md)** — device setup, flags,
discovering a new app, and troubleshooting.
The catalog lookup that used to be a separate `tg4info` binary is now the
provider-agnostic `streamd catalog` (`apps/cli/catalogcmd`).
provider-agnostic `drm catalog` (`apps/cli/catalogcmd`).

View file

@ -3,49 +3,38 @@
package capturecmd
import (
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"unicode"
"streamd/adb"
"streamd/app"
"streamd/modcfg"
"streamd/modhost"
"streamd/phonecap"
"streamd/repo"
"drmdecryption/adb"
"drmdecryption/app"
"drmdecryption/modcfg"
"drmdecryption/phonecap"
)
// Run performs one capture. Providers live under modules/<name>/ and are built
// and executed by modhost — they are not linked into streamd.
// Run performs one capture. App modules are compiled in, so there is no modules
// directory to scan: --app names a registered provider.
func Run(args []string) error {
args = normalizeArgs(args)
root := repo.Root()
available, _ := modhost.Names(root)
appChoices := strings.Join(available, "|")
if appChoices == "" {
appChoices = "NAME"
}
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. Empty = passive MITM, no launch/auto-play")
channel := fs.String("channel", "", "channel id for --auto-play")
allChannels := fs.Bool("all", false, "capture every channel declared by the module (grab-all)")
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)")
autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (requires --app and --channel)")
waitSec := fs.Int("wait", 180, "seconds to wait for license/mpd capture")
python := fs.String("python", "", "python for wvkey.py (default: .venv)")
wvd := fs.String("wvd", "", "path to .wvd device file (required by some apps e.g. c4; MPD-only if omitted)")
wvd := fs.String("wvd", "", "path to .wvd device file (required for key fetch)")
userAgent := fs.String("user-agent", "", "optional User-Agent for license requests")
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)")
keyMode := fs.String("key-mode", "", "override the app's key mode: modulardrm | raw | wrap | none")
keyMode := fs.String("key-mode", "", "override the app's key mode: modulardrm | raw | none")
// Each module contributes --<app>.<field> overrides for its local values.
app.BindFlags(fs)
fs.Usage = func() {
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)
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", strings.Join(app.Names(), "|"))
fs.PrintDefaults()
}
@ -64,9 +53,6 @@ func Run(args []string) error {
// No --app: passive MITM — the operator plays whatever they want and we dump
// whatever DRM traffic appears.
if strings.TrimSpace(*appName) == "" {
if *allChannels {
return fmt.Errorf("--all requires --app")
}
_, err := phonecap.RunPassive(phonecap.Options{
Client: c,
Python: *python,
@ -79,48 +65,26 @@ func Run(args []string) error {
return err
}
a, err := modhost.Open(root, *appName)
a, err := app.Get(*appName)
if err != nil {
return modhost.FormatUnknown(root, *appName)
return err
}
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)
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).
doAutoPlay := *autoPlay || channelID != ""
if *autoPlay && channelID == "" {
if *autoPlay && strings.TrimSpace(*channel) == "" {
return fmt.Errorf("--auto-play requires --channel (%s)", knownChannels(a))
}
if channelID != "" && !a.HasChannel(channelID) {
return fmt.Errorf("unknown channel %q for %s (%s)", channelID, a.Name(), knownChannels(a))
if *channel != "" && !a.HasChannel(*channel) {
return fmt.Errorf("unknown channel %q for %s (%s)", *channel, a.Name(), knownChannels(a))
}
_, err = phonecap.Run(phonecap.Options{
App: a,
Channel: channelID,
Channel: *channel,
Client: c,
Python: *python,
WVD: *wvd,
UserAgent: *userAgent,
Wait: time.Duration(*waitSec) * time.Second,
NoAutoPlay: !doAutoPlay,
NoAutoPlay: !*autoPlay,
CloseApp: *closeApp,
KeyMode: *keyMode,
ClearProxy: true,
@ -128,106 +92,6 @@ func Run(args []string) error {
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 (— – −)
// into ASCII - so `--app` is not silently dropped as a positional token.
func normalizeArgs(args []string) []string {
@ -256,13 +120,6 @@ func normalizeArgs(args []string) []string {
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
// the module has no local values file yet.
func knownChannels(a app.App) string {

View file

@ -1,9 +1,13 @@
module streamd/apps/capture
module drmdecryption/apps/capture
go 1.25.0
require streamd v0.0.0
require drmdecryption v0.0.0
require gopkg.in/yaml.v3 v3.0.1 // indirect
require (
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac // indirect
golang.org/x/sys v0.42.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
replace streamd => ../pkg
replace drmdecryption => ../pkg

View file

@ -1,3 +1,11 @@
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View file

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

View file

@ -1,6 +1,6 @@
// Package catalogcmd resolves a channel's stream credentials from its provider's
// public catalog, with no phone involved. Providers live under modules/<name>/
// and are invoked via modhost.
// public catalog, with no phone involved. It is provider-agnostic: any app module
// implementing app.Catalog works here.
package catalogcmd
import (
@ -11,15 +11,15 @@ import (
"sort"
"strings"
"streamd/modhost"
"streamd/repo"
"streamd/session"
"drmdecryption/app"
"drmdecryption/repo"
"drmdecryption/session"
)
// Run performs a catalog lookup for one channel.
func Run(args []string) error {
fs := flag.NewFlagSet("catalog", flag.ExitOnError)
appName := fs.String("app", "", "app module under modules/<name>/")
appName := fs.String("app", "", "app module to query")
channel := fs.String("channel", "", "channel id")
asJSON := fs.Bool("json", false, "print streamd-ready JSON only")
list := fs.Bool("list", false, "list the app's channels and their catalog ids")
@ -27,6 +27,8 @@ func Run(args []string) error {
withKeys := fs.Bool("keys", false, "also fetch PSSH and resolve KID:KEY via the local CDM")
python := fs.String("python", "", "python for wvkey.py (default: .venv)")
wvd := fs.String("wvd", "", "path to .wvd device file (required with --keys)")
// Each module contributes --<app>.<field> overrides for its local values.
app.BindFlags(fs)
fs.Usage = func() {
fmt.Fprintf(fs.Output(), "catalog — resolve a channel from its public catalog (no phone)\n\nUsage:\n catalog --app <%s> --channel ID [--keys] [--json]\n\nFlags:\n", strings.Join(catalogApps(), "|"))
fs.PrintDefaults()
@ -38,36 +40,33 @@ func Run(args []string) error {
available := catalogApps()
if strings.TrimSpace(*appName) == "" {
if len(available) != 1 {
msg := strings.Join(available, ", ")
if msg == "" {
msg = "(none — add a modules/<name>/ with catalog support)"
}
return fmt.Errorf("--app required (apps with a catalog: %s)", msg)
return fmt.Errorf("--app required (apps with a catalog: %s)", strings.Join(available, ", "))
}
*appName = available[0]
}
a, err := modhost.Open(repo.Root(), *appName)
a, err := app.Get(*appName)
if err != nil {
return modhost.FormatUnknown(repo.Root(), *appName)
return err
}
if !a.Desc.HasCatalog {
cat, ok := a.(app.Catalog)
if !ok {
return fmt.Errorf("app %q has no catalog — capture it from the phone instead: drm capture --app %s", a.Name(), a.Name())
}
if *list {
return listChannels(a)
return listChannels(a, cat)
}
if strings.TrimSpace(*channel) == "" {
return fmt.Errorf("--channel required (see: drm catalog --app %s --list)", a.Name())
}
info, err := a.Resolve(*channel)
info, err := cat.Resolve(*channel)
if err != nil {
return err
}
if *withKeys {
fmt.Fprintln(os.Stderr, "[*] fetching PSSH + Widevine keys…")
if err := a.EnrichWithKeys(&info, *python, *wvd); err != nil {
if err := cat.EnrichWithKeys(&info, *python, *wvd); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "[+] key %s (%d total)\n", info.Key, len(info.Keys))
@ -88,23 +87,48 @@ func Run(args []string) error {
return nil
}
// catalogApps lists external modules that advertise HasCatalog.
// catalogApps lists compiled-in modules that can answer catalog lookups.
func catalogApps() []string {
listed, err := modhost.ListAll(repo.Root())
if err != nil {
return nil
}
out := []string{}
for _, L := range listed {
if L.Desc.HasCatalog {
out = append(out, L.Desc.Name)
for _, a := range app.All() {
if _, ok := a.(app.Catalog); ok {
out = append(out, a.Name())
}
}
sort.Strings(out)
return out
}
func listChannels(a *modhost.RemoteApp) error {
func listChannels(a app.App, cat app.Catalog) error {
if l, ok := cat.(app.CatalogLister); ok {
rows, flags, err := l.ListChannels()
if err != nil {
return err
}
fmt.Printf("%-10s %-16s %s\n", "CHANNEL", "CATALOG ID", "LABEL")
sort.Slice(rows, func(i, j int) bool { return rows[i].ID < rows[j].ID })
for _, r := range rows {
id := r.CatalogID
if id == "" {
id = "-"
}
fmt.Printf("%-10s %-16s %s\n", r.ID, id, r.Label)
}
if len(flags) > 0 {
keys := make([]string, 0, len(flags))
for k := range flags {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, k := range keys {
parts = append(parts, fmt.Sprintf("%s=%v", k, flags[k]))
}
fmt.Printf("\nprovider flags: %s\n", strings.Join(parts, " "))
}
return nil
}
// Fall back to the plain channel list every app can produce.
fmt.Printf("%-10s %s\n", "CHANNEL", "LABEL")
for _, ch := range a.Channels() {
fmt.Printf("%-10s %s\n", ch.ID, ch.Label)

View file

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

View file

@ -1,57 +1,29 @@
// Command streamd is the single entry point for the toolchain: phone capture,
// Command drm is the single entry point for the toolchain: phone capture,
// catalog lookups, the always-on agent, the streamd control plane and the
// on-device MITM. Providers live under modules/<name>/ and are discovered,
// built, and executed by the host — they are not linked into this binary.
// on-device MITM. Every app module under apps/modules is compiled in.
package main
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"
"os"
"strings"
"streamd/apps/agent/agentcmd"
"streamd/apps/capture/capturecmd"
"streamd/apps/cli/catalogcmd"
"streamd/apps/cli/modulescmd"
"streamd/apps/proxy/proxyctlcmd"
"streamd/apps/streamd/servecmd"
"streamd/bootstrap"
"streamd/modhost"
"drmdecryption/apps/agent/agentcmd"
"drmdecryption/apps/capture/capturecmd"
"drmdecryption/apps/cli/catalogcmd"
"drmdecryption/apps/cli/modulescmd"
"drmdecryption/apps/proxy/proxyctlcmd"
"drmdecryption/apps/streamd/servecmd"
// Links every app module into this binary.
_ "drmdecryption/modules/all"
)
func main() {
args := os.Args[1:]
modulesDir, args := peelGlobalFlags(args)
if len(args) < 1 {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
cmd, args := args[0], args[1:]
if modulesDir != "" {
if err := modhost.SetModulesDir(modulesDir); err != nil {
fmt.Fprintln(os.Stderr, "[!] --modules-dir:", err)
os.Exit(1)
}
} else if err := modhost.ApplyEnvModulesDir(); err != nil {
fmt.Fprintln(os.Stderr, "[!] STREAMD_MODULES_DIR / DRM_MODULES_DIR:", err)
os.Exit(1)
}
// Materialise apps/, bin/, modules/, outputs/, … next to this exe when
// missing so a lone downloaded streamd.exe becomes a usable install tree.
if cmd != "help" && cmd != "-h" && cmd != "--help" {
if err := bootstrap.EnsureAndLogFor(cmd); err != nil {
fmt.Fprintln(os.Stderr, "[!] bootstrap:", err)
os.Exit(1)
}
}
cmd, args := os.Args[1], os.Args[2:]
var err error
switch cmd {
case "capture":
@ -79,46 +51,25 @@ func main() {
}
}
// peelGlobalFlags extracts host-level flags that may appear before the subcommand.
func peelGlobalFlags(args []string) (modulesDir string, rest []string) {
rest = make([]string, 0, len(args))
for i := 0; i < len(args); i++ {
a := args[i]
switch {
case a == "--modules-dir" || a == "-modules-dir":
if i+1 >= len(args) {
fmt.Fprintln(os.Stderr, "[!] --modules-dir requires a path")
os.Exit(2)
}
modulesDir = args[i+1]
i++
case strings.HasPrefix(a, "--modules-dir="):
modulesDir = strings.TrimPrefix(a, "--modules-dir=")
default:
rest = append(rest, a)
}
}
return modulesDir, rest
}
func usage() {
fmt.Fprint(os.Stderr, `streamd — capture / restream toolchain
fmt.Fprint(os.Stderr, `drm — DRM capture / restream toolchain
Usage:
streamd [--modules-dir DIR] modules
streamd [--modules-dir DIR] capture --app NAME [--channel ID | --all] [--wvd PATH]
streamd [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json]
streamd agent run|status|devices|enqueue|cancel [--config …]
streamd serve start|stop|restart|status|update|run [flags]
streamd serve [--bind …] [--data …] # foreground (same as run)
streamd proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
drm modules list compiled-in app modules and their channels
drm capture --app NAME [--channel ID] [--auto-play] [--wvd PATH]
one-shot phone MITM capture
drm catalog --app NAME --channel ID [--keys] [--json] [--list]
resolve a channel from its public catalog (no phone)
drm agent run|status|devices|enqueue|cancel [--config …]
always-on credential refresher
drm serve [--bind …] [--data …] [--token …]
streamd control plane + dashboard
drm proxy build|push|install-ca|start|stop|discover|pull|clear-proxy
on-device HTTPS MITM
Global flags:
--modules-dir DIR provider folder (default: <install>/modules, or $STREAMD_MODULES_DIR)
Providers live under modules/<name>/ (Go source + module-publish.yaml).
Local module.yaml holds secrets and is never published; release zips ship
module-publish.yaml renamed to module.yaml. The host builds modules on demand.
App modules are compiled in; their local values live in
apps/modules/<name>/module.yaml (gitignored) and can be overridden per run with
--<app>.<field> flags or <APP>_<FIELD> environment variables.
Run any subcommand with --help for its own flags.
`)

View file

@ -1,5 +1,5 @@
// Package modulescmd lists provider modules discovered under modules/<name>/,
// building them on demand and showing channels + values paths.
// Package modulescmd lists the app modules compiled into this binary, their
// channels, and where each one's local values came from.
package modulescmd
import (
@ -9,11 +9,11 @@ import (
"sort"
"text/tabwriter"
"streamd/modhost"
"streamd/repo"
"drmdecryption/app"
"drmdecryption/modcfg"
)
// Run prints external modules under modules/.
// Run prints the compiled-in app modules.
func Run(args []string) error {
fs := flag.NewFlagSet("modules", flag.ExitOnError)
verbose := fs.Bool("channels", true, "list each module's channels")
@ -21,57 +21,54 @@ func Run(args []string) error {
return err
}
root := repo.Root()
listed, err := modhost.ListAll(root)
if err != nil {
return err
names := app.Names()
if len(names) == 0 {
return fmt.Errorf("no app modules compiled in — check the blank imports in apps/modules/all/all.go")
}
if len(listed) == 0 {
return fmt.Errorf("no modules found under %s — add modules/<name>/ with Go source + module.yaml (see modules/README.md)", modhost.ModulesDir(root))
}
tw := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)
fmt.Fprintln(tw, "APP\tPACKAGE\tKEY MODE\tREWRITER\tCHANNELS\tVALUES")
for _, L := range listed {
d := L.Desc
rewriter := d.Rewriter
if rewriter == "" {
rewriter = "none"
for _, name := range names {
a, err := app.Get(name)
if err != nil {
fmt.Fprintf(tw, "%s\t-\t-\t-\t-\t%v\n", name, err)
continue
}
pkg := d.Package
rewriter := "none"
if sd, ok := a.(app.StreamDefaults); ok && sd.RewriterName() != "" {
rewriter = sd.RewriterName()
}
pkg := a.Package()
if pkg == "" {
pkg = "(not configured)"
}
values := d.ValuesPath
if values == "" {
values = L.Mod.Dir + string(os.PathSeparator) + "module.yaml"
}
values := modcfg.Path(name)
if _, err := os.Stat(values); err != nil {
values = "missing: " + values
} else if !d.ValuesLoaded {
values = values + " (not loaded)"
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%d\t%s\n",
d.Name, pkg, d.KeyMode, rewriter, len(d.Channels), values)
name, pkg, a.KeyMode(), rewriter, len(a.Channels()), values)
}
_ = tw.Flush()
if !*verbose {
return nil
}
for _, L := range listed {
d := L.Desc
chans := append([]modhost.Channel{}, d.Channels...)
for _, name := range names {
a, err := app.Get(name)
if err != nil {
continue
}
chans := a.Channels()
sort.Slice(chans, func(i, j int) bool { return chans[i].ID < chans[j].ID })
fmt.Printf("\n%s channels:", d.Name)
fmt.Printf("\n%s channels:", name)
if len(chans) == 0 {
fmt.Printf(" none — add %s\n", d.ValuesPath)
fmt.Printf(" none — add %s\n", modcfg.Path(name))
continue
}
fmt.Println()
for _, ch := range chans {
catalog := ""
if d.HasCatalog {
if _, ok := a.(app.Catalog); ok {
catalog = " (catalog)"
}
fmt.Printf(" %-10s %s%s\n", ch.ID, ch.Label, catalog)

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.
```text
apps/modules/ Go module: streamd/modules
go.mod replace streamd => ../pkg
apps/modules/ Go module: drmdecryption/modules
go.mod replace drmdecryption => ../pkg
all/all.go blank-imports every module — the link point
provider/ shared base: values loading, channel aliases, durations
<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:
```bash
./bin/streamd catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
./bin/drm catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
export TG4_POLICY_KEY=BCpkAD... # same thing
```
@ -46,9 +46,9 @@ export TG4_POLICY_KEY=BCpkAD... # same thing
1. Create `apps/modules/myapp/` with `config.go` and `myapp.go`
2. Register from `init()`: `appreg.Register(Name, New)` and
`appreg.RegisterFlags(bindFlags)`
3. Add one line to `all/all.go`: `_ "streamd/modules/myapp"`
3. Add one line to `all/all.go`: `_ "drmdecryption/modules/myapp"`
4. Create `apps/modules/myapp/module.yaml` with your values
5. `go -C apps/cli build -o ../../bin/streamd .` then `./bin/streamd modules`
5. `go -C apps/cli build -o ../../bin/drm .` then `./bin/drm modules`
**Authoring guide: [docs/modules.md](../../docs/modules.md)** — the full contract,
`uiflow` reference, optional capability interfaces, and a checklist.
@ -59,9 +59,9 @@ export TG4_POLICY_KEY=BCpkAD... # same thing
## Run
```bash
./bin/streamd modules # what is compiled in
./bin/streamd capture --app rte --channel rteone --auto-play
./bin/streamd capture --app bbc --channel bbcone # transparent MITM; play on phone; MPD only
./bin/streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
./bin/streamd agent run --config apps/agent/agent.yaml
./bin/drm modules # what is compiled in
./bin/drm capture --app rte --channel rteone --auto-play
./bin/drm capture --app bbc --channel bbcone # transparent MITM; play on phone; MPD only
./bin/drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
./bin/drm agent run --config apps/agent/agent.yaml
```

View file

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

View file

@ -4,7 +4,7 @@ import (
"flag"
"testing"
appreg "streamd/app"
appreg "drmdecryption/app"
)
// 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())
}
switch a.KeyMode() {
case "raw", "modulardrm", "wrap", "none":
case "raw", "modulardrm", "none":
default:
t.Errorf("%s: KeyMode() = %q, want raw, modulardrm, wrap, or none", n, a.KeyMode())
t.Errorf("%s: KeyMode() = %q, want raw, modulardrm, or none", n, a.KeyMode())
}
if a.CAHash() == "" {
t.Errorf("%s: CAHash() empty", n)
@ -39,12 +39,6 @@ func TestAllModulesRegisterAndConstruct(t *testing.T) {
if a.CaptureHints().RemoteLog == "" {
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"
"time"
"streamd/adb"
appreg "streamd/app"
"streamd/capture"
"streamd/modules/provider"
"streamd/mpd"
"streamd/uiflow"
"drmdecryption/adb"
appreg "drmdecryption/app"
"drmdecryption/capture"
"drmdecryption/modules/provider"
"drmdecryption/mpd"
"drmdecryption/uiflow"
)
func init() {
@ -90,35 +90,34 @@ func (a *App) Launch(c *adb.Client) error {
return nil
}
// AutoPlay opens Explore, taps the channel logo, then Watch live — same style
// as RTE/TG4 interactive navigation, driven by uiautomator dumps.
// AutoPlay: best-effort; iPlayer UI varies — operator can play by hand.
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))
fmt.Printf("[*] Auto-play %s — open Live and start playback on the phone…\n", a.Label(id))
if ch.VPID != "" {
fmt.Printf(" expected mediaselector vpid ≈ %s\n", ch.VPID)
}
c.DismissShadeIfFocused()
if err := a.openExplorePage(c); err != nil {
return err
if len(ch.PlayDesc) == 0 && len(ch.ChipDesc) == 0 {
return fmt.Errorf("no UI selectors for %s — play manually on the phone", id)
}
if err := a.tapChannel(c, ch); err != nil {
return err
if len(ch.ChipDesc) > 0 {
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{DescRE: ch.ChipDesc}, 20*time.Second); err != nil {
return fmt.Errorf("channel chip: %w", err)
}
time.Sleep(2 * time.Second)
}
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
if err := a.tapWatchLive(c, ch); err != nil {
return err
if len(ch.PlayDesc) > 0 {
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{DescRE: ch.PlayDesc}, 15*time.Second); err != nil {
return fmt.Errorf("play: %w", err)
}
}
// Soft-fail: clear streams often start without a dumpsys audio session.
return uiflow.WaitPlayback(c, a.CacheDir(), a.Package(), uiflow.PlaybackOpts{
Timeout: time.Duration(a.cfg.Timeouts.Playback),
SoftFail: true,
OrDescContains: a.cfg.UI.PlaybackDescContains,
Timeout: time.Duration(a.cfg.Timeouts.Playback),
})
}

View file

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

View file

@ -1,29 +1,27 @@
package bbc
import (
"regexp"
"time"
"streamd/modcfg"
"streamd/modules/provider"
"drmdecryption/modcfg"
"drmdecryption/modules/provider"
)
// Name is the module id (--app bbc).
const Name = "bbc"
// Channel is one live target. Label doubles as the Explore-rail content-desc
// (e.g. "BBC One") unless ChipDesc overrides it.
// Channel is one live (or catch-up) target. Phone UI selectors are optional —
// capture works with manual play; auto-play uses them when present.
type Channel struct {
Label string `yaml:"label"`
// VPID is the mediaselector version/service id (e.g. bbc_one_london).
VPID string `yaml:"vpid"`
// ChipDesc matches the channel logo on Explore (content-desc). Default: Label.
// ChipDesc / PlayDesc are optional UI matchers for --auto-play.
ChipDesc []string `yaml:"chip_desc"`
// PlayDesc matches the Watch-live control on the channel page. Default: Watch live.
PlayDesc []string `yaml:"play_desc"`
}
// Config is modules/bbc/module.yaml (preferred) or apps/modules/bbc/module.yaml.
// Config is apps/modules/bbc/module.yaml.
type Config struct {
provider.Common `yaml:",inline"`
@ -33,79 +31,30 @@ type Config struct {
UI UI `yaml:"ui"`
}
// Timeouts for launch / autoplay. Written as "25s" in module.yaml.
// Timeouts for launch / optional autoplay.
type Timeouts struct {
LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
LaunchSettle provider.Duration `yaml:"launch_settle"`
ExploreNav provider.Duration `yaml:"explore_nav"`
ChannelFind provider.Duration `yaml:"channel_find"`
AfterChannel provider.Duration `yaml:"after_channel"`
WatchLive provider.Duration `yaml:"watch_live"`
AfterWatch provider.Duration `yaml:"after_watch"`
Playback provider.Duration `yaml:"playback"`
LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
LaunchSettle provider.Duration `yaml:"launch_settle"`
Playback provider.Duration `yaml:"playback"`
}
// UI markers for launch readiness and interactive navigation.
// UI markers for launch readiness (localized; keep loose).
type UI struct {
LaunchDescContains []string `yaml:"launch_desc_contains"`
LaunchResourceContains []string `yaml:"launch_resource_contains"`
// ExploreTab is bottom-nav text/desc for the Explore page.
ExploreTab []string `yaml:"explore_tab"`
// WatchLive is the channel-page play control.
WatchLive []string `yaml:"watch_live"`
// PlaybackDescContains are soft player-up signals.
PlaybackDescContains []string `yaml:"playback_desc_contains"`
// ChannelScrollMax limits horizontal swipes while hunting a channel logo.
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(4 * time.Second))
t.ExploreNav = provider.Duration(t.ExploreNav.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.AfterWatch = provider.Duration(t.AfterWatch.D(2 * time.Second))
t.Playback = provider.Duration(t.Playback.D(60 * time.Second))
u := &c.UI
if len(u.LaunchDescContains) == 0 {
u.LaunchDescContains = []string{"Home", "Explore", "Watchlist", "Watch now", "iPlayer"}
}
if len(u.ExploreTab) == 0 {
u.ExploreTab = []string{"Explore"}
}
if len(u.WatchLive) == 0 {
u.WatchLive = []string{"Watch live", "Watch Live", "Watch now"}
}
if len(u.PlaybackDescContains) == 0 {
u.PlaybackDescContains = []string{"Pause", "pause", "Player", "Seek", "scrubber"}
}
if u.ChannelScrollMax <= 0 {
u.ChannelScrollMax = 10
if len(c.UI.LaunchDescContains) == 0 {
c.UI.LaunchDescContains = []string{"iPlayer", "Home", "Live"}
}
return c
}
func (ch Channel) chipPatterns() []string {
if len(ch.ChipDesc) > 0 {
return ch.ChipDesc
}
if ch.Label != "" {
return []string{"^" + regexp.QuoteMeta(ch.Label) + "$", ch.Label}
}
return nil
}
func (ch Channel) playPatterns(ui UI) []string {
if len(ch.PlayDesc) > 0 {
return ch.PlayDesc
}
return ui.WatchLive
}
var flags struct {
packageName string
caHash string

View file

@ -1,93 +0,0 @@
# BBC iPlayer — published universal values (renamed to module.yaml in release zips).
# No secrets. Local overrides / ca_hash / proxy_bin go in gitignored module.yaml.
package: bbc.iplayer.android
proxy_bin: bin/proxy-android-arm64
# Manifest-URL scoring for the on-device MITM / waiter.
score:
hosts:
- open.live.bbc.co.uk
- vs-cmaf-push-uk
- vod-dash-uk
- akamaized.net
- bbci.co.uk
- bidi.net.uk
- bidi.bbc.co.uk
deny:
- telemetry.api.bbci
- bag.api.bbc
- ibl.api.bbci
- thumbnail
aliases:
one: bbcone
bbc1: bbcone
london: bbcone
two: bbctwo
bbc2: bbctwo
three: bbcthree
bbc3: bbcthree
four: bbcfour
bbc4: bbcfour
news: bbcnews
scotland: bbcscotland
alba: bbcalba
parliament: bbcparliament
radio1: bbcradio1
radio: bbcradio1
# Labels must match Explore-rail content-desc for interactive autoplay.
channels:
bbcone:
label: BBC One
vpid: bbc_one_london
bbctwo:
label: BBC Two
vpid: bbc_two_england
bbcthree:
label: BBC Three
vpid: bbc_three
bbcfour:
label: BBC Four
vpid: bbc_four
bbcnews:
label: BBC News
vpid: bbc_news_channel
bbcscotland:
label: BBC Scotland
vpid: bbc_scotland
bbcalba:
label: BBC ALBA
vpid: bbc_alba
bbcparliament:
label: BBC Parliament
vpid: bbc_parliament
cbbc:
label: CBBC
vpid: cbbc
cbeebies:
label: CBeebies
vpid: cbeebies
s4c:
label: S4C
vpid: s4c
bbcradio1:
label: BBC Radio 1
vpid: bbc_radio_one
# Interactive auto-play: Explore → channel logo → Watch live.
timeouts:
launch_wait_ui: 30s
launch_settle: 4s
explore_nav: 20s
channel_find: 45s
after_channel: 3s
watch_live: 20s
playback: 60s
ui:
launch_desc_contains: ["Home", "Explore", "Watchlist", "Watch now"]
explore_tab: ["Explore"]
watch_live: ["Watch live", "Watch Live"]
playback_desc_contains: ["Pause", "pause", "Seek"]
channel_scroll_max: 12

View file

@ -0,0 +1,51 @@
# BBC iPlayer — published values. Package id and channel map only;
# no Widevine license URL (mobile-phone-main streams are clear).
package: bbc.iplayer.android
proxy_bin: bin/proxy-android-arm64
ca_hash: "6c3578b4"
# Manifest-URL scoring for the on-device MITM / waiter.
score:
hosts:
- open.live.bbc.co.uk
- vs-cmaf-push-uk
- vod-dash-uk
- akamaized.net
- bbci.co.uk
- bidi.net.uk
- bidi.bbc.co.uk
deny:
- telemetry.api.bbci
- bag.api.bbc
- ibl.api.bbci
- thumbnail
aliases:
one: bbcone
bbc1: bbcone
london: bbcone
two: bbctwo
bbc2: bbctwo
news: bbcnews
four: bbcfour
channels:
bbcone:
label: BBC One
vpid: bbc_one_london
bbctwo:
label: BBC Two
vpid: bbc_two_england
bbcnews:
label: BBC News
vpid: bbc_news_channel
bbcfour:
label: BBC Four
vpid: bbc_four
# timeouts:
# launch_wait_ui: 30s
# playback: 60s
# ui:
# launch_desc_contains: ["iPlayer", "Home", "Live"]

View file

@ -1,237 +0,0 @@
package bbc
import (
"fmt"
"regexp"
"strings"
"time"
"streamd/adb"
"streamd/uiflow"
)
// openExplorePage taps the Explore bottom-nav tab and waits for the channel rail.
func (a *App) openExplorePage(c *adb.Client) error {
c.DismissShadeIfFocused()
if nodes, err := c.DumpUI(a.CacheDir()); err == nil && a.onExplorePage(nodes) {
fmt.Println("[*] already on Explore")
return nil
}
fmt.Println("[*] open Explore…")
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
TextContains: a.cfg.UI.ExploreTab,
DescContains: a.cfg.UI.ExploreTab,
Pick: uiflow.PickFirst,
}, time.Duration(a.cfg.Timeouts.ExploreNav)); err != nil {
return fmt.Errorf("Explore tab: %w", err)
}
time.Sleep(1500 * time.Millisecond)
deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.ExploreNav))
for time.Now().Before(deadline) {
nodes, err := c.DumpUI(a.CacheDir())
if err == nil && a.onExplorePage(nodes) {
fmt.Println("[*] Explore page ready")
return nil
}
time.Sleep(700 * time.Millisecond)
}
return fmt.Errorf("Explore page did not open")
}
// onExplorePage is true when channel logos (BBC One / BBC Two / …) are visible.
// The Channels header alone is not enough — logos load a moment later.
func (a *App) onExplorePage(nodes []adb.Node) bool {
channelish := 0
for _, n := range nodes {
if looksLikeChannelLogo(strings.TrimSpace(n.Desc)) {
channelish++
}
}
return channelish >= 2
}
func looksLikeChannelLogo(desc string) bool {
d := strings.ToLower(strings.TrimSpace(desc))
if d == "" {
return false
}
if strings.HasPrefix(d, "bbc ") || d == "cbbc" || d == "cbeebies" || d == "s4c" {
return true
}
return false
}
// tapChannel finds the channel logo on the Explore rail (scrolling horizontally
// when needed) and taps it.
func (a *App) tapChannel(c *adb.Client, ch Channel) error {
pats := uiflow.CompileRes(ch.chipPatterns())
if len(pats) == 0 {
return fmt.Errorf("no chip selectors for channel %q", ch.Label)
}
deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.ChannelFind))
scrolled := 0
for time.Now().Before(deadline) {
nodes, err := c.DumpUI(a.CacheDir())
if err != nil {
time.Sleep(800 * time.Millisecond)
continue
}
// Match content-desc on the logo node (often not itself clickable —
// the parent View shares bounds and receives the tap).
if n := findChannelLogo(nodes, pats); n != nil {
label := strings.TrimSpace(n.Desc)
if label == "" {
label = strings.TrimSpace(n.Text)
}
fmt.Printf("[*] tap channel %q @ %d,%d\n", label, n.CX(), n.CY())
return c.Tap(n.CX(), n.CY())
}
// Already on the channel page?
if a.onChannelPage(nodes, ch) {
fmt.Printf("[*] already on %s page\n", ch.Label)
return nil
}
logos := channelLogoNodes(nodes)
if len(logos) == 0 {
// Rail still loading — wait, do not swipe random mid-screen coords.
time.Sleep(800 * time.Millisecond)
continue
}
if scrolled >= a.cfg.UI.ChannelScrollMax {
break
}
x1, y, x2 := channelRailSwipe(logos)
fmt.Printf("[*] channel %q not on screen — swipe rail %d→%d @ y=%d (%d logos)\n", ch.Label, x1, x2, y, len(logos))
_ = c.Swipe(x1, y, x2, y, 350)
scrolled++
time.Sleep(900 * time.Millisecond)
}
return fmt.Errorf("channel logo %q not found on Explore", ch.Label)
}
func findChannelLogo(nodes []adb.Node, pats []*regexp.Regexp) *adb.Node {
var best *adb.Node
for i := range nodes {
n := &nodes[i]
desc := strings.TrimSpace(n.Desc)
text := strings.TrimSpace(n.Text)
matched := false
for _, p := range pats {
if desc != "" && p.MatchString(desc) {
matched = true
break
}
if text != "" && p.MatchString(text) {
matched = true
break
}
}
if !matched {
continue
}
// Prefer smaller logo tiles over large hero cards.
if best == nil || n.Area() < best.Area() {
best = n
}
}
return best
}
func channelLogoNodes(nodes []adb.Node) []adb.Node {
var out []adb.Node
for _, n := range nodes {
if looksLikeChannelLogo(strings.TrimSpace(n.Desc)) {
out = append(out, n)
}
}
return out
}
func (a *App) onChannelPage(nodes []adb.Node, ch Channel) bool {
label := strings.TrimSpace(ch.Label)
hasTitle := false
hasWatch := false
for _, n := range nodes {
text := strings.TrimSpace(n.Text)
desc := strings.TrimSpace(n.Desc)
if label != "" && (strings.EqualFold(text, label) || strings.EqualFold(desc, label)) {
hasTitle = true
}
for _, w := range a.cfg.UI.WatchLive {
if w != "" && (strings.EqualFold(text, w) || strings.EqualFold(desc, w) ||
strings.Contains(strings.ToLower(text), strings.ToLower(w)) ||
strings.Contains(strings.ToLower(desc), strings.ToLower(w))) {
hasWatch = true
}
}
}
return hasTitle && hasWatch
}
// channelRailSwipe picks a horizontal swipe across visible channel logos.
func channelRailSwipe(logos []adb.Node) (x1, y, x2 int) {
minX, maxX := logos[0].X1, logos[0].X2
sumY := 0
for _, n := range logos {
if n.X1 < minX {
minX = n.X1
}
if n.X2 > maxX {
maxX = n.X2
}
sumY += n.CY()
}
y = sumY / len(logos)
width := maxX - minX
if width < 400 {
// Single/partial logo visible — swipe across a wide band around it.
cx := (minX + maxX) / 2
return cx + 400, y, cx - 400
}
x1 = minX + width*85/100
x2 = minX + width*15/100
if x1-x2 < 200 {
cx := (minX + maxX) / 2
return cx + 350, y, cx - 350
}
return x1, y, x2
}
// tapWatchLive taps the Watch live control on the channel page.
func (a *App) tapWatchLive(c *adb.Client, ch Channel) error {
pats := ch.playPatterns(a.cfg.UI)
if nodes, err := c.DumpUI(a.CacheDir()); err == nil {
if playingUI(nodes, a.cfg.UI.PlaybackDescContains) {
fmt.Println("[*] player UI already up")
return nil
}
}
fmt.Println("[*] tap Watch live…")
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
TextContains: pats,
DescContains: pats,
TextRE: pats,
DescRE: pats,
Pick: uiflow.PickLargest,
MinArea: 800,
}, time.Duration(a.cfg.Timeouts.WatchLive)); err != nil {
return fmt.Errorf("Watch live: %w", err)
}
time.Sleep(time.Duration(a.cfg.Timeouts.AfterWatch))
return nil
}
func playingUI(nodes []adb.Node, signals []string) bool {
for _, n := range nodes {
blob := strings.ToLower(n.Text + " " + n.Desc + " " + n.ResourceID)
for _, s := range signals {
if s != "" && strings.Contains(blob, strings.ToLower(s)) {
return true
}
}
}
return false
}

View file

@ -1,148 +0,0 @@
// 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 }

View file

@ -1,116 +0,0 @@
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

@ -1,84 +0,0 @@
# 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

View file

@ -1,175 +0,0 @@
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 streamd/modules
module drmdecryption/modules
go 1.25.0
require streamd v0.0.0
require drmdecryption v0.0.0
require gopkg.in/yaml.v3 v3.0.1 // indirect
replace streamd => ../pkg
replace drmdecryption => ../pkg

View file

@ -1,116 +0,0 @@
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
}

View file

@ -1,124 +0,0 @@
// 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

@ -1,90 +0,0 @@
# 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

View file

@ -1,153 +0,0 @@
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")
}

View file

@ -1,133 +0,0 @@
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

@ -1,118 +0,0 @@
# 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

View file

@ -1,160 +0,0 @@
// 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 }

View file

@ -1,265 +0,0 @@
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"
"strings"
"streamd/capture"
"streamd/modcfg"
"streamd/phonecap"
"streamd/repo"
"drmdecryption/capture"
"drmdecryption/modcfg"
"drmdecryption/phonecap"
"drmdecryption/repo"
)
// Common is the part of a module.yaml that every module has. Modules embed it in
@ -25,9 +25,6 @@ type Common struct {
CAHash string `yaml:"ca_hash"`
Aliases map[string]string `yaml:"aliases"`
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.
@ -56,8 +53,7 @@ func (b *Base) CacheDir() string { return b.cacheDir }
func (b *Base) ConfigPath() string { return b.cfg.Path }
func (b *Base) ConfigLoaded() bool { return b.cfg.Loaded }
// ProxyBin resolves the on-device MITM binary. Empty means “auto” (caller uses
// proxy.FindLocalBin — next to streamd, then repo bin/).
// ProxyBin resolves the on-device MITM binary, relative paths against repo root.
func (b *Base) ProxyBin() string {
if b.common.ProxyBin != "" {
return modcfg.Resolve(b.common.ProxyBin)
@ -71,18 +67,7 @@ func (b *Base) ProxyBin() string {
return p
}
}
if exe, err := os.Executable(); err == nil {
dir := filepath.Dir(exe)
for _, p := range []string{
filepath.Join(dir, "proxy-android-arm64"),
filepath.Join(dir, "bin", "proxy-android-arm64"),
} {
if st, err := os.Stat(p); err == nil && !st.IsDir() {
return p
}
}
}
return ""
return filepath.Join(root, "bin", "proxy-android-arm64")
}
func (b *Base) CAHash() string {
@ -97,18 +82,6 @@ func (b *Base) Score() capture.ScoreCfg {
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.
func (b *Base) Hints(require ...string) capture.Hints {
h := capture.DefaultHints()

View file

@ -3,9 +3,9 @@ package rte
import (
"time"
"streamd/modcfg"
"streamd/modules/provider"
"streamd/mpd"
"drmdecryption/modcfg"
"drmdecryption/modules/provider"
"drmdecryption/mpd"
)
// Name is the module id (--app rte).
@ -87,12 +87,10 @@ func (c Config) withDefaults() Config {
t.AfterLiveTab = provider.Duration(t.AfterLiveTab.D(2 * time.Second))
t.AfterChip = provider.Duration(t.AfterChip.D(2 * time.Second))
if len(c.UI.LaunchDescContains) == 0 {
c.UI.LaunchDescContains = []string{"live tab", "header logo", "Home tab"}
c.UI.LaunchDescContains = []string{"live tab", "header logo"}
}
if len(c.UI.LiveTabDescRE) == 0 {
// Anchor to the bottom-nav desc ("Live tab, 2 out of 5"). Bare "Live"
// also matches home "Watch Live" / "Live Event".
c.UI.LiveTabDescRE = []string{"^Live tab"}
c.UI.LiveTabDescRE = []string{"Live tab"}
}
c.Synthetic = c.Synthetic.WithDefaults()
return c

View file

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

View file

@ -1,61 +0,0 @@
# RTE Player — published universal values (renamed to module.yaml in release zips).
# Fill secrets in local module.yaml: license_url, origins, kids (never commit that file).
package: air.RTE.OSMF.Minimal
proxy_bin: bin/proxy-android-arm64
# SENSITIVE — set in local module.yaml:
# license_url: "https://…"
score:
hosts:
- live.rte.ie
- dai.google.com
deny:
- feed.entertainment
aliases:
rte1: rteone
one: rteone
rte2: rtetwo
two: rtetwo
jr: rtejr
news: rtenews
newsnow: rtenews
channels:
rteone:
label: RTE One
chip_desc: ["^rteone$"]
play_desc: ["play\\s*rteone"]
rtetwo:
label: RTE 2
chip_desc: ["^rte2$"]
play_desc: ["play\\s*rte2"]
rtejr:
label: RTE jr
chip_desc: ["^rtejr$"]
play_desc: ["play\\s*rte\\s*jr", "play\\s*rtejr"]
rtenews:
label: RTE News Now
chip_desc: ["^rtenewsnow$", "^rtenews$"]
play_desc: ["play\\s*rtenews", "play\\s*rtenewsnow"]
# SENSITIVE — set in local module.yaml:
# origins:
# vc11: "https://…"
# vc12: "https://…"
# kids:
# vc11: "…"
# vc12: "…"
ui:
# "Live" alone matches home "Watch Live" / "Live Event" — keep anchored to the bottom tab.
launch_desc_contains: ["live tab", "header logo", "Home tab"]
live_tab_desc_re: ["^Live tab"]
timeouts:
launch_wait_ui: 30s
launch_settle: 4s
live_tab: 30s
playback: 45s

View file

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

View file

@ -9,12 +9,12 @@ import (
"fmt"
"time"
"streamd/adb"
appreg "streamd/app"
"streamd/capture"
"streamd/modules/provider"
"streamd/mpd"
"streamd/uiflow"
"drmdecryption/adb"
appreg "drmdecryption/app"
"drmdecryption/capture"
"drmdecryption/modules/provider"
"drmdecryption/mpd"
"drmdecryption/uiflow"
)
func init() {
@ -84,7 +84,7 @@ func (a *App) Launch(c *adb.Client) error {
}, time.Duration(a.cfg.Timeouts.LaunchWaitUI))
}
// AutoPlay opens the Live tab (when needed), taps the channel chip, then Play.
// AutoPlay navigates to a live channel and waits for playback.
func (a *App) AutoPlay(c *adb.Client, channel string) error {
id, err := a.Resolve(channel)
if err != nil {
@ -94,9 +94,13 @@ func (a *App) AutoPlay(c *adb.Client, channel string) error {
fmt.Printf("[*] Auto-play %s…\n", a.Label(id))
c.DismissShadeIfFocused()
if err := a.openLiveTab(c); err != nil {
return err
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
DescRE: a.cfg.UI.LiveTabDescRE,
}, time.Duration(a.cfg.Timeouts.LiveTab)); err != nil {
return fmt.Errorf("live tab: %w", err)
}
time.Sleep(time.Duration(a.cfg.Timeouts.AfterLiveTab))
if err := a.tapChipThenPlay(c, ch); err != nil {
return err
}

View file

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

View file

@ -5,62 +5,13 @@ import (
"regexp"
"time"
"streamd/adb"
"streamd/uiflow"
"drmdecryption/adb"
"drmdecryption/uiflow"
)
// openLiveTab taps the bottom-nav Live tab and waits for channel chips.
// Home also shows a "Watch Live" label and a "Live Event" row — those must not
// match. The real control's content-desc is "Live tab, N out of 5".
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…")
if err := uiflow.TapUI(c, a.CacheDir(), uiflow.Match{
DescRE: a.cfg.UI.LiveTabDescRE,
Pick: uiflow.PickSmallest,
}, time.Duration(a.cfg.Timeouts.LiveTab)); err != nil {
return fmt.Errorf("live tab: %w", err)
}
time.Sleep(time.Duration(a.cfg.Timeouts.AfterLiveTab))
deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.LiveTab))
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")
}
// onLiveTab is true when channel chips are on screen. Home often embeds the
// same chip rail, so this also short-circuits when Play is already reachable
// without tapping the bottom-nav Live tab.
func (a *App) onLiveTab(nodes []adb.Node) bool {
return a.chipCount(nodes) >= 1
}
func (a *App) chipCount(nodes []adb.Node) int {
n := 0
for _, ch := range a.cfg.Channels {
pats := uiflow.CompileRes(ch.ChipDesc)
if adb.FindSmallest(nodes, pats) != nil {
n++
}
}
return n
}
// tapChipThenPlay is this app's navigation idiom: on the Live tab, tap the
// channel chip, then the large hero Play button that appears. If the hero button
// is already on screen for this channel, tap it directly.
// is already on screen, tap it directly.
func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error {
playPats := uiflow.CompileRes(ch.PlayDesc)
chipPats := uiflow.CompileRes(ch.ChipDesc)
@ -70,30 +21,18 @@ func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error {
return err
}
if cand := a.findHeroPlay(nodes, playPats); cand != nil {
x, y := playTapXY(cand)
fmt.Printf("[*] tap Play %q @ %d,%d\n", cand.Desc, x, y)
return c.Tap(x, y)
fmt.Printf("[*] tap Play @ %d,%d\n", cand.CX(), cand.CY())
return c.Tap(cand.CX(), cand.CY())
}
chip := adb.FindSmallest(nodes, chipPats)
if chip == nil {
deadline := time.Now().Add(time.Duration(a.cfg.Timeouts.ChipWait))
for time.Now().Before(deadline) {
nodes, err = c.DumpUI(a.CacheDir())
if err == nil {
if chip = adb.FindSmallest(nodes, chipPats); chip != nil {
break
}
}
time.Sleep(700 * time.Millisecond)
}
if chip == nil {
return fmt.Errorf("chip not found for %s", ch.Label)
chip, err = c.WaitFor(a.CacheDir(), nil, chipPats, time.Duration(a.cfg.Timeouts.ChipWait))
if err != nil {
return fmt.Errorf("chip not found: %w", err)
}
}
// Chip text nodes are often clickable=false; their centre sits inside a
// larger clickable parent, so a centre tap still lands on the parent.
fmt.Printf("[*] tap chip %q @ %d,%d\n", chip.Desc, chip.CX(), chip.CY())
fmt.Printf("[*] tap chip @ %d,%d\n", chip.CX(), chip.CY())
_ = c.Tap(chip.CX(), chip.CY())
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChip))
@ -102,14 +41,13 @@ func (a *App) tapChipThenPlay(c *adb.Client, ch Channel) error {
nodes, err = c.DumpUI(a.CacheDir())
if err == nil {
if cand := a.findHeroPlay(nodes, playPats); cand != nil {
x, y := playTapXY(cand)
fmt.Printf("[*] tap Play %q @ %d,%d\n", cand.Desc, x, y)
return c.Tap(x, y)
fmt.Printf("[*] tap Play @ %d,%d\n", cand.CX(), cand.CY())
return c.Tap(cand.CX(), cand.CY())
}
}
time.Sleep(700 * time.Millisecond)
}
return fmt.Errorf("Play button did not appear for %s", ch.Label)
return fmt.Errorf("Play button did not appear")
}
// findHeroPlay accepts a Play match only if it is big enough to be the hero
@ -121,14 +59,3 @@ func (a *App) findHeroPlay(nodes []adb.Node, playPats []*regexp.Regexp) *adb.Nod
}
return cand
}
// playTapXY aims at the play icon in the upper half of the hero. The geometric
// centre of the large "Play RTEONE…" node often lands below the hit target and
// the tap is ignored.
func playTapXY(n *adb.Node) (int, int) {
h := n.Y2 - n.Y1
if h < 1 {
return n.CX(), n.CY()
}
return n.CX(), n.Y1 + h*2/5
}

View file

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

View file

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

View file

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

View file

@ -1,64 +0,0 @@
# TG4 — published universal values (renamed to module.yaml in release zips).
# Fill secrets in local module.yaml: account_id, policy_key, playback_config_url,
# and per-channel video_id / token_field / stream_id_field (never commit that file).
package: ie.bytes.tg4.tg4videoapp
proxy_bin: bin/proxy-android-arm64
# SENSITIVE — set in local module.yaml:
# account_id: "…"
# policy_key: "…"
# playback_config_url: "https://…"
score:
hosts:
- fastly.live.brightcove.com
deny:
- metrics.brightcove
- gnsnpaw.com
aliases:
tg4: ioi
live: ioi
ireland: ioi
cula: cula4
plus1: plus
"tg4+": plus
tg4plus: plus
worldwide: ww
tg4sport: sport
sporttg4: sport
channels:
ioi:
label: "TG4 (IOI)"
live_card_index: 0
# video_id / token_field / stream_id_field → local module.yaml
cula4:
label: "Cúla4"
live_card_index: 1
plus:
label: "TG4+1"
live_card_index: 2
sport:
label: "Sport TG4"
phone_only: true
live_card_index: 3
ww:
label: "TG4 Worldwide"
live_card_index: 0
ui:
launch_resource_contains:
- rails_swipe_refresh_layout
- fragment_drawer_toolbar
live_label: live
playback_desc_contains: ["video player"]
playback_resource_contains: ["brightcove_video_view"]
timeouts:
launch_wait_ui: 30s
launch_settle: 4s
live_nav: 25s
card: 30s
playback: 45s

View file

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

View file

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

View file

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

View file

@ -1,10 +1,10 @@
# pkg — shared Go libraries
Imported by `apps/capture`, `apps/agent`, `apps/streamd`, `apps/proxy`, `apps/cli`
and `apps/modules` as module `streamd` via:
and `apps/modules` as module `drmdecryption` via:
```go
replace streamd => ../pkg
replace drmdecryption => ../pkg
```
## Packages
@ -34,4 +34,4 @@ provider values live in that module's gitignored `module.yaml`.
go -C apps/pkg test ./...
```
No binary of its own — everything ships in `bin/streamd`, built from `apps/cli`.
No binary of its own — everything ships in `bin/drm`, built from `apps/cli`.

View file

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

View file

@ -6,10 +6,10 @@ import (
"sort"
"sync"
"streamd/adb"
"streamd/capture"
"streamd/mpd"
"streamd/session"
"drmdecryption/adb"
"drmdecryption/capture"
"drmdecryption/mpd"
"drmdecryption/session"
)
// Channel is a named live target inside an app (e.g. rteone).
@ -83,25 +83,6 @@ type TransparentMITM interface {
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 (
mu sync.RWMutex
registry = map[string]func() (App, error){}

View file

@ -1,171 +0,0 @@
// Package bootstrap materialises a GitHub-like install tree next to streamd
// so a single downloaded binary can create apps/, bin/, outputs/, etc. on first run.
package bootstrap
import (
"embed"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
)
//go:embed all:embedded
var embedded embed.FS
const minProxyBytes = 100_000 // stub ELF is tiny; real proxy-android-arm64 is ~9MB
// InstallRoot is the directory that should contain apps/, bin/, outputs/.
// If streamd lives in …/bin/, the parent is the root; otherwise the exe directory.
func InstallRoot() (string, error) {
exe, err := os.Executable()
if err != nil {
return "", err
}
exe, err = filepath.EvalSymlinks(exe)
if err != nil {
exe, _ = os.Executable()
}
dir := filepath.Dir(exe)
if strings.EqualFold(filepath.Base(dir), "bin") {
return filepath.Dir(dir), nil
}
return dir, nil
}
// Ensure writes any missing layout files from the embedded tree into root.
// Existing files are left untouched (user edits to module.yaml are kept).
func Ensure(root string) (created []string, err error) {
if root == "" {
root, err = InstallRoot()
if err != nil {
return nil, err
}
}
err = fs.WalkDir(embedded, "embedded", func(path string, d fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
// embed.FS paths always use forward slashes — do not use filepath.Rel (Windows).
slashRel := strings.TrimPrefix(path, "embedded/")
if slashRel == path || slashRel == "embedded" || slashRel == "." {
return nil
}
// go:embed rejects files named go.mod. We ship root-go-mod.txt (and
// optionally apps/pkg/pkg.gomod) and materialise apps/pkg/go.mod.
outSlash := slashRel
switch slashRel {
case "root-go-mod.txt", "apps/pkg/pkg.gomod":
outSlash = "apps/pkg/go.mod"
}
dest := filepath.Join(root, filepath.FromSlash(outSlash))
if d.IsDir() {
return os.MkdirAll(dest, 0o755)
}
if st, err := os.Stat(dest); err == nil && !st.IsDir() {
return nil // keep existing
}
data, err := embedded.ReadFile(path)
if err != nil {
return err
}
// Do not write the tiny release stub as a real MITM binary.
if slashRel == "bin/proxy-android-arm64" && len(data) < minProxyBytes {
return nil
}
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return err
}
mode := os.FileMode(0o644)
if strings.HasSuffix(outSlash, "proxy-android-arm64") || strings.HasSuffix(outSlash, ".sh") {
mode = 0o755
}
if err := os.WriteFile(dest, data, mode); err != nil {
return err
}
created = append(created, outSlash)
return nil
})
if err != nil {
return created, err
}
// If streamd is not already under bin/, copy it there for 1:1 layout.
if err := ensureBinHost(root); err != nil {
return created, err
}
return created, nil
}
func ensureBinHost(root string) error {
exe, err := os.Executable()
if err != nil {
return nil
}
exe, _ = filepath.EvalSymlinks(exe)
return copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe"))
}
func copyExeIfMissing(src, dest string) error {
if sameFile(src, dest) {
return nil
}
if st, err := os.Stat(dest); err == nil && !st.IsDir() {
return nil
}
data, err := os.ReadFile(src)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return err
}
return os.WriteFile(dest, data, 0o755)
}
func sameFile(a, b string) bool {
absA, err1 := filepath.Abs(a)
absB, err2 := filepath.Abs(b)
if err1 != nil || err2 != nil {
return false
}
return strings.EqualFold(absA, absB)
}
// EnsureAndLog runs Ensure and prints what was created (if anything).
func EnsureAndLog() error {
return EnsureAndLogFor("")
}
// EnsureAndLogFor is EnsureAndLog with an optional subcommand hint so proxy-only
// runs do not warn about missing modules/.
func EnsureAndLogFor(cmd string) error {
root, err := InstallRoot()
if err != nil {
return err
}
created, err := Ensure(root)
if err != nil {
return err
}
if len(created) > 0 {
fmt.Printf("[*] Bootstrapped install layout under %s (%d new files)\n", root, len(created))
for _, c := range created {
fmt.Printf(" + %s\n", filepath.ToSlash(c))
}
}
proxy := filepath.Join(root, "bin", "proxy-android-arm64")
if st, err := os.Stat(proxy); err != nil || st.Size() < minProxyBytes {
fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to streamd or use a release build that embeds it\n")
}
// Providers live under modules/; only warn when the command needs them.
needsModules := cmd == "" || cmd == "modules" || cmd == "capture" || cmd == "catalog" || cmd == "agent" || cmd == "serve"
if needsModules {
modBBC := filepath.Join(root, "modules", "bbc", "module.yaml")
if _, err := os.Stat(modBBC); err != nil {
fmt.Fprintf(os.Stderr, "[!] no modules/*/ yet — add e.g. modules/bbc/ (Go source + module.yaml); see modules/README.md\n")
}
}
return nil
}

View file

@ -1,22 +0,0 @@
# Streamd
Host binary **`streamd`** + providers under **`modules/`**.
## Quick start
1. Download `streamd` (`v*` release) and module zips (`modules-v*` release).
2. Unzip providers into `modules/<name>/` and edit `module.yaml` (secrets only).
3. `streamd proxy install-ca --reinject`
4. `streamd capture --app bbc --channel bbcone --wait 120`
5. `streamd proxy reset` when finished.
```text
drm modules
drm capture --app NAME [--channel ID] [--wvd PATH]
drm catalog --app NAME --channel ID [--keys] [--json]
drm proxy install-ca --reinject | reset | transparent --package PKG
```
`--modules-dir DIR` or `$STREAMD_MODULES_DIR` selects another modules folder.
Full docs: https://git.nulldrm.com/nulldrm/Null-DRM-Official

View file

@ -1,5 +0,0 @@
module streamd
go 1.25.0
require gopkg.in/yaml.v3 v3.0.1

View file

@ -1,81 +0,0 @@
#!/system/bin/sh
# Transparent redirect: package UID TCP/443 → local appproxy (no Wi‑Fi http_proxy).
# Usage:
# tproxy_iptables.sh start <package> [port]
# tproxy_iptables.sh stop
# tproxy_iptables.sh status
set -eu
CHAIN=APPROXY_TPROXY
ACTION="${1:-}"
uid_for_package() {
pkg="$1"
# dumpsys package <pkg> | grep userId= OR stat on data dir
uid=$(dumpsys package "$pkg" 2>/dev/null | grep -m1 -oE 'userId=[0-9]+' | head -1 | cut -d= -f2 || true)
if [ -z "$uid" ]; then
uid=$(stat -c %u "/data/user/0/$pkg" 2>/dev/null || true)
fi
echo "$uid"
}
stop_rules() {
iptables -t nat -D OUTPUT -j "$CHAIN" 2>/dev/null || true
iptables -t nat -F "$CHAIN" 2>/dev/null || true
iptables -t nat -X "$CHAIN" 2>/dev/null || true
echo "STOPPED"
}
start_rules() {
pkg="$1"
port="$2"
uid=$(uid_for_package "$pkg")
if [ -z "$uid" ] || [ "$uid" = "0" ]; then
echo "ERR: cannot resolve uid for package $pkg" >&2
exit 1
fi
proxy_uid=$(stat -c %u /data/local/tmp/appproxy 2>/dev/null || echo "")
# Prefer the running process uid if available
if pidof appproxy >/dev/null 2>&1; then
proxy_uid=$(stat -c %u /proc/$(pidof appproxy | awk '{print $1}') 2>/dev/null || echo "$proxy_uid")
fi
stop_rules >/dev/null
iptables -t nat -N "$CHAIN"
# Never redirect the mitm itself (loop).
if [ -n "$proxy_uid" ]; then
iptables -t nat -A "$CHAIN" -m owner --uid-owner "$proxy_uid" -j RETURN
fi
# Skip localhost / link-local.
iptables -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
# 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"
iptables -t nat -A OUTPUT -j "$CHAIN"
echo "STARTED pkg=$pkg uid=$uid port=$port proxy_uid=${proxy_uid:-unknown}"
}
status_rules() {
echo "=== $CHAIN ==="
iptables -t nat -L "$CHAIN" -n -v 2>/dev/null || echo "(no chain)"
echo "=== OUTPUT head ==="
iptables -t nat -L OUTPUT -n -v 2>/dev/null | head -20
}
case "$ACTION" in
start)
pkg="${2:?package required}"
port="${3:-8080}"
start_rules "$pkg" "$port"
;;
stop)
stop_rules
;;
status)
status_rules
;;
*)
echo "usage: $0 start <package> [port] | stop | status" >&2
exit 2
;;
esac

View file

@ -1,6 +0,0 @@
# 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

@ -1,367 +0,0 @@
#!/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,2 +0,0 @@
# Optional local configs

View file

@ -1,20 +0,0 @@
# External modules
Each subdirectory is a provider the `streamd` host discovers, builds, and runs.
```
modules/
bbc/
module.yaml # your values (required for channels)
go.mod + *.go # provider CLI (or ship prebuilt under .bin/)
.bin/bbc.exe # built on demand
```
The host binary does **not** embed providers. Add a folder here, then:
```
drm modules
drm capture --app bbc --channel bbcone
```
Requires Go on PATH to build from source. Release zips may ship `.bin/` prebuilt.

View file

@ -1,5 +0,0 @@
module streamd
go 1.25.0
require gopkg.in/yaml.v3 v3.0.1

View file

@ -9,7 +9,7 @@ import (
"strings"
"time"
"streamd/adb"
"drmdecryption/adb"
)
// Hints tell the waiter which fields / log tags mean a capture is complete.
@ -24,9 +24,6 @@ type Hints struct {
// Score ranks candidate manifest URLs. Zero value falls back to
// DefaultScoreCfg, which has no provider hosts.
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
@ -62,23 +59,10 @@ func DefaultPassiveHints() Hints {
// score applies the hints' URL scoring, defaulting when unset.
func (h Hints) score(u string) int {
var sc int
if len(h.Score.Deny) == 0 && len(h.Score.Hosts) == 0 {
sc = DefaultScoreCfg().Score(u)
} else {
sc = h.Score.Score(u)
return DefaultScoreCfg().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
return h.Score.Score(u)
}
// Data is the merged capture payload before key fetch.
@ -86,25 +70,6 @@ type Data map[string]string
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.
func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout time.Duration) (Data, error) {
deadline := time.Now().Add(timeout)
@ -139,7 +104,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
enrichFromProxyLog(cap, logText, hints)
if hints.BestEffort {
if hasUseful(cap, hints) && preferSatisfied(cap, hints) {
if hasUseful(cap, hints) {
_ = os.WriteFile(localCap, mustJSON(cap), 0o644)
return cap, nil
}
@ -151,7 +116,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
break
}
}
if !missing && preferSatisfied(cap, hints) {
if !missing {
_ = os.WriteFile(localCap, mustJSON(cap), 0o644)
return cap, nil
}
@ -160,7 +125,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
have := []string{}
keys := hints.Require
if hints.BestEffort {
keys = []string{"mpd", "license_url", "pssh", "auth", "pid", "license_body"}
keys = []string{"mpd", "license_url", "pssh", "auth", "pid"}
}
for _, k := range keys {
if cap[k] != "" {
@ -260,8 +225,7 @@ func enrichFromProxyLog(cap Data, logText string, hints Hints) {
if sc <= 0 {
return
}
// Prefer higher score; on a tie keep the later URL (last stream played).
if sc > bestScore || (sc == bestScore && sc > 0) {
if sc > bestScore {
bestScore = sc
bestMPD = u
}

View file

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

View file

@ -1,12 +1,10 @@
// Package modcfg loads an app module's values from modules/<name>/,
// with environment-variable overrides.
// Package modcfg loads an app module's values from its local, untracked
// apps/modules/<name>/module.yaml, with environment-variable overrides.
//
// Load order:
// 1. module-publish.yaml (tracked universal template) if present
// 2. module.yaml (local / release copy; may add secrets) overlays on top
//
// Local module.yaml is gitignored and never published. Release zips ship
// module-publish.yaml renamed to module.yaml.
// Compiled-in module code is tracked in git and must contain no account ids,
// policy keys, video ids, license URLs or origin hostnames. Those live here, in
// a file git ignores, and can also be supplied by flag or environment so a run
// needs no file at all.
package modcfg
import (
@ -15,116 +13,42 @@ import (
"path/filepath"
"strings"
"streamd/modhost"
"streamd/repo"
"drmdecryption/repo"
"gopkg.in/yaml.v3"
)
// Dir returns the directory holding a module's values.
// 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.
// Dir returns the directory holding a module's local values.
func Dir(name string) string {
preferred := filepath.Join(modhost.ModulesDir(""), name)
if st, err := os.Stat(preferred); err == nil && st.IsDir() {
return preferred
}
if modhost.ModulesDirOverride() != "" {
return preferred
}
if beside := dirBesideExecutable(name); beside != "" {
return beside
}
root := repo.Root()
if _, err := os.Stat(filepath.Join(root, "modules")); err == nil {
return filepath.Join(root, "modules", name)
}
return filepath.Join(root, "apps", "modules", name)
return filepath.Join(repo.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 module's values file path.
func Path(name string) string {
return filepath.Join(Dir(name), "module.yaml")
}
// PublishPath is the tracked universal template.
func PublishPath(name string) string {
return filepath.Join(Dir(name), "module-publish.yaml")
}
// Result reports where a module's values came from, for `drm modules`.
type Result struct {
Path string
Loaded bool
}
// Load reads module-publish.yaml then overlays module.yaml into dst.
// Missing files are not an error — the module runs on Go defaults plus flags/env.
// Load reads apps/modules/<name>/module.yaml into dst. A missing file is not an
// error — the module runs on its Go defaults plus flags/env.
func Load(name string, dst any) (Result, error) {
dir := Dir(name)
publish := filepath.Join(dir, "module-publish.yaml")
local := filepath.Join(dir, "module.yaml")
res := Result{Path: local}
loadedAny := false
if b, err := os.ReadFile(publish); err == nil {
if err := yaml.Unmarshal(b, dst); err != nil {
return res, fmt.Errorf("%s: %w", publish, err)
path := Path(name)
res := Result{Path: path}
b, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return res, nil
}
loadedAny = true
res.Path = publish
} else if !os.IsNotExist(err) {
return res, err
}
if b, err := os.ReadFile(local); err == nil {
if err := yaml.Unmarshal(b, dst); err != nil {
return res, fmt.Errorf("%s: %w", local, err)
}
loadedAny = true
res.Path = local
} else if !os.IsNotExist(err) {
return res, err
if err := yaml.Unmarshal(b, dst); err != nil {
return res, fmt.Errorf("%s: %w", path, err)
}
res.Loaded = loadedAny
res.Loaded = true
return res, nil
}
@ -146,6 +70,7 @@ func Env(module, field string) string {
}
// Override picks the first non-empty of: flag value, environment, current value.
// Use it in a module's config resolution so precedence is uniform.
func Override(module, field, flagVal, current string) string {
if strings.TrimSpace(flagVal) != "" {
return flagVal

View file

@ -1,107 +0,0 @@
package modhost
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// EnsureBuilt returns the path to the module binary, building from Go source
// when needed. Prebuilt .bin/ is used as-is when source is absent.
func EnsureBuilt(m Module) (string, error) {
bin := m.BinPath()
hasSrc := hasGoSource(m.Dir)
binOK := fileExists(bin)
if !hasSrc && !binOK {
return "", fmt.Errorf("module %s: no Go source in %s and no binary at %s", m.Name, m.Dir, bin)
}
if binOK && (!hasSrc || !sourceNewerThan(m.Dir, bin)) {
return bin, nil
}
goBin, err := findGo()
if err != nil {
if binOK {
fmt.Fprintf(os.Stderr, "[!] go not found; using existing %s\n", bin)
return bin, nil
}
return "", fmt.Errorf("module %s needs building but go is not on PATH: %w", m.Name, err)
}
if err := os.MkdirAll(filepath.Dir(bin), 0o755); err != nil {
return "", err
}
fmt.Printf("[*] Building module %s → %s\n", m.Name, bin)
cmd := exec.Command(goBin, "build", "-trimpath", "-ldflags=-s -w", "-o", bin, ".")
cmd.Dir = m.Dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("go build module %s: %w", m.Name, err)
}
return bin, nil
}
func hasGoSource(dir string) bool {
if fileExists(filepath.Join(dir, "go.mod")) {
return true
}
ents, err := os.ReadDir(dir)
if err != nil {
return false
}
for _, e := range ents {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".go") {
return true
}
}
return false
}
func sourceNewerThan(dir, bin string) bool {
bst, err := os.Stat(bin)
if err != nil {
return true
}
binTime := bst.ModTime()
newer := false
_ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
if info != nil && info.IsDir() && (info.Name() == ".bin" || info.Name() == "vendor") {
return filepath.SkipDir
}
return nil
}
name := info.Name()
if strings.HasSuffix(name, ".go") || name == "go.mod" || name == "go.sum" {
if info.ModTime().After(binTime) {
newer = true
}
}
return nil
})
return newer
}
func findGo() (string, error) {
if p, err := exec.LookPath("go"); err == nil {
return p, nil
}
home, _ := os.UserHomeDir()
candidates := []string{
filepath.Join(home, "go-sdk", "go", "bin", "go"),
filepath.Join(home, "go-sdk", "go", "bin", "go.exe"),
filepath.Join(home, "sdk", "go", "bin", "go"),
`C:\Program Files\Go\bin\go.exe`,
"/usr/local/go/bin/go",
}
for _, c := range candidates {
if st, err := os.Stat(c); err == nil && !st.IsDir() {
return c, nil
}
}
return "", fmt.Errorf("go binary not found (install Go or add it to PATH)")
}

View file

@ -1,140 +0,0 @@
package modhost
import (
"os"
"path/filepath"
"runtime"
"strings"
)
// Module is one on-disk provider under modules/<name>/.
type Module struct {
Name string // directory base name, e.g. "bbc"
Dir string // absolute path to modules/<name>
}
// ModulesDir returns the modules directory (honours --modules-dir / STREAMD_MODULES_DIR / DRM_MODULES_DIR).
func ModulesDir(root string) string {
return EffectiveModulesDir(root)
}
// Discover lists modules/<name>/ directories that look like providers
// (have module.yaml / module-publish.yaml and/or Go source and/or a prebuilt binary).
func Discover(root string) ([]Module, error) {
dir := ModulesDir(root)
ents, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
var out []Module
for _, e := range ents {
if !e.IsDir() {
continue
}
name := e.Name()
if strings.HasPrefix(name, ".") {
continue
}
modDir := filepath.Join(dir, name)
if !looksLikeModule(modDir, name) {
continue
}
out = append(out, Module{Name: name, Dir: modDir})
}
return out, nil
}
func looksLikeModule(dir, name string) bool {
if fileExists(filepath.Join(dir, "module.yaml")) {
return true
}
if fileExists(filepath.Join(dir, "module-publish.yaml")) {
return true
}
if fileExists(filepath.Join(dir, "go.mod")) {
return true
}
if fileExists(BinPath(dir, name)) {
return true
}
// Any .go file in the root of the module dir.
ents, err := os.ReadDir(dir)
if err != nil {
return false
}
for _, e := range ents {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".go") {
return true
}
}
return false
}
// Find returns the module named name, or an error listing what exists.
func Find(root, name string) (Module, error) {
mods, err := Discover(root)
if err != nil {
return Module{}, err
}
for _, m := range mods {
if m.Name == name {
return m, nil
}
}
names := make([]string, 0, len(mods))
for _, m := range mods {
names = append(names, m.Name)
}
if len(names) == 0 {
return Module{}, errNoModules(root)
}
return Module{}, &NotFoundError{Name: name, Available: names}
}
// BinPath is modules/<name>/.bin/<name>[.exe].
func BinPath(modDir, name string) string {
bin := filepath.Join(modDir, ".bin", name)
if runtime.GOOS == "windows" {
bin += ".exe"
}
return bin
}
func (m Module) BinPath() string {
return BinPath(m.Dir, m.Name)
}
func fileExists(p string) bool {
st, err := os.Stat(p)
return err == nil && !st.IsDir()
}
func errNoModules(root string) error {
return &NotFoundError{
Name: "",
Available: nil,
Hint: "create modules/<name>/ with Go source + module.yaml (see docs/modules.md)",
Root: ModulesDir(root),
}
}
// NotFoundError is returned when --app does not match a modules/ directory.
type NotFoundError struct {
Name string
Available []string
Hint string
Root string
}
func (e *NotFoundError) Error() string {
if e.Name == "" {
return "no modules found under " + e.Root + " — " + e.Hint
}
if len(e.Available) == 0 {
return "unknown module " + e.Name + " (modules dir empty) — " + e.Hint
}
return "unknown module " + e.Name + " — available: " + strings.Join(e.Available, ", ")
}

View file

@ -1,113 +0,0 @@
package modhost
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
)
// prepareModuleCmd sets STREAMD_MODULES_DIR so child module binaries load
// panel-store module.yaml. Module builds that call EffectiveModulesDir (or
// ApplyEnvModulesDir) honour this; /api/apps also falls back to parsing the
// panel module.yaml when describe returns no channels.
func prepareModuleCmd(cmd *exec.Cmd) {
ov := ModulesDirOverride()
if ov == "" {
return
}
cmd.Env = append(withoutEnvKeys(os.Environ(), "STREAMD_MODULES_DIR", "DRM_MODULES_DIR"),
"STREAMD_MODULES_DIR="+ov)
}
func withoutEnvKeys(env []string, keys ...string) []string {
drop := map[string]struct{}{}
for _, k := range keys {
drop[strings.ToUpper(k)] = struct{}{}
}
out := make([]string, 0, len(env))
for _, e := range env {
key, _, _ := strings.Cut(e, "=")
if _, skip := drop[strings.ToUpper(key)]; skip {
continue
}
out = append(out, e)
}
return out
}
// Run executes the module binary with args, inheriting stdout/stderr.
func Run(bin string, args ...string) error {
cmd := exec.Command(bin, args...)
prepareModuleCmd(cmd)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
return fmt.Errorf("%s %s: %w", bin, strings.Join(args, " "), err)
}
return nil
}
// RunOutput executes the module binary and returns combined stdout.
func RunOutput(bin string, args ...string) (string, error) {
cmd := exec.Command(bin, args...)
prepareModuleCmd(cmd)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return stdout.String(), fmt.Errorf("%s %s: %w\n%s", bin, strings.Join(args, " "), err, stderr.String())
}
return stdout.String(), nil
}
// RunDescribe runs `bin describe` and parses JSON.
func RunDescribe(bin string) (Describe, error) {
out, err := RunOutput(bin, "describe")
if err != nil {
return Describe{}, err
}
// Allow log lines before JSON: find first '{'.
out = strings.TrimSpace(out)
if i := strings.IndexByte(out, '{'); i > 0 {
out = out[i:]
}
var d Describe
if err := json.Unmarshal([]byte(out), &d); err != nil {
return Describe{}, fmt.Errorf("describe JSON: %w\noutput: %s", err, out)
}
if d.Protocol != 0 && d.Protocol != ProtocolVersion {
return d, fmt.Errorf("module protocol %d unsupported (host wants %d)", d.Protocol, ProtocolVersion)
}
if d.Protocol == 0 {
d.Protocol = ProtocolVersion
}
return d, nil
}
// Load builds (if needed) and describes a module by name.
func Load(root, name string) (Module, string, Describe, error) {
m, err := Find(root, name)
if err != nil {
return Module{}, "", Describe{}, err
}
bin, err := EnsureBuilt(m)
if err != nil {
return m, "", Describe{}, err
}
d, err := RunDescribe(bin)
if err != nil {
return m, bin, Describe{}, err
}
if d.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
}

View file

@ -1,31 +0,0 @@
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,37 +0,0 @@
// Package modhost discovers, builds, and runs external provider modules that
// live under modules/<name>/ (Go source + module.yaml), outside streamd.
package modhost
import "streamd/capture"
// ProtocolVersion is bumped when describe/launch/autoplay CLI contract changes.
const ProtocolVersion = 1
// Channel is one live target advertised by a module.
type Channel struct {
ID string `json:"id"`
Label string `json:"label"`
}
// Describe is the JSON printed by `module-bin describe`.
type Describe struct {
Protocol int `json:"protocol"`
Name string `json:"name"`
Package string `json:"package"`
LicenseURL string `json:"license_url,omitempty"`
KeyMode string `json:"key_mode"`
ProxyBin string `json:"proxy_bin,omitempty"`
CAHash string `json:"ca_hash,omitempty"`
TransparentMITM bool `json:"transparent_mitm"`
MitmHosts []string `json:"mitm_hosts,omitempty"`
Rewriter string `json:"rewriter,omitempty"`
Channels []Channel `json:"channels"`
Require []string `json:"require,omitempty"`
Score capture.ScoreCfg `json:"score,omitempty"`
// ChannelMPDPrefer maps channel id → URL substrings that must win Wait scoring.
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

@ -1,262 +0,0 @@
package modhost
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"streamd/adb"
"streamd/app"
"streamd/capture"
"streamd/mpd"
"streamd/session"
)
// RemoteApp implements app.App by calling an external module binary.
type RemoteApp struct {
Mod Module
Bin string
Desc Describe
}
// Open builds and describes modules/<name>, returning a RemoteApp.
func Open(root, name string) (*RemoteApp, error) {
m, bin, d, err := Load(root, name)
if err != nil {
return nil, err
}
return &RemoteApp{Mod: m, Bin: bin, Desc: d}, nil
}
func (r *RemoteApp) Name() string { return r.Desc.Name }
func (r *RemoteApp) Package() string { return r.Desc.Package }
func (r *RemoteApp) LicenseURL() string { return r.Desc.LicenseURL }
func (r *RemoteApp) ProxyBin() string { return r.Desc.ProxyBin }
func (r *RemoteApp) CAHash() string { return r.Desc.CAHash }
func (r *RemoteApp) KeyMode() string {
if r.Desc.KeyMode == "" {
return "none"
}
return r.Desc.KeyMode
}
func (r *RemoteApp) Channels() []app.Channel {
out := make([]app.Channel, 0, len(r.Desc.Channels))
for _, ch := range r.Desc.Channels {
out = append(out, app.Channel{ID: ch.ID, Label: ch.Label})
}
return out
}
func (r *RemoteApp) HasChannel(id string) bool {
for _, ch := range r.Desc.Channels {
if ch.ID == id {
return true
}
}
return false
}
func (r *RemoteApp) CaptureHints() capture.Hints {
req := r.Desc.Require
if len(req) == 0 {
req = []string{"mpd"}
}
h := capture.DefaultHints()
h.Require = req
h.Score = capture.DefaultScoreCfg().Merge(r.Desc.Score)
return h
}
func (r *RemoteApp) MPDRewriter() mpd.Rewriter {
name := r.Desc.Rewriter
if name == "" || name == "none" {
return mpd.Passthrough{}
}
if rw, ok := mpd.Lookup(name); ok {
return rw
}
return mpd.Passthrough{}
}
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 {
if r.Desc.Rewriter == "" {
return "none"
}
return r.Desc.Rewriter
}
func (r *RemoteApp) Launch(c *adb.Client) error {
args := []string{"launch"}
if c != nil && c.Serial != "" {
args = append(args, "--serial", c.Serial)
}
return Run(r.Bin, args...)
}
func (r *RemoteApp) AutoPlay(c *adb.Client, channel string) error {
args := []string{"autoplay", "--channel", channel}
if c != nil && c.Serial != "" {
args = append(args, "--serial", c.Serial)
}
return Run(r.Bin, args...)
}
// ValuesPath is where module.yaml should live for this module.
func (r *RemoteApp) ValuesPath() string {
if r.Desc.ValuesPath != "" {
return r.Desc.ValuesPath
}
return filepath.Join(r.Mod.Dir, "module.yaml")
}
// Ensure RemoteApp satisfies the interfaces capture / catalog use.
var (
_ app.App = (*RemoteApp)(nil)
_ app.TransparentMITM = (*RemoteApp)(nil)
_ app.RequireWVD = (*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) AudioSelect() string { return "" }
func (r *RemoteApp) LiveWaitSeconds() int { return 0 }
func (r *RemoteApp) TSReadyBytes() int64 { return 0 }
// Resolve runs `module catalog --channel ID --json`.
func (r *RemoteApp) Resolve(channel string) (session.Stream, error) {
if !r.Desc.HasCatalog {
return session.Stream{}, fmt.Errorf("module %s has no catalog", r.Desc.Name)
}
out, err := RunOutput(r.Bin, "catalog", "--channel", channel, "--json")
if err != nil {
return session.Stream{}, err
}
out = strings.TrimSpace(out)
if i := strings.IndexByte(out, '{'); i > 0 {
out = out[i:]
}
var info session.Stream
if err := json.Unmarshal([]byte(out), &info); err != nil {
return session.Stream{}, fmt.Errorf("catalog JSON: %w\noutput: %s", err, out)
}
return info, nil
}
// EnrichWithKeys is not yet implemented for external modules.
func (r *RemoteApp) EnrichWithKeys(info *session.Stream, python, wvd string) error {
return fmt.Errorf("module %s: --keys via external module is not supported yet", r.Desc.Name)
}
// Listed is one discovered module with its describe payload.
type Listed struct {
Mod Module
Bin string
Desc Describe
}
// ListAll discovers, builds, and describes every modules/<name>/.
func ListAll(root string) ([]Listed, error) {
mods, err := Discover(root)
if err != nil {
return nil, err
}
out := make([]Listed, 0, len(mods))
for _, m := range mods {
bin, err := EnsureBuilt(m)
if err != nil {
return out, fmt.Errorf("module %s: %w", m.Name, err)
}
d, err := RunDescribe(bin)
if err != nil {
return out, fmt.Errorf("module %s describe: %w", m.Name, err)
}
if d.Name == "" {
d.Name = m.Name
}
out = append(out, Listed{Mod: m, Bin: bin, Desc: d})
}
return out, nil
}
// Names lists discovered module directory names (no build).
func Names(root string) ([]string, error) {
mods, err := Discover(root)
if err != nil {
return nil, err
}
names := make([]string, 0, len(mods))
for _, m := range mods {
names = append(names, m.Name)
}
return names, nil
}
// FindChannelInModules scans described modules for a channel id.
func FindChannelInModules(root, channelID string) (appName string, ok bool) {
listed, err := ListAll(root)
if err != nil {
return "", false
}
for _, L := range listed {
for _, ch := range L.Desc.Channels {
if ch.ID == channelID {
return L.Mod.Name, true
}
}
}
return "", false
}
// FormatUnknown helps capturecmd error messages when --app is unknown.
func FormatUnknown(root, name string) error {
_, err := Find(root, name)
if err != nil {
if owner, ok := FindChannelInModules(root, name); ok {
return fmt.Errorf("%q is a channel of --app %s, not an app name — use: capture --app %s --channel %s", name, owner, owner, name)
}
return err
}
return fmt.Errorf("unknown module %q", name)
}

View file

@ -1,84 +0,0 @@
package modhost
import (
"os"
"path/filepath"
"strings"
"sync"
"streamd/repo"
)
var (
rootMu sync.RWMutex
modulesDirOV string // absolute path override for the modules directory
)
// SetModulesDir overrides where providers are discovered (streamd --modules-dir).
// Empty clears the override. Relative paths are resolved against the process cwd.
func SetModulesDir(dir string) error {
rootMu.Lock()
defer rootMu.Unlock()
if dir == "" {
modulesDirOV = ""
return nil
}
abs, err := filepath.Abs(dir)
if err != nil {
return err
}
modulesDirOV = abs
return nil
}
// ModulesDirOverride returns the --modules-dir override, or "".
func ModulesDirOverride() string {
rootMu.RLock()
defer rootMu.RUnlock()
return modulesDirOV
}
// envModulesDir returns STREAMD_MODULES_DIR (preferred) or DRM_MODULES_DIR.
func envModulesDir() string {
v := strings.TrimSpace(os.Getenv("STREAMD_MODULES_DIR"))
if v == "" {
v = strings.TrimSpace(os.Getenv("DRM_MODULES_DIR"))
}
if v == "" {
return ""
}
if abs, err := filepath.Abs(v); err == nil {
return abs
}
return v
}
// EffectiveModulesDir is the directory that Discover/Open scan.
// Prefer --modules-dir, 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 {
if ov := ModulesDirOverride(); ov != "" {
return ov
}
if v := envModulesDir(); v != "" {
return v
}
if root == "" {
root = repo.Root()
}
return filepath.Join(root, "modules")
}
// ApplyEnvModulesDir sets the override from STREAMD_MODULES_DIR (preferred) or
// DRM_MODULES_DIR when no flag was set.
func ApplyEnvModulesDir() error {
if ModulesDirOverride() != "" {
return nil
}
v := envModulesDir()
if v == "" {
return nil
}
return SetModulesDir(v)
}

View file

@ -1,39 +0,0 @@
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

@ -1,77 +0,0 @@
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

@ -5,7 +5,6 @@ import (
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
)
@ -28,28 +27,22 @@ type Primer interface {
type LocalServer struct {
URL string
Upstream string
Key string // KID:KEY (optional for clear streams)
Key string // KID:KEY
Headers map[string]string
Proxy string // optional socks5:// or http:// for upstream fetch
rw Rewriter
kidHint string
ln net.Listener
httpServer *http.Server
client *http.Client
}
// StartLocal starts the rewrite proxy. rw must not be nil; pass Passthrough{}
// to serve upstream unchanged. proxyURL may be empty, or socks5:// / http://.
func StartLocal(upstream, key string, headers map[string]string, rw Rewriter, proxyURL ...string) (*LocalServer, error) {
// to serve upstream unchanged.
func StartLocal(upstream, key string, headers map[string]string, rw Rewriter) (*LocalServer, error) {
if rw == nil {
rw = Passthrough{}
}
proxy := ""
if len(proxyURL) > 0 {
proxy = strings.TrimSpace(proxyURL[0])
}
s := &LocalServer{Upstream: upstream, Key: key, Headers: headers, Proxy: proxy, rw: rw}
s := &LocalServer{Upstream: upstream, Key: key, Headers: headers, rw: rw}
if key != "" && strings.Contains(key, ":") {
s.kidHint = strings.SplitN(key, ":", 2)[0]
if r, ok := rw.(KIDResolver); ok {
@ -60,11 +53,6 @@ func StartLocal(upstream, key string, headers map[string]string, rw Rewriter, pr
}
}
}
client, err := httpClientWithProxy(proxy)
if err != nil {
return nil, err
}
s.client = client
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, err
@ -78,18 +66,6 @@ func StartLocal(upstream, key string, headers map[string]string, rw Rewriter, pr
return s, nil
}
func httpClientWithProxy(proxyURL string) (*http.Client, error) {
transport := http.DefaultTransport.(*http.Transport).Clone()
if proxyURL != "" {
u, err := url.Parse(proxyURL)
if err != nil {
return nil, fmt.Errorf("proxy URL: %w", err)
}
transport.Proxy = http.ProxyURL(u)
}
return &http.Client{Timeout: 20 * time.Second, Transport: transport}, nil
}
func (s *LocalServer) Close() {
if s.httpServer != nil {
_ = s.httpServer.Close()
@ -106,10 +82,7 @@ func (s *LocalServer) handle(w http.ResponseWriter, r *http.Request) {
for k, v := range s.Headers {
req.Header.Set(k, v)
}
client := s.client
if client == nil {
client = &http.Client{Timeout: 20 * time.Second}
}
client := &http.Client{Timeout: 20 * time.Second}
if resp, err := client.Do(req); err == nil {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
_ = resp.Body.Close()

View file

@ -12,13 +12,13 @@ import (
"strings"
"time"
"streamd/adb"
"streamd/app"
"streamd/capture"
"streamd/proxy"
"streamd/repo"
"streamd/session"
"streamd/wvkey"
"drmdecryption/adb"
"drmdecryption/app"
"drmdecryption/capture"
"drmdecryption/proxy"
"drmdecryption/repo"
"drmdecryption/session"
"drmdecryption/wvkey"
)
// DefaultCAHash is the subject hash of the bundled MITM CA, used when an app
@ -199,28 +199,17 @@ func Run(opt Options) (res Result, err error) {
proxyBin, caHash := resolveProxy(a, root)
hints := a.CaptureHints()
if chHints, ok := a.(app.ChannelCaptureHints); ok && strings.TrimSpace(opt.Channel) != "" {
hints = chHints.CaptureHintsFor(opt.Channel)
}
useTProxy := false
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
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 {
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
proxy.ClearHTTPProxy(c)
remoteDir := "/data/local/tmp/capture/" + pkgName
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 {
remoteDir := "/data/local/tmp/capture/" + a.Package()
if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false); err != nil {
return res, fmt.Errorf("transparent MITM start: %w", err)
}
defer proxy.StopTransparent(c)
@ -242,6 +231,17 @@ func Run(opt Options) (res Result, err error) {
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)
serialTag := c.Serial
if serialTag == "" {
@ -253,168 +253,80 @@ func Run(opt Options) (res Result, err error) {
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
defer close(stop)
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
if keyMode == "" || keyMode == "auto" {
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
}
needsKeys := keyMode != "none" && keyMode != "clear"
// DRM apps: wait up to 90s for Widevine traffic, then force-stop and retry
// (max 3). Clear / MPD-only apps keep a single wait of opt.Wait.
attempts := 1
waitPer := opt.Wait
if needsKeys {
attempts = 3
waitPer = 90 * time.Second
if opt.Wait > 0 && opt.Wait < waitPer {
waitPer = opt.Wait
}
}
need := hints.Require
if len(need) == 0 {
need = []string{"manifest"}
}
var (
capData capture.Data
licenseURL string
mpdURL string
key string
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)
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))
if keyMode == "" || keyMode == "auto" {
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
}
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
// Skip for clear/MPD-only apps (KeyMode none).
if keyMode != "none" && keyMode != "clear" {
if strings.TrimSpace(capData.Get("pssh")) == "" && strings.TrimSpace(capData.Get("mpd")) != "" {
if pssh, err := extractHLSPSSH(capData.Get("mpd")); err == nil && pssh != "" {
capData["pssh"] = pssh
} else if err != nil {
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
}
}
}
// 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)
mpdURL := strings.TrimSpace(capData.Get("mpd"))
// Console: always surface the MPD we will use (BBC clear streams only need this).
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"} {
v := capData.Get(k)
if k == "license_url" {
v = first(v, licenseURL)
}
if v == "" {
continue
}
if !opt.NoAutoPlay {
if err := a.AutoPlay(c, opt.Channel); err != nil {
lastErr = fmt.Errorf("auto-play: %w", err)
c.ForceStop(a.Package())
continue
}
} else {
fmt.Println("[*] Open the channel on the phone and wait for playback…")
label := k
if k == "license_url" {
label = "license"
}
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)
key := ""
if keyMode == "none" || keyMode == "clear" {
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
} else {
var kerr error
key, 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
return res, kerr
}
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
}
if lastErr != nil {
if needsKeys {
return res, fmt.Errorf("widevine capture failed after %d attempt(s): %w", attempts, lastErr)
}
return res, lastErr
}
if needsKeys && (strings.TrimSpace(key) == "" || !looksLikeKey(key)) {
return res, fmt.Errorf("refusing to save capture without Widevine keys (mpd alone is not enough)")
}
sess := session.Session{
Channel: opt.Channel,
PSSH: capData.Get("pssh"),
Auth: capData.Get("auth"),
PID: capData.Get("pid"),
Key: key,
MPD: mpdURL,
LicenseURL: licenseURL,
LicenseBody: capData.Get("license_body"),
Channel: opt.Channel,
PSSH: capData.Get("pssh"),
Auth: capData.Get("auth"),
PID: capData.Get("pid"),
Key: key,
MPD: mpdURL,
LicenseURL: licenseURL,
}
path, err := session.Write(root, a.Name(), sess)
if err != nil {
@ -431,84 +343,32 @@ func Run(opt Options) (res Result, err error) {
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).
func ClearProxyLater(c *adb.Client) {
proxy.ClearHTTPProxy(c)
}
func resolveProxy(a app.App, root string) (bin, caHash string) {
bin = filepath.Join(root, "bin", "proxy-android-arm64")
caHash = DefaultCAHash
if a != nil {
if p := a.ProxyBin(); p != "" {
if st, err := os.Stat(p); err == nil && !st.IsDir() {
bin = p
}
bin = p
}
if h := a.CAHash(); h != "" {
caHash = h
}
}
if bin == "" {
bin = proxy.FindLocalBin(root)
}
if bin == "" {
bin = filepath.Join(root, "bin", "proxy-android-arm64")
if _, err := os.Stat(bin); err != nil {
for _, p := range []string{
filepath.Join(root, "bin", "proxy-android-arm64"),
filepath.Join(root, "apps", "proxy", "proxy-android-arm64"),
} {
if st, e := os.Stat(p); e == nil && !st.IsDir() {
bin = p
break
}
}
}
return bin, caHash
}
@ -517,25 +377,22 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
if strings.TrimSpace(opt.WVD) == "" {
return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)")
}
// Ensure apps/wvkey + .venv/pywidevine exist on Windows/Linux/macOS.
rt, err := wvkey.EnsureRuntime(root)
if err != nil {
return "", err
}
py := rt.Python
if p := strings.TrimSpace(opt.Python); p != "" && fileExistsPath(p) {
py = p
py := opt.Python
if py == "" {
py = filepath.Join(root, ".venv", "Scripts", "python.exe")
if _, err := os.Stat(py); err != nil {
py = filepath.Join(root, ".venv", "bin", "python")
}
}
wopt := wvkey.Options{
Python: py,
Script: rt.Script,
Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"),
WVD: opt.WVD,
PSSH: cap.Get("pssh"),
Auth: cap.Get("auth"),
PID: cap.Get("pid"),
LicenseURL: licenseURL,
UserAgent: opt.UserAgent,
WrapJSON: cap.Get("license_body"),
}
mode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
if mode == "" || mode == "auto" {
@ -546,11 +403,6 @@ 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 {
case "raw":
// Brightcove returns multiple CONTENT keys; NRE needs all of them.
@ -559,22 +411,11 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
return "", err
}
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:
return wvkey.Fetch(wopt)
}
}
func fileExistsPath(path string) bool {
st, err := os.Stat(path)
return err == nil && !st.IsDir()
}
func first(vals ...string) string {
for _, v := range vals {
if strings.TrimSpace(v) != "" {
@ -612,62 +453,6 @@ func extractHLSPSSH(masterURL string) (string, error) {
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 {
if len(s) <= n {
return s

View file

@ -1,58 +0,0 @@
package proxy
import (
_ "embed"
"fmt"
"os"
"path/filepath"
"streamd/adb"
"streamd/repo"
)
//go:embed embedded/tproxy_iptables.sh
var embeddedTProxyScript []byte
// ensureTProxyScript pushes the iptables helper to the phone.
// Prefers the source-tree copy; falls back to the copy embedded in streamd
// so a portable release zip does not need apps/proxy/device/.
func ensureTProxyScript(c *adb.Client) error {
candidates := []string{
filepath.Join(repo.Root(), "apps", "proxy", "device", "tproxy_iptables.sh"),
}
if exe, err := os.Executable(); err == nil {
dir := filepath.Dir(exe)
candidates = append(candidates,
filepath.Join(dir, "tproxy_iptables.sh"),
filepath.Join(dir, "apps", "proxy", "device", "tproxy_iptables.sh"),
)
}
var local string
for _, p := range candidates {
if st, err := os.Stat(p); err == nil && !st.IsDir() {
local = p
break
}
}
tmp := filepath.Join(os.TempDir(), "tproxy_iptables.sh")
if local != "" {
data, err := os.ReadFile(local)
if err != nil {
return err
}
if err := os.WriteFile(tmp, data, 0o755); err != nil {
return err
}
} else {
if err := os.WriteFile(tmp, embeddedTProxyScript, 0o755); err != nil {
return err
}
fmt.Println("[*] Using embedded tproxy_iptables.sh")
}
defer os.Remove(tmp)
if err := c.Push(tmp, RemoteTProxyScript); err != nil {
return err
}
_, _ = c.Shell("chmod", "755", RemoteTProxyScript)
return nil
}

View file

@ -1,81 +0,0 @@
#!/system/bin/sh
# Transparent redirect: package UID TCP/443 → local appproxy (no Wi‑Fi http_proxy).
# Usage:
# tproxy_iptables.sh start <package> [port]
# tproxy_iptables.sh stop
# tproxy_iptables.sh status
set -eu
CHAIN=APPROXY_TPROXY
ACTION="${1:-}"
uid_for_package() {
pkg="$1"
# dumpsys package <pkg> | grep userId= OR stat on data dir
uid=$(dumpsys package "$pkg" 2>/dev/null | grep -m1 -oE 'userId=[0-9]+' | head -1 | cut -d= -f2 || true)
if [ -z "$uid" ]; then
uid=$(stat -c %u "/data/user/0/$pkg" 2>/dev/null || true)
fi
echo "$uid"
}
stop_rules() {
iptables -t nat -D OUTPUT -j "$CHAIN" 2>/dev/null || true
iptables -t nat -F "$CHAIN" 2>/dev/null || true
iptables -t nat -X "$CHAIN" 2>/dev/null || true
echo "STOPPED"
}
start_rules() {
pkg="$1"
port="$2"
uid=$(uid_for_package "$pkg")
if [ -z "$uid" ] || [ "$uid" = "0" ]; then
echo "ERR: cannot resolve uid for package $pkg" >&2
exit 1
fi
proxy_uid=$(stat -c %u /data/local/tmp/appproxy 2>/dev/null || echo "")
# Prefer the running process uid if available
if pidof appproxy >/dev/null 2>&1; then
proxy_uid=$(stat -c %u /proc/$(pidof appproxy | awk '{print $1}') 2>/dev/null || echo "$proxy_uid")
fi
stop_rules >/dev/null
iptables -t nat -N "$CHAIN"
# Never redirect the mitm itself (loop).
if [ -n "$proxy_uid" ]; then
iptables -t nat -A "$CHAIN" -m owner --uid-owner "$proxy_uid" -j RETURN
fi
# Skip localhost / link-local.
iptables -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
# 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"
iptables -t nat -A OUTPUT -j "$CHAIN"
echo "STARTED pkg=$pkg uid=$uid port=$port proxy_uid=${proxy_uid:-unknown}"
}
status_rules() {
echo "=== $CHAIN ==="
iptables -t nat -L "$CHAIN" -n -v 2>/dev/null || echo "(no chain)"
echo "=== OUTPUT head ==="
iptables -t nat -L OUTPUT -n -v 2>/dev/null | head -20
}
case "$ACTION" in
start)
pkg="${2:?package required}"
port="${3:-8080}"
start_rules "$pkg" "$port"
;;
stop)
stop_rules
;;
status)
status_rules
;;
*)
echo "usage: $0 start <package> [port] | stop | status" >&2
exit 2
;;
esac

View file

@ -17,8 +17,8 @@ import (
"strings"
"time"
"streamd/adb"
"streamd/repo"
"drmdecryption/adb"
"drmdecryption/repo"
)
const (
@ -224,28 +224,17 @@ func PushAndStart(c *adb.Client, localBin string, extraArgs ...string) error {
return nil
}
// FindLocalBin returns the on-device MITM binary.
// Search order: next to this streamd binary (release zip layout), then under the repo.
// FindLocalBin returns the first existing proxy binary under the repo.
func FindLocalBin(root string) string {
if root == "" {
root = repo.Root()
}
candidates := []string{}
if exe, err := os.Executable(); err == nil {
dir := filepath.Dir(exe)
candidates = append(candidates,
filepath.Join(dir, "proxy-android-arm64"),
filepath.Join(dir, "bin", "proxy-android-arm64"),
)
}
candidates = append(candidates,
for _, p := range []string{
filepath.Join(root, "bin", "proxy-android-arm64"),
filepath.Join(root, "apps", "proxy", "proxy-android-arm64"),
filepath.Join(root, "apps", "proxy", "rteproxy-android-arm64"),
filepath.Join(root, "bin", "rteproxy-android-arm64"),
filepath.Join(root, "proxy-android-arm64"),
)
for _, p := range candidates {
} {
if st, err := os.Stat(p); err == nil && !st.IsDir() {
return p
}
@ -322,11 +311,11 @@ func generateMITMCA(certPath, keyPath string) error {
return err
}
// Unique CN so Android subject_hash_old differs per install (filename HASH.0).
cn := fmt.Sprintf("Streamd Capture CA %x", serial.Bytes()[:8])
cn := fmt.Sprintf("Null DRM Capture CA %x", serial.Bytes()[:8])
tmpl := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{
Organization: []string{"Streamd MITM CA"},
Organization: []string{"Null DRM MITM CA"},
CommonName: cn,
},
NotBefore: time.Now().Add(-time.Hour),
@ -478,17 +467,11 @@ const (
// StartTransparent pushes appproxy in -transparent mode (no Wi‑Fi http_proxy),
// installs iptables UID REDIRECT for pkg, and writes captures under remoteDir.
// 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)")
}
func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool) error {
if port == "" {
port = "8080"
}
if remoteDir == "" || strings.HasSuffix(remoteDir, "/capture/") || strings.HasSuffix(remoteDir, `\capture\`) {
if remoteDir == "" {
remoteDir = RemoteCaptureRoot + "/" + pkg
}
stopProxy(c)
@ -506,7 +489,7 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
return fmt.Errorf("CA hash: %w", err)
}
if reinject {
ReinjectCAForPackage(c, caHash, pkg)
ReinjectCA(c, caHash)
}
if st, err := os.Stat(localBin); err != nil || st.IsDir() {
@ -518,26 +501,17 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
}
_, _ = c.Shell("chmod", "755", RemoteBin)
if err := ensureTProxyScript(c); err != nil {
return fmt.Errorf("tproxy script: %w", err)
scriptLocal := filepath.Join(repo.Root(), "apps", "proxy", "device", "tproxy_iptables.sh")
if _, err := os.Stat(scriptLocal); err != nil {
return fmt.Errorf("missing %s", scriptLocal)
}
if err := c.Push(scriptLocal, RemoteTProxyScript); err != nil {
return err
}
_, _ = c.Shell("chmod", "755", RemoteTProxyScript)
_, _ = c.Shell("mkdir", "-p", remoteDir)
_, _ = 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" +
"mkdir -p '" + remoteDir + "'\n" +
"exec " + RemoteBin +
@ -549,7 +523,6 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
" -dns 1.1.1.1,1.0.0.1,8.8.8.8" +
" -log-all" +
" -v" +
mitmFlags +
"\n"
tmp := filepath.Join(os.TempDir(), "start_appproxy_tproxy.sh")
if err := os.WriteFile(tmp, []byte(starter), 0o755); err != nil {
@ -618,81 +591,6 @@ func StopTransparent(c *adb.Client) {
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.
type ResetOptions struct {
KeepCaptures bool // leave /data/local/tmp/capture/
}
// ResetDevice returns the phone to a clean MITM-free state: stop proxy/iptables,
// delete pushed CA/binaries/scripts/overlays. Does not delete host data/proxy-ca.*.
func ResetDevice(c *adb.Client, opt ResetOptions) error {
fmt.Println("[*] Resetting device MITM state…")
StopTransparent(c)
script := `
BB=/data/adb/magisk/busybox
# Best-effort undo conscrypt bind (ignore failures).
if [ -x "$BB" ]; then
$BB umount /apex/com.android.conscrypt/cacerts 2>/dev/null || true
$BB umount /system/etc/security/cacerts 2>/dev/null || true
fi
rm -f /data/local/tmp/appproxy \
/data/local/tmp/rteproxy \
/data/local/tmp/rteproxy-ca.crt /data/local/tmp/rteproxy-ca.key \
/data/local/tmp/appproxy-ca.crt /data/local/tmp/appproxy-ca.key \
/data/local/tmp/appproxy_cap.json /data/local/tmp/appproxy_traffic.jsonl \
/data/local/tmp/appproxy.log /data/local/tmp/rteproxy.log \
/data/local/tmp/appproxy-start.out \
/data/local/tmp/start_appproxy.sh /data/local/tmp/start_appproxy_tproxy.sh \
/data/local/tmp/tproxy_iptables.sh \
/data/local/tmp/reinject_ca.sh /data/local/tmp/reinject_ca.status \
/data/local/tmp/reinject_target_uid \
/data/local/tmp/rte_cap.json
# HASH.0 CA copies we pushed (8 hex chars).
rm -f /data/local/tmp/[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].0 2>/dev/null || true
rm -rf /data/local/tmp/cacerts-overlay
echo RESET_CORE_OK
`
if !opt.KeepCaptures {
script += "rm -rf /data/local/tmp/capture\necho RESET_CAPTURES_OK\n"
} else {
script += "echo RESET_CAPTURES_KEPT\n"
}
tmp := filepath.Join(os.TempDir(), "drm_proxy_reset.sh")
_ = os.WriteFile(tmp, []byte("#!/system/bin/sh\n"+script), 0o755)
defer os.Remove(tmp)
_ = c.Push(tmp, "/data/local/tmp/drm_proxy_reset.sh")
_, _ = c.Shell("chmod", "755", "/data/local/tmp/drm_proxy_reset.sh")
out, errOut, err := c.Run("shell", "su", "-c", "sh /data/local/tmp/drm_proxy_reset.sh")
_, _ = c.Shell("su", "-c", "rm -f /data/local/tmp/drm_proxy_reset.sh")
combined := out + errOut
if strings.TrimSpace(out) != "" {
for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
fmt.Println(" ", line)
}
}
if err != nil && !strings.Contains(combined, "RESET_CORE_OK") {
return fmt.Errorf("proxy reset: %v %s", err, strings.TrimSpace(errOut))
}
fmt.Println("[+] Device MITM artifacts cleared — next transparent/capture starts fresh")
return nil
}
func stopTransparentRules(c *adb.Client) error {
out, errOut, err := c.Run("shell", "su", "-c", "sh "+RemoteTProxyScript+" stop")
if strings.TrimSpace(out) != "" {
@ -788,154 +686,80 @@ func DiscoverOutDir(root, stamp string) string {
return filepath.Join(root, "outputs", "discover", stamp)
}
const (
remoteReinjectScript = "/data/local/tmp/reinject_ca.sh"
remoteReinjectStatus = "/data/local/tmp/reinject_ca.status"
remoteReinjectUID = "/data/local/tmp/reinject_target_uid"
)
// ReinjectCA Magisk-binds the MITM CA into conscrypt (zygote + system).
// ReinjectCA best-effort Magisk bind of the mitm CA into conscrypt.
func ReinjectCA(c *adb.Client, caHash string) {
ReinjectCAForPackage(c, caHash, "")
}
// ReinjectCAForPackage Magisk-binds the MITM CA, optionally also into one app's
// mount namespace (after writing its UID). A stale reinject_target_uid from an
// older run is cleared when pkg is empty — that leftover caused 20s host timeouts.
func ReinjectCAForPackage(c *adb.Client, caHash, pkg string) {
if caHash == "" {
caHash = DefaultCAHash
}
if pkg != "" {
uid := strings.TrimSpace(c.Out("shell", "su", "-c", "stat -c %u /data/data/"+pkg+" 2>/dev/null || dumpsys package "+pkg+" | grep userId= | head -1"))
// dumpsys form: userId=10382
if i := strings.Index(uid, "userId="); i >= 0 {
uid = strings.TrimSpace(uid[i+len("userId="):])
if j := strings.IndexAny(uid, " \t\r\n"); j >= 0 {
uid = uid[:j]
}
}
if uid != "" && uid != "0" {
tmp := filepath.Join(os.TempDir(), "reinject_target_uid")
_ = os.WriteFile(tmp, []byte(uid+"\n"), 0o644)
_ = c.Push(tmp, remoteReinjectUID)
_ = os.Remove(tmp)
fmt.Printf("[*] Magisk reinject target uid %s (%s)\n", uid, pkg)
}
} else {
// Stale UID files make the per-PID nsenter loop hang su -mm.
_, _ = c.Shell("su", "-c", "rm -f "+remoteReinjectUID)
}
// Bound the per-app nsenter loop — wait on hundreds of PIDs can hang forever.
script := fmt.Sprintf(`
BB=/data/adb/magisk/busybox
HASH=%s
STATUS=%s
echo RUNNING > "$STATUS"
[ -f /data/local/tmp/$HASH.0 ] || { echo CA_SKIP > "$STATUS"; exit 0; }
[ -x "$BB" ] || { echo CA_SKIP_NO_BB > "$STATUS"; exit 0; }
[ -f /data/local/tmp/$HASH.0 ] || { echo CA_SKIP; exit 0; }
[ -x "$BB" ] || { echo CA_SKIP; exit 0; }
rm -rf /data/local/tmp/cacerts-overlay
mkdir -p /data/local/tmp/cacerts-overlay
# Copy from the real apex store. If a previous broken bind is mounted, prefer
# the Magisk mirror / stock path so we do not copy an empty/unreadable overlay.
if [ -r /apex/com.android.conscrypt/cacerts/0054e830.0 ] || ls /apex/com.android.conscrypt/cacerts/*.0 >/dev/null 2>&1; then
cp /apex/com.android.conscrypt/cacerts/* /data/local/tmp/cacerts-overlay/ 2>/dev/null || true
fi
cp /apex/com.android.conscrypt/cacerts/* /data/local/tmp/cacerts-overlay/ 2>/dev/null || true
cp /data/local/tmp/$HASH.0 /data/local/tmp/cacerts-overlay/$HASH.0
# tmpfs defaults to 0755 root:root; apps need +x on the dir and 0644 on PEMs.
# Wrong modes/contexts caused DirectoryCertificateSrc EACCES and broke iPlayer TLS.
chmod 755 /data/local/tmp/cacerts-overlay
chmod 644 /data/local/tmp/cacerts-overlay/*
chown root:root /data/local/tmp/cacerts-overlay /data/local/tmp/cacerts-overlay/* 2>/dev/null || true
$BB mount -t tmpfs -o mode=755,uid=0,gid=0 tmpfs /system/etc/security/cacerts 2>/dev/null || true
$BB mount -t tmpfs tmpfs /system/etc/security/cacerts 2>/dev/null || true
cp /data/local/tmp/cacerts-overlay/* /system/etc/security/cacerts/ 2>/dev/null || true
chmod 755 /system/etc/security/cacerts
chmod 644 /system/etc/security/cacerts/*
chown root:root /system/etc/security/cacerts /system/etc/security/cacerts/* 2>/dev/null || true
# Match AOSP cacerts file context (system_file is too loose on some Magisk builds).
chcon u:object_r:system_security_cacerts_file:s0 /system/etc/security/cacerts 2>/dev/null || \
chcon u:object_r:system_file:s0 /system/etc/security/cacerts 2>/dev/null || true
chcon u:object_r:system_security_cacerts_file:s0 /system/etc/security/cacerts/* 2>/dev/null || \
chcon u:object_r:system_file:s0 /system/etc/security/cacerts/* 2>/dev/null || true
chmod 644 /system/etc/security/cacerts/* 2>/dev/null || true
chcon u:object_r:system_file:s0 /system/etc/security/cacerts/* 2>/dev/null || true
$BB mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts 2>/dev/null || true
for Z in $(pidof zygote64 2>/dev/null); do
nsenter --mount=/proc/$Z/ns/mnt -- $BB mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts 2>/dev/null || true
done
PKG_UID_FILE=%s
# Only rebind the target app if set; otherwise skip the full zygote-child sweep (hangs).
PKG_UID_FILE=/data/local/tmp/reinject_target_uid
if [ -f "$PKG_UID_FILE" ]; then
TUID=$(cat "$PKG_UID_FILE")
# Cap the sweep — a long-lived app with many threads must not hang forever.
N=0
for PID in $(ps -A -o PID=,UID= 2>/dev/null | awk -v u="$TUID" '$2==u {print $1}'); do
nsenter --mount=/proc/$PID/ns/mnt -- $BB mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts 2>/dev/null || true
N=$((N+1))
[ "$N" -ge 8 ] && break
done
fi
if ls /apex/com.android.conscrypt/cacerts/$HASH.0 >/dev/null 2>&1; then
echo CA_OK > "$STATUS"
else
echo CA_SKIP > "$STATUS"
fi
`, caHash, remoteReinjectStatus, remoteReinjectUID)
ls /apex/com.android.conscrypt/cacerts/$HASH.0 2>/dev/null && echo CA_OK || echo CA_SKIP
`, caHash)
fmt.Println("[*] Re-injecting system CA (Magisk)...")
_, _ = c.Shell("su", "-c", "rm -f "+remoteReinjectStatus)
tmp := filepath.Join(os.TempDir(), "reinject_ca.sh")
_ = os.WriteFile(tmp, []byte("#!/system/bin/sh\n"+script), 0o755)
defer os.Remove(tmp)
_ = c.Push(tmp, remoteReinjectScript)
_, _ = c.Shell("chmod", "755", remoteReinjectScript)
// Run in background on device so a hung su -mm cannot block the host forever.
// Status is polled from reinject_ca.status.
_ = c.Push(tmp, "/data/local/tmp/reinject_ca.sh")
_, _ = c.Shell("chmod", "755", "/data/local/tmp/reinject_ca.sh")
// Host-side timeout: su -mm + nsenter has hung on some Magisk builds.
type runResult struct {
out string
}
ch := make(chan runResult, 1)
go func() {
_, _, _ = c.Run("shell", "su", "-mm", "-c", "sh "+remoteReinjectScript)
out, _, _ := c.Run("shell", "su", "-mm", "-c", "sh /data/local/tmp/reinject_ca.sh")
ch <- runResult{out: out}
}()
deadline := time.Now().Add(18 * time.Second)
var status string
for time.Now().Before(deadline) {
status = reinjectStatus(c)
if status == "CA_OK" || strings.HasPrefix(status, "CA_SKIP") {
break
}
time.Sleep(400 * time.Millisecond)
}
if status == "" || status == "RUNNING" {
var out string
select {
case r := <-ch:
out = r.out
case <-time.After(20 * time.Second):
_, _ = c.Shell("su", "-c", "killall reinject_ca.sh 2>/dev/null; true")
time.Sleep(300 * time.Millisecond)
status = reinjectStatus(c)
}
switch {
case status == "CA_OK" || caPresentOnDevice(c, caHash):
fmt.Println("[+] System CA present in conscrypt")
case strings.HasPrefix(status, "CA_SKIP"):
fmt.Printf("[!] CA inject skipped (%s) — re-run: drm proxy install-ca --reinject\n", status)
default:
// Script may have finished mounting even if su -mm hung; verify on device.
if caPresentOnDevice(c, caHash) {
fmt.Println("[+] System CA present in conscrypt (status race, mount OK)")
fmt.Println("[+] System CA present in conscrypt (reinject timed out, mount OK)")
} else {
fmt.Println("[!] CA reinject timed out — re-run: drm proxy install-ca --reinject")
fmt.Println("[!] CA reinject timed out after 20s — re-run: drm proxy install-ca --reinject")
}
return
}
if strings.Contains(out, "CA_OK") || caPresentOnDevice(c, caHash) {
fmt.Println("[+] System CA present in conscrypt")
} else {
fmt.Println("[!] CA inject skipped/failed — re-run: drm proxy install-ca --reinject")
}
}
func reinjectStatus(c *adb.Client) string {
return strings.TrimSpace(c.Out("shell", "su", "-c", "cat "+remoteReinjectStatus+" 2>/dev/null"))
}
func caPresentOnDevice(c *adb.Client, caHash string) bool {
if caHash == "" {
caHash = DefaultCAHash
}
path := "/apex/com.android.conscrypt/cacerts/" + caHash + ".0"
out := c.Out("shell", "su", "-c", "ls "+path+" 2>/dev/null")
if strings.Contains(out, caHash+".0") {
return true
}
// Overlay copy is a weaker signal but useful when apex ls races the bind.
out = c.Out("shell", "su", "-c", "ls /data/local/tmp/cacerts-overlay/"+caHash+".0 2>/dev/null")
out := c.Out("shell", "su", "-c", "ls /apex/com.android.conscrypt/cacerts/"+caHash+".0")
return strings.Contains(out, caHash+".0")
}

View file

@ -3,54 +3,20 @@ package repo
import (
"os"
"path/filepath"
"strings"
)
// Root finds the install / repository root (directory that contains
// apps/pkg/go.mod plus a sibling marker such as README.md or outputs/).
//
// Search order:
// 1. Walk up from the current working directory
// 2. Walk up from streamd (if the exe lives in bin/, start at the parent)
// Root finds the repository root (directory that contains apps/pkg/go.mod
// and is not itself under apps/ — i.e. the real checkout root).
func Root() string {
if root := findRoot(wd()); root != "" {
return root
}
if root := findRoot(exeInstallDir()); root != "" {
return root
}
return wd()
}
func wd() string {
wd, err := os.Getwd()
if err != nil {
return "."
wd = "."
}
return wd
}
func exeInstallDir() string {
exe, err := os.Executable()
if err != nil {
return ""
}
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
exe = resolved
}
dir := filepath.Dir(exe)
if strings.EqualFold(filepath.Base(dir), "bin") {
return filepath.Dir(dir)
}
return dir
}
func findRoot(start string) string {
if start == "" {
return ""
}
cur := start
cur := wd
for i := 0; i < 16; i++ {
// Require apps/pkg/go.mod AND a sibling marker so that walking from
// inside apps/pkg does not treat apps/ as the root (apps/pkg/go.mod
// would match the old top-level pkg/ layout check).
pkgMod := filepath.Join(cur, "apps", "pkg", "go.mod")
if _, err := os.Stat(pkgMod); err == nil {
if markerOK(cur) {
@ -63,7 +29,7 @@ func findRoot(start string) string {
}
cur = parent
}
return ""
return wd
}
func markerOK(root string) bool {

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