File size: 7,749 Bytes
64b0986
 
 
 
 
2b86c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64b0986
 
2b86c60
 
64b0986
2b86c60
64b0986
2b86c60
64b0986
2b86c60
 
64b0986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b86c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64b0986
2b86c60
 
 
 
 
 
 
 
 
64b0986
2b86c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64b0986
 
2b86c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27e707f
2b86c60
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
"""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