Spaces:
Running

kpak / app.py
msentimental's picture
Update app.py
aac3006 verified
Raw History Blame Contribute Delete
124 kB
from flask import Flask, render_template, request, jsonify, session, send_from_directory from flask_socketio import SocketIO, emit, join_room from flask_bcrypt import Bcrypt from flask_limiter import Limiter from flask_limiter.util import get_remote_address import jwt import sqlite3 import datetime import re import time import os import hashlib from functools import wraps import requests import threading import json import logging import sys import random import secrets from vpn_checker import vpn_blocker class Snowflake: def __init__(self, worker_id=1, datacenter_id=1): self.worker_id = worker_id self.datacenter_id = datacenter_id self.sequence = 0 self.last_timestamp = -1 # Discord Epoch (2015-01-01) - you can use any start date self.epoch = 1420070400000 def _current_time(self): return int(time.time() * 1000) def generate(self): timestamp = self._current_time() if timestamp < self.last_timestamp: raise Exception("Clock moved backwards!") if timestamp == self.last_timestamp: self.sequence = (self.sequence + 1) & 4095 # 12-bit sequence if self.sequence == 0: # Sequence overflow, wait for next millisecond while timestamp <= self.last_timestamp: timestamp = self._current_time() else: self.sequence = 0 self.last_timestamp = timestamp # 64-bit ID composition: # 42 bits timestamp | 5 bits datacenter | 5 bits worker | 12 bits sequence snowflake = ((timestamp - self.epoch) << 22) | \ (self.datacenter_id << 17) | \ (self.worker_id << 12) | \ self.sequence return snowflake def parse(self, snowflake): """Extract timestamp from snowflake (for debugging)""" timestamp = (snowflake >> 22) + self.epoch return { 'timestamp': timestamp, 'datetime': datetime.datetime.fromtimestamp(timestamp/1000), 'worker': (snowflake >> 12) & 0x1F, 'datacenter': (snowflake >> 17) & 0x1F, 'sequence': snowflake & 0xFFF } # Create a global snowflake generator snowflake_gen = Snowflake(worker_id=1, datacenter_id=1) # Configure logging to show ALL output logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', stream=sys.stdout # Force to stdout ) # Also add a file handler to capture everything file_handler = logging.FileHandler('/tmp/app.log') file_handler.setLevel(logging.DEBUG) logging.getLogger().addHandler(file_handler) print = logging.info # Replace print with logging.info from io import StringIO # Force all stdout to be unbuffered sys.stdout.reconfigure(line_buffering=True) app = Flask(__name__, template_folder='templates', static_folder='static') app.config['SECRET_KEY'] = os.environ.get('JWT_SECRET', 'dba4880f6b7c490ef8bbfc28f15ee4b1eba19f20e5964020a756efada013ac3b') app.config['ABLY_API_KEY'] = os.environ.get('ABLY_API_KEY', '') app.config['RESEND_API_KEY'] = os.environ.get('RESEND_API_KEY', '') app.config['APP_URL'] = os.environ.get('APP_URL', 'https://kpakservices-kpak.hf.space') print(f"πŸ”‘ Resend API Key loaded: {'YES' if app.config['RESEND_API_KEY'] else 'NO'}") if app.config['RESEND_API_KEY']: print(f"πŸ”‘ Resend API Key prefix: {app.config['RESEND_API_KEY'][:10]}...") print(f"πŸ”‘ Resend API Key length: {len(app.config['RESEND_API_KEY'])}") DEFAULT_AVATAR = 'https://static.vecteezy.com/system/resources/thumbnails/003/337/584/small/default-avatar-photo-placeholder-profile-icon-vector.jpg' bcrypt = Bcrypt(app) limiter = Limiter( get_remote_address, app=app, storage_uri="memory://" ) # Socket.IO socketio = SocketIO(app, cors_allowed_origins=["https://kpakservices-kpak.hf.space"], logger=True, engineio_logger=True) print(f"πŸ”§ SocketIO async_mode = {socketio.async_mode}") import shutil DB_PATH = '/tmp/kpak.db' # Use /tmp instead of /data BACKUP_PATH = '/tmp/kpak_backup.db' def backup_db(): """Background thread to backup database every minute""" while True: time.sleep(60) try: if os.path.exists(DB_PATH): shutil.copy2(DB_PATH, BACKUP_PATH) print("βœ… Database backed up") except Exception as e: print(f"❌ Backup error: {e}") # Start backup thread # Disabled: threading.Thread(target=backup_db, daemon=True).start() def get_db(): db = sqlite3.connect(DB_PATH) db.row_factory = sqlite3.Row return db def init_db(): # Try to restore from backup first if os.path.exists(BACKUP_PATH): try: shutil.copy2(BACKUP_PATH, DB_PATH) print("βœ… Restored database from backup") except Exception as e: print(f"❌ Restore error: {e}, creating new database") db = get_db() db.executescript(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL, ip TEXT, email1 TEXT, email2 TEXT, phone TEXT, bio TEXT, avatar TEXT, role TEXT DEFAULT 'user', muted_until INTEGER DEFAULT 0, banned INTEGER DEFAULT 0, banned_ip TEXT, verified INTEGER DEFAULT 1, verification_token TEXT, created_at INTEGER, last_seen INTEGER, online INTEGER DEFAULT 0 ); CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY, user_id INTEGER, username TEXT, text TEXT, timestamp INTEGER, type TEXT DEFAULT 'public', recipient TEXT, deleted INTEGER DEFAULT 0, edited INTEGER DEFAULT 0, edited_at INTEGER, FOREIGN KEY(user_id) REFERENCES users(id) ); CREATE TABLE IF NOT EXISTS blocks ( user_id INTEGER, blocked_user TEXT, PRIMARY KEY (user_id, blocked_user) ); CREATE TABLE IF NOT EXISTS rate_limits ( user_id INTEGER PRIMARY KEY, message_count INTEGER DEFAULT 0, last_message_time INTEGER, dm_count INTEGER DEFAULT 0, last_dm_time INTEGER, delete_count INTEGER DEFAULT 0, last_delete_time INTEGER, edit_count INTEGER DEFAULT 0, last_edit_time INTEGER ); CREATE TABLE IF NOT EXISTS bans ( id INTEGER PRIMARY KEY AUTOINCREMENT, ip TEXT, username TEXT, banned_by TEXT, timestamp INTEGER ); CREATE TABLE IF NOT EXISTS user_tokens ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, token TEXT UNIQUE NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, last_used INTEGER, FOREIGN KEY(user_id) REFERENCES users(id) ); CREATE TABLE IF NOT EXISTS dm_unread ( user_id INTEGER NOT NULL, other_username TEXT NOT NULL, unread_count INTEGER DEFAULT 0, last_message_at INTEGER DEFAULT 0, PRIMARY KEY (user_id, other_username), FOREIGN KEY(user_id) REFERENCES users(id) ); CREATE INDEX IF NOT EXISTS idx_tokens_token ON user_tokens(token); CREATE INDEX IF NOT EXISTS idx_tokens_expires ON user_tokens(expires_at); ''') cursor = db.cursor() cursor.execute("PRAGMA table_info(messages)") columns = [col[1] for col in cursor.fetchall()] if 'ephemeral' not in columns: cursor.execute("ALTER TABLE messages ADD COLUMN ephemeral INTEGER DEFAULT 0") print("βœ… Added ephemeral column to messages table") if 'image_data' not in columns: cursor.execute("ALTER TABLE messages ADD COLUMN image_data TEXT") print("βœ… Added image_data column to messages table") if 'image_name' not in columns: cursor.execute("ALTER TABLE messages ADD COLUMN image_name TEXT") print("βœ… Added image_name column to messages table") if 'reply_to' not in columns: cursor.execute("ALTER TABLE messages ADD COLUMN reply_to TEXT") print("βœ… Added reply_to column to messages table") db.executescript(''' CREATE TABLE IF NOT EXISTS custom_emojis ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, image_data TEXT NOT NULL, added_by TEXT NOT NULL, created_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS reactions ( id INTEGER PRIMARY KEY AUTOINCREMENT, message_id INTEGER NOT NULL, username TEXT NOT NULL, emoji TEXT NOT NULL, created_at INTEGER NOT NULL, UNIQUE(message_id, username, emoji) ); CREATE INDEX IF NOT EXISTS idx_reactions_message ON reactions(message_id); CREATE TABLE IF NOT EXISTS pinned_messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, message_id INTEGER NOT NULL UNIQUE, channel TEXT NOT NULL, pinned_by TEXT NOT NULL, pinned_by_role TEXT NOT NULL, pinned_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_pinned_channel ON pinned_messages(channel); CREATE TABLE IF NOT EXISTS friendships ( id INTEGER PRIMARY KEY AUTOINCREMENT, user1 TEXT NOT NULL, user2 TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', requested_by TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, UNIQUE(user1, user2) ); CREATE INDEX IF NOT EXISTS idx_friend_u1 ON friendships(user1); CREATE INDEX IF NOT EXISTS idx_friend_u2 ON friendships(user2); ''') db.commit() db.close() print("βœ… Database initialized") # Initialize try: init_db() except Exception as e: print(f"❌ Database error: {e}") # Admin list ADMINS = ['Morgenstern', 'Bacon'] MODS = [] @app.before_request def block_vpn(): # Skip check for static files and health endpoint (optional) if request.path.startswith('/static') or request.path == '/health': return None # Get real IP (considering HuggingFace proxy headers) ip = request.headers.get('X-Forwarded-For', request.remote_addr) if ip: ip = ip.split(',')[0].strip() else: ip = request.remote_addr if vpn_blocker.is_vpn(ip): print(f"Blocked VPN IP: {ip} accessing {request.path}") # Changed from logger.warning to print return jsonify({'error': 'VPN/proxy access is not allowed'}), 403 return None def disconnect_user(username, reason='Disconnected'): for sid, user in list(connected_users.items()): if user['username'] == username: socketio.emit('force_disconnect', {'reason': reason}, room=sid) socketio.server.disconnect(sid) def is_strong_password(password): if len(password) < 8: return False if not any(c.isupper() for c in password): return False if not any(c.islower() for c in password): return False if not any(c.isdigit() for c in password): return False return True def validate_image(image_data): """ Validate that the uploaded data is actually a valid image Returns: (is_valid, error_message, mime_type) """ import base64 import io from PIL import Image # Check if it's a data URL if not image_data or not isinstance(image_data, str): return False, "Invalid image data", None # Remove data URL prefix if present if image_data.startswith('data:'): try: # Extract mime type and base64 data header, base64_data = image_data.split(',', 1) mime_type = header.split(':')[1].split(';')[0] # Only allow image types allowed_mime_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'] if mime_type not in allowed_mime_types: return False, f"Invalid image type: {mime_type}. Allowed: JPEG, PNG, GIF, WebP", None image_data = base64_data except: return False, "Malformed data URL", None else: # Try to detect if it's base64 try: base64.b64decode(image_data) except: return False, "Invalid base64 data", None mime_type = 'image/unknown' try: # Decode base64 image_bytes = base64.b64decode(image_data) # Try to open as image with PIL image = Image.open(io.BytesIO(image_bytes)) image.verify() # Verify it's a valid image # Reopen after verify (verify closes the file) image = Image.open(io.BytesIO(image_bytes)) # Optional: Check dimensions (prevent tiny/spam images) width, height = image.size if width < 12 or height < 12: return False, f"Image too small: {width}x{height}. Minimum 16x16", None # Detect actual format actual_format = image.format if actual_format: mime_type = f'image/{actual_format.lower()}' return True, None, mime_type except Exception as e: return False, f"Invalid or corrupted image: {str(e)}", None def create_command_response(user, text, is_dm=False, recipient=None): """Create an ephemeral message from 'Kpak Console' that ONLY the sender can see""" message_id = snowflake_gen.generate() now = int(time.time() * 1000) db = get_db() if is_dm: # DM context - store as DM but ephemeral db.execute(''' INSERT INTO messages (id, user_id, username, text, timestamp, type, recipient, ephemeral) VALUES (?, ?, ?, ?, ?, 'dm', ?, 1) ''', ( message_id, user['id'], 'Kpak Console', text, now, recipient # Store in the actual DM conversation context )) else: # Public context - store as public but ephemeral db.execute(''' INSERT INTO messages (id, user_id, username, text, timestamp, type, ephemeral) VALUES (?, ?, ?, ?, ?, 'public', 1) ''', ( message_id, user['id'], 'Kpak Console', text, now )) db.commit() db.close() return { 'id': str(message_id), 'username': 'Kpak Console', 'text': text, 'timestamp': now, 'type': 'dm' if is_dm else 'public', 'recipient': recipient if is_dm else None, 'user_id': user['id'], 'ephemeral': True, 'visible_to': user['id'] # Only this user should see it } def is_valid_phone(phone): """ Validate phone number format Accepts formats: - +1234567890 - 123-456-7890 - (123) 456-7890 - 1234567890 """ if not phone or phone.strip() == '': return True # Empty is allowed (optional field) # Remove all non-digit characters except + cleaned = re.sub(r'[^\d+]', '', phone) # Check if it starts with + and has 10-15 digits if cleaned.startswith('+'): digits = cleaned[1:] if not digits.isdigit(): return False if len(digits) < 10 or len(digits) > 15: return False else: # Just digits, 10-15 characters if not cleaned.isdigit(): return False if len(cleaned) < 10 or len(cleaned) > 15: return False return True def is_valid_email(email): ALLOWED_DOMAINS = [ 'gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com', 'aol.com', 'protonmail.com', 'proton.me', 'icloud.com', 'me.com', 'mac.com', 'mail.com', 'yandex.com', 'yandex.ru', 'gmx.com', 'gmx.de', 'live.com', 'live.de', 'msn.com' ] # Basic email format validation email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' if not re.match(email_regex, email): return False # Extract domain domain = email.lower().split('@')[1] # Check if domain is in allowed list return domain in ALLOWED_DOMAINS # Rate limiting function - NOW WITH ADMIN EXEMPTION AND NULL SAFETY! def check_rate_limit(user, action, limit, window): """ Check rate limit for a user action Args: user: user object (from database) action: 'message', 'delete', 'edit' limit: max attempts per window window: time window in seconds Returns: bool: True if allowed, False if rate limited """ # ADMINS HAVE NO RATE LIMITS! if user['role'] == 'admin': print(f"πŸ‘‘ Admin {user['username']} bypassing rate limit for {action}") return True db = get_db() now = int(time.time()) rate_data = db.execute(f'SELECT * FROM rate_limits WHERE user_id = ?', (user['id'],)).fetchone() if not rate_data: # First time user - create record and allow db.execute(f'INSERT INTO rate_limits (user_id, {action}_count, last_{action}_time) VALUES (?, 1, ?)', (user['id'], now)) db.commit() db.close() return True # Get values with safe defaults last_time = rate_data[f'last_{action}_time'] current_count = rate_data[f'{action}_count'] # Handle case where last_time is None (shouldn't happen, but just in case) if last_time is None: last_time = 0 # Check if window has expired if now - last_time > window: # Window expired - reset counter db.execute(f'UPDATE rate_limits SET {action}_count = 1, last_{action}_time = ? WHERE user_id = ?', (now, user['id'])) db.commit() db.close() return True # Check if over limit if current_count >= limit: db.close() return False # Increment counter db.execute(f'UPDATE rate_limits SET {action}_count = {action}_count + 1 WHERE user_id = ?', (user['id'],)) db.commit() db.close() return True def send_verification_email(email, token, username): """Send verification email via Cloudflare Pages API""" verification_link = f"{app.config['APP_URL']}/verify-email?token={token}" html = f""" <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background: #0B0A1A; color: #ffffff; padding: 20px; margin: 0; line-height: 1.6; }} .container {{ max-width: 480px; margin: 40px auto; background: #1A1830; border: 2px solid #4A3B8C; border-radius: 16px; padding: 32px; box-shadow: 0 10px 25px rgba(0,0,0,0.5); }} h1 {{ color: #E0B0FF; font-size: 28px; margin-bottom: 16px; font-weight: 700; }} p {{ color: #a3a3a3; font-size: 16px; margin-bottom: 24px; }} .button {{ display: inline-block; background: #4A3B8C; color: white !important; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: 600; font-size: 16px; margin: 20px 0; transition: all 0.3s ease; border: 2px solid transparent; }} .button:hover {{ background: #FFD700; color: black !important; border-color: #4A3B8C; }} .footer {{ margin-top: 32px; padding-top: 20px; border-top: 1px solid #4A3B8C; font-size: 14px; color: #666; }} .link {{ color: #FFD700; word-break: break-all; background: #0B0A1A; padding: 10px; border-radius: 6px; font-family: monospace; font-size: 14px; margin: 15px 0; }} </style> </head> <body> <div class="container"> <h1>✨ Welcome to Kpak, {username}!</h1> <p>Click the button below to verify your email address and start chatting with the community.</p> <a href="{verification_link}" class="button">βœ“ Verify Email Address</a> <p style="margin: 20px 0 10px;">Or copy this link:</p> <div class="link">{verification_link}</div> <div class="footer"> <p>If you didn't create an account, you can safely ignore this email.</p> <p>β€” The Kpak Team</p> </div> </div> </body> </html> """ CLOUDFLARE_API_URL = "https://strike-bot.pages.dev/api/huggingface-kpak-send" try: print(f"πŸ“§ Sending verification email to {email} via Cloudflare...") response = requests.post( CLOUDFLARE_API_URL, json={ 'to': email, 'subject': f'Verify your Kpak account, {username}!', 'html': html, 'fromName': 'Kpak Verification' }, timeout=30 ) if response.status_code == 200: result = response.json() print(f"βœ… Email sent successfully! Message ID: {result.get('messageId', 'unknown')}") return True else: print(f"❌ Cloudflare API error: {response.status_code}") print(f"Response: {response.text}") return False except requests.exceptions.Timeout: print("❌ Email timeout - Cloudflare API didn't respond in time") return False except requests.exceptions.ConnectionError: print("❌ Connection error - Could not reach Cloudflare API") return False except Exception as e: print(f"❌ Unexpected error: {str(e)}") return False def maybe_update_ip(user_id, current_ip): db = get_db() user = db.execute('SELECT ip, last_seen FROM users WHERE id = ?', (user_id,)).fetchone() now = int(time.time()) # Only update if 2 minutes passed OR IP changed if not user or (now - (user['last_seen'] or 0) > 120) or user['ip'] != current_ip: db.execute('UPDATE users SET ip = ?, last_seen = ? WHERE id = ?', (current_ip, now, user_id)) db.commit() db.close() def generate_token(username, user_id): """Generate a simple SHA token""" # Create a unique token using username, user_id, timestamp and random data random_string = secrets.token_urlsafe(32) token_string = f"{username}:{user_id}:{time.time()}:{random_string}" # Create SHA-256 hash token = hashlib.sha256(token_string.encode()).hexdigest() # Store in database (we'll add a tokens table) return token def verify_token(token): """Verify a token exists in database""" db = get_db() user = db.execute(''' SELECT u.* FROM users u JOIN user_tokens t ON u.id = t.user_id WHERE t.token = ? AND t.expires_at > ? ''', (token, int(time.time()))).fetchone() db.close() return user # In app.py, update the token_required decorator: def token_required(f): @wraps(f) def decorated(*args, **kwargs): sweep_expired_mutes() token = request.headers.get('Authorization', '').replace('Bearer ', '') if not token: return jsonify({'error': 'No token'}), 401 token_hash = hashlib.sha256(token.encode()).hexdigest() db = get_db() try: user = db.execute(''' SELECT u.* FROM users u JOIN user_tokens t ON u.id = t.user_id WHERE t.token = ? AND t.expires_at > ? ''', (token_hash, int(time.time()))).fetchone() if not user: db.close() return jsonify({'error': 'Invalid or expired token'}), 401 # Check if user is banned if user['banned']: db.close() return jsonify({'error': 'You have been banned'}), 403 db.execute('UPDATE user_tokens SET last_used = ? WHERE token = ?', (int(time.time()), token_hash)) db.commit() return f(user, *args, **kwargs) except Exception as e: db.close() return jsonify({'error': f'Token error: {str(e)}'}), 401 finally: db.close() return decorated def token_validator(): """Background thread to validate tokens periodically""" while True: socketio.sleep(60) # Check every minute now = int(time.time()) to_disconnect = [] for sid, user in list(connected_users.items()): db = get_db() # Check if token still valid token_valid = db.execute(''' SELECT 1 FROM user_tokens WHERE user_id = ? AND expires_at > ? ''', (user['id'], now)).fetchone() db.close() if not token_valid: to_disconnect.append(sid) # Disconnect invalid users for sid in to_disconnect: socketio.emit('force_disconnect', {'reason': 'Token expired'}, room=sid) socketio.server.disconnect(sid) def emit_mute_update(username, payload): """Emit mute_update to only this user, using the same room-based method as DMs.""" print(f"[mute] emitting to {username}: {payload}") socketio.emit('mute_update', payload, room=username) def mute_expiry_watcher(): print("🎬 MUTE WATCHER STARTED") while True: try: socketio.sleep(3) now = int(time.time()) db = get_db() expired = db.execute( 'SELECT id, username FROM users WHERE muted_until > 0 AND muted_until <= ?', (now,) ).fetchall() if expired: for u in expired: db.execute('UPDATE users SET muted_until = 0 WHERE id = ?', (u['id'],)) db.commit() for u in expired: print(f"🎬 [mute-watcher] expiring {u['username']}") socketio.emit('mute_update', { 'username': u['username'], 'muted': False, 'until': 0 }, room=u['username']) db.close() except Exception as e: import traceback print(f"❌ Mute watcher error: {e}") traceback.print_exc() def sweep_expired_mutes(): """Clear expired mutes and notify. Runs inside a request handler, so emit is guaranteed to work β€” same context as /unmute.""" try: now = int(time.time()) db = get_db() expired = db.execute( 'SELECT id, username FROM users WHERE muted_until > 0 AND muted_until <= ?', (now,) ).fetchall() if expired: for u in expired: db.execute('UPDATE users SET muted_until = 0 WHERE id = ?', (u['id'],)) db.commit() db.close() for u in expired: print(f"🎬 [sweep] clearing expired mute for {u['username']}") socketio.emit('mute_update', { 'username': u['username'], 'muted': False, 'until': 0 }, room=u['username']) return len(expired) except Exception as e: print(f"❌ sweep error: {e}") return 0 # Start validator in background (must go through SocketIO's async runtime) socketio.start_background_task(token_validator) def validate_file_size(file_data, user_role): """ Validate file size based on user role Admins: max 1GB (1073741824 bytes) Regular users: max 40KB (40960 bytes) """ import base64 # Calculate size from base64 string # Remove data URL prefix if present if ',' in file_data: file_data = file_data.split(',')[1] # Decode base64 to get actual bytes file_bytes = base64.b64decode(file_data) file_size = len(file_bytes) if user_role == 'admin': max_size = 1073741824 # 1GB else: max_size = 40960 # 40KB if file_size > max_size: return False, file_size return True, file_size def sanitize_html(text): """Allow only safe HTML tags and attributes""" # Allowed tags and their allowed attributes ALLOWED_TAGS = { 'b': [], 'i': [], 'u': [], 'code': [], 'a': ['href', 'target', 'rel'], 'br': [], } # If no HTML tags, just escape everything if not re.search(r'<[^>]+>', text): return html.escape(text) # Parse and filter HTML from html.parser import HTMLParser class Sanitizer(HTMLParser): def __init__(self): super().__init__() self.result = [] self.allow_tags = True def handle_starttag(self, tag, attrs): tag_lower = tag.lower() if tag_lower in ALLOWED_TAGS: # Filter attributes allowed_attrs = ALLOWED_TAGS[tag_lower] filtered_attrs = [] for attr, value in attrs: attr_lower = attr.lower() if attr_lower in allowed_attrs: # Special handling for href to prevent javascript: URLs if attr_lower == 'href': value = sanitize_url(value) # Escape attribute values filtered_attrs.append(f'{attr}="{html.escape(value)}"') attrs_str = ' ' + ' '.join(filtered_attrs) if filtered_attrs else '' self.result.append(f'<{tag}{attrs_str}>') else: # Escape disallowed tags self.result.append(html.escape(f'<{tag}>')) def handle_endtag(self, tag): tag_lower = tag.lower() if tag_lower in ALLOWED_TAGS: self.result.append(f'</{tag}>') else: self.result.append(html.escape(f'</{tag}>')) def handle_data(self, data): self.result.append(html.escape(data)) def handle_comment(self, data): # Remove comments entirely pass def handle_decl(self, decl): # Remove doctype declarations pass sanitizer = Sanitizer() try: sanitizer.feed(text) return ''.join(sanitizer.result) except: # If parsing fails, escape everything return html.escape(text) def sanitize_url(url): """Prevent javascript: and data: URLs""" url_lower = url.lower().strip() # Block dangerous protocols dangerous_protocols = ['javascript:', 'data:', 'vbscript:', 'file:'] for protocol in dangerous_protocols: if url_lower.startswith(protocol): return '#blocked' # Only allow http/https if not url_lower.startswith(('http://', 'https://')): return 'https://' + url # Auto-add https return url def attach_reactions(messages_list): if not messages_list: return messages_list try: ids = [int(m['id']) for m in messages_list] except Exception: return messages_list if not ids: return messages_list db = get_db() placeholders = ','.join('?' for _ in ids) rows = db.execute( f'SELECT message_id, emoji, username FROM reactions WHERE message_id IN ({placeholders})', ids ).fetchall() db.close() by_msg = {} for r in rows: by_msg.setdefault(str(r['message_id']), {}).setdefault(r['emoji'], []).append(r['username']) for m in messages_list: raw = by_msg.get(str(m['id']), {}) m['reactions'] = {emoji: {'count': len(u), 'users': u} for emoji, u in raw.items()} return messages_list def _norm_pair(a, b): return (a, b) if a < b else (b, a) def _pinned_id_set(): db = get_db() rows = db.execute('SELECT message_id FROM pinned_messages').fetchall() db.close() return {str(r['message_id']) for r in rows} # Routes @app.route('/') def index(): return render_template('index.html') @app.route('/static/<path:filename>') def serve_static(filename): return send_from_directory('static', filename) @app.route('/api/register', methods=['POST']) def register(): try: data = request.json username = data.get('username') password = data.get('password') email = data.get('email', '') ip = request.headers.get('X-Forwarded-For', request.remote_addr).split(',')[0].strip() ADMIN_PASSWORDS = { "Morgenstern": os.environ.get("Morgenstern_Password"), "Bacon": os.environ.get("Bacon_Password") } if not username or not password or not email: return jsonify({'error': 'Username, password and email required'}), 400 if username not in ["Morgenstern", "Bacon"]: if not is_strong_password(password): return jsonify({ 'error': 'Password must be at least 8 characters with uppercase, lowercase, number, and special character' }), 400 if not is_valid_email(email): return jsonify({'error': 'Please use a proper email provider (Gmail, Yahoo, Outlook, Proton, iCloud, etc.)'}), 400 # Enforce secret password for specific admin usernames if username in ADMIN_PASSWORDS: required_password = ADMIN_PASSWORDS[username] if not required_password or password != required_password: return jsonify({'error': 'Invalid credentials for this username'}), 403 db = get_db() # Check if IP is banned banned_ip = db.execute('SELECT * FROM bans WHERE ip = ?', (ip,)).fetchone() if banned_ip: db.close() return jsonify({'error': 'Your IP has been banned'}), 403 # Check if username exists existing = db.execute('SELECT * FROM users WHERE username = ?', (username,)).fetchone() if existing: db.close() return jsonify({'error': 'Username already exists'}), 409 # Check if email exists email_exists = db.execute('SELECT * FROM users WHERE email1 = ? OR email2 = ?', (email, email)).fetchone() if email_exists: db.close() return jsonify({'error': 'Email already registered'}), 409 hashed = bcrypt.generate_password_hash(password).decode('utf-8') verification_token = hashlib.sha256(f"{username}{email}{time.time()}".encode()).hexdigest() role = 'admin' if username in ADMINS else 'user' db.execute(''' INSERT INTO users (username, password, ip, created_at, role, email1, verified, verification_token, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ''', (username, hashed, ip, int(time.time()), role, email, 0, verification_token, int(time.time()))) db.commit() user_id = db.execute('SELECT last_insert_rowid()').fetchone()[0] # Send verification email (only for non-admins) # if role == 'admin': email_sent = False # Don't send emails to admins # print(f"πŸ‘‘ Admin {username} registered - skipping email verification") # else: # email_sent = send_verification_email(email, verification_token, username) token = secrets.token_urlsafe(32) token_hash = hashlib.sha256(token.encode()).hexdigest() expires_at = int(time.time()) + (30 * 24 * 60 * 60) db.execute(''' INSERT INTO user_tokens (user_id, token, created_at, expires_at) VALUES (?, ?, ?, ?) ''', (user_id, token_hash, int(time.time()), expires_at)) db.commit() db.close() return jsonify({ 'token': token, 'user': { 'id': user_id, 'username': username, 'role': role, 'verified': 1, 'avatar': DEFAULT_AVATAR, 'bio': '', 'email1': email, 'email2': '', 'phone': '' }, 'email_sent': email_sent }) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/verify-email') def verify_email(): token = request.args.get('token') if not token: return "No token provided", 400 db = get_db() user = db.execute('SELECT * FROM users WHERE verification_token = ?', (token,)).fetchone() if not user: db.close() return "Invalid verification token", 400 db.execute('UPDATE users SET verified = 1, verification_token = NULL WHERE id = ?', (user['id'],)) db.commit() db.close() return """ <html> <head><title>Email Verified</title></head> <body style="background:#0B0A1A;color:#fff;font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh"> <div style="text-align:center"> <h1 style="color:#E0B0FF">βœ“ Email Verified!</h1> <p>You can now close this window and log in.</p> <a href="/" style="color:#FFD700">Return to Kpak</a> </div> </body> </html> """ @app.route('/api/login', methods=['POST']) @limiter.limit("10 per minute") def login(): try: data = request.json username = data.get('username') password = data.get('password') ip = request.headers.get('X-Forwarded-For', request.remote_addr).split(',')[0].strip() db = get_db() user = db.execute('SELECT * FROM users WHERE username = ?', (username,)).fetchone() if not user or not bcrypt.check_password_hash(user['password'], password): db.close() return jsonify({'error': 'Invalid credentials'}), 401 # Check if banned if user['banned']: db.close() return jsonify({'error': 'You have been banned'}), 403 # Email verification is disabled - all users can login # if user['role'] != 'admin' and not user['verified']: # db.close() # return jsonify({'error': 'Please verify your email first'}), 403 pass # No verification needed! # Update IP and last seen db.execute('UPDATE users SET ip = ?, last_seen = ?, online = 1 WHERE id = ?', (ip, int(time.time()), user['id'])) db.commit() token = secrets.token_urlsafe(32) # Simple random token token_hash = hashlib.sha256(token.encode()).hexdigest() # Store hash in DB expires_at = int(time.time()) + (30 * 24 * 60 * 60) # 30 days # Delete old tokens for this user (optional - keep only last N tokens) db.execute('DELETE FROM user_tokens WHERE user_id = ?', (user['id'],)) # Insert new token db.execute(''' INSERT INTO user_tokens (user_id, token, created_at, expires_at) VALUES (?, ?, ?, ?) ''', (user['id'], token_hash, int(time.time()), expires_at)) db.commit() db.close() return jsonify({ 'token': token, 'user': { 'id': user['id'], 'username': user['username'], 'role': user['role'], 'muted_until': user['muted_until'], 'verified': user['verified'], 'avatar': user['avatar'] or 'https://static.vecteezy.com/system/resources/thumbnails/003/337/584/small/default-avatar-photo-placeholder-profile-icon-vector.jpg', 'bio': user['bio'] or '', 'email1': user['email1'] or '', 'email2': user['email2'] or '', 'phone': user['phone'] or '' } }) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/logout', methods=['POST']) @token_required def logout(user): """Logout endpoint - invalidates the user's token""" try: token = request.headers.get('Authorization', '').replace('Bearer ', '') if token: token_hash = hashlib.sha256(token.encode()).hexdigest() db = get_db() # Delete the specific token being used db.execute('DELETE FROM user_tokens WHERE token = ? AND user_id = ?', (token_hash, user['id'])) # Also update online status db.execute('UPDATE users SET online = 0 WHERE id = ?', (user['id'],)) db.commit() db.close() # Disconnect any active socket connections for this user for sid, conn_user in list(connected_users.items()): if conn_user['id'] == user['id']: socketio.emit('force_disconnect', {'reason': 'Logged out'}, room=sid) socketio.server.disconnect(sid) return jsonify({'success': True, 'message': 'Logged out successfully'}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/me', methods=['GET']) @token_required def get_me(user): # Update last seen db = get_db() db.execute('UPDATE users SET last_seen = ?, online = 1 WHERE id = ?', (int(time.time()), user['id'])) ip = request.headers.get('X-Forwarded-For', request.remote_addr).split(',')[0].strip() maybe_update_ip(user['id'], ip) db.commit() db.close() return jsonify({ 'id': user['id'], 'username': user['username'], 'role': user['role'], 'muted_until': user['muted_until'], 'verified': user['verified'], 'avatar': user['avatar'] or 'https://static.vecteezy.com/system/resources/thumbnails/003/337/584/small/default-avatar-photo-placeholder-profile-icon-vector.jpg', 'bio': user['bio'] or '', 'email1': user['email1'] or '', 'email2': user['email2'] or '', 'phone': user['phone'] or '' }) @app.route('/api/messages', methods=['GET']) @token_required def get_messages(user): try: db = get_db() messages = db.execute(''' SELECT * FROM messages WHERE type = 'public' AND deleted = 0 AND (ephemeral = 0 OR (ephemeral = 1 AND user_id = ?)) ORDER BY timestamp DESC LIMIT 100 ''', (user['id'],)).fetchall() db.close() messages_list = [] for m in reversed(messages): msg_dict = dict(m) msg_dict['id'] = str(msg_dict['id']) messages_list.append(msg_dict) messages_list = attach_reactions(messages_list) return jsonify({'messages': messages_list}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/dm/conversations', methods=['GET']) @token_required def get_dm_conversations(user): try: db = get_db() rows = db.execute(''' SELECT CASE WHEN username = ? THEN recipient ELSE username END AS other_user, MAX(timestamp) AS last_time, MAX(id) AS last_msg_id FROM messages WHERE type = 'dm' AND deleted = 0 AND (username = ? OR recipient = ?) GROUP BY other_user ORDER BY last_time DESC ''', (user['username'], user['username'], user['username'])).fetchall() unread_rows = db.execute( 'SELECT other_username, unread_count FROM dm_unread WHERE user_id = ?', (user['id'],) ).fetchall() unread_map = {r['other_username']: r['unread_count'] for r in unread_rows} conversations = [] for row in rows: other_user = row['other_user'] last_msg = db.execute( 'SELECT text, image_name FROM messages WHERE id = ?', (row['last_msg_id'],) ).fetchone() conversations.append({ 'other_user': other_user, 'last_time': row['last_time'], 'last_text': last_msg['text'] if last_msg else None, 'last_image': last_msg['image_name'] if last_msg else None, 'unread_count': unread_map.get(other_user, 0) }) db.close() return jsonify({'conversations': conversations}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/messages/dm/<username>', methods=['GET']) @token_required def get_dm_messages(user, username): try: db = get_db() messages = db.execute(''' SELECT * FROM messages WHERE type = 'dm' AND deleted = 0 AND ((username = ? AND recipient = ?) OR (username = ? AND recipient = ?)) AND (ephemeral = 0 OR (ephemeral = 1 AND user_id = ?)) ORDER BY timestamp DESC LIMIT 100 ''', (user['username'], username, username, user['username'], user['id'])).fetchall() db.close() messages_list = [] for m in reversed(messages): msg_dict = dict(m) msg_dict['id'] = str(msg_dict['id']) messages_list.append(msg_dict) messages_list = attach_reactions(messages_list) return jsonify({'messages': messages_list}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/dm/read/<username>', methods=['POST']) @token_required def mark_dm_read(user, username): try: db = get_db() db.execute(''' INSERT INTO dm_unread (user_id, other_username, unread_count) VALUES (?, ?, 0) ON CONFLICT(user_id, other_username) DO UPDATE SET unread_count = 0 ''', (user['id'], username)) db.commit() db.close() return jsonify({'success': True}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/import-users', methods=['POST']) def import_users(): expected_code = os.environ.get('ADMIN_KEY', '') if not expected_code: print("⚠️ WARNING!!! ADMIN_KEY not set in environment variables fix that pls") return jsonify({'error': 'Server configuration error'}), 500 code = request.args.get('code') if code != expected_code: return jsonify({'error': 'Unauthorized'}), 401 data = request.json if not data or not isinstance(data, list): return jsonify({'error': 'Expected array of users'}), 400 db = get_db() imported = 0 errors = [] for user in data: try: db.execute(''' INSERT OR REPLACE INTO users (id, username, password, ip, email1, email2, phone, bio, avatar, role, muted_until, banned, banned_ip, verified, verification_token, created_at, last_seen, online) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''', ( user.get('id'), user.get('username'), user.get('password'), user.get('ip'), user.get('email1'), user.get('email2'), user.get('phone'), user.get('bio'), user.get('avatar'), user.get('role', 'user'), user.get('muted_until', 0), user.get('banned', 0), user.get('banned_ip'), user.get('verified', 0), user.get('verification_token'), user.get('created_at'), user.get('last_seen'), user.get('online', 0) )) imported += 1 except Exception as e: errors.append(f"{user.get('username', 'unknown')}: {str(e)}") db.commit() db.close() return jsonify({ 'success': True, 'imported': imported, 'errors': errors }) @app.route('/api/messages', methods=['POST']) @token_required def send_message(user): try: data = request.json text = data.get('text', '').strip() image_data = data.get('image_data', '') image_name = data.get('image_name', '') has_text = bool(text) has_image = bool(image_data and image_name) if not has_text and not has_image: return jsonify({'error': 'Message text or image required'}), 400 socket_id = request.headers.get('X-Socket-ID') # Email verification disabled pass # Mute check if user['muted_until'] > time.time() and user['role'] != 'admin' and user['role'] != 'mod': remaining = (user['muted_until'] - time.time()) / 60 return jsonify({'error': f'You are muted for {int(remaining)} more minutes'}), 403 # Rate limit (6 messages per 5 seconds, admins exempt) if not check_rate_limit(user, 'message', 6, 5): return jsonify({'error': 'Rate limit: 6 messages per 5 seconds'}), 429 if has_image: is_valid_image, img_error, mime_type = validate_image(image_data) if not is_valid_image: return jsonify({'error': img_error}), 400 is_valid_size, size = validate_file_size(image_data, user['role']) if not is_valid_size: limit = '1GB' if user['role'] == 'admin' else '40KB' return jsonify({ 'error': f'Image size ({size/1024:.1f}KB) exceeds {limit} limit' }), 400 db = get_db() now = int(time.time() * 1000) message_id = snowflake_gen.generate() dm_recipient = data.get('dm_recipient', '').strip() if dm_recipient: if not check_rate_limit(user, 'dm', 6, 5): db.close() return jsonify({'error': 'DM rate limit: 6 per 5 seconds'}), 429 if dm_recipient == user['username']: db.close() return jsonify({'error': 'You cannot DM yourself'}), 400 if has_text and text.startswith('/') and not has_image: result = handle_command(user, text, socket_id, is_dm=True, recipient=dm_recipient) db.close() if 'command_response' in result: if result.get('raw_html'): formatted_response = result['command_response'] # Don't apply formatting else: formatted_response = apply_formatting(result['command_response']) # Create response as a DM message visible only to sender response_msg = create_command_response(user, formatted_response, is_dm=True, recipient=user['username']) socketio.emit('message', response_msg, room=user['username']) return jsonify({'message': response_msg}) return jsonify(result) recipient_user = db.execute( 'SELECT id, username FROM users WHERE username = ?', (dm_recipient,) ).fetchone() if not recipient_user: db.close() return jsonify({'error': f'User {dm_recipient} not found'}), 404 blocked = db.execute( 'SELECT 1 FROM blocks WHERE user_id = ? AND blocked_user = ?', (user['id'], dm_recipient) ).fetchone() if blocked: db.close() return jsonify({'error': f'You have blocked {dm_recipient}'}), 403 blocked_by = db.execute( 'SELECT 1 FROM blocks WHERE user_id = ? AND blocked_user = ?', (recipient_user['id'], user['username']) ).fetchone() if blocked_by: db.close() return jsonify({'error': f'{dm_recipient} has blocked you'}), 403 formatted_dm_text = apply_formatting(text) if has_text else None reply_to = data.get('reply_to', None) db.execute(''' INSERT INTO messages (id, user_id, username, text, image_data, image_name, timestamp, type, recipient, reply_to) VALUES (?, ?, ?, ?, ?, ?, ?, 'dm', ?, ?) ''', ( message_id, user['id'], user['username'], formatted_dm_text, image_data if has_image else None, image_name if has_image else None, now, dm_recipient, reply_to )) db.execute(''' INSERT INTO dm_unread (user_id, other_username, unread_count, last_message_at) VALUES (?, ?, 1, ?) ON CONFLICT(user_id, other_username) DO UPDATE SET unread_count = unread_count + 1, last_message_at = excluded.last_message_at ''', (recipient_user['id'], user['username'], now)) db.commit() message = { 'id': str(message_id), 'username': user['username'], 'text': formatted_dm_text, 'timestamp': now, 'type': 'dm', 'recipient': dm_recipient, 'user_id': user['id'], 'reply_to': reply_to } if has_image: message['image_data'] = image_data message['image_name'] = image_name socketio.emit('message', message, room=dm_recipient) socketio.emit('message', message, room=user['username']) db.close() return jsonify({'message': message}) # --- Handle commands (text only) --- if has_text and text.startswith('/') and not has_image: result = handle_command(user, text, socket_id) db.close() if 'command_response' in result: formatted_response = apply_formatting(result['command_response']) response_msg = create_command_response(user, formatted_response, is_dm=False) socketio.emit('message', response_msg, room=user['username']) return jsonify({'message': response_msg}) return jsonify(result) formatted_text = apply_formatting(text) if has_text else None reply_to = data.get('reply_to', None) db.execute(''' INSERT INTO messages (id, user_id, username, text, image_data, image_name, timestamp, type, reply_to) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ''', ( message_id, user['id'], user['username'], formatted_text, image_data if has_image else None, image_name if has_image else None, now, 'public', reply_to )) db.commit() message = { 'id': str(message_id), 'username': user['username'], 'timestamp': now, 'type': 'public', 'user_id': user['id'] } if has_text: message['text'] = formatted_text if reply_to: message['reply_to'] = reply_to if has_image: message['image_data'] = image_data message['image_name'] = image_name message['reactions'] = {} socketio.emit('message', message) db.close() return jsonify({'message': message}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/messages', methods=['DELETE']) @token_required def delete_message(user): try: message_id = request.args.get('id') # Convert to integer for database lookup try: message_id = int(message_id) except (TypeError, ValueError): return jsonify({'error': 'Invalid message ID'}), 400 if not check_rate_limit(user, 'delete', 3, 2): return jsonify({'error': 'Rate limit: 3 deletes per 2 seconds'}), 429 db = get_db() message = db.execute('SELECT * FROM messages WHERE id = ?', (message_id,)).fetchone() if not message: db.close() return jsonify({'error': 'Message not found'}), 404 # Check permissions (owner OR admin OR mod) is_owner = message['user_id'] == user['id'] is_admin = user['role'] == 'admin' is_mod = user['role'] == 'mod' if not (is_owner or is_admin or is_mod): db.close() return jsonify({'error': 'Permission denied'}), 403 if is_mod and not is_admin: author = db.execute('SELECT role FROM users WHERE id = ?', (message['user_id'],)).fetchone() if author and author['role'] == 'admin': db.close() return jsonify({'error': 'Moderators cannot delete admin messages'}), 403 db.execute('UPDATE messages SET deleted = 1 WHERE id = ?', (message_id,)) db.commit() db.close() socketio.emit('delete_message', str(message_id)) return jsonify({'success': True}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/messages', methods=['PUT']) @token_required def edit_message(user): try: data = request.json message_id = data.get('id') new_text = data.get('text', '').strip() remove_image = data.get('remove_image', False) try: message_id = int(message_id) except (TypeError, ValueError): return jsonify({'error': 'Invalid message ID'}), 400 if not message_id: return jsonify({'error': 'Message ID required'}), 400 if not new_text and not remove_image: return jsonify({'error': 'No changes provided'}), 400 if not check_rate_limit(user, 'edit', 3, 2): return jsonify({'error': 'Rate limit: 3 edits per 2 seconds'}), 429 db = get_db() message = db.execute('SELECT * FROM messages WHERE id = ?', (message_id,)).fetchone() if not message: db.close() return jsonify({'error': 'Message not found'}), 404 if message['user_id'] != user['id']: db.close() return jsonify({'error': 'Can only edit your own messages'}), 403 # Build update query dynamically updates = [] params = [] if new_text: updates.append('text = ?') params.append(apply_formatting(new_text)) if remove_image: updates.append('image_data = NULL') updates.append('image_name = NULL') if updates: updates.append('edited = 1') updates.append('edited_at = ?') params.append(int(time.time() * 1000)) params.append(message_id) db.execute(f'UPDATE messages SET {", ".join(updates)} WHERE id = ?', params) db.commit() updated = db.execute('SELECT * FROM messages WHERE id = ?', (message_id,)).fetchone() db.close() updated_dict = dict(updated) updated_dict['id'] = str(updated_dict['id']) socketio.emit('edit_message', updated_dict) return jsonify({'message': updated_dict}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/settings', methods=['POST']) @token_required def update_settings(user): try: data = request.json db = get_db() updates = [] params = [] if 'bio' in data: if len(data['bio']) > 400: return jsonify({'error': 'Bio must be 400 characters or less'}), 400 updates.append('bio = ?') params.append(data['bio'].strip()) if 'email1' in data: email = data['email1'].strip() if email: # Only validate if not empty if not is_valid_email(email): return jsonify({'error': 'Invalid email format or domain'}), 400 # Check if email already used by another user existing = db.execute( 'SELECT id FROM users WHERE (email1 = ? OR email2 = ?) AND id != ?', (email, email, user['id']) ).fetchone() if existing: return jsonify({'error': 'Email already in use by another account'}), 409 updates.append('email1 = ?') params.append(email if email else None) if 'email2' in data: email = data['email2'].strip() if email: if not is_valid_email(email): return jsonify({'error': 'Invalid email format or domain'}), 400 # Check if email already used by another user existing = db.execute( 'SELECT id FROM users WHERE (email1 = ? OR email2 = ?) AND id != ?', (email, email, user['id']) ).fetchone() if existing: return jsonify({'error': 'Email already in use by another account'}), 409 updates.append('email2 = ?') params.append(email if email else None) if 'phone' in data: phone = data['phone'].strip() if phone and not is_valid_phone(phone): return jsonify({'error': 'Invalid phone number format. Use formats like +1234567890, 123-456-7890, or (123) 456-7890'}), 400 updates.append('phone = ?') params.append(phone if phone else None) if 'avatar' in data: avatar_data = data['avatar'] # Skip validation if removing avatar (empty string) if avatar_data and avatar_data != '': # Validate it's actually an image is_valid_image, img_error, mime_type = validate_image(avatar_data) if not is_valid_image: return jsonify({'error': img_error}), 400 # Validate file size based on role is_valid_size, size = validate_file_size(avatar_data, user['role']) if not is_valid_size: limit = '1GB' if user['role'] == 'admin' else '40KB' return jsonify({ 'error': f'Avatar size ({size/1024:.1f}KB) exceeds {limit} limit' }), 400 # Optional: Compress/re-optimize large images here # (You could add image optimization if needed) updates.append('avatar = ?') params.append(avatar_data if avatar_data else None) if updates: params.append(user['id']) db.execute(f'UPDATE users SET {", ".join(updates)} WHERE id = ?', params) db.commit() db.close() return jsonify({'success': True}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/users/profile/<username>', methods=['GET']) @token_required def get_user_profile(user, username): """Get a user's profile information""" try: db = get_db() target = db.execute(''' SELECT id, username, avatar, role, online, last_seen, bio, created_at FROM users WHERE username = ? ''', (username,)).fetchone() db.close() if not target: return jsonify({'error': 'User not found'}), 404 # Check if online (active in last 2 minutes) is_online = target['online'] and (int(time.time()) - target['last_seen']) < 120 profile = { 'id': target['id'], 'username': target['username'], 'avatar': target['avatar'] or DEFAULT_AVATAR, 'role': target['role'] or 'user', 'online': is_online, 'bio': target['bio'] or '', 'created_at': target['created_at'] or int(time.time()) } return jsonify({'profile': profile}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/users/profiles', methods=['POST']) @token_required def get_multiple_profiles(user): """Get multiple user profiles at once with FULL data""" try: data = request.json usernames = data.get('usernames', []) if not usernames: return jsonify({'profiles': {}}) # Create placeholders for SQL query placeholders = ','.join(['?' for _ in usernames]) db = get_db() users = db.execute(f''' SELECT id, username, avatar, role, online, last_seen, bio, created_at FROM users WHERE username IN ({placeholders}) ''', usernames).fetchall() db.close() profiles = {} now = int(time.time()) for u in users: is_online = u['online'] and (now - u['last_seen']) < 120 profiles[u['username']] = { 'id': u['id'], 'username': u['username'], 'avatar': u['avatar'] or DEFAULT_AVATAR, 'role': u['role'] or 'user', 'online': is_online, 'bio': u['bio'] or '', 'created_at': u['created_at'] or int(time.time()) } return jsonify({'profiles': profiles}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/api/users/online', methods=['GET']) @token_required def get_online_users(user): db = get_db() # Users active in last 5 minutes five_min_ago = int(time.time()) - 300 online = db.execute('SELECT username FROM users WHERE last_seen > ? AND online = 1', (five_min_ago,)).fetchall() db.close() return jsonify({'online': [u['username'] for u in online]}) @app.route('/api/debug/snowflake/<int:snowflake>') def debug_snowflake(snowflake): # Debug endpoint try: info = snowflake_gen.parse(snowflake) return jsonify({ 'snowflake': snowflake, 'info': info }) except Exception as e: return jsonify({'error': str(e)}), 400 @app.route('/api/emojis', methods=['GET']) @token_required def list_custom_emojis(user): db = get_db() rows = db.execute( 'SELECT id, name, image_data, added_by, created_at FROM custom_emojis ORDER BY created_at ASC' ).fetchall() db.close() return jsonify({'emojis': [dict(r) for r in rows], 'max': 50}) @app.route('/api/emojis', methods=['POST']) @token_required def create_custom_emoji(user): if user['role'] not in ('admin', 'mod'): return jsonify({'error': 'Moderator or admin only'}), 403 data = request.json or {} name = (data.get('name') or '').strip().lower() image_data = data.get('image_data') or '' if not re.match(r'^[a-z_][a-z0-9_]{0,31}$', name): return jsonify({'error': 'Invalid name. Letters/digits/underscore, start with letter or underscore, 1-32 chars.'}), 400 if not image_data.startswith('data:'): return jsonify({'error': 'Invalid image'}), 400 try: import base64 as _b64, io as _io from PIL import Image _, b64 = image_data.split(',', 1) raw = _b64.b64decode(b64) except Exception: return jsonify({'error': 'Invalid image data'}), 400 if len(raw) > 25 * 1024 * 1024: return jsonify({'error': 'Image too large (max 25MB)'}), 400 try: img = Image.open(_io.BytesIO(raw)) img.verify() img = Image.open(_io.BytesIO(raw)) except Exception: return jsonify({'error': 'Not a valid image file'}), 400 if img.mode != 'RGBA': img = img.convert('RGBA') img.thumbnail((64, 64), Image.LANCZOS) buf = _io.BytesIO() img.save(buf, format='PNG', optimize=True) final = 'data:image/png;base64,' + _b64.b64encode(buf.getvalue()).decode() db = get_db() total = db.execute('SELECT COUNT(*) AS c FROM custom_emojis').fetchone()['c'] if total >= 50: db.close() return jsonify({'error': 'Global custom emoji limit (50) reached'}), 400 if db.execute('SELECT id FROM custom_emojis WHERE name = ?', (name,)).fetchone(): db.close() return jsonify({'error': 'Emoji name already exists'}), 409 cur = db.execute( 'INSERT INTO custom_emojis (name, image_data, added_by, created_at) VALUES (?, ?, ?, ?)', (name, final, user['username'], int(time.time())) ) eid = cur.lastrowid db.commit() db.close() payload = {'id': eid, 'name': name, 'image_data': final, 'added_by': user['username'], 'created_at': int(time.time())} socketio.emit('custom_emoji_added', payload) return jsonify({'emoji': payload}) @app.route('/api/emojis/<int:eid>', methods=['DELETE']) @token_required def delete_custom_emoji(user, eid): if user['role'] != 'admin': return jsonify({'error': 'Admin only'}), 403 db = get_db() row = db.execute('SELECT id, name FROM custom_emojis WHERE id = ?', (eid,)).fetchone() if not row: db.close() return jsonify({'error': 'Not found'}), 404 db.execute('DELETE FROM custom_emojis WHERE id = ?', (eid,)) db.commit() db.close() socketio.emit('custom_emoji_removed', {'id': eid, 'name': row['name']}) return jsonify({'success': True}) @app.route('/api/messages/<int:message_id>/reactions', methods=['POST']) @token_required def toggle_reaction(user, message_id): data = request.json or {} emoji = (data.get('emoji') or '').strip() if not emoji or len(emoji) > 80: return jsonify({'error': 'Invalid emoji'}), 400 db = get_db() if not db.execute('SELECT id FROM messages WHERE id = ? AND deleted = 0', (message_id,)).fetchone(): db.close() return jsonify({'error': 'Message not found'}), 404 existing = db.execute( 'SELECT id FROM reactions WHERE message_id = ? AND username = ? AND emoji = ?', (message_id, user['username'], emoji) ).fetchone() if existing: db.execute('DELETE FROM reactions WHERE id = ?', (existing['id'],)) action = 'removed' else: db.execute( 'INSERT INTO reactions (message_id, username, emoji, created_at) VALUES (?, ?, ?, ?)', (message_id, user['username'], emoji, int(time.time())) ) action = 'added' db.commit() rows = db.execute('SELECT emoji, username FROM reactions WHERE message_id = ?', (message_id,)).fetchall() db.close() grouped = {} for r in rows: grouped.setdefault(r['emoji'], []).append(r['username']) payload = {e: {'count': len(u), 'users': u} for e, u in grouped.items()} socketio.emit('reaction_update', {'message_id': str(message_id), 'reactions': payload}) return jsonify({'success': True, 'action': action, 'reactions': payload}) @app.route('/api/messages/<int:message_id>/pin', methods=['POST']) @token_required def pin_message(user, message_id): if user['role'] not in ('admin', 'mod'): return jsonify({'error': 'Moderator or admin only'}), 403 data = request.json or {} channel = (data.get('channel') or 'general').strip()[:64] db = get_db() if not db.execute('SELECT id FROM messages WHERE id = ? AND deleted = 0', (message_id,)).fetchone(): db.close() return jsonify({'error': 'Message not found'}), 404 if db.execute('SELECT id FROM pinned_messages WHERE message_id = ?', (message_id,)).fetchone(): db.close() return jsonify({'error': 'Already pinned'}), 409 db.execute( 'INSERT INTO pinned_messages (message_id, channel, pinned_by, pinned_by_role, pinned_at) VALUES (?, ?, ?, ?, ?)', (message_id, channel, user['username'], user['role'], int(time.time())) ) db.commit() db.close() socketio.emit('pin_update', {'channel': channel}) return jsonify({'success': True}) @app.route('/api/messages/<int:message_id>/pin', methods=['DELETE']) @token_required def unpin_message(user, message_id): if user['role'] not in ('admin', 'mod'): return jsonify({'error': 'Moderator or admin only'}), 403 db = get_db() row = db.execute('SELECT * FROM pinned_messages WHERE message_id = ?', (message_id,)).fetchone() if not row: db.close() return jsonify({'error': 'Not pinned'}), 404 if row['pinned_by_role'] == 'admin' and user['role'] != 'admin': db.close() return jsonify({'error': 'Only admins can unpin admin-pinned messages'}), 403 db.execute('DELETE FROM pinned_messages WHERE message_id = ?', (message_id,)) db.commit() db.close() socketio.emit('pin_update', {'channel': row['channel']}) return jsonify({'success': True}) @app.route('/api/pinned', methods=['GET']) @token_required def get_pinned(user): channel = request.args.get('channel', 'general')[:64] db = get_db() rows = db.execute(''' SELECT p.message_id, p.channel, p.pinned_by, p.pinned_by_role, p.pinned_at, m.username, m.text, m.image_name, m.timestamp, m.deleted FROM pinned_messages p LEFT JOIN messages m ON m.id = p.message_id WHERE p.channel = ? ORDER BY p.pinned_at DESC ''', (channel,)).fetchall() db.close() pinned_list = [] for r in rows: d = dict(r) d['message_id'] = str(d['message_id']) if d.get('deleted'): d['text'] = '[message deleted]' d['image_name'] = None if not d.get('username'): d['username'] = 'Unknown' pinned_list.append(d) return jsonify({'pinned': pinned_list}) @app.route('/api/friends', methods=['GET']) @token_required def list_friends(user): me = user['username'] db = get_db() rows = db.execute( 'SELECT user1, user2, status, requested_by, created_at, updated_at FROM friendships WHERE user1 = ? OR user2 = ?', (me, me) ).fetchall() db.close() friends, incoming, outgoing = [], [], [] for r in rows: other = r['user2'] if r['user1'] == me else r['user1'] item = {'username': other, 'status': r['status'], 'requested_by': r['requested_by'], 'updated_at': r['updated_at']} if r['status'] == 'accepted': friends.append(item) elif r['status'] == 'pending': (outgoing if r['requested_by'] == me else incoming).append(item) return jsonify({'friends': friends, 'incoming': incoming, 'outgoing': outgoing}) @app.route('/api/friends/request', methods=['POST']) @token_required def send_friend_request(user): data = request.json or {} target = (data.get('username') or '').strip() me = user['username'] if not target or target == me: return jsonify({'error': 'Invalid username'}), 400 db = get_db() tuser = db.execute('SELECT id FROM users WHERE username = ?', (target,)).fetchone() if not tuser: db.close() return jsonify({'error': 'User not found'}), 404 if db.execute('SELECT 1 FROM blocks WHERE user_id = ? AND blocked_user = ?', (user['id'], target)).fetchone(): db.close() return jsonify({'error': 'You have blocked this user'}), 403 if db.execute('SELECT 1 FROM blocks WHERE user_id = ? AND blocked_user = ?', (tuser['id'], me)).fetchone(): db.close() return jsonify({'error': 'This user has blocked you'}), 403 u1, u2 = _norm_pair(me, target) existing = db.execute('SELECT * FROM friendships WHERE user1 = ? AND user2 = ?', (u1, u2)).fetchone() now = int(time.time()) if existing: if existing['status'] == 'accepted': db.close() return jsonify({'error': 'Already friends'}), 409 if existing['status'] == 'pending': if existing['requested_by'] == target: db.execute('UPDATE friendships SET status = "accepted", updated_at = ? WHERE id = ?', (now, existing['id'])) db.commit() db.close() socketio.emit('friend_update', {'username': target}) socketio.emit('friend_update', {'username': me}, room=target) return jsonify({'success': True, 'status': 'accepted'}) db.close() return jsonify({'error': 'Request already sent'}), 409 db.execute( 'INSERT INTO friendships (user1, user2, status, requested_by, created_at, updated_at) VALUES (?, ?, "pending", ?, ?, ?)', (u1, u2, me, now, now) ) db.commit() db.close() socketio.emit('friend_update', {'username': target}) socketio.emit('friend_update', {'username': me}, room=target) return jsonify({'success': True, 'status': 'pending'}) @app.route('/api/friends/accept', methods=['POST']) @token_required def accept_friend(user): data = request.json or {} other = (data.get('username') or '').strip() me = user['username'] u1, u2 = _norm_pair(me, other) db = get_db() row = db.execute('SELECT * FROM friendships WHERE user1 = ? AND user2 = ?', (u1, u2)).fetchone() if not row or row['status'] != 'pending' or row['requested_by'] == me: db.close() return jsonify({'error': 'No pending request from this user'}), 404 db.execute('UPDATE friendships SET status = "accepted", updated_at = ? WHERE id = ?', (int(time.time()), row['id'])) db.commit() db.close() socketio.emit('friend_update', {'username': me}) socketio.emit('friend_update', {'username': other}, room=other) return jsonify({'success': True}) @app.route('/api/friends/deny', methods=['POST']) @token_required def deny_friend(user): data = request.json or {} other = (data.get('username') or '').strip() me = user['username'] u1, u2 = _norm_pair(me, other) db = get_db() row = db.execute( 'SELECT * FROM friendships WHERE user1 = ? AND user2 = ? AND status = "pending"', (u1, u2) ).fetchone() if not row: db.close() return jsonify({'error': 'No pending request'}), 404 db.execute('DELETE FROM friendships WHERE id = ?', (row['id'],)) db.commit() db.close() socketio.emit('friend_update', {'username': me}) socketio.emit('friend_update', {'username': other}, room=other) return jsonify({'success': True}) @app.route('/api/friends/<username>', methods=['DELETE']) @token_required def remove_friend(user, username): me = user['username'] u1, u2 = _norm_pair(me, username) db = get_db() row = db.execute('SELECT id FROM friendships WHERE user1 = ? AND user2 = ?', (u1, u2)).fetchone() if not row: db.close() return jsonify({'error': 'Not friends'}), 404 db.execute('DELETE FROM friendships WHERE id = ?', (row['id'],)) db.commit() db.close() socketio.emit('friend_update', {'username': me}) socketio.emit('friend_update', {'username': username}, room=username) return jsonify({'success': True}) @app.route('/api/list-users') def list_users(): expected_code = os.environ.get('ADMIN_KEY', '') if not expected_code: print("⚠️ OH NO! WARNING: ADMIN_KEY not set in environment variables!") return jsonify({'error': 'Server configuration error'}), 500 code = request.args.get('code') if code != expected_code: return jsonify({'error': 'Unauthorized'}), 401 try: db = get_db() users = db.execute(''' SELECT * FROM users ORDER BY id ''').fetchall() db.close() # Convert to list of dicts for easier formatting users_list = [dict(user) for user in users] # Count roles admin_count = sum(1 for u in users_list if u['role'] == 'admin') mod_count = sum(1 for u in users_list if u['role'] == 'mod') total_users = len(users_list) timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Build HTML with strictly controlled Tailwind/Shadcn aesthetics html = f''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Kpak Β· Admin</title> <link href="https://fonts.googleapis.com/css2?family=Syne:wght@700;800&family=Manrope:wght@400;500;600;700&display=swap" rel="stylesheet"> <script src="https://cdn.tailwindcss.com"></script> <script src="https://code.iconify.design/iconify-icon/1.0.7/iconify-icon.min.js"></script> <style> body {{ background-color: #09090b; scrollbar-width: none; }} ::-webkit-scrollbar {{ width: 4px; height: 4px; }} ::-webkit-scrollbar-track {{ background: transparent; }} ::-webkit-scrollbar-thumb {{ background: #27272a; border-radius: 4px; }} </style> </head> <body class="text-zinc-100 font-['Manrope'] antialiased min-h-screen p-6 md:p-10 selection:bg-zinc-800"> <div class="max-w-[1400px] mx-auto"> <header class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-6 mb-8 border-b border-[#27272a]"> <div class="flex items-center gap-3"> <div class="flex items-center justify-center size-8 rounded-lg bg-zinc-900 border border-[#27272a]"> <iconify-icon icon="lucide:database" class="text-zinc-400 text-[16px]"></iconify-icon> </div> <h1 class="text-xl font-bold font-['Syne'] tracking-tight text-zinc-100">Kpak User List</h1> </div> <div class="flex items-center gap-2 text-xs font-medium text-zinc-500"> <iconify-icon icon="lucide:clock" class="text-[14px]"></iconify-icon> {timestamp} </div> </header> <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-10 w-full"> <div class="flex flex-col rounded-xl border border-[#27272a] bg-[#09090b] p-5 shadow-sm"> <div class="flex flex-row items-center justify-between pb-3"> <span class="text-[13px] font-medium text-zinc-400">Total Users</span> <iconify-icon icon="lucide:users" class="text-zinc-500 text-[16px]"></iconify-icon> </div> <div class="flex flex-col"> <span class="text-3xl font-bold tracking-tight text-zinc-100">{total_users}</span> </div> </div> <div class="flex flex-col rounded-xl border border-[#27272a] bg-[#09090b] p-5 shadow-sm"> <div class="flex flex-row items-center justify-between pb-3"> <span class="text-[13px] font-medium text-zinc-400">Admins</span> <iconify-icon icon="lucide:crown" class="text-zinc-500 text-[16px]"></iconify-icon> </div> <div class="flex flex-col"> <span class="text-3xl font-bold tracking-tight text-zinc-100">{admin_count}</span> </div> </div> <div class="flex flex-col rounded-xl border border-[#27272a] bg-[#09090b] p-5 shadow-sm"> <div class="flex flex-row items-center justify-between pb-3"> <span class="text-[13px] font-medium text-zinc-400">Moderators</span> <iconify-icon icon="lucide:shield" class="text-zinc-500 text-[16px]"></iconify-icon> </div> <div class="flex flex-col"> <span class="text-3xl font-bold tracking-tight text-zinc-100">{mod_count}</span> </div> </div> </div> <div class="flex flex-col sm:flex-row sm:items-center gap-4 mb-6"> <div class="relative w-full max-w-sm"> <iconify-icon icon="lucide:search" class="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500 text-[16px]"></iconify-icon> <input type="text" id="searchInput" placeholder="Search users by name, email, role..." class="h-10 w-full rounded-lg border border-[#27272a] bg-[#09090b] pl-9 pr-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-700 transition-all shadow-sm"> </div> <div id="resultCount" class="text-xs font-medium text-zinc-500 flex items-center gap-1.5"> <iconify-icon icon="lucide:eye" class="text-[14px]"></iconify-icon> Showing {total_users} users </div> </div> <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5" id="userGrid"> ''' # Generate user cards for user in users_list: initials = ''.join(word[0].upper() for word in user['username'].split()[:2]) if user['username'] else '?' if len(initials) > 2: initials = initials[:2] created_at = datetime.datetime.fromtimestamp(user['created_at']).strftime('%Y-%m-%d %H:%M') if user['created_at'] else 'N/A' last_seen = datetime.datetime.fromtimestamp(user['last_seen']).strftime('%Y-%m-%d %H:%M') if user['last_seen'] else 'N/A' muted_until = datetime.datetime.fromtimestamp(user['muted_until']).strftime('%Y-%m-%d %H:%M') if user['muted_until'] and user['muted_until'] > 0 else None role_class = user['role'] role_colors = "border-red-500/20 bg-red-500/10 text-red-400" if role_class == 'admin' else "border-indigo-500/20 bg-indigo-500/10 text-indigo-400" if role_class == 'mod' else "border-[#27272a] bg-zinc-900 text-zinc-400" role_icon = "crown" if role_class == 'admin' else "shield" if role_class == 'mod' else "user" badges = [] if user['online']: badges.append('<span class="inline-flex items-center gap-1 rounded-md border border-emerald-500/20 bg-emerald-500/10 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-widest text-emerald-400"><iconify-icon icon="lucide:circle" class="text-[8px]"></iconify-icon>ONLINE</span>') if user['muted_until'] and user['muted_until'] > time.time(): badges.append('<span class="inline-flex items-center gap-1 rounded-md border border-amber-500/20 bg-amber-500/10 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-widest text-amber-400"><iconify-icon icon="lucide:volume-x" class="text-[10px]"></iconify-icon>MUTED</span>') if user['banned']: badges.append('<span class="inline-flex items-center gap-1 rounded-md border border-red-500/20 bg-red-500/10 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-widest text-red-400"><iconify-icon icon="lucide:ban" class="text-[10px]"></iconify-icon>BANNED</span>') badges_html = ' '.join(badges) bio_text = user['bio'][:50] + '...' if user['bio'] and len(user['bio']) > 50 else user['bio'] or 'No bio provided' html += f''' <div class="user-card flex flex-col rounded-xl border border-[#27272a] bg-[#09090b] overflow-hidden transition-colors" data-search="{user['username']} {user['email1'] or ''} {user['email2'] or ''} {user['phone'] or ''} {user['ip'] or ''} {user['role']}"> <div class="flex items-start justify-between p-5 border-b border-[#27272a] bg-zinc-900/20"> <div class="flex items-center gap-3"> <div class="flex items-center justify-center size-10 rounded-full bg-zinc-800 border border-zinc-700 text-xs font-bold text-zinc-300 shrink-0"> {initials} </div> <div class="flex flex-col gap-1"> <div class="flex items-center gap-2"> <span class="text-[14px] font-semibold text-zinc-100 font-['Syne'] tracking-tight">{user['username']}</span> <span class="inline-flex items-center gap-1 rounded-md border {role_colors} px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-widest"> <iconify-icon icon="lucide:{role_icon}" class="text-[10px]"></iconify-icon> {role_class} </span> </div> <div class="flex flex-wrap gap-1.5"> {badges_html} </div> </div> </div> </div> <div class="flex flex-col p-5 gap-3"> <div class="flex items-start justify-between gap-4 text-[13px]"> <span class="flex items-center gap-1.5 text-zinc-500 font-medium shrink-0"> <iconify-icon icon="lucide:mail" class="text-[14px] opacity-70"></iconify-icon> Email 1 </span> <span class="text-zinc-300 truncate text-right">{user['email1'] or 'Not set'}</span> </div> <div class="flex items-start justify-between gap-4 text-[13px]"> <span class="flex items-center gap-1.5 text-zinc-500 font-medium shrink-0"> <iconify-icon icon="lucide:mail" class="text-[14px] opacity-70"></iconify-icon> Email 2 </span> <span class="text-zinc-300 truncate text-right">{user['email2'] or 'Not set'}</span> </div> <div class="flex items-start justify-between gap-4 text-[13px]"> <span class="flex items-center gap-1.5 text-zinc-500 font-medium shrink-0"> <iconify-icon icon="lucide:phone" class="text-[14px] opacity-70"></iconify-icon> Phone </span> <span class="text-zinc-300 truncate text-right">{user['phone'] or 'Not set'}</span> </div> <div class="flex items-start justify-between gap-4 text-[13px]"> <span class="flex items-center gap-1.5 text-zinc-500 font-medium shrink-0"> <iconify-icon icon="lucide:globe" class="text-[14px] opacity-70"></iconify-icon> IP Address </span> <span class="text-zinc-400 text-[11px] truncate text-right">{user['ip'] or 'Unknown'}</span> </div> <div class="flex items-start justify-between gap-4 text-[13px]"> <span class="flex items-center gap-1.5 text-zinc-500 font-medium shrink-0"> <iconify-icon icon="lucide:file-text" class="text-[14px] opacity-70"></iconify-icon> Bio </span> <span class="text-zinc-400 truncate text-right">{bio_text}</span> </div> <div class="h-px w-full bg-[#27272a] my-1"></div> <div class="flex items-start justify-between gap-4 text-[12px]"> <span class="flex items-center gap-1.5 text-zinc-500 font-medium shrink-0"> <iconify-icon icon="lucide:calendar" class="text-[13px] opacity-70"></iconify-icon> Created </span> <span class="text-zinc-400 text-right">{created_at}</span> </div> <div class="flex items-start justify-between gap-4 text-[12px]"> <span class="flex items-center gap-1.5 text-zinc-500 font-medium shrink-0"> <iconify-icon icon="lucide:clock" class="text-[13px] opacity-70"></iconify-icon> Last Seen </span> <span class="text-zinc-400 text-right">{last_seen}</span> </div> </div> </div> ''' html += f''' </div> <div class="mt-8 pt-8 border-t border-[#27272a]"> <h3 class="text-sm font-semibold text-zinc-100 flex items-center gap-2 mb-4"> <iconify-icon icon="lucide:download" class="text-zinc-400 text-[16px]"></iconify-icon> Export Operations </h3> <div class="flex flex-wrap items-center gap-3"> <button onclick="copyRawJSON()" class="inline-flex items-center gap-2 rounded-lg border border-[#27272a] bg-[#09090b] px-4 py-2 text-[13px] font-medium text-zinc-300 transition-colors hover:bg-zinc-900 hover:text-zinc-100"> <iconify-icon icon="lucide:copy" class="text-[14px]"></iconify-icon> Copy JSON </button> <button onclick="downloadJSON()" class="inline-flex items-center gap-2 rounded-lg border border-[#27272a] bg-[#09090b] px-4 py-2 text-[13px] font-medium text-zinc-300 transition-colors hover:bg-zinc-900 hover:text-zinc-100"> <iconify-icon icon="lucide:download" class="text-[14px]"></iconify-icon> Download JSON </button> <button onclick="toggleRawData()" class="inline-flex items-center gap-2 rounded-lg border border-[#27272a] bg-[#09090b] px-4 py-2 text-[13px] font-medium text-zinc-300 transition-colors hover:bg-zinc-900 hover:text-zinc-100"> <iconify-icon icon="lucide:code" class="text-[14px]"></iconify-icon> Toggle Raw View </button> </div> <div id="rawData" class="hidden mt-4 rounded-xl border border-[#27272a] bg-[#050505] p-5 overflow-auto max-h-[400px]"> <pre class="text-[11px] font-mono text-zinc-400 whitespace-pre-wrap break-all"></pre> </div> </div> </div> <script> const users = {json.dumps(users_list, default=str, indent=2)}; document.getElementById('searchInput').addEventListener('input', function(e) {{ const search = e.target.value.toLowerCase(); const cards = document.querySelectorAll('.user-card'); let visibleCount = 0; cards.forEach(card => {{ const searchText = card.dataset.search.toLowerCase(); if (searchText.includes(search) || search === '') {{ card.style.display = 'flex'; visibleCount++; }} else {{ card.style.display = 'none'; }} }}); document.getElementById('resultCount').innerHTML = `<iconify-icon icon="lucide:eye" class="text-[14px]"></iconify-icon> Showing ${{visibleCount}} of ${{users.length}} users`; }}); function copyRawJSON() {{ const jsonStr = JSON.stringify(users, null, 2); navigator.clipboard.writeText(jsonStr).then(() => {{ alert('JSON copied to clipboard!'); }}); }} function downloadJSON() {{ const jsonStr = JSON.stringify(users, null, 2); const blob = new Blob([jsonStr], {{ type: 'application/json' }}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `kpak-users-${{new Date().toISOString().split('T')[0]}}.json`; a.click(); URL.revokeObjectURL(url); }} function toggleRawData() {{ const rawDiv = document.getElementById('rawData'); const pre = rawDiv.querySelector('pre'); if (rawDiv.classList.contains('hidden')) {{ pre.textContent = JSON.stringify(users, null, 2); rawDiv.classList.remove('hidden'); }} else {{ rawDiv.classList.add('hidden'); }} }} </script> </body> </html> ''' return html except Exception as e: return f"<pre style='color:#ef5e5e;background:#111113;padding:20px;border-radius:10px;font-family:monospace;'>Error: {str(e)}</pre>", 500 @app.route('/api/users/battery', methods=['GET']) @token_required def get_battery(user): if user['role'] not in ['admin', 'mod']: return jsonify({'error': 'Permission denied'}), 403 username = request.args.get('username') db = get_db() target = db.execute('SELECT online, last_seen FROM users WHERE username = ?', (username,)).fetchone() db.close() if not target: return jsonify({'error': 'User not found'}), 404 # Check if online (active in last 2 minutes) is_online = target['online'] and (int(time.time()) - target['last_seen']) < 120 if not is_online: return jsonify({'error': 'User is offline'}), 400 # Return random battery percentage import random battery = random.randint(1, 100) return jsonify({'battery': battery}) # Command handler def handle_command(user, command, socket_id=None, is_dm=False, recipient=None): parts = command.split() cmd = parts[0].lower() db = get_db() result = {'command_response': 'INVALID COMMAND'} if is_dm: # Allow certain commands in DMs allowed_dm_commands = ['/help', '/ban', '/unban', '/flash', '/explode', '/mute', '/battery', '/ip', '/unmute', '/mod', '/unmod', '/block', '/unblock', '/url', '/image'] if cmd not in allowed_dm_commands: return {'command_response': 'Command not available in DMs'} try: # PUBLIC COMMANDS (available to all users) if cmd == '/image': result = {'command_response': 'Opening pixel art maker (32x32)'} elif cmd == '/block' and len(parts) == 2: db.execute('INSERT OR IGNORE INTO blocks (user_id, blocked_user) VALUES (?, ?)', (user['id'], parts[1])) u1, u2 = _norm_pair(user['username'], parts[1]) db.execute('DELETE FROM friendships WHERE user1 = ? AND user2 = ?', (u1, u2)) db.commit() result = {'command_response': f'Blocked {parts[1]}'} elif cmd == '/unblock' and len(parts) == 2: db.execute('DELETE FROM blocks WHERE user_id = ? AND blocked_user = ?', (user['id'], parts[1])) db.commit() result = {'command_response': f'Unblocked {parts[1]}'} elif cmd == '/url' and len(parts) >= 2: url = parts[1] text = ' '.join(parts[2:]) if len(parts) > 2 else url # Sanitize the URL safe_url = sanitize_url(url) safe_text = html.escape(text) # Generate safe HTML result = {'command_response': f'<a href="{safe_url}" target="_blank" rel="noopener noreferrer">{safe_text}</a>'} elif cmd == '/help': help_text = """ *Available Commands:* `/block <user>` - Block a user from DMing you `/unblock <user>` - Unblock a user from DMing you `/url <link> [text]` - Create a clickable link `/image` - Open pixel art maker or image upload area """ if user['role'] in ['mod', 'admin']: help_text += """ \n*Mod:* `/mute <seconds> <user>` - Mute a user `/battery <user>` - Check user's battery `/explode <message>` - Send explosion """ if user['role'] == 'admin': help_text += """ \n*Admin Only:* `/ban ip <user>` - Ban by IP `/ban name <user>` - Ban by username `/unmute <user>` - Unmute user `/scream <user>` - Send a quote-on-quote scream `/mod <user>` - Make user a mod `/unmod <user>` - Deprives a user of mod `/ip <user>` - Get user's IP `/flash` - Flashbang everyone """ result = {'command_response': apply_formatting(help_text)} # ADMIN ONLY COMMANDS elif user['role'] == 'admin': if cmd == '/ip' and len(parts) == 2: target = db.execute('SELECT ip FROM users WHERE username = ?', (parts[1],)).fetchone() if target: result = {'command_response': f'IP for {parts[1]}: {target["ip"]}'} else: result = {'command_response': 'User not found'} elif cmd == '/battery' and len(parts) == 2: target = db.execute('SELECT online, last_seen FROM users WHERE username = ?', (parts[1],)).fetchone() if not target: result = {'command_response': 'User not found'} else: is_online = target['online'] and (int(time.time()) - target['last_seen']) < 120 if not is_online: result = {'command_response': f'{parts[1]} is offline'} else: import random battery = random.randint(1, 100) result = {'command_response': f'{parts[1]} battery: {battery}%'} elif cmd == '/ban' and len(parts) == 3: if parts[1] == 'ip': target = db.execute('SELECT id, ip, role FROM users WHERE username = ?', (parts[2],)).fetchone() if target and target['ip']: if target['id'] == user['id']: result = {'command_response': '❌ You cannot ban yourself!'} elif target['role'] == 'admin' and user['role'] == 'admin': result = {'command_response': '❌ Admins cannot ban other admins!'} else: db.execute('DELETE FROM user_tokens WHERE user_id = ?', (target['id'],)) db.execute('INSERT INTO bans (ip, username, banned_by, timestamp) VALUES (?, ?, ?, ?)', (target['ip'], parts[2], user['username'], int(time.time()))) db.execute('UPDATE users SET banned = 1, banned_ip = ip, online = 0 WHERE id = ?', (target['id'],)) db.commit() socketio.emit('force_disconnect', { 'reason': 'banned', 'message': f'You have been banned by {user["username"]}' }, room=parts[2]) for sid, conn_user in list(connected_users.items()): if conn_user['username'] == parts[2]: socketio.server.disconnect(sid) result = {'command_response': f'Banned IP of {parts[2]}'} else: result = {'command_response': 'User not found or no IP recorded'} elif parts[1] == 'name': target = db.execute('SELECT id, role FROM users WHERE username = ?', (parts[2],)).fetchone() if target: if target['id'] == user['id']: result = {'command_response': '❌ You cannot ban yourself!'} elif target['role'] == 'admin' and user['role'] == 'admin': result = {'command_response': '❌ Admins cannot ban other admins!'} else: # IMMEDIATELY invalidate all tokens for this user db.execute('DELETE FROM user_tokens WHERE user_id = ?', (target['id'],)) db.execute('INSERT INTO bans (username, banned_by, timestamp) VALUES (?, ?, ?)', (parts[2], user['username'], int(time.time()))) db.execute('UPDATE users SET banned = 1, online = 0 WHERE username = ?', (parts[2],)) db.commit() # Emit ban event to force disconnect socketio.emit('force_disconnect', { 'reason': 'banned', 'message': f'You have been banned by {user["username"]}' }, room=parts[2]) # Also disconnect all sessions for sid, conn_user in list(connected_users.items()): if conn_user['username'] == parts[2]: socketio.server.disconnect(sid) result = {'command_response': f'Banned username {parts[2]}'} else: result = {'command_response': 'User not found'} elif cmd == '/unban' and len(parts) == 3: if parts[1] == 'ip': # Find the ban record by IP target_ban = db.execute('SELECT ip, username FROM bans WHERE ip = ?', (parts[2],)).fetchone() if target_ban: # Remove from bans table db.execute('DELETE FROM bans WHERE ip = ?', (parts[2],)) # Unban all users with this IP db.execute('UPDATE users SET banned = 0, banned_ip = NULL WHERE ip = ?', (parts[2],)) db.commit() result = {'command_response': f'Unbanned IP {parts[2]} (User: {target_ban["username"]})'} else: result = {'command_response': f'No ban found for IP {parts[2]}'} elif parts[1] == 'name': target_user = parts[2] # Check if user exists and is banned target = db.execute('SELECT id, banned FROM users WHERE username = ?', (target_user,)).fetchone() if target: if not target['banned']: result = {'command_response': f'User {target_user} is not banned'} else: # Remove from bans table db.execute('DELETE FROM bans WHERE username = ?', (target_user,)) # Unban the user db.execute('UPDATE users SET banned = 0, banned_ip = NULL WHERE username = ?', (target_user,)) db.commit() result = {'command_response': f'Unbanned user {target_user}'} else: result = {'command_response': f'User {target_user} not found'} else: result = {'command_response': 'Usage: /unban ip <ip> OR /unban name <username>'} elif cmd == '/mute' and len(parts) == 3: try: seconds = int(parts[1]) target_username = parts[2] if target_username == user['username']: result = {'command_response': '❌ You cannot mute yourself!'} else: target = db.execute('SELECT id, role FROM users WHERE username = ?', (target_username,)).fetchone() if target: if target['role'] == 'admin' and user['role'] == 'admin': result = {'command_response': '❌ Admins cannot mute other admins!'} elif target['role'] == 'admin' and user['role'] == 'mod': result = {'command_response': '❌ Mods cannot mute admins!'} elif target['role'] == 'mod' and user['role'] == 'mod': result = {'command_response': '❌ Mods cannot mute other mods!'} else: db.execute('UPDATE users SET muted_until = ? WHERE id = ?', (int(time.time()) + seconds, target['id'])) db.commit() result = {'command_response': f'Muted {target_username} for {seconds} seconds'} socketio.emit('toast', { 'username': target_username, 'message': f'You have been muted for {seconds} seconds', 'type': 'warn' }, room=target_username) emit_mute_update(target_username, { 'username': target_username, 'muted': True, 'until': int(time.time()) + seconds, 'seconds': seconds, 'by': user['username'] }) else: result = {'command_response': f'User {target_username} not found'} except ValueError: result = {'command_response': 'Invalid seconds'} elif cmd == '/flash': admin_sids = [] for sid, conn_user in connected_users.items(): if conn_user['role'] == 'admin': admin_sids.append(sid) if admin_sids: socketio.emit('flash', room='main', skip_sid=admin_sids) else: socketio.emit('flash', room='main') result = {'command_response': 'Flashbang deployed'} elif cmd == '/unmute' and len(parts) == 2: target = db.execute('SELECT id FROM users WHERE username = ?', (parts[1],)).fetchone() if target: db.execute('UPDATE users SET muted_until = 0 WHERE id = ?', (target['id'],)) db.commit() result = {'command_response': f'Unmuted {parts[1]}'} socketio.emit('mute_update', { 'username': parts[1], 'muted': False, 'until': 0 }, room=parts[1]) else: result = {'command_response': 'User not found'} elif cmd == '/scream' and len(parts) == 2: target = db.execute('SELECT username FROM users WHERE username = ?', (parts[1],)).fetchone() if target: socketio.emit('scream', {'username': parts[1]}) result = {'command_response': f'Scream sent to {parts[1]}'} else: result = {'command_response': 'User not found'} elif cmd == '/explode': text = ' '.join(parts[1:]) if text: if len(parts) == 2: target_username = parts[1] target = db.execute('SELECT username FROM users WHERE username = ?', (target_username,)).fetchone() if target: socketio.emit('explode', {'text': f'{user["username"]} made you explode!', 'username': user['username']}, room=target_username) result = {'command_response': f'Sent explosion to {target_username}'} else: result = {'command_response': f'User {target_username} not found'} else: non_admins = db.execute('SELECT username FROM users WHERE role != "admin"').fetchall() for target_user in non_admins: socketio.emit('explode', {'text': f'{user["username"]} caused a massive explosion!', 'username': user['username']}, room=target_user['username']) result = {'command_response': 'Explosion sent to all non-admin users'} else: result = {'command_response': 'Usage: /explode <message> or /explode <username>'} elif cmd == '/mod' and len(parts) == 2: target = db.execute( 'SELECT id, role FROM users WHERE username = ?', (parts[1],) ).fetchone() if target: if target['role'] == 'admin': result = {'command_response': '❌ Cannot modify an admin'} elif target['role'] == 'mod': result = {'command_response': f'{parts[1]} is already a moderator'} else: db.execute( 'UPDATE users SET role = "mod" WHERE username = ?', (parts[1],) ) db.commit() for sid, conn_user in connected_users.items(): if conn_user['username'] == parts[1]: conn_user['role'] = 'mod' socketio.emit('role_update', {'username': parts[1], 'role': 'mod'}) result = {'command_response': f'{parts[1]} is now a moderator'} else: result = {'command_response': 'User not found'} elif cmd == '/unmod' and len(parts) == 2: target = db.execute('SELECT id, role FROM users WHERE username = ?', (parts[1],)).fetchone() if target: if target['role'] == 'admin': result = {'command_response': '❌ Cannot remove moderator status from an admin'} elif target['role'] == 'mod': db.execute('UPDATE users SET role = "user" WHERE username = ?', (parts[1],)) db.commit() for sid, conn_user in connected_users.items(): if conn_user['username'] == parts[1]: conn_user['role'] = 'user' socketio.emit('role_update', {'username': parts[1], 'role': 'user'}) result = {'command_response': f'Removed moderator status from {parts[1]}'} else: result = {'command_response': f'{parts[1]} is not a moderator'} else: result = {'command_response': 'User not found'} # MOD COMMANDS (and admin) elif user['role'] in ['admin', 'mod']: if cmd == '/mute' and len(parts) == 3: try: seconds = int(parts[1]) target = db.execute('SELECT id FROM users WHERE username = ?', (parts[2],)).fetchone() if target: db.execute('UPDATE users SET muted_until = ? WHERE id = ?', (int(time.time()) + seconds, target['id'])) db.commit() result = {'command_response': f'Muted {parts[2]} for {seconds} seconds'} emit_mute_update(parts[2], { 'username': parts[2], 'muted': True, 'until': int(time.time()) + seconds, 'seconds': seconds, 'by': user['username'] }) else: result = {'command_response': 'User not found'} except ValueError: result = {'command_response': 'Invalid seconds'} elif cmd == '/battery' and len(parts) == 2: target = db.execute('SELECT online, last_seen FROM users WHERE username = ?', (parts[1],)).fetchone() if not target: result = {'command_response': 'User not found'} else: is_online = target['online'] and (int(time.time()) - target['last_seen']) < 120 if not is_online: result = {'command_response': f'{parts[1]} is offline'} else: import random battery = random.randint(1, 100) result = {'command_response': f'{parts[1]} battery: {battery}%'} elif cmd == '/explode': text = ' '.join(parts[1:]) if text: socketio.emit('explode', {'text': text, 'username': user['username']}) result = {'command_response': 'πŸ’₯ BOOM!'} else: result = {'command_response': 'Usage: /explode <message>'} except Exception as e: result = {'command_response': f'Command error: {str(e)}'} finally: db.close() return result import html def apply_formatting(text): """Apply markdown-like formatting with XSS protection""" # First, sanitize any existing HTML text = sanitize_html(text) # Now apply formatting (these are safe since we're generating the HTML ourselves) # ***text*** = underline text = re.sub(r'\*\*\*(.*?)\*\*\*', r'<u>\1</u>', text) # **text** = italic text = re.sub(r'\*\*(.*?)\*\*', r'<i>\1</i>', text) # *text* = bold text = re.sub(r'\*(.*?)\*', r'<b>\1</b>', text) return text def validate_socket_user(): """Validate that the socket connection is still valid and user isn't banned/muted""" if request.sid not in connected_users: return None socket_user = connected_users[request.sid] # Re-check database for current status (bans, mutes) db = get_db() current_user = db.execute(''' SELECT banned, muted_until, role, online FROM users WHERE id = ? ''', (socket_user['id'],)).fetchone() db.close() if not current_user or current_user['banned']: # User was banned after connecting emit('error', {'message': 'You have been banned'}) return None # Check if still muted if current_user['muted_until'] > time.time(): # Still muted - reject certain actions return {'error': 'muted', 'until': current_user['muted_until']} return socket_user # Store full user info in a connection map connected_users = {} _mute_watcher_started = False @socketio.on('connect') def handle_connect(): global _mute_watcher_started # First, validate token as you already do... token = request.args.get('token') or request.headers.get('Authorization', '').replace('Bearer ', '') if not token: return False token_hash = hashlib.sha256(token.encode()).hexdigest() db = get_db() user = db.execute(''' SELECT u.* FROM users u JOIN user_tokens t ON u.id = t.user_id WHERE t.token = ? AND t.expires_at > ? ''', (token_hash, int(time.time()))).fetchone() db.close() if not user: return False # ---- NEW: VPN check ---- ip = request.headers.get('X-Forwarded-For', request.remote_addr) if ip: ip = ip.split(',')[0].strip() else: ip = request.remote_addr if vpn_blocker.is_vpn(ip): print(f"Socket.IO blocked VPN IP: {ip}") # Changed from logger.warning to print return False # reject connection # ------------------------- # Store user info and join rooms (your existing code) connected_users[request.sid] = { 'id': user['id'], 'username': user['username'], 'role': user['role'], 'muted_until': user['muted_until'] } join_room('main') join_room(user['username']) if not _mute_watcher_started: _mute_watcher_started = True socketio.start_background_task(mute_expiry_watcher) print("🎬 Mute watcher spawned from live connect handler") now = int(time.time()) if user['muted_until'] and user['muted_until'] > now: socketio.emit('mute_update', { 'username': user['username'], 'muted': True, 'until': user['muted_until'], 'seconds': user['muted_until'] - now }, room=user['username']) else: socketio.emit('mute_update', { 'username': user['username'], 'muted': False, 'until': 0 }, room=user['username']) return True @socketio.on('disconnect') def handle_disconnect(): if request.sid in connected_users: user = connected_users[request.sid] db = get_db() db.execute('UPDATE users SET online = 0 WHERE username = ?', (user['username'],)) db.commit() db.close() del connected_users[request.sid] socketio.emit('user_offline', {'username': user['username']}) else: # Clean up any stale entries for sid, user in list(connected_users.items()): if not is_connection_alive(sid): # You'd need to implement this del connected_users[sid] @socketio.on('join') def handle_join(data): # Validate user user = validate_socket_user() if not user or 'error' in user: return False # Use the validated user from connected_users, not session join_room('main') join_room(user['username']) db = get_db() db.execute('UPDATE users SET online = 1, last_seen = ? WHERE id = ?', (int(time.time()), user['id'])) db.commit() db.close() # Health check @app.route('/health') def health(): return jsonify({'status': 'ok'}) if __name__ == '__main__': port = int(os.environ.get('PORT', 7860)) print(f"πŸš€ Starting Kpak on port {port}") print(f"πŸ‘‘ Admins: {ADMINS}") socketio.run(app, host='0.0.0.0', port=port, debug=True)
from flask import Flask, render_template, request, jsonify, session, send_from_directory
from flask_socketio import SocketIO, emit, join_room
from flask_bcrypt import Bcrypt
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import jwt
import sqlite3
import datetime
import re
import time
import os
import hashlib
from functools import wraps
import requests
import threading
import json
import logging
import sys
import random
import secrets
from vpn_checker import vpn_blocker
class Snowflake:
def __init__(self, worker_id=1, datacenter_id=1):
self.worker_id = worker_id
self.datacenter_id = datacenter_id
self.sequence = 0
self.last_timestamp = -1
# Discord Epoch (2015-01-01) - you can use any start date
self.epoch = 1420070400000
def _current_time(self):
return int(time.time() * 1000)
def generate(self):
timestamp = self._current_time()
if timestamp < self.last_timestamp:
raise Exception("Clock moved backwards!")
if timestamp == self.last_timestamp:
self.sequence = (self.sequence + 1) & 4095 # 12-bit sequence
if self.sequence == 0:
# Sequence overflow, wait for next millisecond
while timestamp <= self.last_timestamp:
timestamp = self._current_time()
else:
self.sequence = 0
self.last_timestamp = timestamp
# 64-bit ID composition:
# 42 bits timestamp | 5 bits datacenter | 5 bits worker | 12 bits sequence
snowflake = ((timestamp - self.epoch) << 22) | \
(self.datacenter_id << 17) | \
(self.worker_id << 12) | \
self.sequence
return snowflake
def parse(self, snowflake):
"""Extract timestamp from snowflake (for debugging)"""
timestamp = (snowflake >> 22) + self.epoch
return {
'timestamp': timestamp,
'datetime': datetime.datetime.fromtimestamp(timestamp/1000),
'worker': (snowflake >> 12) & 0x1F,
'datacenter': (snowflake >> 17) & 0x1F,
'sequence': snowflake & 0xFFF
}
# Create a global snowflake generator
snowflake_gen = Snowflake(worker_id=1, datacenter_id=1)
# Configure logging to show ALL output
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
stream=sys.stdout # Force to stdout
)
# Also add a file handler to capture everything
file_handler = logging.FileHandler('/tmp/app.log')
file_handler.setLevel(logging.DEBUG)
logging.getLogger().addHandler(file_handler)
print = logging.info # Replace print with logging.info
from io import StringIO
# Force all stdout to be unbuffered
sys.stdout.reconfigure(line_buffering=True)
app = Flask(__name__, template_folder='templates', static_folder='static')
app.config['SECRET_KEY'] = os.environ.get('JWT_SECRET', 'dba4880f6b7c490ef8bbfc28f15ee4b1eba19f20e5964020a756efada013ac3b')
app.config['ABLY_API_KEY'] = os.environ.get('ABLY_API_KEY', '')
app.config['RESEND_API_KEY'] = os.environ.get('RESEND_API_KEY', '')