Skip to content

Instantly share code, notes, and snippets.

@ensean
Created October 9, 2025 08:20
Show Gist options
  • Save ensean/f75a782a54f7ff52516e2efeb471dfbf to your computer and use it in GitHub Desktop.
Save ensean/f75a782a54f7ff52516e2efeb471dfbf to your computer and use it in GitHub Desktop.
Lambda@Edge for modify m3u8 structure
import urllib3
import re
def lambda_handler(event, context):
request = event['Records'][0]['cf']['request']
response = event['Records'][0]['cf']['response']
# Extract token from query string
token = None
for param in request['querystring'].split('&'):
if param.startswith('token='):
token = param.split('=')[1]
break
if not token or response['headers'].get('content-type', [{}])[0].get('value') != 'application/vnd.apple.mpegurl':
return response
try:
# Fetch original content
http = urllib3.PoolManager()
origin_host = event['Records'][0]['cf']['config']['distributionDomainName']
url = f"https://{origin_host}{request['uri']}"
print("url: " + url)
resp = http.request('GET', url)
original_content = resp.data.decode('utf-8')
print("original_content: \n" + original_content)
# Modify M3U8 content - only add token to EXT-X-KEY URIs
def add_token_to_key(match):
uri_part = match.group(1)
separator = '&' if '?' in uri_part else '?'
return f'URI="{uri_part}{separator}token={token}"'
modified_content = re.sub(r'URI="([^"]+)"', add_token_to_key, original_content)
print("modified_content: \n" + modified_content)
response['body'] = modified_content
return response
except Exception as e:
print(f"Error: {e}")
return response
@ensean
Copy link
Author

ensean commented Oct 9, 2025

Change HLS encryption m3u8 file to append querystring for encryption key request athentication, eg change m3u8 from

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:3
#EXT-X-MEDIA-SEQUENCE:1
#EXT-X-PLAYLIST-TYPE:VOD
#EXT-X-KEY:METHOD=AES-128,URI="https://d1nhxos9liml4.cloudfront.net/keys/enc.key",IV=0x00000000000000000000000000000001
#EXTINF:3,
i9243290432_Ott_Hls_Ts_Avc_Aac_16x9_960x540p_3.5Mbps_qvbr_00001.ts
#EXT-X-KEY:METHOD=AES-128,URI="https://d1nhxos9liml4.cloudfront.net/keys/enc.key",IV=0x00000000000000000000000000000002
#EXTINF:3,

to

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:3
#EXT-X-MEDIA-SEQUENCE:1
#EXT-X-PLAYLIST-TYPE:VOD
#EXT-X-KEY:METHOD=AES-128,URI="https://d1nhxos9liml4.cloudfront.net/keys/enc.key?token=13s4124",IV=0x00000000000000000000000000000001
#EXTINF:3,
i9243290432_Ott_Hls_Ts_Avc_Aac_16x9_960x540p_3.5Mbps_qvbr_00001.ts
#EXT-X-KEY:METHOD=AES-128,URI="https://d1nhxos9liml4.cloudfront.net/keys/enc.key?token=13s4124",IV=0x00000000000000000000000000000002
#EXTINF:3,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment