Spaces:
Running
Running
Harden stream server and speed up video delivery
Browse files
server.js
CHANGED
|
@@ -22,6 +22,8 @@ const API_ID = Number(process.env.TELEGRAM_API_ID || 0);
|
|
| 22 |
const API_HASH = process.env.TELEGRAM_API_HASH || "";
|
| 23 |
const STREAM_SECRET = process.env.STREAM_SECRET || "";
|
| 24 |
const ROLE = (process.env.NODE_ROLE || "stream").toLowerCase();
|
|
|
|
|
|
|
| 25 |
const HASH_LEN = 6;
|
| 26 |
const TOKEN_TTL = 14400;
|
| 27 |
const MB = 1024 * 1024;
|
|
@@ -74,11 +76,11 @@ const STRIPE_KEY = process.env.STRIPE_SECRET_KEY || "";
|
|
| 74 |
const STRIPE_WH = process.env.STRIPE_WEBHOOK_SECRET || "";
|
| 75 |
const RC_SIGN = process.env.RC_SIGN_KEY || "";
|
| 76 |
const SPACE_FALLBACK = [
|
| 77 |
-
"https://dublk2000-
|
| 78 |
-
"https://dublk2000-
|
| 79 |
-
"https://
|
| 80 |
-
"https://
|
| 81 |
-
"https://
|
| 82 |
];
|
| 83 |
const SPACE_URLS = String(process.env.SPACE_URLS || "")
|
| 84 |
.split(",")
|
|
@@ -761,6 +763,28 @@ function uidOk(uid) {
|
|
| 761 |
return typeof uid === "string" && /^[A-Za-z0-9_-]{8,128}$/.test(uid);
|
| 762 |
}
|
| 763 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 764 |
function verifyProof(proof, ip) {
|
| 765 |
if (!RC_SIGN) return true;
|
| 766 |
const m = /^(\d{10})\.([0-9a-f]{64})$/.exec(String(proof || ""));
|
|
@@ -1226,6 +1250,7 @@ async function fillDuration(bot, rec, msgId) {
|
|
| 1226 |
}
|
| 1227 |
|
| 1228 |
const TAIL_MAX = 256 * MB;
|
|
|
|
| 1229 |
const TAIL_MIN_SIZE = 48 * MB;
|
| 1230 |
|
| 1231 |
function lvlPct(l) {
|
|
@@ -1254,8 +1279,7 @@ function previewMaxEnd(size, l, msgId, dur) {
|
|
| 1254 |
if (tCut > base) base = tCut;
|
| 1255 |
}
|
| 1256 |
}
|
| 1257 |
-
|
| 1258 |
-
const head = Math.min(48 * MB, Math.max(4 * MB, Math.floor(size * 0.06)));
|
| 1259 |
return Math.max(0, Math.min(size - 1, base + head - 1));
|
| 1260 |
}
|
| 1261 |
|
|
@@ -1324,7 +1348,7 @@ function applyPreview(rng, size, l, msgId, ticket) {
|
|
| 1324 |
const dur = td > 1 ? td : (durCache.get(String(msgId || "")) || 0);
|
| 1325 |
const maxEnd = previewMaxEnd(size, l, msgId, dur);
|
| 1326 |
const tailAllowed = size >= TAIL_MIN_SIZE;
|
| 1327 |
-
const tailWin = tailAllowed ? Math.max(0, size - Math.min(TAIL_MAX,
|
| 1328 |
if (tailAllowed && rng.start >= tailWin) {
|
| 1329 |
return { start: rng.start, end: endCap, partial: true };
|
| 1330 |
}
|
|
@@ -2467,6 +2491,11 @@ async function handleStream(req, res, url, msgId, kHex, ticketObj) {
|
|
| 2467 |
async function handleVipStatus(req, res) {
|
| 2468 |
if (!destOk(req, ["empty"])) return json(res, 403, { error: "forbidden" });
|
| 2469 |
if (denyHot(req, res)) return;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2470 |
let lvl = "anonymous";
|
| 2471 |
try {
|
| 2472 |
const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
|
|
@@ -2481,6 +2510,48 @@ async function handleVipStatus(req, res) {
|
|
| 2481 |
json(res, 200, { accessLevel: lvl });
|
| 2482 |
}
|
| 2483 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2484 |
function siteReturn(u) {
|
| 2485 |
try {
|
| 2486 |
const p = new URL(String(u || ""), SITE_ORIGIN);
|
|
@@ -2604,6 +2675,48 @@ async function withPayLock(id, fn) {
|
|
| 2604 |
}
|
| 2605 |
}
|
| 2606 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2607 |
async function openPay(uid, planKey, email, auto) {
|
| 2608 |
let rec = null;
|
| 2609 |
try { rec = await rtdb("pay_open/" + uid, "GET"); } catch { rec = null; }
|
|
@@ -2635,6 +2748,7 @@ async function handleVipStart(req, res) {
|
|
| 2635 |
const planKey = String(body.plan || "").trim().toLowerCase();
|
| 2636 |
const plan = PLANS[planKey];
|
| 2637 |
const email = payEmail(idp);
|
|
|
|
| 2638 |
if (!plan || !email) return json(res, 400, { error: "plan" });
|
| 2639 |
if (!verifyProof(body.proof, clientIp(req))) {
|
| 2640 |
return json(res, 400, { error: "captcha" });
|
|
@@ -2643,7 +2757,10 @@ async function handleVipStart(req, res) {
|
|
| 2643 |
const urls = payUrls(body.returnUrl);
|
| 2644 |
const wallets = await ensureFreeWallets();
|
| 2645 |
const reused = await openPay(idp.sub, planKey, email, auto);
|
| 2646 |
-
if (reused)
|
|
|
|
|
|
|
|
|
|
| 2647 |
const nonce = crypto.randomBytes(8).toString("hex");
|
| 2648 |
const idem = "vip" + crypto.createHash("sha256").update(idp.sub + ":" + planKey + ":" + nonce).digest("hex").slice(0, 22);
|
| 2649 |
const homeMsg = "After pay you return to [DUB LK 2000 Home](" + HOME_URL + ")";
|
|
@@ -2677,6 +2794,7 @@ async function handleVipStart(req, res) {
|
|
| 2677 |
"payment_intent_data[receipt_email]": email
|
| 2678 |
};
|
| 2679 |
fields.customer_email = email;
|
|
|
|
| 2680 |
if (auto) {
|
| 2681 |
fields.mode = "subscription";
|
| 2682 |
fields["line_items[0][price_data][recurring][interval]"] = "month";
|
|
@@ -2684,6 +2802,7 @@ async function handleVipStart(req, res) {
|
|
| 2684 |
fields["subscription_data[metadata][uid]"] = idp.sub;
|
| 2685 |
fields["subscription_data[metadata][plan]"] = planKey;
|
| 2686 |
fields["subscription_data[metadata][email]"] = email;
|
|
|
|
| 2687 |
delete fields["payment_intent_data[description]"];
|
| 2688 |
delete fields["payment_intent_data[metadata][uid]"];
|
| 2689 |
delete fields["payment_intent_data[metadata][plan]"];
|
|
@@ -2703,27 +2822,39 @@ async function handleVipStart(req, res) {
|
|
| 2703 |
});
|
| 2704 |
return { r, d: await r.json() };
|
| 2705 |
}
|
| 2706 |
-
let
|
| 2707 |
-
|
| 2708 |
-
|
| 2709 |
-
|
| 2710 |
-
|
| 2711 |
-
|
| 2712 |
-
"branding_settings[logo][type]",
|
| 2713 |
-
"branding_settings[logo][url]",
|
| 2714 |
-
"branding_settings[button_color]",
|
| 2715 |
-
"branding_settings[background_color]",
|
| 2716 |
-
"line_items[0][price_data][product_data][images][0]"
|
| 2717 |
-
].forEach((k) => { delete slim[k]; });
|
| 2718 |
-
({ r, d } = await createSes(slim, idem + "s"));
|
| 2719 |
if (!r.ok) {
|
| 2720 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2721 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2722 |
}
|
| 2723 |
-
if (!r.ok || !d.id || !d.url || d.object !== "checkout.session") return json(res, 400, { error: "Payment failed" });
|
| 2724 |
try {
|
| 2725 |
await rtdb("pay_open/" + idp.sub, "PUT", { sid: d.id, plan: planKey, email: email, auto: auto ? 1 : 0, t: Math.floor(Date.now() / 1000) });
|
| 2726 |
} catch { }
|
|
|
|
| 2727 |
json(res, 200, { sid: d.id, url: d.url });
|
| 2728 |
}
|
| 2729 |
|
|
@@ -2763,24 +2894,37 @@ async function handleVipConfirm(req, res) {
|
|
| 2763 |
} catch {
|
| 2764 |
return json(res, 400, { error: "body" });
|
| 2765 |
}
|
|
|
|
| 2766 |
const d = await stripeSession(body.sid);
|
| 2767 |
const meta = d && d.metadata || {};
|
| 2768 |
const email = payEmail(idp);
|
| 2769 |
const sem = String(meta.email || "");
|
|
|
|
|
|
|
|
|
|
| 2770 |
if (!d || meta.uid !== idp.sub || d.client_reference_id !== idp.sub) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2771 |
return json(res, 400, { error: "Payment failed", paid: false });
|
| 2772 |
}
|
| 2773 |
-
if (
|
| 2774 |
-
|
|
|
|
|
|
|
| 2775 |
let granted = false;
|
| 2776 |
try { granted = await fulfillPaid(d); } catch { granted = false; }
|
| 2777 |
lvlCache.delete(idp.sub);
|
| 2778 |
let sub = null;
|
| 2779 |
try { sub = await rtdb("users/" + idp.sub + "/subscription", "GET"); } catch { }
|
| 2780 |
if (!granted || !vipActive(sub)) {
|
|
|
|
| 2781 |
if (d.payment_status === "paid" && d.status === "complete") return json(res, 402, { error: "order", paid: false });
|
| 2782 |
return json(res, 402, { error: "unpaid", paid: false });
|
| 2783 |
}
|
|
|
|
| 2784 |
json(res, 200, { ok: true, paid: true, accessLevel: "subscribed", subscription: publicSub(sub) });
|
| 2785 |
}
|
| 2786 |
|
|
@@ -2805,6 +2949,8 @@ async function grantVip(uid, planKey, absExp, extra) {
|
|
| 2805 |
const stripeSub = extra && extra.stripeSub ? String(extra.stripeSub) : (old && old.stripeSub ? String(old.stripeSub) : "");
|
| 2806 |
if (/^sub_[A-Za-z0-9_]+$/.test(stripeSub)) sub.stripeSub = stripeSub;
|
| 2807 |
await rtdb("users/" + uid + "/subscription", "PUT", sub);
|
|
|
|
|
|
|
| 2808 |
lvlCache.delete(uid);
|
| 2809 |
return sub;
|
| 2810 |
}
|
|
@@ -2916,7 +3062,7 @@ async function fulfillPaid(ses) {
|
|
| 2916 |
paidOrders.set(sid, Date.now());
|
| 2917 |
const autoOn = ses.metadata && ses.metadata.auto === "1";
|
| 2918 |
const stripeSub = typeof ses.subscription === "string" ? ses.subscription : "";
|
| 2919 |
-
const extra = {};
|
| 2920 |
if (autoOn) extra.autoRenew = true;
|
| 2921 |
if (stripeSub) extra.stripeSub = stripeSub;
|
| 2922 |
await grantVip(uid, planKey, c.exp, extra);
|
|
@@ -2973,8 +3119,9 @@ async function fulfillInvoice(inv) {
|
|
| 2973 |
return withPayLock(invId, async () => {
|
| 2974 |
const c = await claimOrder(invId, uid, planKey, plan.sec);
|
| 2975 |
if (c.state === "conflict" || c.state === "unknown" || !(c.exp > Math.floor(Date.now() / 1000))) return false;
|
| 2976 |
-
await grantVip(uid, planKey, c.exp, { autoRenew: true, stripeSub: subId });
|
| 2977 |
await markOrder(invId, uid, planKey, c.exp);
|
|
|
|
| 2978 |
return true;
|
| 2979 |
});
|
| 2980 |
}
|
|
@@ -3070,7 +3217,12 @@ async function handleStripeWebhook(req, res) {
|
|
| 3070 |
const id = ev.data && ev.data.object && ev.data.object.id;
|
| 3071 |
try {
|
| 3072 |
const ses = await stripeSession(id);
|
| 3073 |
-
if (ses)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3074 |
} catch { did = false; }
|
| 3075 |
} else if (ev.type === "checkout.session.expired") {
|
| 3076 |
const id = ev.data && ev.data.object && ev.data.object.id;
|
|
@@ -3082,6 +3234,9 @@ async function handleStripeWebhook(req, res) {
|
|
| 3082 |
const open = await rtdb("pay_open/" + uid, "GET");
|
| 3083 |
if (open && open.sid === id) await rtdb("pay_open/" + uid, "DELETE");
|
| 3084 |
}
|
|
|
|
|
|
|
|
|
|
| 3085 |
} catch { }
|
| 3086 |
}
|
| 3087 |
did = true;
|
|
@@ -3183,8 +3338,8 @@ async function handleTgMeta(req, res, url) {
|
|
| 3183 |
applyAdminCors(req, res);
|
| 3184 |
if (!adminKeyOk(req)) return json(res, 401, { error: "auth" });
|
| 3185 |
const ip = clientIp(req);
|
| 3186 |
-
if (
|
| 3187 |
-
res.setHeader("Retry-After", "
|
| 3188 |
return json(res, 429, { error: "rate_limited" });
|
| 3189 |
}
|
| 3190 |
let text = String(url.searchParams.get("ids") || url.searchParams.get("text") || "");
|
|
@@ -3293,6 +3448,7 @@ async function onReq(req, res) {
|
|
| 3293 |
const pm = /^\/p\/([0-9a-f]+)(?:\.mp4)?$/i.exec(url.pathname);
|
| 3294 |
if (pm && (req.method === "GET" || req.method === "HEAD")) return handlePlay(req, res, url, pm[1]);
|
| 3295 |
if (url.pathname === "/vip/status" && req.method === "GET") return handleVipStatus(req, res);
|
|
|
|
| 3296 |
if (url.pathname === "/vip/start" && req.method === "POST") return handleVipStart(req, res);
|
| 3297 |
if (url.pathname === "/vip/go" && req.method === "POST") return handleVipGo(req, res);
|
| 3298 |
if (url.pathname === "/vip/confirm" && req.method === "POST") return handleVipConfirm(req, res);
|
|
@@ -3389,7 +3545,9 @@ async function main() {
|
|
| 3389 |
});
|
| 3390 |
srv.listen(PORT, "0.0.0.0", () => {
|
| 3391 |
if (ROLE === "indexer" && STRIPE_KEY) ensureFreeWallets().catch(() => { });
|
| 3392 |
-
if (
|
|
|
|
|
|
|
| 3393 |
});
|
| 3394 |
}
|
| 3395 |
|
|
|
|
| 22 |
const API_HASH = process.env.TELEGRAM_API_HASH || "";
|
| 23 |
const STREAM_SECRET = process.env.STREAM_SECRET || "";
|
| 24 |
const ROLE = (process.env.NODE_ROLE || "stream").toLowerCase();
|
| 25 |
+
const OWNER_UID = String(process.env.OWNER_UID || "").trim();
|
| 26 |
+
const OWNER_VIP_UNTIL = Number(process.env.OWNER_VIP_UNTIL || 0);
|
| 27 |
const HASH_LEN = 6;
|
| 28 |
const TOKEN_TTL = 14400;
|
| 29 |
const MB = 1024 * 1024;
|
|
|
|
| 76 |
const STRIPE_WH = process.env.STRIPE_WEBHOOK_SECRET || "";
|
| 77 |
const RC_SIGN = process.env.RC_SIGN_KEY || "";
|
| 78 |
const SPACE_FALLBACK = [
|
| 79 |
+
"https://dublk2000-s1.hf.space",
|
| 80 |
+
"https://dublk2000-s2.hf.space",
|
| 81 |
+
"https://server2-s3.hf.space",
|
| 82 |
+
"https://server2-s4.hf.space",
|
| 83 |
+
"https://server2-s5.hf.space"
|
| 84 |
];
|
| 85 |
const SPACE_URLS = String(process.env.SPACE_URLS || "")
|
| 86 |
.split(",")
|
|
|
|
| 763 |
return typeof uid === "string" && /^[A-Za-z0-9_-]{8,128}$/.test(uid);
|
| 764 |
}
|
| 765 |
|
| 766 |
+
function cleanVid(v) {
|
| 767 |
+
const s = String(v || "").trim();
|
| 768 |
+
return /^[A-Za-z0-9_-]{8,64}$/.test(s) ? s : "";
|
| 769 |
+
}
|
| 770 |
+
|
| 771 |
+
function payErrorText(e) {
|
| 772 |
+
return String(e || "").replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 120);
|
| 773 |
+
}
|
| 774 |
+
|
| 775 |
+
const PAY_STAGES = {
|
| 776 |
+
plan_click: 1,
|
| 777 |
+
checkout_started: 2,
|
| 778 |
+
checkout_redirect: 3,
|
| 779 |
+
return_success: 3,
|
| 780 |
+
cancelled: 4,
|
| 781 |
+
start_failed: 4,
|
| 782 |
+
confirm_failed: 4,
|
| 783 |
+
expired: 4,
|
| 784 |
+
failed: 4,
|
| 785 |
+
paid: 5
|
| 786 |
+
};
|
| 787 |
+
|
| 788 |
function verifyProof(proof, ip) {
|
| 789 |
if (!RC_SIGN) return true;
|
| 790 |
const m = /^(\d{10})\.([0-9a-f]{64})$/.exec(String(proof || ""));
|
|
|
|
| 1250 |
}
|
| 1251 |
|
| 1252 |
const TAIL_MAX = 256 * MB;
|
| 1253 |
+
const TAIL_META = 1 * MB;
|
| 1254 |
const TAIL_MIN_SIZE = 48 * MB;
|
| 1255 |
|
| 1256 |
function lvlPct(l) {
|
|
|
|
| 1279 |
if (tCut > base) base = tCut;
|
| 1280 |
}
|
| 1281 |
}
|
| 1282 |
+
const head = Math.min(2 * MB, Math.max(512 * 1024, Math.floor(size * 0.002)));
|
|
|
|
| 1283 |
return Math.max(0, Math.min(size - 1, base + head - 1));
|
| 1284 |
}
|
| 1285 |
|
|
|
|
| 1348 |
const dur = td > 1 ? td : (durCache.get(String(msgId || "")) || 0);
|
| 1349 |
const maxEnd = previewMaxEnd(size, l, msgId, dur);
|
| 1350 |
const tailAllowed = size >= TAIL_MIN_SIZE;
|
| 1351 |
+
const tailWin = tailAllowed ? Math.max(0, size - Math.min(TAIL_MAX, TAIL_META)) : Infinity;
|
| 1352 |
if (tailAllowed && rng.start >= tailWin) {
|
| 1353 |
return { start: rng.start, end: endCap, partial: true };
|
| 1354 |
}
|
|
|
|
| 2491 |
async function handleVipStatus(req, res) {
|
| 2492 |
if (!destOk(req, ["empty"])) return json(res, 403, { error: "forbidden" });
|
| 2493 |
if (denyHot(req, res)) return;
|
| 2494 |
+
const ip = clientIp(req);
|
| 2495 |
+
if (slotOver("vipstatus:" + ip, 120)) {
|
| 2496 |
+
res.setHeader("Retry-After", "30");
|
| 2497 |
+
return json(res, 429, { error: "rate_limited" });
|
| 2498 |
+
}
|
| 2499 |
let lvl = "anonymous";
|
| 2500 |
try {
|
| 2501 |
const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
|
|
|
|
| 2510 |
json(res, 200, { accessLevel: lvl });
|
| 2511 |
}
|
| 2512 |
|
| 2513 |
+
async function handleVipTrack(req, res) {
|
| 2514 |
+
if (ROLE !== "indexer") return json(res, 409, { error: "use_s1" });
|
| 2515 |
+
if (!destOk(req, ["empty"])) return json(res, 403, { error: "forbidden" });
|
| 2516 |
+
if (denyHot(req, res)) return;
|
| 2517 |
+
const ip = clientIp(req);
|
| 2518 |
+
if (slotOver("track:" + ip, 60)) {
|
| 2519 |
+
res.setHeader("Retry-After", "30");
|
| 2520 |
+
return json(res, 429, { error: "rate_limited" });
|
| 2521 |
+
}
|
| 2522 |
+
const ctype = String(req.headers["content-type"] || "");
|
| 2523 |
+
if (!/^application\/json(?:\s*;|$)/i.test(ctype)) return json(res, 415, { error: "type" });
|
| 2524 |
+
let body;
|
| 2525 |
+
try {
|
| 2526 |
+
body = JSON.parse((await readBody(req, 4096)).toString("utf8") || "{}");
|
| 2527 |
+
} catch {
|
| 2528 |
+
return json(res, 400, { error: "body" });
|
| 2529 |
+
}
|
| 2530 |
+
const vid = cleanVid(body.vid);
|
| 2531 |
+
const stage = String(body.stage || "").toLowerCase();
|
| 2532 |
+
const allowed = ["plan_click", "checkout_redirect", "return_success", "cancelled", "start_failed", "confirm_failed"];
|
| 2533 |
+
if (!vid || allowed.indexOf(stage) < 0) return json(res, 400, { error: "bad" });
|
| 2534 |
+
let uid = "";
|
| 2535 |
+
let email = "";
|
| 2536 |
+
const rawAuth = String(req.headers.authorization || "").trim();
|
| 2537 |
+
if (rawAuth) {
|
| 2538 |
+
try {
|
| 2539 |
+
const idp = await withTime(verifyIdToken(rawAuth), 3000, null);
|
| 2540 |
+
const g = googleUid(idp);
|
| 2541 |
+
if (g) {
|
| 2542 |
+
uid = g;
|
| 2543 |
+
email = payEmail(idp);
|
| 2544 |
+
}
|
| 2545 |
+
} catch { }
|
| 2546 |
+
}
|
| 2547 |
+
const plan = /^(day|week|month)$/.test(String(body.plan || "")) ? String(body.plan) : "";
|
| 2548 |
+
const sid = /^(cs|in|sub)_[A-Za-z0-9_]+$/.test(String(body.sid || "")) ? String(body.sid) : "";
|
| 2549 |
+
const page = String(body.page || "");
|
| 2550 |
+
const error = body.error ? payErrorText(body.error) : "";
|
| 2551 |
+
await trackPay(vid, { stage: stage, uid: uid, email: email, plan: plan, sid: sid, page: page, error: error, source: "client" }).catch(() => { });
|
| 2552 |
+
json(res, 200, { ok: true });
|
| 2553 |
+
}
|
| 2554 |
+
|
| 2555 |
function siteReturn(u) {
|
| 2556 |
try {
|
| 2557 |
const p = new URL(String(u || ""), SITE_ORIGIN);
|
|
|
|
| 2675 |
}
|
| 2676 |
}
|
| 2677 |
|
| 2678 |
+
async function trackPay(vid, info) {
|
| 2679 |
+
const key = cleanVid(vid) || (info && uidOk(info.uid) ? String(info.uid) : "");
|
| 2680 |
+
if (!key) return;
|
| 2681 |
+
const stage = String(info && info.stage || "").toLowerCase();
|
| 2682 |
+
if (!Object.prototype.hasOwnProperty.call(PAY_STAGES, stage)) return;
|
| 2683 |
+
const now = Math.floor(Date.now() / 1000);
|
| 2684 |
+
await withPayLock("funnel:" + key, async () => {
|
| 2685 |
+
let cur = null;
|
| 2686 |
+
try { cur = await rtdb("pay_funnel/" + key, "GET"); } catch { cur = null; }
|
| 2687 |
+
const old = cur && typeof cur === "object" && !Array.isArray(cur) ? cur : {};
|
| 2688 |
+
const history = Object.assign({}, old.history && typeof old.history === "object" ? old.history : {});
|
| 2689 |
+
history[stage] = now;
|
| 2690 |
+
const rank = PAY_STAGES[stage] || 0;
|
| 2691 |
+
const oldRank = PAY_STAGES[String(old.stage || "")] || 0;
|
| 2692 |
+
const next = Object.assign({}, old, {
|
| 2693 |
+
vid: key,
|
| 2694 |
+
createdAt: Number(old.createdAt) || now,
|
| 2695 |
+
updatedAt: now,
|
| 2696 |
+
history: history
|
| 2697 |
+
});
|
| 2698 |
+
if (rank >= oldRank || !old.stage) {
|
| 2699 |
+
next.stage = stage;
|
| 2700 |
+
next.lastStage = stage;
|
| 2701 |
+
next.lastEventAt = now;
|
| 2702 |
+
if (info && info.source) next.lastSource = String(info.source).slice(0, 12);
|
| 2703 |
+
}
|
| 2704 |
+
if (info && uidOk(info.uid)) next.uid = String(info.uid);
|
| 2705 |
+
if (info && info.email) next.email = String(info.email).slice(0, 200);
|
| 2706 |
+
if (info && info.plan && PLANS[info.plan]) next.plan = String(info.plan);
|
| 2707 |
+
if (info && info.sid && /^(cs|in|sub)_[A-Za-z0-9_]+$/.test(String(info.sid))) next.sid = String(info.sid);
|
| 2708 |
+
if (info && info.amount != null && Number.isFinite(Number(info.amount))) next.amount = Number(info.amount);
|
| 2709 |
+
if (info && info.currency) next.currency = String(info.currency).slice(0, 8).toLowerCase();
|
| 2710 |
+
if (info && info.page) {
|
| 2711 |
+
const p = String(info.page);
|
| 2712 |
+
if (/^\/[A-Za-z0-9._~\-/]{0,199}$/.test(p)) next.page = p;
|
| 2713 |
+
}
|
| 2714 |
+
if (info && info.error) next.lastError = payErrorText(info.error);
|
| 2715 |
+
else if (stage === "paid") next.lastError = "";
|
| 2716 |
+
await rtdb("pay_funnel/" + key, "PUT", next);
|
| 2717 |
+
});
|
| 2718 |
+
}
|
| 2719 |
+
|
| 2720 |
async function openPay(uid, planKey, email, auto) {
|
| 2721 |
let rec = null;
|
| 2722 |
try { rec = await rtdb("pay_open/" + uid, "GET"); } catch { rec = null; }
|
|
|
|
| 2748 |
const planKey = String(body.plan || "").trim().toLowerCase();
|
| 2749 |
const plan = PLANS[planKey];
|
| 2750 |
const email = payEmail(idp);
|
| 2751 |
+
const vid = cleanVid(body.vid);
|
| 2752 |
if (!plan || !email) return json(res, 400, { error: "plan" });
|
| 2753 |
if (!verifyProof(body.proof, clientIp(req))) {
|
| 2754 |
return json(res, 400, { error: "captcha" });
|
|
|
|
| 2757 |
const urls = payUrls(body.returnUrl);
|
| 2758 |
const wallets = await ensureFreeWallets();
|
| 2759 |
const reused = await openPay(idp.sub, planKey, email, auto);
|
| 2760 |
+
if (reused) {
|
| 2761 |
+
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(() => { });
|
| 2762 |
+
return json(res, 200, reused);
|
| 2763 |
+
}
|
| 2764 |
const nonce = crypto.randomBytes(8).toString("hex");
|
| 2765 |
const idem = "vip" + crypto.createHash("sha256").update(idp.sub + ":" + planKey + ":" + nonce).digest("hex").slice(0, 22);
|
| 2766 |
const homeMsg = "After pay you return to [DUB LK 2000 Home](" + HOME_URL + ")";
|
|
|
|
| 2794 |
"payment_intent_data[receipt_email]": email
|
| 2795 |
};
|
| 2796 |
fields.customer_email = email;
|
| 2797 |
+
if (vid) fields["metadata[vid]"] = vid;
|
| 2798 |
if (auto) {
|
| 2799 |
fields.mode = "subscription";
|
| 2800 |
fields["line_items[0][price_data][recurring][interval]"] = "month";
|
|
|
|
| 2802 |
fields["subscription_data[metadata][uid]"] = idp.sub;
|
| 2803 |
fields["subscription_data[metadata][plan]"] = planKey;
|
| 2804 |
fields["subscription_data[metadata][email]"] = email;
|
| 2805 |
+
if (vid) fields["subscription_data[metadata][vid]"] = vid;
|
| 2806 |
delete fields["payment_intent_data[description]"];
|
| 2807 |
delete fields["payment_intent_data[metadata][uid]"];
|
| 2808 |
delete fields["payment_intent_data[metadata][plan]"];
|
|
|
|
| 2822 |
});
|
| 2823 |
return { r, d: await r.json() };
|
| 2824 |
}
|
| 2825 |
+
let r;
|
| 2826 |
+
let d;
|
| 2827 |
+
let firstErr = "";
|
| 2828 |
+
try {
|
| 2829 |
+
({ r, d } = await createSes(fields, idem));
|
| 2830 |
+
firstErr = d && (d.error && d.error.message || d.message || null);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2831 |
if (!r.ok) {
|
| 2832 |
+
const slim = Object.assign({}, fields);
|
| 2833 |
+
[
|
| 2834 |
+
"branding_settings[display_name]",
|
| 2835 |
+
"branding_settings[logo][type]",
|
| 2836 |
+
"branding_settings[logo][url]",
|
| 2837 |
+
"branding_settings[button_color]",
|
| 2838 |
+
"branding_settings[background_color]",
|
| 2839 |
+
"line_items[0][price_data][product_data][images][0]"
|
| 2840 |
+
].forEach((k) => { delete slim[k]; });
|
| 2841 |
+
({ r, d } = await createSes(slim, idem + "s"));
|
| 2842 |
+
if (!r.ok) {
|
| 2843 |
+
process.stderr.write("stripe create failed: " + (firstErr || "unknown") + " | slim: " + ((d && d.error && d.error.message) || "unknown") + "\n");
|
| 2844 |
+
}
|
| 2845 |
}
|
| 2846 |
+
} catch (e) {
|
| 2847 |
+
await trackPay(vid || idp.sub, { stage: "start_failed", uid: idp.sub, email: email, plan: planKey, error: errText(e), source: "server" }).catch(() => { });
|
| 2848 |
+
return json(res, 400, { error: "Payment failed" });
|
| 2849 |
+
}
|
| 2850 |
+
if (!r.ok || !d.id || !d.url || d.object !== "checkout.session") {
|
| 2851 |
+
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(() => { });
|
| 2852 |
+
return json(res, 400, { error: "Payment failed" });
|
| 2853 |
}
|
|
|
|
| 2854 |
try {
|
| 2855 |
await rtdb("pay_open/" + idp.sub, "PUT", { sid: d.id, plan: planKey, email: email, auto: auto ? 1 : 0, t: Math.floor(Date.now() / 1000) });
|
| 2856 |
} catch { }
|
| 2857 |
+
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(() => { });
|
| 2858 |
json(res, 200, { sid: d.id, url: d.url });
|
| 2859 |
}
|
| 2860 |
|
|
|
|
| 2894 |
} catch {
|
| 2895 |
return json(res, 400, { error: "body" });
|
| 2896 |
}
|
| 2897 |
+
const vid = cleanVid(body.vid);
|
| 2898 |
const d = await stripeSession(body.sid);
|
| 2899 |
const meta = d && d.metadata || {};
|
| 2900 |
const email = payEmail(idp);
|
| 2901 |
const sem = String(meta.email || "");
|
| 2902 |
+
const fail = async (err) => {
|
| 2903 |
+
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(() => { });
|
| 2904 |
+
};
|
| 2905 |
if (!d || meta.uid !== idp.sub || d.client_reference_id !== idp.sub) {
|
| 2906 |
+
await fail("session");
|
| 2907 |
+
return json(res, 400, { error: "Payment failed", paid: false });
|
| 2908 |
+
}
|
| 2909 |
+
if (sem && (!email || sem.toLowerCase() !== email)) {
|
| 2910 |
+
await fail("email");
|
| 2911 |
return json(res, 400, { error: "Payment failed", paid: false });
|
| 2912 |
}
|
| 2913 |
+
if (d.payment_status !== "paid" || d.status !== "complete") {
|
| 2914 |
+
await fail("unpaid");
|
| 2915 |
+
return json(res, 402, { error: "unpaid", paid: false });
|
| 2916 |
+
}
|
| 2917 |
let granted = false;
|
| 2918 |
try { granted = await fulfillPaid(d); } catch { granted = false; }
|
| 2919 |
lvlCache.delete(idp.sub);
|
| 2920 |
let sub = null;
|
| 2921 |
try { sub = await rtdb("users/" + idp.sub + "/subscription", "GET"); } catch { }
|
| 2922 |
if (!granted || !vipActive(sub)) {
|
| 2923 |
+
await fail(granted ? "status" : "order");
|
| 2924 |
if (d.payment_status === "paid" && d.status === "complete") return json(res, 402, { error: "order", paid: false });
|
| 2925 |
return json(res, 402, { error: "unpaid", paid: false });
|
| 2926 |
}
|
| 2927 |
+
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(() => { });
|
| 2928 |
json(res, 200, { ok: true, paid: true, accessLevel: "subscribed", subscription: publicSub(sub) });
|
| 2929 |
}
|
| 2930 |
|
|
|
|
| 2949 |
const stripeSub = extra && extra.stripeSub ? String(extra.stripeSub) : (old && old.stripeSub ? String(old.stripeSub) : "");
|
| 2950 |
if (/^sub_[A-Za-z0-9_]+$/.test(stripeSub)) sub.stripeSub = stripeSub;
|
| 2951 |
await rtdb("users/" + uid + "/subscription", "PUT", sub);
|
| 2952 |
+
const aid = now + "_" + crypto.randomBytes(4).toString("hex");
|
| 2953 |
+
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(() => { });
|
| 2954 |
lvlCache.delete(uid);
|
| 2955 |
return sub;
|
| 2956 |
}
|
|
|
|
| 3062 |
paidOrders.set(sid, Date.now());
|
| 3063 |
const autoOn = ses.metadata && ses.metadata.auto === "1";
|
| 3064 |
const stripeSub = typeof ses.subscription === "string" ? ses.subscription : "";
|
| 3065 |
+
const extra = { source: autoOn ? "subscription" : "checkout" };
|
| 3066 |
if (autoOn) extra.autoRenew = true;
|
| 3067 |
if (stripeSub) extra.stripeSub = stripeSub;
|
| 3068 |
await grantVip(uid, planKey, c.exp, extra);
|
|
|
|
| 3119 |
return withPayLock(invId, async () => {
|
| 3120 |
const c = await claimOrder(invId, uid, planKey, plan.sec);
|
| 3121 |
if (c.state === "conflict" || c.state === "unknown" || !(c.exp > Math.floor(Date.now() / 1000))) return false;
|
| 3122 |
+
await grantVip(uid, planKey, c.exp, { autoRenew: true, stripeSub: subId, source: "invoice" });
|
| 3123 |
await markOrder(invId, uid, planKey, c.exp);
|
| 3124 |
+
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(() => { });
|
| 3125 |
return true;
|
| 3126 |
});
|
| 3127 |
}
|
|
|
|
| 3217 |
const id = ev.data && ev.data.object && ev.data.object.id;
|
| 3218 |
try {
|
| 3219 |
const ses = await stripeSession(id);
|
| 3220 |
+
if (ses) {
|
| 3221 |
+
did = await fulfillPaid(ses);
|
| 3222 |
+
const vid = cleanVid(ses.metadata && ses.metadata.vid);
|
| 3223 |
+
const uid = ses.metadata && ses.metadata.uid;
|
| 3224 |
+
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(() => { });
|
| 3225 |
+
}
|
| 3226 |
} catch { did = false; }
|
| 3227 |
} else if (ev.type === "checkout.session.expired") {
|
| 3228 |
const id = ev.data && ev.data.object && ev.data.object.id;
|
|
|
|
| 3234 |
const open = await rtdb("pay_open/" + uid, "GET");
|
| 3235 |
if (open && open.sid === id) await rtdb("pay_open/" + uid, "DELETE");
|
| 3236 |
}
|
| 3237 |
+
if (ses && ses.status === "expired") {
|
| 3238 |
+
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(() => { });
|
| 3239 |
+
}
|
| 3240 |
} catch { }
|
| 3241 |
}
|
| 3242 |
did = true;
|
|
|
|
| 3338 |
applyAdminCors(req, res);
|
| 3339 |
if (!adminKeyOk(req)) return json(res, 401, { error: "auth" });
|
| 3340 |
const ip = clientIp(req);
|
| 3341 |
+
if (slotOver("tgmeta:" + ip, 30)) {
|
| 3342 |
+
res.setHeader("Retry-After", "30");
|
| 3343 |
return json(res, 429, { error: "rate_limited" });
|
| 3344 |
}
|
| 3345 |
let text = String(url.searchParams.get("ids") || url.searchParams.get("text") || "");
|
|
|
|
| 3448 |
const pm = /^\/p\/([0-9a-f]+)(?:\.mp4)?$/i.exec(url.pathname);
|
| 3449 |
if (pm && (req.method === "GET" || req.method === "HEAD")) return handlePlay(req, res, url, pm[1]);
|
| 3450 |
if (url.pathname === "/vip/status" && req.method === "GET") return handleVipStatus(req, res);
|
| 3451 |
+
if (url.pathname === "/vip/track" && req.method === "POST") return handleVipTrack(req, res);
|
| 3452 |
if (url.pathname === "/vip/start" && req.method === "POST") return handleVipStart(req, res);
|
| 3453 |
if (url.pathname === "/vip/go" && req.method === "POST") return handleVipGo(req, res);
|
| 3454 |
if (url.pathname === "/vip/confirm" && req.method === "POST") return handleVipConfirm(req, res);
|
|
|
|
| 3545 |
});
|
| 3546 |
srv.listen(PORT, "0.0.0.0", () => {
|
| 3547 |
if (ROLE === "indexer" && STRIPE_KEY) ensureFreeWallets().catch(() => { });
|
| 3548 |
+
if (ROLE === "indexer" && FB_SECRET && OWNER_UID && OWNER_VIP_UNTIL > Math.floor(Date.now() / 1000)) {
|
| 3549 |
+
grantVip(OWNER_UID, "month", OWNER_VIP_UNTIL, { autoRenew: false, source: "owner" }).catch(() => { });
|
| 3550 |
+
}
|
| 3551 |
});
|
| 3552 |
}
|
| 3553 |
|