JOHN SILLVESTOR commited on
Commit
bef9f34
·
verified ·
1 Parent(s): 1c4e059

stream cap no extra latency

Browse files
Files changed (1) hide show
  1. server.js +261 -90
server.js CHANGED
@@ -1,6 +1,8 @@
1
  "use strict";
2
 
3
  const http = require("http");
 
 
4
  const crypto = require("crypto");
5
  const { TelegramClient, Api } = require("teleproto");
6
  const { StringSession } = require("teleproto/sessions");
@@ -51,6 +53,9 @@ const PLANS = {
51
  week: { amount: 199, label: "1 Week VIP", sec: 604800, price: "1.99" },
52
  month: { amount: 599, label: "1 Month VIP", sec: 2592000, price: "5.99" }
53
  };
 
 
 
54
 
55
  const aesKey = STREAM_SECRET
56
  ? crypto.hkdfSync("sha256", Buffer.from(STREAM_SECRET, "utf8"), Buffer.from("dublk2000"), Buffer.from("aes-256-gcm-ticket"), 32)
@@ -71,6 +76,7 @@ const lvlCache = new Map();
71
  const rateMap = new Map();
72
  const ipStreams = new Map();
73
  const paidOrders = new Map();
 
74
  let fbKeys = { certs: null, exp: 0 };
75
  let rr = 0;
76
 
@@ -171,7 +177,7 @@ function streamLock() {
171
  "X-Content-Type-Options": "nosniff",
172
  "X-Frame-Options": "DENY",
173
  "Referrer-Policy": "strict-origin-when-cross-origin",
174
- "X-Robots-Tag": "noindex, nofollow, noarchive",
175
  "Permissions-Policy": "camera=(), microphone=(), geolocation=(), usb=(), payment=(), browsing-topics=()",
176
  "Cross-Origin-Resource-Policy": "cross-origin"
177
  };
@@ -444,21 +450,57 @@ async function rtdb(path, method, body) {
444
 
445
  const LVL_MISS = { miss: 1 };
446
 
 
 
 
 
 
 
 
447
  function vipActive(sub) {
448
- if (sub === true || sub === "active" || sub === "subscribed" || sub === "vip") return true;
449
  if (!sub || typeof sub !== "object") return false;
450
- const now = Math.floor(Date.now() / 1000);
451
- const nowMs = Date.now();
452
- const exp = Number(sub.expiry || sub.expiresAt || sub.expires || sub.expiration || sub.exp || 0);
453
- const hasExp = Number.isFinite(exp) && exp > 0;
454
- if (hasExp) {
455
- if (exp > 1e11) {
456
- if (exp <= nowMs) return false;
457
- } else if (exp <= now) return false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
458
  }
459
- if (sub.status === "cancelled" || sub.status === "expired" || sub.status === "inactive") return false;
460
- if (sub.status === "active" || sub.status === "subscribed" || sub.status === "vip" || sub.active === true || sub.isVip === true || sub.vip === true || sub.subscribed === true) return true;
461
- return hasExp;
 
 
 
 
 
462
  }
463
 
464
  async function accessLevel(uid) {
@@ -756,18 +798,25 @@ async function fillDuration(bot, rec, msgId) {
756
  }
757
 
758
  const LVL_PCT = { anonymous: 30, registered: 60, subscribed: 100 };
759
- const INDEX_TAIL = 8 * MB;
760
 
761
  function lvlPct(l) {
762
  const p = LVL_PCT[String(l || "")];
763
  return p == null ? 30 : p;
764
  }
765
 
 
 
 
 
 
 
766
  function previewMaxEnd(size, l) {
767
  const pct = lvlPct(l);
768
  if (!size || pct >= 100) return size - 1;
769
- const n = Math.floor(Number(size) * pct / 100) + STREAM_WINDOW;
770
- return Math.max(0, Math.min(size - 1, Math.max(0, n) - 1));
 
771
  }
772
 
773
  function applyPreview(rng, size, l) {
@@ -781,7 +830,10 @@ function applyPreview(rng, size, l) {
781
  };
782
  }
783
  const maxEnd = previewMaxEnd(size, l);
784
- const tailStart = Math.max(0, size - INDEX_TAIL);
 
 
 
785
  if (rng.start <= maxEnd) {
786
  const end = Math.min(rng.end, maxEnd);
787
  return {
@@ -790,7 +842,7 @@ function applyPreview(rng, size, l) {
790
  partial: rng.start > 0 || end < size - 1
791
  };
792
  }
793
- if (rng.end >= tailStart) {
794
  const start = Math.max(rng.start, tailStart);
795
  const end = Math.min(rng.end, size - 1);
796
  return { start, end, partial: true };
@@ -841,7 +893,7 @@ function mediaHeaders(type, msgId, size, hash, rng) {
841
  "Content-Type": type,
842
  "Accept-Ranges": "bytes",
843
  "Cache-Control": "private, no-store, no-transform",
844
- "Content-Disposition": "inline",
845
  "ETag": '"' + msgId + "-" + size + "-" + (hash || "x") + '"',
846
  "X-Accel-Buffering": "no",
847
  "Content-Length": String(rng.end - rng.start + 1),
@@ -1111,6 +1163,7 @@ async function handleGenerate(req, res, url) {
1111
  if (idp) {
1112
  uid = idp.sub;
1113
  lvl = await accessLevel(uid);
 
1114
  }
1115
  } catch {
1116
  lvl = uid ? "registered" : "anonymous";
@@ -1193,7 +1246,7 @@ async function handleStream(req, res, url, msgId) {
1193
  const sizeHint = Number(ticket.s) || 0;
1194
  const mimeHint = String(ticket.n || "video/mp4");
1195
  const typeHint = mimeHint.indexOf("/") > 0 ? mimeHint : "video/mp4";
1196
- const lvl = String(ticket.l || "anonymous");
1197
  if (sizeHint > 0) {
1198
  const rngHot0 = parseRange(req.headers.range, sizeHint);
1199
  const rngHot = applyPreview(rngHot0, sizeHint, lvl);
@@ -1293,13 +1346,60 @@ async function handleVipStatus(req, res) {
1293
  json(res, 200, { accessLevel: lvl });
1294
  }
1295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1296
  async function handleVipStart(req, res) {
1297
- if (ROLE !== "indexer") return json(res, 409, { error: "use_s1" });
1298
- if (!STRIPE_KEY) return json(res, 503, { error: "stripe_not_configured" });
1299
- if (!destOk(req, ["empty"])) return json(res, 403, { error: "forbidden" });
1300
- if (denyHot(req, res)) return;
1301
  const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
1302
- if (!idp) return json(res, 401, { error: "login" });
1303
  if (payLimited(idp.sub, clientIp(req))) {
1304
  res.setHeader("Retry-After", "30");
1305
  return json(res, 429, { error: "rate_limited" });
@@ -1313,70 +1413,119 @@ async function handleVipStart(req, res) {
1313
  const planKey = String(body.plan || "");
1314
  const plan = PLANS[planKey];
1315
  if (!plan) return json(res, 400, { error: "plan" });
 
1316
  const idem = "vip" + crypto.createHash("sha256").update(idp.sub + ":" + planKey).digest("hex").slice(0, 22) + Math.floor(Date.now() / 30000);
1317
- const r = await fetch("https://api.stripe.com/v1/checkout/sessions", {
1318
- method: "POST",
1319
- headers: {
1320
- Authorization: "Bearer " + STRIPE_KEY,
1321
- "Content-Type": "application/x-www-form-urlencoded",
1322
- "Idempotency-Key": idem
1323
- },
1324
- body: new URLSearchParams({
1325
- mode: "payment",
1326
- success_url: ORIGIN + "/?vip=success",
1327
- cancel_url: ORIGIN + "/?pay_error=cancel",
1328
- client_reference_id: String(idp.sub).slice(0, 200),
1329
- "line_items[0][price_data][currency]": "usd",
1330
- "line_items[0][price_data][product_data][name]": plan.label,
1331
- "line_items[0][price_data][unit_amount]": String(plan.amount),
1332
- "line_items[0][quantity]": "1",
1333
- "metadata[uid]": idp.sub,
1334
- "metadata[plan]": planKey,
1335
- "payment_intent_data[metadata][uid]": idp.sub,
1336
- "payment_intent_data[metadata][plan]": planKey
1337
- }).toString(),
1338
- signal: AbortSignal.timeout(12000)
1339
- });
1340
- const d = await r.json();
1341
- if (!r.ok || !d.id || !d.url) return json(res, 400, { error: "Payment failed" });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1342
  json(res, 200, { sid: d.id, url: d.url });
1343
  }
1344
 
1345
  async function handleVipGo(req, res) {
1346
- if (ROLE !== "indexer") return json(res, 409, { error: "use_s1" });
1347
- if (!STRIPE_KEY) return json(res, 503, { error: "stripe_not_configured" });
1348
- if (!destOk(req, ["empty"])) return json(res, 403, { error: "forbidden" });
1349
- if (denyHot(req, res)) return;
1350
  const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
1351
- if (!idp) return json(res, 401, { error: "login" });
1352
  let body;
1353
  try {
1354
  body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
1355
  } catch {
1356
  return json(res, 400, { error: "body" });
1357
  }
1358
- if (!body.sid || !/^cs_[A-Za-z0-9_]+$/.test(String(body.sid))) return json(res, 400, { error: "session" });
1359
- const r = await fetch("https://api.stripe.com/v1/checkout/sessions/" + encodeURIComponent(body.sid), {
1360
- headers: { Authorization: "Bearer " + STRIPE_KEY },
1361
- signal: AbortSignal.timeout(12000)
1362
- });
1363
- const d = await r.json();
1364
- const uid = d.metadata && d.metadata.uid;
1365
- if (!r.ok || !d.url || uid !== idp.sub || d.status === "expired") return json(res, 400, { error: "Payment failed" });
1366
  json(res, 200, { url: d.url });
1367
  }
1368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1369
  async function grantVip(uid, planKey) {
1370
- const plan = PLANS[planKey] || PLANS.month;
 
1371
  const now = Math.floor(Date.now() / 1000);
1372
  let start = now;
1373
  try {
1374
  const old = await rtdb("users/" + uid + "/subscription", "GET");
1375
- if (vipActive(old)) {
1376
- const exp = Number(old.expiry || old.expiresAt || 0);
1377
- const expSec = exp > 1e11 ? Math.floor(exp / 1000) : exp;
1378
- if (expSec > start) start = expSec;
1379
- }
1380
  } catch {}
1381
  const sub = {
1382
  status: "active",
@@ -1393,18 +1542,23 @@ async function grantVip(uid, planKey) {
1393
 
1394
  function stripeOk(raw, sigHeader) {
1395
  if (!STRIPE_WH || !sigHeader) return false;
1396
- const parts = {};
 
1397
  String(sigHeader).split(",").forEach((p) => {
1398
  const i = p.indexOf("=");
1399
- if (i > 0) parts[p.slice(0, i)] = p.slice(i + 1);
 
 
 
 
1400
  });
1401
- const t = parts.t;
1402
- const v1 = parts.v1;
1403
- if (!t || !v1) return false;
1404
  const ts = Number(t);
1405
  if (!Number.isFinite(ts) || Math.abs(Date.now() / 1000 - ts) > 300) return false;
1406
- const mac = crypto.createHmac("sha256", STRIPE_WH).update(t + "." + raw).digest("hex");
1407
- return timingSafeEq(mac, v1);
 
 
1408
  }
1409
 
1410
  async function orderSeen(id) {
@@ -1420,41 +1574,56 @@ async function orderSeen(id) {
1420
  return false;
1421
  }
1422
 
1423
- async function markOrder(id) {
1424
  paidOrders.set(id, Date.now());
1425
  try {
1426
- await rtdb("processed_orders/" + id, "PUT", { t: Math.floor(Date.now() / 1000) });
 
 
 
 
1427
  } catch {}
1428
  }
1429
 
1430
  async function fulfillPaid(ses) {
1431
- if (!ses || ses.mode !== "payment" || ses.payment_status !== "paid") return;
 
 
 
1432
  const uid = ses.metadata && ses.metadata.uid;
1433
  const planKey = ses.metadata && ses.metadata.plan;
1434
  const plan = PLANS[planKey];
1435
- if (!uid || !plan) return;
1436
- if (Number(ses.amount_total) !== plan.amount) return;
1437
- if (String(ses.currency || "").toLowerCase() !== "usd") return;
 
1438
  const sid = String(ses.id || "");
1439
- if (!sid || await orderSeen(sid)) return;
1440
- await markOrder(sid);
1441
- await grantVip(uid, planKey);
 
 
 
 
1442
  }
1443
 
1444
  async function handleStripeWebhook(req, res) {
1445
- const raw = (await readBody(req)).toString("utf8");
1446
- if (!stripeOk(raw, req.headers["stripe-signature"])) {
1447
  res.writeHead(400);
1448
  return res.end();
1449
  }
1450
  let ev;
1451
- try { ev = JSON.parse(raw); } catch {
1452
  res.writeHead(400);
1453
  return res.end();
1454
  }
1455
  if (ev.type === "checkout.session.completed" || ev.type === "checkout.session.async_payment_succeeded") {
1456
- const ses = ev.data && ev.data.object || {};
1457
- try { await fulfillPaid(ses); } catch {}
 
 
 
1458
  }
1459
  json(res, 200, { ok: true });
1460
  }
@@ -1513,11 +1682,13 @@ async function onReq(req, res) {
1513
  try {
1514
  if (url.pathname === "/") return handleHome(req, res);
1515
  if (url.pathname === "/health") return handleHealth(res);
 
1516
  if (url.pathname === "/public/bootstrap") return handleBootstrap(req, res, url);
1517
  if (url.pathname === "/generate-token" && req.method === "GET") return handleGenerate(req, res, url);
1518
  if (url.pathname === "/vip/status" && req.method === "GET") return handleVipStatus(req, res);
1519
  if (url.pathname === "/vip/start" && req.method === "POST") return handleVipStart(req, res);
1520
  if (url.pathname === "/vip/go" && req.method === "POST") return handleVipGo(req, res);
 
1521
  if (url.pathname === "/vip/stripe" && req.method === "POST") return handleStripeWebhook(req, res);
1522
  const sm = /^\/stream\/(\d+)(?:\.(?:mp4|m4v|webm|ogv|ogg))?$/.exec(url.pathname);
1523
  if (sm && (req.method === "GET" || req.method === "HEAD")) return handleStream(req, res, url, Number(sm[1]));
 
1
  "use strict";
2
 
3
  const http = require("http");
4
+ const fs = require("fs");
5
+ const path = require("path");
6
  const crypto = require("crypto");
7
  const { TelegramClient, Api } = require("teleproto");
8
  const { StringSession } = require("teleproto/sessions");
 
53
  week: { amount: 199, label: "1 Week VIP", sec: 604800, price: "1.99" },
54
  month: { amount: 599, label: "1 Month VIP", sec: 2592000, price: "5.99" }
55
  };
56
+ const HOME_URL = "https://dublk2000.blogspot.com/";
57
+ const BRAND_FILE = path.join(__dirname, "brand.png");
58
+ const BRAND_URL = (SPACE_URLS[0] || SPACE_FALLBACK[0]) + "/public/brand.png";
59
 
60
  const aesKey = STREAM_SECRET
61
  ? crypto.hkdfSync("sha256", Buffer.from(STREAM_SECRET, "utf8"), Buffer.from("dublk2000"), Buffer.from("aes-256-gcm-ticket"), 32)
 
76
  const rateMap = new Map();
77
  const ipStreams = new Map();
78
  const paidOrders = new Map();
79
+ const payLocks = new Map();
80
  let fbKeys = { certs: null, exp: 0 };
81
  let rr = 0;
82
 
 
177
  "X-Content-Type-Options": "nosniff",
178
  "X-Frame-Options": "DENY",
179
  "Referrer-Policy": "strict-origin-when-cross-origin",
180
+ "X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet, noimageindex",
181
  "Permissions-Policy": "camera=(), microphone=(), geolocation=(), usb=(), payment=(), browsing-topics=()",
182
  "Cross-Origin-Resource-Policy": "cross-origin"
183
  };
 
450
 
451
  const LVL_MISS = { miss: 1 };
452
 
453
+ function vipExpirySec(sub) {
454
+ if (!sub || typeof sub !== "object") return 0;
455
+ const exp = Number(sub.expiry || 0);
456
+ if (!Number.isFinite(exp) || exp <= 0) return 0;
457
+ return exp > 1e11 ? Math.floor(exp / 1000) : exp;
458
+ }
459
+
460
  function vipActive(sub) {
 
461
  if (!sub || typeof sub !== "object") return false;
462
+ if (sub.status !== "active") return false;
463
+ const exp = vipExpirySec(sub);
464
+ return exp > Math.floor(Date.now() / 1000);
465
+ }
466
+
467
+ function googlePayUser(idp) {
468
+ if (!idp || !idp.sub) return false;
469
+ const fb = idp.firebase;
470
+ if (!fb || fb.sign_in_provider !== "google.com") return false;
471
+ if (idp.email_verified === false) return false;
472
+ return true;
473
+ }
474
+
475
+ function uidOk(uid) {
476
+ return typeof uid === "string" && /^[A-Za-z0-9_-]{8,128}$/.test(uid);
477
+ }
478
+
479
+ async function stripeSession(id) {
480
+ if (!STRIPE_KEY || !id || !/^cs_[A-Za-z0-9_]+$/.test(String(id))) return null;
481
+ const r = await fetch("https://api.stripe.com/v1/checkout/sessions/" + encodeURIComponent(id), {
482
+ headers: { Authorization: "Bearer " + STRIPE_KEY },
483
+ signal: AbortSignal.timeout(12000)
484
+ });
485
+ const d = await r.json();
486
+ if (!r.ok || !d || d.object !== "checkout.session") return null;
487
+ return d;
488
+ }
489
+
490
+ function handleBrand(req, res) {
491
+ let buf;
492
+ try { buf = fs.readFileSync(BRAND_FILE); } catch {
493
+ res.writeHead(404);
494
+ return res.end();
495
  }
496
+ res.writeHead(200, {
497
+ "Content-Type": "image/png",
498
+ "Cache-Control": "public, max-age=86400",
499
+ "Cross-Origin-Resource-Policy": "cross-origin",
500
+ "X-Content-Type-Options": "nosniff"
501
+ });
502
+ if (req.method === "HEAD") return res.end();
503
+ res.end(buf);
504
  }
505
 
506
  async function accessLevel(uid) {
 
798
  }
799
 
800
  const LVL_PCT = { anonymous: 30, registered: 60, subscribed: 100 };
801
+ const INDEX_TAIL = 512 * 1024;
802
 
803
  function lvlPct(l) {
804
  const p = LVL_PCT[String(l || "")];
805
  return p == null ? 30 : p;
806
  }
807
 
808
+ function ticketLvl(ticket) {
809
+ const l = String(ticket && ticket.l || "");
810
+ if (l === "subscribed" || l === "registered" || l === "anonymous") return l;
811
+ return "anonymous";
812
+ }
813
+
814
  function previewMaxEnd(size, l) {
815
  const pct = lvlPct(l);
816
  if (!size || pct >= 100) return size - 1;
817
+ const n = Math.floor(Number(size) * pct / 100);
818
+ if (n <= 0) return 0;
819
+ return Math.min(size - 1, n - 1);
820
  }
821
 
822
  function applyPreview(rng, size, l) {
 
830
  };
831
  }
832
  const maxEnd = previewMaxEnd(size, l);
833
+ const tail = Math.min(INDEX_TAIL, Math.max(32768, Math.floor(size * 0.005)));
834
+ let tailStart = size;
835
+ const ts = size - tail;
836
+ if (ts > maxEnd + 1) tailStart = ts;
837
  if (rng.start <= maxEnd) {
838
  const end = Math.min(rng.end, maxEnd);
839
  return {
 
842
  partial: rng.start > 0 || end < size - 1
843
  };
844
  }
845
+ if (tailStart < size && rng.end >= tailStart) {
846
  const start = Math.max(rng.start, tailStart);
847
  const end = Math.min(rng.end, size - 1);
848
  return { start, end, partial: true };
 
893
  "Content-Type": type,
894
  "Accept-Ranges": "bytes",
895
  "Cache-Control": "private, no-store, no-transform",
896
+ "Content-Disposition": "inline; filename=\"watch.bin\"",
897
  "ETag": '"' + msgId + "-" + size + "-" + (hash || "x") + '"',
898
  "X-Accel-Buffering": "no",
899
  "Content-Length": String(rng.end - rng.start + 1),
 
1163
  if (idp) {
1164
  uid = idp.sub;
1165
  lvl = await accessLevel(uid);
1166
+ if (lvl !== "subscribed") lvl = "registered";
1167
  }
1168
  } catch {
1169
  lvl = uid ? "registered" : "anonymous";
 
1246
  const sizeHint = Number(ticket.s) || 0;
1247
  const mimeHint = String(ticket.n || "video/mp4");
1248
  const typeHint = mimeHint.indexOf("/") > 0 ? mimeHint : "video/mp4";
1249
+ const lvl = ticketLvl(ticket);
1250
  if (sizeHint > 0) {
1251
  const rngHot0 = parseRange(req.headers.range, sizeHint);
1252
  const rngHot = applyPreview(rngHot0, sizeHint, lvl);
 
1346
  json(res, 200, { accessLevel: lvl });
1347
  }
1348
 
1349
+ function blogReturn(u) {
1350
+ try {
1351
+ const p = new URL(String(u || ""), ORIGIN);
1352
+ if (p.protocol !== "https:" || p.hostname !== "dublk2000.blogspot.com") return ORIGIN + "/";
1353
+ return p.origin + p.pathname + p.search + p.hash;
1354
+ } catch {
1355
+ return ORIGIN + "/";
1356
+ }
1357
+ }
1358
+
1359
+ function payUrls(ret) {
1360
+ const base = blogReturn(ret);
1361
+ const join = base.indexOf("?") >= 0 ? "&" : "?";
1362
+ return {
1363
+ success: base + join + "vip=success&sid={CHECKOUT_SESSION_ID}",
1364
+ cancel: base + join + "pay_error=cancel"
1365
+ };
1366
+ }
1367
+
1368
+ function payGate(req, res) {
1369
+ if (ROLE !== "indexer") {
1370
+ json(res, 409, { error: "use_s1" });
1371
+ return null;
1372
+ }
1373
+ if (!STRIPE_KEY) {
1374
+ json(res, 503, { error: "stripe_not_configured" });
1375
+ return null;
1376
+ }
1377
+ if (!destOk(req, ["empty"])) {
1378
+ json(res, 403, { error: "forbidden" });
1379
+ return null;
1380
+ }
1381
+ if (denyHot(req, res)) return null;
1382
+ return true;
1383
+ }
1384
+
1385
+ async function withPayLock(id, fn) {
1386
+ const prev = payLocks.get(id);
1387
+ let done;
1388
+ const cur = new Promise((r) => { done = r; });
1389
+ payLocks.set(id, prev ? prev.then(() => cur, () => cur) : cur);
1390
+ if (prev) await prev.catch(() => {});
1391
+ try {
1392
+ return await fn();
1393
+ } finally {
1394
+ done();
1395
+ if (payLocks.get(id) === cur) payLocks.delete(id);
1396
+ }
1397
+ }
1398
+
1399
  async function handleVipStart(req, res) {
1400
+ if (!payGate(req, res)) return;
 
 
 
1401
  const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
1402
+ if (!idp || !googlePayUser(idp) || !uidOk(idp.sub)) return json(res, 401, { error: "login" });
1403
  if (payLimited(idp.sub, clientIp(req))) {
1404
  res.setHeader("Retry-After", "30");
1405
  return json(res, 429, { error: "rate_limited" });
 
1413
  const planKey = String(body.plan || "");
1414
  const plan = PLANS[planKey];
1415
  if (!plan) return json(res, 400, { error: "plan" });
1416
+ const urls = payUrls(body.returnUrl);
1417
  const idem = "vip" + crypto.createHash("sha256").update(idp.sub + ":" + planKey).digest("hex").slice(0, 22) + Math.floor(Date.now() / 30000);
1418
+ const homeMsg = "After pay you return to [DUB LK 2000 Home](" + HOME_URL + ")";
1419
+ const fields = {
1420
+ mode: "payment",
1421
+ success_url: urls.success,
1422
+ cancel_url: urls.cancel,
1423
+ client_reference_id: idp.sub,
1424
+ "line_items[0][price_data][currency]": "usd",
1425
+ "line_items[0][price_data][product_data][name]": plan.label + " — DUB LK 2000",
1426
+ "line_items[0][price_data][product_data][description]": "Home: " + HOME_URL,
1427
+ "line_items[0][price_data][product_data][images][0]": BRAND_URL,
1428
+ "line_items[0][price_data][unit_amount]": String(plan.amount),
1429
+ "line_items[0][quantity]": "1",
1430
+ "branding_settings[display_name]": "DUB LK 2000",
1431
+ "branding_settings[logo][type]": "url",
1432
+ "branding_settings[logo][url]": BRAND_URL,
1433
+ "branding_settings[button_color]": "#e50914",
1434
+ "branding_settings[background_color]": "#0c0d12",
1435
+ "custom_text[submit][message]": homeMsg,
1436
+ "custom_text[after_submit][message]": "Site: [" + HOME_URL + "](" + HOME_URL + ")",
1437
+ "metadata[uid]": idp.sub,
1438
+ "metadata[plan]": planKey,
1439
+ "payment_intent_data[description]": "DUB LK 2000 VIP " + plan.label,
1440
+ "payment_intent_data[metadata][uid]": idp.sub,
1441
+ "payment_intent_data[metadata][plan]": planKey
1442
+ };
1443
+ if (idp.email && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(idp.email))) {
1444
+ fields.customer_email = String(idp.email).slice(0, 200);
1445
+ }
1446
+ async function createSes(body) {
1447
+ const r = await fetch("https://api.stripe.com/v1/checkout/sessions", {
1448
+ method: "POST",
1449
+ headers: {
1450
+ Authorization: "Bearer " + STRIPE_KEY,
1451
+ "Content-Type": "application/x-www-form-urlencoded",
1452
+ "Idempotency-Key": idem
1453
+ },
1454
+ body: new URLSearchParams(body).toString(),
1455
+ signal: AbortSignal.timeout(12000)
1456
+ });
1457
+ return { r, d: await r.json() };
1458
+ }
1459
+ let { r, d } = await createSes(fields);
1460
+ if (!r.ok) {
1461
+ const slim = Object.assign({}, fields);
1462
+ [
1463
+ "branding_settings[display_name]",
1464
+ "branding_settings[logo][type]",
1465
+ "branding_settings[logo][url]",
1466
+ "branding_settings[button_color]",
1467
+ "branding_settings[background_color]",
1468
+ "line_items[0][price_data][product_data][images][0]"
1469
+ ].forEach((k) => { delete slim[k]; });
1470
+ ({ r, d } = await createSes(slim));
1471
+ }
1472
+ if (!r.ok || !d.id || !d.url || d.object !== "checkout.session") return json(res, 400, { error: "Payment failed" });
1473
  json(res, 200, { sid: d.id, url: d.url });
1474
  }
1475
 
1476
  async function handleVipGo(req, res) {
1477
+ if (!payGate(req, res)) return;
 
 
 
1478
  const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
1479
+ if (!idp || !googlePayUser(idp) || !uidOk(idp.sub)) return json(res, 401, { error: "login" });
1480
  let body;
1481
  try {
1482
  body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
1483
  } catch {
1484
  return json(res, 400, { error: "body" });
1485
  }
1486
+ const d = await stripeSession(body.sid);
1487
+ const uid = d && d.metadata && d.metadata.uid;
1488
+ if (!d || !d.url || uid !== idp.sub || d.status === "expired") return json(res, 400, { error: "Payment failed" });
 
 
 
 
 
1489
  json(res, 200, { url: d.url });
1490
  }
1491
 
1492
+ async function handleVipConfirm(req, res) {
1493
+ if (!payGate(req, res)) return;
1494
+ const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 4000, null);
1495
+ if (!idp || !googlePayUser(idp) || !uidOk(idp.sub)) return json(res, 401, { error: "login" });
1496
+ if (payLimited(idp.sub, clientIp(req))) {
1497
+ res.setHeader("Retry-After", "30");
1498
+ return json(res, 429, { error: "rate_limited" });
1499
+ }
1500
+ let body;
1501
+ try {
1502
+ body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
1503
+ } catch {
1504
+ return json(res, 400, { error: "body" });
1505
+ }
1506
+ const d = await stripeSession(body.sid);
1507
+ const uid = d && d.metadata && d.metadata.uid;
1508
+ if (!d || uid !== idp.sub || (d.client_reference_id && d.client_reference_id !== idp.sub)) {
1509
+ return json(res, 400, { error: "Payment failed", paid: false });
1510
+ }
1511
+ if (d.payment_status !== "paid") return json(res, 402, { error: "unpaid", paid: false });
1512
+ try { await fulfillPaid(d); } catch {}
1513
+ lvlCache.delete(idp.sub);
1514
+ let sub = null;
1515
+ try { sub = await rtdb("users/" + idp.sub + "/subscription", "GET"); } catch {}
1516
+ if (!vipActive(sub)) return json(res, 402, { error: "unpaid", paid: false });
1517
+ json(res, 200, { ok: true, paid: true, accessLevel: "subscribed", subscription: sub });
1518
+ }
1519
+
1520
  async function grantVip(uid, planKey) {
1521
+ const plan = PLANS[planKey];
1522
+ if (!plan || !uidOk(uid)) throw new Error("grant");
1523
  const now = Math.floor(Date.now() / 1000);
1524
  let start = now;
1525
  try {
1526
  const old = await rtdb("users/" + uid + "/subscription", "GET");
1527
+ const oldExp = vipExpirySec(old);
1528
+ if (vipActive(old) && oldExp > start) start = oldExp;
 
 
 
1529
  } catch {}
1530
  const sub = {
1531
  status: "active",
 
1542
 
1543
  function stripeOk(raw, sigHeader) {
1544
  if (!STRIPE_WH || !sigHeader) return false;
1545
+ const v1s = [];
1546
+ let t = "";
1547
  String(sigHeader).split(",").forEach((p) => {
1548
  const i = p.indexOf("=");
1549
+ if (i < 1) return;
1550
+ const k = p.slice(0, i);
1551
+ const v = p.slice(i + 1);
1552
+ if (k === "t") t = v;
1553
+ else if (k === "v1") v1s.push(v);
1554
  });
1555
+ if (!t || !v1s.length) return false;
 
 
1556
  const ts = Number(t);
1557
  if (!Number.isFinite(ts) || Math.abs(Date.now() / 1000 - ts) > 300) return false;
1558
+ const mac = crypto.createHmac("sha256", STRIPE_WH).update(Buffer.from(t + ".", "utf8")).update(raw).digest("hex");
1559
+ let ok = false;
1560
+ for (let i = 0; i < v1s.length; i++) ok = timingSafeEq(mac, v1s[i]) || ok;
1561
+ return ok;
1562
  }
1563
 
1564
  async function orderSeen(id) {
 
1574
  return false;
1575
  }
1576
 
1577
+ async function markOrder(id, uid, planKey) {
1578
  paidOrders.set(id, Date.now());
1579
  try {
1580
+ await rtdb("processed_orders/" + id, "PUT", {
1581
+ t: Math.floor(Date.now() / 1000),
1582
+ uid: uid,
1583
+ plan: planKey
1584
+ });
1585
  } catch {}
1586
  }
1587
 
1588
  async function fulfillPaid(ses) {
1589
+ if (!ses || ses.object !== "checkout.session") return false;
1590
+ if (ses.mode !== "payment" || ses.payment_status !== "paid") return false;
1591
+ if (ses.status === "expired") return false;
1592
+ if (STRIPE_KEY.indexOf("sk_live_") === 0 && ses.livemode !== true) return false;
1593
  const uid = ses.metadata && ses.metadata.uid;
1594
  const planKey = ses.metadata && ses.metadata.plan;
1595
  const plan = PLANS[planKey];
1596
+ if (!uidOk(uid) || !plan) return false;
1597
+ if (ses.client_reference_id && ses.client_reference_id !== uid) return false;
1598
+ if (Number(ses.amount_total) !== plan.amount) return false;
1599
+ if (String(ses.currency || "").toLowerCase() !== "usd") return false;
1600
  const sid = String(ses.id || "");
1601
+ if (!/^cs_[A-Za-z0-9_]+$/.test(sid)) return false;
1602
+ return withPayLock(sid, async () => {
1603
+ if (await orderSeen(sid)) return true;
1604
+ await grantVip(uid, planKey);
1605
+ await markOrder(sid, uid, planKey);
1606
+ return true;
1607
+ });
1608
  }
1609
 
1610
  async function handleStripeWebhook(req, res) {
1611
+ const rawBuf = await readBody(req);
1612
+ if (!stripeOk(rawBuf, req.headers["stripe-signature"])) {
1613
  res.writeHead(400);
1614
  return res.end();
1615
  }
1616
  let ev;
1617
+ try { ev = JSON.parse(rawBuf.toString("utf8")); } catch {
1618
  res.writeHead(400);
1619
  return res.end();
1620
  }
1621
  if (ev.type === "checkout.session.completed" || ev.type === "checkout.session.async_payment_succeeded") {
1622
+ const id = ev.data && ev.data.object && ev.data.object.id;
1623
+ try {
1624
+ const ses = await stripeSession(id);
1625
+ if (ses) await fulfillPaid(ses);
1626
+ } catch {}
1627
  }
1628
  json(res, 200, { ok: true });
1629
  }
 
1682
  try {
1683
  if (url.pathname === "/") return handleHome(req, res);
1684
  if (url.pathname === "/health") return handleHealth(res);
1685
+ if (url.pathname === "/public/brand.png" && (req.method === "GET" || req.method === "HEAD")) return handleBrand(req, res);
1686
  if (url.pathname === "/public/bootstrap") return handleBootstrap(req, res, url);
1687
  if (url.pathname === "/generate-token" && req.method === "GET") return handleGenerate(req, res, url);
1688
  if (url.pathname === "/vip/status" && req.method === "GET") return handleVipStatus(req, res);
1689
  if (url.pathname === "/vip/start" && req.method === "POST") return handleVipStart(req, res);
1690
  if (url.pathname === "/vip/go" && req.method === "POST") return handleVipGo(req, res);
1691
+ if (url.pathname === "/vip/confirm" && req.method === "POST") return handleVipConfirm(req, res);
1692
  if (url.pathname === "/vip/stripe" && req.method === "POST") return handleStripeWebhook(req, res);
1693
  const sm = /^\/stream\/(\d+)(?:\.(?:mp4|m4v|webm|ogv|ogg))?$/.exec(url.pathname);
1694
  if (sm && (req.method === "GET" || req.method === "HEAD")) return handleStream(req, res, url, Number(sm[1]));