354 lines
19 KiB
JavaScript
354 lines
19 KiB
JavaScript
"use strict";
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert/strict");
|
|
const { createSessionTokenService, SessionTokenError, CACHE_ID, STATUS_PROJECTION } = require("../lib/sessionToken");
|
|
const { ValidationError } = require("../lib/jobValidation");
|
|
const { createProxerSessionProbe, classifyWatchResponse } = require("../lib/proxerSessionProbe");
|
|
|
|
const url = "https://proxer.me/watch/42/9/engsub";
|
|
const settings = { tokenPrefix: "fixture_cookie=" };
|
|
const checkedAt = new Date("2026-10-23T12:00:00.000Z");
|
|
const cookie = "fixture_cookie=NOT_A_REAL_COOKIE==";
|
|
const sourcePage = '<!doctype html><html><head><title>Episode - Proxer.Me</title></head><body><script>const stream={"code":"fixture_embed_id"};</script></body></html>';
|
|
|
|
function fixtureRecord(overrides = {}) {
|
|
return {
|
|
_id: CACHE_ID, cookie, cookie_name: "fixture_cookie", state: "ready", revision: "fixture-revision-1",
|
|
saved_at: new Date("2026-10-22T08:00:00Z"), validated_at: new Date("2026-10-22T08:00:00Z"), ...overrides,
|
|
};
|
|
}
|
|
|
|
function database(initial = null) {
|
|
let current = initial ? structuredClone(initial) : null;
|
|
const reads = [];
|
|
const writes = [];
|
|
const collection = {
|
|
async findOne(filter, options) {
|
|
reads.push({ filter: structuredClone(filter), options });
|
|
assert.deepEqual(filter, { _id: CACHE_ID });
|
|
assert.equal(options.maxTimeMS, 5000);
|
|
if (!current) return null;
|
|
return Object.fromEntries(Object.entries(current).filter(([key]) => key === "_id" || options.projection[key] === 1));
|
|
},
|
|
async updateOne(filter, update, options) {
|
|
writes.push({ filter: structuredClone(filter), update: structuredClone(update), options });
|
|
assert.equal(options.maxTimeMS, 5000);
|
|
const matches = current && (Object.hasOwn(filter.revision, "$eq")
|
|
? current.revision === filter.revision.$eq : !Object.hasOwn(current, "revision"));
|
|
if (current && !matches) {
|
|
if (options.upsert) throw Object.assign(new Error("duplicate key"), { code: 11000 });
|
|
return { acknowledged: true, matchedCount: 0, upsertedCount: 0 };
|
|
}
|
|
if (!current && !options.upsert) return { acknowledged: true, matchedCount: 0, upsertedCount: 0 };
|
|
const inserted = !current;
|
|
current ||= { _id: CACHE_ID };
|
|
Object.assign(current, structuredClone(update.$set));
|
|
for (const key of Object.keys(update.$unset || {})) delete current[key];
|
|
return { acknowledged: true, matchedCount: inserted ? 0 : 1, upsertedCount: inserted ? 1 : 0 };
|
|
},
|
|
};
|
|
return {
|
|
db: { collection(name) { assert.equal(name, "settings"); return collection; } },
|
|
reads, writes, collection,
|
|
current: () => structuredClone(current),
|
|
replace(value) { current = structuredClone(value); },
|
|
};
|
|
}
|
|
|
|
function service(store, overrides = {}) {
|
|
return createSessionTokenService({ getDb: async () => store.db, settings, now: () => checkedAt,
|
|
probe: async () => ({ state: "valid" }), ...overrides });
|
|
}
|
|
|
|
function expectedError(code, status) {
|
|
return error => {
|
|
assert.ok(error instanceof SessionTokenError);
|
|
assert.equal(error.code, code);
|
|
if (status) assert.equal(error.httpStatus, status);
|
|
assert.doesNotMatch(error.message, /NOT_A_REAL_|fixture_cookie|fixture_embed|PRIVATE/);
|
|
return true;
|
|
};
|
|
}
|
|
|
|
test("a supplied token is checked against the first canonical source before being cached", async () => {
|
|
const store = database();
|
|
const checks = [];
|
|
const tokens = service(store, { probe: async (...args) => {
|
|
checks.push(args);
|
|
assert.equal(store.current(), null, "the token must not be saved before verification");
|
|
return { state: "valid" };
|
|
} });
|
|
const result = await tokens.resolveForEnqueue("NOT_A_REAL_COOKIE==", { url });
|
|
assert.deepEqual(checks, [[cookie, { url }]]);
|
|
assert.equal(result.cookie, cookie);
|
|
assert.equal(result.source, "supplied");
|
|
assert.equal(result.status.available, true);
|
|
assert.equal(result.status.lastValidatedAt, checkedAt.toISOString());
|
|
assert.equal(store.current().cookie, cookie);
|
|
assert.equal(store.current().cookie_name, "fixture_cookie");
|
|
assert.equal(store.current().state, "ready");
|
|
assert.equal(Object.hasOwn(store.current(), "expires_at"), false);
|
|
assert.doesNotMatch(JSON.stringify(result.status), /NOT_A_REAL_|fixture_cookie/);
|
|
});
|
|
|
|
test("blank submissions reuse a saved token but validate it every time without a time-to-live shortcut", async () => {
|
|
const store = database(fixtureRecord({ saved_at: new Date("2000-01-01"), validated_at: new Date("2000-01-01") }));
|
|
let calls = 0;
|
|
const tokens = service(store, { probe: async (value, input) => {
|
|
assert.equal(value, cookie); assert.equal(input.url, url); calls++;
|
|
return { state: "valid" };
|
|
} });
|
|
for (const value of ["", undefined, null]) {
|
|
const result = await tokens.resolveForEnqueue(value, { url });
|
|
assert.equal(result.source, "cached");
|
|
assert.equal(result.cookie, cookie);
|
|
}
|
|
assert.equal(calls, 3);
|
|
assert.equal(store.current().validated_at.toISOString(), checkedAt.toISOString());
|
|
assert.equal(store.current().saved_at.toISOString(), "2000-01-01T00:00:00.000Z");
|
|
});
|
|
|
|
test("safe cache metadata never reads or exposes the cookie or revision", async () => {
|
|
const store = database(fixtureRecord({ PRIVATE_EXTRA: "PRIVATE_VALUE" }));
|
|
const status = await service(store).readStatus();
|
|
assert.deepEqual(status, { available: true, state: "saved", lastValidatedAt: "2026-10-22T08:00:00.000Z", savedAt: "2026-10-22T08:00:00.000Z" });
|
|
assert.deepEqual(store.reads[0].options.projection, STATUS_PROJECTION);
|
|
assert.equal(Object.hasOwn(STATUS_PROJECTION, "cookie"), false);
|
|
assert.equal(Object.hasOwn(STATUS_PROJECTION, "revision"), false);
|
|
assert.doesNotMatch(JSON.stringify(status), /NOT_A_REAL_|PRIVATE|fixture_cookie|revision/);
|
|
});
|
|
|
|
test("missing, invalid and differently named saved cookies require new input without probing", async () => {
|
|
for (const [record, code] of [[null, "missing"], [fixtureRecord({ state: "invalid" }), "invalid"], [fixtureRecord({ cookie_name: "different_cookie" }), "missing"]]) {
|
|
const store = database(record);
|
|
const tokens = service(store, { probe: async () => assert.fail("No usable cookie must not be probed") });
|
|
await assert.rejects(tokens.resolveForEnqueue("", { url }), expectedError(code, 400));
|
|
assert.equal(store.writes.length, 0);
|
|
}
|
|
});
|
|
|
|
test("malformed supplied values and unsafe source URLs fail before any database or network access", async () => {
|
|
const tokens = createSessionTokenService({ settings,
|
|
getDb: async () => assert.fail("Database must not be used"),
|
|
probe: async () => assert.fail("Network must not be used"),
|
|
});
|
|
for (const value of [[], {}, " ", "abc; other=PRIVATE", "abc\nPRIVATE"]) {
|
|
await assert.rejects(tokens.resolveForEnqueue(value, { url }), ValidationError);
|
|
}
|
|
await assert.rejects(tokens.resolveForEnqueue("fixture", { url: "https://evil.invalid/watch/42/9/engsub" }), ValidationError);
|
|
});
|
|
|
|
test("definite rejection removes only the rejected cached credential and keeps an invalid marker", async () => {
|
|
const store = database(fixtureRecord());
|
|
const tokens = service(store, { probe: async () => ({ state: "invalid" }) });
|
|
await assert.rejects(tokens.resolveForEnqueue("", { url }), expectedError("invalid", 400));
|
|
assert.equal(store.current().state, "invalid");
|
|
assert.equal(Object.hasOwn(store.current(), "cookie"), false);
|
|
assert.notEqual(store.current().revision, "fixture-revision-1");
|
|
assert.equal((await tokens.readStatus()).available, false);
|
|
});
|
|
|
|
test("rejecting a newly supplied token preserves a different saved token", async () => {
|
|
const original = fixtureRecord();
|
|
const store = database(original);
|
|
await assert.rejects(service(store, { probe: async () => ({ state: "invalid" }) })
|
|
.resolveForEnqueue("NOT_A_REAL_BAD_REPLACEMENT", { url }), expectedError("invalid"));
|
|
assert.deepEqual(store.current(), original);
|
|
assert.equal(store.writes.length, 0);
|
|
});
|
|
|
|
test("network, verification, missing-source and unknown checks preserve the cached token and do not claim expiry", async () => {
|
|
for (const state of ["unavailable", "verification", "source", "unverifiable", "unexpected"]) {
|
|
const original = fixtureRecord();
|
|
const store = database(original);
|
|
await assert.rejects(service(store, { probe: async () => ({ state }) }).resolveForEnqueue("", { url }), error => {
|
|
expectedError(state === "unexpected" ? "unverifiable" : state)(error);
|
|
assert.doesNotMatch(error.message, /expired|rejected/i);
|
|
return true;
|
|
});
|
|
assert.deepEqual(store.current(), original);
|
|
assert.equal(store.writes.length, 0);
|
|
}
|
|
});
|
|
|
|
test("probe exceptions and database errors cannot leak upstream response bodies or credentials", async () => {
|
|
const store = database(fixtureRecord());
|
|
await assert.rejects(service(store, { probe: async () => { throw new Error(`PRIVATE ${cookie}`); } })
|
|
.resolveForEnqueue("", { url }), expectedError("unavailable", 503));
|
|
const broken = createSessionTokenService({ settings, getDb: async () => { throw new Error(`PRIVATE ${cookie}`); } });
|
|
await assert.rejects(broken.readStatus(), expectedError("storage", 503));
|
|
await assert.rejects(broken.resolveForEnqueue("fixture", { url }), expectedError("storage", 503));
|
|
});
|
|
|
|
test("malformed stored credentials are invalidated locally without a request", async () => {
|
|
for (const stored of ["wrong_name=PRIVATE", "fixture_cookie=invalid; other=PRIVATE", null]) {
|
|
const store = database(fixtureRecord({ cookie: stored }));
|
|
await assert.rejects(service(store, { probe: async () => assert.fail("Must not send malformed cookie") })
|
|
.resolveForEnqueue("", { url }), expectedError("invalid"));
|
|
assert.equal(store.current().state, "invalid");
|
|
assert.equal(Object.hasOwn(store.current(), "cookie"), false);
|
|
}
|
|
});
|
|
|
|
test("an old failed check cannot invalidate a newer token saved while it was in flight", async () => {
|
|
const store = database(fixtureRecord());
|
|
const fresh = fixtureRecord({ cookie: "fixture_cookie=NOT_A_REAL_NEW_COOKIE", revision: "newer-revision" });
|
|
const tokens = service(store, { probe: async () => { store.replace(fresh); return { state: "invalid" }; } });
|
|
await assert.rejects(tokens.resolveForEnqueue("", { url }), expectedError("invalid"));
|
|
assert.deepEqual(store.current(), fresh);
|
|
assert.deepEqual(store.writes[0].filter.revision, { $eq: "fixture-revision-1" });
|
|
});
|
|
|
|
test("an old successful replacement cannot overwrite a newer concurrently saved token", async () => {
|
|
const store = database(fixtureRecord());
|
|
const fresh = fixtureRecord({ cookie: "fixture_cookie=NOT_A_REAL_NEW_COOKIE", revision: "newer-revision" });
|
|
const tokens = service(store, { probe: async () => { store.replace(fresh); return { state: "valid" }; } });
|
|
const result = await tokens.resolveForEnqueue("NOT_A_REAL_SLOW_REPLACEMENT", { url });
|
|
assert.equal(result.cookie, "fixture_cookie=NOT_A_REAL_SLOW_REPLACEMENT");
|
|
assert.deepEqual(store.current(), fresh);
|
|
assert.equal(result.status.available, true);
|
|
});
|
|
|
|
test("an older rejected check cannot erase a cached token after a later successful revalidation", async () => {
|
|
const store = database(fixtureRecord());
|
|
let releaseOldCheck;
|
|
let oldCheckStarted;
|
|
const started = new Promise(resolve => { oldCheckStarted = resolve; });
|
|
const old = service(store, { probe: async () => {
|
|
oldCheckStarted();
|
|
return new Promise(resolve => { releaseOldCheck = resolve; });
|
|
} });
|
|
const oldResult = old.resolveForEnqueue("", { url });
|
|
const rejected = assert.rejects(oldResult, expectedError("invalid"));
|
|
await started;
|
|
await service(store).resolveForEnqueue("", { url });
|
|
const fresh = store.current();
|
|
assert.notEqual(fresh.revision, "fixture-revision-1");
|
|
releaseOldCheck({ state: "invalid" });
|
|
await rejected;
|
|
assert.deepEqual(store.current(), fresh);
|
|
assert.equal(store.current().cookie, cookie);
|
|
});
|
|
|
|
test("concurrent first saves tolerate the unique-id insertion race without replacing the winner", async () => {
|
|
const store = database();
|
|
const fresh = fixtureRecord({ cookie: "fixture_cookie=NOT_A_REAL_FIRST_WINNER", revision: "winner" });
|
|
const tokens = service(store, { probe: async () => { store.replace(fresh); return { state: "valid" }; } });
|
|
const result = await tokens.resolveForEnqueue("NOT_A_REAL_SLOW_REPLACEMENT", { url });
|
|
assert.equal(result.source, "supplied");
|
|
assert.deepEqual(store.current(), fresh);
|
|
});
|
|
|
|
test("unacknowledged cache writes stop submission with a safe error", async () => {
|
|
const store = database();
|
|
store.collection.updateOne = async () => ({ acknowledged: false });
|
|
await assert.rejects(service(store).resolveForEnqueue("fixture", { url }), expectedError("storage", 503));
|
|
});
|
|
|
|
test("download-access proof requires a usable source marker instead of HTTP 200 alone", () => {
|
|
assert.deepEqual(classifyWatchResponse(200, sourcePage), { state: "valid" });
|
|
for (const body of ["<html>Ordinary page</html>", '<script>{"code":""}</script>', '<script>{"code":"https://evil.invalid"}</script>']) {
|
|
assert.deepEqual(classifyWatchResponse(200, body), { state: "unverifiable" });
|
|
}
|
|
assert.deepEqual(classifyWatchResponse(200, sourcePage, "application/json"), { state: "unverifiable" });
|
|
assert.deepEqual(classifyWatchResponse(404, sourcePage), { state: "source" });
|
|
});
|
|
|
|
test("challenge and access-denial responses are distinguished from token expiry and source changes", () => {
|
|
assert.deepEqual(classifyWatchResponse(403, "<title>Attention Required! | Cloudflare</title>"), { state: "verification" });
|
|
assert.deepEqual(classifyWatchResponse(200, '<form id="challenge-form">check</form>'), { state: "verification" });
|
|
assert.deepEqual(classifyWatchResponse(200, "<main>Bitte logge dich ein, um diesen Bereich betreten zu können.</main>"), { state: "invalid" });
|
|
assert.deepEqual(classifyWatchResponse(200, "<main>Bitte logge dich ein, um diesen Bereich betreten zu können.</main>"), { state: "invalid" });
|
|
assert.deepEqual(classifyWatchResponse(401, "<main>Denied</main>"), { state: "invalid" });
|
|
assert.deepEqual(classifyWatchResponse(403, "<main>Denied</main>"), { state: "unverifiable" });
|
|
assert.deepEqual(classifyWatchResponse(503, "<main>Unavailable</main>"), { state: "unavailable" });
|
|
assert.deepEqual(classifyWatchResponse(200, "<main>Complete the CAPTCHA.</main>"), { state: "verification" });
|
|
assert.deepEqual(classifyWatchResponse(200, '<script>const text="Bitte logge dich ein, um diesen Bereich betreten zu können.";</script>'), { state: "unverifiable" });
|
|
});
|
|
|
|
test("non-HTML error statuses retain their meaning while JSON success and redirects never prove access", () => {
|
|
const json = '{"code":"fixture_embed_id"}';
|
|
for (const [status, expected] of [[401, "invalid"], [429, "unavailable"], [503, "unavailable"], [404, "source"], [410, "source"]]) {
|
|
assert.deepEqual(classifyWatchResponse(status, json, "application/json"), { state: expected });
|
|
}
|
|
assert.deepEqual(classifyWatchResponse(200, json, "application/json"), { state: "unverifiable" });
|
|
assert.deepEqual(classifyWatchResponse(302, sourcePage, "text/html"), { state: "unverifiable" });
|
|
assert.deepEqual(classifyWatchResponse(302, json, "application/json"), { state: "unverifiable" });
|
|
assert.deepEqual(classifyWatchResponse(401, "<title>Attention Required! | Cloudflare</title>", "text/html"), { state: "verification" });
|
|
});
|
|
|
|
test("the probe sends only the configured cookie and stream preference to a canonical HTTPS source", async () => {
|
|
const calls = [];
|
|
const probe = createProxerSessionProbe({ fetch: async (target, options) => {
|
|
calls.push({ target, options });
|
|
return new Response(sourcePage, { headers: { "Content-Type": "text/html; charset=UTF-8" } });
|
|
} });
|
|
assert.deepEqual(await probe(cookie, { url: "https://www.proxer.me/watch/42/9/engsub/#top" }), { state: "valid" });
|
|
assert.equal(calls.length, 1);
|
|
assert.equal(calls[0].target, url);
|
|
assert.equal(calls[0].options.headers.Cookie, `${cookie}; stream_choose=proxer-stream`);
|
|
assert.equal(calls[0].options.redirect, "manual");
|
|
assert.equal(calls[0].options.credentials, "omit");
|
|
assert.equal(calls[0].options.method, "GET");
|
|
});
|
|
|
|
test("redirects, unsupported sources and header injection cannot forward the cookie elsewhere", async () => {
|
|
let calls = 0;
|
|
const probe = createProxerSessionProbe({ fetch: async () => {
|
|
calls++;
|
|
return new Response("", { status: 302, headers: { Location: "https://evil.invalid/capture" } });
|
|
} });
|
|
assert.deepEqual(await probe(cookie, { url }), { state: "unverifiable" });
|
|
assert.equal(calls, 1);
|
|
for (const target of ["http://proxer.me/watch/42/9/engsub", "https://evil.invalid/watch/42/9/engsub", `${url}?token=PRIVATE`]) {
|
|
await assert.rejects(probe(cookie, { url: target }), ValidationError);
|
|
}
|
|
await assert.rejects(probe(`${cookie}; evil=PRIVATE`, { url }), ValidationError);
|
|
assert.equal(calls, 1);
|
|
});
|
|
|
|
test("oversized, truncated and non-HTML responses do not pass the access check", async () => {
|
|
for (const response of [
|
|
new Response(sourcePage, { headers: { "content-type": "text/html", "content-length": "1000000" } }),
|
|
new Response("x".repeat(1000) + sourcePage, { headers: { "content-type": "text/html" } }),
|
|
new Response(sourcePage, { headers: { "content-type": "application/json" } }),
|
|
new Response(new ReadableStream({ start(controller) { controller.error(new Error(`PRIVATE ${cookie}`)); } }), { headers: { "content-type": "text/html" } }),
|
|
]) {
|
|
const probe = createProxerSessionProbe({ fetch: async () => response, maxBytes: 500 });
|
|
const result = await probe(cookie, { url });
|
|
assert.notEqual(result.state, "valid");
|
|
assert.doesNotMatch(JSON.stringify(result), /NOT_A_REAL_|PRIVATE/);
|
|
}
|
|
});
|
|
|
|
test("the probe preserves explicit status for absent and oversized bodies without accepting empty success", async () => {
|
|
for (const [status, expected] of [[401, "invalid"], [503, "unavailable"], [200, "unverifiable"]]) {
|
|
for (const body of [null, "x".repeat(1000)]) {
|
|
const probe = createProxerSessionProbe({ maxBytes: 128, fetch: async () => new Response(body, {
|
|
status, headers: { "content-type": "text/html" },
|
|
}) });
|
|
assert.deepEqual(await probe(cookie, { url }), { state: expected });
|
|
}
|
|
}
|
|
});
|
|
|
|
test("a hard deadline aborts a stuck request without exposing fetch errors", async () => {
|
|
let signal;
|
|
const probe = createProxerSessionProbe({ timeoutMs: 15, fetch: async (_, options) => {
|
|
signal = options.signal;
|
|
return new Promise(() => {});
|
|
} });
|
|
assert.deepEqual(await probe(cookie, { url }), { state: "unavailable" });
|
|
assert.equal(signal.aborted, true);
|
|
const throwing = createProxerSessionProbe({ fetch: async () => { throw new Error(`PRIVATE ${cookie}`); } });
|
|
assert.deepEqual(await throwing(cookie, { url }), { state: "unavailable" });
|
|
});
|
|
|
|
test("a Cloudflare challenge header wins even if an HTML body happens to contain a code field", async () => {
|
|
const probe = createProxerSessionProbe({ fetch: async () => new Response(sourcePage, {
|
|
headers: { "content-type": "text/html", "cf-mitigated": "challenge" },
|
|
}) });
|
|
assert.deepEqual(await probe(cookie, { url }), { state: "verification" });
|
|
});
|