scanner-bot / app.py
asdfnikah's picture
webhook mode deploy
3ce5598 verified
Raw History Blame Contribute Delete
15.7 kB
"""Telegram bot: upload .txt URL lists -> HF private storage -> deep scan.
Commands (owner only):
/upload - bot asks for a .txt file, saves it to the HF private repo
/scan - scans every saved .txt file's URLs with deep_scan.py
/list - lists files stored in the HF private repo
/status - shows counts and config
/cancel - cancel an in-progress upload
"""
import asyncio
import contextlib
import io
import json
import os
import re
import threading
import time
import traceback
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import requests
from huggingface_hub import HfApi, create_repo, hf_hub_download
from telegram import Update
from telegram.ext import (
ApplicationBuilder,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
import deep_scan
BOT_TOKEN = os.environ.get("BOT_TOKEN", "").strip()
OWNER_ID = int(os.environ.get("OWNER_ID", "6336630578"))
HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
DATA_REPO = os.environ.get("DATA_REPO", "asdfnikah/scanner-storage").strip()
SPACE_NAME = os.environ.get("SPACE_NAME", "asdfnikah/scanner-bot").strip()
WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "").strip()
WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "").strip()
if not WEBHOOK_URL:
space_id = SPACE_NAME.replace("/", "-")
WEBHOOK_URL = f"https://{space_id}.hf.space/telegram"
REPO_TYPE = "model"
UPLOAD_DIR = "uploads"
REPORT_DIR = "reports"
MAX_URLS_PER_SCAN = int(os.environ.get("MAX_URLS_PER_SCAN", "40"))
SCAN_TIMEOUT = int(os.environ.get("SCAN_TIMEOUT", "600"))
MAX_FILE_BYTES = 20 * 1024 * 1024
_upload_waiting = set()
_lock = threading.Lock()
_last_log = []
bot_alive = False
api = None
if HF_TOKEN:
api = HfApi(token=HF_TOKEN)
def _push_logs():
if api is None or not HF_TOKEN:
return
try:
ts = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
api.upload_file(
path_or_fileobj=io.BytesIO(("\n".join(_last_log)).encode("utf-8")),
path_in_repo=f"logs/startup_{ts}.log",
repo_id=DATA_REPO, repo_type=REPO_TYPE,
commit_message="container log",
)
except Exception:
pass
def log(msg):
line = f"[{datetime.utcnow().isoformat()}Z] {msg}"
_last_log.append(line)
_last_log[:] = _last_log[-100:]
print(line)
def is_owner(update):
return update.effective_user and update.effective_user.id == OWNER_ID
def owner_only(func):
async def wrapper(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not is_owner(update):
await update.message.reply_text("Denied: owner only.")
return
return await func(update, context)
return wrapper
def ensure_repo():
if api is None:
raise RuntimeError("HF_TOKEN not configured")
try:
api.repo_info(DATA_REPO, repo_type=REPO_TYPE)
except Exception:
create_repo(DATA_REPO, repo_type=REPO_TYPE, private=True, token=HF_TOKEN,
exist_ok=True)
log(f"created private repo {DATA_REPO}")
def extract_urls(text):
found = []
for raw in text.splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
if line.startswith("http://") or line.startswith("https://"):
found.append(line)
continue
cand = line.split()[0]
if re.fullmatch(r"[A-Za-z0-9.-]+\.[A-Za-z]{2,}(:\d+)?(/[^\s]*)?", cand or ""):
found.append("https://" + cand)
seen, out = set(), []
for u in found:
u = u.rstrip("/")
if u not in seen:
seen.add(u)
out.append(u)
return out
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Scanner bot (owner only).\n"
"/upload - send me a .txt with URLs, I save it to HF private storage\n"
"/scan - deep scan all saved URLs (read-only checks)\n"
"/list - files in HF storage\n"
"/status - config/counts\n"
"/cancel - abort upload"
)
@owner_only
async def upload(update: Update, context: ContextTypes.DEFAULT_TYPE):
uid = update.effective_user.id
with _lock:
_upload_waiting.add(uid)
await update.message.reply_text("Send the .txt file now (or /cancel).")
@owner_only
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
with _lock:
_upload_waiting.discard(update.effective_user.id)
await update.message.reply_text("Cancelled.")
@owner_only
async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
uid = update.effective_user.id
with _lock:
waiting = uid in _upload_waiting
if not waiting:
await update.message.reply_text("Use /upload first, then send the file.")
return
doc = update.message.document
if not doc.file_name or not doc.file_name.lower().endswith(".txt"):
await update.message.reply_text("Only .txt files are accepted.")
return
if doc.file_size and doc.file_size > MAX_FILE_BYTES:
await update.message.reply_text("File too big (max 20 MB).")
return
with _lock:
_upload_waiting.discard(uid)
msg = await update.message.reply_text("Downloading file...")
try:
f = await doc.get_file()
data = await f.download_as_bytearray()
text = bytes(data).decode("utf-8", errors="replace")
urls = extract_urls(text)
if not urls:
await msg.edit_text("No URLs found in that file.")
return
ensure_repo()
ts = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
safe = re.sub(r"[^A-Za-z0-9._-]+", "_", doc.file_name)[:80]
path = f"{UPLOAD_DIR}/{ts}_{safe}"
api.upload_file(path_or_fileobj=io.BytesIO(bytes(data)),
path_in_repo=path, repo_id=DATA_REPO,
repo_type=REPO_TYPE,
commit_message=f"telegram upload {safe}")
log(f"uploaded {path} ({len(urls)} urls)")
await msg.edit_text(f"Saved to HF private storage: {path}\nURLs found: {len(urls)}")
except Exception as e:
log(f"upload error: {e}")
await msg.edit_text(f"Upload failed: {e}")
@owner_only
async def scan(update: Update, context: ContextTypes.DEFAULT_TYPE):
if api is None:
await update.message.reply_text("HF_TOKEN not configured.")
return
msg = await update.message.reply_text("Fetching saved files from HF storage...")
try:
ensure_repo()
files = [f for f in api.list_repo_files(DATA_REPO, repo_type=REPO_TYPE)
if f.startswith(UPLOAD_DIR + "/") and f.endswith(".txt")]
except Exception as e:
await msg.edit_text(f"Failed to list storage: {e}")
return
if not files:
await msg.edit_text("No saved .txt files in HF storage. Use /upload first.")
return
await msg.edit_text(f"{len(files)} file(s) found. Downloading...")
urls = []
try:
for f in files:
local = hf_hub_download(repo_id=DATA_REPO, filename=f,
repo_type=REPO_TYPE, token=HF_TOKEN)
with open(local, "r", encoding="utf-8", errors="replace") as fh:
urls.extend(extract_urls(fh.read()))
except Exception as e:
await msg.edit_text(f"Download failed: {e}")
return
seen, urls = set(), []
for u in [x for x in urls]:
if u not in seen:
seen.add(u)
urls.append(u)
if not urls:
await msg.edit_text("No URLs found in saved files.")
return
total = min(len(urls), MAX_URLS_PER_SCAN)
urls = urls[:total]
await msg.edit_text(f"Scanning {total} URL(s) (read-only deep scan)...\n"
f"Each target may take up to {SCAN_TIMEOUT}s.")
results = []
def scan_one(url):
buf = io.StringIO()
try:
with contextlib.redirect_stdout(buf):
rep = deep_scan.Report(target=url,
started=datetime.utcnow().isoformat())
deep_scan.scan(url, rep)
findings = [{"severity": x.severity, "check": x.check,
"detail": x.detail} for x in rep.findings]
counts = {}
for f in findings:
counts[f["severity"]] = counts.get(f["severity"], 0) + 1
return {"url": url, "ok": True, "findings": findings,
"counts": counts, "log": buf.getvalue()[:4000]}
except Exception as e:
return {"url": url, "ok": False, "error": str(e),
"log": buf.getvalue()[:4000]}
loop = asyncio.get_running_loop()
done = 0
with ThreadPoolExecutor(max_workers=3) as ex:
futures = {ex.submit(scan_one, u): u for u in urls}
for fut in asyncio.as_completed(
[asyncio.wrap_future(f) for f in futures]):
try:
r = await asyncio.wait_for(fut, timeout=SCAN_TIMEOUT + 60)
except asyncio.TimeoutError:
r = {"url": "", "ok": False, "error": "global timeout"}
results.append(r)
done += 1
if done % 3 == 0 or done == total:
await msg.edit_text(f"Scanned {done}/{total} targets...")
ts = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
report_path = f"{REPORT_DIR}/report_{ts}.txt"
lines = [f"SCAN REPORT {ts}", f"Targets: {total}",
"Mode: read-only (headers, TLS, exposed paths, CORS, cookies)",
"=" * 60, ""]
for r in results:
if not r["ok"]:
lines.append(f"## {r['url']} -> ERROR: {r.get('error')}")
else:
lines.append(f"## {r['url']}")
if r["findings"]:
for f in sorted(r["findings"],
key=lambda x: ["CRITICAL", "HIGH", "MEDIUM",
"LOW", "INFO"].index(
x["severity"] if x["severity"] in
["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"]
else "INFO")):
lines.append(f" [{f['severity']}] {f['check']}: {f['detail']}")
else:
lines.append(" no findings")
lines.append("")
body = "\n".join(lines)
local = os.path.join("/tmp", f"report_{ts}.txt")
with open(local, "w", encoding="utf-8") as fh:
fh.write(body)
try:
api.upload_file(path_or_fileobj=io.BytesIO(body.encode("utf-8")),
path_in_repo=report_path, repo_id=DATA_REPO,
repo_type=REPO_TYPE, commit_message="scan report")
stored = f"Stored in HF: {DATA_REPO}/{report_path}"
except Exception as e:
stored = f"HF store failed: {e}"
log(f"scan complete: {total} targets -> {report_path}")
await msg.edit_text(f"Done. Scanned {total} target(s).")
with open(local, "rb") as fh:
await update.message.reply_document(document=fh,
filename=f"report_{ts}.txt",
caption=stored)
@owner_only
async def list_files(update: Update, context: ContextTypes.DEFAULT_TYPE):
if api is None:
await update.message.reply_text("HF_TOKEN not configured.")
return
try:
ensure_repo()
files = api.list_repo_files(DATA_REPO, repo_type=REPO_TYPE)
except Exception as e:
await update.message.reply_text(f"Failed: {e}")
return
if not files:
await update.message.reply_text("HF storage is empty.")
return
body = "\n".join(files[:100])
if len(files) > 100:
body += f"\n... and {len(files) - 100} more"
await update.message.reply_text(f"Files in {DATA_REPO}:\n{body}")
@owner_only
async def status(update: Update, context: ContextTypes.DEFAULT_TYPE):
n_files = n_urls = 0
if api:
try:
ensure_repo()
files = [f for f in api.list_repo_files(DATA_REPO, repo_type=REPO_TYPE)]
n_files = len(files)
for f in files:
if f.startswith(UPLOAD_DIR + "/"):
local = hf_hub_download(repo_id=DATA_REPO, filename=f,
repo_type=REPO_TYPE, token=HF_TOKEN)
with open(local, "r", encoding="utf-8", errors="replace") as fh:
n_urls += len(extract_urls(fh.read()))
except Exception as e:
await update.message.reply_text(f"status error: {e}")
return
await update.message.reply_text(
f"Repo: {DATA_REPO}\nFiles: {n_files}\nStored URLs: {n_urls}\n"
f"Scan cap per run: {MAX_URLS_PER_SCAN}\nPer-target timeout: {SCAN_TIMEOUT}s")
async def on_error(update, context):
log(f"telegram error: {context.error}")
def build_app():
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("upload", upload))
app.add_handler(CommandHandler("scan", scan))
app.add_handler(CommandHandler("list", list_files))
app.add_handler(CommandHandler("status", status))
app.add_handler(CommandHandler("cancel", cancel))
app.add_handler(MessageHandler(filters.Document.TEXT, handle_document))
app.add_error_handler(on_error)
return app
async def bot_main():
app = build_app()
log("application built, starting webhook server...")
await app.initialize()
log("webhook server running on :7860/telegram")
_push_logs()
await app.run_webhook(
listen="0.0.0.0",
port=7860,
url_path="telegram",
webhook_url=WEBHOOK_URL,
secret_token=WEBHOOK_SECRET,
allowed_updates=Update.ALL_TYPES,
drop_pending_updates=True,
stop_signals=None,
)
log("webhook loop ended unexpectedly")
def run_bot():
global bot_alive
try:
bot_alive = True
asyncio.run(bot_main())
bot_alive = False
log("webhook loop ended unexpectedly")
except Exception:
bot_alive = False
log("BOT CRASHED:\n" + traceback.format_exc())
_push_logs()
def build_ui():
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.rstrip("/") in ("/health", "/healthz"):
body = f"bot_alive={bot_alive}".encode()
self.send_response(200 if bot_alive else 503)
else:
body = (
"<html><head><title>Scanner Bot</title></head><body>"
"<h1>Scanner Bot</h1>"
"<p>Telegram bot running. Commands: /upload /scan /list /status</p>"
"<pre>" + ("\n".join(_last_log) or "no logs yet") + "</pre>"
"</body></html>"
).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args):
return
return ThreadingHTTPServer(("0.0.0.0", 7860), Handler)
if __name__ == "__main__":
if not BOT_TOKEN:
raise SystemExit("BOT_TOKEN env var missing")
if not HF_TOKEN:
raise SystemExit("HF_TOKEN env var missing")
log(f"webhook url: {WEBHOOK_URL}")
run_bot()