Files
Proxer-Downloader/tests/token-controller.test.js
2026-10-23 18:19:44 +02:00

330 lines
17 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 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);
});