Spaces:
Running
Running
JOHN SILLVESTOR commited on
Improve stream range lookahead and pipe error resilience
Browse files
server.js
CHANGED
|
@@ -9,7 +9,14 @@ const { TelegramClient, Api } = require("teleproto");
|
|
| 9 |
const { StringSession } = require("teleproto/sessions");
|
| 10 |
|
| 11 |
const PORT = Number(process.env.PORT || 7860);
|
| 12 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
const CHANNEL_ID = process.env.TELEGRAM_CHANNEL_ID || "";
|
| 14 |
const API_ID = Number(process.env.TELEGRAM_API_ID || 0);
|
| 15 |
const API_HASH = process.env.TELEGRAM_API_HASH || "";
|
|
@@ -17,7 +24,6 @@ const STREAM_SECRET = process.env.STREAM_SECRET || "";
|
|
| 17 |
const ROLE = (process.env.NODE_ROLE || "stream").toLowerCase();
|
| 18 |
const HASH_LEN = 6;
|
| 19 |
const TOKEN_TTL = 14400;
|
| 20 |
-
const MIN_ALIGN = 4096;
|
| 21 |
const MB = 1024 * 1024;
|
| 22 |
const CPU_N = Math.max(1, (os.cpus() || []).length || 2);
|
| 23 |
function cgroupLimitBytes() {
|
|
@@ -40,7 +46,6 @@ const HOT_TAIL = 12 * MB;
|
|
| 40 |
const STREAM_WINDOW = 32 * MB;
|
| 41 |
const PROBE_HEAD = 8 * MB;
|
| 42 |
const BOT_MAX = 100;
|
| 43 |
-
const PIPE_MS = 30000;
|
| 44 |
const PIPE_FIRST_MS = 60000;
|
| 45 |
const PIPE_IDLE_MS = 22000;
|
| 46 |
const PIPE_MAX_MS = 3 * 60 * 60 * 1000;
|
|
@@ -86,8 +91,8 @@ const PLANS = {
|
|
| 86 |
week: { amount: 199, label: "1 Week VIP", sec: 604800, price: "1.99" },
|
| 87 |
month: { amount: 599, label: "1 Month VIP", sec: 2592000, price: "5.99" }
|
| 88 |
};
|
| 89 |
-
const HOME_URL = "
|
| 90 |
-
const BRAND_URL = "
|
| 91 |
|
| 92 |
const deriveKey = STREAM_SECRET
|
| 93 |
? (info) => crypto.hkdfSync("sha256", Buffer.from(STREAM_SECRET, "utf8"), Buffer.from("dublk2000"), Buffer.from(info), 32)
|
|
@@ -98,11 +103,7 @@ const adminKey = deriveKey ? Buffer.from(deriveKey("admin-api-v1")).toString("he
|
|
| 98 |
const ADMIN_KEY_ENV = String(process.env.ADMIN_API_KEY || "");
|
| 99 |
const ADMIN_KEY = ADMIN_KEY_ENV || adminKey;
|
| 100 |
|
| 101 |
-
|
| 102 |
-
"dublk2000.pages.dev"
|
| 103 |
-
]);
|
| 104 |
-
|
| 105 |
-
function blogHostOf(req) {
|
| 106 |
const o = String((req && req.headers && (req.headers.origin || req.headers.referer)) || "");
|
| 107 |
try {
|
| 108 |
if (!o) return "";
|
|
@@ -192,7 +193,7 @@ function openTicket(hex) {
|
|
| 192 |
|
| 193 |
function cors(req, res) {
|
| 194 |
const o = req.headers.origin || "";
|
| 195 |
-
const allow =
|
| 196 |
if (allow) res.setHeader("Access-Control-Allow-Origin", o);
|
| 197 |
res.setHeader("Vary", "Origin");
|
| 198 |
res.setHeader("Access-Control-Allow-Methods", "GET,POST,HEAD,OPTIONS");
|
|
@@ -205,7 +206,7 @@ function cors(req, res) {
|
|
| 205 |
res.setHeader("X-Frame-Options", "DENY");
|
| 206 |
res.setHeader("X-Robots-Tag", "noindex, nofollow, noarchive");
|
| 207 |
res.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=(), usb=(), payment=(), browsing-topics=()");
|
| 208 |
-
res.setHeader("Strict-Transport-Security", "max-age=
|
| 209 |
res.setHeader("X-Permitted-Cross-Domain-Policies", "none");
|
| 210 |
res.setHeader("X-XSS-Protection", "0");
|
| 211 |
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
|
|
@@ -247,9 +248,8 @@ function streamLock() {
|
|
| 247 |
"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet, noimageindex",
|
| 248 |
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), usb=(), payment=(), browsing-topics=()",
|
| 249 |
"Cross-Origin-Resource-Policy": "cross-origin",
|
| 250 |
-
"Access-Control-Allow-Origin": "*",
|
| 251 |
"Access-Control-Expose-Headers": "Content-Range,Content-Length,Accept-Ranges,Content-Type",
|
| 252 |
-
"Strict-Transport-Security": "max-age=
|
| 253 |
"X-Permitted-Cross-Domain-Policies": "none",
|
| 254 |
"X-XSS-Protection": "0"
|
| 255 |
};
|
|
@@ -326,10 +326,11 @@ function coolBot(bot, e) {
|
|
| 326 |
const sec = m ? Number(m[1]) : Number(e && e.seconds || 0);
|
| 327 |
if (sec > 8) bot.coolUntil = Date.now() + Math.min(sec, 90) * 1000;
|
| 328 |
if (/AUTH_KEY|SESSION_REVOKED|USER_DEACTIVATED|PHONE_NUMBER_BANNED/i.test(t)) bot.ready = false;
|
|
|
|
| 329 |
}
|
| 330 |
|
| 331 |
function botUsable(b) {
|
| 332 |
-
if (!b || !b.ready) return false;
|
| 333 |
if (b.coolUntil && Date.now() < b.coolUntil) return false;
|
| 334 |
if (b.client && b.client.connected === false) return false;
|
| 335 |
return (b.tgLoad || 0) < BOT_MAX;
|
|
@@ -438,6 +439,10 @@ function sweepMaps() {
|
|
| 438 |
if (!v || now - v.ts > LVL_TTL * 4) lvlCache.delete(k);
|
| 439 |
}
|
| 440 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
if (durCache.size > 50000) {
|
| 442 |
const ids = [...durCache.keys()].slice(0, durCache.size - 35000);
|
| 443 |
for (const id of ids) durCache.delete(id);
|
|
@@ -554,19 +559,14 @@ function mintFailed(ip) {
|
|
| 554 |
return slotOver("badm:" + String(ip || "0"), 60);
|
| 555 |
}
|
| 556 |
|
| 557 |
-
function
|
| 558 |
o = String(o || "").trim();
|
| 559 |
if (!o || o.toLowerCase() === "null") return false;
|
| 560 |
try {
|
| 561 |
const u = new URL(o.includes("://") ? o : "https://" + o);
|
| 562 |
if (u.protocol !== "https:" || u.username || u.password) return false;
|
| 563 |
if (u.port && u.port !== "443") return false;
|
| 564 |
-
|
| 565 |
-
if (BLOG_HOSTS.has(h)) return true;
|
| 566 |
-
const allow = String(ORIGIN || "").replace(/\/$/, "");
|
| 567 |
-
if (!allow) return false;
|
| 568 |
-
const au = new URL(allow);
|
| 569 |
-
return u.origin === au.origin && h === au.hostname.toLowerCase();
|
| 570 |
} catch {
|
| 571 |
return false;
|
| 572 |
}
|
|
@@ -580,20 +580,20 @@ function playExt(mime, name) {
|
|
| 580 |
return ".mp4";
|
| 581 |
}
|
| 582 |
|
| 583 |
-
function
|
| 584 |
const o = String(req.headers.origin || "").trim();
|
| 585 |
-
if (o && o.toLowerCase() !== "null") return
|
| 586 |
const r = String(req.headers.referer || "");
|
| 587 |
if (!r) return false;
|
| 588 |
try {
|
| 589 |
-
return
|
| 590 |
} catch {
|
| 591 |
return false;
|
| 592 |
}
|
| 593 |
}
|
| 594 |
|
| 595 |
function denyHot(req, res) {
|
| 596 |
-
if (
|
| 597 |
json(res, 403, { error: "forbidden" });
|
| 598 |
return true;
|
| 599 |
}
|
|
@@ -641,7 +641,7 @@ function ticketUaOk(ticket, ua) {
|
|
| 641 |
function payLimited(uid, ip) {
|
| 642 |
const slot = Math.floor(Date.now() / 60000);
|
| 643 |
const a = "pay:" + uid + ":" + slot;
|
| 644 |
-
const b = "payip:" + ip + ":" + slot;
|
| 645 |
const na = (rateMap.get(a) || 0) + 1;
|
| 646 |
const nb = (rateMap.get(b) || 0) + 1;
|
| 647 |
rateMap.set(a, na);
|
|
@@ -772,7 +772,8 @@ function verifyProof(proof, ip) {
|
|
| 772 |
return timingSafeEq(mac, m[2]);
|
| 773 |
}
|
| 774 |
|
| 775 |
-
async function stripeSession(id) {
|
|
|
|
| 776 |
const r = await fetch("https://api.stripe.com/v1/checkout/sessions/" + encodeURIComponent(id), {
|
| 777 |
headers: { Authorization: "Bearer " + STRIPE_KEY },
|
| 778 |
signal: AbortSignal.timeout(12000)
|
|
@@ -841,6 +842,7 @@ function pickBot(preferIdx, skipIdx, msgId) {
|
|
| 841 |
|
| 842 |
function sweepBots() {
|
| 843 |
for (const b of bots) {
|
|
|
|
| 844 |
if (b.client && b.client.connected === false) b.ready = false;
|
| 845 |
else if (b.client && b.client.connected !== false && !b.ready && !(b.coolUntil && Date.now() < b.coolUntil)) b.ready = true;
|
| 846 |
}
|
|
@@ -848,7 +850,7 @@ function sweepBots() {
|
|
| 848 |
|
| 849 |
async function startBot(token, idx) {
|
| 850 |
const existing = bots.find((b) => b.idx === idx);
|
| 851 |
-
if (existing && existing.ready && existing.client && existing.client.connected !== false) {
|
| 852 |
existing.nextTry = 0;
|
| 853 |
existing.fails = 0;
|
| 854 |
return;
|
|
@@ -884,6 +886,7 @@ async function startBot(token, idx) {
|
|
| 884 |
existing.client = client;
|
| 885 |
existing.token = token;
|
| 886 |
existing.ready = true;
|
|
|
|
| 887 |
existing.load = 0;
|
| 888 |
existing.tgLoad = 0;
|
| 889 |
existing.coolUntil = 0;
|
|
@@ -894,13 +897,14 @@ async function startBot(token, idx) {
|
|
| 894 |
}
|
| 895 |
return;
|
| 896 |
}
|
| 897 |
-
bots.push({ client, token, idx, ready: true, load: 0, tgLoad: 0, coolUntil: 0, fails: 0, nextTry: 0 });
|
| 898 |
}
|
| 899 |
|
| 900 |
async function reviveBots() {
|
| 901 |
sweepBots();
|
| 902 |
const now = Date.now();
|
| 903 |
for (const slot of botSlots) {
|
|
|
|
| 904 |
if (now < (slot.nextTry || 0)) continue;
|
| 905 |
const b = bots.find((x) => x.idx === slot.idx);
|
| 906 |
if (b && b.ready && b.client && b.client.connected !== false) {
|
|
@@ -913,6 +917,11 @@ async function reviveBots() {
|
|
| 913 |
slot.fails = 0;
|
| 914 |
slot.nextTry = 0;
|
| 915 |
} catch (e) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 916 |
slot.fails = (slot.fails || 0) + 1;
|
| 917 |
const base = Math.min(300000, 15000 * Math.pow(2, Math.min(slot.fails - 1, 4)));
|
| 918 |
slot.nextTry = Date.now() + base + Math.floor(Math.random() * 5000);
|
|
@@ -1216,8 +1225,6 @@ async function fillDuration(bot, rec, msgId) {
|
|
| 1216 |
return d;
|
| 1217 |
}
|
| 1218 |
|
| 1219 |
-
const LVL_PCT = { anonymous: 80, registered: 80, subscribed: 100 };
|
| 1220 |
-
const INDEX_WIN = 4 * MB;
|
| 1221 |
const TAIL_MAX = 2 * MB;
|
| 1222 |
const TAIL_MIN_SIZE = 48 * MB;
|
| 1223 |
|
|
@@ -1337,12 +1344,14 @@ function applyPreview(rng, size, l, msgId, ticket) {
|
|
| 1337 |
return null;
|
| 1338 |
}
|
| 1339 |
|
| 1340 |
-
function denyRange(res, size) {
|
| 1341 |
res.writeHead(416, Object.assign(streamLock(), {
|
| 1342 |
"Content-Range": "bytes */" + size,
|
| 1343 |
"Content-Type": "video/mp4",
|
| 1344 |
"Cache-Control": "private, no-store, no-transform",
|
| 1345 |
-
"Accept-Ranges": "bytes"
|
|
|
|
|
|
|
| 1346 |
}));
|
| 1347 |
return res.end();
|
| 1348 |
}
|
|
@@ -1383,7 +1392,7 @@ function parseRange(h, size, msgId) {
|
|
| 1383 |
return { start, end, partial: start > 0 || end < size - 1 };
|
| 1384 |
}
|
| 1385 |
|
| 1386 |
-
function mediaHeaders(type, msgId, size, hash, rng) {
|
| 1387 |
const headers = Object.assign(streamLock(), {
|
| 1388 |
"Content-Type": type,
|
| 1389 |
"Accept-Ranges": "bytes",
|
|
@@ -1393,6 +1402,8 @@ function mediaHeaders(type, msgId, size, hash, rng) {
|
|
| 1393 |
"X-Accel-Buffering": "no",
|
| 1394 |
"Content-Length": String(rng.end - rng.start + 1),
|
| 1395 |
"Content-Range": "bytes " + rng.start + "-" + rng.end + "/" + size,
|
|
|
|
|
|
|
| 1396 |
"Connection": "keep-alive"
|
| 1397 |
});
|
| 1398 |
return headers;
|
|
@@ -1680,7 +1691,6 @@ async function rangeSlicesReady(msgId, start, end) {
|
|
| 1680 |
return true;
|
| 1681 |
}
|
| 1682 |
|
| 1683 |
-
const avLead = new Map();
|
| 1684 |
const elstLeadSec = new Map();
|
| 1685 |
|
| 1686 |
function geckoUA(ua) {
|
|
@@ -1751,12 +1761,6 @@ function rememberElstLead(msgId, buf) {
|
|
| 1751 |
const first = elstLeadSec.keys().next().value;
|
| 1752 |
elstLeadSec.delete(first);
|
| 1753 |
}
|
| 1754 |
-
let st = avLead.get(id);
|
| 1755 |
-
if (!st) {
|
| 1756 |
-
st = { delay: 0, movieTs: 1000 };
|
| 1757 |
-
avLead.set(id, st);
|
| 1758 |
-
}
|
| 1759 |
-
if (!st.delay) st.delay = Math.round(sec * st.movieTs);
|
| 1760 |
}
|
| 1761 |
}
|
| 1762 |
|
|
@@ -2136,10 +2140,8 @@ async function handleGenerate(req, res) {
|
|
| 2136 |
try {
|
| 2137 |
const raw = JSON.parse((await readBody(req, 4096)).toString("utf8") || "{}");
|
| 2138 |
if (raw && raw.enc) {
|
| 2139 |
-
const
|
| 2140 |
-
const
|
| 2141 |
-
const dom = BLOG_HOSTS.has(reqHost) ? reqHost : "dublk2000.pages.dev";
|
| 2142 |
-
try { if (oHeader) dom = new URL(oHeader.includes("://") ? oHeader : "https://" + oHeader).hostname; } catch { }
|
| 2143 |
const decReq = (enc, d) => {
|
| 2144 |
try {
|
| 2145 |
const key = Buffer.from(d, "utf8");
|
|
@@ -2154,7 +2156,7 @@ async function handleGenerate(req, res) {
|
|
| 2154 |
return JSON.parse(out.join(""));
|
| 2155 |
} catch { return null; }
|
| 2156 |
};
|
| 2157 |
-
const parsed = decReq(raw.enc, dom) || decReq(raw.enc,
|
| 2158 |
if (parsed) {
|
| 2159 |
if (parsed.p) path = String(parsed.p);
|
| 2160 |
if (parsed.h) hash = String(parsed.h).toLowerCase();
|
|
@@ -2292,28 +2294,17 @@ async function handleStream(req, res, url, msgId, kHex, ticketObj) {
|
|
| 2292 |
return res.end();
|
| 2293 |
}
|
| 2294 |
const oH = req.headers.origin || "";
|
| 2295 |
-
if (oH && !isBlogOrigin(oH)) {
|
| 2296 |
-
res.writeHead(403);
|
| 2297 |
-
return res.end();
|
| 2298 |
-
}
|
| 2299 |
const rH = req.headers.referer || "";
|
|
|
|
|
|
|
| 2300 |
if (rH) {
|
| 2301 |
-
try {
|
| 2302 |
-
const rOrigin = new URL(rH).origin;
|
| 2303 |
-
if (!isBlogOrigin(rOrigin)) {
|
| 2304 |
-
res.writeHead(403);
|
| 2305 |
-
return res.end();
|
| 2306 |
-
}
|
| 2307 |
-
} catch {
|
| 2308 |
-
res.writeHead(403);
|
| 2309 |
-
return res.end();
|
| 2310 |
-
}
|
| 2311 |
}
|
| 2312 |
-
|
| 2313 |
-
if (!oH && !rH) {
|
| 2314 |
res.writeHead(403);
|
| 2315 |
return res.end();
|
| 2316 |
}
|
|
|
|
| 2317 |
const k = kHex || url.searchParams.get("k") || "";
|
| 2318 |
const ticket = ticketObj || openTicket(k);
|
| 2319 |
if (!ticket || ticket.m !== msgId || !/^[0-9a-f]{6}$/.test(String(ticket.h || ""))) {
|
|
@@ -2331,17 +2322,7 @@ async function handleStream(req, res, url, msgId, kHex, ticketObj) {
|
|
| 2331 |
}
|
| 2332 |
const vipUntil = Number(ticket.x) || 0;
|
| 2333 |
if (ticketLvl(ticket) === "subscribed" && vipUntil > 0 && vipUntil <= Math.floor(Date.now() / 1000)) ticket.l = "registered";
|
| 2334 |
-
const isVip = ticketLvl(ticket) === "subscribed";
|
| 2335 |
|
| 2336 |
-
let validBlog = true;
|
| 2337 |
-
if (oH && !isBlogOrigin(oH)) validBlog = false;
|
| 2338 |
-
else if (rH) {
|
| 2339 |
-
try { validBlog = isBlogOrigin(new URL(rH).origin); } catch { validBlog = false; }
|
| 2340 |
-
}
|
| 2341 |
-
if (!validBlog) {
|
| 2342 |
-
res.writeHead(403);
|
| 2343 |
-
return res.end();
|
| 2344 |
-
}
|
| 2345 |
let held = false;
|
| 2346 |
try {
|
| 2347 |
if (!takeStream(ip, ticket.u, msgId)) {
|
|
@@ -2361,9 +2342,9 @@ async function handleStream(req, res, url, msgId, kHex, ticketObj) {
|
|
| 2361 |
if (sizeHint > 0) {
|
| 2362 |
const rngHot0 = parseRange(req.headers.range, sizeHint, msgId);
|
| 2363 |
const rngHot = applyPreview(rngHot0, sizeHint, lvl, msgId, ticket);
|
| 2364 |
-
if (!rngHot) return denyRange(res, sizeHint);
|
| 2365 |
const needHot = rngHot.end - rngHot.start + 1;
|
| 2366 |
-
const headersHot = mediaHeaders(typeHint, msgId, sizeHint, ticket.h, rngHot);
|
| 2367 |
if (req.method === "HEAD") {
|
| 2368 |
res.writeHead(206, headersHot);
|
| 2369 |
return res.end();
|
|
@@ -2381,7 +2362,7 @@ async function handleStream(req, res, url, msgId, kHex, ticketObj) {
|
|
| 2381 |
if (hit && hit.length > 0 && rngHot.start === 0 && (!req.headers.range || req.headers.range === "bytes=0-")) {
|
| 2382 |
const serveLen = Math.min(hit.length, needHot);
|
| 2383 |
const fastRng = { start: 0, end: serveLen - 1, partial: true };
|
| 2384 |
-
const fastHeaders = mediaHeaders(typeHint, msgId, sizeHint, ticket.h, fastRng);
|
| 2385 |
if (res.socket) {
|
| 2386 |
try { res.socket.setNoDelay(true); } catch { }
|
| 2387 |
}
|
|
@@ -2445,8 +2426,8 @@ async function handleStream(req, res, url, msgId, kHex, ticketObj) {
|
|
| 2445 |
}
|
| 2446 |
const rng0 = parseRange(req.headers.range, size, msgId);
|
| 2447 |
const rng = applyPreview(rng0, size, lvl, msgId, ticket);
|
| 2448 |
-
if (!rng) return denyRange(res, size);
|
| 2449 |
-
const headers = mediaHeaders(typeHint, msgId, size, rec.hash, rng);
|
| 2450 |
if (req.method === "HEAD") {
|
| 2451 |
res.writeHead(206, headers);
|
| 2452 |
return res.end();
|
|
@@ -2502,21 +2483,21 @@ async function handleVipStatus(req, res) {
|
|
| 2502 |
json(res, 200, { accessLevel: lvl });
|
| 2503 |
}
|
| 2504 |
|
| 2505 |
-
function
|
| 2506 |
try {
|
| 2507 |
-
const p = new URL(String(u || ""),
|
| 2508 |
-
if (p.protocol !== "https:" || p.username || p.password) return
|
| 2509 |
-
if (p.port && p.port !== "443") return
|
| 2510 |
-
if (!
|
| 2511 |
const mobile = p.searchParams.get("m") === "1" ? "?m=1" : "";
|
| 2512 |
return p.origin + p.pathname + mobile;
|
| 2513 |
} catch {
|
| 2514 |
-
return
|
| 2515 |
}
|
| 2516 |
}
|
| 2517 |
|
| 2518 |
function payUrls(ret) {
|
| 2519 |
-
const base =
|
| 2520 |
const join = base.indexOf("?") >= 0 ? "&" : "?";
|
| 2521 |
return {
|
| 2522 |
success: base + join + "vip=success&sid={CHECKOUT_SESSION_ID}",
|
|
@@ -2530,36 +2511,6 @@ let walletJob = null;
|
|
| 2530 |
let paypalLive = false;
|
| 2531 |
let payTypes = ["card"];
|
| 2532 |
|
| 2533 |
-
let radarAllowListId = "rsl_1US9ywR5hlNPhhqRtm217ol4";
|
| 2534 |
-
const radarAllowCache = new Set();
|
| 2535 |
-
async function autoAllowEmail(email) {
|
| 2536 |
-
if (!email || !STRIPE_KEY || radarAllowCache.has(email)) return;
|
| 2537 |
-
radarAllowCache.add(email);
|
| 2538 |
-
if (radarAllowCache.size > 5000) {
|
| 2539 |
-
const first = radarAllowCache.values().next().value;
|
| 2540 |
-
radarAllowCache.delete(first);
|
| 2541 |
-
}
|
| 2542 |
-
try {
|
| 2543 |
-
if (!radarAllowListId) {
|
| 2544 |
-
const list = await stripeGet("radar/value_lists");
|
| 2545 |
-
const rows = list && Array.isArray(list.data) ? list.data : [];
|
| 2546 |
-
const match = rows.find((x) => x && x.alias === "customer_email_allowlist");
|
| 2547 |
-
if (match) radarAllowListId = match.id;
|
| 2548 |
-
}
|
| 2549 |
-
if (!radarAllowListId) return;
|
| 2550 |
-
const body = new URLSearchParams({ value_list: radarAllowListId, value: email }).toString();
|
| 2551 |
-
await fetch("https://api.stripe.com/v1/radar/value_list_items", {
|
| 2552 |
-
method: "POST",
|
| 2553 |
-
headers: {
|
| 2554 |
-
Authorization: "Bearer " + STRIPE_KEY,
|
| 2555 |
-
"Content-Type": "application/x-www-form-urlencoded"
|
| 2556 |
-
},
|
| 2557 |
-
body,
|
| 2558 |
-
signal: AbortSignal.timeout(4000)
|
| 2559 |
-
});
|
| 2560 |
-
} catch { }
|
| 2561 |
-
}
|
| 2562 |
-
|
| 2563 |
function payPref(node) {
|
| 2564 |
const d = node && node.display_preference;
|
| 2565 |
if (!d) return "";
|
|
@@ -2690,7 +2641,6 @@ async function handleVipStart(req, res) {
|
|
| 2690 |
if (!verifyProof(body.proof, clientIp(req))) {
|
| 2691 |
return json(res, 400, { error: "captcha" });
|
| 2692 |
}
|
| 2693 |
-
autoAllowEmail(email).catch(() => { });
|
| 2694 |
const auto = planKey === "month" && body.auto === true;
|
| 2695 |
const urls = payUrls(body.returnUrl);
|
| 2696 |
const wallets = await ensureFreeWallets();
|
|
@@ -2769,7 +2719,7 @@ async function handleVipStart(req, res) {
|
|
| 2769 |
].forEach((k) => { delete slim[k]; });
|
| 2770 |
({ r, d } = await createSes(slim, idem + "s"));
|
| 2771 |
if (!r.ok) {
|
| 2772 |
-
|
| 2773 |
}
|
| 2774 |
}
|
| 2775 |
if (!r.ok || !d.id || !d.url || d.object !== "checkout.session") return json(res, 400, { error: "Payment failed" });
|
|
@@ -3098,7 +3048,11 @@ async function stripeEventMark(id) {
|
|
| 3098 |
}
|
| 3099 |
|
| 3100 |
async function handleStripeWebhook(req, res) {
|
| 3101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3102 |
if (!stripeOk(rawBuf, req.headers["stripe-signature"])) {
|
| 3103 |
res.writeHead(400);
|
| 3104 |
return res.end();
|
|
@@ -3148,46 +3102,8 @@ async function handleStripeWebhook(req, res) {
|
|
| 3148 |
json(res, 200, { ok: true });
|
| 3149 |
}
|
| 3150 |
|
| 3151 |
-
const FB_CLIENT_CFG = {
|
| 3152 |
-
apiKey: "AIzaSyAxMYsWapi7dgHq6DBBBF9j3wHHqgmgDjc",
|
| 3153 |
-
authDomain: "dublk2000-auth.firebaseapp.com",
|
| 3154 |
-
databaseURL: "wss://dublk2000-auth-default-rtdb.firebaseio.com/",
|
| 3155 |
-
projectId: "dublk2000-auth",
|
| 3156 |
-
storageBucket: "dublk2000-auth.firebasestorage.app",
|
| 3157 |
-
messagingSenderId: "475299842360",
|
| 3158 |
-
appId: "1:475299842360:web:7f0c4d346a7affe8e3d9cd",
|
| 3159 |
-
measurementId: "G-B8RYS5PYSQ"
|
| 3160 |
-
};
|
| 3161 |
-
const G_CLIENT_ID = "475299842360-crrejjs7b7krvpsuu16jc9mimg0qaing.apps.googleusercontent.com";
|
| 3162 |
-
|
| 3163 |
-
function encDomain(text, domain) {
|
| 3164 |
-
const dom = domain || "dublk2000.pages.dev";
|
| 3165 |
-
const key = Buffer.from(dom, "utf8");
|
| 3166 |
-
const kLen = key.length;
|
| 3167 |
-
const out = [];
|
| 3168 |
-
for (let i = 0; i < text.length; i++) {
|
| 3169 |
-
const k = key[i % kLen];
|
| 3170 |
-
const c = (text.charCodeAt(i) ^ k ^ ((i * 7 + 13) & 0xff));
|
| 3171 |
-
out.push(c);
|
| 3172 |
-
}
|
| 3173 |
-
return out.join(",");
|
| 3174 |
-
}
|
| 3175 |
-
|
| 3176 |
-
async function handleBootstrap(req, res, url) {
|
| 3177 |
-
if (!destOk(req, ["empty"])) return json(res, 403, { error: "forbidden" });
|
| 3178 |
-
if (denyHot(req, res)) return;
|
| 3179 |
-
const bundle = {
|
| 3180 |
-
fb: FB_CLIENT_CFG,
|
| 3181 |
-
gc: G_CLIENT_ID
|
| 3182 |
-
};
|
| 3183 |
-
const dom = BLOG_HOSTS.has(blogHostOf(req)) ? blogHostOf(req) : "dublk2000.pages.dev";
|
| 3184 |
-
json(res, 200, {
|
| 3185 |
-
p: encDomain(JSON.stringify(bundle), dom)
|
| 3186 |
-
}, "private, max-age=30");
|
| 3187 |
-
}
|
| 3188 |
-
|
| 3189 |
function handleHealth(req, res) {
|
| 3190 |
-
if (req && adminKeyOk(req
|
| 3191 |
const mem = process.memoryUsage();
|
| 3192 |
json(res, 200, {
|
| 3193 |
ok: true,
|
|
@@ -3218,13 +3134,15 @@ function chanDigits(id) {
|
|
| 3218 |
return String(id || "").replace(/^-100/, "").replace(/^-/, "");
|
| 3219 |
}
|
| 3220 |
|
| 3221 |
-
function adminKeyOk(req
|
| 3222 |
if (!ADMIN_KEY) return false;
|
| 3223 |
const h = String(req.headers.authorization || "").replace(/^Bearer\s+/i, "").trim();
|
| 3224 |
const x = String(req.headers["x-admin-key"] || "").trim();
|
| 3225 |
const got = h || x;
|
| 3226 |
-
if (!got
|
| 3227 |
-
|
|
|
|
|
|
|
| 3228 |
}
|
| 3229 |
|
| 3230 |
function parseTgPosts(text) {
|
|
@@ -3252,16 +3170,20 @@ function parseTgPosts(text) {
|
|
| 3252 |
return out.slice(0, 40);
|
| 3253 |
}
|
| 3254 |
|
| 3255 |
-
function applyAdminCors(res) {
|
| 3256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3257 |
res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
|
| 3258 |
res.setHeader("Access-Control-Allow-Headers", "Authorization,Content-Type,X-Admin-Key");
|
| 3259 |
res.setHeader("Access-Control-Max-Age", "86400");
|
| 3260 |
}
|
| 3261 |
|
| 3262 |
async function handleTgMeta(req, res, url) {
|
| 3263 |
-
applyAdminCors(res);
|
| 3264 |
-
if (!adminKeyOk(req
|
| 3265 |
const ip = clientIp(req);
|
| 3266 |
if (limited(ip)) {
|
| 3267 |
res.setHeader("Retry-After", "2");
|
|
@@ -3355,7 +3277,7 @@ async function onReq(req, res) {
|
|
| 3355 |
return res.end();
|
| 3356 |
}
|
| 3357 |
cors(req, res);
|
| 3358 |
-
if (url.pathname === "/admin/tg-meta") applyAdminCors(res);
|
| 3359 |
if (req.method === "OPTIONS") {
|
| 3360 |
res.writeHead(204, { "Content-Length": "0" });
|
| 3361 |
return res.end();
|
|
@@ -3363,11 +3285,6 @@ async function onReq(req, res) {
|
|
| 3363 |
try {
|
| 3364 |
if (url.pathname === "/") return handleHome(req, res);
|
| 3365 |
if (url.pathname === "/health") return handleHealth(req, res);
|
| 3366 |
-
if (url.pathname === "/public/brand.png" && (req.method === "GET" || req.method === "HEAD")) {
|
| 3367 |
-
res.writeHead(302, { Location: BRAND_URL, "Cache-Control": "no-store" });
|
| 3368 |
-
return res.end();
|
| 3369 |
-
}
|
| 3370 |
-
if (url.pathname === "/public/bootstrap") return handleBootstrap(req, res, url);
|
| 3371 |
if (url.pathname === "/admin/tg-meta" && (req.method === "GET" || req.method === "POST")) return handleTgMeta(req, res, url);
|
| 3372 |
if ((url.pathname === "/t" || url.pathname === "/generate-token") && (req.method === "GET" || req.method === "POST")) return handleGenerate(req, res, url);
|
| 3373 |
const pm = /^\/p\/([0-9a-f]+)(?:\.mp4)?$/i.exec(url.pathname);
|
|
@@ -3408,10 +3325,13 @@ function shutdown(code, reason) {
|
|
| 3408 |
}
|
| 3409 |
|
| 3410 |
async function main() {
|
| 3411 |
-
if (!API_ID || !API_HASH || !STREAM_SECRET) {
|
| 3412 |
process.stderr.write("missing required settings\n");
|
| 3413 |
process.exit(1);
|
| 3414 |
}
|
|
|
|
|
|
|
|
|
|
| 3415 |
try {
|
| 3416 |
await trimDiskCache();
|
| 3417 |
} catch { }
|
|
@@ -3445,13 +3365,14 @@ async function main() {
|
|
| 3445 |
setInterval(sweepMaps, 30000).unref();
|
| 3446 |
const srv = http.createServer({
|
| 3447 |
keepAlive: true,
|
| 3448 |
-
keepAliveTimeout:
|
| 3449 |
keepAliveTimeoutBuffer: 500,
|
| 3450 |
-
headersTimeout:
|
| 3451 |
-
requestTimeout:
|
| 3452 |
connectionsCheckingInterval: 10000
|
| 3453 |
}, onReq);
|
| 3454 |
-
srv.maxConnections =
|
|
|
|
| 3455 |
srv.timeout = 0;
|
| 3456 |
srv.on("clientError", (err, sock) => {
|
| 3457 |
try {
|
|
|
|
| 9 |
const { StringSession } = require("teleproto/sessions");
|
| 10 |
|
| 11 |
const PORT = Number(process.env.PORT || 7860);
|
| 12 |
+
const RAW_ORIGIN = process.env.ALLOWED_ORIGIN || "https://dublk2000.pages.dev";
|
| 13 |
+
let SITE_ORIGIN = "https://dublk2000.pages.dev";
|
| 14 |
+
try {
|
| 15 |
+
const u = new URL(RAW_ORIGIN);
|
| 16 |
+
if (u.protocol === "https:") SITE_ORIGIN = u.origin;
|
| 17 |
+
} catch { }
|
| 18 |
+
const SITE_HOST = new URL(SITE_ORIGIN).hostname.toLowerCase();
|
| 19 |
+
const SITE_HOSTS = new Set([SITE_HOST]);
|
| 20 |
const CHANNEL_ID = process.env.TELEGRAM_CHANNEL_ID || "";
|
| 21 |
const API_ID = Number(process.env.TELEGRAM_API_ID || 0);
|
| 22 |
const API_HASH = process.env.TELEGRAM_API_HASH || "";
|
|
|
|
| 24 |
const ROLE = (process.env.NODE_ROLE || "stream").toLowerCase();
|
| 25 |
const HASH_LEN = 6;
|
| 26 |
const TOKEN_TTL = 14400;
|
|
|
|
| 27 |
const MB = 1024 * 1024;
|
| 28 |
const CPU_N = Math.max(1, (os.cpus() || []).length || 2);
|
| 29 |
function cgroupLimitBytes() {
|
|
|
|
| 46 |
const STREAM_WINDOW = 32 * MB;
|
| 47 |
const PROBE_HEAD = 8 * MB;
|
| 48 |
const BOT_MAX = 100;
|
|
|
|
| 49 |
const PIPE_FIRST_MS = 60000;
|
| 50 |
const PIPE_IDLE_MS = 22000;
|
| 51 |
const PIPE_MAX_MS = 3 * 60 * 60 * 1000;
|
|
|
|
| 91 |
week: { amount: 199, label: "1 Week VIP", sec: 604800, price: "1.99" },
|
| 92 |
month: { amount: 599, label: "1 Month VIP", sec: 2592000, price: "5.99" }
|
| 93 |
};
|
| 94 |
+
const HOME_URL = SITE_ORIGIN + "/";
|
| 95 |
+
const BRAND_URL = SITE_ORIGIN + "/assets/brand-mark.png";
|
| 96 |
|
| 97 |
const deriveKey = STREAM_SECRET
|
| 98 |
? (info) => crypto.hkdfSync("sha256", Buffer.from(STREAM_SECRET, "utf8"), Buffer.from("dublk2000"), Buffer.from(info), 32)
|
|
|
|
| 103 |
const ADMIN_KEY_ENV = String(process.env.ADMIN_API_KEY || "");
|
| 104 |
const ADMIN_KEY = ADMIN_KEY_ENV || adminKey;
|
| 105 |
|
| 106 |
+
function siteHostOf(req) {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
const o = String((req && req.headers && (req.headers.origin || req.headers.referer)) || "");
|
| 108 |
try {
|
| 109 |
if (!o) return "";
|
|
|
|
| 193 |
|
| 194 |
function cors(req, res) {
|
| 195 |
const o = req.headers.origin || "";
|
| 196 |
+
const allow = isSiteOrigin(o);
|
| 197 |
if (allow) res.setHeader("Access-Control-Allow-Origin", o);
|
| 198 |
res.setHeader("Vary", "Origin");
|
| 199 |
res.setHeader("Access-Control-Allow-Methods", "GET,POST,HEAD,OPTIONS");
|
|
|
|
| 206 |
res.setHeader("X-Frame-Options", "DENY");
|
| 207 |
res.setHeader("X-Robots-Tag", "noindex, nofollow, noarchive");
|
| 208 |
res.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=(), usb=(), payment=(), browsing-topics=()");
|
| 209 |
+
res.setHeader("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload");
|
| 210 |
res.setHeader("X-Permitted-Cross-Domain-Policies", "none");
|
| 211 |
res.setHeader("X-XSS-Protection", "0");
|
| 212 |
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
|
|
|
|
| 248 |
"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet, noimageindex",
|
| 249 |
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), usb=(), payment=(), browsing-topics=()",
|
| 250 |
"Cross-Origin-Resource-Policy": "cross-origin",
|
|
|
|
| 251 |
"Access-Control-Expose-Headers": "Content-Range,Content-Length,Accept-Ranges,Content-Type",
|
| 252 |
+
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
|
| 253 |
"X-Permitted-Cross-Domain-Policies": "none",
|
| 254 |
"X-XSS-Protection": "0"
|
| 255 |
};
|
|
|
|
| 326 |
const sec = m ? Number(m[1]) : Number(e && e.seconds || 0);
|
| 327 |
if (sec > 8) bot.coolUntil = Date.now() + Math.min(sec, 90) * 1000;
|
| 328 |
if (/AUTH_KEY|SESSION_REVOKED|USER_DEACTIVATED|PHONE_NUMBER_BANNED/i.test(t)) bot.ready = false;
|
| 329 |
+
if (/AUTH_KEY_UNREGISTERED|SESSION_REVOKED|USER_DEACTIVATED_BAN|PHONE_NUMBER_BANNED|USER_DEACTIVATED/i.test(t)) bot.dead = true;
|
| 330 |
}
|
| 331 |
|
| 332 |
function botUsable(b) {
|
| 333 |
+
if (!b || b.dead || !b.ready) return false;
|
| 334 |
if (b.coolUntil && Date.now() < b.coolUntil) return false;
|
| 335 |
if (b.client && b.client.connected === false) return false;
|
| 336 |
return (b.tgLoad || 0) < BOT_MAX;
|
|
|
|
| 439 |
if (!v || now - v.ts > LVL_TTL * 4) lvlCache.delete(k);
|
| 440 |
}
|
| 441 |
}
|
| 442 |
+
if (lvlCache.size > 20000) {
|
| 443 |
+
const arr = [...lvlCache.entries()].sort((a, b) => (a[1].ts || 0) - (b[1].ts || 0));
|
| 444 |
+
for (let i = 0; i < arr.length - 15000; i++) lvlCache.delete(arr[i][0]);
|
| 445 |
+
}
|
| 446 |
if (durCache.size > 50000) {
|
| 447 |
const ids = [...durCache.keys()].slice(0, durCache.size - 35000);
|
| 448 |
for (const id of ids) durCache.delete(id);
|
|
|
|
| 559 |
return slotOver("badm:" + String(ip || "0"), 60);
|
| 560 |
}
|
| 561 |
|
| 562 |
+
function isSiteOrigin(o) {
|
| 563 |
o = String(o || "").trim();
|
| 564 |
if (!o || o.toLowerCase() === "null") return false;
|
| 565 |
try {
|
| 566 |
const u = new URL(o.includes("://") ? o : "https://" + o);
|
| 567 |
if (u.protocol !== "https:" || u.username || u.password) return false;
|
| 568 |
if (u.port && u.port !== "443") return false;
|
| 569 |
+
return SITE_HOSTS.has(u.hostname.toLowerCase());
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
} catch {
|
| 571 |
return false;
|
| 572 |
}
|
|
|
|
| 580 |
return ".mp4";
|
| 581 |
}
|
| 582 |
|
| 583 |
+
function fromSite(req) {
|
| 584 |
const o = String(req.headers.origin || "").trim();
|
| 585 |
+
if (o && o.toLowerCase() !== "null") return isSiteOrigin(o);
|
| 586 |
const r = String(req.headers.referer || "");
|
| 587 |
if (!r) return false;
|
| 588 |
try {
|
| 589 |
+
return isSiteOrigin(new URL(r).origin);
|
| 590 |
} catch {
|
| 591 |
return false;
|
| 592 |
}
|
| 593 |
}
|
| 594 |
|
| 595 |
function denyHot(req, res) {
|
| 596 |
+
if (fromSite(req)) return false;
|
| 597 |
json(res, 403, { error: "forbidden" });
|
| 598 |
return true;
|
| 599 |
}
|
|
|
|
| 641 |
function payLimited(uid, ip) {
|
| 642 |
const slot = Math.floor(Date.now() / 60000);
|
| 643 |
const a = "pay:" + uid + ":" + slot;
|
| 644 |
+
const b = "payip:" + ipNet(ip) + ":" + slot;
|
| 645 |
const na = (rateMap.get(a) || 0) + 1;
|
| 646 |
const nb = (rateMap.get(b) || 0) + 1;
|
| 647 |
rateMap.set(a, na);
|
|
|
|
| 772 |
return timingSafeEq(mac, m[2]);
|
| 773 |
}
|
| 774 |
|
| 775 |
+
async function stripeSession(id) {
|
| 776 |
+
if (!STRIPE_KEY || !id || !/^cs_[A-Za-z0-9_]+$/.test(String(id))) return null;
|
| 777 |
const r = await fetch("https://api.stripe.com/v1/checkout/sessions/" + encodeURIComponent(id), {
|
| 778 |
headers: { Authorization: "Bearer " + STRIPE_KEY },
|
| 779 |
signal: AbortSignal.timeout(12000)
|
|
|
|
| 842 |
|
| 843 |
function sweepBots() {
|
| 844 |
for (const b of bots) {
|
| 845 |
+
if (b.dead) continue;
|
| 846 |
if (b.client && b.client.connected === false) b.ready = false;
|
| 847 |
else if (b.client && b.client.connected !== false && !b.ready && !(b.coolUntil && Date.now() < b.coolUntil)) b.ready = true;
|
| 848 |
}
|
|
|
|
| 850 |
|
| 851 |
async function startBot(token, idx) {
|
| 852 |
const existing = bots.find((b) => b.idx === idx);
|
| 853 |
+
if (existing && !existing.dead && existing.ready && existing.client && existing.client.connected !== false) {
|
| 854 |
existing.nextTry = 0;
|
| 855 |
existing.fails = 0;
|
| 856 |
return;
|
|
|
|
| 886 |
existing.client = client;
|
| 887 |
existing.token = token;
|
| 888 |
existing.ready = true;
|
| 889 |
+
existing.dead = false;
|
| 890 |
existing.load = 0;
|
| 891 |
existing.tgLoad = 0;
|
| 892 |
existing.coolUntil = 0;
|
|
|
|
| 897 |
}
|
| 898 |
return;
|
| 899 |
}
|
| 900 |
+
bots.push({ client, token, idx, ready: true, dead: false, load: 0, tgLoad: 0, coolUntil: 0, fails: 0, nextTry: 0 });
|
| 901 |
}
|
| 902 |
|
| 903 |
async function reviveBots() {
|
| 904 |
sweepBots();
|
| 905 |
const now = Date.now();
|
| 906 |
for (const slot of botSlots) {
|
| 907 |
+
if (slot.dead) continue;
|
| 908 |
if (now < (slot.nextTry || 0)) continue;
|
| 909 |
const b = bots.find((x) => x.idx === slot.idx);
|
| 910 |
if (b && b.ready && b.client && b.client.connected !== false) {
|
|
|
|
| 917 |
slot.fails = 0;
|
| 918 |
slot.nextTry = 0;
|
| 919 |
} catch (e) {
|
| 920 |
+
if (/AUTH_KEY_UNREGISTERED|SESSION_REVOKED|USER_DEACTIVATED_BAN|PHONE_NUMBER_BANNED|USER_DEACTIVATED/i.test(errText(e))) {
|
| 921 |
+
slot.dead = true;
|
| 922 |
+
process.stderr.write("bot " + slot.idx + " disabled: " + errText(e) + "\n");
|
| 923 |
+
continue;
|
| 924 |
+
}
|
| 925 |
slot.fails = (slot.fails || 0) + 1;
|
| 926 |
const base = Math.min(300000, 15000 * Math.pow(2, Math.min(slot.fails - 1, 4)));
|
| 927 |
slot.nextTry = Date.now() + base + Math.floor(Math.random() * 5000);
|
|
|
|
| 1225 |
return d;
|
| 1226 |
}
|
| 1227 |
|
|
|
|
|
|
|
| 1228 |
const TAIL_MAX = 2 * MB;
|
| 1229 |
const TAIL_MIN_SIZE = 48 * MB;
|
| 1230 |
|
|
|
|
| 1344 |
return null;
|
| 1345 |
}
|
| 1346 |
|
| 1347 |
+
function denyRange(res, size, allowOrigin) {
|
| 1348 |
res.writeHead(416, Object.assign(streamLock(), {
|
| 1349 |
"Content-Range": "bytes */" + size,
|
| 1350 |
"Content-Type": "video/mp4",
|
| 1351 |
"Cache-Control": "private, no-store, no-transform",
|
| 1352 |
+
"Accept-Ranges": "bytes",
|
| 1353 |
+
"Access-Control-Allow-Origin": allowOrigin || SITE_ORIGIN,
|
| 1354 |
+
"Vary": "Origin"
|
| 1355 |
}));
|
| 1356 |
return res.end();
|
| 1357 |
}
|
|
|
|
| 1392 |
return { start, end, partial: start > 0 || end < size - 1 };
|
| 1393 |
}
|
| 1394 |
|
| 1395 |
+
function mediaHeaders(type, msgId, size, hash, rng, allowOrigin) {
|
| 1396 |
const headers = Object.assign(streamLock(), {
|
| 1397 |
"Content-Type": type,
|
| 1398 |
"Accept-Ranges": "bytes",
|
|
|
|
| 1402 |
"X-Accel-Buffering": "no",
|
| 1403 |
"Content-Length": String(rng.end - rng.start + 1),
|
| 1404 |
"Content-Range": "bytes " + rng.start + "-" + rng.end + "/" + size,
|
| 1405 |
+
"Access-Control-Allow-Origin": allowOrigin || SITE_ORIGIN,
|
| 1406 |
+
"Vary": "Origin",
|
| 1407 |
"Connection": "keep-alive"
|
| 1408 |
});
|
| 1409 |
return headers;
|
|
|
|
| 1691 |
return true;
|
| 1692 |
}
|
| 1693 |
|
|
|
|
| 1694 |
const elstLeadSec = new Map();
|
| 1695 |
|
| 1696 |
function geckoUA(ua) {
|
|
|
|
| 1761 |
const first = elstLeadSec.keys().next().value;
|
| 1762 |
elstLeadSec.delete(first);
|
| 1763 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1764 |
}
|
| 1765 |
}
|
| 1766 |
|
|
|
|
| 2140 |
try {
|
| 2141 |
const raw = JSON.parse((await readBody(req, 4096)).toString("utf8") || "{}");
|
| 2142 |
if (raw && raw.enc) {
|
| 2143 |
+
const reqHost = siteHostOf(req);
|
| 2144 |
+
const dom = SITE_HOSTS.has(reqHost) ? reqHost : SITE_HOST;
|
|
|
|
|
|
|
| 2145 |
const decReq = (enc, d) => {
|
| 2146 |
try {
|
| 2147 |
const key = Buffer.from(d, "utf8");
|
|
|
|
| 2156 |
return JSON.parse(out.join(""));
|
| 2157 |
} catch { return null; }
|
| 2158 |
};
|
| 2159 |
+
const parsed = decReq(raw.enc, dom) || decReq(raw.enc, SITE_HOST);
|
| 2160 |
if (parsed) {
|
| 2161 |
if (parsed.p) path = String(parsed.p);
|
| 2162 |
if (parsed.h) hash = String(parsed.h).toLowerCase();
|
|
|
|
| 2294 |
return res.end();
|
| 2295 |
}
|
| 2296 |
const oH = req.headers.origin || "";
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2297 |
const rH = req.headers.referer || "";
|
| 2298 |
+
const originOk = oH ? isSiteOrigin(oH) : false;
|
| 2299 |
+
let refererOk = true;
|
| 2300 |
if (rH) {
|
| 2301 |
+
try { refererOk = isSiteOrigin(new URL(rH).origin); } catch { refererOk = false; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2302 |
}
|
| 2303 |
+
if ((oH && !originOk) || (rH && !refererOk) || (!oH && !rH)) {
|
|
|
|
| 2304 |
res.writeHead(403);
|
| 2305 |
return res.end();
|
| 2306 |
}
|
| 2307 |
+
const allowOrigin = originOk ? oH : SITE_ORIGIN;
|
| 2308 |
const k = kHex || url.searchParams.get("k") || "";
|
| 2309 |
const ticket = ticketObj || openTicket(k);
|
| 2310 |
if (!ticket || ticket.m !== msgId || !/^[0-9a-f]{6}$/.test(String(ticket.h || ""))) {
|
|
|
|
| 2322 |
}
|
| 2323 |
const vipUntil = Number(ticket.x) || 0;
|
| 2324 |
if (ticketLvl(ticket) === "subscribed" && vipUntil > 0 && vipUntil <= Math.floor(Date.now() / 1000)) ticket.l = "registered";
|
|
|
|
| 2325 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2326 |
let held = false;
|
| 2327 |
try {
|
| 2328 |
if (!takeStream(ip, ticket.u, msgId)) {
|
|
|
|
| 2342 |
if (sizeHint > 0) {
|
| 2343 |
const rngHot0 = parseRange(req.headers.range, sizeHint, msgId);
|
| 2344 |
const rngHot = applyPreview(rngHot0, sizeHint, lvl, msgId, ticket);
|
| 2345 |
+
if (!rngHot) return denyRange(res, sizeHint, allowOrigin);
|
| 2346 |
const needHot = rngHot.end - rngHot.start + 1;
|
| 2347 |
+
const headersHot = mediaHeaders(typeHint, msgId, sizeHint, ticket.h, rngHot, allowOrigin);
|
| 2348 |
if (req.method === "HEAD") {
|
| 2349 |
res.writeHead(206, headersHot);
|
| 2350 |
return res.end();
|
|
|
|
| 2362 |
if (hit && hit.length > 0 && rngHot.start === 0 && (!req.headers.range || req.headers.range === "bytes=0-")) {
|
| 2363 |
const serveLen = Math.min(hit.length, needHot);
|
| 2364 |
const fastRng = { start: 0, end: serveLen - 1, partial: true };
|
| 2365 |
+
const fastHeaders = mediaHeaders(typeHint, msgId, sizeHint, ticket.h, fastRng, allowOrigin);
|
| 2366 |
if (res.socket) {
|
| 2367 |
try { res.socket.setNoDelay(true); } catch { }
|
| 2368 |
}
|
|
|
|
| 2426 |
}
|
| 2427 |
const rng0 = parseRange(req.headers.range, size, msgId);
|
| 2428 |
const rng = applyPreview(rng0, size, lvl, msgId, ticket);
|
| 2429 |
+
if (!rng) return denyRange(res, size, allowOrigin);
|
| 2430 |
+
const headers = mediaHeaders(typeHint, msgId, size, rec.hash, rng, allowOrigin);
|
| 2431 |
if (req.method === "HEAD") {
|
| 2432 |
res.writeHead(206, headers);
|
| 2433 |
return res.end();
|
|
|
|
| 2483 |
json(res, 200, { accessLevel: lvl });
|
| 2484 |
}
|
| 2485 |
|
| 2486 |
+
function siteReturn(u) {
|
| 2487 |
try {
|
| 2488 |
+
const p = new URL(String(u || ""), SITE_ORIGIN);
|
| 2489 |
+
if (p.protocol !== "https:" || p.username || p.password) return SITE_ORIGIN + "/";
|
| 2490 |
+
if (p.port && p.port !== "443") return SITE_ORIGIN + "/";
|
| 2491 |
+
if (!SITE_HOSTS.has(p.hostname.toLowerCase())) return SITE_ORIGIN + "/";
|
| 2492 |
const mobile = p.searchParams.get("m") === "1" ? "?m=1" : "";
|
| 2493 |
return p.origin + p.pathname + mobile;
|
| 2494 |
} catch {
|
| 2495 |
+
return SITE_ORIGIN + "/";
|
| 2496 |
}
|
| 2497 |
}
|
| 2498 |
|
| 2499 |
function payUrls(ret) {
|
| 2500 |
+
const base = siteReturn(ret);
|
| 2501 |
const join = base.indexOf("?") >= 0 ? "&" : "?";
|
| 2502 |
return {
|
| 2503 |
success: base + join + "vip=success&sid={CHECKOUT_SESSION_ID}",
|
|
|
|
| 2511 |
let paypalLive = false;
|
| 2512 |
let payTypes = ["card"];
|
| 2513 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2514 |
function payPref(node) {
|
| 2515 |
const d = node && node.display_preference;
|
| 2516 |
if (!d) return "";
|
|
|
|
| 2641 |
if (!verifyProof(body.proof, clientIp(req))) {
|
| 2642 |
return json(res, 400, { error: "captcha" });
|
| 2643 |
}
|
|
|
|
| 2644 |
const auto = planKey === "month" && body.auto === true;
|
| 2645 |
const urls = payUrls(body.returnUrl);
|
| 2646 |
const wallets = await ensureFreeWallets();
|
|
|
|
| 2719 |
].forEach((k) => { delete slim[k]; });
|
| 2720 |
({ r, d } = await createSes(slim, idem + "s"));
|
| 2721 |
if (!r.ok) {
|
| 2722 |
+
process.stderr.write("stripe create failed: " + (firstErr || "unknown") + " | slim: " + ((d && d.error && d.error.message) || "unknown") + "\n");
|
| 2723 |
}
|
| 2724 |
}
|
| 2725 |
if (!r.ok || !d.id || !d.url || d.object !== "checkout.session") return json(res, 400, { error: "Payment failed" });
|
|
|
|
| 3048 |
}
|
| 3049 |
|
| 3050 |
async function handleStripeWebhook(req, res) {
|
| 3051 |
+
let rawBuf;
|
| 3052 |
+
try { rawBuf = await readBody(req); } catch {
|
| 3053 |
+
res.writeHead(413);
|
| 3054 |
+
return res.end();
|
| 3055 |
+
}
|
| 3056 |
if (!stripeOk(rawBuf, req.headers["stripe-signature"])) {
|
| 3057 |
res.writeHead(400);
|
| 3058 |
return res.end();
|
|
|
|
| 3102 |
json(res, 200, { ok: true });
|
| 3103 |
}
|
| 3104 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3105 |
function handleHealth(req, res) {
|
| 3106 |
+
if (req && adminKeyOk(req)) {
|
| 3107 |
const mem = process.memoryUsage();
|
| 3108 |
json(res, 200, {
|
| 3109 |
ok: true,
|
|
|
|
| 3134 |
return String(id || "").replace(/^-100/, "").replace(/^-/, "");
|
| 3135 |
}
|
| 3136 |
|
| 3137 |
+
function adminKeyOk(req) {
|
| 3138 |
if (!ADMIN_KEY) return false;
|
| 3139 |
const h = String(req.headers.authorization || "").replace(/^Bearer\s+/i, "").trim();
|
| 3140 |
const x = String(req.headers["x-admin-key"] || "").trim();
|
| 3141 |
const got = h || x;
|
| 3142 |
+
if (!got) return false;
|
| 3143 |
+
const a = crypto.createHash("sha256").update(got).digest();
|
| 3144 |
+
const b = crypto.createHash("sha256").update(ADMIN_KEY).digest();
|
| 3145 |
+
return crypto.timingSafeEqual(a, b);
|
| 3146 |
}
|
| 3147 |
|
| 3148 |
function parseTgPosts(text) {
|
|
|
|
| 3170 |
return out.slice(0, 40);
|
| 3171 |
}
|
| 3172 |
|
| 3173 |
+
function applyAdminCors(req, res) {
|
| 3174 |
+
const o = String(req.headers.origin || "");
|
| 3175 |
+
if (o && isSiteOrigin(o)) {
|
| 3176 |
+
res.setHeader("Access-Control-Allow-Origin", o);
|
| 3177 |
+
res.setHeader("Vary", "Origin");
|
| 3178 |
+
}
|
| 3179 |
res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
|
| 3180 |
res.setHeader("Access-Control-Allow-Headers", "Authorization,Content-Type,X-Admin-Key");
|
| 3181 |
res.setHeader("Access-Control-Max-Age", "86400");
|
| 3182 |
}
|
| 3183 |
|
| 3184 |
async function handleTgMeta(req, res, url) {
|
| 3185 |
+
applyAdminCors(req, res);
|
| 3186 |
+
if (!adminKeyOk(req)) return json(res, 401, { error: "auth" });
|
| 3187 |
const ip = clientIp(req);
|
| 3188 |
if (limited(ip)) {
|
| 3189 |
res.setHeader("Retry-After", "2");
|
|
|
|
| 3277 |
return res.end();
|
| 3278 |
}
|
| 3279 |
cors(req, res);
|
| 3280 |
+
if (url.pathname === "/admin/tg-meta") applyAdminCors(req, res);
|
| 3281 |
if (req.method === "OPTIONS") {
|
| 3282 |
res.writeHead(204, { "Content-Length": "0" });
|
| 3283 |
return res.end();
|
|
|
|
| 3285 |
try {
|
| 3286 |
if (url.pathname === "/") return handleHome(req, res);
|
| 3287 |
if (url.pathname === "/health") return handleHealth(req, res);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3288 |
if (url.pathname === "/admin/tg-meta" && (req.method === "GET" || req.method === "POST")) return handleTgMeta(req, res, url);
|
| 3289 |
if ((url.pathname === "/t" || url.pathname === "/generate-token") && (req.method === "GET" || req.method === "POST")) return handleGenerate(req, res, url);
|
| 3290 |
const pm = /^\/p\/([0-9a-f]+)(?:\.mp4)?$/i.exec(url.pathname);
|
|
|
|
| 3325 |
}
|
| 3326 |
|
| 3327 |
async function main() {
|
| 3328 |
+
if (!API_ID || !API_HASH || !STREAM_SECRET || !CHANNEL_ID) {
|
| 3329 |
process.stderr.write("missing required settings\n");
|
| 3330 |
process.exit(1);
|
| 3331 |
}
|
| 3332 |
+
if (!FB_PROJECT || !FB_DB || !FB_SECRET) process.stderr.write("warning: firebase settings incomplete\n");
|
| 3333 |
+
if (ROLE === "indexer" && !STRIPE_KEY) process.stderr.write("warning: stripe not configured\n");
|
| 3334 |
+
if (!RC_SIGN) process.stderr.write("warning: RC_SIGN_KEY not set; checkout proof disabled\n");
|
| 3335 |
try {
|
| 3336 |
await trimDiskCache();
|
| 3337 |
} catch { }
|
|
|
|
| 3365 |
setInterval(sweepMaps, 30000).unref();
|
| 3366 |
const srv = http.createServer({
|
| 3367 |
keepAlive: true,
|
| 3368 |
+
keepAliveTimeout: 65000,
|
| 3369 |
keepAliveTimeoutBuffer: 500,
|
| 3370 |
+
headersTimeout: 20000,
|
| 3371 |
+
requestTimeout: 30000,
|
| 3372 |
connectionsCheckingInterval: 10000
|
| 3373 |
}, onReq);
|
| 3374 |
+
srv.maxConnections = 20000;
|
| 3375 |
+
srv.maxHeadersCount = 100;
|
| 3376 |
srv.timeout = 0;
|
| 3377 |
srv.on("clientError", (err, sock) => {
|
| 3378 |
try {
|