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 vm = require("node:vm");
const ejs = require("ejs");
const {
ValidationError, normalizeWatchUrl, normalizeFilename, validateOutputTarget,
cookieToken, buildQueueJobs, sanitizeLog, toPublicJob, MAX_LOG_BYTES,
} = require("../lib/jobValidation");
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, "..");
const sourceUrl = "https://proxer.me/watch/42/2/engsub";
async function temporaryConfig(t, extra = {}) {
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-web-"));
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
return { outputDir, tokenPrefix: "fixture_cookie=", maxSeriesEpisodes: 500, ...extra };
}
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 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-"))) {
const jobs = await buildQueueJobs({
...fixture.input, mode: fixture.entrypoint.slice(4), token: "fixture-value==",
}, config);
assert.deepEqual(jobs.map(job => job.filename), fixture.expectedFilenames);
assert.ok(jobs.every(job => job.token === "fixture_cookie=fixture-value=="));
}
});
test("video form title is honored and explicit legacy filename takes priority", async t => {
const config = await temporaryConfig(t);
const body = { mode: "video", url: sourceUrl, name: "My video title", token: "fixture" };
assert.equal((await buildQueueJobs(body, config))[0].filename, "My video title");
assert.equal((await buildQueueJobs({ ...body, filename: "Legacy filename" }, config))[0].filename, "Legacy filename");
});
test("URL validation accepts only canonical Proxer episode sources", () => {
assert.equal(normalizeWatchUrl("https://www.proxer.me:443/watch/42/2/engsub/#player").url, sourceUrl);
const invalid = [
"http://proxer.me/watch/42/2/engsub", "https://proxer.me.evil.test/watch/42/2/engsub",
"https://127.0.0.1/watch/42/2/engsub", "file:///watch/42/2/engsub",
"https://user:pass@proxer.me/watch/42/2/engsub", "https://@proxer.me/watch/42/2/engsub",
"https://proxer.me:8443/watch/42/2/engsub", `${sourceUrl}?token=secret`,
"https://proxer.me/watch/42/0/engsub", "https://proxer.me/watch/42/2/invalid",
"https://proxer.me/watch/9007199254740992/2/engsub", "https://proxer.me/watch/42/2/engsub\n",
"https://proxer.me\\watch\\42\\2\\engsub",
];
for (const value of invalid) assert.throws(() => normalizeWatchUrl(value), ValidationError, value);
});
test("series requests reject partial integers, unsupported languages and oversized ranges", async t => {
const config = await temporaryConfig(t, { maxSeriesEpisodes: 3 });
const body = { mode: "series", id: "42", episode_from: "1", episode_to: "3", language: "gerdub", token: "fixture" };
assert.equal((await buildQueueJobs(body, config)).length, 3);
for (const change of [
{ id: "42junk" }, { episode_from: "1.5" }, { episode_to: "4" },
{ episode_from: "3", episode_to: "2" }, { language: "unsupported" },
{ episode_to: "9007199254740992" }, { id: ["42"] },
]) {
await assert.rejects(buildQueueJobs({ ...body, ...change }, config), ValidationError);
}
});
test("filename containment rejects traversal, control characters and symlink destinations", async t => {
const config = await temporaryConfig(t);
for (const filename of ["../escape", "sub/name", "sub\\name", "..", ".", "", " name", "name ", "bad\u0000name", "bad\nname", "ü".repeat(126)]) {
assert.throws(() => normalizeFilename(filename), ValidationError, filename);
}
await fs.writeFile(path.join(config.outputDir, "existing.mp4"), "fixture bytes");
assert.equal(await validateOutputTarget(config.outputDir, "existing"), path.join(config.outputDir, "existing.mp4"));
await fs.symlink(path.join(config.outputDir, "existing.mp4"), path.join(config.outputDir, "link.mp4"));
await assert.rejects(validateOutputTarget(config.outputDir, "link"), ValidationError);
await fs.mkdir(path.join(config.outputDir, "directory.mp4"));
await assert.rejects(validateOutputTarget(config.outputDir, "directory"), ValidationError);
});
test("cookie tokens preserve equals signs and reject injected cookie separators", () => {
assert.equal(cookieToken("base64-like==", "session="), "session=base64-like==");
for (const token of ["", "with space", "foo;other=bar", "foo\nbar", "a".repeat(8192), "ü".repeat(4096), ["array"]]) {
assert.throws(() => cookieToken(token, "session="), ValidationError);
}
assert.throws(() => cookieToken("fixture", undefined), /TOKEN_PREFIX/);
assert.throws(() => cookieToken("fixture", "invalid=prefix="), /TOKEN_PREFIX/);
});
test("filename, source URL and cookie validation reject C1 controls consistently", () => {
for (const control of ["\u0080", "\u0085"]) {
assert.throws(() => normalizeFilename(`file${control}name`), ValidationError);
assert.throws(() => normalizeWatchUrl(`${sourceUrl}#player${control}`), ValidationError);
assert.throws(() => cookieToken(`value${control}padding==`, "session="), ValidationError);
}
});
test("malformed Unicode is rejected before queue serialization while valid surrogate pairs remain intact", async t => {
const config = await temporaryConfig(t);
for (const malformed of ["\uD800", "\uDC00", "\uD800x", "\uDC00\uD800"]) {
assert.throws(() => normalizeFilename(`file${malformed}name`), ValidationError);
assert.throws(() => normalizeWatchUrl(`${sourceUrl}#${malformed}`), ValidationError);
assert.throws(() => cookieToken(`value${malformed}==`, "session="), ValidationError);
await assert.rejects(buildQueueJobs({
mode: "video", url: sourceUrl, name: malformed, token: "fixture",
}, config), ValidationError);
}
const validName = "Episode \uD83C\uDFAC";
assert.equal(normalizeFilename(validName), validName);
assert.equal(normalizeWatchUrl(`${sourceUrl}#\uD83C\uDFAC`).url, sourceUrl);
assert.equal(cookieToken("valid-\uD83C\uDFAC==", "session="), "session=valid-\uD83C\uDFAC==");
assert.equal((await buildQueueJobs({ mode: "video", url: sourceUrl, name: validName, token: "fixture" }, config))[0].filename, validName);
});
test("invalid submissions do not connect or insert, and failure responses never show stacks or tokens", async t => {
const config = await temporaryConfig(t);
let calls = 0;
const controller = createQueueController({ config, getDb: async () => { calls += 1; throw new Error("database fixture secret"); } });
const bad = response();
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/);
const unavailable = response();
await controller.enqueue({ body: { mode: "video", url: sourceUrl, token: "fixture-secret" } }, unavailable);
assert.equal(unavailable.statusCode, 500);
assert.equal(calls, 1);
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 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 { 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?state=queued&added=2");
assert.deepEqual(inserted.map(operation => operation.insertOne.document.filename), ["SeriesE09_engdub", "SeriesE10_engdub"]);
});
test("processing reset is rejected without reading or mutating the database", () => {
const controller = createQueueController({ getDb: () => { throw new Error("must not be called"); } });
const result = response();
controller.clearProcessing({}, result);
assert.equal(result.statusCode, 409);
assert.match(result.data.message, /cannot be cleared safely/);
});
test("public job DTOs and log tails remove credentials, private fields and signed URLs", () => {
const result = toPublicJob({
_id: "fixture-id", filename: "Example", token: "session=fixture-value==",
url: `${sourceUrl}#token=fragment-secret`, raw: { env: { SECRET: "secret" } },
created_at: "2026-01-01T00:00:00Z",
output_log: "session=fixture-value== token=another-secret https://media.test/video.mp4?token=signed-secret\nCookie: private_session=value",
});
assert.equal(result.url, sourceUrl);
assert.equal(result.created_at, "2026-01-01T00:00:00.000Z");
assert.equal(result.token, undefined);
assert.equal(result.raw, undefined);
assert.doesNotMatch(JSON.stringify(result), /fixture-value|another-secret|signed-secret|fragment-secret|private_session/);
const bounded = sanitizeLog("x".repeat(MAX_LOG_BYTES * 3) + "LAST LINE");
assert.ok(Buffer.byteLength(bounded) < MAX_LOG_BYTES + 100);
assert.ok(bounded.endsWith("LAST LINE"));
});
test("status endpoints use projections, exclude secret settings and refuse symlink file-size reads", async t => {
const config = await temporaryConfig(t);
await fs.writeFile(path.join(config.outputDir, "target.mp4"), "fixture");
await fs.symlink(path.join(config.outputDir, "target.mp4"), path.join(config.outputDir, "link.mp4"));
const database = { collection(name) {
if (name === "settings") return { findOne: async (_filter, options) => {
assert.deepEqual(options.projection, { captcha_blocked: 1, pause_reason: 1 });
return { captcha_blocked: true, secret: "settings-secret" };
} };
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 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({ 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.items[0].fileSize, null);
assert.doesNotMatch(JSON.stringify(result.data), /fixture-secret|settings-secret|private_field/);
});
test("projected queued and history logs redact known cookies without exposing them in JSON or view models", async t => {
const config = await temporaryConfig(t);
const groups = ["queued", "processing", "done", "failed"];
const records = Object.fromEntries(groups.map(group => {
const token = `custom_cookie=${group}-exact-credential==`;
return [group, {
_id: group, filename: `Fixture ${group}`, url: sourceUrl, token,
output_log: `Captured ${token}\nUnlabelled ${group}-exact-credential==`,
private_field: "must never reach the view",
}];
}));
const database = { collection(name) {
if (name === "settings") return { findOne: async () => ({ captcha_blocked: false }) };
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 paginatedCursor([projected]);
} };
} };
const controller = createQueueController({ config, getDb: async () => database });
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/);
}
}
});
test("public global status exposes only allowlisted pause reasons and resolution job errors", async t => {
const config = await temporaryConfig(t);
for (const reason of ["resolution", "authentication", "", undefined]) {
const database = { collection(name) {
if (name === "settings") return { findOne: async (_filter, { projection }) => {
assert.deepEqual(projection, { captcha_blocked: 1, pause_reason: 1 });
return { captcha_blocked: true, pause_reason: reason, token: "private-settings-token" };
} };
return { countDocuments: async () => 0, find() { return paginatedCursor([]); } };
} };
const controller = createQueueController({ config, getDb: async () => database });
for (const method of ["statusData", "status", "statusSummary"]) {
const result = response();
await controller[method]({}, result, error => { throw error; });
assert.deepEqual(result.data.global, {
captcha_blocked: true,
pause_reason: ["resolution", "authentication"].includes(reason) ? reason : null,
});
assert.doesNotMatch(JSON.stringify(result.data), /private reason|private-settings-token/);
}
}
const job = toPublicJob({ _id: "fixture", filename: "Episode", error_category: "resolution", token: "hidden" });
assert.equal(job.error_category, "resolution");
assert.equal(Object.hasOwn(job, "token"), false);
});
test("resume clears both the existing global pause flag and its reason before redirecting", async () => {
const operations = [];
const controller = createQueueController({ getDb: async () => ({ collection(name) {
assert.equal(name, "settings");
return { updateOne: async (...args) => { operations.push(args); } };
} }) });
const result = response();
await controller.clearCaptcha({}, result, error => { throw error; });
assert.deepEqual(operations, [[
{ _id: "global" }, { $set: { captcha_blocked: false }, $unset: { pause_reason: "" } },
]]);
assert.equal(result.location, "/status");
});
test("verification banner 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(/([\s\S]*?)<\/span>/)[1];
assert.match(message, /video link could not be resolved/);
assert.match(message, /Possible causes include CAPTCHA or login verification, an unavailable video, or a source change/);
assert.match(rendered, /Resume after verification/);
assert.doesNotMatch(message, /CAPTCHA triggered|CAPTCHA confirmed/);
assert.match(rendered, /