Spaces:
Running
Running
Download server.js from server2/s4: direct link, hf CLI and curl.
- Browser
- Download file 125 kB
-
https://huggingface.co/spaces/server2/s4/resolve/main/server.js
- Command line
-
hf download hf://spaces/server2/s4/server.js
-
curl -L -o server.js https://huggingface.co/spaces/server2/s4/resolve/main/server.js
125 kB
"use strict";
const http = require("http");
const fs = require("fs");
const os = require("os");
const path = require("path");
const crypto = require("crypto");
const { TelegramClient, Api } = require("teleproto");
const { StringSession } = require("teleproto/sessions");
const PORT = Number(process.env.PORT || 7860);
const RAW_ORIGIN = process.env.ALLOWED_ORIGIN || "https://dublk2000.pages.dev";
let SITE_ORIGIN = "https://dublk2000.pages.dev";
try {
const u = new URL(RAW_ORIGIN);
if (u.protocol === "https:") SITE_ORIGIN = u.origin;
} catch { }
const SITE_HOST = new URL(SITE_ORIGIN).hostname.toLowerCase();
const SITE_HOSTS = new Set([SITE_HOST]);
const CHANNEL_ID = process.env.TELEGRAM_CHANNEL_ID || "";
const API_ID = Number(process.env.TELEGRAM_API_ID || 0);
const API_HASH = process.env.TELEGRAM_API_HASH || "";
const STREAM_SECRET = process.env.STREAM_SECRET || "";
const ROLE = (process.env.NODE_ROLE || "stream").toLowerCase();
const OWNER_UID = String(process.env.OWNER_UID || "").trim();
const OWNER_VIP_UNTIL = Number(process.env.OWNER_VIP_UNTIL || 0);
const HASH_LEN = 6;
const TOKEN_TTL = 14400;
const MB = 1024 * 1024;
const CPU_N = Math.max(1, (os.cpus() || []).length || 2);
function cgroupLimitBytes() {
const paths = ["/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"];
for (const p of paths) {
try {
const raw = fs.readFileSync(p, "utf8").trim();
if (!raw || raw === "max") continue;
const n = Number(raw);
if (Number.isFinite(n) && n > 64 * MB) return Math.min(n, os.totalmem() || n);
} catch { }
}
return 0;
}
const CGROUP_BYTES = cgroupLimitBytes();
const RAM_BYTES = CGROUP_BYTES || os.totalmem() || (16 * 1024 * MB);
const CHUNK_SIZE = 512 * 1024;
const HOT_HEAD = 32 * MB;
const HOT_TAIL = 12 * MB;
const STREAM_WINDOW = 32 * MB;
const PROBE_HEAD = 8 * MB;
const BOT_MAX = 100;
const PIPE_FIRST_MS = 60000;
const PIPE_IDLE_MS = 22000;
const PIPE_MAX_MS = 6 * 60 * 60 * 1000;
const RANGE_LOOKAHEAD = 8;
const WARM_AHEAD = 6;
const WARM_BUDGET_BYTES = 128 * MB;
let warmBytesInFlight = 0;
const WARM_BATCH = Math.max(2, Math.min(4, CPU_N * 2));
const IP_STREAM_MAX = 20;
const IP_TITLE_MAX = 40;
const UID_STREAM_MAX = 8;
const UID_TITLE_MAX = 20;
const TITLE_PIPE_MAX = 400;
const GLOBAL_PIPE_MAX = 20000;
const DISK_SLICE_DIR = "/tmp/dlk_slice";
const DISK_MAX_BYTES = 24 * 1024 * 1024 * 1024;
const DISK_FREE_MIN_BYTES = 4 * 1024 * 1024 * 1024;
const HOT_BYTES_MAX = Math.min(3072 * MB, Math.max(1024 * MB, Math.floor(RAM_BYTES * 0.2)));
const BODY_MAX = 262144;
const FILE_TTL = 20 * 60 * 1000;
const LVL_TTL = 60000;
const FB_PROJECT = process.env.FIREBASE_PROJECT_ID || "";
const FB_DB = String(process.env.FIREBASE_DB_URL || "").replace(/\/?$/, "/");
const FB_SECRET = process.env.FIREBASE_DB_SECRET || "";
const STRIPE_KEY = process.env.STRIPE_SECRET_KEY || "";
const STRIPE_WH = process.env.STRIPE_WEBHOOK_SECRET || "";
const RC_SIGN = process.env.RC_SIGN_KEY || "";
const SPACE_FALLBACK = [
"https://dublk2000-s1.hf.space",
"https://dublk2000-s2.hf.space",
"https://server2-s3.hf.space",
"https://server2-s4.hf.space",
"https://server2-s5.hf.space"
];
const SPACE_URLS = String(process.env.SPACE_URLS || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
if (!SPACE_URLS.length) SPACE_URLS.push(...SPACE_FALLBACK);
const PLANS = {
day: { amount: 99, label: "1 Day VIP", sec: 86400, price: "0.99" },
week: { amount: 199, label: "1 Week VIP", sec: 604800, price: "1.99" },
month: { amount: 599, label: "1 Month VIP", sec: 2592000, price: "5.99" }
};
const HOME_URL = SITE_ORIGIN + "/";
const BRAND_URL = SITE_ORIGIN + "/assets/brand-mark.png";
const deriveKey = STREAM_SECRET
? (info) => crypto.hkdfSync("sha256", Buffer.from(STREAM_SECRET, "utf8"), Buffer.from("dublk2000"), Buffer.from(info), 32)
: null;
const aesKey = deriveKey ? deriveKey("aes-256-gcm-ticket") : null;
const hmacKey = deriveKey ? deriveKey("hmac-sha256-ticket") : null;
const adminKey = deriveKey ? Buffer.from(deriveKey("admin-api-v1")).toString("hex") : "";
const ADMIN_KEY_ENV = String(process.env.ADMIN_API_KEY || "");
const ADMIN_KEY = ADMIN_KEY_ENV || adminKey;
function siteHostOf(req) {
const o = String((req && req.headers && (req.headers.origin || req.headers.referer)) || "");
try {
if (!o) return "";
return new URL(o.includes("://") ? o : "https://" + o).hostname.toLowerCase();
} catch {
return "";
}
}
const bots = [];
const botSlots = [];
const fileCache = new Map();
const inflightFile = new Map();
const hotMap = new Map();
const inflightHot = new Map();
const durCache = new Map();
const mdatCache = new Map();
const inflightDur = new Map();
const lvlCache = new Map();
const rateMap = new Map();
const ipStreams = new Map();
const ipTitles = new Map();
const uidStreams = new Map();
const uidTitles = new Map();
const titlePipes = new Map();
const paidOrders = new Map();
const stripeEvents = new Set();
const payLocks = new Map();
const tokCache = new Map();
const genAnonCache = new Map();
let livePipes = 0;
let fbKeys = { certs: null, exp: 0 };
let rr = 0;
let httpServer = null;
let shuttingDown = false;
function timingSafeEq(a, b) {
const x = Buffer.from(String(a));
const y = Buffer.from(String(b));
if (x.length !== y.length) return false;
return crypto.timingSafeEqual(x, y);
}
function packHash(name, size, mime, id) {
return crypto.createHash("md5")
.update(String(name || ""))
.update(String(size || 0))
.update(String(mime || ""))
.update(String(id || 0))
.digest("hex")
.slice(0, HASH_LEN);
}
function sealTicket(obj) {
if (!aesKey || !hmacKey) throw new Error("misconfigured");
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", aesKey, iv);
const pt = Buffer.from(JSON.stringify(obj), "utf8");
const ct = Buffer.concat([cipher.update(pt), cipher.final()]);
const tag = cipher.getAuthTag();
const blob = Buffer.concat([iv, ct, tag]);
const mac = crypto.createHmac("sha256", hmacKey).update(blob).digest();
return Buffer.concat([blob, mac]).toString("hex");
}
function openTicket(hex) {
if (!aesKey || !hmacKey) return null;
if (!/^[0-9a-f]+$/i.test(hex) || hex.length < 120) return null;
const raw = Buffer.from(hex, "hex");
if (raw.length < 12 + 16 + 32) return null;
const blob = raw.subarray(0, raw.length - 32);
const mac = raw.subarray(raw.length - 32);
const expect = crypto.createHmac("sha256", hmacKey).update(blob).digest();
if (!crypto.timingSafeEqual(mac, expect)) return null;
const iv = blob.subarray(0, 12);
const tag = blob.subarray(blob.length - 16);
const ct = blob.subarray(12, blob.length - 16);
try {
const dec = crypto.createDecipheriv("aes-256-gcm", aesKey, iv);
dec.setAuthTag(tag);
const pt = Buffer.concat([dec.update(ct), dec.final()]).toString("utf8");
return JSON.parse(pt);
} catch {
return null;
}
}
function cors(req, res) {
const o = req.headers.origin || "";
const allow = isSiteOrigin(o);
res.setHeader("Access-Control-Allow-Origin", allow ? o : SITE_ORIGIN);
res.setHeader("Vary", "Origin");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,HEAD,OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Authorization,Content-Type,Range");
res.setHeader("Access-Control-Expose-Headers", "Content-Range,Content-Length,Accept-Ranges,Content-Type");
res.setHeader("Access-Control-Max-Age", "86400");
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "origin");
try { res.removeHeader("Server"); } catch { }
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("X-Robots-Tag", "noindex, nofollow, noarchive");
res.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=(), usb=(), payment=(), browsing-topics=()");
res.setHeader("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload");
res.setHeader("X-Permitted-Cross-Domain-Policies", "none");
res.setHeader("X-XSS-Protection", "0");
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
res.setHeader("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'");
}
function json(res, code, body, cache) {
if (res.headersSent || res.writableEnded) return;
const s = JSON.stringify(body);
res.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": cache || "no-store" });
res.end(s);
}
function destOk(req, allow) {
const d = String(req.headers["sec-fetch-dest"] || "").toLowerCase();
if (!d) return true;
if (allow.indexOf(d) >= 0) return true;
if (d === "json" && allow.indexOf("empty") >= 0) return true;
return false;
}
function streamDestOk(req) {
const d = String(req.headers["sec-fetch-dest"] || "").toLowerCase();
if (!d) return true;
const block = [
"document", "iframe", "frame", "fencedframe", "embed", "object",
"script", "style", "manifest", "worker", "sharedworker", "serviceworker",
"report", "xslt", "image", "font", "json"
];
return block.indexOf(d) < 0;
}
function streamLock() {
return {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "no-referrer",
"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet, noimageindex",
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), usb=(), payment=(), browsing-topics=()",
"Cross-Origin-Resource-Policy": "cross-origin",
"Access-Control-Expose-Headers": "Content-Range,Content-Length,Accept-Ranges,Content-Type",
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
"X-Permitted-Cross-Domain-Policies": "none",
"X-XSS-Protection": "0"
};
}
function isIp(s) {
s = String(s || "").trim();
if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(s)) {
return s.split(".").every((n) => Number(n) <= 255);
}
if (s.includes(":") && /^[0-9a-f:.]+$/i.test(s) && s.length >= 3 && s.length <= 45) return true;
return false;
}
function isPrivIp(s) {
s = String(s || "").replace(/^::ffff:/i, "");
if (/^10\./.test(s) || /^127\./.test(s) || /^192\.168\./.test(s) || /^169\.254\./.test(s)) return true;
if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(s)) return true;
if (s === "::1" || /^fc/i.test(s) || /^fd/i.test(s) || /^fe80/i.test(s)) return true;
return false;
}
function pickClientIp(list) {
const hops = list.map((x) => String(x || "").trim()).filter(isIp);
for (let i = hops.length - 1; i >= 0; i--) {
if (!isPrivIp(hops[i])) return hops[i].replace(/^::ffff:/i, "");
}
if (hops.length) return hops[hops.length - 1].replace(/^::ffff:/i, "");
return "";
}
function clientIp(req) {
const hops = [];
const xf = req.headers["x-forwarded-for"];
if (xf) hops.push(...String(xf).split(","));
else {
const real = String(req.headers["x-real-ip"] || "").trim();
if (real) hops.push(real);
}
const picked = pickClientIp(hops);
if (picked) return picked;
const sock = (req.socket && req.socket.remoteAddress) || "0";
return isIp(sock) ? String(sock).replace(/^::ffff:/i, "") : "0";
}
function spaceHostnames() {
return SPACE_URLS.map((u) => {
try { return new URL(u).hostname.toLowerCase(); } catch { return ""; }
}).filter(Boolean);
}
function publicSpaceOrigin(req) {
const h = String(req.headers.host || "").split(":")[0].toLowerCase();
if (h && spaceHostnames().indexOf(h) >= 0) return "https://" + h;
return SPACE_URLS[0] || SPACE_FALLBACK[0];
}
function errText(e) {
return String(e && (e.errorMessage || e.message || e) || "");
}
function isFileRef(e) {
return /FILE_REFERENCE/i.test(errText(e));
}
function isFlood(e) {
return /FLOOD_WAIT/i.test(errText(e)) || (e && e.seconds > 0 && /flood/i.test(String(e.className || e.name || "")));
}
function coolBot(bot, e) {
if (!bot) return;
const t = errText(e);
const m = /FLOOD_WAIT[_ ]?(\d+)/i.exec(t);
const sec = m ? Number(m[1]) : Number(e && e.seconds || 0);
if (sec > 8) bot.coolUntil = Date.now() + Math.min(sec, 90) * 1000;
if (/AUTH_KEY|SESSION_REVOKED|USER_DEACTIVATED|PHONE_NUMBER_BANNED/i.test(t)) bot.ready = false;
if (/AUTH_KEY_UNREGISTERED|SESSION_REVOKED|USER_DEACTIVATED_BAN|PHONE_NUMBER_BANNED|USER_DEACTIVATED/i.test(t)) bot.dead = true;
}
function botUsable(b) {
if (!b || b.dead || !b.ready) return false;
if (b.coolUntil && Date.now() < b.coolUntil) return false;
if (b.client && b.client.connected === false) return false;
return (b.tgLoad || 0) < BOT_MAX;
}
function pipeDead(req, res) {
return !!(req.destroyed || res.destroyed || res.writableEnded || res.writableFinished);
}
function waitDrain(req, res) {
return new Promise((resolve) => {
if (pipeDead(req, res)) return resolve();
let done = false;
const finish = () => {
if (done) return;
done = true;
clearTimeout(tm);
res.off("drain", finish);
res.off("close", finish);
req.off("close", finish);
resolve();
};
const tm = setTimeout(finish, 180000);
res.once("drain", finish);
res.once("close", finish);
req.once("close", finish);
});
}
function takeStream(ip, uid, msgId) {
if (livePipes >= GLOBAL_PIPE_MAX) return false;
const title = String(msgId || "");
const tn = (titlePipes.get(title) || 0) + 1;
if (title && tn > TITLE_PIPE_MAX) return false;
const n = (ipStreams.get(ip) || 0) + 1;
if (n > IP_STREAM_MAX) return false;
let ipSet = ipTitles.get(ip);
if (!ipSet) ipSet = new Set();
const ipNew = title && !ipSet.has(title);
if (ipNew && ipSet.size >= IP_TITLE_MAX) return false;
const u = uid && uid !== "anon" ? String(uid) : "";
if (u) {
const un = (uidStreams.get(u) || 0) + 1;
if (un > UID_STREAM_MAX) return false;
const uidSet = uidTitles.get(u) || new Set();
const uidNew = title && !uidSet.has(title);
if (uidNew && uidSet.size >= UID_TITLE_MAX) return false;
uidStreams.set(u, un);
if (title) {
uidSet.add(title);
uidTitles.set(u, uidSet);
}
}
ipStreams.set(ip, n);
if (title) {
ipSet.add(title);
ipTitles.set(ip, ipSet);
titlePipes.set(title, tn);
}
livePipes += 1;
return true;
}
function freeStream(ip, uid, msgId) {
livePipes = Math.max(0, livePipes - 1);
const n = (ipStreams.get(ip) || 1) - 1;
if (n <= 0) {
ipStreams.delete(ip);
ipTitles.delete(ip);
} else ipStreams.set(ip, n);
const title = String(msgId || "");
if (title && titlePipes.has(title)) {
const tn = titlePipes.get(title) - 1;
if (tn <= 0) titlePipes.delete(title);
else titlePipes.set(title, tn);
}
const u = uid && uid !== "anon" ? String(uid) : "";
if (u) {
const un = (uidStreams.get(u) || 1) - 1;
if (un <= 0) {
uidStreams.delete(u);
uidTitles.delete(u);
} else uidStreams.set(u, un);
}
}
function sweepMaps() {
const now = Date.now();
if (fileCache.size) {
for (const [k, v] of fileCache) {
if (!v || !v.ts || now - v.ts > FILE_TTL) fileCache.delete(k);
}
if (fileCache.size > 50000) {
const arr = [...fileCache.entries()].sort((a, b) => (a[1].ts || 0) - (b[1].ts || 0));
for (let i = 0; i < arr.length - 35000; i++) fileCache.delete(arr[i][0]);
}
}
if (hotMap.size) {
for (const [k, v] of hotMap) {
if (!v || !v.ts || now - v.ts > FILE_TTL) hotMap.delete(k);
}
trimHot();
}
if (lvlCache.size > 10000) {
for (const [k, v] of lvlCache) {
if (!v || now - v.ts > LVL_TTL * 4) lvlCache.delete(k);
}
}
if (lvlCache.size > 20000) {
const arr = [...lvlCache.entries()].sort((a, b) => (a[1].ts || 0) - (b[1].ts || 0));
for (let i = 0; i < arr.length - 15000; i++) lvlCache.delete(arr[i][0]);
}
if (durCache.size > 50000) {
const ids = [...durCache.keys()].slice(0, durCache.size - 35000);
for (const id of ids) durCache.delete(id);
}
if (mdatCache.size > 50000) {
const ids = [...mdatCache.keys()].slice(0, mdatCache.size - 35000);
for (const id of ids) mdatCache.delete(id);
}
if (rateMap.size > 20000) {
const slot = Math.floor(now / 60000);
for (const k of rateMap.keys()) {
if (!k.endsWith(":" + slot) && !k.endsWith(":" + (slot - 1))) rateMap.delete(k);
}
}
if (paidOrders.size > 10000) {
const cut = now - 7 * 24 * 3600 * 1000;
for (const [k, ts] of paidOrders) {
if (ts < cut) paidOrders.delete(k);
}
}
if (tokCache.size) {
for (const [k, v] of tokCache) {
if (!v || (v.exp && v.exp * 1000 < now + 5000) || now - v.ts > 120000) tokCache.delete(k);
}
if (tokCache.size > 2000) {
const arr = [...tokCache.entries()].sort((a, b) => (a[1].ts || 0) - (b[1].ts || 0));
for (let i = 0; i < arr.length - 1200; i++) tokCache.delete(arr[i][0]);
}
}
if (genAnonCache.size) {
for (const [k, v] of genAnonCache) {
if (!v || !v.exp || v.exp < now + 8000) genAnonCache.delete(k);
}
if (genAnonCache.size > 25000) {
const arr = [...genAnonCache.entries()].sort((a, b) => (a[1].ts || 0) - (b[1].ts || 0));
for (let i = 0; i < arr.length - 15000; i++) genAnonCache.delete(arr[i][0]);
}
}
}
function hotBytes() {
let n = 0;
for (const h of hotMap.values()) {
if (h.head) n += h.head.length;
if (h.tail) n += h.tail.length;
}
return n;
}
function trimHot() {
if (hotMap.size <= 8) return;
let bytes = hotBytes();
if (bytes <= HOT_BYTES_MAX && hotMap.size <= 96) return;
const arr = [...hotMap.entries()].sort((a, b) => (a[1].ts || 0) - (b[1].ts || 0));
for (let i = 0; i < arr.length - 8; i++) {
if (bytes <= HOT_BYTES_MAX && hotMap.size <= 64) break;
const h = arr[i][1];
if (h.head) bytes -= h.head.length;
if (h.tail) bytes -= h.tail.length;
hotMap.delete(arr[i][0]);
}
}
function withTime(p, ms, fallback) {
let t;
return Promise.race([
Promise.resolve(p).then((v) => {
clearTimeout(t);
return v;
}, () => {
clearTimeout(t);
return fallback;
}),
new Promise((r) => {
t = setTimeout(() => r(fallback), ms);
})
]);
}
function busyJson(res) {
if (res.headersSent || res.writableEnded) return;
res.setHeader("Retry-After", "1");
json(res, 503, { error: "busy" });
}
function limited(ip) {
const now = Date.now();
const slot = Math.floor(now / 60000);
const key = ipNet(ip) + ":" + slot;
const n = (rateMap.get(key) || 0) + 1;
rateMap.set(key, n);
return n > 3000;
}
function slotOver(key, max) {
const slot = Math.floor(Date.now() / 60000);
const k = key + ":" + slot;
const n = (rateMap.get(k) || 0) + 1;
rateMap.set(k, n);
return n > max;
}
function mintLimited(ip) {
const s = String(ip || "0");
return slotOver("mint:" + s, 120) || slotOver("mintn:" + ipNet(s), 600);
}
function mintBlocked(ip) {
const slot = Math.floor(Date.now() / 60000);
return (rateMap.get("badm:" + String(ip || "0") + ":" + slot) || 0) > 10000;
}
function mintFailed(ip) {
return slotOver("badm:" + String(ip || "0"), 60);
}
function isSiteOrigin(o) {
o = String(o || "").trim();
if (!o || o.toLowerCase() === "null") return false;
try {
const u = new URL(o.includes("://") ? o : "https://" + o);
if (u.protocol !== "https:" || u.username || u.password) return false;
if (u.port && u.port !== "443") return false;
return SITE_HOSTS.has(u.hostname.toLowerCase());
} catch {
return false;
}
}
function playExt(mime, name) {
const t = httpVideoType(mime, name);
if (t.includes("webm")) return ".webm";
if (t.includes("ogg")) return ".ogv";
if (t.includes("matroska")) return ".mkv";
return ".mp4";
}
function fromSite(req) {
const o = String(req.headers.origin || "").trim();
if (o && o.toLowerCase() !== "null") return isSiteOrigin(o);
const r = String(req.headers.referer || "");
if (!r) return false;
try {
return isSiteOrigin(new URL(r).origin);
} catch {
return false;
}
}
function denyHot(req, res) {
if (fromSite(req)) return false;
json(res, 403, { error: "forbidden" });
return true;
}
function ipNet(ip) {
let s = String(ip || "").replace(/^::ffff:/i, "");
if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(s)) {
const p = s.split(".");
return "4." + p[0] + "." + p[1] + "." + p[2];
}
const parts = s.split(":").filter(Boolean);
return "6." + parts.slice(0, 4).join(":");
}
function ipTag(ip) {
if (!hmacKey) return "";
return crypto.createHmac("sha256", hmacKey).update("net:" + ipNet(ip)).digest("hex").slice(0, 16);
}
function uaTag(ua) {
if (!hmacKey) return "";
const s = String(ua || "").toLowerCase();
const os = /android/.test(s) ? "android" : /iphone|ipad|ipod/.test(s) ? "ios" : /windows/.test(s) ? "win" : /mac os|macintosh/.test(s) ? "mac" : "x";
const br = (s.match(/chrome\/\d+/) || s.match(/crios\/\d+/) || s.match(/safari\/\d+/) || ["x"])[0];
return crypto.createHmac("sha256", hmacKey).update("ua:" + os + ":" + br).digest("hex").slice(0, 16);
}
function ticketNetOk(ticket, ip) {
const p = String(ticket && ticket.p || "");
if (!p) return false;
const now = ipTag(ip);
if (!now) return false;
return timingSafeEq(p, now);
}
function ticketUaOk(ticket, ua) {
const a = String(ticket && ticket.a || "");
if (!a) return false;
if (!String(ua || "").trim()) return false;
const now = uaTag(ua);
if (!now) return false;
return timingSafeEq(a, now);
}
function payLimited(uid, ip) {
const slot = Math.floor(Date.now() / 60000);
const a = "pay:" + uid + ":" + slot;
const b = "payip:" + ipNet(ip) + ":" + slot;
const na = (rateMap.get(a) || 0) + 1;
const nb = (rateMap.get(b) || 0) + 1;
rateMap.set(a, na);
rateMap.set(b, nb);
return na > 8 || nb > 12;
}
async function googleCerts() {
if (fbKeys.certs && Date.now() < fbKeys.exp) return fbKeys.certs;
const r = await fetch("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com", {
signal: AbortSignal.timeout(4000)
});
if (!r.ok) throw new Error("certs");
const certs = await r.json();
const cc = r.headers.get("cache-control") || "";
const m = /max-age=(\d+)/.exec(cc);
const age = m ? Number(m[1]) * 1000 : 3600000;
fbKeys = { certs, exp: Date.now() + Math.max(60000, age - 60000) };
return certs;
}
async function verifyIdToken(raw) {
if (!raw) return null;
const token = String(raw).replace(/^Bearer\s+/i, "").trim();
const ck = crypto.createHash("sha256").update(token).digest("hex");
const cached = tokCache.get(ck);
if (cached && cached.p && cached.exp * 1000 > Date.now() + 8000 && Date.now() - cached.ts < 90000) return cached.p;
const parts = token.split(".");
if (parts.length !== 3) return null;
let header;
let payload;
try {
header = JSON.parse(Buffer.from(parts[0], "base64url").toString("utf8"));
payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
} catch {
return null;
}
if (header.alg !== "RS256" || !header.kid) return null;
const certs = await googleCerts();
const pem = Object.prototype.hasOwnProperty.call(certs, header.kid) ? certs[header.kid] : null;
if (!pem) return null;
const ok = crypto.createVerify("SHA256").update(parts[0] + "." + parts[1]).verify(pem, parts[2], "base64url");
if (!ok) return null;
const now = Math.floor(Date.now() / 1000);
if (payload.exp <= now || payload.iat > now + 60) return null;
if (payload.auth_time && payload.auth_time > now + 60) return null;
if (payload.nbf && payload.nbf > now + 60) return null;
if (payload.aud !== FB_PROJECT) return null;
if (payload.iss !== "https://securetoken.google.com/" + FB_PROJECT) return null;
if (!payload.sub || payload.sub.length > 128) return null;
tokCache.set(ck, { p: payload, exp: payload.exp, ts: Date.now() });
return payload;
}
async function rtdb(path, method, body) {
if (!FB_SECRET) throw new Error("db");
const url = FB_DB + path.replace(/^\//, "") + ".json?auth=" + encodeURIComponent(FB_SECRET);
const r = await fetch(url, {
method,
headers: body == null ? undefined : { "Content-Type": "application/json" },
body: body == null ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(4000)
});
if (!r.ok) throw new Error("db " + r.status);
const t = await r.text();
return t ? JSON.parse(t) : null;
}
const LVL_MISS = { miss: 1 };
function vipExpirySec(sub) {
if (!sub || typeof sub !== "object") return 0;
const exp = Number(sub.expiry || sub.expiresAt || sub.expires || sub.expiration || sub.exp || 0);
if (!Number.isFinite(exp) || exp <= 0) return 0;
return exp > 1e11 ? Math.floor(exp / 1000) : exp;
}
function vipActive(sub) {
if (!sub || typeof sub !== "object") return false;
if (sub.status !== "active") return false;
const exp = vipExpirySec(sub);
return exp > Math.floor(Date.now() / 1000);
}
function publicSub(sub) {
if (!sub || typeof sub !== "object") return null;
const exp = vipExpirySec(sub);
return {
status: String(sub.status || ""),
plan: String(sub.plan || "").slice(0, 24),
label: String(sub.label || "").slice(0, 40),
expiry: exp,
autoRenew: sub.autoRenew === true
};
}
function googlePayUser(idp) {
if (!idp || !idp.sub) return false;
const fb = idp.firebase;
if (!fb || fb.sign_in_provider !== "google.com") return false;
if (idp.email_verified === false) return false;
return true;
}
function googleUid(idp) {
if (!googlePayUser(idp) || !uidOk(idp.sub)) return null;
return idp.sub;
}
function payEmail(idp) {
const em = String(idp && idp.email || "").trim().toLowerCase();
if (!em || em.length > 200 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(em)) return "";
return em;
}
function uidOk(uid) {
return typeof uid === "string" && /^[A-Za-z0-9_-]{8,128}$/.test(uid);
}
function cleanVid(v) {
const s = String(v || "").trim();
return /^[A-Za-z0-9_-]{8,64}$/.test(s) ? s : "";
}
function payErrorText(e) {
return String(e || "").replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 120);
}
const PAY_STAGES = {
plan_click: 1,
checkout_started: 2,
checkout_redirect: 3,
return_success: 3,
cancelled: 4,
start_failed: 4,
confirm_failed: 4,
expired: 4,
failed: 4,
paid: 5
};
function verifyProof(proof, ip) {
if (!RC_SIGN) return true;
const m = /^(\d{10})\.([0-9a-f]{64})$/.exec(String(proof || ""));
if (!m) return false;
const exp = Number(m[1]);
const now = Math.floor(Date.now() / 1000);
if (exp < now || exp > now + 600) return false;
const mac = crypto.createHmac("sha256", RC_SIGN).update("vip:" + ip + ":" + exp).digest("hex");
return timingSafeEq(mac, m[2]);
}
async function stripeSession(id) {
if (!STRIPE_KEY || !id || !/^cs_[A-Za-z0-9_]+$/.test(String(id))) return null;
const r = await fetch("https://api.stripe.com/v1/checkout/sessions/" + encodeURIComponent(id), {
headers: { Authorization: "Bearer " + STRIPE_KEY },
signal: AbortSignal.timeout(12000)
});
const d = await r.json();
if (!r.ok || !d || d.object !== "checkout.session") return null;
return d;
}
async function accessLevel(uid) {
if (!uid) return "anonymous";
const hit = lvlCache.get(uid);
if (hit && Date.now() - hit.ts < LVL_TTL) return hit.lvl;
let lvl = "anonymous";
try {
const sub = await withTime(rtdb("users/" + uid + "/subscription", "GET"), 3500, LVL_MISS);
if (sub === LVL_MISS) return "anonymous";
const exp = sub && vipActive(sub) ? vipExpirySec(sub) : 0;
if (exp > Math.floor(Date.now() / 1000)) lvl = "subscribed";
lvlCache.set(uid, { lvl, exp: exp, ts: Date.now() });
} catch { }
return lvl;
}
function httpVideoType(mime, name) {
const s = String(mime || "").toLowerCase();
const n = String(name || "").toLowerCase();
if (s.includes("webm") || n.endsWith(".webm")) return "video/webm";
if (s.includes("ogg") || n.endsWith(".ogv") || n.endsWith(".ogg")) return "video/ogg";
if (s.includes("matroska") || n.endsWith(".mkv")) return "video/x-matroska";
if (s.includes("quicktime") || n.endsWith(".mov")) return "video/mp4";
if (s.startsWith("video/")) return s.split(";")[0].trim();
if (n.endsWith(".mp4") || n.endsWith(".m4v") || n.endsWith(".mpeg") || n.endsWith(".mpg")) return "video/mp4";
return "video/mp4";
}
function pickBot(preferIdx, skipIdx, msgId) {
if (!bots.length) return null;
const readyBots = bots.filter((b) => b && b.ready && (!b.coolUntil || Date.now() >= b.coolUntil) && (b.client && b.client.connected !== false) && b.idx !== skipIdx);
if (!readyBots.length) return null;
const pool = readyBots.filter((b) => (b.tgLoad || 0) < BOT_MAX);
if (!pool.length) return null;
let use = pool;
if (msgId != null) {
const id = String(msgId);
const hot = use.filter((b) => {
const hit = fileCache.get(id + ":" + b.idx);
return hit && Date.now() - hit.ts < FILE_TTL;
});
if (hot.length) {
const hotMin = Math.min(...hot.map((b) => (b.tgLoad || 0)));
const allMin = Math.min(...use.map((b) => (b.tgLoad || 0)));
if (hotMin <= allMin + 2) use = hot;
}
}
const min = Math.min(...use.map((b) => (b.tgLoad || 0)));
if (preferIdx != null) {
const sticky = use.find((b) => b.idx === preferIdx && (b.tgLoad || 0) <= min + 1);
if (sticky) return sticky;
}
const even = use.filter((b) => (b.tgLoad || 0) === min);
const bot = even[rr % even.length];
rr += 1;
return bot;
}
function sweepBots() {
for (const b of bots) {
if (b.dead) continue;
if (b.client && b.client.connected === false) b.ready = false;
else if (b.client && b.client.connected !== false && !b.ready && !(b.coolUntil && Date.now() < b.coolUntil)) b.ready = true;
}
}
async function startBot(token, idx) {
const existing = bots.find((b) => b.idx === idx);
if (existing && !existing.dead && existing.ready && existing.client && existing.client.connected !== false) {
existing.nextTry = 0;
existing.fails = 0;
return;
}
const client = new TelegramClient(new StringSession(""), API_ID, API_HASH, {
connectionRetries: 8,
reconnectRetries: Infinity,
retryDelay: 1500,
autoReconnect: true,
floodSleepThreshold: 2,
requestRetries: 3,
downloadRetries: 3,
maxConcurrentDownloads: 32,
downloadPool: { inflightPerDc: 8, maxSessions: 6, sessions: 6, requestDeadlineMs: 28000 }
});
client.setLogLevel("error");
let timer = null;
try {
await Promise.race([
client.start({ botAuthToken: token }),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error("bot_timeout")), 30000);
})
]);
} catch (e) {
try { await client.disconnect(); } catch { }
throw e;
} finally {
if (timer) clearTimeout(timer);
}
if (existing) {
const old = existing.client;
existing.client = client;
existing.token = token;
existing.ready = true;
existing.dead = false;
existing.load = 0;
existing.tgLoad = 0;
existing.coolUntil = 0;
existing.fails = 0;
existing.nextTry = 0;
if (old && old !== client) {
try { old.disconnect(); } catch { }
}
return;
}
bots.push({ client, token, idx, ready: true, dead: false, load: 0, tgLoad: 0, coolUntil: 0, fails: 0, nextTry: 0 });
}
async function reviveBots() {
sweepBots();
const now = Date.now();
for (const slot of botSlots) {
if (slot.dead) continue;
if (now < (slot.nextTry || 0)) continue;
const b = bots.find((x) => x.idx === slot.idx);
if (b && b.ready && b.client && b.client.connected !== false) {
slot.fails = 0;
slot.nextTry = 0;
continue;
}
try {
await startBot(slot.token, slot.idx);
slot.fails = 0;
slot.nextTry = 0;
} catch (e) {
if (/AUTH_KEY_UNREGISTERED|SESSION_REVOKED|USER_DEACTIVATED_BAN|PHONE_NUMBER_BANNED|USER_DEACTIVATED/i.test(errText(e))) {
slot.dead = true;
process.stderr.write("bot " + slot.idx + " disabled: " + errText(e) + "\n");
continue;
}
slot.fails = (slot.fails || 0) + 1;
const base = Math.min(300000, 15000 * Math.pow(2, Math.min(slot.fails - 1, 4)));
slot.nextTry = Date.now() + base + Math.floor(Math.random() * 5000);
if (slot.fails <= 3 || slot.fails % 10 === 0) {
const wait = Math.max(0, Math.round((slot.nextTry - Date.now()) / 1000));
process.stderr.write("bot " + slot.idx + " revive: " + errText(e) + " (retry in " + wait + "s)\n");
}
}
}
}
function dropFile(msgId, bot) {
if (bot) {
fileCache.delete(String(msgId) + ":" + bot.idx);
return;
}
const p = String(msgId) + ":";
for (const k of [...fileCache.keys()]) {
if (k === String(msgId) || k.startsWith(p)) fileCache.delete(k);
}
}
function recFromMsg(msg, botIdx) {
if (!msg || msg.deleted) return null;
const doc = msg.video || msg.document;
if (!doc) return null;
let name = "video.mp4";
let duration = 0;
const attrs = doc.attributes || [];
for (const a of attrs) {
if (a && a.className === "DocumentAttributeFilename" && a.fileName) name = a.fileName;
const n = Number(a && a.duration);
if (Number.isFinite(n) && n > duration) duration = n;
}
const cached = durCache.get(String(msg.id));
if (cached > 1) duration = cached;
const rec = {
loc: new Api.InputDocumentFileLocation({
id: doc.id,
accessHash: doc.accessHash,
fileReference: doc.fileReference,
thumbSize: ""
}),
size: Number(doc.size || 0),
mime: doc.mimeType || "video/mp4",
name,
id: String(doc.id),
hash: packHash(name, Number(doc.size || 0), doc.mimeType || "video/mp4", String(doc.id)),
dcId: doc.dcId,
duration,
doc,
ts: Date.now()
};
if (duration > 1) durCache.set(String(msg.id), duration);
if (botIdx != null) fileCache.set(String(msg.id) + ":" + botIdx, rec);
return rec;
}
function normFile(name) {
return String(name || "")
.replace(/\.[a-z0-9]{2,5}$/i, "")
.toLowerCase()
.replace(/[._]+/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function seriesFamily(name) {
const n = normFile(name);
const seasonEp = n.match(/^(.*?s\s*\d+)\s*e\s*\d+\b/);
if (seasonEp) return seasonEp[1].replace(/\s+/g, " ").trim();
const ep = n.replace(/\b(?:e|ep|episode)\s*\d+\b/g, " ");
return ep.replace(/\b(?:1080p|720p|480p|2160p|4k|full\s*hd|hd)\b/g, " ").replace(/\s+/g, " ").trim();
}
function episodeNum(name) {
const n = normFile(name);
const m = n.match(/\be\s*(\d+)\b/) || n.match(/\b(?:ep|episode)\s*(\d+)\b/);
return m ? Number(m[1]) : 0;
}
async function loadFile(bot, msgId) {
const msgs = await bot.client.getMessages(CHANNEL_ID, { ids: msgId });
const rec = recFromMsg(msgs && msgs[0], bot.idx);
if (!rec) {
const msg = msgs && msgs[0];
if (!msg || msg.deleted) throw new Error("missing");
throw new Error("media");
}
return rec;
}
async function expandFamily(bot, seedId) {
const seed = await fileFromMsg(bot, seedId);
const fam = seriesFamily(seed.name);
const lo = Math.max(1, seedId - 30);
const hi = seedId + 40;
const ids = [];
for (let i = lo; i <= hi; i++) ids.push(i);
let msgs = [];
try {
msgs = await bot.client.getMessages(CHANNEL_ID, { ids });
} catch {
return [{ msgId: seedId, rec: seed }];
}
const hits = [];
const seen = new Set();
for (const msg of msgs || []) {
const rec = recFromMsg(msg, bot.idx);
if (!rec || !msg) continue;
if (fam && seriesFamily(rec.name) !== fam) continue;
if (seen.has(msg.id)) continue;
seen.add(msg.id);
hits.push({ msgId: msg.id, rec });
}
if (!hits.some((h) => h.msgId === seedId)) hits.push({ msgId: seedId, rec: seed });
hits.sort((a, b) => {
const ea = episodeNum(a.rec.name);
const eb = episodeNum(b.rec.name);
if (ea && eb && ea !== eb) return ea - eb;
return a.msgId - b.msgId;
});
return hits.slice(0, 40);
}
async function fileFromMsg(bot, msgId) {
const key = String(msgId) + ":" + bot.idx;
const hit = fileCache.get(key);
if (hit && Date.now() - hit.ts < FILE_TTL) {
hit.ts = Date.now();
const d = durCache.get(String(msgId));
if (d > 1) hit.duration = d;
return hit;
}
let p = inflightFile.get(key);
if (p) return p;
p = loadFile(bot, msgId).finally(() => inflightFile.delete(key));
inflightFile.set(key, p);
return p;
}
function fileFromAnyCache(msgId) {
const p = String(msgId) + ":";
const now = Date.now();
let best = null;
let minLoad = Infinity;
for (const [k, v] of fileCache) {
if (k.startsWith(p) && v && now - v.ts < FILE_TTL) {
v.ts = now;
const d = durCache.get(String(msgId));
if (d > 1) v.duration = d;
const idx = Number(k.slice(p.length));
const bot = bots.find((b) => b && b.idx === idx);
if (bot && botUsable(bot)) {
const load = bot.tgLoad || 0;
if (load < minLoad) {
minLoad = load;
best = { bot, rec: v };
if (load === 0) break;
}
}
}
}
return best;
}
async function fileFromPool(msgId, prefer, skipIdx) {
const cached = fileFromAnyCache(msgId);
if (cached && (skipIdx == null || cached.bot.idx !== skipIdx)) return cached;
const key = String(msgId) + ":" + String(skipIdx == null ? "_" : skipIdx);
let p = inflightFile.get("pool:" + key);
if (p) return p;
p = fileFromPoolWork(msgId, prefer, skipIdx).finally(() => inflightFile.delete("pool:" + key));
inflightFile.set("pool:" + key, p);
return p;
}
async function fileFromPoolWork(msgId, prefer, skipIdx) {
const cached = fileFromAnyCache(msgId);
if (cached && (skipIdx == null || cached.bot.idx !== skipIdx)) return cached;
const seen = new Set();
const order = [];
const first = prefer && botUsable(prefer) && prefer.idx !== skipIdx ? prefer : pickBot(prefer && prefer.idx, skipIdx, msgId);
if (first) order.push(first);
for (const b of bots) {
if (order.length >= Math.min(8, bots.length || 8)) break;
if (order.includes(b) || !botUsable(b) || b.idx === skipIdx) continue;
order.push(b);
}
let last = null;
for (const bot of order) {
if (seen.has(bot.idx)) continue;
seen.add(bot.idx);
try {
const rec = await fileFromMsg(bot, msgId);
return { bot, rec };
} catch (e) {
last = e;
dropFile(msgId, bot);
coolBot(bot, e);
}
}
throw last || new Error("file");
}
function durationFromMp4(buf) {
if (!buf || buf.length < 32) return 0;
const tag = Buffer.from("mvhd");
let from = 0;
while (from + 28 < buf.length) {
const i = buf.indexOf(tag, from);
if (i < 4 || i + 24 > buf.length) break;
const ver = buf[i + 4];
try {
if (ver === 1) {
if (i + 36 > buf.length) break;
const timescale = buf.readUInt32BE(i + 24);
const duration = Number(buf.readBigUInt64BE(i + 28));
if (timescale > 0 && duration > 0) {
const s = duration / timescale;
if (s > 1 && s < 86400) return s;
}
} else if (ver === 0) {
const timescale = buf.readUInt32BE(i + 16);
const duration = buf.readUInt32BE(i + 20);
if (timescale > 0 && duration > 0) {
const s = duration / timescale;
if (s > 1 && s < 86400) return s;
}
}
} catch { }
from = i + 4;
}
return 0;
}
async function peekDuration(bot, rec) {
if (!bot || !rec || !rec.size) return 0;
const take = Math.min(rec.size, HOT_TAIL);
async function readSpan(start, end) {
let acc = Buffer.alloc(0);
for await (const c of rangeChunks(bot, rec, start, end, () => acc.length >= take)) {
acc = Buffer.concat([acc, c]);
const d = durationFromMp4(acc);
if (d > 1) return d;
if (acc.length >= take) break;
}
return durationFromMp4(acc);
}
bot.load++;
try {
let d = await readSpan(rec.size - take, rec.size - 1);
if (d > 1) return d;
return await readSpan(0, take - 1);
} catch {
return 0;
} finally {
bot.load = Math.max(0, bot.load - 1);
}
}
async function fillDuration(bot, rec, msgId) {
const id = String(msgId || "");
if (!id) return 0;
if (durCache.has(id)) {
rec.duration = durCache.get(id);
return rec.duration;
}
if (rec.duration > 1) {
durCache.set(id, rec.duration);
return rec.duration;
}
const pendingHot = inflightHot.get(id);
if (pendingHot) {
try { await pendingHot; } catch { }
const h = hotMap.get(id);
if (h && h.tail) {
const d = durationFromMp4(h.tail);
if (d > 1) {
rec.duration = d;
durCache.set(id, d);
return d;
}
}
if (durCache.has(id)) {
rec.duration = durCache.get(id);
return rec.duration;
}
}
let p = inflightDur.get(id);
if (!p) {
const worker = pickBot(bot && bot.idx, undefined, msgId) || bot;
p = peekDuration(worker, rec).finally(() => inflightDur.delete(id));
inflightDur.set(id, p);
}
const d = await p;
if (d > 1) {
rec.duration = d;
durCache.set(id, d);
}
return d;
}
const TAIL_MAX = 256 * MB;
const TAIL_META = 1 * MB;
const TAIL_MIN_SIZE = 48 * MB;
function lvlPct(l) {
const s = String(l || "");
if (s === "subscribed") return 100;
return 80;
}
function ticketLvl(ticket) {
const l = String(ticket && ticket.l || "");
if (l === "subscribed" || l === "registered" || l === "anonymous") return l;
return "anonymous";
}
function previewMaxEnd(size, l, msgId, dur) {
const pct = lvlPct(l);
if (!size || pct >= 100) return size - 1;
let base = Math.floor(Number(size) * pct / 100);
const d = Number(dur);
if (d > 1 && d < 86400) {
const bitrate = Number(size) * 8 / d;
if (bitrate > 16000 && bitrate < 40000000) {
const ms0 = mdatStartOff(size, msgId);
const span = Math.max(0, Number(size) - ms0);
const tCut = ms0 + Math.floor(span * pct / 100);
if (tCut > base) base = tCut;
}
}
const head = Math.min(2 * MB, Math.max(512 * 1024, Math.floor(size * 0.002)));
return Math.max(0, Math.min(size - 1, base + head - 1));
}
function mdatStartOff(size, msgId) {
const id = String(msgId || "");
const cached = mdatCache.get(id);
if (cached !== undefined) return cached;
const h = hotMap.get(id);
const buf = h && h.headOff === 0 ? h.head : null;
let out = 0;
if (buf && buf.length >= 16 && size) {
let i = 0;
for (let n = 0; i + 8 <= buf.length && n < 16; n++) {
let sz = buf.readUInt32BE(i);
const typ = buf.toString("ascii", i + 4, i + 8);
let big = false;
if (sz === 1) {
if (i + 16 > buf.length) break;
sz = Number(buf.readBigUInt64BE(i + 8));
big = true;
}
if (!sz || sz < 8) break;
if (typ === "mdat") { out = i + (big ? 16 : 8); break; }
if (typ === "moov") { out = i + sz; break; }
if (i + sz > size) break;
i += sz;
}
}
if (out > 0) mdatCache.set(id, out);
return out;
}
function mp4IndexOff(size, msgId) {
const h = hotMap.get(String(msgId || ""));
const buf = h && h.headOff === 0 ? h.head : null;
if (!buf || buf.length < 16 || !size) return -1;
let i = 0;
for (let n = 0; i + 8 <= buf.length && n < 12; n++) {
let sz = buf.readUInt32BE(i);
const typ = buf.toString("ascii", i + 4, i + 8);
if (sz === 1 && i + 16 <= buf.length) sz = Number(buf.readBigUInt64BE(i + 8));
if (!sz || sz < 8) break;
if (typ === "moov") return i;
if (typ === "mdat") {
const end = i + sz;
if (end > 0 && end < size && size - end <= 8 * MB) return end;
return -1;
}
i += sz;
}
return -1;
}
function applyPreview(rng, size, l, msgId, ticket) {
if (!rng || !size) return rng;
const endCap = Math.min(rng.end, size - 1);
if (rng.start > endCap) return null;
if (lvlPct(l) >= 100) {
return {
start: rng.start,
end: endCap,
partial: rng.start > 0 || endCap < size - 1
};
}
const td = Number(ticket && ticket.d);
const dur = td > 1 ? td : (durCache.get(String(msgId || "")) || 0);
const maxEnd = previewMaxEnd(size, l, msgId, dur);
const tailAllowed = size >= TAIL_MIN_SIZE;
const tailWin = tailAllowed ? Math.max(0, size - Math.min(TAIL_MAX, TAIL_META)) : Infinity;
if (tailAllowed && rng.start >= tailWin) {
return { start: rng.start, end: endCap, partial: true };
}
if (rng.start <= maxEnd) {
const end = Math.min(endCap, maxEnd);
if (rng.start > end) return null;
return {
start: rng.start,
end,
partial: rng.start > 0 || end < size - 1
};
}
if (rng.start <= maxEnd + 65536) {
const start = Math.max(0, maxEnd - 1023);
return { start, end: maxEnd, partial: true };
}
return null;
}
function denyRange(res, size, allowOrigin) {
res.writeHead(416, Object.assign(streamLock(), {
"Content-Range": "bytes */" + size,
"Content-Type": "video/mp4",
"Cache-Control": "private, no-store, no-transform",
"Accept-Ranges": "bytes",
"Access-Control-Allow-Origin": allowOrigin || SITE_ORIGIN,
"Vary": "Origin"
}));
return res.end();
}
function parseRange(h, size, msgId) {
if (!size) return { start: 0, end: 0, partial: false };
let firstEnd = Math.min(size - 1, PROBE_HEAD - 1);
if (msgId && size > PROBE_HEAD) {
try {
const h = hotMap.get(String(msgId));
if (h && h.headOff === 0 && h.head && h.head.length >= 16) {
const mo = mdatStartOff(size, msgId);
if (mo > firstEnd + 1 && mo < size) firstEnd = Math.min(size - 1, mo + CHUNK_SIZE - 1);
}
} catch (e) {}
}
if (!h) return { start: 0, end: firstEnd, partial: firstEnd < size - 1 };
const m = /^bytes=(\d*)-(\d*)$/.exec(String(h).trim());
if (!m) return { start: 0, end: firstEnd, partial: firstEnd < size - 1 };
let start;
let end;
if (m[1] === "") {
const n = Number(m[2] || 0);
start = Math.max(0, size - n);
end = size - 1;
} else {
start = Number(m[1]);
if (m[2] === "") {
if (start === 0) end = firstEnd;
else end = Math.min(size - 1, start + STREAM_WINDOW - 1);
} else {
end = Number(m[2]);
}
}
if (!Number.isFinite(start) || start < 0) start = 0;
if (!Number.isFinite(end) || end >= size) end = size - 1;
if (start > end) return null;
return { start, end, partial: start > 0 || end < size - 1 };
}
function mediaHeaders(type, msgId, size, hash, rng, allowOrigin) {
const headers = Object.assign(streamLock(), {
"Content-Type": type,
"Accept-Ranges": "bytes",
"Cache-Control": "private, no-store, no-transform",
"Content-Disposition": "inline; filename=\"c.mp4\"",
"ETag": '"' + crypto.createHash("sha1").update(String(hash || "x") + ":" + String(size)).digest("hex").slice(0, 16) + '"',
"X-Accel-Buffering": "no",
"Content-Length": String(rng.end - rng.start + 1),
"Content-Range": "bytes " + rng.start + "-" + rng.end + "/" + size,
"Access-Control-Allow-Origin": allowOrigin || SITE_ORIGIN,
"Vary": "Origin",
"Connection": "keep-alive"
});
return headers;
}
function pipeBudget(start, end) {
const n = Math.max(1, end - start + 1);
const ms = Math.ceil(n / (32 * 1024)) * 1000;
return Math.min(PIPE_MAX_MS, Math.max(45000, ms));
}
function hotEntry(msgId, size) {
const id = String(msgId);
let h = hotMap.get(id);
if (!h) {
h = { head: null, headOff: 0, tail: null, tailOff: 0, size: size || 0, ts: Date.now() };
hotMap.set(id, h);
}
h.ts = Date.now();
if (size) h.size = size;
return h;
}
function hotPrefix(msgId, start, end) {
const h = hotMap.get(String(msgId));
if (!h) return null;
const need = end - start + 1;
if (need <= 0) return null;
if (h.head && start >= h.headOff && start < h.headOff + h.head.length) {
const a = start - h.headOff;
const take = Math.min(need, h.head.length - a);
if (take > 0) return h.head.subarray(a, a + take);
}
if (h.tail && start >= h.tailOff && start < h.tailOff + h.tail.length) {
const a = start - h.tailOff;
const take = Math.min(need, h.tail.length - a);
if (take > 0) return h.tail.subarray(a, a + take);
}
return null;
}
function hotFill(msgId, start, buf, size) {
if (!buf || !buf.length) return;
const h = hotEntry(msgId, size);
const end = start + buf.length - 1;
if (start < HOT_HEAD) {
const cut = Math.min(buf.length, HOT_HEAD - start);
if (!h.head) {
h.head = Buffer.from(buf.subarray(0, cut));
h.headOff = start;
} else if (start === h.headOff + h.head.length) {
h.head = Buffer.concat([h.head, buf.subarray(0, cut)]);
if (h.head.length > HOT_HEAD) h.head = h.head.subarray(0, HOT_HEAD);
}
}
const tailStart = Math.max(0, (size || h.size || 0) - HOT_TAIL);
if (size && end >= tailStart) {
const from = Math.max(start, tailStart);
const off = from - start;
const piece = buf.subarray(off);
if (!h.tail) {
h.tail = Buffer.from(piece);
h.tailOff = from;
} else if (from === h.tailOff + h.tail.length) {
h.tail = Buffer.concat([h.tail, piece]);
} else if (from < h.tailOff && end + 1 >= h.tailOff) {
h.tail = Buffer.concat([piece.subarray(0, h.tailOff - from), h.tail]);
h.tailOff = from;
}
}
trimHot();
}
function hotHeadLen(msgId) {
const h = hotMap.get(String(msgId));
return h && h.head ? h.head.length : 0;
}
function waitHotHead(msgId, min, ms) {
const id = String(msgId);
const need = Math.max(1, min | 0);
const budget = Math.max(1, ms | 0);
const t0 = Date.now();
return new Promise((resolve) => {
const tick = () => {
const n = hotHeadLen(id);
if (n >= need || Date.now() - t0 >= budget) return resolve(n);
setTimeout(tick, 12);
};
tick();
});
}
async function warmHot(bot, rec, msgId) {
const id = String(msgId);
const hit = hotMap.get(id);
const headNeed = Math.min(rec.size, CHUNK_SIZE * 2);
if (hit && hit.head && hit.head.length >= headNeed && (durCache.get(id) > 1 || hit.tail)) return;
if (inflightHot.has(id)) return inflightHot.get(id);
let finish;
const p = new Promise((r) => { finish = r; });
inflightHot.set(id, p);
(async () => {
bot.load++;
try {
const headEnd = headNeed - 1;
if (headEnd >= 0 && !(hit && hit.head && hit.head.length >= headNeed)) {
const parts = [];
for await (const c of rangeChunks(bot, rec, 0, headEnd, () => parts.reduce((n, b) => n + b.length, 0) >= headNeed, id)) {
parts.push(c);
}
if (parts.length) hotFill(id, 0, Buffer.concat(parts), rec.size);
}
} catch {
} finally {
bot.load = Math.max(0, bot.load - 1);
inflightHot.delete(id);
finish();
}
})();
if (rec.size > PROBE_HEAD && !durCache.get(id) && !(hit && hit.tail)) {
setTimeout(() => {
if (durCache.get(id) > 1 || (hotMap.get(id) && hotMap.get(id).tail)) return;
warmTail(bot, rec, msgId).catch(() => { });
}, 8000);
}
return p;
}
async function warmTail(bot, rec, msgId) {
const id = String(msgId);
if (!bot || !rec || durCache.get(id) > 1) return;
const tailNeed = Math.min(HOT_TAIL, 2 * MB);
const tailOff = Math.max(0, rec.size - tailNeed);
const parts = [];
for await (const c of rangeChunks(bot, rec, tailOff, rec.size - 1, () => false, id)) {
parts.push(c);
}
if (!parts.length) return;
const buf = Buffer.concat(parts);
hotFill(id, tailOff, buf, rec.size);
const d = durationFromMp4(buf);
if (d > 1) durCache.set(id, d);
}
class SingleFlight {
constructor() {
this.active = new Map();
}
do(key, fn) {
if (this.active.has(key)) return this.active.get(key);
const p = (async () => {
try {
return await fn();
} finally {
this.active.delete(key);
}
})();
this.active.set(key, p);
return p;
}
}
const chunkFlight = new SingleFlight();
let diskBytesUsed = 0;
const SLICE_MEM_MAX = Math.max(1024, Math.min(6144, Math.floor((RAM_BYTES * 0.38) / MB)));
const sliceMemCache = new Map();
function getSliceMem(msgId, offset) {
const k = String(msgId) + ":" + String(offset);
const buf = sliceMemCache.get(k);
if (buf) {
sliceMemCache.delete(k);
sliceMemCache.set(k, buf);
return buf;
}
return null;
}
function setSliceMem(msgId, offset, buf) {
if (!buf || !buf.length) return;
const k = String(msgId) + ":" + String(offset);
if (sliceMemCache.has(k)) sliceMemCache.delete(k);
sliceMemCache.set(k, buf);
const heapCut = Math.floor(RAM_BYTES * 0.22);
const memUsed = process.memoryUsage();
const bufBytes = (memUsed.arrayBuffers || 0) + (memUsed.external || 0);
const overCut = (bufBytes > heapCut || memUsed.rss > heapCut * 1.6);
const memMax = overCut ? Math.max(256, Math.floor(SLICE_MEM_MAX / 4)) : SLICE_MEM_MAX;
while (sliceMemCache.size > memMax) {
const oldest = sliceMemCache.keys().next().value;
sliceMemCache.delete(oldest);
}
}
function sliceFilePath(msgId, offset) {
return path.join(DISK_SLICE_DIR, String(msgId), String(offset) + ".bin");
}
async function readDiskSlice(msgId, offset) {
const mem = getSliceMem(msgId, offset);
if (mem && mem.length) return mem;
try {
const buf = await fs.promises.readFile(sliceFilePath(msgId, offset));
if (buf && buf.length) {
setSliceMem(msgId, offset, buf);
return buf;
}
return null;
} catch {
return null;
}
}
async function trimDiskCache() {
try {
const files = [];
const dirs = await fs.promises.readdir(DISK_SLICE_DIR, { withFileTypes: true });
for (const d of dirs) {
if (d.isDirectory()) {
const sub = path.join(DISK_SLICE_DIR, d.name);
const list = await fs.promises.readdir(sub);
for (const f of list) {
const fp = path.join(sub, f);
try {
const st = await fs.promises.stat(fp);
files.push({ path: fp, size: st.size, mtime: st.mtimeMs });
} catch { }
}
}
}
files.sort((a, b) => a.mtime - b.mtime);
let total = files.reduce((n, f) => n + f.size, 0);
diskBytesUsed = total;
if (total <= DISK_MAX_BYTES) return;
const target = Math.floor(DISK_MAX_BYTES * 0.75);
for (const f of files) {
if (total <= target) break;
try {
await fs.promises.unlink(f.path);
total -= f.size;
} catch { }
}
diskBytesUsed = Math.max(0, total);
} catch { }
}
async function writeDiskSlice(msgId, offset, buffer) {
if (!buffer || !buffer.length) return;
setSliceMem(msgId, offset, buffer);
try {
const file = sliceFilePath(msgId, offset);
await fs.promises.mkdir(path.dirname(file), { recursive: true });
try {
const st = await fs.promises.statfs(DISK_SLICE_DIR);
if (Number(st.bavail) * Number(st.bsize) < DISK_FREE_MIN_BYTES) {
await trimDiskCache();
const st2 = await fs.promises.statfs(DISK_SLICE_DIR);
if (Number(st2.bavail) * Number(st2.bsize) < DISK_FREE_MIN_BYTES) return;
}
} catch { }
await fs.promises.writeFile(file, buffer);
diskBytesUsed += buffer.length;
if (diskBytesUsed > DISK_MAX_BYTES) {
trimDiskCache().catch(() => { });
}
} catch { }
}
async function rangeSlicesReady(msgId, start, end) {
if (msgId == null || end < start) return false;
const first = Math.floor(start / CHUNK_SIZE) * CHUNK_SIZE;
for (let off = first; off <= end; off += CHUNK_SIZE) {
const mem = getSliceMem(msgId, off);
if (mem && mem.length) continue;
try {
await fs.promises.access(sliceFilePath(msgId, off));
} catch {
return false;
}
}
return true;
}
const elstLeadSec = new Map();
function geckoUA(ua) {
const s = String(ua || "");
return /Firefox\//i.test(s) && !/Seamonkey/i.test(s);
}
function handlerNear(buf, from) {
const end = Math.min(buf.length - 4, from + 180);
for (let i = from; i < end; i++) {
if (buf.toString("ascii", i, i + 4) !== "hdlr" || i + 16 > buf.length) continue;
const h = buf.toString("ascii", i + 12, i + 16);
if (h === "vide" || h === "soun") return h;
}
return "";
}
function timescaleNear(buf, from) {
const end = Math.min(buf.length - 8, from + 180);
for (let i = from; i < end; i++) {
if (buf.toString("ascii", i, i + 4) !== "mdhd" || buf[i + 4] !== 0 || i + 20 > buf.length) continue;
const ts = buf.readUInt32BE(i + 16);
if (ts > 1 && ts < 200000) return ts;
}
return 0;
}
function videoEmptyEditSec(buf) {
if (!buf || buf.length < 32) return 0;
let movieTs = 1000;
const mv = buf.indexOf("mvhd");
if (mv > 0 && mv + 24 < buf.length && buf[mv + 4] === 0) {
const ts = buf.readUInt32BE(mv + 16);
if (ts > 0 && ts < 1000000) movieTs = ts;
}
let from = 0;
while (from + 12 < buf.length) {
const mark = buf.indexOf("elst", from);
if (mark < 4) break;
const size = buf.readUInt32BE(mark - 4);
if (size < 28 || size > 512 || mark - 4 + size > buf.length || buf[mark + 4] !== 0) {
from = mark + 4;
continue;
}
const count = buf.readUInt32BE(mark + 8);
if (count < 2 || count > 8 || mark + 12 + count * 12 > buf.length) {
from = mark + 4;
continue;
}
const kind = handlerNear(buf, mark - 4 + size);
const e0dur = buf.readUInt32BE(mark + 12);
const e0mt = buf.readInt32BE(mark + 16);
if (kind === "vide" && e0mt === -1 && e0dur > 0) {
return e0dur / movieTs;
}
from = mark + 4;
}
return 0;
}
function rememberElstLead(msgId, buf) {
const id = String(msgId || "");
if (!id || elstLeadSec.has(id)) return;
const sec = videoEmptyEditSec(buf);
if (sec > 0.05) {
elstLeadSec.set(id, sec);
if (elstLeadSec.size > 20000) {
const first = elstLeadSec.keys().next().value;
elstLeadSec.delete(first);
}
}
}
async function pipeDiskRange(msgId, start, end, req, res, headers, size) {
const t0 = Date.now();
let clientClosed = false;
const onDead = () => { clientClosed = true; };
req.once("close", onDead);
res.once("close", onDead);
try {
if (res.socket) {
res.socket.setNoDelay(true);
res.socket.setKeepAlive(true, 120000);
try { res.socket.setTimeout(0); } catch { }
}
if (pipeDead(req, res)) return true;
res.writeHead(206, headers);
if (typeof res.flushHeaders === "function") res.flushHeaders();
const budget = pipeBudget(start, end);
const first = Math.floor(start / CHUNK_SIZE) * CHUNK_SIZE;
let at = start;
for (let off = first; off <= end; off += CHUNK_SIZE) {
if (clientClosed || pipeDead(req, res) || Date.now() - t0 > budget) break;
const piece = await readDiskSlice(msgId, off);
if (!piece || !piece.length) return false;
let skip = at - off;
if (skip < 0) skip = 0;
if (skip >= piece.length) return false;
let buf = skip ? piece.subarray(skip) : piece;
const left = end - at + 1;
if (buf.length > left) buf = buf.subarray(0, left);
if (!buf.length) continue;
hotFill(msgId, at, buf, size);
rememberElstLead(msgId, buf);
const out = buf;
at += buf.length;
const ok = res.write(out);
if (!ok) await waitDrain(req, res);
}
return at > end;
} finally {
req.off("close", onDead);
res.off("close", onDead);
if (!res.writableEnded && !res.destroyed) {
try { res.end(); } catch { }
}
}
}
const warmRun = new Set();
function kickWarmAhead(bot, rec, msgId, fromOff, fileSize, wantBytes) {
const id = String(msgId);
const need = Number(wantBytes) || 0;
const span = Math.max(0, Math.min(CHUNK_SIZE * WARM_AHEAD, need));
const chunks = Math.max(1, Math.min(WARM_AHEAD, Math.ceil(span / CHUNK_SIZE)));
const start = Math.floor(Math.max(0, fromOff) / CHUNK_SIZE) * CHUNK_SIZE;
const warmKey = id + ":" + Math.floor(start / (16 * MB));
if (!bot || !rec || !id || need <= 0) return;
if (warmRun.has(warmKey) || warmRun.size >= 8) return;
if (warmBytesInFlight + chunks * CHUNK_SIZE > WARM_BUDGET_BYTES) return;
warmRun.add(warmKey);
warmBytesInFlight += chunks * CHUNK_SIZE;
const cap = Number(fileSize) || 0;
(async () => {
try {
const jobs = [];
for (let i = 0; i < chunks; i++) {
const off = start + i * CHUNK_SIZE;
if (cap && off >= cap) break;
if (getSliceMem(id, off)) continue;
try {
await fs.promises.access(sliceFilePath(id, off));
continue;
} catch { }
jobs.push(off);
}
for (let i = 0; i < jobs.length; i += WARM_BATCH) {
const batch = jobs.slice(i, i + WARM_BATCH);
await Promise.all(batch.map((off) => fetchSliceChunk(bot, rec, msgId, off).catch(() => null)));
}
} catch { }
finally {
warmRun.delete(warmKey);
warmBytesInFlight = Math.max(0, warmBytesInFlight - chunks * CHUNK_SIZE);
}
})();
}
async function fetchSliceChunk(bot, rec, msgId, aligned, onPiece) {
const disk = await readDiskSlice(msgId, aligned);
if (disk && disk.length) {
if (onPiece) onPiece(disk, aligned);
return disk;
}
const flightKey = String(msgId) + ":" + String(aligned);
return chunkFlight.do(flightKey, async () => {
const recheck = await readDiskSlice(msgId, aligned);
if (recheck && recheck.length) {
if (onPiece) onPiece(recheck, aligned);
return recheck;
}
let downloadBot = pickBot(bot && bot.idx, undefined, msgId) || bot;
if (!downloadBot || !botUsable(downloadBot)) {
downloadBot = pickBot(undefined, undefined, msgId) || downloadBot;
}
if (!downloadBot || !downloadBot.client) throw new Error("nobot");
downloadBot.tgLoad = (downloadBot.tgLoad || 0) + 1;
try {
const it = downloadBot.client.iterDownload(rec.loc || rec.doc, {
offset: aligned,
limit: CHUNK_SIZE,
requestSize: CHUNK_SIZE,
dcId: rec.dcId
});
const parts = [];
let fileOff = aligned;
for await (const chunk of it) {
const b = Buffer.from(chunk);
if (!b.length) continue;
parts.push(b);
if (onPiece) onPiece(b, fileOff);
fileOff += b.length;
}
const full = Buffer.concat(parts);
if (full.length) {
writeDiskSlice(msgId, aligned, full).catch(() => { });
}
return full;
} catch (err) {
coolBot(downloadBot, err);
if (isFileRef(err)) {
dropFile(msgId, downloadBot);
}
throw err;
} finally {
downloadBot.tgLoad = Math.max(0, (downloadBot.tgLoad || 0) - 1);
}
});
}
async function* rangeChunks(bot, rec, start, end, stop, msgId) {
let at = start;
let fails = 0;
const pending = new Map();
const kick = (off) => {
if (msgId == null || off > end) return;
const al = Math.floor(off / CHUNK_SIZE) * CHUNK_SIZE;
if (pending.has(al)) return;
pending.set(al, fetchSliceChunk(bot, rec, msgId, al).catch(() => null));
};
kick(at);
for (let i = 1; i < RANGE_LOOKAHEAD; i++) kick(at + i * CHUNK_SIZE);
while (at <= end) {
if (stop && stop()) break;
const aligned = Math.floor(at / CHUNK_SIZE) * CHUNK_SIZE;
let skip = at - aligned;
kick(aligned);
for (let i = 1; i < RANGE_LOOKAHEAD; i++) kick(aligned + i * CHUNK_SIZE);
let piece = null;
if (msgId != null) {
try {
piece = await pending.get(aligned);
} catch { }
}
if (piece && piece.length) {
pending.delete(aligned);
let buf = piece;
if (skip > 0) {
if (buf.length <= skip) {
at += buf.length;
continue;
}
buf = buf.subarray(skip);
skip = 0;
}
const left = end - at + 1;
if (buf.length > left) buf = buf.subarray(0, left);
if (buf.length) {
at += buf.length;
yield buf;
}
if (at > end || (stop && stop())) break;
continue;
}
pending.delete(aligned);
const it = bot.client.iterDownload(rec.loc || rec.doc, {
offset: aligned,
limit: CHUNK_SIZE,
requestSize: CHUNK_SIZE,
dcId: rec.dcId
});
let got = 0;
try {
for await (const chunk of it) {
if (stop && stop()) break;
let buf = Buffer.from(chunk);
if (skip > 0) {
if (buf.length <= skip) {
skip -= buf.length;
continue;
}
buf = buf.subarray(skip);
skip = 0;
}
const left = end - at + 1;
if (buf.length > left) buf = buf.subarray(0, left);
if (!buf.length) continue;
at += buf.length;
got += buf.length;
yield buf;
if (at > end || (stop && stop())) break;
}
} catch {
}
if (got <= 0) {
fails += 1;
if (fails > 2) break;
await new Promise((resolve) => setTimeout(resolve, 400 * fails));
if (stop && stop()) break;
continue;
}
fails = 0;
}
}
async function pipeRange(bot, rec, start, end, req, res, status, headers, msgId) {
const t0 = Date.now();
let clientClosed = false;
let sentAny = false;
let lastByte = t0;
const onDead = () => { clientClosed = true; };
req.once("close", onDead);
res.once("close", onDead);
try {
if (res.socket) {
res.socket.setNoDelay(true);
res.socket.setKeepAlive(true, 120000);
try { res.socket.setTimeout(0); } catch { }
}
if (pipeDead(req, res)) return;
const primedPrefix = hotPrefix(msgId, start, end);
let streamedFirst = false;
let streamedTo = start;
if (!(primedPrefix && primedPrefix.length)) {
const aligned = Math.floor(start / CHUNK_SIZE) * CHUNK_SIZE;
let opened = false;
const primedP = fetchSliceChunk(bot, rec, msgId, aligned, (piece, off) => {
if (!piece || !piece.length || clientClosed || pipeDead(req, res)) return;
let buf = piece;
let at = off;
if (at < start) {
const skip = start - at;
if (skip >= buf.length) return;
buf = buf.subarray(skip);
at = start;
}
if (at > end) return;
const left = end - at + 1;
if (buf.length > left) buf = buf.subarray(0, left);
if (!buf.length || res.writableEnded) return;
if (!opened) {
res.writeHead(status, headers);
if (typeof res.flushHeaders === "function") res.flushHeaders();
opened = true;
streamedFirst = true;
}
rememberElstLead(msgId, buf);
const out = buf;
res.write(out);
sentAny = true;
lastByte = Date.now();
streamedTo = at + buf.length;
});
const ready = new Promise((resolve) => {
const timer = setInterval(() => {
if (streamedTo > end || clientClosed || pipeDead(req, res)) {
clearInterval(timer);
resolve();
}
}, 20);
primedP.finally(() => {
clearInterval(timer);
resolve();
});
});
await ready;
const primed = opened ? null : await primedP.catch(() => null);
if (!opened && (!primed || !primed.length)) {
throw new Error("prime_failed");
}
if (!opened) {
res.writeHead(status, headers);
if (typeof res.flushHeaders === "function") res.flushHeaders();
}
}
kickWarmAhead(bot, rec, msgId, streamedFirst ? streamedTo : start, rec.size || (end + 1), end - start + 1);
if (pipeDead(req, res)) return;
if (!res.headersSent) {
res.writeHead(status, headers);
if (typeof res.flushHeaders === "function") res.flushHeaders();
}
const budget = pipeBudget(start, end);
const stop = () => clientClosed || pipeDead(req, res) || Date.now() - t0 > budget || (sentAny ? Date.now() - lastByte > PIPE_IDLE_MS : Date.now() - t0 > PIPE_FIRST_MS);
let pos = streamedFirst ? streamedTo : start;
const prefix = streamedFirst ? null : hotPrefix(msgId, pos, end);
if (prefix && prefix.length) {
rememberElstLead(msgId, prefix);
const patched = prefix;
const ok = res.write(patched);
sentAny = true;
lastByte = Date.now();
pos += prefix.length;
if (!ok) await waitDrain(req, res);
}
if (pos > end || stop()) return;
const gen = rangeChunks(bot, rec, pos, end, stop, msgId);
let at = pos;
for await (const buf of gen) {
if (stop()) break;
hotFill(msgId, at, buf, rec.size);
rememberElstLead(msgId, buf);
const out = buf;
at += buf.length;
const ok = res.write(out);
sentAny = true;
lastByte = Date.now();
if (!ok) await waitDrain(req, res);
}
} finally {
req.off("close", onDead);
res.off("close", onDead);
if (!res.writableEnded && !res.destroyed) {
try { res.end(); } catch { }
}
}
}
async function readBody(req, max) {
const lim = max || BODY_MAX;
const declared = Number(req.headers["content-length"] || 0);
if (Number.isFinite(declared) && declared > lim) throw new Error("body");
const chunks = [];
let n = 0;
const timer = setTimeout(() => {
try { req.destroy(new Error("body_timeout")); } catch { }
}, 20000);
try {
for await (const c of req) {
n += c.length;
if (n > lim) throw new Error("body");
chunks.push(c);
}
} finally {
clearTimeout(timer);
}
return Buffer.concat(chunks);
}
async function handleGenerate(req, res) {
if (req.method !== "POST") {
res.setHeader("Allow", "POST");
return json(res, 405, { error: "method" });
}
if (!aesKey) return json(res, 503, { error: "misconfigured" });
if (!destOk(req, ["empty"])) return json(res, 403, { error: "forbidden" });
if (denyHot(req, res)) return;
const ip = clientIp(req);
if (mintBlocked(ip) || mintLimited(ip)) {
res.setHeader("Retry-After", "3");
return json(res, 429, { error: "rate_limited" });
}
const ctype = String(req.headers["content-type"] || "");
if (!/^application\/json(?:\s*;|$)/i.test(ctype)) return json(res, 415, { error: "type" });
let path = "";
let hash = "";
if (req.method === "POST") {
try {
const raw = JSON.parse((await readBody(req, 4096)).toString("utf8") || "{}");
if (raw && raw.enc) {
const reqHost = siteHostOf(req);
const dom = SITE_HOSTS.has(reqHost) ? reqHost : SITE_HOST;
const decReq = (enc, d) => {
try {
const key = Buffer.from(d, "utf8");
const kl = key.length;
const arr = String(enc || "").split(",");
const out = [];
for (let j = 0; j < arr.length; j++) {
const v = Number(arr[j]);
if (isNaN(v)) continue;
out.push(String.fromCharCode(v ^ key[j % kl] ^ ((j * 11 + 17) & 0xff)));
}
return JSON.parse(out.join(""));
} catch { return null; }
};
const parsed = decReq(raw.enc, dom) || decReq(raw.enc, SITE_HOST);
if (parsed) {
if (parsed.p) path = String(parsed.p);
if (parsed.h) hash = String(parsed.h).toLowerCase();
}
}
if (!path && raw && raw.p) path = String(raw.p);
if (!hash && raw && raw.h) hash = String(raw.h).toLowerCase();
} catch {
if (mintFailed(ip)) {
res.setHeader("Retry-After", "3");
return json(res, 429, { error: "rate_limited" });
}
return json(res, 400, { error: "bad_request" });
}
}
const m = /\/stream\/(\d+)/.exec(path);
if (!m || !/^[0-9a-f]{6}$/.test(hash)) {
if (mintFailed(ip)) {
res.setHeader("Retry-After", "3");
return json(res, 429, { error: "rate_limited" });
}
return json(res, 400, { error: "bad_request" });
}
const msgId = Number(m[1]);
if (!Number.isInteger(msgId) || msgId < 1 || msgId > 1e15) {
if (mintFailed(ip)) {
res.setHeader("Retry-After", "3");
return json(res, 429, { error: "rate_limited" });
}
return json(res, 400, { error: "bad_request" });
}
const rawAuth = String(req.headers.authorization || "").trim();
const authTag = rawAuth ? crypto.createHash("sha256").update(rawAuth).digest("hex").slice(0, 16) : "a";
const gk = path + "|" + hash + "|" + authTag + "|" + ipTag(ip) + "|" + uaTag(req.headers["user-agent"]);
const ghit = genAnonCache.get(gk);
if (ghit && ghit.body && ghit.body.u && ghit.exp > Date.now() + 8000) {
if (!ghit.vipUntil || ghit.vipUntil > Math.floor(Date.now() / 1000) + 30) {
const body = Object.assign({}, ghit.body);
const cd = durCache.get(String(msgId));
if (cd > 1) body.d = Math.floor(cd);
const leadHit = elstLeadSec.get(String(msgId)) || 0;
if (leadHit > 0.05) body.v = Math.round(leadHit * 1000) / 1000;
return json(res, 200, body);
}
}
const authJob = (async () => {
if (!rawAuth) return { uid: null, lvl: "anonymous" };
try {
const idp = await withTime(verifyIdToken(rawAuth), 4000, null);
const g = googleUid(idp);
if (!g) return { uid: null, lvl: "anonymous" };
const lv = await accessLevel(g);
return { uid: g, lvl: lv === "subscribed" ? "subscribed" : "registered" };
} catch {
return { uid: null, lvl: "anonymous" };
}
})();
let got;
try {
got = await fileFromPool(msgId, pickBot(undefined, undefined, msgId));
} catch {
return busyJson(res);
}
const auth = await authJob;
const uid = auth.uid;
const lvl = auth.lvl;
const bot = got.bot;
const rec = got.rec;
if (rec.hash && rec.hash !== hash) {
if (mintFailed(ip)) {
res.setHeader("Retry-After", "3");
return json(res, 429, { error: "rate_limited" });
}
return json(res, 400, { error: "hash" });
}
warmHot(bot, rec, msgId);
await waitHotHead(msgId, Math.min(rec.size, CHUNK_SIZE), 350);
const hid = String(msgId);
if (durCache.get(hid) > 1) rec.duration = durCache.get(hid);
else {
const h = hotMap.get(hid);
const fromHot = (h && h.tail && durationFromMp4(h.tail)) || (h && h.head && durationFromMp4(h.head)) || 0;
if (fromHot > 1) {
rec.duration = fromHot;
durCache.set(hid, fromHot);
}
}
const cachedDur = durCache.get(hid);
if (cachedDur > 1) rec.duration = cachedDur;
const playMime = httpVideoType(rec.mime, rec.name);
const durSec = Number(rec.duration) > 1 ? Math.floor(Number(rec.duration)) : 0;
const nowSec = Math.floor(Date.now() / 1000);
let exp = nowSec + TOKEN_TTL;
let vipUntil = 0;
if (lvl === "subscribed" && uid) {
const hit = lvlCache.get(uid);
vipUntil = hit && Number(hit.exp) || 0;
if (vipUntil > nowSec && vipUntil < exp) exp = vipUntil;
}
const payload = { m: msgId, h: hash, u: uid || "anon", l: lvl, b: bot.idx, e: exp, x: vipUntil, s: rec.size, n: playMime, p: ipTag(ip), a: uaTag(req.headers["user-agent"]), d: durSec };
const k = sealTicket(payload);
const host = publicSpaceOrigin(req);
if (!elstLeadSec.has(hid)) {
const hh = hotMap.get(hid);
if (hh && hh.head) rememberElstLead(msgId, hh.head);
else if (hh && hh.tail) rememberElstLead(msgId, hh.tail);
}
const leadSec = elstLeadSec.get(hid) || 0;
const body = {
u: host + "/p/" + k + ".mp4",
d: durSec,
p: lvlPct(lvl),
a: lvl,
s: rec.size,
e: exp
};
if (leadSec > 0.05) body.v = Math.round(leadSec * 1000) / 1000;
const storeExp = Math.min(Date.now() + 180000, exp * 1000);
genAnonCache.set(gk, { body, exp: storeExp, vipUntil, ts: Date.now() });
json(res, 200, body);
}
async function handlePlay(req, res, url, kHex) {
const ticket = openTicket(kHex);
if (!ticket || !Number.isInteger(ticket.m) || ticket.m < 1) {
res.writeHead(403);
return res.end();
}
return handleStream(req, res, url, ticket.m, kHex, ticket);
}
async function handleStream(req, res, url, msgId, kHex, ticketObj) {
if (!streamDestOk(req)) {
res.writeHead(403);
return res.end();
}
const oH = req.headers.origin || "";
const rH = req.headers.referer || "";
const originOk = oH ? isSiteOrigin(oH) : false;
let refererOk = true;
if (rH) {
try { refererOk = isSiteOrigin(new URL(rH).origin); } catch { refererOk = false; }
}
if ((oH && !originOk) || (rH && !refererOk) || (!oH && !rH)) {
res.writeHead(403);
return res.end();
}
const allowOrigin = originOk ? oH : SITE_ORIGIN;
const k = kHex || url.searchParams.get("k") || "";
const ticket = ticketObj || openTicket(k);
if (!ticket || ticket.m !== msgId || !/^[0-9a-f]{6}$/.test(String(ticket.h || ""))) {
res.writeHead(403);
return res.end();
}
if (ticket.e < Math.floor(Date.now() / 1000)) {
res.writeHead(410);
return res.end();
}
const ip = clientIp(req);
if (!ticketNetOk(ticket, ip) || !ticketUaOk(ticket, req.headers["user-agent"])) {
res.writeHead(403);
return res.end();
}
const vipUntil = Number(ticket.x) || 0;
if (ticketLvl(ticket) === "subscribed" && vipUntil > 0 && vipUntil <= Math.floor(Date.now() / 1000)) ticket.l = "registered";
let held = false;
try {
if (!takeStream(ip, ticket.u, msgId)) {
res.setHeader("Retry-After", "1");
res.writeHead(429);
return res.end();
}
held = true;
const sizeHint = Number(ticket.s) || 0;
if (sizeHint <= 0) {
res.writeHead(502);
return res.end();
}
const mimeHint = String(ticket.n || "video/mp4");
const typeHint = (mimeHint.indexOf("webm") >= 0) ? "video/webm" : "video/mp4";
const lvl = ticketLvl(ticket);
if (sizeHint > 0) {
const rngHot0 = parseRange(req.headers.range, sizeHint, msgId);
const rngHot = applyPreview(rngHot0, sizeHint, lvl, msgId, ticket);
if (!rngHot) return denyRange(res, sizeHint, allowOrigin);
const needHot = rngHot.end - rngHot.start + 1;
const headersHot = mediaHeaders(typeHint, msgId, sizeHint, ticket.h, rngHot, allowOrigin);
if (req.method === "HEAD") {
res.writeHead(206, headersHot);
return res.end();
}
const hit = hotPrefix(msgId, rngHot.start, rngHot.end);
if (hit && hit.length >= needHot) {
if (res.socket) {
try { res.socket.setNoDelay(true); } catch { }
}
res.writeHead(206, headersHot);
rememberElstLead(msgId, hit);
res.end(hit.subarray(0, needHot));
return;
}
if (hit && hit.length > 0 && rngHot.start === 0 && (!req.headers.range || req.headers.range === "bytes=0-")) {
const serveLen = Math.min(hit.length, needHot);
const fastRng = { start: 0, end: serveLen - 1, partial: true };
const fastHeaders = mediaHeaders(typeHint, msgId, sizeHint, ticket.h, fastRng, allowOrigin);
if (res.socket) {
try { res.socket.setNoDelay(true); } catch { }
}
res.writeHead(206, fastHeaders);
rememberElstLead(msgId, hit);
res.end(hit.subarray(0, serveLen));
return;
}
if (await rangeSlicesReady(msgId, rngHot.start, rngHot.end)) {
const diskOk = await pipeDiskRange(msgId, rngHot.start, rngHot.end, req, res, headersHot, sizeHint);
if (diskOk || res.headersSent) return;
}
let pooled = null;
try {
pooled = await fileFromPool(msgId, pickBot(undefined, undefined, msgId));
} catch { }
if (pooled && pooled.rec) {
try {
await pipeRange(pooled.bot, pooled.rec, rngHot.start, rngHot.end, req, res, 206, headersHot, msgId);
return;
} catch {
if (pipeDead(req, res)) return;
if (res.headersSent) {
if (!res.writableEnded && !res.destroyed) {
try { res.end(); } catch { }
}
return;
}
}
}
}
const prefer = Number.isInteger(ticket.b) ? ticket.b : undefined;
let bot = pickBot(prefer, undefined, msgId);
if (!bot) {
res.setHeader("Retry-After", "1");
res.writeHead(503);
return res.end();
}
let rec;
try {
rec = await fileFromMsg(bot, msgId);
} catch (e) {
dropFile(msgId, bot);
coolBot(bot, e);
try {
const got = await fileFromPool(msgId, null, bot.idx);
bot = got.bot;
rec = got.rec;
} catch {
res.writeHead(404);
return res.end();
}
}
if (ticket.h && rec.hash && ticket.h !== rec.hash) {
res.writeHead(403);
return res.end();
}
const size = rec.size;
if (size > PROBE_HEAD) {
warmHot(bot, rec, msgId);
}
const rng0 = parseRange(req.headers.range, size, msgId);
const rng = applyPreview(rng0, size, lvl, msgId, ticket);
if (!rng) return denyRange(res, size, allowOrigin);
const headers = mediaHeaders(typeHint, msgId, size, rec.hash, rng, allowOrigin);
if (req.method === "HEAD") {
res.writeHead(206, headers);
return res.end();
}
const status = 206;
try {
await pipeRange(bot, rec, rng.start, rng.end, req, res, status, headers, msgId);
} catch (e) {
if (pipeDead(req, res)) return;
coolBot(bot, e);
if (isFileRef(e)) dropFile(msgId, bot);
if (!res.headersSent) {
for (let attempt = 0; attempt < 3; attempt++) {
const next = pickBot(undefined, bot.idx, msgId);
if (!next || next.idx === bot.idx) break;
try {
rec = await fileFromMsg(next, msgId);
await pipeRange(next, rec, rng.start, rng.end, req, res, status, headers, msgId);
return;
} catch (e2) {
coolBot(next, e2);
if (isFileRef(e2)) dropFile(msgId, next);
bot = next;
}
}
}
if (!res.headersSent) {
res.writeHead(502);
res.end();
} else if (!res.writableEnded && !res.destroyed) {
try { res.end(); } catch { }
}
}
} finally {
if (held) freeStream(ip, ticket && ticket.u, msgId);
}
}
async function handleVipStatus(req, res) {
if (!destOk(req, ["empty"])) return json(res, 403, { error: "forbidden" });
if (denyHot(req, res)) return;
const ip = clientIp(req);
if (slotOver("vipstatus:" + ip, 120)) {
res.setHeader("Retry-After", "30");
return json(res, 429, { error: "rate_limited" });
}
let lvl = "anonymous";
try {
const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
const g = googleUid(idp);
if (g) {
lvl = await accessLevel(g);
let sub = null;
try { sub = await rtdb("users/" + g + "/subscription", "GET"); } catch { }
return json(res, 200, { accessLevel: lvl, subscription: publicSub(sub) });
}
} catch { }
json(res, 200, { accessLevel: lvl });
}
async function handleVipTrack(req, res) {
if (ROLE !== "indexer") return json(res, 409, { error: "use_s1" });
if (!destOk(req, ["empty"])) return json(res, 403, { error: "forbidden" });
if (denyHot(req, res)) return;
const ip = clientIp(req);
if (slotOver("track:" + ip, 60)) {
res.setHeader("Retry-After", "30");
return json(res, 429, { error: "rate_limited" });
}
const ctype = String(req.headers["content-type"] || "");
if (!/^application\/json(?:\s*;|$)/i.test(ctype)) return json(res, 415, { error: "type" });
let body;
try {
body = JSON.parse((await readBody(req, 4096)).toString("utf8") || "{}");
} catch {
return json(res, 400, { error: "body" });
}
const vid = cleanVid(body.vid);
const stage = String(body.stage || "").toLowerCase();
const allowed = ["plan_click", "checkout_redirect", "return_success", "cancelled", "start_failed", "confirm_failed"];
if (!vid || allowed.indexOf(stage) < 0) return json(res, 400, { error: "bad" });
let uid = "";
let email = "";
const rawAuth = String(req.headers.authorization || "").trim();
if (rawAuth) {
try {
const idp = await withTime(verifyIdToken(rawAuth), 3000, null);
const g = googleUid(idp);
if (g) {
uid = g;
email = payEmail(idp);
}
} catch { }
}
const plan = /^(day|week|month)$/.test(String(body.plan || "")) ? String(body.plan) : "";
const sid = /^(cs|in|sub)_[A-Za-z0-9_]+$/.test(String(body.sid || "")) ? String(body.sid) : "";
const page = String(body.page || "");
const error = body.error ? payErrorText(body.error) : "";
await trackPay(vid, { stage: stage, uid: uid, email: email, plan: plan, sid: sid, page: page, error: error, source: "client" }).catch(() => { });
json(res, 200, { ok: true });
}
function siteReturn(u) {
try {
const p = new URL(String(u || ""), SITE_ORIGIN);
if (p.protocol !== "https:" || p.username || p.password) return SITE_ORIGIN + "/";
if (p.port && p.port !== "443") return SITE_ORIGIN + "/";
if (!SITE_HOSTS.has(p.hostname.toLowerCase())) return SITE_ORIGIN + "/";
const mobile = p.searchParams.get("m") === "1" ? "?m=1" : "";
return p.origin + p.pathname + mobile;
} catch {
return SITE_ORIGIN + "/";
}
}
function payUrls(ret) {
const base = siteReturn(ret);
const join = base.indexOf("?") >= 0 ? "&" : "?";
return {
success: base + join + "vip=success&sid={CHECKOUT_SESSION_ID}",
cancel: base + join + "pay_error=cancel"
};
}
let walletReady = false;
let walletNext = 0;
let walletJob = null;
let paypalLive = false;
let payTypes = ["card"];
function payPref(node) {
const d = node && node.display_preference;
if (!d) return "";
return String(d.value || d.preference || "");
}
async function ensureFreeWallets() {
if (ROLE !== "indexer" || !STRIPE_KEY) return { paypal: false, types: ["card"] };
if (Date.now() < walletNext) return { paypal: paypalLive, types: payTypes.slice() };
if (walletReady && paypalLive) return { paypal: true, types: payTypes.slice() };
if (walletJob) return walletJob;
walletJob = (async () => {
const list = await stripeGet("payment_method_configurations?limit=10");
const rows = list && Array.isArray(list.data) ? list.data : [];
const cfg = rows.find((x) => x && x.is_default && x.active) || rows[0];
if (!cfg || !/^pmc_/.test(String(cfg.id || ""))) {
walletNext = Date.now() + 600000;
return { paypal: paypalLive, types: payTypes.slice() };
}
const want = {
card: "on",
apple_pay: "on",
google_pay: "on",
link: "on",
samsung_pay: "on",
revolut_pay: "on",
paypal: "on"
};
let failed = false;
for (const key of Object.keys(want)) {
if (!cfg[key]) continue;
if (payPref(cfg[key]) === want[key]) continue;
const saved = await stripeForm("payment_method_configurations/" + cfg.id, {
[key + "[display_preference][preference]"]: want[key]
});
if (!saved) failed = true;
}
const fresh = await stripeGet("payment_method_configurations/" + cfg.id);
const pp = fresh && fresh.paypal;
paypalLive = !!(pp && pp.available === true && payPref(pp) === "on");
const order = ["card", "link", "samsung_pay", "revolut_pay", "paypal"];
const next = [];
for (const name of order) {
if (name === "card") {
next.push("card");
continue;
}
const node = fresh && fresh[name];
if (node && node.available === true && payPref(node) === "on") next.push(name);
}
if (next.length) payTypes = next;
if (failed) walletNext = Date.now() + 600000;
else if (paypalLive) walletReady = true;
else walletNext = Date.now() + 120000;
return { paypal: paypalLive, types: payTypes.slice() };
})().catch(() => {
walletNext = Date.now() + 600000;
return { paypal: paypalLive, types: payTypes.slice() };
}).finally(() => {
walletJob = null;
});
return walletJob;
}
function payGate(req, res) {
if (ROLE !== "indexer") {
json(res, 409, { error: "use_s1" });
return null;
}
if (!STRIPE_KEY) {
json(res, 503, { error: "stripe_not_configured" });
return null;
}
if (!destOk(req, ["empty"])) {
json(res, 403, { error: "forbidden" });
return null;
}
if (denyHot(req, res)) return null;
return true;
}
async function withPayLock(id, fn) {
const prev = payLocks.get(id);
let done;
const cur = new Promise((r) => { done = r; });
payLocks.set(id, prev ? prev.then(() => cur, () => cur) : cur);
if (prev) await prev.catch(() => { });
try {
return await fn();
} finally {
done();
if (payLocks.get(id) === cur) payLocks.delete(id);
}
}
async function trackPay(vid, info) {
const key = cleanVid(vid) || (info && uidOk(info.uid) ? String(info.uid) : "");
if (!key) return;
const stage = String(info && info.stage || "").toLowerCase();
if (!Object.prototype.hasOwnProperty.call(PAY_STAGES, stage)) return;
const now = Math.floor(Date.now() / 1000);
await withPayLock("funnel:" + key, async () => {
let cur = null;
try { cur = await rtdb("pay_funnel/" + key, "GET"); } catch { cur = null; }
const old = cur && typeof cur === "object" && !Array.isArray(cur) ? cur : {};
const history = Object.assign({}, old.history && typeof old.history === "object" ? old.history : {});
history[stage] = now;
const rank = PAY_STAGES[stage] || 0;
const oldRank = PAY_STAGES[String(old.stage || "")] || 0;
const next = Object.assign({}, old, {
vid: key,
createdAt: Number(old.createdAt) || now,
updatedAt: now,
history: history
});
if (rank >= oldRank || !old.stage) {
next.stage = stage;
next.lastStage = stage;
next.lastEventAt = now;
if (info && info.source) next.lastSource = String(info.source).slice(0, 12);
}
if (info && uidOk(info.uid)) next.uid = String(info.uid);
if (info && info.email) next.email = String(info.email).slice(0, 200);
if (info && info.plan && PLANS[info.plan]) next.plan = String(info.plan);
if (info && info.sid && /^(cs|in|sub)_[A-Za-z0-9_]+$/.test(String(info.sid))) next.sid = String(info.sid);
if (info && info.amount != null && Number.isFinite(Number(info.amount))) next.amount = Number(info.amount);
if (info && info.currency) next.currency = String(info.currency).slice(0, 8).toLowerCase();
if (info && info.page) {
const p = String(info.page);
if (/^\/[A-Za-z0-9._~\-/]{0,199}$/.test(p)) next.page = p;
}
if (info && info.error) next.lastError = payErrorText(info.error);
else if (stage === "paid") next.lastError = "";
await rtdb("pay_funnel/" + key, "PUT", next);
});
}
async function openPay(uid, planKey, email, auto) {
let rec = null;
try { rec = await rtdb("pay_open/" + uid, "GET"); } catch { rec = null; }
if (!rec || rec.plan !== planKey || rec.email !== email || !/^cs_[A-Za-z0-9_]+$/.test(String(rec.sid || ""))) return null;
if ((rec.auto === 1) !== !!auto) return null;
if (Math.floor(Date.now() / 1000) - Number(rec.t || 0) > 1800) return null;
const ses = await stripeSession(rec.sid);
const meta = ses && ses.metadata || {};
if (!ses || !ses.url || ses.status !== "open" || ses.payment_status === "paid") return null;
if (meta.uid !== uid || String(meta.plan || "").toLowerCase() !== planKey || String(meta.email || "").toLowerCase() !== email) return null;
if ((meta.auto === "1") !== !!auto) return null;
return { sid: ses.id, url: ses.url };
}
async function handleVipStart(req, res) {
if (!payGate(req, res)) return;
const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
if (!idp || !googlePayUser(idp) || !uidOk(idp.sub)) return json(res, 401, { error: "login" });
if (payLimited(idp.sub, clientIp(req))) {
res.setHeader("Retry-After", "30");
return json(res, 429, { error: "rate_limited" });
}
let body;
try {
body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
} catch {
return json(res, 400, { error: "body" });
}
const planKey = String(body.plan || "").trim().toLowerCase();
const plan = PLANS[planKey];
const email = payEmail(idp);
const vid = cleanVid(body.vid);
if (!plan || !email) return json(res, 400, { error: "plan" });
if (!verifyProof(body.proof, clientIp(req))) {
return json(res, 400, { error: "captcha" });
}
const auto = planKey === "month" && body.auto === true;
const urls = payUrls(body.returnUrl);
const wallets = await ensureFreeWallets();
const reused = await openPay(idp.sub, planKey, email, auto);
if (reused) {
await trackPay(vid || idp.sub, { stage: "checkout_started", uid: idp.sub, email: email, plan: planKey, sid: reused.sid, amount: plan.amount, currency: "usd", source: "server" }).catch(() => { });
return json(res, 200, reused);
}
const nonce = crypto.randomBytes(8).toString("hex");
const idem = "vip" + crypto.createHash("sha256").update(idp.sub + ":" + planKey + ":" + nonce).digest("hex").slice(0, 22);
const homeMsg = "After pay you return to [DUB LK 2000 Home](" + HOME_URL + ")";
const fields = {
mode: "payment",
success_url: urls.success,
cancel_url: urls.cancel,
client_reference_id: idp.sub,
"line_items[0][price_data][currency]": "usd",
"line_items[0][price_data][product_data][name]": plan.label + " — DUB LK 2000",
"line_items[0][price_data][product_data][description]": "Home: " + HOME_URL,
"line_items[0][price_data][product_data][images][0]": BRAND_URL,
"line_items[0][price_data][unit_amount]": String(plan.amount),
"line_items[0][quantity]": "1",
"adaptive_pricing[enabled]": "true",
billing_address_collection: "auto",
"branding_settings[display_name]": "DUB LK 2000",
"branding_settings[logo][type]": "url",
"branding_settings[logo][url]": BRAND_URL,
"branding_settings[button_color]": "#e50914",
"branding_settings[background_color]": "#0c0d12",
"custom_text[submit][message]": homeMsg,
"custom_text[after_submit][message]": "Site: [" + HOME_URL + "](" + HOME_URL + ")",
"metadata[uid]": idp.sub,
"metadata[plan]": planKey,
"metadata[email]": email,
"payment_intent_data[description]": "DUB LK 2000 VIP " + plan.label,
"payment_intent_data[metadata][uid]": idp.sub,
"payment_intent_data[metadata][plan]": planKey,
"payment_intent_data[metadata][email]": email,
"payment_intent_data[receipt_email]": email
};
fields.customer_email = email;
if (vid) fields["metadata[vid]"] = vid;
if (auto) {
fields.mode = "subscription";
fields["line_items[0][price_data][recurring][interval]"] = "month";
fields["metadata[auto]"] = "1";
fields["subscription_data[metadata][uid]"] = idp.sub;
fields["subscription_data[metadata][plan]"] = planKey;
fields["subscription_data[metadata][email]"] = email;
if (vid) fields["subscription_data[metadata][vid]"] = vid;
delete fields["payment_intent_data[description]"];
delete fields["payment_intent_data[metadata][uid]"];
delete fields["payment_intent_data[metadata][plan]"];
delete fields["payment_intent_data[metadata][email]"];
delete fields["payment_intent_data[receipt_email]"];
}
async function createSes(body, idemKey) {
const r = await fetch("https://api.stripe.com/v1/checkout/sessions", {
method: "POST",
headers: {
Authorization: "Bearer " + STRIPE_KEY,
"Content-Type": "application/x-www-form-urlencoded",
"Idempotency-Key": idemKey
},
body: new URLSearchParams(body).toString(),
signal: AbortSignal.timeout(12000)
});
return { r, d: await r.json() };
}
let r;
let d;
let firstErr = "";
try {
({ r, d } = await createSes(fields, idem));
firstErr = d && (d.error && d.error.message || d.message || null);
if (!r.ok) {
const slim = Object.assign({}, fields);
[
"branding_settings[display_name]",
"branding_settings[logo][type]",
"branding_settings[logo][url]",
"branding_settings[button_color]",
"branding_settings[background_color]",
"line_items[0][price_data][product_data][images][0]"
].forEach((k) => { delete slim[k]; });
({ r, d } = await createSes(slim, idem + "s"));
if (!r.ok) {
process.stderr.write("stripe create failed: " + (firstErr || "unknown") + " | slim: " + ((d && d.error && d.error.message) || "unknown") + "\n");
}
}
} catch (e) {
await trackPay(vid || idp.sub, { stage: "start_failed", uid: idp.sub, email: email, plan: planKey, error: errText(e), source: "server" }).catch(() => { });
return json(res, 400, { error: "Payment failed" });
}
if (!r.ok || !d.id || !d.url || d.object !== "checkout.session") {
await trackPay(vid || idp.sub, { stage: "start_failed", uid: idp.sub, email: email, plan: planKey, error: firstErr || (d && d.error && d.error.message) || "create", source: "server" }).catch(() => { });
return json(res, 400, { error: "Payment failed" });
}
try {
await rtdb("pay_open/" + idp.sub, "PUT", { sid: d.id, plan: planKey, email: email, auto: auto ? 1 : 0, t: Math.floor(Date.now() / 1000) });
} catch { }
await trackPay(vid || idp.sub, { stage: "checkout_started", uid: idp.sub, email: email, plan: planKey, sid: d.id, amount: Number(d.amount_total) || plan.amount, currency: d.currency || "usd", source: "server" }).catch(() => { });
json(res, 200, { sid: d.id, url: d.url });
}
async function handleVipGo(req, res) {
if (!payGate(req, res)) return;
const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
if (!idp || !googlePayUser(idp) || !uidOk(idp.sub)) return json(res, 401, { error: "login" });
if (payLimited(idp.sub, clientIp(req))) {
res.setHeader("Retry-After", "30");
return json(res, 429, { error: "rate_limited" });
}
let body;
try {
body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
} catch {
return json(res, 400, { error: "body" });
}
const d = await stripeSession(body.sid);
const meta = d && d.metadata || {};
const email = payEmail(idp);
if (!d || !d.url || meta.uid !== idp.sub || d.status === "expired" || d.payment_status === "paid") return json(res, 400, { error: "Payment failed" });
if (meta.email && (!email || String(meta.email).toLowerCase() !== email)) return json(res, 400, { error: "Payment failed" });
json(res, 200, { url: d.url });
}
async function handleVipConfirm(req, res) {
if (!payGate(req, res)) return;
const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
if (!idp || !googlePayUser(idp) || !uidOk(idp.sub)) return json(res, 401, { error: "login" });
if (payLimited(idp.sub, clientIp(req))) {
res.setHeader("Retry-After", "30");
return json(res, 429, { error: "rate_limited" });
}
let body;
try {
body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
} catch {
return json(res, 400, { error: "body" });
}
const vid = cleanVid(body.vid);
const d = await stripeSession(body.sid);
const meta = d && d.metadata || {};
const email = payEmail(idp);
const sem = String(meta.email || "");
const fail = async (err) => {
await trackPay(vid || idp.sub, { stage: "confirm_failed", uid: idp.sub, email: email, plan: meta && meta.plan, sid: d && d.id, error: err, source: "server" }).catch(() => { });
};
if (!d || meta.uid !== idp.sub || d.client_reference_id !== idp.sub) {
await fail("session");
return json(res, 400, { error: "Payment failed", paid: false });
}
if (sem && (!email || sem.toLowerCase() !== email)) {
await fail("email");
return json(res, 400, { error: "Payment failed", paid: false });
}
if (d.payment_status !== "paid" || d.status !== "complete") {
await fail("unpaid");
return json(res, 402, { error: "unpaid", paid: false });
}
let granted = false;
try { granted = await fulfillPaid(d); } catch { granted = false; }
lvlCache.delete(idp.sub);
let sub = null;
try { sub = await rtdb("users/" + idp.sub + "/subscription", "GET"); } catch { }
if (!granted || !vipActive(sub)) {
await fail(granted ? "status" : "order");
if (d.payment_status === "paid" && d.status === "complete") return json(res, 402, { error: "order", paid: false });
return json(res, 402, { error: "unpaid", paid: false });
}
await trackPay(vid || idp.sub, { stage: "paid", uid: idp.sub, email: email, plan: meta.plan, sid: d.id, amount: Number(d.amount_total) || 0, currency: d.currency || "usd", source: "server" }).catch(() => { });
json(res, 200, { ok: true, paid: true, accessLevel: "subscribed", subscription: publicSub(sub) });
}
async function grantVip(uid, planKey, absExp, extra) {
const plan = PLANS[planKey];
const now = Math.floor(Date.now() / 1000);
const exp = Number(absExp) || 0;
if (!plan || !uidOk(uid) || exp <= now) throw new Error("grant");
let old = null;
try { old = await rtdb("users/" + uid + "/subscription", "GET"); } catch { }
const oldExp = vipExpirySec(old);
const keep = old && vipActive(old) && oldExp >= exp;
const sub = {
status: "active",
plan: keep ? String(old.plan || planKey) : planKey,
label: keep ? String(old.label || plan.label) : plan.label,
price: keep ? String(old.price || plan.price) : plan.price,
expiry: keep ? oldExp : exp,
updatedAt: now,
autoRenew: extra && extra.autoRenew === true ? true : (extra && extra.autoRenew === false ? false : old && old.autoRenew === true)
};
const stripeSub = extra && extra.stripeSub ? String(extra.stripeSub) : (old && old.stripeSub ? String(old.stripeSub) : "");
if (/^sub_[A-Za-z0-9_]+$/.test(stripeSub)) sub.stripeSub = stripeSub;
await rtdb("users/" + uid + "/subscription", "PUT", sub);
const aid = now + "_" + crypto.randomBytes(4).toString("hex");
await rtdb("vip_audit/" + uid + "/" + aid, "PUT", { t: now, plan: sub.plan, exp: sub.expiry, source: String(extra && extra.source || "grant").slice(0, 16), autoRenew: sub.autoRenew === true }).catch(() => { });
lvlCache.delete(uid);
return sub;
}
function stripeOk(raw, sigHeader) {
if (!STRIPE_WH || !sigHeader) return false;
const v1s = [];
let t = "";
String(sigHeader).split(",").forEach((p) => {
const i = p.indexOf("=");
if (i < 1) return;
const k = p.slice(0, i);
const v = p.slice(i + 1);
if (k === "t") t = v;
else if (k === "v1") v1s.push(v);
});
if (!t || !v1s.length) return false;
const ts = Number(t);
if (!Number.isFinite(ts) || Math.abs(Date.now() / 1000 - ts) > 300) return false;
const mac = crypto.createHmac("sha256", STRIPE_WH).update(Buffer.from(t + ".", "utf8")).update(raw).digest("hex");
let ok = false;
for (let i = 0; i < v1s.length; i++) ok = timingSafeEq(mac, v1s[i]) || ok;
return ok;
}
async function orderSeen(id) {
if (!id) return true;
if (paidOrders.has(id)) return true;
try {
const hit = await rtdb("processed_orders/" + id, "GET");
if (hit) {
paidOrders.set(id, Date.now());
return true;
}
} catch { }
return false;
}
async function markOrder(id, uid, planKey, exp) {
paidOrders.set(id, Date.now());
const rec = { t: Math.floor(Date.now() / 1000), uid: uid, plan: planKey };
if (Number(exp) > 0) rec.exp = Number(exp);
try {
await rtdb("processed_orders/" + id, "PUT", rec);
} catch { }
}
async function claimOrder(id, uid, planKey, planSec) {
const now = Math.floor(Date.now() / 1000);
const readBack = async () => {
try {
const v = await rtdb("processed_orders/" + id, "GET");
return (v && typeof v === "object" && !Array.isArray(v)) ? v : null;
} catch {
return null;
}
};
let back = await readBack();
if (!back) {
let base = now;
try {
const old = await rtdb("users/" + uid + "/subscription", "GET");
const oldExp = vipExpirySec(old);
if (vipActive(old) && oldExp > base) base = oldExp;
} catch { }
const rec = { t: now, uid: uid, plan: planKey, exp: base + planSec };
try {
await rtdb("processed_orders/" + id, "PUT", rec);
} catch { }
back = await readBack();
}
if (!back) return { state: "unknown", exp: 0 };
if (String(back.uid || "") !== String(uid) || String(back.plan || "") !== String(planKey)) {
return { state: "conflict", exp: 0 };
}
const exp = Number(back.exp) || 0;
return { state: exp > 0 ? "seen" : "claimed", exp: exp };
}
function priceOk(paid, subtotal, expect) {
const total = Number(paid);
const sub = Number(subtotal);
if (!Number.isFinite(total) || total < expect) return false;
return sub === expect || total === expect;
}
async function fulfillPaid(ses) {
if (!ses || ses.object !== "checkout.session") return false;
if (ses.mode !== "payment" && ses.mode !== "subscription") return false;
if (ses.payment_status !== "paid") return false;
if (ses.status !== "complete") return false;
if (STRIPE_KEY.indexOf("sk_test_") !== 0 && STRIPE_KEY.indexOf("rk_test_") !== 0 && ses.livemode !== true) return false;
const uid = ses.metadata && ses.metadata.uid;
const planKey = ses.metadata && ses.metadata.plan;
const plan = PLANS[planKey];
if (!uidOk(uid) || !plan) return false;
if (ses.mode === "subscription" && (planKey !== "month" || !ses.metadata || ses.metadata.auto !== "1")) return false;
if (ses.client_reference_id !== uid) return false;
if (ses.status !== "complete") return false;
const email = String(ses.metadata && ses.metadata.email || "").toLowerCase();
if (email && (email.length > 200 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))) return false;
if (!priceOk(ses.amount_total, ses.amount_subtotal, plan.amount)) return false;
if (String(ses.currency || "").toLowerCase() !== "usd") return false;
const sid = String(ses.id || "");
if (!/^cs_[A-Za-z0-9_]+$/.test(sid)) return false;
return withPayLock(sid, async () => {
const c = await claimOrder(sid, uid, planKey, plan.sec);
if (c.state === "conflict" || c.state === "unknown" || !(c.exp > Math.floor(Date.now() / 1000))) return false;
paidOrders.set(sid, Date.now());
const autoOn = ses.metadata && ses.metadata.auto === "1";
const stripeSub = typeof ses.subscription === "string" ? ses.subscription : "";
const extra = { source: autoOn ? "subscription" : "checkout" };
if (autoOn) extra.autoRenew = true;
if (stripeSub) extra.stripeSub = stripeSub;
await grantVip(uid, planKey, c.exp, extra);
await markOrder(sid, uid, planKey, c.exp);
try {
const open = await rtdb("pay_open/" + uid, "GET");
if (open && open.sid === sid) await rtdb("pay_open/" + uid, "DELETE");
} catch { }
return true;
});
}
async function stripeGet(path) {
if (!STRIPE_KEY) return null;
const r = await fetch("https://api.stripe.com/v1/" + path, {
headers: { Authorization: "Bearer " + STRIPE_KEY },
signal: AbortSignal.timeout(12000)
});
const d = await r.json();
if (!r.ok || !d || d.error) return null;
return d;
}
async function stripeForm(path, fields) {
if (!STRIPE_KEY) return null;
const r = await fetch("https://api.stripe.com/v1/" + path, {
method: "POST",
headers: {
Authorization: "Bearer " + STRIPE_KEY,
"Content-Type": "application/x-www-form-urlencoded"
},
body: new URLSearchParams(fields).toString(),
signal: AbortSignal.timeout(12000)
});
const d = await r.json();
if (!r.ok || !d || d.error) return null;
return d;
}
async function fulfillInvoice(inv) {
if (!inv || inv.object !== "invoice" || inv.status !== "paid") return false;
if (STRIPE_KEY.indexOf("sk_test_") !== 0 && STRIPE_KEY.indexOf("rk_test_") !== 0 && inv.livemode !== true) return false;
if (inv.billing_reason === "subscription_create") return true;
const subId = typeof inv.subscription === "string" ? inv.subscription : "";
const invId = String(inv.id || "");
if (!/^sub_[A-Za-z0-9_]+$/.test(subId) || !/^in_[A-Za-z0-9_]+$/.test(invId)) return false;
const sub = await stripeGet("subscriptions/" + encodeURIComponent(subId));
const uid = sub && sub.metadata && sub.metadata.uid;
const planKey = sub && sub.metadata && sub.metadata.plan;
const plan = PLANS[planKey];
if (!uidOk(uid) || planKey !== "month" || !plan) return false;
if (!priceOk(inv.amount_paid, inv.subtotal, plan.amount)) return false;
if (String(inv.currency || "").toLowerCase() !== "usd") return false;
return withPayLock(invId, async () => {
const c = await claimOrder(invId, uid, planKey, plan.sec);
if (c.state === "conflict" || c.state === "unknown" || !(c.exp > Math.floor(Date.now() / 1000))) return false;
await grantVip(uid, planKey, c.exp, { autoRenew: true, stripeSub: subId, source: "invoice" });
await markOrder(invId, uid, planKey, c.exp);
await trackPay(cleanVid(sub.metadata && sub.metadata.vid) || uid, { stage: "paid", uid: uid, email: sub.metadata && sub.metadata.email, plan: planKey, sid: invId, amount: inv.amount_paid, currency: inv.currency, source: "invoice" }).catch(() => { });
return true;
});
}
async function handleVipAuto(req, res) {
if (!payGate(req, res)) return;
const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
if (!idp || !googlePayUser(idp) || !uidOk(idp.sub)) return json(res, 401, { error: "login" });
if (payLimited(idp.sub, clientIp(req))) {
res.setHeader("Retry-After", "30");
return json(res, 429, { error: "rate_limited" });
}
let body;
try { body = JSON.parse((await readBody(req)).toString("utf8") || "{}"); } catch { return json(res, 400, { error: "body" }); }
const on = body.on === true;
let sub = null;
try { sub = await rtdb("users/" + idp.sub + "/subscription", "GET"); } catch { sub = null; }
const stripeSub = sub && /^sub_[A-Za-z0-9_]+$/.test(String(sub.stripeSub || "")) ? String(sub.stripeSub) : "";
if (!on) {
if (stripeSub) {
const stopped = await stripeForm("subscriptions/" + encodeURIComponent(stripeSub), { cancel_at_period_end: "true" });
if (!stopped) return json(res, 400, { error: "Payment failed" });
}
if (sub && typeof sub === "object") {
sub.autoRenew = false;
try { await rtdb("users/" + idp.sub + "/subscription", "PUT", sub); } catch { return json(res, 400, { error: "Payment failed" }); }
}
lvlCache.delete(idp.sub);
return json(res, 200, { ok: true, autoRenew: false, subscription: publicSub(sub) });
}
if (stripeSub && vipActive(sub)) {
const resumed = await stripeForm("subscriptions/" + encodeURIComponent(stripeSub), { cancel_at_period_end: "false" });
if (!resumed) return json(res, 400, { error: "Payment failed" });
sub.autoRenew = true;
try { await rtdb("users/" + idp.sub + "/subscription", "PUT", sub); } catch { return json(res, 400, { error: "Payment failed" }); }
lvlCache.delete(idp.sub);
return json(res, 200, { ok: true, autoRenew: true, subscription: publicSub(sub) });
}
json(res, 200, { ok: true, needPay: true, autoRenew: false });
}
function rememberStripeEvent(id) {
stripeEvents.add(id);
if (stripeEvents.size > 4000) {
const first = stripeEvents.values().next().value;
stripeEvents.delete(first);
}
}
async function stripeEventSeen(id) {
if (!id) return true;
if (stripeEvents.has(id)) return true;
try {
const v = await rtdb("stripe_events/" + id, "GET");
if (v && v.ok === 1) {
rememberStripeEvent(id);
return true;
}
} catch { }
return false;
}
async function stripeEventMark(id) {
if (!id) return;
rememberStripeEvent(id);
try {
await rtdb("stripe_events/" + id, "PUT", { t: Math.floor(Date.now() / 1000), ok: 1 });
} catch { }
}
async function handleStripeWebhook(req, res) {
let rawBuf;
try { rawBuf = await readBody(req); } catch {
res.writeHead(413);
return res.end();
}
if (!stripeOk(rawBuf, req.headers["stripe-signature"])) {
res.writeHead(400);
return res.end();
}
let ev;
try { ev = JSON.parse(rawBuf.toString("utf8")); } catch {
res.writeHead(400);
return res.end();
}
const evId = String(ev.id || "");
const evOk = evId && /^evt_[A-Za-z0-9_]+$/.test(evId);
if (evOk && await stripeEventSeen(evId)) {
return json(res, 200, { ok: true, dup: 1 });
}
let did = false;
if (ev.type === "checkout.session.completed" || ev.type === "checkout.session.async_payment_succeeded") {
const id = ev.data && ev.data.object && ev.data.object.id;
try {
const ses = await stripeSession(id);
if (ses) {
did = await fulfillPaid(ses);
const vid = cleanVid(ses.metadata && ses.metadata.vid);
const uid = ses.metadata && ses.metadata.uid;
await trackPay(vid || uid, { stage: did ? "paid" : "failed", uid: uid, email: ses.metadata && ses.metadata.email, plan: ses.metadata && ses.metadata.plan, sid: ses.id, amount: ses.amount_total, currency: ses.currency, error: did ? "" : "fulfill", source: "webhook" }).catch(() => { });
}
} catch { did = false; }
} else if (ev.type === "checkout.session.expired") {
const id = ev.data && ev.data.object && ev.data.object.id;
if (/^cs_[A-Za-z0-9_]+$/.test(String(id || ""))) {
try {
const ses = await stripeSession(id);
const uid = ses && ses.metadata && ses.metadata.uid;
if (ses && ses.status === "expired" && uidOk(uid)) {
const open = await rtdb("pay_open/" + uid, "GET");
if (open && open.sid === id) await rtdb("pay_open/" + uid, "DELETE");
}
if (ses && ses.status === "expired") {
await trackPay(cleanVid(ses.metadata && ses.metadata.vid) || uid, { stage: "expired", uid: uid, email: ses.metadata && ses.metadata.email, plan: ses.metadata && ses.metadata.plan, sid: ses.id, amount: ses.amount_total, currency: ses.currency, source: "webhook" }).catch(() => { });
}
} catch { }
}
did = true;
} else if (ev.type === "invoice.paid") {
const id = ev.data && ev.data.object && ev.data.object.id;
try {
const inv = await stripeGet("invoices/" + encodeURIComponent(String(id || "")));
if (inv) did = await fulfillInvoice(inv);
} catch { did = false; }
}
if ((ev.type === "checkout.session.completed" || ev.type === "checkout.session.async_payment_succeeded" || ev.type === "invoice.paid") && !did) {
res.writeHead(500);
return res.end();
}
if (evOk && did) await stripeEventMark(evId);
json(res, 200, { ok: true });
}
function handleHealth(req, res) {
if (req && adminKeyOk(req)) {
const mem = process.memoryUsage();
json(res, 200, {
ok: true,
role: ROLE,
uptime: Math.floor(process.uptime()),
bots: bots.filter((b) => botUsable(b) || (b.ready && !(b.coolUntil && Date.now() < b.coolUntil))).length,
botsTotal: bots.length,
load: bots.reduce((n, b) => n + (b.load || 0) + (b.tgLoad || 0), 0),
cap: bots.filter((b) => b.ready).length * BOT_MAX,
pipes: livePipes,
titles: titlePipes.size,
hot: hotMap.size,
files: fileCache.size,
durs: durCache.size,
memRss: Math.round(mem.rss / MB),
memHeap: Math.round(mem.heapUsed / MB)
});
return;
}
json(res, 200, { ok: true });
}
function encDlK(s) {
return String(s || "").split("").map((c) => String(c.charCodeAt(0) + 5)).join(",");
}
function chanDigits(id) {
return String(id || "").replace(/^-100/, "").replace(/^-/, "");
}
function adminKeyOk(req) {
if (!ADMIN_KEY) return false;
const h = String(req.headers.authorization || "").replace(/^Bearer\s+/i, "").trim();
const x = String(req.headers["x-admin-key"] || "").trim();
const got = h || x;
if (!got) return false;
const a = crypto.createHash("sha256").update(got).digest();
const b = crypto.createHash("sha256").update(ADMIN_KEY).digest();
return crypto.timingSafeEqual(a, b);
}
function parseTgPosts(text) {
const out = [];
const seen = new Set();
const src = String(text || "");
const re = /(?:https?:\/\/)?(?:t\.me|telegram\.me)\/c\/(\d+)\/(?:(\d+)\/)?(\d+)/gi;
let m;
while ((m = re.exec(src))) {
const chan = m[1];
const msgId = Number(m[3] || m[2]);
if (!msgId || seen.has(msgId)) continue;
seen.add(msgId);
out.push({ chan, msgId, link: "https://t.me/c/" + chan + "/" + msgId });
}
if (!out.length) {
const nums = src.match(/\b(\d{1,10})\b/g) || [];
for (const n of nums) {
const msgId = Number(n);
if (!msgId || seen.has(msgId) || n === chanDigits(CHANNEL_ID)) continue;
seen.add(msgId);
out.push({ chan: chanDigits(CHANNEL_ID), msgId, link: "https://t.me/c/" + chanDigits(CHANNEL_ID) + "/" + msgId });
}
}
return out.slice(0, 40);
}
function applyAdminCors(req, res) {
const o = String(req.headers.origin || "");
if (o && isSiteOrigin(o)) {
res.setHeader("Access-Control-Allow-Origin", o);
res.setHeader("Vary", "Origin");
}
res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Authorization,Content-Type,X-Admin-Key");
res.setHeader("Access-Control-Max-Age", "86400");
}
async function handleTgMeta(req, res, url) {
applyAdminCors(req, res);
if (!adminKeyOk(req)) return json(res, 401, { error: "auth" });
const ip = clientIp(req);
if (slotOver("tgmeta:" + ip, 30)) {
res.setHeader("Retry-After", "30");
return json(res, 429, { error: "rate_limited" });
}
let text = String(url.searchParams.get("ids") || url.searchParams.get("text") || "");
if (req.method === "POST") {
try {
const raw = await readBody(req, 65536);
const body = JSON.parse(raw.toString("utf8") || "{}");
if (body && body.text) text = String(body.text);
else if (body && body.ids) text = Array.isArray(body.ids) ? body.ids.join("\n") : String(body.ids);
} catch {
return json(res, 400, { error: "body" });
}
}
const posts = parseTgPosts(text);
if (!posts.length) return json(res, 400, { error: "no_links" });
const expect = chanDigits(CHANNEL_ID);
if (expect && posts.some((p) => p.chan && p.chan !== expect)) {
return json(res, 400, { error: "wrong_channel" });
}
let jobs = posts.map((p) => ({ msgId: p.msgId, rec: null }));
if (posts.length === 1) {
try {
const bot = pickBot(undefined, undefined, posts[0].msgId);
if (!bot) throw new Error("file");
jobs = await expandFamily(bot, posts[0].msgId);
} catch {
jobs = [{ msgId: posts[0].msgId, rec: null }];
}
}
const items = [];
for (const job of jobs) {
const link = "https://t.me/c/" + expect + "/" + job.msgId;
try {
let rec = job.rec;
if (!rec) {
const got = await fileFromPool(job.msgId, pickBot(undefined, undefined, job.msgId));
rec = got.rec;
}
const pathStr = "/stream/" + job.msgId;
const ep = episodeNum(rec.name);
items.push({
ok: true,
msgId: job.msgId,
link,
name: rec.name || "video.mp4",
size: rec.size || 0,
mime: rec.mime || "video/mp4",
duration: rec.duration || 0,
hash: rec.hash,
ep,
path: pathStr,
dataP: encDlK(pathStr),
dataH: encDlK(rec.hash)
});
} catch (e) {
items.push({
ok: false,
msgId: job.msgId,
link,
error: /missing/i.test(errText(e)) ? "missing" : (/media/i.test(errText(e)) ? "media" : "lookup")
});
}
}
json(res, 200, { ok: true, channel: expect, items });
}
function handleHome(req, res) {
if (req.method !== "GET" && req.method !== "HEAD") {
res.setHeader("Allow", "GET, HEAD");
res.writeHead(405, streamLock());
return res.end();
}
res.writeHead(204, Object.assign(streamLock(), {
"Cache-Control": "no-store",
"Content-Length": "0"
}));
res.end();
}
async function onReq(req, res) {
req.on("error", () => { });
res.on("error", () => { });
sweepBots();
let url;
try { url = new URL(req.url, "http://local"); } catch {
res.writeHead(400);
return res.end();
}
cors(req, res);
if (url.pathname === "/admin/tg-meta") applyAdminCors(req, res);
const reqOrigin = String(req.headers.origin || "");
if (reqOrigin && !isSiteOrigin(reqOrigin)) {
res.writeHead(403, { "Content-Length": "0", "Cache-Control": "no-store" });
return res.end();
}
if (req.method === "OPTIONS") {
res.writeHead(204, { "Content-Length": "0" });
return res.end();
}
try {
if (url.pathname === "/") return handleHome(req, res);
if (url.pathname === "/health") return handleHealth(req, res);
if (url.pathname === "/admin/tg-meta" && (req.method === "GET" || req.method === "POST")) return handleTgMeta(req, res, url);
if ((url.pathname === "/t" || url.pathname === "/generate-token") && (req.method === "GET" || req.method === "POST")) return handleGenerate(req, res, url);
const pm = /^\/p\/([0-9a-f]+)(?:\.mp4)?$/i.exec(url.pathname);
if (pm && (req.method === "GET" || req.method === "HEAD")) return handlePlay(req, res, url, pm[1]);
if (url.pathname === "/vip/status" && req.method === "GET") return handleVipStatus(req, res);
if (url.pathname === "/vip/track" && req.method === "POST") return handleVipTrack(req, res);
if (url.pathname === "/vip/start" && req.method === "POST") return handleVipStart(req, res);
if (url.pathname === "/vip/go" && req.method === "POST") return handleVipGo(req, res);
if (url.pathname === "/vip/confirm" && req.method === "POST") return handleVipConfirm(req, res);
if (url.pathname === "/vip/auto" && req.method === "POST") return handleVipAuto(req, res);
if (url.pathname === "/vip/stripe" && req.method === "POST") return handleStripeWebhook(req, res);
res.writeHead(404);
res.end();
} catch (e) {
if (!res.headersSent) json(res, 500, { error: "server" });
else if (!res.writableEnded) res.end();
}
}
function shutdown(code, reason) {
if (shuttingDown) return;
shuttingDown = true;
process.stderr.write("shutdown " + reason + "\n");
try {
if (httpServer) {
httpServer.close(() => process.exit(code));
if (typeof httpServer.closeIdleConnections === "function") httpServer.closeIdleConnections();
}
} catch { }
for (const b of bots) {
try { b.client.disconnect(); } catch { }
}
setTimeout(() => {
try {
if (httpServer && typeof httpServer.closeAllConnections === "function") httpServer.closeAllConnections();
} catch { }
process.exit(code);
}, 8000).unref();
}
async function main() {
if (!API_ID || !API_HASH || !STREAM_SECRET || !CHANNEL_ID) {
process.stderr.write("missing required settings\n");
process.exit(1);
}
if (!FB_PROJECT || !FB_DB || !FB_SECRET) process.stderr.write("warning: firebase settings incomplete\n");
if (ROLE === "indexer" && !STRIPE_KEY) process.stderr.write("warning: stripe not configured\n");
if (!RC_SIGN) process.stderr.write("warning: RC_SIGN_KEY not set; checkout proof disabled\n");
try {
await trimDiskCache();
} catch { }
const _diskSweep = setInterval(() => { trimDiskCache().catch(() => { }); }, 60000);
if (typeof _diskSweep.unref === "function") _diskSweep.unref();
const seenTokens = new Set();
const tokens = String(process.env.BOT_TOKENS || "")
.split(/[\s,]+/)
.map((t) => t.trim())
.filter((t) => {
if (!t.includes(":") || seenTokens.has(t)) return false;
seenTokens.add(t);
return true;
});
if (!tokens.length) {
process.stderr.write("missing BOT_TOKENS\n");
process.exit(1);
}
for (let i = 0; i < tokens.length; i++) {
botSlots.push({ token: tokens[i], idx: i, fails: 0, nextTry: 0 });
try {
await startBot(tokens[i], i);
} catch (e) {
process.stderr.write("bot " + i + " failed: " + errText(e) + "\n");
}
}
if (!bots.length) {
process.stderr.write("no bots online; will keep retrying\n");
}
setInterval(() => { reviveBots().catch(() => { }); }, 20000);
setInterval(sweepMaps, 30000).unref();
const srv = http.createServer({
keepAlive: true,
keepAliveTimeout: 65000,
keepAliveTimeoutBuffer: 500,
headersTimeout: 20000,
requestTimeout: 30000,
connectionsCheckingInterval: 10000
}, onReq);
srv.maxConnections = 20000;
srv.maxHeadersCount = 100;
srv.timeout = 0;
srv.on("clientError", (err, sock) => {
try {
if (sock.writable) sock.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
} catch { }
});
httpServer = srv;
srv.on("error", (e) => {
process.stderr.write("server: " + errText(e) + "\n");
shutdown(1, "server_error");
});
srv.listen(PORT, "0.0.0.0", () => {
if (ROLE === "indexer" && STRIPE_KEY) ensureFreeWallets().catch(() => { });
if (ROLE === "indexer" && FB_SECRET && OWNER_UID && OWNER_VIP_UNTIL > Math.floor(Date.now() / 1000)) {
grantVip(OWNER_UID, "month", OWNER_VIP_UNTIL, { autoRenew: false, source: "owner" }).catch(() => { });
}
});
}
process.on("SIGTERM", () => shutdown(0, "SIGTERM"));
process.on("SIGINT", () => shutdown(0, "SIGINT"));
process.on("unhandledRejection", (e) => {
process.stderr.write("rej " + (e && e.stack ? e.stack : errText(e)) + "\n");
});
process.on("uncaughtException", (e) => {
process.stderr.write("exc " + (e && e.stack ? e.stack : errText(e)) + "\n");
setTimeout(() => shutdown(1, "uncaughtException"), 1200).unref();
});
main().catch((e) => {
process.stderr.write(String(e && e.stack || e) + "\n");
process.exit(1);
});
;
const http = require("http");
const fs = require("fs");
const os = require("os");
const path = require("path");
const crypto = require("crypto");
const { TelegramClient, Api } = require("teleproto");
const { StringSession } = require("teleproto/sessions");
const PORT = Number(process.env.PORT || 7860);
const RAW_ORIGIN = process.env.ALLOWED_ORIGIN || "https://dublk2000.pages.dev";
let SITE_ORIGIN = "https://dublk2000.pages.dev";
try {
const u = new URL(RAW_ORIGIN);
if (u.protocol === "https:") SITE_ORIGIN = u.origin;
} catch { }
const SITE_HOST = new URL(SITE_ORIGIN).hostname.toLowerCase();
const SITE_HOSTS = new Set([SITE_HOST]);
const CHANNEL_ID = process.env.TELEGRAM_CHANNEL_ID || "";
const API_ID = Number(process.env.TELEGRAM_API_ID || 0);
const API_HASH = process.env.TELEGRAM_API_HASH || "";
const STREAM_SECRET = process.env.STREAM_SECRET || "";
const ROLE = (process.env.NODE_ROLE || "stream").toLowerCase();
const OWNER_UID = String(process.env.OWNER_UID || "").trim();
const OWNER_VIP_UNTIL = Number(process.env.OWNER_VIP_UNTIL || 0);
const HASH_LEN = 6;
const TOKEN_TTL = 14400;
const MB = 1024 * 1024;
const CPU_N = Math.max(1, (os.cpus() || []).length || 2);
function cgroupLimitBytes() {
const paths = ["/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"];
for (const p of paths) {
try {
const raw = fs.readFileSync(p, "utf8").trim();
if (!raw || raw === "max") continue;
const n = Number(raw);
if (Number.isFinite(n) && n > 64 * MB) return Math.min(n, os.totalmem() || n);
} catch { }
}
return 0;
}
const CGROUP_BYTES = cgroupLimitBytes();
const RAM_BYTES = CGROUP_BYTES || os.totalmem() || (16 * 1024 * MB);
const CHUNK_SIZE = 512 * 1024;
const HOT_HEAD = 32 * MB;
const HOT_TAIL = 12 * MB;
const STREAM_WINDOW = 32 * MB;
const PROBE_HEAD = 8 * MB;
const BOT_MAX = 100;
const PIPE_FIRST_MS = 60000;
const PIPE_IDLE_MS = 22000;
const PIPE_MAX_MS = 6 * 60 * 60 * 1000;
const RANGE_LOOKAHEAD = 8;
const WARM_AHEAD = 6;
const WARM_BUDGET_BYTES = 128 * MB;
let warmBytesInFlight = 0;
const WARM_BATCH = Math.max(2, Math.min(4, CPU_N * 2));
const IP_STREAM_MAX = 20;
const IP_TITLE_MAX = 40;
const UID_STREAM_MAX = 8;
const UID_TITLE_MAX = 20;
const TITLE_PIPE_MAX = 400;
const GLOBAL_PIPE_MAX = 20000;
const DISK_SLICE_DIR = "/tmp/dlk_slice";
const DISK_MAX_BYTES = 24 * 1024 * 1024 * 1024;
const DISK_FREE_MIN_BYTES = 4 * 1024 * 1024 * 1024;
const HOT_BYTES_MAX = Math.min(3072 * MB, Math.max(1024 * MB, Math.floor(RAM_BYTES * 0.2)));
const BODY_MAX = 262144;
const FILE_TTL = 20 * 60 * 1000;
const LVL_TTL = 60000;
const FB_PROJECT = process.env.FIREBASE_PROJECT_ID || "";
const FB_DB = String(process.env.FIREBASE_DB_URL || "").replace(/\/?$/, "/");
const FB_SECRET = process.env.FIREBASE_DB_SECRET || "";
const STRIPE_KEY = process.env.STRIPE_SECRET_KEY || "";
const STRIPE_WH = process.env.STRIPE_WEBHOOK_SECRET || "";
const RC_SIGN = process.env.RC_SIGN_KEY || "";
const SPACE_FALLBACK = [
"https://dublk2000-s1.hf.space",
"https://dublk2000-s2.hf.space",
"https://server2-s3.hf.space",
"https://server2-s4.hf.space",
"https://server2-s5.hf.space"
];
const SPACE_URLS = String(process.env.SPACE_URLS || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
if (!SPACE_URLS.length) SPACE_URLS.push(...SPACE_FALLBACK);
const PLANS = {
day: { amount: 99, label: "1 Day VIP", sec: 86400, price: "0.99" },
week: { amount: 199, label: "1 Week VIP", sec: 604800, price: "1.99" },
month: { amount: 599, label: "1 Month VIP", sec: 2592000, price: "5.99" }
};
const HOME_URL = SITE_ORIGIN + "/";
const BRAND_URL = SITE_ORIGIN + "/assets/brand-mark.png";
const deriveKey = STREAM_SECRET
? (info) => crypto.hkdfSync("sha256", Buffer.from(STREAM_SECRET, "utf8"), Buffer.from("dublk2000"), Buffer.from(info), 32)