"""Canonical HyperFlow API: explicit lifecycle, scoped execution and recoverable state. This module wires the application: lifecycle, middleware, error mapping and route modules. Endpoints live in backend/flagship/routes/, grouped by area. """ from collections import Counter, defaultdict from contextlib import asynccontextmanager import json import logging import os from pathlib import Path import time import uuid try: from dotenv import load_dotenv load_dotenv() except ImportError: pass from fastapi import FastAPI, HTTPException from fastapi.responses import JSONResponse, FileResponse from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from .store import Store, Conflict from .identity import Identity from .provider import Provider from .commerce import Commerce from .routes import agent, auth, commerce, ml, operations, provider as provider_routes, system logger = logging.getLogger('hyperflow') MAX_BODY_BYTES = 1024 * 1024 ROUTERS = (system, auth, provider_routes, commerce, agent, ml, operations) class BodyLimit: """Reject request bodies over MAX_BODY_BYTES, counting streamed bytes as they arrive so a body without Content-Length cannot bypass the limit.""" def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): if scope['type'] != 'http': return await self.app(scope, receive, send) too_large = JSONResponse({'detail': 'Request body exceeds 1 MiB'}, status_code=413) declared = dict(scope['headers']).get(b'content-length', b'') if declared.isdigit() and int(declared) > MAX_BODY_BYTES: return await too_large(scope, receive, send) received, exceeded = 0, False async def limited(): nonlocal received, exceeded if exceeded: return {'type': 'http.disconnect'} message = await receive() received += len(message.get('body', b'')) if received > MAX_BODY_BYTES: # End the body early; FastAPI would turn a raised error into a generic 400. exceeded = True return {'type': 'http.request', 'body': b'', 'more_body': False} return message async def guarded(message): if not exceeded: await send(message) await self.app(scope, limited, guarded) if exceeded: await too_large(scope, receive, send) def create_app(store=None, provider=None): @asynccontextmanager async def lifespan(app): if app.state.store is None: app.state.store = Store() db = app.state.store if os.getenv('HYPERFLOW_DEMO') == '1': db.migrate() if not db.ready(): raise RuntimeError('Database migration required: python -m backend.flagship.manage migrate') app.state.identity = Identity(db) app.state.provider = provider or Provider(db, app.state.identity) app.state.commerce = Commerce(db, app.state.provider) yield app = FastAPI(title='HyperFlow', version='4.0.0', lifespan=lifespan) app.state.store = store app.state.login_attempts = defaultdict(list) app.state.metrics = Counter() app.state.streams = Counter() try: from backend.api.routers.geo_router import router as geo_router app.include_router(geo_router) except Exception as e: logger.warning(f'Could not mount geo_router: {e}') app.add_middleware(CORSMiddleware, allow_origins=os.getenv('HYPERFLOW_ORIGINS', 'http://localhost:5173,http://127.0.0.1:5173,http://localhost:4173,http://127.0.0.1:4173').split(','), allow_methods=['GET', 'POST', 'DELETE'], allow_headers=['Content-Type', 'Authorization', 'Idempotency-Key', 'Last-Event-ID']) app.add_middleware(BodyLimit) @app.middleware('http') async def observe(request, call_next): correlation = str(uuid.uuid4()) started = time.monotonic() response = await call_next(request) response.headers['X-Request-ID'] = correlation response.headers['X-Content-Type-Options'] = 'nosniff' response.headers['Cache-Control'] = 'no-store' response.headers['X-Robots-Tag'] = 'noindex' # The interactive API docs load their bundle from a CDN; everything else is same-origin only. if request.url.path not in ('/docs', '/redoc'): response.headers['Content-Security-Policy'] = ( "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; " "form-action 'self'; frame-ancestors 'none'") response.headers['X-Frame-Options'] = 'DENY' response.headers['Referrer-Policy'] = 'no-referrer' response.headers['Permissions-Policy'] = 'camera=(), microphone=(), geolocation=(), payment=()' if request.url.scheme == 'https' or request.headers.get('x-forwarded-proto') == 'https': response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains' app.state.metrics[str(response.status_code)] += 1 logger.info(json.dumps({'request_id': correlation, 'method': request.method, 'path': request.url.path, 'status': response.status_code, 'duration_ms': round((time.monotonic() - started) * 1000, 2)})) return response @app.exception_handler(PermissionError) async def forbidden(request, exc): return JSONResponse({'detail': str(exc)}, status_code=403) @app.exception_handler(LookupError) async def missing(request, exc): return JSONResponse({'detail': 'Record not found'}, status_code=404) @app.exception_handler(Conflict) async def conflict(request, exc): return JSONResponse({'detail': str(exc)}, status_code=409) @app.exception_handler(ValueError) async def invalid(request, exc): return JSONResponse({'detail': str(exc)}, status_code=422) @app.exception_handler(TimeoutError) async def timeout(request, exc): return JSONResponse({'detail': 'Provider unavailable; inspect pending action before retrying'}, status_code=503) for module in ROUTERS: app.include_router(module.router) # Compatibility is deliberately closed: old unauthenticated mutation surfaces cannot bypass v2 approvals. @app.api_route('/api/v1/{path:path}', methods=['GET', 'POST', 'PUT', 'DELETE']) @app.api_route('/api/mcp/{path:path}', methods=['GET', 'POST', 'PUT', 'DELETE']) @app.api_route('/api/agent/{path:path}', methods=['GET', 'POST']) @app.api_route('/api/ml/{path:path}', methods=['GET', 'POST']) @app.api_route('/api/analytics/{path:path}', methods=['GET', 'POST']) def retired(path: str): raise HTTPException(410, 'Legacy surface retired; use authenticated /api/v2 workflows') frontend = Path(__file__).resolve().parents[2] / 'frontend' / 'dist' if (frontend / 'assets').exists(): app.mount('/assets', StaticFiles(directory=frontend / 'assets'), name='assets') @app.get('/{path:path}') def spa(path: str): if path.startswith('api/'): raise HTTPException(404) if path in {'manifest.webmanifest', 'sw.js', 'favicon.svg', 'favicon.ico', 'robots.txt'}: asset = frontend / path if asset.exists(): return FileResponse(asset, media_type='application/manifest+json' if path == 'manifest.webmanifest' else None) file = frontend / 'index.html' if not file.exists(): return {'service': 'HyperFlow', 'docs': '/docs', 'frontend': 'Run npm --prefix frontend run build'} return FileResponse(file) return app