/*! SPDX-License-Identifier: GPL-3.0-only * * In-browser decrypt for Hongguo CENC (AES-CTR, whole-sample) MP4 files. * * A TypeScript port of `parseBoxes`, `rebuildMoov`, `decryptSample` and `decryptMp4Buffer` from `hongguo.js` of * jackotom/hongguo-drama @ 3f5927d (https://github.com/jackotom/hongguo-drama), GPL-3.0-only; upstream credits * N3urda/hongguoTV, woshishiq1/drpys and ch6vip/fqapp (all GPL-3.0). * Modified for SinReels on 2026-11-12: Node `Buffer` → `Uint8Array` + `DataView`, AES-128-ECB keystream → * WebCrypto AES-CTR (same keystream: a 16-byte counter block = 8-byte sample IV ‖ 64-bit big-endian block index), * async. Output is byte-identical to the original (unit-tested against it). * Source of this module as shipped: /licenses/hongguo-decrypt-browser.ts.txt · license: /licenses/GPL-3.0.txt * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General * Public License as published by the Free Software Foundation, version 3. It is distributed WITHOUT ANY * WARRANTY; see the GNU General Public License for more details: https://www.gnu.org/licenses/gpl-3.0.html */ // The bang comment above stays in minified bundles. No Node imports: this module ships to browsers. It only needs // `crypto.subtle` (secure contexts) and runs in Node ≥ 20 as well. interface Box { typ: string off: number size: number hdr: number children: Box[] | null } const CONTAINER_BOXES = new Set(['moov', 'trak', 'mdia', 'minf', 'stbl', 'edts', 'dinf', 'udta', 'meta']) const DROPPED_BOXES = new Set(['senc', 'saio', 'saiz', 'sgpd', 'sbgp']) const VIDEO_TYPES = ['avc1', 'avc3', 'hvc1', 'hev1'] const viewOf = (d: Uint8Array) => new DataView(d.buffer, d.byteOffset, d.byteLength) /** `Buffer#toString('latin1', start, end)` (end clamped like Buffer). */ function latin1(d: Uint8Array, start: number, end: number): string { let s = '' for (let i = start; i < Math.min(end, d.length); i++) s += String.fromCharCode(d[i]!) return s } function concat(parts: Uint8Array[]): Uint8Array { let len = 0 for (const p of parts) len += p.length const out = new Uint8Array(len) let at = 0 for (const p of parts) { out.set(p, at) at += p.length } return out } /** `Buffer#writeUInt32BE`: throws instead of wrapping a value out of range. */ function writeU32(v: DataView, off: number, value: number): void { if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) throw new RangeError(`value out of range: ${value}`) v.setUint32(off, value) } function parseBoxes(data: Uint8Array, v: DataView, start: number, end: number): Box[] { const boxes: Box[] = [] let off = start while (off + 8 <= end) { let size = v.getUint32(off) const typ = latin1(data, off + 4, off + 8) let hdr = 8 if (size === 1) { size = Number(v.getBigUint64(off + 8)) hdr = 16 } else if (size === 0) { size = end - off } if (size < hdr || off + size > end) break const children = CONTAINER_BOXES.has(typ) ? parseBoxes(data, v, off + hdr, off + size) : null boxes.push({ typ, off, size, hdr, children }) off += size } return boxes } function* walkChildren(box: Box): Generator { for (const c of box.children ?? []) { yield c yield* walkChildren(c) } } /** Post-order walk (children before their parent), as the original. */ function* walkBoxes(boxes: Box[]): Generator { for (const b of boxes) { if (b.children) yield* walkBoxes(b.children) yield b } } /** Rewrites `moov` without the encryption boxes and with the original sample entry types. Patches `stco` in place. */ function rebuildMoov( data: Uint8Array, v: DataView, moovOff: number, moovSize: number, top: Box[], ): Uint8Array { const moovBox = top.find((b) => b.typ === 'moov') if (!moovBox) throw new Error('no moov box') const clone = (box: Box): Box => ({ ...box, children: box.children ? box.children.map(clone) : null }) const prune = (box: Box): Box => { if (!box.children) return box box.children = box.children.filter((c) => !DROPPED_BOXES.has(c.typ)).map(prune) return box } const tree = prune(clone(moovBox)) const patches = new Map() for (const b of walkChildren(tree)) { if (b.typ !== 'stsd') continue const content = b.off + 8 const count = v.getUint32(content + 4) let p = content + 8 const entries: Uint8Array[] = [] for (let i = 0; i < count; i++) { const esize = v.getUint32(p) const etyp = latin1(data, p + 4, p + 8) if (etyp === 'encv' || etyp === 'enca') { const hdrSize = etyp === 'encv' ? 78 : 28 const children = parseBoxes(data, v, p + 8 + hdrSize, p + esize) let newType: string | null = 'mp4a' if (etyp === 'encv') { const sinf = children.find((child) => child.typ === 'sinf') const frma = sinf ? parseBoxes(data, v, sinf.off + sinf.hdr, sinf.off + sinf.size).find( (child) => child.typ === 'frma', ) : undefined const original = frma && frma.size === frma.hdr + 4 ? latin1(data, frma.off + frma.hdr, frma.off + frma.hdr + 4) : null const avc = children.some((child) => child.typ === 'avcC') const hevc = children.some((child) => child.typ === 'hvcC') newType = original || (avc && !hevc ? 'avc1' : hevc && !avc ? 'hvc1' : null) if ( newType === null || !VIDEO_TYPES.includes(newType) || (newType.startsWith('avc') ? !avc || hevc : !hevc || avc) ) { throw new Error('无法确定加密视频的原始编码(codec),请更换片源重试。') } } const entry = new Uint8Array(8 + hdrSize) for (let k = 0; k < 4; k++) entry[4 + k] = newType.charCodeAt(k) & 0xff entry.set(data.subarray(p + 8, p + 8 + hdrSize), 8) const extra = children .filter((child) => child.typ !== 'sinf') .map((child) => data.subarray(child.off, child.off + child.size)) const fullEntry = concat([entry, ...extra]) writeU32(viewOf(fullEntry), 0, fullEntry.length) entries.push(fullEntry) } else { entries.push(data.subarray(p, p + esize)) } p += esize } const stsdHdr = new Uint8Array(16) stsdHdr.set(data.subarray(b.off, content + 8)) writeU32(viewOf(stsdHdr), 12, entries.length) const fullStsd = concat([stsdHdr, ...entries]) writeU32(viewOf(fullStsd), 0, fullStsd.length) patches.set(b.off, fullStsd) } const serialize = (box: Box): Uint8Array => { if (!box.children) return patches.get(box.off) ?? data.subarray(box.off, box.off + box.size) const body = concat(box.children.map(serialize)) const hdrb = new Uint8Array(box.hdr) hdrb.set(data.subarray(box.off, box.off + box.hdr)) const hv = viewOf(hdrb) if (box.hdr === 8) { writeU32(hv, 0, 8 + body.length) } else { writeU32(hv, 0, 1) hv.setBigUint64(8, BigInt(16 + body.length)) } return concat([hdrb, body]) } const first = serialize(tree) const delta = moovSize - first.length for (const b of walkChildren(tree)) { if (b.typ !== 'stco') continue const nc = v.getUint32(b.off + 12) for (let i = 0; i < nc; i++) { const at = b.off + 16 + i * 4 const value = v.getUint32(at) if (value >= moovOff + moovSize) writeU32(v, at, value - delta) } } return serialize(tree) } /** WebCrypto key (named via `crypto` so the package needs no DOM lib). */ type AesKey = Awaited> /** CENC AES-CTR for one sample: counter block = 8-byte IV ‖ 64-bit big-endian block index from 0. */ async function decryptSample(key: AesKey, nonce: Uint8Array, cipher: Uint8Array): Promise { if (cipher.length === 0) return new Uint8Array(0) const counter = new Uint8Array(16) counter.set(nonce.subarray(0, 8)) const plain = await crypto.subtle.encrypt( { name: 'AES-CTR', counter, length: 64 }, key, cipher as Uint8Array, ) return new Uint8Array(plain) } /** Lowercase/uppercase hex → bytes; throws on anything else. */ export function hexToBytes(hex: string): Uint8Array { if (!/^(?:[0-9a-fA-F]{2})*$/.test(hex)) throw new Error('invalid hex') const out = new Uint8Array(hex.length / 2) for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16) return out } /** * Decrypts a whole CENC AES-CTR encrypted MP4 and returns the playable MP4 (decrypted samples, `moov` rebuilt). * Like the original, it decrypts `data` IN PLACE: pass a buffer the caller owns. `key` is the 16-byte content key. */ export async function decryptMp4(data: Uint8Array, key: Uint8Array): Promise { // The original's AES-128-ECB rejects other key sizes; WebCrypto would silently accept AES-192/256. if (key.length !== 16) throw new Error('Invalid key length') const cryptoKey = await crypto.subtle.importKey('raw', key as Uint8Array, 'AES-CTR', false, [ 'encrypt', ]) const v = viewOf(data) const total = data.length const top = parseBoxes(data, v, 0, total) const moov = top.find((b) => b.typ === 'moov') if (!moov) throw new Error('no moov box found in MP4') const getBox = (boxes: Box[] | null, typ: string) => (boxes ?? []).find((b) => b.typ === typ) const tracks: { sizes: number[]; offs: number[]; ivs: Uint8Array[] }[] = [] for (const stbl of Array.from(walkBoxes(top)).filter((b) => b.typ === 'stbl')) { const stsz = getBox(stbl.children, 'stsz') const stco = getBox(stbl.children, 'stco') const stsc = getBox(stbl.children, 'stsc') const senc = getBox(stbl.children, 'senc') if (!stsz || !stco || !stsc) continue const ss = v.getUint32(stsz.off + 12) const n = v.getUint32(stsz.off + 16) const sizes: number[] = [] for (let i = 0; i < n; i++) sizes.push(ss === 0 ? v.getUint32(stsz.off + 20 + i * 4) : ss) const nc = v.getUint32(stco.off + 12) const chunkOffs: number[] = [] for (let i = 0; i < nc; i++) chunkOffs.push(v.getUint32(stco.off + 16 + i * 4)) const ns = v.getUint32(stsc.off + 12) const stscTab: [number, number][] = [] for (let i = 0; i < ns; i++) stscTab.push([v.getUint32(stsc.off + 16 + i * 12), v.getUint32(stsc.off + 20 + i * 12)]) const ivs: Uint8Array[] = [] if (senc) { const sc = v.getUint32(senc.off + 12) for (let i = 0; i < sc; i++) ivs.push(data.subarray(senc.off + 16 + i * 8, senc.off + 24 + i * 8)) } const chunkSpc = new Map() for (let i = 0; i < stscTab.length; i++) { const [fc, spc] = stscTab[i]! const nxt = i + 1 < stscTab.length ? stscTab[i + 1]![0] : nc + 1 for (let ci = fc - 1; ci < nxt - 1; ci++) chunkSpc.set(ci, spc) } const offs: number[] = [] let si = 0 for (let ci = 0; ci < nc; ci++) { let off = chunkOffs[ci]! const spc = chunkSpc.get(ci) || 1 for (let s = 0; s < spc; s++) { if (si >= n) break offs.push(off) off += sizes[si]! si++ } } tracks.push({ sizes, offs, ivs }) } for (const t of tracks) { for (let i = 0; i < t.offs.length; i++) { const off = t.offs[i]! const sz = t.sizes[i]! if (off + sz > total || i >= t.ivs.length) continue data.set(await decryptSample(cryptoKey, t.ivs[i]!.subarray(0, 8), data.subarray(off, off + sz)), off) } } const newMoov = rebuildMoov(data, v, moov.off, moov.size, top) const out: Uint8Array[] = [] let off = 0 while (off < total) { let size = v.getUint32(off) const typ = latin1(data, off + 4, off + 8) if (size === 1) size = Number(v.getBigUint64(off + 8)) else if (size === 0) size = total - off out.push(typ === 'moov' ? newMoov : data.subarray(off, off + size)) off += size } return concat(out) }