Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
379 lines (330 loc) · 13.4 KB
/
Copy pathbackground.js
File metadata and controls
379 lines (330 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import {
uint8ArrayToBase64,
SettingsManager,
RemoteCDMManager,
PSSHFromKID,
stringToUTF16LEBytes,
} from "./util.js";
import { RemoteCdm } from "./remote_cdm.js";
let manifests = new Map();
let requests = new Map();
const sessions = new Map();
let logs = [];
function decodeBase64(str) {
try {
return atob(str);
} catch (e) {
console.error("Error decoding base64:", e);
return "";
}
}
function parseXML(xmlStr) {
try {
const parser = new DOMParser();
return parser.parseFromString(xmlStr, "text/xml");
} catch (e) {
console.error("Error parsing XML:", e);
return null;
}
}
chrome.webRequest.onBeforeSendHeaders.addListener(
function (details) {
if (details.method === "GET") {
if (!requests.has(details.url)) {
const headers = details.requestHeaders
.filter(
(item) =>
!(
item.name.startsWith("sec-ch-ua") ||
item.name.startsWith("Sec-Fetch") ||
item.name.startsWith("Accept-") ||
item.name.startsWith("Host") ||
item.name === "Connection"
)
)
.reduce((acc, item) => {
acc[item.name] = item.value;
return acc;
}, {});
requests.set(details.url, headers);
}
}
},
{ urls: ["<all_urls>"] },
[
"requestHeaders",
chrome.webRequest.OnSendHeadersOptions.EXTRA_HEADERS,
].filter(Boolean)
);
async function generateChallengeRemote(body, sendResponse, tab_url) {
try {
console.log("[PlayReadyProxy] generateChallengeRemote called with tab_url:", tab_url);
// Verifica che tab_url sia definito
if (!tab_url) {
console.error("[PlayReadyProxy] No tab_url provided, cannot store session");
sendResponse(body);
return;
}
// Decode the base64-encoded body into a binary string
const binaryString = decodeBase64(body);
const byteArray = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
byteArray[i] = binaryString.charCodeAt(i);
}
// Decode using UTF-16LE encoding
const decoder = new TextDecoder("utf-16le");
let xmlString = decoder.decode(byteArray);
let xmlDecoded;
// Extract the Challenge element from the XML string
const challengeRegex = /<Challenge[^>]*>([\s\S]*?)<\/Challenge>/i;
const challengeMatch = challengeRegex.exec(xmlString);
let encoding;
if (challengeMatch) {
const challengeContent = challengeMatch[1].trim();
const encodingRegex = /<Challenge[^>]*encoding="([^"]+)"[^>]*>/i;
const encodingMatch = encodingRegex.exec(xmlString);
encoding = encodingMatch ? encodingMatch[1] : null;
// If encoding is base64encoded, decode the challenge content
if (encoding === "base64encoded") {
const challengeBinaryString = decodeBase64(challengeContent);
const challengeByteArray = new Uint8Array(challengeBinaryString.length);
for (let i = 0; i < challengeBinaryString.length; i++) {
challengeByteArray[i] = challengeBinaryString.charCodeAt(i);
}
const utf8Decoder = new TextDecoder("utf-8");
xmlDecoded = utf8Decoder.decode(challengeByteArray);
}
} else {
console.error("Challenge element not found in XML.");
sendResponse(body);
return;
}
// Extract the KID element
const kidRegex = /<KID>([^<]+)<\/KID>/i;
const kidMatch = kidRegex.exec(xmlDecoded);
let kidBase64;
if (kidMatch) {
kidBase64 = kidMatch[1].trim();
} else {
console.log("[PlayReadyProxy]", "NO_KID_IN_CHALLENGE");
sendResponse(body);
return;
}
// Get PSSH from KID
const pssh = PSSHFromKID(kidBase64);
if (!pssh) {
console.log("[PlayReadyProxy]", "NO_PSSH_DATA_IN_CHALLENGE");
sendResponse(body);
return;
}
// Fetch the selected remote CDM and load it
const selected_remote_cdm_name = await RemoteCDMManager.getSelectedRemoteCDM();
if (!selected_remote_cdm_name) {
sendResponse(body);
return;
}
const selected_remote_cdm = await RemoteCDMManager.loadRemoteCDM(selected_remote_cdm_name);
let remoteCdmObj;
try {
// Check if the selected_remote_cdm is Base64-encoded XML
if (selected_remote_cdm.startsWith("PD94bWwgdm")) {
const decodedString = decodeBase64(selected_remote_cdm);
const parser = new DOMParser();
const xmlDoc = parseXML(decodedString);
remoteCdmObj = RemoteCdm.from_xml(xmlDoc);
} else {
remoteCdmObj = JSON.parse(selected_remote_cdm);
}
} catch (e) {
console.error("Error parsing remote CDM:", e);
sendResponse(body);
return;
}
const remote_cdm = RemoteCdm.from_object(remoteCdmObj);
const session_id = await remote_cdm.open();
if (!session_id) {
console.error("[PlayReadyProxy] Failed to open session.");
sendResponse(body);
return;
}
console.log("[PlayReadyProxy]", "SESSION_ID", session_id);
// Memorizza la sessione per il tab_url corrente
console.log("[PlayReadyProxy] Storing session_id", session_id, "for tab_url", tab_url);
sessions.set(tab_url, session_id);
const challenge = await remote_cdm.get_license_challenge(session_id, pssh);
// Replace the challenge content in the original XML with the new challenge
const newXmlString = xmlString.replace(
/(<Challenge[^>]*>)([\s\S]*?)(<\/Challenge>)/i,
`$1${challenge}$3`
);
// Convert the new XML string to UTF-16LE and then to base64
const utf16leBytes = stringToUTF16LEBytes(newXmlString);
const responseBase64 = uint8ArrayToBase64(utf16leBytes);
// Send the base64-encoded response
sendResponse(responseBase64);
} catch (error) {
console.error("Error in generateChallengeRemote:", error);
sendResponse(body);
}
}
async function parseLicenseRemote(body, sendResponse, tab_url) {
try {
console.log("[PlayReadyProxy] parseLicenseRemote called with tab_url:", tab_url);
// Verifica che tab_url sia definito
if (!tab_url) {
console.error("[PlayReadyProxy] No tab_url provided, cannot retrieve session");
sendResponse();
return;
}
const license_b64 = body; // License message is already Base64-encoded
// Debug delle sessioni disponibili
console.log("[PlayReadyProxy] Current sessions:",
[...sessions.entries()].map(([url, id]) => ({ url, id })));
// Fetch the selected remote CDM and load it
const selected_remote_cdm_name = await RemoteCDMManager.getSelectedRemoteCDM();
if (!selected_remote_cdm_name) {
console.error("[PlayReadyProxy] No remote CDM selected.");
sendResponse();
return;
}
const selected_remote_cdm = await RemoteCDMManager.loadRemoteCDM(selected_remote_cdm_name);
let remoteCdmObj;
try {
remoteCdmObj = JSON.parse(selected_remote_cdm);
} catch (e) {
console.error("[PlayReadyProxy] Error parsing remote CDM JSON:", e);
sendResponse();
return;
}
const remote_cdm = RemoteCdm.from_object(remoteCdmObj);
// Verifica se esiste già una sessione
if (!sessions.has(tab_url)) {
console.error("[PlayReadyProxy] No previous session found for URL:", tab_url);
// Non possiamo proseguire senza prima aver fatto il challenge
console.error("[PlayReadyProxy] Cannot process license without challenge first");
sendResponse();
return;
}
const session_id = sessions.get(tab_url);
console.log("[PlayReadyProxy] Using existing SESSION_ID", session_id, "for tab_url", tab_url);
// Fetch keys using get_keys(session_id, license_b64)
const returned_keys = await remote_cdm.get_keys(session_id, license_b64);
if (!returned_keys || returned_keys.length === 0) {
console.log("[PlayReadyProxy] No keys returned.");
sendResponse();
return;
}
// Format the keys correctly
const keys = returned_keys.map((s) => ({
k: s.key,
kid: s.key_id,
}));
console.log("[PlayReadyProxy]", "KEYS", JSON.stringify(keys), tab_url);
// Store log data
const log = {
type: "PLAYREADY",
keys: keys,
url: tab_url,
timestamp: Math.floor(Date.now() / 1000),
manifests: manifests.has(tab_url) ? manifests.get(tab_url) : [],
};
logs.push(log);
// Close the session after key retrieval
await remote_cdm.close(session_id);
sessions.delete(tab_url);
sendResponse();
} catch (error) {
console.error("[PlayReadyProxy] Error in parseLicenseRemote:", error);
sendResponse();
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
(async () => {
const tab_url = sender.tab ? sender.tab.url : null;
console.log("[PlayReadyProxy] Received message type:", message.type, "for tab_url:", tab_url);
switch (message.type) {
case "REQUEST":
if (!(await SettingsManager.getEnabled())) {
sendResponse(message.body);
manifests.clear();
return;
}
try {
JSON.parse(atob(message.body));
sendResponse(message.body);
return;
} catch {
if (message.body) {
await generateChallengeRemote(
message.body,
sendResponse,
tab_url // Passa tab_url come terzo parametro
);
}
}
break;
case "RESPONSE":
if (!(await SettingsManager.getEnabled())) {
sendResponse(message.body);
manifests.clear();
return;
}
try {
await parseClearKey(message.body, sendResponse, tab_url);
return;
} catch (e) {
console.log("[PlayReadyProxy] parseClearKey failed, trying parseLicenseRemote", e);
await parseLicenseRemote(
message.body,
sendResponse,
tab_url
);
return;
}
case "GET_LOGS":
sendResponse(logs);
break;
case "OPEN_PICKER_LOCAL":
chrome.windows.create({
url: "picker/filePickerLocal.html",
type: "popup",
width: 300,
height: 200,
});
break;
case "OPEN_PICKER":
chrome.windows.create({
url: "picker/filePicker.html",
type: "popup",
width: 300,
height: 200,
});
break;
case "CLEAR":
logs = [];
manifests.clear();
sessions.clear(); // Aggiungi questo per pulire anche le sessioni
break;
case "MANIFEST":
const parsed = JSON.parse(message.body);
const element = {
type: parsed.type,
url: parsed.url,
headers: requests.has(parsed.url)
? requests.get(parsed.url)
: [],
};
if (!manifests.has(tab_url)) {
manifests.set(tab_url, [element]);
} else {
let elements = manifests.get(tab_url);
if (!elements.some((e) => e.url === parsed.url)) {
elements.push(element);
manifests.set(tab_url, elements);
}
}
sendResponse();
}
})();
return true;
});