Skip to content

一分钟搭建影视站,支持Docker等部署方式

fix(download): 修复续传进度重复计数与 AES 无 IV 时的解密错误

bestZweid9484b0ffd24
diff --git a/src/components/download-manager.tsx b/src/components/download-manager.tsx
index ef26d07..fa85b8a 100644
--- a/src/components/download-manager.tsx
+++ b/src/components/download-manager.tsx
@@ -285,7 +285,7 @@ export function DownloadManager({ isOpen, onClose }: { isOpen: boolean; onClose:
<div className="h-1.5 rounded-full bg-chip overflow-hidden">
<div
className="h-full bg-accent transition-all"
- style={{ width: `${t.total > 0 ? Math.round((t.finished / t.total) * 100) : 0}%` }}
+ style={{ width: `${t.total > 0 ? Math.min(100, Math.round((t.finished / t.total) * 100)) : 0}%` }}
/>
</div>
)}
diff --git a/src/lib/m3u8-downloader.test.ts b/src/lib/m3u8-downloader.test.ts
new file mode 100644
index 0000000..ea85434
--- /dev/null
+++ b/src/lib/m3u8-downloader.test.ts
@@ -0,0 +1,92 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { decryptSegment } from './m3u8-downloader';
+import { parseM3u8Playlist } from './m3u8-parse';
+
+const KEY = crypto.getRandomValues(new Uint8Array(16));
+const asBuf = (v: Uint8Array): BufferSource => v.buffer as ArrayBuffer;
+const PLAINTEXT = crypto.getRandomValues(new Uint8Array(188 * 3));
+
+async function encryptForIv(plaintext: BufferSource, iv: Uint8Array): Promise<ArrayBuffer> {
+ const cryptoKey = await crypto.subtle.importKey('raw', asBuf(KEY), 'AES-CBC', false, ['encrypt']);
+ return crypto.subtle.encrypt({ name: 'AES-CBC', iv: asBuf(iv) }, cryptoKey, plaintext);
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('decryptSegment', () => {
+ it('显式 IV:密文往返还原明文', async () => {
+ const cipher = await encryptForIv(PLAINTEXT, new Uint8Array(16).fill(0xab));
+ const out = await decryptSegment(cipher, asBuf(KEY), 'ab'.repeat(16), 0, 0);
+ expect(new Uint8Array(out)).toEqual(PLAINTEXT);
+ });
+
+ it('无 IV 属性:IV = mediaSequence + 分片序号(16 字节大端),逐分片递增', async () => {
+ // 分片 0(媒体序列号 5 → IV=5)与分片 1(IV=6)用各自正确的 IV 加密
+ const ivOf = (seq: number) => {
+ const iv = new Uint8Array(16);
+ iv[15] = seq;
+ return iv;
+ };
+ const cipher0 = await encryptForIv(PLAINTEXT, ivOf(5));
+ const cipher1 = await encryptForIv(PLAINTEXT, ivOf(6));
+
+ const out0 = await decryptSegment(cipher0, asBuf(KEY), undefined, 5, 0);
+ expect(new Uint8Array(out0)).toEqual(PLAINTEXT);
+ const out1 = await decryptSegment(cipher1, asBuf(KEY), undefined, 5, 1);
+ expect(new Uint8Array(out1)).toEqual(PLAINTEXT);
+ });
+
+ it('回归:旧实现恒用零向量 IV——对非零序列号分片解密必然失败', async () => {
+ // 分片按正确 IV=6 加密;旧实现对无 IV 属性的 KEY 恒用零向量 → 解不出明文
+ const cipher = await encryptForIv(PLAINTEXT, ivOf6());
+ const zeroIv = '00'.repeat(16);
+ const out = await decryptSegment(cipher, asBuf(KEY), zeroIv, 5, 1).catch(
+ () => new ArrayBuffer(0)
+ );
+ const same =
+ out.byteLength === PLAINTEXT.byteLength &&
+ new Uint8Array(out).every((b, i) => b === PLAINTEXT[i]);
+ expect(same).toBe(false);
+ });
+});
+
+function ivOf6(): Uint8Array {
+ const iv = new Uint8Array(16);
+ iv[15] = 6;
+ return iv;
+}
+
+describe('parseM3u8Playlist · mediaSequence 与 AES URI 绝对化', () => {
+ it('解析 EXT-X-MEDIA-SEQUENCE,AES key 相对地址转绝对', async () => {
+ const playlist = [
+ '#EXTM3U',
+ '#EXT-X-MEDIA-SEQUENCE:15',
+ '#EXT-X-KEY:METHOD=AES-128,URI="key.bin"',
+ '#EXTINF:4,',
+ 'seg0.ts',
+ '#EXTINF:4,',
+ 'seg1.ts',
+ ].join('\n');
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response(playlist, { status: 200 }))
+ );
+
+ const parsed = await parseM3u8Playlist('https://cdn.example.com/live/index.m3u8');
+ expect(parsed.mediaSequence).toBe(15);
+ expect(parsed.aesConf?.uri).toBe('https://cdn.example.com/live/key.bin');
+ expect(parsed.segments).toHaveLength(2);
+ expect(parsed.segments[0].url).toBe('https://cdn.example.com/live/seg0.ts');
+ });
+
+ it('缺省 MEDIA-SEQUENCE 时为 0', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response('#EXTM3U\n#EXTINF:4,\nseg.ts', { status: 200 }))
+ );
+ const parsed = await parseM3u8Playlist('https://cdn.example.com/a.m3u8');
+ expect(parsed.mediaSequence).toBe(0);
+ });
+});
diff --git a/src/lib/m3u8-downloader.ts b/src/lib/m3u8-downloader.ts
index f0cd6c8..eac937e 100644
--- a/src/lib/m3u8-downloader.ts
+++ b/src/lib/m3u8-downloader.ts
@@ -76,12 +76,35 @@ async function fetchSegment(url: string, signal: AbortSignal): Promise<ArrayBuff
return res.arrayBuffer();
}
-async function decryptAes128Cbc(data: ArrayBuffer, key: ArrayBuffer, ivHex?: string): Promise<ArrayBuffer> {
- const iv = ivHex
- ? Uint8Array.from(ivHex.padStart(32, '0').slice(0, 32).match(/.{2}/g)!.map((h) => parseInt(h, 16)))
- : new Uint8Array(16);
+/**
+ * HLS AES-128 分片解密(AES-CBC / PKCS7)。
+ * IV 规则(RFC 8216 §4.3.2.4):KEY 带IV 属性时全部分片共用;**无 IV 属性时
+ * IV = 分片的媒体序列号(16 字节大端)**,逐分片递增——恒用零向量会导致
+ * 首片恰好正确、后续全部解密失败。
+ */
+function ivForSegment(mediaSequence: number, segmentIndexZeroBased: number): Uint8Array {
+ const seq = BigInt(mediaSequence + segmentIndexZeroBased);
+ const iv = new Uint8Array(16);
+ for (let i = 0; i < 16; i++) {
+ iv[15 - i] = Number((seq >> BigInt(8 * i)) & 0xffn);
+ }
+ return iv;
+}
+
+function hexToBytes(hex: string): Uint8Array {
+ return Uint8Array.from(hex.padStart(32, '0').slice(0, 32).match(/.{2}/g)!.map((h) => parseInt(h, 16)));
+}
+
+export async function decryptSegment(
+ data: ArrayBuffer,
+ key: BufferSource,
+ ivHex: string | undefined,
+ mediaSequence: number,
+ segmentIndexZeroBased: number
+): Promise<ArrayBuffer> {
+ const iv = ivHex ? hexToBytes(ivHex) : ivForSegment(mediaSequence, segmentIndexZeroBased);
const cryptoKey = await crypto.subtle.importKey('raw', key, 'AES-CBC', false, ['decrypt']);
- return crypto.subtle.decrypt({ name: 'AES-CBC', iv }, cryptoKey, data);
+ return crypto.subtle.decrypt({ name: 'AES-CBC', iv: iv as BufferSource }, cryptoKey, data);
}
export interface DownloadJobOptions {
@@ -164,8 +187,7 @@ export async function runDownloadJob(opts: DownloadJobOptions): Promise<void> {
await pause.waitIfPaused();
const cached = await cache.match(new Request(chunkKey(index)));
if (cached) {
- current += 1;
- report(current, total, 'downloading');
+ // 已在恢复预统计里计入,不再累加——否则续传时进度重复计数超过 100%
continue;
}
const seg = parsed.segments[index - 1];
@@ -205,7 +227,7 @@ export async function runDownloadJob(opts: DownloadJobOptions): Promise<void> {
if (!resp) throw new Error(`分片 ${i} 缓存丢失,请重试`);
let data = await resp.arrayBuffer();
if (aesKey && parsed.aesConf) {
- data = await decryptAes128Cbc(data, aesKey, parsed.aesConf.iv);
+ data = await decryptSegment(data, aesKey, parsed.aesConf.iv, parsed.mediaSequence, i - 1);
}
await transmuxer.pushAndTransmux(new Uint8Array(data));
}
@@ -218,7 +240,7 @@ export async function runDownloadJob(opts: DownloadJobOptions): Promise<void> {
if (!resp) throw new Error(`分片 ${i} 缓存丢失,请重试`);
let data = await resp.arrayBuffer();
if (aesKey && parsed.aesConf) {
- data = await decryptAes128Cbc(data, aesKey, parsed.aesConf.iv);
+ data = await decryptSegment(data, aesKey, parsed.aesConf.iv, parsed.mediaSequence, i - 1);
}
await target.write(new Uint8Array(data));
}
diff --git a/src/lib/m3u8-parse.ts b/src/lib/m3u8-parse.ts
index 8baea72..8991cb3 100644
--- a/src/lib/m3u8-parse.ts
+++ b/src/lib/m3u8-parse.ts
@@ -37,6 +37,8 @@ export interface ParsedPlaylist {
/** 出现 EXT-X-BYTERANGE:分片为原文件切片,无法独立缓存,该集禁用缓存 */
byterange: boolean;
totalDuration: number;
+ /** EXT-X-MEDIA-SEQUENCE(缺省 0):KEY 无 IV 属性时,分片 IV = 该值 + 分片序号 */
+ mediaSequence: number;
}
/** 解析深度上限(master → variant → media,正常不超过 2 层,防御异常源) */
@@ -141,6 +143,7 @@ export async function parseM3u8Playlist(
let aesConf: AesConf | undefined;
let byterange = false;
let pendingDuration = 0;
+ const mediaSequence = parseInt(text.match(/^#EXT-X-MEDIA-SEQUENCE:(\d+)/m)?.[1] || '0', 10) || 0;
for (const raw of text.split('\n')) {
const line = raw.trim();
if (line.startsWith('#EXT-X-KEY')) {
@@ -167,5 +170,6 @@ export async function parseM3u8Playlist(
aesConf,
byterange,
totalDuration: segments.reduce((sum, s) => sum + s.duration, 0),
+ mediaSequence,
};
}