DUBLK 2000 Admin commited on
Commit
ab731a2
·
1 Parent(s): 0afcd11

Fix payment idempotency, key separation, origin binding, egress budget

Browse files
Files changed (1) hide show
  1. server.js +0 -344
server.js CHANGED
@@ -56,12 +56,6 @@ const UID_TITLE_MAX = 48;
56
  const TITLE_PIPE_MAX = 15000;
57
  const GLOBAL_PIPE_MAX = 15000;
58
  const DISK_SLICE_DIR = "/tmp/dlk_slice";
59
- const HLS_DIR = "/tmp/dlk_hls";
60
- const HLS_SRC_DIR = "/tmp/dlk_src";
61
- const HLS_SEG_SEC = 6;
62
- const HLS_IP_MAX = 24;
63
- const HLS_BUCKET = 240;
64
- const hlsSegCount = new Map();
65
  const DISK_MAX_BYTES = 8 * 1024 * 1024 * 1024;
66
  const DISK_FREE_MIN_BYTES = 3 * 1024 * 1024 * 1024;
67
  const HOT_BYTES_MAX = Math.min(1536 * MB, Math.max(512 * MB, Math.floor(RAM_BYTES * 0.1)));
@@ -100,7 +94,6 @@ const deriveKey = STREAM_SECRET
100
  : null;
101
  const aesKey = deriveKey ? deriveKey("aes-256-gcm-ticket") : null;
102
  const hmacKey = deriveKey ? deriveKey("hmac-sha256-ticket") : null;
103
- const hlsKey = deriveKey ? deriveKey("hls-sig-v1") : null;
104
  const adminKey = deriveKey ? deriveKey("admin-api-v1").toString("hex") : "";
105
  const ADMIN_KEY_ENV = String(process.env.ADMIN_API_KEY || "");
106
  const ADMIN_KEY = ADMIN_KEY_ENV || adminKey;
@@ -1410,342 +1403,9 @@ class SingleFlight {
1410
  }
1411
  }
1412
  const chunkFlight = new SingleFlight();
1413
- const hlsFlight = new SingleFlight();
1414
- const hlsIpMap = new Map();
1415
  let diskBytesUsed = 0;
1416
  let ffmpegReady = null;
1417
 
1418
- function takeHlsIp(ip) {
1419
- const n = (hlsIpMap.get(ip) || 0) + 1;
1420
- if (n > HLS_IP_MAX) return false;
1421
- hlsIpMap.set(ip, n);
1422
- return true;
1423
- }
1424
-
1425
- function freeHlsIp(ip) {
1426
- const n = (hlsIpMap.get(ip) || 1) - 1;
1427
- if (n <= 0) hlsIpMap.delete(ip);
1428
- else hlsIpMap.set(ip, n);
1429
- }
1430
-
1431
- function hlsBucket() {
1432
- return Math.ceil(Date.now() / 1000 / HLS_BUCKET) * HLS_BUCKET;
1433
- }
1434
-
1435
- function hlsSig(msgId, hash, lvl, bucket) {
1436
- if (!hlsKey) return "";
1437
- return crypto
1438
- .createHmac("sha256", hlsKey)
1439
- .update("hls:" + String(msgId) + ":" + String(hash) + ":" + String(lvl) + ":" + String(bucket))
1440
- .digest("hex")
1441
- .slice(0, 24);
1442
- }
1443
-
1444
- function hlsSigOk(msgId, hash, lvl, bucket, sig) {
1445
- if (!sig || !hash || !lvl) return false;
1446
- const b = Number(bucket);
1447
- if (!Number.isFinite(b) || b < Math.floor(Date.now() / 1000) - 30) return false;
1448
- if (b > Math.floor(Date.now() / 1000) + HLS_BUCKET + 60) return false;
1449
- const want = hlsSig(msgId, hash, lvl, b);
1450
- return want && timingSafeEq(want, String(sig));
1451
- }
1452
-
1453
- function hlsPackDir(msgId) {
1454
- return path.join(HLS_DIR, String(msgId));
1455
- }
1456
-
1457
- function hlsIndexPath(msgId) {
1458
- return path.join(hlsPackDir(msgId), "index.m3u8");
1459
- }
1460
-
1461
- async function hasFfmpeg() {
1462
- if (ffmpegReady != null) return ffmpegReady;
1463
- ffmpegReady = await new Promise((resolve) => {
1464
- const p = spawn("ffmpeg", ["-version"], { stdio: "ignore" });
1465
- p.on("error", () => resolve(false));
1466
- p.on("exit", (c) => resolve(c === 0));
1467
- });
1468
- return ffmpegReady;
1469
- }
1470
-
1471
- async function fileExists(p) {
1472
- try {
1473
- await fs.promises.access(p, fs.constants.R_OK);
1474
- return true;
1475
- } catch {
1476
- return false;
1477
- }
1478
- }
1479
-
1480
- async function materializeSource(bot, rec, msgId) {
1481
- const dest = path.join(HLS_SRC_DIR, String(msgId) + ".mp4");
1482
- try {
1483
- const st = await fs.promises.stat(dest);
1484
- if (st.size === rec.size && st.size > 1024) return dest;
1485
- } catch { }
1486
- return hlsFlight.do("src:" + msgId, async () => {
1487
- try {
1488
- const st = await fs.promises.stat(dest);
1489
- if (st.size === rec.size && st.size > 1024) return dest;
1490
- } catch { }
1491
- await fs.promises.mkdir(HLS_SRC_DIR, { recursive: true });
1492
- const part = dest + ".part";
1493
- try { await fs.promises.unlink(part); } catch { }
1494
- const ws = fs.createWriteStream(part);
1495
- let written = 0;
1496
- try {
1497
- const it = bot.client.iterDownload(rec.loc || rec.doc, {
1498
- offset: 0,
1499
- limit: rec.size,
1500
- requestSize: CHUNK_SIZE,
1501
- dcId: rec.dcId
1502
- });
1503
- for await (const chunk of it) {
1504
- const buf = Buffer.from(chunk);
1505
- written += buf.length;
1506
- if (!ws.write(buf)) await new Promise((r) => ws.once("drain", r));
1507
- }
1508
- await new Promise((resolve, reject) => {
1509
- ws.on("error", reject);
1510
- ws.end(() => resolve());
1511
- });
1512
- if (written < Math.min(rec.size, 1024)) throw new Error("short");
1513
- await fs.promises.rename(part, dest);
1514
- diskBytesUsed += written;
1515
- if (diskBytesUsed > DISK_MAX_BYTES) trimDiskCache().catch(() => { });
1516
- return dest;
1517
- } catch (e) {
1518
- try { ws.destroy(); } catch { }
1519
- try { await fs.promises.unlink(part); } catch { }
1520
- throw e;
1521
- }
1522
- });
1523
- }
1524
-
1525
- function runFfmpeg(args) {
1526
- return new Promise((resolve, reject) => {
1527
- const p = spawn("ffmpeg", args, { stdio: ["ignore", "ignore", "pipe"] });
1528
- let err = "";
1529
- p.stderr.on("data", (d) => {
1530
- err += d.toString();
1531
- if (err.length > 8000) err = err.slice(-4000);
1532
- });
1533
- p.on("error", reject);
1534
- p.on("exit", (c) => {
1535
- if (c === 0) resolve();
1536
- else reject(new Error("ffmpeg " + c + " " + err.slice(-400)));
1537
- });
1538
- });
1539
- }
1540
-
1541
- async function ensureHlsPack(bot, rec, msgId) {
1542
- const index = hlsIndexPath(msgId);
1543
- if (await fileExists(index)) {
1544
- const raw = await fs.promises.readFile(index, "utf8");
1545
- if (raw.indexOf("#EXTINF") >= 0) return hlsPackDir(msgId);
1546
- }
1547
- if (!(await hasFfmpeg())) throw new Error("no_ffmpeg");
1548
- return hlsFlight.do("pack:" + msgId, async () => {
1549
- if (await fileExists(index)) {
1550
- const raw = await fs.promises.readFile(index, "utf8");
1551
- if (raw.indexOf("#EXTINF") >= 0) return hlsPackDir(msgId);
1552
- }
1553
- const src = await materializeSource(bot, rec, msgId);
1554
- const dir = hlsPackDir(msgId);
1555
- await fs.promises.mkdir(dir, { recursive: true });
1556
- const segPattern = path.join(dir, "seg_%05d.ts");
1557
- const outIndex = path.join(dir, "index.m3u8");
1558
- await runFfmpeg([
1559
- "-y",
1560
- "-i", src,
1561
- "-map", "0:v:0",
1562
- "-map", "0:a:0?",
1563
- "-c", "copy",
1564
- "-bsf:v", "h264_mp4toannexb",
1565
- "-f", "hls",
1566
- "-hls_time", String(HLS_SEG_SEC),
1567
- "-hls_playlist_type", "vod",
1568
- "-hls_flags", "independent_segments",
1569
- "-hls_segment_filename", segPattern,
1570
- outIndex
1571
- ]);
1572
- if (!(await fileExists(outIndex))) throw new Error("hls_missing");
1573
- return dir;
1574
- });
1575
- }
1576
-
1577
- function rewriteHlsPlaylist(raw, msgId, q) {
1578
- const lines = String(raw || "").split(/\r?\n/);
1579
- const out = [];
1580
- let inf = 0;
1581
- let total = 0;
1582
- for (const line of lines) {
1583
- if (line.charAt(0) !== "#" && line.trim()) total += 1;
1584
- }
1585
- const pct = lvlPct(q.lvl);
1586
- const maxSeg = pct >= 100 ? total : Math.max(1, Math.floor(total * (pct / 100)));
1587
- hlsSegCount.set(String(msgId), total);
1588
- let seen = 0;
1589
- for (let i = 0; i < lines.length; i++) {
1590
- const line = lines[i];
1591
- if (line.indexOf("#EXTINF") === 0) {
1592
- if (seen >= maxSeg) break;
1593
- out.push(line);
1594
- inf = 1;
1595
- continue;
1596
- }
1597
- if (inf && line.charAt(0) !== "#" && line.trim()) {
1598
- const name = path.basename(line.trim());
1599
- const m = /seg_(\d+)\.ts/i.exec(name);
1600
- const n = m ? Number(m[1]) : seen;
1601
- out.push(
1602
- "/hls/" + msgId + "/seg/" + n + ".ts?h=" + encodeURIComponent(q.hash)
1603
- + "&l=" + encodeURIComponent(q.lvl)
1604
- + "&e=" + encodeURIComponent(String(q.bucket))
1605
- + "&s=" + encodeURIComponent(q.sig)
1606
- );
1607
- seen += 1;
1608
- inf = 0;
1609
- continue;
1610
- }
1611
- if (line.indexOf("#EXT-X-ENDLIST") === 0) {
1612
- if (seen < total) out.push("#EXT-X-ENDLIST");
1613
- else out.push(line);
1614
- continue;
1615
- }
1616
- if (!inf) out.push(line);
1617
- }
1618
- if (out[out.length - 1] !== "#EXT-X-ENDLIST") out.push("#EXT-X-ENDLIST");
1619
- return out.join("\n") + "\n";
1620
- }
1621
-
1622
- function hlsQuery(url) {
1623
- return {
1624
- hash: String(url.searchParams.get("h") || "").toLowerCase(),
1625
- lvl: String(url.searchParams.get("l") || ""),
1626
- bucket: Number(url.searchParams.get("e") || 0),
1627
- sig: String(url.searchParams.get("s") || "")
1628
- };
1629
- }
1630
-
1631
- async function handleHlsIndex(req, res, url, msgId) {
1632
- if (!streamDestOk(req) || !fromBlog(req)) {
1633
- res.writeHead(403);
1634
- return res.end();
1635
- }
1636
- const q = hlsQuery(url);
1637
- if (!/^[0-9a-f]{6}$/.test(q.hash) || !hlsSigOk(msgId, q.hash, q.lvl, q.bucket, q.sig)) {
1638
- res.writeHead(403);
1639
- return res.end();
1640
- }
1641
- const ip = clientIp(req);
1642
- if (!takeHlsIp(ip)) {
1643
- res.setHeader("Retry-After", "1");
1644
- res.writeHead(429);
1645
- return res.end();
1646
- }
1647
- try {
1648
- if (!(await fileExists(hlsIndexPath(msgId)))) {
1649
- res.writeHead(404);
1650
- return res.end();
1651
- }
1652
- const raw = await fs.promises.readFile(hlsIndexPath(msgId), "utf8");
1653
- const body = rewriteHlsPlaylist(raw, msgId, q);
1654
- const headers = Object.assign(streamLock(), {
1655
- "Content-Type": "application/vnd.apple.mpegurl",
1656
- "Cache-Control": "private, max-age=30",
1657
- "Content-Length": Buffer.byteLength(body)
1658
- });
1659
- res.writeHead(200, headers);
1660
- res.end(body);
1661
- } catch {
1662
- if (!res.headersSent) {
1663
- res.writeHead(502);
1664
- res.end();
1665
- }
1666
- } finally {
1667
- freeHlsIp(ip);
1668
- }
1669
- }
1670
-
1671
- async function handleHlsSeg(req, res, url, msgId, segN) {
1672
- if (!streamDestOk(req)) {
1673
- res.writeHead(403);
1674
- return res.end();
1675
- }
1676
- const q = hlsQuery(url);
1677
- if (!/^[0-9a-f]{6}$/.test(q.hash) || !hlsSigOk(msgId, q.hash, q.lvl, q.bucket, q.sig)) {
1678
- res.writeHead(403);
1679
- return res.end();
1680
- }
1681
- if (!Number.isInteger(segN) || segN < 0 || segN > 100000) {
1682
- res.writeHead(400);
1683
- return res.end();
1684
- }
1685
- const pct = lvlPct(q.lvl);
1686
- if (pct < 100) {
1687
- let total = hlsSegCount.get(String(msgId));
1688
- if (!total) {
1689
- try {
1690
- const raw = await fs.promises.readFile(hlsIndexPath(msgId), "utf8");
1691
- total = String(raw).split(/\r?\n/).filter((ln) => ln && ln.charAt(0) !== "#" && ln.trim()).length;
1692
- if (total) hlsSegCount.set(String(msgId), total);
1693
- } catch {
1694
- total = 0;
1695
- }
1696
- }
1697
- const maxSeg = total > 0 ? Math.max(1, Math.floor(total * (pct / 100))) : 1;
1698
- if (segN >= maxSeg) {
1699
- res.writeHead(403);
1700
- return res.end();
1701
- }
1702
- }
1703
- const ip = clientIp(req);
1704
- if (!takeHlsIp(ip)) {
1705
- res.setHeader("Retry-After", "1");
1706
- res.writeHead(429);
1707
- return res.end();
1708
- }
1709
- try {
1710
- const file = path.join(hlsPackDir(msgId), "seg_" + String(segN).padStart(5, "0") + ".ts");
1711
- if (!(await fileExists(file))) {
1712
- res.writeHead(404);
1713
- return res.end();
1714
- }
1715
- const st = await fs.promises.stat(file);
1716
- const headers = Object.assign(streamLock(), {
1717
- "Content-Type": "video/mp2t",
1718
- "Accept-Ranges": "bytes",
1719
- "Cache-Control": "private, no-store, no-transform",
1720
- "Content-Length": String(st.size)
1721
- });
1722
- if (req.method === "HEAD") {
1723
- res.writeHead(200, headers);
1724
- return res.end();
1725
- }
1726
- res.writeHead(200, headers);
1727
- await finished(fs.createReadStream(file).pipe(res));
1728
- } catch {
1729
- if (!res.headersSent) {
1730
- res.writeHead(502);
1731
- res.end();
1732
- } else if (!res.writableEnded) {
1733
- try { res.end(); } catch { }
1734
- }
1735
- } finally {
1736
- freeHlsIp(ip);
1737
- }
1738
- }
1739
-
1740
- function buildHlsUrl(host, msgId, hash, lvl) {
1741
- const bucket = hlsBucket();
1742
- const sig = hlsSig(msgId, hash, lvl, bucket);
1743
- if (!sig) return "";
1744
- return host + "/hls/" + msgId + "/index.m3u8?h=" + encodeURIComponent(hash)
1745
- + "&l=" + encodeURIComponent(lvl)
1746
- + "&e=" + encodeURIComponent(String(bucket))
1747
- + "&s=" + encodeURIComponent(sig);
1748
- }
1749
 
1750
  const SLICE_MEM_MAX = Math.max(1024, Math.min(6144, Math.floor((RAM_BYTES * 0.38) / MB)));
1751
  const sliceMemCache = new Map();
@@ -3197,10 +2857,6 @@ async function onReq(req, res) {
3197
  if (url.pathname === "/vip/go" && req.method === "POST") return handleVipGo(req, res);
3198
  if (url.pathname === "/vip/confirm" && req.method === "POST") return handleVipConfirm(req, res);
3199
  if (url.pathname === "/vip/stripe" && req.method === "POST") return handleStripeWebhook(req, res);
3200
- const hm = /^\/hls\/(\d+)\/index\.m3u8$/.exec(url.pathname);
3201
- if (hm && (req.method === "GET" || req.method === "HEAD")) return handleHlsIndex(req, res, url, Number(hm[1]));
3202
- const hs = /^\/hls\/(\d+)\/seg\/(\d+)\.ts$/.exec(url.pathname);
3203
- if (hs && (req.method === "GET" || req.method === "HEAD")) return handleHlsSeg(req, res, url, Number(hs[1]), Number(hs[2]));
3204
  res.writeHead(404);
3205
  res.end();
3206
  } catch (e) {
 
56
  const TITLE_PIPE_MAX = 15000;
57
  const GLOBAL_PIPE_MAX = 15000;
58
  const DISK_SLICE_DIR = "/tmp/dlk_slice";
 
 
 
 
 
 
59
  const DISK_MAX_BYTES = 8 * 1024 * 1024 * 1024;
60
  const DISK_FREE_MIN_BYTES = 3 * 1024 * 1024 * 1024;
61
  const HOT_BYTES_MAX = Math.min(1536 * MB, Math.max(512 * MB, Math.floor(RAM_BYTES * 0.1)));
 
94
  : null;
95
  const aesKey = deriveKey ? deriveKey("aes-256-gcm-ticket") : null;
96
  const hmacKey = deriveKey ? deriveKey("hmac-sha256-ticket") : null;
 
97
  const adminKey = deriveKey ? deriveKey("admin-api-v1").toString("hex") : "";
98
  const ADMIN_KEY_ENV = String(process.env.ADMIN_API_KEY || "");
99
  const ADMIN_KEY = ADMIN_KEY_ENV || adminKey;
 
1403
  }
1404
  }
1405
  const chunkFlight = new SingleFlight();
 
 
1406
  let diskBytesUsed = 0;
1407
  let ffmpegReady = null;
1408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1409
 
1410
  const SLICE_MEM_MAX = Math.max(1024, Math.min(6144, Math.floor((RAM_BYTES * 0.38) / MB)));
1411
  const sliceMemCache = new Map();
 
2857
  if (url.pathname === "/vip/go" && req.method === "POST") return handleVipGo(req, res);
2858
  if (url.pathname === "/vip/confirm" && req.method === "POST") return handleVipConfirm(req, res);
2859
  if (url.pathname === "/vip/stripe" && req.method === "POST") return handleStripeWebhook(req, res);
 
 
 
 
2860
  res.writeHead(404);
2861
  res.end();
2862
  } catch (e) {