Skip to content

Commit bbf47c7

Browse files
fix(engine): close the HLS master playlist rewrite race
CodeQL flagged two high-severity alerts on the `stripAudioOnlyVariants` rewrite: a check-then-use race (`existsSync` then a separate path-based read and write) and insecure creation of a file at a predictable path in the OS temp dir. Both came from resolving `master.m3u8` three times. Open it once with `r+` and owner-only mode — which neither creates the playlist nor widens its permissions, ffmpeg owns that — then read, truncate and write through that one descriptor. Absence is still tolerated for the argument-level tests that stub ffmpeg, now via ENOENT rather than a prior existence check. No behavior change: `hlsRender.integration.test.ts` still renders a real composition with audio and asserts the stripped master playlist. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent c050416 commit bbf47c7

1 file changed

Lines changed: 23 additions & 3 deletions

File tree

‎packages/engine/src/services/chunkEncoder.ts‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,18 @@
77
*/
88

99
import {
10+
closeSync,
1011
copyFileSync,
1112
existsSync,
13+
ftruncateSync,
1214
mkdirSync,
1315
mkdtempSync,
16+
openSync,
1417
readFileSync,
1518
readdirSync,
1619
statSync,
1720
writeFileSync,
21+
writeSync,
1822
} from "fs";
1923
import { join, dirname, extname } from "path";
2024
import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";
@@ -900,9 +904,25 @@ export async function packageHls(
900904
}
901905
if (result.success && hasAudio) {
902906
const masterPath = join(outputDir, HLS_MASTER_PLAYLIST);
903-
// Guarded because the argument-level tests stub ffmpeg and never write it.
904-
if (existsSync(masterPath)) {
905-
writeFileSync(masterPath, stripAudioOnlyVariants(readFileSync(masterPath, "utf-8")), "utf-8");
907+
// One descriptor for the read-modify-write: re-resolving the path to write
908+
// it back races anything else in this predictable temp dir, and `r+` with
909+
// owner-only mode neither creates nor widens the playlist ffmpeg wrote.
910+
// A missing one is fine — the argument-level tests stub ffmpeg.
911+
let master: number | undefined;
912+
try {
913+
master = openSync(masterPath, "r+", 0o600);
914+
} catch (error) {
915+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
916+
}
917+
if (master !== undefined) {
918+
try {
919+
const stripped = stripAudioOnlyVariants(readFileSync(master, "utf-8"));
920+
// Stripping only shortens the playlist; truncate or the tail survives.
921+
ftruncateSync(master, 0);
922+
writeSync(master, stripped, 0, "utf-8");
923+
} finally {
924+
closeSync(master);
925+
}
906926
}
907927
}
908928
return {

0 commit comments

Comments
 (0)