diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..d87a77c --- /dev/null +++ b/.env.example @@ -0,0 +1,12 @@ +# Copy to .env in the project directory; keep the real file private. +MONGO_URI=mongodb://127.0.0.1:27017 +MONGO_DB=downloads +OUTPUT_DIR=/mnt/media/WIP +# Replace download_user with the actual Linux account. +VENV_PYTHON=/home/download_user/Proxer-Downloader/.venv/bin/python +# Keep the cookie name from your working configuration; replace this placeholder. +# Name and '=' only; enter the cookie value in the download form. +TOKEN_PREFIX=YOUR_COOKIE_NAME= +MAX_SERIES_EPISODES=500 +HOST=127.0.0.1 +PORT=3000 diff --git a/.gitignore b/.gitignore index 30b61dc..d892d8a 100755 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .env node_modules .venv +.test-tmp-* diff --git a/README.md b/README.md index 5eff3c2..508c6e8 100755 --- a/README.md +++ b/README.md @@ -1,32 +1,118 @@ # Proxer-Downloader -Proxer (Token) -> Proxer-Downloader Web (Parameter) -> Python Script (Execution) +Express/EJS submission and status pages, a MongoDB episode queue, Node workers managed by PM2, and Python download entrypoints. -### Available Parameters -scripts/proxer-dl-series.py: - -i id [Number] [Required] - -n name [String] (Default: id_episode_language) [Optional (uncertain about that)] - -e episode range (delimiter "-") [String] [Required] - -l language [String] ["engsub", "engdub", "gersub", "gerdub"] - -t token [String] [Required] - -o output dir [String] (Default: /mnt/media/WIP/) +## Phase 1: reliable execution and a protected streaming boundary -scripts/proxer-dl-video.py: - -u url [String] [Required] - -f filename [String] (Default: id_episode_language) [Optional (uncertain about that)] - -t token [String] [Required] - -o output dir [String] (Default: /mnt/media/WIP/) +The Phase 1 changes preserve the original files in `scripts/lib/`, the streaming call sequence, existing CLI entrypoint names, and the established filename conventions. The top bar redesign, full modular execution architecture, expiring job ownership, automatic retries, and enforced bandwidth controls are later phases. See [the rollout roadmap](docs/rollout-roadmap.md). +The current worker records success only when Python exits with code 0, emits exactly one valid completed result, and produces a nonempty regular output file. This is a completion contract, not full media-integrity verification. The protected stream library still writes directly to the target file and cannot resume a partial transfer. -### Behaviour +## Runtime and configuration -- builds urls from parameters or vice versa, e.g.: https://proxer.me/watch/// -- save urls in a queue mongodb at 192.168.20.21:27023 -- should support multi-downloading up to 4 simultaenously using the queue db=downloads, collection=queue -- remove after downloaded and add success message, and download params to collection=done -- the token is always appened to a existing prefix -- use dotenv to store sensitive information, like mongodb connection string, and the token prefix -- Interface is a WebApp using express.js and ejs views in a dark/grey with red accent colors -- bootstrap flip/toggle switch at the top to toggle between Video and Series -- parameters manually appear depending on the mode -- at any error from the python script, it should prompt the website saying 'Token expired or Captcha required' with a confirm button to refresh and try again \ No newline at end of file +- Node.js **20.19.0 or later**, matching the locked MongoDB driver's minimum requirement. +- A Python environment with the existing dependencies in `scripts/requirements.txt`. Keep the working stream dependency versions for this rollout; validate them against the target interpreter before deployment. +- MongoDB accessible to the application and workers. +- PM2 on the download account's `PATH` when using the worker-management page. +- An existing writable output directory, normally `/mnt/media/WIP`, accessible to the download account through its `plex` group or the existing ACL. + +The application can live under `/home//Proxer-Downloader/` or another chosen checkout path. Worker script paths are resolved from the checkout; there is no account name embedded in the browser or server code. + +Install the locked Node dependencies, copy `.env.example` to `.env`, and replace the example settings with the working deployment values. Do not overwrite an existing production `.env` with the example. + +```sh +npm ci --ignore-scripts +``` + +| Variable | Meaning | Default | +|---|---|---| +| `MONGO_URI` | Private connection string | Required when connecting | +| `MONGO_DB` | Database used by both web and workers | `downloads` | +| `OUTPUT_DIR` | Existing media output directory | `/mnt/media/WIP` | +| `VENV_PYTHON` | Python executable; use the absolute virtual-environment path in production | `python3` | +| `TOKEN_PREFIX` | Existing cookie name followed by `=` | Required for submission | +| `MAX_SERIES_EPISODES` | Maximum episodes in one submission, from 1 to 10000 | `500` | +| `HOST` | Web listener address; the example uses loopback for a reverse proxy | `0.0.0.0` | +| `PORT` | Web listener port | `3000` | + +Configuration is loaded from the checkout's `.env`, independently of the caller's working directory. The web form accepts the cookie **value**; the server prepends `TOKEN_PREFIX`. The example cookie name is a placeholder: retain the name from the working configuration. No live token belongs in source control. + +Run PM2 and the application as the download account. Group access to media is separate from administrative network privileges. Preserve the deployment's existing reverse-proxy/firewall access boundary; this phase does not add application login or multi-user authorization. See [Debian 13 deployment and bandwidth assessment](docs/debian-13-deployment.md). + +## Verification + +```sh +npm run check:protected +npm test +``` + +The test runner checks the entire protected directory before and after all suites. It uses a temporary workspace and removes it afterward. Node tests use fake databases/processes and local fixtures; subprocess integration tests use copied CLI files with a synthetic stream module. Python tests use the standard library and disable bytecode generation. No test connects to production MongoDB or downloads media. + +Set `TEST_PYTHON` to an absolute interpreter path when the test interpreter should differ from `python3`. The protected check covers all seven original files, their executable flags, exact directory entries, additions, deletions, and symlinks. The frozen baseline must not be regenerated to hide an unexpected change. + +The current Phase 1 run, including the unresolved-link pause fix, passed **158 tests** (114 Node and 44 Python). See the [verification report](docs/phase-1-verification.md) for coverage, runtime versions, and the remaining deployment checks. + +## Start locally + +After configuring the database, interpreter, and output directory, start the web application and a worker in separate terminals or under the existing supervisor: + +```sh +npm start +``` + +```sh +npm run worker +``` + +The worker-management page creates workers using the configured checkout and current Node interpreter. It only lists and controls PM2 processes whose executable is this checkout's `queue_worker.js`; unrelated services are excluded. PM2 IDs are resolved on the server. Saving the host-wide PM2 process list is a deployment operation (`pm2 save` as the download account), so the web control is removed. + +## Submission and filenames + +Only HTTPS Proxer watch URLs on `proxer.me` or `www.proxer.me` are accepted. The URL must identify a positive integer series ID, positive integer episode, and one of `engsub`, `engdub`, `gersub`, or `gerdub`. Fragments and an optional trailing slash are normalized away. Query parameters, credentials in URLs, and custom ports are rejected. + +| Source | Filename before `.mp4` | +|---|---| +| Web video with title | Explicit legacy `filename`, then the form's `name` | +| Web video without title | `{id} E{episode} {language}` | +| Web series | `{trimmedNameOrId}E{paddedEpisode}_{language}` | +| Standalone series CLI | `{name}_Episode_{episode}_{language}` | + +Web series padding uses the width of the highest requested episode. All destinations are validated before a batch is queued. Filenames must be single names inside the configured directory; symlink and non-file targets are rejected. The corrected video-title fallback is intentional. [Compatibility fixtures](tests/fixtures/legacy-contracts.json) record the original conventions. + +## Python CLI compatibility + +Both original entrypoints remain available: + +```sh +python3 -B scripts/proxer-dl-video.py --help +python3 -B scripts/proxer-dl-series.py --help +``` + +Video arguments: `-u/--url`, `-f/--filename`, `-o/--output`, and either `-t/--token` or `--token-stdin`. + +Series arguments: `-i/--id`, `-n/--name`, `-e/--episodes` (inclusive `start-end`), `-l/--language`, `-o/--output`, and either token option. + +`--token-stdin` accepts one complete `cookie_name=value` followed by an optional newline and EOF. It preserves `=` inside the value and limits the complete cookie to 8192 UTF-8 bytes. Workers use this interface so credentials do not appear in process arguments. Legacy `-t` remains for compatibility. For a filename beginning with a dash, use `--filename=-Example` so the parser treats it as a value. + +Each download invocation emits a final `PROXER_RESULT` JSON record outside the library's progress output. Exit codes are 0 for completion, 1 for runtime failure, and 2 for invalid input. A series invocation returns a failure exit code when any episode fails and includes counts for completed, failed, and unattempted episodes. Help output remains normal CLI help. + +Both scripts disable bytecode writing before imports, and workers additionally launch Python with `-B` and `PYTHONDONTWRITEBYTECODE=1`. + +## Failure and shutdown behavior + +- Ordinary source/network/validation failures are recorded in failed history with the original job ID, source URL, filename, category, and a bounded sanitized log. They do not pause unrelated jobs. Automatic retries are deferred to the explicit attempt model. +- A missing embed or MP4 marker now produces a `resolution` result and pauses new downloads at the first failure. The full job stays queued for a deliberate retry, while its failed attempt remains visible in history. The banner describes possible CAPTCHA/login verification, an unavailable video, or a changed source page; it does not claim CAPTCHA is confirmed. Verified HTTP 404 remains an ordinary source failure. +- Verified HTTP 401/403 access rejection also pauses the pool and retains the job. The pause is persisted before attempt history and claim release. Workers recheck it after claiming and immediately before launching Python; transfers already admitted may finish. The global action resumes after external verification; it does not solve CAPTCHA or refresh an expired token stored in a queued job. +- Missing interpreter/dependencies and systemic output-storage failures retain the queued request and halt the worker. They do not consume the remaining queue or set a CAPTCHA block. +- On a handled stop, a started child must terminate before its job is made eligible again. A stop during pre-launch validation prevents the child from starting. Resuming an interrupted transfer restarts it from the beginning. +- History persistence must succeed before the queue record is removed. A database error leaves the processing claim held and stops the worker. + +The blanket `clear-processing` operation is disabled and returns HTTP 409. Phase 1 still uses legacy claims: forced kills, host loss, database failure, or multi-step history persistence can require manual reconciliation. Expiring ownership, automatic recovery, atomic job state, collision policy, staged output publication, and safe drain controls are later rollout phases. Never clear a claim while its Python process might still be writing. + +## Documentation + +- [Phase 1 baseline and compatibility boundary](docs/phase-1-baseline.md) +- [Phase 1 verification report](docs/phase-1-verification.md) +- [Unresolved-link pause fix and recovery](docs/phase-1-resolution-fix.md) +- [Debian 13 deployment and bandwidth assessment](docs/debian-13-deployment.md) +- [Rollout roadmap](docs/rollout-roadmap.md) diff --git a/controllers/pm2Controller.js b/controllers/pm2Controller.js index e4c77f9..fb7788a 100755 --- a/controllers/pm2Controller.js +++ b/controllers/pm2Controller.js @@ -1,180 +1,140 @@ -// controllers/pm2Controller.js -const { spawn } = require('child_process'); +const { spawn } = require('node:child_process'); +const path = require('node:path'); +const { config } = require('../lib/config'); -function runPm2Command(args, onData) { +function runPm2Command(args) { return new Promise((resolve, reject) => { - const cmd = spawn('pm2', args); + const child = spawn('pm2', args, { cwd: config.projectRoot, stdio: ['ignore', 'pipe', 'pipe'] }); let stdout = ''; let stderr = ''; - - cmd.stdout.on('data', data => { - const s = data.toString(); - stdout += s; - if (onData) onData({ type: 'stdout', data: s }); - }); - - cmd.stderr.on('data', data => { - const s = data.toString(); - stderr += s; - if (onData) onData({ type: 'stderr', data: s }); - }); - - cmd.on('close', code => resolve({ code, stdout, stderr })); - cmd.on('error', err => reject(err)); + let settled = false; + function finish(error, code) { + if (settled) return; + settled = true; + clearTimeout(timer); + if (error) reject(error); + else resolve({ code, stdout, stderr }); + } + const timer = setTimeout(() => { + child.kill(); + finish(new Error('PM2 did not respond in time.')); + }, 10000); + for (const [stream, field] of [[child.stdout, 'stdout'], [child.stderr, 'stderr']]) { + stream.on('data', (data) => { + if (field === 'stdout') stdout += data.toString(); + else stderr += data.toString(); + if (stdout.length + stderr.length > 1024 * 1024) { + child.kill(); + finish(new Error('PM2 response exceeded the supported size.')); + } + }); + } + child.on('error', () => finish(new Error('PM2 is unavailable for this account.'))); + child.on('close', (code) => finish(null, code)); }); } -function humanUptime(pm_uptime) { - if (!pm_uptime || pm_uptime <= 0) return '—'; - const diff = Date.now() - pm_uptime; - if (diff < 1000) return '0s'; - const sec = Math.floor(diff / 1000); - const days = Math.floor(sec / 86400); - const hrs = Math.floor((sec % 86400) / 3600); - const mins = Math.floor((sec % 3600) / 60); - const parts = []; - if (days) parts.push(days + 'd'); - if (hrs) parts.push(hrs + 'h'); - if (mins) parts.push(mins + 'm'); - if (!parts.length) parts.push((sec % 60) + 's'); - return parts.join(' '); +function humanUptime(timestamp) { + if (!timestamp || timestamp <= 0) return '—'; + const seconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000)); + const days = Math.floor(seconds / 86400); + const hours = Math.floor((seconds % 86400) / 3600); + const minutes = Math.floor((seconds % 3600) / 60); + return [days && `${days}d`, hours && `${hours}h`, minutes && `${minutes}m`].filter(Boolean).join(' ') || `${seconds % 60}s`; } -function normalizeProcess(p) { - const pid = - p.pid || - (p.pm2_env && p.pm2_env.pm_pid) || - (p.pm2_env && p.pm2_env.pmx && p.pm2_env.pmx.pid) || - null; - - const status = (p.pm2_env && p.pm2_env.status) || p.status || 'unknown'; - - let cpu = null, memoryMB = null; - if (p.monit) { - cpu = typeof p.monit.cpu === 'number' ? p.monit.cpu : null; - memoryMB = typeof p.monit.memory === 'number' ? Math.round(p.monit.memory / 1024 / 1024) : null; - } else if (p.pm2_env && p.pm2_env.axm_monitor) { - cpu = p.pm2_env.axm_monitor.cpu; - memoryMB = p.pm2_env.axm_monitor.memory ? Math.round(p.pm2_env.axm_monitor.memory / 1024 / 1024) : null; - } else if (p.pm2_env && p.pm2_env.monit) { - cpu = p.pm2_env.monit.cpu; - memoryMB = p.pm2_env.monit.memory ? Math.round(p.pm2_env.monit.memory / 1024 / 1024) : null; - } - - const pm_uptime = (p.pm2_env && p.pm2_env.pm_uptime) || (p.pm_uptime || 0); - const uptime = humanUptime(pm_uptime); - +function normalizeProcess(process) { + const env = process.pm2_env || {}; + const cpu = process.monit?.cpu; + const memory = process.monit?.memory; return { - name: p.name || (p.pm2_env && p.pm2_env.name) || '—', - pid: pid || '—', - pm_id: (p.pm2_env && p.pm2_env.pm_id) || (p.pm_id !== undefined ? String(p.pm_id) : '—'), - status, - cpu: cpu != null ? Number(cpu).toFixed(1) + '%' : '—', - memoryMB: memoryMB != null ? memoryMB + ' MB' : '—', - uptime, - execPath: - (p.pm2_env && p.pm2_env.pm_exec_path) || - (p.pm2_env && p.pm2_env.exec_interpreter) || - '—', - raw: p + name: String(process.name || env.name || '—'), + pid: process.pid || '—', + pm_id: String(process.pm_id ?? env.pm_id ?? '—'), + status: String(env.status || process.status || 'unknown'), + cpu: typeof cpu === 'number' ? `${cpu.toFixed(1)}%` : '—', + memoryMB: typeof memory === 'number' ? `${Math.round(memory / 1024 / 1024)} MB` : '—', + uptime: humanUptime(env.pm_uptime), + execPath: env.pm_exec_path || '—', }; } -// =============================== -// VIEW: Render UI -// =============================== -exports.getManage = async (req, res, next) => { - try { - const { stdout } = await runPm2Command(['jlist']); - let processes = []; - try { - const parsed = JSON.parse(stdout || '[]'); - processes = Array.isArray(parsed) ? parsed.map(normalizeProcess) : []; - } catch (e) { - processes = []; - } - res.render('pm2', { title: 'PM2 Manager', processes }); - } catch (err) { - next(err); - } -}; +function validName(name) { + return typeof name === 'string' && /^[A-Za-z0-9][\w-]{0,63}$/.test(name) && name.toLowerCase() !== 'all'; +} -// =============================== -// JSON Process List -// =============================== -exports.listJson = async (req, res) => { - try { - const { stdout } = await runPm2Command(['jlist']); - let processes = []; +function createPm2Controller({ run = runPm2Command, settings = config } = {}) { + function managed(process) { + const executable = process.pm2_env?.pm_exec_path; + return typeof executable === 'string' && path.resolve(executable) === settings.workerScript; + } + + async function processes() { + const response = await run(['jlist']); + if (response.code !== 0) throw new Error('PM2 process list is unavailable.'); + let parsed; + try { parsed = JSON.parse(response.stdout); } catch { throw new Error('PM2 returned an invalid process list.'); } + if (!Array.isArray(parsed)) throw new Error('PM2 returned an invalid process list.'); + return parsed; + } + + async function resolveManagedProcess(name) { + if (!validName(name)) return null; + const matches = (await processes()).filter((process) => managed(process) && (process.name || process.pm2_env?.name) === name); + if (matches.length !== 1) return null; + const id = matches[0].pm_id ?? matches[0].pm2_env?.pm_id; + if (!Number.isInteger(id) || id < 0) return null; + return { ...normalizeProcess(matches[0]), pm_id: String(id) }; + } + + async function getManage(req, res, next) { try { - const parsed = JSON.parse(stdout || '[]'); - processes = Array.isArray(parsed) ? parsed.map(normalizeProcess) : []; + res.render('pm2', { title: 'Proxer Workers', processes: (await processes()).filter(managed).map(normalizeProcess) }); + } catch (error) { next(error); } + } + + async function listJson(req, res) { + try { + res.json({ ok: true, processes: (await processes()).filter(managed).map(normalizeProcess) }); } catch { - processes = []; + res.status(503).json({ ok: false, error: 'The worker supervisor is unavailable.' }); } - res.json({ ok: true, processes }); - } catch (err) { - res.status(500).json({ ok: false, error: err.message }); - } -}; - -// =============================== -// COMMAND EXECUTION -// =============================== -exports.postCommand = async (req, res) => { - // expected body: { cmd:'create'|'start'|'stop'|'restart'|'delete'|'save', name?, scriptPath? } - - const allowed = new Set([ - 'start', 'stop', 'restart', 'delete', 'save', 'create' - ]); - - const { cmd, name, scriptPath } = req.body; - - if (!allowed.has(cmd)) { - return res.status(400).json({ ok: false, error: 'Invalid command' }); } - try { - let args = []; - - // ------------------------------- - // CREATE = start script with name - // ------------------------------- - if (cmd === 'create') { - if (!scriptPath || !name) { - return res.status(400).json({ ok: false, error: 'scriptPath and name required' }); - } - if (!/^[\w-]+$/.test(name)) { - return res.status(400).json({ ok: false, error: 'Invalid process name' }); - } - args = ['start', scriptPath, '--name', name]; - console.log(args) + async function postCommand(req, res) { + const { cmd, name, scriptPath } = req.body || {}; + if (!['start', 'stop', 'restart', 'delete', 'save', 'create'].includes(cmd)) { + return res.status(400).json({ ok: false, error: 'Invalid command.' }); } - - // ------------------------------- - // SAVE - // ------------------------------- - else if (cmd === 'save') { - args = ['save']; + if (cmd === 'save') { + return res.status(409).json({ ok: false, error: 'Saving the full PM2 process list is a host-level operation. Run pm2 save as the download user during deployment.' }); } - - // ------------------------------- - // start/stop/restart/delete - // ------------------------------- - else { - if (!name) { - return res.status(400).json({ ok: false, error: 'name is required' }); + if (!validName(name)) return res.status(400).json({ ok: false, error: 'Invalid worker name.' }); + try { + let args; + if (cmd === 'create') { + if (scriptPath !== undefined && scriptPath !== settings.workerScript) { + return res.status(400).json({ ok: false, error: 'The worker executable is configured by the server.' }); + } + if ((await processes()).some((process) => (process.name || process.pm2_env?.name) === name)) { + return res.status(409).json({ ok: false, error: 'This process name is already in use.' }); + } + args = ['start', settings.workerScript, '--name', name, '--cwd', settings.projectRoot, + '--interpreter', process.execPath, '--kill-timeout', '10000']; + } else { + const worker = await resolveManagedProcess(name); + if (!worker) return res.status(404).json({ ok: false, error: 'The selected downloader worker was not found.' }); + args = [cmd, worker.pm_id]; } - if (!/^[\w-]+$/.test(name)) { - return res.status(400).json({ ok: false, error: 'Invalid process name' }); - } - args = [cmd, name]; + const { code } = await run(args); + return res.status(code === 0 ? 200 : 502).json({ ok: code === 0, code, + message: code === 0 ? 'Worker command completed.' : 'Worker command failed. Check the supervisor on the server.' }); + } catch { + return res.status(503).json({ ok: false, error: 'The worker supervisor is unavailable.' }); } - - const { code, stdout, stderr } = await runPm2Command(args); - res.json({ ok: code === 0, code, stdout, stderr }); - - } catch (err) { - res.status(500).json({ ok: false, error: err.message }); } -}; + + return { getManage, listJson, postCommand, resolveManagedProcess }; +} + +module.exports = { ...createPm2Controller(), createPm2Controller, normalizeProcess, validName }; diff --git a/controllers/queueController.js b/controllers/queueController.js index 1a7f981..2c0b30c 100755 --- a/controllers/queueController.js +++ b/controllers/queueController.js @@ -1,199 +1,108 @@ +const fs = require("node:fs/promises"); const { getDb } = require("../lib/mongo"); -const fs = require("fs"); -const path = require("path"); +const { config } = require("../lib/config"); +const { + ValidationError, STATUS_READ_PROJECTION, buildQueueJobs, toPublicJob, validateOutputTarget, +} = require("../lib/jobValidation"); -exports.enqueue = async (req, res) => { - try { - const db = await getDb(); - const body = req.body; +function createQueueController(dependencies = {}) { + const connect = dependencies.getDb || getDb; + const settings = dependencies.config || config; + const now = dependencies.now || (() => new Date()); - // Token always required - if (!body.token) throw new Error("token required"); - - const token_prefix = process.env.TOKEN_PREFIX; - const token = token_prefix + body.token; - - // ========================================= - // VIDEO MODE - // ========================================= - if (body.mode === "video") { - if (!body.url) throw new Error("url required"); - var filename; - if (!body.filename) { - let split_slash = body.url.split("/"); - let split_hash = - `${split_slash[4]} E${split_slash[5]} ${split_slash[6]}`.split("#"); - filename = split_hash[0]; - console.log(filename); + async function enqueue(req, res) { + try { + const jobs = await buildQueueJobs(req.body, settings, now); + const db = await connect(); + if (jobs.length === 1 && req.body.mode === "video") { + await db.collection("queue").insertOne(jobs[0]); } else { - filename = body.filename; + await db.collection("queue").bulkWrite(jobs.map(document => ({ insertOne: { document } }))); } - - await db.collection("queue").insertOne({ - url: body.url, - token, - filename, - created_at: new Date(), + return res.redirect("/status"); + } catch (error) { + const invalid = error instanceof ValidationError; + return res.status(invalid ? 400 : 500).render("error", { + title: "Enqueue failed", + message: invalid ? error.message : "The download could not be queued. Check the service configuration and try again.", + details: null, }); - - return res.redirect("/status"); } - - // ========================================= - // SERIES MODE - // ========================================= - if (body.mode === "series") { - if (!body.id) throw new Error("id required"); - if (!body.language) throw new Error("language required"); - if (!body.episode_from) throw new Error("episode_from required"); - if (!body.episode_to) throw new Error("episode_to required"); - - const id = body.id; - const lang = body.language; - const name = body.name?.trim() || null; - - const from = parseInt(body.episode_from); - const to = parseInt(body.episode_to); - - if (isNaN(from) || from <= 0) - throw new Error("episode_from must be a valid number"); - - if (isNaN(to) || to < from) - throw new Error("episode_to must be >= episode_from"); - - // Insert one queue item per episode - const ops = []; - - // Determine padding width based on the highest episode number - const pad = String(to).length; - - for (let ep = from; ep <= to; ep++) { - const epStr = String(ep).padStart(pad, "0"); - - const url = `https://proxer.me/watch/${id}/${ep}/${lang}`; - - const filename = name - ? `${name}E${epStr}_${lang}` - : `${id}E${epStr}_${lang}`; - - ops.push({ - insertOne: { - document: { - url, - token, - filename, - created_at: new Date(), - }, - }, - }); - } - - await db.collection("queue").bulkWrite(ops); - - return res.redirect("/status"); - } - - throw new Error("Invalid mode"); - } catch (err) { - res.render("error", { - title: "Enqueue Failed", - message: err.message, - details: err.stack, - }); } -}; -exports.status = async (req, res) => { - const db = await getDb(); - - const queued = await db - .collection("queue") - .find({ $or: [{ processing: { $exists: false } }, { processing: false }] }) - .sort({ created_at: 1 }) - .toArray(); - - const processing = await db - .collection("queue") - .find({ processing: true }) - .sort({ created_at: 1 }) - .toArray(); - - const done = await db - .collection("done") - .find({}) - .sort({ finished_at: -1 }) - .toArray(); - - const failed = await db - .collection("failed") - .find({}) - .sort({ failed_at: -1 }) - .toArray(); - - const settings = - (await db.collection("settings").findOne({ _id: "global" })) || {}; - console.log; - res.render("status", { - queued, - processing, - finished: done, - failed, - global: settings, - }); -}; - -exports.statusData = async (req, res) => { - const db = await getDb(); - - const queued = await db - .collection("queue") - .find({ processing: { $ne: true } }) - .sort({ created_at: 1 }) - .toArray(); - - const processing = await db - .collection("queue") - .find({ processing: true }) - .sort({ created_at: 1 }) - .toArray(); - - const done = await db - .collection("done") - .find({}) - .sort({ finished_at: -1 }) - .toArray(); - - const failed = await db - .collection("failed") - .find({}) - .sort({ failed_at: -1 }) - .toArray(); - - // File sizes - const OUTPUT_DIR = process.env.OUTPUT_DIR || "/mnt/media/WIP"; - for (const list of [processing, done]) { - for (const job of list) { + async function readStatus() { + const db = await connect(); + const queries = [ + ["queue", { processing: { $ne: true } }, { created_at: 1 }], + ["queue", { processing: true }, { created_at: 1 }], + ["done", {}, { finished_at: -1 }], + ["failed", {}, { failed_at: -1 }], + ]; + const lists = await Promise.all(queries.map(async ([collection, filter, sort]) => { + const records = await db.collection(collection).find(filter, { projection: STATUS_READ_PROJECTION }).sort(sort).toArray(); + return records.map(toPublicJob); + })); + const [queued, processing, done, failed] = lists; + // Asynchronous file checks avoid blocking the web process. Pagination follows in Phase 2. + for (const job of [...processing, ...done]) { try { - const stat = fs.statSync(path.join(OUTPUT_DIR, `${job.filename}.mp4`)); - job.fileSize = stat.size; + const target = await validateOutputTarget(settings.outputDir, job.filename); + const stat = await fs.lstat(target); + job.fileSize = stat.isFile() && !stat.isSymbolicLink() ? stat.size : null; } catch { job.fileSize = null; } } + const global = await db.collection("settings").findOne({ _id: "global" }, { projection: { captcha_blocked: 1, pause_reason: 1 } }); + return { + queued, processing, done, failed, + global: { + captcha_blocked: global?.captcha_blocked === true, + pause_reason: ["authentication", "resolution"].includes(global?.pause_reason) ? global.pause_reason : null, + }, + }; } - // Fetch global settings - const settings = await db.collection("settings").findOne({ _id: "global" }) || {}; - settings.captcha_blocked = !!settings.captcha_blocked; + async function status(req, res, next) { + try { + const snapshot = await readStatus(); + return res.render("status", { ...snapshot, finished: snapshot.done }); + } catch (error) { + return next(error); + } + } - // Send JSON including global - res.json({ - queued, - processing, - done, - failed, - global: settings, - }); -}; + async function statusData(req, res, next) { + try { + res.set("Cache-Control", "no-store"); + return res.json(await readStatus()); + } catch (error) { + return next(error); + } + } + function clearProcessing(req, res) { + return res.status(409).render("error", { + title: "Active downloads are protected", + message: "Active processing flags cannot be cleared safely while downloads may still be running. Stop the affected worker and verify that its download has ended before performing recovery.", + details: null, + }); + } + async function clearCaptcha(req, res, next) { + try { + const db = await connect(); + await db.collection("settings").updateOne({ _id: "global" }, { + $set: { captcha_blocked: false }, + $unset: { pause_reason: "" }, + }); + return res.redirect("/status"); + } catch (error) { + return next(error); + } + } + + return { enqueue, status, statusData, clearProcessing, clearCaptcha }; +} + +module.exports = { ...createQueueController(), createQueueController }; diff --git a/docs/debian-13-deployment.md b/docs/debian-13-deployment.md new file mode 100644 index 0000000..e6c3ce6 --- /dev/null +++ b/docs/debian-13-deployment.md @@ -0,0 +1,93 @@ +# Debian 13 deployment baseline and bandwidth assessment + +Assessment date: 23 October 2026. + +## Intended environment + +The operator specified Debian 13, an application under `/home//`, and write access to `/mnt/media/WIP/` through the `plex` group, with `sudo` available for administration. A concrete project directory such as `/home//Proxer-Downloader/` can be used without hardcoding the account name in application code. + +These are operator-supplied deployment requirements. This checkout has not inspected or changed that server, its users, PM2 state, mount permissions, MongoDB, firewall, or network interfaces. + +### Application identity and paths + +Run the web application, PM2 daemon, Node workers, and Python download children as the download account. Access to the media directory should work through ordinary group permissions or the existing ACL. Administrative `sudo` access does not require the application itself to execute as root. + +Use the project's configuration for the actual locations: + +| Setting | Intended value or requirement | +|---|---| +| Project working directory | `/home//Proxer-Downloader/`, or the chosen directory under that home | +| `OUTPUT_DIR` | `/mnt/media/WIP` | +| `VENV_PYTHON` | Absolute path to this project's virtual environment Python executable | +| `MONGO_URI` | Existing deployment connection string, kept outside version control | +| `MONGO_DB` | `downloads` unless deliberately configured otherwise; web and workers must agree | +| `TOKEN_PREFIX` | Configured cookie name followed by `=`; do not put a live cookie token in documentation | +| `MAX_SERIES_EPISODES` | Bounded per-submission range; Phase 1 default is 500 | +| `PYTHONDONTWRITEBYTECODE` | `1`, in addition to the worker's `-B` launch argument | + +The current lockfile's MongoDB driver requires Node `>=20.19.0`; verify the installed runtime against [package-lock.json](../package-lock.json). Preserve the existing Python streaming dependency versions during this phase, using an isolated virtual environment. Dependency upgrades require separate stream compatibility verification. + +PM2 supports a systemd startup entry for a chosen user and home directory, and restores the saved process list on boot. Generate that startup integration as the intended download account and review the exact command produced for that installation. Avoid accidentally operating a second root-owned PM2 daemon. See the [PM2 startup documentation](https://pm2.keymetrics.io/docs/usage/startup/). + +### Media access check before deployment + +Confirm the running process identity, not only the interactive login, has the expected `plex` membership. Inspect the mount, directory traversal permissions, ACL, and available space before starting workers. If group membership was changed, restart the relevant service/session so its group list is refreshed. Existing shared media permissions should be preserved; the rollout does not call for recursively changing ownership or permissions under `/mnt/media`. + +For a systemd-managed process, `User=`, `SupplementaryGroups=`, `WorkingDirectory=`, and `UMask=` provide explicit execution settings. A group-compatible output mask should be chosen to match the existing media policy. The actual mount's ACL may also affect resulting permissions. See Debian's [systemd.exec manual](https://manpages.debian.org/trixie/systemd/systemd.exec.5.en.html). + +A single small create/write/remove probe by the download account can validate the intended output directory at deployment time. It has not been performed by this source-only Phase 1 work. No routine runtime command needs `sudo` merely to write an MP4 when the directory permissions are correct. + +## Bandwidth decision + +**Phase 1 conclusion: Debian 13 provides suitable external mechanisms, but no bandwidth backend is enabled or performance-validated by this change.** The later worker-controls phase must demonstrate global and per-worker incoming limits on the intended host before reporting a cap as enforced. + +The protected [`download_mp4`](../scripts/lib/proxer_utils.py) implementation supplies no limiter callback and does not support byte-level resume. Preserve that transport and place enforcement outside the Python library. Delay between episodes, worker count, CPU quota, disk I/O quota, or speed measurement are different controls and must not be presented as a byte-rate cap. + +### Recommended design: isolated worker traffic with an external shaper + +Use a dedicated, identifiable path for Python download traffic. A worker network namespace or equivalent isolated interface is a candidate that can coexist with native PM2: the Node worker may remain under PM2 while the supervised download child enters its registered worker network context. Filesystem access and the download account remain unchanged. Debian's [ip-netns manual](https://manpages.debian.org/trixie/iproute2/ip-netns.8.en.html) documents executing namespace-unaware programs in a named network namespace. This is a proposed architecture, not a configuration already installed here. + +A production prototype should route all participating download traffic through a common worker-bound shaping point, with one parent bandwidth budget and a class for each registered worker. A dedicated gateway interface or an IFB-based path is a possible implementation; select the exact topology after inspecting existing routes, interfaces, DNS, IPv4/IPv6, firewall policy, and local services. Classification must remain valid after address translation and must cover return traffic. Classifying an incoming download solely by the Python process ID is insufficient as a design specification. + +Linux `tc` shapes traffic on an interface's outgoing path; inbound policing has different behavior. To control downloads, place the shaper on the outgoing side of a path leading *toward* the workers, or use a deliberately tested redirection mechanism. A limit attached only to the physical NIC's outbound traffic does not establish a download cap. See Debian's [tc manual](https://manpages.debian.org/trixie/iproute2/tc.8.en.html). + +HTB is a candidate for a shared parent and per-worker children. Its `rate`, `ceil`, classification, and burst settings must be configured together and verified; the parent must cover all worker classes. This gives the required semantics that four workers capped at 3 MiB/s still share an 8 MiB/s global ceiling. Account for protocol overhead and the defined measurement interval when setting tolerances. See Debian's [tc-htb manual](https://manpages.debian.org/trixie/iproute2/tc-htb.8.en.html). + +Start with one active download per worker. Keep bandwidth policy distinct from how many workers may run. A later change to multi-child workers must keep their aggregate traffic within the worker's class. + +### Privilege separation + +Network setup and shaping require administrative network permissions; ordinary media-directory group access does not provide them. Linux describes interface, routing, firewall, and related privileges under `CAP_NET_ADMIN`. See Debian's [capabilities manual](https://manpages.debian.org/trixie/manpages/capabilities.7.en.html). + +The application should request a narrowly defined operation from a separately installed, administrator-controlled helper or service. The helper must resolve registered worker IDs and allowlisted rates/interfaces itself. It must not accept arbitrary shell commands, device names, scripts, or namespace paths from HTTP requests. Download children should run under the download account after entering their prepared context. Do not grant the web application unrestricted passwordless `sudo`, and do not run the web server as root to obtain traffic control. + +Debian systemd can join a prepared namespace using `NetworkNamespacePath=` for suitable services. Its network accounting and address filtering settings are useful for observation and policy, but are not a general download-bytes-per-second limiter. See the [systemd execution manual](https://manpages.debian.org/trixie/systemd/systemd.exec.5.en.html) and [resource-control manual](https://manpages.debian.org/trixie/systemd/systemd.resource-control.5.en.html). The exact PM2/helper/service integration remains a later implementation choice. + +### Lower-infrastructure candidate: trickle and trickled + +Debian 13 includes `trickle`. It is a cooperative userspace shaper for supported stream sockets; its manual excludes statically linked and setuid executables. A compatible dynamically linked Python process is therefore worth testing, but the installed Python/OpenSSL/Requests stack must be measured rather than assumed compatible. The wrapper's use of library interposition also deserves explicit review against the requirement to preserve stream behavior. See the [Debian package page](https://packages.debian.org/en/trixie/net/trickle) and [trickle manual](https://manpages.debian.org/trixie/trickle/trickle.1.en.html). + +`trickled` coordinates several participating sessions and documents an aggregate download limit. Independent standalone `trickle` processes cannot establish one shared global budget by themselves. Use a private, explicitly configured coordination socket if this candidate is tested, and verify both the local worker ceiling and the shared limit under failure and restart. See the [trickled manual](https://manpages.debian.org/trixie/trickle/trickled.8.en.html). + +This remains a candidate, not a shipped fallback. The application must not silently run an advertised limited worker without enforcement if its limiter is missing or unhealthy. Per-job caps and dynamic cap changes should only be exposed after the selected backend's behavior is proven. + +## Required host facts and controlled validation + +Before implementing the limiter, establish the actual PM2 service identity and installation, Python executable, kernel/network capability availability, interface/route topology, IPv6 usage, firewall manager, and whether other applications share the proposed network path. Confirm that MongoDB and the web management interface remain reachable according to their existing access model. No assumption that `sudo` membership automatically grants a particular noninteractive helper permission should be baked into code. + +Use a controlled local or staging HTTP/HTTPS server with generated payloads for the initial benchmark. Test the unchanged protected download function with bytecode writes disabled; no user token or production media source is necessary for that test. + +Acceptance cases for the later implementation: + +1. One transfer respects its cap over a specified measurement interval, including a defined short burst allowance. +2. Two and four simultaneous workers respect both their individual ceilings and the aggregate parent budget. +3. Idle workers release unused capacity according to the chosen sharing policy. +4. IPv4 and IPv6 follow the enforced path, and redirects do not escape it. +5. Resolver requests, TLS, long transfers, missing content lengths, and slow servers remain functional. +6. Limiter loss or misconfiguration produces a visible enforcement failure; it does not silently become unlimited. +7. Reducing or removing a cap has a documented immediate/next-job/restart behavior. +8. Worker stop, cancellation, and reboot leave no orphan download processes or abandoned network rules. +9. Unrelated host traffic remains outside the downloader-specific policy. +10. All protected-library hashes and entries still match the baseline after the run. + +No privileged helper, `tc` rule, namespace, systemd unit, sudoers rule, or bandwidth setting is created by Phase 1. This document supplies the deployment boundary and feasibility decision for the later worker-controls phase. diff --git a/docs/phase-1-baseline.md b/docs/phase-1-baseline.md new file mode 100644 index 0000000..8314882 --- /dev/null +++ b/docs/phase-1-baseline.md @@ -0,0 +1,69 @@ +# Phase 1 baseline and compatibility boundary + +Reviewed upstream commit: `211bfd174dd78eac36f3c74411ecaa72f56eec79`. + +This baseline describes the source checkout, not a verified production deployment. The Phase 1 review and automated checks use synthetic job records, temporary files, and controlled subprocesses. They do not contact the production database or fetch authenticated media. + +## Protected library + +`scripts/lib/` is immutable for this rollout. The complete reviewed directory contains two Python source files and five tracked Python bytecode files. All seven files have the executable bit set in the original Git tree (`100755`). Their original contents and that Git-relevant mode are recorded in [the manifest](../tests/fixtures/protected-lib-manifest.json). + +Run the read-only integrity check from the project directory: + +```sh +node tools/check-protected-lib.js +``` + +The check verifies SHA-256 content hashes, file types, executable bits, the directory structure, and the exact set of entries. Extra bytecode, hidden files, empty directories, symbolic links, removed files, and changed files cause failure. It does not rely on `.gitignore` or only on tracked-file differences. It never imports a Python module or rewrites the manifest. + +Future Python commands must disable bytecode output (`python -B` or `PYTHONDONTWRITEBYTECODE=1`) before loading the protected modules. Do not regenerate the baseline to accept an unexpected change. Investigate and restore the original protected tree instead. Directory ownership and ordinary read/write permission bits are deployment concerns; the integrity check preserves Git's executable/nonexecutable distinction without requiring a specific UID, GID, or umask. + +The checker regression tests mutate only temporary copies: + +```sh +node tests/protected-lib.test.js +``` + +## Captured compatibility fixtures + +[legacy-contracts.json](../tests/fixtures/legacy-contracts.json) records examples of the old CLI flags, filenames, and MongoDB document shapes. Every token, object ID, timestamp, title, and log is fictional. The source URLs describe valid input syntax only and must not be fetched by fixture tests. + +| Entry point | Required arguments at the reviewed commit | Filename convention | +|---|---|---| +| Video CLI | `-u/--url`, `-f/--filename`, `-t/--token`, `-o/--output` | Explicit filename plus `.mp4` | +| Series CLI | `-i/--id`, `-n/--name`, `-e/--episodes`, `-l/--language`, `-t/--token`, `-o/--output` | `{name}_Episode_{episode}_{language}.mp4` | +| Web video | `mode=video`, `url`, `token`, optional `filename` | Default `{id} E{episode} {language}`, then `.mp4` at execution | +| Web series | `mode=series`, `id`, `language`, `episode_from`, `episode_to`, `token`, optional `name` | `{trimmedNameOrId}E{paddedEpisode}_{language}`, then `.mp4` at execution | + +Web series episode padding uses the width of the final episode number. The standalone series CLI does not use that padding. The supported language values are `engsub`, `engdub`, `gersub`, and `gerdub`. The actual CLI parsers required the flags above even though the original README described some arguments as optional. + +The source web form submitted the title as `name`, but video enqueue looked only for `filename`. Accepting the form title as a fallback is an intentional Phase 1 correction. Explicit legacy `filename` input remains meaningful. + +## Legacy job data + +The reviewed `queue` documents contain URL, cookie token, filename, and enqueue time, plus an optional `processing` boolean. The `done` and `failed` documents contain filename, terminal time, and output log, but generally lack the original URL and token. The fixtures preserve these limitations rather than inventing retry information. + +The atomic queue claim already exists in the original source. Phase 1 does not claim to introduce expiring ownership, recovery, exactly-once execution, or a new authoritative job schema. Those belong to later phases. In particular, a process killed during an attempt can still leave a legacy processing record requiring deliberate reconciliation; it must not be made eligible again while its child is still running. + +## Deliberate corrections and boundaries + +Phase 1 establishes truthful Python results and worker handling, handles child startup errors, validates inputs and output containment, removes the blanket processing reset, and limits public response fields. Error reports must not expose submitted credentials or signed media URLs. A download must not be recorded as complete merely because a broad keyword search did not find an error. + +The protected functions continue to resolve the embed URL, resolve the MP4 URL, and download the file in that order. New result handling is outside `scripts/lib/`. The protected transfer function still has no byte-resume, rate-limit, socket-timeout, or structured-progress hook. Its no-content-length path can buffer the response; completion checks based on a nonempty file alone cannot establish full media integrity. + +The initial Phase 1 release classified the protected library's missing-page-marker error as an ordinary source failure. Following a report that this consumed successive queued episodes during a possible verification challenge, the current revision classifies it as `resolution` and pauses at the first occurrence while preserving the queued request. This is an attention gate, not proof of CAPTCHA. The [fix and recovery note](phase-1-resolution-fix.md) explains the distinction and existing failed-job handling. + +The user-interface redesign, durable lease/retry model, temporary-file publication design, and actual bandwidth control are later-phase work. Any Phase 1 tests that simulate process outcomes establish application behavior under those outcomes; they do not prove remote Proxer compatibility or performance on the intended server. + +## Review gates + +Before accepting a Phase 1 change: + +1. Run the protected-library integrity check. +2. Run the Node and Python regression suites, with Python bytecode writes disabled. +3. Confirm the synthetic filename and CLI contracts, allowing only the documented corrections. +4. Confirm failed exit codes, missing result records, malformed results, and child startup errors cannot become successful jobs. +5. Confirm status payloads and rendered logs do not reveal tokens or raw process environments. +6. Run the integrity check again to catch generated files as well as edits. + +Deployment-specific preparation and the external bandwidth feasibility decision are documented in [Debian 13 deployment](debian-13-deployment.md). diff --git a/docs/phase-1-resolution-fix.md b/docs/phase-1-resolution-fix.md new file mode 100644 index 0000000..12a944b --- /dev/null +++ b/docs/phase-1-resolution-fix.md @@ -0,0 +1,90 @@ +# Unresolved-link pause fix + +Date: 23 October 2026. + +## Observed behavior and cause + +After installing Phase 1, the user reported that individual episodes downloaded, +but a failure to resolve the download link was followed by failures on subsequent +episodes until the worker was stopped manually. + +The source code explains this path. The unchanged protected library raises +`lib.proxer_utils.NotFoundError` when an episode page has no expected embed marker +or a player page has no expected MP4 marker. Its HTTP request may have succeeded; +the exception does not carry enough evidence to decide whether the page is a +CAPTCHA/login challenge, an unavailable video, or an altered page format. + +The initial Phase 1 classifier grouped that error with ordinary source failures. +The worker moved each failed job into history and continued. Its pause condition +covered verified HTTP 401/403 rejection only. That condition was too narrow to +protect the queue in the reported situation. The actual page received on the +user's server was not inspected, so CAPTCHA is a possible cause, not a confirmed +diagnosis. + +## Corrected behavior + +| Evidence | Category | Action | +|---|---|---| +| Missing embed/MP4 marker reported by the protected library | `resolution` | Pause the pool immediately and retain the queued request | +| Verified HTTP 401/403 response in the exception chain | `authentication` | Pause the pool and retain the request | +| Verified HTTP 404 | `source` | Record an ordinary failed job | +| Other network or validation failure | Existing category | Preserve the existing ordinary failure behavior | + +For a resolution/access pause, the worker first persists +`captcha_blocked: true` and its allowlisted `pause_reason`, then records the failed +attempt, then releases only that job's `processing` and `started_at` fields. It +does not delete the request, filename, URL, or stored token. A failed or +unacknowledged persistence operation stops the worker instead of falling through +to queue deletion. + +Workers check the pause before claiming, after claiming, and again after output +validation immediately before launching Python. A denied launch preserves the +job without creating failed history. An already admitted transfer may finish; +the legacy queue does not make the global read and process spawn atomic. It does +not continue claiming while the pause remains set. + +The banner explains that verification is needed and lists possible causes. Use +**Resume after verification** only after checking the relevant source page. The +action clears the pause and reason; it neither solves CAPTCHA nor updates tokens +already stored in queued jobs. If a token expired, supplying a new token to a new +submission does not alter older queued requests. + +The standalone series CLI also stops at the first unresolved link and reports +the remaining episodes as not attempted. It does not skip through the rest of +the requested range. + +This deliberately also pauses for an unavailable video or a parser mismatch when +the protected library reports the same missing marker. It avoids inventing +CAPTCHA detection from arbitrary log text or issuing additional source requests. +No protected file, streaming call sequence, or dependency version is changed. + +## Installation and existing failures + +Install this fix over the previously supplied Phase 1 update. Stop the relevant +web process and all downloader workers for this checkout, verify their children +have stopped, and replace the complete supplied file set. Restart every worker +along with the web process. An old Node worker does not recognize the new +`resolution` result and would keep the earlier failure behavior. + +Episodes already moved to failed history by the earlier release are not restored +automatically. Those records contain the source URL, filename, and original job +ID, but no cookie. Identify the affected episodes, check existing queued/completed +records and output files, then resubmit the missing episodes using a currently +valid token and their original filenames. Retain failed history while reconciling +them. Do not bulk-clear processing claims or blindly restore every failed record. + +No database migration or new configuration variable is required. The existing +`captcha_blocked` field and `/clear-captcha` endpoint remain compatible. + +## Verification + +The complete current suite passes **158 tests: 114 Node and 44 Python**, with no +failures or skips. The real Node-to-Python subprocess fixture reproduces both +resolver stages, observes the new result, then verifies that the affected job and +the next episode remain queued and no next claim is made. Other regressions cover +pause-before-history ordering, persistence failures, concurrent claim/launch +checks, HTTP status distinctions, series stopping, and banner/resume behavior. + +These are controlled local tests with synthetic stream modules and database +interfaces. No live source response or production database was used. All seven +protected library files match the original baseline before and after the tests. diff --git a/docs/phase-1-verification.md b/docs/phase-1-verification.md new file mode 100644 index 0000000..d594910 --- /dev/null +++ b/docs/phase-1-verification.md @@ -0,0 +1,56 @@ +# Phase 1 verification report + +Verification date: 23 October 2026. + +**Current result: all 158 tests passed, with no failures, cancellations, or skips.** This includes the unresolved-link pause fix following the user's report of successive failed episodes. The protected library matched the reviewed baseline before and after the integrated run, and an independent check passed afterward. The initial Phase 1 release passed 141 tests. + +The work is available as uncommitted local changes on `phase-1-reliability`, based on upstream commit `211bfd174dd78eac36f3c74411ecaa72f56eec79`. The user installed the initial file update and reported successful episode downloads, followed by an unresolved-link failure that did not pause the queue. This revision fixes that local handling; it has not been checked against the user's live source response or production server. Production validation remains part of the rollout. + +## Executed checks + +The integrated command was: + +```sh +npm test +``` + +| Suite | Passed | What it establishes | +|---|---:|---| +| Python downloader | 44 | CLI validation, preserved filename conventions and stream call order, stdin credentials, completion records, resolution/status distinctions, and series stop/counts | +| Node-to-Python integration | 5 | Actual subprocess invocation, credential transport, output verification, failure handling, and resolver failures that pause without consuming the next episode | +| Protected-library guard | 10 | Exact baseline acceptance and detection of changed, added, missing, linked, or mode-altered entries | +| Runtime services | 25 | Configuration, shared database connection handling, log redaction, and constrained PM2 operations | +| HTTP, WebSocket, and PM2 interface | 19 | Request limits, generic errors, worker-only log subscriptions, cleanup and selection races, bounded log delivery, and safe DOM updates | +| Web validation and status | 19 | Both submission modes, safe filenames and ranges, Unicode validation, public-field/log redaction, pause-reason allowlisting, and resume cleanup | +| Worker lifecycle | 36 | Strict success criteria, process/storage failures, safe log truncation, pause/history/release ordering, acknowledged attention writes, and concurrent pause gates | +| **Total** | **158** | **114 Node tests and 44 Python tests** | + +The run used Node.js `v24.19.0` and Python `3.12.14` in the local workspace. This does not establish compatibility of the installed Python dependency stack on the intended Debian 13 host. + +Additional checks passed: + +```sh +node tools/check-protected-lib.js +git diff --check +git diff --exit-code 211bfd174dd78eac36f3c74411ecaa72f56eec79 -- scripts/lib scripts/requirements.txt +``` + +The protected check covers all seven original files, their SHA-256 hashes and executable bits, the exact directory structure, and unexpected entries. It found no modifications, additions, deletions, or symbolic links. The Python requirements file is unchanged. The Node lockfile retains all dependency versions; its only change adds the application's minimum Node engine metadata. + +## Failure behavior covered by the tests + +Completion requires exit code 0, exactly one valid completed result, and a nonempty regular output file. Nonzero exits, missing or malformed results, duplicate results, stderr-only results, signal termination, and invalid artifacts cannot become completed jobs. A nonempty file check is not full video-integrity validation. + +Ordinary source, network, and validation failures are written to failed history without pausing unrelated jobs. Verified HTTP 404 remains an ordinary source failure. Exact protected-library missing-marker errors now produce `resolution`; these and verified HTTP 401/403 access failures set the existing global pause before failed-attempt history and release of the affected claim. They retain the full request and credential in the queue. Post-claim and final launch checks prevent newly paused work from starting; failures reading pause state leave uncertain claims held. Transfers already admitted may finish. Missing worker infrastructure or unavailable output storage retains the request and stops the worker. A handled shutdown releases only its own claim after the child has terminated; a live-child error cannot release it early. + +History writes precede queue removal. If persistence fails, the worker stops with the processing claim held. These tests verify the ordering under simulated database results; they do not turn the legacy multi-collection sequence into an atomic transaction. + +Submitted cookie values are sent through stdin by workers. Complete log lines are redacted before bounded accumulation, including values split across chunks. Status queries may read a token internally to sanitize older logs, but the returned DTO contains only allowlisted public fields. Neither raw tokens nor PM2 environment objects are included in those tested public responses. + +## Test isolation and remaining deployment checks + +The suites use synthetic jobs, temporary output files, fake database/PM2/process interfaces, and a fake browser DOM. The subprocess integration suite runs actual Node-to-Python launches against copied entrypoints and a synthetic stream module. Express body-limit tests exercise the actual parsers with in-memory HTTP objects. No authenticated media download, live MongoDB connection, PM2 daemon operation, or production-server change was performed. + +Before production rollout, verify the target account's effective `plex` membership and write access to `/mnt/media/WIP`, its actual interpreter and existing dependencies, the MongoDB configuration, and PM2 startup under the same download account. Exercise the real stream on staging before accepting transport compatibility. Replace the worker and Python entrypoints together after existing children have stopped; the new worker requires the new result and stdin interfaces. + +The legacy queue still has no expiring ownership or automatic worker-loss recovery. Forced kills and interrupted persistence can require reconciliation. The protected transfer still writes directly to its target and cannot resume a partial file. No bandwidth cap has been implemented or measured in this phase. These limits are tracked in the [rollout roadmap](rollout-roadmap.md) and [Debian deployment assessment](debian-13-deployment.md). diff --git a/docs/rollout-roadmap.md b/docs/rollout-roadmap.md new file mode 100644 index 0000000..b15c1e7 --- /dev/null +++ b/docs/rollout-roadmap.md @@ -0,0 +1,33 @@ +# Proxer-Downloader rollout roadmap + +Baseline: upstream `211bfd174dd78eac36f3c74411ecaa72f56eec79`. + +The user approved the roadmap and authorized Phase 1 on 23 October 2026. The intended server is Debian 13, under the download account's home directory, with `/mnt/media/WIP/` access through `plex` and administrative `sudo` available. The user has installed the initial Phase 1 update and reported successful episode downloads. A follow-up unresolved-link pause fix is prepared locally; the assistant has not accessed or changed the server. + +All phases preserve the exact contents and paths under `scripts/lib/`. New code stays outside that directory, and Python bytecode writing is disabled. + +**Current status:** Phase 0 review and Phase 1 implementation are complete. The current revision, including the [unresolved-link pause fix](phase-1-resolution-fix.md), passed all 158 offline tests and the protected-tree checks; see the [verification report](phase-1-verification.md). The user is testing Phase 1 on the target server. Phase 2 remains the next planned implementation phase. + +| Phase | Scope | Acceptance gate | +|---|---|---| +| 0 — Review | Clone and inspect the source; map data flow and preservation boundary | Clean reviewed baseline and complete protected-tree manifest | +| 1 — Reliable behavior | Truthful subprocess results; child startup handling; safe input/output validation; corrected video title; public status projections; safe rendering; shared configuration; deployment feasibility | Failed or malformed results cannot become successful jobs; infrastructure failures preserve pending requests; offline regressions and protected-tree checks pass | +| 2 — UI shell | Responsive top bar; consistent visual styling; accessible submission form; filters and pagination; lightweight shared status | Both submission modes work on mobile/keyboard; refresh preserves interaction state and does not repeatedly load all history | +| 3 — Shared execution modules | Extract the shared Python executor and Node planning/process/supervisor services; structured events; temporary output and publication policy | Compatibility of filenames/flags/stream call order; explicit results; safe output publication | +| 4 — Recoverable queue | Explicit authoritative states; ownership and heartbeats; attempts; recovery; retries; global concurrency; grouping and indexes | Safe concurrent claims and worker-loss recovery; stale attempts cannot publish accepted output; reversible data migration | +| 5 — Worker management | Persisted defaults/overrides; pause/drain/restart/cancel; operational limits; proven external bandwidth control | Settings are enforced and survive restarts; per-worker and shared bandwidth caps hold under concurrent transfers | +| 6 — Release validation | End-to-end staging checks; deployment documentation; migration/rollback; pilot with one, then two, then four workers | Stable job lifecycle and recovery; measured limits; protected tree unchanged | + +## Phase 1 boundaries + +The legacy collections remain in place. Successful and ordinary failed jobs are still recorded in their respective history collections before removal from the queue; this sequence is not an atomic cross-collection transaction. Do not mix old and new worker code during a rollout. Stop or drain existing work before replacing the worker/script pair, because the new worker requires the new completion record and stdin credential interface. + +The top-bar redesign and new advanced worker settings are pending. No bandwidth limit, privileged helper, network namespace, traffic-control rule, systemd unit, or sudoers entry is installed by Phase 1. + +The Debian bandwidth assessment recommends validating a separately privileged shaper on an isolated worker traffic path. The host's actual route/interface/capability details and measured incoming-rate behavior remain prerequisites for choosing the backend. + +## Rollback and migration + +Keep the source version and database snapshot for each deployed phase. For Phase 1 rollback, stop the new workers and verify their children have terminated before restoring the old worker and Python entrypoints together. Additional history metadata is additive; no destructive database migration is introduced here. Rollback to the old application also restores its known reliability limitations and should be deliberate. + +The later ownership/state migration requires draining legacy workers, preserving original records and filenames, and reconciling any in-flight attempts. Historical records lacking original source information remain historical; missing retry metadata must not be fabricated. Worker generations with different ownership rules must not run against the same active queue. diff --git a/lib/config.js b/lib/config.js new file mode 100644 index 0000000..5b8762d --- /dev/null +++ b/lib/config.js @@ -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 }; diff --git a/lib/jobValidation.js b/lib/jobValidation.js new file mode 100644 index 0000000..f0d45aa --- /dev/null +++ b/lib/jobValidation.js @@ -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, +}; diff --git a/lib/logging.js b/lib/logging.js new file mode 100644 index 0000000..561beaa --- /dev/null +++ b/lib/logging.js @@ -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 }; diff --git a/lib/mongo.js b/lib/mongo.js index d998bae..0ad6e4a 100755 --- a/lib/mongo.js +++ b/lib/mongo.js @@ -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 }; diff --git a/package-lock.json b/package-lock.json index 3ff3a6a..0cf5f3d 100755 --- a/package-lock.json +++ b/package-lock.json @@ -18,6 +18,9 @@ "morgan": "^1.10.1", "nodemon": "^3.1.11", "ws": "^8.18.3" + }, + "engines": { + "node": ">=20.19.0" } }, "node_modules/@mongodb-js/saslprep": { diff --git a/package.json b/package.json index 07ed8ea..a87f881 100755 --- a/package.json +++ b/package.json @@ -4,7 +4,13 @@ "description": "", "main": "server.js", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "start": "node server.js", + "worker": "node queue_worker.js", + "test": "node tools/run-tests.js", + "check:protected": "node tools/check-protected-lib.js" + }, + "engines": { + "node": ">=20.19.0" }, "repository": { "type": "git", diff --git a/queue_worker.js b/queue_worker.js index db839fc..eafd50a 100755 --- a/queue_worker.js +++ b/queue_worker.js @@ -1,153 +1,297 @@ -// proxer-queue-worker.js -const { exec } = require("child_process"); -const { spawn } = require("child_process"); -const { MongoClient } = require("mongodb"); -const path = require("path"); -require("dotenv").config(); +const { spawn } = require('node:child_process'); +const fs = require('node:fs/promises'); +const { StringDecoder } = require('node:string_decoder'); +const { config } = require('./lib/config'); +const { getDb, closeDb } = require('./lib/mongo'); +const { ValidationError, normalizeWatchUrl, normalizeFilename, validateOutputTarget, cookieToken } = require('./lib/jobValidation'); +const { LOG_LIMIT, sanitizeLog, createLineSanitizer } = require('./lib/logging'); -// ======================== -// CONFIG -// ======================== -const MONGO_URI = process.env.MONGO_URI; -const DB_NAME = process.env.MONGO_DB || "downloads"; -const OUTPUT_DIR = process.env.OUTPUT_DIR || "/mnt/media/WIP"; +const RESULT_PREFIX = 'PROXER_RESULT '; +const ERROR_CATEGORIES = new Set(['validation', 'authentication', 'resolution', 'network', 'source', 'storage', 'configuration', 'unknown']); +const ATTENTION_CATEGORIES = new Set(['authentication', 'resolution']); -const client = new MongoClient(MONGO_URI); -let queueCol, doneCol, failedCol; - -// ======================== -// HELPER -// ======================== - -async function isBlocked() { - const settings = await queueCol.db - .collection("settings") - .findOne({ _id: "global" }); - return settings?.captcha_blocked === true; +function jobSecrets(job) { + const token = typeof job.token === 'string' ? job.token : ''; + const separator = token.indexOf('='); + return [token, separator >= 0 ? token.slice(separator + 1) : ''].filter(Boolean); } -// ======================== -// RUN A JOB -// ======================== -async function runJob(job) { - try { - const cmd = [ - process.env.VENV_PYTHON, - path.join(__dirname, "scripts/proxer-dl-video.py"), - "-u", - job.url, - "-f", - job.filename, - "-t", - job.token, - "-o", - OUTPUT_DIR, - ]; +function collectChild(proc, secrets, onChild = () => {}) { + return new Promise((resolve) => { + let output = ''; + let resultCount = 0; + let result = null; + let line = ''; + let oversizedLine = false; + let settled = false; + let outputTruncated = false; + let spawned = Number.isInteger(proc.pid) && proc.pid > 0; + let childError = false; + const decoder = new StringDecoder('utf8'); - const proc = spawn(cmd[0], cmd.slice(1)); + function append(chunk) { + const combined = output + chunk; + outputTruncated ||= combined.length > LOG_LIMIT; + output = combined.slice(-LOG_LIMIT); + } + // Redact complete lines before retaining a bounded tail. Cutting raw text + // first could retain an unrecognisable suffix of a credential or signed URL. + const stdoutLog = createLineSanitizer(append, { secrets }); + const stderrLog = createLineSanitizer(append, { secrets }); - let output = ""; - proc.stdout.on("data", (d) => (output += d.toString())); - proc.stderr.on("data", (d) => (output += d.toString())); - - const exitCode = await new Promise((resolve) => proc.on("close", resolve)); - - // ========== CAPTCHA / ERROR DETECTION ========== - const suspicious = - output.toLowerCase().includes("captcha") || - output.toLowerCase().includes("403") || - output.toLowerCase().includes("blocked") || - output.toLowerCase().includes("token") || - output.toLowerCase().includes("forbidden") || - - // proxer_utils.py - get_embed_url() - output.toLowerCase().includes("failed to fetch episode page") || - output.toLowerCase().includes("embed code not found in page content") || - - // proxer_utils.py - get_mp4_url() - output.toLowerCase().includes("failed to fetch embed page") || - output.toLowerCase().includes("mp4 url not found in embed page") || - - // proxer_utils.py - download_mp4() - output.toLowerCase().includes("failed to start download"); - - if (suspicious) { - console.log("⛔ CAPTCHA or fatal error detected, notifying system"); - console.log(output); - await failedCol.insertOne({ - filename: job.filename, - failed_at: new Date(), - output_log: output, - }); - - // Unset the processing flag so the job isn't stuck - await queueCol.updateOne( - { _id: job._id }, - { $unset: { processing: "" } } - ); - return true; // signals worker to halt globally + function parseLine() { + if (!oversizedLine && line.startsWith(RESULT_PREFIX)) { + resultCount += 1; + try { + const candidate = JSON.parse(line.slice(RESULT_PREFIX.length)); + if (candidate && candidate.version === 1 && ['completed', 'failed'].includes(candidate.status)) { + result = candidate; + } else result = null; + } catch { result = null; } + } + line = ''; + oversizedLine = false; } - // Success - await doneCol.insertOne({ - filename: job.filename, - finished_at: new Date(), - output_log: output, - }); - - await queueCol.deleteOne({ _id: job._id }); - return false; - } catch (err) { - console.error("Worker crash:", err); - return true; - } -} - -// ======================== -// MAIN LOOP -// ======================== -async function main() { - console.log("Worker started. Watching queue..."); - - try { - await client.connect(); - - const db = client.db(DB_NAME); - queueCol = db.collection("queue"); - doneCol = db.collection("done"); - failedCol = db.collection("failed"); - - while (true) { - if (await isBlocked()) { - console.log("⛔ CAPTCHA BLOCK — Worker paused"); - await new Promise((r) => setTimeout(r, 5000)); - continue; - } - - const job = await queueCol.findOneAndUpdate( - { processing: { $ne: true } }, // prevents grabbing others - { $set: { processing: true } }, - { sort: { created_at: 1 }, returnDocument: "after" } - ); - - if (job && job.token) { - const failed = await runJob(job); - if (failed === true) { - await queueCol.db - .collection("settings") - .updateOne( - { _id: "global" }, - { $set: { captcha_blocked: true } }, - { upsert: true } - ); + function consume(text) { + for (const char of text) { + if (char === '\n' || char === '\r') parseLine(); + else if (!oversizedLine) { + line += char; + if (line.length > 8192) { + if (line.startsWith(RESULT_PREFIX)) { resultCount += 1; result = null; } + line = ''; + oversizedLine = true; + } } - } else { - await new Promise((resolve) => setTimeout(resolve, 1000)); } } - } catch (err) { - console.error("Worker error:", err); + + function finish(exitCode, signal, spawnError = false) { + if (settled) return; + settled = true; + consume(decoder.end()); + parseLine(); + stdoutLog.end(); + stderrLog.end(); + onChild(null); + resolve({ exitCode, signal, spawnError, result: resultCount === 1 ? result : null, + output: (outputTruncated ? '[earlier log output omitted]\n' : '') + output }); + } + + proc.stdout.on('data', (data) => { + const text = decoder.write(data); + stdoutLog.write(data); + consume(text); + }); + proc.stderr.on('data', (data) => stderrLog.write(data)); + proc.once('spawn', () => { spawned = true; }); + proc.on('error', () => { + childError = true; + // A failed kill can emit error while the child is still alive. Only an + // actual spawn failure has no process whose close event must be awaited. + if (!spawned && !(Number.isInteger(proc.pid) && proc.pid > 0)) finish(null, null, true); + }); + proc.on('close', (code, signal) => finish(code, signal, childError)); + // A failed spawn can close stdin before the credential is sent. + if (proc.stdin) proc.stdin.on('error', () => {}); + onChild(proc); + }); +} + +async function executeJob(job, { + settings = config, spawnFn = spawn, onChild, + shouldStop = () => false, canStart = async () => true, +} = {}) { + let source, outputFile; + const secrets = jobSecrets(job); + try { + source = normalizeWatchUrl(job.url); + normalizeFilename(job.filename); + if (typeof job.token !== 'string' || job.token.indexOf('=') < 1) throw new Error('Invalid cookie.'); + const separator = job.token.indexOf('='); + cookieToken(job.token.slice(separator + 1), job.token.slice(0, separator + 1)); + } catch { + return { ok: false, errorCategory: 'validation', exitCode: null, + output: 'The queued source, credentials, filename, or output directory is invalid.' }; + } + try { + outputFile = await validateOutputTarget(settings.outputDir, job.filename); + } catch (error) { + return { ok: false, errorCategory: error instanceof ValidationError ? 'validation' : 'storage', + infrastructureFailure: !(error instanceof ValidationError), exitCode: null, + output: 'The output destination is unavailable or is not a safe regular-file target.' }; + } + if (shouldStop()) return { ok: false, errorCategory: 'interrupted', exitCode: null, output: 'Worker stopped before starting this job.' }; + // Another worker can pause the pool while output validation is awaiting I/O. + // A failed pause read propagates: do not start or release an uncertain claim. + if (!await canStart()) return { ok: false, errorCategory: 'paused', exitCode: null, + output: 'Downloads were paused before this transfer started.' }; + if (shouldStop()) return { ok: false, errorCategory: 'interrupted', exitCode: null, output: 'Worker stopped before starting this job.' }; + + let completed; + try { + const proc = spawnFn(settings.pythonPath, [ + '-B', settings.videoScript, '-u', source.url, `--filename=${job.filename}`, + '--token-stdin', `--output=${settings.outputDir}`, + ], { + cwd: settings.projectRoot, + env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONUNBUFFERED: '1' }, + stdio: ['pipe', 'pipe', 'pipe'], + }); + const completion = collectChild(proc, secrets, onChild); + proc.stdin.end(job.token + '\n'); + completed = await completion; + } catch { + return { ok: false, errorCategory: 'spawn', infrastructureFailure: true, exitCode: null, + output: 'The Python download process could not be started. Check VENV_PYTHON.' }; + } + + const { exitCode, signal, result, output, spawnError } = completed; + if (spawnError) return { ok: false, exitCode, errorCategory: 'spawn', infrastructureFailure: true, + output: 'The Python download process could not be started. Check VENV_PYTHON.' }; + if (exitCode !== 0 || signal || !result || result.status !== 'completed') { + if (shouldStop()) return { ok: false, exitCode, errorCategory: 'interrupted', output: 'Worker stopped; the transfer ended and can be restarted.' }; + const errorCategory = result && result.status === 'failed' && ERROR_CATEGORIES.has(result.errorCategory) + ? result.errorCategory : 'unknown'; + return { ok: false, exitCode, errorCategory, infrastructureFailure: ['configuration', 'storage'].includes(errorCategory), + output: output || 'The download ended without a successful result.' }; + } + + try { + // Recheck after child exit: do not accept a symlink, missing or empty artifact. + const verifiedFile = await validateOutputTarget(settings.outputDir, job.filename); + const stat = await fs.lstat(verifiedFile); + if (verifiedFile !== outputFile || !stat.isFile() || stat.size <= 0) throw new Error('Invalid output.'); + } catch { + return { ok: false, exitCode, errorCategory: 'storage', infrastructureFailure: true, + output: sanitizeLog(output + '\nThe expected nonempty output file was not produced.', secrets) }; + } + return { ok: true, exitCode, output }; +} + +async function processClaimedJob(job, { db, execute = executeJob, now = () => new Date() } = {}) { + const result = await execute(job); + if (['interrupted', 'paused'].includes(result.errorCategory) || result.infrastructureFailure) { + // The runner has either not spawned a child or observed its termination. + // Preserve the complete request for a later worker start; never consume the + // queue because an interpreter, dependency or media mount is unavailable. + await db.collection('queue').updateOne({ _id: job._id, processing: true }, + { $unset: { processing: '', started_at: '' } }); + if (result.infrastructureFailure) throw new Error('Worker infrastructure is unavailable. The job remains queued.'); + return result; + } + const common = { + job_id: job._id, + filename: job.filename, + url: job.url, + created_at: job.created_at, + output_log: sanitizeLog(result.output, jobSecrets(job)), + }; + + if (result.ok) { + // History must be durable before removing the queue record. Full atomic job + // state and recovery are a later migration; leave a claim held on DB errors. + await db.collection('done').insertOne({ ...common, finished_at: now() }); + await db.collection('queue').deleteOne({ _id: job._id, processing: true }); + return result; + } + + const needsAttention = ATTENTION_CATEGORIES.has(result.errorCategory); + if (needsAttention) { + // Stop further admissions before any history write can delay or fail. A + // missing source marker can be a challenge without an HTTP error status. + const pause = await db.collection('settings').updateOne({ _id: 'global' }, + { $set: { captcha_blocked: true, pause_reason: result.errorCategory } }, { upsert: true }); + if (pause?.acknowledged !== true) throw new Error('The download pause could not be confirmed. The claim remains held.'); + } + + const failedAttempt = await db.collection('failed').insertOne({ ...common, failed_at: now(), + error_category: result.errorCategory, exit_code: result.exitCode }); + + if (needsAttention) { + if (failedAttempt?.acknowledged !== true) throw new Error('The failed attempt could not be confirmed. The claim remains held.'); + // Preserve the original request and credential for a deliberate retry. The + // attempt stays visible in history, while the job remains queued and paused. + const release = await db.collection('queue').updateOne({ _id: job._id, processing: true }, + { $unset: { processing: '', started_at: '' } }); + if (release?.acknowledged !== true) throw new Error('The claim release could not be confirmed. Check the paused queue before resuming.'); + } else { + // Ordinary failures become history rather than looping or pausing all jobs. + // Automatic retries arrive with the explicit attempt model in Phase 4. + await db.collection('queue').deleteOne({ _id: job._id, processing: true }); + } + return result; +} + +async function downloadsPaused(db) { + const global = await db.collection('settings').findOne({ _id: 'global' }, + { projection: { captcha_blocked: 1 } }); + return global?.captcha_blocked === true; +} + +async function claimNextJob(db, { shouldStop = () => false, now = () => new Date() } = {}) { + if (shouldStop() || await downloadsPaused(db) || shouldStop()) return null; + const job = await db.collection('queue').findOneAndUpdate( + { processing: { $ne: true } }, + { $set: { processing: true, started_at: now() } }, + { sort: { created_at: 1 }, returnDocument: 'after' }, + ); + if (!job) return null; + if (await downloadsPaused(db) || shouldStop()) { + // A concurrent worker paused after our initial read. No child has started. + await db.collection('queue').updateOne({ _id: job._id, processing: true }, + { $unset: { processing: '', started_at: '' } }); + return null; + } + return job; +} + +async function main() { + const db = await getDb(); + let stopping = false; + let child = null; + function stop() { + stopping = true; + if (child) child.kill('SIGTERM'); + } + process.on('SIGINT', stop); + process.on('SIGTERM', stop); + const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + console.log('Worker started. Watching queue.'); + + try { + while (!stopping) { + const job = await claimNextJob(db, { shouldStop: () => stopping }); + if (!job) { if (!stopping) await delay(1000); continue; } + const result = await processClaimedJob(job, { db, + execute: (request) => executeJob(request, { + shouldStop: () => stopping, + canStart: async () => !await downloadsPaused(db), + onChild: (proc) => { + child = proc; + if (stopping && child) child.kill('SIGTERM'); + }, + }), + }); + if (ATTENTION_CATEGORIES.has(result.errorCategory)) { + console.warn(result.errorCategory === 'resolution' + ? 'Downloads paused: the video link could not be resolved. Check the source page before resuming.' + : 'Downloads paused: the source rejected access. Complete verification before resuming.'); + } + } + } finally { + process.removeListener('SIGINT', stop); + process.removeListener('SIGTERM', stop); + await closeDb(); } } -main(); +if (require.main === module) { + main().catch(() => { + console.error('Worker stopped after a database or configuration error. Check the deployment and reconcile any held claims before restarting.'); + process.exitCode = 1; + }); +} + +module.exports = { RESULT_PREFIX, collectChild, executeJob, processClaimedJob, claimNextJob, main }; diff --git a/routes/index.js b/routes/index.js index 27f8ae1..2559fe1 100755 --- a/routes/index.js +++ b/routes/index.js @@ -30,14 +30,7 @@ router.get("/status-data", queue.statusData); // ======================= // CAPTCHA CLEAR // ======================= -router.post("/clear-captcha", async (req, res) => { - const db = await getDb(); - await db - .collection("settings") - .updateOne({ _id: "global" }, { $set: { captcha_blocked: false } }); - // Redirect to status, controller fetches everything - res.redirect("/status"); -}); +router.post("/clear-captcha", queue.clearCaptcha); router.post("/clear-failed", async (req, res) => { const db = await getDb(); @@ -59,15 +52,8 @@ router.post("/clear-done", async (req, res) => { res.redirect("/status"); }); -router.post("/clear-processing", async (req, res) => { - const db = await getDb(); - await db - .collection("queue") - .updateMany({}, { $unset: { "processing": ""}}) - - // Redirect to status, controller fetches everything - res.redirect("/status"); -}); +// Keep the legacy URL, but never release a job that may still have a live child process. +router.post("/clear-processing", queue.clearProcessing); router.post("/clear-queued", async (req, res) => { const db = await getDb(); diff --git a/scripts/proxer-dl-series.py b/scripts/proxer-dl-series.py index 662b730..2dbe39e 100755 --- a/scripts/proxer-dl-series.py +++ b/scripts/proxer-dl-series.py @@ -1,62 +1,99 @@ import sys -import argparse -from lib.proxer_utils import get_embed_url, get_mp4_url, download_mp4 + +# Protect scripts/lib/__pycache__ even when this CLI is invoked without python -B. +sys.dont_write_bytecode = True + from time import sleep -def download_series_series(serie_id, pretty_name, episode_range, language, auth_token, output_dir): - """ - Downloads all episodes in a specified range of a series. +from request_validation import ( + LANGUAGES, + SafeArgumentParser, + ValidationError, + emit_result, + episode_range as validate_episode_range, + error_result, + output_path, + token_from_args, + positive_integer, + validate_auth_cookie, + validate_filename, + verify_output, +) - :param serie_id: The ID of the series (Proxer) - :param pretty_name: Pretty name for the series used in file names - :param episode_range: A string in the format of "start-end" (inclusive range of episodes) - :param language: The preferred language (e.g., 'engsub', 'gerdub') - :param auth_token: A tuple containing (cookie_name, cookie_value) - :param output_dir: Directory to store downloaded videos - """ - start, end = map(int, episode_range.split("-")) - for episode_number in range(start, end + 1): + +def download_series_series(serie_id, pretty_name, episode_range, language, auth_token, output_dir): + """Preserve sequential CLI naming and report every failed episode.""" + serie_id = positive_integer(serie_id, "Series ID") + validate_filename(pretty_name) + start, end = validate_episode_range(episode_range) + if language not in LANGUAGES: + raise ValidationError("Language is not supported.") + auth_token = validate_auth_cookie(auth_token) + + # Validate every output before beginning a series, including long generated names. + targets = [(episode, output_path(output_dir, f"{pretty_name}_Episode_{episode}_{language}")) + for episode in range(start, end + 1)] + + from lib.proxer_utils import get_embed_url, get_mp4_url, download_mp4 + + completed = 0 + failures = [] + for episode_number, target in targets: episode_url = f"https://proxer.me/watch/{serie_id}/{episode_number}/{language}" try: - print(f"Fetching embed URL for episode {episode_number} for {episode_url}...") + print(f"Resolving episode {episode_number}...", flush=True) embed_url = get_embed_url(episode_url, auth_token) - print(f"Embed URL fetched for episode {episode_number}: {embed_url}") - - print(f"Fetching MP4 URL for episode {episode_number}...") mp4_url = get_mp4_url(embed_url) - print(f"MP4 URL fetched for episode {episode_number}: {mp4_url}") + print(f"Downloading episode {episode_number}...", flush=True) + download_mp4(mp4_url, str(target), label=f"Episode {episode_number} ({language})") + verify_output(target) + completed += 1 + except Exception as error: + result = error_result(error) + failures.append({"episode": episode_number, "errorCategory": result["errorCategory"]}) + print(f"Episode {episode_number} failed: {result['message']}", flush=True) + if result["errorCategory"] in {"authentication", "resolution", "storage", "configuration"}: + # Access, unresolved links, and host failures need intervention. + break + if episode_number < end: + sleep(1) - # Prepare the output file path - output_file = f"{output_dir}/{pretty_name}_Episode_{episode_number}_{language}.mp4" + return {"completed": completed, "failed": len(failures), + "notAttempted": len(targets) - completed - len(failures), "failures": failures} - # Download the episode - print(f"Downloading episode {episode_number}...") - download_mp4(mp4_url, output_file, label=f"Episode {episode_number} ({language})") - print(f"Episode {episode_number} downloaded successfully!") - - except Exception as e: - print(f"Error downloading episode {episode_number}: {e}") - # Optional: Sleep between downloads to avoid being rate-limited - sleep(1) -def parse_args(): - """Parse command-line arguments""" - parser = argparse.ArgumentParser(description="Download a series from Proxer.me") +def parse_args(argv=None): + parser = SafeArgumentParser(description="Download a series from Proxer.me") parser.add_argument('-i', '--id', required=True, type=str, help="The series ID on Proxer.me") parser.add_argument('-n', '--name', required=True, type=str, help="The pretty name of the series") parser.add_argument('-e', '--episodes', required=True, type=str, help="Episode range (start-end), e.g. 1-10") - parser.add_argument('-l', '--language', required=True, choices=['engsub', 'engdub', 'gersub', 'gerdub'], help="Language of the subtitles/audio") - parser.add_argument('-t', '--token', required=True, type=str, help="Proxer authentication token") - parser.add_argument('-o', '--output', required=True, type=str, help="Directory to store downloaded videos") + parser.add_argument('-l', '--language', required=True, choices=LANGUAGES, help="Language of the subtitles/audio") + token = parser.add_mutually_exclusive_group(required=True) + token.add_argument('-t', '--token', type=str, help="Proxer authentication token") + token.add_argument('--token-stdin', action='store_true', help="Read the cookie from standard input instead of process arguments") + parser.add_argument('-o', '--output', required=True, type=str, help="Existing directory to store downloaded videos") + return parser.parse_args(argv) + + +def main(argv=None): + try: + args = parse_args(argv) + summary = download_series_series(args.id, args.name, args.episodes, args.language, token_from_args(args), args.output) + except Exception as error: + result = error_result(error) + emit_result(result) + return 2 if result["errorCategory"] == "validation" else 1 + status = "completed" if summary["failed"] == 0 and summary["notAttempted"] == 0 else "failed" + result = {"version": 1, "status": status, **summary} + if status == "failed": + categories = [failure["errorCategory"] for failure in summary["failures"]] + blocking = next((category for category in reversed(categories) + if category in {"authentication", "resolution", "storage", "configuration"}), None) + result["errorCategory"] = blocking or (categories[0] if categories else "unknown") + result["message"] = "The series did not complete; see the episode summary." + emit_result(result) + return 0 if status == "completed" else 1 - return parser.parse_args() if __name__ == "__main__": - # Parse command-line arguments - args = parse_args() - - # Assuming the Proxer authentication token comes as a cookie string (name=value) - auth_token = tuple(args.token.split("=")) - - # Call the function to download the series - download_series_series(args.id, args.name, args.episodes, args.language, auth_token, args.output) + sys.exit(main()) diff --git a/scripts/proxer-dl-video.py b/scripts/proxer-dl-video.py index 800cb4c..a3738a7 100755 --- a/scripts/proxer-dl-video.py +++ b/scripts/proxer-dl-video.py @@ -1,52 +1,61 @@ import sys -import argparse -from lib.proxer_utils import get_mp4_url, download_mp4, get_embed_url + +# Protect scripts/lib/__pycache__ even when this CLI is invoked without python -B. +sys.dont_write_bytecode = True + +from request_validation import ( + SafeArgumentParser, + emit_result, + error_result, + output_path, + token_from_args, + validate_auth_cookie, + validate_watch_url, + verify_output, +) + def download_video(url, filename, auth_token, output_dir): - """ - Downloads a video from Proxer and saves it to the specified directory. + """Run the existing stream pipeline; errors propagate to the CLI result.""" + url = validate_watch_url(url) + auth_token = validate_auth_cookie(auth_token) + target = output_path(output_dir, filename) - :param url: The URL of the Proxer video page - :param filename: The desired filename for the downloaded video - :param auth_token: A tuple containing (cookie_name, cookie_value) for Proxer authentication - :param output_dir: Directory to save the downloaded video - """ - try: - print(f"Fetching embed URL for video: {url}...") - embed_url = get_embed_url(url, auth_token) - print(f"Embed URL fetched: {embed_url}") + # Import only after validation, leaving all protected source and bytecode intact. + from lib.proxer_utils import get_embed_url, get_mp4_url, download_mp4 - print(f"Fetching MP4 URL for video: {url}...") - mp4_url = get_mp4_url(embed_url) - print(f"MP4 URL fetched: {mp4_url}") + print("Resolving episode...", flush=True) + embed_url = get_embed_url(url, auth_token) + print("Resolving media...", flush=True) + mp4_url = get_mp4_url(embed_url) + print("Downloading video...", flush=True) + download_mp4(mp4_url, str(target), label=f"Downloading {filename}") + verify_output(target) + return target - # Prepare the output file path - output_file = f"{output_dir}/{filename}.mp4" - # Download the video - print(f"Downloading video {filename}...") - download_mp4(mp4_url, output_file, label=f"Downloading {filename}") - print(f"Video {filename} downloaded successfully!") - - except Exception as e: - print(f"Error downloading video: {e}") - -def parse_args(): - """Parse command-line arguments""" - parser = argparse.ArgumentParser(description="Download a video from Proxer.me") +def parse_args(argv=None): + parser = SafeArgumentParser(description="Download a video from Proxer.me") parser.add_argument('-u', '--url', required=True, type=str, help="URL of the Proxer video page") parser.add_argument('-f', '--filename', required=True, type=str, help="Filename for the downloaded video (without extension)") - parser.add_argument('-t', '--token', required=True, type=str, help="Proxer authentication token (cookie)") - parser.add_argument('-o', '--output', required=True, type=str, help="Directory to save the downloaded video") + token = parser.add_mutually_exclusive_group(required=True) + token.add_argument('-t', '--token', type=str, help="Proxer authentication token (cookie)") + token.add_argument('--token-stdin', action='store_true', help="Read the cookie from standard input instead of process arguments") + parser.add_argument('-o', '--output', required=True, type=str, help="Existing directory to save the downloaded video") + return parser.parse_args(argv) + + +def main(argv=None): + try: + args = parse_args(argv) + download_video(args.url, args.filename, token_from_args(args), args.output) + except Exception as error: + result = error_result(error) + emit_result(result) + return 2 if result["errorCategory"] == "validation" else 1 + emit_result({"version": 1, "status": "completed"}) + return 0 - return parser.parse_args() if __name__ == "__main__": - # Parse command-line arguments - args = parse_args() - - # Assuming the Proxer authentication token comes as a cookie string (name=value) - auth_token = tuple(args.token.split("=")) - - # Call the function to download the video - download_video(args.url, args.filename, auth_token, args.output) + sys.exit(main()) diff --git a/scripts/request_validation.py b/scripts/request_validation.py new file mode 100644 index 0000000..f1e0615 --- /dev/null +++ b/scripts/request_validation.py @@ -0,0 +1,204 @@ +"""Validation and safe CLI results around the unchanged streaming library.""" + +import argparse +import json +import os +from pathlib import Path +import re +import sys +from urllib.parse import urlsplit + + +LANGUAGES = ("engsub", "engdub", "gersub", "gerdub") +MAX_SAFE_INTEGER = 9007199254740991 +MAX_TOKEN_BYTES = 8192 +MAX_URL_LENGTH = 2048 +MAX_SERIES_LIMIT = 10000 +RESULT_PREFIX = "PROXER_RESULT " + + +class ValidationError(ValueError): + """An input error whose message is safe to display.""" + + +class SafeArgumentParser(argparse.ArgumentParser): + def error(self, message): + # argparse's default error may echo an unrecognised credential argument. + raise ValidationError("Invalid command-line arguments. Use --help for usage.") + + +def positive_integer(value, label): + text = str(value) + if not re.fullmatch(r"[1-9][0-9]*", text): + raise ValidationError(f"{label} must be a positive whole number.") + if len(text) > len(str(MAX_SAFE_INTEGER)): + raise ValidationError(f"{label} exceeds the supported integer range.") + number = int(text) + if number > MAX_SAFE_INTEGER: + raise ValidationError(f"{label} exceeds the supported integer range.") + return number + + +def parse_token(token): + if not isinstance(token, str): + raise ValidationError("Token must be a cookie in name=value format.") + try: + if len(token.encode("utf-8")) > MAX_TOKEN_BYTES: + raise ValidationError("Token exceeds the supported length.") + except UnicodeEncodeError: + raise ValidationError("Token contains invalid text.") from None + name, separator, value = token.partition("=") + if not separator or not re.fullmatch(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+", name): + raise ValidationError("Token must be a cookie in name=value format.") + if not value or any(character.isspace() or ord(character) < 32 or 127 <= ord(character) <= 159 or character == ";" for character in value): + raise ValidationError("Token contains an empty or invalid cookie value.") + return name, value + + +def token_from_args(args, stream=None): + if not args.token_stdin: + return parse_token(args.token) + stream = sys.stdin if stream is None else stream + reader = getattr(stream, "buffer", stream) + try: + raw = reader.read(MAX_TOKEN_BYTES + 3) + if isinstance(raw, str): + raw = raw.encode("utf-8") + if raw.endswith(b"\r\n"): + raw = raw[:-2] + elif raw.endswith(b"\n"): + raw = raw[:-1] + if len(raw) > MAX_TOKEN_BYTES: + raise ValidationError("Token exceeds the supported length.") + return parse_token(raw.decode("utf-8")) + except (UnicodeError, OSError): + raise ValidationError("Token input could not be read as UTF-8 text.") from None + + +def validate_auth_cookie(auth_cookie): + if not isinstance(auth_cookie, (tuple, list)) or len(auth_cookie) != 2: + raise ValidationError("Token must contain exactly one cookie name and value.") + name, value = auth_cookie + if not isinstance(name, str) or not isinstance(value, str): + raise ValidationError("Token must contain a cookie name and value.") + parsed = parse_token(f"{name}={value}") + if parsed[0] != name: + raise ValidationError("Token contains an invalid cookie name.") + return parsed + + +def validate_watch_url(value): + if (not isinstance(value, str) or len(value) > MAX_URL_LENGTH or "\\" in value + or any(char.isspace() or ord(char) < 32 or 127 <= ord(char) <= 159 for char in value)): + raise ValidationError("URL must be a valid HTTPS Proxer watch URL.") + try: + parsed = urlsplit(value) + if (parsed.scheme != "https" or parsed.hostname not in {"proxer.me", "www.proxer.me"} + or parsed.username is not None or parsed.password is not None + or parsed.port not in (None, 443) or parsed.query): + raise ValueError + except ValueError: + raise ValidationError("URL must be an HTTPS Proxer watch URL without credentials or query parameters.") from None + match = re.fullmatch(r"/watch/([1-9][0-9]*)/([1-9][0-9]*)/(engsub|engdub|gersub|gerdub)/?", parsed.path) + if not match: + raise ValidationError("URL must identify a Proxer series, episode, and supported language.") + series_id = positive_integer(match.group(1), "Series ID") + episode = positive_integer(match.group(2), "Episode") + return f"https://proxer.me/watch/{series_id}/{episode}/{match.group(3)}" + + +def validate_filename(filename): + if (not isinstance(filename, str) or not filename or filename != filename.strip() + or filename in {".", ".."} or "/" in filename or "\\" in filename + or any(ord(character) < 32 or 127 <= ord(character) <= 159 for character in filename)): + raise ValidationError("Filename must be a nonempty single name without path separators or control characters.") + try: + encoded_length = len((filename + ".mp4").encode("utf-8")) + except UnicodeEncodeError: + raise ValidationError("Filename contains invalid text.") from None + if encoded_length > 255: + raise ValidationError("Filename is too long for the output filesystem.") + return filename + + +def output_path(output_dir, filename): + validate_filename(filename) + try: + directory = Path(output_dir).resolve(strict=True) + except (OSError, RuntimeError): + raise OSError("The configured output directory is unavailable.") from None + except (TypeError, ValueError): + raise ValidationError("Output directory must be a valid filesystem path.") from None + if not directory.is_dir(): + raise OSError("The configured output directory is unavailable.") + target = directory / (filename + ".mp4") + if target.is_symlink(): + raise ValidationError("Output file must not be a symbolic link.") + if target.exists() and not target.is_file(): + raise ValidationError("Output file must be a regular file.") + if target.resolve(strict=False).parent != directory: + raise ValidationError("Output file must remain inside the configured output directory.") + return target + + +def verify_output(target): + if target.is_symlink() or not target.is_file() or target.stat().st_size == 0: + raise OSError("The download did not produce a nonempty regular output file.") + + +def episode_range(value): + if not isinstance(value, str) or not re.fullmatch(r"[1-9][0-9]*-[1-9][0-9]*", value): + raise ValidationError("Episodes must be an inclusive start-end range of positive whole numbers.") + start_text, end_text = value.split("-", 1) + start = positive_integer(start_text, "First episode") + end = positive_integer(end_text, "Last episode") + if end < start: + raise ValidationError("Last episode must not be smaller than first episode.") + configured_maximum = os.environ.get("MAX_SERIES_EPISODES") or "500" + if not re.fullmatch(r"[0-9]+", configured_maximum): + raise ValidationError("MAX_SERIES_EPISODES must be a positive whole number.") + normalized_maximum = configured_maximum.lstrip("0") or "0" + if len(normalized_maximum) > len(str(MAX_SERIES_LIMIT)): + raise ValidationError("MAX_SERIES_EPISODES must be between 1 and 10000.") + maximum = int(normalized_maximum) + if maximum < 1 or maximum > MAX_SERIES_LIMIT: + raise ValidationError("MAX_SERIES_EPISODES must be between 1 and 10000.") + if end - start + 1 > maximum: + raise ValidationError("Episode range exceeds MAX_SERIES_EPISODES.") + return start, end + + +def error_result(error): + """Classify exception metadata, never broad keyword matches or raw messages.""" + chain = [] + current = error + while current is not None and len(chain) < 20 and all(current is not item for item in chain): + chain.append(current) + current = current.__cause__ or current.__context__ + + if isinstance(error, ValidationError): + category, message = "validation", str(error) + elif any(isinstance(item, ImportError) for item in chain): + category, message = "configuration", "The download dependencies could not be loaded. Check the Python environment." + elif any(getattr(getattr(item, "response", None), "status_code", None) in (401, 403) for item in chain): + category = "authentication" + message = "The source rejected authentication or access. Refresh the token or complete any required verification before retrying." + elif any(getattr(getattr(item, "response", None), "status_code", None) == 404 for item in chain): + category, message = "source", "The requested video could not be resolved." + elif any(type(item).__name__ == "NotFoundError" and type(item).__module__ == "lib.proxer_utils" for item in chain): + # Missing page markers can mean a challenge or a changed/unavailable + # source. Preserve that uncertainty and require human verification. + category = "resolution" + message = "The video link could not be resolved. Check the source page and complete any required verification before retrying." + elif any(type(item).__module__.startswith(("requests.", "urllib3.")) or (type(item).__name__ == "NetworkError" and type(item).__module__ == "lib.proxer_utils") for item in chain): + category, message = "network", "The source could not be reached or the transfer was interrupted." + elif isinstance(error, OSError): + category, message = "storage", "The output file could not be written or validated." + else: + category, message = "unknown", "The download could not be completed." + return {"version": 1, "status": "failed", "errorCategory": category, "message": message} + + +def emit_result(result): + # A leading newline isolates the record from the library's terminal progress bar. + print("\n" + RESULT_PREFIX + json.dumps(result, ensure_ascii=True), flush=True) diff --git a/server.js b/server.js index 54ea0c0..8c63fff 100755 --- a/server.js +++ b/server.js @@ -1,146 +1,291 @@ -// server.js (Improved Version B) -require('dotenv').config(); -const express = require('express'); -const path = require('path'); -const bodyParser = require('body-parser'); -const http = require('http'); -const WebSocket = require('ws'); -const { spawn } = require('child_process'); +"use strict"; +const express = require('express'); +const path = require('node:path'); +const http = require('node:http'); +const WebSocket = require('ws'); +const { spawn } = require('node:child_process'); +const { config } = require('./lib/config'); +const { closeDb } = require('./lib/mongo'); +const { createLineSanitizer } = require('./lib/logging'); +const { resolveManagedProcess, validName } = require('./controllers/pm2Controller'); const indexRouter = require('./routes/index'); -const app = express(); -const PORT = process.env.PORT || 3000; +const MAX_WS_PAYLOAD = 16 * 1024; +const MAX_WS_BUFFER = 64 * 1024; -// View engine -app.set('view engine', 'ejs'); -app.set('views', path.join(__dirname, 'views')); - -// Middleware -app.use(express.static(path.join(__dirname, 'public'))); -app.use(bodyParser.urlencoded({ extended: true })); -app.use(bodyParser.json()); - -// Routes -app.use('/', indexRouter); - -// Error handler -app.use((err, req, res, next) => { - console.error(err); - res.status(500).render('error', { - message: 'Internal Server Error', - detail: err.message - }); -}); - -// ----------------------------- -// HTTP + WebSocket server -// ----------------------------- -const server = http.createServer(app); -const wss = new WebSocket.Server({ server }); - -// Heartbeat for detecting dead connections -function heartbeat() { - this.isAlive = true; +function handleHttpError(error, req, res, next) { + if (res.headersSent) return next(new Error('The response could not be completed.')); + const tooLarge = error?.type === 'entity.too.large' || error?.status === 413; + const invalid = error?.type === 'entity.parse.failed' || error?.status === 400; + const status = tooLarge ? 413 : invalid ? 400 : 500; + const message = tooLarge + ? 'Request too large. The maximum request size is 32 KiB.' + : invalid ? 'Invalid request body.' : 'The request could not be completed. Check the server configuration and try again.'; + if (req.is?.('application/json') || req.path?.startsWith('/pm2/') || req.path === '/status-data') { + return res.status(status).json({ ok: false, error: message }); + } + return res.status(status).render('error', { title: 'Request failed', message, details: null }); } -wss.on('connection', ws => { - ws.isAlive = true; - ws.on('pong', heartbeat); +function createApplication({ settings = config, router = indexRouter } = {}) { + const app = express(); + app.set('view engine', 'ejs'); + app.set('views', path.join(settings.projectRoot, 'views')); + app.locals.global = { captcha_blocked: false }; + app.use(express.static(path.join(settings.projectRoot, 'public'))); + app.use(express.urlencoded({ extended: false, limit: '32kb', parameterLimit: 100 })); + app.use(express.json({ limit: '32kb' })); + app.use('/', router); + app.use(handleHttpError); + return app; +} - let child = null; +// Attach one bounded log subscription; dependencies are injectable for offline tests. +function attachLogConnection(ws, { + resolveWorker = resolveManagedProcess, + spawnProcess = spawn, + settings = config, +} = {}) { + let disposed = false; + let generation = 0; + let current = null; - ws.send(JSON.stringify({ type: 'connected', message: 'ws ready' })); + function stopCurrent() { + const previous = current; + current = null; + if (previous) { + previous.active = false; + try { previous.child.kill(); } catch { /* already gone */ } + } + } - ws.on('message', msg => { - let payload; + function dispose() { + if (disposed) return; + disposed = true; + generation++; + stopCurrent(); + } + + function disconnect(code, reason) { + dispose(); + try { ws.close(code, reason); } catch { try { ws.terminate(); } catch {} } + } + + function send(payload) { + if (disposed || ws.readyState !== WebSocket.OPEN) return false; + const encoded = JSON.stringify(payload); + if ((ws.bufferedAmount || 0) + Buffer.byteLength(encoded) > MAX_WS_BUFFER) { + disconnect(1013, 'Log stream cannot keep up. Reconnect to continue.'); + return false; + } try { - payload = JSON.parse(msg.toString()); + ws.send(encoded, error => { + if (error) disconnect(1011, 'Log connection failed.'); + }); + return true; } catch { - ws.send(JSON.stringify({ type: 'error', error: 'Invalid JSON' })); + disconnect(1011, 'Log connection failed.'); + return false; + } + } + + async function handleMessage(data, isBinary) { + if (disposed || ws.readyState !== WebSocket.OPEN) return; + if (isBinary) { + send({ type: 'error', error: 'Log requests must be JSON text.' }); + return; + } + const text = Buffer.isBuffer(data) ? data.toString('utf8') : String(data); + if (Buffer.byteLength(text) > MAX_WS_PAYLOAD) { + disconnect(1009, 'Log request is too large.'); + return; + } + let payload; + try { payload = JSON.parse(text); } catch { + send({ type: 'error', error: 'Invalid JSON request.' }); + return; + } + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { + send({ type: 'error', error: 'A JSON object is required.' }); return; } - // ----------------------------- - // START LOGS - // ----------------------------- - if (payload.type === 'logs') { - const name = payload.name || null; - - // Clean previous child - if (child) { - try { child.kill(); } catch {} - child = null; - } - - // Correct PM2 argument ordering - const args = ['logs', '--raw', '--lines', '200']; - if (name) args.splice(1, 0, name); - - try { - child = spawn('pm2', args); - - child.stdout.on('data', data => { - ws.send(JSON.stringify({ type: 'stdout', data: data.toString() })); - }); - - child.stderr.on('data', data => { - ws.send(JSON.stringify({ type: 'stderr', data: data.toString() })); - }); - - child.on('close', code => { - ws.send(JSON.stringify({ type: 'close', code })); - child = null; - }); - - child.on('error', err => { - ws.send(JSON.stringify({ type: 'error', error: err.message })); - child = null; - }); - - ws.send(JSON.stringify({ type: 'info', message: `started logs for ${name || 'all'}` })); - - } catch (err) { - ws.send(JSON.stringify({ type: 'error', error: err.message })); - } - - return; - } - - // ----------------------------- - // STOP LOGS - // ----------------------------- if (payload.type === 'stop-logs') { - if (child) { - try { child.kill(); } catch {} - child = null; - } - ws.send(JSON.stringify({ type: 'info', message: 'logs stopped' })); + generation++; + stopCurrent(); + send({ type: 'info', message: 'Log stream stopped.' }); + return; + } + if (payload.type !== 'logs') { + send({ type: 'error', error: 'Unknown log request.' }); + return; + } + if (!validName(payload.name)) { + send({ type: 'error', error: 'Select a valid downloader worker.' }); return; } - ws.send(JSON.stringify({ type: 'error', error: 'Unknown type' })); - }); + const requestGeneration = ++generation; + stopCurrent(); + try { + const worker = await resolveWorker(payload.name); + if (disposed || generation !== requestGeneration || ws.readyState !== WebSocket.OPEN) return; + const id = worker?.pm_id; + if (!worker || !/^\d+$/.test(String(id)) || !Number.isSafeInteger(Number(id))) { + send({ type: 'error', error: 'The selected downloader worker was not found.' }); + return; + } + const child = spawnProcess('pm2', ['logs', String(Number(id)), '--raw', '--lines', '200'], { + cwd: settings.projectRoot, + stdio: ['ignore', 'pipe', 'pipe'], + }); + const record = { child, active: true }; + current = record; + const active = () => !disposed && record.active && current === record && generation === requestGeneration; + const stdout = createLineSanitizer(line => { + if (active()) send({ type: 'stdout', data: line }); + }, { secrets: [settings.mongoUri] }); + const stderr = createLineSanitizer(line => { + if (active()) send({ type: 'stderr', data: line }); + }, { secrets: [settings.mongoUri] }); - ws.on('close', () => { - if (child) { - try { child.kill(); } catch {} - child = null; + child.on('error', () => { + if (!active()) return; + stopCurrent(); + send({ type: 'error', error: 'The worker log stream could not be started.' }); + }); + for (const stream of [child.stdout, child.stderr]) { + stream.on('error', () => { + if (!active()) return; + stopCurrent(); + send({ type: 'error', error: 'The worker log stream was interrupted.' }); + }); + } + child.stdout.on('data', chunk => { if (active()) stdout.write(chunk); }); + child.stderr.on('data', chunk => { if (active()) stderr.write(chunk); }); + child.on('close', code => { + if (!active()) return; + stdout.end(); + stderr.end(); + if (!active()) return; + current = null; + record.active = false; + send({ type: 'close', code: Number.isInteger(code) ? code : null }); + }); + send({ type: 'info', message: 'Worker log stream started.' }); + } catch { + if (disposed || generation !== requestGeneration) return; + stopCurrent(); + send({ type: 'error', error: 'The worker supervisor is unavailable.' }); } + } + + ws.isAlive = true; + ws.on('pong', () => { ws.isAlive = true; }); + ws.on('message', (data, isBinary) => { + handleMessage(data, isBinary).catch(() => { + stopCurrent(); + send({ type: 'error', error: 'The log request could not be completed.' }); + }); }); -}); + ws.on('close', dispose); + ws.on('error', dispose); + send({ type: 'connected', message: 'Log connection ready.' }); + return { dispose }; +} -// Ping-pong interval every 30s -setInterval(() => { - wss.clients.forEach(ws => { - if (!ws.isAlive) return ws.terminate(); - - ws.isAlive = false; - ws.ping(); // triggers 'pong' +function createServer({ + settings = config, + router = indexRouter, + resolveWorker = resolveManagedProcess, + spawnProcess = spawn, + createHttpServer = http.createServer, + WebSocketServer = WebSocket.Server, + scheduleInterval = setInterval, + cancelInterval = clearInterval, +} = {}) { + const app = createApplication({ settings, router }); + const server = createHttpServer(app); + const wss = new WebSocketServer({ server, maxPayload: MAX_WS_PAYLOAD }); + const connections = new Map(); + let cleaned = false; + let closingWebSocketServer = false; + wss.on('connection', ws => { + const connection = attachLogConnection(ws, { resolveWorker, spawnProcess, settings }); + connections.set(ws, connection); + ws.once('close', () => connections.delete(ws)); }); -}, 30000); -// Start server -server.listen(PORT, () => - console.log(`Proxer-Downloader running on http://localhost:${PORT}`) -); + const heartbeat = scheduleInterval(() => { + for (const ws of wss.clients) { + if (!ws.isAlive || ws.readyState !== WebSocket.OPEN) { + connections.get(ws)?.dispose(); + try { ws.terminate(); } catch {} + continue; + } + ws.isAlive = false; + try { ws.ping(); } catch { + connections.get(ws)?.dispose(); + try { ws.terminate(); } catch {} + } + } + }, 30_000); + heartbeat.unref?.(); + + function cleanup() { + if (cleaned) return; + cleaned = true; + cancelInterval(heartbeat); + for (const [ws, connection] of connections) { + connection.dispose(); + try { ws.terminate(); } catch {} + } + connections.clear(); + } + wss.on('close', cleanup); + function closeWebSocketServer() { + if (closingWebSocketServer) return; + closingWebSocketServer = true; + wss.close(); + } + server.on('close', () => { cleanup(); closeWebSocketServer(); }); + + function close() { + cleanup(); + closeWebSocketServer(); + return new Promise(resolve => { + if (server.listening) server.close(resolve); + else resolve(); + }); + } + return { app, server, wss, close }; +} + +if (require.main === module) { + const runtime = createServer(); + runtime.server.on('error', () => { + console.error('The HTTP server could not start. Check the configured host and port.'); + runtime.close(); + process.exitCode = 1; + }); + runtime.server.listen(config.port, config.host, () => { + console.log(`Proxer-Downloader listening on ${config.host}:${config.port}`); + }); + let stopping = false; + async function shutdown() { + if (stopping) return; + stopping = true; + try { + await runtime.close(); + await closeDb(); + } catch { + console.error('The server could not close every resource cleanly.'); + process.exitCode = 1; + } + } + process.once('SIGINT', shutdown); + process.once('SIGTERM', shutdown); +} + +module.exports = { createApplication, createServer, attachLogConnection, handleHttpError, MAX_WS_PAYLOAD, MAX_WS_BUFFER }; diff --git a/tests/cli-integration.test.js b/tests/cli-integration.test.js new file mode 100644 index 0000000..6be1f14 --- /dev/null +++ b/tests/cli-integration.test.js @@ -0,0 +1,213 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const { executeJob, processClaimedJob, claimNextJob, RESULT_PREFIX } = require('../queue_worker'); + +const repository = path.resolve(__dirname, '..'); +const cookie = 'fixture_cookie=fixture-value=='; + +async function offlineCli(t, mode, { filename = 'Fixture Episode' } = {}) { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'proxer-cli-integration-')); + const outputDir = path.join(directory, 'output'); + const fakeLibrary = path.join(directory, 'lib'); + await fs.mkdir(outputDir); + await fs.mkdir(fakeLibrary); + await fs.copyFile(path.join(repository, 'scripts/proxer-dl-video.py'), path.join(directory, 'proxer-dl-video.py')); + await fs.copyFile(path.join(repository, 'scripts/request_validation.py'), path.join(directory, 'request_validation.py')); + await fs.writeFile(path.join(fakeLibrary, '__init__.py'), '# Offline fixture package only.\n'); + const stub = mode === 'missing-dependency' + ? 'raise ImportError("Synthetic missing dependency; fixture-value==")\n' + : `import json +import os +from pathlib import Path +import sys + +CALLS = [] +ROOT = Path(__file__).resolve().parent.parent + +class NetworkError(Exception): + pass + +class NotFoundError(Exception): + pass + +def record(name): + CALLS.append(name) + (ROOT / "calls.json").write_text(json.dumps(CALLS), encoding="utf-8") + +def get_embed_url(url, auth_cookie): + assert CALLS == [] + assert url == "https://proxer.me/watch/42/1/engsub" + assert auth_cookie == ("fixture_cookie", "fixture-value==") + assert "--token-stdin" in sys.argv + assert not any("fixture-value" in argument for argument in sys.argv) + assert sys.dont_write_bytecode is True + assert os.environ["PYTHONDONTWRITEBYTECODE"] == "1" + record("embed") + if ${mode === 'embed-resolution' ? 'True' : 'False'}: + raise NotFoundError("Synthetic missing embed fixture-value==") + return "https://fixture.invalid/embed" + +def get_mp4_url(embed_url): + assert CALLS == ["embed"] + assert embed_url == "https://fixture.invalid/embed" + record("media") + if ${mode === 'media-resolution' ? 'True' : 'False'}: + raise NotFoundError("Synthetic missing media fixture-value==") + return "https://fixture.invalid/video.mp4?signature=synthetic-secret" + +def download_mp4(mp4_url, save_path, label=""): + assert CALLS == ["embed", "media"] + assert mp4_url == "https://fixture.invalid/video.mp4?signature=synthetic-secret" + assert label == ${JSON.stringify('Downloading ' + filename)} + assert Path(save_path).parent == ROOT / "output" + record("download") + if ${mode === 'network-error' ? 'True' : 'False'}: + raise NetworkError("Synthetic request failure fixture-value== " + mp4_url) + Path(save_path).write_bytes(b"synthetic-MP4-payload") +`; + await fs.writeFile(path.join(fakeLibrary, 'proxer_utils.py'), stub); + let child = null; + t.after(async () => { + if (child) child.kill('SIGTERM'); + await fs.rm(directory, { recursive: true, force: true }); + }); + const settings = { + projectRoot: directory, + videoScript: path.join(directory, 'proxer-dl-video.py'), + outputDir, + pythonPath: process.env.TEST_PYTHON || 'python3', + }; + const job = { + _id: 'integration-fixture', filename, + url: 'https://www.proxer.me:443/watch/42/1/engsub/#player', token: cookie, + }; + const result = await executeJob(job, { settings, onChild: process => { child = process; } }); + return { directory, outputDir, result, job }; +} + +function resultRecord(output) { + const records = output.split(/\r?\n/).filter(line => line.startsWith(RESULT_PREFIX)); + assert.equal(records.length, 1, 'exactly one machine-readable result must survive the subprocess protocol'); + return JSON.parse(records[0].slice(RESULT_PREFIX.length)); +} + +async function assertNoBytecode(directory) { + const entries = await fs.readdir(directory, { withFileTypes: true }); + for (const entry of entries) { + assert.notEqual(entry.name, '__pycache__'); + assert.ok(!entry.name.endsWith('.pyc')); + if (entry.isDirectory()) await assertNoBytecode(path.join(directory, entry.name)); + } +} + +test('real Node-to-Python subprocess preserves stdin credentials, stream call order and successful completion', { timeout: 10000 }, async t => { + const { directory, outputDir, result } = await offlineCli(t, 'success'); + assert.equal(result.ok, true, result.output); + assert.equal(result.exitCode, 0); + assert.deepEqual(resultRecord(result.output), { version: 1, status: 'completed' }); + assert.deepEqual(JSON.parse(await fs.readFile(path.join(directory, 'calls.json'), 'utf8')), ['embed', 'media', 'download']); + assert.equal(await fs.readFile(path.join(outputDir, 'Fixture Episode.mp4'), 'utf8'), 'synthetic-MP4-payload'); + assert.doesNotMatch(result.output, /fixture-value|synthetic-secret|fixture\.invalid/); + await assertNoBytecode(directory); +}); + +test('real Python stream failure exits nonzero and reaches Node with a sanitized network result', { timeout: 10000 }, async t => { + const { directory, outputDir, result } = await offlineCli(t, 'network-error'); + assert.equal(result.ok, false); + assert.equal(result.exitCode, 1); + assert.equal(result.errorCategory, 'network'); + assert.equal(result.infrastructureFailure, false); + const record = resultRecord(result.output); + assert.equal(record.status, 'failed'); + assert.equal(record.errorCategory, 'network'); + assert.match(record.message, /source could not be reached or the transfer was interrupted/); + assert.doesNotMatch(result.output, /fixture-value|synthetic-secret|Synthetic request failure|Traceback|fixture\.invalid/); + assert.deepEqual(JSON.parse(await fs.readFile(path.join(directory, 'calls.json'), 'utf8')), ['embed', 'media', 'download']); + assert.deepEqual(await fs.readdir(outputDir), []); + await assertNoBytecode(directory); +}); + +test('real Python dependency failure becomes an infrastructure result without a transfer', { timeout: 10000 }, async t => { + const { directory, outputDir, result } = await offlineCli(t, 'missing-dependency'); + assert.equal(result.ok, false); + assert.equal(result.exitCode, 1); + assert.equal(result.errorCategory, 'configuration'); + assert.equal(result.infrastructureFailure, true); + const record = resultRecord(result.output); + assert.equal(record.status, 'failed'); + assert.match(record.message, /dependencies could not be loaded/); + assert.doesNotMatch(result.output, /fixture-value|Synthetic missing dependency|Traceback/); + assert.deepEqual(await fs.readdir(outputDir), []); + await assert.rejects(fs.access(path.join(directory, 'calls.json'))); + await assertNoBytecode(directory); +}); + +test('real subprocess treats a leading-dash filename as a value rather than a CLI option', { timeout: 10000 }, async t => { + const filename = '-Fixture Episode'; + const { directory, outputDir, result } = await offlineCli(t, 'success', { filename }); + assert.equal(result.ok, true, result.output); + assert.equal(result.exitCode, 0); + assert.equal(resultRecord(result.output).status, 'completed'); + assert.equal(await fs.readFile(path.join(outputDir, `${filename}.mp4`), 'utf8'), 'synthetic-MP4-payload'); + await assertNoBytecode(directory); +}); + +test('real resolver failures pause the queue, preserve both episodes, and do not claim the next one', { timeout: 10000 }, async t => { + for (const mode of ['embed-resolution', 'media-resolution']) { + const { directory, outputDir, result, job } = await offlineCli(t, mode); + assert.equal(result.ok, false); + assert.equal(result.exitCode, 1); + assert.equal(result.errorCategory, 'resolution'); + assert.equal(resultRecord(result.output).errorCategory, 'resolution'); + assert.doesNotMatch(result.output, /fixture-value|Synthetic missing|Traceback/); + assert.deepEqual(await fs.readdir(outputDir), []); + assert.deepEqual(JSON.parse(await fs.readFile(path.join(directory, 'calls.json'), 'utf8')), + mode === 'embed-resolution' ? ['embed'] : ['embed', 'media']); + + const queue = [{ ...job, processing: true, started_at: new Date() }, + { ...job, _id: 'next-episode', filename: 'Fixture Episode 2', url: 'https://proxer.me/watch/42/2/engsub' }]; + const original = queue.map(entry => ({ ...entry })); + const global = { captcha_blocked: false }; + const history = []; + let claims = 0; + const db = { collection(name) { + if (name === 'settings') return { + updateOne: async (filter, update) => { Object.assign(global, update.$set); return { acknowledged: true }; }, + findOne: async () => ({ ...global }), + }; + if (name === 'failed') return { insertOne: async record => { + assert.equal(global.captcha_blocked, true, 'pause must precede history'); + history.push(record); return { acknowledged: true }; + } }; + assert.equal(name, 'queue'); + return { + updateOne: async (filter, update) => { + const entry = queue.find(candidate => candidate._id === filter._id && candidate.processing === true); + assert.ok(entry); + for (const field of Object.keys(update.$unset)) delete entry[field]; + return { acknowledged: true }; + }, + deleteOne: async () => { assert.fail('a resolution pause must not delete an episode'); }, + findOneAndUpdate: async () => { claims += 1; return queue[1]; }, + }; + } }; + await processClaimedJob(queue[0], { db, execute: async () => result }); + assert.deepEqual(global, { captcha_blocked: true, pause_reason: 'resolution' }); + assert.equal(queue.length, 2); + assert.equal(queue[0].token, cookie); + assert.equal(queue[0].url, original[0].url); + assert.equal(queue[0].filename, original[0].filename); + assert.equal(queue[0].processing, undefined); + assert.equal(queue[0].started_at, undefined); + assert.deepEqual(queue[1], original[1]); + assert.equal(history.length, 1); + assert.equal(history[0].error_category, 'resolution'); + assert.equal(history[0].token, undefined); + assert.equal(await claimNextJob(db), null); + assert.equal(claims, 0); + await assertNoBytecode(directory); + } +}); diff --git a/tests/fixtures/legacy-contracts.json b/tests/fixtures/legacy-contracts.json new file mode 100644 index 0000000..a899580 --- /dev/null +++ b/tests/fixtures/legacy-contracts.json @@ -0,0 +1,85 @@ +{ + "version": 1, + "baselineCommit": "211bfd174dd78eac36f3c74411ecaa72f56eec79", + "description": "Synthetic examples captured from the reviewed source. IDs, tokens, timestamps, filenames, and logs are fictional. These fixtures must never initiate network requests.", + "cli": { + "video": { + "script": "scripts/proxer-dl-video.py", + "requiredFlags": [["-u", "--url"], ["-f", "--filename"], ["-t", "--token"], ["-o", "--output"]] + }, + "series": { + "script": "scripts/proxer-dl-series.py", + "requiredFlags": [["-i", "--id"], ["-n", "--name"], ["-e", "--episodes"], ["-l", "--language"], ["-t", "--token"], ["-o", "--output"]], + "languages": ["engsub", "engdub", "gersub", "gerdub"] + } + }, + "namingCases": [ + { + "entrypoint": "web-video", + "input": { "url": "https://proxer.me/watch/999999999/2/engsub" }, + "expectedFilenames": ["999999999 E2 engsub"] + }, + { + "entrypoint": "web-video", + "input": { "url": "https://proxer.me/watch/999999999/2/engsub", "filename": "Fixture Video S01E02" }, + "expectedFilenames": ["Fixture Video S01E02"] + }, + { + "entrypoint": "web-series", + "input": { "id": "999999999", "name": "Fixture Series ", "episode_from": "9", "episode_to": "10", "language": "gersub" }, + "expectedFilenames": ["Fixture SeriesE09_gersub", "Fixture SeriesE10_gersub"] + }, + { + "entrypoint": "web-series", + "input": { "id": "999999999", "episode_from": "1", "episode_to": "2", "language": "gerdub" }, + "expectedFilenames": ["999999999E1_gerdub", "999999999E2_gerdub"] + }, + { + "entrypoint": "cli-series", + "input": { "id": "999999999", "name": "Fixture Series", "episodes": "9-10", "language": "engdub" }, + "expectedFilenames": ["Fixture Series_Episode_9_engdub.mp4", "Fixture Series_Episode_10_engdub.mp4"] + } + ], + "legacyDocuments": { + "queue": [ + { + "_id": "000000000000000000000001", + "url": "https://proxer.me/watch/999999999/1/engsub", + "token": "PHASE1_FIXTURE_COOKIE=NOT_A_REAL_TOKEN==", + "filename": "Fixture SeriesE1_engsub", + "created_at": "2026-01-01T12:00:00.000Z" + }, + { + "_id": "000000000000000000000002", + "url": "https://proxer.me/watch/999999999/2/engsub", + "token": "PHASE1_FIXTURE_COOKIE=NOT_A_REAL_TOKEN==", + "filename": "Fixture SeriesE2_engsub", + "created_at": "2026-01-01T12:00:00.000Z", + "processing": true + } + ], + "done": [ + { + "_id": "000000000000000000000003", + "filename": "Fixture Completed", + "finished_at": "2026-01-01T12:10:00.000Z", + "output_log": "Synthetic completed download log." + } + ], + "failed": [ + { + "_id": "000000000000000000000004", + "filename": "Fixture Failed", + "failed_at": "2026-01-01T12:11:00.000Z", + "output_log": "Synthetic network failure log." + } + ], + "settings": [{ "_id": "global", "captcha_blocked": false }] + }, + "intentionalPhase1Corrections": [ + "The video web form's name field becomes a usable filename fallback; explicit legacy filename remains supported.", + "Python failures must exit nonzero and produce a failed result; historical zero-exit failures are not preserved.", + "Unsafe or malformed paths, URLs, cookies, and unbounded episode ranges are rejected.", + "Public status documents exclude credential fields." + ] +} diff --git a/tests/fixtures/protected-lib-manifest.json b/tests/fixtures/protected-lib-manifest.json new file mode 100644 index 0000000..dba72e7 --- /dev/null +++ b/tests/fixtures/protected-lib-manifest.json @@ -0,0 +1,16 @@ +{ + "version": 1, + "baselineCommit": "211bfd174dd78eac36f3c74411ecaa72f56eec79", + "protectedRoot": "scripts/lib", + "entries": [ + { "path": ".", "type": "directory" }, + { "path": "__pycache__", "type": "directory" }, + { "path": "__pycache__/proxer_utils.cpython-311.pyc", "type": "file", "sha256": "031db0ff7cdf5658ee6e722f387c40e0d77075c74c889c7e90a0594039fa7c06", "executable": true }, + { "path": "__pycache__/proxer_utils.cpython-313.pyc", "type": "file", "sha256": "6f2f3533e4a73876977d4036be681efaa025a658e666c2fda19f961c34a88a05", "executable": true }, + { "path": "__pycache__/proxer_utils.cpython-38.pyc", "type": "file", "sha256": "84525538e325d3345596147e8f7895c42be89374f03673546a3533db00aecf28", "executable": true }, + { "path": "__pycache__/script_utils.cpython-313.pyc", "type": "file", "sha256": "bf60ab460120ace66aa3cd78b3317fc4193de6339b1150d8e5dcdb30d583e5e0", "executable": true }, + { "path": "__pycache__/script_utils.cpython-38.pyc", "type": "file", "sha256": "cc0fc12c9dfb77d2be003e4c23d020c1940d3694a0be457205f391de31529a45", "executable": true }, + { "path": "proxer_utils.py", "type": "file", "sha256": "52820651360fd5fd351d28fe979fda494092a6947467ae65f600064722941789", "executable": true }, + { "path": "script_utils.py", "type": "file", "sha256": "dfc4e19fd5395b77c746871b34a14c134022883c571e3603bb35346307e9e017", "executable": true } + ] +} diff --git a/tests/protected-lib.test.js b/tests/protected-lib.test.js new file mode 100644 index 0000000..39f880f --- /dev/null +++ b/tests/protected-lib.test.js @@ -0,0 +1,98 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { verifyProtectedTree, readManifest } = require('../tools/check-protected-lib'); + +const repositoryRoot = path.resolve(__dirname, '..'); +const manifest = readManifest(); + +function temporaryRepository(t) { + // Keep temporary writes within the checkout; no source fixture is modified. + const directory = fs.mkdtempSync(path.join(repositoryRoot, '.protected-test-')); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + fs.mkdirSync(path.join(directory, 'scripts')); + fs.cpSync(path.join(repositoryRoot, 'scripts/lib'), path.join(directory, 'scripts/lib'), { recursive: true }); + return directory; +} + +test('the actual protected library matches the reviewed baseline', () => { + const result = verifyProtectedTree(repositoryRoot, manifest); + assert.equal(result.ok, true, result.errors.join('\n')); + assert.equal(result.fileCount, 7); +}); + +test('an unchanged complete copy passes', t => { + const result = verifyProtectedTree(temporaryRepository(t), manifest); + assert.equal(result.ok, true, result.errors.join('\n')); +}); + +test('changed protected source is detected', t => { + const directory = temporaryRepository(t); + fs.appendFileSync(path.join(directory, 'scripts/lib/proxer_utils.py'), '\n# test change\n'); + const result = verifyProtectedTree(directory, manifest); + assert.equal(result.ok, false); + assert.match(result.errors.join('\n'), /content changed: scripts\/lib\/proxer_utils\.py/); +}); + +test('missing protected bytecode is detected', t => { + const directory = temporaryRepository(t); + fs.unlinkSync(path.join(directory, 'scripts/lib/__pycache__/proxer_utils.cpython-311.pyc')); + const result = verifyProtectedTree(directory, manifest); + assert.equal(result.ok, false); + assert.match(result.errors.join('\n'), /Missing protected entry/); +}); + +test('new bytecode and hidden files are detected even if git would ignore them', t => { + const directory = temporaryRepository(t); + fs.writeFileSync(path.join(directory, 'scripts/lib/__pycache__/proxer_utils.cpython-314.pyc'), 'new bytecode'); + fs.writeFileSync(path.join(directory, 'scripts/lib/.generated'), 'new hidden file'); + const result = verifyProtectedTree(directory, manifest); + assert.equal(result.ok, false); + assert.match(result.errors.join('\n'), /Unexpected protected entry: scripts\/lib\/__pycache__\/proxer_utils\.cpython-314\.pyc/); + assert.match(result.errors.join('\n'), /Unexpected protected entry: scripts\/lib\/\.generated/); +}); + +test('an added empty directory is detected', t => { + const directory = temporaryRepository(t); + fs.mkdirSync(path.join(directory, 'scripts/lib/generated')); + const result = verifyProtectedTree(directory, manifest); + assert.equal(result.ok, false); + assert.match(result.errors.join('\n'), /Unexpected protected entry: scripts\/lib\/generated/); +}); + +test('a protected file replaced by a symlink is detected without following it', t => { + const directory = temporaryRepository(t); + const file = path.join(directory, 'scripts/lib/proxer_utils.py'); + fs.unlinkSync(file); + fs.symlinkSync('/nonexistent/protected-test-target', file); + const result = verifyProtectedTree(directory, manifest); + assert.equal(result.ok, false); + assert.match(result.errors.join('\n'), /entry type changed: scripts\/lib\/proxer_utils\.py/); +}); + +test('a symlinked scripts directory is rejected', t => { + const directory = temporaryRepository(t); + fs.renameSync(path.join(directory, 'scripts'), path.join(directory, 'moved-scripts')); + fs.symlinkSync('moved-scripts', path.join(directory, 'scripts')); + const result = verifyProtectedTree(directory, manifest); + assert.equal(result.ok, false); + assert.match(result.errors.join('\n'), /scripts must be a real directory/); +}); + +test('executable-bit changes are detected', t => { + const directory = temporaryRepository(t); + fs.chmodSync(path.join(directory, 'scripts/lib/proxer_utils.py'), 0o644); + const result = verifyProtectedTree(directory, manifest); + assert.equal(result.ok, false); + assert.match(result.errors.join('\n'), /executable bit changed/); +}); + +test('an invalid manifest cannot redirect the checked path', t => { + const directory = temporaryRepository(t); + const result = verifyProtectedTree(directory, { ...manifest, protectedRoot: '../outside' }); + assert.equal(result.ok, false); + assert.match(result.errors.join('\n'), /Invalid protected-library manifest/); +}); diff --git a/tests/python/test_downloader.py b/tests/python/test_downloader.py new file mode 100644 index 0000000..204aace --- /dev/null +++ b/tests/python/test_downloader.py @@ -0,0 +1,490 @@ +"""Offline regression checks for CLI boundaries; no production stream is invoked.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import types +import unittest +from unittest.mock import Mock, patch + + +sys.dont_write_bytecode = True +ROOT = Path(__file__).resolve().parents[2] +SCRIPTS = ROOT / "scripts" +sys.path.insert(0, str(SCRIPTS)) + + +def load_script(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +video = load_script("phase1_video", SCRIPTS / "proxer-dl-video.py") +series = load_script("phase1_series", SCRIPTS / "proxer-dl-series.py") +import request_validation as validation + + +def protected_snapshot(): + return {str(path.relative_to(ROOT)): hashlib.sha256(path.read_bytes()).hexdigest() + for path in (SCRIPTS / "lib").rglob("*") if path.is_file()} + + +class ValidationTests(unittest.TestCase): + def test_cookie_preserves_equals_in_value(self): + self.assertEqual(validation.parse_token("FixtureCookie=base64=="), ("FixtureCookie", "base64==")) + + def test_stdin_cookie_preserves_equals_and_accepts_one_line(self): + args = types.SimpleNamespace(token_stdin=True, token=None) + for ending in ("", "\n", "\r\n"): + with self.subTest(ending=ending): + self.assertEqual(validation.token_from_args(args, io.StringIO("FixtureCookie=base64==" + ending)), + ("FixtureCookie", "base64==")) + + def test_stdin_cookie_rejects_extra_lines_controls_and_overflow(self): + args = types.SimpleNamespace(token_stdin=True, token=None) + for value in ("FixtureCookie=abc\nsecond\n", "FixtureCookie=abc\n\n", "FixtureCookie=a\x00b\n", + "FixtureCookie=a\x80b\n", "a=" + "b" * 8191 + "\n"): + with self.subTest(length=len(value)), self.assertRaises(validation.ValidationError): + validation.token_from_args(args, io.StringIO(value)) + + def test_token_length_boundary_and_invalid_utf8(self): + args = types.SimpleNamespace(token_stdin=True, token=None) + value = "a=" + "b" * 8190 + self.assertEqual(validation.token_from_args(args, io.StringIO(value + "\n")), ("a", "b" * 8190)) + with self.assertRaises(validation.ValidationError): + validation.token_from_args(args, io.BytesIO(b"a=\xff\n")) + with self.assertRaises(validation.ValidationError): + validation.parse_token(value + "b") + + def test_invalid_cookies_are_rejected(self): + for token in ("", "name", "=value", "name=", "bad name=value", "name=a\nb", "name=a;b", "name=a b"): + with self.subTest(token=token), self.assertRaises(validation.ValidationError): + validation.parse_token(token) + + def test_canonical_watch_url(self): + self.assertEqual(validation.validate_watch_url("https://www.proxer.me:443/watch/123/9/engsub/#details"), + "https://proxer.me/watch/123/9/engsub") + + def test_watch_url_length_is_bounded(self): + base = "https://proxer.me/watch/123/1/engsub#" + self.assertEqual(validation.validate_watch_url(base + "x" * (2048 - len(base))), + "https://proxer.me/watch/123/1/engsub") + with self.assertRaises(validation.ValidationError): + validation.validate_watch_url(base + "x" * (2049 - len(base))) + + def test_unsupported_or_ambiguous_urls_are_rejected(self): + for url in ("http://proxer.me/watch/123/1/engsub", "https://proxer.me.evil.invalid/watch/123/1/engsub", + "https://user:password@proxer.me/watch/123/1/engsub", "https://proxer.me:8443/watch/123/1/engsub", + "https://proxer.me/watch/123/1/engsub?cookie=secret", "https://proxer.me/watch/0/1/engsub", + "https://proxer.me/watch/123/0/engsub", "https://proxer.me/watch/123/1/de", + "https://proxer.me/watch/123/1/engsub\n", "https://proxer.me/watch/9007199254740992/1/engsub"): + with self.subTest(url=url), self.assertRaises(validation.ValidationError): + validation.validate_watch_url(url) + + def test_unsafe_filenames_are_rejected(self): + for filename in ("", ".", "..", "../outside", "nested/name", "nested\\name", "nul\x00name", "line\nname", " leading", "trailing "): + with self.subTest(filename=filename), self.assertRaises(validation.ValidationError): + validation.validate_filename(filename) + self.assertEqual(validation.validate_filename("A safe 日本語 name S01E02"), "A safe 日本語 name S01E02") + + def test_filename_limit_counts_utf8_bytes_and_extension(self): + self.assertEqual(validation.validate_filename("a" * 251), "a" * 251) + for filename in ("a" * 252, "日" * 84): + with self.subTest(filename=filename), self.assertRaises(validation.ValidationError): + validation.validate_filename(filename) + + def test_ranges_are_inclusive_bounded_and_strict(self): + with patch.dict(os.environ, {"MAX_SERIES_EPISODES": "2"}): + self.assertEqual(validation.episode_range("9-10"), (9, 10)) + for value in ("1-3", "3-2", "0-2", "1.0-2", "1-2-3", "1-", "1e1-12", "1-9007199254740992"): + with self.subTest(value=value), self.assertRaises(validation.ValidationError): + validation.episode_range(value) + + def test_default_range_limit_is_500(self): + with patch.dict(os.environ, {}, clear=True): + self.assertEqual(validation.episode_range("1-500"), (1, 500)) + with self.assertRaises(validation.ValidationError): + validation.episode_range("1-501") + + def test_bad_range_configuration_is_a_validation_error(self): + with patch.dict(os.environ, {"MAX_SERIES_EPISODES": "unlimited"}), self.assertRaises(validation.ValidationError): + validation.episode_range("1-2") + + def test_series_configuration_matches_shared_limit(self): + for value in ("0", "10001", "9" * 5000): + with self.subTest(length=len(value)), patch.dict(os.environ, {"MAX_SERIES_EPISODES": value}), self.assertRaises(validation.ValidationError): + validation.episode_range("1-2") + for value in ("10000", "00002", ""): + with self.subTest(value=value), patch.dict(os.environ, {"MAX_SERIES_EPISODES": value}): + self.assertEqual(validation.episode_range("1-2"), (1, 2)) + + def test_oversized_integer_is_rejected_without_conversion_failure(self): + with self.assertRaises(validation.ValidationError): + validation.positive_integer("9" * 5000, "Series ID") + + def test_authentication_requires_status_evidence_not_message_keywords(self): + error = RuntimeError("filename token-captcha-403-blocked.mp4") + self.assertEqual(validation.error_result(error)["errorCategory"], "unknown") + error.response = types.SimpleNamespace(status_code=403) + self.assertEqual(validation.error_result(error)["errorCategory"], "authentication") + + def test_chained_authentication_error_is_recognized_without_secret_output(self): + cause = RuntimeError("https://signed.invalid/file?token=DO_NOT_LOG") + cause.response = types.SimpleNamespace(status_code=401) + outer = RuntimeError("wrapped DO_NOT_LOG") + outer.__context__ = cause + result = validation.error_result(outer) + self.assertEqual(result["errorCategory"], "authentication") + self.assertNotIn("DO_NOT_LOG", json.dumps(result)) + + def test_resolution_requires_exact_library_exception_metadata(self): + unrelated_not_found = type("NotFoundError", (Exception,), {"__module__": "unrelated_library"}) + for error in (unrelated_not_found("DO_NOT_LOG"), RuntimeError("Embed code not found captcha DO_NOT_LOG")): + with self.subTest(error_type=type(error)): + result = validation.error_result(error) + self.assertEqual(result["errorCategory"], "unknown") + self.assertNotIn("DO_NOT_LOG", json.dumps(result)) + + +class DownloadTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.original_protected = protected_snapshot() + + @classmethod + def tearDownClass(cls): + if protected_snapshot() != cls.original_protected: + raise AssertionError("The protected library tree changed during Python tests.") + + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="proxer-phase1-") + self.addCleanup(self.temporary.cleanup) + self.output = Path(self.temporary.name) + package = types.ModuleType("lib") + package.__path__ = [] + self.library = types.ModuleType("lib.proxer_utils") + self.library.NetworkError = type("NetworkError", (Exception,), {"__module__": "lib.proxer_utils"}) + self.library.NotFoundError = type("NotFoundError", (Exception,), {"__module__": "lib.proxer_utils"}) + self.library.get_embed_url = Mock(return_value="https://signed.invalid/embed?token=DO_NOT_LOG") + self.library.get_mp4_url = Mock(return_value="https://signed.invalid/video?token=DO_NOT_LOG") + self.library.download_mp4 = Mock(side_effect=lambda url, target, label: Path(target).write_bytes(b"synthetic media fixture")) + self.module_patch = patch.dict(sys.modules, {"lib": package, "lib.proxer_utils": self.library}) + self.module_patch.start() + self.addCleanup(self.module_patch.stop) + self.sleep_patch = patch.object(series, "sleep") + self.sleep_patch.start() + self.addCleanup(self.sleep_patch.stop) + self.env_patch = patch.dict(os.environ, {"MAX_SERIES_EPISODES": "500"}) + self.env_patch.start() + self.addCleanup(self.env_patch.stop) + + def video_args(self, **overrides): + values = {"url": "https://proxer.me/watch/999999999/2/engsub", "filename": "Fixture Video S01E02", + "token": "FixtureCookie=NOT_REAL==", "output": str(self.output)} + values.update(overrides) + return [part for key, value in values.items() for part in ("--" + key, value)] + + def series_args(self, **overrides): + values = {"id": "999999999", "name": "Fixture Series", "episodes": "1-2", "language": "engsub", + "token": "FixtureCookie=NOT_REAL==", "output": str(self.output)} + values.update(overrides) + return [part for key, value in values.items() for part in ("--" + key, value)] + + def invoke(self, entrypoint, args): + stdout, stderr = io.StringIO(), io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + code = entrypoint.main(args) + records = [line[len(validation.RESULT_PREFIX):] for line in stdout.getvalue().splitlines() + if line.startswith(validation.RESULT_PREFIX)] + self.assertEqual(len(records), 1, stdout.getvalue()) + self.assertNotIn("DO_NOT_LOG", stdout.getvalue() + stderr.getvalue()) + self.assertNotIn("NOT_REAL", stdout.getvalue() + stderr.getvalue()) + return code, json.loads(records[0]), stdout.getvalue() + + def test_video_success_has_one_result_and_preserves_stream_order(self): + calls = Mock() + calls.attach_mock(self.library.get_embed_url, "embed") + calls.attach_mock(self.library.get_mp4_url, "media") + calls.attach_mock(self.library.download_mp4, "download") + code, result, _ = self.invoke(video, self.video_args()) + self.assertEqual(code, 0) + self.assertEqual(result, {"version": 1, "status": "completed"}) + self.assertEqual([item[0] for item in calls.mock_calls], ["embed", "media", "download"]) + self.assertEqual(self.library.get_embed_url.call_args.args[1], ("FixtureCookie", "NOT_REAL==")) + self.assertTrue((self.output / "Fixture Video S01E02.mp4").is_file()) + + def test_resolver_failure_is_nonzero_and_requires_verification(self): + for resolver in (self.library.get_embed_url, self.library.get_mp4_url): + for wrapped in (False, True): + with self.subTest(resolver=resolver, wrapped=wrapped): + error = self.library.NotFoundError("https://signed.invalid/page?token=DO_NOT_LOG") + if wrapped: + outer = RuntimeError("wrapped DO_NOT_LOG") + outer.__cause__ = error + error = outer + resolver.side_effect = error + code, result, _ = self.invoke(video, self.video_args()) + self.assertEqual(code, 1) + self.assertEqual(result["status"], "failed") + self.assertEqual(result["errorCategory"], "resolution") + self.assertIn("verification", result["message"]) + self.assertNotIn("captcha", result["message"].lower()) + self.library.download_mp4.assert_not_called() + resolver.side_effect = None + + def test_wrapped_http_status_distinguishes_authentication_from_missing_source(self): + http_error = type("HTTPError", (Exception,), {"__module__": "requests.exceptions"}) + for status, category in ((401, "authentication"), (403, "authentication"), (404, "source")): + with self.subTest(status=status): + cause = http_error("https://signed.invalid/page?token=DO_NOT_LOG") + cause.response = types.SimpleNamespace(status_code=status) + error = self.library.NetworkError("Failed to fetch episode page: DO_NOT_LOG") + error.__context__ = cause + self.library.get_embed_url.side_effect = error + code, result, _ = self.invoke(video, self.video_args()) + self.assertEqual(code, 1) + self.assertEqual(result["errorCategory"], category) + self.library.download_mp4.assert_not_called() + + def test_network_failure_is_not_automatically_authentication(self): + self.library.get_mp4_url.side_effect = self.library.NetworkError("captcha token 403 DO_NOT_LOG") + code, result, _ = self.invoke(video, self.video_args()) + self.assertNotEqual(code, 0) + self.assertEqual(result["errorCategory"], "network") + + def test_transfer_failure_is_nonzero_even_when_an_old_file_exists(self): + (self.output / "Fixture Video S01E02.mp4").write_bytes(b"old output") + self.library.download_mp4.side_effect = RuntimeError("DO_NOT_LOG") + code, result, _ = self.invoke(video, self.video_args()) + self.assertNotEqual(code, 0) + self.assertEqual(result["status"], "failed") + + def test_storage_failure_is_nonzero(self): + self.library.download_mp4.side_effect = PermissionError("DO_NOT_LOG") + code, result, _ = self.invoke(video, self.video_args()) + self.assertNotEqual(code, 0) + self.assertEqual(result["errorCategory"], "storage") + + def test_missing_stream_dependency_is_configuration_failure(self): + for entrypoint, args in ((video, self.video_args()), (series, self.series_args())): + with self.subTest(entrypoint=entrypoint.__name__), patch.dict(sys.modules, {"lib.proxer_utils": None}): + code, result, _ = self.invoke(entrypoint, args) + self.assertNotEqual(code, 0) + self.assertEqual(result["errorCategory"], "configuration") + self.library.get_embed_url.assert_not_called() + + def test_dependency_import_error_never_exposes_exception_text(self): + self.library.get_embed_url.side_effect = ImportError("DO_NOT_LOG") + code, result, _ = self.invoke(video, self.video_args()) + self.assertNotEqual(code, 0) + self.assertEqual(result["errorCategory"], "configuration") + + def test_missing_or_empty_output_is_not_success(self): + for make_empty in (False, True): + with self.subTest(make_empty=make_empty): + self.library.download_mp4.side_effect = lambda url, target, label: Path(target).touch() if make_empty else None + code, result, _ = self.invoke(video, self.video_args()) + self.assertNotEqual(code, 0) + self.assertEqual(result["errorCategory"], "storage") + + def test_invalid_url_never_calls_protected_library(self): + code, result, _ = self.invoke(video, self.video_args(url="https://unrelated.invalid/watch/1/1/engsub")) + self.assertEqual(code, 2) + self.assertEqual(result["errorCategory"], "validation") + self.library.get_embed_url.assert_not_called() + + def test_path_traversal_never_calls_protected_library(self): + code, result, _ = self.invoke(video, self.video_args(filename="../outside")) + self.assertEqual(code, 2) + self.assertEqual(result["errorCategory"], "validation") + self.library.get_embed_url.assert_not_called() + + def test_missing_output_directory_is_not_created(self): + missing = self.output / "missing" + code, result, _ = self.invoke(video, self.video_args(output=str(missing))) + self.assertEqual(code, 1) + self.assertEqual(result["errorCategory"], "storage") + self.assertFalse(missing.exists()) + + def test_symlink_output_is_rejected_and_target_untouched(self): + outside = self.output / "other-file" + outside.write_bytes(b"must not change") + (self.output / "Fixture Video S01E02.mp4").symlink_to(outside) + code, result, _ = self.invoke(video, self.video_args()) + self.assertEqual(code, 2) + self.assertEqual(result["errorCategory"], "validation") + self.assertEqual(outside.read_bytes(), b"must not change") + self.library.download_mp4.assert_not_called() + + def test_nonregular_output_is_rejected(self): + (self.output / "Fixture Video S01E02.mp4").mkdir() + code, _, _ = self.invoke(video, self.video_args()) + self.assertEqual(code, 2) + self.library.download_mp4.assert_not_called() + + def test_invalid_cli_arguments_emit_safe_failure(self): + code, result, output = self.invoke(video, ["--unrecognized", "DO_NOT_LOG"]) + self.assertEqual(code, 2) + self.assertEqual(result["errorCategory"], "validation") + self.assertNotIn("DO_NOT_LOG", output) + + def test_video_stdin_token_uses_same_pipeline(self): + args = self.video_args() + position = args.index("--token") + args[position:position + 2] = ["--token-stdin"] + with patch.object(sys, "stdin", io.StringIO("FixtureCookie=NOT_REAL==\n")): + code, result, _ = self.invoke(video, args) + self.assertEqual(code, 0) + self.assertEqual(result["status"], "completed") + self.assertEqual(self.library.get_embed_url.call_args.args[1], ("FixtureCookie", "NOT_REAL==")) + + def test_series_stdin_token_and_mutual_exclusion(self): + args = self.series_args() + position = args.index("--token") + args[position:position + 2] = ["--token-stdin"] + with patch.object(sys, "stdin", io.StringIO("FixtureCookie=NOT_REAL==\n")): + code, _, _ = self.invoke(series, args) + self.assertEqual(code, 0) + code, result, _ = self.invoke(video, self.video_args() + ["--token-stdin"]) + self.assertEqual(code, 2) + self.assertEqual(result["errorCategory"], "validation") + + def test_series_preserves_legacy_filenames_and_cli_flags(self): + fixtures = json.loads((ROOT / "tests/fixtures/legacy-contracts.json").read_text()) + sample = next(item for item in fixtures["namingCases"] if item["entrypoint"] == "cli-series") + args = self.series_args(**sample["input"]) + code, result, _ = self.invoke(series, args) + self.assertEqual(code, 0) + self.assertEqual(result["completed"], 2) + self.assertEqual(sorted(path.name for path in self.output.iterdir()), sorted(sample["expectedFilenames"])) + for mode, entrypoint, normal_args in (("video", video, self.video_args()), ("series", series, args)): + replacements = {long: short for short, long in fixtures["cli"][mode]["requiredFlags"]} + self.assertEqual(vars(entrypoint.parse_args(normal_args)), + vars(entrypoint.parse_args([replacements.get(arg, arg) for arg in normal_args]))) + + def test_series_partial_failure_is_nonzero_with_counts(self): + calls = 0 + + def transfer(url, target, label): + nonlocal calls + calls += 1 + if calls == 1: + raise self.library.NetworkError("DO_NOT_LOG") + Path(target).write_bytes(b"synthetic media fixture") + + self.library.download_mp4.side_effect = transfer + code, result, _ = self.invoke(series, self.series_args()) + self.assertNotEqual(code, 0) + self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (1, 1, 0)) + self.assertEqual(result["failures"], [{"episode": 1, "errorCategory": "network"}]) + + def test_series_access_failure_stops_remaining_requests(self): + error = self.library.NetworkError("DO_NOT_LOG") + error.response = types.SimpleNamespace(status_code=403) + self.library.get_embed_url.side_effect = error + code, result, _ = self.invoke(series, self.series_args(episodes="1-3")) + self.assertNotEqual(code, 0) + self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (0, 1, 2)) + self.assertEqual(self.library.get_embed_url.call_count, 1) + + def test_series_resolution_failure_stops_remaining_requests(self): + self.library.get_embed_url.side_effect = ["synthetic-embed", self.library.NotFoundError("DO_NOT_LOG")] + code, result, _ = self.invoke(series, self.series_args(episodes="1-4")) + self.assertEqual(code, 1) + self.assertEqual(result["errorCategory"], "resolution") + self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (1, 1, 2)) + self.assertEqual(result["failures"], [{"episode": 2, "errorCategory": "resolution"}]) + self.assertEqual(self.library.get_embed_url.call_count, 2) + self.assertEqual(self.library.download_mp4.call_count, 1) + + def test_series_confirmed_missing_source_does_not_pause_remaining_requests(self): + cause = RuntimeError("DO_NOT_LOG") + cause.response = types.SimpleNamespace(status_code=404) + error = self.library.NetworkError("DO_NOT_LOG") + error.__context__ = cause + self.library.get_embed_url.side_effect = [error, "synthetic-embed"] + code, result, _ = self.invoke(series, self.series_args()) + self.assertEqual(code, 1) + self.assertEqual(result["errorCategory"], "source") + self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (1, 1, 0)) + self.assertEqual(self.library.get_embed_url.call_count, 2) + self.assertEqual(self.library.download_mp4.call_count, 1) + + def test_series_host_failures_stop_remaining_requests(self): + for error, expected_category in ((PermissionError("DO_NOT_LOG"), "storage"), + (ImportError("DO_NOT_LOG"), "configuration")): + with self.subTest(category=expected_category): + self.library.get_embed_url.reset_mock() + self.library.get_embed_url.side_effect = error + code, result, _ = self.invoke(series, self.series_args(episodes="1-3")) + self.assertNotEqual(code, 0) + self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (0, 1, 2)) + self.assertEqual(result["errorCategory"], expected_category) + self.assertEqual(self.library.get_embed_url.call_count, 1) + + def test_series_summary_reports_failure_that_stopped_the_batch(self): + for error, category in ((PermissionError("DO_NOT_LOG"), "storage"), + (self.library.NotFoundError("DO_NOT_LOG"), "resolution")): + with self.subTest(category=category): + self.library.get_embed_url.reset_mock() + self.library.get_embed_url.side_effect = [self.library.NetworkError("DO_NOT_LOG"), error] + code, result, _ = self.invoke(series, self.series_args(episodes="1-3")) + self.assertNotEqual(code, 0) + self.assertEqual(result["errorCategory"], category) + self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (0, 2, 1)) + self.assertEqual(self.library.get_embed_url.call_count, 2) + + def test_series_validates_every_destination_before_requests(self): + (self.output / "Fixture Series_Episode_2_engsub.mp4").symlink_to(self.output / "missing") + code, result, _ = self.invoke(series, self.series_args()) + self.assertEqual(code, 2) + self.assertEqual(result["errorCategory"], "validation") + self.library.get_embed_url.assert_not_called() + + +class ProcessExitTests(unittest.TestCase): + def test_real_cli_entrypoint_reports_process_exit(self): + # Run __main__ in a separate process with an entirely synthetic imported library. + driver = ''' +import pathlib, runpy, sys, types +root, destination, mode = sys.argv[1:] +sys.path.insert(0, str(pathlib.Path(root) / "scripts")) +package = types.ModuleType("lib") +package.__path__ = [] +library = types.ModuleType("lib.proxer_utils") +library.get_embed_url = lambda *args: "synthetic-embed" +library.get_mp4_url = lambda *args: "synthetic-media" +def download(url, path, label): + if mode == "fail": + raise RuntimeError("PRIVATE_SIGNED_URL_DO_NOT_LOG") + pathlib.Path(path).write_bytes(b"synthetic payload") +library.download_mp4 = download +sys.modules["lib"] = package +sys.modules["lib.proxer_utils"] = library +script = str(pathlib.Path(root) / "scripts/proxer-dl-video.py") +sys.argv = [script, "-u", "https://proxer.me/watch/999999999/1/engsub", "-f", "Fixture", "-t", "FixtureCookie=synthetic==", "-o", destination] +runpy.run_path(script, run_name="__main__") +''' + before = protected_snapshot() + for mode, expected_code in (("ok", 0), ("fail", 1)): + with self.subTest(mode=mode), tempfile.TemporaryDirectory(prefix="proxer-cli-") as destination: + result = subprocess.run([sys.executable, "-B", "-c", driver, str(ROOT), destination, mode], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, expected_code, result.stderr) + records = [line for line in result.stdout.splitlines() if line.startswith(validation.RESULT_PREFIX)] + self.assertEqual(len(records), 1) + self.assertNotIn("PRIVATE_SIGNED_URL", result.stdout + result.stderr) + self.assertEqual(protected_snapshot(), before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/runtime.test.js b/tests/runtime.test.js new file mode 100644 index 0000000..440d13c --- /dev/null +++ b/tests/runtime.test.js @@ -0,0 +1,411 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const { createConfig } = require('../lib/config'); +const { createDbProvider } = require('../lib/mongo'); +const { LOG_LIMIT, sanitizeLog, createLineSanitizer } = require('../lib/logging'); +const { createPm2Controller, normalizeProcess } = require('../controllers/pm2Controller'); + +const settings = createConfig({ + MONGO_URI: 'mongodb://fixture-user:NOT_A_REAL_PASSWORD@database.invalid/fixture', + MONGO_DB: 'phase1_fixture', +}); + +function response() { + return { + statusCode: 200, + status(code) { this.statusCode = code; return this; }, + json(value) { this.body = value; return this; }, + render(view, value) { this.view = view; this.body = value; return this; }, + }; +} + +function pm2Process(overrides = {}) { + return { + name: 'proxer-worker-1', + pid: 1234, + pm_id: 0, + monit: { cpu: 2.5, memory: 8 * 1024 * 1024 }, + pm2_env: { + name: 'proxer-worker-1', + pm_id: 0, + status: 'online', + pm_uptime: Date.now() - 60_000, + pm_exec_path: settings.workerScript, + MONGO_URI: settings.mongoUri, + TOKEN: 'NOT_A_REAL_PM2_TOKEN', + env: { PASSWORD: 'NOT_A_REAL_PM2_PASSWORD' }, + }, + ...overrides, + }; +} + +function supervisor(processes = [], commandResult = {}) { + const calls = []; + const controller = createPm2Controller({ + settings, + run: async args => { + calls.push([...args]); + if (args[0] === 'jlist') return { code: 0, stdout: JSON.stringify(processes), stderr: '' }; + return { code: 0, stdout: 'NOT_A_REAL_STDOUT_SECRET', stderr: 'NOT_A_REAL_STDERR_SECRET', ...commandResult }; + }, + }); + return { controller, calls }; +} + +test('configuration defaults describe a portable home-directory installation', () => { + const config = createConfig({}); + assert.equal(config.mongoDb, 'downloads'); + assert.equal(config.outputDir, '/mnt/media/WIP'); + assert.equal(config.pythonPath, 'python3'); + assert.equal(config.maxSeriesEpisodes, 500); + assert.equal(config.port, 3000); + assert.equal(config.mongoUri, ''); + assert.equal(config.tokenPrefix, ''); + assert.equal(config.workerScript, path.join(config.projectRoot, 'queue_worker.js')); + assert.equal(config.videoScript, path.join(config.projectRoot, 'scripts/proxer-dl-video.py')); + assert.equal(Object.isFrozen(config), true); +}); + +test('web and worker configuration share explicit database and path overrides', () => { + const config = createConfig({ + MONGO_URI: settings.mongoUri, + MONGO_DB: 'private_download_queue', + OUTPUT_DIR: '/mnt/media/fixture-output', + VENV_PYTHON: '/home/fixture-download/Proxer-Downloader/.venv/bin/python', + TOKEN_PREFIX: 'FIXTURE_COOKIE=', + MAX_SERIES_EPISODES: '120', + PORT: '3033', + HOST: '127.0.0.1', + }); + assert.equal(config.mongoUri, settings.mongoUri); + assert.equal(config.mongoDb, 'private_download_queue'); + assert.equal(config.outputDir, '/mnt/media/fixture-output'); + assert.equal(config.pythonPath, '/home/fixture-download/Proxer-Downloader/.venv/bin/python'); + assert.equal(config.tokenPrefix, 'FIXTURE_COOKIE='); + assert.equal(config.maxSeriesEpisodes, 120); + assert.equal(config.port, 3033); + assert.equal(config.host, '127.0.0.1'); +}); + +test('configuration rejects malformed, unsafe, and out-of-range positive integers', () => { + for (const value of ['0', '-1', '1.5', 'Infinity', '12x', ' 12 ', '9007199254740993']) { + assert.throws(() => createConfig({ PORT: value }), /PORT/); + assert.throws(() => createConfig({ MAX_SERIES_EPISODES: value }), /MAX_SERIES_EPISODES/); + } + assert.throws(() => createConfig({ PORT: '65536' }), /PORT/); + assert.throws(() => createConfig({ MAX_SERIES_EPISODES: '10001' }), /MAX_SERIES_EPISODES/); + assert.equal(createConfig({ PORT: '', MAX_SERIES_EPISODES: '' }).port, 3000); +}); + +test('concurrent database callers share one connection and the configured database', async () => { + let instances = 0; + let connections = 0; + let closes = 0; + const selectedNames = []; + const selectedDb = { fixture: true }; + let release; + const connected = new Promise(resolve => { release = resolve; }); + class FakeMongoClient { + constructor(uri) { instances++; assert.equal(uri, settings.mongoUri); } + async connect() { connections++; await connected; } + db(name) { selectedNames.push(name); return selectedDb; } + async close() { closes++; } + } + const provider = createDbProvider({ settings, MongoClientClass: FakeMongoClient }); + const resultsPromise = Promise.all([provider.getDb(), provider.getDb(), provider.getDb()]); + await Promise.resolve(); + release(); + const results = await resultsPromise; + assert.equal(instances, 1); + assert.equal(connections, 1); + assert.deepEqual(selectedNames, ['phase1_fixture']); + assert.equal(results.every(value => value === selectedDb), true); + assert.equal(await provider.getDb(), selectedDb); + await provider.closeDb(); + assert.equal(closes, 1); +}); + +test('a failed database connection is sanitized, closed, and retryable', async () => { + let instances = 0; + let closes = 0; + const selectedDb = { recovered: true }; + class FakeMongoClient { + constructor() { this.attempt = ++instances; } + async connect() { + if (this.attempt === 1) throw new Error(`connect failed: ${settings.mongoUri}`); + } + db() { return selectedDb; } + async close() { closes++; } + } + const provider = createDbProvider({ settings, MongoClientClass: FakeMongoClient }); + await assert.rejects(provider.getDb(), error => { + assert.match(error.message, /Database connection failed/); + assert.equal(error.message.includes('NOT_A_REAL_PASSWORD'), false); + assert.equal(error.message.includes('mongodb://'), false); + return true; + }); + assert.equal(closes, 1); + assert.equal(await provider.getDb(), selectedDb); + assert.equal(instances, 2); + await provider.closeDb(); +}); + +test('database client construction errors cannot reveal the connection URI', async () => { + class ConstructorFailure { + constructor() { throw new Error(`Invalid URI: ${settings.mongoUri}`); } + } + const provider = createDbProvider({ settings, MongoClientClass: ConstructorFailure }); + await assert.rejects(provider.getDb(), error => { + assert.match(error.message, /Database connection failed/); + assert.equal(error.message.includes('NOT_A_REAL_PASSWORD'), false); + return true; + }); + await provider.closeDb(); +}); + +test('database selection errors are sanitized and do not poison later attempts', async () => { + let instances = 0; + let closes = 0; + const selectedDb = { recovered: true }; + class SelectionFailure { + constructor() { this.attempt = ++instances; } + async connect() {} + db() { + if (this.attempt === 1) throw new Error(`database selection failed: ${settings.mongoUri}`); + return selectedDb; + } + async close() { closes++; } + } + const provider = createDbProvider({ settings, MongoClientClass: SelectionFailure }); + await assert.rejects(provider.getDb(), error => { + assert.match(error.message, /Database connection failed/); + assert.equal(error.message.includes('NOT_A_REAL_PASSWORD'), false); + return true; + }); + assert.equal(closes, 1); + assert.equal(await provider.getDb(), selectedDb); + assert.equal(instances, 2); + await provider.closeDb(); +}); + +test('missing database configuration fails before constructing any client', async () => { + class UnexpectedClient { constructor() { assert.fail('A client must not be created without MONGO_URI.'); } } + const provider = createDbProvider({ settings: createConfig({}), MongoClientClass: UnexpectedClient }); + await assert.rejects(provider.getDb(), /MONGO_URI must be configured/); + await provider.closeDb(); +}); + +test('database close is idempotent, waits for a pending connection, and allows reopening', async () => { + let instances = 0; + let closes = 0; + let release; + const connected = new Promise(resolve => { release = resolve; }); + class FakeMongoClient { + constructor() { this.attempt = ++instances; } + async connect() { if (this.attempt === 1) await connected; } + db() { return { attempt: this.attempt }; } + async close() { closes++; } + } + const provider = createDbProvider({ settings, MongoClientClass: FakeMongoClient }); + const pending = provider.getDb(); + const closing = provider.closeDb(); + release(); + await Promise.all([pending, closing]); + assert.equal(closes, 1); + await provider.closeDb(); + assert.equal(closes, 1); + assert.deepEqual(await provider.getDb(), { attempt: 2 }); + await provider.closeDb(); + assert.equal(closes, 2); +}); + +test('logs redact URLs, credential fields, explicit secrets, and terminal control characters', () => { + const raw = [ + 'Resolved https://stream.invalid/video.mp4?signature=NOT_A_REAL_SIGNATURE', + 'Database mongodb+srv://fixture:NOT_A_REAL_PASSWORD@database.invalid/', + 'Authorization: Bearer NOT_A_REAL_BEARER', + 'Cookie=FIXTURE_COOKIE=NOT_A_REAL_COOKIE', + 'Raw known value KNOWN_FIXTURE_SECRET==', + '\x1b[31mReadable status\x1b[0m\x00', + ].join('\n'); + const sanitized = sanitizeLog(raw, ['KNOWN_FIXTURE_SECRET==']); + assert.doesNotMatch(sanitized, /NOT_A_REAL_|KNOWN_FIXTURE_SECRET|https:\/\/|mongodb\+srv:\/\/|\x1b|\x00/); + assert.match(sanitized, /Readable status/); + assert.match(sanitized, /\[redacted URL\]/); +}); + +test('streamed log redaction handles URLs and secrets split across pipe chunks', () => { + const lines = []; + const sanitizer = createLineSanitizer(line => lines.push(line), { secrets: ['KNOWN_FIXTURE_SECRET=='] }); + sanitizer.write(Buffer.from('Resolving https://stream.inv')); + sanitizer.write(Buffer.from('alid/video?signature=NOT_A_REAL_SIGNATURE and KNOWN_FIX')); + assert.deepEqual(lines, []); + sanitizer.write(Buffer.from('TURE_SECRET==\n')); + sanitizer.end(); + assert.equal(lines.length, 1); + assert.doesNotMatch(lines.join(''), /NOT_A_REAL_|KNOWN_FIXTURE_SECRET|stream\.invalid|https:/); + assert.match(lines.join(''), /\[redacted URL\]/); + assert.match(lines.join(''), /\[redacted\]/); +}); + +test('streamed log decoding preserves UTF-8 and sanitizes the unterminated final line', () => { + const lines = []; + const sanitizer = createLineSanitizer(line => lines.push(line)); + const input = Buffer.from('Grüße — fertig\nToken=NOT_A_REAL_TOKEN'); + const split = input.indexOf(Buffer.from('ü')) + 1; + sanitizer.write(input.subarray(0, split)); + sanitizer.write(input.subarray(split)); + sanitizer.end(); + assert.equal(lines[0], 'Grüße — fertig\n'); + assert.doesNotMatch(lines.join(''), /NOT_A_REAL_TOKEN|�/); +}); + +test('oversized streamed lines are discarded whole and subsequent lines recover', () => { + const lines = []; + const sanitizer = createLineSanitizer(line => lines.push(line), { maxLineLength: 32 }); + sanitizer.write('x'.repeat(100_000)); + sanitizer.write('NOT_A_REAL_TRAILING_SECRET\nNormal status\n'); + sanitizer.end(); + assert.deepEqual(lines, ['[oversized log line omitted]\n', 'Normal status\n']); +}); + +test('large stored logs remain bounded after redaction', () => { + const sanitized = sanitizeLog('x'.repeat(LOG_LIMIT * 4) + '\nToken=NOT_A_REAL_TOKEN'); + assert.ok(sanitized.length <= LOG_LIMIT + 64); + assert.match(sanitized, /^\[earlier log output omitted\]/); + assert.doesNotMatch(sanitized, /NOT_A_REAL_TOKEN/); +}); + +test('normalized PM2 data retains process ID zero and excludes raw environments', () => { + const normalized = normalizeProcess(pm2Process()); + assert.equal(normalized.pm_id, '0'); + assert.equal(normalized.cpu, '2.5%'); + assert.equal(normalized.memoryMB, '8 MB'); + assert.deepEqual(Object.keys(normalized).sort(), ['name', 'pid', 'pm_id', 'status', 'cpu', 'memoryMB', 'uptime', 'execPath'].sort()); + assert.doesNotMatch(JSON.stringify(normalized), /NOT_A_REAL_|MONGO_URI|pm2_env|"raw"/); +}); + +test('worker lists and management pages include only the configured worker executable', async () => { + const { controller, calls } = supervisor([ + pm2Process(), + pm2Process({ name: 'unrelated-app', pm_id: 3, pm2_env: { pm_exec_path: '/srv/unrelated/queue_worker.js', status: 'online' } }), + pm2Process({ name: 'same-prefix', pm_id: 4, pm2_env: { pm_exec_path: settings.workerScript + '.unrelated' } }), + ]); + const json = response(); + await controller.listJson({}, json); + assert.equal(json.statusCode, 200); + assert.equal(json.body.processes.length, 1); + assert.equal(json.body.processes[0].name, 'proxer-worker-1'); + assert.doesNotMatch(JSON.stringify(json.body), /NOT_A_REAL_|unrelated-app|same-prefix|pm2_env/); + const page = response(); + await controller.getManage({}, page, error => { throw error; }); + assert.equal(page.view, 'pm2'); + assert.equal(page.body.processes.length, 1); + assert.deepEqual(calls, [['jlist'], ['jlist']]); +}); + +test('PM2 management rejects all and leading-option names before calling the supervisor', async () => { + const { controller, calls } = supervisor([pm2Process()]); + for (const name of ['all', 'ALL', '--help', '-worker']) { + const res = response(); + await controller.postCommand({ body: { cmd: 'stop', name } }, res); + assert.equal(res.statusCode, 400, name); + assert.equal(res.body.ok, false); + assert.equal(await controller.resolveManagedProcess(name), null); + } + assert.deepEqual(calls, []); +}); + +test('worker creation rejects arbitrary script paths before invoking PM2', async () => { + const { controller, calls } = supervisor([]); + const res = response(); + await controller.postCommand({ body: { cmd: 'create', name: 'proxer-worker-2', scriptPath: '/tmp/unrelated-script.js' } }, res); + assert.equal(res.statusCode, 400); + assert.deepEqual(calls, []); +}); + +test('worker creation uses server-owned executable and cwd without returning PM2 output', async () => { + const { controller, calls } = supervisor([]); + const res = response(); + await controller.postCommand({ body: { cmd: 'create', name: 'proxer-worker-2' } }, res); + assert.equal(res.statusCode, 200); + assert.equal(res.body.ok, true); + assert.deepEqual(calls[0], ['jlist']); + const create = calls[1]; + assert.deepEqual(create.slice(0, 4), ['start', settings.workerScript, '--name', 'proxer-worker-2']); + assert.equal(create[create.indexOf('--cwd') + 1], settings.projectRoot); + assert.equal(create[create.indexOf('--interpreter') + 1], process.execPath); + assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stdout|stderr|pm2_env/); +}); + +test('worker creation cannot reuse an unrelated PM2 process name', async () => { + const unrelated = pm2Process({ name: 'existing-service', pm2_env: { pm_exec_path: '/srv/existing-service.js' } }); + const { controller, calls } = supervisor([unrelated]); + const res = response(); + await controller.postCommand({ body: { cmd: 'create', name: 'existing-service' } }, res); + assert.equal(res.statusCode, 409); + assert.deepEqual(calls, [['jlist']]); +}); + +test('worker commands target the resolved numeric PM2 ID, including zero', async () => { + for (const cmd of ['start', 'stop', 'restart', 'delete']) { + const { controller, calls } = supervisor([pm2Process()]); + const res = response(); + await controller.postCommand({ body: { cmd, name: 'proxer-worker-1' } }, res); + assert.equal(res.statusCode, 200, cmd); + assert.deepEqual(calls, [['jlist'], [cmd, '0']]); + assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stdout|stderr/); + } +}); + +test('commands cannot target unrelated, ambiguous, or invalid-ID PM2 processes', async () => { + const cases = [ + [pm2Process({ pm2_env: { pm_exec_path: '/srv/unrelated.js' } })], + [pm2Process(), pm2Process({ pm_id: 1 })], + [pm2Process({ pm_id: -1 })], + [pm2Process({ pm_id: '0' })], + ]; + for (const processes of cases) { + const { controller, calls } = supervisor(processes); + const res = response(); + await controller.postCommand({ body: { cmd: 'stop', name: 'proxer-worker-1' } }, res); + assert.equal(res.statusCode, 404); + assert.deepEqual(calls, [['jlist']]); + } +}); + +test('PM2 command failures return a useful status without raw stderr', async () => { + const { controller } = supervisor([pm2Process()], { code: 1 }); + const res = response(); + await controller.postCommand({ body: { cmd: 'restart', name: 'proxer-worker-1' } }, res); + assert.equal(res.statusCode, 502); + assert.equal(res.body.ok, false); + assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stdout|stderr/); +}); + +test('PM2 availability and malformed-list errors are sanitized', async () => { + for (const run of [ + async () => { throw new Error('NOT_A_REAL_SUPERVISOR_SECRET'); }, + async () => ({ code: 0, stdout: 'NOT_A_REAL_INVALID_JSON', stderr: '' }), + async () => ({ code: 0, stdout: '{}', stderr: '' }), + async () => ({ code: 2, stdout: '[]', stderr: 'NOT_A_REAL_STDERR_SECRET' }), + ]) { + const controller = createPm2Controller({ settings, run }); + const res = response(); + await controller.listJson({}, res); + assert.equal(res.statusCode, 503); + assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_/); + } +}); + +test('host-wide PM2 save returns409 without running a supervisor command', async () => { + const { controller, calls } = supervisor([pm2Process()]); + const res = response(); + await controller.postCommand({ body: { cmd: 'save' } }, res); + assert.equal(res.statusCode, 409); + assert.equal(res.body.ok, false); + assert.deepEqual(calls, []); +}); diff --git a/tests/server.test.js b/tests/server.test.js new file mode 100644 index 0000000..2195137 --- /dev/null +++ b/tests/server.test.js @@ -0,0 +1,436 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { EventEmitter } = require('node:events'); +const { Duplex } = require('node:stream'); +const http = require('node:http'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const express = require('express'); +const WebSocket = require('ws'); +const { config } = require('../lib/config'); +const { createApplication, createServer, attachLogConnection, handleHttpError, MAX_WS_PAYLOAD, MAX_WS_BUFFER } = require('../server'); + +class FakeSocket extends EventEmitter { + constructor() { + super(); + this.readyState = WebSocket.OPEN; + this.bufferedAmount = 0; + this.sent = []; + this.closeCalls = []; + this.terminations = 0; + this.pings = 0; + } + send(text, callback) { + assert.equal(this.readyState, WebSocket.OPEN, 'Never send after a socket is closed.'); + if (this.sendFailure) throw new Error('NOT_A_REAL_SEND_SECRET'); + this.sent.push(JSON.parse(text)); + callback?.(this.sendCallbackFailure ? new Error('NOT_A_REAL_CALLBACK_SECRET') : undefined); + } + close(code, reason) { + this.closeCalls.push({ code, reason }); + this.readyState = WebSocket.CLOSED; + this.emit('close'); + } + terminate() { + this.terminations++; + this.readyState = WebSocket.CLOSED; + this.emit('close'); + } + ping() { this.pings++; } +} + +function childProcess() { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.killCalls = 0; + child.kill = () => { child.killCalls++; return true; }; + return child; +} + +function logFixture(resolveWorker = async name => ({ name, pm_id: '0' })) { + const socket = new FakeSocket(); + const children = []; + const calls = []; + const connection = attachLogConnection(socket, { + settings: config, + resolveWorker, + spawnProcess: (...args) => { + calls.push(args); + const child = childProcess(); + children.push(child); + return child; + }, + }); + return { socket, children, calls, connection }; +} + +const settle = () => new Promise(resolve => setImmediate(resolve)); +async function message(socket, payload) { + socket.emit('message', Buffer.from(JSON.stringify(payload)), false); + await settle(); +} + +function deferred() { + let resolve; + let reject; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + return { promise, resolve, reject }; +} + +test('log subscriptions resolve a registered worker and invoke its numeric PM2 ID', async () => { + const names = []; + const fixture = logFixture(async name => { names.push(name); return { name, pm_id: '0' }; }); + await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' }); + assert.deepEqual(names, ['proxer-worker-1']); + assert.deepEqual(fixture.calls[0], ['pm2', ['logs', '0', '--raw', '--lines', '200'], { + cwd: config.projectRoot, + stdio: ['ignore', 'pipe', 'pipe'], + }]); + fixture.connection.dispose(); +}); + +test('log requests reject missing names, all, and option-like names without resolving or spawning', async () => { + let lookups = 0; + const fixture = logFixture(async () => { lookups++; return null; }); + for (const name of [undefined, null, '', 'all', 'ALL', '--help', '-worker']) { + await message(fixture.socket, { type: 'logs', name }); + } + assert.equal(lookups, 0); + assert.equal(fixture.calls.length, 0); + assert.equal(fixture.socket.sent.filter(item => item.type === 'error').length, 7); +}); + +test('unknown workers and invalid resolved IDs cannot start log processes', async () => { + for (const worker of [null, { pm_id: '-1' }, { pm_id: 'all' }, { pm_id: '9007199254740993' }]) { + const fixture = logFixture(async () => worker); + await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' }); + assert.equal(fixture.calls.length, 0); + assert.match(fixture.socket.sent.at(-1).error, /not found/); + } +}); + +test('null, arrays, primitives, malformed JSON, and binary requests are handled safely', async () => { + const fixture = logFixture(); + for (const payload of [null, [], 'logs', 1, true]) await message(fixture.socket, payload); + fixture.socket.emit('message', Buffer.from('{'), false); + fixture.socket.emit('message', Buffer.from('{}'), true); + await settle(); + assert.equal(fixture.calls.length, 0); + assert.equal(fixture.socket.sent.filter(item => item.type === 'error').length, 7); +}); + +test('oversized log requests close the connection with a bounded message', async () => { + const fixture = logFixture(); + fixture.socket.emit('message', Buffer.from('x'.repeat(MAX_WS_PAYLOAD + 1)), false); + await settle(); + assert.equal(fixture.socket.closeCalls[0].code, 1009); + assert.equal(fixture.calls.length, 0); + assert.ok(JSON.stringify(fixture.socket.sent).length < 1000); +}); + +test('log streams redact split-chunk URLs and credential lines and bound oversized lines', async () => { + const fixture = logFixture(); + await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' }); + const child = fixture.children[0]; + child.stdout.emit('data', Buffer.from('Resolved https://stream.inv')); + child.stdout.emit('data', Buffer.from('alid/video?signature=NOT_A_REAL_SIGNATURE\n')); + child.stderr.emit('data', Buffer.from('Token=NOT_A_REAL_')); + child.stderr.emit('data', Buffer.from('TOKEN\n')); + child.stdout.emit('data', Buffer.from('x'.repeat(100_000) + '\n')); + child.stdout.emit('data', Buffer.from('Completed a fixture')); + child.emit('close', 0); + const output = fixture.socket.sent.filter(item => ['stdout', 'stderr'].includes(item.type)); + assert.doesNotMatch(JSON.stringify(output), /NOT_A_REAL_|https:\/\/|stream\.invalid/); + assert.match(JSON.stringify(output), /redacted URL/); + assert.match(JSON.stringify(output), /oversized log line omitted/); + assert.match(JSON.stringify(output), /Completed a fixture/); + assert.ok(JSON.stringify(output).length < 1000); +}); + +test('stop-logs kills the subscription and suppresses later child output', async () => { + const fixture = logFixture(); + await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' }); + const child = fixture.children[0]; + await message(fixture.socket, { type: 'stop-logs' }); + const count = fixture.socket.sent.length; + child.stdout.emit('data', Buffer.from('stale output\n')); + child.emit('close', 0); + assert.equal(child.killCalls, 1); + assert.equal(fixture.socket.sent.length, count); +}); + +test('disconnect and socket errors clean up children without sending on a closed connection', async () => { + for (const event of ['close', 'error']) { + const fixture = logFixture(); + await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' }); + fixture.socket.readyState = WebSocket.CLOSED; + fixture.socket.emit(event, new Error('NOT_A_REAL_SOCKET_SECRET')); + const count = fixture.socket.sent.length; + fixture.children[0].stderr.emit('data', Buffer.from('late output\n')); + fixture.children[0].emit('error', new Error('NOT_A_REAL_LATE_SECRET')); + assert.equal(fixture.children[0].killCalls, 1); + assert.equal(fixture.socket.sent.length, count); + } +}); + +test('stop and disconnect invalidate a pending worker lookup before it can spawn', async () => { + for (const action of ['stop', 'disconnect']) { + const pending = deferred(); + const fixture = logFixture(() => pending.promise); + await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' }); + if (action === 'stop') await message(fixture.socket, { type: 'stop-logs' }); + else fixture.socket.close(1000, 'fixture finished'); + pending.resolve({ pm_id: '0' }); + await settle(); + assert.equal(fixture.calls.length, 0, action); + } +}); + +test('a newer selection wins when an older worker lookup resolves later', async () => { + const old = deferred(); + const fixture = logFixture(name => name === 'worker-old' ? old.promise : Promise.resolve({ pm_id: '2' })); + await message(fixture.socket, { type: 'logs', name: 'worker-old' }); + await message(fixture.socket, { type: 'logs', name: 'worker-new' }); + old.resolve({ pm_id: '1' }); + await settle(); + assert.equal(fixture.calls.length, 1); + assert.equal(fixture.calls[0][1][1], '2'); + fixture.connection.dispose(); +}); + +test('late close events from an old log process cannot clear a new subscription', async () => { + const fixture = logFixture(async name => ({ pm_id: name === 'worker-old' ? '1' : '2' })); + await message(fixture.socket, { type: 'logs', name: 'worker-old' }); + await message(fixture.socket, { type: 'logs', name: 'worker-new' }); + const old = fixture.children[0]; + const current = fixture.children[1]; + assert.equal(old.killCalls, 1); + old.emit('close', 0); + current.stdout.emit('data', Buffer.from('new subscription is active\n')); + assert.match(fixture.socket.sent.at(-1).data, /new subscription is active/); + assert.equal(fixture.socket.sent.some(item => item.type === 'close'), false); + fixture.connection.dispose(); + assert.equal(current.killCalls, 1); +}); + +test('lookup and spawn errors return generic messages without raw details', async () => { + const fixture = logFixture(async () => { throw new Error('NOT_A_REAL_LOOKUP_SECRET'); }); + await message(fixture.socket, { type: 'logs', name: 'worker-one' }); + assert.doesNotMatch(JSON.stringify(fixture.socket.sent), /NOT_A_REAL_/); + const socket = new FakeSocket(); + attachLogConnection(socket, { + resolveWorker: async () => ({ pm_id: '0' }), + spawnProcess: () => { throw new Error('NOT_A_REAL_SPAWN_SECRET'); }, + }); + await message(socket, { type: 'logs', name: 'worker-one' }); + assert.equal(socket.sent.at(-1).type, 'error'); + assert.doesNotMatch(JSON.stringify(socket.sent), /NOT_A_REAL_/); +}); + +test('asynchronous child and pipe errors are handled and cleaned up', async () => { + for (const source of ['child', 'stdout', 'stderr']) { + const fixture = logFixture(); + await message(fixture.socket, { type: 'logs', name: 'worker-one' }); + const child = fixture.children[0]; + (source === 'child' ? child : child[source]).emit('error', new Error('NOT_A_REAL_PIPE_SECRET')); + assert.equal(child.killCalls, 1); + assert.equal(fixture.socket.sent.at(-1).type, 'error'); + assert.doesNotMatch(JSON.stringify(fixture.socket.sent), /NOT_A_REAL_/); + } +}); + +test('a slow WebSocket consumer is disconnected and its log child is stopped', async () => { + const fixture = logFixture(); + await message(fixture.socket, { type: 'logs', name: 'worker-one' }); + fixture.socket.bufferedAmount = MAX_WS_BUFFER; + fixture.children[0].stdout.emit('data', Buffer.from('next bounded line\n')); + assert.equal(fixture.socket.closeCalls.at(-1).code, 1013); + assert.equal(fixture.children[0].killCalls, 1); +}); + +test('WebSocket send failures clean up the active subscription', async () => { + for (const property of ['sendFailure', 'sendCallbackFailure']) { + const fixture = logFixture(); + await message(fixture.socket, { type: 'logs', name: 'worker-one' }); + fixture.socket[property] = true; + fixture.children[0].stdout.emit('data', Buffer.from('next line\n')); + assert.equal(fixture.children[0].killCalls, 1); + assert.equal(fixture.socket.closeCalls.at(-1).code, 1011); + } +}); + +test('HTTP error rendering and JSON responses exclude raw errors and stacks', () => { + function response() { + return { + status(code) { this.statusCode = code; return this; }, + json(body) { this.body = body; return this; }, + render(view, body) { this.view = view; this.body = body; return this; }, + }; + } + for (const api of [false, true]) { + const res = response(); + handleHttpError(new Error('NOT_A_REAL_DATABASE_SECRET'), { path: api ? '/pm2/list-json' : '/', is: () => false }, res, () => assert.fail('Unexpected next().')); + assert.equal(res.statusCode, 500); + assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stack|Error:/); + if (!api) assert.equal(res.view, 'error'); + } + let forwarded; + handleHttpError(new Error('NOT_A_REAL_SECRET'), {}, { headersSent: true }, error => { forwarded = error; }); + assert.doesNotMatch(forwarded.message, /NOT_A_REAL_/); +}); + +// Exercise Express body parsing using real HTTP message objects and no listening socket. +function offlineRequest(app, body, contentType = 'application/json') { + return new Promise((resolve, reject) => { + const socket = new Duplex({ read() {}, write(chunk, encoding, callback) { callback(); } }); + const request = new http.IncomingMessage(socket); + const bytes = Buffer.from(body); + request.method = 'POST'; + request.url = '/pm2/fixture'; + request.headers = { 'content-type': contentType, 'content-length': String(bytes.length) }; + const response = new http.ServerResponse(request); + const timeout = setTimeout(() => reject(new Error('Offline HTTP fixture did not complete.')), 2000); + response.end = data => { + clearTimeout(timeout); + resolve({ status: response.statusCode, text: String(data ?? '') }); + socket.destroy(); + return response; + }; + app.handle(request, response, error => { + clearTimeout(timeout); + socket.destroy(); + reject(error || new Error('Offline HTTP fixture was not handled.')); + }); + request.push(bytes); + request.push(null); + }); +} + +test('application factory has safe shared locals and enforces32KiB JSON/form limits without listening', async () => { + const router = express.Router(); + router.post('/pm2/fixture', (req, res) => res.json({ received: req.body })); + const app = createApplication({ router }); + assert.deepEqual(app.locals.global, { captcha_blocked: false }); + const valid = await offlineRequest(app, JSON.stringify({ title: 'Fixture' })); + assert.equal(valid.status, 200); + assert.deepEqual(JSON.parse(valid.text), { received: { title: 'Fixture' } }); + const invalid = await offlineRequest(app, '{NOT_A_REAL_PARSE_SECRET'); + assert.equal(invalid.status, 400); + assert.doesNotMatch(invalid.text, /NOT_A_REAL_/); + const largeJson = await offlineRequest(app, JSON.stringify({ text: 'x'.repeat(33 * 1024) })); + assert.equal(largeJson.status, 413); + const largeForm = await offlineRequest(app, 'text=' + 'x'.repeat(33 * 1024), 'application/x-www-form-urlencoded'); + assert.equal(largeForm.status, 413); +}); + +test('server construction does not listen and heartbeat/server close clean up log children and timer', async () => { + const server = new EventEmitter(); + server.listening = false; + server.listen = () => assert.fail('createServer must not listen automatically.'); + class FakeWebSocketServer extends EventEmitter { + constructor(options) { super(); this.options = options; this.clients = new Set(); this.closed = false; } + close() { if (!this.closed) { this.closed = true; this.emit('close'); } } + } + let tick; + let cleared = 0; + const interval = { unref() {} }; + const child = childProcess(); + const runtime = createServer({ + router: express.Router(), + createHttpServer: () => server, + WebSocketServer: FakeWebSocketServer, + scheduleInterval: (callback, period) => { tick = callback; assert.equal(period, 30_000); return interval; }, + cancelInterval: actual => { assert.equal(actual, interval); cleared++; }, + resolveWorker: async () => ({ pm_id: '0' }), + spawnProcess: () => child, + }); + assert.equal(runtime.wss.options.maxPayload, 16 * 1024); + const socket = new FakeSocket(); + runtime.wss.clients.add(socket); + runtime.wss.emit('connection', socket); + await message(socket, { type: 'logs', name: 'worker-one' }); + tick(); + assert.equal(socket.pings, 1); + socket.emit('pong'); + tick(); + assert.equal(socket.pings, 2); + tick(); + assert.equal(socket.terminations, 1); + assert.equal(child.killCalls, 1); + server.emit('close'); + assert.equal(cleared, 1); + assert.equal(runtime.wss.closed, true); + await runtime.close(); + assert.equal(cleared, 1); +}); + +test('PM2 browser controls use safe DOM text, visible feedback, ready-state checks, and stop on deselect', async () => { + class Element { + constructor(tag = 'div') { + this.tagName = tag; + this.className = ''; + this.children = []; + this.dataset = {}; + this.style = {}; + this.textContent = ''; + this.listeners = {}; + this.scrollTop = this.scrollHeight = this.clientHeight = 0; + this.classList = { + add: (...names) => { this.className = [...new Set([...this.className.split(' '), ...names])].join(' '); }, + remove: (...names) => { this.className = this.className.split(' ').filter(name => !names.includes(name)).join(' '); }, + }; + } + set innerHTML(value) { assert.fail('Untrusted refreshed process fields must not use innerHTML.'); } + addEventListener(name, callback) { (this.listeners[name] ||= []).push(callback); } + append(...values) { this.children.push(...values); } + appendChild(value) { this.children.push(value); return value; } + replaceChildren(...values) { this.children = values; } + async click() { for (const callback of this.listeners.click || []) await callback({ preventDefault() {}, currentTarget: this }); } + } + const elements = new Map(); + const get = id => { if (!elements.has(id)) elements.set(id, new Element()); return elements.get(id); }; + const document = { + getElementById: get, + createElement: tag => new Element(tag), + querySelectorAll: () => get('process-list').children.filter(node => node.className?.split(' ').includes('pm2-row')), + }; + let socket; + class BrowserSocket { + static OPEN = 1; + constructor() { socket = this; this.readyState = 0; this.sent = []; this.listeners = {}; } + addEventListener(name, callback) { this.listeners[name] = callback; } + send(text) { assert.equal(this.readyState, 1); this.sent.push(JSON.parse(text)); } + } + const maliciousName = ''; + const process = { name: maliciousName, pm_id: '0', pid: '12', status: '', execPath: 'fixture', uptime: '1m' }; + const context = vm.createContext({ + document, + WebSocket: BrowserSocket, + window: { addEventListener() {} }, + location: { protocol: 'http:', host: 'fixture.invalid' }, + fetch: async () => ({ ok: true, json: async () => ({ ok: true, processes: [process] }) }), + }); + const template = fs.readFileSync(path.join(config.projectRoot, 'views/pm2.ejs'), 'utf8'); + assert.equal(template.includes('id="btn-save"'), false); + assert.equal(template.includes('/home/pm2/'), false); + assert.ok(template.indexOf('id="control-output"') < template.indexOf('id="control-centre"')); + const script = template.match(/", undefined]) { + const database = { collection(name) { + if (name === "settings") return { findOne: async (_filter, { projection }) => { + assert.deepEqual(projection, { captcha_blocked: 1, pause_reason: 1 }); + return { captcha_blocked: true, pause_reason: reason, token: "private-settings-token" }; + } }; + return { find() { return { sort() { return this; }, async toArray() { return []; } }; } }; + } }; + const controller = createQueueController({ config, getDb: async () => database }); + for (const method of ["statusData", "status"]) { + const result = response(); + await controller[method]({}, result, error => { throw error; }); + assert.deepEqual(result.data.global, { + captcha_blocked: true, + pause_reason: ["resolution", "authentication"].includes(reason) ? reason : null, + }); + assert.doesNotMatch(JSON.stringify(result.data), /private reason|private-settings-token/); + } + } + const job = toPublicJob({ _id: "fixture", filename: "Episode", error_category: "resolution", token: "hidden" }); + assert.equal(job.error_category, "resolution"); + assert.equal(Object.hasOwn(job, "token"), false); +}); + +test("resume clears both the existing global pause flag and its reason before redirecting", async () => { + const operations = []; + const controller = createQueueController({ getDb: async () => ({ collection(name) { + assert.equal(name, "settings"); + return { updateOne: async (...args) => { operations.push(args); } }; + } }) }); + const result = response(); + await controller.clearCaptcha({}, result, error => { throw error; }); + assert.deepEqual(operations, [[ + { _id: "global" }, { $set: { captcha_blocked: false }, $unset: { pause_reason: "" } }, + ]]); + assert.equal(result.location, "/status"); +}); + +test("verification banner distinguishes resolution failures without claiming a confirmed CAPTCHA", async () => { + const header = path.join(repository, "views/partials/header.ejs"); + const rendered = await ejs.renderFile(header, { global: { captcha_blocked: true, pause_reason: "resolution" } }); + const message = rendered.match(/([\s\S]*?)<\/span>/)[1]; + assert.match(message, /video link could not be resolved/); + assert.match(message, /Possible causes include CAPTCHA or login verification, an unavailable video, or a source change/); + assert.match(rendered, /Resume after verification/); + assert.doesNotMatch(message, /CAPTCHA triggered|CAPTCHA confirmed/); + + const script = [...rendered.matchAll(/ <%- include('partials/footer') %> diff --git a/views/status.ejs b/views/status.ejs index 3c63cad..057c4d9 100755 --- a/views/status.ejs +++ b/views/status.ejs @@ -101,9 +101,6 @@

Processing

-
- -
    @@ -116,7 +113,7 @@ <%= job.filename %>
    <%= job.url %>
    - Started: <%= new Date(job.created_at).toLocaleString() %>
    + <%= job.started_at ? 'Started' : 'Queued' %>: <%= new Date(job.started_at || job.created_at).toLocaleString() %>
    <% if (job.fileSize) { %> Downloaded: <%= job.fileSize %> @@ -125,7 +122,7 @@ <% if (job.output_log) { %>
    Live Log -
    <%- job.output_log %>
    +
    <%= job.output_log %>
    <% } %> @@ -166,7 +163,7 @@ <% if (job.output_log) { %>
    Show Log -
    <%- job.output_log %>
    +
    <%= job.output_log %>
    <% } %> @@ -204,7 +201,7 @@ <% if (job.output_log) { %>
    Show Error Log -
    <%- job.output_log %>
    +
    <%= job.output_log %>
    <% } %> @@ -244,20 +241,20 @@ async function refreshStatus() { /* Renderer helpers */ const q = job => `
  • - ${job.filename}
    - ${job.url}
    + ${escapeHtml(job.filename)}
    + ${escapeHtml(job.url)}
    ${new Date(job.created_at).toLocaleString()}
  • `; const p = job => `
  • - ${job.filename} + ${escapeHtml(job.filename)}
    - ${job.url}
    - Started: ${new Date(job.created_at).toLocaleString()}
    + ${escapeHtml(job.url)}
    + ${job.started_at ? 'Started' : 'Queued'}: ${new Date(job.started_at || job.created_at).toLocaleString()}
    Downloaded: ${formatBytes(job.fileSize || 0)} ${job.output_log ? ` -
    +
    Live Log
    ${escapeHtml(job.output_log)}
    ` : ""} @@ -265,11 +262,11 @@ async function refreshStatus() { const d = job => `
  • - ${job.filename}
    + ${escapeHtml(job.filename)}
    ${new Date(job.finished_at).toLocaleString()}
    Size: ${formatBytes(job.fileSize || 0)} ${job.output_log ? ` -
    +
    Show Log
    ${escapeHtml(job.output_log)}
    ` : ""} @@ -277,10 +274,10 @@ async function refreshStatus() { const f = job => `
  • - ${job.filename}
    + ${escapeHtml(job.filename)}
    ${new Date(job.failed_at).toLocaleString()}
    ${job.output_log ? ` -
    +
    Show Error Log
    ${escapeHtml(job.output_log)}
    ` : ""} @@ -305,7 +302,7 @@ async function refreshStatus() { } function escapeHtml(text) { - return text.replace(/[&<>"']/g, c => + return String(text ?? "").replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]) ); }