"""Independent, database-free BortStack enquiry service. No account imports.""" import json import os import re from email.utils import parseaddr from html import escape from urllib.request import Request, urlopen from uuid import UUID from flask import Flask, request from flask_limiter import Limiter from flask_limiter.util import get_remote_address from werkzeug.middleware.proxy_fix import ProxyFix SERVICES = ('Website Development', 'Custom Software & Web Applications', 'API Development & Integration', 'Managed Hosting & Maintenance') def valid_email(value): return (isinstance(value, str) and len(value) <= 254 and re.fullmatch(r"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+", value) is not None) def deliver(payload, key, config): """Bounded provider call; only provider acceptance with an ID counts as success.""" req = Request('https://api.resend.com/emails', data=json.dumps(payload).encode(), headers={'Authorization': f"Bearer {config['RESEND_API_KEY']}", 'Content-Type': 'application/json', 'Idempotency-Key': f'contact/{key}'}, method='POST') with urlopen(req, timeout=10) as response: result = json.loads(response.read(16384)) if not isinstance(result, dict) or not isinstance(result.get('id'), str) or not result['id']: raise ValueError('Provider did not acknowledge acceptance') def create_app(overrides=None): app = Flask(__name__) app.config.update(MAX_CONTENT_LENGTH=32768, CONTACT_EMAIL=os.environ.get('CONTACT_EMAIL', ''), EMAIL_FROM=os.environ.get('EMAIL_FROM', ''), RESEND_API_KEY=os.environ.get('RESEND_API_KEY', ''), EMAIL_DELIVERY_ENABLED=os.environ.get('EMAIL_DELIVERY_ENABLED', 'false').lower() == 'true', CONTACT_TRUST_PROXY=os.environ.get('CONTACT_TRUST_PROXY', 'false').lower() == 'true') if overrides: app.config.update(overrides) # Enable only behind a single trusted proxy that overwrites client headers. if app.config['CONTACT_TRUST_PROXY']: app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1) limiter = Limiter(get_remote_address, app=app, storage_uri='memory://') app.extensions['contact_limiter'] = limiter def configured(): sender = app.config['EMAIL_FROM'] return bool(app.config['EMAIL_DELIVERY_ENABLED'] and valid_email(app.config['CONTACT_EMAIL']) and isinstance(sender, str) and '\r' not in sender and '\n' not in sender and valid_email(parseaddr(sender)[1]) and app.config['RESEND_API_KEY']) @app.get('/api/health') @app.get('/api/health/live') @app.get('/api/health/ready') def health(): # Process readiness is separate from externally configured mail availability. return {'status': 'ready'} @app.get('/api/contact/config') def contact_config(): email = app.config['CONTACT_EMAIL'] response = app.json.response({'email': email if valid_email(email) else None, 'available': configured()}) response.headers['Cache-Control'] = 'no-store' return response @app.errorhandler(413) def too_large(_error): return {'message': 'Message is too large.'}, 413 @app.errorhandler(429) def limited(_error): return {'message': 'Too many attempts. Please try again later.'}, 429, {'Retry-After': '3600'} @app.post('/api/contact') @limiter.limit('5 per hour;20 per day') def contact(): data = request.get_json(silent=True) if not isinstance(data, dict): return {'message': 'Send a valid enquiry.'}, 400 allowed = {'name', 'email', 'service', 'description', 'website'} if set(data) - allowed or any(not isinstance(v, str) for v in data.values()): return {'message': 'Send a valid enquiry.'}, 400 if data.get('website', ''): return {'message': 'Unable to accept this enquiry.'}, 400 values = {k: data.get(k, '').strip() for k in allowed} errors = {} if not 1 <= len(values['name']) <= 100 or any(ord(c) < 32 for c in values['name']): errors['name'] = 'Enter your name (up to 100 characters).' if not valid_email(values['email']): errors['email'] = 'Enter a valid email address.' if values['service'] and values['service'] not in SERVICES: errors['service'] = 'Choose one of the listed services or leave it blank.' if not 10 <= len(values['description']) <= 5000 or '\x00' in values['description']: errors['description'] = 'Describe your project in 10 to 5,000 characters.' if errors: return {'message': 'Please check the highlighted fields.', 'errors': errors}, 400 key = request.headers.get('Idempotency-Key', '') try: if str(UUID(key)) != key: raise ValueError() except (ValueError, AttributeError): return {'message': 'Refresh the page and try again.'}, 400 if not configured(): return {'message': 'Enquiries are temporarily unavailable. Your message has not been sent.'}, 503 service = values['service'] or 'General enquiry' text = f"Name: {values['name']}\nEmail: {values['email']}\nService: {service}\n\n{values['description']}" payload = {'from': app.config['EMAIL_FROM'], 'to': [app.config['CONTACT_EMAIL']], 'reply_to': values['email'], 'subject': f'BortStack enquiry: {service}', 'text': text, 'html': '
' + escape(text) + ''} try: deliver(payload, key, app.config) except Exception: # No provider exception/body or visitor data in logs/responses. app.logger.warning('Contact provider acceptance could not be confirmed') return {'message': 'Sending could not be confirmed. Your draft is kept; please retry. A retry of the same draft avoids duplicate processing.'}, 503 return {'success': True, 'message': 'Your enquiry has been accepted for delivery. Thank you.'} return app app = create_app()