NGU-Web/server/src/clips.js
Zaldimmar 4066e9ec61 Harden security found in the audit
- Rate limits and IP hashes use the X-Forwarded-For entry nginx adds,
  not the client-supplied first one
- Link preview and feed fetches block IPv4-mapped and other embedded
  IPv6 forms of private addresses (net.BlockList)
- CSRF check on /api writes; security headers and HSTS on every response
- Viewers no longer receive a person's private details (readRole)
- Sessions end 90 days after sign-in however active
- yt-dlp ignores config files and takes the link after --
- Meta tag insert no longer expands $ patterns from record text
- Links with an unsafe scheme draw as text
- Migration 037: leadership lists name published home orgs only
- Ignore *.db-wal, *.db-shm and *.txt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 21:56:49 -05:00

598 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* ═══════════════════════════════════════════════════════════════
VIDEO CLIPS
The work behind Tools → Video clips: download one of our videos
from YouTube or Facebook with yt-dlp, then cut clips from it with
ffmpeg. routes/clips.js is the HTTP around this.
── Configuration (the ngu-api service environment) ──
CLIPS_DIR working files, default ./clips; production
/var/lib/ngu/clips. Temporary: see Cleanup.
YTDLP_PATH default "yt-dlp" on the PATH
FFMPEG_PATH default "ffmpeg"
FFPROBE_PATH default "ffprobe"
When YouTube asks the server to "sign in to confirm you're not a
bot", yt-dlp needs a signed-in account's cookies. One of:
YTDLP_COOKIES a cookies.txt exported from a browser
(Netscape format). Copied per download,
so yt-dlp never writes to the original
YTDLP_COOKIES_FROM_BROWSER a browser on this machine to read them
from, as yt-dlp's --cookies-from-browser
takes it: "firefox", "chrome", or
"firefox:/path/to/profile"
Use a separate Google account, not a personal one: the cookies
are that account's sign-in. If both are set, the file wins.
── Safety ──
Only links on YouTube and Facebook are accepted (SOURCE_HOSTS),
so yt-dlp can't be pointed at anything else, internal addresses
included. Both tools are started with an argument list, never a
shell, so nothing typed can become a command. A source may be at
most MAX_SOURCE_SECONDS long and MAX_SOURCE_SIZE big; a clip at
most MAX_CLIP_SECONDS.
── The queue ──
One job at a time, oldest queued first: video work is heavy for
the VPS, and two at once would only make both slow. A job left
running by a restart is marked failed when the server starts.
── Cleanup ──
A clip's file is deleted as soon as it has been downloaded in
full, unless it was saved to the media library first (then it
lives in the uploads directory like any upload). Every job older
than KEEP_HOURS is deleted with its file, and so is any file in
CLIPS_DIR that no job names.
═══════════════════════════════════════════════════════════════ */
import { spawn } from "node:child_process";
import { randomBytes } from "node:crypto";
import { access, constants, copyFile, mkdir, readdir, rm, stat } from "node:fs/promises";
import path from "node:path";
import { UPLOADS_DIR, PUBLIC_PREFIX } from "./media.js";
export const CLIPS_DIR = path.resolve(process.env.CLIPS_DIR ?? "./clips");
const YTDLP = process.env.YTDLP_PATH ?? "yt-dlp";
const FFMPEG = process.env.FFMPEG_PATH ?? "ffmpeg";
const FFPROBE = process.env.FFPROBE_PATH ?? "ffprobe";
const COOKIES_FILE = process.env.YTDLP_COOKIES || null;
const COOKIES_FROM_BROWSER = process.env.YTDLP_COOKIES_FROM_BROWSER || null;
const MAX_SOURCE_SECONDS = 4 * 60 * 60;
const MAX_SOURCE_SIZE = "4G";
const MAX_CLIP_SECONDS = 60 * 60;
const KEEP_HOURS = 24;
const SWEEP_EVERY_MS = 60 * 60 * 1000;
/* The longest side of a finished video. 1920 covers 1080p landscape
and 1080 × 1920 vertical. */
const MAX_EDGE = 1920;
export const SOURCE_HOSTS = [
"youtube.com",
"www.youtube.com",
"m.youtube.com",
"youtu.be",
"facebook.com",
"www.facebook.com",
"m.facebook.com",
"web.facebook.com",
"fb.watch",
];
/* Output shapes: the aspect a clip is cropped to and the size it's
delivered at, the sizes Instagram, TikTok and YouTube ask for. A
crop from a smaller source is scaled up to it. Original keeps the
source's shape, at most MAX_EDGE on its longer side. */
export const SHAPES = {
original: null,
landscape: { aspect: 16 / 9, width: 1920, height: 1080 },
square: { aspect: 1, width: 1080, height: 1080 },
vertical: { aspect: 9 / 16, width: 1080, height: 1920 },
};
export const FORMATS = ["video", "audio"];
export class ClipError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
/* ── Checking input ────────────────────────────────────────── */
export function checkSourceUrl(raw) {
let url;
try {
url = new URL(String(raw ?? "").trim());
} catch {
throw new ClipError(400, "That isn't a link.");
}
if (url.protocol !== "https:" && url.protocol !== "http:") {
throw new ClipError(400, "Only web links can be downloaded.");
}
if (!SOURCE_HOSTS.includes(url.hostname.toLowerCase())) {
throw new ClipError(400, "Only YouTube and Facebook links can be downloaded.");
}
url.protocol = "https:";
return url.toString();
}
/* A clip request, checked against its source. Times are seconds. */
export function checkClip(input, source) {
const start = Number(input.start);
const end = Number(input.end);
const focus = input.focus == null ? 0.5 : Number(input.focus);
const shape = String(input.shape ?? "original");
const format = String(input.format ?? "video");
if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end <= start) {
throw new ClipError(400, "Pick a start before the end.");
}
if (source.duration && end > source.duration + 0.5) {
throw new ClipError(400, "The end is past the end of the video.");
}
if (end - start > MAX_CLIP_SECONDS) {
throw new ClipError(400, `A clip can be at most ${MAX_CLIP_SECONDS / 60} minutes long.`);
}
if (!(shape in SHAPES)) throw new ClipError(400, "Unknown shape.");
if (!FORMATS.includes(format)) throw new ClipError(400, "Unknown format.");
if (!Number.isFinite(focus) || focus < 0 || focus > 1) throw new ClipError(400, "Bad focus.");
return { start, end: Math.min(end, source.duration ?? end), shape, format, focus };
}
/* ── Running the tools ─────────────────────────────────────── */
/* Runs a tool, calling onLine for each line of its output, and
resolves with the tail of stderr, or rejects with it. */
function run(command, args, { onLine } = {}) {
return new Promise((resolve, reject) => {
let child;
try {
child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
} catch (err) {
reject(err);
return;
}
let tail = "";
let buffered = "";
child.stdout.on("data", (chunk) => {
buffered += chunk.toString();
const lines = buffered.split(/\r?\n|\r/);
buffered = lines.pop() ?? "";
for (const line of lines) onLine?.(line);
});
child.stderr.on("data", (chunk) => {
tail = (tail + chunk.toString()).slice(-4000);
if (onLine) for (const line of chunk.toString().split(/\r?\n|\r/)) onLine(line);
});
child.on("error", (err) =>
reject(
err.code === "ENOENT"
? new ClipError(503, `${path.basename(command)} isn't installed on the server.`)
: err,
),
);
child.on("close", (code) => {
if (buffered) onLine?.(buffered);
if (code === 0) resolve(tail);
else reject(new Error(lastError(tail) || `${path.basename(command)} exited with ${code}`));
});
});
}
/* The most useful line of a tool's error output. */
function lastError(text) {
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
return (lines.reverse().find((l) => /error/i.test(l)) ?? lines[0] ?? "").slice(0, 300);
}
/* Width, height and duration of a media file. */
async function probe(file) {
let out = "";
await run(
FFPROBE,
["-v", "error", "-show_entries", "stream=width,height:format=duration", "-of", "json", file],
{ onLine: (line) => (out += line) },
);
const info = JSON.parse(out || "{}");
const video = (info.streams ?? []).find((s) => s.width);
return {
width: video?.width ?? null,
height: video?.height ?? null,
duration: Number(info.format?.duration) || null,
};
}
let toolsCache = null;
/* Which tools are there, and their versions, for the page to say
what's missing before anyone tries. */
export async function toolVersions() {
if (toolsCache) return toolsCache;
const version = async (command, args, pattern) => {
let first = "";
try {
await run(command, args, { onLine: (line) => (first ||= line) });
return first.match(pattern)?.[1] ?? first.slice(0, 40);
} catch {
return null;
}
};
toolsCache = {
ytdlp: await version(YTDLP, ["--version"], /^(\S+)/),
ffmpeg: await version(FFMPEG, ["-version"], /version (\S+)/),
};
// Look again in a while, in case someone installs one.
setTimeout(() => (toolsCache = null), 5 * 60 * 1000).unref?.();
return toolsCache;
}
/* ── Jobs ──────────────────────────────────────────────────── */
const filePath = (name) => path.join(CLIPS_DIR, path.basename(name));
function update(db, id, fields) {
const keys = Object.keys(fields);
db.prepare(`UPDATE clip_jobs SET ${keys.map((k) => `${k} = ?`).join(", ")} WHERE id = ?`).run(
...keys.map((k) => fields[k]),
id,
);
}
/* yt-dlp's cookie options, from the environment. A cookies file is
copied first: yt-dlp saves updated cookies back to the file it's
given, and the original may be read-only to the service. */
async function cookieArgs(jobId) {
if (COOKIES_FILE) {
const copy = path.join(CLIPS_DIR, `.cookies-${jobId}.txt`);
// Two steps, so a failure names the right one: reading the
// original, or writing the copy into CLIPS_DIR.
try {
await access(COOKIES_FILE, constants.R_OK);
} catch (err) {
const why =
err.code === "ENOENT"
? "it isn't there"
: err.code === "EACCES"
? "the service's user isn't allowed to read it (check its owner and permissions)"
: err.code;
throw new Error(`Couldn't read the cookies file at ${COOKIES_FILE} (YTDLP_COOKIES): ${why}.`);
}
try {
await copyFile(COOKIES_FILE, copy);
} catch (err) {
const why =
err.code === "EACCES" || err.code === "EPERM"
? "the service's user isn't allowed to write there"
: err.code;
throw new Error(`Couldn't copy the cookies file into ${CLIPS_DIR} (CLIPS_DIR): ${why}.`);
}
return { args: ["--cookies", copy], cleanup: () => rm(copy, { force: true }) };
}
if (COOKIES_FROM_BROWSER) {
return { args: ["--cookies-from-browser", COOKIES_FROM_BROWSER], cleanup: async () => {} };
}
return { args: [], cleanup: async () => {} };
}
async function download(db, job) {
const template = path.join(CLIPS_DIR, `source-${job.id}.%(ext)s`);
let file = null;
let title = null;
const cookies = await cookieArgs(job.id);
try {
await run(
YTDLP,
[
// Our options only: no yt-dlp.conf on the box changes them.
"--ignore-config",
...cookies.args,
// YouTube needs a JavaScript runtime to list formats; the one
// running this server will do.
"--js-runtimes",
`node:${process.execPath}`,
"--no-playlist",
"--no-simulate",
"--newline",
"--progress",
"--progress-template",
"download:PROGRESS %(progress._percent_str)s",
"--print",
"before_dl:TITLE %(title)s",
"--print",
"after_move:FILE %(filepath)s",
"-f",
"bv*[height<=1080][ext=mp4]+ba[ext=m4a]/b[height<=1080][ext=mp4]/bv*[height<=1080]+ba/b",
"--merge-output-format",
"mp4",
"--max-filesize",
MAX_SOURCE_SIZE,
"--match-filter",
`duration <= ${MAX_SOURCE_SECONDS}`,
// Only when a path is configured: on the PATH, yt-dlp finds it.
...(process.env.FFMPEG_PATH ? ["--ffmpeg-location", process.env.FFMPEG_PATH] : []),
"-o",
template,
// Last, after --, so the link can never be read as an option.
"--",
job.source_url,
],
{
onLine: (line) => {
const percent = line.match(/^PROGRESS\s+([\d.]+)%/);
if (percent) update(db, job.id, { progress: Math.min(0.99, Number(percent[1]) / 100) });
const t = line.match(/^TITLE (.+)$/);
if (t) title = t[1].slice(0, 300);
const f = line.match(/^FILE (.+)$/);
if (f) file = f[1].trim();
},
},
);
} finally {
await cookies.cleanup();
}
if (!file) throw new Error("The video couldn't be downloaded. It may be private, too long, or too big.");
const info = await probe(file);
const { size } = await stat(file);
update(db, job.id, {
file: path.basename(file),
bytes: size,
title,
duration: info.duration,
});
}
async function cut(db, job) {
const source = db.prepare(`SELECT * FROM clip_jobs WHERE id = ?`).get(job.source_id);
if (!source?.file) throw new Error("Its source video is gone.");
const params = JSON.parse(job.params);
const input = filePath(source.file);
const length = params.end - params.start;
const audio = params.format === "audio";
const name = `clip-${job.id}.${audio ? "mp3" : "mp4"}`;
const args = ["-hide_banner", "-y", "-ss", String(params.start), "-i", input, "-t", String(length)];
if (audio) {
args.push("-vn", "-c:a", "libmp3lame", "-b:a", "192k");
} else {
const filters = [];
const target = SHAPES[params.shape];
const aspect = target?.aspect;
if (aspect) {
const { width, height } = await probe(input);
if (width && height) {
// Crop the source to the shape. The focus is where along the
// cropped direction the frame is centred (0 left/top, 1
// right/bottom); even sizes, as the H.264 encoder needs.
let w = width;
let h = height;
let x = 0;
let y = 0;
if (width / height > aspect) {
w = Math.floor((height * aspect) / 2) * 2;
x = Math.round(Math.min(Math.max(params.focus * width - w / 2, 0), width - w));
} else {
h = Math.floor(width / aspect / 2) * 2;
y = Math.round(Math.min(Math.max(params.focus * height - h / 2, 0), height - h));
}
filters.push(`crop=${w}:${h}:${x}:${y}`);
}
}
filters.push(
target
? `scale=${target.width}:${target.height},setsar=1`
: `scale='if(gte(iw,ih),min(${MAX_EDGE},iw),-2)':'if(gte(iw,ih),-2,min(${MAX_EDGE},ih))'`,
);
args.push(
"-vf",
filters.join(","),
"-c:v",
"libx264",
"-preset",
"veryfast",
"-crf",
"21",
"-pix_fmt",
"yuv420p",
"-c:a",
"aac",
"-b:a",
"160k",
"-movflags",
"+faststart",
);
}
args.push("-progress", "pipe:1", "-nostats", filePath(name));
await run(FFMPEG, args, {
onLine: (line) => {
const us = line.match(/^out_time_us=(\d+)/);
if (us) update(db, job.id, { progress: Math.min(0.99, Number(us[1]) / 1e6 / length) });
},
});
const { size } = await stat(filePath(name));
update(db, job.id, {
file: name,
bytes: size,
title: source.title,
duration: length,
});
}
let running = false;
let dbRef = null;
/* Start the next queued job if nothing is running. Called after a
job is queued and after one finishes. */
export function kick(db = dbRef) {
if (running || !db) return;
const job = db.prepare(`SELECT * FROM clip_jobs WHERE status = 'queued' ORDER BY id LIMIT 1`).get();
if (!job) return;
running = true;
update(db, job.id, { status: "running", progress: 0 });
(async () => {
try {
await mkdir(CLIPS_DIR, { recursive: true }).catch((err) => {
throw new Error(
`Couldn't use the working folder ${CLIPS_DIR} (CLIPS_DIR): ${
err.code === "EACCES" || err.code === "EPERM" ? "the service's user isn't allowed to write there" : err.code
}.`,
);
});
if (job.kind === "source") await download(db, job);
else await cut(db, job);
update(db, job.id, { status: "done", progress: 1, finished_at: new Date().toISOString() });
console.log(`clips: job ${job.id} (${job.kind}) done`);
} catch (err) {
console.warn(`clips: job ${job.id} (${job.kind}) failed: ${err.message}`);
update(db, job.id, {
status: "failed",
error: String(err.message ?? err).slice(0, 500),
finished_at: new Date().toISOString(),
});
} finally {
running = false;
kick(db);
}
})();
}
/* ── Files out ─────────────────────────────────────────────── */
export const fileOf = (job) => (job?.file ? filePath(job.file) : null);
/* A finished clip into the media library: copied into the uploads
directory under a random name, given a media row, and its working
file deleted. Returns the media row's id. */
export async function saveToLibrary(db, job, userId) {
const from = fileOf(job);
if (!from) throw new ClipError(410, "That clip's file is gone. Make it again.");
const audio = job.file.endsWith(".mp3");
const ext = audio ? ".mp3" : ".mp4";
const filename = `${randomBytes(12).toString("hex")}${ext}`;
const to = path.join(UPLOADS_DIR, filename);
// Each step says what it was doing if it fails, so the page can
// tell an admin (this tool is admin-only) what to fix: usually the
// uploads folder's permissions, or UPLOADS_DIR not set.
const step = async (what, fn) => {
try {
return await fn();
} catch (err) {
const why =
err.code === "EACCES" || err.code === "EPERM"
? "the service's user isn't allowed to write there"
: err.message;
throw new ClipError(500, `Couldn't save it to the library: ${what} (${why}).`);
}
};
await step(`making the uploads folder ${UPLOADS_DIR}`, () => mkdir(UPLOADS_DIR, { recursive: true }));
await step(`copying the clip into ${UPLOADS_DIR}`, () => copyFile(from, to));
let id;
try {
const info = audio
? { width: null, height: null }
: await step("reading the clip's size", () => probe(from));
const { size } = await stat(from);
const params = JSON.parse(job.params ?? "{}");
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
const label = `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`;
id = await step("adding it to the media table", () =>
Number(
db
.prepare(
`INSERT INTO media (filename, original_name, content_type, bytes, width, height, processed, uploaded_by)
VALUES (?, ?, ?, ?, ?, ?, 0, ?)`,
)
.run(filename, label.slice(0, 200), audio ? "audio/mpeg" : "video/mp4", size, info.width, info.height, userId)
.lastInsertRowid,
),
);
} catch (err) {
await rm(to, { force: true }); // no file in uploads without its row
throw err;
}
await rm(from, { force: true });
update(db, job.id, { saved_media_id: id, file: null });
return { id, url: `${PUBLIC_PREFIX}${filename}` };
}
/* After a clip has gone out in full: its file isn't needed. */
export async function forgetDownloaded(db, job) {
await rm(fileOf(job) ?? "", { force: true });
update(db, job.id, { file: null, downloaded_at: new Date().toISOString() });
}
/* A job and everything it made: a source takes its clips with it. */
export async function removeJob(db, job) {
const clips = db.prepare(`SELECT file FROM clip_jobs WHERE source_id = ?`).all(job.id);
for (const clip of clips) if (clip.file) await rm(filePath(clip.file), { force: true });
if (job.file) await rm(filePath(job.file), { force: true });
db.prepare(`DELETE FROM clip_jobs WHERE id = ?`).run(job.id);
}
/* ── Cleanup ───────────────────────────────────────────────── */
async function sweep(db) {
const old = db
.prepare(
`SELECT * FROM clip_jobs
WHERE status != 'running' AND created_at < datetime('now', ?)
ORDER BY kind = 'source'`,
)
.all(`-${KEEP_HOURS} hours`);
for (const job of old) await removeJob(db, job);
// Files no job names: a download that died halfway, say.
const named = new Set(db.prepare(`SELECT file FROM clip_jobs WHERE file IS NOT NULL`).all().map((r) => r.file));
let names = [];
try {
names = await readdir(CLIPS_DIR);
} catch {
return;
}
const cutoff = Date.now() - KEEP_HOURS * 3600 * 1000;
for (const name of names) {
if (named.has(name)) continue;
const full = filePath(name);
try {
if ((await stat(full)).mtimeMs < cutoff) await rm(full, { force: true, recursive: true });
} catch {
/* gone already */
}
}
}
/* At boot: fail what a restart interrupted, start the queue, and
sweep now and every hour. */
export function startClipWorker(db) {
dbRef = db;
db.prepare(
`UPDATE clip_jobs SET status = 'failed', error = 'Interrupted by a server restart.',
finished_at = datetime('now')
WHERE status = 'running'`,
).run();
const tick = () => sweep(db).catch((err) => console.warn(`clips: sweep failed: ${err.message}`));
tick();
setInterval(tick, SWEEP_EVERY_MS).unref?.();
kick(db);
}