Spaces:
Running
Running
Download sim_access_middleware.py from Tonic/uas-eus-webhook: direct link, hf CLI and curl.
- Browser
- Download file 2.07 kB
-
https://huggingface.co/spaces/Tonic/uas-eus-webhook/resolve/main/sim_access_middleware.py
- Command line
-
hf download hf://spaces/Tonic/uas-eus-webhook/sim_access_middleware.py
-
curl -L -o sim_access_middleware.py https://huggingface.co/spaces/Tonic/uas-eus-webhook/resolve/main/sim_access_middleware.py
2.07 kB
| """Sim-side pro-area gate for Tonic/sim-factory-demo. | |
| Drop into the sim Space and wrap the app: | |
| from sim_access_middleware import SimAccessMiddleware | |
| app.add_middleware(SimAccessMiddleware) | |
| It verifies the `?access=` HMAC token minted by the uas.eus API (/api/sim-token) for users with | |
| the RevenueCat `pro` entitlement. Protected path prefixes come from env SIM_PRO_PATHS (default | |
| below). Tokens are signed with SIM_ACCESS_SECRET — the SAME secret must be set in BOTH Spaces. | |
| token format: b64url(payload).b64url(hmac_sha256(secret, payload_b64)) payload: {sub, pro, exp} | |
| """ | |
| import base64, hashlib, hmac, json, os, time | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.responses import JSONResponse | |
| SECRET = os.environ.get("SIM_ACCESS_SECRET", "") | |
| PRO_PATHS = tuple(p for p in os.environ.get( | |
| "SIM_PRO_PATHS", | |
| "/api/editor/hillclimb,/api/bom,/api/models/latest,/api/sweeps/grid,/runs/saved", | |
| ).split(",") if p) | |
| def _b64u_decode(s: str) -> bytes: | |
| return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) | |
| def verify(token: str) -> dict | None: | |
| try: | |
| body, sig = token.split(".") | |
| expect = base64.urlsafe_b64encode( | |
| hmac.new(SECRET.encode(), body.encode(), hashlib.sha256).digest()).decode().rstrip("=") | |
| if not hmac.compare_digest(expect, sig): | |
| return None | |
| payload = json.loads(_b64u_decode(body)) | |
| if not payload.get("pro") or payload.get("exp", 0) < time.time(): | |
| return None | |
| return payload | |
| except Exception: | |
| return None | |
| class SimAccessMiddleware(BaseHTTPMiddleware): | |
| async def dispatch(self, request, call_next): | |
| path = request.url.path | |
| if path.startswith(PRO_PATHS): | |
| token = request.query_params.get("access", "") | |
| payload = verify(token) if token else None | |
| if not payload: | |
| return JSONResponse({"detail": "pro access required"}, status_code=403) | |
| request.state.sim_user = payload["sub"] | |
| return await call_next(request) | |