AgPerry commited on
Commit
8030948
·
verified ·
1 Parent(s): d3fa89e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/fandango/environment/agent-browser/browser-use +152 -0
  2. tasks/fandango/environment/agent-browser/gateway.py +524 -0
  3. tasks/fandango/environment/candidate-abi/websitebench-candidate-preflight +5 -0
  4. tasks/fandango/environment/mailbox/Dockerfile +5 -0
  5. tasks/fandango/environment/mailbox/mailbox.py +2433 -0
  6. tasks/fandango/environment/reference/.websitebench-reference-tls/ca.crt +20 -0
  7. tasks/fandango/environment/reference/.websitebench-reference-tls/reference.crt +20 -0
  8. tasks/fandango/environment/reference/.websitebench-reference-tls/reference.key +28 -0
  9. tasks/fandango/environment/reference/.websitebench-reference-tls/tls_proxy.py +164 -0
  10. tasks/fandango/environment/reference/Dockerfile +19 -0
  11. tasks/fandango/environment/reference/README.md +9 -0
  12. tasks/fandango/environment/reference/backend/model.json +225 -0
  13. tasks/fandango/environment/reference/backend/runtime.json +74 -0
  14. tasks/fandango/environment/reference/clone/app.py +269 -0
  15. tasks/fandango/environment/reference/clone/backend/__init__.py +1 -0
  16. tasks/fandango/environment/reference/clone/backend/catalog.py +1080 -0
  17. tasks/fandango/environment/reference/clone/backend/navigation-catalog.json +0 -0
  18. tasks/fandango/environment/reference/clone/backend/site_backend_integration.py +112 -0
  19. tasks/fandango/environment/reference/clone/backend/store.py +659 -0
  20. tasks/fandango/environment/reference/clone/frontend/index.html +22 -0
  21. tasks/fandango/environment/reference/clone/requirements.txt +2 -0
  22. tasks/fandango/environment/reference/clone/static/app.js +330 -0
  23. tasks/fandango/environment/reference/clone/static/home-data.js +847 -0
  24. tasks/fandango/environment/reference/clone/static/home.css +149 -0
  25. tasks/fandango/environment/reference/clone/static/home.js +145 -0
  26. tasks/fandango/environment/reference/clone/static/nav-assets/0001-FAN_FanStore_Stacked_FullColor_RGB.png +3 -0
  27. tasks/fandango/environment/reference/clone/static/nav-assets/0004-Rotten_Tomatoes_logo_svg.png +3 -0
  28. tasks/fandango/environment/reference/clone/static/nav-assets/0009-JSW10956-Grogu-Mandalorian-Short-Glasses-Listing-1.jpg +3 -0
  29. tasks/fandango/environment/reference/clone/static/nav-assets/0010-Screenshot_2026-06-05_at_7-16-05_PM.png +3 -0
  30. tasks/fandango/environment/reference/clone/static/nav-assets/0012-unisex-garment-dyed-heavyweight-t-shirt-ivory-front-2-6a5e3f3d217e0.jpg +3 -0
  31. tasks/fandango/environment/reference/clone/static/nav-assets/0015-FAN_Shopify_SpidermanBND_PosterBundle_Card_2048x2048_ac5b17c3-558a-4a6.jpg +3 -0
  32. tasks/fandango/environment/reference/clone/static/nav-assets/0023-1-1-1-1-20487-D-3_v2-1772118566769_eca93243-79f7-4071-b311-3a1451ccde5.jpg +3 -0
  33. tasks/fandango/environment/reference/clone/static/nav-assets/0024-FAN_Shopify_PracticalMagic2Bundle_Standard_2048x2048_f8c66d34-b257-4ad.jpg +3 -0
  34. tasks/fandango/environment/reference/clone/static/nav-assets/0025-FAN_Shopify_PracticalMagic2Bundle_PopcornBucket_2048x2048_02db5341-836.jpg +3 -0
  35. tasks/fandango/environment/reference/clone/static/nav-assets/0028-JSW10956_-_Grogu_Mandalorian_Short_Glasses_Lifestyle-3-legal.jpg +3 -0
  36. tasks/fandango/environment/reference/clone/static/nav-assets/0031-unisex-garment-dyed-heavyweight-t-shirt-ivory-front-6a5e3f3d213cf.jpg +3 -0
  37. tasks/fandango/environment/reference/clone/static/nav-assets/0032-unisex-garment-dyed-heavyweight-t-shirt-ivory-front-2-6a5e3f3d217e0.jpg +3 -0
  38. tasks/fandango/environment/reference/clone/static/nav-assets/0033-unisex-garment-dyed-heavyweight-t-shirt-ivory-front-2-6a5e3f3d21a88.jpg +3 -0
  39. tasks/fandango/environment/reference/clone/static/nav-assets/0034-shaker-pint-glass-_16-oz_-16-oz-front-6a5e48fd13c09.jpg +3 -0
  40. tasks/fandango/environment/reference/clone/static/nav-assets/0036-shaker-pint-glass-_16-oz_-16-oz-front-6a5e493c42fa0.jpg +3 -0
  41. tasks/fandango/environment/reference/clone/static/nav-assets/0037-shaker-pint-glass-_16-oz_-16-oz-right-6a5e48fd147c8.jpg +3 -0
  42. tasks/fandango/environment/reference/clone/static/nav-assets/0038-can-cooler-white-regular-12-oz-front-680fab155ba87.jpg +3 -0
  43. tasks/fandango/environment/reference/clone/static/nav-assets/0039-can-cooler-white-regular-12-oz-back-680fab155bcc2.jpg +3 -0
  44. tasks/fandango/environment/reference/clone/static/nav-assets/0040-can-cooler-white-regular-12-oz-front-680fab155bb31.jpg +3 -0
  45. tasks/fandango/environment/reference/clone/static/nav-assets/0041-can-cooler-white-regular-12-oz-front-680fab155bc01.jpg +3 -0
  46. tasks/fandango/environment/reference/clone/static/nav-assets/0043-FAN_Shopify_ToyStory5_PrintBundle_Print_2048x2048_573188cb-4474-4229-a.jpg +3 -0
  47. tasks/fandango/environment/reference/clone/static/nav-assets/0045-white-ceramic-mug-with-color-inside-orange-11-oz-front-6a5e358264039.jpg +3 -0
  48. tasks/fandango/environment/reference/clone/static/nav-assets/0047-white-ceramic-mug-with-color-inside-orange-11-oz-left-6a5e359bab63c.jpg +3 -0
  49. tasks/fandango/environment/reference/clone/static/nav-assets/0049-300321444.png +3 -0
  50. tasks/fandango/environment/reference/clone/static/nav-assets/0050-unisex-premium-t-shirt-black-front-6a5e4470a4742.jpg +3 -0
tasks/fandango/environment/agent-browser/browser-use ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Forward the safe Browser Use CLI subset to the isolated browser sidecar."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ import shutil
9
+ import sys
10
+ import urllib.error
11
+ import urllib.request
12
+ import uuid
13
+ from pathlib import Path
14
+
15
+
16
+ GATEWAY_URL = os.environ.get(
17
+ "WEBSITEBENCH_BROWSER_GATEWAY_URL",
18
+ "http://browser:9224/v1/command",
19
+ )
20
+ SHARED_ROOT = Path("/browser-share")
21
+
22
+
23
+ def _translate_candidate_origin(arguments: list[str]) -> list[str]:
24
+ public_origin = os.environ.get(
25
+ "WEBSITEBENCH_CANDIDATE_URL", "http://127.0.0.1:3000"
26
+ ).rstrip("/")
27
+ browser_origin = os.environ.get(
28
+ "WEBSITEBENCH_BROWSER_CANDIDATE_URL", "http://candidate:3000"
29
+ ).rstrip("/")
30
+ return [
31
+ browser_origin + value[len(public_origin) :]
32
+ if value == public_origin or value.startswith(public_origin + "/")
33
+ else value
34
+ for value in arguments
35
+ ]
36
+
37
+
38
+ def _command_index(arguments: list[str]) -> int | None:
39
+ index = 0
40
+ while index < len(arguments):
41
+ value = arguments[index]
42
+ if value in {"--session"}:
43
+ index += 2
44
+ continue
45
+ if value.startswith("--session=") or value == "--json":
46
+ index += 1
47
+ continue
48
+ if value in {"-h", "--help"}:
49
+ return None
50
+ if value.startswith("-"):
51
+ return index
52
+ return index
53
+ return None
54
+
55
+
56
+ def _prepare_screenshot(arguments: list[str]) -> tuple[list[str], Path | None, Path | None]:
57
+ forwarded = list(arguments)
58
+ command_index = _command_index(forwarded)
59
+ if command_index is None or forwarded[command_index] != "screenshot":
60
+ return forwarded, None, None
61
+
62
+ local_path: Path | None = None
63
+ path_index: int | None = None
64
+ for index in range(command_index + 1, len(forwarded)):
65
+ if forwarded[index] == "--path" and index + 1 < len(forwarded):
66
+ path_index = index + 1
67
+ local_path = Path(forwarded[path_index])
68
+ break
69
+ if not forwarded[index].startswith("-"):
70
+ path_index = index
71
+ local_path = Path(forwarded[path_index])
72
+ break
73
+ if local_path is None:
74
+ local_path = Path("screenshot.png")
75
+ forwarded.append(str(local_path))
76
+ path_index = len(forwarded) - 1
77
+
78
+ shared_path = SHARED_ROOT / f"screenshot-{uuid.uuid4().hex}.png"
79
+ assert path_index is not None
80
+ forwarded[path_index] = str(shared_path)
81
+ return forwarded, local_path, shared_path
82
+
83
+
84
+ def _prepare_asset(arguments: list[str]) -> tuple[list[str], Path | None, Path | None]:
85
+ forwarded = list(arguments)
86
+ command_index = _command_index(forwarded)
87
+ if command_index is None or forwarded[command_index] != "save-asset":
88
+ return forwarded, None, None
89
+ tail = forwarded[command_index + 1 :]
90
+ if len(tail) != 2:
91
+ # Let the gateway reject the malformed command with its own message.
92
+ return forwarded, None, None
93
+ local_path = Path(tail[1])
94
+ shared_path = SHARED_ROOT / f"asset-{uuid.uuid4().hex}"
95
+ forwarded[command_index + 2] = str(shared_path)
96
+ return forwarded, local_path, shared_path
97
+
98
+
99
+ def main() -> int:
100
+ translated = _translate_candidate_origin(sys.argv[1:])
101
+ arguments, local_screenshot, shared_screenshot = _prepare_screenshot(translated)
102
+ if local_screenshot is None:
103
+ arguments, local_screenshot, shared_screenshot = _prepare_asset(arguments)
104
+ request = urllib.request.Request(
105
+ GATEWAY_URL,
106
+ data=json.dumps({"argv": arguments}, separators=(",", ":")).encode("utf-8"),
107
+ headers={"Content-Type": "application/json"},
108
+ method="POST",
109
+ )
110
+ try:
111
+ with urllib.request.urlopen(request, timeout=240) as response:
112
+ payload = json.load(response)
113
+ except urllib.error.HTTPError as exc:
114
+ try:
115
+ detail = json.loads(exc.read().decode("utf-8")).get("error")
116
+ except (UnicodeError, ValueError, AttributeError):
117
+ detail = None
118
+ print(detail or f"Browser Use gateway refused the command (HTTP {exc.code})", file=sys.stderr)
119
+ return 2
120
+ except (OSError, UnicodeError, ValueError) as exc:
121
+ print(f"Browser Use gateway unavailable: {exc}", file=sys.stderr)
122
+ return 2
123
+
124
+ stdout = payload.get("stdout", "")
125
+ stderr = payload.get("stderr", "")
126
+ if local_screenshot is not None and shared_screenshot is not None:
127
+ # The shared file is moved to the caller's path below; report that path, not the
128
+ # transient gateway-owned one, so a later read of the printed path succeeds.
129
+ if isinstance(stdout, str):
130
+ stdout = stdout.replace(str(shared_screenshot), str(local_screenshot))
131
+ if isinstance(stderr, str):
132
+ stderr = stderr.replace(str(shared_screenshot), str(local_screenshot))
133
+ if isinstance(stdout, str) and stdout:
134
+ print(stdout, end="" if stdout.endswith("\n") else "\n")
135
+ if isinstance(stderr, str) and stderr:
136
+ print(stderr, end="" if stderr.endswith("\n") else "\n", file=sys.stderr)
137
+
138
+ if local_screenshot is not None and shared_screenshot is not None and shared_screenshot.exists():
139
+ try:
140
+ local_screenshot.parent.mkdir(parents=True, exist_ok=True)
141
+ shutil.copyfile(shared_screenshot, local_screenshot)
142
+ shared_screenshot.unlink(missing_ok=True)
143
+ except OSError as exc:
144
+ print(f"Browser file transfer failed: {exc}", file=sys.stderr)
145
+ return 2
146
+
147
+ exit_code = payload.get("exit_code", 2)
148
+ return exit_code if isinstance(exit_code, int) and 0 <= exit_code <= 255 else 2
149
+
150
+
151
+ if __name__ == "__main__":
152
+ raise SystemExit(main())
tasks/fandango/environment/agent-browser/gateway.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Constrained Browser Use command gateway for browser-only references.
3
+
4
+ The gateway is the only process that joins the reference network. It exposes
5
+ interactive browser actions, but deliberately excludes arbitrary Python,
6
+ JavaScript evaluation, DOM serialization, cloud/tunnel commands, and direct
7
+ CDP attachment. The Agent container can inspect the rendered site without
8
+ obtaining a general-purpose HTTP path to its source responses.
9
+
10
+ Static assets are the one exception to that boundary. ``assets`` lists the
11
+ reference-origin images, icons, fonts and media the current page uses, and
12
+ ``save-asset`` copies one of them into the Agent's repository. Stylesheets and
13
+ scripts are the reference's code: formal runs never hand them to the Agent, so
14
+ both commands refuse them, as they refuse documents and API responses.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import re
22
+ import ssl
23
+ import subprocess
24
+ import threading
25
+ import urllib.error
26
+ import urllib.parse
27
+ import urllib.request
28
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+
33
+ MAX_REQUEST_BYTES = 64 * 1024
34
+ MAX_OUTPUT_BYTES = 4 * 1024 * 1024
35
+ COMMAND_TIMEOUT_SEC = 180
36
+ SESSION_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\Z")
37
+ SHARED_ROOT = Path("/browser-share").resolve()
38
+ ASSET_MAX_BYTES = 32 * 1024 * 1024
39
+ ASSET_TIMEOUT_SEC = 60
40
+ ASSET_LIST_LIMIT = 2000
41
+ ASSET_SHARED_NAME = re.compile(r"asset-[0-9a-f]{32}\Z")
42
+ # Static media only: a document, JSON or other API body is never an asset, and neither is
43
+ # a stylesheet or script (the agent must not receive the reference's CSS or JavaScript).
44
+ STATIC_CONTENT_PREFIXES = ("image/", "font/", "audio/", "video/")
45
+ STATIC_CONTENT_TYPES = frozenset(
46
+ {
47
+ "application/font-woff",
48
+ "application/font-woff2",
49
+ "application/x-font-woff",
50
+ "application/x-font-ttf",
51
+ "application/x-font-otf",
52
+ "application/font-sfnt",
53
+ "application/vnd.ms-fontobject",
54
+ }
55
+ )
56
+ # Servers often label fonts and media application/octet-stream; accept that
57
+ # label only when the path itself names a static file.
58
+ STATIC_EXTENSIONS = frozenset(
59
+ {
60
+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".ico", ".bmp",
61
+ ".woff", ".woff2", ".ttf", ".otf", ".eot",
62
+ ".mp4", ".webm", ".ogv", ".mp3", ".ogg", ".wav", ".m4a",
63
+ }
64
+ )
65
+ # Reference code is refused whatever its declared type: a script served as octet-stream or a
66
+ # stylesheet under an image-like path must not pass.
67
+ CODE_CONTENT_TYPES = frozenset(
68
+ {
69
+ "text/css",
70
+ "text/javascript",
71
+ "text/ecmascript",
72
+ "application/javascript",
73
+ "application/x-javascript",
74
+ "application/ecmascript",
75
+ "application/wasm",
76
+ }
77
+ )
78
+ CODE_EXTENSIONS = frozenset({".css", ".scss", ".less", ".js", ".mjs", ".cjs", ".jsx", ".ts", ".tsx", ".map", ".wasm"})
79
+ # Gateway-owned inventory script: returns only URLs the page references or loaded.
80
+ ASSET_INVENTORY_JS = r"""JSON.stringify((() => {
81
+ const found = new Set();
82
+ const add = (value, base) => { try { if (value) found.add(new URL(value, base || location.href).href); } catch (e) {} };
83
+ const urls = (text, base) => { for (const m of String(text || '').matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/g)) add(m[1], base); };
84
+ for (const entry of performance.getEntriesByType('resource')) add(entry.name);
85
+ for (const image of document.images) { add(image.currentSrc); add(image.src); }
86
+ for (const node of document.querySelectorAll('link[href]')) add(node.href);
87
+ for (const node of document.querySelectorAll('script[src]')) add(node.src);
88
+ for (const node of document.querySelectorAll('source[src], source[srcset], video[src], video[poster], audio[src], img[srcset]')) {
89
+ add(node.src); add(node.poster);
90
+ for (const part of String(node.srcset || '').split(',')) add(part.trim().split(/\s+/)[0]);
91
+ }
92
+ let count = 0;
93
+ for (const element of document.querySelectorAll('*')) {
94
+ if (++count > 5000) break;
95
+ const style = getComputedStyle(element);
96
+ urls(style.backgroundImage); urls(style.listStyleImage); urls(style.content);
97
+ }
98
+ for (const sheet of document.styleSheets) {
99
+ try { for (const rule of sheet.cssRules) urls(rule.cssText, sheet.href || location.href); } catch (e) {}
100
+ }
101
+ return [...found];
102
+ })())"""
103
+ REAL_BROWSER_USE = os.environ.get(
104
+ "WEBSITEBENCH_BROWSER_USE_REAL",
105
+ "/usr/local/bin/browser-use-real",
106
+ )
107
+ SAFE_COMMANDS = frozenset(
108
+ {
109
+ "open",
110
+ "click",
111
+ "type",
112
+ "input",
113
+ "scroll",
114
+ "back",
115
+ "screenshot",
116
+ "state",
117
+ "switch",
118
+ "close-tab",
119
+ "keys",
120
+ "select",
121
+ "hover",
122
+ "dblclick",
123
+ "rightclick",
124
+ "cookies",
125
+ "close",
126
+ "sessions",
127
+ }
128
+ )
129
+ FORBIDDEN_COMMANDS = frozenset(
130
+ {
131
+ "install",
132
+ "init",
133
+ "setup",
134
+ "doctor",
135
+ "upload",
136
+ "eval",
137
+ "extract",
138
+ "get",
139
+ "python",
140
+ "tunnel",
141
+ "cloud",
142
+ "profile",
143
+ "wait",
144
+ }
145
+ )
146
+ FORBIDDEN_GLOBAL_OPTIONS = frozenset(
147
+ {"--headed", "--profile", "--cdp-url", "--connect", "--mcp", "--template"}
148
+ )
149
+
150
+
151
+ class CommandRejected(ValueError):
152
+ """Raised when an Agent command crosses the browser-only boundary."""
153
+
154
+
155
+ def _origin(value: str) -> tuple[str, str, int]:
156
+ parsed = urllib.parse.urlsplit(value)
157
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
158
+ raise ValueError(f"invalid browser origin: {value!r}")
159
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
160
+ return parsed.scheme, parsed.hostname.lower(), port
161
+
162
+
163
+ def allowed_origins() -> frozenset[tuple[str, str, int]]:
164
+ values = (
165
+ os.environ.get(
166
+ "WEBSITEBENCH_BROWSER_REFERENCE_URL", "https://reference:8080"
167
+ ),
168
+ os.environ.get(
169
+ "WEBSITEBENCH_BROWSER_CANDIDATE_URL", "http://candidate:3000"
170
+ ),
171
+ os.environ.get(
172
+ "WEBSITEBENCH_BROWSER_MAILBOX_URL", "http://mailbox:8026"
173
+ ),
174
+ )
175
+ return frozenset(_origin(value) for value in values)
176
+
177
+
178
+ def reference_origin() -> tuple[str, str, int]:
179
+ return _origin(
180
+ os.environ.get("WEBSITEBENCH_BROWSER_REFERENCE_URL", "https://reference:8080")
181
+ )
182
+
183
+
184
+ def _reference_asset_url(value: str) -> str:
185
+ try:
186
+ requested = _origin(value)
187
+ except (TypeError, ValueError) as exc:
188
+ raise CommandRejected(str(exc)) from exc
189
+ if requested != reference_origin():
190
+ raise CommandRejected("static assets can only be saved from the reference origin")
191
+ parsed = urllib.parse.urlsplit(value)
192
+ if parsed.username is not None or parsed.password is not None:
193
+ raise CommandRejected("asset URL must not carry credentials")
194
+ return urllib.parse.urlunsplit(parsed._replace(fragment=""))
195
+
196
+
197
+ def is_reference_code(url: str, content_type: str = "") -> bool:
198
+ media = content_type.split(";", 1)[0].strip().lower()
199
+ suffix = Path(urllib.parse.urlsplit(url).path).suffix.lower()
200
+ return media in CODE_CONTENT_TYPES or suffix in CODE_EXTENSIONS
201
+
202
+
203
+ def is_static_asset(url: str, content_type: str) -> bool:
204
+ if is_reference_code(url, content_type):
205
+ return False
206
+ media = content_type.split(";", 1)[0].strip().lower()
207
+ if media.startswith(STATIC_CONTENT_PREFIXES) or media in STATIC_CONTENT_TYPES:
208
+ return True
209
+ suffix = Path(urllib.parse.urlsplit(url).path).suffix.lower()
210
+ return media in {"application/octet-stream", "binary/octet-stream", ""} and suffix in STATIC_EXTENSIONS
211
+
212
+
213
+ def _parse_global_options(arguments: list[str]) -> tuple[str, int]:
214
+ session = "default"
215
+ index = 0
216
+ while index < len(arguments):
217
+ value = arguments[index]
218
+ if value == "--session":
219
+ if index + 1 >= len(arguments):
220
+ raise CommandRejected("--session requires a value")
221
+ session = arguments[index + 1]
222
+ index += 2
223
+ continue
224
+ if value.startswith("--session="):
225
+ session = value.partition("=")[2]
226
+ index += 1
227
+ continue
228
+ if value == "--json":
229
+ index += 1
230
+ continue
231
+ if value in {"-h", "--help"}:
232
+ break
233
+ if value in FORBIDDEN_GLOBAL_OPTIONS or any(
234
+ value.startswith(option + "=") for option in FORBIDDEN_GLOBAL_OPTIONS
235
+ ):
236
+ raise CommandRejected(f"Browser Use option {value!r} is disabled")
237
+ if value.startswith("-"):
238
+ raise CommandRejected(f"unsupported Browser Use option {value!r}")
239
+ break
240
+ if not SESSION_PATTERN.fullmatch(session):
241
+ raise CommandRejected("invalid Browser Use session name")
242
+ return session, index
243
+
244
+
245
+ def validate_command(raw_arguments: Any) -> list[str]:
246
+ if not isinstance(raw_arguments, list) or not raw_arguments:
247
+ raise CommandRejected("argv must be a non-empty string array")
248
+ if len(raw_arguments) > 128:
249
+ raise CommandRejected("too many Browser Use arguments")
250
+ arguments: list[str] = []
251
+ for value in raw_arguments:
252
+ if not isinstance(value, str) or "\x00" in value or len(value) > 16_384:
253
+ raise CommandRejected("invalid Browser Use argument")
254
+ arguments.append(value)
255
+
256
+ for value in arguments:
257
+ if value in FORBIDDEN_GLOBAL_OPTIONS or any(
258
+ value.startswith(option + "=") for option in FORBIDDEN_GLOBAL_OPTIONS
259
+ ):
260
+ raise CommandRejected(f"Browser Use option {value!r} is disabled")
261
+
262
+ _session, command_index = _parse_global_options(arguments)
263
+ if (
264
+ command_index == len(arguments) - 1
265
+ and arguments[command_index] in {"-h", "--help"}
266
+ ):
267
+ return arguments
268
+ if command_index >= len(arguments):
269
+ raise CommandRejected("missing Browser Use command")
270
+ command = arguments[command_index]
271
+ if command == "assets":
272
+ if len(arguments) != command_index + 1:
273
+ raise CommandRejected("assets takes no arguments; it lists the current page")
274
+ return arguments
275
+ if command == "save-asset":
276
+ tail = arguments[command_index + 1 :]
277
+ if len(tail) != 2:
278
+ raise CommandRejected("save-asset requires a reference asset URL and a destination path")
279
+ url = _reference_asset_url(tail[0])
280
+ if is_reference_code(url):
281
+ raise CommandRejected("reference stylesheets and scripts are not available to the agent")
282
+ destination = Path(tail[1]).resolve()
283
+ if destination.parent != SHARED_ROOT or ASSET_SHARED_NAME.fullmatch(destination.name) is None:
284
+ raise CommandRejected("saved assets must use one gateway-owned path")
285
+ return arguments[: command_index + 1] + [url, str(destination)]
286
+ if command in FORBIDDEN_COMMANDS:
287
+ raise CommandRejected(
288
+ f"Browser Use command {command!r} is disabled for browser-only references"
289
+ )
290
+ if command not in SAFE_COMMANDS:
291
+ raise CommandRejected(f"unsupported Browser Use command {command!r}")
292
+
293
+ if command == "open":
294
+ urls = [
295
+ value
296
+ for value in arguments[command_index + 1 :]
297
+ if "://" in value
298
+ ]
299
+ if len(urls) != 1:
300
+ raise CommandRejected("open requires exactly one absolute URL")
301
+ try:
302
+ requested_origin = _origin(urls[0])
303
+ except (TypeError, ValueError) as exc:
304
+ raise CommandRejected(str(exc)) from exc
305
+ if requested_origin not in allowed_origins():
306
+ raise CommandRejected("browser navigation target is outside task origins")
307
+
308
+ if command == "screenshot":
309
+ # The bundled Browser Use CLI is `screenshot [--full] [path]`; accept the spellings
310
+ # agents reach for (`--full-page`, `--path X`, `--path=X`) and hand the CLI its own.
311
+ path_values: list[str] = []
312
+ options: list[str] = []
313
+ tail = arguments[command_index + 1 :]
314
+ index = 0
315
+ while index < len(tail):
316
+ value = tail[index]
317
+ if value == "--path":
318
+ if index + 1 >= len(tail):
319
+ raise CommandRejected("screenshot --path requires a value")
320
+ path_values.append(tail[index + 1])
321
+ index += 2
322
+ continue
323
+ if value.startswith("--path="):
324
+ path_values.append(value.partition("=")[2])
325
+ index += 1
326
+ continue
327
+ if value in {"--full", "--full-page"}:
328
+ if "--full" not in options:
329
+ options.append("--full")
330
+ index += 1
331
+ continue
332
+ if value in {"--json", "-h", "--help"}:
333
+ options.append(value)
334
+ index += 1
335
+ continue
336
+ if value.startswith("-"):
337
+ raise CommandRejected(f"unsupported screenshot option {value!r}")
338
+ path_values.append(value)
339
+ index += 1
340
+ paths = [Path(value).resolve() for value in path_values]
341
+ if (
342
+ len(paths) != 1
343
+ or paths[0].parent != SHARED_ROOT
344
+ or re.fullmatch(r"screenshot-[0-9a-f]{32}\.png", paths[0].name) is None
345
+ ):
346
+ raise CommandRejected("screenshots must use one gateway-owned PNG path")
347
+ return arguments[: command_index + 1] + options + [str(paths[0])]
348
+
349
+ return arguments
350
+
351
+
352
+ _COMMAND_LOCK = threading.Lock()
353
+
354
+
355
+ def execute(arguments: list[str]) -> dict[str, Any]:
356
+ with _COMMAND_LOCK:
357
+ try:
358
+ completed = subprocess.run(
359
+ [REAL_BROWSER_USE, *arguments],
360
+ stdin=subprocess.DEVNULL,
361
+ stdout=subprocess.PIPE,
362
+ stderr=subprocess.PIPE,
363
+ timeout=COMMAND_TIMEOUT_SEC,
364
+ check=False,
365
+ )
366
+ except subprocess.TimeoutExpired as exc:
367
+ raise CommandRejected("Browser Use command exceeded 180 seconds") from exc
368
+ except OSError as exc:
369
+ raise CommandRejected(f"Browser Use runtime unavailable: {exc}") from exc
370
+ stdout = completed.stdout[:MAX_OUTPUT_BYTES]
371
+ stderr = completed.stderr[:MAX_OUTPUT_BYTES]
372
+ if len(completed.stdout) > MAX_OUTPUT_BYTES or len(completed.stderr) > MAX_OUTPUT_BYTES:
373
+ raise CommandRejected("Browser Use output exceeded the interactive limit")
374
+ return {
375
+ "exit_code": completed.returncode,
376
+ "stdout": stdout.decode("utf-8", errors="replace"),
377
+ "stderr": stderr.decode("utf-8", errors="replace"),
378
+ }
379
+
380
+
381
+ GATEWAY_HELP = """
382
+ WebsiteBench gateway commands:
383
+ assets List the reference-origin images, icons, fonts and media that the
384
+ current page references or loaded.
385
+ save-asset URL PATH Save one of those assets to PATH (for example under /app/repo).
386
+ Stylesheets, scripts, HTML documents, JSON and other API responses are refused.
387
+ """
388
+
389
+
390
+ def _find_result(value: Any) -> Any:
391
+ if isinstance(value, dict):
392
+ if "result" in value:
393
+ return value["result"]
394
+ for nested in value.values():
395
+ found = _find_result(nested)
396
+ if found is not None:
397
+ return found
398
+ return None
399
+
400
+
401
+ def list_assets(arguments: list[str], command_index: int) -> dict[str, Any]:
402
+ inventory = execute(arguments[:command_index] + ["--json", "eval", ASSET_INVENTORY_JS])
403
+ if inventory["exit_code"] != 0:
404
+ return {"exit_code": inventory["exit_code"], "stdout": "", "stderr": "could not list assets: " + inventory["stderr"][-400:]}
405
+ try:
406
+ urls = json.loads(_find_result(json.loads(inventory["stdout"])) or "[]")
407
+ except (TypeError, ValueError):
408
+ return {"exit_code": 1, "stdout": "", "stderr": "could not list assets: no page is open"}
409
+ origin = reference_origin()
410
+ assets = []
411
+ for url in urls if isinstance(urls, list) else []:
412
+ try:
413
+ if not isinstance(url, str) or _origin(url) != origin:
414
+ continue
415
+ except ValueError:
416
+ continue
417
+ path = urllib.parse.urlsplit(url).path
418
+ if is_reference_code(url):
419
+ continue
420
+ if Path(path).suffix.lower() in STATIC_EXTENSIONS or "/static/" in path or "/assets/" in path:
421
+ assets.append(urllib.parse.urlunsplit(urllib.parse.urlsplit(url)._replace(fragment="")))
422
+ assets = sorted(set(assets))[:ASSET_LIST_LIMIT]
423
+ text = "\n".join(assets) + ("\n" if assets else "no reference static assets found on the current page\n")
424
+ return {"exit_code": 0, "stdout": text, "stderr": ""}
425
+
426
+
427
+ class _SameOriginRedirect(urllib.request.HTTPRedirectHandler):
428
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[override]
429
+ _reference_asset_url(urllib.parse.urljoin(req.full_url, newurl))
430
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
431
+
432
+
433
+ def save_asset(url: str, destination: Path) -> dict[str, Any]:
434
+ opener = urllib.request.build_opener(
435
+ urllib.request.HTTPSHandler(context=ssl.create_default_context()), _SameOriginRedirect()
436
+ )
437
+ request = urllib.request.Request(url, headers={"User-Agent": "WebsiteBenchAssetGateway/1", "Accept": "*/*"})
438
+ try:
439
+ with opener.open(request, timeout=ASSET_TIMEOUT_SEC) as response:
440
+ content_type = response.headers.get("Content-Type", "")
441
+ final_url = response.geturl()
442
+ if is_reference_code(final_url, content_type):
443
+ raise CommandRejected(f"refused stylesheet or script ({content_type or 'no content type'}): reference CSS and JavaScript are not available to the agent")
444
+ if not is_static_asset(final_url, content_type):
445
+ raise CommandRejected(f"refused non-static response ({content_type or 'no content type'})")
446
+ body = response.read(ASSET_MAX_BYTES + 1)
447
+ except urllib.error.HTTPError as exc:
448
+ raise CommandRejected(f"reference returned HTTP {exc.code} for {url}") from exc
449
+ except (urllib.error.URLError, OSError) as exc:
450
+ raise CommandRejected(f"asset download failed: {exc}") from exc
451
+ if len(body) > ASSET_MAX_BYTES:
452
+ raise CommandRejected("asset exceeds the 32 MiB limit")
453
+ temporary = destination.with_name(destination.name + ".partial")
454
+ temporary.write_bytes(body)
455
+ os.replace(temporary, destination)
456
+ return {
457
+ "exit_code": 0,
458
+ "stdout": f"saved {url} -> {destination} ({len(body)} bytes, {content_type.split(';', 1)[0].strip() or 'unknown type'})\n",
459
+ "stderr": "",
460
+ }
461
+
462
+
463
+ def run(arguments: list[str]) -> dict[str, Any]:
464
+ _session, command_index = _parse_global_options(arguments)
465
+ command = arguments[command_index] if command_index < len(arguments) else None
466
+ if command == "assets":
467
+ return list_assets(arguments, command_index)
468
+ if command == "save-asset":
469
+ return save_asset(arguments[command_index + 1], Path(arguments[command_index + 2]))
470
+ result = execute(arguments)
471
+ if command in {None, "-h", "--help"}:
472
+ result["stdout"] = result["stdout"] + GATEWAY_HELP
473
+ return result
474
+
475
+
476
+ class Handler(BaseHTTPRequestHandler):
477
+ server_version = "WebsiteBenchBrowserGateway/1"
478
+
479
+ def log_message(self, _format: str, *_arguments: object) -> None:
480
+ return
481
+
482
+ def _send(self, status: int, value: dict[str, Any]) -> None:
483
+ body = json.dumps(value, separators=(",", ":")).encode("utf-8")
484
+ self.send_response(status)
485
+ self.send_header("Content-Type", "application/json")
486
+ self.send_header("Content-Length", str(len(body)))
487
+ self.send_header("Cache-Control", "no-store")
488
+ self.end_headers()
489
+ self.wfile.write(body)
490
+
491
+ def do_GET(self) -> None:
492
+ if self.path == "/healthz":
493
+ self._send(200, {"status": "ok"})
494
+ else:
495
+ self._send(404, {"error": "not_found"})
496
+
497
+ def do_POST(self) -> None:
498
+ if self.path != "/v1/command":
499
+ self._send(404, {"error": "not_found"})
500
+ return
501
+ try:
502
+ length = int(self.headers.get("Content-Length", ""))
503
+ if length <= 0 or length > MAX_REQUEST_BYTES:
504
+ raise CommandRejected("invalid request size")
505
+ payload = json.loads(self.rfile.read(length))
506
+ if not isinstance(payload, dict) or set(payload) != {"argv"}:
507
+ raise CommandRejected("request must contain only argv")
508
+ result = run(validate_command(payload["argv"]))
509
+ except (CommandRejected, json.JSONDecodeError, UnicodeError, ValueError) as exc:
510
+ self._send(400, {"error": str(exc)})
511
+ return
512
+ self._send(200, result)
513
+
514
+
515
+ def main() -> None:
516
+ bind = os.environ.get("WEBSITEBENCH_BROWSER_GATEWAY_BIND", "0.0.0.0")
517
+ port = int(os.environ.get("WEBSITEBENCH_BROWSER_GATEWAY_PORT", "9224"))
518
+ server = ThreadingHTTPServer((bind, port), Handler)
519
+ server.daemon_threads = True
520
+ server.serve_forever()
521
+
522
+
523
+ if __name__ == "__main__":
524
+ main()
tasks/fandango/environment/candidate-abi/websitebench-candidate-preflight ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ PYTHONPATH=/opt/websitebench/candidate-abi
4
+ export PYTHONPATH
5
+ exec python3 -m websitebench.harbor.candidate_preflight "$@"
tasks/fandango/environment/mailbox/Dockerfile ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ FROM python:3.12.11-slim-bookworm@sha256:519591d6871b7bc437060736b9f7456b8731f1499a57e22e6c285135ae657bf7
2
+ WORKDIR /srv/mailbox
3
+ COPY mailbox.py .
4
+ HEALTHCHECK --interval=2s --timeout=2s --retries=30 CMD python -c "import os,urllib.request as r;a=os.environ.get('WEBSITEBENCH_MAILBOX_API_BIND') or '127.0.0.1';i=os.environ.get('WEBSITEBENCH_MAILBOX_INBOX_BIND') or '127.0.0.1';r.urlopen(f'http://{a}:8025/healthz',timeout=1);r.urlopen(f'http://{i}:8026/healthz',timeout=1)"
5
+ CMD ["python", "mailbox.py", "--smtp-port", "1025", "--http-port", "8025", "--inbox-port", "8026"]
tasks/fandango/environment/mailbox/mailbox.py ADDED
@@ -0,0 +1,2433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local-only mail writers plus Inbox HTTP sidecar for deterministic tasks.
2
+
3
+ The sidecar serves two disjoint listeners so the agent and the evaluator never
4
+ share a surface:
5
+
6
+ ``api``
7
+ The Bearer-gated JSON API plus ``/internal/bootstrap``. The reference site
8
+ and the evaluator reach it; it is where every capability lives.
9
+ ``inbox``
10
+ An HTML-only inbox for exactly one namespace, reachable without a
11
+ credential because a browser has none to present. It exposes no JSON, no
12
+ capability, and no way to name a second namespace.
13
+
14
+ Formal candidates receive a separate per-case write listener. Its primary
15
+ surface is a text-only Resend-style ``POST /emails`` API; legacy SMTP and the
16
+ ``websitebench.site_backend`` bootstrap remain compatibility writers. None of
17
+ those surfaces exposes an inbox or a JSON read route.
18
+
19
+ This module is copied *alone* into the mailbox container build context, so it
20
+ must stay self-contained: no imports outside the standard library.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import email
26
+ import hashlib
27
+ import hmac
28
+ import html
29
+ import http.client
30
+ import json
31
+ import os
32
+ import re
33
+ import secrets
34
+ import shutil
35
+ import socket
36
+ import socketserver
37
+ import signal
38
+ import subprocess
39
+ import sys
40
+ import tempfile
41
+ import threading
42
+ import time
43
+ import urllib.parse
44
+ from collections.abc import Mapping
45
+ from dataclasses import dataclass, field, replace
46
+ from email.message import EmailMessage
47
+ from email.policy import default
48
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
49
+ from typing import Any
50
+
51
+
52
+ _NAMESPACE = re.compile(r"^[a-zA-Z0-9._-]{1,160}$")
53
+ _OTP = re.compile(r"(?<!\d)(\d{4,8})(?!\d)")
54
+ _MAX_MESSAGE_BYTES = 1024 * 1024
55
+ _MAX_MESSAGES_PER_NAMESPACE = 32
56
+ _MAX_STORED_BYTES_PER_NAMESPACE = 2 * 1024 * 1024
57
+ _MAX_RECIPIENTS = 16
58
+ _MAX_COMMANDS_PER_CONNECTION = 256
59
+ _CONNECTION_TIMEOUT_SECONDS = 10
60
+ _MAX_CONNECTION_LIFETIME_SECONDS = 30
61
+ _MAX_CONCURRENT_CONNECTIONS = 16
62
+ MAILPIT_IMAGE = (
63
+ "ghcr.io/axllent/mailpit:v1.30.6@"
64
+ "sha256:7f33095f80e901f6ad08028f06ca284aa58fe84942be5496008d041d3b9f4d4d"
65
+ )
66
+ #: The one variable that names the Mailpit a trial or capture must use. It is
67
+ #: read in exactly one place, :meth:`MailPlane.from_environment`.
68
+ MAILPIT_HTTP_SOCKET_ENV = "WEBSITEBENCH_MAILPIT_HTTP_SOCKET"
69
+ #: Where Mailpit's private sockets live inside the compose sidecar. A value
70
+ #: mentioning this path in a candidate environment is an evaluator-side leak.
71
+ MAILPIT_RUNTIME_DIR = "/run/websitebench-mailpit"
72
+ #: The envelope sender every benchmark mail writer presents. Some captured
73
+ #: runtimes pin this exact suffix before opening SMTP, so paired capture and a
74
+ #: scored candidate trial must agree on it to the byte.
75
+ CANDIDATE_MAIL_SENDER = "no-reply@candidate.websitebench.local"
76
+ #: The complete optional mail ABI a candidate runtime may be handed. Nothing
77
+ #: outside this set ever reaches a candidate process.
78
+ CANDIDATE_MAIL_ENVIRONMENT = frozenset(
79
+ {
80
+ "WEBSITEBENCH_MAIL_API_URL",
81
+ "WEBSITEBENCH_MAIL_API_TOKEN",
82
+ "WEBSITEBENCH_MAIL_FROM",
83
+ "WEBSITEBENCH_SMTP_HOST",
84
+ "WEBSITEBENCH_SMTP_PORT",
85
+ "WEBSITEBENCH_SMTP_FROM",
86
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL",
87
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN",
88
+ }
89
+ )
90
+ #: Every mail variable an authoring capture exports into its own process, so
91
+ #: capture can save and restore exactly this set around a shard.
92
+ AUTHORING_MAIL_ENVIRONMENT = (
93
+ "WEBSITEBENCH_MAIL_API_URL",
94
+ "WEBSITEBENCH_MAIL_API_TOKEN",
95
+ "WEBSITEBENCH_MAIL_FROM",
96
+ "WEBSITEBENCH_SMTP_FROM",
97
+ "WEBSITEBENCH_MAILBOX_URL",
98
+ "WEBSITEBENCH_MAILBOX_ALLOWLIST",
99
+ "WEBSITEBENCH_MAILBOX_NAMESPACE",
100
+ "WEBSITEBENCH_SMTP_HOST",
101
+ "WEBSITEBENCH_SMTP_PORT",
102
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL",
103
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN",
104
+ "WEBSITEBENCH_MAILBOX_CREDENTIAL",
105
+ )
106
+ _LOG_SECRET = re.compile(
107
+ r"(?i)(?:bearer\s+[^\s\"']+|"
108
+ r"(?:authorization|cookie|credential|password|secret|token|otp|"
109
+ r"verification[-_ ]?code|card[-_ ]?number)\s*[:=]\s*"
110
+ r"(?:bearer\s+)?[^\s,;]+)"
111
+ )
112
+
113
+
114
+ class MailpitInfrastructureError(RuntimeError):
115
+ """Mailpit is missing or unhealthy, as distinct from rejected candidate mail."""
116
+
117
+
118
+ class MailInfrastructureUnavailable(MailpitInfrastructureError):
119
+ """No Mailpit is configured for this process, or the configured one is down."""
120
+
121
+
122
+ class MailboxCapacityError(RuntimeError):
123
+ """A namespace exhausted its fixed message or submitted-byte quota."""
124
+
125
+
126
+ class _UnixHTTPConnection(http.client.HTTPConnection):
127
+ """A minimal HTTP/1.1 connection transported over one Unix socket."""
128
+
129
+ def __init__(self, socket_path: str, timeout: float) -> None:
130
+ super().__init__("localhost", timeout=timeout)
131
+ self._socket_path = socket_path
132
+
133
+ def connect(self) -> None:
134
+ connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
135
+ connection.settimeout(self.timeout)
136
+ connection.connect(self._socket_path)
137
+ self.sock = connection
138
+
139
+
140
+ class MailpitClient:
141
+ """Trusted Mailpit client: HTTP UDS reads and sibling SMTP UDS writes.
142
+
143
+ This is intentionally not a general Mailpit client. It never exposes the
144
+ UI, delete, release, tag-mutation, or remote-content endpoints. All
145
+ candidate-authored control headers are discarded and the SMTP writer adds
146
+ exactly one trusted tag.
147
+ """
148
+
149
+ _MAX_RESPONSE_BYTES = 8 * 1024 * 1024
150
+
151
+ def __init__(
152
+ self,
153
+ socket_path: str | os.PathLike[str],
154
+ *,
155
+ smtp_socket_path: str | os.PathLike[str] | None = None,
156
+ timeout: float = 5.0,
157
+ ) -> None:
158
+ self.socket_path = os.fspath(socket_path)
159
+ if not self.socket_path:
160
+ raise ValueError("Mailpit HTTP socket path must not be empty")
161
+ if timeout <= 0:
162
+ raise ValueError("Mailpit timeout must be positive")
163
+ self.smtp_socket_path = (
164
+ os.fspath(smtp_socket_path)
165
+ if smtp_socket_path is not None
166
+ else os.path.join(os.path.dirname(self.socket_path), "smtp.sock")
167
+ )
168
+ self.timeout = float(timeout)
169
+
170
+ def _request(
171
+ self, method: str, path: str, body: dict[str, Any] | None = None
172
+ ) -> tuple[int, bytes]:
173
+ encoded = None if body is None else json.dumps(body).encode("utf-8")
174
+ headers = {"Accept": "application/json", "Connection": "close"}
175
+ if encoded is not None:
176
+ headers["Content-Type"] = "application/json"
177
+ headers["Content-Length"] = str(len(encoded))
178
+ connection = _UnixHTTPConnection(self.socket_path, self.timeout)
179
+ try:
180
+ connection.request(method, path, body=encoded, headers=headers)
181
+ response = connection.getresponse()
182
+ length = response.getheader("Content-Length")
183
+ if length is not None and int(length) > self._MAX_RESPONSE_BYTES:
184
+ raise MailpitInfrastructureError("Mailpit response exceeded limit")
185
+ value = response.read(self._MAX_RESPONSE_BYTES + 1)
186
+ if len(value) > self._MAX_RESPONSE_BYTES:
187
+ raise MailpitInfrastructureError("Mailpit response exceeded limit")
188
+ return int(response.status), value
189
+ except (OSError, TimeoutError, http.client.HTTPException, ValueError) as error:
190
+ raise MailpitInfrastructureError(
191
+ f"Mailpit request failed: {redact_text(str(error))}"
192
+ ) from error
193
+ finally:
194
+ connection.close()
195
+
196
+ def _json(
197
+ self, method: str, path: str, body: dict[str, Any] | None = None
198
+ ) -> dict[str, Any]:
199
+ status, raw = self._request(method, path, body)
200
+ if not 200 <= status < 300:
201
+ raise MailpitInfrastructureError(f"Mailpit API returned HTTP {status}")
202
+ try:
203
+ value = json.loads(raw)
204
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
205
+ raise MailpitInfrastructureError("Mailpit returned invalid JSON") from error
206
+ if not isinstance(value, dict):
207
+ raise MailpitInfrastructureError("Mailpit returned an invalid response")
208
+ return value
209
+
210
+ def ready(self) -> bool:
211
+ """Return whether Mailpit's built-in readiness endpoint is healthy."""
212
+
213
+ try:
214
+ status, _body = self._request("GET", "/readyz")
215
+ except MailpitInfrastructureError:
216
+ return False
217
+ return status == 200
218
+
219
+ def send(
220
+ self,
221
+ raw: bytes,
222
+ envelope_from: str,
223
+ recipients: list[str],
224
+ *,
225
+ tag: str,
226
+ ) -> str:
227
+ """Store mail with one trusted tag, ignoring all untrusted X-headers."""
228
+
229
+ if any(
230
+ "\r" in value or "\n" in value for value in [envelope_from, *recipients]
231
+ ):
232
+ raise ValueError("invalid SMTP envelope")
233
+ message = email.message_from_bytes(raw, policy=default)
234
+ for part in message.walk():
235
+ for header in list(part.keys()):
236
+ lowered = header.lower()
237
+ if lowered == "x-tags" or lowered.startswith("x-websitebench-"):
238
+ del part[header]
239
+ for header in ("From", "To", "Cc", "Bcc"):
240
+ if message.get(header) is not None:
241
+ del message[header]
242
+ message["From"] = envelope_from
243
+ message["To"] = ", ".join(recipients)
244
+ message["X-Tags"] = tag
245
+ wire = message.as_bytes(policy=default.clone(linesep="\r\n"))
246
+
247
+ connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
248
+ connection.settimeout(self.timeout)
249
+ stream = None
250
+ try:
251
+ connection.connect(self.smtp_socket_path)
252
+ stream = connection.makefile("rb")
253
+
254
+ def response() -> tuple[int, str]:
255
+ lines: list[str] = []
256
+ while True:
257
+ line = stream.readline(65537)
258
+ if not line or len(line) > 65536:
259
+ raise MailpitInfrastructureError(
260
+ "invalid Mailpit SMTP response"
261
+ )
262
+ decoded = line.decode("utf-8", "replace").rstrip("\r\n")
263
+ lines.append(decoded)
264
+ if len(decoded) < 4 or decoded[3:4] != "-":
265
+ break
266
+ try:
267
+ return int(lines[-1][:3]), "\n".join(lines)
268
+ except ValueError as error:
269
+ raise MailpitInfrastructureError(
270
+ "invalid Mailpit SMTP status"
271
+ ) from error
272
+
273
+ def command(value: bytes, expected: set[int]) -> str:
274
+ connection.sendall(value + b"\r\n")
275
+ status, reply = response()
276
+ if status not in expected:
277
+ raise MailpitInfrastructureError(
278
+ f"Mailpit SMTP returned status {status}: "
279
+ f"{redact_text(reply)[:200]}"
280
+ )
281
+ return reply
282
+
283
+ status, _greeting = response()
284
+ if status != 220:
285
+ raise MailpitInfrastructureError(
286
+ "Mailpit SMTP did not greet the gateway"
287
+ )
288
+ command(b"EHLO websitebench.local", {250})
289
+ command(f"MAIL FROM:<{envelope_from}>".encode("utf-8"), {250})
290
+ for recipient in recipients:
291
+ command(f"RCPT TO:<{recipient}>".encode("utf-8"), {250})
292
+ command(b"DATA", {354})
293
+ stuffed = b"\r\n".join(
294
+ (b"." + line if line.startswith(b".") else line)
295
+ for line in wire.split(b"\r\n")
296
+ )
297
+ connection.sendall(stuffed + b"\r\n.\r\n")
298
+ status, reply = response()
299
+ if status != 250:
300
+ raise MailpitInfrastructureError(
301
+ f"Mailpit SMTP returned status {status}: {redact_text(reply)[:200]}"
302
+ )
303
+ match = re.search(r"queued as ([A-Za-z0-9_-]+)", reply)
304
+ return match.group(1) if match else hashlib.sha256(wire).hexdigest()[:24]
305
+ except (OSError, TimeoutError) as error:
306
+ raise MailpitInfrastructureError("Mailpit SMTP request failed") from error
307
+ finally:
308
+ if stream is not None:
309
+ stream.close()
310
+ connection.close()
311
+
312
+ @staticmethod
313
+ def _addresses(value: Any) -> list[str]:
314
+ if not isinstance(value, list):
315
+ return []
316
+ return [
317
+ str(item.get("Address", item.get("Email")))
318
+ for item in value
319
+ if isinstance(item, dict)
320
+ and isinstance(item.get("Address", item.get("Email")), str)
321
+ ]
322
+
323
+ def messages(self, *, tag: str, recipient: str) -> list[dict[str, Any]]:
324
+ """Read only exact-tag, exact-recipient messages, oldest first."""
325
+
326
+ query = urllib.parse.urlencode(
327
+ {"query": f"tag:{tag}", "start": "0", "limit": "512"}
328
+ )
329
+ listing = self._json("GET", f"/api/v1/search?{query}")
330
+ summaries = listing.get("messages", [])
331
+ if not isinstance(summaries, list):
332
+ raise MailpitInfrastructureError(
333
+ "Mailpit returned invalid message summaries"
334
+ )
335
+ values: list[dict[str, Any]] = []
336
+ for summary in reversed(summaries):
337
+ if not isinstance(summary, dict):
338
+ continue
339
+ tags = summary.get("Tags", [])
340
+ all_recipients = (
341
+ self._addresses(summary.get("To"))
342
+ + self._addresses(summary.get("Cc"))
343
+ + self._addresses(summary.get("Bcc"))
344
+ )
345
+ identifier = summary.get("ID")
346
+ if (
347
+ tag not in tags
348
+ or recipient not in all_recipients
349
+ or not isinstance(identifier, str)
350
+ ):
351
+ continue
352
+ detail = self._json(
353
+ "GET", "/api/v1/message/" + urllib.parse.quote(identifier, safe="")
354
+ )
355
+ # Recheck authorization against the detailed record. Search is an
356
+ # index, never an authorization decision.
357
+ detail_tags = detail.get("Tags", [])
358
+ detailed_recipients = (
359
+ self._addresses(detail.get("To"))
360
+ + self._addresses(detail.get("Cc"))
361
+ + self._addresses(detail.get("Bcc"))
362
+ )
363
+ if tag not in detail_tags or recipient not in detailed_recipients:
364
+ continue
365
+ sender = detail.get("From", {})
366
+ attachments = detail.get("Attachments", [])
367
+ inline = detail.get("Inline", [])
368
+ metadata = [
369
+ *(attachments if isinstance(attachments, list) else []),
370
+ *(inline if isinstance(inline, list) else []),
371
+ ]
372
+ values.append(
373
+ {
374
+ "mailpit_id": identifier,
375
+ "envelope_from": str(sender.get("Address", sender.get("Email", "")))
376
+ if isinstance(sender, dict)
377
+ else "",
378
+ "recipients": detailed_recipients,
379
+ "subject": str(detail.get("Subject", "")),
380
+ "text": str(detail.get("Text", "")),
381
+ "attachments": metadata,
382
+ "stored_bytes": int(detail.get("Size", 0)),
383
+ }
384
+ )
385
+ for index, item in enumerate(values, 1):
386
+ item["id"] = index
387
+ match = _OTP.search(str(item["text"]))
388
+ item["otp"] = match.group(1) if match else None
389
+ return values
390
+
391
+
392
+ @dataclass
393
+ class MailAccount:
394
+ """Internal ``websitebench.mail-account.v1`` logical account."""
395
+
396
+ account_id: str
397
+ tag: str
398
+ address: str
399
+ role: str
400
+ allowed_from: set[str]
401
+ allowed_to: set[str]
402
+ send_capability: str = field(repr=False)
403
+ read_capability: str = field(repr=False)
404
+ state: str = "active"
405
+ schema: str = field(default="websitebench.mail-account.v1", init=False)
406
+
407
+
408
+ class MailAccountBroker:
409
+ """Authorize logical accounts before calling the untrusted storage engine."""
410
+
411
+ _SEND_ROLES = frozenset(
412
+ {
413
+ "reference-backend",
414
+ "formal-candidate",
415
+ "capture-writer",
416
+ "gateway",
417
+ "selfhost-pair",
418
+ "formal-pair",
419
+ "capture-pair",
420
+ }
421
+ )
422
+ _READ_ROLES = frozenset(
423
+ {
424
+ "agent",
425
+ "formal-verifier",
426
+ "capture-reader",
427
+ "gateway",
428
+ "selfhost-pair",
429
+ "formal-pair",
430
+ "capture-pair",
431
+ }
432
+ )
433
+ _ROLES = _SEND_ROLES | _READ_ROLES
434
+
435
+ def __init__(self, client: MailpitClient) -> None:
436
+ self.client = client
437
+ self._accounts: dict[str, MailAccount] = {}
438
+ self._lock = threading.Lock()
439
+
440
+ def create_account(
441
+ self,
442
+ *,
443
+ address: str,
444
+ role: str,
445
+ allowed_from: Any = (),
446
+ allowed_to: Any = (),
447
+ ) -> MailAccount:
448
+ if address and ("@" not in address or "\r" in address or "\n" in address):
449
+ raise ValueError("invalid mail account address")
450
+ if role not in self._ROLES:
451
+ raise ValueError("invalid mail account role")
452
+ account = MailAccount(
453
+ account_id="acct_" + secrets.token_hex(24),
454
+ tag="wb-" + secrets.token_hex(24),
455
+ address=address,
456
+ role=role,
457
+ allowed_from=set(allowed_from),
458
+ allowed_to=set(allowed_to) | ({address} if address else set()),
459
+ send_capability="send_" + secrets.token_hex(32),
460
+ read_capability="read_" + secrets.token_hex(32),
461
+ )
462
+ with self._lock:
463
+ self._accounts[account.account_id] = account
464
+ return account
465
+
466
+ def _account(self, account_id: str) -> MailAccount:
467
+ with self._lock:
468
+ account = self._accounts.get(account_id)
469
+ if account is None or account.state == "destroyed":
470
+ raise PermissionError("mail account is unavailable")
471
+ return account
472
+
473
+ def send(
474
+ self,
475
+ account_id: str,
476
+ capability: str,
477
+ raw: bytes,
478
+ envelope_from: str,
479
+ recipients: list[str],
480
+ ) -> str:
481
+ account = self._account(account_id)
482
+ if (
483
+ account.role not in self._SEND_ROLES
484
+ or account.state != "active"
485
+ or not hmac.compare_digest(account.send_capability, capability)
486
+ ):
487
+ raise PermissionError("mail account cannot send")
488
+ if (
489
+ not envelope_from
490
+ or "@" not in envelope_from
491
+ or "\r" in envelope_from
492
+ or "\n" in envelope_from
493
+ or not 1 <= len(recipients) <= _MAX_RECIPIENTS
494
+ or len(raw) > _MAX_MESSAGE_BYTES
495
+ or any(
496
+ not recipient
497
+ or len(recipient) > 320
498
+ or "@" not in recipient
499
+ or "\r" in recipient
500
+ or "\n" in recipient
501
+ for recipient in recipients
502
+ )
503
+ ):
504
+ raise PermissionError("mail envelope is not allowed")
505
+ if account.allowed_from and envelope_from not in account.allowed_from:
506
+ raise PermissionError("mail sender is not allowed")
507
+ learn_recipients = account.role == "gateway" or not account.allowed_to
508
+ if account.role != "gateway" and account.allowed_to and any(
509
+ value not in account.allowed_to for value in recipients
510
+ ):
511
+ raise PermissionError("mail recipient is not allowed")
512
+ provider_id = self.client.send(raw, envelope_from, recipients, tag=account.tag)
513
+ if learn_recipients:
514
+ # A trial can legitimately exercise more than one authentication
515
+ # address. Namespace-scoped gateway accounts therefore learn every
516
+ # address from a Mailpit-accepted envelope; reads remain limited to
517
+ # those exact delivered addresses and still require the capability.
518
+ with self._lock:
519
+ account.allowed_to.update(recipients)
520
+ if not account.address and recipients:
521
+ account.address = recipients[0]
522
+ return provider_id
523
+
524
+ def messages(
525
+ self, account_id: str, capability: str, recipient: str | None = None
526
+ ) -> list[dict[str, Any]]:
527
+ account = self._account(account_id)
528
+ if account.role not in self._READ_ROLES or not hmac.compare_digest(
529
+ account.read_capability, capability
530
+ ):
531
+ raise PermissionError("mail account cannot read")
532
+ with self._lock:
533
+ allowed_to = set(account.allowed_to)
534
+ # SMTP delivery is asynchronous. A verifier can legitimately poll the
535
+ # exact recipient before the writer has learned its first envelope. An
536
+ # empty account therefore means "not delivered yet", not "forbidden".
537
+ # Once the first envelope arrives, the usual exact-recipient boundary
538
+ # applies and a different address is still rejected.
539
+ if recipient is not None and not allowed_to:
540
+ return []
541
+ targets = [recipient] if recipient is not None else sorted(allowed_to)
542
+ if any(target not in allowed_to for target in targets):
543
+ raise PermissionError("mail recipient is not allowed")
544
+ combined: dict[str, dict[str, Any]] = {}
545
+ for target in targets:
546
+ for message in self.client.messages(tag=account.tag, recipient=target):
547
+ combined[str(message["mailpit_id"])] = message
548
+ values = list(combined.values())
549
+ for index, item in enumerate(values, 1):
550
+ item["id"] = index
551
+ return values
552
+
553
+ def seal(self, account_id: str) -> None:
554
+ account = self._account(account_id)
555
+ with self._lock:
556
+ account.state = "sealed"
557
+
558
+ def destroy(self, account_id: str) -> None:
559
+ account = self._account(account_id)
560
+ with self._lock:
561
+ account.state = "destroyed"
562
+
563
+
564
+ class EphemeralMailpit:
565
+ """One pinned, networkless Mailpit container with a private UDS directory."""
566
+
567
+ def __init__(
568
+ self,
569
+ runtime_dir: str | os.PathLike[str] | None = None,
570
+ *,
571
+ docker_binary: str = "docker",
572
+ startup_timeout: float = 45.0,
573
+ ) -> None:
574
+ if startup_timeout <= 0:
575
+ raise ValueError("startup timeout must be positive")
576
+ self._owns_runtime_dir = runtime_dir is None
577
+ self.runtime_dir = (
578
+ tempfile.mkdtemp(prefix="websitebench-mailpit-")
579
+ if runtime_dir is None
580
+ else os.path.abspath(os.fspath(runtime_dir))
581
+ )
582
+ os.makedirs(self.runtime_dir, mode=0o700, exist_ok=True)
583
+ os.chmod(self.runtime_dir, 0o700)
584
+ self.docker_binary = docker_binary
585
+ self.startup_timeout = float(startup_timeout)
586
+ self.container_name = "websitebench-mailpit-" + secrets.token_hex(12)
587
+ self.client = MailpitClient(os.path.join(self.runtime_dir, "http.sock"))
588
+ self._process: subprocess.Popen[bytes] | None = None
589
+
590
+ def _uses_rootless_podman(self) -> bool:
591
+ """Detect the Podman Docker shim that needs the host uid preserved."""
592
+
593
+ try:
594
+ result = subprocess.run(
595
+ [self.docker_binary, "info"],
596
+ stdin=subprocess.DEVNULL,
597
+ stdout=subprocess.PIPE,
598
+ stderr=subprocess.STDOUT,
599
+ text=True,
600
+ timeout=5,
601
+ check=False,
602
+ )
603
+ except (OSError, subprocess.TimeoutExpired):
604
+ return False
605
+ output = result.stdout.casefold()
606
+ return result.returncode == 0 and "podman" in output and "rootless" in output
607
+
608
+ def start(self) -> "EphemeralMailpit":
609
+ if self._process is not None:
610
+ return self
611
+ command = [
612
+ self.docker_binary,
613
+ "run",
614
+ "--rm",
615
+ "--name",
616
+ self.container_name,
617
+ ]
618
+ if self._uses_rootless_podman():
619
+ command.append("--userns=keep-id")
620
+ command.extend(
621
+ [
622
+ "--user",
623
+ f"{os.getuid()}:{os.getgid()}",
624
+ "--network",
625
+ "none",
626
+ "--tmpfs",
627
+ "/tmp:rw,noexec,nosuid,nodev,size=64m",
628
+ "--mount",
629
+ f"type=bind,src={self.runtime_dir},dst=/run/websitebench-mailpit",
630
+ ]
631
+ )
632
+ settings = {
633
+ "MP_UI_BIND_ADDR": "unix:/run/websitebench-mailpit/http.sock:660",
634
+ "MP_SMTP_BIND_ADDR": "unix:/run/websitebench-mailpit/smtp.sock:660",
635
+ "MP_DATABASE": "/tmp/mailpit.db",
636
+ "MP_MAX_MESSAGES": "512",
637
+ "MP_MAX_MESSAGE_SIZE": "1",
638
+ "MP_SMTP_MAX_RECIPIENTS": "16",
639
+ "MP_POP3_BIND_ADDR": "",
640
+ "MP_POP3_AUTH_FILE": "",
641
+ "MP_SMTP_RELAY_CONFIG": "",
642
+ "MP_SMTP_RELAY_ALL": "false",
643
+ "MP_SMTP_FORWARD_CONFIG": "",
644
+ "MP_WEBHOOK_URL": "",
645
+ "MP_ENABLE_CHAOS": "false",
646
+ "MP_ENABLE_PROMETHEUS": "false",
647
+ "MP_DISABLE_VERSION_CHECK": "true",
648
+ "MP_BLOCK_REMOTE_CSS_AND_FONTS": "true",
649
+ "MP_ALLOW_INTERNAL_HTTP_REQUESTS": "false",
650
+ }
651
+ for key, value in settings.items():
652
+ command.extend(("--env", f"{key}={value}"))
653
+ command.append(MAILPIT_IMAGE)
654
+ try:
655
+ self._process = subprocess.Popen(
656
+ command,
657
+ stdin=subprocess.DEVNULL,
658
+ stdout=subprocess.DEVNULL,
659
+ stderr=subprocess.DEVNULL,
660
+ )
661
+ except OSError as error:
662
+ self.close()
663
+ raise MailpitInfrastructureError(
664
+ "Docker is unavailable for Mailpit"
665
+ ) from error
666
+ deadline = time.monotonic() + self.startup_timeout
667
+ while time.monotonic() < deadline:
668
+ if self._process.poll() is not None:
669
+ self.close()
670
+ raise MailpitInfrastructureError(
671
+ "Mailpit container exited during startup"
672
+ )
673
+ if self.client.ready():
674
+ return self
675
+ time.sleep(0.1)
676
+ self.close()
677
+ raise MailpitInfrastructureError("Mailpit did not become ready")
678
+
679
+ def close(self) -> None:
680
+ process, self._process = self._process, None
681
+ if process is not None and process.poll() is None:
682
+ try:
683
+ subprocess.run(
684
+ [self.docker_binary, "stop", "--time", "3", self.container_name],
685
+ stdin=subprocess.DEVNULL,
686
+ stdout=subprocess.DEVNULL,
687
+ stderr=subprocess.DEVNULL,
688
+ timeout=8,
689
+ check=False,
690
+ )
691
+ except (OSError, subprocess.TimeoutExpired):
692
+ process.terminate()
693
+ try:
694
+ process.wait(timeout=5)
695
+ except subprocess.TimeoutExpired:
696
+ process.kill()
697
+ process.wait(timeout=5)
698
+ if self._owns_runtime_dir:
699
+ shutil.rmtree(self.runtime_dir, ignore_errors=True)
700
+ else:
701
+ for name in ("http.sock", "smtp.sock"):
702
+ try:
703
+ os.unlink(os.path.join(self.runtime_dir, name))
704
+ except FileNotFoundError:
705
+ pass
706
+
707
+ def __enter__(self) -> "EphemeralMailpit":
708
+ return self.start()
709
+
710
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
711
+ self.close()
712
+
713
+
714
+ def redact_text(value: str) -> str:
715
+ """Redact secret-like log fragments without retaining the matched value."""
716
+
717
+ return _LOG_SECRET.sub("[REDACTED]", value)
718
+
719
+
720
+ def redact_log_file(path: str) -> None:
721
+ """Sanitize one UTF-8 verifier log in place before it is published."""
722
+
723
+ from pathlib import Path
724
+
725
+ target = Path(path)
726
+ if not target.is_file():
727
+ return
728
+ value = target.read_text(encoding="utf-8", errors="replace")
729
+ target.write_text(redact_text(value), encoding="utf-8", newline="\n")
730
+
731
+
732
+ def redact_evidence(value: Any) -> Any:
733
+ """Remove credentials and sensitive form values from retained evidence."""
734
+
735
+ sensitive = re.compile(
736
+ r"(?:authorization|cookie|credential|password|secret|token|otp|code|payment|card)",
737
+ re.IGNORECASE,
738
+ )
739
+ if isinstance(value, dict):
740
+ return {
741
+ str(key): "[REDACTED]"
742
+ if sensitive.search(str(key))
743
+ else redact_evidence(child)
744
+ for key, child in value.items()
745
+ }
746
+ if isinstance(value, list):
747
+ return [redact_evidence(child) for child in value]
748
+ return value
749
+
750
+
751
+ @dataclass
752
+ class MailboxStore:
753
+ mailpit_client: MailpitClient
754
+ _capabilities: dict[str, str] = field(default_factory=dict)
755
+ _idempotency: dict[tuple[str, str], str] = field(default_factory=dict)
756
+ _namespace_message_counts: dict[str, int] = field(default_factory=dict)
757
+ _namespace_stored_bytes: dict[str, int] = field(default_factory=dict)
758
+ _lock: threading.Lock = field(default_factory=threading.Lock)
759
+ _broker: MailAccountBroker = field(init=False)
760
+ _accounts: dict[str, MailAccount] = field(default_factory=dict, init=False)
761
+
762
+ def __post_init__(self) -> None:
763
+ if not isinstance(self.mailpit_client, MailpitClient):
764
+ raise MailpitInfrastructureError("Mailpit client is required")
765
+ self._broker = MailAccountBroker(self.mailpit_client)
766
+
767
+ def healthy(self) -> bool:
768
+ return self.mailpit_client.ready()
769
+
770
+ def register(
771
+ self,
772
+ namespace: str,
773
+ capability: str,
774
+ *,
775
+ allowed_from: tuple[str, ...] = (),
776
+ ) -> None:
777
+ if not _NAMESPACE.fullmatch(namespace) or len(capability) < 32:
778
+ raise ValueError("invalid mailbox namespace capability")
779
+ if any(
780
+ not value or "@" not in value or "\r" in value or "\n" in value
781
+ for value in allowed_from
782
+ ):
783
+ raise ValueError("invalid allowed mail sender")
784
+ allowed_senders = set(allowed_from)
785
+ with self._lock:
786
+ existing = self._capabilities.get(namespace)
787
+ if existing is not None and existing != capability:
788
+ raise ValueError("mailbox namespace is already registered")
789
+ self._capabilities[namespace] = capability
790
+ account = self._accounts.get(namespace)
791
+ if account is None:
792
+ self._accounts[namespace] = self._broker.create_account(
793
+ address="", role="gateway", allowed_from=allowed_senders
794
+ )
795
+ elif account.allowed_from != allowed_senders:
796
+ raise ValueError("mailbox namespace sender policy is already registered")
797
+
798
+ def authorized(self, namespace: str, capability: str | None) -> bool:
799
+ with self._lock:
800
+ expected = self._capabilities.get(namespace)
801
+ return (
802
+ expected is not None
803
+ and capability is not None
804
+ and hmac.compare_digest(expected, capability)
805
+ )
806
+
807
+ def seal_namespace(self, namespace: str) -> None:
808
+ """Retire one writer while retaining trusted reads until teardown."""
809
+
810
+ with self._lock:
811
+ self._capabilities.pop(namespace, None)
812
+ account = self._accounts.get(namespace)
813
+ self._namespace_message_counts.pop(namespace, None)
814
+ self._namespace_stored_bytes.pop(namespace, None)
815
+ self._idempotency = {
816
+ identity: provider_id
817
+ for identity, provider_id in self._idempotency.items()
818
+ if identity[0] != namespace
819
+ }
820
+ if account is not None:
821
+ self._broker.seal(account.account_id)
822
+
823
+ def destroy_namespaces(self) -> None:
824
+ """Revoke every logical account without deleting Mailpit messages."""
825
+
826
+ with self._lock:
827
+ accounts = list(self._accounts.values())
828
+ self._capabilities.clear()
829
+ self._accounts.clear()
830
+ self._namespace_message_counts.clear()
831
+ self._namespace_stored_bytes.clear()
832
+ self._idempotency.clear()
833
+ for account in accounts:
834
+ if account.state != "destroyed":
835
+ self._broker.destroy(account.account_id)
836
+
837
+ def _store_message(
838
+ self,
839
+ message: Any,
840
+ envelope_from: str,
841
+ recipients: list[str],
842
+ *,
843
+ namespace: str,
844
+ idempotency_key: str | None = None,
845
+ raw: bytes | None = None,
846
+ ) -> tuple[bool, str | None]:
847
+ with self._lock:
848
+ idempotency_identity = (
849
+ (namespace, idempotency_key) if idempotency_key else None
850
+ )
851
+ if idempotency_identity is not None:
852
+ previous = self._idempotency.get(idempotency_identity)
853
+ if previous is not None:
854
+ return True, previous
855
+ account = self._accounts.get(namespace)
856
+ if account is None:
857
+ return False, None
858
+ wire = raw if raw is not None else message.as_bytes()
859
+ message_count = self._namespace_message_counts.get(namespace, 0)
860
+ stored_bytes = self._namespace_stored_bytes.get(namespace, 0)
861
+ if (
862
+ message_count >= _MAX_MESSAGES_PER_NAMESPACE
863
+ or stored_bytes + len(wire) > _MAX_STORED_BYTES_PER_NAMESPACE
864
+ ):
865
+ raise MailboxCapacityError("mailbox namespace capacity exceeded")
866
+ # Keep the lock across the final hop so concurrent requests with
867
+ # one idempotency key cannot manufacture two accepted messages.
868
+ # No message body or code is retained after Mailpit acknowledges
869
+ # the SMTP DATA command.
870
+ provider_id = self._broker.send(
871
+ account.account_id,
872
+ account.send_capability,
873
+ wire,
874
+ envelope_from,
875
+ recipients,
876
+ )
877
+ self._namespace_message_counts[namespace] = message_count + 1
878
+ self._namespace_stored_bytes[namespace] = stored_bytes + len(wire)
879
+ if idempotency_identity is not None:
880
+ self._idempotency[idempotency_identity] = provider_id
881
+ return True, provider_id
882
+
883
+ def deliver(self, raw: bytes, envelope_from: str, recipients: list[str]) -> bool:
884
+ message = email.message_from_bytes(raw, policy=default)
885
+ namespace = str(message.get("X-WebsiteBench-Namespace", "default"))
886
+ capability = str(message.get("X-WebsiteBench-Capability", ""))
887
+ if not _NAMESPACE.fullmatch(namespace) or not self.authorized(
888
+ namespace, capability
889
+ ):
890
+ return False
891
+ accepted, _provider_id = self._store_message(
892
+ message,
893
+ envelope_from,
894
+ recipients,
895
+ namespace=namespace,
896
+ raw=raw,
897
+ )
898
+ return accepted
899
+
900
+ def deliver_to(
901
+ self,
902
+ namespace: str,
903
+ raw: bytes,
904
+ envelope_from: str,
905
+ recipients: list[str],
906
+ ) -> bool:
907
+ """Store mail on a listener already fixed to one registered namespace.
908
+
909
+ Formal candidate runtimes receive access to that write-only listener,
910
+ not to the namespace-selecting SMTP or JSON API used by reference
911
+ capture. The routing decision therefore belongs to trusted verifier
912
+ infrastructure rather than to candidate-authored message headers.
913
+ """
914
+
915
+ if not _NAMESPACE.fullmatch(namespace):
916
+ return False
917
+ with self._lock:
918
+ registered = namespace in self._capabilities
919
+ if not registered:
920
+ return False
921
+ message = email.message_from_bytes(raw, policy=default)
922
+ accepted, _provider_id = self._store_message(
923
+ message,
924
+ envelope_from,
925
+ recipients,
926
+ namespace=namespace,
927
+ raw=raw,
928
+ )
929
+ return accepted
930
+
931
+ def deliver_resend_style_to(
932
+ self,
933
+ namespace: str,
934
+ *,
935
+ envelope_from: str,
936
+ recipients: list[str],
937
+ subject: str,
938
+ text: str,
939
+ idempotency_key: str | None,
940
+ ) -> tuple[bool, str | None]:
941
+ """Store one text-only Resend-style request in a fixed namespace."""
942
+
943
+ if not _NAMESPACE.fullmatch(namespace):
944
+ return False, None
945
+ with self._lock:
946
+ registered = namespace in self._capabilities
947
+ if not registered:
948
+ return False, None
949
+ message = EmailMessage()
950
+ message["From"] = envelope_from
951
+ message["To"] = ", ".join(recipients)
952
+ message["Subject"] = subject
953
+ message.set_content(text)
954
+ return self._store_message(
955
+ message,
956
+ envelope_from,
957
+ recipients,
958
+ namespace=namespace,
959
+ idempotency_key=idempotency_key,
960
+ raw=message.as_bytes(),
961
+ )
962
+
963
+ def messages(
964
+ self, namespace: str, recipient: str | None = None
965
+ ) -> list[dict[str, Any]]:
966
+ with self._lock:
967
+ account = self._accounts.get(namespace)
968
+ if account is None:
969
+ return []
970
+ values = self._broker.messages(
971
+ account.account_id, account.read_capability, recipient
972
+ )
973
+ for item in values:
974
+ item["namespace"] = namespace
975
+ item.pop("stored_bytes", None)
976
+ item.pop("mailpit_id", None)
977
+ return values
978
+
979
+
980
+ _INBOX_STYLE = (
981
+ "body{font:16px/1.5 system-ui,sans-serif;margin:0;background:#f6f7f9;"
982
+ "color:#1b1f24}"
983
+ "header{background:#fff;border-bottom:1px solid #d8dee4;padding:16px 24px}"
984
+ "h1{font-size:20px;margin:0}"
985
+ "main{max-width:52rem;margin:0 auto;padding:24px}"
986
+ "a{color:#0b62d0}"
987
+ ".msg{background:#fff;border:1px solid #d8dee4;border-radius:8px;"
988
+ "padding:12px 16px;margin-bottom:12px}"
989
+ ".msg h2{font-size:16px;margin:0 0 4px}"
990
+ ".meta{color:#57606a;font-size:13px;margin:0}"
991
+ ".empty{color:#57606a}"
992
+ "pre{white-space:pre-wrap;word-break:break-word;background:#f6f8fa;"
993
+ "border-radius:6px;padding:12px;margin:12px 0 0}"
994
+ )
995
+
996
+
997
+ def _document(title: str, body: str) -> bytes:
998
+ """One self-contained HTML page. Every interpolated value is escaped."""
999
+
1000
+ return (
1001
+ "<!doctype html><html lang=en><meta charset=utf-8>"
1002
+ '<meta name=viewport content="width=device-width,initial-scale=1">'
1003
+ f"<title>{html.escape(title)}</title>"
1004
+ f"<style>{_INBOX_STYLE}</style>"
1005
+ f"<header><h1>{html.escape(title)}</h1></header><main>{body}</main>"
1006
+ "</html>"
1007
+ ).encode("utf-8")
1008
+
1009
+
1010
+ def _recipients(message: dict[str, Any]) -> str:
1011
+ return ", ".join(str(item) for item in message.get("recipients", []))
1012
+
1013
+
1014
+ def render_inbox(messages: list[dict[str, Any]], *, base_path: str = "") -> bytes:
1015
+ """The message list an agent reads in a browser.
1016
+
1017
+ The extracted ``otp`` is deliberately absent: an agent should read the code
1018
+ out of the body the way a person would. That field stays an evaluator-side
1019
+ convenience on the JSON API.
1020
+ """
1021
+
1022
+ if not messages:
1023
+ body = (
1024
+ "<p class=empty id=inbox-empty>No messages yet. Mail sent to this "
1025
+ "mailbox appears here.</p>"
1026
+ )
1027
+ else:
1028
+ body = "".join(
1029
+ "<article class=msg>"
1030
+ f'<h2><a href="{html.escape(base_path)}/messages/{int(item["id"])}">'
1031
+ f"{html.escape(str(item.get('subject', '')))}</a></h2>"
1032
+ f"<p class=meta>From {html.escape(str(item.get('envelope_from', '')))}"
1033
+ f" &middot; To {html.escape(_recipients(item))}"
1034
+ f" &middot; Message {int(item['id'])}</p>"
1035
+ "</article>"
1036
+ for item in messages
1037
+ )
1038
+ refresh = f'<p><a href="{html.escape(base_path)}" id=inbox-refresh>Refresh</a></p>'
1039
+ return _document("Inbox", body + refresh)
1040
+
1041
+
1042
+ def render_message(message: dict[str, Any], *, base_path: str = "") -> bytes:
1043
+ """One message, body included, for the agent to read the code out of."""
1044
+
1045
+ body = (
1046
+ "<article class=msg>"
1047
+ f"<h2>{html.escape(str(message.get('subject', '')))}</h2>"
1048
+ f"<p class=meta>From {html.escape(str(message.get('envelope_from', '')))}"
1049
+ f" &middot; To {html.escape(_recipients(message))}</p>"
1050
+ f"<pre id=message-body>{html.escape(str(message.get('text', '')))}</pre>"
1051
+ "</article>"
1052
+ f'<p><a href="{html.escape(base_path)}" id=inbox-back>Back to inbox</a></p>'
1053
+ )
1054
+ return _document("Message", body)
1055
+
1056
+
1057
+ class _SmtpHandler(socketserver.StreamRequestHandler):
1058
+ def handle(self) -> None:
1059
+ timer = threading.Timer(
1060
+ _MAX_CONNECTION_LIFETIME_SECONDS, self._expire_connection
1061
+ )
1062
+ timer.daemon = True
1063
+ timer.start()
1064
+ try:
1065
+ self._handle_session()
1066
+ finally:
1067
+ timer.cancel()
1068
+
1069
+ def _expire_connection(self) -> None:
1070
+ try:
1071
+ self.connection.shutdown(socket.SHUT_RDWR)
1072
+ except OSError:
1073
+ pass
1074
+
1075
+ def _handle_session(self) -> None:
1076
+ store: MailboxStore = self.server.store # type: ignore[attr-defined]
1077
+ self.connection.settimeout(_CONNECTION_TIMEOUT_SECONDS)
1078
+ self.wfile.write(b"220 websitebench.local ESMTP\r\n")
1079
+ envelope_from = ""
1080
+ recipients: list[str] = []
1081
+ for _command_count in range(_MAX_COMMANDS_PER_CONNECTION):
1082
+ try:
1083
+ line = self.rfile.readline(65537)
1084
+ except (TimeoutError, socket.timeout):
1085
+ return
1086
+ if not line:
1087
+ return
1088
+ if len(line) > 65536:
1089
+ self.wfile.write(b"500 Command line too long\r\n")
1090
+ return
1091
+ command = line.decode("utf-8", "replace").rstrip("\r\n")
1092
+ upper = command.upper()
1093
+ if upper.startswith(("EHLO", "HELO")):
1094
+ self.wfile.write(b"250-websitebench.local\r\n250 SIZE 1048576\r\n")
1095
+ elif upper.startswith("MAIL FROM:"):
1096
+ path = command.split(":", 1)[1].strip()
1097
+ envelope_from = (
1098
+ path[1:].split(">", 1)[0]
1099
+ if path.startswith("<") and ">" in path
1100
+ else path.split(None, 1)[0].strip("<>")
1101
+ )
1102
+ recipients = []
1103
+ self.wfile.write(b"250 OK\r\n")
1104
+ elif upper.startswith("RCPT TO:"):
1105
+ if len(recipients) >= _MAX_RECIPIENTS:
1106
+ self.wfile.write(b"452 Too many recipients\r\n")
1107
+ continue
1108
+ path = command.split(":", 1)[1].strip()
1109
+ recipients.append(
1110
+ path[1:].split(">", 1)[0]
1111
+ if path.startswith("<") and ">" in path
1112
+ else path.split(None, 1)[0].strip("<>")
1113
+ )
1114
+ self.wfile.write(b"250 OK\r\n")
1115
+ elif upper == "DATA":
1116
+ self.wfile.write(b"354 End data with <CR><LF>.<CR><LF>\r\n")
1117
+ chunks = bytearray()
1118
+ oversized = False
1119
+ while True:
1120
+ try:
1121
+ data_line = self.rfile.readline(65537)
1122
+ except (TimeoutError, socket.timeout):
1123
+ return
1124
+ if data_line in {b".\r\n", b".\n", b""}:
1125
+ break
1126
+ if len(data_line) > 65536:
1127
+ oversized = True
1128
+ value = data_line[1:] if data_line.startswith(b"..") else data_line
1129
+ if len(chunks) + len(value) > _MAX_MESSAGE_BYTES:
1130
+ oversized = True
1131
+ elif not oversized:
1132
+ chunks.extend(value)
1133
+ if oversized:
1134
+ self.wfile.write(b"552 Message exceeds fixed local limit\r\n")
1135
+ continue
1136
+ fixed_namespace = getattr(self.server, "fixed_namespace", None)
1137
+ try:
1138
+ accepted = (
1139
+ store.deliver_to(
1140
+ fixed_namespace,
1141
+ bytes(chunks),
1142
+ envelope_from,
1143
+ recipients,
1144
+ )
1145
+ if isinstance(fixed_namespace, str)
1146
+ else store.deliver(bytes(chunks), envelope_from, recipients)
1147
+ )
1148
+ except MailboxCapacityError:
1149
+ self.wfile.write(b"452 Mailbox capacity exceeded\r\n")
1150
+ continue
1151
+ except PermissionError:
1152
+ self.wfile.write(b"550 Mail sender or recipient is not allowed\r\n")
1153
+ continue
1154
+ except MailpitInfrastructureError:
1155
+ self.wfile.write(b"451 Mailpit delivery unavailable\r\n")
1156
+ continue
1157
+ self.wfile.write(
1158
+ b"250 Accepted by Mailpit\r\n"
1159
+ if accepted
1160
+ else b"550 Invalid namespace capability\r\n"
1161
+ )
1162
+ elif upper == "RSET":
1163
+ envelope_from, recipients = "", []
1164
+ self.wfile.write(b"250 OK\r\n")
1165
+ elif upper == "NOOP":
1166
+ self.wfile.write(b"250 OK\r\n")
1167
+ elif upper == "QUIT":
1168
+ self.wfile.write(b"221 Bye\r\n")
1169
+ return
1170
+ else:
1171
+ self.wfile.write(b"502 Command not implemented\r\n")
1172
+ self.wfile.write(b"421 Command limit exceeded\r\n")
1173
+
1174
+
1175
+ class _SmtpServer(socketserver.ThreadingTCPServer):
1176
+ allow_reuse_address = True
1177
+ daemon_threads = True
1178
+
1179
+ def __init__(
1180
+ self,
1181
+ address: tuple[str, int],
1182
+ store: MailboxStore,
1183
+ *,
1184
+ fixed_namespace: str | None = None,
1185
+ ) -> None:
1186
+ self.store = store
1187
+ self.fixed_namespace = fixed_namespace
1188
+ self._connection_slots = threading.BoundedSemaphore(_MAX_CONCURRENT_CONNECTIONS)
1189
+ super().__init__(address, _SmtpHandler)
1190
+
1191
+ def process_request(self, request: Any, client_address: Any) -> None:
1192
+ if not self._connection_slots.acquire(blocking=False):
1193
+ request.close()
1194
+ return
1195
+ super().process_request(request, client_address)
1196
+
1197
+ def process_request_thread(self, request: Any, client_address: Any) -> None:
1198
+ try:
1199
+ super().process_request_thread(request, client_address)
1200
+ finally:
1201
+ self._connection_slots.release()
1202
+
1203
+
1204
+ class _HttpServer(ThreadingHTTPServer):
1205
+ daemon_threads = True
1206
+
1207
+ def __init__(self, address: tuple[str, int], handler: Any) -> None:
1208
+ self._connection_slots = threading.BoundedSemaphore(_MAX_CONCURRENT_CONNECTIONS)
1209
+ super().__init__(address, handler)
1210
+
1211
+ def process_request(self, request: Any, client_address: Any) -> None:
1212
+ if not self._connection_slots.acquire(blocking=False):
1213
+ request.close()
1214
+ return
1215
+ super().process_request(request, client_address)
1216
+
1217
+ def process_request_thread(self, request: Any, client_address: Any) -> None:
1218
+ def expire() -> None:
1219
+ try:
1220
+ request.shutdown(socket.SHUT_RDWR)
1221
+ except OSError:
1222
+ pass
1223
+
1224
+ timer = threading.Timer(_MAX_CONNECTION_LIFETIME_SECONDS, expire)
1225
+ timer.daemon = True
1226
+ timer.start()
1227
+ try:
1228
+ request.settimeout(_CONNECTION_TIMEOUT_SECONDS)
1229
+ super().process_request_thread(request, client_address)
1230
+ finally:
1231
+ timer.cancel()
1232
+ self._connection_slots.release()
1233
+
1234
+
1235
+ def _http_handler(
1236
+ store: MailboxStore,
1237
+ bootstrap: "_Bootstrap | _BootstrapSlot | None" = None,
1238
+ ) -> type[BaseHTTPRequestHandler]:
1239
+ """The evaluator- and site-facing listener: JSON, Bearer-gated throughout."""
1240
+
1241
+ slot = (
1242
+ bootstrap
1243
+ if isinstance(bootstrap, _BootstrapSlot)
1244
+ else _BootstrapSlot(bootstrap)
1245
+ )
1246
+
1247
+ class Handler(BaseHTTPRequestHandler):
1248
+ def _authorized(self, namespace: str) -> bool:
1249
+ prefix = "Bearer "
1250
+ header = self.headers.get("Authorization", "")
1251
+ capability = header[len(prefix) :] if header.startswith(prefix) else None
1252
+ if store.authorized(namespace, capability):
1253
+ return True
1254
+ self._json(403, {"error": "forbidden"})
1255
+ return False
1256
+
1257
+ def _json(self, status: int, value: Any) -> None:
1258
+ body = json.dumps(value, ensure_ascii=False, sort_keys=True).encode("utf-8")
1259
+ self.send_response(status)
1260
+ self.send_header("Content-Type", "application/json; charset=utf-8")
1261
+ self.send_header("Content-Length", str(len(body)))
1262
+ self.end_headers()
1263
+ self.wfile.write(body)
1264
+
1265
+ def _html(self, status: int, body: bytes) -> None:
1266
+ self.send_response(status)
1267
+ self.send_header("Content-Type", "text/html; charset=utf-8")
1268
+ self.send_header("Content-Length", str(len(body)))
1269
+ self.end_headers()
1270
+ self.wfile.write(body)
1271
+
1272
+ def do_GET(self) -> None: # noqa: N802
1273
+ parsed = urllib.parse.urlsplit(self.path)
1274
+ if parsed.path == "/healthz":
1275
+ if store.healthy():
1276
+ self._json(200, {"status": "ok"})
1277
+ else:
1278
+ self._json(503, {"status": "unavailable"})
1279
+ return
1280
+ if parsed.path == "/internal/bootstrap":
1281
+ # The site process learns this trial's namespace and capability
1282
+ # here. It is gated on its own token so the route stays closed
1283
+ # even if the internal network were misrouted.
1284
+ identity = slot.get()
1285
+ if identity is None:
1286
+ self._json(404, {"error": "not_found"})
1287
+ return
1288
+ prefix = "Bearer "
1289
+ header = self.headers.get("Authorization", "")
1290
+ presented = header[len(prefix) :] if header.startswith(prefix) else ""
1291
+ if not hmac.compare_digest(identity.token, presented):
1292
+ self._json(403, {"error": "forbidden"})
1293
+ return
1294
+ self._json(200, identity.payload())
1295
+ return
1296
+ parts = parsed.path.strip("/").split("/")
1297
+ if (
1298
+ len(parts) >= 4
1299
+ and parts[:2] == ["api", "namespaces"]
1300
+ and parts[3] == "messages"
1301
+ ):
1302
+ namespace = urllib.parse.unquote(parts[2])
1303
+ if not _NAMESPACE.fullmatch(namespace):
1304
+ self._json(400, {"error": "invalid_namespace"})
1305
+ return
1306
+ if not self._authorized(namespace):
1307
+ return
1308
+ recipient = urllib.parse.parse_qs(parsed.query).get(
1309
+ "recipient", [None]
1310
+ )[0]
1311
+ try:
1312
+ values = store.messages(namespace, recipient)
1313
+ except PermissionError:
1314
+ self._json(403, {"error": "recipient_forbidden"})
1315
+ return
1316
+ except MailpitInfrastructureError:
1317
+ self._json(503, {"error": "mailpit_unavailable"})
1318
+ return
1319
+ if len(parts) == 5 and parts[4] == "latest":
1320
+ if not values:
1321
+ self._json(404, {"error": "message_not_found"})
1322
+ else:
1323
+ self._json(200, values[-1])
1324
+ else:
1325
+ self._json(200, {"messages": values})
1326
+ return
1327
+ if len(parts) == 2 and parts[0] == "inbox":
1328
+ namespace = urllib.parse.unquote(parts[1])
1329
+ if not _NAMESPACE.fullmatch(namespace):
1330
+ self._json(400, {"error": "invalid_namespace"})
1331
+ return
1332
+ if not self._authorized(namespace):
1333
+ return
1334
+ try:
1335
+ messages = store.messages(namespace)
1336
+ except PermissionError:
1337
+ self._json(403, {"error": "forbidden"})
1338
+ return
1339
+ except MailpitInfrastructureError:
1340
+ self._json(503, {"error": "mailpit_unavailable"})
1341
+ return
1342
+ body = render_inbox(
1343
+ messages, base_path=f"/inbox/{urllib.parse.quote(namespace)}"
1344
+ )
1345
+ self._html(200, body)
1346
+ return
1347
+ self._json(404, {"error": "not_found"})
1348
+
1349
+ def do_POST(self) -> None: # noqa: N802
1350
+ """Accept reference mail through a bootstrap-token write-only API."""
1351
+
1352
+ parsed = urllib.parse.urlsplit(self.path)
1353
+ if parsed.path != "/emails" or parsed.query or parsed.fragment:
1354
+ self._json(404, {"error": "not_found"})
1355
+ return
1356
+ identity = slot.get()
1357
+ if identity is None:
1358
+ self._json(404, {"error": "not_found"})
1359
+ return
1360
+ prefix = "Bearer "
1361
+ header = self.headers.get("Authorization", "")
1362
+ presented = header[len(prefix) :] if header.startswith(prefix) else ""
1363
+ if not hmac.compare_digest(identity.token, presented):
1364
+ self._json(401, {"error": "unauthorized"})
1365
+ return
1366
+ if self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() != "application/json":
1367
+ self._json(415, {"error": "application_json_required"})
1368
+ return
1369
+ try:
1370
+ content_length = int(self.headers.get("Content-Length", ""))
1371
+ except ValueError:
1372
+ self._json(411, {"error": "content_length_required"})
1373
+ return
1374
+ if content_length < 0 or content_length > _MAX_MESSAGE_BYTES:
1375
+ self._json(413, {"error": "message_too_large"})
1376
+ return
1377
+ try:
1378
+ value = json.loads(self.rfile.read(content_length).decode("utf-8"))
1379
+ except (UnicodeDecodeError, json.JSONDecodeError):
1380
+ self._json(400, {"error": "invalid_json"})
1381
+ return
1382
+ if not isinstance(value, dict) or set(value) != {"from", "to", "subject", "text"}:
1383
+ self._json(400, {"error": "invalid_message_fields"})
1384
+ return
1385
+ envelope_from = value.get("from")
1386
+ recipients = value.get("to")
1387
+ subject = value.get("subject")
1388
+ message_text = value.get("text")
1389
+ recipients = [recipients] if isinstance(recipients, str) else recipients
1390
+ if (
1391
+ not isinstance(envelope_from, str)
1392
+ or not envelope_from
1393
+ or "@" not in envelope_from
1394
+ or "\r" in envelope_from
1395
+ or "\n" in envelope_from
1396
+ or not isinstance(recipients, list)
1397
+ or not 1 <= len(recipients) <= _MAX_RECIPIENTS
1398
+ or any(
1399
+ not isinstance(recipient, str)
1400
+ or not recipient
1401
+ or len(recipient) > 320
1402
+ or "@" not in recipient
1403
+ or "\r" in recipient
1404
+ or "\n" in recipient
1405
+ for recipient in recipients
1406
+ )
1407
+ or not isinstance(subject, str)
1408
+ or len(subject) > 998
1409
+ or "\r" in subject
1410
+ or "\n" in subject
1411
+ or not isinstance(message_text, str)
1412
+ or len(message_text.encode("utf-8")) > _MAX_MESSAGE_BYTES
1413
+ ):
1414
+ self._json(400, {"error": "invalid_message"})
1415
+ return
1416
+ idempotency_key = self.headers.get("Idempotency-Key")
1417
+ if idempotency_key is not None and (
1418
+ not idempotency_key
1419
+ or len(idempotency_key) > 256
1420
+ or "\r" in idempotency_key
1421
+ or "\n" in idempotency_key
1422
+ ):
1423
+ self._json(400, {"error": "invalid_idempotency_key"})
1424
+ return
1425
+ try:
1426
+ accepted, provider_id = store.deliver_resend_style_to(
1427
+ identity.namespace,
1428
+ envelope_from=envelope_from,
1429
+ recipients=recipients,
1430
+ subject=subject,
1431
+ text=message_text,
1432
+ idempotency_key=idempotency_key,
1433
+ )
1434
+ except MailboxCapacityError:
1435
+ self._json(429, {"error": "mailbox_capacity"})
1436
+ return
1437
+ except MailpitInfrastructureError:
1438
+ self._json(503, {"error": "mailpit_unavailable"})
1439
+ return
1440
+ if not accepted or provider_id is None:
1441
+ self._json(503, {"error": "delivery_failed"})
1442
+ return
1443
+ self._json(200, {"id": provider_id})
1444
+
1445
+ def log_message(self, format: str, *args: Any) -> None:
1446
+ return
1447
+
1448
+ return Handler
1449
+
1450
+
1451
+ def _candidate_bootstrap_handler(
1452
+ *,
1453
+ store: MailboxStore,
1454
+ bootstrap_token: str,
1455
+ mail_api_token: str,
1456
+ namespace: str,
1457
+ capability: str,
1458
+ smtp_host: str,
1459
+ smtp_port: int,
1460
+ sender: str,
1461
+ ) -> type[BaseHTTPRequestHandler]:
1462
+ """Expose write-only mail paths without exposing the mailbox read API.
1463
+
1464
+ ``POST /emails`` is deliberately a small Resend-style subset: one fixed
1465
+ sender, one or more recipients, a subject, and a plain-text body. The
1466
+ endpoint owns the trial namespace, so candidate input can never select a
1467
+ second mailbox. The legacy bootstrap and SMTP coordinates remain here for
1468
+ candidates using the vendored ``websitebench.site_backend`` transport.
1469
+ """
1470
+
1471
+ payload = {
1472
+ "namespace": namespace,
1473
+ "capability": capability,
1474
+ "smtp_host": smtp_host,
1475
+ "smtp_port": smtp_port,
1476
+ }
1477
+
1478
+ class CandidateBootstrapHandler(BaseHTTPRequestHandler):
1479
+ def _json(self, status: int, value: Any) -> None:
1480
+ body = json.dumps(value, ensure_ascii=False, sort_keys=True).encode("utf-8")
1481
+ self.send_response(status)
1482
+ self.send_header("Content-Type", "application/json; charset=utf-8")
1483
+ self.send_header("Content-Length", str(len(body)))
1484
+ self.send_header("Cache-Control", "no-store")
1485
+ self.end_headers()
1486
+ self.wfile.write(body)
1487
+
1488
+ def do_GET(self) -> None: # noqa: N802
1489
+ parsed = urllib.parse.urlsplit(self.path)
1490
+ if parsed.path == "/healthz":
1491
+ healthy = store.healthy()
1492
+ self._json(200 if healthy else 503, {"status": "ok" if healthy else "unavailable"})
1493
+ return
1494
+ if parsed.path != "/internal/bootstrap":
1495
+ self._json(404, {"error": "not_found"})
1496
+ return
1497
+ prefix = "Bearer "
1498
+ header = self.headers.get("Authorization", "")
1499
+ presented = header[len(prefix) :] if header.startswith(prefix) else ""
1500
+ if not hmac.compare_digest(bootstrap_token, presented):
1501
+ self._json(403, {"error": "forbidden"})
1502
+ return
1503
+ self._json(200, payload)
1504
+
1505
+ def do_POST(self) -> None: # noqa: N802
1506
+ parsed = urllib.parse.urlsplit(self.path)
1507
+ if parsed.path != "/emails" or parsed.query or parsed.fragment:
1508
+ self._json(404, {"error": "not_found"})
1509
+ return
1510
+ prefix = "Bearer "
1511
+ header = self.headers.get("Authorization", "")
1512
+ presented = header[len(prefix) :] if header.startswith(prefix) else ""
1513
+ if not hmac.compare_digest(mail_api_token, presented):
1514
+ self._json(401, {"error": "unauthorized"})
1515
+ return
1516
+ content_type = self.headers.get("Content-Type", "").split(";", 1)[0]
1517
+ if content_type.strip().lower() != "application/json":
1518
+ self._json(415, {"error": "application_json_required"})
1519
+ return
1520
+ try:
1521
+ content_length = int(self.headers.get("Content-Length", ""))
1522
+ except ValueError:
1523
+ self._json(411, {"error": "content_length_required"})
1524
+ return
1525
+ if content_length < 0 or content_length > _MAX_MESSAGE_BYTES:
1526
+ self._json(413, {"error": "message_too_large"})
1527
+ return
1528
+ raw = self.rfile.read(content_length)
1529
+ if len(raw) != content_length:
1530
+ self._json(400, {"error": "incomplete_request"})
1531
+ return
1532
+ try:
1533
+ value = json.loads(raw.decode("utf-8"))
1534
+ except (UnicodeDecodeError, json.JSONDecodeError):
1535
+ self._json(400, {"error": "invalid_json"})
1536
+ return
1537
+ if not isinstance(value, dict) or set(value) != {
1538
+ "from",
1539
+ "to",
1540
+ "subject",
1541
+ "text",
1542
+ }:
1543
+ self._json(400, {"error": "invalid_message_fields"})
1544
+ return
1545
+ envelope_from = value.get("from")
1546
+ subject = value.get("subject")
1547
+ text = value.get("text")
1548
+ raw_recipients = value.get("to")
1549
+ recipients = (
1550
+ [raw_recipients] if isinstance(raw_recipients, str) else raw_recipients
1551
+ )
1552
+ if (
1553
+ envelope_from != sender
1554
+ or not isinstance(subject, str)
1555
+ or not isinstance(text, str)
1556
+ or not isinstance(recipients, list)
1557
+ or not 1 <= len(recipients) <= _MAX_RECIPIENTS
1558
+ or any(
1559
+ not isinstance(recipient, str)
1560
+ or not recipient
1561
+ or len(recipient) > 320
1562
+ or "@" not in recipient
1563
+ or "\r" in recipient
1564
+ or "\n" in recipient
1565
+ for recipient in recipients
1566
+ )
1567
+ or len(subject) > 998
1568
+ or "\r" in subject
1569
+ or "\n" in subject
1570
+ ):
1571
+ self._json(400, {"error": "invalid_message"})
1572
+ return
1573
+ try:
1574
+ encoded_text = text.encode("utf-8")
1575
+ subject.encode("utf-8")
1576
+ for recipient in recipients:
1577
+ recipient.encode("utf-8")
1578
+ except UnicodeEncodeError:
1579
+ self._json(400, {"error": "invalid_message"})
1580
+ return
1581
+ if len(encoded_text) > _MAX_MESSAGE_BYTES:
1582
+ self._json(413, {"error": "message_too_large"})
1583
+ return
1584
+ idempotency_key = self.headers.get("Idempotency-Key")
1585
+ if idempotency_key is not None and (
1586
+ not idempotency_key
1587
+ or len(idempotency_key) > 256
1588
+ or "\r" in idempotency_key
1589
+ or "\n" in idempotency_key
1590
+ ):
1591
+ self._json(400, {"error": "invalid_idempotency_key"})
1592
+ return
1593
+ try:
1594
+ accepted, provider_id = store.deliver_resend_style_to(
1595
+ namespace,
1596
+ envelope_from=envelope_from,
1597
+ recipients=recipients,
1598
+ subject=subject,
1599
+ text=text,
1600
+ idempotency_key=idempotency_key,
1601
+ )
1602
+ except MailboxCapacityError:
1603
+ self._json(429, {"error": "mailbox_capacity"})
1604
+ return
1605
+ except MailpitInfrastructureError:
1606
+ self._json(503, {"error": "mailpit_unavailable"})
1607
+ return
1608
+ if not accepted or provider_id is None:
1609
+ self._json(429, {"error": "mailbox_capacity"})
1610
+ return
1611
+ self._json(200, {"id": provider_id})
1612
+
1613
+ def log_message(self, format: str, *args: Any) -> None:
1614
+ return
1615
+
1616
+ return CandidateBootstrapHandler
1617
+
1618
+
1619
+ @dataclass(frozen=True, repr=False)
1620
+ class _Bootstrap:
1621
+ """What the site process is allowed to learn, and the token that gates it."""
1622
+
1623
+ token: str
1624
+ namespace: str
1625
+ capability: str
1626
+ smtp_host: str
1627
+ smtp_port: int
1628
+
1629
+ def __repr__(self) -> str:
1630
+ return f"_Bootstrap(namespace={self.namespace!r}, token=<redacted>)"
1631
+
1632
+ def payload(self) -> dict[str, Any]:
1633
+ return {
1634
+ "namespace": self.namespace,
1635
+ "capability": self.capability,
1636
+ "smtp_host": self.smtp_host,
1637
+ "smtp_port": self.smtp_port,
1638
+ }
1639
+
1640
+
1641
+ class _BootstrapSlot:
1642
+ """The identity ``/internal/bootstrap`` is serving right now.
1643
+
1644
+ A trial's mailbox identity is minted once and never moves, so the slot is
1645
+ written once and read forever. Reference capture is the exception that
1646
+ makes it a slot at all: it relaunches the reference between tasks, and each
1647
+ relaunch has to be its own trial -- same bootstrap token, because that is
1648
+ the site process's own credential and the site is what stays the same, but
1649
+ a namespace and capability nothing before it could have seen. Rotating
1650
+ behind the slot lets the operator do that without tearing down the listener
1651
+ the site is about to call.
1652
+ """
1653
+
1654
+ def __init__(self, bootstrap: "_Bootstrap | None" = None) -> None:
1655
+ self._lock = threading.Lock()
1656
+ self._value = bootstrap
1657
+
1658
+ def __repr__(self) -> str:
1659
+ return f"_BootstrapSlot({self._value!r})"
1660
+
1661
+ def get(self) -> "_Bootstrap | None":
1662
+ with self._lock:
1663
+ return self._value
1664
+
1665
+ def rotate(self, *, namespace: str, capability: str) -> "_Bootstrap":
1666
+ """Swap in a fresh namespace and capability, keeping the token."""
1667
+
1668
+ with self._lock:
1669
+ current = self._value
1670
+ if current is None:
1671
+ raise RuntimeError("this mailbox serves no bootstrap identity")
1672
+ rotated = replace(current, namespace=namespace, capability=capability)
1673
+ self._value = rotated
1674
+ return rotated
1675
+
1676
+
1677
+ def _inbox_handler(
1678
+ store: MailboxStore, namespace: str, token: str
1679
+ ) -> type[BaseHTTPRequestHandler]:
1680
+ """The agent-facing listener: one namespace, HTML only, no capability.
1681
+
1682
+ The namespace is closed over at construction, so there is no request-time
1683
+ parameter an agent could vary to reach a second mailbox. Requirement 5
1684
+ holds by construction rather than by a check that could be bypassed.
1685
+ """
1686
+
1687
+ inbox_path = "/inbox/" + urllib.parse.quote(token, safe="")
1688
+
1689
+ class InboxHandler(BaseHTTPRequestHandler):
1690
+ def _send(self, status: int, body: bytes, content_type: str) -> None:
1691
+ self.send_response(status)
1692
+ self.send_header("Content-Type", content_type)
1693
+ self.send_header("Content-Length", str(len(body)))
1694
+ # The inbox is per-trial and mutates; never let it be cached.
1695
+ self.send_header("Cache-Control", "no-store")
1696
+ self.send_header("Referrer-Policy", "no-referrer")
1697
+ self.end_headers()
1698
+ self.wfile.write(body)
1699
+
1700
+ def _not_found(self) -> None:
1701
+ self._send(
1702
+ 404,
1703
+ _document("Not found", "<p>No such page.</p>"),
1704
+ "text/html; charset=utf-8",
1705
+ )
1706
+
1707
+ def do_GET(self) -> None: # noqa: N802
1708
+ parsed = urllib.parse.urlsplit(self.path)
1709
+ if parsed.path == "/healthz":
1710
+ healthy = store.healthy()
1711
+ body = json.dumps(
1712
+ {"status": "ok" if healthy else "unavailable"}
1713
+ ).encode("utf-8")
1714
+ self._send(
1715
+ 200 if healthy else 503,
1716
+ body,
1717
+ "application/json; charset=utf-8",
1718
+ )
1719
+ return
1720
+ if parsed.path in {"", "/"}:
1721
+ self.send_response(302)
1722
+ self.send_header("Location", inbox_path)
1723
+ self.send_header("Content-Length", "0")
1724
+ self.end_headers()
1725
+ return
1726
+ parts = [
1727
+ urllib.parse.unquote(part) for part in parsed.path.strip("/").split("/")
1728
+ ]
1729
+ # Defence in depth for the shared-origin topology, where the path is
1730
+ # the only thing separating one trial's inbox from another's.
1731
+ if len(parts) < 2 or parts[0] != "inbox":
1732
+ self._not_found()
1733
+ return
1734
+ if not hmac.compare_digest(token, parts[1]):
1735
+ self._not_found()
1736
+ return
1737
+ try:
1738
+ values = store.messages(namespace)
1739
+ except MailpitInfrastructureError:
1740
+ body = json.dumps({"status": "unavailable"}).encode("utf-8")
1741
+ self._send(503, body, "application/json; charset=utf-8")
1742
+ return
1743
+ if len(parts) == 2:
1744
+ self._send(
1745
+ 200,
1746
+ render_inbox(values, base_path=inbox_path),
1747
+ "text/html; charset=utf-8",
1748
+ )
1749
+ return
1750
+ if len(parts) == 4 and parts[2] == "messages":
1751
+ try:
1752
+ identifier = int(parts[3])
1753
+ except ValueError:
1754
+ self._not_found()
1755
+ return
1756
+ for item in values:
1757
+ if int(item["id"]) == identifier:
1758
+ self._send(
1759
+ 200,
1760
+ render_message(item, base_path=inbox_path),
1761
+ "text/html; charset=utf-8",
1762
+ )
1763
+ return
1764
+ self._not_found()
1765
+
1766
+ def log_message(self, format: str, *args: Any) -> None:
1767
+ return
1768
+
1769
+ return InboxHandler
1770
+
1771
+
1772
+ class LocalMailboxSidecar:
1773
+ """A loopback-only SMTP and Inbox API pair with namespace isolation."""
1774
+
1775
+ def __init__(
1776
+ self,
1777
+ *,
1778
+ smtp_port: int = 0,
1779
+ http_port: int = 0,
1780
+ bind_host: str = "127.0.0.1",
1781
+ inbox_port: int | None = None,
1782
+ inbox_bind_host: str | None = None,
1783
+ inbox_namespace: str | None = None,
1784
+ inbox_token: str | None = None,
1785
+ bootstrap: "_Bootstrap | None" = None,
1786
+ mailpit_client: MailpitClient,
1787
+ ) -> None:
1788
+ self.store = MailboxStore(mailpit_client=mailpit_client)
1789
+ self._bootstrap = _BootstrapSlot(bootstrap)
1790
+ self.smtp = _SmtpServer((bind_host, smtp_port), self.store)
1791
+ self.http = _HttpServer(
1792
+ (bind_host, http_port), _http_handler(self.store, self._bootstrap)
1793
+ )
1794
+ self.inbox: _HttpServer | None = None
1795
+ self._inbox_token = inbox_token
1796
+ if inbox_namespace is not None or inbox_token is not None:
1797
+ if not inbox_namespace or not inbox_token:
1798
+ raise ValueError("an inbox listener needs both namespace and token")
1799
+ self.inbox = _HttpServer(
1800
+ (inbox_bind_host or bind_host, inbox_port or 0),
1801
+ _inbox_handler(self.store, inbox_namespace, inbox_token),
1802
+ )
1803
+ self._threads: list[threading.Thread] = []
1804
+
1805
+ @property
1806
+ def smtp_port(self) -> int:
1807
+ return int(self.smtp.server_address[1])
1808
+
1809
+ @property
1810
+ def http_port(self) -> int:
1811
+ return int(self.http.server_address[1])
1812
+
1813
+ @property
1814
+ def inbox_port(self) -> int:
1815
+ if self.inbox is None:
1816
+ raise RuntimeError("this sidecar has no inbox listener")
1817
+ return int(self.inbox.server_address[1])
1818
+
1819
+ @property
1820
+ def url(self) -> str:
1821
+ return f"http://127.0.0.1:{self.http_port}"
1822
+
1823
+ @property
1824
+ def inbox_url(self) -> str:
1825
+ """The bare origin an agent is handed. It carries no secret."""
1826
+
1827
+ return f"http://127.0.0.1:{self.inbox_port}"
1828
+
1829
+ @property
1830
+ def _servers(self) -> tuple[Any, ...]:
1831
+ return (
1832
+ (self.smtp, self.http)
1833
+ if self.inbox is None
1834
+ else (
1835
+ self.smtp,
1836
+ self.http,
1837
+ self.inbox,
1838
+ )
1839
+ )
1840
+
1841
+ def register_namespace(self, namespace: str, capability: str) -> None:
1842
+ """Bind one opaque namespace to its unguessable per-worker capability."""
1843
+
1844
+ self.store.register(namespace, capability)
1845
+
1846
+ def rotate_bootstrap(self, namespace: str, capability: str) -> None:
1847
+ """Point ``/internal/bootstrap`` at a freshly minted namespace.
1848
+
1849
+ Registration happens first on purpose: a site that fetched the new
1850
+ identity and sent before the store knew it would have its message
1851
+ dropped at the SMTP door, which reads as a flaky mailbox rather than
1852
+ the ordering bug it is.
1853
+ """
1854
+
1855
+ previous = self._bootstrap.get()
1856
+ self.register_namespace(namespace, capability)
1857
+ # Candidate trials route direct SMTP into one fixed namespace. Mirror
1858
+ # that ABI during paired reference capture so runtimes using the direct
1859
+ # writer do not need the structured transport's namespace headers.
1860
+ self.smtp.fixed_namespace = namespace
1861
+ self._bootstrap.rotate(namespace=namespace, capability=capability)
1862
+ if previous is not None and previous.namespace != namespace:
1863
+ self.store.seal_namespace(previous.namespace)
1864
+
1865
+ def start(self) -> "LocalMailboxSidecar":
1866
+ if not self.store.healthy():
1867
+ raise MailpitInfrastructureError("Mailpit is not ready")
1868
+ for server in self._servers:
1869
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
1870
+ thread.start()
1871
+ self._threads.append(thread)
1872
+ return self
1873
+
1874
+ def close(self) -> None:
1875
+ for server in self._servers:
1876
+ server.shutdown()
1877
+ server.server_close()
1878
+ for thread in self._threads:
1879
+ thread.join(timeout=5)
1880
+ self._threads.clear()
1881
+ self.store.destroy_namespaces()
1882
+
1883
+ def __enter__(self) -> "LocalMailboxSidecar":
1884
+ return self.start()
1885
+
1886
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
1887
+ self.close()
1888
+
1889
+
1890
+ class CandidateMailboxTrial:
1891
+ """One formal case's write-only candidate mailbox and trusted reader.
1892
+
1893
+ Candidate code prefers the Resend-style ``POST /emails`` endpoint and may
1894
+ use ``smtp``/``bootstrap`` for compatibility. Both writers are fixed to
1895
+ this trial's namespace. The verifier API listens on a third, unadvertised
1896
+ port that the candidate sandbox does not permit, and it uses a distinct
1897
+ read credential that never enters the candidate environment.
1898
+ """
1899
+
1900
+ def __init__(
1901
+ self,
1902
+ *,
1903
+ bind_host: str = "127.0.0.1",
1904
+ mailpit_client: MailpitClient | None = None,
1905
+ ) -> None:
1906
+ self._runtime = None if mailpit_client is not None else EphemeralMailpit()
1907
+ storage_client = (
1908
+ mailpit_client
1909
+ if mailpit_client is not None
1910
+ else self._runtime.client
1911
+ if self._runtime is not None
1912
+ else None
1913
+ )
1914
+ namespace, read_credential, _inbox_token = _mint_identity()
1915
+ self.namespace = namespace
1916
+ self.read_credential = read_credential
1917
+ self._write_capability = secrets.token_hex(32)
1918
+ self._bootstrap_token = secrets.token_hex(32)
1919
+ self._mail_api_token = secrets.token_hex(32)
1920
+ self._sender = CANDIDATE_MAIL_SENDER
1921
+ self.store = MailboxStore(mailpit_client=storage_client)
1922
+ self.store.register(
1923
+ namespace,
1924
+ read_credential,
1925
+ allowed_from=(self._sender,),
1926
+ )
1927
+ self.smtp = _SmtpServer(
1928
+ (bind_host, 0),
1929
+ self.store,
1930
+ fixed_namespace=namespace,
1931
+ )
1932
+ self.http = _HttpServer(
1933
+ (bind_host, 0),
1934
+ _http_handler(self.store),
1935
+ )
1936
+ self.bootstrap = _HttpServer(
1937
+ (bind_host, 0),
1938
+ _candidate_bootstrap_handler(
1939
+ store=self.store,
1940
+ bootstrap_token=self._bootstrap_token,
1941
+ mail_api_token=self._mail_api_token,
1942
+ namespace=namespace,
1943
+ capability=self._write_capability,
1944
+ smtp_host=bind_host,
1945
+ smtp_port=self.smtp_port,
1946
+ sender=self._sender,
1947
+ ),
1948
+ )
1949
+ self._threads: list[threading.Thread] = []
1950
+
1951
+ @property
1952
+ def smtp_port(self) -> int:
1953
+ return int(self.smtp.server_address[1])
1954
+
1955
+ @property
1956
+ def http_port(self) -> int:
1957
+ return int(self.http.server_address[1])
1958
+
1959
+ @property
1960
+ def bootstrap_port(self) -> int:
1961
+ return int(self.bootstrap.server_address[1])
1962
+
1963
+ @property
1964
+ def url(self) -> str:
1965
+ return f"http://127.0.0.1:{self.http_port}"
1966
+
1967
+ @property
1968
+ def candidate_environment(self) -> dict[str, str]:
1969
+ """The complete optional mail ABI handed to the candidate runtime."""
1970
+
1971
+ return {
1972
+ "WEBSITEBENCH_MAIL_API_URL": (
1973
+ f"http://127.0.0.1:{self.bootstrap_port}/emails"
1974
+ ),
1975
+ "WEBSITEBENCH_MAIL_API_TOKEN": self._mail_api_token,
1976
+ "WEBSITEBENCH_MAIL_FROM": self._sender,
1977
+ "WEBSITEBENCH_SMTP_HOST": "127.0.0.1",
1978
+ "WEBSITEBENCH_SMTP_PORT": str(self.smtp_port),
1979
+ "WEBSITEBENCH_SMTP_FROM": self._sender,
1980
+ # Compatibility seam for candidates using websitebench.site_backend.
1981
+ # It serves write coordinates only and has no read routes.
1982
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL": (
1983
+ f"http://127.0.0.1:{self.bootstrap_port}/internal/bootstrap"
1984
+ ),
1985
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN": self._bootstrap_token,
1986
+ }
1987
+
1988
+ @property
1989
+ def candidate_connect_ports(self) -> frozenset[int]:
1990
+ return frozenset({self.smtp_port, self.bootstrap_port})
1991
+
1992
+ def start(self) -> "CandidateMailboxTrial":
1993
+ if self._runtime is not None:
1994
+ try:
1995
+ self._runtime.start()
1996
+ except BaseException:
1997
+ for server in (self.smtp, self.http, self.bootstrap):
1998
+ server.server_close()
1999
+ raise
2000
+ if not self.store.healthy():
2001
+ for server in (self.smtp, self.http, self.bootstrap):
2002
+ server.server_close()
2003
+ if self._runtime is not None:
2004
+ self._runtime.close()
2005
+ raise MailpitInfrastructureError("Mailpit is not ready")
2006
+ for server in (self.smtp, self.http, self.bootstrap):
2007
+ thread = threading.Thread(
2008
+ target=server.serve_forever,
2009
+ name=f"candidate-mailbox-{server.server_address[1]}",
2010
+ daemon=True,
2011
+ )
2012
+ thread.start()
2013
+ self._threads.append(thread)
2014
+ return self
2015
+
2016
+ def close(self) -> None:
2017
+ for server in (self.smtp, self.http, self.bootstrap):
2018
+ server.shutdown()
2019
+ server.server_close()
2020
+ for thread in self._threads:
2021
+ thread.join(timeout=5)
2022
+ self._threads.clear()
2023
+ self.store.destroy_namespaces()
2024
+ if self._runtime is not None:
2025
+ self._runtime.close()
2026
+
2027
+ def __enter__(self) -> "CandidateMailboxTrial":
2028
+ return self.start()
2029
+
2030
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
2031
+ self.close()
2032
+
2033
+
2034
+ def _candidate_environment_problem(
2035
+ environment: Mapping[str, str], private_values: tuple[str, ...]
2036
+ ) -> str | None:
2037
+ """Return why ``environment`` may not be handed to a candidate, or ``None``.
2038
+
2039
+ The candidate mail ABI is a closed set of names carrying loopback
2040
+ coordinates only. A name outside the set, a Mailpit control variable, or
2041
+ any value naming the evaluator's own Mailpit socket would hand a candidate
2042
+ the trusted store instead of its write-only door.
2043
+ """
2044
+
2045
+ unknown = sorted(set(environment) - CANDIDATE_MAIL_ENVIRONMENT)
2046
+ if unknown:
2047
+ return f"candidate mailbox environment has unknown names: {unknown}"
2048
+ leaked = any(
2049
+ name.startswith("WEBSITEBENCH_MAILPIT_")
2050
+ or MAILPIT_RUNTIME_DIR in str(value)
2051
+ or any(private and private in str(value) for private in private_values)
2052
+ for name, value in environment.items()
2053
+ )
2054
+ if leaked:
2055
+ return "candidate mailbox environment exposed the Mailpit UDS"
2056
+ return None
2057
+
2058
+
2059
+ class MailTrial:
2060
+ """One case's candidate mailbox, as the rest of the evaluator sees it.
2061
+
2062
+ The candidate environment handed out here is already proved to be the
2063
+ closed mail ABI and free of evaluator-side coordinates, so no caller
2064
+ re-scans it. Reads stay on the trusted side: :meth:`deliveries` is the
2065
+ only way out of the store and it never leaves this trial's namespace.
2066
+ """
2067
+
2068
+ def __init__(
2069
+ self,
2070
+ trial: CandidateMailboxTrial,
2071
+ *,
2072
+ private_values: tuple[str, ...] = (),
2073
+ ) -> None:
2074
+ environment = dict(trial.candidate_environment)
2075
+ problem = _candidate_environment_problem(environment, private_values)
2076
+ if problem is not None:
2077
+ trial.close()
2078
+ raise MailpitInfrastructureError(problem)
2079
+ self._trial = trial
2080
+ self._environment = environment
2081
+
2082
+ @property
2083
+ def namespace(self) -> str:
2084
+ return self._trial.namespace
2085
+
2086
+ @property
2087
+ def read_credential(self) -> str:
2088
+ return self._trial.read_credential
2089
+
2090
+ @property
2091
+ def url(self) -> str:
2092
+ """The verifier-only reader origin; the candidate cannot reach it."""
2093
+
2094
+ return self._trial.url
2095
+
2096
+ @property
2097
+ def http_port(self) -> int:
2098
+ return self._trial.http_port
2099
+
2100
+ @property
2101
+ def store(self) -> MailboxStore:
2102
+ return self._trial.store
2103
+
2104
+ @property
2105
+ def candidate_environment(self) -> dict[str, str]:
2106
+ """The complete optional mail ABI this case's candidate receives."""
2107
+
2108
+ return dict(self._environment)
2109
+
2110
+ @property
2111
+ def candidate_connect_ports(self) -> frozenset[int]:
2112
+ """The loopback ports the candidate sandbox may connect out to."""
2113
+
2114
+ return self._trial.candidate_connect_ports
2115
+
2116
+ def healthy(self) -> bool:
2117
+ """Whether the backing store still answers, so an outage is not scored."""
2118
+
2119
+ return self._trial.store.healthy()
2120
+
2121
+ def deliveries(self) -> list[dict[str, Any]]:
2122
+ """Every message this trial's namespace received, newest first."""
2123
+
2124
+ return self._trial.store.messages(self._trial.namespace)
2125
+
2126
+ def close(self) -> None:
2127
+ self._trial.close()
2128
+
2129
+ def __enter__(self) -> "MailTrial":
2130
+ return self
2131
+
2132
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
2133
+ self.close()
2134
+
2135
+
2136
+ class MailPlane:
2137
+ """The evaluator's single door to Mailpit.
2138
+
2139
+ Everything that knows a socket path, a container lifetime, a namespace or
2140
+ the candidate mail ABI lives behind this facade. ``formal``,
2141
+ ``trusted_check`` and ``capture`` ask the plane for a trial, a runner
2142
+ passthrough or an authoring gateway; they never build a Mailpit client,
2143
+ read a Mailpit variable, or inspect what they hand a candidate.
2144
+ """
2145
+
2146
+ def __init__(
2147
+ self, client: MailpitClient, *, runtime: EphemeralMailpit | None = None
2148
+ ) -> None:
2149
+ self.client = client
2150
+ self._runtime = runtime
2151
+
2152
+ @staticmethod
2153
+ def _configured_socket(env: Mapping[str, str]) -> str:
2154
+ """The evaluator's only read of :data:`MAILPIT_HTTP_SOCKET_ENV`."""
2155
+
2156
+ return str(env.get(MAILPIT_HTTP_SOCKET_ENV, "") or "").strip()
2157
+
2158
+ @classmethod
2159
+ def from_environment(cls, env: Mapping[str, str] = os.environ) -> "MailPlane":
2160
+ """Open the Mailpit the environment advertises.
2161
+
2162
+ A missing variable and an unhealthy Mailpit are the same answer to the
2163
+ caller: this process has no mail plane.
2164
+ """
2165
+
2166
+ socket_path = cls._configured_socket(env)
2167
+ if not socket_path:
2168
+ raise MailInfrastructureUnavailable(
2169
+ f"{MAILPIT_HTTP_SOCKET_ENV} is not configured"
2170
+ )
2171
+ client = MailpitClient(socket_path)
2172
+ if not client.ready():
2173
+ raise MailInfrastructureUnavailable(
2174
+ "Mailpit is not ready on its configured HTTP socket"
2175
+ )
2176
+ return cls(client)
2177
+
2178
+ @classmethod
2179
+ def ephemeral(
2180
+ cls, runtime_dir: str | os.PathLike[str] | None = None
2181
+ ) -> "MailPlane":
2182
+ """Start a private, networkless Mailpit this plane owns and will stop.
2183
+
2184
+ Host-side only: a Harbor trial has no Docker binary, so a scored run
2185
+ always goes through :meth:`from_environment` instead.
2186
+ """
2187
+
2188
+ runtime = EphemeralMailpit(runtime_dir=runtime_dir).start()
2189
+ return cls(runtime.client, runtime=runtime)
2190
+
2191
+ @classmethod
2192
+ def open(
2193
+ cls,
2194
+ *,
2195
+ runtime_dir: str | os.PathLike[str] | None = None,
2196
+ env: Mapping[str, str] = os.environ,
2197
+ ) -> "MailPlane":
2198
+ """Prefer the advertised Mailpit; start a private one when there is none."""
2199
+
2200
+ if cls._configured_socket(env):
2201
+ return cls.from_environment(env)
2202
+ return cls.ephemeral(runtime_dir=runtime_dir)
2203
+
2204
+ @property
2205
+ def socket_path(self) -> str:
2206
+ return self.client.socket_path
2207
+
2208
+ @property
2209
+ def owns_runtime(self) -> bool:
2210
+ """Whether closing this plane stops a Mailpit container."""
2211
+
2212
+ return self._runtime is not None
2213
+
2214
+ def healthy(self) -> bool:
2215
+ return self.client.ready()
2216
+
2217
+ def trial(self, *, bind_host: str = "127.0.0.1") -> MailTrial:
2218
+ """Start one case's write-only candidate mailbox on this plane.
2219
+
2220
+ The result is a context manager, so a caller that owns the mailbox for
2221
+ the length of a ``with`` block needs no other cleanup; a caller that
2222
+ owns it for the length of a case calls :meth:`MailTrial.close`.
2223
+ """
2224
+
2225
+ trial = CandidateMailboxTrial(
2226
+ bind_host=bind_host, mailpit_client=self.client
2227
+ ).start()
2228
+ return MailTrial(trial, private_values=(self.socket_path,))
2229
+
2230
+ def runner_environment(self, base: Mapping[str, str]) -> dict[str, str]:
2231
+ """Add to ``base`` exactly what a child verifier runner needs.
2232
+
2233
+ A trusted CI/CD runner is launched with a scrubbed environment and has
2234
+ to find the same Mailpit; that is one variable, and no other mail
2235
+ coordinate crosses the boundary.
2236
+ """
2237
+
2238
+ return {**dict(base), MAILPIT_HTTP_SOCKET_ENV: self.socket_path}
2239
+
2240
+ def authoring_gateway(
2241
+ self,
2242
+ *,
2243
+ namespace: str,
2244
+ capability: str,
2245
+ bootstrap_token: str,
2246
+ smtp_port: int,
2247
+ bind_host: str = "127.0.0.1",
2248
+ ) -> LocalMailboxSidecar:
2249
+ """Expose the stable loopback writer ABI over this plane, for authoring.
2250
+
2251
+ Capture hands a reference site the same SMTP/bootstrap door a scored
2252
+ candidate gets, so what capture exercises is what a trial will run.
2253
+ There is intentionally no in-memory fallback.
2254
+ """
2255
+
2256
+ if not self.client.ready():
2257
+ raise MailInfrastructureUnavailable("Mailpit is not ready for capture")
2258
+ sidecar = LocalMailboxSidecar(
2259
+ smtp_port=smtp_port,
2260
+ bind_host=bind_host,
2261
+ bootstrap=_Bootstrap(
2262
+ token=bootstrap_token,
2263
+ namespace=namespace,
2264
+ capability=capability,
2265
+ smtp_host=bind_host,
2266
+ smtp_port=smtp_port,
2267
+ ),
2268
+ mailpit_client=self.client,
2269
+ )
2270
+ sidecar.register_namespace(namespace, capability)
2271
+ sidecar.start()
2272
+ return sidecar
2273
+
2274
+ def close(self) -> None:
2275
+ runtime, self._runtime = self._runtime, None
2276
+ if runtime is not None:
2277
+ runtime.close()
2278
+
2279
+ def __enter__(self) -> "MailPlane":
2280
+ return self
2281
+
2282
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
2283
+ self.close()
2284
+
2285
+
2286
+ def authoring_environment(
2287
+ sidecar: LocalMailboxSidecar,
2288
+ *,
2289
+ namespace: str,
2290
+ capability: str,
2291
+ bootstrap_token: str,
2292
+ smtp_port: int,
2293
+ smtp_host: str = "127.0.0.1",
2294
+ ) -> dict[str, str]:
2295
+ """The complete mail ABI an authoring capture exports around a reference site.
2296
+
2297
+ It is a superset of the candidate ABI: authoring also owns the read
2298
+ credential and the namespace, which a scored candidate never sees. The
2299
+ names are exactly :data:`AUTHORING_MAIL_ENVIRONMENT`.
2300
+ """
2301
+
2302
+ gateway = sidecar.url.rstrip("/")
2303
+ return {
2304
+ "WEBSITEBENCH_MAILBOX_URL": sidecar.url,
2305
+ "WEBSITEBENCH_MAILBOX_ALLOWLIST": "",
2306
+ "WEBSITEBENCH_MAILBOX_CREDENTIAL": capability,
2307
+ "WEBSITEBENCH_MAILBOX_NAMESPACE": namespace,
2308
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL": f"{gateway}/internal/bootstrap",
2309
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN": bootstrap_token,
2310
+ "WEBSITEBENCH_SMTP_HOST": smtp_host,
2311
+ "WEBSITEBENCH_SMTP_PORT": str(smtp_port),
2312
+ # Paired capture must present the same sender ABI as a formal candidate
2313
+ # trial: some runtimes pin this exact suffix before opening SMTP, so a
2314
+ # site-specific authoring sender would disable their only mail path.
2315
+ "WEBSITEBENCH_MAIL_API_URL": f"{gateway}/emails",
2316
+ "WEBSITEBENCH_MAIL_API_TOKEN": bootstrap_token,
2317
+ "WEBSITEBENCH_MAIL_FROM": CANDIDATE_MAIL_SENDER,
2318
+ "WEBSITEBENCH_SMTP_FROM": CANDIDATE_MAIL_SENDER,
2319
+ }
2320
+
2321
+
2322
+ def _mint_identity() -> tuple[str, str, str]:
2323
+ """Mint one trial's mailbox identity.
2324
+
2325
+ Minted from ``secrets``, never derived from the public ``seed-<seed>``
2326
+ trial ID, while the inbox token doubles as the browser's access token.
2327
+ Determinism is not lost, because scoring reads no mail.
2328
+ """
2329
+
2330
+ return (
2331
+ f"trial-{secrets.token_hex(16)}",
2332
+ secrets.token_hex(32),
2333
+ secrets.token_urlsafe(32),
2334
+ )
2335
+
2336
+
2337
+ def main(argv: list[str] | None = None) -> int:
2338
+ """Run one trial's mailbox, minting that trial's identity at boot.
2339
+
2340
+ ``materialize`` runs once per *bundle*; a trial is one *run* of that
2341
+ bundle, so a value written into ``docker-compose.yaml`` can never be
2342
+ per-trial. The identity is therefore minted here, by the one process that
2343
+ owns it, and each party learns only its own half over the listener it is
2344
+ allowed to reach: the site reads ``/internal/bootstrap`` on the API
2345
+ listener, the agent gets a bare inbox URL and no credential at all.
2346
+
2347
+ The values come from ``secrets`` rather than from the public
2348
+ ``seed-<seed>`` trial ID. Determinism is not lost, because formal scoring
2349
+ never reads mail.
2350
+ """
2351
+
2352
+ import argparse
2353
+
2354
+ parser = argparse.ArgumentParser(prog="websitebench-local-mailbox")
2355
+ parser.add_argument("--smtp-port", type=int, default=1025)
2356
+ parser.add_argument("--http-port", type=int, default=8025)
2357
+ parser.add_argument("--inbox-port", type=int, default=8026)
2358
+ parser.add_argument("--bind-host", default="127.0.0.1")
2359
+ parser.add_argument(
2360
+ "--api-bind-host",
2361
+ default=None,
2362
+ help="interface for the SMTP and JSON API listeners (defaults to --bind-host)",
2363
+ )
2364
+ parser.add_argument(
2365
+ "--inbox-bind-host",
2366
+ default=None,
2367
+ help="interface for the agent inbox listener (defaults to --bind-host)",
2368
+ )
2369
+ args = parser.parse_args(argv)
2370
+
2371
+ api_bind = (
2372
+ args.api_bind_host
2373
+ or os.environ.get("WEBSITEBENCH_MAILBOX_API_BIND")
2374
+ or args.bind_host
2375
+ )
2376
+ inbox_bind = (
2377
+ args.inbox_bind_host
2378
+ or os.environ.get("WEBSITEBENCH_MAILBOX_INBOX_BIND")
2379
+ or args.bind_host
2380
+ )
2381
+ smtp_advertise_host = (
2382
+ os.environ.get("WEBSITEBENCH_MAILBOX_SMTP_ADVERTISE_HOST", "").strip()
2383
+ or api_bind
2384
+ )
2385
+
2386
+ namespace, capability, inbox_token = _mint_identity()
2387
+ bootstrap_token = os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN", "")
2388
+ if len(bootstrap_token) < 32:
2389
+ raise SystemExit(
2390
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN must be at least 32 characters"
2391
+ )
2392
+ try:
2393
+ mailpit_client = MailPlane.from_environment().client
2394
+ except MailInfrastructureUnavailable as error:
2395
+ # The sidecar discovers its store the same way the evaluator does, and
2396
+ # refuses to serve an in-memory production mailbox when there is none.
2397
+ raise SystemExit(f"{error}; refusing an in-memory production mailbox")
2398
+
2399
+ stopped = threading.Event()
2400
+ signal.signal(signal.SIGTERM, lambda _signum, _frame: stopped.set())
2401
+ signal.signal(signal.SIGINT, lambda _signum, _frame: stopped.set())
2402
+ sidecar = LocalMailboxSidecar(
2403
+ smtp_port=args.smtp_port,
2404
+ http_port=args.http_port,
2405
+ bind_host=api_bind,
2406
+ inbox_port=args.inbox_port,
2407
+ inbox_bind_host=inbox_bind,
2408
+ inbox_namespace=namespace,
2409
+ inbox_token=inbox_token,
2410
+ bootstrap=_Bootstrap(
2411
+ token=bootstrap_token,
2412
+ namespace=namespace,
2413
+ capability=capability,
2414
+ smtp_host=smtp_advertise_host,
2415
+ smtp_port=args.smtp_port,
2416
+ ),
2417
+ mailpit_client=mailpit_client,
2418
+ )
2419
+ sidecar.register_namespace(namespace, capability)
2420
+ sidecar.start()
2421
+ # The inbox path is the agent's entry point and holds no secret beyond the
2422
+ # token that scopes it to this trial; nothing else about the trial is
2423
+ # printed, and the capability never is.
2424
+ print(f"inbox listening on {inbox_bind}:{args.inbox_port}", flush=True)
2425
+ try:
2426
+ stopped.wait()
2427
+ finally:
2428
+ sidecar.close()
2429
+ return 0
2430
+
2431
+
2432
+ if __name__ == "__main__":
2433
+ raise SystemExit(main(sys.argv[1:]))
tasks/fandango/environment/reference/.websitebench-reference-tls/ca.crt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIDSzCCAjOgAwIBAgIJV1NCSEFSQk9SMA0GCSqGSIb3DQEBCwUAMDExLzAtBgNV
3
+ BAMMJldlYnNpdGVCZW5jaCBIYXJib3IgTG9jYWwgUmVmZXJlbmNlIENBMB4XDTI2
4
+ MDgyMjEzMDg1NloXDTQ2MDgyMjEzMDg1NlowMTEvMC0GA1UEAwwmV2Vic2l0ZUJl
5
+ bmNoIEhhcmJvciBMb2NhbCBSZWZlcmVuY2UgQ0EwggEiMA0GCSqGSIb3DQEBAQUA
6
+ A4IBDwAwggEKAoIBAQCnBZES7bXJo/hajL5T54GDV/FLmQxmk0dGN+aPwRrgpiN6
7
+ syddg/krh/dhiUzfxgJV+6ajnYuYyQ4BVo1rQGY0va95T8cjcHgC7EyEAaDUZF+i
8
+ qo3v/ucMmquZodezEkghWz6FDcGH3dDtz0bQyYgoGQKnioeYXsVlfvIzXJpE1VTW
9
+ iGUH83/APzvPInZ5jRRrCEnqj1WtSoi+Yycs/eaYueDomoZeT3xvK5MTz6tC6EvW
10
+ hAh8qyv2DjPZUSToiZH23X6qXYRkKkLDXHWHfhamRwlFoh9pp2s4D+Cq/Wke+o2f
11
+ /cj8KvAkTnMo4iMmZFpb/NRaGjhfy8UBPuM7SwMJAgMBAAGjZjBkMB0GA1UdDgQW
12
+ BBQn+U1eizvlvKbfavSxHoXFYQ/UfTAfBgNVHSMEGDAWgBQn+U1eizvlvKbfavSx
13
+ HoXFYQ/UfTASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjANBgkq
14
+ hkiG9w0BAQsFAAOCAQEAoSC3zzZEAs2eigloiDkdeh98+2cPmcs44TG+TU6sq6SP
15
+ EBEgHg/c6yzh74UijEImksT9aZ+LxtTNM+nfNFzWku1T3R7gSimP5TSnC4rTEhfM
16
+ Ih8fMoUbcAe/uFwVE9UHn/QQNsqRg6hg2jdUlmwr206e62/eBQXDNeuLcapAxcdU
17
+ VYno4HNi5gAaakS2dM/IgiorRqM7SVT+s8B9Fl0mzMdRNCUeOOU4q8zGtQGp4IV+
18
+ x/LZIMsLogP2Rpks8ecyanRSXYpGbqpZ+14rcO5bdWQ7P8B/sFssT3b1mR3H/aVh
19
+ yZycwgzCbkbdMaxyz2Vm/c7PVb3so5Xb98jufp2L9A==
20
+ -----END CERTIFICATE-----
tasks/fandango/environment/reference/.websitebench-reference-tls/reference.crt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIDWjCCAkKgAwIBAgIIV1NCUkVGMDEwDQYJKoZIhvcNAQELBQAwMTEvMC0GA1UE
3
+ AwwmV2Vic2l0ZUJlbmNoIEhhcmJvciBMb2NhbCBSZWZlcmVuY2UgQ0EwHhcNMjYw
4
+ ODIyMTMwODU2WhcNNDYwODIyMTMwODU2WjAUMRIwEAYDVQQDDAlyZWZlcmVuY2Uw
5
+ ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDNJXc7onbK78RiLSAe3LjI
6
+ eko9xNumYRejoB+kKFGLBL4U7vY+02coiXpne4e1CMzUVzRiaQ9i9XHBe0Oq4CR1
7
+ HW7wzMRV8XVM5/dVq+j0vZVarZbITyHSWHwypa7yPL7o/kBekdwi8ncdUy/mhYqw
8
+ 7sOdM4Nq0ifj+lcJ/rwSqjvcML4//4THY9CP5iB2YT+U+Z7F/JfLOJFZ12l4Sglx
9
+ RDf1awDLJpGfpX0kRgW7jYuWf49C5VcPjggTRl1WYy1qrgaNIFu75sresXYkDgRx
10
+ uLiXfc/6wNwykh9fQo+GNFqBGy2lC8Ey425m4XEROraenAGMqVMfxJsJ5wjqRhlV
11
+ AgMBAAGjgZIwgY8wDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCBaAwEwYDVR0l
12
+ BAwwCgYIKwYBBQUHAwEwGgYDVR0RBBMwEYIJcmVmZXJlbmNlhwR/AAABMB0GA1Ud
13
+ DgQWBBQ0EtbLFU1HI9Wdikc8qRx8TdRT8TAfBgNVHSMEGDAWgBQn+U1eizvlvKbf
14
+ avSxHoXFYQ/UfTANBgkqhkiG9w0BAQsFAAOCAQEATXVQdAfuOvbbsBhNHCvfoYuM
15
+ rgnUOdAHevutvg/gPe6AcshAJMvvfL6J/TpimY+TKDqVBVs0qB6jXjgZURQ9EsFR
16
+ WDJywamDHAFNTTuq1A+78VAS3LK3z54JH2BRlvtjnEDkzDei0/brOentce73YwVR
17
+ XU6+y/yGlSYGdq63wzDxBOUwD/I/src9WpmYqrSwstlD1epemMUIsfDpfSRcGYM2
18
+ tB+zMBccmP/hrB3eJcrjiediwhSBNJjdKysK66GzFRqcyGwwvsz1YPbWcpcQXoVZ
19
+ nnNXEs5TrxTj67/DLuP/233oEoz2XQNh1O2ohq1o5JMu4hbotqkepCwcidNBmQ==
20
+ -----END CERTIFICATE-----
tasks/fandango/environment/reference/.websitebench-reference-tls/reference.key ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN PRIVATE KEY-----
2
+ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDNJXc7onbK78Ri
3
+ LSAe3LjIeko9xNumYRejoB+kKFGLBL4U7vY+02coiXpne4e1CMzUVzRiaQ9i9XHB
4
+ e0Oq4CR1HW7wzMRV8XVM5/dVq+j0vZVarZbITyHSWHwypa7yPL7o/kBekdwi8ncd
5
+ Uy/mhYqw7sOdM4Nq0ifj+lcJ/rwSqjvcML4//4THY9CP5iB2YT+U+Z7F/JfLOJFZ
6
+ 12l4SglxRDf1awDLJpGfpX0kRgW7jYuWf49C5VcPjggTRl1WYy1qrgaNIFu75sre
7
+ sXYkDgRxuLiXfc/6wNwykh9fQo+GNFqBGy2lC8Ey425m4XEROraenAGMqVMfxJsJ
8
+ 5wjqRhlVAgMBAAECggEAIdiyWyGzKUjVVSBeWhEvII6CpL3Pwpvmz02KIuavC3l5
9
+ FhGWCagN71N9YUjxizYcO1V29FyimABoaBR7BdyMz1DPnsWeCBL6ODnWZilimkyU
10
+ MX2N8NcTfLWyKhYJbviERAM84g19LTvlWK6Cqu0yBH6kQhG/dzacs8G4LhM7+vUU
11
+ +43RFW4GFmYDXtfUEZuZ8IRzWxDdXQ9yVnKxKrhuYj4/UYgTTspOx87m++Ft6BJR
12
+ IQRw1dZ7dE2R8pZbYQdOXRXSjf59KisJSr9N2+mYZYNUWWv7zF8bmD17hxtsQk9C
13
+ wesyN3DqzoLHK3GfoG3ZuA+v3aEVKHRk8Tc1aosYyQKBgQD0ddALajm0XHictsG3
14
+ /JTC1RL0nj+SoVVgYdWccA7VUs68Cbpq1RYzUawDOhYlQjbJBJTQ9z5kwWP+50vH
15
+ VPjpU/cMFx4d63WwDEXcC2o09mh3OjkfujUdRroyn6rJgKXuSJeMAz0JrGCTIS91
16
+ 0t2cmoSqKSIaN2oU5IsONLg6SQKBgQDW1JBCiP1c6tYi9wKpEJLjlRqSIsLgLApg
17
+ h6o1sWFfUrbQ21ORS1jhLnCkJsyLWoyZkUgwaXbXoLoVw3kIdPLJ8TI1FJ+ZPYdt
18
+ EJcvvVjmJIrcq9um1qoKKpmiKuwRe4/OYdFQcdTRwob1wpoAi7T9CfiNgo53WHsR
19
+ mviPzSEGrQKBgQDnpL+YIXc+niU4MsFL6463NBq7Kz0IX9I7+1jj3RdhMw9tBTbd
20
+ Rr+7r1d001Tqx1yMjMfLX42DAfIUN+4Jm04mIwdFMJ68MUMap/aGtVZVi2ygFc7N
21
+ brAn5r5HfB7kw//31FeuN99dzDbTFC4Z0s9mNtEhQMrs1rexxoKx2mj76QKBgBi5
22
+ AZkGltG4nMgNURsPszfJkvM6WN7fcppFQotHTINhy3QhqW5RE3tmksPxSxzGYOPT
23
+ WlFn8atC7edPRYB5pO8keLivFObXs9wTSrLNwYtKrUhT5sU+cvcUi/WjpuMkKxp/
24
+ G018rBcvocRqjrp9WWi9WwM+ARMu9YrDINO7sY9JAoGBAJlTUtKVOOuaujK53Vnq
25
+ 2O5FrC/HcsUa1nTRO/WSDyUjGWeqAr75yi05UD6M2tTov1uGbtg47Q5n6eqjVyy3
26
+ FTYmG+lVbVXjVcOFuUhZxJhELsHulsJ1LRPAJccC0Uci8IZ8rfIZyREn7tKpBJI4
27
+ 4s+BQ5R45Cv3eUi2JU/xuAtK
28
+ -----END PRIVATE KEY-----
tasks/fandango/environment/reference/.websitebench-reference-tls/tls_proxy.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Terminate trusted local TLS in front of a Harbor reference process.
2
+
3
+ The reference application's own launch contract remains HTTP on loopback. The
4
+ Agent-facing Docker service is HTTPS only, so Secure ``__Host-`` cookies have
5
+ the same browser semantics as the source site without changing clone code.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import contextlib
12
+ import os
13
+ import signal
14
+ import ssl
15
+ import subprocess
16
+ import sys
17
+ from pathlib import Path
18
+
19
+
20
+ BUFFER_SIZE = 64 * 1024
21
+ STARTUP_TIMEOUT_SECONDS = 30.0
22
+
23
+
24
+ async def _copy_stream(
25
+ reader: asyncio.StreamReader,
26
+ writer: asyncio.StreamWriter,
27
+ ) -> None:
28
+ while block := await reader.read(BUFFER_SIZE):
29
+ writer.write(block)
30
+ await writer.drain()
31
+
32
+
33
+ async def _forward(
34
+ client_reader: asyncio.StreamReader,
35
+ client_writer: asyncio.StreamWriter,
36
+ *,
37
+ upstream_port: int,
38
+ ) -> None:
39
+ try:
40
+ upstream_reader, upstream_writer = await asyncio.open_connection(
41
+ "127.0.0.1", upstream_port
42
+ )
43
+ except OSError:
44
+ client_writer.close()
45
+ await client_writer.wait_closed()
46
+ return
47
+
48
+ tasks = {
49
+ asyncio.create_task(_copy_stream(client_reader, upstream_writer)),
50
+ asyncio.create_task(_copy_stream(upstream_reader, client_writer)),
51
+ }
52
+ try:
53
+ _done, pending = await asyncio.wait(
54
+ tasks, return_when=asyncio.FIRST_COMPLETED
55
+ )
56
+ for task in pending:
57
+ task.cancel()
58
+ await asyncio.gather(*tasks, return_exceptions=True)
59
+ finally:
60
+ upstream_writer.close()
61
+ client_writer.close()
62
+ with contextlib.suppress(OSError):
63
+ await upstream_writer.wait_closed()
64
+ with contextlib.suppress(OSError):
65
+ await client_writer.wait_closed()
66
+
67
+
68
+ async def _wait_for_upstream(process: subprocess.Popen[bytes], port: int) -> None:
69
+ loop = asyncio.get_running_loop()
70
+ deadline = loop.time() + STARTUP_TIMEOUT_SECONDS
71
+ while loop.time() < deadline:
72
+ return_code = process.poll()
73
+ if return_code is not None:
74
+ raise RuntimeError(
75
+ f"reference process exited before readiness with {return_code}"
76
+ )
77
+ try:
78
+ _reader, writer = await asyncio.open_connection("127.0.0.1", port)
79
+ except OSError:
80
+ await asyncio.sleep(0.1)
81
+ continue
82
+ writer.close()
83
+ await writer.wait_closed()
84
+ return
85
+ raise TimeoutError("reference process did not open its loopback port")
86
+
87
+
88
+ async def _terminate(process: subprocess.Popen[bytes]) -> None:
89
+ if process.poll() is not None:
90
+ return
91
+ process.terminate()
92
+ try:
93
+ await asyncio.wait_for(asyncio.to_thread(process.wait), timeout=10.0)
94
+ except TimeoutError:
95
+ process.kill()
96
+ await asyncio.to_thread(process.wait)
97
+
98
+
99
+ async def _serve(command: list[str]) -> int:
100
+ external_port = int(os.environ.get("PORT", "8080"))
101
+ upstream_port = int(
102
+ os.environ.get("WEBSITEBENCH_REFERENCE_UPSTREAM_PORT", "18080")
103
+ )
104
+ if external_port == upstream_port:
105
+ raise ValueError("reference TLS and upstream ports must differ")
106
+
107
+ child_environment = dict(os.environ)
108
+ child_environment["HOST"] = "127.0.0.1"
109
+ child_environment["PORT"] = str(upstream_port)
110
+ process = subprocess.Popen(command, env=child_environment)
111
+ server: asyncio.AbstractServer | None = None
112
+ try:
113
+ await _wait_for_upstream(process, upstream_port)
114
+ tls_root = Path(__file__).resolve().parent
115
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
116
+ context.minimum_version = ssl.TLSVersion.TLSv1_2
117
+ context.load_cert_chain(
118
+ certfile=tls_root / "reference.crt",
119
+ keyfile=tls_root / "reference.key",
120
+ )
121
+ server = await asyncio.start_server(
122
+ lambda reader, writer: _forward(
123
+ reader, writer, upstream_port=upstream_port
124
+ ),
125
+ "0.0.0.0",
126
+ external_port,
127
+ ssl=context,
128
+ )
129
+ print(
130
+ "WebsiteBench reference HTTPS ready on "
131
+ f"0.0.0.0:{external_port}; upstream=127.0.0.1:{upstream_port}",
132
+ flush=True,
133
+ )
134
+
135
+ stop = asyncio.Event()
136
+ loop = asyncio.get_running_loop()
137
+ for signum in (signal.SIGINT, signal.SIGTERM):
138
+ loop.add_signal_handler(signum, stop.set)
139
+ process_wait = asyncio.create_task(asyncio.to_thread(process.wait))
140
+ stop_wait = asyncio.create_task(stop.wait())
141
+ done, pending = await asyncio.wait(
142
+ {process_wait, stop_wait}, return_when=asyncio.FIRST_COMPLETED
143
+ )
144
+ for task in pending:
145
+ task.cancel()
146
+ await asyncio.gather(*pending, return_exceptions=True)
147
+ if process_wait in done:
148
+ return process_wait.result()
149
+ return 0
150
+ finally:
151
+ if server is not None:
152
+ server.close()
153
+ await server.wait_closed()
154
+ await _terminate(process)
155
+
156
+
157
+ def main() -> int:
158
+ if len(sys.argv) < 2:
159
+ raise SystemExit("usage: tls_proxy.py COMMAND [ARG ...]")
160
+ return asyncio.run(_serve(sys.argv[1:]))
161
+
162
+
163
+ if __name__ == "__main__":
164
+ raise SystemExit(main())
tasks/fandango/environment/reference/Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12.11-slim-bookworm@sha256:519591d6871b7bc437060736b9f7456b8731f1499a57e22e6c285135ae657bf7
2
+ WORKDIR /srv/reference
3
+ # BEGIN WebsiteBench runtime dependencies
4
+ COPY --from=ghcr.io/astral-sh/uv:0.12.8@sha256:d1cbaeadc234fe19c0d93daabcf5e98738cd93c6d1dd4918ef6aa30735feb23a /uv /usr/local/bin/uv
5
+ COPY vendor.requirements.lock vendor.requirements.lock
6
+ RUN uv pip install --python /usr/local/bin/python --no-cache --no-deps --require-hashes --only-binary :all: --link-mode copy --target vendor -r vendor.requirements.lock && rm -f vendor/.lock
7
+ # END WebsiteBench runtime dependencies
8
+ COPY . .
9
+ ENV HOST=0.0.0.0 PORT=8080 DATA_DIR=/tmp/websitebench-fandango-reference-data SEED=0 TZ=UTC
10
+ RUN ./compile.sh
11
+ HEALTHCHECK --interval=2s --timeout=3s --retries=30 CMD python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/healthz', timeout=2)"
12
+ CMD ["./executable"]
13
+
14
+ # Added by the WebsiteBench Harbor materializer. The original app runs only on loopback; the Agent-facing reference is trusted HTTPS.
15
+ COPY .websitebench-reference-tls/ /opt/websitebench/reference-tls/
16
+ RUN chmod 600 /opt/websitebench/reference-tls/reference.key && chmod 755 /opt/websitebench/reference-tls/tls_proxy.py
17
+ ENV WEBSITEBENCH_REFERENCE_UPSTREAM_PORT=18080
18
+ HEALTHCHECK --interval=2s --timeout=3s --retries=30 CMD python3 -c "import os,ssl,urllib.request as r;c=ssl.create_default_context(cafile='/opt/websitebench/reference-tls/ca.crt');u='https://127.0.0.1:'+os.environ.get('PORT','8080')+'/healthz';r.urlopen(u,context=c,timeout=2).close()"
19
+ CMD ["python3", "/opt/websitebench/reference-tls/tls_proxy.py", "./run.sh"]
tasks/fandango/environment/reference/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Fandango direct reference adapter
2
+
3
+ The frozen clone and its generated backend are projected beside this overlay.
4
+ The adapter changes no route and no persistence: it fixes the health response,
5
+ publishes the site, database and migration proof headers every scored case
6
+ reads, and declares the payment and mail profiles this site actually runs
7
+ with. This clone has no reachable mail-producing flow -- its verification
8
+ codes never leave the process -- so the task disables the generated mail
9
+ capability rather than pretending a Mailpit writer exists.
tasks/fandango/environment/reference/backend/model.json ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "offline-clone.backend-model.v1",
3
+ "site_id": "fandango",
4
+ "status": "draft",
5
+ "profile": "offline-benchmark",
6
+ "database": {
7
+ "engine": "sqlite",
8
+ "location_policy": "runtime-data-outside-candidate",
9
+ "concurrency_model": "wal-transactional-single-writer",
10
+ "migration_strategy": "versioned-forward-migrations",
11
+ "deterministic_reset": true,
12
+ "restart_persistence": true,
13
+ "site_isolation": "one-database-per-site",
14
+ "proofs": [
15
+ {
16
+ "obligation": "data-location",
17
+ "status": "planned",
18
+ "evidence": []
19
+ },
20
+ {
21
+ "obligation": "schema-migration",
22
+ "status": "planned",
23
+ "evidence": []
24
+ },
25
+ {
26
+ "obligation": "deterministic-reset",
27
+ "status": "planned",
28
+ "evidence": []
29
+ },
30
+ {
31
+ "obligation": "restart-persistence",
32
+ "status": "planned",
33
+ "evidence": []
34
+ },
35
+ {
36
+ "obligation": "backup-restore",
37
+ "status": "planned",
38
+ "evidence": []
39
+ },
40
+ {
41
+ "obligation": "concurrency",
42
+ "status": "planned",
43
+ "evidence": []
44
+ }
45
+ ]
46
+ },
47
+ "auth_semantics": {
48
+ "account_database_scope": "site-isolated",
49
+ "credential_storage": "salted-scrypt-hash",
50
+ "session_storage": "opaque-cookie-digest-at-rest",
51
+ "registration_account_creation": "direct-password",
52
+ "verification_challenge_storage": "not-applicable",
53
+ "password_reset_enumeration": "not-applicable",
54
+ "mail_default": "LOCAL_ONLY",
55
+ "mail_statuses": [
56
+ "LOCAL_ONLY",
57
+ "SMTP_PENDING",
58
+ "SMTP_SENT",
59
+ "SMTP_FAILED"
60
+ ],
61
+ "smtp_activation": "explicit-complete-config-only",
62
+ "smtp_delivery_ceiling": 3,
63
+ "rejected_secret_journaling": "forbidden",
64
+ "legacy_write_policy": "read-compatible-write-rejected"
65
+ },
66
+ "common_capabilities": {
67
+ "account_registration": "account-registration",
68
+ "account_sign_in": "account-sign-in",
69
+ "session_lifecycle": "session-lifecycle",
70
+ "password_recovery": "password-recovery",
71
+ "email_delivery": "email-delivery"
72
+ },
73
+ "capabilities": [
74
+ {
75
+ "id": "account-registration",
76
+ "label": "Direct local account registration",
77
+ "priority": "p1",
78
+ "category": "authentication",
79
+ "implementation_status": "implemented",
80
+ "semantic_profile": "local-account-registration-v1",
81
+ "external_effect": "local-only",
82
+ "journey_ids": [
83
+ "account.lifecycle"
84
+ ],
85
+ "invariant_ids": [
86
+ "actor.isolation"
87
+ ],
88
+ "proofs": {
89
+ "evidence": {},
90
+ "planned": [
91
+ "valid",
92
+ "invalid",
93
+ "duplicate",
94
+ "stale",
95
+ "foreign-owner",
96
+ "unauthorized-role",
97
+ "restart",
98
+ "migration",
99
+ "concurrency"
100
+ ],
101
+ "not_applicable": []
102
+ }
103
+ },
104
+ {
105
+ "id": "account-sign-in",
106
+ "label": "Local account sign-in",
107
+ "priority": "p1",
108
+ "category": "authentication",
109
+ "implementation_status": "implemented",
110
+ "semantic_profile": "local-account-sign-in-v1",
111
+ "external_effect": "local-only",
112
+ "journey_ids": [
113
+ "account.lifecycle"
114
+ ],
115
+ "invariant_ids": [
116
+ "actor.isolation"
117
+ ],
118
+ "proofs": {
119
+ "evidence": {},
120
+ "planned": [
121
+ "valid",
122
+ "invalid",
123
+ "duplicate",
124
+ "stale",
125
+ "foreign-owner",
126
+ "unauthorized-role",
127
+ "restart",
128
+ "migration",
129
+ "concurrency"
130
+ ],
131
+ "not_applicable": []
132
+ }
133
+ },
134
+ {
135
+ "id": "session-lifecycle",
136
+ "label": "Opaque local session lifecycle",
137
+ "priority": "p1",
138
+ "category": "authentication",
139
+ "implementation_status": "implemented",
140
+ "semantic_profile": "local-session-lifecycle-v1",
141
+ "external_effect": "local-only",
142
+ "journey_ids": [
143
+ "account.lifecycle"
144
+ ],
145
+ "invariant_ids": [
146
+ "actor.isolation"
147
+ ],
148
+ "proofs": {
149
+ "evidence": {},
150
+ "planned": [
151
+ "valid",
152
+ "invalid",
153
+ "duplicate",
154
+ "stale",
155
+ "foreign-owner",
156
+ "unauthorized-role",
157
+ "restart",
158
+ "migration",
159
+ "concurrency"
160
+ ],
161
+ "not_applicable": []
162
+ }
163
+ },
164
+ {
165
+ "id": "password-recovery",
166
+ "label": "Password recovery preview that sends nothing",
167
+ "priority": "p1",
168
+ "category": "authentication",
169
+ "implementation_status": "implemented",
170
+ "semantic_profile": "local-password-recovery-v1",
171
+ "external_effect": "local-only",
172
+ "journey_ids": [
173
+ "account.lifecycle"
174
+ ],
175
+ "invariant_ids": [
176
+ "actor.isolation"
177
+ ],
178
+ "proofs": {
179
+ "evidence": {},
180
+ "planned": [
181
+ "valid",
182
+ "invalid",
183
+ "duplicate",
184
+ "stale",
185
+ "foreign-owner",
186
+ "unauthorized-role",
187
+ "restart",
188
+ "migration",
189
+ "concurrency"
190
+ ],
191
+ "not_applicable": []
192
+ }
193
+ },
194
+ {
195
+ "id": "email-delivery",
196
+ "label": "Local outbox with no SMTP egress",
197
+ "priority": "p1",
198
+ "category": "authentication",
199
+ "implementation_status": "implemented",
200
+ "semantic_profile": "local-mail-delivery-v1",
201
+ "external_effect": "local-only",
202
+ "journey_ids": [
203
+ "account.lifecycle"
204
+ ],
205
+ "invariant_ids": [
206
+ "actor.isolation"
207
+ ],
208
+ "proofs": {
209
+ "evidence": {},
210
+ "planned": [
211
+ "valid",
212
+ "invalid",
213
+ "duplicate",
214
+ "stale",
215
+ "foreign-owner",
216
+ "unauthorized-role",
217
+ "restart",
218
+ "migration",
219
+ "concurrency"
220
+ ],
221
+ "not_applicable": []
222
+ }
223
+ }
224
+ ]
225
+ }
tasks/fandango/environment/reference/backend/runtime.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "database": {
3
+ "data_dir": "data",
4
+ "engine": "sqlite",
5
+ "filename": "fandango.sqlite3",
6
+ "legacy_unbound_migration": false,
7
+ "migration_hook": null,
8
+ "seed_hook": null
9
+ },
10
+ "deployment": {
11
+ "profiles": {
12
+ "cloudflare-review": {
13
+ "mail_adapter": "redis-resend",
14
+ "payment_adapter": "local-sandbox",
15
+ "persistence": "ephemeral-reset"
16
+ },
17
+ "docker-volume": {
18
+ "mail_adapter": "effects-gateway",
19
+ "payment_adapter": "local-sandbox",
20
+ "persistence": "persistent-volume"
21
+ },
22
+ "offline-harbor": {
23
+ "mail_adapter": "local-outbox",
24
+ "payment_adapter": "local-sandbox",
25
+ "persistence": "persistent"
26
+ }
27
+ }
28
+ },
29
+ "mail": {
30
+ "enabled": false,
31
+ "purposes": {},
32
+ "sender": {
33
+ "address_env": "RESEND_FROM_EMAIL",
34
+ "display_name": "Fandango"
35
+ }
36
+ },
37
+ "payments": {
38
+ "currency": "USD",
39
+ "default_adapter": "local-sandbox",
40
+ "enabled": false,
41
+ "local_sandbox": {
42
+ "scenarios": [
43
+ {
44
+ "display_label": "Simulated approval",
45
+ "id": "sandbox-approved",
46
+ "outcome": "approved"
47
+ },
48
+ {
49
+ "display_label": "Simulated decline",
50
+ "id": "sandbox-declined",
51
+ "outcome": "declined"
52
+ },
53
+ {
54
+ "display_label": "Simulated retry",
55
+ "id": "sandbox-retry",
56
+ "outcome": "retryable"
57
+ }
58
+ ]
59
+ },
60
+ "stripe_test": null
61
+ },
62
+ "schema_version": "websitebench.site-backend-runtime.v1",
63
+ "session": {
64
+ "host_only": true,
65
+ "http_only": true,
66
+ "same_site": "Lax",
67
+ "secure": true
68
+ },
69
+ "site": {
70
+ "id": "fandango",
71
+ "label": "Fandango",
72
+ "public_origin": "https://fandango.offline.invalid"
73
+ }
74
+ }
tasks/fandango/environment/reference/clone/app.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stateful, no-external-effects Fandango WebsiteBench clone."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from fastapi import FastAPI, Request
10
+ from fastapi.responses import HTMLResponse, JSONResponse, Response
11
+ from starlette.staticfiles import StaticFiles
12
+
13
+ from backend import store
14
+ from websitebench.local_clone_auth import AuthError
15
+
16
+
17
+ SITE_ID = "fandango"
18
+ ROOT = Path(__file__).resolve().parent
19
+ STATIC = ROOT / "static"
20
+ INDEX = ROOT / "frontend" / "index.html"
21
+
22
+ app = FastAPI(title="Fandango offline clone", docs_url=None, redoc_url=None, openapi_url=None)
23
+ app.mount("/static", StaticFiles(directory=str(STATIC)), name="static")
24
+
25
+ CSP = (
26
+ "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; "
27
+ "script-src 'self'; connect-src 'self'; font-src 'self' data:; frame-ancestors 'none'; "
28
+ "base-uri 'self'; form-action 'self'"
29
+ )
30
+
31
+
32
+ @app.middleware("http")
33
+ async def headers(request: Request, call_next):
34
+ response = await call_next(request)
35
+ response.headers["Content-Security-Policy"] = CSP
36
+ response.headers["Referrer-Policy"] = "no-referrer"
37
+ response.headers["X-Content-Type-Options"] = "nosniff"
38
+ response.headers["X-Frame-Options"] = "DENY"
39
+ return response
40
+
41
+
42
+ def actor(request: Request) -> tuple[str, str, dict[str, Any]]:
43
+ actor_id = request.cookies.get("wb_fandango_actor") or store.new_actor()
44
+ token, session = store.ensure_auth_session(request.cookies.get("wb_fandango_auth"))
45
+ return actor_id, token, session
46
+
47
+
48
+ def attach(response: Response, request: Request, actor_id: str, token: str) -> Response:
49
+ secure = request.url.scheme == "https"
50
+ response.set_cookie("wb_fandango_actor", actor_id, httponly=True, samesite="lax", secure=secure, max_age=2592000)
51
+ response.set_cookie("wb_fandango_auth", token, httponly=True, samesite="lax", secure=secure, max_age=2592000)
52
+ return response
53
+
54
+
55
+ def payload(data: Any, request: Request, status: int = 200) -> JSONResponse:
56
+ actor_id, token, _ = actor(request)
57
+ return attach(JSONResponse(data, status_code=status), request, actor_id, token)
58
+
59
+
60
+ async def body(request: Request) -> dict[str, Any]:
61
+ try:
62
+ value = await request.json()
63
+ except Exception:
64
+ return {}
65
+ return value if isinstance(value, dict) else {}
66
+
67
+
68
+ def error(message: str, request: Request, status: int = 422) -> JSONResponse:
69
+ return payload({"error": message}, request, status)
70
+
71
+
72
+ @app.get("/healthz", include_in_schema=False)
73
+ async def health() -> dict[str, Any]:
74
+ return {"ok": True, "site_id": SITE_ID}
75
+
76
+
77
+ @app.get("/api/bootstrap")
78
+ async def bootstrap(request: Request) -> JSONResponse:
79
+ actor_id, token, session = actor(request)
80
+ return attach(JSONResponse(store.bootstrap(actor_id, session.get("account"))), request, actor_id, token)
81
+
82
+
83
+ @app.get('/api/navigation/state')
84
+ async def navigation_state(request: Request) -> JSONResponse:
85
+ actor_id, token, _ = actor(request)
86
+ return attach(JSONResponse(store.navigation_state(actor_id)), request, actor_id, token)
87
+
88
+
89
+ @app.post('/api/navigation/state')
90
+ async def update_navigation(request: Request) -> JSONResponse:
91
+ actor_id, token, _ = actor(request)
92
+ try:
93
+ result = store.update_navigation(actor_id, await body(request))
94
+ except ValueError as exc:
95
+ return error(str(exc), request)
96
+ return attach(JSONResponse(result), request, actor_id, token)
97
+
98
+
99
+ @app.get("/api/movies")
100
+ async def movies(request: Request, q: str = "", genre: str = "", sort: str = "rating", max_price: float | None = None,
101
+ service: str = "", status: str = "", theater: str = "") -> JSONResponse:
102
+ actor_id, token, _ = actor(request)
103
+ rows = store.search(q, genre, sort, max_price, service, status, theater)
104
+ return attach(
105
+ JSONResponse({"movies": rows, "query": q, "genres": store.genres(), "theaters": store.THEATERS}),
106
+ request, actor_id, token,
107
+ )
108
+
109
+
110
+ @app.get("/api/theaters")
111
+ async def theaters(request: Request, date: str = "") -> JSONResponse:
112
+ actor_id, token, _ = actor(request)
113
+ return attach(
114
+ JSONResponse({
115
+ "theaters": store.theater_directory(date),
116
+ "dates": store.showtime_dates(),
117
+ "date": date if store.valid_date(date) else store.upcoming_friday(),
118
+ }),
119
+ request, actor_id, token,
120
+ )
121
+
122
+
123
+ @app.get("/api/movies/{movie_id}")
124
+ async def movie(movie_id: str, request: Request, date: str = "") -> JSONResponse:
125
+ row = store.movie(movie_id, date)
126
+ if not row:
127
+ return error("Movie not found", request, 404)
128
+ return payload({"movie": row, "dates": store.showtime_dates(),
129
+ "date": date if store.valid_date(date) else store.upcoming_friday()}, request)
130
+
131
+
132
+ @app.post("/api/favorites/{movie_id}")
133
+ async def favorite(movie_id: str, request: Request) -> JSONResponse:
134
+ actor_id, token, _ = actor(request)
135
+ try:
136
+ result = store.toggle_favorite(actor_id, movie_id)
137
+ except KeyError:
138
+ return attach(JSONResponse({"error": "Movie not found"}, status_code=404), request, actor_id, token)
139
+ return attach(JSONResponse(result), request, actor_id, token)
140
+
141
+
142
+ @app.post("/api/selection/showtime")
143
+ async def showtime(request: Request) -> JSONResponse:
144
+ actor_id, token, _ = actor(request)
145
+ data = await body(request)
146
+ try:
147
+ result = store.select_showtime(actor_id, str(data.get("movie_id", "")), str(data.get("theater_id", "")), str(data.get("showtime_id", "")), str(data.get("date", "")))
148
+ except ValueError as exc:
149
+ return attach(JSONResponse({"error": str(exc)}, status_code=422), request, actor_id, token)
150
+ return attach(JSONResponse(result, status_code=201), request, actor_id, token)
151
+
152
+
153
+ @app.post("/api/selection/tickets")
154
+ async def tickets(request: Request) -> JSONResponse:
155
+ actor_id, token, _ = actor(request)
156
+ data = await body(request)
157
+ try:
158
+ result = store.set_tickets(actor_id, int(data.get("adults", 0)), int(data.get("children", 0)), int(data.get("seniors", 0)))
159
+ except (ValueError, TypeError) as exc:
160
+ return attach(JSONResponse({"error": str(exc)}, status_code=422), request, actor_id, token)
161
+ return attach(JSONResponse(result), request, actor_id, token)
162
+
163
+
164
+ @app.post("/api/selection/seats")
165
+ async def seats(request: Request) -> JSONResponse:
166
+ actor_id, token, _ = actor(request)
167
+ data = await body(request)
168
+ try:
169
+ result = store.set_seats(actor_id, [str(value) for value in data.get("seats", [])])
170
+ except (ValueError, TypeError) as exc:
171
+ return attach(JSONResponse({"error": str(exc)}, status_code=422), request, actor_id, token)
172
+ return attach(JSONResponse(result), request, actor_id, token)
173
+
174
+
175
+ @app.post("/api/checkout/review")
176
+ async def checkout_review(request: Request) -> JSONResponse:
177
+ actor_id, token, _ = actor(request)
178
+ data = await body(request)
179
+ try:
180
+ result = store.review(actor_id, str(data.get("email", "")), str(data.get("postal_code", "")))
181
+ except ValueError as exc:
182
+ return attach(JSONResponse({"error": str(exc)}, status_code=422), request, actor_id, token)
183
+ return attach(JSONResponse(result), request, actor_id, token)
184
+
185
+
186
+ @app.post("/api/checkout/confirm")
187
+ async def checkout_confirm(request: Request) -> JSONResponse:
188
+ actor_id, token, _ = actor(request)
189
+ try:
190
+ result = store.confirm(actor_id)
191
+ except ValueError as exc:
192
+ return attach(JSONResponse({"error": str(exc)}, status_code=422), request, actor_id, token)
193
+ return attach(JSONResponse(result, status_code=201), request, actor_id, token)
194
+
195
+
196
+ @app.post("/api/bookings/{booking_id}/{action}")
197
+ async def booking_action(booking_id: str, action: str, request: Request) -> JSONResponse:
198
+ actor_id, token, _ = actor(request)
199
+ data = await body(request)
200
+ try:
201
+ result = store.update_booking(actor_id, booking_id, action, data.get("value"))
202
+ except KeyError:
203
+ return attach(JSONResponse({"error": "Booking not found"}, status_code=404), request, actor_id, token)
204
+ except ValueError as exc:
205
+ return attach(JSONResponse({"error": str(exc)}, status_code=422), request, actor_id, token)
206
+ return attach(JSONResponse(result), request, actor_id, token)
207
+
208
+
209
+ @app.post("/api/auth/register")
210
+ async def register(request: Request) -> JSONResponse:
211
+ actor_id, token, _ = actor(request)
212
+ data = await body(request)
213
+ try:
214
+ store.register(str(data.get("display_name", "")), str(data.get("email", "")), str(data.get("password", "")))
215
+ signed = store.login(token, str(data.get("email", "")), str(data.get("password", "")))
216
+ except (AuthError, ValueError) as exc:
217
+ return attach(JSONResponse({"error": str(exc)}, status_code=422), request, actor_id, token)
218
+ return attach(
219
+ JSONResponse({"profile": signed["account"]}, status_code=201),
220
+ request,
221
+ actor_id,
222
+ signed["session_token"],
223
+ )
224
+
225
+
226
+ @app.post("/api/auth/login")
227
+ async def login(request: Request) -> JSONResponse:
228
+ actor_id, token, _ = actor(request)
229
+ data = await body(request)
230
+ try:
231
+ signed = store.login(token, str(data.get("email", "")), str(data.get("password", "")))
232
+ except (AuthError, ValueError) as exc:
233
+ return attach(JSONResponse({"error": str(exc)}, status_code=401), request, actor_id, token)
234
+ return attach(JSONResponse({"profile": signed["account"]}), request, actor_id, signed["session_token"])
235
+
236
+
237
+ @app.post("/api/auth/logout")
238
+ async def logout(request: Request) -> JSONResponse:
239
+ actor_id, token, _ = actor(request)
240
+ store.logout(token)
241
+ new_token, _ = store.ensure_auth_session(None)
242
+ return attach(JSONResponse({"signed_out": True}), request, actor_id, new_token)
243
+
244
+
245
+ @app.post("/api/auth/recovery-preview")
246
+ async def recovery(request: Request) -> JSONResponse:
247
+ data = await body(request)
248
+ email_value = str(data.get("email", "")).strip()
249
+ if "@" not in email_value:
250
+ return error("Enter a valid email address", request)
251
+ return payload({"sent": False, "message": "No email was sent. This is a local recovery preview."}, request)
252
+
253
+
254
+ def known(path: str) -> bool:
255
+ prefixes = ("/movies", "/theaters", "/tickets", "/checkout", "/confirmation", "/account",
256
+ "/help", "/search", "/favorites", "/policies", "/offers", "/fanstore",
257
+ "/streaming", "/movie-news", "/movie-photos", "/movie-trailer")
258
+ return path == "/" or path.startswith(prefixes)
259
+
260
+
261
+ @app.get("/{path:path}", response_class=HTMLResponse)
262
+ async def page(path: str, request: Request) -> HTMLResponse:
263
+ route = "/" + path
264
+ status = 200 if known(route) else 404
265
+ source = INDEX.read_text(encoding="utf-8")
266
+ source = source.replace("__ROUTE__", html.escape(route, quote=True))
267
+ response = HTMLResponse(source, status_code=status)
268
+ actor_id, token, _ = actor(request)
269
+ return attach(response, request, actor_id, token)
tasks/fandango/environment/reference/clone/backend/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Fandango local clone backend."""
tasks/fandango/environment/reference/clone/backend/catalog.py ADDED
@@ -0,0 +1,1080 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fandango catalog captured from the public source site.
2
+
3
+ Generated from source-assets/fandango-2026-08-23 and the movie/theater pages listed
4
+ in each row's source_url. Regenerating means re-running the capture, not hand-editing.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ CAPTURE_ID = "fandango-2026-08-23"
12
+
13
+ THEATERS: list[dict[str, Any]] = [
14
+ {
15
+ "id": "regal-union-square",
16
+ "name": "Regal Union Square ScreenX & 4DX",
17
+ "location": "850 Broadway, New York, NY 10003",
18
+ "distance": 0.1,
19
+ "services": [
20
+ "Reserved Seating",
21
+ "Digital Projection",
22
+ "Full Bar",
23
+ "Listening Devices",
24
+ "Mobile Tickets",
25
+ "Print at Home Tickets",
26
+ "Stadium Seating",
27
+ "Ticket Kiosk",
28
+ "Wheelchair Accessible"
29
+ ],
30
+ "policy": "Refund or exchange before the posted showtime. Photo ID may be required for R-rated films.",
31
+ "source_url": "https://www.fandango.com/regal-union-square-screenx-and-4dx-aajnk/theater-page"
32
+ },
33
+ {
34
+ "id": "amc-village-7",
35
+ "name": "AMC Village 7",
36
+ "location": "66 3rd Ave., New York, NY 10003",
37
+ "distance": 0.4,
38
+ "services": [
39
+ "Ticket Kiosk",
40
+ "Concession Pickup",
41
+ "Digital Projection",
42
+ "Mobile Tickets",
43
+ "Print at Home Tickets",
44
+ "Reserved Seating"
45
+ ],
46
+ "policy": "Refunds and exchanges are available online until the posted showtime.",
47
+ "source_url": "https://www.fandango.com/amc-village-7-aabqf/theater-page"
48
+ },
49
+ {
50
+ "id": "regal-essex-crossing",
51
+ "name": "Regal Essex Crossing & RPX",
52
+ "location": "129 Delancey St., New York, NY 10002",
53
+ "distance": 1.0,
54
+ "services": [
55
+ "Digital Projection",
56
+ "Café",
57
+ "Full Bar",
58
+ "Listening Devices",
59
+ "Mobile Tickets",
60
+ "Print at Home Tickets",
61
+ "Reserved Seating",
62
+ "Ticket Kiosk",
63
+ "Wheelchair Accessible"
64
+ ],
65
+ "policy": "Exchanges permitted up to showtime. RPX auditoriums carry a premium.",
66
+ "source_url": "https://www.fandango.com/regal-essex-crossing-and-rpx-aayny/theater-page"
67
+ },
68
+ {
69
+ "id": "amc-kips-bay-15",
70
+ "name": "AMC Kips Bay 15",
71
+ "location": "570 Second Ave., New York, NY 10016",
72
+ "distance": 1.2,
73
+ "services": [
74
+ "Café",
75
+ "Print at Home Tickets",
76
+ "Mobile Tickets",
77
+ "IMAX",
78
+ "Digital Projection",
79
+ "Concession Pickup",
80
+ "Wheelchair Accessible",
81
+ "Ticket Kiosk",
82
+ "Stadium Seating",
83
+ "Reserved Seating"
84
+ ],
85
+ "policy": "Exchanges permitted up to showtime. IMAX auditoriums carry a premium.",
86
+ "source_url": "https://www.fandango.com/amc-kips-bay-15-aancl/theater-page"
87
+ },
88
+ {
89
+ "id": "regal-battery-park",
90
+ "name": "Regal Battery Park",
91
+ "location": "102 North End Ave., New York, NY 10282",
92
+ "distance": 2.7,
93
+ "services": [
94
+ "Digital Projection",
95
+ "Listening Devices",
96
+ "Mobile Tickets",
97
+ "Print at Home Tickets",
98
+ "Reserved Seating",
99
+ "Stadium Seating",
100
+ "Ticket Kiosk",
101
+ "Wheelchair Accessible"
102
+ ],
103
+ "policy": "Refund or exchange before the posted showtime.",
104
+ "source_url": "https://www.fandango.com/regal-battery-park-aapos/theater-page"
105
+ }
106
+ ]
107
+
108
+ MOVIES: list[dict[str, Any]] = [
109
+ {
110
+ "id": "mutiny-2026-245697",
111
+ "title": "Mutiny",
112
+ "year": 2026,
113
+ "genre": "Action/Adventure",
114
+ "genres": [
115
+ "Action/Adventure",
116
+ "Suspense/Thriller"
117
+ ],
118
+ "rating": "NR",
119
+ "score": 86,
120
+ "critic_score": 51,
121
+ "runtime": "",
122
+ "status": "now-playing",
123
+ "poster": "/static/assets/poster-mutiny-2026.jpg",
124
+ "synopsis": "In MUTINY, after witnessing his billionaire boss's murder and being framed for the crime, Cole Reed (Jason Statham) boards a cargo ship on a one-man crusade to avenge his boss's death only to discover an international conspiracy.",
125
+ "director": "Jean-François Richet",
126
+ "source_url": "https://www.fandango.com/mutiny-2026-245697/movie-overview"
127
+ },
128
+ {
129
+ "id": "spider-man-brand-new-day-2026-243819",
130
+ "title": "Spider-Man: Brand New Day",
131
+ "year": 2026,
132
+ "genre": "Action/Adventure",
133
+ "genres": [
134
+ "Action/Adventure",
135
+ "Sci-Fi/Fantasy"
136
+ ],
137
+ "rating": "PG-13",
138
+ "score": 0,
139
+ "critic_score": 0,
140
+ "runtime": "2 hr 25 min",
141
+ "status": "now-playing",
142
+ "poster": "/static/assets/poster-spider-man-brand-new-day-2026.jpg",
143
+ "synopsis": "It's a BRAND NEW DAY for Peter Parker. Fighting crime full-time as Spider-Man in a world that doesn’t remember him -- and the pressure of seeing his old friends move on without him -- sparks a change in Peter he may not have the power to control. But that transformation might also be the only thing that can stop a shocking new threat to the city and those he loves - a powerful villain no one can",
144
+ "director": "Destin Daniel Cretton",
145
+ "source_url": "https://www.fandango.com/spider-man-brand-new-day-2026-243819/movie-overview"
146
+ },
147
+ {
148
+ "id": "insidious-out-of-the-further-2026-246427",
149
+ "title": "Insidious: Out of the Further",
150
+ "year": 2026,
151
+ "genre": "Horror",
152
+ "genres": [
153
+ "Horror"
154
+ ],
155
+ "rating": "NR",
156
+ "score": 70,
157
+ "critic_score": 58,
158
+ "runtime": "",
159
+ "status": "now-playing",
160
+ "poster": "/static/assets/poster-insidious-out-of-the-further-2026.jpg",
161
+ "synopsis": "In Insidious: Out of the Further, Amelia Eve stars as Gemma, a young mother raising her daughter in the house she grew up in who discovers she can travel into The Further, the purgatorial realm of lost souls at the heart of the Insidious universe. When something evil comes after her, Gemma discovers an ability that changes everything: she doesn't just enter The Further, she can bring what lives th",
162
+ "director": "Jacob Chase",
163
+ "source_url": "https://www.fandango.com/insidious-out-of-the-further-2026-246427/movie-overview"
164
+ },
165
+ {
166
+ "id": "the-odyssey-2026-241283",
167
+ "title": "The Odyssey",
168
+ "year": 2026,
169
+ "genre": "Action/Adventure",
170
+ "genres": [
171
+ "Action/Adventure",
172
+ "Sci-Fi/Fantasy"
173
+ ],
174
+ "rating": "R",
175
+ "score": 0,
176
+ "critic_score": 0,
177
+ "runtime": "2 hr 52 min",
178
+ "status": "now-playing",
179
+ "poster": "/static/assets/poster-the-odyssey-2026.jpg",
180
+ "synopsis": "Odysseus, king of Ithaca, embarks on a perilous journey to return home after the Trojan War.",
181
+ "director": "Christopher Nolan",
182
+ "source_url": "https://www.fandango.com/the-odyssey-2026-241283/movie-overview"
183
+ },
184
+ {
185
+ "id": "it-ends-2026-246704",
186
+ "title": "It Ends",
187
+ "year": 2026,
188
+ "genre": "Horror",
189
+ "genres": [
190
+ "Horror",
191
+ "Suspense/Thriller"
192
+ ],
193
+ "rating": "R",
194
+ "score": 0,
195
+ "critic_score": 0,
196
+ "runtime": "1 hr 29 min",
197
+ "status": "now-playing",
198
+ "poster": "/static/assets/poster-it-ends-2026.jpg",
199
+ "synopsis": "A group of recent grads head out on a late night drive for grub, hoping to enjoy one final hangout before their paths diverge. Instead, they accidentally turn onto a never-ending, two lane hellscape surrounded by untold horrors and cosmic forces beyond their understanding.",
200
+ "director": "Alexander Ullom",
201
+ "source_url": "https://www.fandango.com/it-ends-2026-246704/movie-overview"
202
+ },
203
+ {
204
+ "id": "the-end-of-oak-street-2026-245149",
205
+ "title": "The End of Oak Street",
206
+ "year": 2026,
207
+ "genre": "Sci-Fi/Fantasy",
208
+ "genres": [
209
+ "Sci-Fi/Fantasy",
210
+ "Suspense/Thriller"
211
+ ],
212
+ "rating": "PG-13",
213
+ "score": 0,
214
+ "critic_score": 0,
215
+ "runtime": "1 hr 39 min",
216
+ "status": "now-playing",
217
+ "poster": "/static/assets/poster-the-end-of-oak-street-2026.jpg",
218
+ "synopsis": "After a mysterious cosmic event rips Oak Street from suburbia and transports their neighborhood to someplace unknown, the Platt family soon discovers that their very survival depends on them sticking together as they navigate their now unrecognizable surroundings.",
219
+ "director": "David Robert Mitchell",
220
+ "source_url": "https://www.fandango.com/the-end-of-oak-street-2026-245149/movie-overview"
221
+ },
222
+ {
223
+ "id": "spa-weekend-2026-245958",
224
+ "title": "Spa Weekend",
225
+ "year": 2026,
226
+ "genre": "Comedy",
227
+ "genres": [
228
+ "Comedy"
229
+ ],
230
+ "rating": "R",
231
+ "score": 76,
232
+ "critic_score": 34,
233
+ "runtime": "1 hr 37 min",
234
+ "status": "now-playing",
235
+ "poster": "/static/assets/poster-spa-weekend-2026.jpg",
236
+ "synopsis": "Three friends go on a spa weekend that descends into chaos when their trainwreck friend joins, leading to hilarious consequences.",
237
+ "director": "Scott Moore",
238
+ "source_url": "https://www.fandango.com/spa-weekend-2026-245958/movie-overview"
239
+ },
240
+ {
241
+ "id": "paw-patrol-the-dino-movie-2026-245603",
242
+ "title": "PAW Patrol: The Dino Movie",
243
+ "year": 2026,
244
+ "genre": "Animated",
245
+ "genres": [
246
+ "Animated",
247
+ "Family"
248
+ ],
249
+ "rating": "PG",
250
+ "score": 0,
251
+ "critic_score": 0,
252
+ "runtime": "1 hr 28 min",
253
+ "status": "now-playing",
254
+ "poster": "/static/assets/poster-paw-patrol-the-dino-movie-2026.jpg",
255
+ "synopsis": "After their ship gets caught in a mysterious storm, the PAW Patrol pups crash land on an uncharted tropical island filled with dinosaurs. They meet Rex, a pup who has been stranded on the island for years and has become an expert in all things dino-related. When the PAW Patrol's archrival, Mayor Humdinger, begins recklessly mining in hopes of exploiting the island for its natural resources, he ina",
256
+ "director": "Cal Brunker",
257
+ "source_url": "https://www.fandango.com/paw-patrol-the-dino-movie-2026-245603/movie-overview"
258
+ },
259
+ {
260
+ "id": "toy-story-5-2026-243393",
261
+ "title": "Toy Story 5",
262
+ "year": 2026,
263
+ "genre": "Animated",
264
+ "genres": [
265
+ "Animated",
266
+ "Comedy"
267
+ ],
268
+ "rating": "PG",
269
+ "score": 0,
270
+ "critic_score": 0,
271
+ "runtime": "1 hr 42 min",
272
+ "status": "now-playing",
273
+ "poster": "/static/assets/poster-toy-story-5-2026.jpg",
274
+ "synopsis": "The toys are back in Disney and Pixar’s “Toy Story 5,” and this time it’s Toy meets Tech. Woody (voice of Tom Hanks), Buzz Lightyear (voice of Tim Allen), Jessie (voice of Joan Cusack) and the rest of the gang's jobs are challenged when they come face-to-face with Lilypad (voice of Greta Lee), a brand-new tablet device that arrives with her own disruptive ideas about what is best for their kid, Bo",
275
+ "director": "Andrew Stanton",
276
+ "source_url": "https://www.fandango.com/toy-story-5-2026-243393/movie-overview"
277
+ },
278
+ {
279
+ "id": "minions-and-monsters-2026-244409",
280
+ "title": "Minions & Monsters",
281
+ "year": 2026,
282
+ "genre": "Animated",
283
+ "genres": [
284
+ "Animated",
285
+ "Comedy"
286
+ ],
287
+ "rating": "PG",
288
+ "score": 0,
289
+ "critic_score": 0,
290
+ "runtime": "1 hr 30 min",
291
+ "status": "now-playing",
292
+ "poster": "/static/assets/poster-minions-and-monsters-2026.jpg",
293
+ "synopsis": "This is the rambunctious, ridiculous and totally true story of how the Minions conquered Hollywood, became movie stars, lost everything, unleashed monsters onto the world and then banded together to try and save the planet from the mayhem they had just created.",
294
+ "director": "Pierre Coffin",
295
+ "source_url": "https://www.fandango.com/minions-and-monsters-2026-244409/movie-overview"
296
+ },
297
+ {
298
+ "id": "the-magic-faraway-tree-2026-245875",
299
+ "title": "The Magic Faraway Tree",
300
+ "year": 2026,
301
+ "genre": "Family",
302
+ "genres": [
303
+ "Family",
304
+ "Sci-Fi/Fantasy"
305
+ ],
306
+ "rating": "PG",
307
+ "score": 0,
308
+ "critic_score": 0,
309
+ "runtime": "1 hr 50 min",
310
+ "status": "now-playing",
311
+ "poster": "/static/assets/poster-the-magic-faraway-tree-2026.jpg",
312
+ "synopsis": "Adapted from Enid Blyton's beloved classic novel The Magic Faraway Tree, the film centers on Polly (Claire Foy), Tim (Andrew Garfield), and their three children -- a modern family forced to relocate to the remote English countryside. As they adapt to their new lives, the children discover a magical tree and its extraordinary and eccentric residents, including treasured characters Moonface (Nonso A",
313
+ "director": "Ben Gregor",
314
+ "source_url": "https://www.fandango.com/the-magic-faraway-tree-2026-245875/movie-overview"
315
+ },
316
+ {
317
+ "id": "texas-chain-saw-day-2026-246288",
318
+ "title": "Texas Chain Saw Day",
319
+ "year": 2026,
320
+ "genre": "Horror",
321
+ "genres": [
322
+ "Horror"
323
+ ],
324
+ "rating": "R",
325
+ "score": 0,
326
+ "critic_score": 0,
327
+ "runtime": "1 hr 43 min",
328
+ "status": "now-playing",
329
+ "poster": "/static/assets/poster-texas-chain-saw-day-2026.jpg",
330
+ "synopsis": "Shocking, lurid and completely unapologetic in its brutality, director Tobe Hooper’s THE TEXAS CHAIN SAW MASSACRE completely changed cinema following its debut in 1974. The film follows five youths on a weekend getaway in the Texas countryside on August 18th, 1973, as they fall prey to a butcher in a mask made of human skin and his cannibalistic family. Violent, confrontational, and shockingly re",
331
+ "director": "",
332
+ "source_url": "https://www.fandango.com/texas-chain-saw-day-2026-246288/movie-overview"
333
+ },
334
+ {
335
+ "id": "one-night-only-2026-245604",
336
+ "title": "One Night Only",
337
+ "year": 2026,
338
+ "genre": "Comedy",
339
+ "genres": [
340
+ "Comedy",
341
+ "Romance"
342
+ ],
343
+ "rating": "R",
344
+ "score": 76,
345
+ "critic_score": 46,
346
+ "runtime": "1 hr 42 min",
347
+ "status": "now-playing",
348
+ "poster": "/static/assets/poster-one-night-only-2026.jpg",
349
+ "synopsis": "Two New Yorkers search for love on the one night of the year when sex is legal.",
350
+ "director": "Will Gluck",
351
+ "source_url": "https://www.fandango.com/one-night-only-2026-245604/movie-overview"
352
+ },
353
+ {
354
+ "id": "the-rivals-of-amziah-king-2026-245978",
355
+ "title": "The Rivals of Amziah King",
356
+ "year": 2026,
357
+ "genre": "Drama",
358
+ "genres": [
359
+ "Drama",
360
+ "Suspense/Thriller"
361
+ ],
362
+ "rating": "R",
363
+ "score": 0,
364
+ "critic_score": 0,
365
+ "runtime": "2 hr 10 min",
366
+ "status": "now-playing",
367
+ "poster": "/static/assets/poster-the-rivals-of-amziah-king-2026.jpg",
368
+ "synopsis": "Amziah King, beekeeper, musician, and anchor of his community, reunites with former foster daughter Kateri after many years apart, and fends off threats to his honey business.",
369
+ "director": "Andrew Patterson",
370
+ "source_url": "https://www.fandango.com/the-rivals-of-amziah-king-2026-245978/movie-overview"
371
+ },
372
+ {
373
+ "id": "the-brink-of-war-2026-246132",
374
+ "title": "The Brink of War",
375
+ "year": 2026,
376
+ "genre": "Drama",
377
+ "genres": [
378
+ "Drama",
379
+ "Suspense/Thriller"
380
+ ],
381
+ "rating": "PG",
382
+ "score": 0,
383
+ "critic_score": 0,
384
+ "runtime": "1 hr 57 min",
385
+ "status": "now-playing",
386
+ "poster": "/static/assets/poster-the-brink-of-war-2026.jpg",
387
+ "synopsis": "President Reagan races against time to salvage a deal with Soviet leader Mikhail Gorbachev that could dismantle nuclear arsenals—or ignite disaster. With pressure mounting from advisors, intelligence agencies, and history itself, every word spoken brings the world closer to peace… or destruction.",
388
+ "director": "Michael Russell Gunn",
389
+ "source_url": "https://www.fandango.com/the-brink-of-war-2026-246132/movie-overview"
390
+ },
391
+ {
392
+ "id": "nimrods-2026-246455",
393
+ "title": "Nimrods",
394
+ "year": 2026,
395
+ "genre": "Comedy",
396
+ "genres": [
397
+ "Comedy",
398
+ "Drama"
399
+ ],
400
+ "rating": "R",
401
+ "score": 0,
402
+ "critic_score": 0,
403
+ "runtime": "1 hr 42 min",
404
+ "status": "now-playing",
405
+ "poster": "/static/assets/poster-nimrods-2026.jpg",
406
+ "synopsis": "Three buddies drive cross-country in a van, causing mayhem and mischief while racing to LA for their big break: opening for Green Day on New Year's Eve.",
407
+ "director": "Lee Kirk",
408
+ "source_url": "https://www.fandango.com/nimrods-2026-246455/movie-overview"
409
+ },
410
+ {
411
+ "id": "dune-part-three-2026-244800",
412
+ "title": "Dune: Part Three",
413
+ "year": 2026,
414
+ "genre": "Action/Adventure",
415
+ "genres": [
416
+ "Action/Adventure",
417
+ "Sci-Fi/Fantasy"
418
+ ],
419
+ "rating": "NR",
420
+ "score": 0,
421
+ "critic_score": 0,
422
+ "runtime": "",
423
+ "status": "coming-soon",
424
+ "poster": "/static/assets/poster-dune-part-three-2026.jpg",
425
+ "synopsis": "Directed by Denis Villeneuve and written by Villeneuve and Brian K. Vaughan, Dune: Part Three is based on the novel Dune Messiah by Frank Herbert and delivers the epic conclusion to Villeneuve’s trilogy.",
426
+ "director": "Denis Villeneuve",
427
+ "source_url": "https://www.fandango.com/dune-part-three-2026-244800/movie-overview"
428
+ },
429
+ {
430
+ "id": "avengers-doomsday-2026-237176",
431
+ "title": "Avengers: Doomsday",
432
+ "year": 2026,
433
+ "genre": "Sci-Fi/Fantasy",
434
+ "genres": [
435
+ "Sci-Fi/Fantasy"
436
+ ],
437
+ "rating": "NR",
438
+ "score": 0,
439
+ "critic_score": 0,
440
+ "runtime": "",
441
+ "status": "coming-soon",
442
+ "poster": "/static/assets/poster-avengers-doomsday-2026.jpg",
443
+ "synopsis": "Universes collide and the Multiverse Saga begins its final chapter in Marvel Studios' Avengers: Doomsday. Beloved heroes from three distinct universes will be set on a deadly collision course and ultimately face an existential threat unlike anything they've ever encountered. This epic film will lay the foundation for the future of the Marvel Cinematic Universe. See it in Infinity Vision, the way i",
444
+ "director": "Anthony Russo, Joe Russo",
445
+ "source_url": "https://www.fandango.com/avengers-doomsday-2026-237176/movie-overview"
446
+ },
447
+ {
448
+ "id": "the-hunger-games-sunrise-on-the-reaping-2026-240138",
449
+ "title": "The Hunger Games: Sunrise on the Reaping",
450
+ "year": 2026,
451
+ "genre": "Action/Adventure",
452
+ "genres": [
453
+ "Action/Adventure",
454
+ "Sci-Fi/Fantasy"
455
+ ],
456
+ "rating": "NR",
457
+ "score": 0,
458
+ "critic_score": 0,
459
+ "runtime": "",
460
+ "status": "coming-soon",
461
+ "poster": "/static/assets/poster-the-hunger-games-sunrise-on-the-reaping-2026.jpg",
462
+ "synopsis": "Explores Panem 24 years before Katniss' saga, starting on the morning of the reaping for the 50th Hunger Games, where a young Haymitch Abernathy participates.",
463
+ "director": "Francis Lawrence",
464
+ "source_url": "https://www.fandango.com/the-hunger-games-sunrise-on-the-reaping-2026-240138/movie-overview"
465
+ },
466
+ {
467
+ "id": "practical-magic-2-2026-246473",
468
+ "title": "Practical Magic 2",
469
+ "year": 2026,
470
+ "genre": "Comedy",
471
+ "genres": [
472
+ "Comedy",
473
+ "Drama"
474
+ ],
475
+ "rating": "NR",
476
+ "score": 0,
477
+ "critic_score": 0,
478
+ "runtime": "2 hr 10 min",
479
+ "status": "coming-soon",
480
+ "poster": "/static/assets/poster-practical-magic-2-2026.jpg",
481
+ "synopsis": "PRACTICAL MAGIC 2 returns to a world steeped in moonlit mischief and powerful ancestral magic, as the Owens sisters must confront the dark curse that threatens to unravel their family once and for all in a must-see cinematic event of fun, magic and mayhem.",
482
+ "director": "Susanne Bier",
483
+ "source_url": "https://www.fandango.com/practical-magic-2-2026-246473/movie-overview"
484
+ },
485
+ {
486
+ "id": "clayface-2026-244768",
487
+ "title": "Clayface",
488
+ "year": 2026,
489
+ "genre": "Horror",
490
+ "genres": [
491
+ "Horror"
492
+ ],
493
+ "rating": "NR",
494
+ "score": 0,
495
+ "critic_score": 0,
496
+ "runtime": "",
497
+ "status": "coming-soon",
498
+ "poster": "/static/assets/poster-clayface-2026.jpg",
499
+ "synopsis": "",
500
+ "director": "James Watkins",
501
+ "source_url": "https://www.fandango.com/clayface-2026-244768/movie-overview"
502
+ },
503
+ {
504
+ "id": "the-cat-in-the-hat-2026-241291",
505
+ "title": "The Cat in the Hat",
506
+ "year": 2026,
507
+ "genre": "Animated",
508
+ "genres": [
509
+ "Animated",
510
+ "Comedy"
511
+ ],
512
+ "rating": "NR",
513
+ "score": 0,
514
+ "critic_score": 0,
515
+ "runtime": "",
516
+ "status": "coming-soon",
517
+ "poster": "/static/assets/poster-the-cat-in-the-hat-2026.jpg",
518
+ "synopsis": "Meet the Cat in the Hat you don't know! In the wonderfully whimsical tradition of Dr. Seuss, The Cat in the Hat comes to the big screen in his animated theatrical feature film debut, an all-new, epic adventure with an edge, where mischief, magic and mayhem reign supreme. Doing what he does best, the Cat--voiced by Bill Hader--spreads joy to kids in his hilarious, signature and singularly irreveren",
519
+ "director": "Alessandro Carloni, Erica Rivinoja",
520
+ "source_url": "https://www.fandango.com/the-cat-in-the-hat-2026-241291/movie-overview"
521
+ }
522
+ ]
523
+
524
+ # movie id -> theater id -> [[slot, format, base seats available]]
525
+ SHOWTIMES: dict[str, dict[str, list[list[Any]]]] = {
526
+ "mutiny-2026-245697": {
527
+ "regal-union-square": [
528
+ [
529
+ "matinee",
530
+ "Standard",
531
+ 88
532
+ ],
533
+ [
534
+ "early",
535
+ "Standard",
536
+ 74
537
+ ],
538
+ [
539
+ "prime",
540
+ "ScreenX",
541
+ 61
542
+ ],
543
+ [
544
+ "late",
545
+ "4DX",
546
+ 42
547
+ ]
548
+ ],
549
+ "amc-village-7": [
550
+ [
551
+ "afternoon",
552
+ "Standard",
553
+ 52
554
+ ],
555
+ [
556
+ "prime",
557
+ "Standard",
558
+ 45
559
+ ],
560
+ [
561
+ "night",
562
+ "Standard",
563
+ 66
564
+ ]
565
+ ],
566
+ "amc-kips-bay-15": [
567
+ [
568
+ "early",
569
+ "Standard",
570
+ 91
571
+ ],
572
+ [
573
+ "late",
574
+ "IMAX",
575
+ 70
576
+ ]
577
+ ]
578
+ },
579
+ "spider-man-brand-new-day-2026-243819": {
580
+ "regal-union-square": [
581
+ [
582
+ "afternoon",
583
+ "Standard",
584
+ 48
585
+ ],
586
+ [
587
+ "prime",
588
+ "4DX",
589
+ 39
590
+ ],
591
+ [
592
+ "night",
593
+ "Standard",
594
+ 57
595
+ ]
596
+ ],
597
+ "regal-essex-crossing": [
598
+ [
599
+ "matinee",
600
+ "Standard",
601
+ 143
602
+ ],
603
+ [
604
+ "early",
605
+ "RPX",
606
+ 121
607
+ ],
608
+ [
609
+ "late",
610
+ "Standard",
611
+ 63
612
+ ]
613
+ ]
614
+ },
615
+ "insidious-out-of-the-further-2026-246427": {
616
+ "amc-village-7": [
617
+ [
618
+ "matinee",
619
+ "Standard",
620
+ 54
621
+ ],
622
+ [
623
+ "prime",
624
+ "Standard",
625
+ 78
626
+ ]
627
+ ],
628
+ "regal-battery-park": [
629
+ [
630
+ "afternoon",
631
+ "Standard",
632
+ 49
633
+ ],
634
+ [
635
+ "late",
636
+ "Standard",
637
+ 196
638
+ ]
639
+ ]
640
+ },
641
+ "the-odyssey-2026-241283": {
642
+ "regal-essex-crossing": [
643
+ [
644
+ "early",
645
+ "Standard",
646
+ 173
647
+ ],
648
+ [
649
+ "prime",
650
+ "RPX",
651
+ 86
652
+ ]
653
+ ],
654
+ "amc-kips-bay-15": [
655
+ [
656
+ "afternoon",
657
+ "Standard",
658
+ 51
659
+ ],
660
+ [
661
+ "night",
662
+ "IMAX",
663
+ 88
664
+ ]
665
+ ]
666
+ },
667
+ "it-ends-2026-246704": {
668
+ "regal-union-square": [
669
+ [
670
+ "matinee",
671
+ "Standard",
672
+ 74
673
+ ],
674
+ [
675
+ "late",
676
+ "4DX",
677
+ 61
678
+ ]
679
+ ],
680
+ "regal-battery-park": [
681
+ [
682
+ "early",
683
+ "Standard",
684
+ 83
685
+ ],
686
+ [
687
+ "prime",
688
+ "Standard",
689
+ 52
690
+ ]
691
+ ]
692
+ },
693
+ "the-end-of-oak-street-2026-245149": {
694
+ "regal-union-square": [
695
+ [
696
+ "matinee",
697
+ "Standard",
698
+ 45
699
+ ],
700
+ [
701
+ "early",
702
+ "4DX",
703
+ 66
704
+ ],
705
+ [
706
+ "prime",
707
+ "Standard",
708
+ 91
709
+ ],
710
+ [
711
+ "late",
712
+ "Standard",
713
+ 70
714
+ ]
715
+ ],
716
+ "amc-village-7": [
717
+ [
718
+ "afternoon",
719
+ "Standard",
720
+ 48
721
+ ],
722
+ [
723
+ "prime",
724
+ "Standard",
725
+ 39
726
+ ],
727
+ [
728
+ "night",
729
+ "Standard",
730
+ 57
731
+ ]
732
+ ],
733
+ "amc-kips-bay-15": [
734
+ [
735
+ "early",
736
+ "Standard",
737
+ 143
738
+ ],
739
+ [
740
+ "late",
741
+ "IMAX",
742
+ 121
743
+ ]
744
+ ]
745
+ },
746
+ "spa-weekend-2026-245958": {
747
+ "regal-union-square": [
748
+ [
749
+ "afternoon",
750
+ "Standard",
751
+ 63
752
+ ],
753
+ [
754
+ "prime",
755
+ "4DX",
756
+ 54
757
+ ],
758
+ [
759
+ "night",
760
+ "Standard",
761
+ 78
762
+ ]
763
+ ],
764
+ "regal-essex-crossing": [
765
+ [
766
+ "matinee",
767
+ "Standard",
768
+ 49
769
+ ],
770
+ [
771
+ "early",
772
+ "RPX",
773
+ 196
774
+ ],
775
+ [
776
+ "late",
777
+ "Standard",
778
+ 173
779
+ ]
780
+ ]
781
+ },
782
+ "paw-patrol-the-dino-movie-2026-245603": {
783
+ "amc-village-7": [
784
+ [
785
+ "matinee",
786
+ "Standard",
787
+ 86
788
+ ],
789
+ [
790
+ "prime",
791
+ "Standard",
792
+ 51
793
+ ]
794
+ ],
795
+ "regal-battery-park": [
796
+ [
797
+ "afternoon",
798
+ "Standard",
799
+ 88
800
+ ],
801
+ [
802
+ "late",
803
+ "Standard",
804
+ 74
805
+ ]
806
+ ]
807
+ },
808
+ "toy-story-5-2026-243393": {
809
+ "regal-essex-crossing": [
810
+ [
811
+ "early",
812
+ "Standard",
813
+ 61
814
+ ],
815
+ [
816
+ "prime",
817
+ "RPX",
818
+ 83
819
+ ]
820
+ ],
821
+ "amc-kips-bay-15": [
822
+ [
823
+ "afternoon",
824
+ "Standard",
825
+ 52
826
+ ],
827
+ [
828
+ "night",
829
+ "IMAX",
830
+ 45
831
+ ]
832
+ ]
833
+ },
834
+ "minions-and-monsters-2026-244409": {
835
+ "regal-union-square": [
836
+ [
837
+ "matinee",
838
+ "Standard",
839
+ 66
840
+ ],
841
+ [
842
+ "late",
843
+ "4DX",
844
+ 91
845
+ ]
846
+ ],
847
+ "regal-battery-park": [
848
+ [
849
+ "early",
850
+ "Standard",
851
+ 70
852
+ ],
853
+ [
854
+ "prime",
855
+ "Standard",
856
+ 48
857
+ ]
858
+ ]
859
+ },
860
+ "the-magic-faraway-tree-2026-245875": {
861
+ "regal-union-square": [
862
+ [
863
+ "matinee",
864
+ "Standard",
865
+ 39
866
+ ],
867
+ [
868
+ "early",
869
+ "4DX",
870
+ 57
871
+ ],
872
+ [
873
+ "prime",
874
+ "Standard",
875
+ 143
876
+ ],
877
+ [
878
+ "late",
879
+ "Standard",
880
+ 121
881
+ ]
882
+ ],
883
+ "amc-village-7": [
884
+ [
885
+ "afternoon",
886
+ "Standard",
887
+ 63
888
+ ],
889
+ [
890
+ "prime",
891
+ "Standard",
892
+ 54
893
+ ],
894
+ [
895
+ "night",
896
+ "Standard",
897
+ 78
898
+ ]
899
+ ],
900
+ "amc-kips-bay-15": [
901
+ [
902
+ "early",
903
+ "Standard",
904
+ 49
905
+ ],
906
+ [
907
+ "late",
908
+ "IMAX",
909
+ 196
910
+ ]
911
+ ]
912
+ },
913
+ "texas-chain-saw-day-2026-246288": {
914
+ "regal-union-square": [
915
+ [
916
+ "afternoon",
917
+ "Standard",
918
+ 173
919
+ ],
920
+ [
921
+ "prime",
922
+ "4DX",
923
+ 86
924
+ ],
925
+ [
926
+ "night",
927
+ "Standard",
928
+ 51
929
+ ]
930
+ ],
931
+ "regal-essex-crossing": [
932
+ [
933
+ "matinee",
934
+ "Standard",
935
+ 88
936
+ ],
937
+ [
938
+ "early",
939
+ "RPX",
940
+ 74
941
+ ],
942
+ [
943
+ "late",
944
+ "Standard",
945
+ 61
946
+ ]
947
+ ]
948
+ },
949
+ "one-night-only-2026-245604": {
950
+ "amc-village-7": [
951
+ [
952
+ "matinee",
953
+ "Standard",
954
+ 83
955
+ ],
956
+ [
957
+ "prime",
958
+ "Standard",
959
+ 52
960
+ ]
961
+ ],
962
+ "regal-battery-park": [
963
+ [
964
+ "afternoon",
965
+ "Standard",
966
+ 45
967
+ ],
968
+ [
969
+ "late",
970
+ "Standard",
971
+ 66
972
+ ]
973
+ ]
974
+ },
975
+ "the-rivals-of-amziah-king-2026-245978": {
976
+ "regal-essex-crossing": [
977
+ [
978
+ "early",
979
+ "Standard",
980
+ 91
981
+ ],
982
+ [
983
+ "prime",
984
+ "RPX",
985
+ 70
986
+ ]
987
+ ],
988
+ "amc-kips-bay-15": [
989
+ [
990
+ "afternoon",
991
+ "Standard",
992
+ 48
993
+ ],
994
+ [
995
+ "night",
996
+ "IMAX",
997
+ 39
998
+ ]
999
+ ]
1000
+ },
1001
+ "the-brink-of-war-2026-246132": {
1002
+ "regal-union-square": [
1003
+ [
1004
+ "matinee",
1005
+ "Standard",
1006
+ 57
1007
+ ],
1008
+ [
1009
+ "late",
1010
+ "4DX",
1011
+ 143
1012
+ ]
1013
+ ],
1014
+ "regal-battery-park": [
1015
+ [
1016
+ "early",
1017
+ "Standard",
1018
+ 121
1019
+ ],
1020
+ [
1021
+ "prime",
1022
+ "Standard",
1023
+ 63
1024
+ ]
1025
+ ]
1026
+ },
1027
+ "nimrods-2026-246455": {
1028
+ "regal-union-square": [
1029
+ [
1030
+ "matinee",
1031
+ "Standard",
1032
+ 54
1033
+ ],
1034
+ [
1035
+ "early",
1036
+ "4DX",
1037
+ 78
1038
+ ],
1039
+ [
1040
+ "prime",
1041
+ "Standard",
1042
+ 49
1043
+ ],
1044
+ [
1045
+ "late",
1046
+ "Standard",
1047
+ 196
1048
+ ]
1049
+ ],
1050
+ "amc-village-7": [
1051
+ [
1052
+ "afternoon",
1053
+ "Standard",
1054
+ 173
1055
+ ],
1056
+ [
1057
+ "prime",
1058
+ "Standard",
1059
+ 86
1060
+ ],
1061
+ [
1062
+ "night",
1063
+ "Standard",
1064
+ 51
1065
+ ]
1066
+ ],
1067
+ "amc-kips-bay-15": [
1068
+ [
1069
+ "early",
1070
+ "Standard",
1071
+ 88
1072
+ ],
1073
+ [
1074
+ "late",
1075
+ "IMAX",
1076
+ 74
1077
+ ]
1078
+ ]
1079
+ }
1080
+ }
tasks/fandango/environment/reference/clone/backend/navigation-catalog.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/fandango/environment/reference/clone/backend/site_backend_integration.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generated, site-bound backend integration seam."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import json
7
+ import os
8
+ import sqlite3
9
+ from pathlib import Path
10
+ from typing import Any, Callable
11
+
12
+ from websitebench.local_clone_auth import LocalAuthStore
13
+ from websitebench.site_backend import (
14
+ SiteBackend,
15
+ load_runtime,
16
+ serve_jsonl,
17
+ validate_allowlist,
18
+ )
19
+
20
+
21
+ DEFAULT_RUNTIME_PATH = (
22
+ Path(__file__).resolve().parents[2] / "backend" / "runtime.json"
23
+ )
24
+ BRIDGE_DESCRIPTOR_PATH = (
25
+ Path(__file__).resolve().parents[2] / "backend" / "node-bridge.json"
26
+ )
27
+
28
+
29
+ def _declared_hook(
30
+ declaration: str | None,
31
+ ) -> Callable[[sqlite3.Connection], None] | None:
32
+ if declaration is None:
33
+ return None
34
+ module_name, function_name = declaration.split(":", 1)
35
+ module = importlib.import_module(module_name)
36
+ hook: Any = getattr(module, function_name, None)
37
+ if not callable(hook):
38
+ raise RuntimeError(f"declared backend hook is not callable: {declaration}")
39
+ actual = f"{hook.__module__}:{hook.__name__}"
40
+ if actual != declaration:
41
+ raise RuntimeError(
42
+ f"declared backend hook resolved as {actual!r}, expected {declaration!r}"
43
+ )
44
+ return hook
45
+
46
+
47
+ def open_site_services() -> tuple[SiteBackend, LocalAuthStore]:
48
+ """Open one bound database; never omit the site id for permanent auth."""
49
+
50
+ runtime_path = Path(
51
+ os.environ.get(
52
+ "WEBSITEBENCH_SITE_BACKEND_RUNTIME",
53
+ str(DEFAULT_RUNTIME_PATH),
54
+ )
55
+ ).resolve()
56
+ runtime = load_runtime(runtime_path)
57
+ migration_hook = _declared_hook(runtime.migration_hook)
58
+ seed_hook = _declared_hook(runtime.seed_hook)
59
+ deployed_database = os.environ.get(
60
+ "WEBSITEBENCH_SITE_BACKEND_DATABASE",
61
+ )
62
+ if deployed_database is None:
63
+ backend = SiteBackend.open(
64
+ runtime_path,
65
+ migration_hook=migration_hook,
66
+ seed_hook=seed_hook,
67
+ )
68
+ else:
69
+ database_path = Path(deployed_database).resolve()
70
+ if database_path.name != runtime.database_filename:
71
+ raise RuntimeError(
72
+ "deployed database filename does not match runtime contract"
73
+ )
74
+ backend = SiteBackend.open(
75
+ json.loads(runtime_path.read_text(encoding="utf-8")),
76
+ data_root=database_path.parent,
77
+ migration_hook=migration_hook,
78
+ seed_hook=seed_hook,
79
+ )
80
+ if backend.lifecycle.database_path != database_path:
81
+ raise RuntimeError(
82
+ "deployed database path does not match backend preflight"
83
+ )
84
+ backend.lifecycle.initialize()
85
+ auth = LocalAuthStore(
86
+ backend.lifecycle.database_path,
87
+ site_id=backend.config.site_id,
88
+ )
89
+ auth.ensure_schema()
90
+ return backend, auth
91
+
92
+
93
+ def run_stdio_bridge() -> None:
94
+ """Run only operations frozen in this site's descriptor."""
95
+
96
+ backend, auth = open_site_services()
97
+ descriptor = json.loads(BRIDGE_DESCRIPTOR_PATH.read_text(encoding="utf-8"))
98
+ allowed = validate_allowlist(
99
+ descriptor,
100
+ expected_site_id=backend.config.site_id,
101
+ )
102
+ serve_jsonl(backend, auth, allowed, sys.stdin, sys.stdout)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ import argparse
107
+ import sys
108
+
109
+ parser = argparse.ArgumentParser(prog="websitebench-node-backend-bridge")
110
+ parser.add_argument("--stdio", action="store_true", required=True)
111
+ parser.parse_args()
112
+ run_stdio_bridge()
tasks/fandango/environment/reference/clone/backend/store.py ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import hashlib
5
+ import json
6
+ import secrets
7
+ import time
8
+ import uuid
9
+ from datetime import date, timedelta
10
+ from threading import RLock
11
+ from typing import Any
12
+ from pathlib import Path
13
+
14
+ from backend.catalog import MOVIES, SHOWTIMES, THEATERS
15
+ from backend.site_backend_integration import open_site_services
16
+
17
+
18
+ LOCK = RLock()
19
+ backend, auth = open_site_services()
20
+ NAV_CATALOG = json.loads((Path(__file__).parent / 'navigation-catalog.json').read_text(encoding='utf-8'))
21
+ NAV_PRODUCTS = {p['id']: p for p in NAV_CATALOG['products']}
22
+
23
+ SCHEMA = """
24
+ CREATE TABLE IF NOT EXISTS fandango_actor_state (
25
+ actor_id TEXT PRIMARY KEY,
26
+ state_json TEXT NOT NULL,
27
+ updated_at INTEGER NOT NULL
28
+ );
29
+ """
30
+
31
+
32
+ def initialize() -> None:
33
+ with backend.lifecycle.connection(transaction=True) as connection:
34
+ connection.executescript(SCHEMA)
35
+
36
+
37
+ initialize()
38
+
39
+
40
+ def navigation_state(actor_id: str) -> dict[str, Any]:
41
+ value = state(actor_id)
42
+ cart = []
43
+ for line in value.get('fanstore_cart', []):
44
+ product = NAV_PRODUCTS.get(line['product'])
45
+ variant = next((v for v in product['variants'] if v['id'] == line['variant']), None) if product else None
46
+ if variant:
47
+ cart.append({**line, 'title': product['title'], 'image': product['image'],
48
+ 'option': variant['title'], 'price': variant['price']})
49
+ return {'cart': cart, 'subtotal': round(sum(v['price'] * v['quantity'] for v in cart), 2),
50
+ 'theaters': value.get('saved_theaters', []), 'library': value.get('streaming_library', [])}
51
+
52
+
53
+ def update_navigation(actor_id: str, action: dict[str, Any]) -> dict[str, Any]:
54
+ with LOCK:
55
+ value = state(actor_id)
56
+ kind = action.get('kind')
57
+ if kind == 'cart':
58
+ product = NAV_PRODUCTS.get(action.get('product'))
59
+ variant = next((v for v in product['variants'] if v['id'] == action.get('variant')), None) if product else None
60
+ quantity = action.get('quantity')
61
+ if not variant or type(quantity) is not int or not 0 <= quantity <= 99:
62
+ raise ValueError('Choose a valid product, option and quantity from 0 to 99.')
63
+ if quantity and not variant['available']:
64
+ raise ValueError('This option is sold out in the captured catalog.')
65
+ lines = [v for v in value.get('fanstore_cart', []) if v['variant'] != variant['id']]
66
+ if quantity:
67
+ lines.append({'product': product['id'], 'variant': variant['id'], 'quantity': quantity})
68
+ value['fanstore_cart'] = lines
69
+ elif kind in ('theaters', 'library'):
70
+ key = 'saved_theaters' if kind == 'theaters' else 'streaming_library'
71
+ allowed = NAV_CATALOG['theaters' if kind == 'theaters' else 'streaming']
72
+ item = action.get('id')
73
+ if item not in allowed:
74
+ raise ValueError('This item is not available in the captured catalog.')
75
+ saved = value.setdefault(key, [])
76
+ if item in saved:
77
+ saved.remove(item)
78
+ else:
79
+ saved.append(item)
80
+ else:
81
+ raise ValueError('Unknown navigation action.')
82
+ _save_state(actor_id, value)
83
+ return navigation_state(actor_id)
84
+
85
+
86
+ SHOWTIME_WINDOW_DAYS = 14
87
+
88
+
89
+ def upcoming_friday() -> str:
90
+ today = date.today()
91
+ delta = (4 - today.weekday()) % 7
92
+ if delta == 0:
93
+ delta = 7
94
+ return (today + timedelta(days=delta)).isoformat()
95
+
96
+
97
+ def showtime_dates() -> list[dict[str, Any]]:
98
+ """The selectable date strip on movie and theater pages."""
99
+ today = date.today()
100
+ rows = []
101
+ for offset in range(SHOWTIME_WINDOW_DAYS):
102
+ day = today + timedelta(days=offset)
103
+ rows.append({
104
+ "date": day.isoformat(),
105
+ "weekday": "Today" if offset == 0 else ("Tomorrow" if offset == 1 else day.strftime("%a")),
106
+ "month": day.strftime("%b").upper(),
107
+ "day": day.day,
108
+ })
109
+ return rows
110
+
111
+
112
+ def valid_date(value: str) -> bool:
113
+ return any(row["date"] == value for row in showtime_dates())
114
+
115
+
116
+ def _availability(base: int, theater_id: str, showtime_id: str, on_date: str) -> int:
117
+ """Seats left varies by date so the strip is not a static repeat."""
118
+ digest = hashlib.sha256(f"{theater_id}|{showtime_id}|{on_date}".encode()).digest()
119
+ return max(4, base - digest[0] % max(1, base // 2))
120
+
121
+
122
+ THEATER_BY_ID = {row["id"]: row for row in THEATERS}
123
+
124
+ _SLOTS = {
125
+ "matinee": ("1:15 PM", 795),
126
+ "afternoon": ("4:05 PM", 965),
127
+ "early": ("6:40 PM", 1120),
128
+ "prime": ("7:30 PM", 1170),
129
+ "late": ("9:15 PM", 1275),
130
+ "night": ("10:20 PM", 1340),
131
+ }
132
+
133
+ _FORMAT_PRICE = {
134
+ "Standard": 18.49,
135
+ "RPX": 22.49,
136
+ "IMAX": 25.99,
137
+ "ScreenX": 22.99,
138
+ "4DX": 26.49,
139
+ }
140
+
141
+
142
+ def _showtimes_for(theater_id: str, slots: list[tuple[str, str, int]], on_date: str) -> list[dict[str, Any]]:
143
+ rows = []
144
+ for slot, fmt, base in slots:
145
+ time_label, minutes = _SLOTS[slot]
146
+ showtime_id = f"{slot}-{fmt.lower().replace(' ', '-')}"
147
+ rows.append({
148
+ "id": showtime_id,
149
+ "time": time_label,
150
+ "minutes": minutes,
151
+ "format": fmt,
152
+ "price": _FORMAT_PRICE[fmt],
153
+ "available": _availability(base, theater_id, showtime_id, on_date),
154
+ })
155
+ rows.sort(key=lambda row: row["minutes"])
156
+ return rows
157
+
158
+
159
+ def _movie_theaters(movie_id: str, on_date: str) -> list[dict[str, Any]]:
160
+ plan = SHOWTIMES.get(movie_id, {})
161
+ rows = [
162
+ {**THEATER_BY_ID[theater_id], "date": on_date, "showtimes": _showtimes_for(theater_id, slots, on_date)}
163
+ for theater_id, slots in plan.items()
164
+ ]
165
+ rows.sort(key=lambda row: row["distance"])
166
+ return rows
167
+
168
+
169
+ def catalog(on_date: str = "") -> list[dict[str, Any]]:
170
+ on_date = on_date if on_date and valid_date(on_date) else upcoming_friday()
171
+ return [
172
+ {**movie, "theaters": _movie_theaters(movie["id"], on_date)}
173
+ for movie in copy.deepcopy(MOVIES)
174
+ ]
175
+
176
+
177
+ def theater_directory(on_date: str = "") -> list[dict[str, Any]]:
178
+ """Every theater with the movies and showtimes playing there on a given date."""
179
+ on_date = on_date if on_date and valid_date(on_date) else upcoming_friday()
180
+ rows = []
181
+ for theater in copy.deepcopy(THEATERS):
182
+ playing = []
183
+ for movie in MOVIES:
184
+ slots = SHOWTIMES.get(movie["id"], {}).get(theater["id"])
185
+ if not slots:
186
+ continue
187
+ playing.append({
188
+ "id": movie["id"], "title": movie["title"], "rating": movie["rating"],
189
+ "runtime": movie["runtime"], "genre": movie["genre"],
190
+ "poster": movie["poster"], "year": movie["year"], "score": movie["score"],
191
+ "showtimes": _showtimes_for(theater["id"], slots, on_date),
192
+ })
193
+ rows.append({**theater, "date": on_date, "movies": playing})
194
+ rows.sort(key=lambda row: row["distance"])
195
+ return rows
196
+
197
+
198
+ SEAT_ROWS = ["A", "B", "C", "D", "E", "F", "G", "H"]
199
+ SEATS_PER_ROW = 12
200
+
201
+
202
+ def sold_seats(theater_id: str, showtime_id: str) -> list[str]:
203
+ """Deterministic per-showtime sold seats so the map is stable across reloads."""
204
+ digest = hashlib.sha256(f"{theater_id}|{showtime_id}".encode()).digest()
205
+ taken = {
206
+ f"{SEAT_ROWS[digest[index] % len(SEAT_ROWS)]}{digest[index + 1] % SEATS_PER_ROW + 1}"
207
+ for index in range(0, 24, 2)
208
+ }
209
+ return sorted(taken)
210
+
211
+
212
+ def new_actor() -> str:
213
+ return "moviegoer_" + secrets.token_urlsafe(18)
214
+
215
+
216
+ def account_actor(account: dict[str, Any]) -> str:
217
+ # This server-only namespace is never accepted from an actor cookie.
218
+ return "account:" + str(account["subject_id"])
219
+
220
+
221
+ def claim_registration_state(guest: str, account: dict[str, Any]) -> None:
222
+ """Move this guest's state to their newly created account exactly once."""
223
+ if not guest.startswith("moviegoer_"):
224
+ return
225
+ owner = account_actor(account)
226
+ with LOCK, backend.lifecycle.connection(transaction=True) as connection:
227
+ if connection.execute("SELECT 1 FROM fandango_actor_state WHERE actor_id=?", (owner,)).fetchone():
228
+ return
229
+ connection.execute("UPDATE fandango_actor_state SET actor_id=? WHERE actor_id=?", (owner, guest))
230
+
231
+
232
+ def offers() -> list[dict[str, Any]]:
233
+ """The rotating promo band above the fold, built from the captured lineup."""
234
+ now_playing = [row for row in MOVIES if row["status"] == "now-playing"]
235
+ coming_soon = [row for row in MOVIES if row["status"] == "coming-soon"]
236
+ templates = [
237
+ ("Buy a ticket to {title}", "Join FanClub with your ticket order to get 2 free tickets to use later."),
238
+ ("Pre-order {title} now", "Save $5 when you buy your ticket before opening weekend."),
239
+ ("See {title} in a premium format", "ScreenX, 4DX and IMAX auditoriums are bookable at checkout."),
240
+ ("{title} is now playing", "Reserve seats at a theater near New York, NY."),
241
+ ]
242
+ picks = (now_playing[:2] + coming_soon[:1] + now_playing[2:3])
243
+ rows = []
244
+ for index, movie in enumerate(picks):
245
+ headline, detail = templates[index % len(templates)]
246
+ rows.append({
247
+ "id": f"offer-{movie['id']}",
248
+ "movie_id": movie["id"],
249
+ "headline": headline.format(title=movie["title"]),
250
+ "detail": detail + " Captured source promotion; discounts and rewards are not applied to local simulated bookings.",
251
+ })
252
+ return rows
253
+
254
+
255
+ def featured_thriller() -> dict[str, Any]:
256
+ """The ClawBench task targets a currently showing thriller at Regal Union Square."""
257
+ return next(
258
+ row for row in MOVIES
259
+ if row["status"] == "now-playing"
260
+ and "Suspense/Thriller" in (row.get("genres") or [])
261
+ and "regal-union-square" in SHOWTIMES.get(row["id"], {})
262
+ )
263
+
264
+
265
+ def _seed_booking() -> dict[str, Any]:
266
+ movie = featured_thriller()
267
+ theater = THEATER_BY_ID["regal-union-square"]
268
+ slot, fmt, _ = SHOWTIMES[movie["id"]]["regal-union-square"][2]
269
+ time_label, _ = _SLOTS[slot]
270
+ unit = _FORMAT_PRICE[fmt]
271
+ subtotal = round(unit * 3, 2)
272
+ fees = round(2.29 * 3, 2)
273
+ return {
274
+ "id": "FDG-SEED-2048",
275
+ "status": "Upcoming",
276
+ "movie": movie["title"],
277
+ "genre": movie["genre"],
278
+ "theater": theater["name"],
279
+ "location": theater["location"],
280
+ "date": upcoming_friday(),
281
+ "time": time_label,
282
+ "format": fmt,
283
+ "tickets": 3,
284
+ "seats": ["E5", "E6", "E7"],
285
+ "total": round(subtotal + fees + (subtotal + fees) * 0.08875, 2),
286
+ "contact_status": None,
287
+ "review": None,
288
+ }
289
+
290
+
291
+ def _new_state() -> dict[str, Any]:
292
+ return {
293
+ "favorites": [],
294
+ "selection": {},
295
+ "bookings": [_seed_booking()],
296
+ "profile": None,
297
+ }
298
+
299
+
300
+ def state(actor: str) -> dict[str, Any]:
301
+ with LOCK:
302
+ with backend.lifecycle.connection(transaction=True) as connection:
303
+ row = connection.execute("SELECT state_json FROM fandango_actor_state WHERE actor_id=?", (actor,)).fetchone()
304
+ if row:
305
+ return json.loads(str(row["state_json"]))
306
+ value = _new_state()
307
+ connection.execute(
308
+ "INSERT INTO fandango_actor_state(actor_id,state_json,updated_at) VALUES(?,?,?)",
309
+ (actor, json.dumps(value, separators=(",", ":")), int(time.time())),
310
+ )
311
+ return value
312
+
313
+
314
+ def _save_state(actor: str, value: dict[str, Any], connection=None) -> None:
315
+ if connection is None:
316
+ with backend.lifecycle.connection(transaction=True) as transaction:
317
+ _save_state(actor, value, transaction)
318
+ return
319
+ connection.execute(
320
+ "INSERT INTO fandango_actor_state(actor_id,state_json,updated_at) VALUES(?,?,?) ON CONFLICT(actor_id) DO UPDATE SET state_json=excluded.state_json,updated_at=excluded.updated_at",
321
+ (actor, json.dumps(value, separators=(",", ":")), int(time.time())),
322
+ )
323
+
324
+
325
+ def _booked_seats(selection: dict[str, Any], connection=None, *, exclude_id: str | None = None) -> set[str]:
326
+ """Read durable bookings, including pre-upgrade orders, for this screening.
327
+
328
+ Display names/time/format are the immutable screening fields that older
329
+ orders already store. The per-actor demo order is not a real reservation.
330
+ A caller making a reservation must hold the same BEGIN IMMEDIATE transaction
331
+ across this read and its order write, not just the process-local LOCK.
332
+ """
333
+ if connection is None:
334
+ with backend.lifecycle.connection() as reader:
335
+ return _booked_seats(selection, reader, exclude_id=exclude_id)
336
+ fields = ("movie", "theater", "date", "time", "format")
337
+ seats: set[str] = set()
338
+ for row in connection.execute("SELECT state_json FROM fandango_actor_state"):
339
+ for booking in json.loads(row["state_json"]).get("bookings", []):
340
+ if booking["id"] in ("FDG-SEED-2048", exclude_id) or booking["status"] == "Cancelled":
341
+ continue
342
+ if all(booking.get(field) == selection.get(field) for field in fields):
343
+ seats.update(booking["seats"])
344
+ return seats
345
+
346
+
347
+ def ensure_auth_session(token: str | None) -> tuple[str, dict[str, Any]]:
348
+ return auth.ensure_session(token)
349
+
350
+
351
+ def resolve_account(token: str | None) -> dict[str, Any] | None:
352
+ return auth.resolve_session(token)
353
+
354
+
355
+ def bootstrap(actor: str, account: dict[str, Any] | None = None) -> dict[str, Any]:
356
+ with LOCK:
357
+ current = state(actor)
358
+ selection = current["selection"]
359
+ if selection:
360
+ selection["sold_seats"] = sorted(set(sold_seats(selection["theater_id"], selection["showtime_id"])) | _booked_seats(selection))
361
+ return {
362
+ "movies": catalog(),
363
+ "theaters": copy.deepcopy(THEATERS),
364
+ "genres": genres(),
365
+ "dates": showtime_dates(),
366
+ "featured": {k: featured_thriller()[k] for k in ("id", "title", "poster")},
367
+ "offers": offers(),
368
+ "friday": upcoming_friday(),
369
+ **copy.deepcopy(current),
370
+ "profile": account,
371
+ }
372
+
373
+
374
+ def genres() -> list[str]:
375
+ """Every genre a source movie is tagged with, not just its primary one."""
376
+ return sorted({name for movie in MOVIES for name in movie.get("genres") or [movie["genre"]]})
377
+
378
+
379
+ def search(query: str = "", genre: str = "", sort: str = "rating", max_price: float | None = None,
380
+ service: str = "", status: str = "", theater: str = "") -> list[dict[str, Any]]:
381
+ rows = copy.deepcopy(catalog())
382
+ q = query.strip().lower()
383
+ if q:
384
+ rows = [
385
+ row for row in rows
386
+ if q in row["title"].lower() or q in row["synopsis"].lower()
387
+ or any(q in name.lower() for name in row.get("genres") or [row["genre"]])
388
+ or any(q in item["name"].lower() for item in row["theaters"])
389
+ ]
390
+ if status:
391
+ rows = [row for row in rows if row["status"] == status]
392
+ if theater:
393
+ rows = [row for row in rows if any(item["id"] == theater for item in row["theaters"])]
394
+ if genre:
395
+ wanted = genre.lower()
396
+ rows = [row for row in rows
397
+ if wanted in {name.lower() for name in row.get("genres") or [row["genre"]]}]
398
+ if max_price is not None:
399
+ rows = [row for row in rows if any(show["price"] <= max_price for theater in row["theaters"] for show in theater["showtimes"])]
400
+ if service:
401
+ rows = [row for row in rows if any(service in theater["services"] for theater in row["theaters"])]
402
+ if sort == "title":
403
+ rows.sort(key=lambda row: row["title"])
404
+ elif sort == "price":
405
+ rows.sort(key=lambda row: min([show["price"] for theater in row["theaters"] for show in theater["showtimes"]] or [999]))
406
+ else:
407
+ rows.sort(key=lambda row: row["score"], reverse=True)
408
+ return rows
409
+
410
+
411
+ def movie(movie_id: str, on_date: str = "") -> dict[str, Any] | None:
412
+ return next((row for row in catalog(on_date) if row["id"] == movie_id), None)
413
+
414
+
415
+ def toggle_favorite(actor: str, movie_id: str) -> dict[str, Any]:
416
+ if not movie(movie_id):
417
+ raise KeyError(movie_id)
418
+ with LOCK:
419
+ current = state(actor)
420
+ favorites = current["favorites"]
421
+ if movie_id in favorites:
422
+ favorites.remove(movie_id)
423
+ saved = False
424
+ else:
425
+ favorites.append(movie_id)
426
+ saved = True
427
+ _save_state(actor, current)
428
+ return {"saved": saved, "favorites": copy.deepcopy(favorites)}
429
+
430
+
431
+ def select_showtime(actor: str, movie_id: str, theater_id: str, showtime_id: str, selected_date: str) -> dict[str, Any]:
432
+ if not valid_date(selected_date):
433
+ raise ValueError("Choose a date within the next two weeks")
434
+ row = movie(movie_id, selected_date)
435
+ if not row:
436
+ raise ValueError("Movie not found")
437
+ theater = next((item for item in row["theaters"] if item["id"] == theater_id), None)
438
+ showtime = next((item for item in theater["showtimes"] if item["id"] == showtime_id), None) if theater else None
439
+ if not theater or not showtime:
440
+ raise ValueError("Showtime not found")
441
+ with LOCK:
442
+ current = state(actor)
443
+ selection = {
444
+ "movie_id": movie_id,
445
+ "movie": row["title"],
446
+ "genre": row["genre"],
447
+ "theater_id": theater_id,
448
+ "theater": theater["name"],
449
+ "location": theater["location"],
450
+ "date": selected_date,
451
+ "showtime_id": showtime_id,
452
+ "time": showtime["time"],
453
+ "format": showtime["format"],
454
+ "unit_price": showtime["price"],
455
+ "ticket_count": 0,
456
+ "ticket_types": {},
457
+ "seats": [],
458
+ "sold_seats": sold_seats(theater_id, showtime_id),
459
+ "seat_rows": SEAT_ROWS,
460
+ "seats_per_row": SEATS_PER_ROW,
461
+ }
462
+ selection["sold_seats"] = sorted(set(selection["sold_seats"]) | _booked_seats(selection))
463
+ current["selection"] = selection
464
+ _save_state(actor, current)
465
+ return copy.deepcopy(selection)
466
+
467
+
468
+ def _review_inputs(selection: dict[str, Any]) -> dict[str, Any]:
469
+ return {key: copy.deepcopy(selection.get(key)) for key in (
470
+ "movie_id", "theater_id", "showtime_id", "date", "unit_price",
471
+ "ticket_count", "ticket_types", "seats",
472
+ )}
473
+
474
+
475
+ def _invalidate_review(selection: dict[str, Any]) -> None:
476
+ for key in ("subtotal", "fees", "tax", "total", "payment_adapter", "is_simulation", "reviewed_selection"):
477
+ selection.pop(key, None)
478
+
479
+
480
+ def set_tickets(actor: str, adults: int, children: int = 0, seniors: int = 0) -> dict[str, Any]:
481
+ if any(type(value) is not int or value < 0 or value > 8 for value in (adults, children, seniors)):
482
+ raise ValueError("Ticket quantities must be whole numbers from 0 to 8")
483
+ count = adults + children + seniors
484
+ if count < 1 or count > 8:
485
+ raise ValueError("Choose between 1 and 8 tickets")
486
+ with LOCK:
487
+ current = state(actor)
488
+ selection = current["selection"]
489
+ if not selection:
490
+ raise ValueError("Select a showtime first")
491
+ selection["ticket_count"] = count
492
+ selection["ticket_types"] = {"Adult": adults, "Child": children, "Senior": seniors}
493
+ selection["seats"] = []
494
+ _invalidate_review(selection)
495
+ _save_state(actor, current)
496
+ return copy.deepcopy(selection)
497
+
498
+
499
+ def set_seats(actor: str, seats: list[str]) -> dict[str, Any]:
500
+ with LOCK:
501
+ current = state(actor)
502
+ selection = current["selection"]
503
+ if not selection or not selection.get("ticket_count"):
504
+ raise ValueError("Select a showtime and tickets first")
505
+ if not isinstance(seats, list) or not seats or any(not isinstance(seat, str) for seat in seats):
506
+ raise ValueError("Select one seat for each ticket")
507
+ if len(seats) != selection.get("ticket_count", 0):
508
+ raise ValueError("Select one seat for each ticket")
509
+ valid_seats = {f"{row}{number}" for row in SEAT_ROWS for number in range(1, SEATS_PER_ROW + 1)}
510
+ if any(seat not in valid_seats for seat in seats):
511
+ raise ValueError("Choose seats from the displayed seat map")
512
+ parsed = [(seat[0], int(seat[1:])) for seat in seats if len(seat) >= 2]
513
+ if len(parsed) != len(seats) or len({seat for seat in seats}) != len(seats):
514
+ raise ValueError("Seats must be unique")
515
+ taken = set(sold_seats(selection["theater_id"], selection["showtime_id"])) | _booked_seats(selection)
516
+ conflict = [seat for seat in seats if seat in taken]
517
+ if conflict:
518
+ raise ValueError(f"Seat {', '.join(conflict)} is already sold for this showtime")
519
+ if len({row for row, _ in parsed}) != 1:
520
+ raise ValueError("Choose adjacent seats in one row")
521
+ numbers = sorted(number for _, number in parsed)
522
+ if numbers != list(range(numbers[0], numbers[0] + len(numbers))):
523
+ raise ValueError("Choose adjacent seats")
524
+ row_letter = parsed[0][0]
525
+ selection["seats"] = [f"{row_letter}{number}" for number in numbers]
526
+ _invalidate_review(selection)
527
+ _save_state(actor, current)
528
+ return copy.deepcopy(selection)
529
+
530
+
531
+ def review(actor: str, email: str, postal_code: str) -> dict[str, Any]:
532
+ with LOCK:
533
+ current = state(actor)
534
+ selection = current["selection"]
535
+ if not email or "@" not in email:
536
+ raise ValueError("Enter a valid email")
537
+ if len(postal_code.strip()) < 5:
538
+ raise ValueError("Enter a billing ZIP or postal code")
539
+ if not selection.get("seats"):
540
+ raise ValueError("Select seats before review")
541
+ subtotal = round(selection["unit_price"] * selection["ticket_count"], 2)
542
+ fees = round(2.29 * selection["ticket_count"], 2)
543
+ tax = round((subtotal + fees) * 0.08875, 2)
544
+ total = round(subtotal + fees + tax, 2)
545
+ selection["contact_email"] = email.strip().lower()
546
+ selection["billing_postal_code"] = postal_code.strip()
547
+ selection["subtotal"] = subtotal
548
+ selection["fees"] = fees
549
+ selection["tax"] = tax
550
+ selection["total"] = total
551
+ selection["payment_adapter"] = "local-sandbox"
552
+ selection["is_simulation"] = True
553
+ selection["reviewed_selection"] = _review_inputs(selection)
554
+ _save_state(actor, current)
555
+ return copy.deepcopy(selection)
556
+
557
+
558
+ def confirm(actor: str) -> dict[str, Any]:
559
+ # BEGIN IMMEDIATE serializes conflict check + order write across processes.
560
+ with LOCK, backend.lifecycle.connection(transaction=True) as connection:
561
+ row = connection.execute("SELECT state_json FROM fandango_actor_state WHERE actor_id=?", (actor,)).fetchone()
562
+ current = json.loads(row["state_json"]) if row else _new_state()
563
+ selection = current["selection"]
564
+ if not selection.get("total") or selection.get("reviewed_selection") != _review_inputs(selection):
565
+ raise ValueError("Review the booking first")
566
+ if not selection.get("seats") or len(selection["seats"]) != selection.get("ticket_count"):
567
+ raise ValueError("Select one seat for each ticket and review the booking again")
568
+ conflict = sorted(set(selection["seats"]) & _booked_seats(selection, connection))
569
+ if conflict:
570
+ raise ValueError(f"Seat {', '.join(conflict)} is already sold for this showtime")
571
+ booking = {
572
+ "id": f"FDG-{uuid.uuid4().hex[:8].upper()}",
573
+ "status": "Confirmed (Local Simulation)",
574
+ "movie": selection["movie"],
575
+ "genre": selection["genre"],
576
+ "theater": selection["theater"],
577
+ "location": selection["location"],
578
+ "date": selection["date"],
579
+ "time": selection["time"],
580
+ "format": selection["format"],
581
+ "tickets": selection["ticket_count"],
582
+ "seats": copy.deepcopy(selection["seats"]),
583
+ "total": selection["total"],
584
+ "contact_status": None,
585
+ "review": None,
586
+ }
587
+ current["bookings"].insert(0, booking)
588
+ current["selection"] = {}
589
+ _save_state(actor, current, connection)
590
+ return copy.deepcopy(booking)
591
+
592
+
593
+ def update_booking(actor: str, booking_id: str, action: str, value: Any = None) -> dict[str, Any]:
594
+ with LOCK, backend.lifecycle.connection(transaction=True) as connection:
595
+ row = connection.execute("SELECT state_json FROM fandango_actor_state WHERE actor_id=?", (actor,)).fetchone()
596
+ current = json.loads(row["state_json"]) if row else _new_state()
597
+ booking = next((row for row in current["bookings"] if row["id"] == booking_id), None)
598
+ if not booking:
599
+ raise KeyError(booking_id)
600
+ if action == "cancel":
601
+ booking["status"] = "Cancelled"
602
+ elif action == "reschedule":
603
+ if booking["status"] == "Cancelled":
604
+ raise ValueError("Cancelled bookings cannot be rescheduled; book again instead")
605
+ if not isinstance(value, str) or not valid_date(value):
606
+ raise ValueError("Choose an available showtime date")
607
+ target = {**booking, "date": value}
608
+ conflict = sorted(set(booking["seats"]) & _booked_seats(target, connection, exclude_id=booking_id))
609
+ if conflict:
610
+ raise ValueError(f"Seat {', '.join(conflict)} is already sold for this showtime")
611
+ booking["date"] = target["date"]
612
+ booking["status"] = "Rescheduled"
613
+ elif action == "contact":
614
+ booking["contact_status"] = "Local message saved — nothing was sent"
615
+ elif action == "review":
616
+ booking["review"] = str(value or "5-star local review")
617
+ elif action == "book-again":
618
+ target = next((row for row in MOVIES if row["title"] == booking["movie"]), featured_thriller())
619
+ theater_id = next(iter(SHOWTIMES.get(target["id"], {})), "regal-union-square")
620
+ slot, fmt, _ = SHOWTIMES[target["id"]][theater_id][0]
621
+ time_label, _ = _SLOTS[slot]
622
+ theater = THEATER_BY_ID[theater_id]
623
+ current["selection"] = {
624
+ "movie_id": target["id"], "movie": target["title"], "genre": target["genre"],
625
+ "theater_id": theater_id, "theater": theater["name"], "location": theater["location"],
626
+ "date": upcoming_friday(),
627
+ "showtime_id": f"{slot}-{fmt.lower().replace(' ', '-')}",
628
+ "time": time_label, "format": fmt, "unit_price": _FORMAT_PRICE[fmt],
629
+ "ticket_count": booking["tickets"], "ticket_types": {"Adult": booking["tickets"]}, "seats": [],
630
+ "sold_seats": sold_seats(theater_id, f"{slot}-{fmt.lower().replace(' ', '-')}"),
631
+ "seat_rows": SEAT_ROWS, "seats_per_row": SEATS_PER_ROW,
632
+ }
633
+ else:
634
+ raise ValueError("Unknown booking action")
635
+ _save_state(actor, current, connection)
636
+ return {"booking": copy.deepcopy(booking), "selection": copy.deepcopy(current["selection"])}
637
+
638
+
639
+ def register(display_name: str, email: str, password: str) -> dict[str, Any]:
640
+ details = auth.validate_registration_details(email=email, display_name=display_name, password=password)
641
+ if auth.account_exists(details["email"]):
642
+ raise ValueError("An account already exists for this email")
643
+ subject = "moviegoer_" + hashlib.sha256(details["email"].encode()).hexdigest()[:20]
644
+ auth.seed_account(subject_id=subject, email=details["email"], display_name=details["display_name"], password=details["password"], email_verified=True)
645
+ return {"subject_id": subject, "display_name": details["display_name"], "email_normalized": details["email"]}
646
+
647
+
648
+ def login(session_token: str, email: str, password: str) -> dict[str, Any]:
649
+ return auth.sign_in(session_token, email=email, password=password)
650
+
651
+
652
+ def logout(session_token: str | None) -> None:
653
+ auth.sign_out(session_token)
654
+
655
+
656
+ def reset() -> None:
657
+ def site_reset(connection):
658
+ connection.execute("DELETE FROM fandango_actor_state")
659
+ auth.reset_site_state(site_reset=site_reset, seed_accounts=[])
tasks/fandango/environment/reference/clone/frontend/index.html ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <meta name="theme-color" content="#121212">
7
+ <meta name="description" content="Buy movie tickets, find showtimes and browse theaters near you on Fandango.">
8
+ <title>Movie Tickets &amp; Movie Times | Fandango</title>
9
+ <link rel="stylesheet" href="/static/site.css?v=4">
10
+ <link rel="stylesheet" href="/static/home.css?v=4">
11
+ <script src="/static/home-data.js?v=4" defer></script>
12
+ <script src="/static/home.js?v=5" defer></script>
13
+ <link rel="stylesheet" href="/static/navigation.css?v=1">
14
+ <script src="/static/navigation-data.js?v=1" defer></script>
15
+ <script src="/static/navigation.js?v=1" defer></script>
16
+ <script src="/static/app.js?v=6" defer></script>
17
+ </head>
18
+ <body data-route="__ROUTE__">
19
+ <div id="app"></div>
20
+ <div id="toast" role="status" aria-live="polite"></div>
21
+ </body>
22
+ </html>
tasks/fandango/environment/reference/clone/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastapi>=0.115,<1
2
+ uvicorn>=0.30,<1
tasks/fandango/environment/reference/clone/static/app.js ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const root = document.querySelector('#app');
2
+ const toast = document.querySelector('#toast');
3
+ const state = {data:null, search:[], selectedSeats:[], checkoutReview:null, confirmation:null, theaters:null};
4
+
5
+ function esc(value='') { return String(value).replace(/[&<>'"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[c])); }
6
+ function money(value) { return new Intl.NumberFormat('en-US',{style:'currency',currency:'USD'}).format(Number(value||0)); }
7
+ function longDate(value) {
8
+ if (!value) return '';
9
+ const [y,m,d] = value.split('-').map(Number);
10
+ return new Intl.DateTimeFormat('en-US',{weekday:'short',month:'short',day:'numeric',timeZone:'UTC'}).format(new Date(Date.UTC(y,m-1,d)));
11
+ }
12
+ async function api(path, options={}) {
13
+ const response = await fetch(path,{headers:{'Content-Type':'application/json',...(options.headers||{})},...options});
14
+ let data={}; try{data=await response.json();}catch(_){ }
15
+ if(!response.ok) throw new Error(data.error||`Request failed (${response.status})`);
16
+ return data;
17
+ }
18
+ function notify(message){ toast.textContent=message; toast.classList.add('show'); clearTimeout(notify.timer); notify.timer=setTimeout(()=>toast.classList.remove('show'),2400); }
19
+ function go(path){ history.pushState({},'',path); state.checkoutReview=null; render(); window.scrollTo(0,0); }
20
+ async function refresh(){ state.data=await api('/api/bootstrap'); return state.data; }
21
+
22
+ /* ---------- chrome ---------- */
23
+ function header(){ return homeHeader(); }
24
+ function layout(content){ document.body.className='fandango-page'; root.innerHTML=`${header()}<main>${content}</main>${homeFooter()}`; bindGlobal(); bindHomePromo(); bindNavigationChrome(); }
25
+
26
+ /* ---------- posters + cards ---------- */
27
+ function posterMarkup(movie, extra=''){
28
+ return `<div class="poster">${extra}<img src="${esc(movie.poster)}" alt="${esc(movie.title)} (${movie.year}) movie poster" loading="lazy" width="400" height="592"></div>`;
29
+ }
30
+ function scoreBadge(movie){
31
+ if(!movie.score) return `<span class="score-badge">Not yet scored</span>`;
32
+ return `<span class="score-badge ${movie.score>=85?'fresh':''}"><i></i>${movie.score}% Audience</span>`;
33
+ }
34
+ function movieCard(movie){
35
+ const soon=movie.status==='coming-soon';
36
+ return `<article class="movie-card" data-movie-card="${movie.id}">
37
+ <a class="poster-link" href="/movies/${movie.id}" data-link aria-label="${esc(movie.title)} (${movie.year})">${posterMarkup(movie, soon?'<span class="presale">PRE-SALE</span>':'')}</a>
38
+ <h3><a href="/movies/${movie.id}" data-link>${esc(movie.title)} (${movie.year})</a></h3>
39
+ ${movie.score?scoreBadge(movie):''}
40
+ </article>`;
41
+ }
42
+
43
+ /* ---------- home ---------- */
44
+ function home(){
45
+ renderHome();
46
+ }
47
+
48
+ /* ---------- listing ---------- */
49
+ async function moviesPage(){
50
+ const params=new URLSearchParams(location.search);
51
+ const query=params.get('q')||'';
52
+ const genre=params.get('genre')||'';
53
+ const sort=params.get('sort')||'rating';
54
+ const maxPrice=params.get('max_price')||'';
55
+ const service=params.get('service')||'';
56
+ // "Now Playing" is the default tab, matching the source listing page.
57
+ const status=params.get('status')||(params.get('q')?'':'now-playing');
58
+ const theater=params.get('theater')||'';
59
+ const showFilters=params.get('filters')==='1'||genre||maxPrice||service||theater||query;
60
+ const search=new URLSearchParams({q:query,genre,sort,service,status,theater});
61
+ if(maxPrice) search.set('max_price',maxPrice);
62
+ const data=await api(`/api/movies?${search}`);
63
+ state.search=data.movies;
64
+ const tab=path=>{const p=new URLSearchParams(location.search);if(path)p.set('status',path);else p.delete('status');return `/movies?${p}`;};
65
+ layout(`<div class="shell">
66
+ <nav class="listing-tabs">
67
+ <a class="${status==='coming-soon'?'':'active'}" href="${tab('')}" data-link><span aria-hidden="true">🎬</span>Now Playing</a>
68
+ <a class="${status==='coming-soon'?'active':''}" href="${tab('coming-soon')}" data-link><span aria-hidden="true">📅</span>Coming Soon</a>
69
+ <button class="filter-toggle" type="button" data-toggle-filters>Filters <span aria-hidden="true">⚙</span></button>
70
+ </nav>
71
+ ${showFilters?`<div class="filters"><form data-filter>
72
+ <label>Keyword<input name="q" value="${esc(query)}" placeholder="Movie, genre or theater"></label>
73
+ <label>Genre<select name="genre"><option value="">All genres</option>${(data.genres||[]).map(g=>`<option ${genre===g?'selected':''}>${esc(g)}</option>`).join('')}</select></label>
74
+ <label>Theater<select name="theater"><option value="">All theaters</option>${(data.theaters||[]).map(t=>`<option value="${t.id}" ${theater===t.id?'selected':''}>${esc(t.name)}</option>`).join('')}</select></label>
75
+ <label>Max ticket price<select name="max_price"><option value="">Any price</option><option value="26" ${maxPrice==='26'?'selected':''}>Under $26</option><option value="20" ${maxPrice==='20'?'selected':''}>Under $20</option><option value="18.5" ${maxPrice==='18.5'?'selected':''}>Under $18.50</option></select></label>
76
+ <label>Service<select name="service"><option value="">Any service</option>${['Reserved Seating','Mobile Ticket','Closed Caption','IMAX','Dolby Cinema','RPX'].map(s=>`<option ${service===s?'selected':''}>${esc(s)}</option>`).join('')}</select></label>
77
+ <label>Sort<select name="sort"><option value="rating" ${sort==='rating'?'selected':''}>Audience rating</option><option value="price" ${sort==='price'?'selected':''}>Lowest price</option><option value="title" ${sort==='title'?'selected':''}>Title A–Z</option></select></label>
78
+ <input type="hidden" name="status" value="${esc(status)}"><input type="hidden" name="filters" value="1">
79
+ <button type="submit">Apply</button></form></div>`:''}
80
+ <h1 class="section-title" style="margin-top:26px">${query?`Results for “${esc(query)}”`:status==='coming-soon'?'Coming Soon To Theaters':'Movies In Theaters'}</h1>
81
+ ${query?`<p class="card-meta">Searching now playing and coming soon.</p>`:''}
82
+ <p class="result-count">${data.movies.length} movie${data.movies.length===1?'':'s'} near New York, NY for ${longDate(state.data.friday)}</p>
83
+ ${data.movies.length
84
+ ? `<div class="poster-grid">${data.movies.map(movieCard).join('')}</div>`
85
+ : `<div class="empty"><h2>No movies found</h2><p>We couldn’t find anything matching <strong>${esc(query||'those filters')}</strong>.</p><a class="primary" href="/movies" data-link>Browse available movies</a></div>`}
86
+ </div>`);
87
+ root.querySelector('[data-filter]')?.addEventListener('submit',event=>{event.preventDefault();const p=new URLSearchParams(new FormData(event.currentTarget));[...p.keys()].forEach(k=>{if(!p.get(k))p.delete(k);});go(`/movies?${p}`);});
88
+ root.querySelector('[data-toggle-filters]')?.addEventListener('click',()=>{const p=new URLSearchParams(location.search);showFilters?p.delete('filters'):p.set('filters','1');go(`/movies?${p}`);});
89
+ }
90
+
91
+ /* ---------- movie detail ---------- */
92
+ function findMovie(movieId){ return state.data.movies.find(row=>row.id===movieId); }
93
+ function showtimeButtons(movieId, theater, onDate){
94
+ const date=onDate||theater.date||state.data.friday;
95
+ return theater.showtimes.map(show=>`<button data-showtime data-movie="${movieId}" data-theater="${theater.id}" data-show="${show.id}" data-date="${date}"><strong>${show.time}</strong><small>${esc(show.format)}</small><small>${money(show.price)} · ${show.available} seats</small></button>`).join('');
96
+ }
97
+ function theaterDetail(movie, theater, onDate){
98
+ return `<article class="showtime-theater"><header><div><h3><a href="/theaters/${theater.id}" data-link>${esc(theater.name)}</a></h3><p>${esc(theater.location)} · ${theater.distance} mi</p><p>${theater.services.map(esc).join(' · ')}</p></div><span class="availability">Tickets available</span></header><div class="showtimes">${showtimeButtons(movie.id, theater, onDate)}</div><details><summary>Policies &amp; amenities</summary><p>${esc(theater.policy)}</p></details></article>`;
99
+ }
100
+ function dateStrip(dates, selected, hrefFor){
101
+ return `<div class="date-strip" role="group" aria-label="Choose a showtime date">${dates.map(row=>`<a class="date-tile ${row.date===selected?'active':''}" href="${hrefFor(row.date)}" data-link aria-current="${row.date===selected}"><small>${esc(row.weekday)}</small><span>${esc(row.month)}</span><strong>${row.day}</strong></a>`).join('')}</div>`;
102
+ }
103
+ function formatChips(formats, selected, hrefFor){
104
+ return `<div class="format-chips" role="group" aria-label="Filter by format"><a class="chip ${selected?'':'active'}" href="${hrefFor('')}" data-link>All</a>${formats.map(f=>`<a class="chip ${selected===f?'active':''}" href="${hrefFor(f)}" data-link>${esc(f)}</a>`).join('')}</div>`;
105
+ }
106
+ async function moviePage(movieId){
107
+ const params=new URLSearchParams(location.search);
108
+ const wanted=params.get('date')||'';
109
+ const format=params.get('format')||'';
110
+ let data;
111
+ try{ data=await api(`/api/movies/${encodeURIComponent(movieId)}?date=${encodeURIComponent(wanted)}`); }
112
+ catch(_){ notFound(); return; }
113
+ const movie=data.movie, selectedDate=data.date;
114
+ const saved=state.data.favorites.includes(movie.id);
115
+ const formats=[...new Set(movie.theaters.flatMap(t=>t.showtimes.map(s=>s.format)))];
116
+ const shown=movie.theaters
117
+ .map(theater=>({...theater, showtimes: format?theater.showtimes.filter(s=>s.format===format):theater.showtimes}))
118
+ .filter(theater=>theater.showtimes.length);
119
+ const href=(d,f)=>{const p=new URLSearchParams(location.search);d?p.set('date',d):p.delete('date');f?p.set('format',f):p.delete('format');const q=p.toString();return `/movies/${movie.id}${q?'?'+q:''}`;};
120
+ layout(`<section class="movie-hero"><div class="shell movie-hero-grid">
121
+ ${posterMarkup(movie)}
122
+ <div><p class="eyebrow">${esc(movie.genre)}</p><h1>${esc(movie.title)} (${movie.year})</h1>
123
+ <p class="rating-chip">${esc(movie.rating)}</p>
124
+ <div class="scores">${scoreBadge(movie)}${movie.critic_score?`<span class="score-badge"><i></i>${movie.critic_score}% Critics</span>`:''}<span class="card-meta">${[movie.runtime, movie.director?`Directed by ${movie.director}`:''].filter(Boolean).map(esc).join(' · ')}</span></div>
125
+ ${movie.synopsis?`<p class="synopsis">${esc(movie.synopsis)}</p>`:''}
126
+ ${movie.cast?`<p class="synopsis"><strong>Cast:</strong> ${esc(movie.cast)}</p>`:''}
127
+ <div class="hero-actions"><button class="save-btn" type="button" disabled>▶ Trailer</button><button class="save-btn" data-favorite="${movie.id}">${saved?'★ Saved to My Movies':'♡ Save to My Movies'}</button></div></div>
128
+ </div></section>
129
+ <div class="shell"><section class="section"><div class="section-head"><div><p class="eyebrow">Theaters near New York, NY</p><h2>Showtimes for ${longDate(selectedDate)}</h2></div><a href="/theaters" data-link>Browse all theaters</a></div>
130
+ ${dateStrip(data.dates, selectedDate, d=>href(d,format))}
131
+ ${formats.length>1?formatChips(formats, format, f=>href(selectedDate===state.data.friday?'':selectedDate, f)):''}
132
+ ${shown.length?shown.map(theater=>theaterDetail(movie,theater,selectedDate)).join(''):`<div class="empty"><h2>No showtimes for this selection</h2><p>Try another date or format.</p><a class="primary" href="${href('','')}" data-link>Reset filters</a></div>`}</section></div>`);
133
+ bindShowtimes();
134
+ }
135
+
136
+ /* ---------- theaters ---------- */
137
+ async function theatersPage(theaterId=''){
138
+ const wanted=new URLSearchParams(location.search).get('date')||'';
139
+ const data=await api(`/api/theaters?date=${encodeURIComponent(wanted)}`);
140
+ state.theaters=data.theaters;
141
+ const selectedDate=data.date;
142
+ const rows=theaterId?data.theaters.filter(t=>t.id===theaterId):data.theaters;
143
+ if(theaterId && !rows.length){notFound();return;}
144
+ const href=d=>`${theaterId?`/theaters/${theaterId}`:'/theaters'}${d?`?date=${d}`:''}`;
145
+ layout(`<section class="page-title"><div class="shell"><p class="eyebrow">Theaters</p>
146
+ <h1>${theaterId?esc(rows[0].name):'Movie Theaters Near New York, NY'}</h1>
147
+ <p>${theaterId?`${esc(rows[0].location)} · ${rows[0].distance} mi away`:'Compare distance, amenities, formats and showtimes near you.'}</p>
148
+ ${dateStrip(data.dates, selectedDate, href)}</div></section>
149
+ <div class="shell">${rows.map(theater=>`<section class="section"><div class="section-head"><div><h2>${esc(theater.name)}</h2><p class="card-meta">${esc(theater.location)} · ${theater.distance} mi · ${theater.services.map(esc).join(' · ')}</p></div>${theaterId?'':`<a href="/theaters/${theater.id}" data-link>See theater</a>`}</div>
150
+ ${theater.movies.length?theater.movies.map(movie=>`<article class="theater-movie">${posterMarkup(movie)}<div><h3><a href="/movies/${movie.id}" data-link>${esc(movie.title)}</a></h3><p class="card-meta">${[movie.rating, movie.runtime, movie.score?`${movie.score}% Audience`:''].filter(Boolean).map(esc).join(' · ')}</p><div class="showtimes">${showtimeButtons(movie.id, {id:theater.id, showtimes:movie.showtimes, date:selectedDate})}</div></div></article>`).join(''):'<p class="card-meta">No showtimes scheduled at this theater.</p>'}
151
+ <details><summary>Policies &amp; amenities</summary><p>${esc(theater.policy)}</p></details></section>`).join('')}</div>`);
152
+ bindShowtimes();
153
+ }
154
+ function bindShowtimes(){
155
+ root.querySelectorAll('[data-showtime]').forEach(button=>button.addEventListener('click',async()=>{
156
+ try{
157
+ await api('/api/selection/showtime',{method:'POST',body:JSON.stringify({movie_id:button.dataset.movie,theater_id:button.dataset.theater,showtime_id:button.dataset.show,date:button.dataset.date})});
158
+ await refresh(); state.selectedSeats=[]; go('/tickets');
159
+ }catch(err){notify(err.message);}
160
+ }));
161
+ }
162
+
163
+ /* ---------- booking ---------- */
164
+ function bookingSteps(active){ const steps=['Tickets','Seats','Review','Confirmation']; return `<ol class="steps">${steps.map((step,i)=>`<li class="${i<=active?'active':''}"><span>${i+1}</span>${step}</li>`).join('')}</ol>`; }
165
+ function selectionSummary(selection){
166
+ return `<aside class="order-summary"><h2>Your Movie</h2><h3>${esc(selection.movie||'Choose a showtime')}</h3>${selection.theater?`<p>${esc(selection.theater)}<br>${longDate(selection.date)} · ${esc(selection.time)}<br>${esc(selection.format)}</p>`:''}${selection.ticket_count?`<p><strong>${selection.ticket_count} ticket${selection.ticket_count===1?'':'s'}</strong></p>`:''}${selection.seats?.length?`<p>Seats ${selection.seats.map(esc).join(', ')}</p>`:''}${selection.total?`<dl><div><dt>Tickets</dt><dd>${money(selection.subtotal)}</dd></div><div><dt>Convenience fees</dt><dd>${money(selection.fees)}</dd></div><div><dt>Tax</dt><dd>${money(selection.tax)}</dd></div><div class="total"><dt>Total</dt><dd>${money(selection.total)}</dd></div></dl>`:''}</aside>`;
167
+ }
168
+ function ticketsPage(){
169
+ const selection=state.data.selection;
170
+ if(!selection.movie){ layout(`<div class="shell"><div class="empty"><h1>Choose a showtime first</h1><p>Pick a movie and time to start a ticket order.</p><a class="primary" href="/movies" data-link>Find Showtimes</a></div></div>`);return; }
171
+ layout(`<div class="shell booking-shell">${bookingSteps(0)}<div class="booking-grid"><section><p class="eyebrow">Select Tickets</p><h1>How many tickets?</h1><form class="ticket-form" data-ticket-form><label>Adult <input name="adults" type="number" min="0" max="8" value="${selection.ticket_types?.Adult??3}"></label><label>Child <input name="children" type="number" min="0" max="8" value="${selection.ticket_types?.Child||0}"></label><label>Senior <input name="seniors" type="number" min="0" max="8" value="${selection.ticket_types?.Senior||0}"></label><div class="inline-error"></div><button class="primary" type="submit">Continue to Seats</button></form></section>${selectionSummary(selection)}</div></div>`);
172
+ root.querySelector('[data-ticket-form]').addEventListener('submit',async event=>{event.preventDefault();const element=event.currentTarget;const form=new FormData(element);try{await api('/api/selection/tickets',{method:'POST',body:JSON.stringify({adults:Number(form.get('adults')),children:Number(form.get('children')),seniors:Number(form.get('seniors'))})});await refresh();state.selectedSeats=[];go('/tickets/seats');}catch(err){element.querySelector('.inline-error').textContent=err.message;}});
173
+ }
174
+ function seatMap(){
175
+ const selection=state.data.selection;
176
+ if(!selection.ticket_count){go('/tickets');return;}
177
+ const sold=new Set(selection.sold_seats||[]);
178
+ const rows=selection.seat_rows||['A','B','C','D','E','F','G','H'];
179
+ const perRow=selection.seats_per_row||12;
180
+ const seats=rows.map(row=>`<div class="seat-row"><span>${row}</span>${Array.from({length:perRow},(_,i)=>{const id=`${row}${i+1}`;const center=['D','E','F'].includes(row)&&i>=4&&i<=7;return `<button class="seat ${sold.has(id)?'sold':''} ${state.selectedSeats.includes(id)?'selected':''} ${center?'center':''}" ${sold.has(id)?'disabled':''} data-seat="${id}" aria-label="Seat ${id}${sold.has(id)?', sold':''}" aria-pressed="${state.selectedSeats.includes(id)}">${i+1}</button>`;}).join('')}<span>${row}</span></div>`).join('');
181
+ layout(`<div class="shell booking-shell">${bookingSteps(1)}<div class="booking-grid"><section><p class="eyebrow">Reserved Seating</p><h1>Choose ${selection.ticket_count} adjacent seat${selection.ticket_count===1?'':'s'}</h1><p class="card-meta">Seats must be next to each other in one row. Center seats in rows D–F are highlighted.</p><div class="screen">SCREEN</div><div class="seat-map">${seats}</div><div class="seat-legend"><span><i></i>Available</span><span><i class="center"></i>Center D–F</span><span><i class="selected"></i>Selected</span><span><i class="sold"></i>Sold</span></div><p data-seat-status class="card-meta">${state.selectedSeats.length?`Selected: ${state.selectedSeats.join(', ')}`:'No seats selected'}</p><div class="inline-error"></div><button class="primary" data-continue-seats>Continue to Review</button></section>${selectionSummary({...selection,seats:state.selectedSeats})}</div></div>`);
182
+ root.querySelectorAll('[data-seat]').forEach(button=>button.addEventListener('click',()=>{const id=button.dataset.seat;if(state.selectedSeats.includes(id)){state.selectedSeats=state.selectedSeats.filter(s=>s!==id);}else if(state.selectedSeats.length<selection.ticket_count){state.selectedSeats.push(id);}else{notify(`You selected ${selection.ticket_count} tickets. Deselect a seat first.`);return;}seatMap();}));
183
+ root.querySelector('[data-continue-seats]').addEventListener('click',async()=>{try{await api('/api/selection/seats',{method:'POST',body:JSON.stringify({seats:state.selectedSeats})});await refresh();go('/checkout');}catch(err){root.querySelector('.inline-error').textContent=err.message;}});
184
+ }
185
+ function checkout(){
186
+ const selection=state.checkoutReview||state.data.selection;
187
+ if(!selection.seats?.length){layout(`<div class="shell"><div class="empty"><h1>Your seat selection is incomplete</h1><p>Pick a showtime and seats before checkout.</p><a class="primary" href="/movies" data-link>Start over</a></div></div>`);return;}
188
+ layout(`<div class="shell booking-shell">${bookingSteps(2)}<div class="booking-grid"><section><p class="eyebrow">Checkout</p><h1>Review and confirm</h1><div class="sandbox-note"><strong>Local Sandbox Payment</strong><p>No card number is accepted and no charge will occur.</p></div><form class="checkout-form" data-review-form><label>Email for local receipt<input name="email" type="email" value="${esc(selection.contact_email||'')}" placeholder="you@example.com" required></label><label>Billing ZIP / postal code<input name="postal_code" value="${esc(selection.billing_postal_code||'')}" placeholder="10003" required></label><fieldset><legend>Payment method</legend><label class="radio"><input type="radio" checked disabled> Local Sandbox — no real payment</label></fieldset><div class="inline-error"></div><button class="primary" type="submit">Calculate Total &amp; Review</button></form>${state.checkoutReview?`<div class="final-review"><h2>Final booking review</h2><p>Verify the movie, showtime, theater, ticket count and adjacent seats before confirming.</p><button class="primary" data-confirm-booking>Confirm Local Booking</button></div>`:''}</section>${selectionSummary(selection)}</div></div>`);
189
+ root.querySelector('[data-review-form]').addEventListener('submit',async event=>{event.preventDefault();const element=event.currentTarget;const form=new FormData(element);try{state.checkoutReview=await api('/api/checkout/review',{method:'POST',body:JSON.stringify({email:form.get('email'),postal_code:form.get('postal_code')})});checkout();}catch(err){element.querySelector('.inline-error').textContent=err.message;}});
190
+ root.querySelector('[data-confirm-booking]')?.addEventListener('click',async()=>{try{state.confirmation=await api('/api/checkout/confirm',{method:'POST',body:'{}'});await refresh();go('/confirmation');}catch(err){notify(err.message);}});
191
+ }
192
+ function confirmation(){
193
+ const booking=state.confirmation||state.data.bookings[0];
194
+ if(!booking){layout(`<div class="shell"><div class="empty"><h1>No booking to show</h1><a class="primary" href="/movies" data-link>Find Showtimes</a></div></div>`);return;}
195
+ layout(`<div class="shell confirmation">${bookingSteps(3)}<div class="checkmark">✓</div><p class="eyebrow">Local Booking Confirmed</p><h1>You’re going to ${esc(booking.movie)}!</h1><p class="confirmation-id">Confirmation ${esc(booking.id)}</p><div class="confirmation-card"><h2>${esc(booking.movie)}</h2><dl><div><dt>Theater</dt><dd>${esc(booking.theater)}</dd></div><div><dt>Date &amp; time</dt><dd>${longDate(booking.date)} · ${esc(booking.time)}</dd></div><div><dt>Format</dt><dd>${esc(booking.format)}</dd></div><div><dt>Tickets</dt><dd>${booking.tickets}</dd></div><div><dt>Seats</dt><dd>${booking.seats.map(esc).join(', ')}</dd></div><div><dt>Total</dt><dd>${money(booking.total)}</dd></div></dl></div><p class="card-meta">This confirmation exists only in the local WebsiteBench clone. No real ticket was issued.</p><p><a class="primary" href="/account/bookings" data-link>Manage My Tickets</a></p></div>`);
196
+ }
197
+
198
+ /* ---------- auth ---------- */
199
+ function authPage(mode){
200
+ const register=mode==='register', recover=mode==='recover';
201
+ layout(`<section class="auth-page"><div class="auth-card"><a class="logo" href="/" data-link><span class="ticket">F</span>FANDANGO</a>
202
+ <h1>${register?'Create your account':recover?'Reset your password':'Sign in'}</h1>
203
+ <p>${register?'Save movies and manage tickets in one place.':recover?'Preview the reset flow without sending an email.':'Access saved movies and upcoming or past tickets.'}</p>
204
+ <form data-auth-form>${register?'<label>Full name<input name="display_name" autocomplete="name" required></label>':''}
205
+ <label>Email address<input name="email" type="email" autocomplete="email" required></label>
206
+ ${recover?'':`<label>Password<input name="password" type="password" minlength="8" autocomplete="${register?'new-password':'current-password'}" required></label>`}
207
+ ${register?'<label class="radio"><input name="terms" type="checkbox" required> I agree to the <a href="/policies/terms-of-use" data-link>Terms of Use</a> and <a href="/policies/privacy-policy" data-link>Privacy Policy</a>. Your email is verified locally — this site never sends mail.</label>':''}
208
+ <div class="inline-error"></div><button class="primary" type="submit">${register?'Create Account':recover?'Continue':'Sign In'}</button></form>
209
+ <div class="auth-links">${register?'<a href="/account/login" data-link>Already have an account?</a>':recover?'<a href="/account/login" data-link>Return to sign in</a>':'<a href="/account/register" data-link>Create account</a><a href="/account/recover" data-link>Forgot password?</a>'}</div>
210
+ ${recover?'':'<div class="idp"><span>or continue with</span><button type="button" disabled>Google</button><button type="button" disabled>Apple</button></div>'}</div></section>`);
211
+ root.querySelector('[data-auth-form]').addEventListener('submit',async event=>{event.preventDefault();const element=event.currentTarget;const form=new FormData(element);const endpoint=recover?'recovery-preview':register?'register':'login';try{const result=await api(`/api/auth/${endpoint}`,{method:'POST',body:JSON.stringify(Object.fromEntries(form))});if(recover){element.querySelector('.inline-error').textContent=result.message;}else{await refresh();go('/account');notify(register?'Account created locally. No verification email was sent.':'Signed in');}}catch(err){element.querySelector('.inline-error').textContent=err.message;}});
212
+ }
213
+
214
+ /* ---------- account ---------- */
215
+ function account(section='overview'){
216
+ if(!state.data.profile){authPage('login');return;}
217
+ const bookings=state.data.bookings;
218
+ const favorites=state.data.movies.filter(movie=>state.data.favorites.includes(movie.id));
219
+ const content=section==='favorites'
220
+ ? `<h1>My Movies</h1>${favorites.length?`<div class="poster-grid">${favorites.map(movieCard).join('')}</div>`:'<div class="empty"><h2>No saved movies yet</h2><p>Save a movie to find it here later.</p><a class="primary" href="/movies" data-link>Browse movies</a></div>'}`
221
+ : section==='bookings'
222
+ ? `<h1>My Tickets</h1><div class="booking-list">${bookings.length?bookings.map(bookingCard).join(''):'<div class="empty"><h2>No tickets yet</h2><a class="primary" href="/movies" data-link>Find Showtimes</a></div>'}</div>`
223
+ : `<h1>Hi, ${esc(state.data.profile.display_name)}</h1><div class="account-cards"><a href="/account/bookings" data-link><strong>${bookings.length}</strong><span>Upcoming &amp; past tickets</span></a><a href="/favorites" data-link><strong>${favorites.length}</strong><span>Saved movies</span></a></div><button class="save-btn" data-logout>Sign Out</button>`;
224
+ layout(`<div class="shell account-layout"><aside><h2>My Account</h2><a href="/account" data-link>Overview</a><a href="/account/bookings" data-link>My Tickets</a><a href="/favorites" data-link>My Movies</a><a href="/help" data-link>Help</a></aside><div class="account-content">${content}</div></div>`);
225
+ root.querySelector('[data-logout]')?.addEventListener('click',async()=>{await api('/api/auth/logout',{method:'POST',body:'{}'});await refresh();go('/');});
226
+ bindBookingActions();
227
+ }
228
+ function bookingCard(booking){
229
+ return `<article class="booking-card" data-booking="${booking.id}"><div><span class="status">${esc(booking.status)}</span><h2>${esc(booking.movie)}</h2><p>${esc(booking.theater)} · ${longDate(booking.date)} · ${esc(booking.time)}</p><p>${booking.tickets} tickets · Seats ${booking.seats.map(esc).join(', ')} · ${money(booking.total)}</p>${booking.contact_status?`<p class="notice">${esc(booking.contact_status)}</p>`:''}${booking.review?`<p class="notice">Review: ${esc(booking.review)}</p>`:''}</div><div class="booking-actions">${booking.status==='Cancelled'?'':`<label>New date <select data-reschedule-date="${booking.id}" aria-label="New date for ${esc(booking.movie)}">${state.data.dates.map(day=>`<option value="${day.date}" ${day.date===booking.date?'selected':''}>${longDate(day.date)}</option>`).join('')}</select></label><button data-booking-action="reschedule" data-id="${booking.id}">Reschedule</button><button data-booking-action="cancel" data-id="${booking.id}">Cancel</button>`}<button data-booking-action="contact" data-id="${booking.id}">Contact Theater</button><button data-booking-action="review" data-id="${booking.id}">Write Review</button><button data-booking-action="book-again" data-id="${booking.id}">Book Again</button><a href="/movies" data-link>Back to Movies</a></div></article>`;
230
+ }
231
+ function bindBookingActions(){
232
+ root.querySelectorAll('[data-booking-action]').forEach(button=>button.addEventListener('click',async()=>{
233
+ let value=null; if(button.dataset.bookingAction==='review') value='5 stars — Great local test experience';
234
+ if(button.dataset.bookingAction==='reschedule') value=button.closest('[data-booking]').querySelector('[data-reschedule-date]').value;
235
+ try{ await api(`/api/bookings/${button.dataset.id}/${button.dataset.bookingAction}`,{method:'POST',body:JSON.stringify({value})}); await refresh();
236
+ if(button.dataset.bookingAction==='book-again'){state.selectedSeats=[];go('/tickets');}else{account('bookings');notify('Booking updated locally');}
237
+ }catch(err){notify(err.message);}
238
+ }));
239
+ }
240
+
241
+ /* ---------- offers ---------- */
242
+ function offersPage(){
243
+ const offers=state.data.offers||[];
244
+ const byId=Object.fromEntries(state.data.movies.map(movie=>[movie.id,movie]));
245
+ layout(`<section class="page-title"><div class="shell"><p class="eyebrow">Offers</p><h1>Special Offers</h1>
246
+ <p>Current promotions on movies playing near New York, NY. These captured source promotions are shown for reference. Local simulated bookings do not apply discounts or issue rewards.</p></div></section>
247
+ <div class="shell"><section class="section"><div class="offer-list">
248
+ ${offers.map(offer=>{const movie=byId[offer.movie_id];return `<article class="offer-card">
249
+ ${movie?`<a class="poster-link" href="/movies/${movie.id}" data-link>${posterMarkup(movie)}</a>`:''}
250
+ <div><p class="eyebrow">Offer</p><h2><a href="/movies/${offer.movie_id}" data-link>${esc(offer.headline)}</a></h2>
251
+ <p class="card-meta">${esc(offer.detail)}</p>
252
+ <a class="btn-ticket" href="/movies/${offer.movie_id}" data-link>Get Tickets</a></div>
253
+ </article>`;}).join('')}
254
+ </div>
255
+ <p class="card-meta" style="margin-top:20px">Looking for gift cards? See <a href="/help#gift-cards" data-link>the gift card guidance</a> in the Help Center.</p>
256
+ </section></div>`);
257
+ }
258
+
259
+ /* ---------- help, legal, 404 ---------- */
260
+ function help(){
261
+ layout(`<section class="page-title"><div class="shell"><p class="eyebrow">Help Center</p><h1>How can we help?</h1><form class="help-search"><input aria-label="Search help" placeholder="Search tickets, refunds or account help"><button type="submit">Search</button></form></div></section>
262
+ <div class="shell help-grid"><article><h2>Tickets &amp; Showtimes</h2><p>Learn how to choose quantities, formats and adjacent seats.</p><a href="/movies" data-link>Find showtimes</a></article>
263
+ <article><h2>Account Access</h2><p>Get help signing in, registering or previewing password recovery.</p><a href="/account/recover" data-link>Password help</a></article>
264
+ <article><h2>Refunds &amp; Failed Actions</h2><p>Manage a local booking, reschedule or cancel before showtime.</p><a href="/account/bookings" data-link>Manage tickets</a></article>
265
+ <article><h2>Contact a Theater</h2><p>The local flow saves a contact request but never sends a real message.</p><a href="/account/bookings" data-link>Open ticket history</a></article>
266
+ <article><h2>Theater Policies</h2><p>Amenities, formats and refund windows for every theater near you.</p><a href="/theaters" data-link>Browse theaters</a></article>
267
+ <article id="gift-cards"><h2>Gift Cards</h2><p>Fandango gift cards are redeemed at checkout on the real site. This offline recreation accepts no card numbers and issues no balances, so gift card redemption is disabled here.</p><a href="/offers" data-link>See current offers</a></article>
268
+ <article><h2>Terms &amp; Privacy</h2><p>What this local recreation stores and what it never collects.</p><a href="/policies/privacy-policy" data-link>Read the policy</a></article></div>`);
269
+ root.querySelector('.help-search').addEventListener('submit',e=>{e.preventDefault();notify('Help results: tickets, account access, refunds and failed actions');});
270
+ }
271
+ const LEGAL={
272
+ '/policies/terms-of-use':{title:'Terms of Use',intro:'These terms describe how this local Fandango recreation may be used.',sections:[
273
+ ['Acceptance','By browsing showtimes or creating an account here you accept these terms. This is an offline WebsiteBench recreation, so no agreement is formed with Fandango Media, LLC.'],
274
+ ['Tickets and bookings','Every booking, confirmation code and seat assignment produced here exists only in a local database. No ticket is issued and no theater is notified.'],
275
+ ['Payment','No card numbers are accepted anywhere in this recreation, and no charge is ever made. The checkout step is a structural simulation only.'],
276
+ ['Acceptable use','Do not use this recreation to reach the live Fandango service and do not enter real payment or identity details.'],
277
+ ['Changes','These terms may be revised as the recreation changes. Continued use after a revision means you accept it.'],
278
+ ]},
279
+ '/policies/privacy-policy':{title:'Privacy Policy',intro:'This policy explains what this local Fandango recreation stores and what it never collects.',sections:[
280
+ ['What we store','Your display name, email address, password hash, saved movies, ticket selections and bookings are written to a SQLite database on the machine running this site.'],
281
+ ['What we never collect','No card numbers, billing addresses beyond a postal code, government identifiers or location data are requested or accepted.'],
282
+ ['No third parties','Nothing is shared with Fandango, theaters, advertisers or analytics providers. The site makes no outbound network requests at runtime.'],
283
+ ['Email and messaging','Password recovery and "contact theater" actions are previewed locally. No message is ever sent to any address or venue.'],
284
+ ['Deleting your data','Removing the local database file erases every account, booking and saved movie created here.'],
285
+ ]},
286
+ };
287
+ function legalPage(pathname){
288
+ const page=LEGAL[pathname];
289
+ layout(`<div class="shell legal"><p class="eyebrow">Fandango Policies</p><h1>${esc(page.title)}</h1><p>${esc(page.intro)}</p><p class="card-meta">Last updated August 2026</p>
290
+ ${page.sections.map(([h,c])=>`<section><h2>${esc(h)}</h2><p>${esc(c)}</p></section>`).join('')}
291
+ <div class="legal-links"><a href="/policies/terms-of-use" data-link>Terms of Use</a><a href="/policies/privacy-policy" data-link>Privacy Policy</a><a href="/account/register" data-link>Back to sign up</a><a href="/help" data-link>Help Center</a></div></div>`);
292
+ }
293
+ function notFound(){
294
+ layout(`<div class="shell not-found"><div class="ticket-stub">404</div><h1>That page missed the show.</h1><p>The link may have changed, but movies and showtimes are still available.</p><div><a class="primary" href="/movies" data-link>Browse Movies</a><a href="/theaters" data-link>Theaters Near You</a><a href="/help" data-link>Visit Help Center</a></div></div>`);
295
+ }
296
+
297
+ /* ---------- wiring ---------- */
298
+ function bindGlobal(){
299
+ root.querySelectorAll('[data-link]').forEach(link=>link.addEventListener('click',event=>{if(event.button===0&&!event.ctrlKey&&!event.metaKey){event.preventDefault();go(link.getAttribute('href'));}}));
300
+ root.querySelector('[data-search-form]')?.addEventListener('submit',event=>{event.preventDefault();const q=new FormData(event.currentTarget).get('q');go(`/movies?q=${encodeURIComponent(q)}`);});
301
+ root.querySelectorAll('[data-favorite]').forEach(button=>button.addEventListener('click',async()=>{try{const result=await api(`/api/favorites/${button.dataset.favorite}`,{method:'POST',body:'{}'});await refresh();notify(result.saved?'Saved to My Movies':'Removed from My Movies');render();}catch(err){notify(err.message);}}));
302
+ }
303
+
304
+ async function render(){
305
+ if(!state.data) await refresh();
306
+ const path=location.pathname;
307
+ if(await navigationRoute(path)) return;
308
+ if(path==='/'){home();return;}
309
+ if(path==='/movies'||path==='/search'){await moviesPage();return;}
310
+ if(path.startsWith('/movies/')){await moviePage(path.split('/')[2]);return;}
311
+ if(path==='/theaters'){await theatersPage();return;}
312
+ if(path.startsWith('/theaters/')){await theatersPage(path.split('/')[2]);return;}
313
+ if(path==='/tickets'){ticketsPage();return;}
314
+ if(path==='/tickets/seats'){seatMap();return;}
315
+ if(path==='/checkout'){checkout();return;}
316
+ if(path==='/confirmation'){confirmation();return;}
317
+ if(path==='/account/login'){authPage('login');return;}
318
+ if(path==='/account/register'){authPage('register');return;}
319
+ if(path==='/account/recover'){authPage('recover');return;}
320
+ if(path==='/account/bookings'){account('bookings');return;}
321
+ if(path==='/favorites'){account('favorites');return;}
322
+ if(path==='/account'){account();return;}
323
+ if(path==='/help'){help();return;}
324
+ if(path==='/offers'){offersPage();return;}
325
+ if(LEGAL[path]){legalPage(path);return;}
326
+ notFound();
327
+ }
328
+
329
+ window.addEventListener('popstate',render);
330
+ render();
tasks/fandango/environment/reference/clone/static/home-data.js ADDED
@@ -0,0 +1,847 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const HOME_DATA = {
2
+ "capture": "User reference 官网首页1.png; supporting public DOM 2026-09-04",
3
+ "source": "https://www.fandango.com/",
4
+ "defaultZip": "90001",
5
+ "now": [
6
+ {
7
+ "title": "Onslaught (2026)",
8
+ "href": "https://www.fandango.com/onslaught-2026-245994/movie-overview",
9
+ "image": "/static/home-assets/44b94659e8eda628.jpg",
10
+ "gift": true
11
+ },
12
+ {
13
+ "title": "By Any Means (2026)",
14
+ "href": "https://www.fandango.com/by-any-means-2026-246005/movie-overview",
15
+ "image": "/static/home-assets/6107823b6c926267.jpg",
16
+ "gift": true
17
+ },
18
+ {
19
+ "title": "Spider-Man: Brand New Day (2026)",
20
+ "href": "https://www.fandango.com/spider-man-brand-new-day-2026-243819/movie-overview",
21
+ "image": "/static/home-assets/d5bc8dda4f6aede4.jpg",
22
+ "gift": true
23
+ },
24
+ {
25
+ "title": "Coyote vs. Acme",
26
+ "href": "https://www.fandango.com/coyote-vs-acme-246329/movie-overview",
27
+ "image": "/static/home-assets/4e078d9f5b4a0b72.jpg",
28
+ "gift": false
29
+ },
30
+ {
31
+ "title": "The Dog Stars (2026)",
32
+ "href": "https://www.fandango.com/the-dog-stars-2026-245569/movie-overview",
33
+ "image": "/static/home-assets/0859904f00fba36d.jpg",
34
+ "gift": false
35
+ },
36
+ {
37
+ "title": "Tom and Jerry Forbidden Compass (2026)",
38
+ "href": "https://www.fandango.com/tom-and-jerry-forbidden-compass-2026-246938/movie-overview",
39
+ "image": "/static/home-assets/7c7dd94f5248a4de.jpg",
40
+ "gift": false
41
+ },
42
+ {
43
+ "title": "Insidious: Out of the Further (2026)",
44
+ "href": "https://www.fandango.com/insidious-out-of-the-further-2026-246427/movie-overview",
45
+ "image": "/static/home-assets/cefad4c2dd5a9db0.jpg",
46
+ "gift": true
47
+ },
48
+ {
49
+ "title": "Cars: 20th Anniversary (2026)",
50
+ "href": "https://www.fandango.com/cars-20th-anniversary-2026-246886/movie-overview",
51
+ "image": "/static/home-assets/8f78367ba96ff951.jpg",
52
+ "gift": false
53
+ },
54
+ {
55
+ "title": "Fall 2: Deadpoint (2026)",
56
+ "href": "https://www.fandango.com/fall-2-deadpoint-2026-245753/movie-overview",
57
+ "image": "/static/home-assets/7f7449c393c8f0ef.jpg",
58
+ "gift": false
59
+ },
60
+ {
61
+ "title": "The Odyssey (2026)",
62
+ "href": "https://www.fandango.com/the-odyssey-2026-241283/movie-overview",
63
+ "image": "/static/home-assets/cb069ac9acb2a971.jpg",
64
+ "gift": false
65
+ },
66
+ {
67
+ "title": "Mutiny (2026)",
68
+ "href": "https://www.fandango.com/mutiny-2026-245697/movie-overview",
69
+ "image": "/static/home-assets/85c7b475d3705c0c.jpg",
70
+ "gift": true
71
+ },
72
+ {
73
+ "title": "Finding Emily (2026)",
74
+ "href": "https://www.fandango.com/finding-emily-2026-242517/movie-overview",
75
+ "image": "/static/home-assets/38b54c1db4f80485.jpg",
76
+ "gift": false
77
+ },
78
+ {
79
+ "title": "Idiots (2026)",
80
+ "href": "https://www.fandango.com/idiots-2026-245445/movie-overview",
81
+ "image": "/static/home-assets/8511cbd4bc48940b.jpg",
82
+ "gift": false
83
+ },
84
+ {
85
+ "title": "Buddy (2026)",
86
+ "href": "https://www.fandango.com/buddy-2026-245699/movie-overview",
87
+ "image": "/static/home-assets/1f82cee1e2f3915e.jpg",
88
+ "gift": false
89
+ },
90
+ {
91
+ "title": "It Ends (2026)",
92
+ "href": "https://www.fandango.com/it-ends-2026-246704/movie-overview",
93
+ "image": "/static/home-assets/739afa0dba0b7142.jpg",
94
+ "gift": false
95
+ },
96
+ {
97
+ "title": "Colony (2026)",
98
+ "href": "https://www.fandango.com/colony-2026-245476/movie-overview",
99
+ "image": "/static/home-assets/b6d52efb11d0940f.jpg",
100
+ "gift": false
101
+ },
102
+ {
103
+ "title": "Spa Weekend (2026)",
104
+ "href": "https://www.fandango.com/spa-weekend-2026-245958/movie-overview",
105
+ "image": "/static/home-assets/16e80f8c810a7e30.jpg",
106
+ "gift": false
107
+ },
108
+ {
109
+ "title": "The End of Oak Street (2026)",
110
+ "href": "https://www.fandango.com/the-end-of-oak-street-2026-245149/movie-overview",
111
+ "image": "/static/home-assets/2de7b59f34584192.jpg",
112
+ "gift": false
113
+ },
114
+ {
115
+ "title": "PAW Patrol: The Dino Movie (2026)",
116
+ "href": "https://www.fandango.com/paw-patrol-the-dino-movie-2026-245603/movie-overview",
117
+ "image": "/static/home-assets/8a9b4c3b3fe98d0f.jpg",
118
+ "gift": false
119
+ },
120
+ {
121
+ "title": "One Night Only (2026)",
122
+ "href": "https://www.fandango.com/one-night-only-2026-245604/movie-overview",
123
+ "image": "/static/home-assets/8be4da42cbf7c3b6.jpg",
124
+ "gift": false
125
+ },
126
+ {
127
+ "title": "Teenage Sex and Death at Camp Miasma (2026)",
128
+ "href": "https://www.fandango.com/teenage-sex-and-death-at-camp-miasma-2026-244691/movie-overview",
129
+ "image": "/static/home-assets/b8e31adaba1d1ce0.jpg",
130
+ "gift": false
131
+ },
132
+ {
133
+ "title": "Tony (2026)",
134
+ "href": "https://www.fandango.com/tony-2026-245704/movie-overview",
135
+ "image": "/static/home-assets/6873900f2ea1d4bd.jpg",
136
+ "gift": false
137
+ }
138
+ ],
139
+ "soon": [
140
+ {
141
+ "title": "Ryan Garcia vs. Conor Benn (2026)",
142
+ "href": "https://www.fandango.com/ryan-garcia-vs-conor-benn-2026-247004/movie-overview",
143
+ "image": "/static/home-assets/5faad959c4cc1e03.png",
144
+ "gift": false
145
+ },
146
+ {
147
+ "title": "Resident Evil (2026)",
148
+ "href": "https://www.fandango.com/resident-evil-2026-245893/movie-overview",
149
+ "image": "/static/home-assets/faec24600c6ad881.jpg",
150
+ "gift": false
151
+ },
152
+ {
153
+ "title": "Avengers Endgame: Encore (2026)",
154
+ "href": "https://www.fandango.com/avengers-endgame-encore-2026-246870/movie-overview",
155
+ "image": "/static/home-assets/843ccac864683fbc.jpg",
156
+ "gift": false
157
+ },
158
+ {
159
+ "title": "Avengers: Doomsday (2026)",
160
+ "href": "https://www.fandango.com/avengers-doomsday-2026-237176/movie-overview",
161
+ "image": "/static/home-assets/fafc61b8e364ef2d.jpg",
162
+ "gift": false
163
+ },
164
+ {
165
+ "title": "Heart of the Beast (2026)",
166
+ "href": "https://www.fandango.com/heart-of-the-beast-2026-246224/movie-overview",
167
+ "image": "/static/home-assets/b0c260ece9ad793d.jpg",
168
+ "gift": false
169
+ },
170
+ {
171
+ "title": "Practical Magic 2 (2026)",
172
+ "href": "https://www.fandango.com/practical-magic-2-2026-246473/movie-overview",
173
+ "image": "/static/home-assets/fcf08645fff42437.jpg",
174
+ "gift": false
175
+ },
176
+ {
177
+ "title": "The Uprising (2026)",
178
+ "href": "https://www.fandango.com/the-uprising-2026-246531/movie-overview",
179
+ "image": "/static/home-assets/cf78e38a9645298d.jpg",
180
+ "gift": false
181
+ },
182
+ {
183
+ "title": "Dune: Part Three (2026)",
184
+ "href": "https://www.fandango.com/dune-part-three-2026-244800/movie-overview",
185
+ "image": "/static/home-assets/97dc16438f121ff3.jpg",
186
+ "gift": false
187
+ },
188
+ {
189
+ "title": "The Transformers: The Movie 40th Anniversary (2026)",
190
+ "href": "https://www.fandango.com/the-transformers-the-movie-40th-anniversary-2026-246634/movie-overview",
191
+ "image": "/static/home-assets/560577b2972ef3c6.jpg",
192
+ "gift": false
193
+ },
194
+ {
195
+ "title": "Oasis: Don't Look Back in Anger (2026)",
196
+ "href": "https://www.fandango.com/oasis-dont-look-back-in-anger-2026-246559/movie-overview",
197
+ "image": "/static/home-assets/0a47837b78e1fafa.jpg",
198
+ "gift": false
199
+ },
200
+ {
201
+ "title": "LINKIN PARK: UNSHATTER (2026)",
202
+ "href": "https://www.fandango.com/linkin-park-unshatter-2026-246798/movie-overview",
203
+ "image": "/static/home-assets/22c381e7dcd4db15.jpg",
204
+ "gift": false
205
+ },
206
+ {
207
+ "title": "MST3K: The RiffTrax Experiments - Sting of Death (2026)",
208
+ "href": "https://www.fandango.com/mst3k-the-rifftrax-experiments-sting-of-death-2026-246452/movie-overview",
209
+ "image": "/static/home-assets/8b12fe2606629fb9.jpg",
210
+ "gift": false
211
+ },
212
+ {
213
+ "title": "The Passion of the Christ (2026)",
214
+ "href": "https://www.fandango.com/the-passion-of-the-christ-2026-246353/movie-overview",
215
+ "image": "/static/home-assets/72c64f2f21924331.jpg",
216
+ "gift": false
217
+ },
218
+ {
219
+ "title": "Runner (2026)",
220
+ "href": "https://www.fandango.com/runner-2026-246493/movie-overview",
221
+ "image": "/static/home-assets/47a42e5b4f487cd1.jpg",
222
+ "gift": false
223
+ },
224
+ {
225
+ "title": "Digger (2026)",
226
+ "href": "https://www.fandango.com/digger-2026-245150/movie-overview",
227
+ "image": "/static/home-assets/b43947b3af5e35f9.jpg",
228
+ "gift": false
229
+ },
230
+ {
231
+ "title": "How to Rob a Bank (2026)",
232
+ "href": "https://www.fandango.com/how-to-rob-a-bank-2026-245989/movie-overview",
233
+ "image": "/static/home-assets/9a98c5db56b8be95.jpg",
234
+ "gift": false
235
+ },
236
+ {
237
+ "title": "Primetime (2026)",
238
+ "href": "https://www.fandango.com/primetime-2026-245965/movie-overview",
239
+ "image": "/static/home-assets/50f4edda45328b7e.jpg",
240
+ "gift": false
241
+ },
242
+ {
243
+ "title": "Street Fighter (2026)",
244
+ "href": "https://www.fandango.com/street-fighter-2026-246472/movie-overview",
245
+ "image": "/static/home-assets/f17ff488a6a40539.jpg",
246
+ "gift": false
247
+ },
248
+ {
249
+ "title": "Hexed (2026)",
250
+ "href": "https://www.fandango.com/hexed-2026-246251/movie-overview",
251
+ "image": "/static/home-assets/191ead7caecf38b7.jpg",
252
+ "gift": false
253
+ },
254
+ {
255
+ "title": "Focker-In-Law (2026)",
256
+ "href": "https://www.fandango.com/focker-in-law-2026-241598/movie-overview",
257
+ "image": "/static/home-assets/55e93c2b14b6b59d.jpg",
258
+ "gift": false
259
+ },
260
+ {
261
+ "title": "Daniel and the Fiery Furnace (2026)",
262
+ "href": "https://www.fandango.com/daniel-and-the-fiery-furnace-2026-246805/movie-overview",
263
+ "image": "/static/home-assets/d3e9f0691be46190.png",
264
+ "gift": false
265
+ },
266
+ {
267
+ "title": "Clayface (2026)",
268
+ "href": "https://www.fandango.com/clayface-2026-244768/movie-overview",
269
+ "image": "/static/home-assets/2111f117c8d594b7.jpg",
270
+ "gift": false
271
+ },
272
+ {
273
+ "title": "The Cat in the Hat (2026)",
274
+ "href": "https://www.fandango.com/the-cat-in-the-hat-2026-241291/movie-overview",
275
+ "image": "/static/home-assets/4e7114903179866b.jpg",
276
+ "gift": false
277
+ },
278
+ {
279
+ "title": "Wildwood (2026)",
280
+ "href": "https://www.fandango.com/wildwood-2026-246438/movie-overview",
281
+ "image": "/static/home-assets/348988e399593ee1.jpg",
282
+ "gift": false
283
+ },
284
+ {
285
+ "title": "Sense and Sensibility (2026)",
286
+ "href": "https://www.fandango.com/sense-and-sensibility-2026-244998/movie-overview",
287
+ "image": "/static/home-assets/07ddd8664be31a01.jpg",
288
+ "gift": false
289
+ },
290
+ {
291
+ "title": "The Hunger Games: Sunrise on the Reaping (2026)",
292
+ "href": "https://www.fandango.com/the-hunger-games-sunrise-on-the-reaping-2026-240138/movie-overview",
293
+ "image": "/static/home-assets/366c8af8994d8090.jpg",
294
+ "gift": false
295
+ },
296
+ {
297
+ "title": "I Play Rocky (2026)",
298
+ "href": "https://www.fandango.com/i-play-rocky-2026-246500/movie-overview",
299
+ "image": "/static/home-assets/99c9b6e398d31679",
300
+ "gift": false
301
+ },
302
+ {
303
+ "title": "Other Mommy (2026)",
304
+ "href": "https://www.fandango.com/other-mommy-2026-246464/movie-overview",
305
+ "image": "/static/home-assets/61d428ee7ee38bbb.jpg",
306
+ "gift": false
307
+ },
308
+ {
309
+ "title": "Verity (2026)",
310
+ "href": "https://www.fandango.com/verity-2026-240033/movie-overview",
311
+ "image": "/static/home-assets/a2b0e1ac54a4ab1f.jpg",
312
+ "gift": false
313
+ }
314
+ ],
315
+ "free": [
316
+ {
317
+ "title": "Alien: Covenant",
318
+ "href": "https://athome.fandango.com/content/browse/details/Alien-Covenant/853471",
319
+ "image": "/static/home-assets/6e7b40536cdfbefc",
320
+ "gift": false
321
+ },
322
+ {
323
+ "title": "GoldenEye",
324
+ "href": "https://athome.fandango.com/content/browse/details/GoldenEye/12424",
325
+ "image": "/static/home-assets/44fe00020bfc5d67",
326
+ "gift": false
327
+ },
328
+ {
329
+ "title": "The Wolf of Wall Street",
330
+ "href": "https://athome.fandango.com/content/browse/details/The-Wolf-of-Wall-Street/488007",
331
+ "image": "/static/home-assets/675a083356eeb10e",
332
+ "gift": false
333
+ },
334
+ {
335
+ "title": "Den of Thieves",
336
+ "href": "https://athome.fandango.com/content/browse/details/Den-of-Thieves/910340",
337
+ "image": "/static/home-assets/f94176fba1cc9dca",
338
+ "gift": false
339
+ },
340
+ {
341
+ "title": "Oppenheimer",
342
+ "href": "https://athome.fandango.com/content/browse/details/Oppenheimer/2535279",
343
+ "image": "/static/home-assets/5aeae9be818e5599",
344
+ "gift": false
345
+ },
346
+ {
347
+ "title": "The Super Mario Bros. Movie",
348
+ "href": "https://athome.fandango.com/content/browse/details/The-Super-Mario-Bros-Movie/2302740",
349
+ "image": "/static/home-assets/d1f4ca53e26def02",
350
+ "gift": false
351
+ },
352
+ {
353
+ "title": "The Iron Claw",
354
+ "href": "https://athome.fandango.com/content/browse/details/The-Iron-Claw/2794806",
355
+ "image": "/static/home-assets/82eabcd244606352",
356
+ "gift": false
357
+ },
358
+ {
359
+ "title": "Snakes on a Plane",
360
+ "href": "https://athome.fandango.com/content/browse/details/Snakes-on-a-Plane/66478",
361
+ "image": "/static/home-assets/e736289432f44e02",
362
+ "gift": false
363
+ },
364
+ {
365
+ "title": "Resident Evil: The Final Chapter",
366
+ "href": "https://athome.fandango.com/content/browse/details/Resident-Evil-The-Final-Chapter/832524",
367
+ "image": "/static/home-assets/688524494e54703b",
368
+ "gift": false
369
+ },
370
+ {
371
+ "title": "50 First Dates",
372
+ "href": "https://athome.fandango.com/content/browse/details/50-First-Dates/40722",
373
+ "image": "/static/home-assets/40053b5c58ec888f",
374
+ "gift": false
375
+ },
376
+ {
377
+ "title": "American Psycho",
378
+ "href": "https://athome.fandango.com/content/browse/details/American-Psycho/5042",
379
+ "image": "/static/home-assets/a489963a101de06e",
380
+ "gift": false
381
+ },
382
+ {
383
+ "title": "The Sixth Sense",
384
+ "href": "https://athome.fandango.com/content/browse/details/The-Sixth-Sense/15533",
385
+ "image": "/static/home-assets/9dedbfeef510df72",
386
+ "gift": false
387
+ },
388
+ {
389
+ "title": "Five Nights at Freddy's",
390
+ "href": "https://athome.fandango.com/content/browse/details/Five-Nights-at-Freddys/2700071",
391
+ "image": "/static/home-assets/0da1fb98399052ac",
392
+ "gift": false
393
+ },
394
+ {
395
+ "title": "Borderlands",
396
+ "href": "https://athome.fandango.com/content/browse/details/Borderlands/3324616",
397
+ "image": "/static/home-assets/910092e27e675a3a",
398
+ "gift": false
399
+ },
400
+ {
401
+ "title": "Signs",
402
+ "href": "https://athome.fandango.com/content/browse/details/Signs/30267",
403
+ "image": "/static/home-assets/1b77768a27b20f68",
404
+ "gift": false
405
+ },
406
+ {
407
+ "title": "Any Given Sunday",
408
+ "href": "https://athome.fandango.com/content/browse/details/Any-Given-Sunday/9448",
409
+ "image": "/static/home-assets/305e1b04c7be3aed",
410
+ "gift": false
411
+ },
412
+ {
413
+ "title": "Sense and Sensibility",
414
+ "href": "https://athome.fandango.com/content/browse/details/Sense-and-Sensibility/12462",
415
+ "image": "/static/home-assets/cc9f8f981916e69b",
416
+ "gift": false
417
+ },
418
+ {
419
+ "title": "Never Been Kissed",
420
+ "href": "https://athome.fandango.com/content/browse/details/Never-Been-Kissed/8018",
421
+ "image": "/static/home-assets/9cbb9bda442159a5",
422
+ "gift": false
423
+ },
424
+ {
425
+ "title": "Renfield",
426
+ "href": "https://athome.fandango.com/content/browse/details/Renfield/2329112",
427
+ "image": "/static/home-assets/342cff17b9767c38",
428
+ "gift": false
429
+ },
430
+ {
431
+ "title": "Drive Angry",
432
+ "href": "https://athome.fandango.com/content/browse/details/Drive-Angry/185748",
433
+ "image": "/static/home-assets/ebce995cdbe58f84",
434
+ "gift": false
435
+ },
436
+ {
437
+ "title": "Killing Them Softly",
438
+ "href": "https://athome.fandango.com/content/browse/details/Killing-Them-Softly/378104",
439
+ "image": "/static/home-assets/a82e5bc651116b68",
440
+ "gift": false
441
+ },
442
+ {
443
+ "title": "Knowing",
444
+ "href": "https://athome.fandango.com/content/browse/details/Knowing/161187",
445
+ "image": "/static/home-assets/43ac9d7c0cd164da",
446
+ "gift": false
447
+ }
448
+ ],
449
+ "features": [
450
+ {
451
+ "title": "Exclusive Clip: 'Buddy'",
452
+ "description": "Check out this exclusive clip from 'Buddy'",
453
+ "href": "https://www.youtube.com/watch?v=0gyxe7qDNMs",
454
+ "image": "/static/home-assets/b92581bf3fb2c22a.jpg",
455
+ "video": true
456
+ },
457
+ {
458
+ "title": "Seen on the Screen: 'Resident Evil'",
459
+ "description": "Filmmaker Zach Cregger on 'Weapons', 'Barbarian', and 'Resident Evil'",
460
+ "href": "https://www.fandango.com/movie-news/seen-on-the-screen-podcast-zach-cregger-talks-weapons-barbarian-and-resident-evil-755288",
461
+ "image": "/static/home-assets/bf97625c9c326d53.jpg",
462
+ "video": false
463
+ },
464
+ {
465
+ "title": "Seen on the Screen: 'Onslaught'",
466
+ "description": "Adria Arjona on the grueling physical demands of 'Onslaught' & her 'Andor' audition",
467
+ "href": "https://www.fandango.com/movie-news/seen-on-the-screen-podcast-onslaught-star-adria-arjona-is-officially-in-her-action-star-era-755287",
468
+ "image": "/static/home-assets/f8b76d7de6a76bad.jpg",
469
+ "video": false
470
+ },
471
+ {
472
+ "title": "Big Ticket: 'Practical Magic 2'",
473
+ "description": "Nicole Kidman & the cast reflect on returning to their roles after 28 years",
474
+ "href": "https://www.fandango.com/movie-trailer/practical-magic-2-2026/246473?mpxId=2510637635517",
475
+ "image": "/static/home-assets/1d7fe18b3c7e9c39.jpg",
476
+ "video": true
477
+ }
478
+ ],
479
+ "newSoon": [
480
+ {
481
+ "title": "The Dog Stars (2026)",
482
+ "href": "https://www.fandango.com/the-dog-stars-2026-245569/movie-overview",
483
+ "image": "/static/home-assets/0859904f00fba36d.jpg"
484
+ },
485
+ {
486
+ "title": "Insidious: Out of the Further (2026)",
487
+ "href": "https://www.fandango.com/insidious-out-of-the-further-2026-246427/movie-overview",
488
+ "image": "/static/home-assets/cefad4c2dd5a9db0.jpg"
489
+ },
490
+ {
491
+ "title": "PAW Patrol: The Dino Movie (2026)",
492
+ "href": "https://www.fandango.com/paw-patrol-the-dino-movie-2026-245603/movie-overview",
493
+ "image": "/static/home-assets/8a9b4c3b3fe98d0f.jpg"
494
+ },
495
+ {
496
+ "title": "Onslaught (2026)",
497
+ "href": "https://www.fandango.com/onslaught-2026-245994/movie-overview",
498
+ "image": "/static/home-assets/44b94659e8eda628.jpg"
499
+ },
500
+ {
501
+ "title": "Spider-Man: Brand New Day (2026)",
502
+ "href": "https://www.fandango.com/spider-man-brand-new-day-2026-243819/movie-overview",
503
+ "image": "/static/home-assets/d5bc8dda4f6aede4.jpg"
504
+ },
505
+ {
506
+ "title": "By Any Means (2026)",
507
+ "href": "https://www.fandango.com/by-any-means-2026-246005/movie-overview",
508
+ "image": "/static/home-assets/6107823b6c926267.jpg"
509
+ },
510
+ {
511
+ "title": "The End of Oak Street (2026)",
512
+ "href": "https://www.fandango.com/the-end-of-oak-street-2026-245149/movie-overview",
513
+ "image": "/static/home-assets/2de7b59f34584192.jpg"
514
+ },
515
+ {
516
+ "title": "Coyote vs. Acme",
517
+ "href": "https://www.fandango.com/coyote-vs-acme-246329/movie-overview",
518
+ "image": "/static/home-assets/4e078d9f5b4a0b72.jpg"
519
+ }
520
+ ],
521
+ "banner": {
522
+ "image": "/static/home-assets/garcia-vs-benn-banner.png?v=2",
523
+ "href": "https://www.fandango.com/ryan-garcia-vs-conor-benn-2026-247004/movie-overview"
524
+ },
525
+ "promo": {
526
+ "headline": "Ryan Garcia vs. Conor Benn",
527
+ "detail": "See Garcia defend his title on the big screen!",
528
+ "href": "https://www.fandango.com/ryan-garcia-vs-conor-benn-2026-247004/movie-overview",
529
+ "icon": "/static/home-assets/promo-ticket.svg"
530
+ },
531
+ "theaters": [
532
+ {
533
+ "name": "Park Twin Theatre",
534
+ "distance": "1.3mi",
535
+ "address": "6504 Pacific Blvd",
536
+ "city": "Huntington Park, CA 90255",
537
+ "href": "https://www.fandango.com/park-twin-theatre-AACQN/theater-page"
538
+ },
539
+ {
540
+ "name": "Regal Edwards South Gate",
541
+ "distance": "5.1mi",
542
+ "address": "8630 Garfield Ave",
543
+ "city": "South Gate, CA 90280",
544
+ "href": "https://www.fandango.com/regal-edwards-south-gate-AAPDQ/theater-page"
545
+ },
546
+ {
547
+ "name": "Regal LA Live",
548
+ "distance": "5.1mi",
549
+ "address": "1000 W. Olympic Blvd.",
550
+ "city": "Los Angeles, CA 90015",
551
+ "href": "https://www.fandango.com/regal-la-live-AAVPA/theater-page"
552
+ },
553
+ {
554
+ "name": "Alamo Drafthouse Cinema Downtown LA",
555
+ "distance": "5.2mi",
556
+ "address": "700 W 7th St Ste. U240",
557
+ "city": "Los Angeles, CA 90017",
558
+ "href": "https://www.fandango.com/alamo-drafthouse-cinema-downtown-la-AAYPC/theater-page"
559
+ },
560
+ {
561
+ "name": "Cinemark Baldwin Hills Crenshaw and XD",
562
+ "distance": "5.7mi",
563
+ "address": "4020 Marlton Ave.",
564
+ "city": "Los Angeles, CA 90008",
565
+ "href": "https://www.fandango.com/cinemark-baldwin-hills-crenshaw-and-xd-AAWJU/theater-page"
566
+ },
567
+ {
568
+ "name": "Cinépolis Luxury Cinemas Inglewood IMAX",
569
+ "distance": "5.8mi",
570
+ "address": "1233 District Drive Suite 100",
571
+ "city": "Inglewood, CA 90303",
572
+ "href": "https://www.fandango.com/cinepolis-luxury-cinemas-inglewood-imax-AAYYG/theater-page"
573
+ }
574
+ ],
575
+ "offers": [
576
+ {
577
+ "title": "Zach Cregger Enters Resident Evil",
578
+ "description": "Zach Cregger Reveals How Gaming, Practical Effects And Horror Shaped His Resident Evil Vision.",
579
+ "cta": "TUNE IN",
580
+ "href": "https://www.fandango.com/movie-news/seen-on-the-screen-podcast-zach-cregger-talks-weapons-barbarian-and-resident-evil-755288",
581
+ "image": "/static/home-assets/zach-offer-reference.png"
582
+ },
583
+ {
584
+ "title": "Take aim, by any means necessary.",
585
+ "description": "Buy A Ticket To By Any Means, Get The Mark Wahlberg 5 Movie Collection For $7.99",
586
+ "cta": "GET TICKETS",
587
+ "href": "https://www.fandangomovietickets.com/byanymeansgwp/",
588
+ "image": "/static/home-assets/offer-by-any-means.jpg?v=2"
589
+ },
590
+ {
591
+ "title": "Wands at the Ready!",
592
+ "description": "Back To Hogwarts Has Returned, And We’re Celebrating 25 Years Of Magic.",
593
+ "cta": "GET TICKETS",
594
+ "href": "https://www.fandangomovietickets.com/backtohogwarts/",
595
+ "image": "/static/home-assets/offer-hogwarts.png"
596
+ },
597
+ {
598
+ "title": "Put the lime in the coconut and call the witches",
599
+ "description": "Get The Practical Magic 2 Popcorn Bucket Bundle And Receive A Movie Ticket To Practical Magic 2 Plus An Exclusive Margarita Popcorn Bucket!",
600
+ "cta": "LEARN MORE",
601
+ "href": "https://store.fandango.com/products/practical-magic-2-margarita-popcorn-bucket",
602
+ "image": "/static/home-assets/offer-practical-magic.png?v=2"
603
+ }
604
+ ],
605
+ "footerColumns": [
606
+ {
607
+ "title": "Experience + Explore",
608
+ "links": [
609
+ {
610
+ "title": "Movies In Theaters",
611
+ "href": "https://www.fandango.com/movies-in-theaters"
612
+ },
613
+ {
614
+ "title": "Movie Actors and Actresses",
615
+ "href": "https://www.fandango.com/famous-actors-and-actresses"
616
+ },
617
+ {
618
+ "title": "Mobile",
619
+ "href": "https://www.fandango.com/info/mobile-movie-tickets"
620
+ },
621
+ {
622
+ "title": "New For Streaming",
623
+ "href": "https://athome.fandango.com"
624
+ },
625
+ {
626
+ "title": "Special Offers",
627
+ "href": "https://www.fandango.com/freemovietickets"
628
+ },
629
+ {
630
+ "title": "Gift Cards",
631
+ "href": "https://www.fandango.com/fandango-gift-cards"
632
+ }
633
+ ]
634
+ },
635
+ {
636
+ "title": "Editorial Features",
637
+ "links": [
638
+ {
639
+ "title": "Movie News & Features",
640
+ "href": "https://www.fandango.com/movie-news"
641
+ },
642
+ {
643
+ "title": "D23 2026: Exclusive Interviews",
644
+ "href": "https://www.fandango.com/movie-news/d23-2026-exclusive-interviews-for-lilo-and-stitch-2-star-wars-starfighter-and-more-755286"
645
+ },
646
+ {
647
+ "title": "Seen on the Screen: 'Resident Evil'",
648
+ "href": "https://www.fandango.com/movie-news/seen-on-the-screen-podcast-zach-cregger-talks-weapons-barbarian-and-resident-evil-755288"
649
+ },
650
+ {
651
+ "title": "Seen on the Screen: 'Obsession'",
652
+ "href": "https://www.fandango.com/movie-news/curry-baker-on-franchising-obsession-and-the-darkness-in-comedy-755277"
653
+ }
654
+ ]
655
+ },
656
+ {
657
+ "title": "Videos",
658
+ "links": [
659
+ {
660
+ "title": "Movie Trailers",
661
+ "href": "https://www.youtube.com/channel/UCi8e0iOVk1fEOogdfu4YgfA"
662
+ },
663
+ {
664
+ "title": "Big Ticket",
665
+ "href": "https://www.youtube.com/playlist?list=PLIqpKQ_TJ_bAORcL3JTtAJJ9ehLeFduvM"
666
+ },
667
+ {
668
+ "title": "Movieclips",
669
+ "href": "https://www.youtube.com/c/MOVIECLIPS"
670
+ }
671
+ ]
672
+ },
673
+ {
674
+ "title": "Exclusives",
675
+ "links": [
676
+ {
677
+ "title": "Big Ticket: 'Practical Magic 2'",
678
+ "href": "https://www.fandango.com/movie-trailer/practical-magic-2-2026/246473?mpxId=2510637635517"
679
+ },
680
+ {
681
+ "title": "Big Ticket: 'The Dog Stars'",
682
+ "href": "https://www.fandango.com/movie-trailer/the-dog-stars-2026/245569?mpxId=2512231491724"
683
+ },
684
+ {
685
+ "title": "Interview: 'Tony'",
686
+ "href": "https://www.fandango.com/movie-trailer/tony-2026/245704?mpxId=2510020675860"
687
+ },
688
+ {
689
+ "title": "Inde Navarrette on 'Obsession'",
690
+ "href": "https://www.fandango.com/movie-trailer/obsession-2026/242812?mpxId=2500508739817"
691
+ }
692
+ ]
693
+ }
694
+ ],
695
+ "footerLinks": [
696
+ [
697
+ {
698
+ "title": "Check Gift Card Balance",
699
+ "href": "https://tickets.fandango.com/MobileExpress/CheckBalance"
700
+ },
701
+ {
702
+ "title": "Refunds & Exchanges",
703
+ "href": "https://tickets.fandango.com/returns"
704
+ },
705
+ {
706
+ "title": "Help",
707
+ "href": "https://support.fandango.com/"
708
+ },
709
+ {
710
+ "title": "My Account",
711
+ "href": "https://www.fandango.com/accounts/dashboard"
712
+ }
713
+ ],
714
+ [
715
+ {
716
+ "title": "About Fandango",
717
+ "href": "https://www.fandango.com/about-us"
718
+ },
719
+ {
720
+ "title": "Careers",
721
+ "href": "https://www.fandango.com/careers"
722
+ },
723
+ {
724
+ "title": "Site Index",
725
+ "href": "https://www.fandango.com/site-index"
726
+ },
727
+ {
728
+ "title": "Ad Choices",
729
+ "href": "https://www.fandango.com/policies/cookies-and-tracking#cookie_management"
730
+ },
731
+ {
732
+ "title": "Privacy Policy",
733
+ "href": "https://www.fandango.com/policies/privacy-policy"
734
+ },
735
+ {
736
+ "title": "California Notice",
737
+ "href": "https://www.fandango.com/californianotice"
738
+ },
739
+ {
740
+ "title": "Terms and Policies",
741
+ "href": "https://www.fandango.com/policies/terms-and-policies"
742
+ },
743
+ {
744
+ "title": "Accessibility",
745
+ "href": "https://support.fandango.com/en_us/accessibility-ryfc4Tz85"
746
+ }
747
+ ],
748
+ [
749
+ {
750
+ "title": "Fandango Stream",
751
+ "href": "https://athome.fandango.com/"
752
+ },
753
+ {
754
+ "title": "Movieclips",
755
+ "href": "https://www.youtube.com/c/MOVIECLIPS"
756
+ },
757
+ {
758
+ "title": "Rotten Tomatoes",
759
+ "href": "https://www.rottentomatoes.com/"
760
+ }
761
+ ]
762
+ ],
763
+ "social": [
764
+ {
765
+ "title": "Fandango on Facebook",
766
+ "href": "https://www.facebook.com/fandango",
767
+ "icon": "facebook"
768
+ },
769
+ {
770
+ "title": "Fandango on X",
771
+ "href": "https://www.twitter.com/fandango",
772
+ "icon": "twitter"
773
+ },
774
+ {
775
+ "title": "Fandango on Instagram",
776
+ "href": "https://www.instagram.com/fandango",
777
+ "icon": "instagram"
778
+ },
779
+ {
780
+ "title": "Fandango on Youtube",
781
+ "href": "https://www.youtube.com/@fandango",
782
+ "icon": "youtube"
783
+ },
784
+ {
785
+ "title": "Fandango iOS App",
786
+ "href": "https://itunes.apple.com/app/fandango-movies-times-tickets/id307906541?mt=8",
787
+ "icon": "apple-app-store"
788
+ },
789
+ {
790
+ "title": "Fandango Android App",
791
+ "href": "https://play.google.com/store/apps/details?id=com.fandango",
792
+ "icon": "google-play-store"
793
+ }
794
+ ],
795
+ "studios": "/static/home-assets/studio-logos.png",
796
+ "icons": {
797
+ "logo": "/static/home-assets/logo.svg?v=2",
798
+ "facebook": "/static/home-assets/facebook.svg",
799
+ "twitter": "/static/home-assets/twitter.svg?v=2",
800
+ "instagram": "/static/home-assets/instagram.svg",
801
+ "google-play-store": "/static/home-assets/google-play-store.svg",
802
+ "gift": "/static/home-assets/gift.svg?v=2",
803
+ "play": "/static/home-assets/play.svg",
804
+ "location": "/static/home-assets/location.svg",
805
+ "youtube": "/static/home-assets/youtube.svg?v=2",
806
+ "apple-app-store": "/static/home-assets/apple-app-store.svg?v=2",
807
+ "privacy": "/static/home-assets/privacy.png?v=2"
808
+ },
809
+ "additionalPromos": [
810
+ {
811
+ "headline": "Get 10% off the A24 Shop with ticket purchase",
812
+ "detail": "Buy a ticket to Onslaught, get the discount!",
813
+ "href": "https://www.fandangomovietickets.com/onslaughtgwp?cmp=TARS~FANDANGO~OnslaughtGWP_promomodule",
814
+ "icon": "/static/home-assets/1ec1cee707a93ad9.svg"
815
+ },
816
+ {
817
+ "headline": "Watch Bundesliga for free on Fandango Stream!",
818
+ "detail": "No subscription or login required.",
819
+ "href": "https://athome.fandango.com/content/browse/uxpage/Bundesliga/405?cmp=TARS~FANDANGO~Bundesliga_promomodule",
820
+ "icon": "/static/home-assets/5f1e5adbea7b6e90.svg"
821
+ },
822
+ {
823
+ "headline": "Bring your best friend!",
824
+ "detail": "With code HEARTDOLBY at checkout",
825
+ "href": "https://www.fandangomovietickets.com/heartofthebeastoffer?cmp=TARS~FANDANGO~HeartoftheBeastOffer_promomodule",
826
+ "icon": "/static/home-assets/b105f83e18c00ba4.svg"
827
+ },
828
+ {
829
+ "headline": "The Fix Free Ticket Offer",
830
+ "detail": "Use code THEFIXFREE",
831
+ "href": "https://www.fandangomovietickets.com/thefixfreetickets?cmp=TARS~FANDANGO~TheFixFreeTicket_promomodule",
832
+ "icon": "/static/home-assets/d82a2f5a0f6988d5.svg"
833
+ },
834
+ {
835
+ "headline": "Buy a ticket to Avengers: Doomsday",
836
+ "detail": "Chance to win a trip to the film's Premiere!",
837
+ "href": "https://www.fandangomovietickets.com/superpremieresweepstakes",
838
+ "icon": "/static/home-assets/b105f83e18c00ba4.svg"
839
+ },
840
+ {
841
+ "headline": "Special IMAX offer for Resident Evil!",
842
+ "detail": "Use code RESIDENTEVILIMAX at checkout.",
843
+ "href": "https://www.fandangomovietickets.com/residentevilimaxoffer/?cmp=TARS~FANDANGO~ResidentEvilIMAXOffer_promomodule",
844
+ "icon": "/static/home-assets/b105f83e18c00ba4.svg"
845
+ }
846
+ ]
847
+ };
tasks/fandango/environment/reference/clone/static/home.css ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Scoped to the homepage; dimensions measured from the source at DPR 1. */
2
+ @font-face{font-family:FandangoHome;src:url('/static/home-assets/proxima-regular.woff2') format('woff2');font-weight:400;font-display:swap}
3
+ @font-face{font-family:FandangoHome;src:url('/static/home-assets/proxima-bold.woff2') format('woff2');font-weight:700;font-display:swap}
4
+ html:has(body.homepage){scrollbar-gutter:stable}
5
+ body.homepage{padding-top:50px;background:#1e1e1e;color:#f2f3f3;font-family:FandangoHome,Helvetica,Arial,sans-serif}
6
+ .homepage #app{width:min(1280px,100%);background:#121212;min-height:0}
7
+ .homepage a{color:#3e8ede}
8
+ .homepage a:hover{color:#68a7e7}
9
+ .homepage h2{font-size:20px;line-height:24px;font-weight:700}
10
+ .homepage h3{font-size:16px;line-height:20px;font-weight:700}
11
+ .homepage button:focus-visible,.homepage a:focus-visible,.home-track:focus-visible{outline:2px solid #3e8ede;outline-offset:3px}
12
+ .home-header{background:#121212}
13
+ .home-utility{height:40px;background:#285b93;display:flex;align-items:center;gap:22px;padding:0 20px}
14
+ .home-utility a{color:white;font-size:14px;display:flex;align-items:center;gap:6px}
15
+ .home-icon{display:inline-block;width:20px;height:20px;object-fit:contain;vertical-align:middle}
16
+ .home-utility .home-icon{width:18px;height:18px}
17
+ .home-nav{height:70px;display:flex;align-items:center;padding:0 10px;gap:12px;border-bottom:1px solid #252525}
18
+ .home-logo{flex:0 0 242px;height:56px}
19
+ .home-logo .home-icon{width:242px;height:56px}
20
+ .home-search{position:relative;flex:1;max-width:452px;margin-right:20px}
21
+ .home-search input{width:100%;height:46px;border-radius:24px;border:1px solid #333;background:#121212;color:#f2f3f3;padding:10px 48px 10px 25px;font-size:16px;font-weight:700}
22
+ .home-search input::placeholder{color:#888}
23
+ .home-search button{position:absolute;right:10px;top:8px;width:30px;height:30px;border:0;border-radius:50%;background:#3478c1;display:grid;place-items:center}
24
+ .home-search svg{width:14px;height:14px;fill:none;stroke:#fff;stroke-width:1.3}
25
+ .home-nav nav{display:flex;justify-content:space-between;align-items:center;flex:1;max-width:516px;gap:20px;margin-left:0}
26
+ .home-nav nav a{display:flex;flex-direction:column;gap:6px;align-items:center;color:white;white-space:nowrap;font-size:14px;line-height:16px}
27
+ .home-promo{height:82px;border-bottom:1px solid #292929;display:flex;align-items:center;justify-content:center;gap:94px}
28
+ .home-promo-content{position:relative;width:380px;padding:13px 0}
29
+ .home-promo-content>a{display:flex;align-items:center;justify-content:center;gap:16px;font-size:16px;line-height:18px;text-align:center;white-space:nowrap}
30
+ .home-promo-content>a>img{width:38px;height:38px}
31
+ .home-promo-content strong,.home-promo-content span span{display:block}
32
+ .home-promo-content span span{color:#f2f3f3;font-weight:400}
33
+ .home-promo-dots{position:absolute;bottom:0;display:flex;justify-content:center;gap:7px;width:100%}
34
+ .home-promo-dots button{border:0;padding:0;width:8px;height:8px;border-radius:50%;background:#888}
35
+ .home-promo-dots button[aria-current="true"]{background:#c6c6c6;width:11px;height:11px;margin-top:-1px}
36
+ .home-promo-arrow,.home-carousel-arrow{flex:none;border:2px solid #ddd;border-radius:50%;background:#121212;position:relative;color:#fff;width:32px;height:32px;padding:0;z-index:1}
37
+ .home-promo-arrow{width:24px;height:24px;border-width:1px}
38
+ .home-promo-arrow:after,.home-carousel-arrow:after{content:"";display:block;width:9px;height:9px;border-right:2px solid currentColor;border-top:2px solid currentColor;position:absolute;top:9px;left:7px;transform:rotate(45deg)}
39
+ .home-promo-arrow:after{width:7px;height:7px;top:7px;left:6px;border-width:1px}
40
+ .home-promo-arrow.previous,.home-carousel-arrow.previous{transform:rotate(180deg)}
41
+ .home-main{padding:0;background:#121212}
42
+ .home-section{padding:40px 20px 24px}
43
+ .home-section h2{margin:0}
44
+ .home-section-link{font-size:14px;line-height:16px;display:block;font-weight:700;margin:0}
45
+ .home-carousel{position:relative;margin-top:20px}
46
+ .home-carousel-now{width:calc(100% - 330px)}
47
+ .home-track{display:flex;flex-wrap:nowrap;gap:20px;overflow-x:auto;overflow-y:hidden;scrollbar-width:none;scroll-snap-type:x mandatory;align-items:flex-start}
48
+ .home-track::-webkit-scrollbar{display:none}
49
+ .home-slide{flex:0 0 140px;min-width:0;scroll-snap-align:start}
50
+ .home-slide>a{display:block;color:#f2f3f3}
51
+ .home-image{position:relative}
52
+ .home-image>img{width:140px;height:210px;object-fit:fill;border-radius:8px}
53
+ .home-slide h3{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden;font-size:16px;line-height:20px;margin:8px 0 0;color:#f2f3f3}
54
+ .home-slide p{font-size:14px;line-height:18px;color:#f2f3f3;margin:4px 0 0;font-weight:400}
55
+ .home-gift{position:absolute;top:0;right:0;width:26px;height:26px;display:grid;place-items:center;background:#9c4eb0;border-bottom-left-radius:4px;border-top-right-radius:8px}
56
+ .home-gift .home-icon{width:17px;height:21px}
57
+ .home-carousel-arrow{position:absolute;top:100px}
58
+ .home-carousel-arrow.next{right:-16px}
59
+ .home-carousel-arrow.previous{left:-16px}
60
+ .home-carousel-arrow:disabled{visibility:hidden;pointer-events:none}
61
+ .home-features{padding-bottom:60px}
62
+ .home-features .home-slide{flex-basis:calc((100% - 40px)/3)}
63
+ .home-features .home-image>img{width:100%;height:auto;aspect-ratio:600/314;border-radius:8px}
64
+ .home-features .home-image>.home-play{position:absolute;width:56px;height:56px;left:20px;bottom:20px}
65
+ .home-theaters{padding:0 20px 74px}
66
+ .home-location{display:flex;align-items:center;color:#919191;font-size:14px;line-height:20px;margin-top:4px}
67
+ .home-location button{display:inline-flex;align-items:center;color:#3e8ede;background:transparent;border:0;font-weight:700;font-size:14px;padding:0 5px}
68
+ .home-location .home-icon{width:12px;height:14px}
69
+ .home-theaters .home-section-link{margin-top:16px;margin-bottom:16px}
70
+ .home-theater-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px}
71
+ .home-theater{display:block;border:1px solid #333;border-radius:8px;min-height:120px;padding:16px;color:#f2f3f3!important}
72
+ .home-theater>div{display:flex;justify-content:space-between;gap:12px;align-items:baseline}
73
+ .home-theater h3{font-size:14px;line-height:20px;margin:0}
74
+ .home-theater span{font-size:14px;color:#919191;font-weight:400;white-space:nowrap}
75
+ .home-theater p{font-size:14px;line-height:20px;color:#919191;font-weight:400;margin:8px 0 0}
76
+ .home-theater:hover{border-color:#3e8ede;text-decoration:none}
77
+ .home-banner img{width:100%;height:auto;display:block}
78
+ .home-offers{padding:60px 20px 0}
79
+ .home-offers .home-section-link{margin-top:4px}
80
+ .home-offer-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin-top:18px}
81
+ .home-offer{border:1px solid #333;border-radius:8px;overflow:hidden;display:flex;flex-direction:column}
82
+ .home-offer>a>img{width:100%;height:118px;object-fit:fill}
83
+ .home-offer>div{padding:16px;display:flex;flex-direction:column;flex:1;min-height:177px}
84
+ .home-offer h3{font-size:16px;line-height:20px;margin:0}
85
+ .home-offer p{font-size:14px;line-height:20px;margin:5px 0 0;font-weight:400}
86
+ .home-offer-cta{margin-top:auto;padding-top:2px;font-size:14px;line-height:20px}
87
+ .home-new-soon{padding:60px 20px}
88
+ .home-new-soon>div{display:flex;justify-content:space-between;gap:10px;overflow:hidden;margin-top:20px}
89
+ .home-new-soon a{flex:0 0 144px}
90
+ .home-new-soon img{width:144px;height:221px;object-fit:fill;border-radius:4px}
91
+ .home-footer{padding:0;margin:0;border:0;background:#121212}
92
+ .home-footer-columns{background:#000;padding:40px 30px;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:20px}
93
+ .home-footer-columns h3{text-transform:uppercase;font-size:14px;line-height:24px;margin:0 0 10px}
94
+ .home-footer-columns a{display:block;font-size:14px;line-height:16px;padding:5px 0;font-weight:400}
95
+ .home-social{display:grid;grid-template-columns:1fr 1fr;gap:30px;padding:28px 20px 60px}
96
+ .home-social>div{display:flex;align-items:center;justify-content:center;gap:12px}
97
+ .home-social h2{font-size:20px;line-height:24px;margin-right:8px}
98
+ .home-social .home-icon{width:30px;height:30px}
99
+ .home-social a[aria-label="Fandango iOS App"] .home-icon{width:90px}
100
+ .home-social a[aria-label="Fandango Android App"] .home-icon{width:100px}
101
+ .home-legal{text-align:center;padding:0 20px 20px;font-size:14px;line-height:20px}
102
+ .home-legal button{background:none;border:0;color:#f2f3f3;padding:0 6px;font-weight:700}
103
+ .home-support-links{text-transform:uppercase;margin:0 0 28px}
104
+ .home-policy-links{margin-bottom:12px}
105
+ .home-policy-links .home-icon{width:29px;height:14px;margin-right:4px}
106
+ .home-support-links a,.home-policy-links a,.home-affiliates a{padding:0 6px;border-right:1px solid #333}
107
+ .home-support-links a:last-child,.home-policy-links a:last-child,.home-affiliates a:last-child{border:0}
108
+ .home-advertise{display:inline-block;border:1px solid #3478c1;border-radius:3px;margin:20px auto 28px;padding:6px 48px;font-size:12px;line-height:18px;color:#f2f3f3!important}
109
+ .home-studios{width:343px;height:auto;margin:0 auto 26px}
110
+ .home-copyright{font-size:12px;margin:0}
111
+ .home-copyright a{color:#f2f3f3;font-weight:400}
112
+ .home-disclaimer{font-size:12px;line-height:18px;color:#b8b8b8;margin:16px auto 0;max-width:760px}
113
+ .home-dialog{width:min(460px,calc(100% - 32px));background:#1e1e1e;color:#f2f3f3;border:1px solid #555;border-radius:8px;padding:32px}
114
+ .home-dialog::backdrop{background:#000b}
115
+ .home-dialog-close{position:absolute;right:8px;top:4px;background:none;border:0;color:white;font-size:28px}
116
+ .home-dialog h2{margin:0 0 20px}
117
+ .home-dialog label{display:block;margin-bottom:8px}
118
+ .home-dialog input{width:100%;padding:12px;background:#121212;border:1px solid #777;color:white;border-radius:4px}
119
+ .home-dialog p{line-height:1.5}
120
+ .home-location-hint{font-size:13px;color:#ccc}
121
+ .home-location-error{color:#ffb19c}
122
+ @media(max-width:1100px){
123
+ .home-nav{height:auto;min-height:70px;flex-wrap:wrap;padding:8px 16px}
124
+ .home-logo{flex-basis:210px}.home-logo .home-icon{width:210px}
125
+ .home-search{max-width:none;margin-right:0}
126
+ .home-nav nav{flex-basis:100%;max-width:none;justify-content:space-around;padding:8px 0}
127
+ .home-carousel-now{width:100%}
128
+ .home-social{display:flex;flex-wrap:wrap;justify-content:center}
129
+ .home-offer-grid{grid-template-columns:repeat(2,minmax(0,1fr))}
130
+ }
131
+ @media(max-width:700px){
132
+ html:has(body.homepage){scrollbar-gutter:auto}
133
+ body.homepage{padding-top:0}
134
+ .home-nav{gap:8px}.home-logo{flex-basis:170px;height:40px}.home-logo .home-icon{width:170px;height:40px}
135
+ .home-search{flex-basis:100%;order:2}.home-search input{font-size:14px}
136
+ .home-nav nav{order:3;gap:8px;justify-content:space-between}.home-nav nav a{font-size:10px;gap:5px}.home-nav nav .home-icon{width:18px;height:18px}
137
+ .home-promo{gap:10px;padding:10px 16px}.home-promo-content{width:calc(100% - 70px)}.home-promo-content>a{white-space:normal;font-size:12px;line-height:15px;gap:8px}.home-promo-content>a>img{width:28px;height:28px}
138
+ .home-section{padding:28px 16px 12px}.homepage h2{font-size:18px}
139
+ .home-slide{flex-basis:110px}.home-image>img{width:110px;height:165px}.home-slide h3{font-size:14px;line-height:18px}
140
+ .home-carousel-arrow{top:calc(165px / 2 - 16px)}
141
+ .home-features{padding-bottom:40px}.home-features .home-slide{flex-basis:82%}.home-features .home-image>.home-play{width:40px;height:40px;left:12px;bottom:12px}
142
+ .home-theaters{padding:0 16px 40px}.home-theater-grid{grid-template-columns:1fr}.home-theater{min-height:100px}
143
+ .home-theaters .home-section-link{margin-top:12px}.home-location{font-size:11px}.home-location button{font-size:12px}
144
+ .home-offers{padding:32px 16px 0}.home-offer-grid{grid-template-columns:1fr}.home-offer>div{min-height:150px}.home-offer>a>img{height:auto;aspect-ratio:300/118}
145
+ .home-new-soon{padding:32px 16px}.home-new-soon>div{justify-content:flex-start}.home-new-soon a{flex-basis:94px}.home-new-soon img{width:94px;height:144px}
146
+ .home-footer-columns{grid-template-columns:repeat(2,minmax(0,1fr));padding:28px 16px;gap:24px 16px}.home-footer-columns h3{font-size:12px}.home-footer-columns a{font-size:12px}
147
+ .home-social{padding:30px 16px;gap:28px}.home-social>div{gap:8px}.home-social h2{font-size:15px;margin-right:0}
148
+ .home-legal{font-size:12px;padding:0 16px 20px}.home-support-links,.home-policy-links,.home-affiliates{display:flex;flex-wrap:wrap;justify-content:center;gap:8px 0}
149
+ }
tasks/fandango/environment/reference/clone/static/home.js ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Homepage reference: 官网首页1.png, supported by public source DOM on 2026-09-04. */
2
+ let homeZip = localStorage.getItem('fandango-home-zip') || HOME_DATA.defaultZip;
3
+ let homePromoIndex = 0;
4
+ let homeResizeObserver;
5
+
6
+ function homeHref(href){
7
+ const url=new URL(href, HOME_DATA.source);
8
+ if(url.hostname==='store.fandango.com') return `/fanstore${url.pathname==='/'?'':url.pathname}${url.search}`;
9
+ if(url.hostname==='athome.fandango.com') return url.pathname.includes('/details/')?`/streaming/movies/${url.pathname.split('/').pop()}`:'/streaming';
10
+ if(url.hostname==='www.fandango.com'){
11
+ if(url.pathname==='/movie-news'||url.pathname.startsWith('/movie-news/')||url.pathname.startsWith('/movie-photos/')||url.pathname.startsWith('/movie-trailer/')) return url.pathname+url.search;
12
+ if(url.pathname.match(/^\/\d{5}_movietimes$/)) return `/theaters?zip=${url.pathname.slice(1,6)}`;
13
+ if(url.pathname.endsWith('/theater-page')) return `/theaters/local/${url.pathname.split('/')[1].split('-').pop()}`;
14
+ const routes={'/':'/','/movies-in-theaters':'/movies','/accounts/join-now':'/account','/accounts/dashboard':'/account','/offers':'/offers','/fandango-gift-cards':'/help#gift-cards','/policies/privacy-policy':'/policies/privacy-policy','/policies/terms-and-policies':'/policies/terms-of-use'};
15
+ if(routes[url.pathname]) return routes[url.pathname];
16
+ const movie=state.data.movies.find(m=>url.pathname===`/${m.id}/movie-overview`);
17
+ if(movie) return `/movies/${movie.id}`;
18
+ if(url.pathname.endsWith('/movie-overview')) return `/movies/reference/${url.pathname.split('/')[1]}`;
19
+ }
20
+ return href;
21
+ }
22
+ function homeLink(href,content,attributes=''){
23
+ const target=homeHref(href);
24
+ return `<a href="${esc(target)}" ${target.startsWith('/')?'data-link':'target="_blank" rel="noopener noreferrer"'} ${attributes}>${content}</a>`;
25
+ }
26
+ function homeIcon(name,extra=''){
27
+ return `<img class="home-icon ${extra}" src="${HOME_DATA.icons[name]||`/static/home-assets/icon-nav-${name}.svg`}" alt="" aria-hidden="true">`;
28
+ }
29
+ function homePromos(){
30
+ return [HOME_DATA.promo,...(state.data.offers||[]).map(o=>({...o,href:`/movies/${o.movie_id}`,icon:HOME_DATA.promo.icon})),...HOME_DATA.additionalPromos];
31
+ }
32
+ function homePromo(){
33
+ const offers=homePromos();
34
+ const index=((homePromoIndex%offers.length)+offers.length)%offers.length;
35
+ const offer=offers[index];
36
+ return `<div class="home-promo" aria-label="Promotions">
37
+ <button class="home-promo-arrow previous" data-home-promo-step="-1" aria-label="Previous offer"></button>
38
+ <div class="home-promo-content">${homeLink(offer.href,`<img src="${esc(offer.icon)}" alt=""><span><strong>${esc(offer.headline)}</strong><span>${esc(offer.detail)}</span></span>`)}
39
+ <div class="home-promo-dots">${offers.map((o,i)=>`<button data-home-promo-go="${i}" aria-label="Show offer ${i+1}" aria-current="${index===i}"></button>`).join('')}</div>
40
+ </div>
41
+ <button class="home-promo-arrow next" data-home-promo-step="1" aria-label="Next offer"></button>
42
+ </div>`;
43
+ }
44
+ function homeHeader(){
45
+ const profile=state.data.profile;
46
+ const items=[['/movies','movies','Movies'],[`/theaters?zip=${homeZip}`,'theaters','Theaters'],['/fanstore','fanstore','FanStore'],['/streaming','on-demand','Streaming'],['/movie-news','news','Movie News'],['/account','account',profile?profile.display_name.split(' ')[0]:'Sign In/Join']];
47
+ return `<header class="home-header"><div class="home-utility"><a href="/help#gift-cards" data-link>Gift Cards</a><a href="/offers" data-link>Offers</a>${homeLink('https://www.fandango.com/fanclub/memberships',`${homeIcon('fanclub')} FanClub`)}</div>
48
+ <div class="home-nav"><a class="home-logo" href="/" data-link aria-label="Fandango">${homeIcon('logo')}</a>
49
+ <form class="home-search" data-search-form role="search"><input name="q" aria-label="Search by city, state, zip or movie" placeholder="Search by city, state, zip or movie"><button aria-label="Search"><svg viewBox="0 0 14 14" aria-hidden="true"><circle cx="5.5" cy="5.5" r="4.5"/><path d="m9 9 4 4"/></svg></button></form>
50
+ <nav class="nav-icons" aria-label="Primary">${items.map(([href,icon,label])=>homeLink(href,`${homeIcon(icon)}<span>${esc(label)}</span>`)).join('')}</nav>
51
+ </div>${homePromo()}</header>`;
52
+ }
53
+ function homeCarousel(id,title,rows,link='',features=false){
54
+ return `<section class="home-section ${features?'home-features':''}" aria-labelledby="${id}-title"><h2 id="${id}-title">${title}</h2>${link?homeLink(link,'SEE ALL MOVIES','class="home-section-link"'):''}
55
+ <div class="home-carousel ${id==='now'?'home-carousel-now':''}" data-home-carousel="${id}" aria-roledescription="carousel">
56
+ <div class="home-track" id="${id}-track" tabindex="0" aria-label="${title}">
57
+ ${rows.map(row=>`<article class="home-slide">${homeLink(row.href,`<div class="home-image"><img src="${esc(row.image)}" alt="${esc(row.title)}" width="${features?400:140}" height="${features?210:210}" loading="${id==='now'?'eager':'lazy'}">${row.gift?`<span class="home-gift" aria-label="Gift with purchase">${homeIcon('gift')}</span>`:''}${features&&row.video?homeIcon('play','home-play'):''}</div><h3>${esc(row.title)}</h3>${features?`<p>${esc(row.description)}</p>`:''}`)}</article>`).join('')}
58
+ </div>
59
+ <button class="home-carousel-arrow previous" data-home-step="-1" aria-label="Previous ${title.toLowerCase()}" aria-controls="${id}-track" disabled></button>
60
+ <button class="home-carousel-arrow next" data-home-step="1" aria-label="Next ${title.toLowerCase()}" aria-controls="${id}-track"></button>
61
+ </div></section>`;
62
+ }
63
+ function homeTheaters(){
64
+ const theaters=homeZip==='90001'?HOME_DATA.theaters:state.data.theaters.map(t=>({name:t.name,distance:`${t.distance}mi`,address:t.location.split(',')[0],city:t.location.split(',').slice(1).join(',').trim(),href:`/theaters/${t.id}`}));
65
+ return `<section class="home-theaters" aria-labelledby="home-theaters-title"><h2 id="home-theaters-title">THEATERS NEAR YOU</h2>
66
+ <div class="home-location">ENTER CITY, STATE, OR ZIPCODE <button data-home-location aria-label="Theaters near ${homeZip}">${homeIcon('location')}${homeZip}</button></div>
67
+ ${homeLink(homeZip==='90001'?'https://www.fandango.com/90001_movietimes':'/theaters','SEE MORE THEATERS','class="home-section-link"')}
68
+ <div class="home-theater-grid">${theaters.map(t=>homeLink(t.href,`<div><h3>${esc(t.name)}</h3><span>${esc(t.distance)}</span></div><p>${esc(t.address)}<br>${esc(t.city)}</p>`,'class="home-theater"')).join('')}</div>
69
+ </section>`;
70
+ }
71
+ function homeOffers(){
72
+ return `<section class="home-offers" aria-labelledby="home-offers-title"><h2 id="home-offers-title">OFFERS</h2><a class="home-section-link" href="/offers" data-link>SEE ALL OFFERS</a>
73
+ <div class="home-offer-grid">${HOME_DATA.offers.map(o=>`<article class="home-offer">${homeLink(o.href,`<img src="${o.image}" alt="${esc(o.title)}" loading="lazy" width="300" height="118">`)}<div><h3>${esc(o.title)}</h3><p>${esc(o.description)}</p>${homeLink(o.href,esc(o.cta),'class="home-offer-cta"')}</div></article>`).join('')}</div></section>`;
74
+ }
75
+ function homeFooter(){
76
+ return `<footer class="home-footer"><nav class="home-footer-columns" aria-label="Explore Fandango">${HOME_DATA.footerColumns.map(c=>`<div><h3>${esc(c.title)}</h3>${c.links.map(l=>homeLink(l.href,esc(l.title))).join('')}</div>`).join('')}</nav>
77
+ <div class="home-social"><div><h2>FOLLOW US</h2>${HOME_DATA.social.slice(0,4).map(l=>homeLink(l.href,homeIcon(l.icon),`aria-label="${esc(l.title)}"`)).join('')}</div><div><h2>GET FANDANGO APPS</h2>${HOME_DATA.social.slice(4).map(l=>homeLink(l.href,homeIcon(l.icon),`aria-label="${esc(l.title)}"`)).join('')}</div></div>
78
+ <div class="home-legal"><div class="home-support-links">${HOME_DATA.footerLinks[0].map(l=>homeLink(l.href,esc(l.title))).join('')}<button data-home-notice="feedback">FEEDBACK</button></div>
79
+ <div class="home-policy-links">${HOME_DATA.footerLinks[1].map((l,i)=>`${i===5?`<button data-home-notice="privacy">${homeIcon('privacy')}Your Privacy Choices</button>`:''}${homeLink(l.href,esc(l.title))}`).join('')}</div>
80
+ <div class="home-affiliates">Fandango Affiliated Companies: ${HOME_DATA.footerLinks[2].map(l=>homeLink(l.href,esc(l.title))).join('')}</div>
81
+ ${homeLink('https://together.nbcuni.com/advertise/','Advertise With Us','class="home-advertise"')}
82
+ <img class="home-studios" src="${HOME_DATA.studios}" alt="Movie studio brands" loading="lazy">
83
+ <p class="home-copyright">© 2026 Fandango | ${homeLink('https://versantmedia.com/','A Versant Media Company')}</p>
84
+ <p class="home-disclaimer">WebsiteBench offline recreation. Not the official Fandango service. No real tickets, charges, emails or venue messages. Some links open the original website.</p>
85
+ </div></footer>`;
86
+ }
87
+ function bindHomeCarousel(){
88
+ homeResizeObserver?.disconnect();
89
+ homeResizeObserver=new ResizeObserver(entries=>entries.forEach(entry=>entry.target.dispatchEvent(new Event('scroll'))));
90
+ root.querySelectorAll('[data-home-carousel]').forEach(carousel=>{
91
+ const track=carousel.querySelector('.home-track');
92
+ const previous=carousel.querySelector('.previous');
93
+ const next=carousel.querySelector('.next');
94
+ const update=()=>{previous.disabled=track.scrollLeft<1;next.disabled=track.scrollLeft>=track.scrollWidth-track.clientWidth-1;};
95
+ carousel.querySelectorAll('[data-home-step]').forEach(button=>button.addEventListener('click',()=>{
96
+ const slide=track.querySelector('.home-slide');
97
+ const step=slide.getBoundingClientRect().width+20;
98
+ track.scrollBy({left:Number(button.dataset.homeStep)*step*Math.max(1,Math.floor(track.clientWidth/step)),behavior:'smooth'});
99
+ }));
100
+ track.addEventListener('scroll',update,{passive:true});
101
+ track.addEventListener('keydown',event=>{if(event.key==='ArrowRight'||event.key==='ArrowLeft'){event.preventDefault();(event.key==='ArrowRight'?next:previous).click();}});
102
+ homeResizeObserver.observe(track);
103
+ update();
104
+ });
105
+ }
106
+ function bindHomePromo(){
107
+ const promo=root.querySelector('.home-promo');
108
+ const change=index=>{homePromoIndex=index;promo.outerHTML=homePromo();bindHomePromo();};
109
+ promo.querySelectorAll('[data-home-promo-step]').forEach(b=>b.addEventListener('click',()=>change(homePromoIndex+Number(b.dataset.homePromoStep))));
110
+ promo.querySelectorAll('[data-home-promo-go]').forEach(b=>b.addEventListener('click',()=>change(Number(b.dataset.homePromoGo))));
111
+ promo.querySelectorAll('[data-link]').forEach(a=>a.addEventListener('click',e=>{if(!e.defaultPrevented&&e.button===0&&!e.ctrlKey&&!e.metaKey){e.preventDefault();go(a.getAttribute('href'));}}));
112
+ }
113
+ function homeDialog(content){
114
+ const old=root.querySelector('.home-dialog');if(old) old.remove();
115
+ root.insertAdjacentHTML('beforeend',`<dialog class="home-dialog"><button class="home-dialog-close" aria-label="Close">×</button>${content}</dialog>`);
116
+ const dialog=root.querySelector('.home-dialog');
117
+ dialog.querySelector('.home-dialog-close').addEventListener('click',()=>dialog.close());
118
+ dialog.addEventListener('click',event=>{if(event.target===dialog)dialog.close();});
119
+ dialog.showModal();return dialog;
120
+ }
121
+ function homeLocationDialog(onChange){
122
+ const dialog=homeDialog(`<h2>Enter city, state, or ZIP code</h2><form><label for="home-zip">Location</label><input id="home-zip" name="zip" value="${homeZip}" autocomplete="postal-code"><p class="home-location-hint">Available in this offline preview: Los Angeles, CA 90001 and New York, NY 10003.</p><p class="home-location-error" role="alert"></p><button class="primary" type="submit">UPDATE LOCATION</button></form>`);
123
+ dialog.querySelector('form').addEventListener('submit',event=>{
124
+ event.preventDefault();const value=new FormData(event.currentTarget).get('zip').toString().trim().toLowerCase();
125
+ const zip={'90001':'90001','los angeles':'90001','los angeles, ca':'90001','10003':'10003','new york':'10003','new york, ny':'10003'}[value];
126
+ if(!zip){dialog.querySelector('.home-location-error').textContent='This preview has captured data for 90001 and 10003 only.';return;}
127
+ homeZip=zip;localStorage.setItem('fandango-home-zip',zip);dialog.close();if(typeof onChange==='function'){onChange(zip);return;}const y=scrollY;renderHome();window.scrollTo(0,y);
128
+ });
129
+ }
130
+ function renderHome(){
131
+ document.body.className='homepage';
132
+ root.innerHTML=`${homeHeader()}<main class="home-main">
133
+ ${homeCarousel('now','MOVIES IN THEATERS',HOME_DATA.now,'/movies')}
134
+ ${homeCarousel('soon','COMING SOON TO THEATERS',HOME_DATA.soon)}
135
+ ${homeCarousel('free','FREE TO WATCH',HOME_DATA.free,'https://athome.fandango.com/')}
136
+ ${homeCarousel('features','FEATURES',HOME_DATA.features,'',true)}
137
+ ${homeTheaters()}
138
+ <div class="home-banner">${homeLink(HOME_DATA.banner.href,`<img src="${HOME_DATA.banner.image}" alt="Ryan Garcia vs. Conor Benn — Saturday September 12. Learn more." width="1232" height="258" loading="lazy">`)}</div>
139
+ ${homeOffers()}
140
+ <section class="home-new-soon"><h2>NEW &amp; COMING SOON</h2><div>${HOME_DATA.newSoon.map(m=>homeLink(m.href,`<img src="${m.image}" alt="${esc(m.title)}" width="144" height="221" loading="lazy">`)).join('')}</div></section>
141
+ </main>${homeFooter()}`;
142
+ bindGlobal();bindHomeCarousel();bindHomePromo();
143
+ root.querySelector('[data-home-location]').addEventListener('click',homeLocationDialog);
144
+ root.querySelectorAll('[data-home-notice]').forEach(b=>b.addEventListener('click',()=>homeDialog(b.dataset.homeNotice==='privacy'?'<h2>Your Privacy Choices</h2><p>This offline recreation does not sell or share your information, load advertising, or track you across websites.</p><p><a href="/policies/privacy-policy">Read the local privacy policy</a></p>':'<h2>Feedback</h2><p>This is an offline recreation. Feedback is not sent to Fandango. Share feedback with the owner of this preview.</p>')));
145
+ }
tasks/fandango/environment/reference/clone/static/nav-assets/0001-FAN_FanStore_Stacked_FullColor_RGB.png ADDED

Git LFS Details

  • SHA256: 8c873db2c68cb69bf7bdada4df631baedfdd41d7e34c7187d34bae14c552da02
  • Pointer size: 130 Bytes
  • Size of remote file: 26 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0004-Rotten_Tomatoes_logo_svg.png ADDED

Git LFS Details

  • SHA256: 7b20bf868646651ff9267b50179fc9bcb67f04ca7f74986d36c76ad2877b9b34
  • Pointer size: 130 Bytes
  • Size of remote file: 10.9 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0009-JSW10956-Grogu-Mandalorian-Short-Glasses-Listing-1.jpg ADDED

Git LFS Details

  • SHA256: 77950b3e2ffc4b917858ec123651537a275cfc186f98173344f52c3239184833
  • Pointer size: 131 Bytes
  • Size of remote file: 123 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0010-Screenshot_2026-06-05_at_7-16-05_PM.png ADDED

Git LFS Details

  • SHA256: eea5c39e16c6d8dc31a0268ea56a54196389cd60ae9f231f6d68a608c36df759
  • Pointer size: 131 Bytes
  • Size of remote file: 445 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0012-unisex-garment-dyed-heavyweight-t-shirt-ivory-front-2-6a5e3f3d217e0.jpg ADDED

Git LFS Details

  • SHA256: 1c08f3d970717964193be37c03a8bca156021746820cb905828b58095ab10060
  • Pointer size: 130 Bytes
  • Size of remote file: 85.1 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0015-FAN_Shopify_SpidermanBND_PosterBundle_Card_2048x2048_ac5b17c3-558a-4a6.jpg ADDED

Git LFS Details

  • SHA256: 7bf758554986268e6a1f86c07308ad92441c00ec832fba9e3e0798f1b47539bb
  • Pointer size: 131 Bytes
  • Size of remote file: 518 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0023-1-1-1-1-20487-D-3_v2-1772118566769_eca93243-79f7-4071-b311-3a1451ccde5.jpg ADDED

Git LFS Details

  • SHA256: 41f8c653cac7fde7a64c42eaee0dba880ca8c388b0b61d3a3f86a470fab0285c
  • Pointer size: 130 Bytes
  • Size of remote file: 72.7 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0024-FAN_Shopify_PracticalMagic2Bundle_Standard_2048x2048_f8c66d34-b257-4ad.jpg ADDED

Git LFS Details

  • SHA256: ec49f1488348f0153d9e429fa69b7fc08faed3cb85989e8afac2a626b50735ec
  • Pointer size: 131 Bytes
  • Size of remote file: 238 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0025-FAN_Shopify_PracticalMagic2Bundle_PopcornBucket_2048x2048_02db5341-836.jpg ADDED

Git LFS Details

  • SHA256: 01290a99d10563466b9c8e689b270003438b92db32f175ffc0043c6c80013ca5
  • Pointer size: 131 Bytes
  • Size of remote file: 138 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0028-JSW10956_-_Grogu_Mandalorian_Short_Glasses_Lifestyle-3-legal.jpg ADDED

Git LFS Details

  • SHA256: ef7ef115ca4d648c492380d4bddbb5895123b287624bf3931ccfe17973818e22
  • Pointer size: 131 Bytes
  • Size of remote file: 420 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0031-unisex-garment-dyed-heavyweight-t-shirt-ivory-front-6a5e3f3d213cf.jpg ADDED

Git LFS Details

  • SHA256: bff46e8394f5fe0b15f85e7ab8baa178b0d274291aaf7a61cd77fe8a71aa9ef4
  • Pointer size: 131 Bytes
  • Size of remote file: 304 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0032-unisex-garment-dyed-heavyweight-t-shirt-ivory-front-2-6a5e3f3d217e0.jpg ADDED

Git LFS Details

  • SHA256: 3f49117fc364dd371db0f03414e02a4756d8c2291bd18eea2492f814ebdb49f4
  • Pointer size: 131 Bytes
  • Size of remote file: 193 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0033-unisex-garment-dyed-heavyweight-t-shirt-ivory-front-2-6a5e3f3d21a88.jpg ADDED

Git LFS Details

  • SHA256: ac081f781101ad78b6b06ad33d895bf11f9362f19f3fd395c6ea730d29845571
  • Pointer size: 131 Bytes
  • Size of remote file: 154 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0034-shaker-pint-glass-_16-oz_-16-oz-front-6a5e48fd13c09.jpg ADDED

Git LFS Details

  • SHA256: 1514207501e7c448f8169720d2cba3eb1f93f2e24aa6eeb7622ce5f24d64aceb
  • Pointer size: 131 Bytes
  • Size of remote file: 130 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0036-shaker-pint-glass-_16-oz_-16-oz-front-6a5e493c42fa0.jpg ADDED

Git LFS Details

  • SHA256: cb7d884f57b4a4272f8aba2a52006bc7b8fe315cfaa7d35e2999d553cb63f95b
  • Pointer size: 131 Bytes
  • Size of remote file: 219 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0037-shaker-pint-glass-_16-oz_-16-oz-right-6a5e48fd147c8.jpg ADDED

Git LFS Details

  • SHA256: 74c71a296bba26b237de18475caab4e68f88c659d7b919f0db01a5fecad599af
  • Pointer size: 131 Bytes
  • Size of remote file: 125 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0038-can-cooler-white-regular-12-oz-front-680fab155ba87.jpg ADDED

Git LFS Details

  • SHA256: 190036980f65d0fc4dc5aaa023686f4bb8f1c636555161e231413a5a2def1f0d
  • Pointer size: 130 Bytes
  • Size of remote file: 97 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0039-can-cooler-white-regular-12-oz-back-680fab155bcc2.jpg ADDED

Git LFS Details

  • SHA256: e7a80d64514165d9f8a0960593347d9074aa0b388358904319c40ee9aef43ee2
  • Pointer size: 131 Bytes
  • Size of remote file: 107 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0040-can-cooler-white-regular-12-oz-front-680fab155bb31.jpg ADDED

Git LFS Details

  • SHA256: 012ea5d98754a58502e6838637d33d5677296906d2dee31b82271ad6668cd8b2
  • Pointer size: 130 Bytes
  • Size of remote file: 74.8 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0041-can-cooler-white-regular-12-oz-front-680fab155bc01.jpg ADDED

Git LFS Details

  • SHA256: 1d355778b39272de9a0e190227cde839a76bb16dbc4fd16b6b1536358737e6a0
  • Pointer size: 131 Bytes
  • Size of remote file: 125 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0043-FAN_Shopify_ToyStory5_PrintBundle_Print_2048x2048_573188cb-4474-4229-a.jpg ADDED

Git LFS Details

  • SHA256: ce620c40c14aefa6421cb56d89b15e8d408259d7cd8c345b2e80cd175f28b452
  • Pointer size: 131 Bytes
  • Size of remote file: 157 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0045-white-ceramic-mug-with-color-inside-orange-11-oz-front-6a5e358264039.jpg ADDED

Git LFS Details

  • SHA256: 3361906d4ecbaf8f69c5c1c86bdd9cb992601487636a97e1e697b183552cd7b8
  • Pointer size: 131 Bytes
  • Size of remote file: 103 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0047-white-ceramic-mug-with-color-inside-orange-11-oz-left-6a5e359bab63c.jpg ADDED

Git LFS Details

  • SHA256: a3539aff6166e3be99f449f7301240ad933e42302b7552ae55cc6c329b02ea98
  • Pointer size: 131 Bytes
  • Size of remote file: 304 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0049-300321444.png ADDED

Git LFS Details

  • SHA256: 35785b72e3c797b672a4b2eb64026749cf98bf8b15d4351463b9afffd13f38b3
  • Pointer size: 131 Bytes
  • Size of remote file: 141 kB
tasks/fandango/environment/reference/clone/static/nav-assets/0050-unisex-premium-t-shirt-black-front-6a5e4470a4742.jpg ADDED

Git LFS Details

  • SHA256: 5fced7c03d39ae918dd909982b877d71a2ca351c6e330401e0a479c3e420a462
  • Pointer size: 131 Bytes
  • Size of remote file: 105 kB