This commit is contained in:
collector
2026-12-06 12:41:22 +01:00
commit 53d31572a1
49 changed files with 8546 additions and 0 deletions

220
ext/lib/wv.js Normal file
View 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;
}