JOHN SILLVESTOR commited on
Commit
d7a91e9
·
verified ·
1 Parent(s): 01e5eff

harden server; enforce pages.dev only

Browse files
Files changed (1) hide show
  1. server.js +109 -26
server.js CHANGED
@@ -5,8 +5,6 @@ const fs = require("fs");
5
  const os = require("os");
6
  const path = require("path");
7
  const crypto = require("crypto");
8
- const { spawn } = require("child_process");
9
- const { finished } = require("stream/promises");
10
  const { TelegramClient, Api } = require("teleproto");
11
  const { StringSession } = require("teleproto/sessions");
12
 
@@ -137,6 +135,8 @@ const genAnonCache = new Map();
137
  let livePipes = 0;
138
  let fbKeys = { certs: null, exp: 0 };
139
  let rr = 0;
 
 
140
 
141
  function timingSafeEq(a, b) {
142
  const x = Buffer.from(String(a));
@@ -837,7 +837,11 @@ function sweepBots() {
837
 
838
  async function startBot(token, idx) {
839
  const existing = bots.find((b) => b.idx === idx);
840
- if (existing && existing.ready && existing.client && existing.client.connected !== false) return;
 
 
 
 
841
  const client = new TelegramClient(new StringSession(""), API_ID, API_HASH, {
842
  connectionRetries: 8,
843
  reconnectRetries: Infinity,
@@ -850,31 +854,61 @@ async function startBot(token, idx) {
850
  downloadPool: { inflightPerDc: 8, maxSessions: 6, sessions: 6, requestDeadlineMs: 28000 }
851
  });
852
  client.setLogLevel("error");
853
- await client.start({ botAuthToken: token });
 
 
 
 
 
 
 
 
 
 
 
 
 
854
  if (existing) {
855
  const old = existing.client;
856
  existing.client = client;
857
  existing.token = token;
858
  existing.ready = true;
859
  existing.load = 0;
 
860
  existing.coolUntil = 0;
 
 
861
  if (old && old !== client) {
862
  try { old.disconnect(); } catch { }
863
  }
864
  return;
865
  }
866
- bots.push({ client, token, idx, ready: true, load: 0, coolUntil: 0 });
867
  }
868
 
869
  async function reviveBots() {
870
  sweepBots();
 
871
  for (const slot of botSlots) {
 
872
  const b = bots.find((x) => x.idx === slot.idx);
873
- if (b && b.ready && b.client && b.client.connected !== false) continue;
 
 
 
 
874
  try {
875
  await startBot(slot.token, slot.idx);
 
 
876
  } catch (e) {
877
- process.stderr.write("bot " + slot.idx + " revive: " + (e && e.message) + "\n");
 
 
 
 
 
 
878
  }
879
  }
880
  }
@@ -2059,10 +2093,17 @@ async function readBody(req, max) {
2059
  if (Number.isFinite(declared) && declared > lim) throw new Error("body");
2060
  const chunks = [];
2061
  let n = 0;
2062
- for await (const c of req) {
2063
- n += c.length;
2064
- if (n > lim) throw new Error("body");
2065
- chunks.push(c);
 
 
 
 
 
 
 
2066
  }
2067
  return Buffer.concat(chunks);
2068
  }
@@ -3007,13 +3048,21 @@ async function handleVipAuto(req, res) {
3007
  json(res, 200, { ok: true, needPay: true, autoRenew: false });
3008
  }
3009
 
 
 
 
 
 
 
 
 
3010
  async function stripeEventSeen(id) {
3011
  if (!id) return true;
3012
  if (stripeEvents.has(id)) return true;
3013
  try {
3014
  const v = await rtdb("stripe_events/" + id, "GET");
3015
  if (v && v.ok === 1) {
3016
- stripeEvents.add(id);
3017
  return true;
3018
  }
3019
  } catch { }
@@ -3022,11 +3071,7 @@ async function stripeEventSeen(id) {
3022
 
3023
  async function stripeEventMark(id) {
3024
  if (!id) return;
3025
- stripeEvents.add(id);
3026
- if (stripeEvents.size > 4000) {
3027
- const first = stripeEvents.values().next().value;
3028
- stripeEvents.delete(first);
3029
- }
3030
  try {
3031
  await rtdb("stripe_events/" + id, "PUT", { t: Math.floor(Date.now() / 1000), ok: 1 });
3032
  } catch { }
@@ -3123,17 +3168,22 @@ async function handleBootstrap(req, res, url) {
3123
 
3124
  function handleHealth(req, res) {
3125
  if (req && adminKeyOk(req, new URL("http://local"))) {
 
3126
  json(res, 200, {
3127
  ok: true,
3128
  role: ROLE,
 
3129
  bots: bots.filter((b) => botUsable(b) || (b.ready && !(b.coolUntil && Date.now() < b.coolUntil))).length,
3130
- load: bots.reduce((n, b) => n + b.load, 0),
 
3131
  cap: bots.filter((b) => b.ready).length * BOT_MAX,
3132
  pipes: livePipes,
3133
  titles: titlePipes.size,
3134
  hot: hotMap.size,
3135
  files: fileCache.size,
3136
- durs: durCache.size
 
 
3137
  });
3138
  return;
3139
  }
@@ -3316,6 +3366,27 @@ async function onReq(req, res) {
3316
  }
3317
  }
3318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3319
  async function main() {
3320
  if (!API_ID || !API_HASH || !STREAM_SECRET) {
3321
  process.stderr.write("missing required settings\n");
@@ -3326,25 +3397,29 @@ async function main() {
3326
  } catch { }
3327
  const _diskSweep = setInterval(() => { trimDiskCache().catch(() => { }); }, 60000);
3328
  if (typeof _diskSweep.unref === "function") _diskSweep.unref();
 
3329
  const tokens = String(process.env.BOT_TOKENS || "")
3330
  .split(/[\s,]+/)
3331
  .map((t) => t.trim())
3332
- .filter((t) => t.includes(":"));
 
 
 
 
3333
  if (!tokens.length) {
3334
  process.stderr.write("missing BOT_TOKENS\n");
3335
  process.exit(1);
3336
  }
3337
  for (let i = 0; i < tokens.length; i++) {
3338
- botSlots.push({ token: tokens[i], idx: i });
3339
  try {
3340
  await startBot(tokens[i], i);
3341
  } catch (e) {
3342
- process.stderr.write("bot " + i + " failed: " + (e && e.message) + "\n");
3343
  }
3344
  }
3345
  if (!bots.length) {
3346
- process.stderr.write("no bots online\n");
3347
- process.exit(1);
3348
  }
3349
  setInterval(() => { reviveBots().catch(() => { }); }, 20000);
3350
  setInterval(sweepMaps, 30000).unref();
@@ -3363,16 +3438,24 @@ async function main() {
3363
  if (sock.writable) sock.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
3364
  } catch { }
3365
  });
 
 
 
 
 
3366
  srv.listen(PORT, "0.0.0.0", () => {
3367
  if (ROLE === "indexer" && STRIPE_KEY) ensureFreeWallets().catch(() => { });
3368
  });
3369
  }
3370
 
 
 
3371
  process.on("unhandledRejection", (e) => {
3372
- process.stderr.write("rej " + errText(e) + "\n");
3373
  });
3374
  process.on("uncaughtException", (e) => {
3375
- process.stderr.write("exc " + errText(e) + "\n");
 
3376
  });
3377
 
3378
  main().catch((e) => {
 
5
  const os = require("os");
6
  const path = require("path");
7
  const crypto = require("crypto");
 
 
8
  const { TelegramClient, Api } = require("teleproto");
9
  const { StringSession } = require("teleproto/sessions");
10
 
 
135
  let livePipes = 0;
136
  let fbKeys = { certs: null, exp: 0 };
137
  let rr = 0;
138
+ let httpServer = null;
139
+ let shuttingDown = false;
140
 
141
  function timingSafeEq(a, b) {
142
  const x = Buffer.from(String(a));
 
837
 
838
  async function startBot(token, idx) {
839
  const existing = bots.find((b) => b.idx === idx);
840
+ if (existing && existing.ready && existing.client && existing.client.connected !== false) {
841
+ existing.nextTry = 0;
842
+ existing.fails = 0;
843
+ return;
844
+ }
845
  const client = new TelegramClient(new StringSession(""), API_ID, API_HASH, {
846
  connectionRetries: 8,
847
  reconnectRetries: Infinity,
 
854
  downloadPool: { inflightPerDc: 8, maxSessions: 6, sessions: 6, requestDeadlineMs: 28000 }
855
  });
856
  client.setLogLevel("error");
857
+ let timer = null;
858
+ try {
859
+ await Promise.race([
860
+ client.start({ botAuthToken: token }),
861
+ new Promise((_, reject) => {
862
+ timer = setTimeout(() => reject(new Error("bot_timeout")), 30000);
863
+ })
864
+ ]);
865
+ } catch (e) {
866
+ try { await client.disconnect(); } catch { }
867
+ throw e;
868
+ } finally {
869
+ if (timer) clearTimeout(timer);
870
+ }
871
  if (existing) {
872
  const old = existing.client;
873
  existing.client = client;
874
  existing.token = token;
875
  existing.ready = true;
876
  existing.load = 0;
877
+ existing.tgLoad = 0;
878
  existing.coolUntil = 0;
879
+ existing.fails = 0;
880
+ existing.nextTry = 0;
881
  if (old && old !== client) {
882
  try { old.disconnect(); } catch { }
883
  }
884
  return;
885
  }
886
+ bots.push({ client, token, idx, ready: true, load: 0, tgLoad: 0, coolUntil: 0, fails: 0, nextTry: 0 });
887
  }
888
 
889
  async function reviveBots() {
890
  sweepBots();
891
+ const now = Date.now();
892
  for (const slot of botSlots) {
893
+ if (now < (slot.nextTry || 0)) continue;
894
  const b = bots.find((x) => x.idx === slot.idx);
895
+ if (b && b.ready && b.client && b.client.connected !== false) {
896
+ slot.fails = 0;
897
+ slot.nextTry = 0;
898
+ continue;
899
+ }
900
  try {
901
  await startBot(slot.token, slot.idx);
902
+ slot.fails = 0;
903
+ slot.nextTry = 0;
904
  } catch (e) {
905
+ slot.fails = (slot.fails || 0) + 1;
906
+ const base = Math.min(300000, 15000 * Math.pow(2, Math.min(slot.fails - 1, 4)));
907
+ slot.nextTry = Date.now() + base + Math.floor(Math.random() * 5000);
908
+ if (slot.fails <= 3 || slot.fails % 10 === 0) {
909
+ const wait = Math.max(0, Math.round((slot.nextTry - Date.now()) / 1000));
910
+ process.stderr.write("bot " + slot.idx + " revive: " + errText(e) + " (retry in " + wait + "s)\n");
911
+ }
912
  }
913
  }
914
  }
 
2093
  if (Number.isFinite(declared) && declared > lim) throw new Error("body");
2094
  const chunks = [];
2095
  let n = 0;
2096
+ const timer = setTimeout(() => {
2097
+ try { req.destroy(new Error("body_timeout")); } catch { }
2098
+ }, 20000);
2099
+ try {
2100
+ for await (const c of req) {
2101
+ n += c.length;
2102
+ if (n > lim) throw new Error("body");
2103
+ chunks.push(c);
2104
+ }
2105
+ } finally {
2106
+ clearTimeout(timer);
2107
  }
2108
  return Buffer.concat(chunks);
2109
  }
 
3048
  json(res, 200, { ok: true, needPay: true, autoRenew: false });
3049
  }
3050
 
3051
+ function rememberStripeEvent(id) {
3052
+ stripeEvents.add(id);
3053
+ if (stripeEvents.size > 4000) {
3054
+ const first = stripeEvents.values().next().value;
3055
+ stripeEvents.delete(first);
3056
+ }
3057
+ }
3058
+
3059
  async function stripeEventSeen(id) {
3060
  if (!id) return true;
3061
  if (stripeEvents.has(id)) return true;
3062
  try {
3063
  const v = await rtdb("stripe_events/" + id, "GET");
3064
  if (v && v.ok === 1) {
3065
+ rememberStripeEvent(id);
3066
  return true;
3067
  }
3068
  } catch { }
 
3071
 
3072
  async function stripeEventMark(id) {
3073
  if (!id) return;
3074
+ rememberStripeEvent(id);
 
 
 
 
3075
  try {
3076
  await rtdb("stripe_events/" + id, "PUT", { t: Math.floor(Date.now() / 1000), ok: 1 });
3077
  } catch { }
 
3168
 
3169
  function handleHealth(req, res) {
3170
  if (req && adminKeyOk(req, new URL("http://local"))) {
3171
+ const mem = process.memoryUsage();
3172
  json(res, 200, {
3173
  ok: true,
3174
  role: ROLE,
3175
+ uptime: Math.floor(process.uptime()),
3176
  bots: bots.filter((b) => botUsable(b) || (b.ready && !(b.coolUntil && Date.now() < b.coolUntil))).length,
3177
+ botsTotal: bots.length,
3178
+ load: bots.reduce((n, b) => n + (b.load || 0) + (b.tgLoad || 0), 0),
3179
  cap: bots.filter((b) => b.ready).length * BOT_MAX,
3180
  pipes: livePipes,
3181
  titles: titlePipes.size,
3182
  hot: hotMap.size,
3183
  files: fileCache.size,
3184
+ durs: durCache.size,
3185
+ memRss: Math.round(mem.rss / MB),
3186
+ memHeap: Math.round(mem.heapUsed / MB)
3187
  });
3188
  return;
3189
  }
 
3366
  }
3367
  }
3368
 
3369
+ function shutdown(code, reason) {
3370
+ if (shuttingDown) return;
3371
+ shuttingDown = true;
3372
+ process.stderr.write("shutdown " + reason + "\n");
3373
+ try {
3374
+ if (httpServer) {
3375
+ httpServer.close(() => process.exit(code));
3376
+ if (typeof httpServer.closeIdleConnections === "function") httpServer.closeIdleConnections();
3377
+ }
3378
+ } catch { }
3379
+ for (const b of bots) {
3380
+ try { b.client.disconnect(); } catch { }
3381
+ }
3382
+ setTimeout(() => {
3383
+ try {
3384
+ if (httpServer && typeof httpServer.closeAllConnections === "function") httpServer.closeAllConnections();
3385
+ } catch { }
3386
+ process.exit(code);
3387
+ }, 8000).unref();
3388
+ }
3389
+
3390
  async function main() {
3391
  if (!API_ID || !API_HASH || !STREAM_SECRET) {
3392
  process.stderr.write("missing required settings\n");
 
3397
  } catch { }
3398
  const _diskSweep = setInterval(() => { trimDiskCache().catch(() => { }); }, 60000);
3399
  if (typeof _diskSweep.unref === "function") _diskSweep.unref();
3400
+ const seenTokens = new Set();
3401
  const tokens = String(process.env.BOT_TOKENS || "")
3402
  .split(/[\s,]+/)
3403
  .map((t) => t.trim())
3404
+ .filter((t) => {
3405
+ if (!t.includes(":") || seenTokens.has(t)) return false;
3406
+ seenTokens.add(t);
3407
+ return true;
3408
+ });
3409
  if (!tokens.length) {
3410
  process.stderr.write("missing BOT_TOKENS\n");
3411
  process.exit(1);
3412
  }
3413
  for (let i = 0; i < tokens.length; i++) {
3414
+ botSlots.push({ token: tokens[i], idx: i, fails: 0, nextTry: 0 });
3415
  try {
3416
  await startBot(tokens[i], i);
3417
  } catch (e) {
3418
+ process.stderr.write("bot " + i + " failed: " + errText(e) + "\n");
3419
  }
3420
  }
3421
  if (!bots.length) {
3422
+ process.stderr.write("no bots online; will keep retrying\n");
 
3423
  }
3424
  setInterval(() => { reviveBots().catch(() => { }); }, 20000);
3425
  setInterval(sweepMaps, 30000).unref();
 
3438
  if (sock.writable) sock.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
3439
  } catch { }
3440
  });
3441
+ httpServer = srv;
3442
+ srv.on("error", (e) => {
3443
+ process.stderr.write("server: " + errText(e) + "\n");
3444
+ shutdown(1, "server_error");
3445
+ });
3446
  srv.listen(PORT, "0.0.0.0", () => {
3447
  if (ROLE === "indexer" && STRIPE_KEY) ensureFreeWallets().catch(() => { });
3448
  });
3449
  }
3450
 
3451
+ process.on("SIGTERM", () => shutdown(0, "SIGTERM"));
3452
+ process.on("SIGINT", () => shutdown(0, "SIGINT"));
3453
  process.on("unhandledRejection", (e) => {
3454
+ process.stderr.write("rej " + (e && e.stack ? e.stack : errText(e)) + "\n");
3455
  });
3456
  process.on("uncaughtException", (e) => {
3457
+ process.stderr.write("exc " + (e && e.stack ? e.stack : errText(e)) + "\n");
3458
+ setTimeout(() => shutdown(1, "uncaughtException"), 1200).unref();
3459
  });
3460
 
3461
  main().catch((e) => {