#!/usr/bin/env python3 """Single-process Harbor adapter for the frozen bluemercury clone. An unscored agent environment with trial-local mail and simulated payments. """ from __future__ import annotations import os import random import sys import time from pathlib import Path import secrets ROOT = Path(__file__).resolve().parent SITE_ID = "bluemercury" DATABASE_NAME = "bluemercury.sqlite3" DISPLAY_NAME = "bluemercury" MAIL_TRANSPORT_CONTRACT = "websitebench.resend-style-text.v1" health_contract = "/healthz" migration_version = 1 required_invariants = ('site-isolation', 'persistent-data', 'browser-mailbox') PAYMENT_ADAPTER = "local-sandbox" payment_profile = "local-sandbox" for _name in ("HOST", "PORT", "DATA_DIR", "SEED", "TZ"): if not os.environ.get(_name): raise SystemExit(f"{_name} is required") data_dir = Path(os.environ["DATA_DIR"]) if not data_dir.is_absolute(): raise SystemExit("DATA_DIR must be absolute") data_dir.mkdir(parents=True, exist_ok=True) try: random.seed(int(os.environ["SEED"])) except ValueError: raise SystemExit("SEED must be an integer") from None if hasattr(time, "tzset"): time.tzset() os.environ["WEBSITEBENCH_SITE_BACKEND_DATABASE"] = str(data_dir / DATABASE_NAME) os.environ["WEBSITEBENCH_SITE_BACKEND_RUNTIME"] = str(ROOT / "backend" / "runtime.json") os.environ["WEBSITEBENCH_DEPLOYMENT_PROFILE"] = "offline-harbor" os.environ["WEBSITEBENCH_PAYMENT_PROFILE"] = PAYMENT_ADAPTER os.environ["WEBSITEBENCH_LOCAL_HTTP_COOKIE"] = "1" os.environ["WEBSITEBENCH_HARBOR_MIGRATION_VERSION"] = str(migration_version) os.environ["PYTHONDONTWRITEBYTECODE"] = "1" for _name in ( "STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET", "STRIPE_TEST_SECRET_KEY", "STRIPE_TEST_WEBHOOK_SECRET", ): os.environ.pop(_name, None) sys.dont_write_bytecode = True sys.path.insert(0, str(ROOT / "vendor")) sys.path.insert(0, str(ROOT / "clone")) # The frozen clone resolves its own static mounts relative to the process # working directory, so the adapter enters the clone tree rather than # rewriting a pinned path. os.chdir(ROOT / "clone") import websitebench.local_clone_auth as auth_package # noqa: E402 from websitebench.local_clone_auth import store as auth_store # noqa: E402 from websitebench.local_clone_auth import ( # noqa: E402 MAIL_SMTP_PENDING, AuthError, ) _BASE_AUTH_STORE = auth_store.LocalAuthStore _MAIL_WORKER_TOKEN = secrets.token_urlsafe(48) def _send_trial_message(recipient, subject, text): import json from urllib.parse import urlsplit from urllib.request import Request, urlopen endpoint = os.environ.get('WEBSITEBENCH_MAIL_API_URL', '') token = os.environ.get('WEBSITEBENCH_MAIL_API_TOKEN', '') sender = os.environ.get('WEBSITEBENCH_MAIL_FROM', '') parsed = urlsplit(endpoint) if parsed.scheme != 'http' or parsed.hostname not in {'mailbox-internal', 'localhost', '127.0.0.1'} or parsed.path != '/emails' or parsed.username or parsed.password or not token or not sender: raise AuthError('Trial mail writer is unavailable') body = json.dumps({'from': sender, 'to': recipient, 'subject': subject, 'text': text}).encode() request = Request(endpoint, data=body, headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}, method='POST') with urlopen(request, timeout=10) as response: if not 200 <= response.status < 300: raise AuthError('Trial mail writer rejected the message') response.read(65536) class MailpitAuthStore(_BASE_AUTH_STORE): """Claim once and send through the trial's canonical write-only mail API.""" def __init__(self, database_path, **kwargs): kwargs['mail_mode'] = MAIL_SMTP_PENDING kwargs['mail_worker_token'] = _MAIL_WORKER_TOKEN super().__init__(database_path, **kwargs) def _deliver(self, session_token, purpose): import json from urllib.parse import urlsplit from urllib.request import Request, urlopen endpoint = os.environ.get('WEBSITEBENCH_MAIL_API_URL', '') token = os.environ.get('WEBSITEBENCH_MAIL_API_TOKEN', '') sender = os.environ.get('WEBSITEBENCH_MAIL_FROM', '') parsed = urlsplit(endpoint) if parsed.scheme != 'http' or parsed.hostname not in {'mailbox-internal', 'localhost', '127.0.0.1'} or parsed.path != '/emails' or parsed.username or parsed.password or not token or not sender: raise AuthError('Trial mail writer is unavailable') claim = self.claim_pending_mail_for_session(session_token, purpose=purpose, worker_token=_MAIL_WORKER_TOKEN) if claim is None: return mail_id, claim_token = int(claim['mail_id']), claim['claim_token'] self.reserve_mail_target_request(mail_id, claim_token, worker_token=_MAIL_WORKER_TOKEN) body = json.dumps({'from': sender, 'to': claim['recipient'], 'subject': DISPLAY_NAME + ' ' + purpose, 'text': 'Your verification code is ' + claim['verification_code'] + '.'}).encode() request = Request(endpoint, data=body, headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}, method='POST') try: with urlopen(request, timeout=10) as response: if not 200 <= response.status < 300: raise OSError('Mail writer rejected the message') response.read(65536) except Exception: self.finish_mail_claim(mail_id, claim_token, sent=False, target_request_count=1, accepted_request_count=0, error='network', worker_token=_MAIL_WORKER_TOKEN) raise AuthError('Mail delivery is unavailable. Please retry.') from None self.finish_mail_claim(mail_id, claim_token, sent=True, target_request_count=1, accepted_request_count=1, worker_token=_MAIL_WORKER_TOKEN) def start_registration(self, session_token, **kwargs): result = super().start_registration(session_token, **kwargs) self._deliver(session_token, 'registration') return result def start_password_reset(self, session_token, **kwargs): result = super().start_password_reset(session_token, **kwargs) self._deliver(session_token, 'password-reset') return result auth_store.LocalAuthStore = MailpitAuthStore auth_package.LocalAuthStore = MailpitAuthStore import app as clone from uvicorn.middleware.wsgi import WSGIMiddleware if hasattr(clone, "business") and hasattr(clone.business, "services"): clone.business.services() app = WSGIMiddleware(clone.app) import uvicorn _application = app async def app(scope, receive, send): if scope['type'] == 'http': async def site_send(message): if message['type'] == 'http.response.start': message = dict(message) message['headers'] = [(k,v) for k,v in message.get('headers', []) if k.lower() != b'x-websitebench-site'] + [(b'x-websitebench-site', SITE_ID.encode())] await send(message) if scope['method'] == 'GET' and scope['path'] in {'/healthz', '/__websitebench/health'}: await site_send({'type':'http.response.start','status':200,'headers':[(b'content-type',b'application/json')]}) await send({'type':'http.response.body','body':b'{"status":"ok"}'}) else: await _application(scope, receive, site_send) else: await _application(scope, receive, send) if __name__ == "__main__": uvicorn.run( app, host=os.environ["HOST"], port=int(os.environ["PORT"]), log_level="warning", )