Buckets:
| from datetime import datetime, timedelta, timezone | |
| from typing import Optional, Tuple, Any, Dict, List | |
| import secrets | |
| import smtplib | |
| import subprocess | |
| import shutil | |
| from email.mime.text import MIMEText | |
| from email.mime.multipart import MIMEMultipart | |
| import re | |
| import html | |
| import platform | |
| import tempfile | |
| import os | |
| import socket | |
| import ipaddress | |
| from urllib.parse import urlparse, urljoin | |
| import requests | |
| import pipmaster as pm | |
| pm.ensure_packages("bleach") | |
| import bleach | |
| from fastapi import Depends | |
| from fastapi.security import OAuth2PasswordBearer | |
| from jose import jwt, JWTError | |
| from passlib.context import CryptContext | |
| from backend.config import SECRET_KEY, ALGORITHM | |
| import json | |
| import ast | |
| pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") | |
| api_key_context = CryptContext(schemes=["bcrypt"], deprecated="auto") | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/token") | |
| # --- Sanitization Configuration --- | |
| ALLOWED_TAGS = [ | |
| 'p', 'b', 'i', 'u', 'em', 'strong', 'a', 'br', 'ul', 'ol', 'li', | |
| 'code', 'pre', 'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', | |
| 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'strike', 'hr', 'span', 'div', | |
| 'youtube', 'youtube_video', 'iframe' | |
| ] | |
| def _filter_iframe_attrs(tag, name, value): | |
| if name == 'src': | |
| return bool(re.match(r'^https://(?:www\.)?(?:youtube\.com|youtube-nocookie\.com)/embed/(?:videoseries\?list=[a-zA-Z0-9_-]{12,64}|[a-zA-Z0-9_-]{11}(?:\?[a-zA-Z0-9_=&-]+)?)$', value)) | |
| return name in ['width', 'height', 'frameborder', 'allow', 'allowfullscreen', 'title', 'loading', 'referrerpolicy', 'sandbox', 'class'] | |
| ALLOWED_ATTRS = { | |
| 'a': ['href', 'title', 'target', 'rel'], | |
| 'img': ['src', 'alt', 'title', 'width', 'height'], | |
| 'span': ['class'], | |
| 'div': ['class'], | |
| 'code': ['class'], | |
| 'pre': ['class'], | |
| 'youtube': ['id', 'url', 'list', 'start', 'title', 'width', 'height'], | |
| 'youtube_video': ['id', 'url', 'list', 'start', 'title', 'width', 'height'], | |
| 'iframe': _filter_iframe_attrs | |
| } | |
| BLOCKED_IP_NETWORKS = [ | |
| ipaddress.ip_network("127.0.0.0/8"), # IPv4 loopback | |
| ipaddress.ip_network("10.0.0.0/8"), # RFC 1918 private | |
| ipaddress.ip_network("172.16.0.0/12"), # RFC 1918 private | |
| ipaddress.ip_network("192.168.0.0/16"), # RFC 1918 private | |
| ipaddress.ip_network("169.254.0.0/16"), # Link-local / Cloud Metadata (169.254.169.254) | |
| ipaddress.ip_network("100.64.0.0/10"), # Shared address space / CGNAT | |
| ipaddress.ip_network("0.0.0.0/8"), # Current network | |
| ipaddress.ip_network("224.0.0.0/4"), # Multicast | |
| ipaddress.ip_network("240.0.0.0/4"), # Reserved | |
| ipaddress.ip_network("::1/128"), # IPv6 loopback | |
| ipaddress.ip_network("fc00::/7"), # IPv6 Unique Local Address | |
| ipaddress.ip_network("fe80::/10"), # IPv6 Link-local | |
| ipaddress.ip_network("::ffff:0:0/96"), # IPv4-mapped IPv6 | |
| ] | |
| def is_ip_blocked(ip: Any) -> bool: | |
| """Checks if an IP address falls inside any blocked/private network range.""" | |
| if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped: | |
| ip = ip.ipv4_mapped | |
| if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved or ip.is_unspecified: | |
| return True | |
| for network in BLOCKED_IP_NETWORKS: | |
| if ip in network: | |
| return True | |
| return False | |
| def validate_url(url: str) -> str: | |
| """ | |
| Validates a URL to prevent SSRF attacks. | |
| Ensures the scheme is http/https and the host does not resolve to private/local/metadata IPs. | |
| Raises ValueError on violation. | |
| """ | |
| try: | |
| parsed = urlparse(url) | |
| if parsed.scheme.lower() not in ('http', 'https'): | |
| raise ValueError(f"Invalid scheme: {parsed.scheme}") | |
| hostname = parsed.hostname | |
| if not hostname: | |
| raise ValueError("Invalid hostname") | |
| clean_host = hostname.strip("[]") | |
| try: | |
| ip = ipaddress.ip_address(clean_host) | |
| if is_ip_blocked(ip): | |
| raise ValueError(f"Access to local/private IP {hostname} is forbidden.") | |
| return url | |
| except ValueError as e: | |
| if "forbidden" in str(e): | |
| raise | |
| try: | |
| addr_info = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM) | |
| if not addr_info: | |
| raise ValueError(f"Could not resolve hostname '{hostname}'.") | |
| for family, _, _, _, sockaddr in addr_info: | |
| ip_str = sockaddr[0] | |
| ip = ipaddress.ip_address(ip_str) | |
| if is_ip_blocked(ip): | |
| raise ValueError(f"Domain {hostname} resolves to private IP {ip_str}.") | |
| except socket.gaierror as e: | |
| raise ValueError(f"DNS resolution failed for hostname '{hostname}': {e}") | |
| return url | |
| except Exception as e: | |
| if isinstance(e, ValueError): | |
| raise | |
| raise ValueError(f"URL validation failed: {str(e)}") | |
| def safe_requests_get( | |
| url: str, | |
| headers: Optional[Dict[str, str]] = None, | |
| timeout: int = 5, | |
| max_redirects: int = 5, | |
| max_response_size: int = 524288, | |
| **kwargs | |
| ) -> requests.Response: | |
| """ | |
| Executes an HTTP GET request with robust SSRF and redirect protection: | |
| - Validates the initial URL against private/metadata IPs. | |
| - Disables automatic redirects (allow_redirects=False). | |
| - Iterates manually over redirects, re-validating the Location header at every hop. | |
| - Limits maximum download size and response time. | |
| """ | |
| current_url = validate_url(url) | |
| redirect_count = 0 | |
| session = requests.Session() | |
| kwargs["allow_redirects"] = False | |
| while True: | |
| resp = session.get( | |
| current_url, | |
| headers=headers, | |
| timeout=timeout, | |
| stream=True, | |
| **kwargs | |
| ) | |
| if resp.status_code in (301, 302, 303, 307, 308): | |
| redirect_count += 1 | |
| if redirect_count > max_redirects: | |
| resp.close() | |
| raise ValueError(f"Too many redirects (exceeded maximum limit of {max_redirects}).") | |
| location = resp.headers.get("Location") | |
| if not location: | |
| resp.close() | |
| raise ValueError("Redirect response missing Location header.") | |
| next_url = urljoin(current_url, location) | |
| current_url = validate_url(next_url) | |
| resp.close() | |
| continue | |
| return resp | |
| def sanitize_content(content: str) -> str: | |
| """ | |
| Sanitizes user input to prevent XSS while allowing basic formatting. | |
| Centralized logic used by Routers and Maintenance Tasks. | |
| """ | |
| if not content: | |
| return content | |
| # Remove script blocks entirely including their content | |
| content = re.sub(r'<script[^>]*>.*?</script>', '', content, flags=re.DOTALL | re.IGNORECASE) | |
| # Neutralize dangerous javascript: and pseudo-protocols in links/markdown | |
| content = re.sub(r'href\s*=\s*["\']?\s*(?:javascript|vbscript|data):[^"\'>\s]*', 'href="#"', content, flags=re.IGNORECASE) | |
| content = re.sub(r'\[(.*?)\]\(\s*(?:javascript|vbscript|data):[^\)]*\)', r'[\1](#)', content, flags=re.IGNORECASE) | |
| # bleach.clean will strip or escape tags not in ALLOWED_TAGS | |
| # and strip attributes not in ALLOWED_ATTRS. | |
| return bleach.clean(content, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRS, protocols=['http', 'https', 'mailto'], strip=True) | |
| def verify_custom_node_code(code: str, lollms_client: Optional[Any] = None) -> Tuple[bool, str]: | |
| """ | |
| Performs dual-layer security validation on custom node Python code: | |
| 1. Static AST Analysis: Reject blocked modules, functions, and double-underscore attributes. | |
| 2. LLM-Based Cognitive Analysis: Auditor agent inspects the code for backdoors or obfuscation. | |
| """ | |
| if not code: | |
| return True, "" | |
| # --- LAYER 1: STATIC AST ANALYSIS --- | |
| try: | |
| tree = ast.parse(code) | |
| except SyntaxError as e: | |
| return False, f"Syntax Error: {e}" | |
| blocked_modules = { | |
| 'os', 'subprocess', 'sys', 'shutil', 'ctypes', 'socket', 'importlib', | |
| 'pickle', 'marshal', 'pty', 'platform', 'requests', 'urllib', 'http' | |
| } | |
| blocked_builtins = {'eval', 'exec', 'compile', 'open', '__import__', 'getattr', 'setattr', 'delattr'} | |
| dangerous_names = {"__builtins__", "__import__"} | |
| for node in ast.walk(tree): | |
| # Check Imports | |
| if isinstance(node, ast.Import): | |
| for name in node.names: | |
| base_mod = name.name.split('.')[0] | |
| if base_mod in blocked_modules: | |
| return False, f"Security Violation: Import of blocked module '{base_mod}' is forbidden." | |
| elif isinstance(node, ast.ImportFrom): | |
| if node.module: | |
| base_mod = node.module.split('.')[0] | |
| if base_mod in blocked_modules: | |
| return False, f"Security Violation: Import from blocked module '{base_mod}' is forbidden." | |
| # Check dangerous bare identifiers (e.g., __builtins__, __import__) | |
| elif isinstance(node, ast.Name): | |
| if node.id in dangerous_names: | |
| return False, f"Security Violation: Use of forbidden name '{node.id}' is forbidden." | |
| # Check Attribute Access (prevent dunder escapes like __globals__, __subclasses__) | |
| elif isinstance(node, ast.Attribute): | |
| if node.attr.startswith('__') and node.attr.endswith('__'): | |
| return False, f"Access to dangerous attribute '{node.attr}' is forbidden" | |
| # Check Function Calls (blocked builtins) | |
| elif isinstance(node, ast.Call): | |
| if isinstance(node.func, ast.Name): | |
| if node.func.id in blocked_builtins: | |
| return False, f"Security Violation: Call to blocked function '{node.func.id}' is forbidden." | |
| elif isinstance(node.func, ast.Attribute): | |
| if node.func.attr.startswith('__') and node.func.attr.endswith('__'): | |
| return False, f"Security Violation: Call to dangerous attribute method '{node.func.attr}' is forbidden." | |
| # --- LAYER 2: LLM COGNITIVE AUDIT --- | |
| if lollms_client: | |
| try: | |
| system_prompt = """You are an elite secure code auditor. Your job is to analyze the provided custom node Python code. | |
| Look for security threats, backdoors, obfuscation, or sneaky workarounds to escape sandboxing. | |
| You must return a JSON object with exactly two keys: | |
| 1. "safe": boolean (true if the code is entirely safe and contains no malicious operations, false otherwise) | |
| 2. "reason": string (if unsafe, explain why; if safe, keep it brief) | |
| IMPORTANT: Output ONLY the valid JSON block. No markdown wrappers or additional text.""" | |
| prompt = f"Analyze this Python code for any security exploits, obfuscation, or backdoors:\n\n```python\n{code}\n```" | |
| audit_res = lollms_client.generate_text(prompt, system_prompt=system_prompt, temp=0.1) | |
| json_start = audit_res.find('{') | |
| json_end = audit_res.rfind('}') + 1 | |
| if json_start != -1 and json_end != -1: | |
| data = json.loads(audit_res[json_start:json_end]) | |
| if data.get("safe") is False: | |
| return False, f"AI Auditor Rejection: {data.get('reason', 'Malicious patterns detected.')}" | |
| except Exception as e: | |
| return False, f"Security Violation: LLM security audit unavailable or failed ({e})." | |
| return True, "" | |
| def verify_password(plain_password: str, hashed_password: str) -> bool: | |
| """Verifies a plain password against a hashed one.""" | |
| return pwd_context.verify(plain_password, hashed_password) | |
| def get_password_hash(password: str) -> str: | |
| """Hashes a plain password.""" | |
| return pwd_context.hash(password) | |
| def generate_api_key() -> Tuple[str, str]: | |
| """Generates a secure API key and its non-secret prefix.""" | |
| prefix = secrets.token_urlsafe(6) # e.g., lollms_aBcDeF12 | |
| # Ensure the prefix does not contain underscores. Regenerate if it does. | |
| while "_" in prefix: | |
| prefix = secrets.token_urlsafe(6) | |
| key = secrets.token_urlsafe(32) | |
| prefix = "lollms_" + prefix | |
| full_key = f"{prefix}_{key}" | |
| return full_key, prefix | |
| def generate_sso_secret() -> str: | |
| """Generates a secure, URL-safe random string for SSO client secrets.""" | |
| return secrets.token_urlsafe(32) | |
| def hash_api_key(api_key: str) -> str: | |
| """Hashes a plain text API key for storage.""" | |
| return api_key_context.hash(api_key) | |
| def verify_api_key(plain_key: str, hashed_key: str) -> bool: | |
| """Verifies a plain text API key against a stored hash.""" | |
| return api_key_context.verify(plain_key, hashed_key) | |
| def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: | |
| """ | |
| Creates a JWT access token for the main application using the global SECRET_KEY. | |
| """ | |
| to_encode = data.copy() | |
| from backend.settings import settings | |
| now_utc = datetime.now(timezone.utc) | |
| if expires_delta: | |
| expire = now_utc + expires_delta | |
| else: | |
| try: | |
| expire_minutes = settings.get("access_token_expire_minutes", 30*24*3600) | |
| if isinstance(expire_minutes, dict): | |
| expire_minutes = expire_minutes.get("value", 30*24*3600) # Default to 30 days | |
| elif isinstance(expire_minutes, str): | |
| try: | |
| expire_minutes = json.loads(expire_minutes).get("value", 30*24*3600) # Default to 30 days | |
| except Exception: | |
| expire_minutes = 30*24*3600 | |
| minutes = int(expire_minutes) | |
| except (ValueError, TypeError): | |
| print(f"WARNING: Invalid 'access_token_expire_minutes' value ({expire_minutes}). Using fallback of 30 days.") | |
| minutes = 30*24*3600 # 30 days in minutes | |
| expire = now_utc + timedelta(minutes=minutes) | |
| if "exp" not in to_encode: | |
| to_encode["exp"] = expire | |
| if "iat" not in to_encode: | |
| to_encode["iat"] = int(now_utc.timestamp()) | |
| encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) | |
| return encoded_jwt | |
| def create_sso_token(data: dict, secret_key: str, audience: str) -> str: | |
| """ | |
| Creates a JWT access token specifically for an SSO application. | |
| """ | |
| to_encode = data.copy() | |
| expire = datetime.now(timezone.utc) + timedelta(minutes=15) # SSO tokens have a short lifespan | |
| to_encode.update({ | |
| "exp": expire, | |
| "aud": audience | |
| }) | |
| encoded_jwt = jwt.encode(to_encode, secret_key, algorithm=ALGORITHM) | |
| return encoded_jwt | |
| def create_reset_token() -> str: | |
| """Generates a secure, URL-safe random token for password resets.""" | |
| return secrets.token_urlsafe(32) | |
| def _convert_html_to_text(html_string: str) -> str: | |
| """ | |
| A more robust function to convert an HTML string to a plain text string, | |
| preserving block-level spacing. | |
| """ | |
| if not html_string: | |
| return "" | |
| text = html.unescape(html_string) | |
| text = re.sub(r'</(p|div|h[1-6]|blockquote|tr|li)>', '\n\n', text, flags=re.IGNORECASE) | |
| text = re.sub(r'<br>\s*', '\n', text, flags=re.IGNORECASE) | |
| text = re.sub(r'<li[^>]*>', '* ', text, flags=re.IGNORECASE) | |
| text = re.sub(r'<[^>]+>', '', text) | |
| text = re.sub(r'[ \t]+', ' ', text) | |
| text = re.sub(r'\n{3,}', '\n\n', text) | |
| return text.strip() | |
| def _get_full_html_email(body: str, background_color: Optional[str]) -> str: | |
| """Wraps the email body in a full HTML document with a background color.""" | |
| safe_bg_color = "#f4f4f4" # Default light gray background | |
| if background_color and re.match(r'^#(?:[0-9a-fA-F]{3}){1,2}$', background_color): | |
| safe_bg_color = background_color | |
| return f""" | |
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Email</title> | |
| </head> | |
| <body style="margin: 0; padding: 20px; font-family: sans-serif; background-color: {safe_bg_color};"> | |
| <div style="max-width: 600px; margin: auto; background: #ffffff; padding: 20px; border-radius: 8px;"> | |
| {body} | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| EMAIL_RE = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$') | |
| def validate_email_address(email: str) -> str: | |
| """ | |
| Validates an email address to prevent CLI argument injection, CRLF header injection, | |
| and malformed recipients. | |
| """ | |
| if not email or not isinstance(email, str): | |
| raise ValueError("Recipient email address cannot be empty.") | |
| cleaned = email.strip() | |
| if '\n' in cleaned or '\r' in cleaned or '\0' in cleaned: | |
| raise ValueError("Invalid email address: contains newline or control characters.") | |
| if cleaned.startswith('-'): | |
| raise ValueError("Invalid email address: leading hyphen is forbidden.") | |
| if not EMAIL_RE.match(cleaned): | |
| raise ValueError(f"Invalid email address format: '{cleaned}'") | |
| return cleaned | |
| def _send_email_smtp(to_email: str, subject: str, html_content: Optional[str], text_content: str): | |
| """Sends an email using a configured SMTP server. It can be text-only or multipart.""" | |
| safe_email = validate_email_address(to_email) | |
| safe_subject = subject.replace("\n", " ").replace("\r", " ").strip() | |
| from backend.settings import settings | |
| smtp_host = settings.get("smtp_host") | |
| smtp_port = settings.get("smtp_port", 587) | |
| smtp_user = settings.get("smtp_user") | |
| smtp_password = settings.get("smtp_password") | |
| from_email = settings.get("smtp_from_email") | |
| use_tls = settings.get("smtp_use_tls", True) | |
| if not all([smtp_host, smtp_port, smtp_user, smtp_password, from_email]): | |
| raise ValueError("SMTP settings are not fully configured.") | |
| if html_content: | |
| msg = MIMEMultipart('alternative') | |
| part1 = MIMEText(text_content, 'plain', 'utf-8') | |
| part2 = MIMEText(html_content, 'html', 'utf-8') | |
| msg.attach(part1) | |
| msg.attach(part2) | |
| else: | |
| msg = MIMEText(text_content, 'plain', 'utf-8') | |
| msg['Subject'] = safe_subject | |
| msg['From'] = from_email | |
| msg['To'] = safe_email | |
| try: | |
| with smtplib.SMTP(smtp_host, smtp_port) as server: | |
| if use_tls: | |
| server.starttls() | |
| server.login(smtp_user, smtp_password) | |
| server.sendmail(from_email, [safe_email], msg.as_string()) | |
| print(f"INFO: Email (SMTP) sent to {safe_email}") | |
| except Exception as e: | |
| print(f"CRITICAL: Failed to send SMTP email. Error: {e}") | |
| raise | |
| def _send_email_gmail(to_email: str, subject: str, html_content: Optional[str], text_content: str): | |
| """Sends an email using Gmail's SMTP servers with pre-configured host/port.""" | |
| safe_email = validate_email_address(to_email) | |
| safe_subject = subject.replace("\n", " ").replace("\r", " ").strip() | |
| from backend.settings import settings | |
| smtp_host = "smtp.gmail.com" | |
| smtp_port = 587 | |
| smtp_user = settings.get("smtp_user") | |
| smtp_password = settings.get("smtp_password") | |
| from_email = smtp_user | |
| use_tls = True | |
| if not all([smtp_user, smtp_password]): | |
| raise ValueError("Gmail credentials (user and app password) are not configured.") | |
| if html_content: | |
| msg = MIMEMultipart('alternative') | |
| part1 = MIMEText(text_content, 'plain', 'utf-8') | |
| part2 = MIMEText(html_content, 'html', 'utf-8') | |
| msg.attach(part1) | |
| msg.attach(part2) | |
| else: | |
| msg = MIMEText(text_content, 'plain', 'utf-8') | |
| msg['Subject'] = safe_subject | |
| msg['From'] = from_email | |
| msg['To'] = safe_email | |
| try: | |
| with smtplib.SMTP(smtp_host, smtp_port) as server: | |
| if use_tls: | |
| server.starttls() | |
| server.login(smtp_user, smtp_password) | |
| server.sendmail(from_email, [safe_email], msg.as_string()) | |
| print(f"INFO: Email (Gmail) sent to {safe_email}") | |
| except Exception as e: | |
| print(f"CRITICAL: Failed to send Gmail email. Error: {e}") | |
| raise | |
| def _send_email_system_mail_text(to_email: str, subject: str, text_content: str): | |
| """Sends a plain text email using system commands (sendmail, mailx, or mail) with argument injection guards.""" | |
| safe_email = validate_email_address(to_email) | |
| safe_subject = subject.replace("\n", " ").replace("\r", " ").strip() | |
| # 1. Try sendmail first | |
| if shutil.which("sendmail"): | |
| full_email = ( | |
| f"To: {safe_email}\n" | |
| f"Subject: {safe_subject}\n" | |
| f"Content-Type: text/plain; charset=utf-8\n" | |
| f"\n" | |
| f"{text_content}" | |
| ) | |
| command = ["sendmail", "-t", "-i", "--"] | |
| try: | |
| subprocess.run(command, input=full_email, capture_output=True, text=True, check=True, encoding="utf-8") | |
| print(f"INFO: Email (Text system mail) sent to {safe_email} via sendmail.") | |
| return | |
| except Exception as e: | |
| print(f"WARNING: sendmail failed: {e}") | |
| # 2. Try mailx | |
| if shutil.which("mailx"): | |
| command = ["mailx", "-s", safe_subject, "--", safe_email] | |
| try: | |
| subprocess.run(command, input=text_content, capture_output=True, text=True, check=True, encoding="utf-8") | |
| print(f"INFO: Email (Text system mail) sent to {safe_email} via mailx.") | |
| return | |
| except Exception as e: | |
| print(f"WARNING: mailx failed: {e}") | |
| # 3. Try standard mail | |
| if shutil.which("mail"): | |
| command = ["mail", "-s", safe_subject, "--", safe_email] | |
| try: | |
| subprocess.run(command, input=text_content, capture_output=True, text=True, check=True, encoding="utf-8") | |
| print(f"INFO: Email (Text system mail) sent to {safe_email} via mail.") | |
| return | |
| except Exception as e: | |
| print(f"ERROR: mail command failed: {e}") | |
| raise | |
| raise FileNotFoundError("Neither 'sendmail', 'mailx', nor 'mail' command found on host system.") | |
| def _send_email_system_mail_html(to_email: str, subject: str, html_content: str, text_content: str): | |
| """Sends HTML multipart email using sendmail or mailx with graceful plain text fallback.""" | |
| if shutil.which("sendmail"): | |
| try: | |
| return _send_email_sendmail_html(to_email, subject, html_content, text_content) | |
| except Exception as ex: | |
| print(f"WARNING: sendmail HTML delivery failed: {ex}. Falling back to system text mail.") | |
| return _send_email_system_mail_text(to_email, subject, text_content) | |
| return _send_email_system_mail_text(to_email, subject, text_content) | |
| def _send_email_sendmail_html(to_email: str, subject: str, html_content: str, text_content: str): | |
| """Send HTML email using sendmail (more reliable for MIME).""" | |
| if not shutil.which("sendmail"): | |
| raise FileNotFoundError("The 'sendmail' command not found.") | |
| safe_email = validate_email_address(to_email) | |
| safe_subject = subject.replace("\n", " ").replace("\r", " ").strip() | |
| boundary = f"----=_NextPart_{secrets.token_hex(16)}" | |
| full_email = ( | |
| f"To: {safe_email}\n" | |
| f"Subject: {safe_subject}\n" | |
| f"MIME-Version: 1.0\n" | |
| f"Content-Type: multipart/alternative; boundary=\"{boundary}\"\n" | |
| f"\n" | |
| f"This is a multi-part message in MIME format.\n" | |
| f"--{boundary}\n" | |
| f"Content-Type: text/plain; charset=utf-8\n" | |
| f"Content-Transfer-Encoding: 8bit\n\n" | |
| f"{text_content}\n\n" | |
| f"--{boundary}\n" | |
| f"Content-Type: text/html; charset=utf-8\n" | |
| f"Content-Transfer-Encoding: 8bit\n\n" | |
| f"{html_content}\n\n" | |
| f"--{boundary}--\n" | |
| ) | |
| command = ["sendmail", "-t", "-i", "--"] | |
| try: | |
| process = subprocess.run( | |
| command, | |
| input=full_email, | |
| capture_output=True, | |
| text=True, | |
| check=True, | |
| encoding="utf-8" | |
| ) | |
| print(f"INFO: Email sent via sendmail to {safe_email}.") | |
| except subprocess.CalledProcessError as e: | |
| print(f"ERROR: Sendmail command failed.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") | |
| raise | |
| def _send_email_outlook(to_email: str, subject: str, body: str): | |
| """Sends an email using Outlook.""" | |
| try: | |
| import win32com.client | |
| except ImportError: | |
| print("win32com.client not installed. Please install pywin32.") | |
| return | |
| safe_email = validate_email_address(to_email) | |
| safe_subject = subject.replace("\n", " ").replace("\r", " ").strip() | |
| try: | |
| outlook = win32com.client.Dispatch("Outlook.Application") | |
| mail = outlook.CreateItem(0) | |
| mail.To = safe_email | |
| mail.Subject = safe_subject | |
| if "<" in body and ">" in body: | |
| mail.HTMLBody = body | |
| else: | |
| mail.Body = body | |
| mail.Send() | |
| print(f"INFO: Email sent using Outlook to {safe_email}") | |
| except Exception as e: | |
| print(f"ERROR: Failed to send email using Outlook. Error: {e}") | |
| def send_generic_email(to_email: str, subject: str, body: str, background_color: Optional[str] = "#f4f4f4", send_as_text: bool = False): | |
| """ | |
| Prepares and sends a generic email, handling both HTML and plain text modes correctly. | |
| """ | |
| safe_email = validate_email_address(to_email) | |
| safe_subject = subject.replace("\n", " ").replace("\r", " ").strip() | |
| from backend.settings import settings | |
| recovery_mode = settings.get("password_recovery_mode", "manual") | |
| html_body = _get_full_html_email(body, background_color) if not send_as_text else None | |
| recovery_mode = str(recovery_mode).lower().strip() | |
| if recovery_mode in ("smtp", "automatic"): | |
| text_content = _convert_html_to_text(body) | |
| _send_email_smtp(safe_email, safe_subject, html_body, text_content) | |
| elif recovery_mode == "gmail": | |
| text_content = _convert_html_to_text(body) | |
| _send_email_gmail(safe_email, safe_subject, html_body, text_content) | |
| elif recovery_mode == "system_mail": | |
| text_content = _convert_html_to_text(body) | |
| if send_as_text: | |
| _send_email_system_mail_text(safe_email, safe_subject, text_content) | |
| else: | |
| _send_email_system_mail_html(safe_email, safe_subject, html_body, text_content) | |
| elif recovery_mode == "outlook": | |
| if platform.system() == "Windows": | |
| _send_email_outlook(safe_email, safe_subject, body) | |
| else: | |
| print("Outlook integration is only supported on Windows.") | |
| else: | |
| error_msg = f"Email sending is set to '{recovery_mode}'. No email configuration found or manual mode is active." | |
| print(f"WARNING: {error_msg}") | |
| raise ValueError(error_msg) | |
| def generate_verification_code(length: int = 6) -> str: | |
| """Generates a secure numeric OTP verification code.""" | |
| return ''.join(secrets.choice('0123456789') for _ in range(length)) | |
| def send_verification_code_email(to_email: str, code: str, username: str, expiry_minutes: int = 10): | |
| """Sends a 2FA/Email Verification login code.""" | |
| subject = "Your LoLLMs Authentication Code" | |
| body_content = f""" | |
| <h2>Authentication Verification</h2> | |
| <p>Hello <strong>{username}</strong>,</p> | |
| <p>A login request requires email verification. Use the following security code to complete sign-in:</p> | |
| <div style="background-color: #f1f5f9; padding: 18px; border-radius: 12px; font-size: 28px; font-weight: bold; letter-spacing: 6px; text-align: center; color: #1e293b; margin: 24px 0;"> | |
| {code} | |
| </div> | |
| <p style="color: #64748b; font-size: 13px;">This code will expire in {expiry_minutes} minutes. If you did not attempt to sign in, please secure your account immediately.</p> | |
| """ | |
| try: | |
| send_generic_email(to_email, subject, body_content, background_color="#f8fafc", send_as_text=False) | |
| except Exception as e: | |
| print(f"ERROR: Failed sending verification code email to {to_email}: {e}") | |
| # Fallback to plain text transmission | |
| text_content = f"Hello {username},\n\nYour LoLLMs authentication code is: {code}\nThis code expires in {expiry_minutes} minutes." | |
| send_generic_email(to_email, subject, text_content, send_as_text=True) | |
| def send_password_reset_email(to_email: str, reset_link: str, username: str): | |
| """Prepares and sends a password reset email using the configured method.""" | |
| subject = "Password Reset Request" | |
| body_content = f""" | |
| <h2>Password Reset Request</h2> | |
| <p>Hello <strong>{username}</strong>,</p> | |
| <p>You requested a password reset for your LoLLMs account. Click the button below to set a new password:</p> | |
| <div style="margin: 25px 0;"> | |
| <a href="{reset_link}" style="color: #ffffff; background-color: #2563eb; padding: 12px 24px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">Reset Password</a> | |
| </div> | |
| <p style="color: #64748b; font-size: 13px;">Or copy and paste this URL into your browser:<br><a href="{reset_link}" style="color: #2563eb;">{reset_link}</a></p> | |
| <p style="color: #94a3b8; font-size: 12px;">This link expires in 1 hour. If you did not request this, you can safely ignore this email.</p> | |
| """ | |
| try: | |
| send_generic_email(to_email, subject, body_content, background_color="#f8fafc", send_as_text=False) | |
| except Exception as e: | |
| print(f"ERROR: HTML password reset email failed for {to_email}: {e}. Retrying as plain text...") | |
| text_content = f"Hello {username},\n\nYou requested a password reset for your LoLLMs account.\nReset link: {reset_link}\nThis link expires in 1 hour." | |
| send_generic_email(to_email, subject, text_content, send_as_text=True) | |
| def decode_main_access_token(token: str) -> Optional[dict]: | |
| """Decodes a main application JWT using the global SECRET_KEY.""" | |
| try: | |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
| return payload | |
| except JWTError: | |
| return None | |
| def decode_sso_token(token: str, secret_key: str, audience: str) -> Optional[dict]: | |
| """Decodes an SSO JWT using the application-specific secret key and audience.""" | |
| try: | |
| payload = jwt.decode(token, secret_key, algorithms=[ALGORITHM], audience=audience) | |
| return payload | |
| except JWTError: | |
| return None | |
Xet Storage Details
- Size:
- 30.4 kB
- Xet hash:
- 12bdce70e0836fc55318a4eea1ef8f3708231f29eb3096af107801449c7bb616
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.