phase 1 rework
This commit is contained in:
1 parent
211bfd174d
commit
20054198f3
38 files changed
+5001
-1019
No files matched your search
@@ -0,0 +1,32 @@
|
||||
const path = require('node:path');
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
require('dotenv').config({ path: path.join(projectRoot, '.env'), quiet: true });
|
||||
|
||||
function positiveInteger(value, fallback, name, maximum) {
|
||||
if (value === undefined || value === '') return fallback;
|
||||
if (!/^\d+$/.test(String(value))) throw new Error(`${name} must be a positive integer.`);
|
||||
const parsed = Number(value);
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > maximum) {
|
||||
throw new Error(`${name} must be between 1 and ${maximum}.`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function createConfig(env = process.env) {
|
||||
return Object.freeze({
|
||||
projectRoot,
|
||||
workerScript: path.join(projectRoot, 'queue_worker.js'),
|
||||
videoScript: path.join(projectRoot, 'scripts', 'proxer-dl-video.py'),
|
||||
mongoUri: env.MONGO_URI || '',
|
||||
mongoDb: env.MONGO_DB || 'downloads',
|
||||
outputDir: path.resolve(env.OUTPUT_DIR || '/mnt/media/WIP'),
|
||||
pythonPath: env.VENV_PYTHON || 'python3',
|
||||
tokenPrefix: env.TOKEN_PREFIX || '',
|
||||
maxSeriesEpisodes: positiveInteger(env.MAX_SERIES_EPISODES, 500, 'MAX_SERIES_EPISODES', 10000),
|
||||
port: positiveInteger(env.PORT, 3000, 'PORT', 65535),
|
||||
host: env.HOST || '0.0.0.0',
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { config: createConfig(), createConfig };
|
||||
@@ -0,0 +1,196 @@
|
||||
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,
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
const { StringDecoder } = require('node:string_decoder');
|
||||
|
||||
const LOG_LIMIT = 16 * 1024;
|
||||
|
||||
function sanitizeLog(value, secrets = []) {
|
||||
if (value === undefined || value === null) return '';
|
||||
let text = String(value);
|
||||
for (const secret of secrets) {
|
||||
if (typeof secret === 'string' && secret.length) {
|
||||
text = text.split(secret).join('[redacted]');
|
||||
}
|
||||
}
|
||||
text = text
|
||||
.replace(/https?:\/\/[^\s<>"']+/gi, '[redacted URL]')
|
||||
.replace(/\b(?:mongodb(?:\+srv)?):\/\/[^\s<>"']+/gi, '[redacted database URL]')
|
||||
.replace(/\b(token|cookie|authorization|password|mongo_uri|token_prefix)\s*[:=]\s*[^\r\n]+/gi, '$1=[redacted]')
|
||||
.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
|
||||
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
|
||||
return text.length > LOG_LIMIT ? '[earlier log output omitted]\n' + text.slice(-LOG_LIMIT) : text;
|
||||
}
|
||||
|
||||
// Buffer complete lines before redacting; credentials/URLs can cross pipe chunks.
|
||||
function createLineSanitizer(onLine, { secrets = [], maxLineLength = 8192 } = {}) {
|
||||
const decoder = new StringDecoder('utf8');
|
||||
let pending = '';
|
||||
let discarding = false;
|
||||
|
||||
function consume(text) {
|
||||
for (const char of text) {
|
||||
if (char === '\n' || char === '\r') {
|
||||
if (discarding) onLine('[oversized log line omitted]\n');
|
||||
else if (pending) onLine(sanitizeLog(pending, secrets) + '\n');
|
||||
pending = '';
|
||||
discarding = false;
|
||||
} else if (!discarding) {
|
||||
pending += char;
|
||||
if (pending.length > maxLineLength) {
|
||||
pending = '';
|
||||
discarding = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
write(chunk) { consume(decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))); },
|
||||
end() {
|
||||
consume(decoder.end());
|
||||
if (discarding) onLine('[oversized log line omitted]\n');
|
||||
else if (pending) onLine(sanitizeLog(pending, secrets) + '\n');
|
||||
pending = '';
|
||||
discarding = false;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { LOG_LIMIT, sanitizeLog, createLineSanitizer };
|
||||
+34
-10
@@ -1,14 +1,38 @@
|
||||
const { MongoClient } = require("mongodb");
|
||||
require("dotenv").config();
|
||||
const { MongoClient } = require('mongodb');
|
||||
const { config } = require('./config');
|
||||
|
||||
let client, db;
|
||||
function createDbProvider({ settings = config, MongoClientClass = MongoClient } = {}) {
|
||||
let client = null;
|
||||
let pending = null;
|
||||
|
||||
exports.getDb = async function () {
|
||||
if (db) return db;
|
||||
async function getDb() {
|
||||
if (!settings.mongoUri) throw new Error('MONGO_URI must be configured.');
|
||||
if (!pending) {
|
||||
let candidate;
|
||||
pending = Promise.resolve().then(async () => {
|
||||
candidate = new MongoClientClass(settings.mongoUri);
|
||||
client = candidate;
|
||||
await candidate.connect();
|
||||
return candidate.db(settings.mongoDb);
|
||||
}).catch(async () => {
|
||||
pending = null;
|
||||
client = null;
|
||||
if (candidate) await Promise.resolve().then(() => candidate.close()).catch(() => {});
|
||||
throw new Error('Database connection failed. Check the server configuration.');
|
||||
});
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
client = new MongoClient(process.env.MONGO_URI);
|
||||
await client.connect();
|
||||
async function closeDb() {
|
||||
if (pending) await pending.catch(() => {});
|
||||
const previous = client;
|
||||
client = null;
|
||||
pending = null;
|
||||
if (previous) await previous.close();
|
||||
}
|
||||
|
||||
db = client.db("downloads");
|
||||
return db;
|
||||
};
|
||||
return { getDb, closeDb };
|
||||
}
|
||||
|
||||
module.exports = { ...createDbProvider(), createDbProvider };
|
||||
Reference in new issue
Block a user