Add support for obfuscating parameters by encrypting & support ip, exp time restriction for generated url
Browse filesFiles changed (7)
29 unmodified lines30313233343536114 unmodified lines15115215315415515615715815916056 unmodified lines21721821922022122229 unmodified lines- Retrieve public IP address of the MediaFlow Proxy server for use with Debrid services- Support for HTTP/HTTPS/SOCKS5 proxy forwarding- Protect against unauthorized access and network bandwidth abuses- Support for play expired or self-signed SSL certificates server streams## Configuration114 unmodified lines### Examples#### Proxy HTTPS Stream```bashmpv "http://localhost:8888/proxy/stream?d=https://jsoncompare.org/LearningContainer/SampleFiles/Video/MP4/sample-mp4-file.mp4&api_password=your_password"```#### Proxy HTTPS self-signed certificate Stream56 unmodified linesvlc "http://127.0.0.1:8888/proxy/mpd/manifest?key_id=nrQFDeRLSAKTLifXUIPiZg&key=FmY0xnWCPCNaSpRG-tUuTQ&api_password=dedsec&d=https%3A%2F%2Fmedia.axprod.net%2FTestVectors%2Fv7-MultiDRM-SingleKey%2FManifest_1080p_ClearKey.mpd"```### Using MediaFlow Proxy with Debrid Services and Stremio AddonsMediaFlow Proxy can be particularly useful when working with Debrid services (like Real-Debrid, AllDebrid) and Stremio addons. The `/proxy/ip` endpoint allows you to retrieve the public IP address of the MediaFlow Proxy server, which is crucial for routing Debrid streams correctly.29 unmodified lines30313233343536373839114 unmodified lines15415515615715815916016116216356 unmodified lines22022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625729 unmodified lines- Retrieve public IP address of the MediaFlow Proxy server for use with Debrid services- Support for HTTP/HTTPS/SOCKS5 proxy forwarding- Protect against unauthorized access and network bandwidth abuses- Support for play expired or self-signed SSL certificates server streams `(verify_ssl=false)` default is `false`- Flexible request proxy usage control per request `(use_request_proxy=true/false)` default is `true`- Obfuscating endpoint parameters by encrypting them to hide sensitive information from third-party.- Optional IP-based access control restriction & expiration for encrypted URLs to prevent unauthorized access## Configuration114 unmodified lines### Examples#### Proxy HTTPS Stream (without using configured proxy)```bashmpv "http://localhost:8888/proxy/stream?d=https://jsoncompare.org/LearningContainer/SampleFiles/Video/MP4/sample-mp4-file.mp4&api_password=your_password&use_request_proxy=false"```#### Proxy HTTPS self-signed certificate Stream56 unmodified linesvlc "http://127.0.0.1:8888/proxy/mpd/manifest?key_id=nrQFDeRLSAKTLifXUIPiZg&key=FmY0xnWCPCNaSpRG-tUuTQ&api_password=dedsec&d=https%3A%2F%2Fmedia.axprod.net%2FTestVectors%2Fv7-MultiDRM-SingleKey%2FManifest_1080p_ClearKey.mpd"```### Generating Encrypted URLsTo generate an encrypted URL with optional IP restriction and expiration, Use the `/generate_encrypted_or_encoded_url` endpoint via swagger UI or programmatically as shown below:```pythonimport requestsurl = "http://localhost:8888/generate_encrypted_or_encoded_url"data = {"mediaflow_proxy_url": "http://localhost:8888","endpoint": "/proxy/mpd/manifest","destination_url": "https://media.axprod.net/TestVectors/v7-MultiDRM-SingleKey/Manifest_1080p_ClearKey.mpd","query_params": {"key_id": "nrQFDeRLSAKTLifXUIPiZg","key": "FmY0xnWCPCNaSpRG-tUuTQ"},"request_headers": {"referer": "https://media.axprod.net/","origin": "https://media.axprod.net",},"expiration": 3600, # URL will expire in 1 hour"ip": "123.123.123.123", # Optional: Restrict access to this IP"api_password": "your_password"}response = requests.post(url, json=data)encrypted_url = response.json()["encoded_url"]print(encrypted_url)```You can then use the `encoded_url` in your player or application to access the media stream.### Using MediaFlow Proxy with Debrid Services and Stremio AddonsMediaFlow Proxy can be particularly useful when working with Debrid services (like Real-Debrid, AllDebrid) and Stremio addons. The `/proxy/ip` endpoint allows you to retrieve the public IP address of the MediaFlow Proxy server, which is crucial for routing Debrid streams correctly.
8 unmodified lines910111213146 unmodified lines21222324252623 unmodified lines5051525354558 unmodified linesfrom mediaflow_proxy.configs import settingsfrom mediaflow_proxy.routes import proxy_routerlogging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")app = FastAPI()6 unmodified linesallow_methods=["*"],allow_headers=["*"],)async def verify_api_key(api_key: str = Security(api_password_query), api_key_alt: str = Security(api_password_header)):23 unmodified linesreturn RedirectResponse(url="/logo.png")app.include_router(proxy_router, prefix="/proxy", tags=["proxy"], dependencies=[Depends(verify_api_key)])static_path = resources.files("mediaflow_proxy").joinpath("static")8 unmodified lines910111213141516176 unmodified lines2425262728293023 unmodified lines545556575859606162636465666768697071727374757677788 unmodified linesfrom mediaflow_proxy.configs import settingsfrom mediaflow_proxy.routes import proxy_routerfrom mediaflow_proxy.schemas import GenerateUrlRequestfrom mediaflow_proxy.utils.crypto_utils import EncryptionHandler, EncryptionMiddlewarefrom mediaflow_proxy.utils.http_utils import encode_mediaflow_proxy_urllogging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")app = FastAPI()6 unmodified linesallow_methods=["*"],allow_headers=["*"],)app.add_middleware(EncryptionMiddleware)async def verify_api_key(api_key: str = Security(api_password_query), api_key_alt: str = Security(api_password_header)):23 unmodified linesreturn RedirectResponse(url="/logo.png")@app.post("/generate_encrypted_or_encoded_url")async def generate_encrypted_or_encoded_url(request: GenerateUrlRequest):if "api_password" not in request.query_params:request.query_params["api_password"] = request.api_passwordencoded_url = encode_mediaflow_proxy_url(request.mediaflow_proxy_url,request.endpoint,request.destination_url,request.query_params,request.request_headers,request.response_headers,EncryptionHandler(request.api_password) if request.api_password else None,request.expiration,str(request.ip) if request.ip else None,)return {"encoded_url": encoded_url}app.include_router(proxy_router, prefix="/proxy", tags=["proxy"], dependencies=[Depends(verify_api_key)])static_path = resources.files("mediaflow_proxy").joinpath("static")
6 unmodified lines78910111294 unmodified lines1071081091101111127 unmodified lines12012112212312412567 unmodified lines1931941951961971988 unmodified lines2072082092102112126 unmodified linesfrom mediaflow_proxy.configs import settingsfrom mediaflow_proxy.drm.decrypter import decrypt_segmentfrom mediaflow_proxy.utils.http_utils import encode_mediaflow_proxy_url, get_original_scheme, ProxyRequestHeaderslogger = logging.getLogger(__name__)94 unmodified lines"""hls = ["#EXTM3U", "#EXT-X-VERSION:6"]query_params = dict(request.query_params)video_profiles = {}audio_profiles = {}7 unmodified linesplaylist_url = encode_mediaflow_proxy_url(proxy_url,query_params=query_params,)if "video" in profile["mimeType"]:67 unmodified linesquery_params = dict(request.query_params)query_params.pop("profile_id", None)query_params.pop("d", None)for segment in segments:if mpd_dict["isLive"]:8 unmodified linesencode_mediaflow_proxy_url(proxy_url,query_params=query_params,))added_segments += 16 unmodified lines7891011121394 unmodified lines1081091101111121131147 unmodified lines12212312412512612712867 unmodified lines1961971981992002012028 unmodified lines2112122132142152162176 unmodified linesfrom mediaflow_proxy.configs import settingsfrom mediaflow_proxy.drm.decrypter import decrypt_segmentfrom mediaflow_proxy.utils.crypto_utils import encryption_handlerfrom mediaflow_proxy.utils.http_utils import encode_mediaflow_proxy_url, get_original_scheme, ProxyRequestHeaderslogger = logging.getLogger(__name__)94 unmodified lines"""hls = ["#EXTM3U", "#EXT-X-VERSION:6"]query_params = dict(request.query_params)has_encrypted = query_params.pop("has_encrypted", False)video_profiles = {}audio_profiles = {}7 unmodified linesplaylist_url = encode_mediaflow_proxy_url(proxy_url,query_params=query_params,encryption_handler=encryption_handler if has_encrypted else None,)if "video" in profile["mimeType"]:67 unmodified linesquery_params = dict(request.query_params)query_params.pop("profile_id", None)query_params.pop("d", None)has_encrypted = query_params.pop("has_encrypted", False)for segment in segments:if mpd_dict["isLive"]:8 unmodified linesencode_mediaflow_proxy_url(proxy_url,query_params=query_params,encryption_handler=encryption_handler if has_encrypted else None,))added_segments += 1
1234567891011121314151617from pydantic import BaseModel, Field, IPvAnyAddress
class GenerateUrlRequest(BaseModel): mediaflow_proxy_url: str = Field(..., description="The base URL for the mediaflow proxy.") endpoint: str | None = Field(None, description="The specific endpoint to be appended to the base URL.") destination_url: str | None = Field(None, description="The destination URL to which the request will be proxied.") query_params: dict | None = Field(None, description="Query parameters to be included in the request.") request_headers: dict | None = Field(None, description="Headers to be included in the request.") response_headers: dict | None = Field(None, description="Headers to be included in the response.") expiration: int | None = Field( None, description="Expiration time for the URL in seconds. If not provided, the URL will not expire." ) api_password: str | None = Field( None, description="API password for encryption. If not provided, the URL will only be encoded." ) ip: IPvAnyAddress | None = Field(None, description="The IP address to restrict the URL to.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import base64import jsonimport timefrom urllib.parse import urlencode
from Crypto.Cipher import AESfrom Crypto.Random import get_random_bytesfrom Crypto.Util.Padding import pad, unpadfrom fastapi import HTTPException, Requestfrom starlette.middleware.base import BaseHTTPMiddlewarefrom starlette.responses import JSONResponse
from mediaflow_proxy.configs import settings
class EncryptionHandler: def __init__(self, secret_key: str): self.secret_key = secret_key.encode("utf-8").ljust(32)[:32]
def encrypt_data(self, data: dict, expiration: int = None, ip: str = None) -> str: if expiration: data["exp"] = int(time.time()) + expiration if ip: data["ip"] = ip json_data = json.dumps(data).encode("utf-8") iv = get_random_bytes(16) cipher = AES.new(self.secret_key, AES.MODE_CBC, iv) encrypted_data = cipher.encrypt(pad(json_data, AES.block_size)) return base64.urlsafe_b64encode(iv + encrypted_data).decode("utf-8")
def decrypt_data(self, token: str, client_ip: str) -> dict: try: encrypted_data = base64.urlsafe_b64decode(token.encode("utf-8")) iv = encrypted_data[:16] cipher = AES.new(self.secret_key, AES.MODE_CBC, iv) decrypted_data = unpad(cipher.decrypt(encrypted_data[16:]), AES.block_size) data = json.loads(decrypted_data)
if "exp" in data: if data["exp"] < time.time(): raise HTTPException(status_code=401, detail="Token has expired") del data["exp"] # Remove expiration from the data
if "ip" in data: if data["ip"] != client_ip: raise HTTPException(status_code=403, detail="IP address mismatch") del data["ip"] # Remove IP from the data
return data except Exception as e: raise HTTPException(status_code=401, detail="Invalid or expired token")
class EncryptionMiddleware(BaseHTTPMiddleware): def __init__(self, app): super().__init__(app) self.encryption_handler = encryption_handler
async def dispatch(self, request: Request, call_next): encrypted_token = request.query_params.get("token") if encrypted_token: try: client_ip = self.get_client_ip(request) decrypted_data = self.encryption_handler.decrypt_data(encrypted_token, client_ip) # Modify request query parameters with decrypted data query_params = dict(request.query_params) query_params.pop("token") # Remove the encrypted token from query params query_params.update(decrypted_data) # Add decrypted data to query params query_params["has_encrypted"] = True
# Create a new request scope with updated query parameters new_query_string = urlencode(query_params) request.scope["query_string"] = new_query_string.encode() request._query_params = query_params except HTTPException as e: return JSONResponse(content={"error": str(e.detail)}, status_code=e.status_code)
response = await call_next(request) return response
@staticmethod def get_client_ip(request: Request) -> str | None: """ Extract the client's real IP address from the request headers or fallback to the client host. """ x_forwarded_for = request.headers.get("X-Forwarded-For") if x_forwarded_for: # In some cases, this header can contain multiple IPs # separated by commas. # The first one is the original client's IP. return x_forwarded_for.split(",")[0].strip() # Fallback to X-Real-IP if X-Forwarded-For is not available x_real_ip = request.headers.get("X-Real-IP") if x_real_ip: return x_real_ip return request.client.host if request.client else "127.0.0.1"
encryption_handler = EncryptionHandler(settings.api_password)2 unmodified lines3456787 unmodified lines161718192021193 unmodified lines2152162172182192202212222232 unmodified lines22622722822923023111 unmodified lines2432442452462472482492502 unmodified linesfrom dataclasses import dataclassfrom functools import partialfrom urllib import parseimport anyioimport httpx7 unmodified linesfrom mediaflow_proxy.configs import settingsfrom mediaflow_proxy.const import SUPPORTED_REQUEST_HEADERSlogger = logging.getLogger(__name__)193 unmodified linesquery_params: dict | None = None,request_headers: dict | None = None,response_headers: dict | None = None,) -> str:"""Encodes a MediaFlow proxy URL with query parameters and headers.Args:mediaflow_proxy_url (str): The base MediaFlow proxy URL.2 unmodified linesquery_params (dict, optional): Additional query parameters to include. Defaults to None.request_headers (dict, optional): Headers to include as query parameters. Defaults to None.response_headers (dict, optional): Headers to include as query parameters. Defaults to None.Returns:str: The encoded MediaFlow proxy URL.11 unmodified linesquery_params.update({key if key.startswith("r_") else f"r_{key}": value for key, value in response_headers.items()})# Encode the query parametersencoded_params = parse.urlencode(query_params, quote_via=parse.quote)# Construct the full URLif endpoint is None:2 unmodified lines34567897 unmodified lines17181920212223193 unmodified lines2172182192202212222232242252262272282 unmodified lines23123223323423523623723823911 unmodified lines2512522532542552562572582592602612622 unmodified linesfrom dataclasses import dataclassfrom functools import partialfrom urllib import parsefrom urllib.parse import urlencodeimport anyioimport httpx7 unmodified linesfrom mediaflow_proxy.configs import settingsfrom mediaflow_proxy.const import SUPPORTED_REQUEST_HEADERSfrom mediaflow_proxy.utils.crypto_utils import EncryptionHandlerlogger = logging.getLogger(__name__)193 unmodified linesquery_params: dict | None = None,request_headers: dict | None = None,response_headers: dict | None = None,encryption_handler: EncryptionHandler = None,expiration: int = None,ip: str = None,) -> str:"""Encodes & Encrypt (Optional) a MediaFlow proxy URL with query parameters and headers.Args:mediaflow_proxy_url (str): The base MediaFlow proxy URL.2 unmodified linesquery_params (dict, optional): Additional query parameters to include. Defaults to None.request_headers (dict, optional): Headers to include as query parameters. Defaults to None.response_headers (dict, optional): Headers to include as query parameters. Defaults to None.encryption_handler (EncryptionHandler, optional): The encryption handler to use. Defaults to None.expiration (int, optional): The expiration time for the encrypted token. Defaults to None.ip (str, optional): The public IP address to include in the query parameters. Defaults to None.Returns:str: The encoded MediaFlow proxy URL.11 unmodified linesquery_params.update({key if key.startswith("r_") else f"r_{key}": value for key, value in response_headers.items()})if encryption_handler:encrypted_token = encryption_handler.encrypt_data(query_params, expiration, ip)encoded_params = urlencode({"token": encrypted_token})else:encoded_params = urlencode(query_params)# Construct the full URLif endpoint is None:
2 unmodified lines34567865 unmodified lines747576777879808182832 unmodified linesfrom pydantic import HttpUrlfrom mediaflow_proxy.utils.http_utils import encode_mediaflow_proxy_url, get_original_scheme65 unmodified linesstr: The proxied URL."""full_url = parse.urljoin(base_url, url)return encode_mediaflow_proxy_url(self.mediaflow_proxy_url,"",full_url,query_params=dict(self.request.query_params),)2 unmodified lines345678965 unmodified lines757677787980818283848586872 unmodified linesfrom pydantic import HttpUrlfrom mediaflow_proxy.utils.crypto_utils import encryption_handlerfrom mediaflow_proxy.utils.http_utils import encode_mediaflow_proxy_url, get_original_scheme65 unmodified linesstr: The proxied URL."""full_url = parse.urljoin(base_url, url)query_params = dict(self.request.query_params)has_encrypted = query_params.pop("has_encrypted", False)return encode_mediaflow_proxy_url(self.mediaflow_proxy_url,"",full_url,query_params=dict(self.request.query_params),encryption_handler=encryption_handler if has_encrypted else None,)
README.md+38-3
mediaflow_proxy/main.py+23
mediaflow_proxy/mpd_processor.py+5
mediaflow_proxy/schemas.pyAdded+17
mediaflow_proxy/utils/crypto_utils.pyAdded+99
mediaflow_proxy/utils/http_utils.py+15-3
mediaflow_proxy/utils/m3u8_processor.py+4