JOHN SILLVESTOR commited on
Commit
be13ffd
·
verified ·
1 Parent(s): 7901d75

dublk stream node

Browse files
Files changed (6) hide show
  1. .dockerignore +3 -0
  2. Dockerfile +11 -7
  3. README.md +4 -6
  4. package-lock.json +144 -0
  5. package.json +12 -0
  6. server.js +638 -0
.dockerignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ node_modules
2
+ .venv
3
+ *.md.bak
Dockerfile CHANGED
@@ -1,8 +1,12 @@
1
- FROM python:3.12-slim
2
- RUN useradd -m -u 1000 user
3
- USER user
4
- ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH
5
- WORKDIR /home/user/app
6
- COPY --chown=user . /home/user/app
 
 
 
 
7
  EXPOSE 7860
8
- CMD ["python", "-m", "http.server", "7860", "--bind", "0.0.0.0"]
 
1
+ FROM node:22-bookworm-slim
2
+ WORKDIR /app
3
+ COPY package.json ./
4
+ RUN npm install --omit=dev --no-audit --no-fund
5
+ COPY server.js ./
6
+ RUN chown -R node:node /app
7
+ USER node
8
+ ENV HOME=/home/node
9
+ ENV NODE_ENV=production
10
+ ENV PORT=7860
11
  EXPOSE 7860
12
+ CMD ["node", "server.js"]
README.md CHANGED
@@ -1,11 +1,9 @@
1
  ---
2
- title: dublk-s3
3
- emoji: 🐳
4
- colorFrom: blue
5
- colorTo: green
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
  ---
10
-
11
- dublk-s3
 
1
  ---
2
+ title: dublk-node
3
+ emoji: 🎬
4
+ colorFrom: red
5
+ colorTo: yellow
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
  ---
 
 
package-lock.json ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "dublk-node",
3
+ "lockfileVersion": 3,
4
+ "requires": true,
5
+ "packages": {
6
+ "": {
7
+ "name": "dublk-node",
8
+ "dependencies": {
9
+ "big-integer": "1.6.52",
10
+ "teleproto": "1.228.5"
11
+ },
12
+ "engines": {
13
+ "node": ">=22"
14
+ }
15
+ },
16
+ "node_modules/big-integer": {
17
+ "version": "1.6.52",
18
+ "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz",
19
+ "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==",
20
+ "license": "Unlicense",
21
+ "engines": {
22
+ "node": ">=0.6"
23
+ }
24
+ },
25
+ "node_modules/graceful-fs": {
26
+ "version": "4.2.11",
27
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
28
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
29
+ "license": "ISC"
30
+ },
31
+ "node_modules/imurmurhash": {
32
+ "version": "0.1.4",
33
+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
34
+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
35
+ "license": "MIT",
36
+ "engines": {
37
+ "node": ">=0.8.19"
38
+ }
39
+ },
40
+ "node_modules/ip-address": {
41
+ "version": "10.5.0",
42
+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.5.0.tgz",
43
+ "integrity": "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g==",
44
+ "license": "MIT",
45
+ "engines": {
46
+ "node": ">= 12"
47
+ }
48
+ },
49
+ "node_modules/mime": {
50
+ "version": "3.0.0",
51
+ "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",
52
+ "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==",
53
+ "license": "MIT",
54
+ "bin": {
55
+ "mime": "cli.js"
56
+ },
57
+ "engines": {
58
+ "node": ">=10.0.0"
59
+ }
60
+ },
61
+ "node_modules/node-localstorage": {
62
+ "version": "2.2.1",
63
+ "resolved": "https://registry.npmjs.org/node-localstorage/-/node-localstorage-2.2.1.tgz",
64
+ "integrity": "sha512-vv8fJuOUCCvSPjDjBLlMqYMHob4aGjkmrkaE42/mZr0VT+ZAU10jRF8oTnX9+pgU9/vYJ8P7YT3Vd6ajkmzSCw==",
65
+ "license": "MIT",
66
+ "dependencies": {
67
+ "write-file-atomic": "^1.1.4"
68
+ },
69
+ "engines": {
70
+ "node": ">=0.12"
71
+ }
72
+ },
73
+ "node_modules/slide": {
74
+ "version": "1.1.6",
75
+ "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz",
76
+ "integrity": "sha512-NwrtjCg+lZoqhFU8fOwl4ay2ei8PaqCBOUV3/ektPY9trO1yQ1oXEfmHAhKArUVUr/hOHvy5f6AdP17dCM0zMw==",
77
+ "license": "ISC",
78
+ "engines": {
79
+ "node": "*"
80
+ }
81
+ },
82
+ "node_modules/smart-buffer": {
83
+ "version": "4.2.0",
84
+ "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
85
+ "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
86
+ "license": "MIT",
87
+ "engines": {
88
+ "node": ">= 6.0.0",
89
+ "npm": ">= 3.0.0"
90
+ }
91
+ },
92
+ "node_modules/socks": {
93
+ "version": "2.8.9",
94
+ "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.9.tgz",
95
+ "integrity": "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==",
96
+ "license": "MIT",
97
+ "dependencies": {
98
+ "ip-address": "^10.1.1",
99
+ "smart-buffer": "^4.2.0"
100
+ },
101
+ "engines": {
102
+ "node": ">= 10.0.0",
103
+ "npm": ">= 3.0.0"
104
+ }
105
+ },
106
+ "node_modules/store2": {
107
+ "version": "2.14.4",
108
+ "resolved": "https://registry.npmjs.org/store2/-/store2-2.14.4.tgz",
109
+ "integrity": "sha512-srTItn1GOvyvOycgxjAnPA63FZNwy0PTyUBFMHRM+hVFltAeoh0LmNBz9SZqUS9mMqGk8rfyWyXn3GH5ReJ8Zw==",
110
+ "license": "MIT"
111
+ },
112
+ "node_modules/teleproto": {
113
+ "version": "1.228.5",
114
+ "resolved": "https://registry.npmjs.org/teleproto/-/teleproto-1.228.5.tgz",
115
+ "integrity": "sha512-NMBFB4oB+0mjJIPVqdLd3wAaU7kf5dw7frrYdnnXM38DSdbnN36Dao6Ae1xNZR9NICiefbfJqM8yDijOPqE8MA==",
116
+ "license": "MIT",
117
+ "dependencies": {
118
+ "big-integer": "^1.6.48",
119
+ "mime": "^3.0.0",
120
+ "node-localstorage": "^2.2.1",
121
+ "socks": "^2.6.2",
122
+ "store2": "^2.13.0"
123
+ },
124
+ "engines": {
125
+ "node": ">=18"
126
+ },
127
+ "funding": {
128
+ "type": "github",
129
+ "url": "https://github.com/sponsors/sanyok12345"
130
+ }
131
+ },
132
+ "node_modules/write-file-atomic": {
133
+ "version": "1.3.4",
134
+ "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-1.3.4.tgz",
135
+ "integrity": "sha512-SdrHoC/yVBPpV0Xq/mUZQIpW2sWXAShb/V4pomcJXh92RuaO+f3UTWItiR3Px+pLnV2PvC2/bfn5cwr5X6Vfxw==",
136
+ "license": "ISC",
137
+ "dependencies": {
138
+ "graceful-fs": "^4.1.11",
139
+ "imurmurhash": "^0.1.4",
140
+ "slide": "^1.1.5"
141
+ }
142
+ }
143
+ }
144
+ }
package.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "dublk-node",
3
+ "private": true,
4
+ "type": "commonjs",
5
+ "engines": {
6
+ "node": ">=22"
7
+ },
8
+ "dependencies": {
9
+ "big-integer": "1.6.52",
10
+ "teleproto": "1.228.5"
11
+ }
12
+ }
server.js ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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");
7
+ const bigInt = require("big-integer");
8
+
9
+ const PORT = Number(process.env.PORT || 7860);
10
+ const ORIGIN = process.env.ALLOWED_ORIGIN || "https://dublk2000.blogspot.com";
11
+ const CHANNEL_ID = process.env.TELEGRAM_CHANNEL_ID || "-1003812446346";
12
+ const API_ID = Number(process.env.TELEGRAM_API_ID || process.env.API_ID || 0);
13
+ const API_HASH = process.env.TELEGRAM_API_HASH || process.env.API_HASH || "";
14
+ const STREAM_SECRET = process.env.STREAM_SECRET || process.env.SECRET_KEY || "";
15
+ const ROLE = (process.env.NODE_ROLE || "stream").toLowerCase();
16
+ const HASH_LEN = 6;
17
+ const TOKEN_TTL = 900;
18
+ const CHUNK = 512 * 1024;
19
+ const MIN_ALIGN = 4096;
20
+ const BOT_MAX = 3;
21
+ const FB_PROJECT = process.env.FIREBASE_PROJECT_ID || "dublk2000-auth";
22
+ const FB_DB = (process.env.FIREBASE_DB_URL || "https://dublk2000-auth-default-rtdb.firebaseio.com/").replace(/\/?$/, "/");
23
+ const FB_SECRET = process.env.FIREBASE_DB_SECRET || "";
24
+ const STRIPE_KEY = process.env.STRIPE_SECRET_KEY || "";
25
+ const STRIPE_WH = process.env.STRIPE_WEBHOOK_SECRET || "";
26
+ const SPACE_URLS = (process.env.SPACE_URLS || [
27
+ "https://dublk2000-dublk-s1.hf.space",
28
+ "https://dublk2000-dublk-s2.hf.space",
29
+ "https://activenodes-dublk-s3.hf.space",
30
+ "https://activenodes-dublk-s4.hf.space",
31
+ "https://activenodes-dublk-s5.hf.space"
32
+ ].join(",")).split(",").map((s) => s.trim()).filter(Boolean);
33
+
34
+ const FB_WEB = {
35
+ apiKey: process.env.FIREBASE_API_KEY || "AIzaSyCho6yF39MqCrWitmDqXnuBtbP6aANQ8EA",
36
+ authDomain: process.env.FIREBASE_AUTH_DOMAIN || "dublk2000-auth.firebaseapp.com",
37
+ databaseURL: process.env.FIREBASE_DB_URL || "https://dublk2000-auth-default-rtdb.firebaseio.com/",
38
+ projectId: FB_PROJECT,
39
+ storageBucket: process.env.FIREBASE_STORAGE_BUCKET || "dublk2000-auth.firebasestorage.app",
40
+ messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID || "475299842360",
41
+ appId: process.env.FIREBASE_APP_ID || "1:475299842360:web:7f0c4d346a7affe8e3d9cd",
42
+ measurementId: process.env.FIREBASE_MEASUREMENT_ID || "G-B8RYS5PYSQ"
43
+ };
44
+
45
+ const PLANS = {
46
+ day: { amount: 99, label: "1 Day VIP", sec: 86400, price: "0.99" },
47
+ week: { amount: 199, label: "1 Week VIP", sec: 604800, price: "1.99" },
48
+ month: { amount: 599, label: "1 Month VIP", sec: 2592000, price: "5.99" }
49
+ };
50
+
51
+ const aesKey = STREAM_SECRET
52
+ ? crypto.hkdfSync("sha256", Buffer.from(STREAM_SECRET, "utf8"), Buffer.from("dublk2000"), Buffer.from("aes-256-gcm-ticket"), 32)
53
+ : null;
54
+ const hmacKey = STREAM_SECRET
55
+ ? crypto.hkdfSync("sha256", Buffer.from(STREAM_SECRET, "utf8"), Buffer.from("dublk2000"), Buffer.from("hmac-sha256-ticket"), 32)
56
+ : null;
57
+
58
+ const bots = [];
59
+ const fileCache = new Map();
60
+ const rateMap = new Map();
61
+ let fbKeys = { certs: null, exp: 0 };
62
+ let rr = 0;
63
+
64
+ function timingSafeEq(a, b) {
65
+ const x = Buffer.from(String(a));
66
+ const y = Buffer.from(String(b));
67
+ if (x.length !== y.length) return false;
68
+ return crypto.timingSafeEqual(x, y);
69
+ }
70
+
71
+ function packHash(name, size, mime, id) {
72
+ return crypto.createHash("md5")
73
+ .update(String(name || ""))
74
+ .update(String(size || 0))
75
+ .update(String(mime || ""))
76
+ .update(String(id || 0))
77
+ .digest("hex")
78
+ .slice(0, HASH_LEN);
79
+ }
80
+
81
+ function sealTicket(obj) {
82
+ if (!aesKey || !hmacKey) throw new Error("misconfigured");
83
+ const iv = crypto.randomBytes(12);
84
+ const cipher = crypto.createCipheriv("aes-256-gcm", aesKey, iv);
85
+ const pt = Buffer.from(JSON.stringify(obj), "utf8");
86
+ const ct = Buffer.concat([cipher.update(pt), cipher.final()]);
87
+ const tag = cipher.getAuthTag();
88
+ const blob = Buffer.concat([iv, ct, tag]);
89
+ const mac = crypto.createHmac("sha256", hmacKey).update(blob).digest();
90
+ return Buffer.concat([blob, mac]).toString("hex");
91
+ }
92
+
93
+ function openTicket(hex) {
94
+ if (!aesKey || !hmacKey) return null;
95
+ if (!/^[0-9a-f]+$/i.test(hex) || hex.length < 120) return null;
96
+ const raw = Buffer.from(hex, "hex");
97
+ if (raw.length < 12 + 16 + 32) return null;
98
+ const blob = raw.subarray(0, raw.length - 32);
99
+ const mac = raw.subarray(raw.length - 32);
100
+ const expect = crypto.createHmac("sha256", hmacKey).update(blob).digest();
101
+ if (!crypto.timingSafeEqual(mac, expect)) return null;
102
+ const iv = blob.subarray(0, 12);
103
+ const tag = blob.subarray(blob.length - 16);
104
+ const ct = blob.subarray(12, blob.length - 16);
105
+ try {
106
+ const dec = crypto.createDecipheriv("aes-256-gcm", aesKey, iv);
107
+ dec.setAuthTag(tag);
108
+ const pt = Buffer.concat([dec.update(ct), dec.final()]).toString("utf8");
109
+ return JSON.parse(pt);
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+
115
+ function cors(req, res) {
116
+ const o = req.headers.origin || "";
117
+ const allow = o === ORIGIN || o.endsWith(".blogspot.com") && o.startsWith("https://");
118
+ res.setHeader("Access-Control-Allow-Origin", allow ? o : ORIGIN);
119
+ res.setHeader("Vary", "Origin");
120
+ res.setHeader("Access-Control-Allow-Methods", "GET,POST,HEAD,OPTIONS");
121
+ res.setHeader("Access-Control-Allow-Headers", "Authorization,Content-Type,Range");
122
+ res.setHeader("Access-Control-Expose-Headers", "Content-Range,Content-Length,Accept-Ranges,Content-Type");
123
+ res.setHeader("Access-Control-Max-Age", "86400");
124
+ res.setHeader("X-Content-Type-Options", "nosniff");
125
+ }
126
+
127
+ function json(res, code, body) {
128
+ const s = JSON.stringify(body);
129
+ res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
130
+ res.end(s);
131
+ }
132
+
133
+ function limited(ip) {
134
+ const now = Date.now();
135
+ const slot = Math.floor(now / 60000);
136
+ const key = ip + ":" + slot;
137
+ const n = (rateMap.get(key) || 0) + 1;
138
+ rateMap.set(key, n);
139
+ if (rateMap.size > 4000) {
140
+ for (const k of rateMap.keys()) {
141
+ if (!k.endsWith(":" + slot) && !k.endsWith(":" + (slot - 1))) rateMap.delete(k);
142
+ }
143
+ }
144
+ return n > 40;
145
+ }
146
+
147
+ async function googleCerts() {
148
+ if (fbKeys.certs && Date.now() < fbKeys.exp) return fbKeys.certs;
149
+ const r = await fetch("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com");
150
+ if (!r.ok) throw new Error("certs");
151
+ const certs = await r.json();
152
+ const cc = r.headers.get("cache-control") || "";
153
+ const m = /max-age=(\d+)/.exec(cc);
154
+ const age = m ? Number(m[1]) * 1000 : 3600000;
155
+ fbKeys = { certs, exp: Date.now() + Math.max(60000, age - 60000) };
156
+ return certs;
157
+ }
158
+
159
+ async function verifyIdToken(raw) {
160
+ if (!raw) return null;
161
+ const token = String(raw).replace(/^Bearer\s+/i, "").trim();
162
+ const parts = token.split(".");
163
+ if (parts.length !== 3) return null;
164
+ let header;
165
+ let payload;
166
+ try {
167
+ header = JSON.parse(Buffer.from(parts[0], "base64url").toString("utf8"));
168
+ payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
169
+ } catch {
170
+ return null;
171
+ }
172
+ if (header.alg !== "RS256" || !header.kid) return null;
173
+ const certs = await googleCerts();
174
+ const pem = certs[header.kid];
175
+ if (!pem) return null;
176
+ const ok = crypto.createVerify("SHA256").update(parts[0] + "." + parts[1]).verify(pem, parts[2], "base64url");
177
+ if (!ok) return null;
178
+ const now = Math.floor(Date.now() / 1000);
179
+ if (payload.exp <= now || payload.iat > now + 60) return null;
180
+ if (payload.aud !== FB_PROJECT) return null;
181
+ if (payload.iss !== "https://securetoken.google.com/" + FB_PROJECT) return null;
182
+ if (!payload.sub || payload.sub.length > 128) return null;
183
+ return payload;
184
+ }
185
+
186
+ async function rtdb(path, method, body) {
187
+ if (!FB_SECRET) throw new Error("db");
188
+ const url = FB_DB + path.replace(/^\//, "") + ".json?auth=" + encodeURIComponent(FB_SECRET);
189
+ const r = await fetch(url, {
190
+ method,
191
+ headers: body == null ? undefined : { "Content-Type": "application/json" },
192
+ body: body == null ? undefined : JSON.stringify(body)
193
+ });
194
+ if (!r.ok) throw new Error("db " + r.status);
195
+ const t = await r.text();
196
+ return t ? JSON.parse(t) : null;
197
+ }
198
+
199
+ function vipActive(sub) {
200
+ if (!sub || typeof sub !== "object") return false;
201
+ const now = Math.floor(Date.now() / 1000);
202
+ const exp = Number(sub.expiry || sub.expiresAt || 0);
203
+ if (exp > 1e11) {
204
+ if (exp <= Date.now()) return false;
205
+ } else if (exp && exp <= now) return false;
206
+ if (sub.status === "cancelled" || sub.status === "expired" || sub.status === "inactive") return false;
207
+ return sub.status === "active" || sub.status === "subscribed" || sub.status === "vip" || sub.active === true || !!exp;
208
+ }
209
+
210
+ async function accessLevel(uid) {
211
+ if (!uid) return "anonymous";
212
+ try {
213
+ const sub = await rtdb("users/" + uid + "/subscription", "GET");
214
+ if (vipActive(sub)) return "subscribed";
215
+ } catch {}
216
+ return "registered";
217
+ }
218
+
219
+ async function bumpQuota(id, lvl) {
220
+ if (lvl === "subscribed") return true;
221
+ const day = new Date().toISOString().slice(0, 10);
222
+ const path = "preview_quota/" + String(id).replace(/[.#$\[\]]/g, "_") + "/" + day;
223
+ let cur = 0;
224
+ try { cur = Number((await rtdb(path, "GET")) || 0); } catch { cur = 0; }
225
+ const cap = lvl === "registered" ? 12 : 6;
226
+ if (cur >= cap) return false;
227
+ try { await rtdb(path, "PUT", cur + 1); } catch {}
228
+ return true;
229
+ }
230
+
231
+ function pickBot() {
232
+ if (!bots.length) return null;
233
+ const live = bots.filter((b) => b.ready && b.load < BOT_MAX);
234
+ const pool = live.length ? live : bots.filter((b) => b.ready);
235
+ if (!pool.length) return null;
236
+ pool.sort((a, b) => a.load - b.load);
237
+ const b = pool[rr % pool.length];
238
+ rr++;
239
+ return b;
240
+ }
241
+
242
+ async function startBot(token, idx) {
243
+ const client = new TelegramClient(new StringSession(""), API_ID, API_HASH, {
244
+ connectionRetries: 8,
245
+ retryDelay: 1500,
246
+ autoReconnect: true,
247
+ useWSS: true,
248
+ maxConcurrentDownloads: 3
249
+ });
250
+ client.setLogLevel("error");
251
+ await client.start({ botAuthToken: token });
252
+ bots.push({ client, token, idx, ready: true, load: 0 });
253
+ }
254
+
255
+ async function fileFromMsg(bot, msgId) {
256
+ const key = String(msgId);
257
+ const hit = fileCache.get(key);
258
+ if (hit && Date.now() - hit.ts < 8 * 60 * 1000) return hit;
259
+ const msgs = await bot.client.getMessages(CHANNEL_ID, { ids: msgId });
260
+ const msg = msgs && msgs[0];
261
+ if (!msg || msg.deleted) throw new Error("missing");
262
+ const doc = msg.video || msg.document;
263
+ if (!doc) throw new Error("media");
264
+ let name = "video.mp4";
265
+ const attrs = doc.attributes || [];
266
+ for (const a of attrs) {
267
+ if (a && a.className === "DocumentAttributeFilename" && a.fileName) name = a.fileName;
268
+ }
269
+ const loc = new Api.InputDocumentFileLocation({
270
+ id: doc.id,
271
+ accessHash: doc.accessHash,
272
+ fileReference: doc.fileReference,
273
+ thumbSize: ""
274
+ });
275
+ const rec = {
276
+ loc,
277
+ size: Number(doc.size || 0),
278
+ mime: doc.mimeType || "video/mp4",
279
+ name,
280
+ id: String(doc.id),
281
+ hash: packHash(name, Number(doc.size || 0), doc.mimeType || "video/mp4", String(doc.id)),
282
+ dcId: doc.dcId,
283
+ ts: Date.now()
284
+ };
285
+ fileCache.set(key, rec);
286
+ return rec;
287
+ }
288
+
289
+ function parseRange(h, size) {
290
+ if (!h || !size) return { start: 0, end: size - 1, partial: false };
291
+ const m = /^bytes=(\d*)-(\d*)$/.exec(String(h).trim());
292
+ if (!m) return { start: 0, end: size - 1, partial: false };
293
+ let start = m[1] === "" ? size - Number(m[2] || 0) : Number(m[1]);
294
+ let end = m[2] === "" ? size - 1 : Number(m[2]);
295
+ if (!Number.isFinite(start) || start < 0) start = 0;
296
+ if (!Number.isFinite(end) || end >= size) end = size - 1;
297
+ if (start > end) start = 0;
298
+ return { start, end, partial: true };
299
+ }
300
+
301
+ async function pipeRange(bot, rec, start, end, res) {
302
+ const aligned = Math.floor(start / MIN_ALIGN) * MIN_ALIGN;
303
+ const skip = start - aligned;
304
+ let sent = 0;
305
+ const need = end - start + 1;
306
+ bot.load++;
307
+ try {
308
+ const it = bot.client.iterDownload({
309
+ file: rec.loc,
310
+ offset: bigInt(aligned),
311
+ requestSize: CHUNK,
312
+ fileSize: bigInt(rec.size),
313
+ dcId: rec.dcId
314
+ });
315
+ for await (const chunk of it) {
316
+ if (res.destroyed || res.writableEnded) break;
317
+ let buf = Buffer.from(chunk);
318
+ if (skip && sent === 0) {
319
+ if (buf.length <= skip) continue;
320
+ buf = buf.subarray(skip);
321
+ }
322
+ const left = need - sent;
323
+ if (buf.length > left) buf = buf.subarray(0, left);
324
+ if (!buf.length) continue;
325
+ const ok = res.write(buf);
326
+ sent += buf.length;
327
+ if (sent >= need) break;
328
+ if (!ok) await new Promise((r) => res.once("drain", r));
329
+ }
330
+ } finally {
331
+ bot.load = Math.max(0, bot.load - 1);
332
+ if (!res.writableEnded) res.end();
333
+ }
334
+ }
335
+
336
+ async function readBody(req) {
337
+ const chunks = [];
338
+ for await (const c of req) chunks.push(c);
339
+ return Buffer.concat(chunks);
340
+ }
341
+
342
+ async function handleGenerate(req, res, url) {
343
+ if (!aesKey) return json(res, 503, { error: "misconfigured" });
344
+ const ip = req.headers["x-forwarded-for"] ? String(req.headers["x-forwarded-for"]).split(",")[0].trim() : req.socket.remoteAddress || "0";
345
+ if (limited(ip)) return json(res, 429, { error: "rate_limited" });
346
+ const path = url.searchParams.get("path") || "";
347
+ const hash = (url.searchParams.get("hash") || "").toLowerCase();
348
+ const m = /\/stream\/(\d+)/.exec(path);
349
+ if (!m || !/^[0-9a-f]{6}$/.test(hash)) return json(res, 400, { error: "bad_request" });
350
+ const msgId = Number(m[1]);
351
+ let uid = null;
352
+ let lvl = "anonymous";
353
+ try {
354
+ const idp = await verifyIdToken(req.headers.authorization || "");
355
+ if (idp) {
356
+ uid = idp.sub;
357
+ lvl = await accessLevel(uid);
358
+ }
359
+ } catch {
360
+ lvl = "anonymous";
361
+ }
362
+ const qid = uid || "ip:" + ip;
363
+ if (!(await bumpQuota(qid, lvl))) return json(res, 403, { error: "preview limit" });
364
+ const bot = pickBot();
365
+ if (!bot) return json(res, 503, { error: "bots_offline" });
366
+ let rec;
367
+ try {
368
+ rec = await fileFromMsg(bot, msgId);
369
+ } catch (e) {
370
+ fileCache.delete(String(msgId));
371
+ return json(res, 400, { error: "file" });
372
+ }
373
+ const exp = Math.floor(Date.now() / 1000) + TOKEN_TTL;
374
+ const k = sealTicket({ m: msgId, h: hash, u: uid || "anon", l: lvl, e: exp, s: rec.size, n: rec.mime });
375
+ const host = "https://" + (req.headers.host || "localhost");
376
+ json(res, 200, {
377
+ url: host + "/stream/" + msgId + "?k=" + k,
378
+ fileSize: rec.size,
379
+ mime: rec.mime,
380
+ accessLevel: lvl,
381
+ expiry: exp
382
+ });
383
+ }
384
+
385
+ async function handleStream(req, res, url, msgId) {
386
+ const k = url.searchParams.get("k") || "";
387
+ const ticket = openTicket(k);
388
+ if (!ticket || ticket.m !== msgId) {
389
+ res.writeHead(403);
390
+ return res.end();
391
+ }
392
+ if (ticket.e < Math.floor(Date.now() / 1000)) {
393
+ res.writeHead(410);
394
+ return res.end();
395
+ }
396
+ const bot = pickBot();
397
+ if (!bot) {
398
+ res.writeHead(503);
399
+ return res.end();
400
+ }
401
+ let rec;
402
+ try {
403
+ rec = await fileFromMsg(bot, msgId);
404
+ } catch {
405
+ fileCache.delete(String(msgId));
406
+ res.writeHead(404);
407
+ return res.end();
408
+ }
409
+ const size = rec.size;
410
+ const rng = parseRange(req.headers.range, size);
411
+ const headers = {
412
+ "Content-Type": rec.mime || "video/mp4",
413
+ "Accept-Ranges": "bytes",
414
+ "Cache-Control": "private, max-age=60",
415
+ "Content-Disposition": "inline"
416
+ };
417
+ if (req.method === "HEAD") {
418
+ headers["Content-Length"] = String(rng.partial ? rng.end - rng.start + 1 : size);
419
+ if (rng.partial) {
420
+ headers["Content-Range"] = "bytes " + rng.start + "-" + rng.end + "/" + size;
421
+ res.writeHead(206, headers);
422
+ } else {
423
+ res.writeHead(200, headers);
424
+ }
425
+ return res.end();
426
+ }
427
+ headers["Content-Length"] = String(rng.end - rng.start + 1);
428
+ if (rng.partial || req.headers.range) {
429
+ headers["Content-Range"] = "bytes " + rng.start + "-" + rng.end + "/" + size;
430
+ res.writeHead(206, headers);
431
+ } else {
432
+ res.writeHead(200, headers);
433
+ }
434
+ try {
435
+ await pipeRange(bot, rec, rng.start, rng.end, res);
436
+ } catch (e) {
437
+ const msg = String(e && e.errorMessage || e.message || e);
438
+ if (/FILE_REFERENCE/i.test(msg)) fileCache.delete(String(msgId));
439
+ if (!res.headersSent) {
440
+ res.writeHead(502);
441
+ res.end();
442
+ } else if (!res.writableEnded) res.end();
443
+ }
444
+ }
445
+
446
+ async function handleVipStatus(req, res) {
447
+ let lvl = "anonymous";
448
+ try {
449
+ const idp = await verifyIdToken(req.headers.authorization || "");
450
+ if (idp) {
451
+ lvl = await accessLevel(idp.sub);
452
+ let sub = null;
453
+ try { sub = await rtdb("users/" + idp.sub + "/subscription", "GET"); } catch {}
454
+ return json(res, 200, { accessLevel: lvl, subscription: sub || null });
455
+ }
456
+ } catch {}
457
+ json(res, 200, { accessLevel: lvl });
458
+ }
459
+
460
+ async function handleVipStart(req, res) {
461
+ if (ROLE !== "indexer") return json(res, 409, { error: "use_s1" });
462
+ if (!STRIPE_KEY) return json(res, 503, { error: "stripe_not_configured" });
463
+ const idp = await verifyIdToken(req.headers.authorization || "");
464
+ if (!idp) return json(res, 401, { error: "login" });
465
+ const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
466
+ const plan = PLANS[body.plan];
467
+ if (!plan) return json(res, 400, { error: "plan" });
468
+ const r = await fetch("https://api.stripe.com/v1/checkout/sessions", {
469
+ method: "POST",
470
+ headers: {
471
+ Authorization: "Bearer " + STRIPE_KEY,
472
+ "Content-Type": "application/x-www-form-urlencoded"
473
+ },
474
+ body: new URLSearchParams({
475
+ mode: "payment",
476
+ success_url: ORIGIN + "/?vip=success",
477
+ cancel_url: ORIGIN + "/?pay_error=cancel",
478
+ "line_items[0][price_data][currency]": "usd",
479
+ "line_items[0][price_data][product_data][name]": plan.label,
480
+ "line_items[0][price_data][unit_amount]": String(plan.amount),
481
+ "line_items[0][quantity]": "1",
482
+ "metadata[uid]": idp.sub,
483
+ "metadata[plan]": body.plan,
484
+ "payment_intent_data[metadata][uid]": idp.sub,
485
+ "payment_intent_data[metadata][plan]": body.plan
486
+ }).toString()
487
+ });
488
+ const d = await r.json();
489
+ if (!r.ok || !d.id) return json(res, 400, { error: d.error && d.error.message || "Payment failed" });
490
+ json(res, 200, { sid: d.id });
491
+ }
492
+
493
+ async function handleVipGo(req, res) {
494
+ if (ROLE !== "indexer") return json(res, 409, { error: "use_s1" });
495
+ if (!STRIPE_KEY) return json(res, 503, { error: "stripe_not_configured" });
496
+ const idp = await verifyIdToken(req.headers.authorization || "");
497
+ if (!idp) return json(res, 401, { error: "login" });
498
+ const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
499
+ if (!body.sid) return json(res, 400, { error: "session" });
500
+ const r = await fetch("https://api.stripe.com/v1/checkout/sessions/" + encodeURIComponent(body.sid), {
501
+ headers: { Authorization: "Bearer " + STRIPE_KEY }
502
+ });
503
+ const d = await r.json();
504
+ if (!r.ok || !d.url) return json(res, 400, { error: d.error && d.error.message || "Payment failed" });
505
+ json(res, 200, { url: d.url });
506
+ }
507
+
508
+ async function grantVip(uid, planKey) {
509
+ const plan = PLANS[planKey] || PLANS.month;
510
+ const now = Math.floor(Date.now() / 1000);
511
+ const sub = {
512
+ status: "active",
513
+ plan: planKey,
514
+ label: plan.label,
515
+ price: plan.price,
516
+ expiry: now + plan.sec,
517
+ updatedAt: now
518
+ };
519
+ await rtdb("users/" + uid + "/subscription", "PUT", sub);
520
+ return sub;
521
+ }
522
+
523
+ function stripeOk(raw, sigHeader) {
524
+ if (!STRIPE_WH || !sigHeader) return false;
525
+ const parts = {};
526
+ String(sigHeader).split(",").forEach((p) => {
527
+ const i = p.indexOf("=");
528
+ if (i > 0) parts[p.slice(0, i)] = p.slice(i + 1);
529
+ });
530
+ const t = parts.t;
531
+ const v1 = parts.v1;
532
+ if (!t || !v1) return false;
533
+ const mac = crypto.createHmac("sha256", STRIPE_WH).update(t + "." + raw).digest("hex");
534
+ return timingSafeEq(mac, v1);
535
+ }
536
+
537
+ async function handleStripeWebhook(req, res) {
538
+ const raw = (await readBody(req)).toString("utf8");
539
+ if (!stripeOk(raw, req.headers["stripe-signature"])) {
540
+ res.writeHead(400);
541
+ return res.end();
542
+ }
543
+ let ev;
544
+ try { ev = JSON.parse(raw); } catch {
545
+ res.writeHead(400);
546
+ return res.end();
547
+ }
548
+ if (ev.type === "checkout.session.completed") {
549
+ const ses = ev.data && ev.data.object || {};
550
+ const uid = ses.metadata && ses.metadata.uid;
551
+ const plan = ses.metadata && ses.metadata.plan;
552
+ if (uid) {
553
+ try { await grantVip(uid, plan || "month"); } catch {}
554
+ }
555
+ }
556
+ json(res, 200, { ok: true });
557
+ }
558
+
559
+ async function handleBootstrap(req, res, url) {
560
+ json(res, 200, {
561
+ worker: SPACE_URLS[0],
562
+ spaces: SPACE_URLS,
563
+ fb: FB_WEB,
564
+ blogId: url.searchParams.get("bid") || "",
565
+ role: ROLE,
566
+ bots: bots.filter((b) => b.ready).length
567
+ });
568
+ }
569
+
570
+ function handleHealth(res) {
571
+ json(res, 200, {
572
+ ok: true,
573
+ role: ROLE,
574
+ bots: bots.filter((b) => b.ready).length,
575
+ load: bots.reduce((n, b) => n + b.load, 0)
576
+ });
577
+ }
578
+
579
+ async function onReq(req, res) {
580
+ cors(req, res);
581
+ if (req.method === "OPTIONS") {
582
+ res.writeHead(204);
583
+ return res.end();
584
+ }
585
+ let url;
586
+ try { url = new URL(req.url, "http://local"); } catch {
587
+ res.writeHead(400);
588
+ return res.end();
589
+ }
590
+ try {
591
+ if (url.pathname === "/" || url.pathname === "/health") return handleHealth(res);
592
+ if (url.pathname === "/public/bootstrap") return handleBootstrap(req, res, url);
593
+ if (url.pathname === "/generate-token" && req.method === "GET") return handleGenerate(req, res, url);
594
+ if (url.pathname === "/vip/status" && req.method === "GET") return handleVipStatus(req, res);
595
+ if (url.pathname === "/vip/start" && req.method === "POST") return handleVipStart(req, res);
596
+ if (url.pathname === "/vip/go" && req.method === "POST") return handleVipGo(req, res);
597
+ if (url.pathname === "/vip/stripe" && req.method === "POST") return handleStripeWebhook(req, res);
598
+ const sm = /^\/stream\/(\d+)$/.exec(url.pathname);
599
+ if (sm && (req.method === "GET" || req.method === "HEAD")) return handleStream(req, res, url, Number(sm[1]));
600
+ res.writeHead(404);
601
+ res.end();
602
+ } catch (e) {
603
+ if (!res.headersSent) json(res, 500, { error: "server" });
604
+ else if (!res.writableEnded) res.end();
605
+ }
606
+ }
607
+
608
+ async function main() {
609
+ if (!API_ID || !API_HASH || !STREAM_SECRET) {
610
+ process.stderr.write("missing TELEGRAM_API_ID / TELEGRAM_API_HASH / STREAM_SECRET\n");
611
+ process.exit(1);
612
+ }
613
+ const tokens = String(process.env.BOT_TOKENS || "")
614
+ .split(/[\s,]+/)
615
+ .map((t) => t.trim())
616
+ .filter((t) => t.includes(":"));
617
+ if (!tokens.length) {
618
+ process.stderr.write("missing BOT_TOKENS\n");
619
+ process.exit(1);
620
+ }
621
+ for (let i = 0; i < tokens.length; i++) {
622
+ try {
623
+ await startBot(tokens[i], i);
624
+ } catch (e) {
625
+ process.stderr.write("bot " + i + " failed: " + (e && e.message) + "\n");
626
+ }
627
+ }
628
+ if (!bots.length) {
629
+ process.stderr.write("no bots online\n");
630
+ process.exit(1);
631
+ }
632
+ http.createServer(onReq).listen(PORT, "0.0.0.0");
633
+ }
634
+
635
+ main().catch((e) => {
636
+ process.stderr.write(String(e && e.stack || e) + "\n");
637
+ process.exit(1);
638
+ });