Files
2026-10-23 18:19:44 +02:00

311 lines
16 KiB
JavaScript

"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);
}
});