Compare commits

..
14 Commits
Author SHA1 Message Date
Andy bf9087a1ce chore(release): bump version to 3.0.0
BREAKING CHANGE: PlayReady users without explicit playready_devices no longer get access to all devices by default.

Key changes:
- feat(drm): add MonaLisa DRM support to core infrastructure
- feat(cdm): add remote PlayReady CDM support via pyplayready RemoteCdm
- feat(serve): add PlayReady CDM support alongside Widevine
- feat(gluetun): Gluetun VPN integration and Windscribe support
- feat(audio): codec lists and split muxing
- feat(tracks): prioritize Atmos audio tracks over higher bitrate non-Atmos
- feat(video): detect interlaced scan type from MPD manifests
- feat(cdm): normalize CDM detection for local and remote implementations
- fix(serve)!: make PlayReady users config consistently a mapping
- 50+ additional bug fixes across HLS/DASH, proxies, subtitles, and more
2026-02-15 13:04:42 -07:00
Andy 23cc351f77 feat(tracks): prioritize Atmos audio tracks over higher bitrate non-Atmos 2026-02-15 12:08:27 -07:00
Andy 132d3549f9 fix(main): update copyright year dynamically in version display 2026-02-11 16:01:33 -07:00
Andy 3ee554401a feat(HLS): improve audio codec handling with error handling for codec extraction 2026-02-10 08:34:54 -07:00
Andy 29a697a8e7 fix(tracks): close temp session and improve path type error 2026-02-08 20:04:22 -07:00
Andy c5b063391c fix(serve): default PlayReady access to none
Remove unreachable fallback to all devices; if a user has no explicit playready_devices configured, the PlayReady subapp receives an empty list (secure-by-default).
2026-02-08 20:00:39 -07:00
Andy 5fa0b33664 revert(monalisa): pass key via argv again
Reverts the env/stdin key passing change introduced in 6c83790, since ML-Worker builds in use expect the key as argv[1].
2026-02-08 19:51:22 -07:00
Andy 5650c2b591 fix(hls): remove no-op encryption_data reassignment 2026-02-08 10:43:49 -07:00
Andy 5f49663ea8 fix(monalisa): harden wasm calls and license handling
- Validate _monalisa_context_alloc return and cleanup on init failure
- Derive deterministic KID when DCID missing to avoid collisions
- Ensure stackRestore always runs via try/finally in _ccall
- Log base64 decode failures without leaking license contents
- Add bounds/alignment checks for i32 memory writes
2026-02-08 10:39:23 -07:00
Andy 6b8a8ba8a8 feat(cdm): normalize CDM detection for local and remote implementations
Add unshackle.core.cdm.detect helpers to classify CDMs consistently across local and remote backends.

- Add is_playready_cdm/is_widevine_cdm for DRM selection across pyplayready, pywidevine, and wrappers

- Add is_remote_cdm/is_local_cdm/cdm_location so services can branch on CDM execution location

- Switch core DASH/HLS parsing, track DRM selection, and dl CDM switching away from brittle isinstance/DecryptLabs-only checks

- Make unshackle.core.cdm import-light via lazy __getattr__ so optional CDM deps are only imported when needed
2026-02-08 00:37:53 -07:00
Andy b9fb928292 fix(service): redact proxy credentials in logs
Proxy URIs may contain embedded userinfo (username/password). Add a small sanitizer helper and use it for proxy mapping and proxy selection logs to avoid leaking credentials.
2026-02-07 20:36:25 -07:00
Andy 984a8b9efa fix(proxies): harden surfshark and windscribe selection 2026-02-07 20:34:31 -07:00
Andy 71adee4ec6 fix(api): log PSSH extraction failures 2026-02-07 20:29:53 -07:00
Andy ee8f7cb650 docs(config): clarify sdh_method uses subtitle-filter 2026-02-07 20:29:31 -07:00
21 changed files with 476 additions and 106 deletions
+33 -2
View File
@@ -6,7 +6,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
This changelog is automatically generated using [git-cliff](https://git-cliff.org). This changelog is automatically generated using [git-cliff](https://git-cliff.org).
## [Unreleased] ## [3.0.0] - 2026-02-15
### Features ### Features
@@ -21,6 +21,9 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
- *drm*: Add MonaLisa DRM support to core infrastructure - *drm*: Add MonaLisa DRM support to core infrastructure
- *audio*: Codec lists and split muxing - *audio*: Codec lists and split muxing
- *proxy*: Add specific server selection for WindscribeVPN - *proxy*: Add specific server selection for WindscribeVPN
- *cdm*: Normalize CDM detection for local and remote implementations
- *HLS*: Improve audio codec handling with error handling for codec extraction
- *tracks*: Prioritize Atmos audio tracks over higher bitrate non-Atmos
### Bug Fixes ### Bug Fixes
@@ -53,11 +56,39 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
- *dl*: Always clean up hybrid temp hevc outputs - *dl*: Always clean up hybrid temp hevc outputs
- *hls*: Finalize n_m3u8dl_re outputs - *hls*: Finalize n_m3u8dl_re outputs
- *downloader*: Restore requests progress for single-url downloads - *downloader*: Restore requests progress for single-url downloads
- *dl*: Invert audio codec suffixing when splitting
- *dl*: Support snake_case keys for RemoteCdm
- *aria2c*: Warn on config mismatch and wait for RPC ready
- *serve*: [**breaking**] Make PlayReady users config consistently a mapping
- *dl*: Preserve proxy_query selector (not resolved URI)
- *gluetun*: Stop leaking proxy/vpn secrets to process list
- *monalisa*: Avoid leaking secrets and add worker safety
- *dl*: Avoid selecting all variants when multiple audio codecs requested
- *hls*: Keep range offset numeric and align MonaLisa licensing
- *titles*: Remove trailing space from HDR dynamic range label
- *config*: Normalize playready_remote remote_cdm keys
- *titles*: Avoid None/double spaces in HDR tokens
- *naming*: Keep technical tokens with scene_naming off
- *api*: Log PSSH extraction failures
- *proxies*: Harden surfshark and windscribe selection
- *service*: Redact proxy credentials in logs
- *monalisa*: Harden wasm calls and license handling
- *hls*: Remove no-op encryption_data reassignment
- *serve*: Default PlayReady access to none
- *tracks*: Close temp session and improve path type error
- *main*: Update copyright year dynamically in version display
### Reverts
- *monalisa*: Pass key via argv again
### Documentation ### Documentation
- Add configuration documentation WIP - Add configuration documentation WIP
- *changelog*: Add 2.4.0 release notes - *changelog*: Add 2.4.0 release notes
- *changelog*: Update cliff config and regenerate changelog
- *changelog*: Complete 2.4.0 notes
- *config*: Clarify sdh_method uses subtitle-filter
### Performance Improvements ### Performance Improvements
@@ -451,7 +482,7 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
- Reorganize Planned Features section in README for clarity - Reorganize Planned Features section in README for clarity
- Improve track selection logic in dl.py - Improve track selection logic in dl.py
[unreleased]: https://github.com/unshackle-dl/unshackle/compare/2.3.0..HEAD [3.0.0]: https://github.com/unshackle-dl/unshackle/compare/2.3.0..3.0.0
[2.3.0]: https://github.com/unshackle-dl/unshackle/compare/2.2.0..2.3.0 [2.3.0]: https://github.com/unshackle-dl/unshackle/compare/2.2.0..2.3.0
[2.2.0]: https://github.com/unshackle-dl/unshackle/compare/2.1.0..2.2.0 [2.2.0]: https://github.com/unshackle-dl/unshackle/compare/2.1.0..2.2.0
[2.1.0]: https://github.com/unshackle-dl/unshackle/compare/2.0.0..2.1.0 [2.1.0]: https://github.com/unshackle-dl/unshackle/compare/2.0.0..2.1.0
+6 -5
View File
@@ -1433,20 +1433,21 @@ Control subtitle conversion, SDH (hearing-impaired) stripping behavior, and form
- `sdh_method`: How to strip SDH cues. Default: `auto`. - `sdh_method`: How to strip SDH cues. Default: `auto`.
- `auto`: Try subby for SRT first, then SubtitleEdit, then subtitle-filter. - `auto`: Try subby for SRT first, then SubtitleEdit, then `filter-subs` (the `subtitle-filter` library).
- `subby`: Use subby's SDHStripper (SRT only). - `subby`: Use subby's SDHStripper (SRT only).
- `subtitleedit`: Use SubtitleEdit's RemoveTextForHI when available. - `subtitleedit`: Use SubtitleEdit's RemoveTextForHI when available.
- `filter-subs`: Use the subtitle-filter library directly. - `filter-subs`: Use the `subtitle-filter` library directly.
Note: `filter-subs` is the canonical `sdh_method` config value; it maps to the `subtitle-filter` library.
- `strip_sdh`: Automatically create stripped (non-SDH) versions of SDH subtitles. Default: `true`. - `strip_sdh`: Automatically create stripped (non-SDH) versions of SDH subtitles. Default: `true`.
Set to `false` to disable automatic SDH stripping entirely. When `true`, unshackle will automatically Set to `false` to disable automatic SDH stripping entirely. When `true`, unshackle will automatically
detect SDH subtitles and create clean versions alongside the originals. detect SDH subtitles and create clean versions alongside the originals.
- `convert_before_strip`: Auto-convert VTT/other formats to SRT before using subtitle-filter. Default: `true`. - `convert_before_strip`: Auto-convert VTT/other formats to SRT before using `subtitle-filter`
(via `sdh_method: filter-subs`, including as the final fallback in `sdh_method: auto`). Default: `true`.
This ensures compatibility when subtitle-filter is used as the fallback SDH stripping method, as This ensures compatibility when `subtitle-filter` is used, as it works best with SRT format.
subtitle-filter works best with SRT format.
- `preserve_formatting`: Preserve original subtitle formatting (tags, positioning, styling). Default: `true`. - `preserve_formatting`: Preserve original subtitle formatting (tags, positioning, styling). Default: `true`.
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project] [project]
name = "unshackle" name = "unshackle"
version = "2.4.0" version = "3.0.0"
description = "Modular Movie, TV, and Music Archival Software." description = "Modular Movie, TV, and Music Archival Software."
authors = [{ name = "unshackle team" }] authors = [{ name = "unshackle team" }]
requires-python = ">=3.10,<3.13" requires-python = ">=3.10,<3.13"
+6 -16
View File
@@ -43,6 +43,7 @@ from rich.tree import Tree
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.cdm import CustomRemoteCDM, DecryptLabsRemoteCDM from unshackle.core.cdm import CustomRemoteCDM, DecryptLabsRemoteCDM
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.console import console from unshackle.core.console import console
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY, AnyTrack, context_settings from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY, AnyTrack, context_settings
@@ -1601,9 +1602,7 @@ class dl:
if video_tracks: if video_tracks:
highest_quality = max((track.height for track in video_tracks if track.height), default=0) highest_quality = max((track.height for track in video_tracks if track.height), default=0)
if highest_quality > 0: if highest_quality > 0:
if isinstance(self.cdm, (WidevineCdm, DecryptLabsRemoteCDM)) and not ( if is_widevine_cdm(self.cdm):
isinstance(self.cdm, DecryptLabsRemoteCDM) and self.cdm.is_playready
):
quality_based_cdm = self.get_cdm( quality_based_cdm = self.get_cdm(
self.service, self.profile, drm="widevine", quality=highest_quality self.service, self.profile, drm="widevine", quality=highest_quality
) )
@@ -1612,9 +1611,7 @@ class dl:
f"Pre-selecting Widevine CDM based on highest quality {highest_quality}p across all video tracks" f"Pre-selecting Widevine CDM based on highest quality {highest_quality}p across all video tracks"
) )
self.cdm = quality_based_cdm self.cdm = quality_based_cdm
elif isinstance(self.cdm, (PlayReadyCdm, DecryptLabsRemoteCDM)) and ( elif is_playready_cdm(self.cdm):
isinstance(self.cdm, DecryptLabsRemoteCDM) and self.cdm.is_playready
):
quality_based_cdm = self.get_cdm( quality_based_cdm = self.get_cdm(
self.service, self.profile, drm="playready", quality=highest_quality self.service, self.profile, drm="playready", quality=highest_quality
) )
@@ -1646,10 +1643,7 @@ class dl:
licence=partial( licence=partial(
service.get_playready_license service.get_playready_license
if ( if (
isinstance(self.cdm, PlayReadyCdm) is_playready_cdm(self.cdm)
or (
isinstance(self.cdm, DecryptLabsRemoteCDM) and self.cdm.is_playready
)
) )
and hasattr(service, "get_playready_license") and hasattr(service, "get_playready_license")
else service.get_widevine_license, else service.get_widevine_license,
@@ -2186,9 +2180,7 @@ class dl:
track_quality = track.height track_quality = track.height
if isinstance(drm, Widevine): if isinstance(drm, Widevine):
if not isinstance(self.cdm, (WidevineCdm, DecryptLabsRemoteCDM)) or ( if not is_widevine_cdm(self.cdm):
isinstance(self.cdm, DecryptLabsRemoteCDM) and self.cdm.is_playready
):
widevine_cdm = self.get_cdm(self.service, self.profile, drm="widevine", quality=track_quality) widevine_cdm = self.get_cdm(self.service, self.profile, drm="widevine", quality=track_quality)
if widevine_cdm: if widevine_cdm:
if track_quality: if track_quality:
@@ -2198,9 +2190,7 @@ class dl:
self.cdm = widevine_cdm self.cdm = widevine_cdm
elif isinstance(drm, PlayReady): elif isinstance(drm, PlayReady):
if not isinstance(self.cdm, (PlayReadyCdm, DecryptLabsRemoteCDM)) or ( if not is_playready_cdm(self.cdm):
isinstance(self.cdm, DecryptLabsRemoteCDM) and not self.cdm.is_playready
):
playready_cdm = self.get_cdm(self.service, self.profile, drm="playready", quality=track_quality) playready_cdm = self.get_cdm(self.service, self.profile, drm="playready", quality=track_quality)
if playready_cdm: if playready_cdm:
if track_quality: if track_quality:
+1 -1
View File
@@ -211,7 +211,7 @@ def serve(
"devices": prd_devices, "devices": prd_devices,
"users": { "users": {
user_key: { user_key: {
"devices": user_cfg.get("playready_devices", prd_device_names), "devices": user_cfg.get("playready_devices", []),
"username": user_cfg.get("username", "user"), "username": user_cfg.get("username", "user"),
} }
for user_key, user_cfg in serve_config["users"].items() for user_key, user_cfg in serve_config["users"].items()
+1 -1
View File
@@ -1 +1 @@
__version__ = "2.4.0" __version__ = "3.0.0"
+2 -1
View File
@@ -1,5 +1,6 @@
import atexit import atexit
import logging import logging
from datetime import datetime
import click import click
import urllib3 import urllib3
@@ -58,7 +59,7 @@ def main(version: bool, debug: bool) -> None:
r" ▀▀▀ ▀▀ █▪ ▀▀▀▀ ▀▀▀ · ▀ ▀ ·▀▀▀ ·▀ ▀.▀▀▀ ▀▀▀ ", r" ▀▀▀ ▀▀ █▪ ▀▀▀▀ ▀▀▀ · ▀ ▀ ·▀▀▀ ·▀ ▀.▀▀▀ ▀▀▀ ",
style="ascii.art", style="ascii.art",
), ),
f"v [repr.number]{__version__}[/] - © 2025 - github.com/unshackle-dl/unshackle", f"v [repr.number]{__version__}[/] - © 2025-{datetime.now().year} - github.com/unshackle-dl/unshackle",
), ),
(1, 11, 1, 10), (1, 11, 1, 10),
expand=True, expand=True,
+18 -1
View File
@@ -207,6 +207,7 @@ def serialize_drm(drm_list) -> Optional[List[Dict[str, Any]]]:
# Get PSSH - handle both Widevine and PlayReady # Get PSSH - handle both Widevine and PlayReady
if hasattr(drm, "_pssh") and drm._pssh: if hasattr(drm, "_pssh") and drm._pssh:
pssh_obj = None
try: try:
pssh_obj = drm._pssh pssh_obj = drm._pssh
# Try to get base64 representation # Try to get base64 representation
@@ -225,8 +226,24 @@ def serialize_drm(drm_list) -> Optional[List[Dict[str, Any]]]:
# Check if it's already base64-like or an object repr # Check if it's already base64-like or an object repr
if not pssh_str.startswith("<"): if not pssh_str.startswith("<"):
drm_info["pssh"] = pssh_str drm_info["pssh"] = pssh_str
except (ValueError, TypeError, KeyError):
# Some PSSH implementations can fail to parse/serialize; log and continue.
pssh_type = type(pssh_obj).__name__ if pssh_obj is not None else None
log.warning(
"Failed to extract/serialize PSSH for DRM type=%s pssh_type=%s",
drm_class,
pssh_type,
exc_info=True,
)
except Exception: except Exception:
pass # Don't silently swallow unexpected failures; make them visible and propagate.
pssh_type = type(pssh_obj).__name__ if pssh_obj is not None else None
log.exception(
"Unexpected error while extracting/serializing PSSH for DRM type=%s pssh_type=%s",
drm_class,
pssh_type,
)
raise
# Get KIDs # Get KIDs
if hasattr(drm, "kids") and drm.kids: if hasattr(drm, "kids") and drm.kids:
+56 -4
View File
@@ -1,5 +1,57 @@
from .custom_remote_cdm import CustomRemoteCDM """
from .decrypt_labs_remote_cdm import DecryptLabsRemoteCDM CDM helpers and implementations.
from .monalisa import MonaLisaCDM
__all__ = ["DecryptLabsRemoteCDM", "CustomRemoteCDM", "MonaLisaCDM"] Keep this module import-light: downstream code frequently imports helpers from
`unshackle.core.cdm.detect`, which requires importing this package first.
Some CDM implementations pull in optional/heavy dependencies, so we lazily
import them via `__getattr__` (PEP 562).
"""
from __future__ import annotations
from typing import Any
__all__ = [
"DecryptLabsRemoteCDM",
"CustomRemoteCDM",
"MonaLisaCDM",
"is_remote_cdm",
"is_local_cdm",
"cdm_location",
"is_playready_cdm",
"is_widevine_cdm",
]
def __getattr__(name: str) -> Any:
if name == "DecryptLabsRemoteCDM":
from .decrypt_labs_remote_cdm import DecryptLabsRemoteCDM
return DecryptLabsRemoteCDM
if name == "CustomRemoteCDM":
from .custom_remote_cdm import CustomRemoteCDM
return CustomRemoteCDM
if name == "MonaLisaCDM":
from .monalisa import MonaLisaCDM
return MonaLisaCDM
if name in {
"is_remote_cdm",
"is_local_cdm",
"cdm_location",
"is_playready_cdm",
"is_widevine_cdm",
}:
from .detect import cdm_location, is_local_cdm, is_playready_cdm, is_remote_cdm, is_widevine_cdm
return {
"is_remote_cdm": is_remote_cdm,
"is_local_cdm": is_local_cdm,
"cdm_location": cdm_location,
"is_playready_cdm": is_playready_cdm,
"is_widevine_cdm": is_widevine_cdm,
}[name]
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+187
View File
@@ -0,0 +1,187 @@
from __future__ import annotations
from typing import Any
def is_remote_cdm(cdm: Any) -> bool:
"""
Return True if the CDM instance is backed by a remote/service CDM.
This is useful for service logic that needs to know whether the CDM runs
locally (in-process) vs over HTTP/RPC (remote).
"""
if cdm is None:
return False
if hasattr(cdm, "is_remote_cdm"):
try:
return bool(getattr(cdm, "is_remote_cdm"))
except Exception:
pass
try:
from pyplayready.remote.remotecdm import RemoteCdm as PlayReadyRemoteCdm
except Exception:
PlayReadyRemoteCdm = None
if PlayReadyRemoteCdm is not None:
try:
if isinstance(cdm, PlayReadyRemoteCdm):
return True
except Exception:
pass
try:
from pywidevine.remotecdm import RemoteCdm as WidevineRemoteCdm
except Exception:
WidevineRemoteCdm = None
if WidevineRemoteCdm is not None:
try:
if isinstance(cdm, WidevineRemoteCdm):
return True
except Exception:
pass
cls = getattr(cdm, "__class__", None)
mod = getattr(cls, "__module__", "") or ""
name = getattr(cls, "__name__", "") or ""
if mod == "unshackle.core.cdm.decrypt_labs_remote_cdm" and name == "DecryptLabsRemoteCDM":
return True
if mod == "unshackle.core.cdm.custom_remote_cdm" and name == "CustomRemoteCDM":
return True
if mod.startswith("pyplayready.remote") or mod.startswith("pywidevine.remote"):
return True
if "remote" in mod.lower() and name.lower().endswith("cdm"):
return True
if name.lower().endswith("remotecdm"):
return True
return False
def is_local_cdm(cdm: Any) -> bool:
"""
Return True if the CDM instance is local/in-process.
Unknown CDM types return False (use `cdm_location()` if you need 3-state).
"""
if cdm is None:
return False
if is_remote_cdm(cdm):
return False
if is_playready_cdm(cdm) or is_widevine_cdm(cdm):
return True
cls = getattr(cdm, "__class__", None)
mod = getattr(cls, "__module__", "") or ""
name = getattr(cls, "__name__", "") or ""
if mod == "unshackle.core.cdm.monalisa.monalisa_cdm" and name == "MonaLisaCDM":
return True
return False
def cdm_location(cdm: Any) -> str:
"""
Return one of: "local", "remote", "unknown".
"""
if is_remote_cdm(cdm):
return "remote"
if is_local_cdm(cdm):
return "local"
return "unknown"
def is_playready_cdm(cdm: Any) -> bool:
"""
Return True if the given CDM should be treated as PlayReady.
This intentionally supports both:
- Local PlayReady CDMs (pyplayready.cdm.Cdm)
- Remote/wrapper CDMs (e.g. DecryptLabsRemoteCDM) that expose `is_playready`
"""
if cdm is None:
return False
if hasattr(cdm, "is_playready"):
try:
return bool(getattr(cdm, "is_playready"))
except Exception:
pass
try:
from pyplayready.cdm import Cdm as PlayReadyCdm
except Exception:
PlayReadyCdm = None
if PlayReadyCdm is not None:
try:
return isinstance(cdm, PlayReadyCdm)
except Exception:
pass
try:
from pyplayready.remote.remotecdm import RemoteCdm as PlayReadyRemoteCdm
except Exception:
PlayReadyRemoteCdm = None
if PlayReadyRemoteCdm is not None:
try:
return isinstance(cdm, PlayReadyRemoteCdm)
except Exception:
pass
mod = getattr(getattr(cdm, "__class__", None), "__module__", "") or ""
return "pyplayready" in mod
def is_widevine_cdm(cdm: Any) -> bool:
"""
Return True if the given CDM should be treated as Widevine.
Note: for remote/wrapper CDMs that expose `is_playready`, Widevine is treated
as the logical opposite.
"""
if cdm is None:
return False
if hasattr(cdm, "is_playready"):
try:
return not bool(getattr(cdm, "is_playready"))
except Exception:
pass
try:
from pywidevine.cdm import Cdm as WidevineCdm
except Exception:
WidevineCdm = None
if WidevineCdm is not None:
try:
return isinstance(cdm, WidevineCdm)
except Exception:
pass
try:
from pywidevine.remotecdm import RemoteCdm as WidevineRemoteCdm
except Exception:
WidevineRemoteCdm = None
if WidevineRemoteCdm is not None:
try:
return isinstance(cdm, WidevineRemoteCdm)
except Exception:
pass
mod = getattr(getattr(cdm, "__class__", None), "__module__", "") or ""
return "pywidevine" in mod
+64 -18
View File
@@ -7,8 +7,11 @@ a WebAssembly module that runs locally via wasmtime.
import base64 import base64
import ctypes import ctypes
import hashlib
import json import json
import logging
import re import re
import sys
import uuid import uuid
from pathlib import Path from pathlib import Path
from typing import Dict, Optional, Union from typing import Dict, Optional, Union
@@ -17,6 +20,8 @@ import wasmtime
from unshackle.core import binaries from unshackle.core import binaries
logger = logging.getLogger(__name__)
class MonaLisaCDM: class MonaLisaCDM:
""" """
@@ -128,10 +133,27 @@ class MonaLisaCDM:
} }
self.exports["___wasm_call_ctors"](self.store) self.exports["___wasm_call_ctors"](self.store)
self.ctx = self.exports["_monalisa_context_alloc"](self.store) ctx = self.exports["_monalisa_context_alloc"](self.store)
self.ctx = ctx
# _monalisa_context_alloc is expected to return a positive pointer/handle.
# Treat 0/negative/non-int-like values as allocation failure.
try:
ctx_int = int(ctx)
except Exception:
ctx_int = None
if ctx_int is None or ctx_int <= 0:
# Ensure we don't leave a partially-initialized instance around.
self.close()
raise RuntimeError(f"Failed to allocate MonaLisa context (ctx={ctx!r})")
return 1 return 1
except Exception as e: except Exception as e:
raise RuntimeError(f"Failed to initialize session: {e}") # Clean up partial state (e.g., store/memory/instance) before propagating failure.
self.close()
if isinstance(e, RuntimeError):
raise
raise RuntimeError(f"Failed to initialize session: {e}") from e
def close(self, session_id: int = 1) -> None: def close(self, session_id: int = 1) -> None:
""" """
@@ -188,7 +210,9 @@ class MonaLisaCDM:
# Extract DCID from license to generate KID # Extract DCID from license to generate KID
try: try:
decoded = base64.b64decode(license_b64).decode("ascii", errors="ignore") decoded = base64.b64decode(license_b64).decode("ascii", errors="ignore")
except Exception: except Exception as e:
# Avoid logging raw license content; log only safe metadata.
logger.exception("Failed to base64-decode MonaLisa license (len=%s): %s", len(license_b64), e)
decoded = "" decoded = ""
m = re.search( m = re.search(
@@ -198,7 +222,14 @@ class MonaLisaCDM:
if m: if m:
kid_bytes = uuid.uuid5(uuid.NAMESPACE_DNS, m.group()).bytes kid_bytes = uuid.uuid5(uuid.NAMESPACE_DNS, m.group()).bytes
else: else:
kid_bytes = uuid.UUID(int=0).bytes # No DCID in the license: derive a deterministic per-license KID to avoid collisions.
try:
license_raw = base64.b64decode(license_b64)
except Exception:
license_raw = license_b64.encode("utf-8", errors="replace")
license_hash = hashlib.sha256(license_raw).hexdigest()
kid_bytes = uuid.uuid5(uuid.NAMESPACE_DNS, f"monalisa:license:{license_hash}").bytes
return {"kid": kid_bytes.hex(), "key": key_bytes.hex(), "type": "CONTENT"} return {"kid": kid_bytes.hex(), "key": key_bytes.hex(), "type": "CONTENT"}
@@ -221,21 +252,29 @@ class MonaLisaCDM:
stack = 0 stack = 0
converted_args = [] converted_args = []
for arg in args: try:
if isinstance(arg, str): for arg in args:
if stack == 0: if isinstance(arg, str):
stack = self.exports["stackSave"](self.store) if stack == 0:
max_length = (len(arg) << 2) + 1 stack = self.exports["stackSave"](self.store)
ptr = self.exports["stackAlloc"](self.store, max_length) max_length = (len(arg) << 2) + 1
self._string_to_utf8(arg, ptr, max_length) ptr = self.exports["stackAlloc"](self.store, max_length)
converted_args.append(ptr) self._string_to_utf8(arg, ptr, max_length)
else: converted_args.append(ptr)
converted_args.append(arg) else:
converted_args.append(arg)
result = self.exports[func_name](self.store, *converted_args) result = self.exports[func_name](self.store, *converted_args)
finally:
if stack != 0: # stackAlloc pointers live on the WASM stack; always restore even if the call throws.
self.exports["stackRestore"](self.store, stack) if stack != 0:
exc = sys.exc_info()[1]
try:
self.exports["stackRestore"](self.store, stack)
except Exception:
# If we're already failing, don't mask the original exception.
if exc is None:
raise
if return_type is bool: if return_type is bool:
return bool(result) return bool(result)
@@ -243,6 +282,13 @@ class MonaLisaCDM:
def _write_i32(self, addr: int, value: int) -> None: def _write_i32(self, addr: int, value: int) -> None:
"""Write a 32-bit integer to WASM memory.""" """Write a 32-bit integer to WASM memory."""
if addr % 4 != 0:
raise ValueError(f"Unaligned i32 write: addr={addr} (must be 4-byte aligned)")
data_len = self.memory.data_len(self.store)
if addr < 0 or addr + 4 > data_len:
raise IndexError(f"i32 write out of bounds: addr={addr}, mem_len={data_len}")
data = self.memory.data_ptr(self.store) data = self.memory.data_ptr(self.store)
mem_ptr = ctypes.cast(data, ctypes.POINTER(ctypes.c_int32)) mem_ptr = ctypes.cast(data, ctypes.POINTER(ctypes.c_int32))
mem_ptr[addr >> 2] = value mem_ptr[addr >> 2] = value
+1 -7
View File
@@ -234,11 +234,7 @@ class MonaLisa:
raise MonaLisa.Exceptions.DecryptionFailed(f"Segment file does not exist: {segment_path}") raise MonaLisa.Exceptions.DecryptionFailed(f"Segment file does not exist: {segment_path}")
# Stage 1: ML-Worker decryption # Stage 1: ML-Worker decryption
# Do not pass secrets via argv (visible in process listings/logs). cmd = [str(worker_path), str(self._key), str(bbts_path), str(ents_path)]
# ML-Worker supports receiving the key out-of-band; we provide it via env + stdin.
cmd = [str(worker_path), "-", str(bbts_path), str(ents_path)]
worker_env = os.environ.copy()
worker_env["WORKER_KEY"] = self._key
startupinfo = None startupinfo = None
if sys.platform == "win32": if sys.platform == "win32":
@@ -251,8 +247,6 @@ class MonaLisa:
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, text=True,
input=self._key,
env=worker_env,
startupinfo=startupinfo, startupinfo=startupinfo,
timeout=worker_timeout_s, timeout=worker_timeout_s,
) )
+2 -2
View File
@@ -19,12 +19,12 @@ import requests
from curl_cffi.requests import Session as CurlSession from curl_cffi.requests import Session as CurlSession
from langcodes import Language, tag_is_valid from langcodes import Language, tag_is_valid
from lxml.etree import Element, ElementTree from lxml.etree import Element, ElementTree
from pyplayready.cdm import Cdm as PlayReadyCdm
from pyplayready.system.pssh import PSSH as PR_PSSH from pyplayready.system.pssh import PSSH as PR_PSSH
from pywidevine.cdm import Cdm as WidevineCdm from pywidevine.cdm import Cdm as WidevineCdm
from pywidevine.pssh import PSSH from pywidevine.pssh import PSSH
from requests import Session from requests import Session
from unshackle.core.cdm.detect import is_playready_cdm
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.downloaders import requests as requests_downloader from unshackle.core.downloaders import requests as requests_downloader
from unshackle.core.drm import DRM_T, PlayReady, Widevine from unshackle.core.drm import DRM_T, PlayReady, Widevine
@@ -477,7 +477,7 @@ class DASH:
track.data["dash"]["segment_durations"] = segment_durations track.data["dash"]["segment_durations"] = segment_durations
if not track.drm and init_data and isinstance(track, (Video, Audio)): if not track.drm and init_data and isinstance(track, (Video, Audio)):
prefers_playready = isinstance(cdm, PlayReadyCdm) or (hasattr(cdm, "is_playready") and cdm.is_playready) prefers_playready = is_playready_cdm(cdm)
if prefers_playready: if prefers_playready:
try: try:
track.drm = [PlayReady.from_init_data(init_data)] track.drm = [PlayReady.from_init_data(init_data)]
+11 -12
View File
@@ -28,6 +28,7 @@ from pywidevine.pssh import PSSH as WV_PSSH
from requests import Session from requests import Session
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.downloaders import requests as requests_downloader from unshackle.core.downloaders import requests as requests_downloader
from unshackle.core.drm import DRM_T, ClearKey, MonaLisa, PlayReady, Widevine from unshackle.core.drm import DRM_T, ClearKey, MonaLisa, PlayReady, Widevine
@@ -115,9 +116,14 @@ class HLS:
for playlist in self.manifest.playlists: for playlist in self.manifest.playlists:
audio_group = playlist.stream_info.audio audio_group = playlist.stream_info.audio
if audio_group: audio_codec: Optional[Audio.Codec] = None
audio_codec = Audio.Codec.from_codecs(playlist.stream_info.codecs) if audio_group and playlist.stream_info.codecs:
audio_codecs_by_group_id[audio_group] = audio_codec try:
audio_codec = Audio.Codec.from_codecs(playlist.stream_info.codecs)
except ValueError:
audio_codec = None
if audio_codec:
audio_codecs_by_group_id[audio_group] = audio_codec
try: try:
# TODO: Any better way to figure out the primary track type? # TODO: Any better way to figure out the primary track type?
@@ -610,8 +616,6 @@ class HLS:
discon_i += 1 discon_i += 1
range_offset = 0 # TODO: Should this be reset or not? range_offset = 0 # TODO: Should this be reset or not?
map_data = None map_data = None
if encryption_data:
encryption_data = (encryption_data[0], encryption_data[1])
if segment.init_section and (not map_data or segment.init_section != map_data[0]): if segment.init_section and (not map_data or segment.init_section != map_data[0]):
if segment.init_section.byterange: if segment.init_section.byterange:
@@ -914,15 +918,10 @@ class HLS:
""" """
playready_urn = f"urn:uuid:{PR_PSSH.SYSTEM_ID}" playready_urn = f"urn:uuid:{PR_PSSH.SYSTEM_ID}"
playready_keyformats = {playready_urn, "com.microsoft.playready"} playready_keyformats = {playready_urn, "com.microsoft.playready"}
if isinstance(cdm, WidevineCdm): if is_widevine_cdm(cdm):
return [k for k in keys if k.keyformat and k.keyformat.lower() == WidevineCdm.urn] return [k for k in keys if k.keyformat and k.keyformat.lower() == WidevineCdm.urn]
elif isinstance(cdm, PlayReadyCdm): elif is_playready_cdm(cdm):
return [k for k in keys if k.keyformat and k.keyformat.lower() in playready_keyformats] return [k for k in keys if k.keyformat and k.keyformat.lower() in playready_keyformats]
elif hasattr(cdm, "is_playready"):
if cdm.is_playready:
return [k for k in keys if k.keyformat and k.keyformat.lower() in playready_keyformats]
else:
return [k for k in keys if k.keyformat and k.keyformat.lower() == WidevineCdm.urn]
return keys return keys
@staticmethod @staticmethod
+10 -5
View File
@@ -142,12 +142,17 @@ class SurfsharkVPN(Proxy):
) )
# Get connection names from filtered servers # Get connection names from filtered servers
connection_names = [x["connectionName"] for x in servers] if not servers:
raise ValueError(f"Could not get random server for country '{country_id}': no servers found.")
try: # Only include servers that actually have a connection name to avoid KeyError.
return random.choice(connection_names) connection_names = [x["connectionName"] for x in servers if "connectionName" in x]
except (IndexError, KeyError): if not connection_names:
raise ValueError(f"Could not get random server for country '{country_id}'.") raise ValueError(
f"Could not get random server for country '{country_id}': no servers with connectionName found."
)
return random.choice(connection_names)
@staticmethod @staticmethod
def get_countries() -> list[dict]: def get_countries() -> list[dict]:
+1 -1
View File
@@ -62,7 +62,7 @@ class WindscribeVPN(Proxy):
server_map_key = f"{query}:{city}" if city else query server_map_key = f"{query}:{city}" if city else query
if server_map_key in self.server_map: if server_map_key in self.server_map:
hostname = self.server_map[server_map_key] hostname = self.server_map[server_map_key]
elif query in self.server_map and not city: elif query in self.server_map:
hostname = self.server_map[query] hostname = self.server_map[query]
else: else:
server_match = re.match(r"^([a-z]{2})(\d+)$", query) server_match = re.match(r"^([a-z]{2})(\d+)$", query)
+55 -6
View File
@@ -5,7 +5,7 @@ from collections.abc import Generator
from http.cookiejar import CookieJar from http.cookiejar import CookieJar
from pathlib import Path from pathlib import Path
from typing import Optional, Union from typing import Optional, Union
from urllib.parse import urlparse from urllib.parse import urlparse, urlunparse
import click import click
import m3u8 import m3u8
@@ -27,6 +27,45 @@ from unshackle.core.tracks import Chapters, Tracks
from unshackle.core.utilities import get_cached_ip_info, get_ip_info from unshackle.core.utilities import get_cached_ip_info, get_ip_info
def sanitize_proxy_for_log(uri: Optional[str]) -> Optional[str]:
"""
Sanitize a proxy URI for logs by redacting any embedded userinfo (username/password).
Examples:
- http://user:pass@host:8080 -> http://REDACTED@host:8080
- socks5h://user@host:1080 -> socks5h://REDACTED@host:1080
"""
if uri is None:
return None
if not isinstance(uri, str):
return str(uri)
if not uri:
return uri
try:
parsed = urlparse(uri)
# Handle schemeless proxies like "user:pass@host:port"
if not parsed.scheme and not parsed.netloc and "@" in uri and "://" not in uri:
# Parse as netloc using a dummy scheme, then strip scheme back out.
dummy = urlparse(f"http://{uri}")
netloc = dummy.netloc
if "@" in netloc:
netloc = f"REDACTED@{netloc.split('@', 1)[1]}"
# urlparse("http://...") sets path to "" for typical netloc-only strings; keep it just in case.
return f"{netloc}{dummy.path}"
netloc = parsed.netloc
if "@" in netloc:
netloc = f"REDACTED@{netloc.split('@', 1)[1]}"
return urlunparse(parsed._replace(netloc=netloc))
except Exception:
if "@" in uri:
return f"REDACTED@{uri.split('@', 1)[1]}"
return uri
class Service(metaclass=ABCMeta): class Service(metaclass=ABCMeta):
"""The Service Base Class.""" """The Service Base Class."""
@@ -75,7 +114,9 @@ class Service(metaclass=ABCMeta):
# Check if there's a mapping for this query # Check if there's a mapping for this query
mapped_value = proxy_map.get(full_proxy_key) mapped_value = proxy_map.get(full_proxy_key)
if mapped_value: if mapped_value:
self.log.info(f"Found service-specific proxy mapping: {full_proxy_key} -> {mapped_value}") self.log.info(
f"Found service-specific proxy mapping: {full_proxy_key} -> {sanitize_proxy_for_log(mapped_value)}"
)
# Query the proxy provider with the mapped value # Query the proxy provider with the mapped value
if proxy_provider_name: if proxy_provider_name:
# Specific provider requested # Specific provider requested
@@ -87,9 +128,13 @@ class Service(metaclass=ABCMeta):
mapped_proxy_uri = proxy_provider.get_proxy(mapped_value) mapped_proxy_uri = proxy_provider.get_proxy(mapped_value)
if mapped_proxy_uri: if mapped_proxy_uri:
proxy = mapped_proxy_uri proxy = mapped_proxy_uri
self.log.info(f"Using mapped proxy from {proxy_provider.__class__.__name__}: {proxy}") self.log.info(
f"Using mapped proxy from {proxy_provider.__class__.__name__}: {sanitize_proxy_for_log(proxy)}"
)
else: else:
self.log.warning(f"Failed to get proxy for mapped value '{mapped_value}', using default") self.log.warning(
f"Failed to get proxy for mapped value '{sanitize_proxy_for_log(mapped_value)}', using default"
)
else: else:
self.log.warning(f"Proxy provider '{proxy_provider_name}' not found, using default proxy") self.log.warning(f"Proxy provider '{proxy_provider_name}' not found, using default proxy")
else: else:
@@ -98,10 +143,14 @@ class Service(metaclass=ABCMeta):
mapped_proxy_uri = proxy_provider.get_proxy(mapped_value) mapped_proxy_uri = proxy_provider.get_proxy(mapped_value)
if mapped_proxy_uri: if mapped_proxy_uri:
proxy = mapped_proxy_uri proxy = mapped_proxy_uri
self.log.info(f"Using mapped proxy from {proxy_provider.__class__.__name__}: {proxy}") self.log.info(
f"Using mapped proxy from {proxy_provider.__class__.__name__}: {sanitize_proxy_for_log(proxy)}"
)
break break
else: else:
self.log.warning(f"No provider could resolve mapped value '{mapped_value}', using default") self.log.warning(
f"No provider could resolve mapped value '{sanitize_proxy_for_log(mapped_value)}', using default"
)
if not proxy: if not proxy:
# don't override the explicit proxy set by the user, even if they may be geoblocked # don't override the explicit proxy set by the user, even if they may be geoblocked
+10 -4
View File
@@ -65,9 +65,13 @@ class Attachment:
path = None path = None
else: else:
try: try:
session = session or requests.Session() if session is None:
response = session.get(url, stream=True) with requests.Session() as session:
response.raise_for_status() response = session.get(url, stream=True)
response.raise_for_status()
else:
response = session.get(url, stream=True)
response.raise_for_status()
config.directories.temp.mkdir(parents=True, exist_ok=True) config.directories.temp.mkdir(parents=True, exist_ok=True)
download_path.parent.mkdir(parents=True, exist_ok=True) download_path.parent.mkdir(parents=True, exist_ok=True)
@@ -80,7 +84,9 @@ class Attachment:
raise ValueError(f"Failed to download attachment from URL: {e}") raise ValueError(f"Failed to download attachment from URL: {e}")
if path is not None and not isinstance(path, (str, Path)): if path is not None and not isinstance(path, (str, Path)):
raise ValueError("The attachment path must be provided.") raise ValueError(
f"Invalid attachment path type: expected str or Path, got {type(path).__name__}."
)
if path is not None: if path is not None:
path = Path(path) path = Path(path)
+4 -14
View File
@@ -15,11 +15,10 @@ from zlib import crc32
from curl_cffi.requests import Session as CurlSession from curl_cffi.requests import Session as CurlSession
from langcodes import Language from langcodes import Language
from pyplayready.cdm import Cdm as PlayReadyCdm
from pywidevine.cdm import Cdm as WidevineCdm
from requests import Session from requests import Session
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY
from unshackle.core.downloaders import aria2c, curl_impersonate, n_m3u8dl_re, requests from unshackle.core.downloaders import aria2c, curl_impersonate, n_m3u8dl_re, requests
@@ -297,7 +296,7 @@ class Track:
if not self.drm and track_type in ("Video", "Audio"): if not self.drm and track_type in ("Video", "Audio"):
# the service might not have explicitly defined the `drm` property # the service might not have explicitly defined the `drm` property
# try find DRM information from the init data of URL based on CDM type # try find DRM information from the init data of URL based on CDM type
if isinstance(cdm, PlayReadyCdm): if is_playready_cdm(cdm):
try: try:
self.drm = [PlayReady.from_track(self, session)] self.drm = [PlayReady.from_track(self, session)]
except PlayReady.Exceptions.PSSHNotFound: except PlayReady.Exceptions.PSSHNotFound:
@@ -451,23 +450,14 @@ class Track:
if not self.drm: if not self.drm:
return None return None
if isinstance(cdm, WidevineCdm): if is_widevine_cdm(cdm):
for drm in self.drm: for drm in self.drm:
if isinstance(drm, Widevine): if isinstance(drm, Widevine):
return drm return drm
elif isinstance(cdm, PlayReadyCdm): elif is_playready_cdm(cdm):
for drm in self.drm: for drm in self.drm:
if isinstance(drm, PlayReady): if isinstance(drm, PlayReady):
return drm return drm
elif hasattr(cdm, "is_playready"):
if cdm.is_playready:
for drm in self.drm:
if isinstance(drm, PlayReady):
return drm
else:
for drm in self.drm:
if isinstance(drm, Widevine):
return drm
return self.drm[0] return self.drm[0]
+6 -4
View File
@@ -221,13 +221,15 @@ class Tracks:
self.videos.sort(key=lambda x: not is_close_match(language, [x.language])) self.videos.sort(key=lambda x: not is_close_match(language, [x.language]))
def sort_audio(self, by_language: Optional[Sequence[Union[str, Language]]] = None) -> None: def sort_audio(self, by_language: Optional[Sequence[Union[str, Language]]] = None) -> None:
"""Sort audio tracks by bitrate, descriptive, and optionally language.""" """Sort audio tracks by bitrate, Atmos, descriptive, and optionally language."""
if not self.audio: if not self.audio:
return return
# descriptive # bitrate (highest first)
self.audio.sort(key=lambda x: x.descriptive)
# bitrate (within each descriptive group)
self.audio.sort(key=lambda x: float(x.bitrate or 0.0), reverse=True) self.audio.sort(key=lambda x: float(x.bitrate or 0.0), reverse=True)
# Atmos tracks first (prioritize over higher bitrate non-Atmos)
self.audio.sort(key=lambda x: not x.atmos)
# descriptive tracks last
self.audio.sort(key=lambda x: x.descriptive)
# language # language
for language in reversed(by_language or []): for language in reversed(by_language or []):
if str(language) in ("all", "best"): if str(language) in ("all", "best"):
Generated
+1 -1
View File
@@ -1627,7 +1627,7 @@ wheels = [
[[package]] [[package]]
name = "unshackle" name = "unshackle"
version = "2.4.0" version = "3.0.0"
source = { editable = "." } source = { editable = "." }
dependencies = [ dependencies = [
{ name = "aiohttp" }, { name = "aiohttp" },