v0.1.1: external modules, publish YAML, proxy reset, binary-first README
All checks were successful
release / build-and-upload (push) Successful in 6m8s
modules-release / build-and-upload (push) Successful in 4m47s

- Host discovers/builds modules under modules/ (bbc, rte, tg4)
- module-publish.yaml tracked; local module.yaml gitignored
- drm --modules-dir / DRM_MODULES_DIR
- drm proxy reset; Magisk reinject reliability
- modules-v* Forgejo release workflow + build scripts
- BBC full Explore channel map including S4C
- README quickstart based on release binaries
This commit is contained in:
404errordeveloper 2026-10-08 23:16:14 +02:00
parent 1d36961a7c
commit f9c28be3f1
52 changed files with 2915 additions and 636 deletions

View file

@ -6,8 +6,9 @@ import (
"strings"
"time"
"drmdecryption/app"
"drmdecryption/modhost"
"drmdecryption/phonecap"
"drmdecryption/repo"
"drmdecryption/apps/agent/internal/client"
"drmdecryption/apps/agent/internal/device"
@ -88,11 +89,11 @@ func isUnknownAppErr(err error) bool {
return false
}
s := strings.ToLower(err.Error())
return strings.Contains(s, "unknown app")
return strings.Contains(s, "unknown app") || strings.Contains(s, "unknown module") || strings.Contains(s, "no modules found")
}
func (w *Worker) runJob(job queue.Job) error {
a, err := app.Get(job.App)
a, err := modhost.Open(repo.Root(), job.App)
if err != nil {
return err
}

View file

@ -12,18 +12,27 @@ import (
"drmdecryption/adb"
"drmdecryption/app"
"drmdecryption/modcfg"
"drmdecryption/modhost"
"drmdecryption/phonecap"
"drmdecryption/repo"
)
// Run performs one capture. App modules are compiled in, so there is no modules
// directory to scan: --app names a registered provider.
// Run performs one capture. Providers live under modules/<name>/ and are built
// and executed by modhost — they are not linked into drm.exe.
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. Empty = passive MITM, no launch/auto-play")
appName := fs.String("app", "", "app module under modules/<name>/. Empty = passive MITM, no launch/auto-play")
channel := fs.String("channel", "", "channel id for --auto-play")
autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (requires --app and --channel)")
autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (implied when --channel is set)")
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 for key fetch)")
@ -31,10 +40,8 @@ func Run(args []string) error {
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 | 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] [--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(), "|"))
fmt.Fprintf(fs.Output(), "capture — one-shot phone MITM capture\n\nUsage:\n capture --app <%s> [--channel ID] [--auto-play] [--wvd PATH]\n capture (passive: play anything on the phone)\n\nExample (BBC + NordVPN UK):\n capture --app bbc --channel bbcone --wait 120\n\nFlags:\n", appChoices)
fs.PrintDefaults()
}
@ -65,26 +72,29 @@ func Run(args []string) error {
return err
}
a, err := app.Get(*appName)
a, err := modhost.Open(root, *appName)
if err != nil {
return err
return modhost.FormatUnknown(root, *appName)
}
if *autoPlay && strings.TrimSpace(*channel) == "" {
channelID := strings.TrimSpace(*channel)
// --channel implies interactive auto-play (Explore → channel → Watch live).
doAutoPlay := *autoPlay || channelID != ""
if *autoPlay && channelID == "" {
return fmt.Errorf("--auto-play requires --channel (%s)", knownChannels(a))
}
if *channel != "" && !a.HasChannel(*channel) {
return fmt.Errorf("unknown channel %q for %s (%s)", *channel, a.Name(), knownChannels(a))
if channelID != "" && !a.HasChannel(channelID) {
return fmt.Errorf("unknown channel %q for %s (%s)", channelID, a.Name(), knownChannels(a))
}
_, err = phonecap.Run(phonecap.Options{
App: a,
Channel: *channel,
Channel: channelID,
Client: c,
Python: *python,
WVD: *wvd,
UserAgent: *userAgent,
Wait: time.Duration(*waitSec) * time.Second,
NoAutoPlay: !*autoPlay,
NoAutoPlay: !doAutoPlay,
CloseApp: *closeApp,
KeyMode: *keyMode,
ClearProxy: true,

View file

@ -5,8 +5,6 @@ import (
"testing"
"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. It is provider-agnostic: any app module
// implementing app.Catalog works here.
// public catalog, with no phone involved. Providers live under modules/<name>/
// and are invoked via modhost.
package catalogcmd
import (
@ -11,7 +11,7 @@ import (
"sort"
"strings"
"drmdecryption/app"
"drmdecryption/modhost"
"drmdecryption/repo"
"drmdecryption/session"
)
@ -19,7 +19,7 @@ import (
// 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 to query")
appName := fs.String("app", "", "app module under modules/<name>/")
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,8 +27,6 @@ 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()
@ -40,33 +38,36 @@ func Run(args []string) error {
available := catalogApps()
if strings.TrimSpace(*appName) == "" {
if len(available) != 1 {
return fmt.Errorf("--app required (apps with a catalog: %s)", strings.Join(available, ", "))
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)
}
*appName = available[0]
}
a, err := app.Get(*appName)
a, err := modhost.Open(repo.Root(), *appName)
if err != nil {
return err
return modhost.FormatUnknown(repo.Root(), *appName)
}
cat, ok := a.(app.Catalog)
if !ok {
if !a.Desc.HasCatalog {
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, cat)
return listChannels(a)
}
if strings.TrimSpace(*channel) == "" {
return fmt.Errorf("--channel required (see: drm catalog --app %s --list)", a.Name())
}
info, err := cat.Resolve(*channel)
info, err := a.Resolve(*channel)
if err != nil {
return err
}
if *withKeys {
fmt.Fprintln(os.Stderr, "[*] fetching PSSH + Widevine keys…")
if err := cat.EnrichWithKeys(&info, *python, *wvd); err != nil {
if err := a.EnrichWithKeys(&info, *python, *wvd); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "[+] key %s (%d total)\n", info.Key, len(info.Keys))
@ -87,48 +88,23 @@ func Run(args []string) error {
return nil
}
// catalogApps lists compiled-in modules that can answer catalog lookups.
// catalogApps lists external modules that advertise HasCatalog.
func catalogApps() []string {
listed, err := modhost.ListAll(repo.Root())
if err != nil {
return nil
}
out := []string{}
for _, a := range app.All() {
if _, ok := a.(app.Catalog); ok {
out = append(out, a.Name())
for _, L := range listed {
if L.Desc.HasCatalog {
out = append(out, L.Desc.Name)
}
}
sort.Strings(out)
return out
}
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.
func listChannels(a *modhost.RemoteApp) error {
fmt.Printf("%-10s %s\n", "CHANNEL", "LABEL")
for _, ch := range a.Channels() {
fmt.Printf("%-10s %s\n", ch.ID, ch.Label)

View file

@ -8,7 +8,6 @@ require (
drmdecryption/apps/capture v0.0.0
drmdecryption/apps/proxy v0.0.0
drmdecryption/apps/streamd v0.0.0
drmdecryption/modules v0.0.0
)
require (
@ -32,5 +31,4 @@ replace (
drmdecryption/apps/capture => ../capture
drmdecryption/apps/proxy => ../proxy
drmdecryption/apps/streamd => ../streamd
drmdecryption/modules => ../modules
)

View file

@ -1,11 +1,13 @@
// 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. Every app module under apps/modules is compiled in.
// on-device MITM. Providers live under modules/<name>/ and are discovered,
// built, and executed by the host — they are not linked into this binary.
package main
import (
"fmt"
"os"
"strings"
"drmdecryption/apps/agent/agentcmd"
"drmdecryption/apps/capture/capturecmd"
@ -14,22 +16,33 @@ import (
"drmdecryption/apps/proxy/proxyctlcmd"
"drmdecryption/apps/streamd/servecmd"
"drmdecryption/bootstrap"
// Links every app module into this binary.
_ "drmdecryption/modules/all"
"drmdecryption/modhost"
)
func main() {
if len(os.Args) < 2 {
args := os.Args[1:]
modulesDir, args := peelGlobalFlags(args)
if len(args) < 1 {
usage()
os.Exit(2)
}
cmd, args := os.Args[1], os.Args[2:]
cmd, args := args[0], args[1:]
// Materialise apps/, bin/, outputs/, … next to this exe when missing
// so a lone downloaded drm.exe becomes a GitHub-like install tree.
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, "[!] DRM_MODULES_DIR:", err)
os.Exit(1)
}
// Materialise apps/, bin/, modules/, outputs/, … next to this exe when
// missing so a lone downloaded drm.exe becomes a GitHub-like install tree.
if cmd != "help" && cmd != "-h" && cmd != "--help" {
if err := bootstrap.EnsureAndLog(); err != nil {
if err := bootstrap.EnsureAndLogFor(cmd); err != nil {
fmt.Fprintln(os.Stderr, "[!] bootstrap:", err)
os.Exit(1)
}
@ -62,27 +75,45 @@ 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, `drm — DRM capture / restream toolchain
Usage:
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 [--modules-dir DIR] modules
drm [--modules-dir DIR] capture --app NAME [--channel ID] [--wvd PATH]
drm [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json]
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
drm proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
App module *code* is compiled in; module *values* are never inside the exe.
Put configs at apps/modules/<name>/module.yaml yourself (see the GitHub repo).
On first run, drm only creates the scaffold (apps/pkg, bin/proxy, outputs, …).
Global flags:
--modules-dir DIR provider folder (default: <install>/modules, or $DRM_MODULES_DIR)
Overrides: --<app>.<field> flags or <APP>_<FIELD> environment variables.
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.
Run any subcommand with --help for its own flags.
`)

View file

@ -1,5 +1,5 @@
// Package modulescmd lists the app modules compiled into this binary, their
// channels, and where each one's local values came from.
// Package modulescmd lists provider modules discovered under modules/<name>/,
// building them on demand and showing channels + values paths.
package modulescmd
import (
@ -9,11 +9,11 @@ import (
"sort"
"text/tabwriter"
"drmdecryption/app"
"drmdecryption/modcfg"
"drmdecryption/modhost"
"drmdecryption/repo"
)
// Run prints the compiled-in app modules.
// Run prints external modules under modules/.
func Run(args []string) error {
fs := flag.NewFlagSet("modules", flag.ExitOnError)
verbose := fs.Bool("channels", true, "list each module's channels")
@ -21,54 +21,57 @@ func Run(args []string) error {
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")
root := repo.Root()
listed, err := modhost.ListAll(root)
if err != nil {
return err
}
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 _, 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
for _, L := range listed {
d := L.Desc
rewriter := d.Rewriter
if rewriter == "" {
rewriter = "none"
}
rewriter := "none"
if sd, ok := a.(app.StreamDefaults); ok && sd.RewriterName() != "" {
rewriter = sd.RewriterName()
}
pkg := a.Package()
pkg := d.Package
if pkg == "" {
pkg = "(not configured)"
}
values := modcfg.Path(name)
values := d.ValuesPath
if values == "" {
values = L.Mod.Dir + string(os.PathSeparator) + "module.yaml"
}
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",
name, pkg, a.KeyMode(), rewriter, len(a.Channels()), values)
d.Name, pkg, d.KeyMode, rewriter, len(d.Channels), values)
}
_ = tw.Flush()
if !*verbose {
return nil
}
for _, name := range names {
a, err := app.Get(name)
if err != nil {
continue
}
chans := a.Channels()
for _, L := range listed {
d := L.Desc
chans := append([]modhost.Channel{}, d.Channels...)
sort.Slice(chans, func(i, j int) bool { return chans[i].ID < chans[j].ID })
fmt.Printf("\n%s channels:", name)
fmt.Printf("\n%s channels:", d.Name)
if len(chans) == 0 {
fmt.Printf(" none — add %s\n", modcfg.Path(name))
fmt.Printf(" none — add %s\n", d.ValuesPath)
continue
}
fmt.Println()
for _, ch := range chans {
catalog := ""
if _, ok := a.(app.Catalog); ok {
if d.HasCatalog {
catalog = " (catalog)"
}
fmt.Printf(" %-10s %s%s\n", ch.ID, ch.Label, catalog)

View file

@ -90,34 +90,35 @@ func (a *App) Launch(c *adb.Client) error {
return nil
}
// AutoPlay: best-effort; iPlayer UI varies — operator can play by hand.
// AutoPlay opens Explore, taps the channel logo, then Watch live — same style
// as RTE/TG4 interactive navigation, driven by uiautomator dumps.
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 — open Live and start playback on the phone…\n", a.Label(id))
fmt.Printf("[*] Auto-play %s…\n", a.Label(id))
if ch.VPID != "" {
fmt.Printf(" expected mediaselector vpid ≈ %s\n", ch.VPID)
}
c.DismissShadeIfFocused()
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.openExplorePage(c); 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)
if err := a.tapChannel(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)
}
time.Sleep(time.Duration(a.cfg.Timeouts.AfterChannel))
if err := a.tapWatchLive(c, ch); err != nil {
return 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),
Timeout: time.Duration(a.cfg.Timeouts.Playback),
SoftFail: true,
OrDescContains: a.cfg.UI.PlaybackDescContains,
})
}

View file

@ -1,6 +1,7 @@
package bbc
import (
"regexp"
"time"
"drmdecryption/modcfg"
@ -10,18 +11,19 @@ import (
// Name is the module id (--app bbc).
const Name = "bbc"
// Channel is one live (or catch-up) target. Phone UI selectors are optional —
// capture works with manual play; auto-play uses them when present.
// Channel is one live target. Label doubles as the Explore-rail content-desc
// (e.g. "BBC One") unless ChipDesc overrides it.
type Channel struct {
Label string `yaml:"label"`
// VPID is the mediaselector version/service id (e.g. bbc_one_london).
VPID string `yaml:"vpid"`
// ChipDesc / PlayDesc are optional UI matchers for --auto-play.
// ChipDesc matches the channel logo on Explore (content-desc). Default: Label.
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 apps/modules/bbc/module.yaml.
// Config is modules/bbc/module.yaml (preferred) or apps/modules/bbc/module.yaml.
type Config struct {
provider.Common `yaml:",inline"`
@ -31,30 +33,79 @@ type Config struct {
UI UI `yaml:"ui"`
}
// Timeouts for launch / optional autoplay.
// Timeouts for launch / autoplay. Written as "25s" in module.yaml.
type Timeouts struct {
LaunchWaitUI provider.Duration `yaml:"launch_wait_ui"`
LaunchSettle provider.Duration `yaml:"launch_settle"`
Playback provider.Duration `yaml:"playback"`
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"`
}
// UI markers for launch readiness (localized; keep loose).
// UI markers for launch readiness and interactive navigation.
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))
if len(c.UI.LaunchDescContains) == 0 {
c.UI.LaunchDescContains = []string{"iPlayer", "Home", "Live"}
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
}
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

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

@ -1,51 +0,0 @@
# 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"]

237
apps/modules/bbc/steps.go Normal file
View file

@ -0,0 +1,237 @@
package bbc
import (
"fmt"
"regexp"
"strings"
"time"
"drmdecryption/adb"
"drmdecryption/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

@ -0,0 +1,60 @@
# 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:
launch_desc_contains: ["live tab", "header logo", "Live"]
live_tab_desc_re: ["Live tab", "Live"]
timeouts:
launch_wait_ui: 30s
launch_settle: 4s
live_tab: 30s
playback: 45s

View file

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

@ -132,6 +132,12 @@ func sameFile(a, b string) bool {
// 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
@ -150,10 +156,13 @@ func EnsureAndLog() error {
if st, err := os.Stat(proxy); err != nil || st.Size() < minProxyBytes {
fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to drm or use a release build that embeds it\n")
}
// Module configs are never shipped inside drm.exe — operator must add them.
modBBC := filepath.Join(root, "apps", "modules", "bbc", "module.yaml")
if _, err := os.Stat(modBBC); err != nil {
fmt.Fprintf(os.Stderr, "[!] no apps/modules/*/module.yaml yet — create e.g. apps/modules/bbc/module.yaml (not bundled in the exe)\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,154 +1,22 @@
# DRM-Decryption
# Null DRM
Capture Widevine live sessions from Android streaming apps and restream them.
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.
- **[docs/](docs/)** — architecture, module authoring, per-provider setup
- **[docs/quickstart.md](docs/quickstart.md)** — the longer version of what follows
---
Host binary **`drm`** + providers under **`modules/`**.
## Quick start
### 1. Prerequisites
| Need | Why |
|---|---|
| **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 |
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.
### 2. Clone and build
```bash
git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official.git
cd Null-DRM-Official
# Linux / macOS
go -C apps/cli build -o ../../bin/drm .
# Windows
go -C apps/cli build -o ../../bin/drm.exe .
```
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:
1. Download `drm` (`v*` release) and module zips (`modules-v*` release).
2. Unzip providers into `modules/<name>/` and edit `module.yaml` (secrets only).
3. `drm proxy install-ca --reinject`
4. `drm capture --app bbc --channel bbcone --wait 120`
5. `drm proxy reset` when finished.
```text
apps/modules/tg4/module.yaml
apps/modules/rte/module.yaml
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
```
Where each value comes from:
`--modules-dir DIR` or `$DRM_MODULES_DIR` selects another modules folder.
- **[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.
---
## Subcommands
| 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` |
Run any of them with `--help`.
## 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
```
## Tests
```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.
Full docs: https://git.nulldrm.com/nulldrm/Null-DRM-Official

View file

@ -0,0 +1,20 @@
# External modules
Each subdirectory is a provider the `drm` 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,10 +1,12 @@
// Package modcfg loads an app module's values from its local, untracked
// apps/modules/<name>/module.yaml, with environment-variable overrides.
// Package modcfg loads an app module's values from modules/<name>/,
// with environment-variable overrides.
//
// 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.
// 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.
package modcfg
import (
@ -13,42 +15,75 @@ import (
"path/filepath"
"strings"
"drmdecryption/modhost"
"drmdecryption/repo"
"gopkg.in/yaml.v3"
)
// Dir returns the directory holding a module's local values.
// Dir returns the directory holding a module's values.
// Prefers the active modules dir (see modhost / --modules-dir); falls back to
// apps/modules/<name>/ for older checkouts.
func Dir(name string) string {
return filepath.Join(repo.Root(), "apps", "modules", name)
preferred := filepath.Join(modhost.ModulesDir(""), name)
if st, err := os.Stat(preferred); err == nil && st.IsDir() {
return preferred
}
if modhost.ModulesDirOverride() != "" {
return preferred
}
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)
}
// Path returns the module's values file path.
// Path returns the preferred values file path (module.yaml).
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 apps/modules/<name>/module.yaml into dst. A missing file is not an
// error — the module runs on its Go defaults plus flags/env.
// 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.
func Load(name string, dst any) (Result, error) {
path := Path(name)
res := Result{Path: path}
b, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return res, nil
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)
}
loadedAny = true
res.Path = publish
} else if !os.IsNotExist(err) {
return res, err
}
if err := yaml.Unmarshal(b, dst); err != nil {
return res, fmt.Errorf("%s: %w", path, 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
}
res.Loaded = true
res.Loaded = loadedAny
return res, nil
}
@ -70,7 +105,6 @@ 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

107
apps/pkg/modhost/build.go Normal file
View file

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

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

78
apps/pkg/modhost/exec.go Normal file
View file

@ -0,0 +1,78 @@
package modhost
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
)
// Run executes the module binary with args, inheriting stdout/stderr.
func Run(bin string, args ...string) error {
cmd := exec.Command(bin, args...)
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...)
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
}
return m, bin, d, nil
}

View file

@ -0,0 +1,33 @@
// Package modhost discovers, builds, and runs external provider modules that
// live under modules/<name>/ (Go source + module.yaml), outside drm.exe.
package modhost
import "drmdecryption/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"`
Rewriter string `json:"rewriter,omitempty"`
Channels []Channel `json:"channels"`
Require []string `json:"require,omitempty"`
Score capture.ScoreCfg `json:"score,omitempty"`
HasCatalog bool `json:"has_catalog"`
ValuesPath string `json:"values_path,omitempty"`
ValuesLoaded bool `json:"values_loaded"`
}

View file

@ -0,0 +1,224 @@
package modhost
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"drmdecryption/adb"
"drmdecryption/app"
"drmdecryption/capture"
"drmdecryption/mpd"
"drmdecryption/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) 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.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)
}

62
apps/pkg/modhost/root.go Normal file
View file

@ -0,0 +1,62 @@
package modhost
import (
"os"
"path/filepath"
"sync"
"drmdecryption/repo"
)
var (
rootMu sync.RWMutex
modulesDirOV string // absolute path override for the modules directory
)
// SetModulesDir overrides where providers are discovered (drm --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
}
// EffectiveModulesDir is the directory that Discover/Open scan.
// Prefer --modules-dir / DRM_MODULES_DIR; else <root>/modules.
func EffectiveModulesDir(root string) string {
if ov := ModulesDirOverride(); ov != "" {
return ov
}
if root == "" {
root = repo.Root()
}
return filepath.Join(root, "modules")
}
// ApplyEnvModulesDir sets the override from DRM_MODULES_DIR when no flag was set.
func ApplyEnvModulesDir() error {
if ModulesDirOverride() != "" {
return nil
}
v := os.Getenv("DRM_MODULES_DIR")
if v == "" {
return nil
}
return SetModulesDir(v)
}

View file

@ -500,7 +500,7 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
return fmt.Errorf("CA hash: %w", err)
}
if reinject {
ReinjectCA(c, caHash)
ReinjectCAForPackage(c, caHash, pkg)
}
if st, err := os.Stat(localBin); err != nil || st.IsDir() {
@ -597,6 +597,67 @@ func StopTransparent(c *adb.Client) {
fmt.Println("[*] transparent capture stopped")
}
// 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) != "" {
@ -692,80 +753,154 @@ func DiscoverOutDir(root, stamp string) string {
return filepath.Join(root, "outputs", "discover", stamp)
}
// ReinjectCA best-effort Magisk bind of the mitm CA into conscrypt.
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).
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
}
// Bound the per-app nsenter loop — wait on hundreds of PIDs can hang forever.
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)
}
script := fmt.Sprintf(`
BB=/data/adb/magisk/busybox
HASH=%s
[ -f /data/local/tmp/$HASH.0 ] || { echo CA_SKIP; exit 0; }
[ -x "$BB" ] || { echo CA_SKIP; exit 0; }
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; }
rm -rf /data/local/tmp/cacerts-overlay
mkdir -p /data/local/tmp/cacerts-overlay
cp /apex/com.android.conscrypt/cacerts/* /data/local/tmp/cacerts-overlay/ 2>/dev/null || true
# 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 /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/*
$BB mount -t tmpfs tmpfs /system/etc/security/cacerts 2>/dev/null || true
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
cp /data/local/tmp/cacerts-overlay/* /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
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
$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
# Only rebind the target app if set; otherwise skip the full zygote-child sweep (hangs).
PKG_UID_FILE=/data/local/tmp/reinject_target_uid
PKG_UID_FILE=%s
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
ls /apex/com.android.conscrypt/cacerts/$HASH.0 2>/dev/null && echo CA_OK || echo CA_SKIP
`, caHash)
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)
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, "/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)
_ = 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.
go func() {
out, _, _ := c.Run("shell", "su", "-mm", "-c", "sh /data/local/tmp/reinject_ca.sh")
ch <- runResult{out: out}
_, _, _ = c.Run("shell", "su", "-mm", "-c", "sh "+remoteReinjectScript)
}()
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")
// Script may have finished mounting even if su -mm hung; verify on device.
if caPresentOnDevice(c, caHash) {
fmt.Println("[+] System CA present in conscrypt (reinject timed out, mount OK)")
} else {
fmt.Println("[!] CA reinject timed out after 20s — re-run: drm proxy install-ca --reinject")
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
}
return
time.Sleep(400 * time.Millisecond)
}
if strings.Contains(out, "CA_OK") || caPresentOnDevice(c, caHash) {
if status == "" || status == "RUNNING" {
_, _ = 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")
} else {
fmt.Println("[!] CA inject skipped/failed — re-run: drm proxy install-ca --reinject")
case strings.HasPrefix(status, "CA_SKIP"):
fmt.Printf("[!] CA inject skipped (%s) — re-run: drm proxy install-ca --reinject\n", status)
default:
if caPresentOnDevice(c, caHash) {
fmt.Println("[+] System CA present in conscrypt (status race, mount OK)")
} else {
fmt.Println("[!] CA reinject timed out — 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
}
out := c.Out("shell", "su", "-c", "ls /apex/com.android.conscrypt/cacerts/"+caHash+".0")
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")
return strings.Contains(out, caHash+".0")
}

View file

@ -51,6 +51,8 @@ func Run(args []string) error {
clearProxyCmd(rest)
case "transparent", "tproxy":
transparentCmd(rest)
case "reset":
return resetCmd(rest)
case "help", "-h", "--help":
Usage()
default:
@ -82,12 +84,32 @@ Usage:
proxyctl transparent --package PKG [--serial S] [--out DIR] [--reinject]
iptables REDIRECT capture (UK VPN OK; no Wi‑Fi proxy)
writes /data/local/tmp/capture/<pkg>/ ; adb-pulled to --out
proxyctl reset [--serial S] [--keep-captures]
stop MITM + delete pushed CA/binaries/scripts on device
Artifacts land under outputs/discover/<timestamp>/ by default.
Transparent captures pull into outputs/transparent/<stamp>/ by default.
`)
}
func resetCmd(args []string) error {
fs := flag.NewFlagSet("reset", flag.ContinueOnError)
serial := fs.String("serial", "", "adb device serial")
keep := fs.Bool("keep-captures", false, "leave /data/local/tmp/capture/")
yes := fs.Bool("yes", true, "confirm reset (default true)")
if err := fs.Parse(args); err != nil {
return err
}
if !*yes {
return fmt.Errorf("reset cancelled")
}
c := adb.New()
if *serial != "" {
c = c.WithSerial(*serial)
}
return proxy.ResetDevice(c, proxy.ResetOptions{KeepCaptures: *keep})
}
func clientFrom(fs *flag.FlagSet, args []string) *adb.Client {
serial := fs.String("serial", "", "adb device serial")
_ = fs.Parse(args)

View file

@ -30,7 +30,7 @@ Open `http://HOST:8083/` and put the token in the header box for mutating action
| Method | Path | Notes |
|---|---|---|
| GET | `/api/health` | liveness + uptime |
| GET | `/api/apps` | compiled-in app modules, channels, registered rewriters |
| GET | `/api/apps` | modules/<name>/ providers, channels, registered rewriters |
| GET | `/api/streams` | list + runtime (the agent polls this) |
| POST | `/api/streams` | create |
| GET/PATCH/DELETE | `/api/streams/:id` | detail / edit / delete |

View file

@ -3,12 +3,13 @@ package api
import (
"net/http"
"drmdecryption/app"
"drmdecryption/modhost"
"drmdecryption/mpd"
"drmdecryption/repo"
)
// appInfo describes one compiled-in app module to the dashboard, so the UI never
// has to hardcode a provider or channel name.
// appInfo describes one modules/<name>/ provider to the dashboard, so the UI
// never has to hardcode a provider or channel name.
type appInfo struct {
Name string `json:"name"`
Channels []channelInfo `json:"channels"`
@ -21,22 +22,27 @@ type channelInfo struct {
Label string `json:"label"`
}
// apps answers GET /api/apps: which providers this binary was built with.
// apps answers GET /api/apps: which providers exist under modules/.
func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
out := []appInfo{}
for _, a := range app.All() {
info := appInfo{Name: a.Name(), Channels: []channelInfo{}, Rewriter: "none"}
for _, ch := range a.Channels() {
listed, err := modhost.ListAll(repo.Root())
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
for _, L := range listed {
d := L.Desc
info := appInfo{Name: d.Name, Channels: []channelInfo{}, Rewriter: "none"}
for _, ch := range d.Channels {
info.Channels = append(info.Channels, channelInfo{ID: ch.ID, Label: ch.Label})
}
// A module with no local values file has no channels to offer yet.
info.HasConfig = len(info.Channels) > 0
if sd, ok := a.(app.StreamDefaults); ok {
info.Rewriter = sd.RewriterName()
if d.Rewriter != "" {
info.Rewriter = d.Rewriter
}
out = append(out, info)
}

View file

@ -5,6 +5,8 @@ import (
"drmdecryption/app"
"drmdecryption/apps/streamd/internal/db"
"drmdecryption/modhost"
"drmdecryption/repo"
)
// streamSettings are the downloader knobs for one stream. They come from the
@ -40,23 +42,21 @@ func settingsFor(st db.Stream) streamSettings {
TSReadyBytes: defaultTSReadyBytes,
IsHLS: isHLS(st),
}
if a, err := app.Get(st.App); err == nil {
if sd, ok := a.(app.StreamDefaults); ok {
if s.VideoSelect == "" {
s.VideoSelect = sd.VideoSelect()
}
if s.AudioSelect == "" {
s.AudioSelect = sd.AudioSelect()
}
if s.Rewriter == "" {
s.Rewriter = sd.RewriterName()
}
if n := sd.LiveWaitSeconds(); n > 0 {
s.LiveWait = n
}
if n := sd.TSReadyBytes(); n > 0 {
s.TSReadyBytes = n
}
if sd := streamDefaultsFor(st.App); sd != nil {
if s.VideoSelect == "" {
s.VideoSelect = sd.VideoSelect()
}
if s.AudioSelect == "" {
s.AudioSelect = sd.AudioSelect()
}
if s.Rewriter == "" {
s.Rewriter = sd.RewriterName()
}
if n := sd.LiveWaitSeconds(); n > 0 {
s.LiveWait = n
}
if n := sd.TSReadyBytes(); n > 0 {
s.TSReadyBytes = n
}
}
if s.IsHLS {
@ -79,6 +79,23 @@ func settingsFor(st db.Stream) streamSettings {
return s
}
// streamDefaultsFor prefers an external modules/<name>/ provider; falls back to
// any in-process app.Register (used by unit tests).
func streamDefaultsFor(name string) app.StreamDefaults {
if name == "" {
return nil
}
if a, err := modhost.Open(repo.Root(), name); err == nil {
return a
}
if a, err := app.Get(name); err == nil {
if sd, ok := a.(app.StreamDefaults); ok {
return sd
}
}
return nil
}
// isHLS reports whether a stream's manifest is an HLS playlist, by URL shape.
// No provider host is consulted: a module declares its own needs through
// app.StreamDefaults.