init
This commit is contained in:
4
ext/lib/device.js
Normal file
4
ext/lib/device.js
Normal file
@@ -0,0 +1,4 @@
|
||||
// Classic Widevine L3 device (same files OF-Scraper's manual mode uses).
|
||||
export const CLIENT_BLOB_B64 = "CAESmgsK3QMIAhIQT30ajtB91RUzwMQQ0Wc8MRj0n96PBiKOAjCCAQoCggEBALOpKShDvD0RTJlg//DxrSMYR506TuPd6/XcFl0ZDMFmFPjLF2kANsB3S7MoJZtR0eBngTBpnawgM/vv49S3IXV+ItkrSHYGhXNM5Mqj1tlDStO1TEXTqk9bPneSZvaE+PoURNB9f+sKJXWFOSqngXQwDgbK877pZbjQ4RfBaZTZ8LA9nHz9pTO6bgOtKnTUFOn4bitaWT7ryqrF5NRirrQ9bJ+TP3A0u+XJxurvglTYH8Ib4cSMbWVMnWbiVKqMS03EHn36h2e6zGvO8pNd+vcx2UCdklAjfMBGR/L8nnMIceY92sKIkdhN6k7nX+AwwtmyWCZVjq8s8b0O04BSWIMCAwEAASjwIkgBUqoBCAEQABqBAQRAgPPDpqjCqwmKLpGRDD/T1qazqZRCXGfOJ3L3sI4XanzS2wyipwtUAUw9aiKD3c4SykB4InynJLji3fFZjMjDfQGRKQNtI6KW0DWZDHFuD0VOylica+BaK8+r3/KDACSxVvm/gLIJCJX/IlzB+YE2rnOokXoeRisZrLWsoZeTTiIgu2bvvdxDvB4cc+3s0+ktKzUG56ExJGaoezNJeoqIf1ASgAIeOsyI1pwR2NPA7YgU+rODJV9lmGgf8zJ2Lo94oBxlM2Thz2puj+y/ZwbuJJRV2fBIPZRKrPMH3ZJHZqxmv9rhs53qLXuhvk+ESVdTES5YP0oXyJuP+ifUphinyxjyrBQj2lCpW5o4aY2035vPeSeeTLwyNKdjYAcQ7RZsjG5y5aQJ2tfcAl6Vz3HH6nFm74PP0oHv0p1KH1ohGgl2f3q1dIG6vtojsz80ZaCouCKola52Tg8QGQc41HIFQiJ8VhIgK0+Buxcp4N7yHFYk7MpzkNZ9fToo/D54FKirEz3JBL1T4JPIewG9p2Ocgwkjbhs12GxUI4ThF+cRvBtQwwmTGrQFCq4CCAESEGnj6Ji7LD+4o7MoHYT4jBQYjtW+kQUijgIwggEKAoIBAQDY9um1ifBRIOmkPtDZTqH+CZUBbb0eK0Cn3NHFf8MFUDzPEz+emK/OTub/hNxCJCao//pP5L8tRNUPFDrrvCBMo7Rn+iUb+mA/2yXiJ6ivqcN9Cu9i5qOU1ygon9SWZRsujFFB8nxVreY5Lzeq0283zn1Cg1stcX4tOHT7utPzFG/ReDFQt0O/GLlzVwB0d1sn3SKMO4XLjhZdncrtF9jljpg7xjMIlnWJUqxDo7TQkTytJmUl0kcM7bndBLerAdJFGaXc6oSY4eNy/IGDluLCQR3KZEQsy/mLeV1ggQ44MFr7XOM+rd+4/314q/deQbjHqjWFuVr8iIaKbq+R63ShAgMBAAEo8CISgAMii2Mw6z+Qs1bvvxGStie9tpcgoO2uAt5Zvv0CDXvrFlwnSbo+qR71Ru2IlZWVSbN5XYSIDwcwBzHjY8rNr3fgsXtSJty425djNQtF5+J2jrAhf3Q2m7EI5aohZGpD2E0cr+dVj9o8x0uJR2NWR8FVoVQSXZpad3M/4QzBLNto/tz+UKyZwa7Sc/eTQc2+ZcDS3ZEO3lGRsH864Kf/cEGvJRBBqcpJXKfG+ItqEW1AAPptjuggzmZEzRq5xTGf6or+bXrKjCpBS9G1SOyvCNF1k5z6lG8KsXhgQxL6ADHMoulxvUIihyPY5MpimdXfUdEQ5HA2EqNiNVNIO4qP007jW51yAeThOry4J22xs8RdkIClOGAauLIl0lLA4flMzW+VfQl5xYxP0E5tuhn0h+844DslU8ZF7U1dU2QprIApffXD9wgAACk26Rggy8e96z8i86/+YYyZQkc9hIdCAERrgEYCEbByzONrdRDs1MrS/ch1moV5pJv63BIKvQHGvLkaFgoMY29tcGFueV9uYW1lEgZHb29nbGUaIQoKbW9kZWxfbmFtZRITQU9TUCBvbiBJQSBFbXVsYXRvchoYChFhcmNoaXRlY3R1cmVfbmFtZRIDeDg2Gh4KC2RldmljZV9uYW1lEg9nZW5lcmljX3g4Nl9hcm0aIgoMcHJvZHVjdF9uYW1lEhJzZGtfZ3Bob25lX3g4Nl9hcm0aZAoKYnVpbGRfaW5mbxJWZ29vZ2xlL3Nka19ncGhvbmVfeDg2X2FybS9nZW5lcmljX3g4Nl9hcm06OS9QU1IxLjE4MDcyMC4xMjIvNjczNjc0Mjp1c2VyZGVidWcvZGV2LWtleXMaHgoUd2lkZXZpbmVfY2RtX3ZlcnNpb24SBjE0LjAuMBokCh9vZW1fY3J5cHRvX3NlY3VyaXR5X3BhdGNoX2xldmVsEgEwMg4QASAAKA0wAEAASABQAA==";
|
||||
// device_private_key as PKCS#8 DER (base64) — WebCrypto importKey('pkcs8') ready
|
||||
export const PRIVATE_KEY_DER_B64 = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCzqSkoQ7w9EUyZYP/w8a0jGEedOk7j3ev13BZdGQzBZhT4yxdpADbAd0uzKCWbUdHgZ4EwaZ2sIDP77+PUtyF1fiLZK0h2BoVzTOTKo9bZQ0rTtUxF06pPWz53kmb2hPj6FETQfX/rCiV1hTkqp4F0MA4GyvO+6WW40OEXwWmU2fCwPZx8/aUzum4DrSp01BTp+G4rWlk+68qqxeTUYq60PWyfkz9wNLvlycbq74JU2B/CG+HEjG1lTJ1m4lSqjEtNxB59+odnusxrzvKTXfr3MdlAnZJQI3zARkfy/J5zCHHmPdrCiJHYTepO51/gMMLZslgmVY6vLPG9DtOAUliDAgMBAAECggEBAID8ljv+RYtifCgyaA7ItJFZwTC0yCb5EYu2s6ercGj5rVziErCkIqsT+xlpXXahy5jdNvdXHIiTpj7fACecQz1jjgl09dUm4XDiZ/DEqF/b3EEbDOOlD8VhsPuP9LRQy6BgJPe64rgQ1MwHFf/1uw974NYnp9ANKacC8Fhp2C+xAoubeZCAWxBZXsCG9Uu+MbxpQMyraKUyGWKNYAsCsHl3eSi0Ti5kYk4jBPiiTWL5ZqYooo1HiM+6MkgJ8UEL1AgSEP92cpgMq6DHC1nAjrqWtfM5tdDvOirs1bDUSbudpgCHRS/1RyOMLriJV9ZwWaA7F9ttesSVF1VREf5MPmECgYEA89kIgWSG64Yc9qGbfKOcd4J90ITa2VLLLX9Q+r35yGMcwEKqVTpnulndeeIKPz34MJQDSE8e1o9Z8uAMwPR3ZoPDn6VDV91cS/PHiLIneM9w8sKOOFaDB1cl8oTK5/gfF07JGXggac2nfx7VS1vCNExI4kqxCM6q6D8qNz1st38CgYEAvJ09vUvmw692bZnh2vudWX0urXY0WChlevRb8B0kN8wci7ecVh507T/lqwKLbz1m8a9qqhjbp+bttwdB6C34DTm+jB0exGMMEJOcL5JotqGCssXLDZJxJoHrgtzkgUUNFIYw42A+YEXqMtbMPXoMwLwtVAvMGSMVDDL11CyfAP0CgYBSSddY8vek22lCwV6bPQs8OUkD6RGBbTMrc198fkegm/HD37tjb4Y5mMHos6MJnHv4yLoi2LBrb4zHLVygcN8qNST65uZG7GiNKQMY2iX/2uEeyxD7ahZlj786jB19EnpLf0bV1Xf6vG/dsiYAfEKZK3UdCF+dvUBnh4lTguMBOQKBgQCq5zOFLZxIndmKUA/1c15NMv+zj1K4usnREk+oD0+8+0a2VsXixrAeNXKudJzRS+rWfaMBw4ps5fNpj7rpXZXQrgz5On2hZzoMXyP7ewdEzK33vP9TKek7AifbKLooY+AJQ9pSfOeoJlGihT0FS2z4ysmryRDDiiVNK3PSMChXJQKBgQCgCwDgzmbxFLi7qxFyFsncBLMQ38WLS3JwZvLXXgfmJxb2/CAcuKd2viwrN0c7Mb0xLIOIukLWNsioCkqY9SWqTp8F9wsM7Owl6n0YYGPHqiUxYjFKLVKSPstzdaVOZWlndl1S88k4mKJdIGz3T6J2BVFMevK5VR1pusLcWqMxJA==";
|
||||
BIN
ext/lib/device_client_id_blob
Normal file
BIN
ext/lib/device_client_id_blob
Normal file
Binary file not shown.
27
ext/lib/device_private_key
Normal file
27
ext/lib/device_private_key
Normal file
@@ -0,0 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpQIBAAKCAQEAs6kpKEO8PRFMmWD/8PGtIxhHnTpO493r9dwWXRkMwWYU+MsX
|
||||
aQA2wHdLsyglm1HR4GeBMGmdrCAz++/j1LchdX4i2StIdgaFc0zkyqPW2UNK07VM
|
||||
RdOqT1s+d5Jm9oT4+hRE0H1/6woldYU5KqeBdDAOBsrzvulluNDhF8FplNnwsD2c
|
||||
fP2lM7puA60qdNQU6fhuK1pZPuvKqsXk1GKutD1sn5M/cDS75cnG6u+CVNgfwhvh
|
||||
xIxtZUydZuJUqoxLTcQeffqHZ7rMa87yk1369zHZQJ2SUCN8wEZH8vyecwhx5j3a
|
||||
woiR2E3qTudf4DDC2bJYJlWOryzxvQ7TgFJYgwIDAQABAoIBAQCA/JY7/kWLYnwo
|
||||
MmgOyLSRWcEwtMgm+RGLtrOnq3Bo+a1c4hKwpCKrE/sZaV12ocuY3Tb3VxyIk6Y+
|
||||
3wAnnEM9Y44JdPXVJuFw4mfwxKhf29xBGwzjpQ/FYbD7j/S0UMugYCT3uuK4ENTM
|
||||
BxX/9bsPe+DWJ6fQDSmnAvBYadgvsQKLm3mQgFsQWV7AhvVLvjG8aUDMq2ilMhli
|
||||
jWALArB5d3kotE4uZGJOIwT4ok1i+WamKKKNR4jPujJICfFBC9QIEhD/dnKYDKug
|
||||
xwtZwI66lrXzObXQ7zoq7NWw1Em7naYAh0Uv9UcjjC64iVfWcFmgOxfbbXrElRdV
|
||||
URH+TD5hAoGBAPPZCIFkhuuGHPahm3yjnHeCfdCE2tlSyy1/UPq9+chjHMBCqlU6
|
||||
Z7pZ3XniCj89+DCUA0hPHtaPWfLgDMD0d2aDw5+lQ1fdXEvzx4iyJ3jPcPLCjjhW
|
||||
gwdXJfKEyuf4HxdOyRl4IGnNp38e1UtbwjRMSOJKsQjOqug/Kjc9bLd/AoGBALyd
|
||||
Pb1L5sOvdm2Z4dr7nVl9Lq12NFgoZXr0W/AdJDfMHIu3nFYedO0/5asCi289ZvGv
|
||||
aqoY26fm7bcHQegt+A05vowdHsRjDBCTnC+SaLahgrLFyw2ScSaB64Lc5IFFDRSG
|
||||
MONgPmBF6jLWzD16DMC8LVQLzBkjFQwy9dQsnwD9AoGAUknXWPL3pNtpQsFemz0L
|
||||
PDlJA+kRgW0zK3NffH5HoJvxw9+7Y2+GOZjB6LOjCZx7+Mi6Itiwa2+Mxy1coHDf
|
||||
KjUk+ubmRuxojSkDGNol/9rhHssQ+2oWZY+/OowdfRJ6S39G1dV3+rxv3bImAHxC
|
||||
mSt1HQhfnb1AZ4eJU4LjATkCgYEAquczhS2cSJ3ZilAP9XNeTTL/s49SuLrJ0RJP
|
||||
qA9PvPtGtlbF4sawHjVyrnSc0Uvq1n2jAcOKbOXzaY+66V2V0K4M+Tp9oWc6DF8j
|
||||
+3sHRMyt97z/UynpOwIn2yi6KGPgCUPaUnznqCZRooU9BUts+MrJq8kQw4olTStz
|
||||
0jAoVyUCgYEAoAsA4M5m8RS4u6sRchbJ3ASzEN/Fi0tycGby114H5icW9vwgHLin
|
||||
dr4sKzdHOzG9MSyDiLpC1jbIqApKmPUlqk6fBfcLDOzsJep9GGBjx6olMWIxSi1S
|
||||
kj7Lc3WlTmVpZ3ZdUvPJOJiiXSBs90+idgVRTHryuVUdabrC3FqjMSQ=
|
||||
-----END RSA PRIVATE KEY-----
|
||||
229
ext/lib/holds.js
Normal file
229
ext/lib/holds.js
Normal file
@@ -0,0 +1,229 @@
|
||||
// Disk-backed holds: media streams into the browser's private filesystem
|
||||
// (OPFS) instead of living in RAM, so multi-GB files never bloat the
|
||||
// offscreen document. Files are laid out exactly like the old in-memory
|
||||
// arrays (header first, then each decrypted fragment in order) so the
|
||||
// MuxPlanner offsets match the previous behavior byte for byte.
|
||||
|
||||
// ground-truth capture for building our own decrypt/mux: the first DRM
|
||||
// download after load records real inputs and the wasm's exact outputs
|
||||
export const drmCapture = { frags: [], moofs: [], headers: {}, mux: null, sent: false };
|
||||
const b64 = (bytes) => {
|
||||
let s = "";
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
|
||||
return btoa(s);
|
||||
};
|
||||
|
||||
export async function holdsDir() {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
return root.getDirectoryHandle("holds", { create: true });
|
||||
}
|
||||
|
||||
/** Stream a fetch Response body into OPFS. Returns {id, size}. */
|
||||
export async function streamIntoHold(dir, res, onChunk) {
|
||||
const id = "h_" + Math.random().toString(36).slice(2);
|
||||
const fh = await dir.getFileHandle(id, { create: true });
|
||||
const w = await fh.createWritable();
|
||||
let size = 0;
|
||||
for await (const chunk of res.body) {
|
||||
await w.write(chunk);
|
||||
size += chunk.byteLength;
|
||||
if (onChunk) onChunk(chunk.byteLength);
|
||||
}
|
||||
await w.close();
|
||||
return { id, size };
|
||||
}
|
||||
|
||||
/** Blob URL for a held file — disk-backed, so chrome.downloads streams it. */
|
||||
export async function holdFileUrl(dir, id, mime = "application/octet-stream") {
|
||||
const fh = await dir.getFileHandle(id);
|
||||
const file = await fh.getFile();
|
||||
// slice with a contentType — OPFS files carry no MIME type, and an untyped
|
||||
// blob makes Chrome append .txt to the download
|
||||
return URL.createObjectURL(file.slice(0, file.size, mime || "application/octet-stream"));
|
||||
}
|
||||
|
||||
export async function removeHolds(dir, names) {
|
||||
for (const name of names ?? []) {
|
||||
if (!name) continue;
|
||||
try { await dir.removeEntry(name); } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Async-iterate the top-level boxes of an mp4 File with chunked reads.
|
||||
* Yields {type, start, end, bytes} — `bytes` is a copy only for types in
|
||||
* `withBytes`. Boxes bigger than a chunk are skipped without buffering
|
||||
* unless their bytes were requested, so huge mdats never enter RAM here.
|
||||
*/
|
||||
export async function* mp4Boxes(file, { withBytes = [], chunkSize = 1 << 22 } = {}) {
|
||||
const want = new Set(withBytes);
|
||||
let buf = new Uint8Array(0); // pending bytes, starting at file offset `base`
|
||||
let base = 0;
|
||||
for (;;) {
|
||||
let size = 0;
|
||||
if (buf.length >= 8) {
|
||||
const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
size = dv.getUint32(0);
|
||||
if (size === 1) {
|
||||
size = buf.length >= 16 ? Number(dv.getBigUint64(8)) : -1; // need more
|
||||
} else if (size === 0) {
|
||||
size = file.size - base; // box extends to EOF
|
||||
}
|
||||
if (size >= 0 && size < 8) return; // malformed, like the old parser
|
||||
if (size >= 8) {
|
||||
const type = String.fromCharCode(buf[4], buf[5], buf[6], buf[7]);
|
||||
if (buf.length >= size) {
|
||||
yield { type, start: base, end: base + size, bytes: want.has(type) ? buf.slice(0, size) : undefined };
|
||||
buf = buf.subarray(size);
|
||||
base += size;
|
||||
continue;
|
||||
}
|
||||
if (!want.has(type) && base + size <= file.size) {
|
||||
// large box we don't need bytes for — skip past it without buffering
|
||||
yield { type, start: base, end: base + size, bytes: undefined };
|
||||
buf = new Uint8Array(0);
|
||||
base += size;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (base + buf.length >= file.size) return; // EOF (or partial box at EOF)
|
||||
const from = base + buf.length;
|
||||
const to = Math.min(from + chunkSize, file.size);
|
||||
const chunk = new Uint8Array(await file.slice(from, to).arrayBuffer());
|
||||
const merged = new Uint8Array(buf.length + chunk.length);
|
||||
merged.set(buf);
|
||||
merged.set(chunk, buf.length);
|
||||
buf = merged;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream-decrypt one track. Reads the source hold, decrypts each
|
||||
* moof..mdat fragment in place with the same wasm calls as the in-memory
|
||||
* flow, and appends to a new OPFS file laid out like the old result array:
|
||||
* header first, fragments in order. Returns {header} (the pre-strip source
|
||||
* header, as the old code used it).
|
||||
*/
|
||||
export async function decryptTrackToOpfs(dir, srcId, decId, keyBytes, fns, label = "video", onProgress) {
|
||||
const src = await (await dir.getFileHandle(srcId)).getFile();
|
||||
const dec = await dir.getFileHandle(decId, { create: true });
|
||||
const w = await dec.createWritable();
|
||||
let header = null;
|
||||
try {
|
||||
let marker = 0, pattern = null, civ = null;
|
||||
let moofStart = -1, done = 0;
|
||||
for await (const box of mp4Boxes(src)) {
|
||||
if (header === null) {
|
||||
if (box.type !== "moof") continue;
|
||||
header = new Uint8Array(await src.slice(0, box.start).arrayBuffer());
|
||||
marker = fns.tencMarker(header);
|
||||
if (marker < 0) throw new Error("no tenc — not CENC-protected");
|
||||
fns.stripInit(header);
|
||||
pattern = fns.tencCryptPattern(header);
|
||||
civ = fns.tencConstantIv(header);
|
||||
await w.write(header);
|
||||
moofStart = box.start;
|
||||
continue;
|
||||
}
|
||||
if (box.type === "moof") { moofStart = box.start; continue; }
|
||||
if (box.type === "mdat" && moofStart >= 0) {
|
||||
const bytes = new Uint8Array(await src.slice(moofStart, box.end).arrayBuffer());
|
||||
if (!drmCapture.sent && drmCapture.frags.filter((f) => f.track === label).length < 1) {
|
||||
drmCapture.headers[label] = b64(header);
|
||||
drmCapture.key = b64(keyBytes);
|
||||
drmCapture.marker = marker;
|
||||
drmCapture.pattern = pattern ? [...pattern] : null;
|
||||
drmCapture.civ = civ ? [...civ] : null;
|
||||
var capIn = b64(bytes);
|
||||
}
|
||||
if (pattern) {
|
||||
fns.decryptAndStripFragmentCbcs(bytes, keyBytes, marker, pattern[0] ?? 0, pattern[1] ?? 0, civ ?? new Uint8Array());
|
||||
} else {
|
||||
fns.decryptAndStripFragment(bytes, keyBytes, marker);
|
||||
}
|
||||
await w.write(bytes);
|
||||
done += bytes.length;
|
||||
if (onProgress) onProgress(done, src.size);
|
||||
if (capIn) { drmCapture.frags.push({ track: label, in: capIn, out: b64(bytes) }); capIn = null; }
|
||||
moofStart = -1;
|
||||
}
|
||||
}
|
||||
if (header === null) {
|
||||
// degenerate track with no fragments: the old flow treated the whole
|
||||
// file as its own "header"
|
||||
await w.write(new Uint8Array(await src.slice(0, src.size).arrayBuffer()));
|
||||
}
|
||||
} catch (e) {
|
||||
try { await w.close(); } catch {}
|
||||
try { await dir.removeEntry(decId); } catch {}
|
||||
throw e;
|
||||
}
|
||||
await w.close();
|
||||
return { header };
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-parse a decrypted track file and feed every moof into the MuxPlanner
|
||||
* exactly like the in-memory flow did: bytes from the moof's start through
|
||||
* whatever follows it up to (not including) the next mdat, at the moof's
|
||||
* offset. Returns the bytes before the first moof — the header the planner
|
||||
* constructor wants.
|
||||
*/
|
||||
export async function pushTrackMoofs(dir, decId, planner, isVideo) {
|
||||
const file = await (await dir.getFileHandle(decId)).getFile();
|
||||
let header = null, moofStart = -1;
|
||||
for await (const box of mp4Boxes(file)) {
|
||||
if (box.type === "moof") {
|
||||
if (header === null) header = new Uint8Array(await file.slice(0, box.start).arrayBuffer());
|
||||
moofStart = box.start;
|
||||
continue;
|
||||
}
|
||||
if (box.type === "mdat" && moofStart >= 0) {
|
||||
const moof = new Uint8Array(await file.slice(moofStart, box.start).arrayBuffer());
|
||||
const track = isVideo ? "video" : "audio";
|
||||
if (!drmCapture.sent && drmCapture.moofs.filter((x) => x.track === track).length < 3) {
|
||||
drmCapture.moofs.push({ track, offset: moofStart, moof: b64(moof) });
|
||||
}
|
||||
isVideo ? planner.pushVideoMoof(moof, moofStart) : planner.pushAudioMoof(moof, moofStart);
|
||||
moofStart = -1;
|
||||
}
|
||||
}
|
||||
return header ?? new Uint8Array(await file.slice(0, file.size).arrayBuffer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the muxed output: muxed header, then each layout range copied from
|
||||
* the decrypted track files in chunks. Returns {blobUrl, size}.
|
||||
*/
|
||||
export async function writeMuxedFile(dir, finalId, muxed, videoFile, audioFile) {
|
||||
const fh = await dir.getFileHandle(finalId, { create: true });
|
||||
const w = await fh.createWritable();
|
||||
try {
|
||||
await w.write(muxed.header());
|
||||
const layout = muxed.layout();
|
||||
for (let i = 0; i < layout.length; i += 3) {
|
||||
const isVideo = layout[i], off = layout[i + 1], len = layout[i + 2];
|
||||
const f = (isVideo || !audioFile) ? videoFile : audioFile;
|
||||
let p = off;
|
||||
const end = off + len;
|
||||
while (p < end) {
|
||||
const n = Math.min(1 << 22, end - p);
|
||||
await w.write(await f.slice(p, p + n).arrayBuffer());
|
||||
p += n;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
try { await w.close(); } catch {}
|
||||
try { await dir.removeEntry(finalId); } catch {}
|
||||
throw e;
|
||||
}
|
||||
await w.close();
|
||||
if (!drmCapture.sent) {
|
||||
try { drmCapture.mux = { header: b64(muxed.header()), layout: [...muxed.layout()] }; } catch {}
|
||||
}
|
||||
const ofile = await fh.getFile();
|
||||
// OPFS files have no MIME type — an untyped blob URL makes Chrome append
|
||||
// .txt to the download, so hand out a typed view of the same file
|
||||
return { blobUrl: URL.createObjectURL(ofile.slice(0, ofile.size, "video/mp4")), size: ofile.size };
|
||||
}
|
||||
234
ext/lib/main-hook.js
Normal file
234
ext/lib/main-hook.js
Normal file
@@ -0,0 +1,234 @@
|
||||
// MAIN world: hook the page's network and index every media entry OF sends us.
|
||||
// Posts/media land in window.__ofsaverMedia; the content script picks them up
|
||||
// via a DOM CustomEvent, so both worlds see the same data.
|
||||
(() => {
|
||||
if (window.__ofsaverHooked) return;
|
||||
window.__ofsaverHooked = true;
|
||||
const store = new Map(); // mediaId -> entry (includes .raw = full media object)
|
||||
const users = new Map(); // userId -> username (from any response that names a user)
|
||||
|
||||
const emit = () => {
|
||||
try {
|
||||
window.dispatchEvent(new CustomEvent("ofsaver-media-data", {
|
||||
detail: [...store.values()],
|
||||
}));
|
||||
window.dispatchEvent(new CustomEvent("ofsaver-users", {
|
||||
detail: [...users.entries()],
|
||||
}));
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const walk = (obj, found) => {
|
||||
if (!obj || typeof obj !== "object") return;
|
||||
if (Array.isArray(obj)) { for (const v of obj) walk(v, found); return; }
|
||||
const type = obj.type;
|
||||
const files = obj.files;
|
||||
if ((type === "video" || type === "audio" || type === "photo" || type === "gif") && files && typeof files === "object" && obj.id != null) {
|
||||
found.add(obj);
|
||||
}
|
||||
for (const k of Object.keys(obj)) walk(obj[k], found);
|
||||
};
|
||||
|
||||
const ingest = (json, url) => {
|
||||
let data;
|
||||
try { data = JSON.parse(json); } catch { return; }
|
||||
// chat messages: emit the ordered batch so the content script can map
|
||||
// DOM rows positionally (the chat rows expose no message ids). Locked
|
||||
// chat media ships WITHOUT a files key and is NOT added to the media
|
||||
// store — its info rides in this batch instead, keeping the store
|
||||
// exactly as the download flow expects it.
|
||||
if (url) {
|
||||
const cm = String(url).match(/\/api2\/v2\/chats\/([^/]+)\/messages/);
|
||||
if (cm) {
|
||||
const list = data?.list ?? (Array.isArray(data) ? data : null);
|
||||
if (list && list.length) {
|
||||
const fu = list.find((m) => m.fromUser)?.fromUser;
|
||||
if (fu) console.log("[ofsaver] chat batch fromUser sample:", fu.id, fu.username);
|
||||
try {
|
||||
window.dispatchEvent(new CustomEvent("ofsaver-chat-batch", {
|
||||
detail: {
|
||||
chatId: cm[1],
|
||||
msgs: list.map((m) => ({
|
||||
id: String(m.id),
|
||||
username: m.fromUser?.username ?? null,
|
||||
media: (m.media ?? []).map((x) => ({
|
||||
id: x.id,
|
||||
type: x.type,
|
||||
duration: x.duration ?? x.videoDuration ?? null,
|
||||
canView: x.canView !== false,
|
||||
})),
|
||||
})),
|
||||
},
|
||||
}));
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
const found = new Set();
|
||||
walk(data, found);
|
||||
// find post context: any post objects mapping postId → their media list
|
||||
const postMedia = new Map();
|
||||
// containers: posts (postedAt/responseType) and chat messages (fromUser/createdAt)
|
||||
const containers = [];
|
||||
const walkContainers = (o) => {
|
||||
if (!o || typeof o !== "object") return;
|
||||
if (Array.isArray(o)) { for (const v of o) walkContainers(v); return; }
|
||||
if (o.id != null && Array.isArray(o.media) && o.media.length) {
|
||||
const isPost = o.postedAt !== undefined || o.responseType !== undefined;
|
||||
const isMessage = Array.isArray(o.media) && (o.fromUser !== undefined || o.createdAt !== undefined) && !isPost;
|
||||
if (isPost || isMessage) {
|
||||
containers.push({
|
||||
id: o.id,
|
||||
responseType: isMessage ? "message" : (o.responseType ?? "post"),
|
||||
username: o.author?.username ?? o.fromUser?.username,
|
||||
creatorId: o.author?.id ?? o.fromUser?.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const k of Object.keys(o)) walkContainers(o[k]);
|
||||
};
|
||||
walkContainers(data);
|
||||
// second pass: map media ids to their container
|
||||
const containerMedia = new Map();
|
||||
const walkMediaLinks = (o) => {
|
||||
if (!o || typeof o !== "object") return;
|
||||
if (Array.isArray(o)) { for (const v of o) walkMediaLinks(v); return; }
|
||||
if (o.id != null && Array.isArray(o.media) && o.media.length) {
|
||||
const isPost = o.postedAt !== undefined || o.responseType !== undefined;
|
||||
const isMessage = o.fromUser !== undefined || (o.createdAt !== undefined && !isPost);
|
||||
if (isPost || isMessage) {
|
||||
for (const m of o.media) {
|
||||
if (m?.id != null) containerMedia.set(m.id, {
|
||||
postId: o.id,
|
||||
responseType: isMessage ? "message" : (o.responseType ?? "post"),
|
||||
username: o.author?.username ?? o.fromUser?.username,
|
||||
creatorId: o.author?.id ?? o.fromUser?.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const k of Object.keys(o)) walkMediaLinks(o[k]);
|
||||
};
|
||||
walkMediaLinks(data);
|
||||
|
||||
// any response that names a user fixes the id → handle mapping for all
|
||||
// future naming (some views ship fromUser.id without the username)
|
||||
const usersBefore = users.size;
|
||||
const walkUsers = (o) => {
|
||||
if (!o || typeof o !== "object") return;
|
||||
if (Array.isArray(o)) { for (const v of o) walkUsers(v); return; }
|
||||
if (o.id != null && typeof o.username === "string" && o.username) users.set(String(o.id), o.username);
|
||||
for (const k of Object.keys(o)) walkUsers(o[k]);
|
||||
};
|
||||
walkUsers(data);
|
||||
|
||||
for (const m of found) {
|
||||
const drm = m.files?.drm;
|
||||
const src = m.files?.source?.url ?? m.files?.full?.url ?? null;
|
||||
const prev = store.get(m.id);
|
||||
// keep the richest info we've seen (later API views may be less privileged)
|
||||
const ctx = containerMedia.get(m.id) ?? {};
|
||||
const entry = {
|
||||
id: m.id,
|
||||
postId: ctx.postId ?? prev?.postId ?? null,
|
||||
responseType: ctx.responseType ?? prev?.responseType ?? null,
|
||||
username: ctx.username ?? (ctx.creatorId != null ? users.get(String(ctx.creatorId)) : null) ?? prev?.username ?? null,
|
||||
creatorId: ctx.creatorId ?? prev?.creatorId ?? null,
|
||||
type: m.type,
|
||||
canView: m.canView !== false, // latest API view wins
|
||||
duration: m.duration ?? m.videoDuration ?? prev?.duration ?? null,
|
||||
createdAt: m.createdAt ?? prev?.createdAt ?? null,
|
||||
height: m.height ?? m.files?.source?.h ?? prev?.height ?? null,
|
||||
drm: (drm?.manifest && drm) || prev?.drm || null,
|
||||
source: (m.canView !== false && src) || prev?.source || null,
|
||||
raw: m, // full media object for quality variants
|
||||
};
|
||||
if (m.canView === false) entry.canView = false;
|
||||
store.set(m.id, entry);
|
||||
}
|
||||
if (found.size || users.size !== usersBefore) emit();
|
||||
};
|
||||
|
||||
const of = window.fetch;
|
||||
window.fetch = async function (...args) {
|
||||
try {
|
||||
const u = typeof args[0] === "string" ? args[0] : args[0]?.url ?? "";
|
||||
if (/\/api2\//.test(u)) {
|
||||
const h = args[1]?.headers;
|
||||
const get = (k) => {
|
||||
if (!h) return null;
|
||||
if (typeof Headers !== "undefined" && h instanceof Headers) return h.get(k);
|
||||
return h[k] ?? h[k.toLowerCase()] ?? null;
|
||||
};
|
||||
const uid = get("user-id");
|
||||
const bc = get("x-bc");
|
||||
if (uid != null || bc != null) {
|
||||
const store = JSON.parse(document.documentElement.getAttribute("data-ofsaver-auth") || "{}");
|
||||
if (uid != null) store.uid = String(uid);
|
||||
if (bc != null) store.bc = String(bc);
|
||||
store.t = Date.now();
|
||||
document.documentElement.setAttribute("data-ofsaver-auth", JSON.stringify(store));
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
const res = await of.apply(this, args);
|
||||
try {
|
||||
const url = typeof args[0] === "string" ? args[0] : args[0]?.url ?? "";
|
||||
if (/\/api2\/v2\//.test(url) && res.ok) {
|
||||
const clone = res.clone();
|
||||
clone.text().then((t) => ingest(t, url)).catch(() => {});
|
||||
}
|
||||
} catch {}
|
||||
return res;
|
||||
};
|
||||
|
||||
// capture the page's own license request headers for auth debugging
|
||||
const osrh = XMLHttpRequest.prototype.setRequestHeader;
|
||||
XMLHttpRequest.prototype.setRequestHeader = function (k, v) {
|
||||
try {
|
||||
const lk = String(k).toLowerCase();
|
||||
const u = String(this.__ofsaverUrl ?? "");
|
||||
// session auth capture: every signed /api2/ request carries user-id
|
||||
// and x-bc — the tab's own session, which is the only correct one in
|
||||
// incognito (chrome.cookies reads the regular jar there)
|
||||
if (/\/api2\//.test(u) && (lk === "user-id" || lk === "x-bc")) {
|
||||
const store = JSON.parse(document.documentElement.getAttribute("data-ofsaver-auth") || "{}");
|
||||
if (lk === "user-id") store.uid = String(v);
|
||||
else store.bc = String(v);
|
||||
store.t = Date.now();
|
||||
document.documentElement.setAttribute("data-ofsaver-auth", JSON.stringify(store));
|
||||
}
|
||||
if (/\/drm\/|\/licenses?\b|type=widevine/i.test(u) || /sign|time|x-bc|app-token|user-id|x-of-rev/i.test(lk)) {
|
||||
const store = JSON.parse(document.documentElement.getAttribute("data-ofsaver-lic") || "{}");
|
||||
(store.h = store.h || {})[lk] = v;
|
||||
store.url = u.slice(0, 120);
|
||||
store.t = Date.now();
|
||||
document.documentElement.setAttribute("data-ofsaver-lic", JSON.stringify(store));
|
||||
}
|
||||
} catch {}
|
||||
return osrh.call(this, k, v);
|
||||
};
|
||||
|
||||
const oo = XMLHttpRequest.prototype.open;
|
||||
const os = XMLHttpRequest.prototype.send;
|
||||
XMLHttpRequest.prototype.open = function (method, url, ...rest) {
|
||||
this.__ofsaverUrl = url;
|
||||
return oo.call(this, method, url, ...rest);
|
||||
};
|
||||
XMLHttpRequest.prototype.send = function (...args) {
|
||||
this.addEventListener("load", () => {
|
||||
try {
|
||||
if (/\/api2\/v2\//.test(String(this.__ofsaverUrl ?? "")) && this.responseText) ingest(this.responseText, this.__ofsaverUrl);
|
||||
} catch {}
|
||||
});
|
||||
return os.apply(this, args);
|
||||
};
|
||||
|
||||
emit();
|
||||
|
||||
// content script can push fetched API data back in (backfills for posts
|
||||
// whose responses happened before this hook installed)
|
||||
window.addEventListener("ofsaver-ingest", (e) => {
|
||||
try { ingest(e.detail); } catch {}
|
||||
});
|
||||
})();
|
||||
556
ext/lib/owndrm.js
Normal file
556
ext/lib/owndrm.js
Normal file
@@ -0,0 +1,556 @@
|
||||
// Own DRM module — drop-in replacement for fanripper's drm.wasm.
|
||||
// Decrypt is AES-128-CTR (cenc) / CBC (cbcs) with per-sample IVs from senc,
|
||||
// verified byte-identical against the wasm. The muxer builds a progressive
|
||||
// MP4 (merged header + interleaved mdat), mirroring MuxPlanner.
|
||||
|
||||
// AES-128 decrypt — equivalent inverse cipher, T-table driven.
|
||||
const S = new Uint8Array(256)
|
||||
const SI = new Uint8Array(256)
|
||||
const xt0 = (a, b) => { let r = 0; while (b) { if (b & 1) r ^= a; a = (a << 1) ^ ((a >> 7) * 0x11b); b >>>= 1 } return r & 255 }
|
||||
const rotl8 = (v, n) => ((v << n) | (v >>> (8 - n))) & 255
|
||||
for (let i = 0; i < 256; i++) {
|
||||
let inv = 0
|
||||
if (i !== 0) { let base = i, e = 254, r = 1; while (e) { if (e & 1) r = xt0(r, base); base = xt0(base, base); e >>= 1 } inv = r }
|
||||
S[i] = inv ^ rotl8(inv, 1) ^ rotl8(inv, 2) ^ rotl8(inv, 3) ^ rotl8(inv, 4) ^ 0x63
|
||||
SI[S[i]] = i
|
||||
}
|
||||
const xt = (a, b) => { let r = 0; while (b) { if (b & 1) r ^= a; a = (a << 1) ^ ((a >> 7) * 0x11b); b >>>= 1 } return r & 255 }
|
||||
const U0 = new Uint32Array(256), U1 = new Uint32Array(256), U2 = new Uint32Array(256), U3 = new Uint32Array(256)
|
||||
for (let i = 0; i < 256; i++) {
|
||||
const s = SI[i]
|
||||
const r0 = xt(s, 0xe), r1 = xt(s, 9), r2 = xt(s, 0xd), r3 = xt(s, 0xb)
|
||||
U0[i] = (r0 << 24) | (r1 << 16) | (r2 << 8) | r3
|
||||
U1[i] = (r3 << 24) | (r0 << 16) | (r1 << 8) | r2
|
||||
U2[i] = (r2 << 24) | (r3 << 16) | (r0 << 8) | r1
|
||||
U3[i] = (r1 << 24) | (r2 << 16) | (r3 << 8) | r0
|
||||
}
|
||||
export function makeKeys(key) {
|
||||
const w = new Uint32Array(44)
|
||||
for (let i = 0; i < 4; i++) w[i] = (key[4*i] << 24) | (key[4*i+1] << 16) | (key[4*i+2] << 8) | key[4*i+3]
|
||||
let rc = 1
|
||||
for (let i = 4; i < 44; i++) {
|
||||
let t = w[i-1]
|
||||
if (i % 4 === 0) {
|
||||
t = ((t << 8) | (t >>> 24)) >>> 0
|
||||
t = (S[t >>> 24] << 24) ^ (S[(t >>> 16) & 255] << 16) ^ (S[(t >>> 8) & 255] << 8) ^ S[t & 255] ^ (rc << 24)
|
||||
rc = xt(rc, 2)
|
||||
}
|
||||
w[i] = w[i-4] ^ t
|
||||
}
|
||||
const dw = new Uint32Array(44)
|
||||
for (let r = 1; r < 10; r++) {
|
||||
for (let c = 0; c < 4; c++) {
|
||||
const col = w[r*4+c]
|
||||
const a0 = col >>> 24, a1 = (col >>> 16) & 255, a2 = (col >>> 8) & 255, a3 = col & 255
|
||||
dw[r*4+c] = ((xt(a0, 14) ^ xt(a1, 11) ^ xt(a2, 13) ^ xt(a3, 9)) << 24) |
|
||||
((xt(a0, 9) ^ xt(a1, 14) ^ xt(a2, 11) ^ xt(a3, 13)) << 16) |
|
||||
((xt(a0, 13) ^ xt(a1, 9) ^ xt(a2, 14) ^ xt(a3, 11)) << 8) |
|
||||
(xt(a0, 11) ^ xt(a1, 13) ^ xt(a2, 9) ^ xt(a3, 14))
|
||||
}
|
||||
}
|
||||
return { w, dw }
|
||||
}
|
||||
/** In-place CBC decrypt of buf[off .. off+len] (len%16 tail copied as-is).
|
||||
* iv: 16-byte initial chain. Returns nothing (mutates buf). */
|
||||
export function cbcDecrypt(buf, off, len, iv, keys) {
|
||||
const { w, dw } = keys
|
||||
const st = new Uint8Array(16)
|
||||
const xti = (a, b) => { let r = 0; while (b) { if (b & 1) r ^= a; a = (a << 1) ^ ((a >> 7) * 0x11b); b >>>= 1 } return r & 255 }
|
||||
const full = Math.floor(len / 16) * 16
|
||||
for (let p = off; p < off + full; p += 16) {
|
||||
const prev = buf.subarray(p, p + 16)
|
||||
const prevCopy = Uint8Array.from(prev)
|
||||
for (let k = 0; k < 16; k++) st[k] = prev[k]
|
||||
const rk = (getWord) => { for (let k = 0; k < 16; k++) st[k] ^= (getWord(k >> 2) >>> ((3 - (k & 3)) * 8)) & 255 }
|
||||
rk((i) => w[40 + i])
|
||||
for (let r = 9; r >= 1; r--) {
|
||||
// InvShiftRows: row j rotates right by j
|
||||
for (let j = 1; j < 4; j++) {
|
||||
const row = [st[j], st[4 + j], st[8 + j], st[12 + j]]
|
||||
const rot = [row[(4 - j) % 4], row[(5 - j) % 4], row[(6 - j) % 4], row[(7 - j) % 4]]
|
||||
st[j] = rot[0]; st[4 + j] = rot[1]; st[8 + j] = rot[2]; st[12 + j] = rot[3]
|
||||
}
|
||||
for (let k = 0; k < 16; k++) st[k] = SI[st[k]]
|
||||
rk((i) => w[r * 4 + i])
|
||||
// InvMixColumns
|
||||
for (let c = 0; c < 4; c++) {
|
||||
const a0 = st[c * 4], a1 = st[c * 4 + 1], a2 = st[c * 4 + 2], a3 = st[c * 4 + 3]
|
||||
st[c * 4] = xti(a0, 14) ^ xti(a1, 11) ^ xti(a2, 13) ^ xti(a3, 9)
|
||||
st[c * 4 + 1] = xti(a0, 9) ^ xti(a1, 14) ^ xti(a2, 11) ^ xti(a3, 13)
|
||||
st[c * 4 + 2] = xti(a0, 13) ^ xti(a1, 9) ^ xti(a2, 14) ^ xti(a3, 11)
|
||||
st[c * 4 + 3] = xti(a0, 11) ^ xti(a1, 13) ^ xti(a2, 9) ^ xti(a3, 14)
|
||||
}
|
||||
}
|
||||
for (let j = 1; j < 4; j++) {
|
||||
const row = [st[j], st[4 + j], st[8 + j], st[12 + j]]
|
||||
const rot = [row[(4 - j) % 4], row[(5 - j) % 4], row[(6 - j) % 4], row[(7 - j) % 4]]
|
||||
st[j] = rot[0]; st[4 + j] = rot[1]; st[8 + j] = rot[2]; st[12 + j] = rot[3]
|
||||
}
|
||||
for (let k = 0; k < 16; k++) st[k] = SI[st[k]]
|
||||
for (let k = 0; k < 16; k++) st[k] ^= (w[k >> 2] >>> ((3 - (k & 3)) * 8)) & 255
|
||||
for (let k = 0; k < 16; k++) buf[p + k] = st[k] ^ iv[k]
|
||||
iv = prevCopy
|
||||
}
|
||||
return iv
|
||||
}
|
||||
|
||||
// forward AES block encrypt (for CTR keystream)
|
||||
const T0 = new Uint32Array(256), T1 = new Uint32Array(256), T2 = new Uint32Array(256), T3 = new Uint32Array(256)
|
||||
for (let i = 0; i < 256; i++) {
|
||||
const s2 = xt(S[i], 2), s3 = xt(S[i], 3)
|
||||
T0[i] = (s2 << 24) | (S[i] << 16) | (S[i] << 8) | s3
|
||||
T1[i] = (s3 << 24) | (s2 << 16) | (S[i] << 8) | S[i]
|
||||
T2[i] = (S[i] << 24) | (s3 << 16) | (s2 << 8) | S[i]
|
||||
T3[i] = (S[i] << 24) | (S[i] << 16) | (s3 << 8) | s2
|
||||
}
|
||||
export function encryptBlock(out, o, inp, i2, keys) {
|
||||
const { w } = keys
|
||||
let s0 = ((inp[i2] << 24) | (inp[i2+1] << 16) | (inp[i2+2] << 8) | inp[i2+3]) ^ w[0]
|
||||
let s1 = ((inp[i2+4] << 24) | (inp[i2+5] << 16) | (inp[i2+6] << 8) | inp[i2+7]) ^ w[1]
|
||||
let s2 = ((inp[i2+8] << 24) | (inp[i2+9] << 16) | (inp[i2+10] << 8) | inp[i2+11]) ^ w[2]
|
||||
let s3 = ((inp[i2+12] << 24) | (inp[i2+13] << 16) | (inp[i2+14] << 8) | inp[i2+15]) ^ w[3]
|
||||
for (let r = 1; r <= 9; r++) {
|
||||
const t0 = T0[s0 >>> 24] ^ T1[(s1 >>> 16) & 255] ^ T2[(s2 >>> 8) & 255] ^ T3[s3 & 255] ^ w[r*4]
|
||||
const t1 = T0[s1 >>> 24] ^ T1[(s2 >>> 16) & 255] ^ T2[(s3 >>> 8) & 255] ^ T3[s0 & 255] ^ w[r*4+1]
|
||||
const t2 = T0[s2 >>> 24] ^ T1[(s3 >>> 16) & 255] ^ T2[(s0 >>> 8) & 255] ^ T3[s1 & 255] ^ w[r*4+2]
|
||||
const t3 = T0[s3 >>> 24] ^ T1[(s0 >>> 16) & 255] ^ T2[(s1 >>> 8) & 255] ^ T3[s2 & 255] ^ w[r*4+3]
|
||||
s0 = t0; s1 = t1; s2 = t2; s3 = t3
|
||||
}
|
||||
const e0 = ((S[s0 >>> 24] << 24) | (S[(s1 >>> 16) & 255] << 16) | (S[(s2 >>> 8) & 255] << 8) | S[s3 & 255]) ^ w[40]
|
||||
const e1 = ((S[s1 >>> 24] << 24) | (S[(s2 >>> 16) & 255] << 16) | (S[(s3 >>> 8) & 255] << 8) | S[s0 & 255]) ^ w[41]
|
||||
const e2 = ((S[s2 >>> 24] << 24) | (S[(s3 >>> 16) & 255] << 16) | (S[(s0 >>> 8) & 255] << 8) | S[s1 & 255]) ^ w[42]
|
||||
const e3 = ((S[s3 >>> 24] << 24) | (S[(s0 >>> 16) & 255] << 16) | (S[(s1 >>> 8) & 255] << 8) | S[s2 & 255]) ^ w[43]
|
||||
const put = (v, k) => { out[o + 4*k] = v >>> 24; out[o + 4*k + 1] = (v >>> 16) & 255; out[o + 4*k + 2] = (v >>> 8) & 255; out[o + 4*k + 3] = v & 255 }
|
||||
put(e0, 0); put(e1, 1); put(e2, 2); put(e3, 3)
|
||||
}
|
||||
|
||||
// ---- box helpers -----------------------------------------------------------
|
||||
function u32(v) { return [(v >>> 24) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255] }
|
||||
function b64bytes(s) { return Uint8Array.from(atob(s), (c) => c.charCodeAt(0)) }
|
||||
|
||||
function parseBoxes(buf, start, end) {
|
||||
const out = []; let i = start
|
||||
while (i + 8 <= end) {
|
||||
let size = ((buf[i] << 24) | (buf[i+1] << 16) | (buf[i+2] << 8) | buf[i+3]) >>> 0
|
||||
const type = String.fromCharCode(buf[i+4], buf[i+5], buf[i+6], buf[i+7])
|
||||
let hdr = 8
|
||||
if (size === 1) { size = Number((BigInt(buf[i+8]) << 56n) | (BigInt(buf[i+9]) << 48n) | (BigInt(buf[i+10]) << 40n) | (BigInt(buf[i+11]) << 32n) | (BigInt(buf[i+12]) << 24n) | (BigInt(buf[i+13]) << 16n) | (BigInt(buf[i+14]) << 8n) | BigInt(buf[i+15])); hdr = 16 }
|
||||
if (size < 8 || i + size > end) break
|
||||
out.push({ type, start: i, end: i + size, hdr })
|
||||
i += size
|
||||
}
|
||||
return out
|
||||
}
|
||||
function child(buf, start, end, type) { return parseBoxes(buf, start, end).find((b) => b.type === type) || null }
|
||||
function sub(buf, b) { return buf.subarray(b.start, b.end) }
|
||||
function box(type, ...parts) {
|
||||
const len = 8 + parts.reduce((n, p) => n + p.length, 0)
|
||||
const out = new Uint8Array(len)
|
||||
out.set(u32(len), 0)
|
||||
out.set([...type].map((c) => c.charCodeAt(0)), 4)
|
||||
let o = 8
|
||||
for (const p of parts) { out.set(p, o); o += p.length }
|
||||
return out
|
||||
}
|
||||
function concat(parts) {
|
||||
const n = parts.reduce((a, p) => a + p.length, 0)
|
||||
const out = new Uint8Array(n)
|
||||
let o = 0
|
||||
for (const p of parts) { out.set(p, o); o += p.length }
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- tenc parsing ----------------------------------------------------------
|
||||
export function stripInit() {}
|
||||
export function initDrmWasm() {}
|
||||
function tencOf(header) {
|
||||
const moov = child(header, 0, header.length, "moov")
|
||||
if (!moov) return null
|
||||
const trak = child(header, moov.start + moov.hdr, moov.end, "trak")
|
||||
if (!trak) return null
|
||||
const mdia = child(header, trak.start + trak.hdr, trak.end, "mdia")
|
||||
const minf = mdia && child(header, mdia.start + mdia.hdr, mdia.end, "minf")
|
||||
const stbl = minf && child(header, minf.start + minf.hdr, minf.end, "stbl")
|
||||
const stsd = stbl && child(header, stbl.start + stbl.hdr, stbl.end, "stsd")
|
||||
if (!stsd) return null
|
||||
for (const entry of parseBoxes(header, stsd.start + stsd.hdr + 8, stsd.end)) {
|
||||
// the entry payload starts with raw sample-entry fields; the encryption
|
||||
// info sits in frma/schm/schi (sometimes wrapped in sinf) — scan for a
|
||||
// valid tenc box by its type bytes instead of walking a box tree
|
||||
for (let p = entry.start + entry.hdr; p + 8 <= entry.end; p++) {
|
||||
if (!(header[p + 4] === 0x74 && header[p + 5] === 0x65 && header[p + 6] === 0x6e && header[p + 7] === 0x63)) continue // "tenc"
|
||||
const start = p
|
||||
const size = ((header[start] << 24) | (header[start + 1] << 16) | (header[start + 2] << 8) | header[start + 3]) >>> 0
|
||||
if (size < 20 || start + size > entry.end) continue
|
||||
return { tenc: { type: "tenc", start, end: start + size, hdr: 8 }, sinf: null }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
export function tencMarker(header) {
|
||||
const t = tencOf(header)
|
||||
if (!t) return -1
|
||||
return header[t.tenc.start + t.tenc.hdr + 7]
|
||||
}
|
||||
export function tencCryptPattern(header) {
|
||||
const t = tencOf(header)
|
||||
if (!t) return undefined
|
||||
const ver = header[t.tenc.start + t.tenc.hdr]
|
||||
if (ver !== 1) return undefined
|
||||
const p = header[t.tenc.start + t.tenc.hdr + 24]
|
||||
const crypt = p >> 4, skip = p & 15
|
||||
return crypt || skip ? [skip, crypt] : undefined
|
||||
}
|
||||
export function tencConstantIv(header) {
|
||||
const t = tencOf(header)
|
||||
if (!t) return undefined
|
||||
const ver = header[t.tenc.start + t.tenc.hdr]
|
||||
if (ver !== 1) return undefined
|
||||
const p = header[t.tenc.start + t.tenc.hdr + 24]
|
||||
const size = header[t.tenc.start + t.tenc.hdr + 25]
|
||||
if (!(p >> 4) || !size) return undefined
|
||||
return header.slice(t.tenc.start + t.tenc.hdr + 26, t.tenc.start + t.tenc.hdr + 26 + size)
|
||||
}
|
||||
|
||||
// ---- fragment decryption ---------------------------------------------------
|
||||
const RENAME = new Set(["pssh", "senc", "saio", "saiz", "sbgp", "sgpd"])
|
||||
|
||||
function parseFragment(frag) {
|
||||
const moof = child(frag, 0, Math.min(frag.length, 1 << 20), "moof")
|
||||
if (!moof) throw new Error("no moof")
|
||||
const traf = child(frag, moof.start + moof.hdr, moof.end, "traf")
|
||||
if (!traf) throw new Error("no traf")
|
||||
let dataOff = null, sizes = [], senc = null
|
||||
for (const b of parseBoxes(frag, traf.start + traf.hdr, traf.end)) {
|
||||
if (b.type === "trun") {
|
||||
const flags = ((frag[b.start + b.hdr + 1] << 16) | (frag[b.start + b.hdr + 2] << 8) | frag[b.start + b.hdr + 3])
|
||||
const count = ((frag[b.start + b.hdr + 4] << 24) | (frag[b.start + b.hdr + 5] << 16) | (frag[b.start + b.hdr + 6] << 8) | frag[b.start + b.hdr + 7]) >>> 0
|
||||
let p = b.start + b.hdr + 8
|
||||
if (flags & 0x1) { dataOff = ((frag[p] << 24) | (frag[p+1] << 16) | (frag[p+2] << 8) | frag[p+3]); p += 4 }
|
||||
if (flags & 0x4) p += 4
|
||||
for (let k = 0; k < count; k++) {
|
||||
if (flags & 0x100) p += 4
|
||||
if (flags & 0x200) { sizes.push(((frag[p] << 24) | (frag[p+1] << 16) | (frag[p+2] << 8) | frag[p+3]) >>> 0); p += 4 } else sizes.push(0)
|
||||
if (flags & 0x400) p += 4
|
||||
if (flags & 0x800) p += 4
|
||||
}
|
||||
}
|
||||
if (b.type === "senc") senc = b
|
||||
}
|
||||
if (!senc) throw new Error("no senc")
|
||||
const payload = frag.subarray(senc.start + senc.hdr, senc.end)
|
||||
const sflags = ((payload[1] << 16) | (payload[2] << 8) | payload[3])
|
||||
const count = ((payload[4] << 24) | (payload[5] << 16) | (payload[6] << 8) | payload[7]) >>> 0
|
||||
let q = 8
|
||||
const samples = []
|
||||
for (let k = 0; k < count; k++) {
|
||||
const iv = payload.slice(q, q + 8); q += 8
|
||||
if (sflags & 0x2) {
|
||||
const nsub = (payload[q] << 8) | payload[q + 1]; q += 2
|
||||
const runs = []
|
||||
for (let s = 0; s < nsub; s++) {
|
||||
runs.push([(payload[q] << 8) | payload[q + 1], ((payload[q+2] << 24) | (payload[q+3] << 16) | (payload[q+4] << 8) | payload[q+5]) >>> 0])
|
||||
q += 6
|
||||
}
|
||||
samples.push({ iv, runs })
|
||||
} else {
|
||||
samples.push({ iv, runs: [[0, sizes[k] || 0]] })
|
||||
}
|
||||
}
|
||||
// rename encryption boxes to free
|
||||
for (const b of parseBoxes(frag, moof.start + moof.hdr, moof.end)) if (RENAME.has(b.type)) frag.set([102, 114, 101, 101], b.start + 4)
|
||||
for (const b of parseBoxes(frag, traf.start + traf.hdr, traf.end)) if (RENAME.has(b.type)) frag.set([102, 114, 101, 101], b.start + 4)
|
||||
return { samples, sizes, dataOff }
|
||||
}
|
||||
|
||||
/** cenc (AES-CTR) — verified byte-identical */
|
||||
export function decryptAndStripFragment(frag, key, marker) {
|
||||
const { samples, sizes, dataOff } = parseFragment(frag)
|
||||
const keys = makeKeys(key)
|
||||
const ctr = new Uint8Array(16)
|
||||
const ks = new Uint8Array(16)
|
||||
let off = 0
|
||||
for (let si = 0; si < samples.length; si++) {
|
||||
const smp = samples[si]
|
||||
let pos = 0
|
||||
let counter = 0n
|
||||
let kpos = 16
|
||||
for (const [clear, prot] of smp.runs) {
|
||||
pos += clear
|
||||
for (let k = 0; k < prot; k++) {
|
||||
if (kpos === 16) {
|
||||
ctr.fill(0)
|
||||
ctr.set(smp.iv, 0)
|
||||
ctr.set([Number((counter >> 56n) & 255n), Number((counter >> 48n) & 255n), Number((counter >> 40n) & 255n), Number((counter >> 32n) & 255n), Number((counter >> 24n) & 255n), Number((counter >> 16n) & 255n), Number((counter >> 8n) & 255n), Number(counter & 255n)], 8)
|
||||
encryptBlock(ks, 0, ctr, 0, keys)
|
||||
counter++
|
||||
kpos = 0
|
||||
}
|
||||
frag[dataOff + off + pos + k] ^= ks[kpos++]
|
||||
}
|
||||
pos += prot
|
||||
}
|
||||
off += sizes[si] || 0
|
||||
}
|
||||
return frag
|
||||
}
|
||||
|
||||
/** cbcs (AES-CBC with pattern) */
|
||||
export function decryptAndStripFragmentCbcs(frag, key, marker, skip, crypt, constantIv) {
|
||||
const { samples, sizes, dataOff } = parseFragment(frag)
|
||||
const keys = makeKeys(key)
|
||||
let off = 0
|
||||
for (let si = 0; si < samples.length; si++) {
|
||||
const smp = samples[si]
|
||||
let iv = new Uint8Array(16)
|
||||
if (constantIv && constantIv.length) iv.set(constantIv)
|
||||
else iv.set(smp.iv.subarray(0, 8), 0)
|
||||
let pos = 0
|
||||
for (const [clear, prot] of smp.runs) {
|
||||
pos += clear
|
||||
let rem = prot
|
||||
while (rem > 0) {
|
||||
const take = Math.min(16, rem)
|
||||
const blk = frag.slice(dataOff + off + pos, dataOff + off + pos + 16)
|
||||
const chain = blk.slice()
|
||||
cbcDecrypt(blk, 0, 16, iv, keys)
|
||||
frag.set(blk.subarray(0, take), dataOff + off + pos)
|
||||
iv = chain
|
||||
pos += take
|
||||
rem -= take
|
||||
}
|
||||
}
|
||||
off += sizes[si] || 0
|
||||
}
|
||||
return frag
|
||||
}
|
||||
|
||||
// ---- progressive muxer (mirrors MuxPlanner) --------------------------------
|
||||
const patchU32 = (b, at, v) => { b[at] = (v >>> 24) & 255; b[at+1] = (v >>> 16) & 255; b[at+2] = (v >>> 8) & 255; b[at+3] = v & 255 }
|
||||
const readU32 = (b, o) => ((b[o] << 24) | (b[o+1] << 16) | (b[o+2] << 8) | b[o+3]) >>> 0
|
||||
const u64 = (v) => [...u32(Math.floor(v / 2 ** 32)), ...u32(v >>> 0)]
|
||||
const pad4 = (v) => v >>> 0
|
||||
function fullbox(type, ver, ...parts) { return box(type, new Uint8Array([ver & 255, 0, 0, 0]), ...parts) }
|
||||
|
||||
function trackParts(header) {
|
||||
const moov = child(header, 0, header.length, "moov")
|
||||
const trak = child(header, moov.start + moov.hdr, moov.end, "trak")
|
||||
const tkhd = child(header, trak.start + trak.hdr, trak.end, "tkhd")
|
||||
const mdia = child(header, trak.start + trak.hdr, trak.end, "mdia")
|
||||
const mdhd = child(header, mdia.start + mdia.hdr, mdia.end, "mdhd")
|
||||
const hdlr = child(header, mdia.start + mdia.hdr, mdia.end, "hdlr")
|
||||
const minf = child(header, mdia.start + mdia.hdr, mdia.end, "minf")
|
||||
const stbl = child(header, minf.start + minf.hdr, minf.end, "stbl")
|
||||
return {
|
||||
moov,
|
||||
tkhd: sub(header, tkhd),
|
||||
mdhd: sub(header, mdhd),
|
||||
hdlr: sub(header, hdlr),
|
||||
vmhd: (() => { const b = child(header, minf.start + minf.hdr, minf.end, "vmhd"); return b && sub(header, b) })(),
|
||||
smhd: (() => { const b = child(header, minf.start + minf.hdr, minf.end, "smhd"); return b && sub(header, b) })(),
|
||||
dinf: sub(header, child(header, minf.start + minf.hdr, minf.end, "dinf")),
|
||||
stsd: sub(header, child(header, stbl.start + stbl.hdr, stbl.end, "stsd")),
|
||||
timescale: readU32(header, mdhd.start + mdhd.hdr + 12),
|
||||
mvhd: null,
|
||||
ftyp: null,
|
||||
}
|
||||
}
|
||||
|
||||
function moofSamples(moof) {
|
||||
const traf = child(moof, 8, moof.length, "traf")
|
||||
const trun = child(moof, traf.start + traf.hdr, traf.end, "trun")
|
||||
const p = (trun.start + trun.hdr)
|
||||
const flags = (moof[p+1] << 16) | (moof[p+2] << 8) | moof[p+3]
|
||||
const count = readU32(moof, p + 4)
|
||||
let q = p + 8
|
||||
if (flags & 0x1) q += 4
|
||||
let firstFlags = 0
|
||||
if (flags & 0x4) { firstFlags = readU32(moof, q); q += 4 }
|
||||
const samples = []
|
||||
let sizeSum = 0
|
||||
for (let k = 0; k < count; k++) {
|
||||
const dur = flags & 0x100 ? readU32(moof, q) : 0
|
||||
if (flags & 0x100) q += 4
|
||||
const size = flags & 0x200 ? readU32(moof, q) : 0
|
||||
if (flags & 0x200) q += 4
|
||||
const sflags = flags & 0x400 ? readU32(moof, q) : (k === 0 ? firstFlags : 0)
|
||||
if (flags & 0x400) q += 4
|
||||
let comp = 0
|
||||
if (flags & 0x800) { const raw = readU32(moof, q); comp = raw | 0; q += 4 }
|
||||
samples.push({ dur, size, flags: sflags, comp, sync: k === 0 })
|
||||
sizeSum += size
|
||||
}
|
||||
return { samples, sizeSum }
|
||||
}
|
||||
|
||||
function rle(values) {
|
||||
const out = []
|
||||
let i = 0
|
||||
while (i < values.length) {
|
||||
let j = i
|
||||
while (j + 1 < values.length && values[j + 1] === values[i]) j++
|
||||
out.push([j - i + 1, values[i]])
|
||||
i = j + 1
|
||||
}
|
||||
return out
|
||||
}
|
||||
const sttsOf = (samples) => { const r = rle(samples.map((s) => s.dur)); return fullbox("stts", 0, u32(r.length), ...r.flatMap(([c, d]) => [u32(c), u32(d)])) }
|
||||
const cttsOf = (samples) => { const r = rle(samples.map((s) => s.comp)); return fullbox("ctts", 1, u32(r.length), ...r.flatMap(([c, d]) => [u32(c), u32(d)])) }
|
||||
const stssOf = (samples) => {
|
||||
const sync = []
|
||||
samples.forEach((s, i) => { if (s.sync && !(s.flags & 0x10000)) sync.push(u32(i + 1)) })
|
||||
return fullbox("stss", 0, u32(sync.length), ...sync)
|
||||
}
|
||||
const stscOf = (chunks) => {
|
||||
const r = rle(chunks.map((c) => c[2]))
|
||||
let chunkNo = 1
|
||||
const parts = []
|
||||
for (const [count, per] of r) { parts.push(u32(chunkNo), u32(per), u32(1)); chunkNo += count }
|
||||
return fullbox("stsc", 0, u32(r.length), ...parts)
|
||||
}
|
||||
const stszOf = (samples) => fullbox("stsz", 0, u32(0), u32(samples.length), ...samples.map((s) => u32(s.size)))
|
||||
const co64Of = (chunks) => fullbox("co64", 0, u32(chunks.length), ...chunks.map(() => new Uint8Array(8)))
|
||||
|
||||
export class MuxPlanner {
|
||||
constructor(videoHeader, audioHeader) {
|
||||
this.v = trackParts(videoHeader)
|
||||
this.v.ftyp = sub(videoHeader, child(videoHeader, 0, videoHeader.length, "ftyp"))
|
||||
this.v.mvhd = sub(videoHeader, child(videoHeader, this.v.moov.start + this.v.moov.hdr, this.v.moov.end, "mvhd"))
|
||||
this.a = audioHeader ? trackParts(audioHeader) : null
|
||||
this.vs = []
|
||||
this.as = []
|
||||
this.vchunks = []
|
||||
this.achunks = []
|
||||
}
|
||||
pushVideoMoof(moof, offset) {
|
||||
const s = moofSamples(moof)
|
||||
this.vs.push(...s.samples)
|
||||
this.vchunks.push([offset + moof.length + 8, s.sizeSum, s.samples.length])
|
||||
}
|
||||
pushAudioMoof(moof, offset) {
|
||||
const s = moofSamples(moof)
|
||||
this.as.push(...s.samples)
|
||||
this.achunks.push([offset + moof.length + 8, s.sizeSum, s.samples.length])
|
||||
}
|
||||
finish() {
|
||||
const vDur = this.vs.reduce((n, s) => n + s.dur, 0)
|
||||
const aDur = this.as.reduce((n, s) => n + s.dur, 0)
|
||||
const movieTs = this.v.timescale
|
||||
const vFirstDur = this.vs.length ? this.vs[0].dur : 1
|
||||
const vTrackDur = vDur + vFirstDur
|
||||
const aTrackDur = this.a ? Math.round(aDur * movieTs / this.a.timescale) : 0
|
||||
const movieDur = Math.max(vTrackDur, aTrackDur)
|
||||
const trackCount = this.a ? 2 : 1
|
||||
|
||||
// --- layout: interleave chunks video/audio ---
|
||||
const layout = []
|
||||
const n = Math.max(this.vchunks.length, this.achunks.length)
|
||||
for (let k = 0; k < n; k++) {
|
||||
const vc = this.vchunks[k]
|
||||
if (vc) layout.push(1, vc[0], vc[1])
|
||||
const ac = this.achunks[k]
|
||||
if (ac) layout.push(0, ac[0], ac[1])
|
||||
}
|
||||
|
||||
// --- build header with placeholder co64 + mdat header (16B, 64-bit size) ---
|
||||
const mdatPayload = layout.reduce((sum, val, i) => (i % 3 === 2 ? sum + val : sum), 0)
|
||||
const vTkhd = this.v.tkhd.slice()
|
||||
patchU32(vTkhd, 8 + 12, 1)
|
||||
patchU32(vTkhd, 8 + 20, vTrackDur)
|
||||
const mdhdV = this.v.mdhd.slice()
|
||||
patchU32(mdhdV, 8 + 12, movieTs)
|
||||
patchU32(mdhdV, 8 + 16, vDur)
|
||||
const elstEntries = [u32(vFirstDur), u32(0xffffffff), u32(0x00010000), u32(vDur), u32(vFirstDur), u32(0x00010000)]
|
||||
const edts = box("edts", fullbox("elst", 0, u32(2), ...elstEntries))
|
||||
// sample entries must be plain avc1/mp4a — the source stsd may be the
|
||||
// encrypted encv/enca variant, which players like AVFoundation refuse
|
||||
const stsdV = this.v.stsd.slice()
|
||||
if (stsdV[20] === 0x65 && stsdV[21] === 0x6e && stsdV[22] === 0x63 && stsdV[23] === 0x76) stsdV.set([97, 118, 99, 49], 20) // encv -> avc1
|
||||
const co64V = co64Of(this.vchunks)
|
||||
const stblV = box("stbl", stsdV, sttsOf(this.vs), cttsOf(this.vs), stssOf(this.vs), stscOf(this.vchunks), stszOf(this.vs), co64V)
|
||||
const minfV = box("minf", this.v.vmhd, this.v.dinf, stblV)
|
||||
const mdiaV = box("mdia", mdhdV, this.v.hdlr, minfV)
|
||||
const trakV = box("trak", vTkhd, edts, mdiaV)
|
||||
|
||||
let trakA = null
|
||||
let co64A = null
|
||||
if (this.a) {
|
||||
const aTkhd = this.a.tkhd.slice()
|
||||
patchU32(aTkhd, 8 + 12, 2)
|
||||
patchU32(aTkhd, 8 + 20, aTrackDur)
|
||||
const stsdA = this.a.stsd.slice()
|
||||
if (stsdA[20] === 0x65 && stsdA[21] === 0x6e && stsdA[22] === 0x63 && stsdA[23] === 0x61) stsdA.set([109, 112, 52, 97], 20) // enca -> mp4a
|
||||
co64A = co64Of(this.achunks)
|
||||
const stblA = box("stbl", stsdA, sttsOf(this.as), stscOf(this.achunks), stszOf(this.as), co64A)
|
||||
const minfA = box("minf", this.a.smhd, this.a.dinf, stblA)
|
||||
const mdiaA = box("mdia", this.a.mdhd, this.a.hdlr, minfA)
|
||||
trakA = box("trak", aTkhd, mdiaA)
|
||||
}
|
||||
|
||||
const mvhd = this.v.mvhd.slice()
|
||||
patchU32(mvhd, 8 + 16, movieDur)
|
||||
patchU32(mvhd, 8 + 96, trackCount + 1)
|
||||
const moov = box("moov", mvhd, trakV, ...(trakA ? [trakA] : []))
|
||||
const header = concat([this.v.ftyp, moov])
|
||||
|
||||
// patch real chunk offsets (header len + 16-byte ftyp?? no — mdat header 16)
|
||||
const mdatStart = header.length + 16
|
||||
// patch real chunk offsets into the finished header's co64 boxes
|
||||
const mdatStart2 = header.length + 16
|
||||
const co64s = []
|
||||
const collect = (start2, end2) => {
|
||||
for (const b of parseBoxes(header, start2, end2)) {
|
||||
if (b.type === "co64") co64s.push(b)
|
||||
if (["moov","trak","mdia","minf","stbl"].includes(b.type)) collect(b.start + b.hdr, b.end)
|
||||
}
|
||||
}
|
||||
collect(0, header.length)
|
||||
const vo2 = [0, 0]
|
||||
let cum2 = 0
|
||||
let ci = 0
|
||||
for (let k = 0; k < n; k++) {
|
||||
const vc = this.vchunks[k]
|
||||
if (vc) {
|
||||
const b = co64s[0]
|
||||
const off = mdatStart2 + cum2
|
||||
patchU32(header, b.start + 16 + vo2[0], 0)
|
||||
patchU32(header, b.start + 16 + vo2[0] + 4, off)
|
||||
vo2[0] += 8
|
||||
cum2 += vc[1]
|
||||
}
|
||||
const ac = this.achunks[k]
|
||||
if (ac) {
|
||||
const b = co64s[1]
|
||||
if (b) {
|
||||
const off = mdatStart2 + cum2
|
||||
patchU32(header, b.start + 16 + vo2[1], 0)
|
||||
patchU32(header, b.start + 16 + vo2[1] + 4, off)
|
||||
vo2[1] += 8
|
||||
}
|
||||
cum2 += ac[1]
|
||||
}
|
||||
}
|
||||
ci = 0
|
||||
// header byte sizes must be unchanged by patching — they are.
|
||||
|
||||
const mdatHeader = new Uint8Array(16)
|
||||
mdatHeader.set(u32(1), 0)
|
||||
mdatHeader.set([109, 100, 97, 116], 4) // mdat
|
||||
const total = 16 + mdatPayload
|
||||
mdatHeader.set(u64(total).slice(4), 8) // 64-bit size low half?? fixed below
|
||||
mdatHeader.set([...u32(Math.floor(total / 2 ** 32)), ...u32(total >>> 0)], 8)
|
||||
const full = concat([header, mdatHeader])
|
||||
return new MuxResult(full, layout, mdatHeader)
|
||||
}
|
||||
}
|
||||
|
||||
class MuxResult {
|
||||
constructor(header, layout, mdatHeader) {
|
||||
this._h = header
|
||||
this._l = layout
|
||||
this._m = mdatHeader
|
||||
}
|
||||
header() { return this._h }
|
||||
layout() { return this._l }
|
||||
mdatHeader() { return this._m }
|
||||
}
|
||||
100
ext/lib/paths.js
Normal file
100
ext/lib/paths.js
Normal file
@@ -0,0 +1,100 @@
|
||||
// Folder/filename scheme builder, shared by background + options preview.
|
||||
// Folder and file naming schemes.
|
||||
|
||||
export const SINGLE_SCHEMES = {
|
||||
one: { label: "One folder", desc: "Saves go straight into Downloads.", folders: [] },
|
||||
creator: { label: "By creator", desc: "A folder for each creator.", folders: ["{creator}"] },
|
||||
"creator-type": {
|
||||
label: "By creator and type",
|
||||
rec: true,
|
||||
desc: "A folder per creator, with Videos, Photos and Audio inside.",
|
||||
folders: ["{creator}", "{typeFolder}"],
|
||||
},
|
||||
"site-creator-type": {
|
||||
label: "By site, creator and type",
|
||||
desc: "Like By creator and type, with a folder for each site on top.",
|
||||
folders: ["OnlyFans", "{creator}", "{typeFolder}"],
|
||||
},
|
||||
};
|
||||
|
||||
export const BULK_SCHEMES = {
|
||||
"creator-section-type": {
|
||||
label: "By creator, section and type",
|
||||
rec: true,
|
||||
desc: "A folder per creator, then Timeline, Messages, Paid… with Videos and Photos inside.",
|
||||
folders: ["{creator}", "{section}", "{typeFolder}"],
|
||||
},
|
||||
same: { label: "Same as single downloads", desc: "Bulk downloads fill the folders your single downloads use.", same: true },
|
||||
"creator-date-section": {
|
||||
label: "By creator, date and section (classic)",
|
||||
desc: "A folder for the day each run starts, split by section.",
|
||||
folders: ["{creator}", "{date}", "{section}"],
|
||||
},
|
||||
one: { label: "One folder", desc: "Saves go straight into Downloads.", folders: [] },
|
||||
};
|
||||
|
||||
const TYPE_FOLDERS = { video: "Videos", photo: "Photos", gif: "Photos", audio: "Audio" };
|
||||
|
||||
/** Build the full download path (relative to Downloads).
|
||||
* opts: { scheme, bulk, creator, type, section, date(ts s|Date|str), timestamp, mediaId, postId, quality, ext, template } */
|
||||
export function buildPath(opts) {
|
||||
const scheme = opts.scheme ?? "creator-type";
|
||||
const def = opts.bulk ? BULK_SCHEMES[scheme] ?? BULK_SCHEMES.same : SINGLE_SCHEMES[scheme] ?? SINGLE_SCHEMES["creator-type"];
|
||||
const folders = def.same ? (SINGLE_SCHEMES[opts.singleScheme ?? "creator-type"] ?? SINGLE_SCHEMES["creator-type"]).folders : def.folders;
|
||||
|
||||
const type = opts.type ?? "video";
|
||||
const typeFolder = TYPE_FOLDERS[type] ?? "Other";
|
||||
const date = formatDate(opts.date);
|
||||
const creator = sanitize(opts.creator ?? "unknown");
|
||||
|
||||
const parts = folders.map((f) =>
|
||||
sanitize(
|
||||
f
|
||||
.replaceAll("{creator}", creator)
|
||||
.replaceAll("{typeFolder}", typeFolder)
|
||||
.replaceAll("{section}", sanitize(opts.section ?? "Timeline"))
|
||||
.replaceAll("{date}", date)
|
||||
)
|
||||
);
|
||||
|
||||
const name = buildName(opts);
|
||||
return [...parts, name].filter(Boolean).join("/");
|
||||
}
|
||||
|
||||
export function buildName(opts) {
|
||||
const type = opts.type ?? "video";
|
||||
const template = opts.template ?? "{creator}_{type}_{date}_{timestamp}_{mediaId}_{quality}";
|
||||
const out = template
|
||||
.replaceAll("{creator}", sanitize(opts.creator ?? "unknown"))
|
||||
.replaceAll("{type}", type)
|
||||
.replaceAll("{date}", formatDate(opts.date))
|
||||
.replaceAll("{timestamp}", String(opts.timestamp ?? Math.floor(Date.now() / 1000)))
|
||||
.replaceAll("{mediaId}", String(opts.mediaId ?? ""))
|
||||
.replaceAll("{postId}", String(opts.postId ?? ""))
|
||||
.replaceAll("{quality}", opts.quality ?? "")
|
||||
.replaceAll("{ext}", opts.ext ?? "mp4")
|
||||
.replace(/_+(\.)/g, "$1")
|
||||
.replace(/_{2,}/g, "_");
|
||||
const out2 = sanitize(out);
|
||||
// always end with a sensible extension
|
||||
const ext = (opts.ext ?? "mp4").replace(/^\./, "");
|
||||
return out2.toLowerCase().endsWith("." + ext.toLowerCase()) ? out2 : `${out2.replace(/_+$/, "")}.${ext}`;
|
||||
}
|
||||
|
||||
function formatDate(d) {
|
||||
if (!d) return "";
|
||||
let date;
|
||||
if (d instanceof Date) date = d;
|
||||
else if (typeof d === "number") date = new Date(d * (d > 1e12 ? 1 : 1000));
|
||||
else {
|
||||
const parsed = Date.parse(d);
|
||||
if (Number.isNaN(parsed)) return sanitize(String(d));
|
||||
date = new Date(parsed);
|
||||
}
|
||||
const p = (n) => String(n).padStart(2, "0");
|
||||
return `${date.getFullYear()}-${p(date.getMonth() + 1)}-${p(date.getDate())}`;
|
||||
}
|
||||
|
||||
function sanitize(s) {
|
||||
return String(s ?? "").replace(/[^\w.-]+/g, "_").replace(/^\.+/, "_");
|
||||
}
|
||||
104
ext/lib/pb.js
Normal file
104
ext/lib/pb.js
Normal file
@@ -0,0 +1,104 @@
|
||||
/** Minimal protobuf wire-format writer/reader (widevine messages) — Uint8Array only (browser-safe). */
|
||||
|
||||
export function varint(n) {
|
||||
const out = [];
|
||||
let v = BigInt(n);
|
||||
while (v > 0x7fn) {
|
||||
out.push(Number((v & 0x7fn) | 0x80n));
|
||||
v >>= 7n;
|
||||
}
|
||||
out.push(Number(v));
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
export function tag(field, wire) {
|
||||
return varint((field << 3) | wire);
|
||||
}
|
||||
|
||||
export function pbVarint(field, value) {
|
||||
return concat(tag(field, 0), varint(value));
|
||||
}
|
||||
|
||||
export function pbBytes(field, buf) {
|
||||
return concat(tag(field, 2), varint(buf.length), buf);
|
||||
}
|
||||
|
||||
export function pbString(field, str) {
|
||||
return pbBytes(field, new TextEncoder().encode(str));
|
||||
}
|
||||
|
||||
/** Concatenate pre-encoded fields. */
|
||||
export function pbMsg(...parts) {
|
||||
return concat(...parts);
|
||||
}
|
||||
|
||||
export function concat(...arrays) {
|
||||
const len = arrays.reduce((n, a) => n + a.length, 0);
|
||||
const out = new Uint8Array(len);
|
||||
let o = 0;
|
||||
for (const a of arrays) { out.set(a, o); o += a.length; }
|
||||
return out;
|
||||
}
|
||||
|
||||
export function tryParse(buf) {
|
||||
const out = [];
|
||||
let i = 0;
|
||||
while (i < buf.length) {
|
||||
let key = 0, shift = 0;
|
||||
while (true) {
|
||||
if (i >= buf.length) return null;
|
||||
const b = buf[i++];
|
||||
key |= (b & 0x7f) << shift;
|
||||
if (!(b & 0x80)) break;
|
||||
shift += 7;
|
||||
if (shift > 35) return null;
|
||||
}
|
||||
const field = key >> 3, wire = key & 7;
|
||||
if (field === 0) return null;
|
||||
if (wire === 0) {
|
||||
let v = 0n, s = 0n;
|
||||
while (true) {
|
||||
if (i >= buf.length) return null;
|
||||
const b = buf[i++];
|
||||
v |= BigInt(b & 0x7f) << s;
|
||||
if (!(b & 0x80)) break;
|
||||
s += 7n;
|
||||
}
|
||||
out.push([field, 0, v]);
|
||||
} else if (wire === 1) {
|
||||
if (i + 8 > buf.length) return null;
|
||||
out.push([field, 1, buf.slice(i, i + 8)]);
|
||||
i += 8;
|
||||
} else if (wire === 2) {
|
||||
let len = 0, sh = 0;
|
||||
while (true) {
|
||||
if (i >= buf.length) return null;
|
||||
const b = buf[i++];
|
||||
len |= (b & 0x7f) << sh;
|
||||
if (!(b & 0x80)) break;
|
||||
sh += 7;
|
||||
if (sh > 30) return null;
|
||||
}
|
||||
if (i + len > buf.length) return null;
|
||||
out.push([field, 2, buf.slice(i, i + len)]);
|
||||
i += len;
|
||||
} else if (wire === 5) {
|
||||
if (i + 4 > buf.length) return null;
|
||||
out.push([field, 5, buf.slice(i, i + 4)]);
|
||||
i += 4;
|
||||
} else return null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Get field values: getAll(buf, field) → array of values. */
|
||||
export function getAll(buf, field) {
|
||||
const fields = tryParse(buf);
|
||||
if (!fields) return [];
|
||||
return fields.filter(([f]) => f === field).map(([, , v]) => v);
|
||||
}
|
||||
|
||||
export function get(buf, field) {
|
||||
const all = getAll(buf, field);
|
||||
return all.length ? all[0] : undefined;
|
||||
}
|
||||
4
ext/lib/signer-module.js
Normal file
4
ext/lib/signer-module.js
Normal file
File diff suppressed because one or more lines are too long
222
ext/lib/signer.js
Normal file
222
ext/lib/signer.js
Normal file
@@ -0,0 +1,222 @@
|
||||
// Live OF request signer — port of ofsaver's ofrules.js for the offscreen
|
||||
// document (eval allowed via relaxed CSP). In-memory cache per revision.
|
||||
|
||||
const BUNDLE_ROOT = "https://static2.onlyfans.com/static/prod/f";
|
||||
const REV_ENDPOINT = "https://onlyfans.com/api2/v2/ip";
|
||||
const RC4_ALPHABET =
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=";
|
||||
export const APP_TOKEN = "33d57ade8c02dbc5a333db99ff9ae26a";
|
||||
|
||||
// --- sync SHA-1 (hex) — the signer's dep is called synchronously ----------
|
||||
export function sha1hex(text) {
|
||||
const msg = new TextEncoder().encode(text);
|
||||
const ml = msg.length;
|
||||
const padded = new Uint8Array((((ml + 8) >> 6) + 1) << 6);
|
||||
padded.set(msg);
|
||||
padded[ml] = 0x80;
|
||||
const bitLen = ml * 8;
|
||||
const dv = new DataView(padded.buffer);
|
||||
dv.setUint32(padded.length - 4, bitLen >>> 0);
|
||||
dv.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
|
||||
let h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0;
|
||||
const w = new Uint32Array(80);
|
||||
const rol = (x, n) => (x << n) | (x >>> (32 - n));
|
||||
for (let i = 0; i < padded.length; i += 64) {
|
||||
for (let j = 0; j < 16; j++) w[j] = dv.getUint32(i + j * 4);
|
||||
for (let j = 16; j < 80; j++) w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
|
||||
let a = h0, b = h1, c = h2, d = h3, e = h4;
|
||||
for (let j = 0; j < 80; j++) {
|
||||
let f, k;
|
||||
if (j < 20) { f = (b & c) | (~b & d); k = 0x5a827999; }
|
||||
else if (j < 40) { f = b ^ c ^ d; k = 0x6ed9eba1; }
|
||||
else if (j < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8f1bbcdc; }
|
||||
else { f = b ^ c ^ d; k = 0xca62c1d6; }
|
||||
const t = (rol(a, 5) + f + e + k + w[j]) >>> 0;
|
||||
e = d; d = c; c = rol(b, 30); b = a; a = t;
|
||||
}
|
||||
h0 = (h0 + a) >>> 0; h1 = (h1 + b) >>> 0; h2 = (h2 + c) >>> 0; h3 = (h3 + d) >>> 0; h4 = (h4 + e) >>> 0;
|
||||
}
|
||||
return [h0, h1, h2, h3, h4].map((x) => x.toString(16).padStart(8, "0")).join("");
|
||||
}
|
||||
|
||||
export function pathGet(obj, path, fallback) {
|
||||
if (obj == null) return fallback;
|
||||
let cur = obj;
|
||||
for (const key of String(path).split(".")) {
|
||||
if (cur == null) return fallback;
|
||||
cur = cur[key];
|
||||
}
|
||||
return cur === undefined ? fallback : cur;
|
||||
}
|
||||
|
||||
export async function fetchRevision() {
|
||||
const res = await fetch(REV_ENDPOINT, { method: "HEAD", signal: AbortSignal.timeout(10_000) });
|
||||
const rev = res.headers.get("x-of-rev");
|
||||
if (!rev) throw new Error("no x-of-rev header on /api2/v2/ip response");
|
||||
return rev;
|
||||
}
|
||||
|
||||
export function extractChunkRenameMap(appJs) {
|
||||
const marker = '}[e]||e)+".js"';
|
||||
const idx = appJs.indexOf(marker);
|
||||
if (idx === -1) throw new Error("chunk map not found in app.js");
|
||||
const start = appJs.lastIndexOf("({", idx) + 1;
|
||||
const literal = appJs.slice(start, idx);
|
||||
const map = {};
|
||||
for (const m of literal.matchAll(/(\d+):"([^"]+)"/g)) map[m[1]] = m[2];
|
||||
return map;
|
||||
}
|
||||
|
||||
export function extractInitialChunkIds(appJs) {
|
||||
const m = appJs.match(/\.O\(void 0,\[([\d,]+)\]/);
|
||||
if (!m) throw new Error("initial chunk list not found in app.js");
|
||||
return m[1].split(",").filter(Boolean);
|
||||
}
|
||||
|
||||
export function extractModuleSource(chunkText, moduleId) {
|
||||
const key = `${moduleId}:function(`;
|
||||
const start = chunkText.indexOf(key);
|
||||
if (start === -1) return null;
|
||||
const fnStart = start + moduleId.length + 1;
|
||||
const bodyStart = chunkText.indexOf("{", fnStart);
|
||||
let depth = 0, inStr = null, esc = false;
|
||||
for (let i = bodyStart; i < chunkText.length; i++) {
|
||||
const ch = chunkText[i];
|
||||
if (esc) { esc = false; continue; }
|
||||
if (inStr) {
|
||||
if (ch === "\\") esc = true;
|
||||
else if (ch === inStr) inStr = null;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' || ch === "'" || ch === "`") { inStr = ch; continue; }
|
||||
if (ch === "{") depth++;
|
||||
else if (ch === "}") {
|
||||
depth--;
|
||||
if (depth === 0) return chunkText.slice(fnStart, i + 1);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function moduleIdBefore(chunkText, markerIndex) {
|
||||
const re = /(\d+):function\(/g;
|
||||
let last = null, m;
|
||||
while ((m = re.exec(chunkText)) && m.index < markerIndex) last = m;
|
||||
return last ? last[1] : null;
|
||||
}
|
||||
|
||||
function makeRequire(table) {
|
||||
const cache = {};
|
||||
const req = (id) => {
|
||||
if (cache[id]) return cache[id].exports;
|
||||
const fn = table[id];
|
||||
if (!fn) throw new Error("missing module " + id);
|
||||
const mod = { exports: {} };
|
||||
cache[id] = mod;
|
||||
fn.call(mod.exports, mod, mod.exports, req);
|
||||
return mod.exports;
|
||||
};
|
||||
req.d = (exports, definition) => {
|
||||
for (const key in definition)
|
||||
if (!Object.prototype.hasOwnProperty.call(exports, key) &&
|
||||
Object.prototype.hasOwnProperty.call(definition, key))
|
||||
Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
|
||||
};
|
||||
req.n = (module) => {
|
||||
const getter = module && module.__esModule ? () => module.default : () => module;
|
||||
req.d(getter, { a: getter });
|
||||
return getter;
|
||||
};
|
||||
req.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
|
||||
req.r = (exports) => {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
};
|
||||
return req;
|
||||
}
|
||||
|
||||
function makeUniversalDep(userIdHolder) {
|
||||
const dep = function (a, b, c) {
|
||||
if (b === undefined) return sha1hex(String(a));
|
||||
return pathGet(a, b, c);
|
||||
};
|
||||
dep.A = {
|
||||
get getters() { return { "auth/authUserId": userIdHolder.value }; },
|
||||
};
|
||||
return dep;
|
||||
}
|
||||
|
||||
import signerFactoryDefault from "./signer-module.js";
|
||||
|
||||
async function registerSigner(table, signerModuleId, signerSource, userIdHolder) {
|
||||
const t = { ...table };
|
||||
const header = signerSource.slice(0, 800);
|
||||
for (const m of header.matchAll(/([A-Za-z_$][\w$]*)=t\((\d+)\)/g)) {
|
||||
const id = m[2];
|
||||
t[id] = (module) => { module.exports = makeUniversalDep(userIdHolder); };
|
||||
}
|
||||
t[signerModuleId] = signerFactoryDefault;
|
||||
return t;
|
||||
}
|
||||
|
||||
const bundleCache = new Map(); // rev -> {appJs, chunks: Map}
|
||||
async function cachedFetch(rev, name, url) {
|
||||
let entry = bundleCache.get(rev);
|
||||
if (!entry) { entry = { chunks: new Map() }; bundleCache.set(rev, entry); }
|
||||
if (name === "app.js") {
|
||||
if (!entry.appJs) entry.appJs = await (await fetch(url, { signal: AbortSignal.timeout(60_000) })).text();
|
||||
return entry.appJs;
|
||||
}
|
||||
if (!entry.chunks.has(name)) {
|
||||
entry.chunks.set(name, await (await fetch(url, { signal: AbortSignal.timeout(60_000) })).text());
|
||||
}
|
||||
return entry.chunks.get(name);
|
||||
}
|
||||
|
||||
/** Build the live signer: { revision, appToken, sign(urlPath, userId) }. */
|
||||
export async function loadLiveSigner(log = () => {}) {
|
||||
if (typeof globalThis.window === "undefined") globalThis.window = globalThis;
|
||||
const rev = await fetchRevision();
|
||||
log(`bundle revision: ${rev}`);
|
||||
|
||||
const appJs = await cachedFetch(rev, "app.js", `${BUNDLE_ROOT}/${rev}/app.js`);
|
||||
const renameMap = extractChunkRenameMap(appJs);
|
||||
const initialIds = extractInitialChunkIds(appJs);
|
||||
log(`initial chunks: ${initialIds.length}`);
|
||||
|
||||
const userIdHolder = { value: "0" };
|
||||
for (const id of initialIds) {
|
||||
const name = renameMap[id] ?? id;
|
||||
let text;
|
||||
try {
|
||||
text = await cachedFetch(rev, `${name}.js`, `${BUNDLE_ROOT}/${rev}/${name}.js`);
|
||||
} catch { continue; }
|
||||
const markerIdx = text.indexOf(RC4_ALPHABET);
|
||||
if (markerIdx === -1) continue;
|
||||
const moduleId = moduleIdBefore(text, markerIdx);
|
||||
if (!moduleId) continue;
|
||||
const source = extractModuleSource(text, moduleId);
|
||||
if (!source || !/\.A\s*=/.test(source)) continue;
|
||||
try {
|
||||
const table = await registerSigner({}, moduleId, source, userIdHolder);
|
||||
const signer = makeRequire(table)(moduleId);
|
||||
if (typeof signer.A !== "function") continue;
|
||||
userIdHolder.value = "0";
|
||||
const probe = signer.A({ url: "/api2/v2/users/me" });
|
||||
if (!probe || typeof probe.sign !== "string" || probe.sign.split(":").length < 3 || !probe.time) continue;
|
||||
log(`signer module ${moduleId} active from chunk ${name}.js`);
|
||||
return {
|
||||
mode: "bundle",
|
||||
revision: rev,
|
||||
appToken: APP_TOKEN,
|
||||
sign(urlPath, userId) {
|
||||
userIdHolder.value = String(userId ?? "0");
|
||||
const out = signer.A({ url: urlPath });
|
||||
return { sign: out.sign, time: String(out.time) };
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
log(`candidate chunk ${name}.js failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
throw new Error("signer module not found in any initial chunk");
|
||||
}
|
||||
220
ext/lib/wv.js
Normal file
220
ext/lib/wv.js
Normal file
@@ -0,0 +1,220 @@
|
||||
// Widevine L3 DRM core for the browser (WebCrypto port of ofsaver's src/drm).
|
||||
// Same protocol as ofsaver: classic device blob, PSS-SHA1 challenge signature,
|
||||
// CMAC key derivation, AES-CBC key unwrap, HMAC license verify.
|
||||
import { CLIENT_BLOB_B64, PRIVATE_KEY_DER_B64 } from "./device.js";
|
||||
import { pbMsg, pbBytes, pbVarint, pbString, tryParse, get, getAll } from "./pb.js";
|
||||
|
||||
// ---- crypto helpers ----------------------------------------------------
|
||||
|
||||
const b64ToBytes = (b64) => {
|
||||
const bin = atob(b64);
|
||||
const out = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
||||
return out;
|
||||
};
|
||||
const bytesToB64 = (bytes) => {
|
||||
let s = "";
|
||||
for (const b of bytes) s += String.fromCharCode(b);
|
||||
return btoa(s);
|
||||
};
|
||||
|
||||
let signKeyPromise = null, decKeyPromise = null;
|
||||
function rsaSignKey() {
|
||||
if (!signKeyPromise) {
|
||||
signKeyPromise = crypto.subtle.importKey(
|
||||
"pkcs8", b64ToBytes(PRIVATE_KEY_DER_B64),
|
||||
{ name: "RSA-PSS", hash: "SHA-1" }, false, ["sign"]
|
||||
);
|
||||
}
|
||||
return signKeyPromise;
|
||||
}
|
||||
function rsaDecKey() {
|
||||
if (!decKeyPromise) {
|
||||
decKeyPromise = crypto.subtle.importKey(
|
||||
"pkcs8", b64ToBytes(PRIVATE_KEY_DER_B64),
|
||||
{ name: "RSA-OAEP", hash: "SHA-1" }, false, ["decrypt"]
|
||||
);
|
||||
}
|
||||
return decKeyPromise;
|
||||
}
|
||||
|
||||
/** Widevine device signature: RSA-PSS SHA-1, salt length = 20. */
|
||||
export async function signDevice(data) {
|
||||
const key = await rsaSignKey();
|
||||
return new Uint8Array(await crypto.subtle.sign({ name: "RSA-PSS", saltLength: 20 }, key, data));
|
||||
}
|
||||
|
||||
/** sessionKey = RSA-OAEP-SHA1 unwrap of SignedLicense.SessionKey (f4). */
|
||||
async function unwrapSessionKey(wrapped) {
|
||||
const key = await rsaDecKey();
|
||||
const buf = await crypto.subtle.decrypt({ name: "RSA-OAEP" }, key, wrapped);
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
/** AES single block encrypt via CBC with zero IV (== ECB for one block). */
|
||||
async function aesEncBlock(keyBytes, block) {
|
||||
const key = await crypto.subtle.importKey("raw", keyBytes, "AES-CBC", false, ["encrypt"]);
|
||||
const buf = await crypto.subtle.encrypt(
|
||||
{ name: "AES-CBC", iv: new Uint8Array(16) }, key, block
|
||||
);
|
||||
return new Uint8Array(buf.slice(0, 16));
|
||||
}
|
||||
|
||||
/** AES-CMAC (NIST SP 800-38B) — faithful port of ofsaver's validated cmac.js. */
|
||||
export async function aesCmac(keyBytes, data) {
|
||||
const blockSize = 16;
|
||||
const l = await aesEncBlock(keyBytes, new Uint8Array(16));
|
||||
const RB = new Uint8Array(16);
|
||||
RB[15] = 0x87; // Rb constant occupies the LAST byte of the block
|
||||
let k1 = shiftLeft(l);
|
||||
if (l[0] & 0x80) k1 = xor(k1, RB);
|
||||
let k2 = shiftLeft(k1);
|
||||
if (k1[0] & 0x80) k2 = xor(k2, RB);
|
||||
|
||||
const lastComplete = data.length > 0 && data.length % blockSize === 0;
|
||||
// main loop processes only the complete blocks BEFORE the last block
|
||||
const nonZeroLen = lastComplete ? data.length - blockSize : Math.floor(data.length / blockSize) * blockSize;
|
||||
|
||||
let x = new Uint8Array(16);
|
||||
for (let i = 0; i < nonZeroLen; i += blockSize) {
|
||||
// X_i = AES_K(X_{i-1} XOR M_i) — XOR happens before encryption
|
||||
x = await aesEncBlock(keyBytes, xor(x, data.slice(i, i + blockSize)));
|
||||
}
|
||||
let last = data.slice(nonZeroLen);
|
||||
if (last.length < blockSize || !lastComplete) {
|
||||
const padded = new Uint8Array(16);
|
||||
padded.set(last, 0);
|
||||
padded[last.length] = 0x80;
|
||||
last = xor(padded, k2);
|
||||
} else {
|
||||
last = xor(new Uint8Array(last), k1);
|
||||
}
|
||||
return aesEncBlock(keyBytes, xor(last, x));
|
||||
}
|
||||
|
||||
function shiftLeft(b) {
|
||||
const out = new Uint8Array(b.length);
|
||||
let carry = 0;
|
||||
for (let i = b.length - 1; i >= 0; i--) {
|
||||
out[i] = ((b[i] << 1) | carry) & 0xff;
|
||||
carry = b[i] >> 7;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function xor(a, b) {
|
||||
const out = new Uint8Array(a.length);
|
||||
for (let i = 0; i < a.length; i++) out[i] = a[i] ^ b[i];
|
||||
return out;
|
||||
}
|
||||
|
||||
/** key = AES-CBC-PKCS7(container.Key, Enc, container.Iv) */
|
||||
async function aesCbcDecrypt(keyBytes, iv, data) {
|
||||
const key = await crypto.subtle.importKey("raw", keyBytes, "AES-CBC", false, ["decrypt"]);
|
||||
const buf = await crypto.subtle.decrypt({ name: "AES-CBC", iv }, key, data);
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
async function hmacSha256(keyBytes, data) {
|
||||
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
||||
return new Uint8Array(await crypto.subtle.sign("HMAC", key, data));
|
||||
}
|
||||
|
||||
// ---- challenge ---------------------------------------------------------
|
||||
|
||||
const CLIENT_INFO_B64 = null; // blob carries its own client_info
|
||||
|
||||
/** The classic blob IS the ClientIdentification (cert chain pre-signed by
|
||||
* Google's L3 intermediate) — used verbatim, same as ofsaver. */
|
||||
export function clientIdentification() {
|
||||
return b64ToBytes(CLIENT_BLOB_B64);
|
||||
}
|
||||
|
||||
/** ContentIdentification embedding the media's own widevine pssh payload. */
|
||||
export function buildContentIdentification(psshPayload, requestId) {
|
||||
return pbMsg(pbBytes(1, pbMsg(pbBytes(1, psshPayload), pbVarint(2, 1), pbString(3, requestId))));
|
||||
}
|
||||
|
||||
/** SignedRequest for LICENSE_REQUEST (same layout as the verified ofsaver one). */
|
||||
export async function buildChallenge(psshPayload) {
|
||||
const requestId = [...crypto.getRandomValues(new Uint8Array(16))]
|
||||
.map((b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();
|
||||
const licenseRequest = pbMsg(
|
||||
pbBytes(1, clientIdentification()),
|
||||
pbBytes(2, buildContentIdentification(psshPayload, requestId)),
|
||||
pbVarint(3, 1), // NEW
|
||||
pbVarint(4, Math.floor(Date.now() / 1000)),
|
||||
pbVarint(6, 21),
|
||||
pbVarint(7, new Uint32Array(crypto.getRandomValues(new Uint8Array(4)).buffer)[0]) // key_control_nonce
|
||||
);
|
||||
const sig = await signDevice(licenseRequest);
|
||||
return pbMsg(pbVarint(1, 1), pbBytes(2, licenseRequest), pbBytes(3, sig));
|
||||
}
|
||||
|
||||
// ---- license processing ------------------------------------------------
|
||||
|
||||
/** Full license processing (identical to ofsaver's verified processLicense). */
|
||||
export async function processLicense(licenseBuf, challengeLicenseRequestBytes) {
|
||||
const msg = new Uint8Array(get(licenseBuf, 2));
|
||||
const sessionKeyWrapped = new Uint8Array(get(licenseBuf, 4));
|
||||
const signature = new Uint8Array(get(licenseBuf, 3));
|
||||
|
||||
const sessionKey = await unwrapSessionKey(sessionKeyWrapped);
|
||||
if (sessionKey.length !== 16) throw new Error(`session key ${sessionKey.length}B, expected 16`);
|
||||
|
||||
const encKeyBase = Uint8Array.from([
|
||||
...new TextEncoder().encode("ENCRYPTION"), 0,
|
||||
...challengeLicenseRequestBytes, 0, 0, 0, 0x80,
|
||||
]);
|
||||
const authKeyBase = Uint8Array.from([
|
||||
...new TextEncoder().encode("AUTHENTICATION"), 0,
|
||||
...challengeLicenseRequestBytes, 0, 0, 2, 0,
|
||||
]);
|
||||
const encKey = await aesCmac(sessionKey, Uint8Array.from([1, ...encKeyBase]));
|
||||
const auth1 = Uint8Array.from([
|
||||
...(await aesCmac(sessionKey, Uint8Array.from([1, ...authKeyBase]))),
|
||||
...(await aesCmac(sessionKey, Uint8Array.from([2, ...authKeyBase]))),
|
||||
]);
|
||||
|
||||
const hmac = await hmacSha256(auth1, msg);
|
||||
const signatureOk = hmac.every((b, i) => b === signature[i]);
|
||||
|
||||
const keys = [];
|
||||
for (const container of getAll(msg, 3)) {
|
||||
const id = get(container, 1);
|
||||
const iv = get(container, 2);
|
||||
const wrapped = get(container, 3);
|
||||
const type = Number(get(container, 4) ?? 0);
|
||||
if (type === 1 /* SIGNING */ || !wrapped || !iv) continue;
|
||||
const key = await aesCbcDecrypt(encKey, iv, wrapped);
|
||||
keys.push({
|
||||
kidHex: id ? [...new Uint8Array(id)].map((b) => b.toString(16).padStart(2, "0")).join("") : null,
|
||||
keyHex: [...key].map((b) => b.toString(16).padStart(2, "0")).join(""),
|
||||
type,
|
||||
});
|
||||
}
|
||||
return { keys, sessionKeyHex: [...sessionKey].map((b) => b.toString(16).padStart(2, "0")).join(""), signatureOk };
|
||||
}
|
||||
|
||||
// ---- MPD helpers -------------------------------------------------------
|
||||
|
||||
/** Extract the widevine PSSH payload from an MPD (systemId edef8ba9-…). */
|
||||
export function widevinePsshFromMpd(mpdText) {
|
||||
const re = /<cenc:pssh[^>]*>([^<]+)<\/cenc:pssh>/g;
|
||||
let m;
|
||||
while ((m = re.exec(mpdText))) {
|
||||
const box = b64ToBytes(m[1]);
|
||||
const hex = [...box.slice(12, 28)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
||||
if (hex.startsWith("edef8ba9")) {
|
||||
const dataSize = (box[28] << 24) | (box[29] << 16) | (box[30] << 8) | box[31];
|
||||
return box.slice(32, 32 + dataSize);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** KID from the MPD's cenc:default_KID. */
|
||||
export function kidFromMpd(mpdText) {
|
||||
const m = /cenc:default_KID="([0-9a-fA-F-]{36})"/.exec(mpdText);
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
Reference in New Issue
Block a user