phase 2 rework
This commit is contained in:
1 parent
20054198f3
commit
b397ea9256
44 files changed
+5528
-1377
No files matched your search
@@ -0,0 +1,322 @@
|
||||
"use strict";
|
||||
|
||||
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 { createWorkerIdentity, toPublicWorkerIdentity } = require("../lib/workerIdentity");
|
||||
const {
|
||||
readActivity, createInventoryReader, readActiveFileSize,
|
||||
ACTIVE_JOB_LIMIT, WORKER_LIMIT, ACTIVITY_READ_PROJECTION,
|
||||
} = require("../lib/activity");
|
||||
const { createDashboardController, RECENT_LIMIT } = require("../controllers/dashboardController");
|
||||
const { STATUS_READ_PROJECTION } = require("../lib/jobValidation");
|
||||
const { QUERY_TIMEOUT_MS } = require("../lib/statusQuery");
|
||||
|
||||
const HOST = "download-host";
|
||||
const START = "2026-01-01T12:00:00.000Z";
|
||||
const CLAIM = "2026-01-01T12:01:00.000Z";
|
||||
const RUN_ID = "7b3c9e3a-8b0b-41c6-988c-8e9e01dbbf4a";
|
||||
const identity = (changes = {}) => ({
|
||||
name: "proxer-worker-1", pid: 1234, host: HOST, run_id: RUN_ID, started_at: START, ...changes,
|
||||
});
|
||||
const processRecord = (changes = {}) => ({
|
||||
name: "proxer-worker-1", pid: 1234, pm_id: "1", status: "online", startedAtISO: START, ...changes,
|
||||
});
|
||||
const activeRecord = (changes = {}) => ({
|
||||
_id: "job-1", filename: "ExampleS001E001_engsub", processing: true, created_at: START,
|
||||
started_at: CLAIM, url: "https://proxer.me/watch/42/1/engsub", worker: identity(), ...changes,
|
||||
});
|
||||
|
||||
function activityDatabase(records = [], failure) {
|
||||
const reads = [];
|
||||
const db = { collection(name) {
|
||||
assert.equal(name, "queue");
|
||||
return { find(filter, options) {
|
||||
const read = { filter, options };
|
||||
reads.push(read);
|
||||
const cursor = {
|
||||
sort(value) { read.sort = value; return cursor; },
|
||||
limit(value) { read.limit = value; return cursor; },
|
||||
async toArray() { if (failure) throw failure; return records.slice(0, read.limit); },
|
||||
};
|
||||
return cursor;
|
||||
} };
|
||||
} };
|
||||
return { db, reads };
|
||||
}
|
||||
|
||||
async function activityFixture(records, processes = [processRecord()], options = {}) {
|
||||
const fixture = activityDatabase(records);
|
||||
const fileChecks = [];
|
||||
const result = await readActivity(fixture.db, {
|
||||
host: HOST, listWorkers: async () => processes,
|
||||
readFileSize: async job => { fileChecks.push(job._id); return 123; }, ...options,
|
||||
});
|
||||
return { ...fixture, result, fileChecks };
|
||||
}
|
||||
|
||||
test("worker identity is immutable, names are safe, and each actual process run has a unique ID", () => {
|
||||
const explicit = createWorkerIdentity({
|
||||
env: { PROXER_WORKER_NAME: "proxer-worker-9", name: "proxer-worker-1" },
|
||||
pid: 1234, host: HOST, uuid: () => RUN_ID, now: () => new Date(START),
|
||||
});
|
||||
assert.equal(Object.isFrozen(explicit), true);
|
||||
assert.throws(() => { explicit.pid = 5; }, TypeError);
|
||||
assert.deepEqual(explicit, identity({ name: "proxer-worker-9" }));
|
||||
const unsafe = createWorkerIdentity({
|
||||
env: { PROXER_WORKER_NAME: "<script>private</script>", name: "bad name" },
|
||||
pid: 1234, host: HOST, uuid: () => RUN_ID, now: () => new Date(START),
|
||||
});
|
||||
assert.equal(unsafe.name, "worker-1234");
|
||||
const actual = createWorkerIdentity({ env: {} });
|
||||
assert.equal(actual.pid, process.pid);
|
||||
assert.equal(actual.host, os.hostname());
|
||||
assert.equal(actual.name, `worker-${process.pid}`);
|
||||
assert.notEqual(actual.run_id, createWorkerIdentity({ env: {} }).run_id);
|
||||
});
|
||||
|
||||
test("worker identity DTO drops extra fields and rejects incomplete or unsafe legacy metadata", () => {
|
||||
assert.deepEqual(toPublicWorkerIdentity({ ...identity(), token: "secret", env: { PRIVATE: "value" } }), identity());
|
||||
for (const value of [
|
||||
null, [], {}, { name: "proxer-worker-1", pid: 1234 },
|
||||
identity({ pid: "1234" }), identity({ pid: 0 }), identity({ pid: NaN }),
|
||||
identity({ name: "<script>" }), identity({ host: "https://host/secret" }),
|
||||
identity({ run_id: "not-a-run-id" }), identity({ started_at: "2026-02-31T12:00:00.000Z" }),
|
||||
]) assert.equal(toPublicWorkerIdentity(value), null);
|
||||
});
|
||||
|
||||
test("activity connects a verified local claim to its managed worker and includes idle and stopped workers", async () => {
|
||||
const { result } = await activityFixture([activeRecord()], [
|
||||
processRecord({ name: "renamed-worker" }),
|
||||
processRecord({ pm_id: "2", pid: 2345, name: "proxer-worker-2" }),
|
||||
processRecord({ pm_id: "3", pid: 0, name: "proxer-worker-3", status: "stopped" }),
|
||||
]);
|
||||
assert.equal(result.available, true);
|
||||
assert.equal(result.workers.length, 3);
|
||||
assert.equal(result.workers[0].name, "renamed-worker");
|
||||
assert.equal(result.workers[0].jobs[0]._id, "job-1");
|
||||
assert.deepEqual(result.workers[0].jobs[0].worker, identity());
|
||||
assert.equal(result.workers[0].jobs[0].fileSize, 123);
|
||||
assert.deepEqual(result.workers[1].jobs, []);
|
||||
assert.equal(result.workers[1].activityUnknown, false);
|
||||
assert.equal(result.workers[2].status, "stopped");
|
||||
assert.equal(result.workers[2].pid, null);
|
||||
assert.deepEqual(result.unassigned, []);
|
||||
});
|
||||
|
||||
test("pre-update active jobs stay unassigned and do not falsely imply that known workers are idle", async () => {
|
||||
const { result } = await activityFixture([
|
||||
activeRecord({ worker: undefined }), activeRecord({ _id: "job-2", worker: { name: "proxer-worker-1", pid: 1234 } }),
|
||||
]);
|
||||
assert.deepEqual(result.workers[0].jobs, []);
|
||||
assert.equal(result.workers[0].activityUnknown, true);
|
||||
assert.equal(result.unassigned.length, 2);
|
||||
for (const job of result.unassigned) {
|
||||
assert.equal(job.worker, null);
|
||||
assert.equal(job.assignmentReason, "unknown-worker");
|
||||
}
|
||||
});
|
||||
|
||||
test("PID reuse, other hosts, missing launch time, and ambiguous inventory never attach a claim to a current worker", async () => {
|
||||
const cases = [
|
||||
["stale-worker", activeRecord(), [processRecord({ startedAtISO: "2026-01-01T12:02:00.000Z" })]],
|
||||
["remote-worker", activeRecord({ worker: identity({ host: "other-host" }) }), [processRecord()]],
|
||||
["unverified-worker", activeRecord(), [processRecord({ startedAtISO: null })]],
|
||||
["unverified-worker", activeRecord({ started_at: "2026-01-01T11:59:00.000Z" }), [processRecord()]],
|
||||
["ambiguous-worker", activeRecord(), [processRecord(), processRecord({ pm_id: "2", name: "another-worker" })]],
|
||||
["worker-not-running", activeRecord(), [processRecord({ pid: 4321 })]],
|
||||
["worker-not-running", activeRecord(), [processRecord({ status: "stopped" })]],
|
||||
];
|
||||
for (const [reason, job, processes] of cases) {
|
||||
const { result } = await activityFixture([job], processes);
|
||||
assert.ok(result.workers.every(worker => worker.jobs.length === 0), reason);
|
||||
assert.equal(result.unassigned[0].assignmentReason, reason);
|
||||
}
|
||||
});
|
||||
|
||||
test("unavailable PM2 preserves active jobs and their saved identity while a database read failure propagates", async () => {
|
||||
const unavailable = async () => { throw new Error("private supervisor failure"); };
|
||||
const { result } = await activityFixture([activeRecord()], [], { listWorkers: unavailable });
|
||||
assert.equal(result.available, false);
|
||||
assert.deepEqual(result.workers, []);
|
||||
assert.equal(result.unassigned[0].assignmentReason, "supervisor-unavailable");
|
||||
assert.deepEqual(result.unassigned[0].worker, identity());
|
||||
assert.doesNotMatch(JSON.stringify(result), /private supervisor failure/);
|
||||
const failure = new Error("database unavailable");
|
||||
const broken = activityDatabase([], failure);
|
||||
await assert.rejects(readActivity(broken.db, { listWorkers: unavailable }), error => error === failure);
|
||||
});
|
||||
|
||||
test("active reads and filesystem checks are bounded and truncation cannot mark unobserved workers idle", async () => {
|
||||
const records = Array.from({ length: ACTIVE_JOB_LIMIT + 10 }, (_, index) => activeRecord({ _id: `job-${index}` }));
|
||||
const { result, reads, fileChecks } = await activityFixture(records);
|
||||
assert.deepEqual(reads, [{
|
||||
filter: { processing: true }, options: { projection: ACTIVITY_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS },
|
||||
sort: { created_at: 1, _id: 1 }, limit: ACTIVE_JOB_LIMIT + 1,
|
||||
}]);
|
||||
assert.equal(result.truncated, true);
|
||||
assert.equal(result.workers[0].activityUnknown, true);
|
||||
assert.equal(result.workers[0].jobs.length, ACTIVE_JOB_LIMIT);
|
||||
assert.equal(fileChecks.length, ACTIVE_JOB_LIMIT);
|
||||
});
|
||||
|
||||
test("worker inventory is bounded while duplicates outside the visible page remain ambiguous", async () => {
|
||||
const processes = Array.from({ length: WORKER_LIMIT + 1 }, (_, index) => processRecord({
|
||||
pm_id: String(index + 1), name: `proxer-worker-${index + 1}`, pid: 1234 + index,
|
||||
}));
|
||||
processes.push(processRecord({ pm_id: "99", name: "duplicate-beyond-page", pid: 1234 }));
|
||||
const { result } = await activityFixture([activeRecord()], processes);
|
||||
assert.equal(result.workers.length, WORKER_LIMIT);
|
||||
assert.equal(result.workersTruncated, true);
|
||||
assert.equal(result.unassigned[0].assignmentReason, "ambiguous-worker");
|
||||
assert.ok(result.workers.every(worker => worker.activityUnknown));
|
||||
});
|
||||
|
||||
test("activity DTOs remove credentials, signed URLs, raw supervisor metadata, and unknown worker fields", async () => {
|
||||
const { result } = await activityFixture([activeRecord({
|
||||
token: "session=private-cookie-value",
|
||||
url: "https://media.example/file.mp4?signature=private-signature",
|
||||
output_log: "credential private-cookie-value https://media.example/file.mp4?signature=private-signature",
|
||||
worker: { ...identity(), env: { PRIVATE: "private-env" }, token: "private-worker-token" },
|
||||
})], [processRecord({ execPath: "/private-host-path", pm2_env: { SECRET: "private-pm2-env" } })]);
|
||||
const publicText = JSON.stringify(result);
|
||||
assert.doesNotMatch(publicText, /private-cookie-value|private-signature|private-env|private-worker-token|private-host-path|private-pm2-env/);
|
||||
assert.equal(result.workers[0].jobs[0].url, "Source URL unavailable");
|
||||
assert.equal(result.workers[0].jobs[0].token, undefined);
|
||||
});
|
||||
|
||||
test("inventory caching shares concurrent PM2 reads and expires after ten seconds", async () => {
|
||||
let clock = 0;
|
||||
let calls = 0;
|
||||
let finish;
|
||||
const gate = new Promise(resolve => { finish = resolve; });
|
||||
const readInventory = createInventoryReader(async () => { calls += 1; await gate; return [processRecord()]; }, { now: () => clock });
|
||||
const first = readInventory();
|
||||
const second = readInventory();
|
||||
assert.equal(calls, 1);
|
||||
finish();
|
||||
assert.equal((await first).available, true);
|
||||
assert.equal((await second).available, true);
|
||||
await readInventory();
|
||||
assert.equal(calls, 1);
|
||||
clock = 10000;
|
||||
await readInventory();
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test("a supervisor failure is briefly cached but can recover at the next inventory refresh", async () => {
|
||||
let clock = 0;
|
||||
let fail = true;
|
||||
let calls = 0;
|
||||
const readInventory = createInventoryReader(async () => {
|
||||
calls += 1;
|
||||
if (fail) throw new Error("unavailable");
|
||||
return [processRecord()];
|
||||
}, { now: () => clock });
|
||||
assert.equal((await readInventory()).available, false);
|
||||
fail = false;
|
||||
assert.equal((await readInventory()).available, false);
|
||||
assert.equal(calls, 1);
|
||||
clock = 10000;
|
||||
assert.equal((await readInventory()).available, true);
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test("active filesize lookup never follows links or unsafe filenames", async t => {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-activity-"));
|
||||
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
|
||||
await fs.writeFile(path.join(outputDir, "regular.mp4"), "fixture");
|
||||
await fs.symlink(path.join(outputDir, "regular.mp4"), path.join(outputDir, "link.mp4"));
|
||||
assert.equal(await readActiveFileSize({ filename: "regular" }, { outputDir }), 7);
|
||||
for (const filename of ["link", "missing", "../regular"]) {
|
||||
assert.equal(await readActiveFileSize({ filename }, { outputDir }), null);
|
||||
}
|
||||
});
|
||||
|
||||
function dashboardDatabase({ failure } = {}) {
|
||||
const reads = [];
|
||||
const db = { collection(name) {
|
||||
return {
|
||||
async countDocuments(filter, options) {
|
||||
reads.push({ type: "count", name, filter, options });
|
||||
if (failure) throw failure;
|
||||
return name === "queue" ? (filter.processing === true ? 2 : 3) : 8;
|
||||
},
|
||||
async findOne(filter, options) {
|
||||
reads.push({ type: "global", name, filter, options });
|
||||
return { captcha_blocked: true, pause_reason: "resolution", private: "private-global" };
|
||||
},
|
||||
find(filter, options) {
|
||||
const read = { type: "recent", name, filter, options };
|
||||
reads.push(read);
|
||||
const cursor = {
|
||||
sort(value) { read.sort = value; return cursor; },
|
||||
limit(value) { read.limit = value; return cursor; },
|
||||
async toArray() {
|
||||
return Array.from({ length: 8 }, (_, index) => ({
|
||||
_id: `${name}-${index}`, filename: `Episode ${index}`, token: "cookie=private-history-cookie",
|
||||
output_log: "legacy private-history-cookie", [name === "done" ? "finished_at" : "failed_at"]: CLAIM,
|
||||
})).slice(0, read.limit);
|
||||
},
|
||||
};
|
||||
return cursor;
|
||||
},
|
||||
};
|
||||
} };
|
||||
return { db, reads };
|
||||
}
|
||||
|
||||
test("dashboard returns bounded recent history, counts, pause state, and activity without exposing raw records", async () => {
|
||||
const fixture = dashboardDatabase();
|
||||
const activity = { workers: [], unassigned: [], truncated: false, workersTruncated: false, available: true };
|
||||
const settings = { outputDir: "/fixture/output" };
|
||||
const controller = createDashboardController({
|
||||
getDb: async () => fixture.db, config: settings,
|
||||
readActivity: async (db, options) => { assert.equal(db, fixture.db); assert.equal(options.settings, settings); return activity; },
|
||||
});
|
||||
const result = await controller.readDashboard();
|
||||
assert.deepEqual(result.counts, { queued: 3, processing: 2, done: 8, failed: 8 });
|
||||
assert.deepEqual(result.global, { captcha_blocked: true, pause_reason: "resolution" });
|
||||
assert.equal(result.activity, activity);
|
||||
for (const state of ["done", "failed"]) {
|
||||
assert.equal(result.recent[state].length, RECENT_LIMIT);
|
||||
assert.equal(result.recent[state][0].fileSize, undefined);
|
||||
}
|
||||
assert.doesNotMatch(JSON.stringify(result), /private-history-cookie|private-global/);
|
||||
const recentReads = fixture.reads.filter(read => read.type === "recent");
|
||||
assert.equal(recentReads.length, 2);
|
||||
for (const read of recentReads) {
|
||||
assert.deepEqual(read.options, { projection: STATUS_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS });
|
||||
assert.equal(read.limit, RECENT_LIMIT);
|
||||
assert.deepEqual(read.sort, { [read.name === "done" ? "finished_at" : "failed_at"]: -1, _id: -1 });
|
||||
}
|
||||
const countReads = fixture.reads.filter(read => read.type === "count");
|
||||
assert.equal(countReads.length, 4);
|
||||
assert.ok(countReads.every(read => read.options.maxTimeMS === QUERY_TIMEOUT_MS));
|
||||
});
|
||||
|
||||
test("dashboard page and JSON disable caching, and database errors reach the generic error handler", async () => {
|
||||
const fixture = dashboardDatabase();
|
||||
const controller = createDashboardController({ getDb: async () => fixture.db, readActivity: async () => ({ workers: [] }) });
|
||||
for (const [method, render] of [["dashboard", true], ["dashboardData", false]]) {
|
||||
const headers = {};
|
||||
let payload, template;
|
||||
const response = {
|
||||
set(name, value) { headers[name] = value; return response; },
|
||||
render(name, value) { template = name; payload = value; return response; },
|
||||
json(value) { payload = value; return response; },
|
||||
};
|
||||
await controller[method]({}, response, error => { throw error; });
|
||||
assert.equal(headers["Cache-Control"], "no-store");
|
||||
if (render) { assert.equal(template, "dashboard"); assert.equal(payload.activePage, "dashboard"); }
|
||||
else assert.equal(payload.counts.processing, 2);
|
||||
}
|
||||
const failure = new Error("private database detail");
|
||||
const broken = dashboardDatabase({ failure });
|
||||
const unavailable = createDashboardController({ getDb: async () => broken.db, readActivity: async () => ({ workers: [] }) });
|
||||
let received;
|
||||
await unavailable.dashboardData({}, { set() {}, json() { assert.fail("Must not report an empty dashboard on failure"); } }, error => { received = error; });
|
||||
assert.equal(received, failure);
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createConfig } = require('../lib/config');
|
||||
const { createPm2Controller, normalizeProcess } = require('../controllers/pm2Controller');
|
||||
|
||||
const settings = createConfig({ MONGO_URI: 'mongodb://fixture.invalid/unused' });
|
||||
const SEQUENCE_ID = 'worker-name-sequence';
|
||||
|
||||
function response() {
|
||||
return { statusCode: 200,
|
||||
status(code) { this.statusCode = code; return this; },
|
||||
json(body) { this.body = body; return this; },
|
||||
};
|
||||
}
|
||||
|
||||
function processRecord(name, managed = true, id = 0) {
|
||||
return { name, pid: 1000 + id, pm_id: id, pm2_env: {
|
||||
name, status: 'online', pm_exec_path: managed ? settings.workerScript : '/unrelated/server.js',
|
||||
pm_uptime: Date.UTC(2026, 9, 23, 10), TOKEN: 'PRIVATE_PM2_ENV',
|
||||
} };
|
||||
}
|
||||
|
||||
function database(initial) {
|
||||
const state = { value: initial, calls: [], initializationRace: false, acknowledged: true };
|
||||
const collection = {
|
||||
async updateOne(filter, update, options) {
|
||||
state.calls.push({ method: 'updateOne', filter, update, options });
|
||||
assert.deepEqual(filter, { _id: SEQUENCE_ID });
|
||||
assert.equal(options.maxTimeMS, 5000);
|
||||
assert.deepEqual(Object.keys(update), ['$max']);
|
||||
if (state.value === undefined || state.value < update.$max.value) state.value = update.$max.value;
|
||||
if (state.initializationRace && options.upsert) {
|
||||
state.initializationRace = false;
|
||||
const error = new Error('PRIVATE_MONGO_ERROR');
|
||||
error.code = 11000;
|
||||
throw error;
|
||||
}
|
||||
return { acknowledged: state.acknowledged };
|
||||
},
|
||||
async findOneAndUpdate(filter, update, options) {
|
||||
state.calls.push({ method: 'findOneAndUpdate', filter, update, options });
|
||||
assert.deepEqual(filter, { _id: SEQUENCE_ID, value: { $gte: 0, $lt: Number.MAX_SAFE_INTEGER } });
|
||||
assert.deepEqual(update, { $inc: { value: 1 } });
|
||||
assert.equal(options.returnDocument, 'after');
|
||||
assert.equal(options.includeResultMetadata, false);
|
||||
assert.equal(options.maxTimeMS, 5000);
|
||||
assert.deepEqual(options.projection, { value: 1 });
|
||||
if (typeof state.value !== 'number' || state.value < 0 || state.value >= Number.MAX_SAFE_INTEGER) return null;
|
||||
return { _id: SEQUENCE_ID, value: ++state.value };
|
||||
},
|
||||
};
|
||||
const db = { collection(name) { assert.equal(name, 'settings'); return collection; } };
|
||||
return { db, state, collection };
|
||||
}
|
||||
|
||||
function supervisor(existing = [], db = database(), commandResult = {}) {
|
||||
const calls = [];
|
||||
const run = async args => {
|
||||
calls.push([...args]);
|
||||
if (args[0] === 'jlist') return { code: 0, stdout: JSON.stringify(existing) };
|
||||
return { code: 0, stdout: 'PRIVATE_PM2_OUTPUT', ...commandResult };
|
||||
};
|
||||
return { controller: createPm2Controller({ settings, run, getDb: async () => db.db }), calls, db, run };
|
||||
}
|
||||
|
||||
test('quick add chooses the next number above managed and unrelated PM2 names', async () => {
|
||||
const f = supervisor([
|
||||
processRecord('proxer-worker-2'), processRecord('proxer-worker-012', false),
|
||||
processRecord('unrelated-worker-999', false), processRecord('proxer-worker-latest', false),
|
||||
]);
|
||||
const res = response();
|
||||
await f.controller.quickAdd({ body: {} }, res);
|
||||
assert.equal(res.statusCode, 200);
|
||||
assert.equal(res.body.name, 'proxer-worker-13');
|
||||
assert.equal(res.body.ok, true);
|
||||
assert.deepEqual(f.calls, [['jlist'], ['start', settings.workerScript, '--name', 'proxer-worker-13',
|
||||
'--cwd', settings.projectRoot, '--interpreter', process.execPath, '--kill-timeout', '10000']]);
|
||||
assert.equal(f.db.state.calls[0].update.$max.value, 12);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /PRIVATE_|stdout|pm2_env/);
|
||||
});
|
||||
|
||||
test('quick add starts at one and keeps increasing after process deletion and controller restart', async () => {
|
||||
const db = database();
|
||||
for (const expected of [1, 2, 3]) {
|
||||
const f = supervisor([], db);
|
||||
const res = response();
|
||||
await f.controller.quickAdd({}, res);
|
||||
assert.equal(res.body.name, `proxer-worker-${expected}`);
|
||||
}
|
||||
assert.equal(db.state.value, 3);
|
||||
});
|
||||
|
||||
test('concurrent quick-add requests across controllers reserve distinct persistent numbers', async () => {
|
||||
const db = database();
|
||||
const requests = Array.from({ length: 8 }, () => supervisor([processRecord('proxer-worker-5')], db));
|
||||
const results = await Promise.all(requests.map(async f => {
|
||||
const res = response();
|
||||
await f.controller.quickAdd({}, res);
|
||||
assert.equal(res.statusCode, 200);
|
||||
return res.body.name;
|
||||
}));
|
||||
assert.equal(new Set(results).size, 8);
|
||||
assert.deepEqual(results.map(name => Number(name.split('-').at(-1))).sort((a, b) => a - b), [6, 7, 8, 9, 10, 11, 12, 13]);
|
||||
assert.equal(db.state.value, 13);
|
||||
});
|
||||
|
||||
test('a duplicate-key initialization race retries seeding without another upsert', async () => {
|
||||
const db = database();
|
||||
db.state.initializationRace = true;
|
||||
const f = supervisor([processRecord('proxer-worker-7')], db);
|
||||
const res = response();
|
||||
await f.controller.quickAdd({}, res);
|
||||
assert.equal(res.body.name, 'proxer-worker-8');
|
||||
assert.equal(db.state.calls.length, 3);
|
||||
assert.equal(db.state.calls[0].options.upsert, true);
|
||||
assert.equal(db.state.calls[1].options.upsert, undefined);
|
||||
});
|
||||
|
||||
test('quick add does not accept a client-selected name, command or script', async () => {
|
||||
const f = supervisor();
|
||||
for (const body of [{ name: 'all' }, { scriptPath: '/unrelated.js' }, { cmd: 'delete' }, [], 'bad']) {
|
||||
const res = response();
|
||||
await f.controller.quickAdd({ body }, res);
|
||||
assert.equal(res.statusCode, 400);
|
||||
}
|
||||
assert.equal(f.calls.length, 0);
|
||||
assert.equal(f.db.state.calls.length, 0);
|
||||
});
|
||||
|
||||
test('failed starts consume their reserved number and expose no supervisor output', async () => {
|
||||
const f = supervisor([], database(), { code: 1 });
|
||||
const failed = response();
|
||||
await f.controller.quickAdd({}, failed);
|
||||
assert.equal(failed.statusCode, 502);
|
||||
assert.equal(failed.body.ok, false);
|
||||
assert.equal(failed.body.name, 'proxer-worker-1');
|
||||
const next = supervisor([], f.db);
|
||||
const created = response();
|
||||
await next.controller.quickAdd({}, created);
|
||||
assert.equal(created.body.name, 'proxer-worker-2');
|
||||
assert.doesNotMatch(JSON.stringify(failed.body), /PRIVATE_/);
|
||||
});
|
||||
|
||||
test('unconfirmed starts keep their reserved number and request refresh before retrying', async () => {
|
||||
const db = database();
|
||||
const controller = createPm2Controller({ settings, getDb: async () => db.db,
|
||||
run: async args => {
|
||||
if (args[0] === 'jlist') return { code: 0, stdout: '[]' };
|
||||
throw new Error('PRIVATE_PM2_FAILURE');
|
||||
},
|
||||
});
|
||||
const res = response();
|
||||
await controller.quickAdd({}, res);
|
||||
assert.equal(res.statusCode, 503);
|
||||
assert.equal(res.body.name, 'proxer-worker-1');
|
||||
assert.match(res.body.error, /Refresh the worker list/);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /PRIVATE_/);
|
||||
assert.equal(db.state.value, 1);
|
||||
});
|
||||
|
||||
test('database failures and unacknowledged reservations never start a process', async () => {
|
||||
for (const mode of ['connect', 'seed', 'reserve', 'acknowledge']) {
|
||||
const db = database();
|
||||
if (mode === 'acknowledge') db.state.acknowledged = false;
|
||||
if (mode === 'seed') db.collection.updateOne = async () => { throw new Error('PRIVATE_DATABASE_FAILURE'); };
|
||||
if (mode === 'reserve') db.collection.findOneAndUpdate = async () => { throw new Error('PRIVATE_DATABASE_FAILURE'); };
|
||||
const calls = [];
|
||||
const controller = createPm2Controller({ settings,
|
||||
getDb: async () => { if (mode === 'connect') throw new Error('PRIVATE_DATABASE_FAILURE'); return db.db; },
|
||||
run: async args => { calls.push(args); return { code: 0, stdout: '[]' }; },
|
||||
});
|
||||
const res = response();
|
||||
await controller.quickAdd({}, res);
|
||||
assert.equal(res.statusCode, 503, mode);
|
||||
assert.deepEqual(calls, [['jlist']], mode);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /PRIVATE_/);
|
||||
}
|
||||
});
|
||||
|
||||
test('unsafe, exhausted and corrupt saved counters cannot create guessed or duplicate names', async () => {
|
||||
for (const value of [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER + 1, 'corrupt-counter', 0.5]) {
|
||||
const f = supervisor([], database(value));
|
||||
const res = response();
|
||||
await f.controller.quickAdd({}, res);
|
||||
assert.equal(res.statusCode, 409);
|
||||
assert.deepEqual(f.calls, [['jlist']]);
|
||||
}
|
||||
const f = supervisor([processRecord('proxer-worker-9007199254740992', false)]);
|
||||
const res = response();
|
||||
await f.controller.quickAdd({}, res);
|
||||
assert.equal(res.statusCode, 409);
|
||||
assert.equal(f.db.state.calls.length, 0);
|
||||
assert.deepEqual(f.calls, [['jlist']]);
|
||||
});
|
||||
|
||||
test('managed worker inventory includes validated absolute start time and excludes environments', async () => {
|
||||
const f = supervisor([processRecord('proxer-worker-1'), processRecord('unrelated', false, 4)]);
|
||||
const workers = await f.controller.listManagedProcesses();
|
||||
assert.equal(workers.length, 1);
|
||||
assert.equal(workers[0].startedAtISO, '2026-10-23T10:00:00.000Z');
|
||||
assert.doesNotMatch(JSON.stringify(workers), /PRIVATE_|pm2_env/);
|
||||
for (const value of [undefined, null, 0, -1, Infinity, '178234', 1e20]) {
|
||||
const record = processRecord('proxer-worker-1');
|
||||
record.pm2_env.pm_uptime = value;
|
||||
assert.equal(normalizeProcess(record).startedAtISO, null);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
"use strict";
|
||||
|
||||
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 { ValidationError, planQueueJobs, buildQueueJobs, STATUS_READ_PROJECTION } = require("../lib/jobValidation");
|
||||
const { createQueueController } = require("../controllers/queueController");
|
||||
const { QUERY_TIMEOUT_MS } = require("../lib/statusQuery");
|
||||
|
||||
const CREATED = new Date("2026-01-01T12:00:00.000Z");
|
||||
|
||||
function seriesBody(changes = {}) {
|
||||
return {
|
||||
mode: "series", id: "42", episode_from: "9", episode_to: "10", language: "engsub",
|
||||
name: "Title", token: "fixture-token", season: "1", ...changes,
|
||||
};
|
||||
}
|
||||
|
||||
async function temporaryConfig(t) {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-refinements-"));
|
||||
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
|
||||
return { outputDir, tokenPrefix: "fixture_cookie=", maxSeriesEpisodes: 500 };
|
||||
}
|
||||
|
||||
function response() {
|
||||
return {
|
||||
statusCode: 200, headers: {},
|
||||
status(code) { this.statusCode = code; return this; },
|
||||
set(name, value) { this.headers[name] = value; return this; },
|
||||
render(template, data) { this.template = template; this.data = data; return this; },
|
||||
json(data) { this.data = data; return this; },
|
||||
redirect(location) { this.location = location; return this; },
|
||||
};
|
||||
}
|
||||
|
||||
test("series planning uses a minimum three digits for explicit season and episode with the language suffix", async t => {
|
||||
const settings = await temporaryConfig(t);
|
||||
const planned = await planQueueJobs(seriesBody({ token: undefined }), settings, () => CREATED);
|
||||
assert.deepEqual(planned, [
|
||||
{ url: "https://proxer.me/watch/42/9/engsub", filename: "TitleS001E009_engsub", created_at: CREATED },
|
||||
{ url: "https://proxer.me/watch/42/10/engsub", filename: "TitleS001E010_engsub", created_at: CREATED },
|
||||
]);
|
||||
const jobs = await buildQueueJobs(seriesBody(), settings, () => CREATED);
|
||||
assert.deepEqual(jobs, planned.map(job => ({ ...job, token: "fixture_cookie=fixture-token" })));
|
||||
assert.equal(`${jobs[0].filename}.mp4`, "TitleS001E009_engsub.mp4");
|
||||
});
|
||||
|
||||
test("season zero supports specials and larger season or episode numbers are preserved without truncation", async t => {
|
||||
const settings = await temporaryConfig(t);
|
||||
for (const [season, first, expected] of [
|
||||
["0", "9", "TitleS000E009_gerdub"],
|
||||
[1, "9", "TitleS001E009_gerdub"],
|
||||
["1234", "9", "TitleS1234E009_gerdub"],
|
||||
["1", "1234", "TitleS001E1234_gerdub"],
|
||||
["1234", "1234", "TitleS1234E1234_gerdub"],
|
||||
]) {
|
||||
const jobs = await buildQueueJobs(seriesBody({ season, episode_from: first, episode_to: first, language: "gerdub" }), settings);
|
||||
assert.equal(jobs[0].filename, expected);
|
||||
assert.equal(jobs[0].url, `https://proxer.me/watch/42/${first}/gerdub`);
|
||||
}
|
||||
});
|
||||
|
||||
test("series filename limits include the full season, episode, language, extension, and Unicode byte length", async t => {
|
||||
const settings = await temporaryConfig(t);
|
||||
const suffix = "S001E009_engsub.mp4";
|
||||
const available = 255 - Buffer.byteLength(suffix, "utf8");
|
||||
const title = "界".repeat(Math.floor(available / 3)) + "a".repeat(available % 3);
|
||||
const body = seriesBody({ name: title, episode_to: "9" });
|
||||
const jobs = await buildQueueJobs(body, settings);
|
||||
assert.equal(Buffer.byteLength(`${jobs[0].filename}.mp4`, "utf8"), 255);
|
||||
await assert.rejects(planQueueJobs({ ...body, name: title + "界" }, settings), ValidationError);
|
||||
await assert.rejects(buildQueueJobs({ ...body, name: title + "a" }, settings), ValidationError);
|
||||
});
|
||||
|
||||
test("malformed explicit seasons fail instead of silently selecting a default or legacy filename", async t => {
|
||||
const settings = await temporaryConfig(t);
|
||||
const malformed = ["", null, true, {}, [], "01", "-1", "-0", "1.5", " 1", "1 ", "1e2", "+1", "NaN",
|
||||
Number.MAX_SAFE_INTEGER + 1, Infinity, NaN];
|
||||
for (const season of malformed) {
|
||||
await assert.rejects(planQueueJobs(seriesBody({ season }), settings), ValidationError, String(season));
|
||||
}
|
||||
});
|
||||
|
||||
test("clients omitting season retain legacy names and single-video requests ignore the series season field", async t => {
|
||||
const settings = await temporaryConfig(t);
|
||||
const legacy = seriesBody({ season: undefined, episode_from: "9", episode_to: "12" });
|
||||
const jobs = await buildQueueJobs(legacy, settings);
|
||||
assert.deepEqual(jobs.map(job => job.filename), ["TitleE09_engsub", "TitleE10_engsub", "TitleE11_engsub", "TitleE12_engsub"]);
|
||||
const video = {
|
||||
mode: "video", url: "https://proxer.me/watch/42/9/engsub", filename: "My single download",
|
||||
token: "fixture-token", season: { $gt: "not-a-season" },
|
||||
};
|
||||
const planned = await planQueueJobs(video, settings);
|
||||
const built = await buildQueueJobs(video, settings);
|
||||
assert.equal(planned[0].filename, "My single download");
|
||||
assert.equal(built[0].filename, "My single download");
|
||||
assert.equal(planned[0].token, undefined);
|
||||
assert.equal(built[0].token, "fixture_cookie=fixture-token");
|
||||
});
|
||||
|
||||
test("clear-state validates a scalar allowlisted state and protects processing before any database access", async () => {
|
||||
let connections = 0;
|
||||
const controller = createQueueController({ getDb: async () => { connections += 1; throw new Error("Must not connect"); } });
|
||||
for (const state of [undefined, null, [], ["queued"], {}, { $ne: "processing" }, "settings", "$where", "all", " queued", "DONE"]) {
|
||||
const result = response();
|
||||
await controller.clearState({ body: { state } }, result, error => { throw error; });
|
||||
assert.equal(result.statusCode, 400, String(state));
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.equal(result.location, undefined);
|
||||
}
|
||||
const processing = response();
|
||||
await controller.clearState({ body: { state: "processing" } }, processing, error => { throw error; });
|
||||
assert.equal(processing.statusCode, 409);
|
||||
assert.equal(processing.location, undefined);
|
||||
assert.equal(connections, 0);
|
||||
});
|
||||
|
||||
test("clearing waiting jobs uses one atomic processing-not-true predicate and preserves a concurrently claimed job", async () => {
|
||||
let records = [{ _id: "waiting" }, { _id: "claimed-during-request" }, { _id: "already-active", processing: true }];
|
||||
const calls = [];
|
||||
const db = { collection(name) {
|
||||
calls.push({ operation: "collection", name });
|
||||
return { async deleteMany(filter) {
|
||||
calls.push({ operation: "delete", filter });
|
||||
assert.deepEqual(filter, { processing: { $ne: true } });
|
||||
// This claim arrives after the HTTP request but before Mongo evaluates
|
||||
// the delete predicate. No earlier list of IDs can authorize its removal.
|
||||
records.find(record => record._id === "claimed-during-request").processing = true;
|
||||
const before = records.length;
|
||||
records = records.filter(record => record.processing === true);
|
||||
return { acknowledged: true, deletedCount: before - records.length };
|
||||
} };
|
||||
} };
|
||||
const result = response();
|
||||
await createQueueController({ getDb: async () => db }).clearState({
|
||||
body: { state: "queued", filter: {}, processing: {}, q: "injected" },
|
||||
query: { state: "processing", q: { $where: "ignored" }, page: "999" },
|
||||
}, result, error => { throw error; });
|
||||
assert.deepEqual(calls, [
|
||||
{ operation: "collection", name: "queue" }, { operation: "delete", filter: { processing: { $ne: true } } },
|
||||
]);
|
||||
assert.deepEqual(records.map(record => record._id), ["claimed-during-request", "already-active"]);
|
||||
assert.equal(result.location, "/status?state=queued");
|
||||
});
|
||||
|
||||
test("clearing history deletes only the selected history collection and preserves downloaded media", async t => {
|
||||
const settings = await temporaryConfig(t);
|
||||
const media = path.join(settings.outputDir, "TitleS001E009_engsub.mp4");
|
||||
await fs.writeFile(media, "downloaded-video-fixture");
|
||||
for (const state of ["done", "failed"]) {
|
||||
const calls = [];
|
||||
const db = { collection(name) {
|
||||
return { async deleteMany(filter) { calls.push({ name, filter }); return { acknowledged: true, deletedCount: 4 }; } };
|
||||
} };
|
||||
const result = response();
|
||||
await createQueueController({ config: settings, getDb: async () => db }).clearState({
|
||||
body: { state }, query: { q: "arbitrary-filter", filename: media },
|
||||
}, result, error => { throw error; });
|
||||
assert.deepEqual(calls, [{ name: state, filter: {} }]);
|
||||
assert.equal(result.location, `/status?state=${state}`);
|
||||
assert.equal(await fs.readFile(media, "utf8"), "downloaded-video-fixture");
|
||||
}
|
||||
});
|
||||
|
||||
test("clear-state database rejection and uncertain deletion reach the error handler without success redirects", async () => {
|
||||
for (const failure of ["rejected", "unacknowledged", "missing", "null", "no-acknowledgement"]) {
|
||||
const original = new Error("private database write detail");
|
||||
const db = { collection() { return { async deleteMany() {
|
||||
if (failure === "rejected") throw original;
|
||||
if (failure === "missing") return undefined;
|
||||
if (failure === "null") return null;
|
||||
if (failure === "no-acknowledgement") return { deletedCount: 4 };
|
||||
return { acknowledged: false };
|
||||
} }; } };
|
||||
const result = response();
|
||||
let error;
|
||||
await createQueueController({ getDb: async () => db }).clearState({ body: { state: "queued" } }, result, received => { error = received; });
|
||||
assert.ok(error instanceof Error, failure);
|
||||
if (failure === "rejected") assert.equal(error, original);
|
||||
assert.equal(result.location, undefined);
|
||||
assert.equal(result.data, undefined);
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
}
|
||||
});
|
||||
|
||||
function queueReadFixture({ recordsAllowed = true } = {}) {
|
||||
const reads = [];
|
||||
const db = { collection(name) {
|
||||
if (name === "settings") return { async findOne(filter, options) {
|
||||
reads.push({ type: "global", filter, options });
|
||||
return { captcha_blocked: true, pause_reason: "resolution", token: "private-setting" };
|
||||
} };
|
||||
return {
|
||||
async countDocuments(filter, options) {
|
||||
reads.push({ type: "count", name, filter, options });
|
||||
return name === "queue" ? (filter.processing === true ? 1 : 2) : 3;
|
||||
},
|
||||
find(filter, options) {
|
||||
assert.equal(recordsAllowed, true, "summary must not load job records");
|
||||
const read = { type: "records", name, filter, options };
|
||||
reads.push(read);
|
||||
const cursor = {
|
||||
sort(value) { read.sort = value; return cursor; },
|
||||
skip(value) { read.skip = value; return cursor; },
|
||||
limit(value) { read.limit = value; return cursor; },
|
||||
async toArray() {
|
||||
return [{ _id: "queued", filename: "TitleS001E009_engsub", token: "cookie=private-job-token",
|
||||
output_log: "Captured private-job-token", created_at: CREATED }];
|
||||
},
|
||||
};
|
||||
return cursor;
|
||||
},
|
||||
};
|
||||
} };
|
||||
return { db, reads };
|
||||
}
|
||||
|
||||
test("status-data includes the activity service snapshot and still returns a bounded sanitized selected page", async () => {
|
||||
const fixture = queueReadFixture();
|
||||
const activity = {
|
||||
workers: [{ key: "pm2:1", name: "proxer-worker-1", jobs: [] }],
|
||||
unassigned: [], truncated: false, workersTruncated: false, available: true,
|
||||
};
|
||||
const settings = { outputDir: "/fixture-output", maxSeriesEpisodes: 500 };
|
||||
let activityCalls = 0;
|
||||
const controller = createQueueController({
|
||||
config: settings, getDb: async () => fixture.db,
|
||||
readActivity: async (db, options) => {
|
||||
activityCalls += 1;
|
||||
assert.equal(db, fixture.db);
|
||||
assert.equal(options.settings, settings);
|
||||
return activity;
|
||||
},
|
||||
});
|
||||
const result = response();
|
||||
await controller.statusData({ query: {} }, result, error => { throw error; });
|
||||
assert.equal(activityCalls, 1);
|
||||
assert.equal(result.data.activity, activity);
|
||||
assert.deepEqual(result.data.filters, { state: "queued", q: "" });
|
||||
assert.equal(result.data.items[0].token, undefined);
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /private-job-token|private-setting/);
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
const reads = fixture.reads.filter(read => read.type === "records");
|
||||
assert.deepEqual(reads, [{
|
||||
type: "records", name: "queue", filter: { processing: { $ne: true } },
|
||||
options: { projection: STATUS_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS },
|
||||
sort: { created_at: 1, _id: 1 }, skip: 0, limit: 25,
|
||||
}]);
|
||||
});
|
||||
|
||||
test("status-summary remains count-only and never invokes activity, inventory, job reads, or filesystem checks", async () => {
|
||||
const fixture = queueReadFixture({ recordsAllowed: false });
|
||||
const settings = { get outputDir() { throw new Error("Summary must not inspect output files"); } };
|
||||
const controller = createQueueController({
|
||||
config: settings, getDb: async () => fixture.db,
|
||||
readActivity: async () => { assert.fail("Summary must not request activity or supervisor inventory"); },
|
||||
});
|
||||
const result = response();
|
||||
await controller.statusSummary({}, result, error => { throw error; });
|
||||
assert.deepEqual(result.data, {
|
||||
counts: { queued: 2, processing: 1, done: 3, failed: 3 },
|
||||
global: { captcha_blocked: true, pause_reason: "resolution" },
|
||||
});
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.equal(fixture.reads.filter(read => read.type === "count").length, 4);
|
||||
assert.equal(fixture.reads.filter(read => read.type === "records").length, 0);
|
||||
assert.ok(fixture.reads.every(read => read.options.maxTimeMS === QUERY_TIMEOUT_MS));
|
||||
});
|
||||
@@ -284,7 +284,7 @@ test('normalized PM2 data retains process ID zero and excludes raw environments'
|
||||
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.deepEqual(Object.keys(normalized).sort(), ['name', 'pid', 'pm_id', 'status', 'cpu', 'memoryMB', 'uptime', 'startedAtISO', 'execPath'].sort());
|
||||
assert.doesNotMatch(JSON.stringify(normalized), /NOT_A_REAL_|MONGO_URI|pm2_env|"raw"/);
|
||||
});
|
||||
|
||||
|
||||
+15
-62
@@ -7,7 +7,6 @@ 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');
|
||||
@@ -368,69 +367,23 @@ test('server construction does not listen and heartbeat/server close clean up lo
|
||||
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 = '<img src=x onerror=alert(1)>';
|
||||
const process = { name: maliciousName, pm_id: '0', pid: '12', status: '<script>fixture</script>', execPath: '<b>fixture</b>', 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] }) }),
|
||||
test('worker view escapes process fields and exposes accessible scoped controls', async () => {
|
||||
const filename = path.join(config.projectRoot, 'views/pm2.ejs');
|
||||
const template = fs.readFileSync(filename, 'utf8');
|
||||
const attack = '<img src=x onerror="alert(1)">';
|
||||
const rendered = await require('ejs').renderFile(filename, {
|
||||
processes: [{ name: attack, pm_id: '0', pid: '12', status: attack, execPath: attack,
|
||||
cpu: '1.2%', memoryMB: '40 MB', uptime: '1m' }],
|
||||
});
|
||||
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(/<script>([\s\S]*?)<\/script>/)[1];
|
||||
vm.runInContext(script + '\nglobalThis.fixture = { refreshList, sendLogRequest, appendLog };', context);
|
||||
assert.equal(context.fixture.sendLogRequest({ type: 'logs', name: 'worker-one' }, false), false);
|
||||
assert.equal(socket.sent.length, 0);
|
||||
await context.fixture.refreshList();
|
||||
const row = document.querySelectorAll()[0];
|
||||
assert.equal(row.children[0].children[0].textContent, maliciousName);
|
||||
assert.equal(row.dataset.name, maliciousName);
|
||||
socket.readyState = 1;
|
||||
await row.click();
|
||||
assert.equal(socket.sent.at(-1).type, 'logs');
|
||||
await row.click();
|
||||
assert.equal(socket.sent.at(-1).type, 'stop-logs');
|
||||
context.fixture.appendLog('x'.repeat(200_000));
|
||||
assert.ok(get('logs').textContent.length < 66 * 1024);
|
||||
assert.match(template, /<script src="\/workers\.js" defer><\/script>/);
|
||||
assert.doesNotMatch(template, /<script>/);
|
||||
assert.ok(!rendered.includes(attack));
|
||||
assert.match(rendered, /<img src=x onerror="alert\(1\)">/);
|
||||
assert.match(rendered, /type="button" class="worker-row" aria-pressed="false"/);
|
||||
assert.match(rendered, /data-pmid="0"/);
|
||||
assert.match(rendered, /for="worker-name"/);
|
||||
assert.match(rendered, /role="status" aria-live="polite"/);
|
||||
});
|
||||
@@ -0,0 +1,353 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { createSessionTokenService, SessionTokenError, CACHE_ID, STATUS_PROJECTION } = require("../lib/sessionToken");
|
||||
const { ValidationError } = require("../lib/jobValidation");
|
||||
const { createProxerSessionProbe, classifyWatchResponse } = require("../lib/proxerSessionProbe");
|
||||
|
||||
const url = "https://proxer.me/watch/42/9/engsub";
|
||||
const settings = { tokenPrefix: "fixture_cookie=" };
|
||||
const checkedAt = new Date("2026-10-23T12:00:00.000Z");
|
||||
const cookie = "fixture_cookie=NOT_A_REAL_COOKIE==";
|
||||
const sourcePage = '<!doctype html><html><head><title>Episode - Proxer.Me</title></head><body><script>const stream={"code":"fixture_embed_id"};</script></body></html>';
|
||||
|
||||
function fixtureRecord(overrides = {}) {
|
||||
return {
|
||||
_id: CACHE_ID, cookie, cookie_name: "fixture_cookie", state: "ready", revision: "fixture-revision-1",
|
||||
saved_at: new Date("2026-10-22T08:00:00Z"), validated_at: new Date("2026-10-22T08:00:00Z"), ...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function database(initial = null) {
|
||||
let current = initial ? structuredClone(initial) : null;
|
||||
const reads = [];
|
||||
const writes = [];
|
||||
const collection = {
|
||||
async findOne(filter, options) {
|
||||
reads.push({ filter: structuredClone(filter), options });
|
||||
assert.deepEqual(filter, { _id: CACHE_ID });
|
||||
assert.equal(options.maxTimeMS, 5000);
|
||||
if (!current) return null;
|
||||
return Object.fromEntries(Object.entries(current).filter(([key]) => key === "_id" || options.projection[key] === 1));
|
||||
},
|
||||
async updateOne(filter, update, options) {
|
||||
writes.push({ filter: structuredClone(filter), update: structuredClone(update), options });
|
||||
assert.equal(options.maxTimeMS, 5000);
|
||||
const matches = current && (Object.hasOwn(filter.revision, "$eq")
|
||||
? current.revision === filter.revision.$eq : !Object.hasOwn(current, "revision"));
|
||||
if (current && !matches) {
|
||||
if (options.upsert) throw Object.assign(new Error("duplicate key"), { code: 11000 });
|
||||
return { acknowledged: true, matchedCount: 0, upsertedCount: 0 };
|
||||
}
|
||||
if (!current && !options.upsert) return { acknowledged: true, matchedCount: 0, upsertedCount: 0 };
|
||||
const inserted = !current;
|
||||
current ||= { _id: CACHE_ID };
|
||||
Object.assign(current, structuredClone(update.$set));
|
||||
for (const key of Object.keys(update.$unset || {})) delete current[key];
|
||||
return { acknowledged: true, matchedCount: inserted ? 0 : 1, upsertedCount: inserted ? 1 : 0 };
|
||||
},
|
||||
};
|
||||
return {
|
||||
db: { collection(name) { assert.equal(name, "settings"); return collection; } },
|
||||
reads, writes, collection,
|
||||
current: () => structuredClone(current),
|
||||
replace(value) { current = structuredClone(value); },
|
||||
};
|
||||
}
|
||||
|
||||
function service(store, overrides = {}) {
|
||||
return createSessionTokenService({ getDb: async () => store.db, settings, now: () => checkedAt,
|
||||
probe: async () => ({ state: "valid" }), ...overrides });
|
||||
}
|
||||
|
||||
function expectedError(code, status) {
|
||||
return error => {
|
||||
assert.ok(error instanceof SessionTokenError);
|
||||
assert.equal(error.code, code);
|
||||
if (status) assert.equal(error.httpStatus, status);
|
||||
assert.doesNotMatch(error.message, /NOT_A_REAL_|fixture_cookie|fixture_embed|PRIVATE/);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
test("a supplied token is checked against the first canonical source before being cached", async () => {
|
||||
const store = database();
|
||||
const checks = [];
|
||||
const tokens = service(store, { probe: async (...args) => {
|
||||
checks.push(args);
|
||||
assert.equal(store.current(), null, "the token must not be saved before verification");
|
||||
return { state: "valid" };
|
||||
} });
|
||||
const result = await tokens.resolveForEnqueue("NOT_A_REAL_COOKIE==", { url });
|
||||
assert.deepEqual(checks, [[cookie, { url }]]);
|
||||
assert.equal(result.cookie, cookie);
|
||||
assert.equal(result.source, "supplied");
|
||||
assert.equal(result.status.available, true);
|
||||
assert.equal(result.status.lastValidatedAt, checkedAt.toISOString());
|
||||
assert.equal(store.current().cookie, cookie);
|
||||
assert.equal(store.current().cookie_name, "fixture_cookie");
|
||||
assert.equal(store.current().state, "ready");
|
||||
assert.equal(Object.hasOwn(store.current(), "expires_at"), false);
|
||||
assert.doesNotMatch(JSON.stringify(result.status), /NOT_A_REAL_|fixture_cookie/);
|
||||
});
|
||||
|
||||
test("blank submissions reuse a saved token but validate it every time without a time-to-live shortcut", async () => {
|
||||
const store = database(fixtureRecord({ saved_at: new Date("2000-01-01"), validated_at: new Date("2000-01-01") }));
|
||||
let calls = 0;
|
||||
const tokens = service(store, { probe: async (value, input) => {
|
||||
assert.equal(value, cookie); assert.equal(input.url, url); calls++;
|
||||
return { state: "valid" };
|
||||
} });
|
||||
for (const value of ["", undefined, null]) {
|
||||
const result = await tokens.resolveForEnqueue(value, { url });
|
||||
assert.equal(result.source, "cached");
|
||||
assert.equal(result.cookie, cookie);
|
||||
}
|
||||
assert.equal(calls, 3);
|
||||
assert.equal(store.current().validated_at.toISOString(), checkedAt.toISOString());
|
||||
assert.equal(store.current().saved_at.toISOString(), "2000-01-01T00:00:00.000Z");
|
||||
});
|
||||
|
||||
test("safe cache metadata never reads or exposes the cookie or revision", async () => {
|
||||
const store = database(fixtureRecord({ PRIVATE_EXTRA: "PRIVATE_VALUE" }));
|
||||
const status = await service(store).readStatus();
|
||||
assert.deepEqual(status, { available: true, state: "saved", lastValidatedAt: "2026-10-22T08:00:00.000Z", savedAt: "2026-10-22T08:00:00.000Z" });
|
||||
assert.deepEqual(store.reads[0].options.projection, STATUS_PROJECTION);
|
||||
assert.equal(Object.hasOwn(STATUS_PROJECTION, "cookie"), false);
|
||||
assert.equal(Object.hasOwn(STATUS_PROJECTION, "revision"), false);
|
||||
assert.doesNotMatch(JSON.stringify(status), /NOT_A_REAL_|PRIVATE|fixture_cookie|revision/);
|
||||
});
|
||||
|
||||
test("missing, invalid and differently named saved cookies require new input without probing", async () => {
|
||||
for (const [record, code] of [[null, "missing"], [fixtureRecord({ state: "invalid" }), "invalid"], [fixtureRecord({ cookie_name: "different_cookie" }), "missing"]]) {
|
||||
const store = database(record);
|
||||
const tokens = service(store, { probe: async () => assert.fail("No usable cookie must not be probed") });
|
||||
await assert.rejects(tokens.resolveForEnqueue("", { url }), expectedError(code, 400));
|
||||
assert.equal(store.writes.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("malformed supplied values and unsafe source URLs fail before any database or network access", async () => {
|
||||
const tokens = createSessionTokenService({ settings,
|
||||
getDb: async () => assert.fail("Database must not be used"),
|
||||
probe: async () => assert.fail("Network must not be used"),
|
||||
});
|
||||
for (const value of [[], {}, " ", "abc; other=PRIVATE", "abc\nPRIVATE"]) {
|
||||
await assert.rejects(tokens.resolveForEnqueue(value, { url }), ValidationError);
|
||||
}
|
||||
await assert.rejects(tokens.resolveForEnqueue("fixture", { url: "https://evil.invalid/watch/42/9/engsub" }), ValidationError);
|
||||
});
|
||||
|
||||
test("definite rejection removes only the rejected cached credential and keeps an invalid marker", async () => {
|
||||
const store = database(fixtureRecord());
|
||||
const tokens = service(store, { probe: async () => ({ state: "invalid" }) });
|
||||
await assert.rejects(tokens.resolveForEnqueue("", { url }), expectedError("invalid", 400));
|
||||
assert.equal(store.current().state, "invalid");
|
||||
assert.equal(Object.hasOwn(store.current(), "cookie"), false);
|
||||
assert.notEqual(store.current().revision, "fixture-revision-1");
|
||||
assert.equal((await tokens.readStatus()).available, false);
|
||||
});
|
||||
|
||||
test("rejecting a newly supplied token preserves a different saved token", async () => {
|
||||
const original = fixtureRecord();
|
||||
const store = database(original);
|
||||
await assert.rejects(service(store, { probe: async () => ({ state: "invalid" }) })
|
||||
.resolveForEnqueue("NOT_A_REAL_BAD_REPLACEMENT", { url }), expectedError("invalid"));
|
||||
assert.deepEqual(store.current(), original);
|
||||
assert.equal(store.writes.length, 0);
|
||||
});
|
||||
|
||||
test("network, verification, missing-source and unknown checks preserve the cached token and do not claim expiry", async () => {
|
||||
for (const state of ["unavailable", "verification", "source", "unverifiable", "unexpected"]) {
|
||||
const original = fixtureRecord();
|
||||
const store = database(original);
|
||||
await assert.rejects(service(store, { probe: async () => ({ state }) }).resolveForEnqueue("", { url }), error => {
|
||||
expectedError(state === "unexpected" ? "unverifiable" : state)(error);
|
||||
assert.doesNotMatch(error.message, /expired|rejected/i);
|
||||
return true;
|
||||
});
|
||||
assert.deepEqual(store.current(), original);
|
||||
assert.equal(store.writes.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("probe exceptions and database errors cannot leak upstream response bodies or credentials", async () => {
|
||||
const store = database(fixtureRecord());
|
||||
await assert.rejects(service(store, { probe: async () => { throw new Error(`PRIVATE ${cookie}`); } })
|
||||
.resolveForEnqueue("", { url }), expectedError("unavailable", 503));
|
||||
const broken = createSessionTokenService({ settings, getDb: async () => { throw new Error(`PRIVATE ${cookie}`); } });
|
||||
await assert.rejects(broken.readStatus(), expectedError("storage", 503));
|
||||
await assert.rejects(broken.resolveForEnqueue("fixture", { url }), expectedError("storage", 503));
|
||||
});
|
||||
|
||||
test("malformed stored credentials are invalidated locally without a request", async () => {
|
||||
for (const stored of ["wrong_name=PRIVATE", "fixture_cookie=invalid; other=PRIVATE", null]) {
|
||||
const store = database(fixtureRecord({ cookie: stored }));
|
||||
await assert.rejects(service(store, { probe: async () => assert.fail("Must not send malformed cookie") })
|
||||
.resolveForEnqueue("", { url }), expectedError("invalid"));
|
||||
assert.equal(store.current().state, "invalid");
|
||||
assert.equal(Object.hasOwn(store.current(), "cookie"), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("an old failed check cannot invalidate a newer token saved while it was in flight", async () => {
|
||||
const store = database(fixtureRecord());
|
||||
const fresh = fixtureRecord({ cookie: "fixture_cookie=NOT_A_REAL_NEW_COOKIE", revision: "newer-revision" });
|
||||
const tokens = service(store, { probe: async () => { store.replace(fresh); return { state: "invalid" }; } });
|
||||
await assert.rejects(tokens.resolveForEnqueue("", { url }), expectedError("invalid"));
|
||||
assert.deepEqual(store.current(), fresh);
|
||||
assert.deepEqual(store.writes[0].filter.revision, { $eq: "fixture-revision-1" });
|
||||
});
|
||||
|
||||
test("an old successful replacement cannot overwrite a newer concurrently saved token", async () => {
|
||||
const store = database(fixtureRecord());
|
||||
const fresh = fixtureRecord({ cookie: "fixture_cookie=NOT_A_REAL_NEW_COOKIE", revision: "newer-revision" });
|
||||
const tokens = service(store, { probe: async () => { store.replace(fresh); return { state: "valid" }; } });
|
||||
const result = await tokens.resolveForEnqueue("NOT_A_REAL_SLOW_REPLACEMENT", { url });
|
||||
assert.equal(result.cookie, "fixture_cookie=NOT_A_REAL_SLOW_REPLACEMENT");
|
||||
assert.deepEqual(store.current(), fresh);
|
||||
assert.equal(result.status.available, true);
|
||||
});
|
||||
|
||||
test("an older rejected check cannot erase a cached token after a later successful revalidation", async () => {
|
||||
const store = database(fixtureRecord());
|
||||
let releaseOldCheck;
|
||||
let oldCheckStarted;
|
||||
const started = new Promise(resolve => { oldCheckStarted = resolve; });
|
||||
const old = service(store, { probe: async () => {
|
||||
oldCheckStarted();
|
||||
return new Promise(resolve => { releaseOldCheck = resolve; });
|
||||
} });
|
||||
const oldResult = old.resolveForEnqueue("", { url });
|
||||
const rejected = assert.rejects(oldResult, expectedError("invalid"));
|
||||
await started;
|
||||
await service(store).resolveForEnqueue("", { url });
|
||||
const fresh = store.current();
|
||||
assert.notEqual(fresh.revision, "fixture-revision-1");
|
||||
releaseOldCheck({ state: "invalid" });
|
||||
await rejected;
|
||||
assert.deepEqual(store.current(), fresh);
|
||||
assert.equal(store.current().cookie, cookie);
|
||||
});
|
||||
|
||||
test("concurrent first saves tolerate the unique-id insertion race without replacing the winner", async () => {
|
||||
const store = database();
|
||||
const fresh = fixtureRecord({ cookie: "fixture_cookie=NOT_A_REAL_FIRST_WINNER", revision: "winner" });
|
||||
const tokens = service(store, { probe: async () => { store.replace(fresh); return { state: "valid" }; } });
|
||||
const result = await tokens.resolveForEnqueue("NOT_A_REAL_SLOW_REPLACEMENT", { url });
|
||||
assert.equal(result.source, "supplied");
|
||||
assert.deepEqual(store.current(), fresh);
|
||||
});
|
||||
|
||||
test("unacknowledged cache writes stop submission with a safe error", async () => {
|
||||
const store = database();
|
||||
store.collection.updateOne = async () => ({ acknowledged: false });
|
||||
await assert.rejects(service(store).resolveForEnqueue("fixture", { url }), expectedError("storage", 503));
|
||||
});
|
||||
|
||||
test("download-access proof requires a usable source marker instead of HTTP 200 alone", () => {
|
||||
assert.deepEqual(classifyWatchResponse(200, sourcePage), { state: "valid" });
|
||||
for (const body of ["<html>Ordinary page</html>", '<script>{"code":""}</script>', '<script>{"code":"https://evil.invalid"}</script>']) {
|
||||
assert.deepEqual(classifyWatchResponse(200, body), { state: "unverifiable" });
|
||||
}
|
||||
assert.deepEqual(classifyWatchResponse(200, sourcePage, "application/json"), { state: "unverifiable" });
|
||||
assert.deepEqual(classifyWatchResponse(404, sourcePage), { state: "source" });
|
||||
});
|
||||
|
||||
test("challenge and access-denial responses are distinguished from token expiry and source changes", () => {
|
||||
assert.deepEqual(classifyWatchResponse(403, "<title>Attention Required! | Cloudflare</title>"), { state: "verification" });
|
||||
assert.deepEqual(classifyWatchResponse(200, '<form id="challenge-form">check</form>'), { state: "verification" });
|
||||
assert.deepEqual(classifyWatchResponse(200, "<main>Bitte logge dich ein, um diesen Bereich betreten zu können.</main>"), { state: "invalid" });
|
||||
assert.deepEqual(classifyWatchResponse(200, "<main>Bitte logge dich ein, um diesen Bereich betreten zu können.</main>"), { state: "invalid" });
|
||||
assert.deepEqual(classifyWatchResponse(401, "<main>Denied</main>"), { state: "invalid" });
|
||||
assert.deepEqual(classifyWatchResponse(403, "<main>Denied</main>"), { state: "unverifiable" });
|
||||
assert.deepEqual(classifyWatchResponse(503, "<main>Unavailable</main>"), { state: "unavailable" });
|
||||
assert.deepEqual(classifyWatchResponse(200, "<main>Complete the CAPTCHA.</main>"), { state: "verification" });
|
||||
assert.deepEqual(classifyWatchResponse(200, '<script>const text="Bitte logge dich ein, um diesen Bereich betreten zu können.";</script>'), { state: "unverifiable" });
|
||||
});
|
||||
|
||||
test("non-HTML error statuses retain their meaning while JSON success and redirects never prove access", () => {
|
||||
const json = '{"code":"fixture_embed_id"}';
|
||||
for (const [status, expected] of [[401, "invalid"], [429, "unavailable"], [503, "unavailable"], [404, "source"], [410, "source"]]) {
|
||||
assert.deepEqual(classifyWatchResponse(status, json, "application/json"), { state: expected });
|
||||
}
|
||||
assert.deepEqual(classifyWatchResponse(200, json, "application/json"), { state: "unverifiable" });
|
||||
assert.deepEqual(classifyWatchResponse(302, sourcePage, "text/html"), { state: "unverifiable" });
|
||||
assert.deepEqual(classifyWatchResponse(302, json, "application/json"), { state: "unverifiable" });
|
||||
assert.deepEqual(classifyWatchResponse(401, "<title>Attention Required! | Cloudflare</title>", "text/html"), { state: "verification" });
|
||||
});
|
||||
|
||||
test("the probe sends only the configured cookie and stream preference to a canonical HTTPS source", async () => {
|
||||
const calls = [];
|
||||
const probe = createProxerSessionProbe({ fetch: async (target, options) => {
|
||||
calls.push({ target, options });
|
||||
return new Response(sourcePage, { headers: { "Content-Type": "text/html; charset=UTF-8" } });
|
||||
} });
|
||||
assert.deepEqual(await probe(cookie, { url: "https://www.proxer.me/watch/42/9/engsub/#top" }), { state: "valid" });
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0].target, url);
|
||||
assert.equal(calls[0].options.headers.Cookie, `${cookie}; stream_choose=proxer-stream`);
|
||||
assert.equal(calls[0].options.redirect, "manual");
|
||||
assert.equal(calls[0].options.credentials, "omit");
|
||||
assert.equal(calls[0].options.method, "GET");
|
||||
});
|
||||
|
||||
test("redirects, unsupported sources and header injection cannot forward the cookie elsewhere", async () => {
|
||||
let calls = 0;
|
||||
const probe = createProxerSessionProbe({ fetch: async () => {
|
||||
calls++;
|
||||
return new Response("", { status: 302, headers: { Location: "https://evil.invalid/capture" } });
|
||||
} });
|
||||
assert.deepEqual(await probe(cookie, { url }), { state: "unverifiable" });
|
||||
assert.equal(calls, 1);
|
||||
for (const target of ["http://proxer.me/watch/42/9/engsub", "https://evil.invalid/watch/42/9/engsub", `${url}?token=PRIVATE`]) {
|
||||
await assert.rejects(probe(cookie, { url: target }), ValidationError);
|
||||
}
|
||||
await assert.rejects(probe(`${cookie}; evil=PRIVATE`, { url }), ValidationError);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test("oversized, truncated and non-HTML responses do not pass the access check", async () => {
|
||||
for (const response of [
|
||||
new Response(sourcePage, { headers: { "content-type": "text/html", "content-length": "1000000" } }),
|
||||
new Response("x".repeat(1000) + sourcePage, { headers: { "content-type": "text/html" } }),
|
||||
new Response(sourcePage, { headers: { "content-type": "application/json" } }),
|
||||
new Response(new ReadableStream({ start(controller) { controller.error(new Error(`PRIVATE ${cookie}`)); } }), { headers: { "content-type": "text/html" } }),
|
||||
]) {
|
||||
const probe = createProxerSessionProbe({ fetch: async () => response, maxBytes: 500 });
|
||||
const result = await probe(cookie, { url });
|
||||
assert.notEqual(result.state, "valid");
|
||||
assert.doesNotMatch(JSON.stringify(result), /NOT_A_REAL_|PRIVATE/);
|
||||
}
|
||||
});
|
||||
|
||||
test("the probe preserves explicit status for absent and oversized bodies without accepting empty success", async () => {
|
||||
for (const [status, expected] of [[401, "invalid"], [503, "unavailable"], [200, "unverifiable"]]) {
|
||||
for (const body of [null, "x".repeat(1000)]) {
|
||||
const probe = createProxerSessionProbe({ maxBytes: 128, fetch: async () => new Response(body, {
|
||||
status, headers: { "content-type": "text/html" },
|
||||
}) });
|
||||
assert.deepEqual(await probe(cookie, { url }), { state: expected });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a hard deadline aborts a stuck request without exposing fetch errors", async () => {
|
||||
let signal;
|
||||
const probe = createProxerSessionProbe({ timeoutMs: 15, fetch: async (_, options) => {
|
||||
signal = options.signal;
|
||||
return new Promise(() => {});
|
||||
} });
|
||||
assert.deepEqual(await probe(cookie, { url }), { state: "unavailable" });
|
||||
assert.equal(signal.aborted, true);
|
||||
const throwing = createProxerSessionProbe({ fetch: async () => { throw new Error(`PRIVATE ${cookie}`); } });
|
||||
assert.deepEqual(await throwing(cookie, { url }), { state: "unavailable" });
|
||||
});
|
||||
|
||||
test("a Cloudflare challenge header wins even if an HTML body happens to contain a code field", async () => {
|
||||
const probe = createProxerSessionProbe({ fetch: async () => new Response(sourcePage, {
|
||||
headers: { "content-type": "text/html", "cf-mitigated": "challenge" },
|
||||
}) });
|
||||
assert.deepEqual(await probe(cookie, { url }), { state: "verification" });
|
||||
});
|
||||
@@ -0,0 +1,310 @@
|
||||
"use strict";
|
||||
|
||||
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 { createQueueController: createRealQueueController } = require("../controllers/queueController");
|
||||
// These tests isolate the existing form/page contracts. Dedicated activity and
|
||||
// token-controller suites exercise the added services, without live HTTP calls.
|
||||
function createQueueController(options = {}) {
|
||||
return createRealQueueController({
|
||||
...options,
|
||||
readActivity: options.readActivity || (async () => ({ workers: [], unassigned: [], available: true, truncated: false, workersTruncated: false })),
|
||||
sessionTokens: options.sessionTokens || {
|
||||
readStatus: async () => ({ available: false, state: "missing", lastValidatedAt: null, savedAt: null }),
|
||||
resolveForEnqueue: async value => ({ cookie: require("../lib/jobValidation").cookieToken(value, options.config?.tokenPrefix || "fixture=") }),
|
||||
},
|
||||
});
|
||||
}
|
||||
const { ValidationError } = require("../lib/jobValidation");
|
||||
const { parseStatusQuery, stateQuery, statusFilter, publicGlobal, QUERY_TIMEOUT_MS } = require("../lib/statusQuery");
|
||||
|
||||
function response() {
|
||||
return {
|
||||
statusCode: 200, headers: {},
|
||||
status(code) { this.statusCode = code; return this; },
|
||||
set(name, value) { this.headers[name] = value; return this; },
|
||||
render(template, data) { this.template = template; this.data = data; return this; },
|
||||
json(data) { this.data = data; return this; },
|
||||
redirect(location) { this.location = location; return this; },
|
||||
};
|
||||
}
|
||||
|
||||
function databaseFixture({ data = {}, global = null, recordReadsAllowed = true } = {}) {
|
||||
const calls = [];
|
||||
function matches(record, filter) {
|
||||
if (filter.processing === true && record.processing !== true) return false;
|
||||
if (filter.processing?.$ne === true && record.processing === true) return false;
|
||||
if (filter.filename && !new RegExp(filter.filename.$regex, filter.filename.$options).test(record.filename)) return false;
|
||||
return true;
|
||||
}
|
||||
const db = { collection(name) {
|
||||
if (name === "settings") return { findOne: async (filter, options) => {
|
||||
calls.push({ operation: "settings", filter, options });
|
||||
return global;
|
||||
} };
|
||||
return {
|
||||
countDocuments: async (filter, options) => {
|
||||
calls.push({ operation: "count", name, filter, options });
|
||||
return (data[name] || []).filter(record => matches(record, filter)).length;
|
||||
},
|
||||
find(filter, options) {
|
||||
assert.ok(recordReadsAllowed, "summary must not read job records");
|
||||
const call = { operation: "find", name, filter, options };
|
||||
calls.push(call);
|
||||
return {
|
||||
sort(sort) { call.sort = sort; return this; },
|
||||
skip(skip) { call.skip = skip; return this; },
|
||||
limit(limit) { call.limit = limit; return this; },
|
||||
async toArray() {
|
||||
assert.ok(Number.isInteger(call.skip) && call.skip >= 0, "skip is set before materialization");
|
||||
assert.ok([10, 25, 50].includes(call.limit), "bounded limit is set before materialization");
|
||||
const rows = (data[name] || []).filter(record => matches(record, filter));
|
||||
rows.sort((a, b) => {
|
||||
for (const [key, direction] of Object.entries(call.sort)) {
|
||||
if (a[key] < b[key]) return -direction;
|
||||
if (a[key] > b[key]) return direction;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
return rows.slice(call.skip, call.skip + call.limit).map(record =>
|
||||
Object.fromEntries(Object.entries(record).filter(([key]) => options.projection[key] === 1)));
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
} };
|
||||
return { db, calls };
|
||||
}
|
||||
|
||||
async function temporaryConfig(t, extras = {}) {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-status-query-"));
|
||||
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
|
||||
return { outputDir, tokenPrefix: "fixture=", maxSeriesEpisodes: 500, ...extras };
|
||||
}
|
||||
|
||||
test("queue filters default safely and accept bounded scalar pagination", () => {
|
||||
assert.deepEqual(parseStatusQuery(), { state: "queued", q: "", page: 1, pageSize: 25 });
|
||||
assert.deepEqual(parseStatusQuery({ state: "done", q: " Episode 🎬 ", page: "100000", pageSize: "50" }), {
|
||||
state: "done", q: "Episode 🎬", page: 100000, pageSize: 50,
|
||||
});
|
||||
assert.deepEqual(parseStatusQuery({ q: " ", pageSize: "10", ignored: "anything" }), {
|
||||
state: "queued", q: "", page: 1, pageSize: 10,
|
||||
});
|
||||
});
|
||||
|
||||
test("query parsing rejects arrays, objects, malformed Unicode and unbounded numbers", () => {
|
||||
const invalid = [null, [], "string", { state: "all" }, { state: ["queued", "done"] }, { q: { $ne: "" } },
|
||||
{ q: "x".repeat(101) }, { q: "line\nbreak" }, { q: "bad\u0085control" }, { q: "bad\uD800" },
|
||||
{ page: "0" }, { page: "1.5" }, { page: "1e3" }, { page: "01" }, { page: "100001" },
|
||||
{ page: "9".repeat(300) }, { page: 2 }, { pageSize: "500" }, { pageSize: "025" }, { pageSize: ["10"] }];
|
||||
for (const query of invalid) assert.throws(() => parseStatusQuery(query), ValidationError, JSON.stringify(query));
|
||||
});
|
||||
|
||||
test("filename search escapes every regex operator and never accepts arbitrary Mongo fields", () => {
|
||||
const text = "Episode [1].*(a|b)?+$^{}\\";
|
||||
const filter = statusFilter("queued", text);
|
||||
assert.deepEqual(filter.processing, { $ne: true });
|
||||
assert.deepEqual(Object.keys(filter).sort(), ["filename", "processing"]);
|
||||
assert.equal(filter.filename.$options, "i");
|
||||
const regex = new RegExp(filter.filename.$regex, "i");
|
||||
assert.ok(regex.test(`Prefix ${text} suffix`));
|
||||
assert.equal(regex.test("Episode 1 and everything else"), false);
|
||||
assert.deepEqual(statusFilter("failed", ""), {});
|
||||
});
|
||||
|
||||
test("each status sort has a deterministic id tie breaker", () => {
|
||||
for (const state of ["queued", "processing", "done", "failed"]) {
|
||||
const selected = stateQuery(state);
|
||||
assert.equal(Object.keys(selected.sort).at(-1), "_id");
|
||||
assert.equal(selected.sort._id, ["queued", "processing"].includes(state) ? 1 : -1);
|
||||
}
|
||||
assert.throws(() => stateQuery("settings"), ValidationError);
|
||||
});
|
||||
|
||||
test("summary counts states without loading records, logs, credentials or file metadata", async () => {
|
||||
const { db, calls } = databaseFixture({
|
||||
data: { queue: [{ processing: false }, {}, { processing: true }], done: [{}, {}], failed: [{}] },
|
||||
global: { captcha_blocked: true, pause_reason: "resolution", token: "private-settings" },
|
||||
recordReadsAllowed: false,
|
||||
});
|
||||
const controller = createQueueController({ getDb: async () => db });
|
||||
const result = response();
|
||||
await controller.statusSummary({}, result, error => { throw error; });
|
||||
assert.deepEqual(result.data, { counts: { queued: 2, processing: 1, done: 2, failed: 1 },
|
||||
global: { captcha_blocked: true, pause_reason: "resolution" } });
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.equal(calls.filter(call => call.operation === "count").length, 4);
|
||||
assert.ok(calls.every(call => call.options.maxTimeMS === QUERY_TIMEOUT_MS));
|
||||
assert.deepEqual(calls.find(call => call.operation === "settings").options.projection, { captcha_blocked: 1, pause_reason: 1 });
|
||||
});
|
||||
|
||||
test("paginated status reads only one selected collection page with an internal redaction projection", async () => {
|
||||
const queue = Array.from({ length: 72 }, (_, index) => ({
|
||||
_id: String(index).padStart(3, "0"), filename: `Episode ${index}`, created_at: new Date("2026-01-01"),
|
||||
processing: false, token: "session=internal-credential==", output_log: "Captured internal-credential==",
|
||||
private_field: "private-data",
|
||||
}));
|
||||
queue.push({ _id: "active", processing: true });
|
||||
const { db, calls } = databaseFixture({ data: { queue, done: [{ _id: "history" }] } });
|
||||
const controller = createQueueController({ getDb: async () => db });
|
||||
const result = response();
|
||||
await controller.statusData({ query: { state: "queued", page: "2", pageSize: "25" } }, result, error => { throw error; });
|
||||
assert.equal(result.data.items.length, 25);
|
||||
assert.equal(result.data.items[0]._id, "025");
|
||||
assert.equal(result.data.items.at(-1)._id, "049");
|
||||
assert.deepEqual(result.data.counts, { queued: 72, processing: 1, done: 1, failed: 0 });
|
||||
assert.deepEqual(result.data.pagination, { page: 2, pageSize: 25, total: 72, totalPages: 3 });
|
||||
assert.deepEqual(result.data.filters, { state: "queued", q: "" });
|
||||
const reads = calls.filter(call => call.operation === "find");
|
||||
assert.equal(reads.length, 1);
|
||||
assert.equal(reads[0].name, "queue");
|
||||
assert.equal(reads[0].skip, 25);
|
||||
assert.equal(reads[0].limit, 25);
|
||||
assert.equal(reads[0].options.projection.token, 1);
|
||||
assert.equal(reads[0].options.maxTimeMS, QUERY_TIMEOUT_MS);
|
||||
assert.match(result.data.items[0].output_log, /\[redacted\]/);
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /internal-credential|private-data|private_field|"token"/);
|
||||
assert.equal(Object.hasOwn(result.data, "queued"), false);
|
||||
assert.equal(Object.hasOwn(result.data, "done"), false);
|
||||
});
|
||||
|
||||
test("literal search changes the selected total while keeping global state counts intact", async () => {
|
||||
const { db, calls } = databaseFixture({ data: { failed: [
|
||||
{ _id: "one", filename: "Episode [01]", failed_at: "2026-01-01" },
|
||||
{ _id: "two", filename: "Episode 0", failed_at: "2026-01-02" },
|
||||
{ _id: "three", filename: "episode [01] repeat", failed_at: "2026-01-03" },
|
||||
] } });
|
||||
const controller = createQueueController({ getDb: async () => db });
|
||||
const result = response();
|
||||
await controller.statusData({ query: { state: "failed", q: " [01] " } }, result, error => { throw error; });
|
||||
assert.deepEqual(result.data.items.map(job => job._id), ["three", "one"]);
|
||||
assert.equal(result.data.counts.failed, 3);
|
||||
assert.equal(result.data.pagination.total, 2);
|
||||
assert.equal(result.data.filters.q, "[01]");
|
||||
const extraCount = calls.filter(call => call.operation === "count" && call.filter.filename);
|
||||
assert.equal(extraCount.length, 1);
|
||||
assert.deepEqual(extraCount[0].filter, calls.find(call => call.operation === "find").filter);
|
||||
});
|
||||
|
||||
test("pages clamp after records disappear and an empty state remains on page one", async () => {
|
||||
for (const amount of [0, 12]) {
|
||||
const { db, calls } = databaseFixture({ data: { queue: Array.from({ length: amount }, (_, index) => ({
|
||||
_id: String(index), filename: `Episode ${index}`,
|
||||
})) } });
|
||||
const result = response();
|
||||
await createQueueController({ getDb: async () => db }).statusData({ query: { page: "999", pageSize: "10" } }, result, error => { throw error; });
|
||||
assert.equal(result.data.pagination.page, amount ? 2 : 1);
|
||||
assert.equal(result.data.pagination.totalPages, amount ? 2 : 1);
|
||||
assert.equal(result.data.items.length, amount ? 2 : 0);
|
||||
assert.equal(calls.find(call => call.operation === "find").skip, amount ? 10 : 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("malformed filters produce safe 400s before any database access", async () => {
|
||||
const controller = createQueueController({ getDb: () => { throw new Error("database must not be read"); } });
|
||||
for (const method of ["status", "statusData"]) {
|
||||
const result = response();
|
||||
await controller[method]({ query: { q: { $where: "private-input" } } }, result, error => { throw error; });
|
||||
assert.equal(result.statusCode, 400);
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /private-input|\$where/);
|
||||
if (method === "status") assert.equal(result.template, "error");
|
||||
else assert.equal(result.data.ok, false);
|
||||
}
|
||||
});
|
||||
|
||||
test("history file sizes are restricted to visible regular files and refuse links", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
await fs.writeFile(path.join(config.outputDir, "Episode.mp4"), "fixture-bytes");
|
||||
await fs.symlink(path.join(config.outputDir, "Episode.mp4"), path.join(config.outputDir, "Link.mp4"));
|
||||
const { db } = databaseFixture({ data: { done: [
|
||||
{ _id: "one", filename: "Episode" }, { _id: "two", filename: "Link" }, { _id: "three", filename: "../outside" },
|
||||
] } });
|
||||
const result = response();
|
||||
await createQueueController({ config, getDb: async () => db }).statusData({ query: { state: "done" } }, result, error => { throw error; });
|
||||
const sizes = Object.fromEntries(result.data.items.map(job => [job.filename, job.fileSize]));
|
||||
assert.equal(sizes.Episode, 13);
|
||||
assert.equal(sizes.Link, null);
|
||||
assert.equal(sizes["../outside"], null);
|
||||
});
|
||||
|
||||
test("global status keeps only the known pause flag and reasons", () => {
|
||||
assert.deepEqual(publicGlobal(null), { captcha_blocked: false, pause_reason: null });
|
||||
assert.deepEqual(publicGlobal({ captcha_blocked: "true", pause_reason: "<script>" }), { captcha_blocked: false, pause_reason: null });
|
||||
for (const reason of ["authentication", "resolution"]) assert.deepEqual(publicGlobal({ captcha_blocked: true, pause_reason: reason }), {
|
||||
captcha_blocked: true, pause_reason: reason,
|
||||
});
|
||||
});
|
||||
|
||||
test("the download form receives configured bounds and a safe initial mode with safe cache metadata", async () => {
|
||||
const controller = createQueueController({ config: { outputDir: "/mnt/media/WIP", maxSeriesEpisodes: 12 },
|
||||
getDb: () => { throw new Error("must not connect"); } });
|
||||
for (const mode of ["video", "series", ["video"], "<script>"]) {
|
||||
const result = response();
|
||||
await controller.home({ query: { mode } }, result);
|
||||
assert.equal(result.template, "index");
|
||||
assert.equal(result.data.values.mode, mode === "video" ? "video" : "series");
|
||||
assert.equal(result.data.maxSeriesEpisodes, 12);
|
||||
assert.equal(result.data.outputDir, "/mnt/media/WIP");
|
||||
assert.equal(result.data.formError, null);
|
||||
assert.equal(Object.hasOwn(result.data.values, "token"), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("validation errors preserve bounded non-secret form fields and clear credentials", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
const controller = createQueueController({ config, getDb: () => { throw new Error("must not connect"); } });
|
||||
const result = response();
|
||||
await controller.enqueue({ body: {
|
||||
mode: "series", id: "42", episode_from: "4", episode_to: "1", language: "gerdub",
|
||||
name: "Series fixture-secret", token: "fixture-secret", private_field: "hidden-field",
|
||||
} }, result);
|
||||
assert.equal(result.statusCode, 400);
|
||||
assert.equal(result.template, "index");
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.deepEqual(result.data.values, { mode: "series", id: "42", episode_from: "4", episode_to: "1",
|
||||
language: "gerdub", season: "1", name: "Series [redacted]", url: "" });
|
||||
assert.match(result.data.formError, /Last episode/);
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /fixture-secret|hidden-field|"token"/);
|
||||
});
|
||||
|
||||
test("successful submissions report the actual inserted count in their queue redirect", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
let inserted;
|
||||
const controller = createQueueController({ config, getDb: async () => ({ collection: () => ({
|
||||
bulkWrite: async operations => { inserted = operations; return { isOk: () => true, insertedCount: operations.length }; },
|
||||
}) }) });
|
||||
const result = response();
|
||||
await controller.enqueue({ body: { mode: "series", id: "42", episode_from: "3", episode_to: "5",
|
||||
language: "engsub", name: "Series", token: "credential" } }, result);
|
||||
assert.equal(inserted.length, 3);
|
||||
assert.equal(result.location, "/status?state=queued&added=3");
|
||||
});
|
||||
|
||||
test("SSR notices accept only bounded numeric added counts without reflecting arbitrary text", async () => {
|
||||
const { db } = databaseFixture();
|
||||
const controller = createQueueController({ config: { maxSeriesEpisodes: 500 }, getDb: async () => db });
|
||||
for (const added of ["3", "0", "501", "<script>", ["1"], undefined]) {
|
||||
const result = response();
|
||||
await controller.status({ query: { added } }, result, error => { throw error; });
|
||||
assert.equal(result.data.added, added === "3" ? 3 : 0);
|
||||
assert.equal(result.data.activePage, "queue");
|
||||
assert.equal(result.data.title, "Queue");
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /<script>/);
|
||||
}
|
||||
});
|
||||
|
||||
test("database failures propagate to the shared generic error handler without raw error JSON", async () => {
|
||||
const expected = new Error("private connection details");
|
||||
const controller = createQueueController({ getDb: async () => { throw expected; } });
|
||||
for (const method of ["status", "statusData", "statusSummary"]) {
|
||||
const result = response();
|
||||
let caught;
|
||||
await controller[method]({}, result, error => { caught = error; });
|
||||
assert.equal(caught, expected);
|
||||
assert.equal(result.data, undefined);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,329 @@
|
||||
"use strict";
|
||||
|
||||
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 ejs = require("ejs");
|
||||
const { createQueueController } = require("../controllers/queueController");
|
||||
const { createSessionTokenService, CACHE_ID, STATUS_PROJECTION } = require("../lib/sessionToken");
|
||||
|
||||
const CHECKED = new Date("2026-10-23T12:00:00.000Z");
|
||||
const PRIVATE_TOKEN = "PRIVATE_CONTROLLER_TOKEN==";
|
||||
const COOKIE = `fixture_cookie=${PRIVATE_TOKEN}`;
|
||||
|
||||
function response() {
|
||||
return {
|
||||
statusCode: 200, headers: {},
|
||||
status(code) { this.statusCode = code; return this; },
|
||||
set(name, value) { this.headers[name] = value; return this; },
|
||||
render(template, data) { this.template = template; this.data = data; return this; },
|
||||
json(data) { this.data = data; return this; },
|
||||
redirect(location) { this.location = location; return this; },
|
||||
};
|
||||
}
|
||||
|
||||
function requestBody(changes = {}) {
|
||||
return {
|
||||
mode: "series", id: "42", episode_from: "9", episode_to: "10", language: "engsub",
|
||||
season: "2", name: "A series title", token: PRIVATE_TOKEN, ...changes,
|
||||
};
|
||||
}
|
||||
|
||||
function cachedToken(changes = {}) {
|
||||
return {
|
||||
_id: CACHE_ID, cookie: COOKIE, cookie_name: "fixture_cookie", state: "ready", revision: "PRIVATE_REVISION",
|
||||
saved_at: new Date("2026-01-01T12:00:00Z"), validated_at: new Date("2026-01-01T12:00:00Z"),
|
||||
PRIVATE_FIELD: "PRIVATE_METADATA", ...changes,
|
||||
};
|
||||
}
|
||||
|
||||
function memoryDatabase({ initial = null, queueError, metadataError } = {}) {
|
||||
let cache = initial ? structuredClone(initial) : null;
|
||||
const queue = [];
|
||||
const reads = [];
|
||||
const events = [];
|
||||
const db = { collection(name) {
|
||||
if (name === "settings") return {
|
||||
async findOne(filter, options) {
|
||||
events.push("settings.read"); reads.push({ filter, options });
|
||||
if (metadataError) throw metadataError;
|
||||
if (!cache) return null;
|
||||
return Object.fromEntries(Object.entries(cache).filter(([key]) => key === "_id" || options.projection[key] === 1));
|
||||
},
|
||||
async updateOne(filter, update, options = {}) {
|
||||
events.push("settings.write");
|
||||
const matches = cache && (Object.hasOwn(filter.revision, "$eq")
|
||||
? cache.revision === filter.revision.$eq : !Object.hasOwn(cache, "revision"));
|
||||
if ((cache && !matches) || (!cache && !options.upsert)) return { acknowledged: true, matchedCount: 0, upsertedCount: 0 };
|
||||
const inserted = !cache;
|
||||
cache ||= { _id: CACHE_ID };
|
||||
Object.assign(cache, structuredClone(update.$set || {}));
|
||||
for (const key of Object.keys(update.$unset || {})) delete cache[key];
|
||||
return { acknowledged: true, matchedCount: inserted ? 0 : 1, upsertedCount: inserted ? 1 : 0 };
|
||||
},
|
||||
};
|
||||
assert.equal(name, "queue");
|
||||
return {
|
||||
async insertOne(document) {
|
||||
events.push("queue.insertOne");
|
||||
if (queueError) throw queueError;
|
||||
queue.push(structuredClone(document));
|
||||
return { acknowledged: true, insertedId: "fixture-job" };
|
||||
},
|
||||
async bulkWrite(operations) {
|
||||
events.push("queue.bulkWrite");
|
||||
if (queueError) throw queueError;
|
||||
queue.push(...operations.map(operation => structuredClone(operation.insertOne.document)));
|
||||
return { ok: 1, insertedCount: operations.length, isOk: () => true };
|
||||
},
|
||||
};
|
||||
} };
|
||||
return { db, queue, reads, events, cache: () => structuredClone(cache) };
|
||||
}
|
||||
|
||||
async function integratedFixture(t, { state = "valid", probeError, ...databaseOptions } = {}) {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-token-controller-"));
|
||||
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
|
||||
const settings = { outputDir, tokenPrefix: "fixture_cookie=", maxSeriesEpisodes: 500 };
|
||||
const store = memoryDatabase(databaseOptions);
|
||||
const probes = [];
|
||||
let connections = 0;
|
||||
const connect = async () => { connections += 1; return store.db; };
|
||||
const sessionTokens = createSessionTokenService({
|
||||
getDb: connect, settings, now: () => CHECKED,
|
||||
probe: async (cookie, options) => {
|
||||
probes.push({ cookie, options }); store.events.push("probe");
|
||||
if (probeError) throw probeError;
|
||||
return { state };
|
||||
},
|
||||
});
|
||||
const controller = createQueueController({
|
||||
getDb: connect, config: settings, now: () => CHECKED, sessionTokens,
|
||||
});
|
||||
return { store, probes, controller, settings, sessionTokens, connections: () => connections };
|
||||
}
|
||||
|
||||
test("controller plans a series then verifies its first source before caching and inserting the verified cookie", async t => {
|
||||
const fixture = await integratedFixture(t);
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body: requestBody() }, result);
|
||||
assert.equal(result.location, "/status?state=queued&added=2");
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.deepEqual(fixture.probes, [{ cookie: COOKIE, options: { url: "https://proxer.me/watch/42/9/engsub" } }]);
|
||||
assert.deepEqual(fixture.store.queue.map(job => job.filename), ["A series titleS002E009_engsub", "A series titleS002E010_engsub"]);
|
||||
assert.ok(fixture.store.queue.every(job => job.token === COOKIE && job.created_at.toISOString() === CHECKED.toISOString()));
|
||||
assert.equal(fixture.store.cache().cookie, COOKIE);
|
||||
assert.ok(fixture.store.events.indexOf("probe") < fixture.store.events.indexOf("settings.write"));
|
||||
assert.ok(fixture.store.events.indexOf("probe") < fixture.store.events.indexOf("queue.bulkWrite"));
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_CONTROLLER_TOKEN|fixture_cookie=/);
|
||||
});
|
||||
|
||||
test("a blank-token single download revalidates the cached cookie and inserts the canonical source", async t => {
|
||||
const fixture = await integratedFixture(t, { initial: cachedToken() });
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body: {
|
||||
mode: "video", url: "https://www.proxer.me:443/watch/42/9/engsub/#player", name: "Single episode", token: "",
|
||||
} }, result);
|
||||
assert.equal(result.location, "/status?state=queued&added=1");
|
||||
assert.deepEqual(fixture.probes, [{ cookie: COOKIE, options: { url: "https://proxer.me/watch/42/9/engsub" } }]);
|
||||
assert.deepEqual(fixture.store.queue, [{
|
||||
url: "https://proxer.me/watch/42/9/engsub", filename: "Single episode", created_at: CHECKED, token: COOKIE,
|
||||
}]);
|
||||
assert.ok(fixture.store.events.indexOf("probe") < fixture.store.events.indexOf("queue.insertOne"));
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_CONTROLLER_TOKEN|PRIVATE_REVISION/);
|
||||
});
|
||||
|
||||
test("the controller uses the session service's verified cookie rather than rebuilding it from submitted text", async t => {
|
||||
const fixture = await integratedFixture(t);
|
||||
const calls = [];
|
||||
const controller = createQueueController({
|
||||
config: fixture.settings, getDb: async () => fixture.store.db,
|
||||
sessionTokens: {
|
||||
readStatus: async () => ({ available: true, state: "saved" }),
|
||||
resolveForEnqueue: async (...args) => { calls.push(args); return { cookie: "fixture_cookie=VERIFIED_SERVICE_VALUE" }; },
|
||||
},
|
||||
});
|
||||
const result = response();
|
||||
await controller.enqueue({ body: requestBody({ token: "UNVERIFIED_SUBMITTED_VALUE" }) }, result);
|
||||
assert.deepEqual(calls, [["UNVERIFIED_SUBMITTED_VALUE", { url: "https://proxer.me/watch/42/9/engsub" }]]);
|
||||
assert.ok(fixture.store.queue.every(job => job.token === "fixture_cookie=VERIFIED_SERVICE_VALUE"));
|
||||
assert.equal(result.location, "/status?state=queued&added=2");
|
||||
});
|
||||
|
||||
test("GET download renders only token metadata, leaves the password input empty, and disables caching", async t => {
|
||||
const fixture = await integratedFixture(t, { initial: cachedToken() });
|
||||
const result = response();
|
||||
await fixture.controller.home({ query: { mode: "series", token: PRIVATE_TOKEN } }, result);
|
||||
assert.equal(result.statusCode, 200);
|
||||
assert.equal(result.template, "index");
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.deepEqual(result.data.tokenStatus, {
|
||||
available: true, state: "saved", lastValidatedAt: "2026-01-01T12:00:00.000Z", savedAt: "2026-01-01T12:00:00.000Z",
|
||||
});
|
||||
assert.equal(result.data.values.season, "1");
|
||||
assert.equal(result.data.values.token, undefined);
|
||||
assert.equal(fixture.probes.length, 0);
|
||||
assert.deepEqual(fixture.store.reads[0].options.projection, STATUS_PROJECTION);
|
||||
const html = await ejs.renderFile(path.resolve(__dirname, "../views/index.ejs"), result.data);
|
||||
assert.doesNotMatch(JSON.stringify(result.data) + html, /PRIVATE_CONTROLLER_TOKEN|PRIVATE_REVISION|PRIVATE_METADATA/);
|
||||
const input = html.match(/<input\b[^>]*\bid="download-token"[^>]*>/)?.[0];
|
||||
assert.ok(input);
|
||||
assert.doesNotMatch(input, /\bvalue\s*=/i);
|
||||
assert.match(html, /Token saved/);
|
||||
});
|
||||
|
||||
test("token rejection, missing credentials, verification, and network errors render safe warnings without queue writes", async t => {
|
||||
const cases = [
|
||||
{ state: "invalid", status: 400, message: /rejected/i },
|
||||
{ state: "verification", status: 409, message: /verification/i },
|
||||
{ state: "unavailable", status: 503, message: /could not reach|timed out/i },
|
||||
{ state: "source", status: 409, message: /unavailable/i },
|
||||
{ state: "unverifiable", status: 409, message: /could not be resolved/i },
|
||||
{ state: "valid", token: "", status: 400, message: /No saved token/i },
|
||||
{ state: "valid", probeError: new Error(`PRIVATE_UPSTREAM ${COOKIE}`), status: 503, message: /could not reach|timed out/i },
|
||||
];
|
||||
for (const scenario of cases) {
|
||||
const fixture = await integratedFixture(t, scenario);
|
||||
const body = requestBody({ token: scenario.token ?? PRIVATE_TOKEN, season: "12", language: "gerdub", name: "Retained title" });
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body }, result);
|
||||
assert.equal(result.statusCode, scenario.status, scenario.state);
|
||||
assert.equal(result.template, "index");
|
||||
assert.match(result.data.formError, scenario.message);
|
||||
assert.equal(result.data.values.id, "42");
|
||||
assert.equal(result.data.values.name, "Retained title");
|
||||
assert.equal(result.data.values.season, "12");
|
||||
assert.equal(result.data.values.language, "gerdub");
|
||||
assert.equal(result.data.values.episode_from, "9");
|
||||
assert.equal(result.data.values.episode_to, "10");
|
||||
assert.equal(result.data.values.token, undefined);
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.equal(result.location, undefined);
|
||||
assert.deepEqual(fixture.store.queue, []);
|
||||
assert.ok(fixture.store.events.every(event => !event.startsWith("queue.")));
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_CONTROLLER_TOKEN|PRIVATE_UPSTREAM|fixture_cookie=/);
|
||||
if (scenario.token === "") assert.equal(fixture.probes.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("a submitted token accidentally pasted into another field is removed from the retry form", async t => {
|
||||
const fixture = await integratedFixture(t, { state: "verification" });
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body: requestBody({ name: `A title ${PRIVATE_TOKEN}`, season: "3" }) }, result);
|
||||
assert.equal(result.statusCode, 409);
|
||||
assert.equal(result.data.values.name, "A title [redacted]");
|
||||
assert.equal(result.data.values.season, "3");
|
||||
const html = await ejs.renderFile(path.resolve(__dirname, "../views/index.ejs"), result.data);
|
||||
assert.doesNotMatch(html + JSON.stringify(result.data), /PRIVATE_CONTROLLER_TOKEN/);
|
||||
assert.match(html, /Download not added/);
|
||||
assert.equal(result.location, undefined);
|
||||
});
|
||||
|
||||
test("invalid sources and malformed season values fail before token checks or database access", async t => {
|
||||
const fixture = await integratedFixture(t);
|
||||
for (const body of [
|
||||
requestBody({ season: "not-a-season" }),
|
||||
requestBody({ season: { $ne: "1" } }),
|
||||
{ mode: "video", url: `https://evil.invalid/watch/42/9/engsub?token=${PRIVATE_TOKEN}`, token: PRIVATE_TOKEN },
|
||||
{ mode: "video", url: "https://proxer.me/watch/42/9/engsub?token=private-source-query", token: PRIVATE_TOKEN },
|
||||
]) {
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body }, result);
|
||||
assert.equal(result.statusCode, 400);
|
||||
assert.equal(result.template, "index");
|
||||
assert.equal(result.location, undefined);
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_CONTROLLER_TOKEN/);
|
||||
}
|
||||
assert.equal(fixture.connections(), 0);
|
||||
assert.equal(fixture.probes.length, 0);
|
||||
assert.equal(fixture.store.queue.length, 0);
|
||||
});
|
||||
|
||||
test("a queue database failure after successful token verification returns a safe failure without claiming success", async t => {
|
||||
for (const mode of ["series", "video"]) {
|
||||
const fixture = await integratedFixture(t, { queueError: new Error(`PRIVATE_DATABASE ${COOKIE} https://private.invalid/?signed=secret`) });
|
||||
const body = mode === "series" ? requestBody() : {
|
||||
mode: "video", url: "https://proxer.me/watch/42/9/engsub", name: "Single episode", token: PRIVATE_TOKEN,
|
||||
};
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body }, result);
|
||||
assert.equal(fixture.probes.length, 1);
|
||||
assert.equal(result.statusCode, 500);
|
||||
assert.equal(result.template, "error");
|
||||
assert.equal(result.data.details, null);
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.equal(result.location, undefined);
|
||||
assert.deepEqual(fixture.store.queue, []);
|
||||
assert.match(result.data.message, /submission could not be confirmed/i);
|
||||
assert.match(result.data.message, /check the queue before retrying/i);
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_DATABASE|PRIVATE_CONTROLLER_TOKEN|private.invalid|signed=secret/);
|
||||
}
|
||||
});
|
||||
|
||||
test("uncertain insertion acknowledgements or partial batch counts never produce an added-to-queue redirect", async t => {
|
||||
const fixture = await integratedFixture(t);
|
||||
const singleResults = [undefined, null, {}, { acknowledged: false }, { acknowledged: "true" }];
|
||||
const batchResults = [undefined, null, {}, { ok: 1, insertedCount: 2 },
|
||||
{ isOk: () => false, insertedCount: 2 },
|
||||
{ isOk: () => true, insertedCount: 0 }, { isOk: () => true, insertedCount: 1 },
|
||||
{ isOk: () => true, insertedCount: 3 }, { isOk: () => true, insertedCount: "2" }];
|
||||
for (const [mode, outcomes] of [["video", singleResults], ["series", batchResults]]) {
|
||||
for (const outcome of outcomes) {
|
||||
let attempted = 0;
|
||||
const controller = createQueueController({
|
||||
config: fixture.settings,
|
||||
sessionTokens: { resolveForEnqueue: async () => ({ cookie: COOKIE }) },
|
||||
getDb: async () => ({ collection(name) {
|
||||
assert.equal(name, "queue");
|
||||
return {
|
||||
async insertOne() { attempted += 1; return outcome; },
|
||||
async bulkWrite() { attempted += 1; return outcome; },
|
||||
};
|
||||
} }),
|
||||
});
|
||||
const body = mode === "series" ? requestBody() : {
|
||||
mode: "video", url: "https://proxer.me/watch/42/9/engsub", name: "Single episode", token: PRIVATE_TOKEN,
|
||||
};
|
||||
const result = response();
|
||||
await controller.enqueue({ body }, result);
|
||||
assert.equal(attempted, 1);
|
||||
assert.equal(result.statusCode, 500, mode);
|
||||
assert.equal(result.template, "error");
|
||||
assert.equal(result.location, undefined);
|
||||
assert.match(result.data.message, /submission could not be confirmed/i);
|
||||
assert.match(result.data.message, /check the queue before retrying/i);
|
||||
assert.equal(result.data.details, null);
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_CONTROLLER_TOKEN/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a token-storage failure stops enqueue without a second metadata database request", async t => {
|
||||
const fixture = await integratedFixture(t, { metadataError: new Error(`PRIVATE_STORAGE_FAILURE ${COOKIE}`) });
|
||||
const result = response();
|
||||
await fixture.controller.enqueue({ body: requestBody() }, result);
|
||||
assert.equal(result.statusCode, 503);
|
||||
assert.equal(result.template, "index");
|
||||
assert.equal(result.location, undefined);
|
||||
assert.equal(fixture.store.reads.length, 1);
|
||||
assert.equal(fixture.connections(), 1);
|
||||
assert.equal(fixture.probes.length, 0);
|
||||
assert.deepEqual(fixture.store.queue, []);
|
||||
assert.deepEqual(result.data.tokenStatus, { available: false, state: "unavailable" });
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_STORAGE_FAILURE|PRIVATE_CONTROLLER_TOKEN/);
|
||||
});
|
||||
|
||||
test("an unavailable metadata read still renders the form without exposing database errors or cookies", async t => {
|
||||
const fixture = await integratedFixture(t, { initial: cachedToken(), metadataError: new Error(`PRIVATE_METADATA_FAILURE ${COOKIE}`) });
|
||||
const result = response();
|
||||
await fixture.controller.home({ query: { mode: "video" } }, result);
|
||||
assert.equal(result.statusCode, 200);
|
||||
assert.equal(result.template, "index");
|
||||
assert.deepEqual(result.data.tokenStatus, { available: false, state: "unavailable" });
|
||||
assert.equal(result.data.values.mode, "video");
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE_METADATA_FAILURE|PRIVATE_CONTROLLER_TOKEN/);
|
||||
assert.equal(fixture.probes.length, 0);
|
||||
});
|
||||
+111
-62
@@ -9,7 +9,19 @@ const {
|
||||
ValidationError, normalizeWatchUrl, normalizeFilename, validateOutputTarget,
|
||||
cookieToken, buildQueueJobs, sanitizeLog, toPublicJob, MAX_LOG_BYTES,
|
||||
} = require("../lib/jobValidation");
|
||||
const { createQueueController } = require("../controllers/queueController");
|
||||
const { createQueueController: createRealQueueController } = require("../controllers/queueController");
|
||||
// These tests isolate the existing form/page contracts. Dedicated activity and
|
||||
// token-controller suites exercise the added services, without live HTTP calls.
|
||||
function createQueueController(options = {}) {
|
||||
return createRealQueueController({
|
||||
...options,
|
||||
readActivity: options.readActivity || (async () => ({ workers: [], unassigned: [], available: true, truncated: false, workersTruncated: false })),
|
||||
sessionTokens: options.sessionTokens || {
|
||||
readStatus: async () => ({ available: false, state: "missing", lastValidatedAt: null, savedAt: null }),
|
||||
resolveForEnqueue: async value => ({ cookie: require("../lib/jobValidation").cookieToken(value, options.config?.tokenPrefix || "fixture=") }),
|
||||
},
|
||||
});
|
||||
}
|
||||
const fixtures = require("./fixtures/legacy-contracts.json");
|
||||
|
||||
const repository = path.resolve(__dirname, "..");
|
||||
@@ -32,6 +44,19 @@ function response() {
|
||||
};
|
||||
}
|
||||
|
||||
function paginatedCursor(records) {
|
||||
let offset = 0, pageSize;
|
||||
return {
|
||||
sort() { return this; },
|
||||
skip(value) { offset = value; return this; },
|
||||
limit(value) { pageSize = value; return this; },
|
||||
async toArray() {
|
||||
assert.ok([10, 25, 50].includes(pageSize), "status records must be bounded before retrieval");
|
||||
return records.slice(offset, offset + pageSize);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("legacy web naming fixtures stay compatible", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
for (const fixture of fixtures.namingCases.filter(entry => entry.entrypoint.startsWith("web-"))) {
|
||||
@@ -132,6 +157,10 @@ test("invalid submissions do not connect or insert, and failure responses never
|
||||
await controller.enqueue({ body: { mode: "video", url: "https://evil.test/file", token: "fixture-secret" } }, bad);
|
||||
assert.equal(bad.statusCode, 400);
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(bad.template, "index");
|
||||
assert.equal(bad.data.values.mode, "video");
|
||||
assert.equal(Object.hasOwn(bad.data.values, "token"), false);
|
||||
assert.ok(bad.data.formError);
|
||||
assert.equal(bad.data.details, null);
|
||||
assert.doesNotMatch(JSON.stringify(bad.data), /fixture-secret|Error:|stack/);
|
||||
|
||||
@@ -142,16 +171,16 @@ test("invalid submissions do not connect or insert, and failure responses never
|
||||
assert.doesNotMatch(JSON.stringify(unavailable.data), /database fixture secret|fixture-secret|Error:/);
|
||||
});
|
||||
|
||||
test("enqueue inserts all validated episode jobs in one batch and redirects to existing status URL", async t => {
|
||||
test("enqueue inserts all validated episode jobs in one batch and redirects to the queued view with its count", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
let inserted;
|
||||
const controller = createQueueController({ config, getDb: async () => ({ collection(name) {
|
||||
assert.equal(name, "queue");
|
||||
return { bulkWrite: async operations => { inserted = operations; } };
|
||||
return { bulkWrite: async operations => { inserted = operations; return { isOk: () => true, insertedCount: operations.length }; } };
|
||||
} }) });
|
||||
const result = response();
|
||||
await controller.enqueue({ body: { mode: "series", id: "42", episode_from: "9", episode_to: "10", language: "engdub", name: "Series", token: "fixture" } }, result);
|
||||
assert.equal(result.location, "/status");
|
||||
assert.equal(result.location, "/status?state=queued&added=2");
|
||||
assert.deepEqual(inserted.map(operation => operation.insertOne.document.filename), ["SeriesE09_engdub", "SeriesE10_engdub"]);
|
||||
});
|
||||
|
||||
@@ -189,21 +218,21 @@ test("status endpoints use projections, exclude secret settings and refuse symli
|
||||
assert.deepEqual(options.projection, { captcha_blocked: 1, pause_reason: 1 });
|
||||
return { captcha_blocked: true, secret: "settings-secret" };
|
||||
} };
|
||||
return { find(filter, options) {
|
||||
return {
|
||||
countDocuments: async filter => name === "queue" && filter.processing === true ? 1 : 0,
|
||||
find(filter, options) {
|
||||
assert.equal(options.projection.token, 1, "tokens are internal inputs to exact-value log redaction");
|
||||
return { sort() { return this; }, async toArray() {
|
||||
return name === "queue" && filter.processing === true
|
||||
return paginatedCursor(name === "queue" && filter.processing === true
|
||||
? [{ _id: "active", filename: "link", url: sourceUrl, token: "fixture-secret", private_field: true }]
|
||||
: [];
|
||||
} };
|
||||
: []);
|
||||
} };
|
||||
} };
|
||||
const controller = createQueueController({ config, getDb: async () => database });
|
||||
const result = response();
|
||||
await controller.statusData({}, result, error => { throw error; });
|
||||
await controller.statusData({ query: { state: "processing" } }, result, error => { throw error; });
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.deepEqual(result.data.global, { captcha_blocked: true, pause_reason: null });
|
||||
assert.equal(result.data.processing[0].fileSize, null);
|
||||
assert.equal(result.data.items[0].fileSize, null);
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /fixture-secret|settings-secret|private_field/);
|
||||
});
|
||||
|
||||
@@ -220,30 +249,31 @@ test("projected queued and history logs redact known cookies without exposing th
|
||||
}));
|
||||
const database = { collection(name) {
|
||||
if (name === "settings") return { findOne: async () => ({ captcha_blocked: false }) };
|
||||
return { find(filter, { projection }) {
|
||||
return { countDocuments: async () => 1, find(filter, { projection }) {
|
||||
const group = name === "queue" ? (filter.processing === true ? "processing" : "queued") : name;
|
||||
assert.equal(projection.token, 1);
|
||||
// Apply the real inclusion projection so this test cannot accidentally
|
||||
// redact a token which MongoDB would have omitted from the response.
|
||||
const projected = Object.fromEntries(Object.entries(records[group]).filter(([key]) => projection[key] === 1));
|
||||
return { sort() { return this; }, async toArray() { return [projected]; } };
|
||||
return paginatedCursor([projected]);
|
||||
} };
|
||||
} };
|
||||
const controller = createQueueController({ config, getDb: async () => database });
|
||||
const jsonResponse = response();
|
||||
await controller.statusData({}, jsonResponse, error => { throw error; });
|
||||
const viewResponse = response();
|
||||
await controller.status({}, viewResponse, error => { throw error; });
|
||||
for (const snapshot of [jsonResponse.data, viewResponse.data]) {
|
||||
for (const group of groups) {
|
||||
const job = snapshot[group][0];
|
||||
for (const group of groups) {
|
||||
for (const method of ["statusData", "status"]) {
|
||||
const result = response();
|
||||
await controller[method]({ query: { state: group } }, result, error => { throw error; });
|
||||
const snapshot = result.data;
|
||||
assert.equal(snapshot.filters.state, group);
|
||||
assert.equal(snapshot.items.length, 1);
|
||||
const job = snapshot.items[0];
|
||||
assert.equal(Object.hasOwn(job, "token"), false);
|
||||
assert.equal(Object.hasOwn(job, "private_field"), false);
|
||||
assert.match(job.output_log, /\[redacted\]/);
|
||||
assert.ok(!job.output_log.includes(`${group}-exact-credential==`));
|
||||
assert.ok(!job.output_log.includes("custom_cookie="));
|
||||
assert.doesNotMatch(JSON.stringify(snapshot), /exact-credential|must never reach the view/);
|
||||
}
|
||||
assert.doesNotMatch(JSON.stringify(snapshot), /exact-credential|must never reach the view/);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -255,10 +285,10 @@ test("public global status exposes only allowlisted pause reasons and resolution
|
||||
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 []; } }; } };
|
||||
return { countDocuments: async () => 0, find() { return paginatedCursor([]); } };
|
||||
} };
|
||||
const controller = createQueueController({ config, getDb: async () => database });
|
||||
for (const method of ["statusData", "status"]) {
|
||||
for (const method of ["statusData", "status", "statusSummary"]) {
|
||||
const result = response();
|
||||
await controller[method]({}, result, error => { throw error; });
|
||||
assert.deepEqual(result.data.global, {
|
||||
@@ -287,7 +317,7 @@ test("resume clears both the existing global pause flag and its reason before re
|
||||
assert.equal(result.location, "/status");
|
||||
});
|
||||
|
||||
test("verification banner distinguishes resolution failures without claiming a confirmed CAPTCHA", async () => {
|
||||
test("verification banner and shared status updates distinguish 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(/<span id="captcha-message">([\s\S]*?)<\/span>/)[1];
|
||||
@@ -296,55 +326,74 @@ test("verification banner distinguishes resolution failures without claiming a c
|
||||
assert.match(rendered, /Resume after verification/);
|
||||
assert.doesNotMatch(message, /CAPTCHA triggered|CAPTCHA confirmed/);
|
||||
|
||||
const script = [...rendered.matchAll(/<script>([\s\S]*?)<\/script>/g)][0][1];
|
||||
const elements = { "captcha-alert": { style: {} }, "captcha-message": { textContent: "" } };
|
||||
let globalState = { captcha_blocked: true, pause_reason: "resolution" };
|
||||
assert.match(rendered, /<script src="\/app\.js" defer><\/script>/);
|
||||
const script = await fs.readFile(path.join(repository, "public/app.js"), "utf8");
|
||||
const listeners = new Map();
|
||||
const classes = new Set();
|
||||
const elements = {
|
||||
"main-content": { dataset: { page: "queue" } },
|
||||
"captcha-alert": { hidden: true },
|
||||
"captcha-message": { textContent: "" },
|
||||
"global-status": {
|
||||
classList: {
|
||||
add(value) { classes.add(value); }, remove(value) { classes.delete(value); },
|
||||
toggle(value, enabled) { if (enabled) classes.add(value); else classes.delete(value); },
|
||||
},
|
||||
removeAttribute() {},
|
||||
},
|
||||
"global-status-text": { textContent: "" },
|
||||
"nav-queue-count": { textContent: "", hidden: true },
|
||||
};
|
||||
const context = {
|
||||
document: { getElementById: id => elements[id] },
|
||||
fetch: async () => ({ json: async () => ({ global: globalState }) }),
|
||||
setInterval: () => {}, console,
|
||||
document: { getElementById: id => elements[id], addEventListener: (name, handler) => listeners.set(name, handler) },
|
||||
window: { addEventListener() {} },
|
||||
fetch: async () => { throw new Error("the queue page must not perform duplicate summary polling"); },
|
||||
setTimeout: () => 0, clearTimeout() {}, console,
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(script, context);
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
assert.equal(elements["captcha-alert"].style.display, "block");
|
||||
const update = global => listeners.get("proxer:status")({ detail: {
|
||||
global, counts: { queued: 2, processing: 1, done: 4, failed: 1 },
|
||||
} });
|
||||
update({ captcha_blocked: true, pause_reason: "resolution" });
|
||||
assert.equal(elements["captcha-alert"].hidden, false);
|
||||
assert.match(elements["captcha-message"].textContent, /unavailable video/);
|
||||
globalState = { captcha_blocked: true, pause_reason: "authentication" };
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
assert.equal(elements["global-status-text"].textContent, "Downloads paused");
|
||||
assert.ok(classes.has("is-paused"));
|
||||
assert.equal(elements["nav-queue-count"].textContent, "3");
|
||||
update({ captcha_blocked: true, pause_reason: "authentication" });
|
||||
assert.match(elements["captcha-message"].textContent, /Authentication or access needs verification/);
|
||||
globalState = { captcha_blocked: true, pause_reason: "<img onerror=evil>" };
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
update({ captcha_blocked: true, pause_reason: "<img onerror=evil>" });
|
||||
assert.doesNotMatch(elements["captcha-message"].textContent, /<img|evil/);
|
||||
globalState = { captcha_blocked: false, pause_reason: null };
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
assert.equal(elements["captcha-alert"].style.display, "none");
|
||||
listeners.get("proxer:status-error")();
|
||||
assert.equal(elements["captcha-alert"].hidden, false, "an unavailable refresh must not hide a known pause");
|
||||
assert.match(elements["global-status-text"].textContent, /Paused.*unavailable/);
|
||||
update({ captcha_blocked: false, pause_reason: null });
|
||||
assert.equal(elements["captcha-alert"].hidden, true);
|
||||
assert.equal(elements["global-status-text"].textContent, "Queue ready");
|
||||
assert.ok(classes.has("is-ready"));
|
||||
assert.equal(classes.has("is-stale"), false);
|
||||
});
|
||||
|
||||
test("server-rendered and refreshed status escape HTML-like filenames, IDs and logs", async () => {
|
||||
test("paginated status views escape HTML-like filenames, IDs, logs and search text in every state", async () => {
|
||||
const attack = '<img src=x onerror="alert(1)">';
|
||||
const job = { _id: `id" onmouseover="alert(2)`, filename: attack, url: attack, output_log: attack, created_at: "2026-01-01T00:00:00Z" };
|
||||
const rendered = await ejs.renderFile(path.join(repository, "views/status.ejs"), {
|
||||
queued: [job], processing: [job], finished: [{ ...job, finished_at: job.created_at }],
|
||||
failed: [{ ...job, failed_at: job.created_at }], global: { captcha_blocked: false },
|
||||
});
|
||||
assert.ok(!rendered.includes(attack));
|
||||
assert.match(rendered, /<img src=x onerror="alert\(1\)">/);
|
||||
assert.doesNotMatch(rendered, /action="\/clear-processing"/);
|
||||
const scripts = [...rendered.matchAll(/<script>([\s\S]*?)<\/script>/g)];
|
||||
const statusScript = scripts.find(match => match[1].includes("function refreshStatus"))[1];
|
||||
const context = {
|
||||
document: { querySelectorAll: () => [] },
|
||||
fetch: async () => ({ json: async () => ({ queued: [job], processing: [job], done: [job], failed: [job] }) }),
|
||||
setInterval: () => {}, console,
|
||||
queuedList: {}, processingList: {}, doneList: {}, failedList: {},
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(statusScript, context);
|
||||
await vm.runInContext("refreshStatus()", context);
|
||||
for (const key of ["queuedList", "processingList", "doneList", "failedList"]) {
|
||||
assert.ok(!context[key].innerHTML.includes(attack));
|
||||
assert.match(context[key].innerHTML, /<img/);
|
||||
assert.doesNotMatch(context[key].innerHTML, /data-id="[^\n]*" onmouseover=/);
|
||||
for (const state of ["queued", "processing", "done", "failed"]) {
|
||||
const rendered = await ejs.renderFile(path.join(repository, "views/status.ejs"), {
|
||||
items: [job, { ...job, _id: "safe", filename: "A normal episode", url: sourceUrl }],
|
||||
counts: { queued: 2, processing: 2, done: 2, failed: 2 },
|
||||
pagination: { page: 1, pageSize: 25, total: 2, totalPages: 1 },
|
||||
filters: { state, q: attack }, global: { captcha_blocked: false },
|
||||
});
|
||||
assert.ok(!rendered.includes(attack));
|
||||
assert.match(rendered, /<img src=x onerror="alert\(1\)">/);
|
||||
assert.doesNotMatch(rendered, /action="\/clear-processing"/);
|
||||
assert.doesNotMatch(rendered, /data-job-id="id" onmouseover=/);
|
||||
assert.match(rendered, /data-job-id="id" onmouseover="alert\(2\)"/);
|
||||
assert.match(rendered, /Source unavailable/);
|
||||
assert.match(rendered, /Series 42 · Episode 2 · English sub/);
|
||||
assert.match(rendered, /href="https:\/\/proxer\.me\/watch\/42\/2\/engsub" target="_blank" rel="noopener noreferrer"/);
|
||||
assert.match(rendered, /<script src="\/status\.js" defer><\/script>/);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+44
-7
@@ -7,6 +7,7 @@ const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { executeJob, processClaimedJob, claimNextJob, RESULT_PREFIX } = require('../queue_worker');
|
||||
const { LOG_LIMIT } = require('../lib/logging');
|
||||
const { createWorkerIdentity } = require('../lib/workerIdentity');
|
||||
|
||||
const now = new Date('2026-01-01T12:00:00.000Z');
|
||||
const successfulResult = `${RESULT_PREFIX}${JSON.stringify({ version: 1, status: 'completed' })}\n`;
|
||||
@@ -14,6 +15,10 @@ const makeJob = (changes = {}) => ({
|
||||
_id: 'fixture-job', filename: 'Fixture Episode', url: 'https://proxer.me/watch/42/1/engsub',
|
||||
token: 'fixture_cookie=fixture-secret==', created_at: now, processing: true, ...changes,
|
||||
});
|
||||
const workerIdentity = createWorkerIdentity({
|
||||
env: { name: 'proxer-worker-7' }, pid: 12345, host: 'download-host', now: () => now,
|
||||
uuid: () => '7b3c9e3a-8b0b-41c6-988c-8e9e01dbbf4a',
|
||||
});
|
||||
|
||||
async function temporarySettings(t) {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), 'proxer-worker-'));
|
||||
@@ -267,7 +272,7 @@ test('the final pause gate releases a never-started claim without history or del
|
||||
assert.equal(result.errorCategory, 'paused');
|
||||
assert.equal(spawns, 0);
|
||||
assert.deepEqual(operations, [{ collection: 'queue', method: 'updateOne',
|
||||
args: [{ _id: 'fixture-job', processing: true }, { $unset: { processing: '', started_at: '' } }],
|
||||
args: [{ _id: 'fixture-job', processing: true }, { $unset: { processing: '', started_at: '', worker: '' } }],
|
||||
}]);
|
||||
});
|
||||
|
||||
@@ -449,7 +454,7 @@ test('authentication and resolution pause the pool before history and preserve t
|
||||
assert.doesNotMatch(operations[1].args[0].output_log, /fixture-secret/);
|
||||
assert.equal(operations[1].args[0].token, undefined);
|
||||
assert.deepEqual(operations[2].args, [
|
||||
{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '' } },
|
||||
{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '', worker: '' } },
|
||||
]);
|
||||
assert.equal(job.token, 'fixture_cookie=fixture-secret==');
|
||||
}
|
||||
@@ -496,6 +501,7 @@ test('unacknowledged attention writes halt without consuming the request', async
|
||||
|
||||
function claimDatabase({ pauseReads = [false, false], readFailureAt = -1, afterClaim = () => {} } = {}) {
|
||||
const operations = [];
|
||||
const claims = [];
|
||||
let readCount = 0;
|
||||
const job = makeJob();
|
||||
const db = { collection(name) {
|
||||
@@ -507,18 +513,49 @@ function claimDatabase({ pauseReads = [false, false], readFailureAt = -1, afterC
|
||||
} };
|
||||
assert.equal(name, 'queue');
|
||||
return {
|
||||
findOneAndUpdate: async () => { operations.push('queue.claim'); afterClaim(); return job; },
|
||||
findOneAndUpdate: async (...args) => { operations.push('queue.claim'); claims.push(args); afterClaim(); return job; },
|
||||
updateOne: async (filter, update) => {
|
||||
operations.push('queue.release');
|
||||
assert.deepEqual(filter, { _id: job._id, processing: true });
|
||||
assert.deepEqual(update, { $unset: { processing: '', started_at: '' } });
|
||||
assert.deepEqual(update, { $unset: { processing: '', started_at: '', worker: '' } });
|
||||
return { acknowledged: true };
|
||||
},
|
||||
};
|
||||
} };
|
||||
return { db, operations, job };
|
||||
return { db, operations, job, claims };
|
||||
}
|
||||
|
||||
test('a worker identity is recorded in the atomic claim alongside its start time', async () => {
|
||||
const fixture = claimDatabase();
|
||||
await claimNextJob(fixture.db, { workerIdentity: { ...workerIdentity, token: 'must-not-be-copied' }, now: () => now });
|
||||
assert.deepEqual(fixture.claims, [[
|
||||
{ processing: { $ne: true } },
|
||||
{ $set: { processing: true, started_at: now, worker: workerIdentity } },
|
||||
{ sort: { created_at: 1 }, returnDocument: 'after' },
|
||||
]]);
|
||||
});
|
||||
|
||||
test('a claim without valid identity cannot retain stale worker telemetry from an earlier attempt', async () => {
|
||||
const fixture = claimDatabase();
|
||||
await claimNextJob(fixture.db, { workerIdentity: { ...workerIdentity, pid: '12345' }, now: () => now });
|
||||
assert.deepEqual(fixture.claims[0][1], {
|
||||
$set: { processing: true, started_at: now }, $unset: { worker: '' },
|
||||
});
|
||||
});
|
||||
|
||||
test('history retains only validated worker metadata without changing claim transitions', async () => {
|
||||
for (const ok of [true, false]) {
|
||||
const { db, operations } = recordingDatabase();
|
||||
await processClaimedJob(makeJob({ worker: { ...workerIdentity, token: 'private-worker-data' } }), {
|
||||
db, execute: async () => ({ ok, exitCode: ok ? 0 : 1, errorCategory: 'resolution', output: 'fixture' }),
|
||||
});
|
||||
const history = operations.find(entry => entry.method === 'insertOne').args[0];
|
||||
assert.deepEqual(history.worker, workerIdentity);
|
||||
assert.doesNotMatch(JSON.stringify(history), /private-worker-data/);
|
||||
if (!ok) assert.deepEqual(operations.at(-1).args[1], { $unset: { processing: '', started_at: '', worker: '' } });
|
||||
}
|
||||
});
|
||||
|
||||
test('a paused pool does not claim a new job', async () => {
|
||||
const fixture = claimDatabase({ pauseReads: [true] });
|
||||
assert.equal(await claimNextJob(fixture.db), null);
|
||||
@@ -567,7 +604,7 @@ test('interrupted jobs release only their own claim without creating history or
|
||||
assert.equal(result.errorCategory, 'interrupted');
|
||||
assert.deepEqual(operations, [{
|
||||
collection: 'queue', method: 'updateOne',
|
||||
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '' } }],
|
||||
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '', worker: '' } }],
|
||||
}]);
|
||||
});
|
||||
|
||||
@@ -580,7 +617,7 @@ test('infrastructure failures preserve the request, release its claim, and rejec
|
||||
}) }), /infrastructure is unavailable.*remains queued/);
|
||||
assert.deepEqual(operations, [{
|
||||
collection: 'queue', method: 'updateOne',
|
||||
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '' } }],
|
||||
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '', worker: '' } }],
|
||||
}]);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,294 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { startWorkerPage, validWorkerName, boundedLog, MAX_VISIBLE_LOG_BYTES } = require('../public/workers');
|
||||
|
||||
class Element {
|
||||
constructor(tag = 'div') {
|
||||
this.tagName = tag;
|
||||
this.className = '';
|
||||
this.children = [];
|
||||
this.dataset = {};
|
||||
this.attributes = {};
|
||||
this.listeners = {};
|
||||
this.textContent = '';
|
||||
this.value = '';
|
||||
this.hidden = this.disabled = false;
|
||||
this.scrollTop = this.scrollHeight = this.clientHeight = 0;
|
||||
this.classList = { toggle: (name, enabled) => {
|
||||
const names = new Set(this.className.split(' ').filter(Boolean));
|
||||
if (enabled) names.add(name); else names.delete(name);
|
||||
this.className = [...names].join(' ');
|
||||
} };
|
||||
}
|
||||
set innerHTML(_value) { assert.fail('Worker data must never be written as HTML.'); }
|
||||
addEventListener(type, listener) { (this.listeners[type] ||= []).push(listener); }
|
||||
async dispatch(type, values = {}) {
|
||||
for (const listener of this.listeners[type] || []) await listener({ preventDefault() {}, ...values });
|
||||
}
|
||||
setAttribute(name, value) { this.attributes[name] = String(value); }
|
||||
setCustomValidity(value) { this.validationMessage = value; }
|
||||
append(...nodes) {
|
||||
for (const node of nodes) { node.parentElement = this; this.children.push(node); }
|
||||
}
|
||||
remove() {
|
||||
if (this.parentElement) this.parentElement.children = this.parentElement.children.filter(node => node !== this);
|
||||
this.parentElement = null;
|
||||
}
|
||||
querySelectorAll(selector) {
|
||||
const matches = node => selector.startsWith('.')
|
||||
? node.className.split(' ').includes(selector.slice(1))
|
||||
: Object.hasOwn(node.dataset, selector.slice(6, -1).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()));
|
||||
return this.children.flatMap(node => [...(matches(node) ? [node] : []), ...node.querySelectorAll(selector)]);
|
||||
}
|
||||
querySelector(selector) { return this.querySelectorAll(selector)[0] || null; }
|
||||
}
|
||||
|
||||
const worker = (name = 'proxer-worker-1', pm_id = '0') => ({
|
||||
name, pm_id, pid: '122', status: 'online', cpu: '1.2%', memoryMB: '40 MB', uptime: '5m', execPath: '/fixture/queue_worker.js',
|
||||
});
|
||||
|
||||
function fixture(initial = [worker()]) {
|
||||
const nodes = new Map();
|
||||
const get = id => {
|
||||
if (!nodes.has(id)) nodes.set(id, new Element());
|
||||
return nodes.get(id);
|
||||
};
|
||||
const document = new Element();
|
||||
document.hidden = false;
|
||||
document.getElementById = get;
|
||||
document.createElement = tag => new Element(tag);
|
||||
get('follow-logs').checked = true;
|
||||
get('create-worker-form').reportValidity = () => !get('worker-name').validationMessage;
|
||||
const sockets = [];
|
||||
class BrowserSocket extends Element {
|
||||
static OPEN = 1;
|
||||
constructor(url) { super(); this.url = url; this.readyState = 0; this.sent = []; sockets.push(this); }
|
||||
send(value) { assert.equal(this.readyState, 1, 'Never send on a connecting/closed socket.'); this.sent.push(JSON.parse(value)); }
|
||||
close() { this.readyState = 3; this.closed = true; this.dispatch('close'); }
|
||||
async open() { this.readyState = 1; await this.dispatch('open'); }
|
||||
async message(payload) { await this.dispatch('message', { data: JSON.stringify(payload) }); }
|
||||
}
|
||||
const window = new Element();
|
||||
let reloads = 0;
|
||||
window.location = { protocol: 'https:', host: 'fixture.invalid', reload: () => reloads++ };
|
||||
window.confirmations = [];
|
||||
window.allowConfirm = true;
|
||||
window.confirm = message => { window.confirmations.push(message); return window.allowConfirm; };
|
||||
const requests = [];
|
||||
const timers = new Map();
|
||||
let nextTimer = 1;
|
||||
const state = { workers: initial, handler: null };
|
||||
const response = result => ({ ok: true, json: async () => result });
|
||||
const page = startWorkerPage({
|
||||
document, window, WebSocket: BrowserSocket, AbortController,
|
||||
setTimeout: (callback, delay) => { const id = nextTimer++; timers.set(id, { callback, delay }); return id; },
|
||||
clearTimeout: id => timers.delete(id),
|
||||
fetch: async (url, options) => {
|
||||
requests.push({ url, options });
|
||||
if (state.handler) return state.handler(url, options);
|
||||
return response(url === '/pm2/list-json' ? { ok: true, processes: state.workers } : { ok: true });
|
||||
},
|
||||
});
|
||||
return { page, get, state, document, window, requests, sockets, timers, response, reloads: () => reloads };
|
||||
}
|
||||
|
||||
test('worker logs enforce a 64 KiB UTF-8 bound without splitting Unicode text', () => {
|
||||
const result = boundedLog('🚀漢字'.repeat(30_000) + '\nLATEST LINE');
|
||||
assert.ok(Buffer.byteLength(result, 'utf8') <= MAX_VISIBLE_LOG_BYTES);
|
||||
assert.match(result, /^\[Earlier log output omitted\]/);
|
||||
assert.ok(result.endsWith('\nLATEST LINE'));
|
||||
assert.doesNotMatch(result, /\uFFFD/);
|
||||
assert.equal(boundedLog('short output'), 'short output');
|
||||
});
|
||||
|
||||
test('worker form name rules match managed command restrictions', () => {
|
||||
for (const name of ['worker-1', '2_worker', 'a'.repeat(64)]) assert.equal(validWorkerName(name), true);
|
||||
for (const name of ['', 'all', 'ALL', '-worker', 'a/b', 'worker name', '<img>', 'a'.repeat(65)]) {
|
||||
assert.equal(validWorkerName(name), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('worker refresh preserves row identity and selection while rendering unsafe fields only as text', async () => {
|
||||
const f = fixture([worker(), { ...worker('<img onerror=attack>', '2'), status: '<b>offline</b>' }]);
|
||||
await f.page.refreshList();
|
||||
const row = f.get('process-list').querySelectorAll('.worker-row')[0];
|
||||
const unsafe = f.get('process-list').querySelectorAll('.worker-row')[1];
|
||||
assert.equal(unsafe.querySelector('.worker-name').textContent, '<img onerror=attack>');
|
||||
assert.equal(unsafe.querySelector('[data-worker-status]').textContent, '<b>offline</b>');
|
||||
assert.equal(unsafe.disabled, true);
|
||||
await row.dispatch('click');
|
||||
assert.equal(f.sockets.length, 1);
|
||||
f.state.workers = [{ ...worker(), cpu: '5.1%', execPath: '<script>ignored</script>' }];
|
||||
await f.page.refreshList();
|
||||
assert.equal(f.get('process-list').querySelectorAll('.worker-row')[0], row);
|
||||
assert.equal(row.attributes['aria-pressed'], 'true');
|
||||
assert.equal(f.get('detail-cpu').textContent, '5.1%');
|
||||
assert.equal(f.get('detail-exec').textContent, '<script>ignored</script>');
|
||||
assert.equal(f.sockets.length, 1, 'Polling must not reconnect the selected log stream.');
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('log selection waits for connection readiness, rejects stale streams and closes on deselect', async () => {
|
||||
const f = fixture([worker(), worker('proxer-worker-2', '1')]);
|
||||
await f.page.refreshList();
|
||||
f.page.selectWorker('0:proxer-worker-1');
|
||||
const first = f.sockets[0];
|
||||
assert.equal(first.url, 'wss://fixture.invalid');
|
||||
assert.equal(first.sent.length, 0);
|
||||
await first.open();
|
||||
assert.deepEqual(first.sent, [{ type: 'logs', name: 'proxer-worker-1' }]);
|
||||
f.page.selectWorker('1:proxer-worker-2');
|
||||
assert.equal(first.closed, true);
|
||||
assert.deepEqual(first.sent.at(-1), { type: 'stop-logs' });
|
||||
await first.message({ type: 'stdout', data: 'STALE WORKER OUTPUT' });
|
||||
assert.doesNotMatch(f.get('logs').textContent, /STALE/);
|
||||
const second = f.sockets[1];
|
||||
await second.open();
|
||||
await second.message({ type: 'stdout', data: '<img onerror=attack>' });
|
||||
assert.match(f.get('logs').textContent, /<img onerror=attack>/);
|
||||
f.page.clearSelection();
|
||||
assert.deepEqual(second.sent.at(-1), { type: 'stop-logs' });
|
||||
assert.equal(second.closed, true);
|
||||
assert.equal(f.get('control-centre').hidden, true);
|
||||
assert.equal(f.get('reconnect-logs').disabled, true);
|
||||
await second.message({ type: 'stderr', data: 'LATE PACKET' });
|
||||
assert.doesNotMatch(f.get('logs').textContent, /LATE/);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('concurrent list reads coalesce and commands wait for older reads before refreshing', async () => {
|
||||
const f = fixture();
|
||||
let resolveFirst;
|
||||
const firstRead = new Promise(resolve => { resolveFirst = resolve; });
|
||||
let reads = 0;
|
||||
f.state.handler = (url, options) => {
|
||||
if (url === '/pm2/list-json') {
|
||||
reads++;
|
||||
return reads === 1 ? firstRead : f.response({ ok: true, processes: [{ ...worker(), status: 'stopped' }] });
|
||||
}
|
||||
assert.deepEqual(JSON.parse(options.body), { cmd: 'stop', name: 'proxer-worker-1' });
|
||||
return f.response({ ok: true });
|
||||
};
|
||||
const a = f.page.refreshList();
|
||||
assert.equal(f.page.refreshList(), a);
|
||||
const command = f.page.execCommand('stop', 'proxer-worker-1');
|
||||
assert.equal(await f.page.execCommand('stop', 'proxer-worker-1'), false, 'Duplicate commands must not be sent.');
|
||||
assert.equal(f.get('btn-create').disabled, true);
|
||||
assert.equal(f.get('btn-quick-add').disabled, true);
|
||||
assert.equal(f.requests.length, 1);
|
||||
resolveFirst(f.response({ ok: true, processes: [worker()] }));
|
||||
assert.equal(await command, true);
|
||||
assert.deepEqual(f.requests.map(request => request.url), ['/pm2/list-json', '/pm2/command', '/pm2/list-json']);
|
||||
assert.equal(f.get('btn-create').disabled, false);
|
||||
assert.equal(f.get('btn-quick-add').disabled, false);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('destructive worker controls honor cancellation and name validation blocks reserved names', async () => {
|
||||
const f = fixture();
|
||||
await f.page.refreshList();
|
||||
f.page.selectWorker('0:proxer-worker-1');
|
||||
f.window.allowConfirm = false;
|
||||
for (const action of ['stop', 'restart', 'delete']) await f.get(`btn-${action}`).dispatch('click');
|
||||
assert.equal(f.requests.filter(request => request.url === '/pm2/command').length, 0);
|
||||
assert.equal(f.window.confirmations.length, 3);
|
||||
assert.ok(f.window.confirmations.every(message => /interrupt/i.test(message)));
|
||||
f.get('worker-name').value = 'all';
|
||||
await f.get('create-worker-form').dispatch('submit');
|
||||
assert.match(f.get('worker-name').validationMessage, /reserved/);
|
||||
assert.equal(f.requests.filter(request => request.url === '/pm2/command').length, 0);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('named worker creation submits only managed inputs and selects the returned worker', async () => {
|
||||
const f = fixture([]);
|
||||
f.state.handler = (url, options) => {
|
||||
if (url === '/pm2/command') {
|
||||
assert.deepEqual(JSON.parse(options.body), { cmd: 'create', name: 'media-worker-3' });
|
||||
f.state.workers = [worker('media-worker-3', '3')];
|
||||
return f.response({ ok: true });
|
||||
}
|
||||
return f.response({ ok: true, processes: f.state.workers });
|
||||
};
|
||||
f.get('worker-name').value = ' media-worker-3 ';
|
||||
await f.get('create-worker-form').dispatch('submit');
|
||||
assert.equal(f.get('cc-name').textContent, 'media-worker-3');
|
||||
assert.equal(f.get('worker-name').value, '');
|
||||
assert.equal(f.get('control-centre').hidden, false);
|
||||
assert.equal(f.sockets.length, 1);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('quick add sends no client-selected name and selects the server-assigned worker', async () => {
|
||||
const f = fixture([]);
|
||||
f.get('worker-name').value = 'unfinished-custom-name';
|
||||
f.state.handler = (url, options) => {
|
||||
if (url === '/pm2/quick-add') {
|
||||
assert.equal(options.method, 'POST');
|
||||
assert.deepEqual(JSON.parse(options.body), {});
|
||||
f.state.workers = [worker('proxer-worker-14', '12')];
|
||||
return f.response({ ok: true, name: 'proxer-worker-14' });
|
||||
}
|
||||
assert.equal(url, '/pm2/list-json');
|
||||
return f.response({ ok: true, processes: f.state.workers });
|
||||
};
|
||||
await f.get('btn-quick-add').dispatch('click');
|
||||
assert.equal(f.get('cc-name').textContent, 'proxer-worker-14');
|
||||
assert.equal(f.get('control-centre').hidden, false);
|
||||
assert.equal(f.get('worker-name').value, 'unfinished-custom-name');
|
||||
assert.match(f.get('control-output').textContent, /proxer-worker-14 was created and started/);
|
||||
assert.equal(f.sockets.length, 1);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('quick add shares the command lock and refuses to invent a name from an invalid response', async () => {
|
||||
const f = fixture([]);
|
||||
let resolveCreation;
|
||||
const pending = new Promise(resolve => { resolveCreation = resolve; });
|
||||
f.state.handler = url => url === '/pm2/quick-add' ? pending : f.response({ ok: true, processes: [] });
|
||||
const creation = f.page.execCommand('quick-add');
|
||||
assert.equal(f.get('btn-quick-add').disabled, true);
|
||||
assert.equal(await f.page.execCommand('quick-add'), false);
|
||||
assert.equal(await f.page.execCommand('create', 'another-worker'), false);
|
||||
resolveCreation(f.response({ ok: true, name: '<script>bad response</script>' }));
|
||||
assert.equal(await creation, false);
|
||||
assert.equal(f.get('btn-quick-add').disabled, false);
|
||||
assert.equal(f.get('control-centre').hidden, true);
|
||||
assert.match(f.get('control-output').textContent, /name could not be confirmed/);
|
||||
assert.equal(f.requests.filter(request => request.url === '/pm2/quick-add').length, 1);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('failed refresh and uncertain commands keep their last state and show distinct feedback', async () => {
|
||||
const f = fixture();
|
||||
await f.page.refreshList();
|
||||
const row = f.get('process-list').querySelector('.worker-row');
|
||||
f.state.handler = () => { throw new Error('offline'); };
|
||||
assert.equal(await f.page.refreshList(), false);
|
||||
assert.equal(f.get('process-list').querySelector('.worker-row'), row);
|
||||
assert.match(f.get('worker-refresh-state').textContent, /last available list/);
|
||||
assert.equal(await f.page.execCommand('restart', 'proxer-worker-1'), false);
|
||||
assert.match(f.get('control-output').textContent, /Could not confirm.*Refresh the worker list/);
|
||||
assert.equal(f.get('btn-create').disabled, false);
|
||||
f.page.dispose();
|
||||
});
|
||||
|
||||
test('worker polling pauses in hidden pages and page lifecycle cleans up and recovers on browser back', async () => {
|
||||
const f = fixture();
|
||||
assert.equal(f.timers.size, 1);
|
||||
f.document.hidden = true;
|
||||
await f.document.dispatch('visibilitychange');
|
||||
assert.equal(f.timers.size, 0);
|
||||
f.document.hidden = false;
|
||||
await f.document.dispatch('visibilitychange');
|
||||
await f.page.refreshList();
|
||||
f.page.selectWorker('0:proxer-worker-1');
|
||||
await f.sockets[0].open();
|
||||
await f.window.dispatch('pagehide');
|
||||
assert.equal(f.timers.size, 0);
|
||||
assert.equal(f.sockets[0].closed, true);
|
||||
await f.window.dispatch('pageshow', { persisted: true });
|
||||
assert.equal(f.reloads(), 1);
|
||||
});
|
||||
Reference in new issue
Block a user