Download tasks/insureon/solution/site/implementation/harbor_entry.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 7.29 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/insureon/solution/site/implementation/harbor_entry.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/insureon/solution/site/implementation/harbor_entry.py
-
curl -L -o harbor_entry.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/insureon/solution/site/implementation/harbor_entry.py
7.29 kB
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import urllib.parse | |
| import urllib.request | |
| from contextvars import ContextVar | |
| from pathlib import Path | |
| from typing import Any | |
| import uvicorn | |
| from fastapi import Request | |
| from starlette.responses import JSONResponse, Response | |
| from websitebench.local_clone_auth.store import LocalAuthStore | |
| ROOT = Path(__file__).resolve().parent | |
| SITE_ID = "insureon" | |
| DATABASE_NAME = "insureon.sqlite3" | |
| data_dir = Path(os.environ["DATA_DIR"]).resolve() | |
| migration_version = 1 | |
| REQUIRED_INVARIANTS = ( | |
| "insureon.frozen-route-closure", | |
| "insureon.account-business-isolation", | |
| "insureon.mailpit-only-mail", | |
| "insureon.local-sandbox-policy-payment", | |
| ) | |
| required_invariants = REQUIRED_INVARIANTS | |
| PAYMENT_ADAPTER = "local-sandbox" | |
| MAILPIT_DIRECT_WRITER = "WEBSITEBENCH_MAILPIT_DIRECT_WRITER_V1" | |
| status_code = 200 | |
| data_dir.mkdir(parents=True, exist_ok=True) | |
| runtime_contract = json.loads( | |
| (ROOT / "backend/runtime.json").read_text(encoding="utf-8") | |
| ) | |
| if ( | |
| runtime_contract.get("site", {}).get("id") != SITE_ID | |
| or runtime_contract.get("database", {}).get("filename") != DATABASE_NAME | |
| ): | |
| raise RuntimeError("assembled backend runtime does not match the site contract") | |
| def _mailpit_writer() -> tuple[str, str, str]: | |
| url = os.environ.get("WEBSITEBENCH_MAIL_API_URL", "").strip() | |
| token = os.environ.get("WEBSITEBENCH_MAIL_API_TOKEN", "").strip() | |
| sender = os.environ.get("WEBSITEBENCH_MAIL_FROM", "").strip() | |
| parsed = urllib.parse.urlsplit(url) | |
| if ( | |
| parsed.scheme != "http" | |
| or parsed.hostname not in {"127.0.0.1", "localhost", "::1", "mailbox-internal"} | |
| or not token | |
| or not sender | |
| ): | |
| raise RuntimeError("Mailpit-backed candidate writer is unavailable") | |
| return url, token, sender | |
| def _send_code(recipient: str, code: str, purpose: str) -> None: | |
| url, token, sender = _mailpit_writer() | |
| declared = runtime_contract.get("mail", {}).get("purposes", {}).get(purpose) | |
| if not isinstance(declared, dict): | |
| raise ValueError("unsupported mail purpose") | |
| subject = str(declared["subject"]) | |
| lead = str(declared["lead"]) | |
| body = str(declared["body"]).replace("${code}", code) | |
| expiry = str(declared["expiry"]).replace("${minutes}", "15") | |
| footer = str(declared["footer"]) | |
| text = "\n\n".join((lead, body, expiry, footer)) | |
| payload = json.dumps( | |
| {"from": sender, "to": recipient, "subject": subject, "text": text}, | |
| separators=(",", ":"), | |
| ).encode() | |
| request = urllib.request.Request( | |
| url, | |
| data=payload, | |
| method="POST", | |
| headers={ | |
| "Authorization": "Bearer " + token, | |
| "Content-Type": "application/json", | |
| }, | |
| ) | |
| with urllib.request.urlopen(request, timeout=5) as response: | |
| if not 200 <= response.status < 300: | |
| raise RuntimeError("Mailpit-backed candidate writer rejected message") | |
| _active_delivery: ContextVar[dict[str, str] | None] = ContextVar( | |
| "insureon_mailpit_delivery", default=None | |
| ) | |
| _original_start_registration = LocalAuthStore.start_registration | |
| _original_start_password_reset = LocalAuthStore.start_password_reset | |
| def _suppress_outbox(self: LocalAuthStore, *args: Any, **kwargs: Any) -> None: | |
| """Formal direct flows never create clone-local mail rows.""" | |
| if _active_delivery.get() is None: | |
| raise RuntimeError("mail creation requires an active Mailpit delivery") | |
| def _capture_code(self: LocalAuthStore, purpose: str, flow_id: str, code: str) -> None: | |
| """Keep the generated OTP only in the active call frame until delivery.""" | |
| active = _active_delivery.get() | |
| if active is not None: | |
| active.update({"purpose": purpose, "flow_id": flow_id, "code": code}) | |
| else: | |
| raise RuntimeError("mail code capture requires an active Mailpit delivery") | |
| def _disable_local_reader( | |
| self: LocalAuthStore, session_token: str, *, purpose: str | |
| ) -> None: | |
| """Candidate code has no mail-reading surface.""" | |
| return None | |
| def _start_registration( | |
| self: LocalAuthStore, | |
| session_token: str, | |
| *, | |
| email: str, | |
| display_name: str, | |
| password: str, | |
| restart_invalid_flow: bool = False, | |
| ) -> dict[str, Any]: | |
| active: dict[str, str] = {} | |
| context = _active_delivery.set(active) | |
| try: | |
| result = _original_start_registration( | |
| self, | |
| session_token, | |
| email=email, | |
| display_name=display_name, | |
| password=password, | |
| restart_invalid_flow=restart_invalid_flow, | |
| ) | |
| code = active.get("code") | |
| if not code: | |
| raise RuntimeError("registration did not generate a Mailpit code") | |
| _send_code(email.strip().casefold(), code, "registration") | |
| return {**result, "mail_status": "MAILPIT_SENT"} | |
| finally: | |
| active.clear() | |
| _active_delivery.reset(context) | |
| def _start_password_reset( | |
| self: LocalAuthStore, | |
| session_token: str, | |
| *, | |
| email: str, | |
| restart_invalid_flow: bool = False, | |
| ) -> dict[str, Any]: | |
| active: dict[str, str] = {} | |
| context = _active_delivery.set(active) | |
| try: | |
| result = _original_start_password_reset( | |
| self, | |
| session_token, | |
| email=email, | |
| restart_invalid_flow=restart_invalid_flow, | |
| ) | |
| code = active.get("code") | |
| if code is not None: | |
| _send_code(email.strip().casefold(), code, "password-reset") | |
| return result | |
| finally: | |
| active.clear() | |
| _active_delivery.reset(context) | |
| LocalAuthStore._insert_mail_unlocked = _suppress_outbox | |
| LocalAuthStore._remember_mail_code = _capture_code | |
| LocalAuthStore.local_mail_for_session = _disable_local_reader | |
| LocalAuthStore.start_registration = _start_registration | |
| LocalAuthStore.start_password_reset = _start_password_reset | |
| from app import APP, _seed_fixtures # noqa: E402 | |
| # The clone's own diagnostic seed establishes a deterministic public quote | |
| # fixture used by the trusted business/payment route probes. | |
| _seed_fixtures() | |
| def _headers(response: Response) -> Response: | |
| response.headers["X-WebsiteBench-Site"] = SITE_ID | |
| response.headers["X-WebsiteBench-Database"] = DATABASE_NAME | |
| response.headers["X-WebsiteBench-Migration"] = str(migration_version) | |
| response.headers["X-WebsiteBench-Invariants"] = ",".join(REQUIRED_INVARIANTS) | |
| response.headers["X-WebsiteBench-Payment-Adapter"] = PAYMENT_ADAPTER | |
| response.headers["X-WebsiteBench-Mail-Transport"] = MAILPIT_DIRECT_WRITER | |
| return response | |
| async def harbor_contract(request: Request, call_next: Any) -> Response: | |
| if request.method == "GET" and request.url.path in { | |
| "/healthz", | |
| "/__websitebench/health", | |
| }: | |
| return _headers(JSONResponse({"status": "ok"})) | |
| if request.url.path in {"/api/account/local-mail", "/account/local-mail"}: | |
| return _headers( | |
| JSONResponse({"error": "mail-reader-disabled"}, status_code=404) | |
| ) | |
| return _headers(await call_next(request)) | |
| if __name__ == "__main__": | |
| uvicorn.run( | |
| APP, | |
| host=os.environ.get("HOST", "127.0.0.1"), | |
| port=int(os.environ.get("PORT", "8080")), | |
| log_level="warning", | |
| ) | |