Spaces:
Running
Running
DUBLK 2000 Admin commited on
Commit ·
86f1cb4
1
Parent(s): b10a096
Fix player scope, preview fail-closed, origin allowlist, payment idempotency
Browse files
server.js
CHANGED
|
@@ -22,7 +22,20 @@ const TOKEN_TTL = 21600;
|
|
| 22 |
const MIN_ALIGN = 4096;
|
| 23 |
const MB = 1024 * 1024;
|
| 24 |
const CPU_N = Math.max(1, (os.cpus() || []).length || 2);
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
const CHUNK_SIZE = 1024 * 1024;
|
| 27 |
const HOT_HEAD = 24 * MB;
|
| 28 |
const HOT_TAIL = 8 * MB;
|
|
@@ -102,6 +115,7 @@ const uidStreams = new Map();
|
|
| 102 |
const uidTitles = new Map();
|
| 103 |
const titlePipes = new Map();
|
| 104 |
const paidOrders = new Map();
|
|
|
|
| 105 |
const payLocks = new Map();
|
| 106 |
const tokCache = new Map();
|
| 107 |
const genAnonCache = new Map();
|
|
@@ -492,7 +506,7 @@ function busyJson(res) {
|
|
| 492 |
function limited(ip) {
|
| 493 |
const now = Date.now();
|
| 494 |
const slot = Math.floor(now / 60000);
|
| 495 |
-
const key = ip + ":" + slot;
|
| 496 |
const n = (rateMap.get(key) || 0) + 1;
|
| 497 |
rateMap.set(key, n);
|
| 498 |
return n > 360;
|
|
@@ -505,7 +519,7 @@ function isBlogOrigin(o) {
|
|
| 505 |
const u = new URL(o.includes("://") ? o : "https://" + o);
|
| 506 |
if (u.protocol !== "https:") return false;
|
| 507 |
const h = u.hostname.toLowerCase();
|
| 508 |
-
if (h === "dublk2000.blogspot.com" || h.endsWith(".dublk2000.blogspot.com") || /^dublk2000\.blogspot\.[a-z
|
| 509 |
const allow = String(ORIGIN || "").replace(/\/$/, "");
|
| 510 |
return allow && u.origin === allow;
|
| 511 |
} catch {
|
|
@@ -729,11 +743,11 @@ async function accessLevel(uid) {
|
|
| 729 |
if (!uid) return "anonymous";
|
| 730 |
const hit = lvlCache.get(uid);
|
| 731 |
if (hit && Date.now() - hit.ts < LVL_TTL) return hit.lvl;
|
| 732 |
-
let lvl = "
|
| 733 |
try {
|
| 734 |
const sub = await withTime(rtdb("users/" + uid + "/subscription", "GET"), 3500, LVL_MISS);
|
| 735 |
-
if (sub === LVL_MISS) return "
|
| 736 |
-
if (vipActive(sub)) lvl = "subscribed";
|
| 737 |
lvlCache.set(uid, { lvl, ts: Date.now() });
|
| 738 |
} catch { }
|
| 739 |
return lvl;
|
|
@@ -754,13 +768,10 @@ function httpVideoType(mime, name) {
|
|
| 754 |
function pickBot(preferIdx, skipIdx, msgId) {
|
| 755 |
if (!bots.length) return null;
|
| 756 |
const readyBots = bots.filter((b) => b && b.ready && (!b.coolUntil || Date.now() >= b.coolUntil) && (b.client && b.client.connected !== false) && b.idx !== skipIdx);
|
| 757 |
-
if (!readyBots.length)
|
| 758 |
-
const connected = bots.filter((b) => b && b.client && b.client.connected !== false && b.idx !== skipIdx);
|
| 759 |
-
if (!connected.length) return null;
|
| 760 |
-
return connected[rr++ % connected.length];
|
| 761 |
-
}
|
| 762 |
const pool = readyBots.filter((b) => (b.tgLoad || 0) < BOT_MAX);
|
| 763 |
-
|
|
|
|
| 764 |
if (msgId != null) {
|
| 765 |
const id = String(msgId);
|
| 766 |
const hot = use.filter((b) => {
|
|
@@ -795,12 +806,11 @@ async function startBot(token, idx) {
|
|
| 795 |
reconnectRetries: Infinity,
|
| 796 |
retryDelay: 1500,
|
| 797 |
autoReconnect: true,
|
| 798 |
-
useWSS: true,
|
| 799 |
floodSleepThreshold: 2,
|
| 800 |
requestRetries: 3,
|
| 801 |
downloadRetries: 3,
|
| 802 |
maxConcurrentDownloads: 16,
|
| 803 |
-
downloadPool: {
|
| 804 |
});
|
| 805 |
client.setLogLevel("error");
|
| 806 |
await client.start({ botAuthToken: token });
|
|
@@ -1117,6 +1127,8 @@ async function fillDuration(bot, rec, msgId) {
|
|
| 1117 |
|
| 1118 |
const LVL_PCT = { anonymous: 40, registered: 70, subscribed: 100 };
|
| 1119 |
const INDEX_WIN = 4 * MB;
|
|
|
|
|
|
|
| 1120 |
|
| 1121 |
function lvlPct(l) {
|
| 1122 |
const p = LVL_PCT[String(l || "")];
|
|
@@ -1168,8 +1180,9 @@ function applyPreview(rng, size, l, msgId, ticket) {
|
|
| 1168 |
};
|
| 1169 |
}
|
| 1170 |
const maxEnd = previewMaxEnd(size, l);
|
| 1171 |
-
const
|
| 1172 |
-
|
|
|
|
| 1173 |
return { start: rng.start, end: endCap, partial: true };
|
| 1174 |
}
|
| 1175 |
if (rng.start <= maxEnd) {
|
|
@@ -1748,7 +1761,10 @@ function setSliceMem(msgId, offset, buf) {
|
|
| 1748 |
if (sliceMemCache.has(k)) sliceMemCache.delete(k);
|
| 1749 |
sliceMemCache.set(k, buf);
|
| 1750 |
const heapCut = Math.floor(RAM_BYTES * 0.22);
|
| 1751 |
-
const
|
|
|
|
|
|
|
|
|
|
| 1752 |
while (sliceMemCache.size > memMax) {
|
| 1753 |
const oldest = sliceMemCache.keys().next().value;
|
| 1754 |
sliceMemCache.delete(oldest);
|
|
@@ -1901,7 +1917,19 @@ function rememberElstLead(msgId, buf) {
|
|
| 1901 |
const id = String(msgId || "");
|
| 1902 |
if (!id || elstLeadSec.has(id)) return;
|
| 1903 |
const sec = videoEmptyEditSec(buf);
|
| 1904 |
-
if (sec > 0.05)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1905 |
}
|
| 1906 |
|
| 1907 |
function patchAvSync(buf, fileOff, msgId, ua) {
|
|
@@ -1990,7 +2018,7 @@ async function pipeDiskRange(msgId, start, end, req, res, headers, size) {
|
|
| 1990 |
if (!piece || !piece.length) return false;
|
| 1991 |
let skip = at - off;
|
| 1992 |
if (skip < 0) skip = 0;
|
| 1993 |
-
if (skip >= piece.length)
|
| 1994 |
let buf = skip ? piece.subarray(skip) : piece;
|
| 1995 |
const left = end - at + 1;
|
| 1996 |
if (buf.length > left) buf = buf.subarray(0, left);
|
|
@@ -2228,6 +2256,8 @@ async function pipeRange(bot, rec, start, end, req, res, status, headers, msgId)
|
|
| 2228 |
|
| 2229 |
async function readBody(req, max) {
|
| 2230 |
const lim = max || BODY_MAX;
|
|
|
|
|
|
|
| 2231 |
const chunks = [];
|
| 2232 |
let n = 0;
|
| 2233 |
for await (const c of req) {
|
|
@@ -2432,7 +2462,22 @@ async function handleStream(req, res, url, msgId, kHex, ticketObj) {
|
|
| 2432 |
}
|
| 2433 |
let held = false;
|
| 2434 |
try {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2435 |
const sizeHint = Number(ticket.s) || 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2436 |
const mimeHint = String(ticket.n || "video/mp4");
|
| 2437 |
const typeHint = (mimeHint.indexOf("webm") >= 0) ? "video/webm" : "video/mp4";
|
| 2438 |
const lvl = ticketLvl(ticket);
|
|
@@ -2485,12 +2530,6 @@ async function handleStream(req, res, url, msgId, kHex, ticketObj) {
|
|
| 2485 |
res.writeHead(503);
|
| 2486 |
return res.end();
|
| 2487 |
}
|
| 2488 |
-
if (!takeStream(ip, ticket.u, msgId)) {
|
| 2489 |
-
res.setHeader("Retry-After", "1");
|
| 2490 |
-
res.writeHead(429);
|
| 2491 |
-
return res.end();
|
| 2492 |
-
}
|
| 2493 |
-
held = true;
|
| 2494 |
let rec;
|
| 2495 |
try {
|
| 2496 |
rec = await fileFromMsg(bot, msgId);
|
|
@@ -2635,7 +2674,7 @@ async function handleVipStart(req, res) {
|
|
| 2635 |
const plan = PLANS[planKey];
|
| 2636 |
if (!plan) return json(res, 400, { error: "plan" });
|
| 2637 |
const urls = payUrls(body.returnUrl);
|
| 2638 |
-
const idem = "vip" + crypto.createHash("sha256").update(idp.sub + ":" + planKey).digest("hex").slice(0, 22)
|
| 2639 |
const homeMsg = "After pay you return to [DUB LK 2000 Home](" + HOME_URL + ")";
|
| 2640 |
const fields = {
|
| 2641 |
mode: "payment",
|
|
@@ -2678,6 +2717,7 @@ async function handleVipStart(req, res) {
|
|
| 2678 |
return { r, d: await r.json() };
|
| 2679 |
}
|
| 2680 |
let { r, d } = await createSes(fields);
|
|
|
|
| 2681 |
if (!r.ok) {
|
| 2682 |
const slim = Object.assign({}, fields);
|
| 2683 |
[
|
|
@@ -2689,6 +2729,9 @@ async function handleVipStart(req, res) {
|
|
| 2689 |
"line_items[0][price_data][product_data][images][0]"
|
| 2690 |
].forEach((k) => { delete slim[k]; });
|
| 2691 |
({ r, d } = await createSes(slim));
|
|
|
|
|
|
|
|
|
|
| 2692 |
}
|
| 2693 |
if (!r.ok || !d.id || !d.url || d.object !== "checkout.session") return json(res, 400, { error: "Payment failed" });
|
| 2694 |
json(res, 200, { sid: d.id, url: d.url });
|
|
@@ -2698,6 +2741,10 @@ async function handleVipGo(req, res) {
|
|
| 2698 |
if (!payGate(req, res)) return;
|
| 2699 |
const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
|
| 2700 |
if (!idp || !googlePayUser(idp) || !uidOk(idp.sub)) return json(res, 401, { error: "login" });
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2701 |
let body;
|
| 2702 |
try {
|
| 2703 |
body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
|
|
@@ -2806,6 +2853,23 @@ async function markOrder(id, uid, planKey) {
|
|
| 2806 |
} catch { }
|
| 2807 |
}
|
| 2808 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2809 |
async function fulfillPaid(ses) {
|
| 2810 |
if (!ses || ses.object !== "checkout.session") return false;
|
| 2811 |
if (ses.mode !== "payment" || ses.payment_status !== "paid") return false;
|
|
@@ -2821,6 +2885,19 @@ async function fulfillPaid(ses) {
|
|
| 2821 |
const sid = String(ses.id || "");
|
| 2822 |
if (!/^cs_[A-Za-z0-9_]+$/.test(sid)) return false;
|
| 2823 |
return withPayLock(sid, async () => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2824 |
if (await orderSeen(sid)) return true;
|
| 2825 |
await grantVip(uid, planKey);
|
| 2826 |
await markOrder(sid, uid, planKey);
|
|
@@ -2828,6 +2905,35 @@ async function fulfillPaid(ses) {
|
|
| 2828 |
});
|
| 2829 |
}
|
| 2830 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2831 |
async function handleStripeWebhook(req, res) {
|
| 2832 |
const rawBuf = await readBody(req);
|
| 2833 |
if (!stripeOk(rawBuf, req.headers["stripe-signature"])) {
|
|
@@ -2839,12 +2945,22 @@ async function handleStripeWebhook(req, res) {
|
|
| 2839 |
res.writeHead(400);
|
| 2840 |
return res.end();
|
| 2841 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2842 |
if (ev.type === "checkout.session.completed" || ev.type === "checkout.session.async_payment_succeeded") {
|
| 2843 |
const id = ev.data && ev.data.object && ev.data.object.id;
|
| 2844 |
try {
|
| 2845 |
const ses = await stripeSession(id);
|
| 2846 |
if (ses) await fulfillPaid(ses);
|
| 2847 |
} catch { }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2848 |
}
|
| 2849 |
json(res, 200, { ok: true });
|
| 2850 |
}
|
|
@@ -2887,8 +3003,6 @@ async function handleBootstrap(req, res, url) {
|
|
| 2887 |
}
|
| 2888 |
|
| 2889 |
function handleHealth(req, res) {
|
| 2890 |
-
sweepMaps();
|
| 2891 |
-
sweepBots();
|
| 2892 |
if (req && adminKeyOk(req, new URL("http://local"))) {
|
| 2893 |
json(res, 200, {
|
| 2894 |
ok: true,
|
|
@@ -3029,6 +3143,11 @@ async function handleTgMeta(req, res, url) {
|
|
| 3029 |
}
|
| 3030 |
|
| 3031 |
function handleHome(req, res) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3032 |
res.writeHead(204, Object.assign(streamLock(), {
|
| 3033 |
"Cache-Control": "no-store",
|
| 3034 |
"Content-Length": "0"
|
|
|
|
| 22 |
const MIN_ALIGN = 4096;
|
| 23 |
const MB = 1024 * 1024;
|
| 24 |
const CPU_N = Math.max(1, (os.cpus() || []).length || 2);
|
| 25 |
+
function cgroupLimitBytes() {
|
| 26 |
+
const paths = ["/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"];
|
| 27 |
+
for (const p of paths) {
|
| 28 |
+
try {
|
| 29 |
+
const raw = fs.readFileSync(p, "utf8").trim();
|
| 30 |
+
if (!raw || raw === "max") continue;
|
| 31 |
+
const n = Number(raw);
|
| 32 |
+
if (Number.isFinite(n) && n > 64 * MB) return Math.min(n, os.totalmem() || n);
|
| 33 |
+
} catch { }
|
| 34 |
+
}
|
| 35 |
+
return 0;
|
| 36 |
+
}
|
| 37 |
+
const CGROUP_BYTES = cgroupLimitBytes();
|
| 38 |
+
const RAM_BYTES = CGROUP_BYTES || os.totalmem() || (16 * 1024 * MB);
|
| 39 |
const CHUNK_SIZE = 1024 * 1024;
|
| 40 |
const HOT_HEAD = 24 * MB;
|
| 41 |
const HOT_TAIL = 8 * MB;
|
|
|
|
| 115 |
const uidTitles = new Map();
|
| 116 |
const titlePipes = new Map();
|
| 117 |
const paidOrders = new Map();
|
| 118 |
+
const stripeEvents = new Set();
|
| 119 |
const payLocks = new Map();
|
| 120 |
const tokCache = new Map();
|
| 121 |
const genAnonCache = new Map();
|
|
|
|
| 506 |
function limited(ip) {
|
| 507 |
const now = Date.now();
|
| 508 |
const slot = Math.floor(now / 60000);
|
| 509 |
+
const key = ipNet(ip) + ":" + slot;
|
| 510 |
const n = (rateMap.get(key) || 0) + 1;
|
| 511 |
rateMap.set(key, n);
|
| 512 |
return n > 360;
|
|
|
|
| 519 |
const u = new URL(o.includes("://") ? o : "https://" + o);
|
| 520 |
if (u.protocol !== "https:") return false;
|
| 521 |
const h = u.hostname.toLowerCase();
|
| 522 |
+
if (h === "dublk2000.blogspot.com" || h.endsWith(".dublk2000.blogspot.com") || /^dublk2000\.blogspot\.[a-z]{2,6}$/.test(h)) return true;
|
| 523 |
const allow = String(ORIGIN || "").replace(/\/$/, "");
|
| 524 |
return allow && u.origin === allow;
|
| 525 |
} catch {
|
|
|
|
| 743 |
if (!uid) return "anonymous";
|
| 744 |
const hit = lvlCache.get(uid);
|
| 745 |
if (hit && Date.now() - hit.ts < LVL_TTL) return hit.lvl;
|
| 746 |
+
let lvl = "anonymous";
|
| 747 |
try {
|
| 748 |
const sub = await withTime(rtdb("users/" + uid + "/subscription", "GET"), 3500, LVL_MISS);
|
| 749 |
+
if (sub === LVL_MISS) return "anonymous";
|
| 750 |
+
if (sub && vipActive(sub)) lvl = "subscribed";
|
| 751 |
lvlCache.set(uid, { lvl, ts: Date.now() });
|
| 752 |
} catch { }
|
| 753 |
return lvl;
|
|
|
|
| 768 |
function pickBot(preferIdx, skipIdx, msgId) {
|
| 769 |
if (!bots.length) return null;
|
| 770 |
const readyBots = bots.filter((b) => b && b.ready && (!b.coolUntil || Date.now() >= b.coolUntil) && (b.client && b.client.connected !== false) && b.idx !== skipIdx);
|
| 771 |
+
if (!readyBots.length) return null;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 772 |
const pool = readyBots.filter((b) => (b.tgLoad || 0) < BOT_MAX);
|
| 773 |
+
if (!pool.length) return null;
|
| 774 |
+
let use = pool;
|
| 775 |
if (msgId != null) {
|
| 776 |
const id = String(msgId);
|
| 777 |
const hot = use.filter((b) => {
|
|
|
|
| 806 |
reconnectRetries: Infinity,
|
| 807 |
retryDelay: 1500,
|
| 808 |
autoReconnect: true,
|
|
|
|
| 809 |
floodSleepThreshold: 2,
|
| 810 |
requestRetries: 3,
|
| 811 |
downloadRetries: 3,
|
| 812 |
maxConcurrentDownloads: 16,
|
| 813 |
+
downloadPool: { inflightPerDc: 4, maxSessions: 4, sessions: 4, requestDeadlineMs: 28000 }
|
| 814 |
});
|
| 815 |
client.setLogLevel("error");
|
| 816 |
await client.start({ botAuthToken: token });
|
|
|
|
| 1127 |
|
| 1128 |
const LVL_PCT = { anonymous: 40, registered: 70, subscribed: 100 };
|
| 1129 |
const INDEX_WIN = 4 * MB;
|
| 1130 |
+
const TAIL_MAX = 2 * MB;
|
| 1131 |
+
const TAIL_MIN_SIZE = 48 * MB;
|
| 1132 |
|
| 1133 |
function lvlPct(l) {
|
| 1134 |
const p = LVL_PCT[String(l || "")];
|
|
|
|
| 1180 |
};
|
| 1181 |
}
|
| 1182 |
const maxEnd = previewMaxEnd(size, l);
|
| 1183 |
+
const tailAllowed = size >= TAIL_MIN_SIZE;
|
| 1184 |
+
const tailWin = tailAllowed ? Math.max(0, size - Math.min(TAIL_MAX, Math.floor(size * 0.01))) : Infinity;
|
| 1185 |
+
if (tailAllowed && rng.start >= tailWin) {
|
| 1186 |
return { start: rng.start, end: endCap, partial: true };
|
| 1187 |
}
|
| 1188 |
if (rng.start <= maxEnd) {
|
|
|
|
| 1761 |
if (sliceMemCache.has(k)) sliceMemCache.delete(k);
|
| 1762 |
sliceMemCache.set(k, buf);
|
| 1763 |
const heapCut = Math.floor(RAM_BYTES * 0.22);
|
| 1764 |
+
const memUsed = process.memoryUsage();
|
| 1765 |
+
const bufBytes = (memUsed.arrayBuffers || 0) + (memUsed.external || 0);
|
| 1766 |
+
const overCut = (bufBytes > heapCut || memUsed.rss > heapCut * 1.6);
|
| 1767 |
+
const memMax = overCut ? Math.max(256, Math.floor(SLICE_MEM_MAX / 4)) : SLICE_MEM_MAX;
|
| 1768 |
while (sliceMemCache.size > memMax) {
|
| 1769 |
const oldest = sliceMemCache.keys().next().value;
|
| 1770 |
sliceMemCache.delete(oldest);
|
|
|
|
| 1917 |
const id = String(msgId || "");
|
| 1918 |
if (!id || elstLeadSec.has(id)) return;
|
| 1919 |
const sec = videoEmptyEditSec(buf);
|
| 1920 |
+
if (sec > 0.05) {
|
| 1921 |
+
elstLeadSec.set(id, sec);
|
| 1922 |
+
if (elstLeadSec.size > 20000) {
|
| 1923 |
+
const first = elstLeadSec.keys().next().value;
|
| 1924 |
+
elstLeadSec.delete(first);
|
| 1925 |
+
}
|
| 1926 |
+
let st = avLead.get(id);
|
| 1927 |
+
if (!st) {
|
| 1928 |
+
st = { delay: 0, movieTs: 1000 };
|
| 1929 |
+
avLead.set(id, st);
|
| 1930 |
+
}
|
| 1931 |
+
if (!st.delay) st.delay = Math.round(sec * st.movieTs);
|
| 1932 |
+
}
|
| 1933 |
}
|
| 1934 |
|
| 1935 |
function patchAvSync(buf, fileOff, msgId, ua) {
|
|
|
|
| 2018 |
if (!piece || !piece.length) return false;
|
| 2019 |
let skip = at - off;
|
| 2020 |
if (skip < 0) skip = 0;
|
| 2021 |
+
if (skip >= piece.length) return false;
|
| 2022 |
let buf = skip ? piece.subarray(skip) : piece;
|
| 2023 |
const left = end - at + 1;
|
| 2024 |
if (buf.length > left) buf = buf.subarray(0, left);
|
|
|
|
| 2256 |
|
| 2257 |
async function readBody(req, max) {
|
| 2258 |
const lim = max || BODY_MAX;
|
| 2259 |
+
const declared = Number(req.headers["content-length"] || 0);
|
| 2260 |
+
if (Number.isFinite(declared) && declared > lim) throw new Error("body");
|
| 2261 |
const chunks = [];
|
| 2262 |
let n = 0;
|
| 2263 |
for await (const c of req) {
|
|
|
|
| 2462 |
}
|
| 2463 |
let held = false;
|
| 2464 |
try {
|
| 2465 |
+
if (limited(ip)) {
|
| 2466 |
+
res.setHeader("Retry-After", "2");
|
| 2467 |
+
res.writeHead(429);
|
| 2468 |
+
return res.end();
|
| 2469 |
+
}
|
| 2470 |
+
if (!takeStream(ip, ticket.u, msgId)) {
|
| 2471 |
+
res.setHeader("Retry-After", "1");
|
| 2472 |
+
res.writeHead(429);
|
| 2473 |
+
return res.end();
|
| 2474 |
+
}
|
| 2475 |
+
held = true;
|
| 2476 |
const sizeHint = Number(ticket.s) || 0;
|
| 2477 |
+
if (sizeHint <= 0) {
|
| 2478 |
+
res.writeHead(502);
|
| 2479 |
+
return res.end();
|
| 2480 |
+
}
|
| 2481 |
const mimeHint = String(ticket.n || "video/mp4");
|
| 2482 |
const typeHint = (mimeHint.indexOf("webm") >= 0) ? "video/webm" : "video/mp4";
|
| 2483 |
const lvl = ticketLvl(ticket);
|
|
|
|
| 2530 |
res.writeHead(503);
|
| 2531 |
return res.end();
|
| 2532 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2533 |
let rec;
|
| 2534 |
try {
|
| 2535 |
rec = await fileFromMsg(bot, msgId);
|
|
|
|
| 2674 |
const plan = PLANS[planKey];
|
| 2675 |
if (!plan) return json(res, 400, { error: "plan" });
|
| 2676 |
const urls = payUrls(body.returnUrl);
|
| 2677 |
+
const idem = "vip" + crypto.createHash("sha256").update(idp.sub + ":" + planKey).digest("hex").slice(0, 22);
|
| 2678 |
const homeMsg = "After pay you return to [DUB LK 2000 Home](" + HOME_URL + ")";
|
| 2679 |
const fields = {
|
| 2680 |
mode: "payment",
|
|
|
|
| 2717 |
return { r, d: await r.json() };
|
| 2718 |
}
|
| 2719 |
let { r, d } = await createSes(fields);
|
| 2720 |
+
const firstErr = d && (d.error && d.error.message || d.message || null);
|
| 2721 |
if (!r.ok) {
|
| 2722 |
const slim = Object.assign({}, fields);
|
| 2723 |
[
|
|
|
|
| 2729 |
"line_items[0][price_data][product_data][images][0]"
|
| 2730 |
].forEach((k) => { delete slim[k]; });
|
| 2731 |
({ r, d } = await createSes(slim));
|
| 2732 |
+
if (!r.ok) {
|
| 2733 |
+
errText(new Error("stripe: " + (firstErr || "unknown") + " | slim: " + ((d && d.error && d.error.message) || "unknown")));
|
| 2734 |
+
}
|
| 2735 |
}
|
| 2736 |
if (!r.ok || !d.id || !d.url || d.object !== "checkout.session") return json(res, 400, { error: "Payment failed" });
|
| 2737 |
json(res, 200, { sid: d.id, url: d.url });
|
|
|
|
| 2741 |
if (!payGate(req, res)) return;
|
| 2742 |
const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
|
| 2743 |
if (!idp || !googlePayUser(idp) || !uidOk(idp.sub)) return json(res, 401, { error: "login" });
|
| 2744 |
+
if (payLimited(idp.sub, clientIp(req))) {
|
| 2745 |
+
res.setHeader("Retry-After", "30");
|
| 2746 |
+
return json(res, 429, { error: "rate_limited" });
|
| 2747 |
+
}
|
| 2748 |
let body;
|
| 2749 |
try {
|
| 2750 |
body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
|
|
|
|
| 2853 |
} catch { }
|
| 2854 |
}
|
| 2855 |
|
| 2856 |
+
async function claimOrder(id, uid, planKey) {
|
| 2857 |
+
const rec = { t: Math.floor(Date.now() / 1000), uid: uid, plan: planKey, s: "claim" };
|
| 2858 |
+
paidOrders.set(id, Date.now());
|
| 2859 |
+
try {
|
| 2860 |
+
await rtdb("processed_orders/" + id, "POST", rec);
|
| 2861 |
+
return "claimed";
|
| 2862 |
+
} catch (e) {
|
| 2863 |
+
if (String(e && e.message || "").indexOf("409") >= 0) return "seen";
|
| 2864 |
+
if (await orderSeen(id)) return "seen";
|
| 2865 |
+
try {
|
| 2866 |
+
await rtdb("processed_orders/" + id, "PUT", rec);
|
| 2867 |
+
return "claimed";
|
| 2868 |
+
} catch { }
|
| 2869 |
+
return "unknown";
|
| 2870 |
+
}
|
| 2871 |
+
}
|
| 2872 |
+
|
| 2873 |
async function fulfillPaid(ses) {
|
| 2874 |
if (!ses || ses.object !== "checkout.session") return false;
|
| 2875 |
if (ses.mode !== "payment" || ses.payment_status !== "paid") return false;
|
|
|
|
| 2885 |
const sid = String(ses.id || "");
|
| 2886 |
if (!/^cs_[A-Za-z0-9_]+$/.test(sid)) return false;
|
| 2887 |
return withPayLock(sid, async () => {
|
| 2888 |
+
const claim = await claimOrder(sid, uid, planKey);
|
| 2889 |
+
if (claim === "seen") return true;
|
| 2890 |
+
if (claim === "claimed") {
|
| 2891 |
+
try {
|
| 2892 |
+
await grantVip(uid, planKey);
|
| 2893 |
+
await markOrder(sid, uid, planKey);
|
| 2894 |
+
return true;
|
| 2895 |
+
} catch {
|
| 2896 |
+
try { await rtdb("processed_orders/" + sid, "DELETE"); } catch { }
|
| 2897 |
+
paidOrders.delete(sid);
|
| 2898 |
+
return false;
|
| 2899 |
+
}
|
| 2900 |
+
}
|
| 2901 |
if (await orderSeen(sid)) return true;
|
| 2902 |
await grantVip(uid, planKey);
|
| 2903 |
await markOrder(sid, uid, planKey);
|
|
|
|
| 2905 |
});
|
| 2906 |
}
|
| 2907 |
|
| 2908 |
+
async function stripeEventSeen(id) {
|
| 2909 |
+
if (!id) return true;
|
| 2910 |
+
if (stripeEvents.has(id)) return true;
|
| 2911 |
+
try {
|
| 2912 |
+
await rtdb("stripe_events/" + id, "POST", { t: Math.floor(Date.now() / 1000) });
|
| 2913 |
+
stripeEvents.add(id);
|
| 2914 |
+
if (stripeEvents.size > 4000) {
|
| 2915 |
+
const first = stripeEvents.values().next().value;
|
| 2916 |
+
stripeEvents.delete(first);
|
| 2917 |
+
}
|
| 2918 |
+
return false;
|
| 2919 |
+
} catch (e) {
|
| 2920 |
+
if (String(e && e.message || "").indexOf("409") >= 0) {
|
| 2921 |
+
stripeEvents.add(id);
|
| 2922 |
+
return true;
|
| 2923 |
+
}
|
| 2924 |
+
try {
|
| 2925 |
+
const hit = await rtdb("stripe_events/" + id, "GET");
|
| 2926 |
+
if (hit) {
|
| 2927 |
+
stripeEvents.add(id);
|
| 2928 |
+
return true;
|
| 2929 |
+
}
|
| 2930 |
+
stripeEvents.add(id);
|
| 2931 |
+
return false;
|
| 2932 |
+
} catch { }
|
| 2933 |
+
return false;
|
| 2934 |
+
}
|
| 2935 |
+
}
|
| 2936 |
+
|
| 2937 |
async function handleStripeWebhook(req, res) {
|
| 2938 |
const rawBuf = await readBody(req);
|
| 2939 |
if (!stripeOk(rawBuf, req.headers["stripe-signature"])) {
|
|
|
|
| 2945 |
res.writeHead(400);
|
| 2946 |
return res.end();
|
| 2947 |
}
|
| 2948 |
+
const evId = String(ev.id || "");
|
| 2949 |
+
if (evId && /^evt_[A-Za-z0-9_]+$/.test(evId) && await stripeEventSeen(evId)) {
|
| 2950 |
+
return json(res, 200, { ok: true, dup: 1 });
|
| 2951 |
+
}
|
| 2952 |
if (ev.type === "checkout.session.completed" || ev.type === "checkout.session.async_payment_succeeded") {
|
| 2953 |
const id = ev.data && ev.data.object && ev.data.object.id;
|
| 2954 |
try {
|
| 2955 |
const ses = await stripeSession(id);
|
| 2956 |
if (ses) await fulfillPaid(ses);
|
| 2957 |
} catch { }
|
| 2958 |
+
} else if (ev.type === "checkout.session.expired") {
|
| 2959 |
+
const id = ev.data && ev.data.object && ev.data.object.id;
|
| 2960 |
+
if (/^cs_[A-Za-z0-9_]+$/.test(String(id || ""))) {
|
| 2961 |
+
try { await rtdb("processed_orders/" + id, "DELETE"); } catch { }
|
| 2962 |
+
paidOrders.delete(String(id));
|
| 2963 |
+
}
|
| 2964 |
}
|
| 2965 |
json(res, 200, { ok: true });
|
| 2966 |
}
|
|
|
|
| 3003 |
}
|
| 3004 |
|
| 3005 |
function handleHealth(req, res) {
|
|
|
|
|
|
|
| 3006 |
if (req && adminKeyOk(req, new URL("http://local"))) {
|
| 3007 |
json(res, 200, {
|
| 3008 |
ok: true,
|
|
|
|
| 3143 |
}
|
| 3144 |
|
| 3145 |
function handleHome(req, res) {
|
| 3146 |
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
| 3147 |
+
res.setHeader("Allow", "GET, HEAD");
|
| 3148 |
+
res.writeHead(405, streamLock());
|
| 3149 |
+
return res.end();
|
| 3150 |
+
}
|
| 3151 |
res.writeHead(204, Object.assign(streamLock(), {
|
| 3152 |
"Cache-Control": "no-store",
|
| 3153 |
"Content-Length": "0"
|