phase 2 rework
This commit is contained in:
1 parent
20054198f3
commit
b397ea9256
44 files changed
+5528
-1377
No files matched your search
+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>/);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user