197 lines
8.3 KiB
JavaScript
197 lines
8.3 KiB
JavaScript
const fs = require("node:fs/promises");
|
|
const path = require("node:path");
|
|
|
|
const LANGUAGES = new Set(["engsub", "engdub", "gersub", "gerdub"]);
|
|
const MAX_LOG_BYTES = 16 * 1024;
|
|
// Database input for status DTOs. The token is read only to redact legacy logs;
|
|
// callers must pass every record through toPublicJob before returning it.
|
|
const STATUS_READ_PROJECTION = Object.freeze({
|
|
_id: 1, filename: 1, url: 1, created_at: 1, started_at: 1,
|
|
finished_at: 1, failed_at: 1, output_log: 1, error_category: 1, token: 1,
|
|
});
|
|
|
|
class ValidationError extends Error {
|
|
constructor(message) {
|
|
super(message);
|
|
this.name = "ValidationError";
|
|
}
|
|
}
|
|
|
|
function positiveInteger(value, label) {
|
|
const text = typeof value === "number" ? String(value) : value;
|
|
if (typeof text !== "string" || !/^[1-9]\d*$/.test(text)) {
|
|
throw new ValidationError(`${label} must be a positive whole number.`);
|
|
}
|
|
const number = Number(text);
|
|
if (!Number.isSafeInteger(number)) {
|
|
throw new ValidationError(`${label} is too large.`);
|
|
}
|
|
return number;
|
|
}
|
|
|
|
function isWellFormedText(value) {
|
|
// In Unicode mode a valid surrogate pair is one code point outside this range.
|
|
// Lone surrogates would otherwise be replaced silently when converted to UTF-8.
|
|
return typeof value === "string" && !/[\uD800-\uDFFF]/u.test(value);
|
|
}
|
|
|
|
function normalizeWatchUrl(value) {
|
|
if (!isWellFormedText(value) || value.length > 2048 || /[\s\\\u0000-\u001f\u007f-\u009f]/u.test(value)) {
|
|
throw new ValidationError("Enter a valid HTTPS Proxer episode URL.");
|
|
}
|
|
let url;
|
|
try {
|
|
url = new URL(value);
|
|
} catch {
|
|
throw new ValidationError("Enter a valid HTTPS Proxer episode URL.");
|
|
}
|
|
if (url.protocol !== "https:" || !["proxer.me", "www.proxer.me"].includes(url.hostname)
|
|
|| /^https:\/\/[^/?#]*@/i.test(value)
|
|
|| url.username || url.password || (url.port && url.port !== "443") || url.search) {
|
|
throw new ValidationError("Use an HTTPS proxer.me episode URL without credentials or query parameters.");
|
|
}
|
|
const match = url.pathname.match(/^\/watch\/([1-9]\d*)\/([1-9]\d*)\/(engsub|engdub|gersub|gerdub)\/?$/);
|
|
if (!match) {
|
|
throw new ValidationError("The episode URL must contain a series ID, episode number, and supported language.");
|
|
}
|
|
const id = positiveInteger(match[1], "Series ID");
|
|
const episode = positiveInteger(match[2], "Episode");
|
|
const language = match[3];
|
|
return { id, episode, language, url: `https://proxer.me/watch/${id}/${episode}/${language}` };
|
|
}
|
|
|
|
function normalizeFilename(value) {
|
|
if (!isWellFormedText(value) || !value || value.trim() !== value
|
|
|| value === "." || value === ".." || /[\/\\\u0000-\u001f\u007f-\u009f]/u.test(value)
|
|
|| Buffer.byteLength(`${value}.mp4`, "utf8") > 255) {
|
|
throw new ValidationError("The filename must be a single nonempty name without path separators, control characters, or surrounding spaces (maximum 255 bytes including .mp4).");
|
|
}
|
|
return value;
|
|
}
|
|
|
|
async function outputDirectory(outputDir) {
|
|
let resolved;
|
|
try {
|
|
resolved = await fs.realpath(outputDir);
|
|
const stat = await fs.stat(resolved);
|
|
if (!stat.isDirectory()) throw new Error("not a directory");
|
|
} catch {
|
|
throw new Error("The configured output directory is unavailable.");
|
|
}
|
|
return resolved;
|
|
}
|
|
|
|
async function validateOutputTarget(outputDir, filename) {
|
|
const name = normalizeFilename(filename);
|
|
const root = await outputDirectory(outputDir);
|
|
const target = path.resolve(root, `${name}.mp4`);
|
|
if (path.dirname(target) !== root) {
|
|
throw new ValidationError("The filename must stay inside the output directory.");
|
|
}
|
|
try {
|
|
const stat = await fs.lstat(target);
|
|
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
throw new ValidationError("The output filename is already used by a link or non-file entry. Choose another name.");
|
|
}
|
|
} catch (error) {
|
|
if (error.code !== "ENOENT") throw error;
|
|
}
|
|
return target;
|
|
}
|
|
|
|
function cookieToken(value, prefix) {
|
|
if (typeof prefix !== "string" || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+=$/.test(prefix)) {
|
|
throw new Error("A valid cookie-name TOKEN_PREFIX ending in '=' is required.");
|
|
}
|
|
if (!isWellFormedText(value) || !value || Buffer.byteLength(prefix + value, "utf8") > 8192 || /[\s;\u0000-\u001f\u007f-\u009f]/u.test(value)) {
|
|
throw new ValidationError("Enter a nonempty token without spaces, control characters, or cookie separators.");
|
|
}
|
|
return prefix + value;
|
|
}
|
|
|
|
function optionalTitle(value) {
|
|
if (value === undefined || value === null || value === "") return "";
|
|
if (typeof value !== "string") throw new ValidationError("The title must be text.");
|
|
return value.trim();
|
|
}
|
|
|
|
async function buildQueueJobs(body, config, now = () => new Date()) {
|
|
if (!body || typeof body !== "object" || Array.isArray(body)) throw new ValidationError("Invalid download request.");
|
|
if (body.mode !== "video" && body.mode !== "series") throw new ValidationError("Choose video or series mode.");
|
|
const token = cookieToken(body.token, config.tokenPrefix);
|
|
const created_at = now();
|
|
const jobs = [];
|
|
if (body.mode === "video") {
|
|
const source = normalizeWatchUrl(body.url);
|
|
const filename = normalizeFilename(optionalTitle(body.filename) || optionalTitle(body.name)
|
|
|| `${source.id} E${source.episode} ${source.language}`);
|
|
jobs.push({ url: source.url, token, filename, created_at });
|
|
} else {
|
|
const id = positiveInteger(body.id, "Series ID");
|
|
const from = positiveInteger(body.episode_from, "First episode");
|
|
const to = positiveInteger(body.episode_to, "Last episode");
|
|
if (to < from) throw new ValidationError("Last episode must be greater than or equal to the first episode.");
|
|
if (to - from + 1 > config.maxSeriesEpisodes) {
|
|
throw new ValidationError(`A submission can contain at most ${config.maxSeriesEpisodes} episodes.`);
|
|
}
|
|
if (!LANGUAGES.has(body.language)) throw new ValidationError("Choose a supported language.");
|
|
const name = optionalTitle(body.name) || String(id);
|
|
const pad = String(to).length;
|
|
for (let ep = from; ep <= to; ep += 1) {
|
|
jobs.push({
|
|
url: `https://proxer.me/watch/${id}/${ep}/${body.language}`,
|
|
token,
|
|
filename: normalizeFilename(`${name}E${String(ep).padStart(pad, "0")}_${body.language}`),
|
|
created_at,
|
|
});
|
|
}
|
|
}
|
|
// Check every destination before inserting anything, so invalid batches are not partially queued.
|
|
for (const job of jobs) await validateOutputTarget(config.outputDir, job.filename);
|
|
return jobs;
|
|
}
|
|
|
|
function sanitizeLog(value, sensitiveValues = []) {
|
|
if (typeof value !== "string") return "";
|
|
let result = value;
|
|
for (const secret of sensitiveValues) {
|
|
if (typeof secret === "string" && secret.length) {
|
|
result = result.split(secret).join("[redacted]");
|
|
const equals = secret.indexOf("=");
|
|
if (equals > 0 && equals < secret.length - 1) {
|
|
result = result.split(secret.slice(equals + 1)).join("[redacted]");
|
|
}
|
|
}
|
|
}
|
|
result = result
|
|
.replace(/\b(?:https?|mongodb(?:\+srv)?):\/\/[^\s<>"']+/gi, "[URL redacted]")
|
|
.replace(/\b(?:authorization|cookie|set-cookie)\s*:\s*[^\r\n]*/gi, "[credential redacted]")
|
|
.replace(/\b(?:token|password|secret|PHPSESSID)\s*[=:]\s*[^\s;,]+/gi, "[credential redacted]");
|
|
const buffer = Buffer.from(result, "utf8");
|
|
return buffer.length <= MAX_LOG_BYTES ? result : `[Earlier log output omitted]\n${buffer.subarray(-MAX_LOG_BYTES).toString("utf8")}`;
|
|
}
|
|
|
|
function toPublicJob(job) {
|
|
const view = { _id: String(job._id), filename: typeof job.filename === "string" ? job.filename : "Unnamed download" };
|
|
if (typeof job.url === "string") {
|
|
try { view.url = normalizeWatchUrl(job.url).url; } catch { view.url = "Source URL unavailable"; }
|
|
}
|
|
for (const field of ["created_at", "started_at", "finished_at", "failed_at"]) {
|
|
if (job[field] != null) {
|
|
const date = new Date(job[field]);
|
|
if (Number.isFinite(date.getTime())) view[field] = date.toISOString();
|
|
}
|
|
}
|
|
if (job.output_log) view.output_log = sanitizeLog(job.output_log, [job.token]);
|
|
if (["validation", "authentication", "resolution", "network", "source", "storage", "unknown", "spawn"].includes(job.error_category)) {
|
|
view.error_category = job.error_category;
|
|
}
|
|
return view;
|
|
}
|
|
|
|
module.exports = {
|
|
ValidationError, LANGUAGES, MAX_LOG_BYTES, STATUS_READ_PROJECTION,
|
|
positiveInteger, normalizeWatchUrl, normalizeFilename, validateOutputTarget,
|
|
cookieToken, buildQueueJobs, sanitizeLog, toPublicJob,
|
|
};
|