streamd v0.2.2: session uptimes, egress DNS, Support, agent/Widevine
All checks were successful
release / build-and-upload (push) Successful in 7m2s

Dashboard Live uptimes + Recent runs from stream_sessions; overview.recent_sessions.
WireGuard netns resolv.conf + missing-deps WARN. Support donations card.
Agent start/stop/update, job_backoff default off, wvkey ensure/venv, phonecap retries,
modhost YAML enrich, DRM SetCredentials requires keys.
This commit is contained in:
404errordeveloper 2026-10-10 19:26:39 +02:00
parent 3ae1dd58b3
commit a091922efa
34 changed files with 2391 additions and 154 deletions

View file

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

View file

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

View file

@ -105,5 +105,9 @@ func Load(root, name string) (Module, string, Describe, error) {
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

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

View file

@ -206,17 +206,21 @@ func Run(opt Options) (res Result, err error) {
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/" + a.Package()
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, a.Package(), "8080", remoteDir, false, mitmHosts...); err != nil {
if err := proxy.StartTransparent(c, proxyBin, pkgName, "8080", remoteDir, false, mitmHosts...); err != nil {
return res, fmt.Errorf("transparent MITM start: %w", err)
}
defer proxy.StopTransparent(c)
@ -238,17 +242,6 @@ 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 == "" {
@ -256,107 +249,161 @@ func Run(opt Options) (res Result, err error) {
}
localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log")
localCap := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+"_cap.json")
// Fresh local mirrors each run so grab-all does not reuse a prior channel's MPD.
_ = os.WriteFile(localLog, nil, 0o644)
_ = os.Remove(localCap)
stop := make(chan struct{})
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"}
}
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.
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
// Skip for clear/MPD-only apps (KeyMode none).
if keyMode != "none" && keyMode != "clear" {
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
curPSSH := strings.TrimSpace(capData.Get("pssh"))
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
if needPSSH && mpdForPSSH != "" {
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
if curPSSH != "" && curPSSH != pssh {
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
}
capData["pssh"] = pssh
} else if err != nil && curPSSH == "" {
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
}
} else if curPSSH == "" {
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
capData["pssh"] = pssh
} else if err != nil {
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
}
}
}
}
mpdURL := strings.TrimSpace(capData.Get("mpd"))
// 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", "license_body"} {
v := capData.Get(k)
if k == "license_url" {
v = first(v, licenseURL)
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)
}
if v == "" {
// Fresh local mirrors each attempt so we do not reuse a prior MPD/PSSH.
_ = os.WriteFile(localLog, nil, 0o644)
_ = os.Remove(localCap)
if err := a.Launch(c); err != nil {
lastErr = fmt.Errorf("launch: %w", err)
continue
}
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")))
if !opt.NoAutoPlay {
if err := a.AutoPlay(c, opt.Channel); err != nil {
lastErr = fmt.Errorf("auto-play: %w", err)
c.ForceStop(a.Package())
continue
}
} else {
fmt.Println("[*] Open the channel on the phone and wait for playback…")
}
fmt.Println(" ", label+":", trim(v, 120))
}
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)
fmt.Printf("[*] Waiting for %s (attempt %d/%d, timeout %s)…\n",
strings.Join(need, " + "), attempt, attempts, waitPer.Round(time.Second))
fmt.Println(" watch:", localLog)
cap, err := capture.Wait(c, hints, localLog, localCap, waitPer)
if err != nil {
lastErr = err
fmt.Fprintf(os.Stderr, "[!] capture wait failed: %v\n", err)
c.ForceStop(a.Package())
continue
}
capData = cap
licenseURL = first(capData.Get("license_url"), a.LicenseURL())
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
if needsKeys {
enrichWidevinePSSH(capData)
}
mpdURL = strings.TrimSpace(capData.Get("mpd"))
fmt.Println()
fmt.Println("========== MPD ==========")
if mpdURL != "" {
fmt.Println(mpdURL)
} else {
fmt.Println("(none)")
}
fmt.Println("=========================")
fmt.Println()
fmt.Println("[+] Capture:")
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
v := capData.Get(k)
if k == "license_url" {
v = first(v, licenseURL)
}
if v == "" {
continue
}
label := k
switch k {
case "license_url":
label = "license"
case "license_body":
label = "license_body"
v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
}
fmt.Println(" ", label+":", trim(v, 120))
}
if !needsKeys {
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
lastErr = nil
break
}
k, kerr := fetchKey(opt, root, capData, licenseURL)
if kerr != nil {
// Allow MPD-only sessions when no .wvd was passed (grab-all / first pass),
// unless the app requires keys (e.g. c4).
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() {
return res, kerr
c.ForceStop(a.Package())
continue
}
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
} else {
return res, kerr
key = ""
lastErr = nil
break
}
} else {
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
fmt.Fprintf(os.Stderr, "[!] key fetch failed (attempt %d/%d): %v\n", attempt, attempts, kerr)
c.ForceStop(a.Package())
continue
}
if strings.TrimSpace(k) == "" || !looksLikeKey(k) {
lastErr = fmt.Errorf("wvkey returned no usable KID:KEY")
fmt.Fprintf(os.Stderr, "[!] %v (attempt %d/%d)\n", lastErr, attempt, attempts)
c.ForceStop(a.Package())
continue
}
key = k
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
lastErr = nil
break
}
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{
@ -384,6 +431,62 @@ 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)
@ -414,16 +517,18 @@ 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)")
}
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")
}
// 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
}
wopt := wvkey.Options{
Python: py,
Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"),
Script: rt.Script,
WVD: opt.WVD,
PSSH: cap.Get("pssh"),
Auth: cap.Get("auth"),
@ -465,6 +570,11 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
}
}
func fileExistsPath(path string) bool {
st, err := os.Stat(path)
return err == nil && !st.IsDir()
}
func first(vals ...string) string {
for _, v := range vals {
if strings.TrimSpace(v) != "" {

View file

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

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

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

View file

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