358 lines
19 KiB
JavaScript
358 lines
19 KiB
JavaScript
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 } = require("../controllers/queueController");
|
|
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; },
|
|
};
|
|
}
|
|
|
|
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.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 existing status URL", 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; } };
|
|
} }) });
|
|
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.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 { 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
|
|
? [{ _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; });
|
|
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.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 { 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]; } };
|
|
} };
|
|
} };
|
|
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];
|
|
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", "<script>private reason</script>", undefined]) {
|
|
const database = { collection(name) {
|
|
if (name === "settings") return { findOne: async (_filter, { projection }) => {
|
|
assert.deepEqual(projection, { captcha_blocked: 1, pause_reason: 1 });
|
|
return { captcha_blocked: true, pause_reason: reason, token: "private-settings-token" };
|
|
} };
|
|
return { find() { return { sort() { return this; }, async toArray() { return []; } }; } };
|
|
} };
|
|
const controller = createQueueController({ config, getDb: async () => database });
|
|
for (const method of ["statusData", "status"]) {
|
|
const result = response();
|
|
await controller[method]({}, result, error => { throw error; });
|
|
assert.deepEqual(result.data.global, {
|
|
captcha_blocked: true,
|
|
pause_reason: ["resolution", "authentication"].includes(reason) ? reason : null,
|
|
});
|
|
assert.doesNotMatch(JSON.stringify(result.data), /private reason|private-settings-token/);
|
|
}
|
|
}
|
|
const job = toPublicJob({ _id: "fixture", filename: "Episode", error_category: "resolution", token: "hidden" });
|
|
assert.equal(job.error_category, "resolution");
|
|
assert.equal(Object.hasOwn(job, "token"), false);
|
|
});
|
|
|
|
test("resume clears both the existing global pause flag and its reason before redirecting", async () => {
|
|
const operations = [];
|
|
const controller = createQueueController({ getDb: async () => ({ collection(name) {
|
|
assert.equal(name, "settings");
|
|
return { updateOne: async (...args) => { operations.push(args); } };
|
|
} }) });
|
|
const result = response();
|
|
await controller.clearCaptcha({}, result, error => { throw error; });
|
|
assert.deepEqual(operations, [[
|
|
{ _id: "global" }, { $set: { captcha_blocked: false }, $unset: { pause_reason: "" } },
|
|
]]);
|
|
assert.equal(result.location, "/status");
|
|
});
|
|
|
|
test("verification banner distinguishes resolution failures without claiming a confirmed CAPTCHA", async () => {
|
|
const header = path.join(repository, "views/partials/header.ejs");
|
|
const rendered = await ejs.renderFile(header, { global: { captcha_blocked: true, pause_reason: "resolution" } });
|
|
const message = rendered.match(/<span id="captcha-message">([\s\S]*?)<\/span>/)[1];
|
|
assert.match(message, /video link could not be resolved/);
|
|
assert.match(message, /Possible causes include CAPTCHA or login verification, an unavailable video, or a source change/);
|
|
assert.match(rendered, /Resume after verification/);
|
|
assert.doesNotMatch(message, /CAPTCHA triggered|CAPTCHA confirmed/);
|
|
|
|
const script = [...rendered.matchAll(/<script>([\s\S]*?)<\/script>/g)][0][1];
|
|
const elements = { "captcha-alert": { style: {} }, "captcha-message": { textContent: "" } };
|
|
let globalState = { captcha_blocked: true, pause_reason: "resolution" };
|
|
const context = {
|
|
document: { getElementById: id => elements[id] },
|
|
fetch: async () => ({ json: async () => ({ global: globalState }) }),
|
|
setInterval: () => {}, console,
|
|
};
|
|
vm.createContext(context);
|
|
vm.runInContext(script, context);
|
|
await vm.runInContext("updateCaptchaAlert()", context);
|
|
assert.equal(elements["captcha-alert"].style.display, "block");
|
|
assert.match(elements["captcha-message"].textContent, /unavailable video/);
|
|
globalState = { captcha_blocked: true, pause_reason: "authentication" };
|
|
await vm.runInContext("updateCaptchaAlert()", context);
|
|
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);
|
|
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");
|
|
});
|
|
|
|
test("server-rendered and refreshed status escape HTML-like filenames, IDs and logs", 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=/);
|
|
}
|
|
});
|
|
|
|
test("error view renders without a details local and never exposes a supplied stack", async () => {
|
|
for (const data of [{ message: "A safe error" }, { message: "A safe error", details: "PRIVATE STACK" }]) {
|
|
const rendered = await ejs.renderFile(path.join(repository, "views/error.ejs"), data);
|
|
assert.match(rendered, /A safe error/);
|
|
assert.doesNotMatch(rendered, /PRIVATE STACK/);
|
|
}
|
|
});
|