JOHN SILLVESTOR commited on
Commit
afeeeef
·
verified ·
1 Parent(s): 9852cf4

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