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

163 lines
7.8 KiB
JavaScript

"use strict";
const { randomUUID } = require("node:crypto");
const { getDb } = require("./mongo");
const { config } = require("./config");
const { ValidationError, cookieToken, normalizeWatchUrl } = require("./jobValidation");
const { probeSessionToken } = require("./proxerSessionProbe");
const CACHE_ID = "proxer-session-token";
const CACHE_QUERY_TIMEOUT_MS = 5000;
const STATUS_PROJECTION = Object.freeze({ cookie_name: 1, state: 1, validated_at: 1, saved_at: 1 });
class SessionTokenError extends ValidationError {
constructor(code, message, httpStatus = 400) {
super(message);
this.name = "SessionTokenError";
this.code = code;
this.httpStatus = httpStatus;
}
}
function iso(value) {
if (value == null) return null;
const date = new Date(value);
return Number.isFinite(date.getTime()) ? date.toISOString() : null;
}
function publicCacheStatus(record, prefix) {
const matches = record && record.cookie_name === prefix.slice(0, -1);
const state = matches && record.state === "ready" ? "saved" : matches && record.state === "invalid" ? "invalid" : "missing";
return {
available: state === "saved", state,
lastValidatedAt: matches ? iso(record.validated_at) : null,
savedAt: matches ? iso(record.saved_at) : null,
};
}
function revisionFilter(record) {
return {
_id: CACHE_ID,
revision: record && Object.hasOwn(record, "revision") ? { $eq: record.revision } : { $exists: false },
};
}
function storageError() {
return new SessionTokenError("storage", "The saved token could not be accessed or updated. Check the database connection and try again. Nothing was queued.", 503);
}
function probeError(state) {
if (state === "invalid") return new SessionTokenError("invalid", "Proxer rejected the token. Supply a current token and try again. Nothing was queued.");
if (state === "verification") return new SessionTokenError("verification", "Proxer requires verification before the token can be used. Complete the verification in your browser and supply a refreshed token, then try again. Nothing was queued.", 409);
if (state === "source") return new SessionTokenError("source", "The first requested episode is unavailable, so token access could not be checked. Check the series, episode, and language, then try again. The saved token was kept and nothing was queued.", 409);
if (state === "unavailable") return new SessionTokenError("unavailable", "The token access check could not reach Proxer or timed out. Try again when the connection is available. The saved token was kept and nothing was queued.", 503);
return new SessionTokenError("unverifiable", "The first episode's video link could not be resolved during the token access check. Open that source page, complete any required verification, and supply a current token if needed. The saved token was kept and nothing was queued.", 409);
}
function createSessionTokenService({ getDb: connect = getDb, settings = config, probe = probeSessionToken, now = () => new Date() } = {}) {
async function statusFrom(collection) {
const record = await collection.findOne({ _id: CACHE_ID }, { projection: STATUS_PROJECTION, maxTimeMS: CACHE_QUERY_TIMEOUT_MS });
return publicCacheStatus(record, settings.tokenPrefix);
}
async function readStatus() {
try {
return await statusFrom((await connect()).collection("settings"));
} catch {
throw storageError();
}
}
async function invalidate(collection, record) {
if (!record) return;
const result = await collection.updateOne(revisionFilter(record), {
$set: { state: "invalid", invalidated_at: now(), revision: randomUUID() },
$unset: { cookie: "" },
}, { maxTimeMS: CACHE_QUERY_TIMEOUT_MS });
if (!result.acknowledged) throw storageError();
}
async function resolveForEnqueue(rawValue, { url } = {}) {
try {
const target = normalizeWatchUrl(url).url;
const supplied = rawValue !== undefined && rawValue !== null && rawValue !== "";
// Validate a supplied value before touching MongoDB or the network.
let cookie = supplied ? cookieToken(rawValue, settings.tokenPrefix) : null;
const collection = (await connect()).collection("settings");
const record = await collection.findOne({ _id: CACHE_ID }, {
projection: { cookie: 1, cookie_name: 1, state: 1, revision: 1, validated_at: 1, saved_at: 1 },
maxTimeMS: CACHE_QUERY_TIMEOUT_MS,
});
if (!supplied) {
const status = publicCacheStatus(record, settings.tokenPrefix);
if (!status.available) {
throw new SessionTokenError(status.state === "invalid" ? "invalid" : "missing",
status.state === "invalid" ? "The saved token was rejected. Supply a new token before adding downloads."
: "No saved token is available. Supply a token once; it will be checked and saved for later downloads.");
}
try {
if (typeof record.cookie !== "string" || !record.cookie.startsWith(settings.tokenPrefix)) throw new Error("invalid cache");
cookie = cookieToken(record.cookie.slice(settings.tokenPrefix.length), settings.tokenPrefix);
} catch {
await invalidate(collection, record);
throw new SessionTokenError("invalid", "The saved token cannot be used. Supply a new token before adding downloads.");
}
}
let outcome;
try {
outcome = await probe(cookie, { url: target });
} catch {
throw probeError("unavailable");
}
if (outcome?.state !== "valid") {
// Only a proven rejection invalidates a cached credential. A challenge,
// a source failure, a layout change and network errors retain it.
// Matching a revision prevents an old in-flight check erasing a token
// supplied successfully by another browser or server process.
if (outcome?.state === "invalid" && record && record.cookie === cookie) await invalidate(collection, record);
throw probeError(outcome?.state);
}
const checkedAt = now();
let saved = false;
let status;
if (supplied) {
const replacement = {
cookie, cookie_name: settings.tokenPrefix.slice(0, -1), state: "ready",
revision: randomUUID(), saved_at: checkedAt, validated_at: checkedAt,
};
try {
const result = await collection.updateOne(revisionFilter(record), {
$set: replacement, $unset: { invalidated_at: "" },
}, { upsert: !record, maxTimeMS: CACHE_QUERY_TIMEOUT_MS });
if (!result.acknowledged) throw storageError();
saved = result.matchedCount === 1 || result.upsertedCount === 1;
} catch (error) {
// Two first-time submissions may both observe an empty cache. The
// unique _id and compare-and-set let one publish without overwriting
// the other's newer credential; both validated queue jobs remain safe.
if (error.code !== 11000) throw error;
}
if (saved) status = publicCacheStatus(replacement, settings.tokenPrefix);
} else {
const result = await collection.updateOne(revisionFilter(record), {
$set: { validated_at: checkedAt, revision: randomUUID() },
}, { maxTimeMS: CACHE_QUERY_TIMEOUT_MS });
if (!result.acknowledged) throw storageError();
saved = result.matchedCount === 1;
if (saved) status = publicCacheStatus({ ...record, validated_at: checkedAt }, settings.tokenPrefix);
}
if (!status) status = await statusFrom(collection);
return { cookie, source: supplied ? "supplied" : "cached", status };
} catch (error) {
if (error instanceof SessionTokenError || error instanceof ValidationError) throw error;
throw storageError();
}
}
return { readStatus, resolveForEnqueue };
}
module.exports = { CACHE_ID, STATUS_PROJECTION, SessionTokenError, publicCacheStatus, createSessionTokenService };