phase 2 rework
This commit is contained in:
1 parent
20054198f3
commit
b397ea9256
44 files changed
+5528
-1377
No files matched your search
+140
@@ -0,0 +1,140 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs/promises");
|
||||
const os = require("node:os");
|
||||
const { config } = require("./config");
|
||||
const { STATUS_READ_PROJECTION, toPublicJob, validateOutputTarget } = require("./jobValidation");
|
||||
const { QUERY_TIMEOUT_MS } = require("./statusQuery");
|
||||
const { toPublicWorkerIdentity, validWorkerName, isoTimestamp } = require("./workerIdentity");
|
||||
|
||||
const ACTIVE_JOB_LIMIT = 50;
|
||||
const WORKER_LIMIT = 50;
|
||||
const INVENTORY_CACHE_MS = 10000;
|
||||
const ACTIVITY_READ_PROJECTION = Object.freeze({ ...STATUS_READ_PROJECTION, worker: 1 });
|
||||
const PROCESS_STATES = new Set(["online", "stopped", "stopping", "launching", "errored", "waiting restart", "one-launch-status"]);
|
||||
|
||||
async function inventorySnapshot(listWorkers) {
|
||||
try {
|
||||
const workers = await listWorkers();
|
||||
if (!Array.isArray(workers)) throw new Error("Invalid worker inventory.");
|
||||
const visible = workers.slice(0, WORKER_LIMIT + 1);
|
||||
const pidCounts = new Map(visible.filter(worker => Number.isSafeInteger(worker?.pid) && worker.pid > 0)
|
||||
.map(worker => [worker.pid, 0]));
|
||||
// Check duplicate PIDs against the full bounded PM2 response before keeping
|
||||
// only the first page. A duplicate beyond that page is still ambiguous.
|
||||
for (const worker of workers) {
|
||||
if (pidCounts.has(worker?.pid)) pidCounts.set(worker.pid, pidCounts.get(worker.pid) + 1);
|
||||
}
|
||||
return { available: true, workers: visible,
|
||||
ambiguousPids: new Set([...pidCounts].filter(([, count]) => count > 1).map(([pid]) => pid)) };
|
||||
} catch {
|
||||
// A supervisor failure must not turn existing processing records into an
|
||||
// apparently empty queue, or prevent users from reading download status.
|
||||
return { available: false, workers: [], ambiguousPids: new Set() };
|
||||
}
|
||||
}
|
||||
|
||||
function createInventoryReader(listWorkers, { now = Date.now, ttlMs = INVENTORY_CACHE_MS } = {}) {
|
||||
let cached = null;
|
||||
let expiresAt = 0;
|
||||
let pending = null;
|
||||
return async function readInventory() {
|
||||
if (cached && now() < expiresAt) return cached;
|
||||
if (pending) return pending;
|
||||
pending = inventorySnapshot(listWorkers).then(snapshot => {
|
||||
cached = snapshot;
|
||||
expiresAt = now() + ttlMs;
|
||||
return snapshot;
|
||||
}).finally(() => { pending = null; });
|
||||
return pending;
|
||||
};
|
||||
}
|
||||
|
||||
const readDefaultInventory = createInventoryReader(() => require("../controllers/pm2Controller").listManagedProcesses());
|
||||
|
||||
async function readActiveFileSize(job, settings) {
|
||||
try {
|
||||
const target = await validateOutputTarget(settings.outputDir, job.filename);
|
||||
const stat = await fs.lstat(target);
|
||||
return stat.isFile() && !stat.isSymbolicLink() ? stat.size : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function publicProcess(record, index) {
|
||||
const value = record && typeof record === "object" ? record : {};
|
||||
const id = typeof value.pm_id === "number" ? String(value.pm_id) : value.pm_id;
|
||||
const pm_id = typeof id === "string" && /^(0|[1-9]\d{0,9})$/.test(id) ? id : null;
|
||||
return {
|
||||
key: `pm2:${pm_id ?? "unknown"}:${index}`,
|
||||
name: validWorkerName(value.name) ? value.name : (pm_id === null ? "Unknown worker" : `Worker ${pm_id}`),
|
||||
pm_id, pid: Number.isSafeInteger(value.pid) && value.pid > 0 ? value.pid : null,
|
||||
status: PROCESS_STATES.has(value.status) ? value.status : "unknown",
|
||||
startedAtISO: isoTimestamp(value.startedAtISO),
|
||||
available: true, jobs: [], activityUnknown: false,
|
||||
};
|
||||
}
|
||||
|
||||
function assignment(job, inventory, workers, host) {
|
||||
const identity = job.worker;
|
||||
if (!identity) return { reason: "unknown-worker" };
|
||||
if (identity.host !== host) return { reason: "remote-worker" };
|
||||
if (!inventory.available) return { reason: "supervisor-unavailable" };
|
||||
const candidates = workers.filter(worker => worker.pid === identity.pid);
|
||||
// Duplicate inventory PIDs are ambiguous. Do not choose whichever row happens
|
||||
// to come first, even if only one of the rows claims to be online.
|
||||
if (candidates.length > 1 || inventory.ambiguousPids.has(identity.pid)) return { reason: "ambiguous-worker" };
|
||||
const worker = candidates[0];
|
||||
if (!worker && inventory.workers.length > WORKER_LIMIT) return { reason: "worker-not-shown" };
|
||||
if (!worker || worker.status !== "online") return { reason: "worker-not-running" };
|
||||
const workerStarted = Date.parse(identity.started_at);
|
||||
const claimStarted = Date.parse(job.started_at);
|
||||
if (!worker.startedAtISO || !Number.isFinite(claimStarted) || workerStarted > claimStarted) {
|
||||
return { reason: "unverified-worker" };
|
||||
}
|
||||
// A recycled PID must not attach an old held claim to a replacement process.
|
||||
if (workerStarted < Date.parse(worker.startedAtISO)) return { reason: "stale-worker" };
|
||||
return { worker };
|
||||
}
|
||||
|
||||
async function readActivity(db, {
|
||||
settings = config, listWorkers, host = os.hostname(), readFileSize = readActiveFileSize,
|
||||
} = {}) {
|
||||
const [records, inventory] = await Promise.all([
|
||||
db.collection("queue").find({ processing: true }, {
|
||||
projection: ACTIVITY_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS,
|
||||
}).sort({ created_at: 1, _id: 1 }).limit(ACTIVE_JOB_LIMIT + 1).toArray(),
|
||||
listWorkers ? inventorySnapshot(listWorkers) : readDefaultInventory(),
|
||||
]);
|
||||
const truncated = records.length > ACTIVE_JOB_LIMIT;
|
||||
const workersTruncated = inventory.workers.length > WORKER_LIMIT;
|
||||
const inventoryWorkers = inventory.workers.map(publicProcess);
|
||||
const workers = inventoryWorkers.slice(0, WORKER_LIMIT);
|
||||
const jobs = await Promise.all(records.slice(0, ACTIVE_JOB_LIMIT).map(async record => {
|
||||
const job = { ...toPublicJob(record), worker: toPublicWorkerIdentity(record.worker) };
|
||||
try {
|
||||
const size = await readFileSize(job, settings);
|
||||
job.fileSize = Number.isSafeInteger(size) && size >= 0 ? size : null;
|
||||
} catch { job.fileSize = null; }
|
||||
return job;
|
||||
}));
|
||||
const unassigned = [];
|
||||
for (const job of jobs) {
|
||||
const match = assignment(job, inventory, inventoryWorkers, host);
|
||||
if (match.worker && workers.includes(match.worker)) match.worker.jobs.push(job);
|
||||
else unassigned.push({ ...job, assignmentReason: match.reason || "worker-not-shown" });
|
||||
}
|
||||
const uncertainLocalClaims = unassigned.some(job => !job.worker || job.worker.host === host);
|
||||
for (const worker of workers) {
|
||||
// Pre-update claims have no reliable worker identity. In that situation an
|
||||
// empty card means activity is unknown, not evidence that a worker is idle.
|
||||
worker.activityUnknown = truncated || workersTruncated || uncertainLocalClaims;
|
||||
}
|
||||
return { workers, unassigned, truncated, workersTruncated, available: inventory.available };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
readActivity, createInventoryReader, readActiveFileSize,
|
||||
ACTIVE_JOB_LIMIT, WORKER_LIMIT, INVENTORY_CACHE_MS, ACTIVITY_READ_PROJECTION,
|
||||
};
|
||||
+24
-7
@@ -29,6 +29,14 @@ function positiveInteger(value, label) {
|
||||
return number;
|
||||
}
|
||||
|
||||
function seasonNumber(value) {
|
||||
const text = typeof value === "number" ? String(value) : value;
|
||||
if (typeof text !== "string" || !/^(0|[1-9]\d*)$/.test(text) || !Number.isSafeInteger(Number(text))) {
|
||||
throw new ValidationError("Season must be a whole number of zero or greater within the supported range.");
|
||||
}
|
||||
return Number(text);
|
||||
}
|
||||
|
||||
function isWellFormedText(value) {
|
||||
// In Unicode mode a valid surrogate pair is one code point outside this range.
|
||||
// Lone surrogates would otherwise be replaced silently when converted to UTF-8.
|
||||
@@ -115,17 +123,16 @@ function optionalTitle(value) {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
async function buildQueueJobs(body, config, now = () => new Date()) {
|
||||
async function planQueueJobs(body, config, now = () => new Date()) {
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) throw new ValidationError("Invalid download request.");
|
||||
if (body.mode !== "video" && body.mode !== "series") throw new ValidationError("Choose video or series mode.");
|
||||
const token = cookieToken(body.token, config.tokenPrefix);
|
||||
const created_at = now();
|
||||
const jobs = [];
|
||||
if (body.mode === "video") {
|
||||
const source = normalizeWatchUrl(body.url);
|
||||
const filename = normalizeFilename(optionalTitle(body.filename) || optionalTitle(body.name)
|
||||
|| `${source.id} E${source.episode} ${source.language}`);
|
||||
jobs.push({ url: source.url, token, filename, created_at });
|
||||
jobs.push({ url: source.url, filename, created_at });
|
||||
} else {
|
||||
const id = positiveInteger(body.id, "Series ID");
|
||||
const from = positiveInteger(body.episode_from, "First episode");
|
||||
@@ -137,11 +144,15 @@ async function buildQueueJobs(body, config, now = () => new Date()) {
|
||||
if (!LANGUAGES.has(body.language)) throw new ValidationError("Choose a supported language.");
|
||||
const name = optionalTitle(body.name) || String(id);
|
||||
const pad = String(to).length;
|
||||
// Older direct API clients omit season and keep their established names.
|
||||
// The web form always sends a season, including zero for specials.
|
||||
const season = body.season === undefined ? null : seasonNumber(body.season);
|
||||
for (let ep = from; ep <= to; ep += 1) {
|
||||
jobs.push({
|
||||
url: `https://proxer.me/watch/${id}/${ep}/${body.language}`,
|
||||
token,
|
||||
filename: normalizeFilename(`${name}E${String(ep).padStart(pad, "0")}_${body.language}`),
|
||||
filename: normalizeFilename(season === null
|
||||
? `${name}E${String(ep).padStart(pad, "0")}_${body.language}`
|
||||
: `${name}S${String(season).padStart(3, "0")}E${String(ep).padStart(3, "0")}_${body.language}`),
|
||||
created_at,
|
||||
});
|
||||
}
|
||||
@@ -151,6 +162,12 @@ async function buildQueueJobs(body, config, now = () => new Date()) {
|
||||
return jobs;
|
||||
}
|
||||
|
||||
async function buildQueueJobs(body, config, now = () => new Date()) {
|
||||
const jobs = await planQueueJobs(body, config, now);
|
||||
const token = cookieToken(body.token, config.tokenPrefix);
|
||||
return jobs.map(job => ({ ...job, token }));
|
||||
}
|
||||
|
||||
function sanitizeLog(value, sensitiveValues = []) {
|
||||
if (typeof value !== "string") return "";
|
||||
let result = value;
|
||||
@@ -191,6 +208,6 @@ function toPublicJob(job) {
|
||||
|
||||
module.exports = {
|
||||
ValidationError, LANGUAGES, MAX_LOG_BYTES, STATUS_READ_PROJECTION,
|
||||
positiveInteger, normalizeWatchUrl, normalizeFilename, validateOutputTarget,
|
||||
cookieToken, buildQueueJobs, sanitizeLog, toPublicJob,
|
||||
positiveInteger, seasonNumber, normalizeWatchUrl, normalizeFilename, validateOutputTarget,
|
||||
cookieToken, planQueueJobs, buildQueueJobs, sanitizeLog, toPublicJob,
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
"use strict";
|
||||
|
||||
const { normalizeWatchUrl, cookieToken } = require("./jobValidation");
|
||||
|
||||
const PROBE_TIMEOUT_MS = 12_000;
|
||||
const PROBE_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
// This is a read-only download-access check, not an account-login assertion.
|
||||
// The configured cookie may be a Joomla session or a verification cookie.
|
||||
// scripts/lib/proxer_utils.py resolves the same exact `"code":"` marker;
|
||||
// HTTP 200 alone, a missing marker, and a generic 403 prove neither login nor
|
||||
// expiry. No protected library or media-transfer code is involved here.
|
||||
function classifyWatchResponse(status, html, contentType = "text/html") {
|
||||
const isHtml = typeof html === "string"
|
||||
&& /^\s*(?:text\/html|application\/xhtml\+xml)(?:\s*;|\s*$)/i.test(contentType);
|
||||
const title = isHtml ? html.match(/<title\b[^>]*>([\s\S]*?)<\/title\s*>/i)?.[1] || "" : "";
|
||||
const challenge = isHtml && (/(?:Just a moment|Attention Required|Checking your browser)/i.test(title)
|
||||
|| /\bid\s*=\s*["'](?:challenge-form|cf-challenge-running|cf-error-details)["']/i.test(html));
|
||||
if (challenge) return { state: "verification" };
|
||||
// These HTTP outcomes remain meaningful when an upstream error is JSON or
|
||||
// plain text. An observed verification challenge still takes precedence.
|
||||
if (status === 401) return { state: "invalid" };
|
||||
if (status === 429 || status >= 500) return { state: "unavailable" };
|
||||
if (status === 404 || status === 410) return { state: "source" };
|
||||
if (status !== 200 || !isHtml) return { state: "unverifiable" };
|
||||
|
||||
// Restrict the marker's value to a plausible embed identifier; never return
|
||||
// it or any upstream HTML, user information, signed URL, or response header.
|
||||
if (/"code":"[A-Za-z0-9_-]{1,256}"/.test(html)) return { state: "valid" };
|
||||
|
||||
const visibleText = html.replace(/<!--[\s\S]*?-->/g, " ")
|
||||
.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, " ")
|
||||
.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ");
|
||||
// Proxer's public logged-out pages use this explicit access-denied wording.
|
||||
// Observed primary source: https://proxer.me/manga/doujin/clicks/S
|
||||
// A login form in the navigation alone is not treated as an invalid cookie.
|
||||
if (/Bitte logge dich ein, um diesen Bereich betreten zu k(?:ö|ö)nnen\./i.test(visibleText)) {
|
||||
return { state: "invalid" };
|
||||
}
|
||||
if (/\bcaptcha\b/i.test(visibleText)) return { state: "verification" };
|
||||
return { state: "unverifiable" };
|
||||
}
|
||||
|
||||
async function boundedHtml(response, maxBytes) {
|
||||
const declaredLength = Number(response.headers.get("content-length"));
|
||||
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
|
||||
await response.body?.cancel().catch(() => {});
|
||||
return null;
|
||||
}
|
||||
if (!response.body) return null;
|
||||
const reader = response.body.getReader();
|
||||
let size = 0;
|
||||
const parts = [];
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) return Buffer.concat(parts, size).toString("utf8");
|
||||
size += value.byteLength;
|
||||
if (size > maxBytes) {
|
||||
await reader.cancel().catch(() => {});
|
||||
return null;
|
||||
}
|
||||
parts.push(Buffer.from(value));
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
function createProxerSessionProbe({ fetch: fetchImpl = globalThis.fetch, timeoutMs = PROBE_TIMEOUT_MS, maxBytes = PROBE_MAX_BYTES } = {}) {
|
||||
return async function probe(cookie, { url } = {}) {
|
||||
// Canonicalization forbids arbitrary hosts, ports, credentials, queries and
|
||||
// non-watch paths. Redirects are never followed with the credential.
|
||||
const target = normalizeWatchUrl(url).url;
|
||||
const equals = typeof cookie === "string" ? cookie.indexOf("=") : -1;
|
||||
if (equals < 1) throw new Error("A complete validated cookie is required for the access check.");
|
||||
cookieToken(cookie.slice(equals + 1), cookie.slice(0, equals + 1));
|
||||
const controller = new AbortController();
|
||||
let timer;
|
||||
try {
|
||||
const inspect = (async () => {
|
||||
const response = await fetchImpl(target, {
|
||||
method: "GET", redirect: "manual", credentials: "omit", signal: controller.signal,
|
||||
headers: {
|
||||
"User-Agent": "Mozilla/5.0", Accept: "text/html,application/xhtml+xml",
|
||||
"Cache-Control": "no-cache", Cookie: `${cookie}; stream_choose=proxer-stream`,
|
||||
},
|
||||
});
|
||||
if (response.headers.get("cf-mitigated") === "challenge") {
|
||||
await response.body?.cancel().catch(() => {});
|
||||
return { state: "verification" };
|
||||
}
|
||||
if (response.status >= 300 && response.status < 400) {
|
||||
await response.body?.cancel().catch(() => {});
|
||||
return { state: "unverifiable" };
|
||||
}
|
||||
const html = await boundedHtml(response, maxBytes);
|
||||
// An absent or oversized body cannot prove success. Preserve explicit
|
||||
// HTTP rejection/source/availability outcomes; challenge headers were
|
||||
// already handled before reading any body.
|
||||
return classifyWatchResponse(response.status, html ?? "", response.headers.get("content-type") || "");
|
||||
})();
|
||||
const timeout = new Promise(resolve => {
|
||||
timer = setTimeout(() => {
|
||||
controller.abort();
|
||||
resolve({ state: "unavailable" });
|
||||
}, timeoutMs);
|
||||
});
|
||||
return await Promise.race([inspect, timeout]);
|
||||
} catch {
|
||||
return { state: "unavailable" };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
PROBE_TIMEOUT_MS, PROBE_MAX_BYTES, classifyWatchResponse, createProxerSessionProbe,
|
||||
probeSessionToken: createProxerSessionProbe(),
|
||||
};
|
||||
@@ -0,0 +1,162 @@
|
||||
"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 };
|
||||
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
|
||||
const { ValidationError } = require("./jobValidation");
|
||||
|
||||
const STATES = Object.freeze(["queued", "processing", "done", "failed"]);
|
||||
const PAGE_SIZES = Object.freeze([10, 25, 50]);
|
||||
const MAX_PAGE = 100000;
|
||||
const MAX_SEARCH_LENGTH = 100;
|
||||
const QUERY_TIMEOUT_MS = 5000;
|
||||
|
||||
function parseStatusQuery(query = {}) {
|
||||
if (!query || typeof query !== "object" || Array.isArray(query)) {
|
||||
throw new ValidationError("Invalid queue filters.");
|
||||
}
|
||||
for (const key of ["state", "q", "page", "pageSize"]) {
|
||||
if (query[key] !== undefined && typeof query[key] !== "string") {
|
||||
throw new ValidationError("Each queue filter must have a single text value.");
|
||||
}
|
||||
}
|
||||
const state = query.state === undefined ? "queued" : query.state;
|
||||
if (!STATES.includes(state)) throw new ValidationError("Choose a supported queue state.");
|
||||
const rawSearch = query.q ?? "";
|
||||
if (rawSearch.length > MAX_SEARCH_LENGTH || /[\u0000-\u001f\u007f-\u009f\uD800-\uDFFF]/u.test(rawSearch)) {
|
||||
throw new ValidationError(`Search must contain at most ${MAX_SEARCH_LENGTH} characters without control characters.`);
|
||||
}
|
||||
const q = rawSearch.trim();
|
||||
const pageText = query.page ?? "1";
|
||||
if (!/^[1-9]\d{0,5}$/.test(pageText) || Number(pageText) > MAX_PAGE) {
|
||||
throw new ValidationError(`Page must be a whole number between 1 and ${MAX_PAGE}.`);
|
||||
}
|
||||
const sizeText = query.pageSize ?? "25";
|
||||
if (!/^(10|25|50)$/.test(sizeText)) throw new ValidationError("Choose 10, 25, or 50 items per page.");
|
||||
return { state, q, page: Number(pageText), pageSize: Number(sizeText) };
|
||||
}
|
||||
|
||||
function stateQuery(state) {
|
||||
if (state === "queued") return { collection: "queue", filter: { processing: { $ne: true } }, sort: { created_at: 1, _id: 1 } };
|
||||
if (state === "processing") return { collection: "queue", filter: { processing: true }, sort: { created_at: 1, _id: 1 } };
|
||||
if (state === "done") return { collection: "done", filter: {}, sort: { finished_at: -1, _id: -1 } };
|
||||
if (state === "failed") return { collection: "failed", filter: {}, sort: { failed_at: -1, _id: -1 } };
|
||||
throw new ValidationError("Choose a supported queue state.");
|
||||
}
|
||||
|
||||
function statusFilter(state, q) {
|
||||
const { filter } = stateQuery(state);
|
||||
// Treat user input as literal text. No query keys or regular expressions are
|
||||
// accepted from the caller; search is confined to public filenames.
|
||||
if (q) filter.filename = { $regex: q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), $options: "i" };
|
||||
return filter;
|
||||
}
|
||||
|
||||
function publicGlobal(record) {
|
||||
return {
|
||||
captcha_blocked: record?.captcha_blocked === true,
|
||||
pause_reason: ["authentication", "resolution"].includes(record?.pause_reason) ? record.pause_reason : null,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
STATES, PAGE_SIZES, MAX_PAGE, MAX_SEARCH_LENGTH, QUERY_TIMEOUT_MS,
|
||||
parseStatusQuery, stateQuery, statusFilter, publicGlobal,
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
|
||||
const os = require("node:os");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
|
||||
function validWorkerName(value) {
|
||||
return typeof value === "string" && /^[A-Za-z0-9][\w-]{0,63}$/.test(value)
|
||||
&& value.toLowerCase() !== "all";
|
||||
}
|
||||
|
||||
function isoTimestamp(value) {
|
||||
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) return null;
|
||||
const date = new Date(value);
|
||||
return Number.isFinite(date.getTime()) && date.getTime() > 0 && date.toISOString() === value ? value : null;
|
||||
}
|
||||
|
||||
// Worker metadata is display-only. It is never a lease or permission to release
|
||||
// a claim, and malformed/legacy metadata must never identify a current worker.
|
||||
function toPublicWorkerIdentity(value) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)
|
||||
|| !validWorkerName(value.name)
|
||||
|| !Number.isSafeInteger(value.pid) || value.pid <= 0
|
||||
|| typeof value.host !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,252}$/.test(value.host)
|
||||
|| typeof value.run_id !== "string"
|
||||
|| !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.run_id)
|
||||
|| !isoTimestamp(value.started_at)) return null;
|
||||
return {
|
||||
name: value.name, pid: value.pid, host: value.host,
|
||||
run_id: value.run_id.toLowerCase(), started_at: value.started_at,
|
||||
};
|
||||
}
|
||||
|
||||
function createWorkerIdentity({
|
||||
env = process.env, pid = process.pid, host = os.hostname(),
|
||||
now = () => new Date(), uuid = randomUUID,
|
||||
} = {}) {
|
||||
const name = [env.PROXER_WORKER_NAME, env.name].find(validWorkerName) || `worker-${pid}`;
|
||||
const identity = toPublicWorkerIdentity({ name, pid, host, run_id: uuid(), started_at: now().toISOString() });
|
||||
if (!identity) throw new Error("The worker identity could not be initialized.");
|
||||
// This identity belongs to one Node process and is reused for every claim.
|
||||
return Object.freeze(identity);
|
||||
}
|
||||
|
||||
module.exports = { createWorkerIdentity, toPublicWorkerIdentity, validWorkerName, isoTimestamp };
|
||||
Reference in new issue
Block a user