AgPerry commited on
Commit
5b847ea
·
verified ·
1 Parent(s): 205b258

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/dooney-bourke/environment/agent-browser/browser-use +128 -0
  2. tasks/dooney-bourke/environment/agent-browser/gateway.py +305 -0
  3. tasks/dooney-bourke/environment/candidate-abi/websitebench-candidate-preflight +5 -0
  4. tasks/dooney-bourke/environment/candidate-abi/websitebench/__init__.py +1 -0
  5. tasks/dooney-bourke/environment/candidate-abi/websitebench/harbor/__init__.py +1 -0
  6. tasks/dooney-bourke/environment/candidate-abi/websitebench/harbor/candidate_preflight.py +179 -0
  7. tasks/dooney-bourke/environment/candidate-abi/websitebench/harbor/compiler.py +1128 -0
  8. tasks/dooney-bourke/environment/candidate-abi/websitebench/harbor/sandbox.py +841 -0
  9. tasks/dooney-bourke/environment/mailbox/Dockerfile +5 -0
  10. tasks/dooney-bourke/environment/mailbox/mailbox.py +2433 -0
  11. tasks/dooney-bourke/environment/reference/.websitebench-reference-tls/ca.crt +20 -0
  12. tasks/dooney-bourke/environment/reference/.websitebench-reference-tls/reference.crt +20 -0
  13. tasks/dooney-bourke/environment/reference/.websitebench-reference-tls/reference.key +28 -0
  14. tasks/dooney-bourke/environment/reference/.websitebench-reference-tls/tls_proxy.py +164 -0
  15. tasks/dooney-bourke/environment/reference/Dockerfile +19 -0
  16. tasks/dooney-bourke/environment/reference/README.md +5 -0
  17. tasks/dooney-bourke/environment/reference/backend/model.json +435 -0
  18. tasks/dooney-bourke/environment/reference/backend/runtime.json +104 -0
  19. tasks/dooney-bourke/environment/reference/clone/README.md +5 -0
  20. tasks/dooney-bourke/environment/reference/clone/app.py +370 -0
  21. tasks/dooney-bourke/environment/reference/clone/backend/business.py +332 -0
  22. tasks/dooney-bourke/environment/reference/clone/backend/site_backend_integration.py +112 -0
  23. tasks/dooney-bourke/environment/reference/clone/compile.sh +6 -0
  24. tasks/dooney-bourke/environment/reference/clone/requirements.txt +1 -0
  25. tasks/dooney-bourke/environment/reference/clone/static/assets/fonts/BemboStd.woff2 +0 -0
  26. tasks/dooney-bourke/environment/reference/clone/static/assets/fonts/Lato-Bold.woff2 +0 -0
  27. tasks/dooney-bourke/environment/reference/clone/static/assets/fonts/Lato-Regular.woff2 +0 -0
  28. tasks/dooney-bourke/environment/reference/clone/static/assets/icons/contact.svg +5 -0
  29. tasks/dooney-bourke/environment/reference/clone/static/assets/icons/dooney-logo-black.svg +15 -0
  30. tasks/dooney-bourke/environment/reference/clone/static/assets/icons/shipping.svg +3 -0
  31. tasks/dooney-bourke/environment/reference/clone/static/assets/icons/warranty.svg +13 -0
  32. tasks/dooney-bourke/environment/reference/clone/static/assets/images/categories/sports/nfl-cowboys-crossbody.avif +0 -0
  33. tasks/dooney-bourke/environment/reference/clone/static/assets/images/categories/sports/nfl-eagles-pocket-tote.avif +0 -0
  34. tasks/dooney-bourke/environment/reference/clone/static/assets/images/home/newsletter-source.webp.b64 +1 -0
  35. tasks/dooney-bourke/environment/reference/clone/static/site.css +248 -0
  36. tasks/dooney-bourke/environment/reference/clone/static/site.js +89 -0
  37. tasks/dooney-bourke/environment/reference/clone/tools/form-contracts.html +3 -0
  38. tasks/dooney-bourke/environment/reference/clone/websitebench/__init__.py +1 -0
  39. tasks/dooney-bourke/environment/reference/clone/websitebench/local_clone_auth/VENDOR_MANIFEST.json +16 -0
  40. tasks/dooney-bourke/environment/reference/clone/websitebench/local_clone_auth/__init__.py +39 -0
  41. tasks/dooney-bourke/environment/reference/clone/websitebench/local_clone_auth/store.py +2186 -0
  42. tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/VENDOR_MANIFEST.json +66 -0
  43. tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/__init__.py +47 -0
  44. tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/auth_mail.py +272 -0
  45. tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/backend.py +55 -0
  46. tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/database.py +726 -0
  47. tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/effects_mail.py +236 -0
  48. tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/errors.py +35 -0
  49. tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/mail.py +502 -0
  50. tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/payments.py +745 -0
tasks/dooney-bourke/environment/agent-browser/browser-use ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 main() -> int:
85
+ translated = _translate_candidate_origin(sys.argv[1:])
86
+ arguments, local_screenshot, shared_screenshot = _prepare_screenshot(translated)
87
+ request = urllib.request.Request(
88
+ GATEWAY_URL,
89
+ data=json.dumps({"argv": arguments}, separators=(",", ":")).encode("utf-8"),
90
+ headers={"Content-Type": "application/json"},
91
+ method="POST",
92
+ )
93
+ try:
94
+ with urllib.request.urlopen(request, timeout=240) as response:
95
+ payload = json.load(response)
96
+ except urllib.error.HTTPError as exc:
97
+ try:
98
+ detail = json.loads(exc.read().decode("utf-8")).get("error")
99
+ except (UnicodeError, ValueError, AttributeError):
100
+ detail = None
101
+ print(detail or f"Browser Use gateway refused the command (HTTP {exc.code})", file=sys.stderr)
102
+ return 2
103
+ except (OSError, UnicodeError, ValueError) as exc:
104
+ print(f"Browser Use gateway unavailable: {exc}", file=sys.stderr)
105
+ return 2
106
+
107
+ stdout = payload.get("stdout", "")
108
+ stderr = payload.get("stderr", "")
109
+ if isinstance(stdout, str) and stdout:
110
+ print(stdout, end="" if stdout.endswith("\n") else "\n")
111
+ if isinstance(stderr, str) and stderr:
112
+ print(stderr, end="" if stderr.endswith("\n") else "\n", file=sys.stderr)
113
+
114
+ if local_screenshot is not None and shared_screenshot is not None:
115
+ try:
116
+ local_screenshot.parent.mkdir(parents=True, exist_ok=True)
117
+ shutil.copyfile(shared_screenshot, local_screenshot)
118
+ shared_screenshot.unlink(missing_ok=True)
119
+ except OSError as exc:
120
+ print(f"Browser screenshot transfer failed: {exc}", file=sys.stderr)
121
+ return 2
122
+
123
+ exit_code = payload.get("exit_code", 2)
124
+ return exit_code if isinstance(exit_code, int) and 0 <= exit_code <= 255 else 2
125
+
126
+
127
+ if __name__ == "__main__":
128
+ raise SystemExit(main())
tasks/dooney-bourke/environment/agent-browser/gateway.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import re
16
+ import subprocess
17
+ import threading
18
+ import urllib.parse
19
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+
24
+ MAX_REQUEST_BYTES = 64 * 1024
25
+ MAX_OUTPUT_BYTES = 4 * 1024 * 1024
26
+ COMMAND_TIMEOUT_SEC = 180
27
+ SESSION_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\Z")
28
+ SHARED_ROOT = Path("/browser-share").resolve()
29
+ REAL_BROWSER_USE = os.environ.get(
30
+ "WEBSITEBENCH_BROWSER_USE_REAL",
31
+ "/usr/local/bin/browser-use-real",
32
+ )
33
+ SAFE_COMMANDS = frozenset(
34
+ {
35
+ "open",
36
+ "click",
37
+ "type",
38
+ "input",
39
+ "scroll",
40
+ "back",
41
+ "screenshot",
42
+ "state",
43
+ "switch",
44
+ "close-tab",
45
+ "keys",
46
+ "select",
47
+ "hover",
48
+ "dblclick",
49
+ "rightclick",
50
+ "cookies",
51
+ "close",
52
+ "sessions",
53
+ }
54
+ )
55
+ FORBIDDEN_COMMANDS = frozenset(
56
+ {
57
+ "install",
58
+ "init",
59
+ "setup",
60
+ "doctor",
61
+ "upload",
62
+ "eval",
63
+ "extract",
64
+ "get",
65
+ "python",
66
+ "tunnel",
67
+ "cloud",
68
+ "profile",
69
+ "wait",
70
+ }
71
+ )
72
+ FORBIDDEN_GLOBAL_OPTIONS = frozenset(
73
+ {"--headed", "--profile", "--cdp-url", "--connect", "--mcp", "--template"}
74
+ )
75
+
76
+
77
+ class CommandRejected(ValueError):
78
+ """Raised when an Agent command crosses the browser-only boundary."""
79
+
80
+
81
+ def _origin(value: str) -> tuple[str, str, int]:
82
+ parsed = urllib.parse.urlsplit(value)
83
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
84
+ raise ValueError(f"invalid browser origin: {value!r}")
85
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
86
+ return parsed.scheme, parsed.hostname.lower(), port
87
+
88
+
89
+ def allowed_origins() -> frozenset[tuple[str, str, int]]:
90
+ values = (
91
+ os.environ.get(
92
+ "WEBSITEBENCH_BROWSER_REFERENCE_URL", "https://reference:8080"
93
+ ),
94
+ os.environ.get(
95
+ "WEBSITEBENCH_BROWSER_CANDIDATE_URL", "http://candidate:3000"
96
+ ),
97
+ os.environ.get(
98
+ "WEBSITEBENCH_BROWSER_MAILBOX_URL", "http://mailbox:8026"
99
+ ),
100
+ )
101
+ return frozenset(_origin(value) for value in values)
102
+
103
+
104
+ def _parse_global_options(arguments: list[str]) -> tuple[str, int]:
105
+ session = "default"
106
+ index = 0
107
+ while index < len(arguments):
108
+ value = arguments[index]
109
+ if value == "--session":
110
+ if index + 1 >= len(arguments):
111
+ raise CommandRejected("--session requires a value")
112
+ session = arguments[index + 1]
113
+ index += 2
114
+ continue
115
+ if value.startswith("--session="):
116
+ session = value.partition("=")[2]
117
+ index += 1
118
+ continue
119
+ if value == "--json":
120
+ index += 1
121
+ continue
122
+ if value in {"-h", "--help"}:
123
+ break
124
+ if value in FORBIDDEN_GLOBAL_OPTIONS or any(
125
+ value.startswith(option + "=") for option in FORBIDDEN_GLOBAL_OPTIONS
126
+ ):
127
+ raise CommandRejected(f"Browser Use option {value!r} is disabled")
128
+ if value.startswith("-"):
129
+ raise CommandRejected(f"unsupported Browser Use option {value!r}")
130
+ break
131
+ if not SESSION_PATTERN.fullmatch(session):
132
+ raise CommandRejected("invalid Browser Use session name")
133
+ return session, index
134
+
135
+
136
+ def validate_command(raw_arguments: Any) -> list[str]:
137
+ if not isinstance(raw_arguments, list) or not raw_arguments:
138
+ raise CommandRejected("argv must be a non-empty string array")
139
+ if len(raw_arguments) > 128:
140
+ raise CommandRejected("too many Browser Use arguments")
141
+ arguments: list[str] = []
142
+ for value in raw_arguments:
143
+ if not isinstance(value, str) or "\x00" in value or len(value) > 16_384:
144
+ raise CommandRejected("invalid Browser Use argument")
145
+ arguments.append(value)
146
+
147
+ for value in arguments:
148
+ if value in FORBIDDEN_GLOBAL_OPTIONS or any(
149
+ value.startswith(option + "=") for option in FORBIDDEN_GLOBAL_OPTIONS
150
+ ):
151
+ raise CommandRejected(f"Browser Use option {value!r} is disabled")
152
+
153
+ _session, command_index = _parse_global_options(arguments)
154
+ if (
155
+ command_index == len(arguments) - 1
156
+ and arguments[command_index] in {"-h", "--help"}
157
+ ):
158
+ return arguments
159
+ if command_index >= len(arguments):
160
+ raise CommandRejected("missing Browser Use command")
161
+ command = arguments[command_index]
162
+ if command in FORBIDDEN_COMMANDS:
163
+ raise CommandRejected(
164
+ f"Browser Use command {command!r} is disabled for browser-only references"
165
+ )
166
+ if command not in SAFE_COMMANDS:
167
+ raise CommandRejected(f"unsupported Browser Use command {command!r}")
168
+
169
+ if command == "open":
170
+ urls = [
171
+ value
172
+ for value in arguments[command_index + 1 :]
173
+ if "://" in value
174
+ ]
175
+ if len(urls) != 1:
176
+ raise CommandRejected("open requires exactly one absolute URL")
177
+ try:
178
+ requested_origin = _origin(urls[0])
179
+ except (TypeError, ValueError) as exc:
180
+ raise CommandRejected(str(exc)) from exc
181
+ if requested_origin not in allowed_origins():
182
+ raise CommandRejected("browser navigation target is outside task origins")
183
+
184
+ if command == "screenshot":
185
+ # The bundled Browser Use CLI is `screenshot [--full] [path]`; accept the spellings
186
+ # agents reach for (`--full-page`, `--path X`, `--path=X`) and hand the CLI its own.
187
+ path_values: list[str] = []
188
+ options: list[str] = []
189
+ tail = arguments[command_index + 1 :]
190
+ index = 0
191
+ while index < len(tail):
192
+ value = tail[index]
193
+ if value == "--path":
194
+ if index + 1 >= len(tail):
195
+ raise CommandRejected("screenshot --path requires a value")
196
+ path_values.append(tail[index + 1])
197
+ index += 2
198
+ continue
199
+ if value.startswith("--path="):
200
+ path_values.append(value.partition("=")[2])
201
+ index += 1
202
+ continue
203
+ if value in {"--full", "--full-page"}:
204
+ if "--full" not in options:
205
+ options.append("--full")
206
+ index += 1
207
+ continue
208
+ if value in {"--json", "-h", "--help"}:
209
+ options.append(value)
210
+ index += 1
211
+ continue
212
+ if value.startswith("-"):
213
+ raise CommandRejected(f"unsupported screenshot option {value!r}")
214
+ path_values.append(value)
215
+ index += 1
216
+ paths = [Path(value).resolve() for value in path_values]
217
+ if (
218
+ len(paths) != 1
219
+ or paths[0].parent != SHARED_ROOT
220
+ or re.fullmatch(r"screenshot-[0-9a-f]{32}\.png", paths[0].name) is None
221
+ ):
222
+ raise CommandRejected("screenshots must use one gateway-owned PNG path")
223
+ return arguments[: command_index + 1] + options + [str(paths[0])]
224
+
225
+ return arguments
226
+
227
+
228
+ _COMMAND_LOCK = threading.Lock()
229
+
230
+
231
+ def execute(arguments: list[str]) -> dict[str, Any]:
232
+ with _COMMAND_LOCK:
233
+ try:
234
+ completed = subprocess.run(
235
+ [REAL_BROWSER_USE, *arguments],
236
+ stdin=subprocess.DEVNULL,
237
+ stdout=subprocess.PIPE,
238
+ stderr=subprocess.PIPE,
239
+ timeout=COMMAND_TIMEOUT_SEC,
240
+ check=False,
241
+ )
242
+ except subprocess.TimeoutExpired as exc:
243
+ raise CommandRejected("Browser Use command exceeded 180 seconds") from exc
244
+ except OSError as exc:
245
+ raise CommandRejected(f"Browser Use runtime unavailable: {exc}") from exc
246
+ stdout = completed.stdout[:MAX_OUTPUT_BYTES]
247
+ stderr = completed.stderr[:MAX_OUTPUT_BYTES]
248
+ if len(completed.stdout) > MAX_OUTPUT_BYTES or len(completed.stderr) > MAX_OUTPUT_BYTES:
249
+ raise CommandRejected("Browser Use output exceeded the interactive limit")
250
+ return {
251
+ "exit_code": completed.returncode,
252
+ "stdout": stdout.decode("utf-8", errors="replace"),
253
+ "stderr": stderr.decode("utf-8", errors="replace"),
254
+ }
255
+
256
+
257
+ class Handler(BaseHTTPRequestHandler):
258
+ server_version = "WebsiteBenchBrowserGateway/1"
259
+
260
+ def log_message(self, _format: str, *_arguments: object) -> None:
261
+ return
262
+
263
+ def _send(self, status: int, value: dict[str, Any]) -> None:
264
+ body = json.dumps(value, separators=(",", ":")).encode("utf-8")
265
+ self.send_response(status)
266
+ self.send_header("Content-Type", "application/json")
267
+ self.send_header("Content-Length", str(len(body)))
268
+ self.send_header("Cache-Control", "no-store")
269
+ self.end_headers()
270
+ self.wfile.write(body)
271
+
272
+ def do_GET(self) -> None:
273
+ if self.path == "/healthz":
274
+ self._send(200, {"status": "ok"})
275
+ else:
276
+ self._send(404, {"error": "not_found"})
277
+
278
+ def do_POST(self) -> None:
279
+ if self.path != "/v1/command":
280
+ self._send(404, {"error": "not_found"})
281
+ return
282
+ try:
283
+ length = int(self.headers.get("Content-Length", ""))
284
+ if length <= 0 or length > MAX_REQUEST_BYTES:
285
+ raise CommandRejected("invalid request size")
286
+ payload = json.loads(self.rfile.read(length))
287
+ if not isinstance(payload, dict) or set(payload) != {"argv"}:
288
+ raise CommandRejected("request must contain only argv")
289
+ result = execute(validate_command(payload["argv"]))
290
+ except (CommandRejected, json.JSONDecodeError, UnicodeError, ValueError) as exc:
291
+ self._send(400, {"error": str(exc)})
292
+ return
293
+ self._send(200, result)
294
+
295
+
296
+ def main() -> None:
297
+ bind = os.environ.get("WEBSITEBENCH_BROWSER_GATEWAY_BIND", "0.0.0.0")
298
+ port = int(os.environ.get("WEBSITEBENCH_BROWSER_GATEWAY_PORT", "9224"))
299
+ server = ThreadingHTTPServer((bind, port), Handler)
300
+ server.daemon_threads = True
301
+ server.serve_forever()
302
+
303
+
304
+ if __name__ == "__main__":
305
+ main()
tasks/dooney-bourke/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/dooney-bourke/environment/candidate-abi/websitebench/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Public WebsiteBench candidate ABI tooling."""
tasks/dooney-bourke/environment/candidate-abi/websitebench/harbor/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Public Harbor candidate ABI tooling."""
tasks/dooney-bourke/environment/candidate-abi/websitebench/harbor/candidate_preflight.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agent-visible preflight for the public Harbor candidate runtime ABI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import socket
8
+ import sys
9
+ import tempfile
10
+ from pathlib import Path
11
+ from typing import Sequence
12
+
13
+ from .compiler import (
14
+ CompilerSandboxError,
15
+ RuntimeInfrastructureError,
16
+ compile_candidate,
17
+ validate_runtime_lifecycle,
18
+ )
19
+
20
+
21
+ FORBIDDEN_PRIVATE_ROOT = b"/app/repo"
22
+ NONPORTABLE_PYTHON_SHEBANG = b"#!/usr/bin/python3"
23
+ PORTABLE_PYTHON_SHEBANG = b"#!/usr/bin/env python3"
24
+
25
+
26
+ def _first_line(path: Path) -> bytes:
27
+ with path.open("rb") as handle:
28
+ return handle.readline(4097).rstrip(b"\r\n")
29
+
30
+
31
+ def _contains(path: Path, needle: bytes) -> bool:
32
+ overlap = max(0, len(needle) - 1)
33
+ previous = b""
34
+ with path.open("rb") as handle:
35
+ while chunk := handle.read(1024 * 1024):
36
+ value = previous + chunk
37
+ if needle in value:
38
+ return True
39
+ previous = value[-overlap:] if overlap else b""
40
+ return False
41
+
42
+
43
+ def validate_portable_candidate_paths(
44
+ compile_script: Path, executable: Path | None = None
45
+ ) -> None:
46
+ """Reject paths that work in the Agent checkout but not the private build."""
47
+
48
+ if _contains(compile_script, FORBIDDEN_PRIVATE_ROOT):
49
+ raise CompilerSandboxError(
50
+ "compile.sh hard-codes /app/repo; the verifier relocates the candidate "
51
+ "to a private build root. Use paths relative to the current directory "
52
+ "or $WEBSITEBENCH_BUILD_ROOT."
53
+ )
54
+ if _first_line(compile_script) == NONPORTABLE_PYTHON_SHEBANG:
55
+ raise CompilerSandboxError(
56
+ "compile.sh uses the non-portable #!/usr/bin/python3 shebang; use "
57
+ "#!/usr/bin/env python3."
58
+ )
59
+ if executable is None:
60
+ return
61
+ if _first_line(executable) == NONPORTABLE_PYTHON_SHEBANG:
62
+ raise CompilerSandboxError(
63
+ "executable uses the non-portable #!/usr/bin/python3 shebang; use "
64
+ "#!/usr/bin/env python3."
65
+ )
66
+ if _contains(executable, FORBIDDEN_PRIVATE_ROOT):
67
+ raise CompilerSandboxError(
68
+ "executable contains /app/repo; runtime files live in the private "
69
+ "build root. Resolve resources relative to executable, not /app/repo."
70
+ )
71
+
72
+
73
+ def _free_port() -> int:
74
+ with socket.socket() as probe:
75
+ probe.bind(("127.0.0.1", 0))
76
+ return int(probe.getsockname()[1])
77
+
78
+
79
+ def _build_log(private_root: Path) -> str:
80
+ path = private_root / "build.log"
81
+ try:
82
+ value = path.read_text(encoding="utf-8", errors="replace")
83
+ except OSError:
84
+ return ""
85
+ return value[-65536:]
86
+
87
+
88
+ def run_preflight(
89
+ candidate_root: Path,
90
+ *,
91
+ timeout: float = 300.0,
92
+ seed: int = 0,
93
+ timezone: str = "UTC",
94
+ ) -> dict[str, object]:
95
+ candidate = candidate_root.resolve(strict=True)
96
+ compile_script = candidate / "compile.sh"
97
+ if not compile_script.is_file():
98
+ raise CompilerSandboxError("candidate root does not contain compile.sh")
99
+ validate_portable_candidate_paths(compile_script)
100
+ with tempfile.TemporaryDirectory(prefix="websitebench-candidate-preflight-") as raw:
101
+ working_root = Path(raw)
102
+ private_root = working_root / "compiler"
103
+ try:
104
+ artifact = compile_candidate(
105
+ candidate,
106
+ private_root,
107
+ timeout=timeout,
108
+ seed=seed,
109
+ timezone=timezone,
110
+ )
111
+ except CompilerSandboxError as exc:
112
+ log = _build_log(private_root)
113
+ if log:
114
+ raise CompilerSandboxError(f"{exc}\ncompiler output:\n{log}") from exc
115
+ raise
116
+ validate_portable_candidate_paths(
117
+ artifact.build_root / "compile.sh", artifact.executable
118
+ )
119
+ lifecycle = validate_runtime_lifecycle(
120
+ artifact,
121
+ port=_free_port(),
122
+ seed=seed,
123
+ working_root=working_root / "runtime-preflight",
124
+ worker_access_roots=(working_root,),
125
+ timezone=timezone,
126
+ )
127
+ if lifecycle.get("valid") is not True:
128
+ failed = sorted(
129
+ key
130
+ for key, value in lifecycle.items()
131
+ if key not in {"deployment_abi", "tree_sha256", "valid"}
132
+ and value is not True
133
+ )
134
+ raise CompilerSandboxError(
135
+ "candidate runtime ABI lifecycle failed: " + ",".join(failed)
136
+ )
137
+ return {
138
+ "schema": "websitebench.harbor.candidate-preflight",
139
+ "status": "valid",
140
+ "candidate_root": str(candidate),
141
+ "tree_sha256": artifact.tree_sha256,
142
+ "lifecycle": lifecycle,
143
+ }
144
+
145
+
146
+ def _parser() -> argparse.ArgumentParser:
147
+ parser = argparse.ArgumentParser(
148
+ description="Check a candidate with the formal private compile/runtime ABI."
149
+ )
150
+ parser.add_argument("candidate_root", nargs="?", type=Path, default=Path.cwd())
151
+ parser.add_argument("--timeout", type=float, default=300.0)
152
+ parser.add_argument("--seed", type=int, default=0)
153
+ parser.add_argument("--timezone", default="UTC")
154
+ return parser
155
+
156
+
157
+ def main(arguments: Sequence[str] | None = None) -> int:
158
+ values = _parser().parse_args(arguments)
159
+ try:
160
+ report = run_preflight(
161
+ values.candidate_root,
162
+ timeout=values.timeout,
163
+ seed=values.seed,
164
+ timezone=values.timezone,
165
+ )
166
+ except (
167
+ CompilerSandboxError,
168
+ RuntimeInfrastructureError,
169
+ OSError,
170
+ ValueError,
171
+ ) as exc:
172
+ print(f"candidate ABI preflight failed: {exc}", file=sys.stderr)
173
+ return 2
174
+ print(json.dumps(report, indent=2, sort_keys=True))
175
+ return 0
176
+
177
+
178
+ if __name__ == "__main__":
179
+ raise SystemExit(main())
tasks/dooney-bourke/environment/candidate-abi/websitebench/harbor/compiler.py ADDED
@@ -0,0 +1,1128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Quarantined compiler and runtime for the Harbor compile-executable ABI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import errno
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import shutil
11
+ import signal
12
+ import stat
13
+ import subprocess
14
+ import time
15
+ import urllib.error
16
+ import urllib.request
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Any, Iterable, Mapping, Sequence
20
+
21
+ try: # pragma: no cover - unavailable on Windows authoring hosts
22
+ import resource
23
+ except ImportError: # pragma: no cover
24
+ resource = None # type: ignore[assignment]
25
+
26
+ from . import sandbox
27
+
28
+
29
+ DEPLOYMENT_ABI = "websitebench.harbor.compile-executable"
30
+ COMPILE_ENTRYPOINT = "compile.sh"
31
+ EXECUTABLE_ENTRYPOINT = "executable"
32
+ HEALTH_PATH = "/healthz"
33
+ # The contract moved to /healthz (ADR-0010) because every reference site and
34
+ # every manifest already served that path, while nothing ever implemented the
35
+ # benchmark-private one. Candidates built against the old instruction text keep
36
+ # working: probing falls back to these.
37
+ LEGACY_HEALTH_PATHS = ("/__websitebench/health",)
38
+ HEALTH_PATHS = (HEALTH_PATH, *LEGACY_HEALTH_PATHS)
39
+ HEALTH_BODY = {"status": "ok"}
40
+ RUNTIME_PROCESS_MODEL = {
41
+ "kind": "single-process",
42
+ "process_fork": False,
43
+ "threads": True,
44
+ "launcher": "direct-exec-or-shell-builtins-only",
45
+ }
46
+ DEFAULT_COMPILE_TIMEOUT = 900.0
47
+ MAX_LOG_BYTES = 256 * 1024 * 1024
48
+ WORKER_OS_UID = 10001
49
+ WORKER_OS_GID = 10001
50
+ _RUNTIME_PRIVATE_DIRECTORIES = (
51
+ "home",
52
+ "tmp",
53
+ "xdg-cache",
54
+ "xdg-config",
55
+ "xdg-data",
56
+ )
57
+ CANDIDATE_MAIL_ENVIRONMENT = frozenset(
58
+ {
59
+ "WEBSITEBENCH_MAIL_API_URL",
60
+ "WEBSITEBENCH_MAIL_API_TOKEN",
61
+ "WEBSITEBENCH_MAIL_FROM",
62
+ "WEBSITEBENCH_SMTP_HOST",
63
+ "WEBSITEBENCH_SMTP_PORT",
64
+ "WEBSITEBENCH_SMTP_FROM",
65
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL",
66
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN",
67
+ }
68
+ )
69
+ CANDIDATE_EVALUATOR_ENVIRONMENT = frozenset(
70
+ {
71
+ "WEBSITEBENCH_VERIFIER_MODE",
72
+ "WEBSITEBENCH_VERIFIER_ALEX_SECRET",
73
+ "WEBSITEBENCH_VERIFIER_JORDAN_SECRET",
74
+ "WEBSITEBENCH_EVALUATOR_PRIMARY_SECRET",
75
+ "WEBSITEBENCH_EVALUATOR_SECONDARY_SECRET",
76
+ }
77
+ )
78
+
79
+
80
+ class CompilerSandboxError(RuntimeError):
81
+ """The candidate artifact, compiler, or compiled runtime broke the ABI."""
82
+
83
+
84
+ class RuntimeInfrastructureError(RuntimeError):
85
+ """The trusted runtime supervisor could not establish its worker boundary."""
86
+
87
+
88
+ def _runtime_worker_credentials() -> tuple[int, int] | None:
89
+ """Return the fixed worker identity only for a privileged supervisor."""
90
+
91
+ if os.geteuid() == 0:
92
+ return WORKER_OS_UID, WORKER_OS_GID
93
+ return None
94
+
95
+
96
+ def _worker_execute_bit(metadata: os.stat_result, uid: int, gid: int) -> int:
97
+ if metadata.st_uid == uid:
98
+ return stat.S_IXUSR
99
+ if metadata.st_gid == gid:
100
+ return stat.S_IXGRP
101
+ return stat.S_IXOTH
102
+
103
+
104
+ def _worker_access_root(path: Path, roots: Sequence[Path]) -> Path:
105
+ matches = [root for root in roots if path == root or root in path.parents]
106
+ if not matches:
107
+ raise OSError(
108
+ errno.EPERM,
109
+ f"worker path is outside caller-declared access roots: {path}",
110
+ )
111
+ return max(matches, key=lambda root: len(root.parts))
112
+
113
+
114
+ def _make_worker_ancestors_traversable(
115
+ path: Path,
116
+ uid: int,
117
+ gid: int,
118
+ *,
119
+ access_root: Path,
120
+ ) -> None:
121
+ """Grant traverse only within one exact caller-declared task root."""
122
+
123
+ for boundary_parent in access_root.parents:
124
+ metadata = boundary_parent.stat()
125
+ if not stat.S_ISDIR(metadata.st_mode) or not (
126
+ stat.S_IMODE(metadata.st_mode)
127
+ & _worker_execute_bit(metadata, uid, gid)
128
+ ):
129
+ raise OSError(
130
+ errno.EACCES,
131
+ f"worker access-root boundary is not traversable: {boundary_parent}",
132
+ )
133
+
134
+ ancestors = [path, *path.parents]
135
+ try:
136
+ boundary_index = ancestors.index(access_root)
137
+ except ValueError as exc: # guarded by _worker_access_root
138
+ raise OSError(errno.EPERM, "worker access-root containment changed") from exc
139
+ for ancestor in ancestors[: boundary_index + 1]:
140
+ metadata = ancestor.stat()
141
+ if not stat.S_ISDIR(metadata.st_mode):
142
+ raise OSError(errno.ENOTDIR, f"worker ancestor is not a directory: {ancestor}")
143
+ mode = stat.S_IMODE(metadata.st_mode)
144
+ execute_bit = _worker_execute_bit(metadata, uid, gid)
145
+ if not mode & execute_bit:
146
+ ancestor.chmod(mode | execute_bit)
147
+
148
+
149
+ def _prepare_runtime_directories(
150
+ build: Path,
151
+ data: Path,
152
+ credentials: tuple[int, int] | None,
153
+ *,
154
+ worker_access_roots: Sequence[Path],
155
+ ) -> None:
156
+ """Create private runtime state and make it usable by the worker identity."""
157
+
158
+ data.mkdir(parents=True, exist_ok=True, mode=0o700)
159
+ private_directories = [data]
160
+ for name in _RUNTIME_PRIVATE_DIRECTORIES:
161
+ directory = data / name
162
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
163
+ private_directories.append(directory)
164
+
165
+ for directory in private_directories:
166
+ metadata = directory.lstat()
167
+ if not stat.S_ISDIR(metadata.st_mode):
168
+ raise OSError(
169
+ errno.ENOTDIR,
170
+ f"runtime private path is not a directory: {directory}",
171
+ )
172
+
173
+ if credentials is not None:
174
+ uid, gid = credentials
175
+ roots: list[Path] = []
176
+ for raw_root in worker_access_roots:
177
+ absolute = Path(raw_root).absolute()
178
+ root = absolute.resolve(strict=True)
179
+ metadata = absolute.lstat()
180
+ if (
181
+ root == Path(root.anchor)
182
+ or root != absolute
183
+ or not stat.S_ISDIR(metadata.st_mode)
184
+ ):
185
+ raise OSError(errno.EPERM, f"invalid worker access root: {raw_root}")
186
+ if root not in roots:
187
+ roots.append(root)
188
+ if not roots:
189
+ raise OSError(errno.EPERM, "worker access roots were not declared")
190
+ for directory in private_directories:
191
+ os.chown(directory, uid, gid, follow_symlinks=False)
192
+ for target in (build, data):
193
+ access_root = _worker_access_root(target, roots)
194
+ _make_worker_ancestors_traversable(
195
+ target,
196
+ uid,
197
+ gid,
198
+ access_root=access_root,
199
+ )
200
+
201
+ for directory in private_directories:
202
+ directory.chmod(0o700)
203
+
204
+
205
+ def _proc_status_identity(path: Path) -> tuple[tuple[int, ...], tuple[int, ...], int]:
206
+ """Read real/effective/saved/fs IDs and PPid from a proc status file."""
207
+
208
+ fields: dict[str, tuple[int, ...]] = {}
209
+ try:
210
+ for line in path.read_text(encoding="ascii").splitlines():
211
+ name, separator, value = line.partition(":")
212
+ if separator and name in {"Uid", "Gid", "PPid"}:
213
+ fields[name] = tuple(int(item) for item in value.split())
214
+ except (OSError, UnicodeError, ValueError) as exc:
215
+ raise OSError(errno.EIO, f"process identity is unreadable: {path}") from exc
216
+ if len(fields.get("Uid", ())) != 4 or len(fields.get("Gid", ())) != 4:
217
+ raise OSError(errno.EIO, f"process identity is incomplete: {path}")
218
+ if len(fields.get("PPid", ())) != 1:
219
+ raise OSError(errno.EIO, f"process parent identity is incomplete: {path}")
220
+ return fields["Uid"], fields["Gid"], fields["PPid"][0]
221
+
222
+
223
+ @dataclass(frozen=True)
224
+ class CompiledArtifact:
225
+ source_root: Path
226
+ build_root: Path
227
+ executable: Path
228
+ tree_sha256: str
229
+ build_log: Path
230
+
231
+
232
+ def _safe_name(name: str) -> bool:
233
+ return (
234
+ bool(name)
235
+ and name not in {".", ".."}
236
+ and "/" not in name
237
+ and "\x00" not in name
238
+ )
239
+
240
+
241
+ def _tree_entries(root: Path) -> Iterable[tuple[Path, os.stat_result]]:
242
+ """Walk with lstat only; never follow candidate-authored links."""
243
+
244
+ stack = [root]
245
+ while stack:
246
+ directory = stack.pop()
247
+ with os.scandir(directory) as iterator:
248
+ entries = sorted(iterator, key=lambda item: os.fsencode(item.name))
249
+ subdirectories: list[Path] = []
250
+ for entry in entries:
251
+ if not _safe_name(entry.name):
252
+ raise CompilerSandboxError(f"unsafe artifact name: {entry.name!r}")
253
+ path = Path(entry.path)
254
+ metadata = entry.stat(follow_symlinks=False)
255
+ yield path, metadata
256
+ if stat.S_ISDIR(metadata.st_mode):
257
+ subdirectories.append(path)
258
+ stack.extend(reversed(subdirectories))
259
+
260
+
261
+ def validate_artifact_tree(root: Path | str) -> list[Path]:
262
+ """Reject links, special files, multiple links, and paths outside ``root``."""
263
+
264
+ resolved = Path(root).resolve(strict=True)
265
+ root_stat = resolved.lstat()
266
+ if not stat.S_ISDIR(root_stat.st_mode):
267
+ raise CompilerSandboxError("candidate artifact root must be a directory")
268
+ files: list[Path] = []
269
+ for path, metadata in _tree_entries(resolved):
270
+ try:
271
+ relative = path.relative_to(resolved)
272
+ except ValueError as exc: # defensive: scandir paths must remain below root
273
+ raise CompilerSandboxError(f"artifact path escapes root: {path}") from exc
274
+ if not relative.parts or any(
275
+ part in {"", ".", ".."} for part in relative.parts
276
+ ):
277
+ raise CompilerSandboxError(f"unsafe artifact path: {relative}")
278
+ if stat.S_ISLNK(metadata.st_mode):
279
+ raise CompilerSandboxError(f"symbolic links are forbidden: {relative}")
280
+ if stat.S_ISREG(metadata.st_mode):
281
+ if metadata.st_nlink != 1:
282
+ raise CompilerSandboxError(
283
+ f"hard-linked files are forbidden: {relative}"
284
+ )
285
+ files.append(path)
286
+ elif not stat.S_ISDIR(metadata.st_mode):
287
+ raise CompilerSandboxError(f"special files are forbidden: {relative}")
288
+ return files
289
+
290
+
291
+ def quarantine_artifact(source: Path | str, destination: Path | str) -> Path:
292
+ """Copy `/app/repo` into a fresh private build root without link semantics."""
293
+
294
+ source_root = Path(source).resolve(strict=True)
295
+ destination_root = Path(destination).resolve()
296
+ validate_artifact_tree(source_root)
297
+ if destination_root.exists():
298
+ raise FileExistsError(f"private build root already exists: {destination_root}")
299
+ destination_root.mkdir(parents=True, mode=0o700)
300
+ try:
301
+ for path, metadata in _tree_entries(source_root):
302
+ relative = path.relative_to(source_root)
303
+ target = destination_root / relative
304
+ if stat.S_ISDIR(metadata.st_mode):
305
+ target.mkdir(mode=stat.S_IMODE(metadata.st_mode) | 0o700)
306
+ else:
307
+ target.parent.mkdir(parents=True, exist_ok=True)
308
+ with (
309
+ path.open("rb") as source_handle,
310
+ target.open("xb") as target_handle,
311
+ ):
312
+ shutil.copyfileobj(source_handle, target_handle, length=1024 * 1024)
313
+ target_handle.flush()
314
+ os.fsync(target_handle.fileno())
315
+ target.chmod(stat.S_IMODE(metadata.st_mode))
316
+ validate_artifact_tree(destination_root)
317
+ except BaseException:
318
+ shutil.rmtree(destination_root, ignore_errors=True)
319
+ raise
320
+ return destination_root
321
+
322
+
323
+ def _compile_environment(
324
+ build_root: Path, data_root: Path, seed: int, timezone: str
325
+ ) -> dict[str, str]:
326
+ # This is an allowlist, not a copy of the verifier environment. In
327
+ # particular no provider, cloud, source, or hidden-fixture credential can
328
+ # reach compile.sh.
329
+ return {
330
+ "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
331
+ "LANG": "C.UTF-8",
332
+ "LC_ALL": "C.UTF-8",
333
+ "HOST": "127.0.0.1",
334
+ "PORT": "3000",
335
+ "DATA_DIR": str(data_root),
336
+ "SEED": str(seed),
337
+ "TZ": timezone,
338
+ "HOME": str(data_root / "home"),
339
+ "TMPDIR": str(data_root / "tmp"),
340
+ "XDG_CACHE_HOME": str(data_root / "xdg-cache"),
341
+ "XDG_CONFIG_HOME": str(data_root / "xdg-config"),
342
+ "XDG_DATA_HOME": str(data_root / "xdg-data"),
343
+ "WEBSITEBENCH_DEPLOYMENT_ABI": DEPLOYMENT_ABI,
344
+ "WEBSITEBENCH_BUILD_ROOT": str(build_root),
345
+ }
346
+
347
+
348
+ def _install_socket_deny_filter() -> None:
349
+ """Deny sockets and process-group escape while allowing compiler children."""
350
+
351
+ (
352
+ audit_arch,
353
+ socket_syscall,
354
+ _fcntl_syscall,
355
+ seccomp_syscall,
356
+ _denied,
357
+ ) = sandbox._architecture()
358
+ escape_syscalls = (109, 112) if audit_arch == 0xC000003E else (154, 157)
359
+ instructions = [
360
+ (sandbox.BPF_LD_W_ABS, 0, 0, 4),
361
+ (sandbox.BPF_JMP_JEQ_K, 1, 0, audit_arch),
362
+ (sandbox.BPF_RET_K, 0, 0, sandbox.SECCOMP_RET_KILL_PROCESS),
363
+ (sandbox.BPF_LD_W_ABS, 0, 0, 0),
364
+ (sandbox.BPF_JMP_JEQ_K, 0, 1, socket_syscall),
365
+ (
366
+ sandbox.BPF_RET_K,
367
+ 0,
368
+ 0,
369
+ sandbox.SECCOMP_RET_ERRNO | errno.EPERM,
370
+ ),
371
+ ]
372
+ for syscall_number in escape_syscalls:
373
+ instructions.extend(
374
+ [
375
+ (sandbox.BPF_JMP_JEQ_K, 0, 1, syscall_number),
376
+ (
377
+ sandbox.BPF_RET_K,
378
+ 0,
379
+ 0,
380
+ sandbox.SECCOMP_RET_ERRNO | errno.EPERM,
381
+ ),
382
+ ]
383
+ )
384
+ instructions.append((sandbox.BPF_RET_K, 0, 0, sandbox.SECCOMP_RET_ALLOW))
385
+ filters = (sandbox._SockFilter * len(instructions))(
386
+ *(sandbox._SockFilter(*instruction) for instruction in instructions)
387
+ )
388
+ program = sandbox._SockFprog(len(instructions), filters)
389
+ libc = ctypes.CDLL(None, use_errno=True)
390
+ if libc.prctl(sandbox.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
391
+ raise OSError(ctypes.get_errno(), "cannot set compiler no_new_privs")
392
+ result = int(
393
+ libc.syscall(
394
+ seccomp_syscall,
395
+ sandbox.SECCOMP_SET_MODE_FILTER,
396
+ 0,
397
+ ctypes.byref(program),
398
+ )
399
+ )
400
+ if result != 0:
401
+ raise OSError(ctypes.get_errno(), "cannot install compiler network filter")
402
+
403
+
404
+ def _compiler_preexec(
405
+ build_root: Path, data_root: Path, memory_mb: int, cpu_seconds: int
406
+ ) -> None:
407
+ os.umask(0o077)
408
+ if resource is not None:
409
+ memory = memory_mb * 1024 * 1024
410
+ resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
411
+ resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds + 5))
412
+ resource.setrlimit(resource.RLIMIT_NOFILE, (1024, 1024))
413
+ resource.setrlimit(resource.RLIMIT_FSIZE, (MAX_LOG_BYTES, MAX_LOG_BYTES))
414
+ # Root and data are deliberately the same writable private tree for
415
+ # compilation. Landlock grants system toolchains read/execute access and
416
+ # grants no TCP bind/connect ports. It also withholds shared filesystem
417
+ # socket locations such as /run and /tmp.
418
+ sandbox._landlock(build_root, data_root, 1, set())
419
+ _install_socket_deny_filter()
420
+
421
+
422
+ def _process_group_alive(group: int) -> bool:
423
+ proc = Path("/proc")
424
+ if proc.is_dir():
425
+ for status_path in proc.glob("[0-9]*/stat"):
426
+ try:
427
+ raw = status_path.read_text(encoding="ascii")
428
+ fields = raw[raw.rfind(")") + 2 :].split()
429
+ if int(fields[2]) == group and fields[0] != "Z":
430
+ return True
431
+ except (OSError, UnicodeError, ValueError, IndexError):
432
+ continue
433
+ return False
434
+ try:
435
+ os.killpg(group, 0)
436
+ except (ProcessLookupError, PermissionError):
437
+ return False
438
+ return True
439
+
440
+
441
+ def _terminate_group(
442
+ process: subprocess.Popen[Any],
443
+ timeout: float = 10.0,
444
+ *,
445
+ accept_forced: bool = False,
446
+ ) -> bool:
447
+ group = process.pid
448
+ if process.poll() is None:
449
+ try:
450
+ os.killpg(group, signal.SIGTERM)
451
+ except ProcessLookupError:
452
+ pass
453
+ deadline = time.monotonic() + timeout
454
+ while _process_group_alive(group) and time.monotonic() < deadline:
455
+ time.sleep(0.02)
456
+ graceful = not _process_group_alive(group)
457
+ if not graceful:
458
+ try:
459
+ os.killpg(group, signal.SIGKILL)
460
+ except ProcessLookupError:
461
+ pass
462
+ try:
463
+ process.wait(timeout=5)
464
+ except subprocess.TimeoutExpired:
465
+ return False
466
+ terminated = not _process_group_alive(group)
467
+ return graceful or (accept_forced and terminated)
468
+
469
+
470
+ def _stop_controlled_group(
471
+ process: subprocess.Popen[Any],
472
+ control_fd: int,
473
+ timeout: float = 10.0,
474
+ *,
475
+ accept_forced: bool = False,
476
+ ) -> bool:
477
+ """Ask the trusted sandbox launcher to stop its tracee, then reap the group."""
478
+
479
+ if process.poll() is None:
480
+ try:
481
+ os.write(control_fd, b"T")
482
+ except OSError:
483
+ pass
484
+ deadline = time.monotonic() + timeout
485
+ while _process_group_alive(process.pid) and time.monotonic() < deadline:
486
+ time.sleep(0.02)
487
+ graceful = not _process_group_alive(process.pid)
488
+ if not graceful:
489
+ try:
490
+ os.write(control_fd, b"K")
491
+ except OSError:
492
+ pass
493
+ time.sleep(0.1)
494
+ if _process_group_alive(process.pid):
495
+ try:
496
+ os.killpg(process.pid, signal.SIGKILL)
497
+ except ProcessLookupError:
498
+ pass
499
+ try:
500
+ process.wait(timeout=5)
501
+ except subprocess.TimeoutExpired:
502
+ return False
503
+ terminated = not _process_group_alive(process.pid)
504
+ return graceful or (accept_forced and terminated)
505
+
506
+
507
+ def _processes_referencing(root: Path, *, exclude: Sequence[int] = ()) -> list[int]:
508
+ references: list[int] = []
509
+ root_text = str(root.resolve())
510
+ excluded = set(exclude)
511
+ for process in Path("/proc").glob("[0-9]*"):
512
+ try:
513
+ pid = int(process.name)
514
+ if pid in excluded:
515
+ continue
516
+ cwd = os.readlink(process / "cwd")
517
+ command = (
518
+ (process / "cmdline")
519
+ .read_bytes()
520
+ .replace(b"\x00", b" ")
521
+ .decode("utf-8", errors="replace")
522
+ )
523
+ except (OSError, ValueError):
524
+ continue
525
+ if (
526
+ cwd == root_text
527
+ or cwd.startswith(root_text + os.sep)
528
+ or root_text in command
529
+ ):
530
+ references.append(pid)
531
+ return sorted(references)
532
+
533
+
534
+ def tree_digest(root: Path | str) -> str:
535
+ resolved = Path(root).resolve(strict=True)
536
+ validate_artifact_tree(resolved)
537
+ digest = hashlib.sha256()
538
+ for path, metadata in _tree_entries(resolved):
539
+ relative = path.relative_to(resolved).as_posix().encode("utf-8")
540
+ kind = b"d" if stat.S_ISDIR(metadata.st_mode) else b"f"
541
+ digest.update(kind + b"\0" + relative + b"\0")
542
+ digest.update(f"{stat.S_IMODE(metadata.st_mode):04o}".encode("ascii") + b"\0")
543
+ if kind == b"f":
544
+ with path.open("rb") as handle:
545
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
546
+ digest.update(chunk)
547
+ digest.update(b"\0")
548
+ return digest.hexdigest()
549
+
550
+
551
+ def freeze_build_tree(root: Path | str) -> str:
552
+ resolved = Path(root).resolve(strict=True)
553
+ validate_artifact_tree(resolved)
554
+ entries = list(_tree_entries(resolved))
555
+ for path, metadata in entries:
556
+ if stat.S_ISREG(metadata.st_mode):
557
+ executable = bool(stat.S_IMODE(metadata.st_mode) & 0o111)
558
+ path.chmod(0o555 if executable else 0o444)
559
+ for path, metadata in reversed(entries):
560
+ if stat.S_ISDIR(metadata.st_mode):
561
+ path.chmod(0o555)
562
+ resolved.chmod(0o555)
563
+ return tree_digest(resolved)
564
+
565
+
566
+ def compile_candidate(
567
+ source_root: Path | str,
568
+ private_root: Path | str,
569
+ *,
570
+ timeout: float = DEFAULT_COMPILE_TIMEOUT,
571
+ seed: int = 0,
572
+ timezone: str = "UTC",
573
+ memory_mb: int = 8192,
574
+ ) -> CompiledArtifact:
575
+ """Quarantine, compile offline once, validate, freeze, and hash the build."""
576
+
577
+ source = Path(source_root).resolve(strict=True)
578
+ private = Path(private_root).resolve()
579
+ if private.exists():
580
+ raise FileExistsError(f"private compiler root already exists: {private}")
581
+ private.mkdir(parents=True, mode=0o700)
582
+ build = private / "build"
583
+ log = private / "build.log"
584
+ quarantine_artifact(source, build)
585
+ data = build / ".websitebench-compile-data"
586
+ if data.exists():
587
+ if data.is_dir() and not data.is_symlink():
588
+ shutil.rmtree(data)
589
+ else:
590
+ data.unlink()
591
+ data.mkdir(mode=0o700)
592
+ for name in ("home", "tmp", "xdg-cache", "xdg-config", "xdg-data"):
593
+ (data / name).mkdir(mode=0o700)
594
+ compile_script = build / COMPILE_ENTRYPOINT
595
+ if not compile_script.is_file() or compile_script.is_symlink():
596
+ raise CompilerSandboxError("candidate root must contain regular compile.sh")
597
+ if compile_script.stat().st_nlink != 1 or not os.access(compile_script, os.X_OK):
598
+ raise CompilerSandboxError("compile.sh must be an independent executable file")
599
+
600
+ # A submitted executable is never trusted as compiler output.
601
+ preexisting = build / EXECUTABLE_ENTRYPOINT
602
+ if preexisting.exists():
603
+ if preexisting.is_dir():
604
+ shutil.rmtree(preexisting)
605
+ else:
606
+ preexisting.unlink()
607
+
608
+ environment = _compile_environment(build, data, seed, timezone)
609
+ with log.open("wb") as log_handle:
610
+ try:
611
+ process = subprocess.Popen(
612
+ [str(compile_script)],
613
+ cwd=build,
614
+ env=environment,
615
+ stdin=subprocess.DEVNULL,
616
+ stdout=log_handle,
617
+ stderr=subprocess.STDOUT,
618
+ start_new_session=True,
619
+ preexec_fn=lambda: _compiler_preexec(
620
+ build, build, memory_mb, max(1, int(timeout))
621
+ ),
622
+ )
623
+ try:
624
+ return_code = process.wait(timeout=timeout)
625
+ except subprocess.TimeoutExpired as exc:
626
+ _terminate_group(process)
627
+ raise CompilerSandboxError(
628
+ f"compile.sh exceeded {timeout:g} seconds"
629
+ ) from exc
630
+ if _process_group_alive(process.pid):
631
+ _terminate_group(process)
632
+ raise CompilerSandboxError(
633
+ "compile.sh left a child process or listener alive"
634
+ )
635
+ if return_code != 0:
636
+ raise CompilerSandboxError(f"compile.sh exited {return_code}")
637
+ finally:
638
+ log_handle.flush()
639
+ os.fsync(log_handle.fileno())
640
+
641
+ leaked = _processes_referencing(build, exclude=(os.getpid(),))
642
+ if leaked:
643
+ for pid in leaked:
644
+ try:
645
+ os.kill(pid, signal.SIGKILL)
646
+ except ProcessLookupError:
647
+ pass
648
+ raise CompilerSandboxError(f"compiler left detached processes: {leaked}")
649
+ if log.stat().st_size > MAX_LOG_BYTES:
650
+ raise CompilerSandboxError("compiler log exceeded 256 MiB")
651
+
652
+ shutil.rmtree(data)
653
+ validate_artifact_tree(build)
654
+ executable = build / EXECUTABLE_ENTRYPOINT
655
+ try:
656
+ metadata = executable.lstat()
657
+ except OSError as exc:
658
+ raise CompilerSandboxError(
659
+ "compile.sh did not produce root executable"
660
+ ) from exc
661
+ if (
662
+ not stat.S_ISREG(metadata.st_mode)
663
+ or metadata.st_nlink != 1
664
+ or not stat.S_IMODE(metadata.st_mode) & 0o111
665
+ or executable.resolve() != executable
666
+ ):
667
+ raise CompilerSandboxError(
668
+ "executable must be an independent regular executable at the build root"
669
+ )
670
+ digest = freeze_build_tree(build)
671
+ return CompiledArtifact(
672
+ source_root=source,
673
+ build_root=build,
674
+ executable=executable,
675
+ tree_sha256=digest,
676
+ build_log=log,
677
+ )
678
+
679
+
680
+ @dataclass
681
+ class ExecutableRuntime:
682
+ """One foreground compiled candidate bound to one isolated DATA_DIR."""
683
+
684
+ build_root: Path
685
+ data_dir: Path
686
+ port: int
687
+ seed: int
688
+ timezone: str = "UTC"
689
+ log_path: Path | None = None
690
+ # RLIMIT_AS covers reserved virtual address space, not resident memory.
691
+ # Current Node/V8 runtimes reserve more than the 8192 MiB Harbor RSS
692
+ # budget before serving any request; keep the evaluator's cgroup budget
693
+ # authoritative while leaving enough address space for that reservation.
694
+ memory_mb: int = 16384
695
+ expected_tree_sha256: str | None = None
696
+ mailbox_environment: Mapping[str, str] | None = None
697
+ mailbox_connect_ports: frozenset[int] = frozenset()
698
+ evaluator_environment: Mapping[str, str] | None = None
699
+ worker_access_roots: tuple[Path, ...] = ()
700
+ process: subprocess.Popen[bytes] | None = None
701
+ _log_handle: Any | None = None
702
+ _cleanup_complete: bool = True
703
+ _control_write_fd: int | None = None
704
+ _broker_tid: int | None = None
705
+ _candidate_pid: int | None = None
706
+
707
+ def _environment(self) -> dict[str, str]:
708
+ data = self.data_dir.resolve()
709
+ environment = {
710
+ "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
711
+ "LANG": "C.UTF-8",
712
+ "LC_ALL": "C.UTF-8",
713
+ "HOST": "127.0.0.1",
714
+ "PORT": str(self.port),
715
+ "DATA_DIR": str(data),
716
+ "SEED": str(self.seed),
717
+ "TZ": self.timezone,
718
+ "HOME": str(data / "home"),
719
+ "TMPDIR": str(data / "tmp"),
720
+ "XDG_CACHE_HOME": str(data / "xdg-cache"),
721
+ "XDG_CONFIG_HOME": str(data / "xdg-config"),
722
+ "XDG_DATA_HOME": str(data / "xdg-data"),
723
+ "WEBSITEBENCH_DEPLOYMENT_ABI": DEPLOYMENT_ABI,
724
+ }
725
+ if self.mailbox_environment is not None:
726
+ unknown = set(self.mailbox_environment) - CANDIDATE_MAIL_ENVIRONMENT
727
+ if unknown:
728
+ raise CompilerSandboxError(
729
+ f"candidate mailbox environment has unknown names: {sorted(unknown)}"
730
+ )
731
+ environment.update(
732
+ {name: str(value) for name, value in self.mailbox_environment.items()}
733
+ )
734
+ if self.evaluator_environment is not None:
735
+ unknown = set(self.evaluator_environment) - CANDIDATE_EVALUATOR_ENVIRONMENT
736
+ if unknown:
737
+ raise CompilerSandboxError(
738
+ "candidate evaluator environment has unknown names: "
739
+ f"{sorted(unknown)}"
740
+ )
741
+ if any(not str(value) for value in self.evaluator_environment.values()):
742
+ raise CompilerSandboxError(
743
+ "candidate evaluator environment values must be non-empty"
744
+ )
745
+ environment.update(
746
+ {name: str(value) for name, value in self.evaluator_environment.items()}
747
+ )
748
+ return environment
749
+
750
+ def _sandbox_command(
751
+ self,
752
+ *,
753
+ build: Path,
754
+ executable: Path,
755
+ control_read_fd: int,
756
+ broker_write_fd: int,
757
+ credentials: tuple[int, int] | None,
758
+ ) -> list[str]:
759
+ sandbox_path = Path(sandbox.__file__).resolve(strict=True)
760
+ command = [
761
+ os.sys.executable,
762
+ str(sandbox_path),
763
+ "--root",
764
+ str(build),
765
+ "--data",
766
+ str(self.data_dir.resolve()),
767
+ "--bind-port",
768
+ str(self.port),
769
+ "--connect-port",
770
+ str(self.port),
771
+ ]
772
+ for connect_port in sorted(self.mailbox_connect_ports):
773
+ command.extend(("--connect-port", str(connect_port)))
774
+ if credentials is not None:
775
+ uid, gid = credentials
776
+ command.extend(("--uid", str(uid), "--gid", str(gid)))
777
+ command.extend(
778
+ (
779
+ "--file-size-limit-bytes",
780
+ str(MAX_LOG_BYTES),
781
+ "--broker-tid-fd",
782
+ str(broker_write_fd),
783
+ "--control-fd",
784
+ str(control_read_fd),
785
+ "--",
786
+ str(executable),
787
+ )
788
+ )
789
+ return command
790
+
791
+ def _attest_worker_identity(
792
+ self,
793
+ *,
794
+ expected_uid: int,
795
+ expected_gid: int,
796
+ ) -> None:
797
+ if self.process is None or self._broker_tid is None or self._candidate_pid is None:
798
+ raise OSError(errno.EIO, "sandbox identity proof is incomplete")
799
+ launcher_pid = self.process.pid
800
+ broker_status = Path(
801
+ f"/proc/{launcher_pid}/task/{self._broker_tid}/status"
802
+ )
803
+ candidate_status = Path(f"/proc/{self._candidate_pid}/status")
804
+ broker_uid, broker_gid, _broker_parent = _proc_status_identity(broker_status)
805
+ candidate_uid, candidate_gid, candidate_parent = _proc_status_identity(
806
+ candidate_status
807
+ )
808
+ expected_uids = (expected_uid,) * 4
809
+ expected_gids = (expected_gid,) * 4
810
+ if (
811
+ broker_uid != expected_uids
812
+ or broker_gid != expected_gids
813
+ or candidate_uid != expected_uids
814
+ or candidate_gid != expected_gids
815
+ or candidate_parent != launcher_pid
816
+ ):
817
+ raise OSError(
818
+ errno.EPERM,
819
+ "sandbox broker or candidate retained an unexpected OS identity",
820
+ )
821
+
822
+ def _preexec(self) -> None:
823
+ os.umask(0o077)
824
+ if resource is not None:
825
+ memory = self.memory_mb * 1024 * 1024
826
+ resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
827
+ resource.setrlimit(resource.RLIMIT_NOFILE, (1024, 1024))
828
+ resource.setrlimit(resource.RLIMIT_FSIZE, (MAX_LOG_BYTES, MAX_LOG_BYTES))
829
+
830
+ def start(self) -> None:
831
+ if not self._cleanup_complete:
832
+ raise CompilerSandboxError(
833
+ "runtime cleanup is incomplete; restart forbidden"
834
+ )
835
+ if self.process is not None and self.process.poll() is None:
836
+ raise CompilerSandboxError("compiled runtime is already running")
837
+ for connect_port in self.mailbox_connect_ports:
838
+ if not 1 <= connect_port <= 65535 or connect_port == self.port:
839
+ raise CompilerSandboxError("candidate mailbox connect port is invalid")
840
+ build = self.build_root.resolve(strict=True)
841
+ current_digest = tree_digest(build)
842
+ if current_digest == "": # pragma: no cover - digest is never empty
843
+ raise CompilerSandboxError("compiled build hash is unavailable")
844
+ if (
845
+ self.expected_tree_sha256 is not None
846
+ and current_digest != self.expected_tree_sha256
847
+ ):
848
+ raise CompilerSandboxError("compiled build tree changed after freezing")
849
+ executable = build / EXECUTABLE_ENTRYPOINT
850
+ metadata = executable.lstat()
851
+ if not stat.S_ISREG(metadata.st_mode) or not metadata.st_mode & 0o111:
852
+ raise CompilerSandboxError("compiled executable contract changed")
853
+ credentials = _runtime_worker_credentials()
854
+ try:
855
+ _prepare_runtime_directories(
856
+ build,
857
+ self.data_dir.resolve(),
858
+ credentials,
859
+ worker_access_roots=self.worker_access_roots,
860
+ )
861
+ except OSError as exc:
862
+ raise RuntimeInfrastructureError(
863
+ "compiled runtime worker directories could not be prepared"
864
+ ) from exc
865
+ if self.log_path is not None:
866
+ log = self.log_path.resolve()
867
+ data = self.data_dir.resolve()
868
+ if data not in log.parents:
869
+ raise CompilerSandboxError("runtime log must be inside DATA_DIR")
870
+ log.parent.mkdir(parents=True, exist_ok=True)
871
+ self._log_handle = log.open("ab")
872
+ control_read_fd, control_write_fd = os.pipe()
873
+ broker_read_fd, broker_write_fd = os.pipe()
874
+ os.set_blocking(broker_read_fd, False)
875
+ command = self._sandbox_command(
876
+ build=build,
877
+ executable=executable,
878
+ control_read_fd=control_read_fd,
879
+ broker_write_fd=broker_write_fd,
880
+ credentials=credentials,
881
+ )
882
+ try:
883
+ self.process = subprocess.Popen(
884
+ command,
885
+ cwd=build,
886
+ env=self._environment(),
887
+ stdin=subprocess.DEVNULL,
888
+ stdout=self._log_handle or subprocess.DEVNULL,
889
+ stderr=self._log_handle or subprocess.DEVNULL,
890
+ start_new_session=True,
891
+ preexec_fn=self._preexec,
892
+ pass_fds=(control_read_fd, broker_write_fd),
893
+ )
894
+ except BaseException:
895
+ os.close(control_read_fd)
896
+ os.close(control_write_fd)
897
+ os.close(broker_read_fd)
898
+ os.close(broker_write_fd)
899
+ self._close_log()
900
+ raise
901
+ os.close(control_read_fd)
902
+ os.close(broker_write_fd)
903
+ self._control_write_fd = control_write_fd
904
+ self._cleanup_complete = False
905
+ proof = b""
906
+ # Process creation can be delayed materially when several Harbor
907
+ # verifier shards contend for I/O. Identity proof is an
908
+ # infrastructure handshake, not candidate readiness, so give the
909
+ # trusted launcher enough time to report its already-created workers.
910
+ deadline = time.monotonic() + 15.0
911
+ try:
912
+ while b"\n" not in proof and time.monotonic() < deadline:
913
+ try:
914
+ proof += os.read(broker_read_fd, 128)
915
+ except BlockingIOError:
916
+ pass
917
+ if self.process.poll() is not None:
918
+ break
919
+ time.sleep(0.01)
920
+ except OSError as exc:
921
+ self.stop(timeout=1.0)
922
+ raise RuntimeInfrastructureError(
923
+ "compiled runtime sandbox identity proof could not be read"
924
+ ) from exc
925
+ finally:
926
+ os.close(broker_read_fd)
927
+ try:
928
+ proof_fields = proof.splitlines()[0].split()
929
+ if len(proof_fields) != 2:
930
+ raise ValueError("sandbox proof must contain two process IDs")
931
+ self._broker_tid, self._candidate_pid = map(int, proof_fields)
932
+ except (ValueError, IndexError):
933
+ self._broker_tid = None
934
+ self._candidate_pid = None
935
+ if (
936
+ self._broker_tid is not None
937
+ and not Path(f"/proc/{self.process.pid}/task/{self._broker_tid}").is_dir()
938
+ ):
939
+ self._broker_tid = None
940
+ if self._broker_tid is None or self._candidate_pid is None:
941
+ self.stop(timeout=1.0)
942
+ raise RuntimeInfrastructureError(
943
+ "compiled runtime sandbox did not attest its broker and candidate IDs"
944
+ )
945
+ expected_uid, expected_gid = credentials or (os.geteuid(), os.getegid())
946
+ try:
947
+ self._attest_worker_identity(
948
+ expected_uid=expected_uid,
949
+ expected_gid=expected_gid,
950
+ )
951
+ except OSError as exc:
952
+ self.stop(timeout=1.0)
953
+ raise RuntimeInfrastructureError(
954
+ "compiled runtime sandbox worker identity could not be verified"
955
+ ) from exc
956
+
957
+ def ready(self, *, timeout: float = 30.0) -> bool:
958
+ deadline = time.monotonic() + timeout
959
+ urls = [f"http://127.0.0.1:{self.port}{path}" for path in HEALTH_PATHS]
960
+ while time.monotonic() < deadline:
961
+ if self.process is None or self.process.poll() is not None:
962
+ return False
963
+ for url in urls:
964
+ try:
965
+ request = urllib.request.Request(url, method="GET")
966
+ with urllib.request.urlopen(request, timeout=0.5) as response:
967
+ payload = response.read(4096)
968
+ if (
969
+ response.status == 200
970
+ and json.loads(payload) == HEALTH_BODY
971
+ ):
972
+ return self.process.poll() is None
973
+ except (
974
+ OSError,
975
+ ValueError,
976
+ urllib.error.URLError,
977
+ json.JSONDecodeError,
978
+ ):
979
+ pass
980
+ time.sleep(0.05)
981
+ return False
982
+
983
+ def stop(
984
+ self, *, timeout: float = 10.0, accept_forced: bool = False
985
+ ) -> bool:
986
+ if self.process is None:
987
+ self._close_control()
988
+ self._close_log()
989
+ self._cleanup_complete = True
990
+ return True
991
+ if self._control_write_fd is None:
992
+ graceful = _terminate_group(
993
+ self.process, timeout, accept_forced=accept_forced
994
+ )
995
+ else:
996
+ graceful = _stop_controlled_group(
997
+ self.process,
998
+ self._control_write_fd,
999
+ timeout,
1000
+ accept_forced=accept_forced,
1001
+ )
1002
+ self._close_control()
1003
+ self._close_log()
1004
+ self._cleanup_complete = graceful
1005
+ self._broker_tid = None
1006
+ self._candidate_pid = None
1007
+ return graceful
1008
+
1009
+ def _close_control(self) -> None:
1010
+ if self._control_write_fd is not None:
1011
+ try:
1012
+ os.close(self._control_write_fd)
1013
+ except OSError:
1014
+ pass
1015
+ self._control_write_fd = None
1016
+
1017
+ def _close_log(self) -> None:
1018
+ if self._log_handle is not None:
1019
+ self._log_handle.flush()
1020
+ os.fsync(self._log_handle.fileno())
1021
+ self._log_handle.close()
1022
+ self._log_handle = None
1023
+
1024
+
1025
+ def validate_runtime_lifecycle(
1026
+ artifact: CompiledArtifact,
1027
+ *,
1028
+ port: int,
1029
+ seed: int,
1030
+ working_root: Path | str,
1031
+ worker_access_roots: Sequence[Path | str],
1032
+ timezone: str = "UTC",
1033
+ ) -> dict[str, Any]:
1034
+ """Probe health, foreground/SIGTERM, restart persistence and new-dir isolation."""
1035
+
1036
+ root = Path(working_root).resolve()
1037
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
1038
+ first_data = root / "data-first"
1039
+ second_data = root / "data-second"
1040
+ first_data.mkdir(mode=0o700)
1041
+ second_data.mkdir(mode=0o700)
1042
+ sentinel = first_data / ".websitebench-persistence"
1043
+ sentinel.write_text(f"{seed}\n", encoding="ascii")
1044
+ first = ExecutableRuntime(
1045
+ artifact.build_root,
1046
+ first_data,
1047
+ port,
1048
+ seed,
1049
+ timezone,
1050
+ first_data / "runtime.log",
1051
+ expected_tree_sha256=artifact.tree_sha256,
1052
+ worker_access_roots=tuple(Path(value) for value in worker_access_roots),
1053
+ )
1054
+ first.start()
1055
+ healthy = first.ready()
1056
+ graceful = first.stop(timeout=10.0)
1057
+ sentinel_persisted = sentinel.read_text(encoding="ascii") == f"{seed}\n"
1058
+ restarted = False
1059
+ if graceful:
1060
+ first.start()
1061
+ restarted = first.ready()
1062
+ graceful = first.stop(timeout=10.0) and graceful
1063
+ second = ExecutableRuntime(
1064
+ artifact.build_root,
1065
+ second_data,
1066
+ port,
1067
+ seed,
1068
+ timezone,
1069
+ second_data / "runtime.log",
1070
+ expected_tree_sha256=artifact.tree_sha256,
1071
+ worker_access_roots=tuple(Path(value) for value in worker_access_roots),
1072
+ )
1073
+ second.start()
1074
+ second_healthy = second.ready()
1075
+ second_graceful = second.stop(timeout=10.0)
1076
+ isolated = (
1077
+ second_healthy
1078
+ and second_graceful
1079
+ and not (second_data / sentinel.name).exists()
1080
+ )
1081
+ return {
1082
+ "deployment_abi": DEPLOYMENT_ABI,
1083
+ "health": healthy,
1084
+ "foreground": healthy,
1085
+ "sigterm": graceful,
1086
+ "restart": restarted,
1087
+ "persistence": sentinel_persisted,
1088
+ "new_data_dir_health": second_healthy,
1089
+ "new_data_dir_isolation": isolated,
1090
+ "tree_sha256": artifact.tree_sha256,
1091
+ "valid": all(
1092
+ (
1093
+ healthy,
1094
+ graceful,
1095
+ restarted,
1096
+ sentinel_persisted,
1097
+ second_healthy,
1098
+ second_graceful,
1099
+ isolated,
1100
+ )
1101
+ ),
1102
+ }
1103
+
1104
+
1105
+ __all__ = [
1106
+ "COMPILE_ENTRYPOINT",
1107
+ "DEFAULT_COMPILE_TIMEOUT",
1108
+ "DEPLOYMENT_ABI",
1109
+ "EXECUTABLE_ENTRYPOINT",
1110
+ "HEALTH_BODY",
1111
+ "HEALTH_PATH",
1112
+ "HEALTH_PATHS",
1113
+ "LEGACY_HEALTH_PATHS",
1114
+ "MAX_LOG_BYTES",
1115
+ "RUNTIME_PROCESS_MODEL",
1116
+ "RuntimeInfrastructureError",
1117
+ "WORKER_OS_GID",
1118
+ "WORKER_OS_UID",
1119
+ "CompiledArtifact",
1120
+ "CompilerSandboxError",
1121
+ "ExecutableRuntime",
1122
+ "compile_candidate",
1123
+ "freeze_build_tree",
1124
+ "quarantine_artifact",
1125
+ "tree_digest",
1126
+ "validate_artifact_tree",
1127
+ "validate_runtime_lifecycle",
1128
+ ]
tasks/dooney-bourke/environment/candidate-abi/websitebench/harbor/sandbox.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Linux kernel sandbox launcher for untrusted Harbor candidates.
2
+
3
+ The launcher is executed by the privileged verifier, installs an irreversible
4
+ Landlock/seccomp policy, drops to the opaque worker UID, and only then execs the
5
+ candidate entrypoint. It deliberately has no dependency outside the standard
6
+ library so the formal verifier image has a small, inspectable trusted surface.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import array
13
+ import ctypes
14
+ import errno
15
+ import fcntl
16
+ import os
17
+ import platform
18
+ import resource
19
+ import signal
20
+ import socket
21
+ import stat
22
+ import struct
23
+ import threading
24
+ import time
25
+ from pathlib import Path
26
+ from typing import Sequence
27
+
28
+
29
+ PR_SET_NO_NEW_PRIVS = 38
30
+ PR_SET_DUMPABLE = 4
31
+ PR_SET_SECCOMP = 22
32
+ SECCOMP_MODE_FILTER = 2
33
+ SECCOMP_RET_KILL_PROCESS = 0x80000000
34
+ SECCOMP_RET_ERRNO = 0x00050000
35
+ SECCOMP_RET_USER_NOTIF = 0x7FC00000
36
+ SECCOMP_RET_ALLOW = 0x7FFF0000
37
+ SECCOMP_FILTER_FLAG_NEW_LISTENER = 1 << 3
38
+ SECCOMP_SET_MODE_FILTER = 1
39
+ SECCOMP_GET_ACTION_AVAIL = 2
40
+
41
+ BPF_LD_W_ABS = 0x20
42
+ BPF_JMP_JEQ_K = 0x15
43
+ BPF_JMP_JSET_K = 0x45
44
+ BPF_ALU_AND_K = 0x54
45
+ BPF_RET_K = 0x06
46
+
47
+ LANDLOCK_CREATE_RULESET_VERSION = 1
48
+ LANDLOCK_RULE_PATH_BENEATH = 1
49
+ LANDLOCK_RULE_NET_PORT = 2
50
+ LANDLOCK_ACCESS_FS_EXECUTE = 1 << 0
51
+ LANDLOCK_ACCESS_FS_WRITE_FILE = 1 << 1
52
+ LANDLOCK_ACCESS_FS_READ_FILE = 1 << 2
53
+ LANDLOCK_ACCESS_FS_READ_DIR = 1 << 3
54
+ LANDLOCK_ACCESS_FS_REMOVE_DIR = 1 << 4
55
+ LANDLOCK_ACCESS_FS_REMOVE_FILE = 1 << 5
56
+ LANDLOCK_ACCESS_FS_MAKE_CHAR = 1 << 6
57
+ LANDLOCK_ACCESS_FS_MAKE_DIR = 1 << 7
58
+ LANDLOCK_ACCESS_FS_MAKE_REG = 1 << 8
59
+ LANDLOCK_ACCESS_FS_MAKE_SOCK = 1 << 9
60
+ LANDLOCK_ACCESS_FS_MAKE_FIFO = 1 << 10
61
+ LANDLOCK_ACCESS_FS_MAKE_BLOCK = 1 << 11
62
+ LANDLOCK_ACCESS_FS_MAKE_SYM = 1 << 12
63
+ LANDLOCK_ACCESS_FS_REFER = 1 << 13
64
+ LANDLOCK_ACCESS_FS_TRUNCATE = 1 << 14
65
+ LANDLOCK_ACCESS_FS_IOCTL_DEV = 1 << 15
66
+ LANDLOCK_ACCESS_NET_BIND_TCP = 1 << 0
67
+ LANDLOCK_ACCESS_NET_CONNECT_TCP = 1 << 1
68
+
69
+ _FS_ABI_1 = (1 << 13) - 1
70
+ _FS_ABI_2 = _FS_ABI_1 | LANDLOCK_ACCESS_FS_REFER
71
+ _FS_ABI_3 = _FS_ABI_2 | LANDLOCK_ACCESS_FS_TRUNCATE
72
+ _FS_ABI_5 = _FS_ABI_3 | LANDLOCK_ACCESS_FS_IOCTL_DEV
73
+ _FS_READ_EXECUTE = (
74
+ LANDLOCK_ACCESS_FS_EXECUTE
75
+ | LANDLOCK_ACCESS_FS_READ_FILE
76
+ | LANDLOCK_ACCESS_FS_READ_DIR
77
+ )
78
+
79
+
80
+ class _RulesetAttr(ctypes.Structure):
81
+ _fields_ = [
82
+ ("handled_access_fs", ctypes.c_uint64),
83
+ ("handled_access_net", ctypes.c_uint64),
84
+ ]
85
+
86
+
87
+ class _PathBeneathAttr(ctypes.Structure):
88
+ _fields_ = [
89
+ ("allowed_access", ctypes.c_uint64),
90
+ ("parent_fd", ctypes.c_int32),
91
+ ("reserved", ctypes.c_uint32),
92
+ ]
93
+
94
+
95
+ class _NetPortAttr(ctypes.Structure):
96
+ _fields_ = [("allowed_access", ctypes.c_uint64), ("port", ctypes.c_uint64)]
97
+
98
+
99
+ class _SockFilter(ctypes.Structure):
100
+ _fields_ = [
101
+ ("code", ctypes.c_ushort),
102
+ ("jt", ctypes.c_ubyte),
103
+ ("jf", ctypes.c_ubyte),
104
+ ("k", ctypes.c_uint32),
105
+ ]
106
+
107
+
108
+ class _SockFprog(ctypes.Structure):
109
+ _fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.POINTER(_SockFilter))]
110
+
111
+
112
+ _SECCOMP_NOTIF_FORMAT = "=QIIiIQQQQQQQ"
113
+ _SECCOMP_RESP_FORMAT = "=QqiI"
114
+ _SECCOMP_NOTIF_SIZE = struct.calcsize(_SECCOMP_NOTIF_FORMAT)
115
+ _SECCOMP_RESP_SIZE = struct.calcsize(_SECCOMP_RESP_FORMAT)
116
+
117
+
118
+ def _iowr(kind: int, number: int, size: int) -> int:
119
+ return (3 << 30) | (size << 16) | (kind << 8) | number
120
+
121
+
122
+ _SECCOMP_IOCTL_NOTIF_RECV = _iowr(ord("!"), 0, _SECCOMP_NOTIF_SIZE)
123
+ _SECCOMP_IOCTL_NOTIF_SEND = _iowr(ord("!"), 1, _SECCOMP_RESP_SIZE)
124
+
125
+
126
+ def _architecture() -> tuple[int, int, int, int, tuple[int, ...]]:
127
+ machine = platform.machine().lower()
128
+ if machine in {"x86_64", "amd64"}:
129
+ # AUDIT_ARCH_X86_64, socket(2), and shared cross-process facilities.
130
+ return (
131
+ 0xC000003E,
132
+ 41,
133
+ 72,
134
+ 317,
135
+ (
136
+ 29,
137
+ 30,
138
+ 31,
139
+ 57,
140
+ 58,
141
+ 64,
142
+ 65,
143
+ 66,
144
+ 67,
145
+ 68,
146
+ 69,
147
+ 70,
148
+ 71,
149
+ 109,
150
+ 112,
151
+ 240,
152
+ 241,
153
+ 242,
154
+ 243,
155
+ 244,
156
+ 245,
157
+ 248,
158
+ 249,
159
+ 250,
160
+ 253,
161
+ 254,
162
+ 255,
163
+ 294,
164
+ 298,
165
+ 300,
166
+ 301,
167
+ 425,
168
+ 73,
169
+ ),
170
+ )
171
+ if machine in {"aarch64", "arm64"}:
172
+ return (
173
+ 0xC00000B7,
174
+ 198,
175
+ 25,
176
+ 277,
177
+ tuple(range(180, 198))
178
+ + (26, 27, 28, 32, 154, 157, 217, 218, 219, 241, 262, 263, 425),
179
+ )
180
+ raise OSError(errno.ENOTSUP, f"unsupported verifier architecture: {machine}")
181
+
182
+
183
+ def _syscalls() -> tuple[int, int, int]:
184
+ machine = platform.machine().lower()
185
+ if machine in {"x86_64", "amd64", "aarch64", "arm64"}:
186
+ return 444, 445, 446
187
+ raise OSError(errno.ENOTSUP, f"unsupported verifier architecture: {machine}")
188
+
189
+
190
+ def sandbox_runtime_fingerprint() -> dict[str, object]:
191
+ """Return trusted kernel capabilities required by the candidate sandbox."""
192
+
193
+ audit_arch, socket_syscall, _fcntl_syscall, seccomp_syscall, _denied = (
194
+ _architecture()
195
+ )
196
+ create_ruleset, _add_rule, _restrict_self = _syscalls()
197
+ libc = ctypes.CDLL(None, use_errno=True)
198
+ abi = int(libc.syscall(create_ruleset, 0, 0, LANDLOCK_CREATE_RULESET_VERSION))
199
+ action = ctypes.c_uint32(SECCOMP_RET_USER_NOTIF)
200
+ user_notification = (
201
+ libc.syscall(
202
+ seccomp_syscall,
203
+ SECCOMP_GET_ACTION_AVAIL,
204
+ 0,
205
+ ctypes.byref(action),
206
+ )
207
+ == 0
208
+ )
209
+ x32_unavailable = True
210
+ if audit_arch == 0xC000003E:
211
+ ctypes.set_errno(0)
212
+ result = libc.syscall(0x40000000 | socket_syscall, -1, -1, -1)
213
+ x32_unavailable = result == -1 and ctypes.get_errno() == errno.ENOSYS
214
+ return {
215
+ "schema": "websitebench.harbor.sandbox-runtime",
216
+ "architecture": platform.machine().lower(),
217
+ "landlock_abi": abi,
218
+ "seccomp_user_notification": user_notification,
219
+ "x32_unavailable": x32_unavailable,
220
+ }
221
+
222
+
223
+ def sandbox_preflight() -> dict[str, object]:
224
+ """Fail closed before scoring when the verifier kernel cannot sandbox."""
225
+
226
+ fingerprint = sandbox_runtime_fingerprint()
227
+ if (
228
+ int(fingerprint["landlock_abi"]) < 4
229
+ or fingerprint["seccomp_user_notification"] is not True
230
+ or fingerprint["x32_unavailable"] is not True
231
+ ):
232
+ raise OSError(errno.ENOTSUP, f"candidate sandbox unavailable: {fingerprint}")
233
+ child = os.fork()
234
+ if child == 0:
235
+ try:
236
+ _landlock(Path("/"), Path("/tmp"), 65534, {65534})
237
+ listener = _seccomp()
238
+ os.close(listener)
239
+ os._exit(0)
240
+ except BaseException:
241
+ os._exit(1)
242
+ _waited, status = os.waitpid(child, 0)
243
+ if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0:
244
+ raise OSError(errno.ENOTSUP, "candidate sandbox enforcement probe failed")
245
+ fingerprint["enforcement_probe_passed"] = True
246
+ return fingerprint
247
+
248
+
249
+ def _landlock(
250
+ root: Path,
251
+ data: Path,
252
+ bind_port: int,
253
+ connect_ports: set[int],
254
+ read_paths: Sequence[Path] = (),
255
+ ) -> None:
256
+ libc = ctypes.CDLL(None, use_errno=True)
257
+ create_ruleset, add_rule, restrict_self = _syscalls()
258
+ abi = int(libc.syscall(create_ruleset, 0, 0, LANDLOCK_CREATE_RULESET_VERSION))
259
+ if abi < 4:
260
+ code = ctypes.get_errno() if abi < 0 else errno.ENOTSUP
261
+ raise OSError(code, "Landlock ABI 4 or newer is required")
262
+
263
+ handled_fs = _FS_ABI_1
264
+ if abi >= 2:
265
+ handled_fs = _FS_ABI_2
266
+ if abi >= 3:
267
+ handled_fs = _FS_ABI_3
268
+ if abi >= 5:
269
+ handled_fs = _FS_ABI_5
270
+ handled_net = LANDLOCK_ACCESS_NET_BIND_TCP | LANDLOCK_ACCESS_NET_CONNECT_TCP
271
+ attributes = _RulesetAttr(handled_fs, handled_net)
272
+ ruleset_fd = int(
273
+ libc.syscall(
274
+ create_ruleset,
275
+ ctypes.byref(attributes),
276
+ ctypes.sizeof(attributes),
277
+ 0,
278
+ )
279
+ )
280
+ if ruleset_fd < 0:
281
+ raise OSError(ctypes.get_errno(), "cannot create Landlock ruleset")
282
+
283
+ def add_path(path: Path, access: int) -> None:
284
+ if not path.exists():
285
+ return
286
+ descriptor = os.open(path, os.O_PATH | os.O_CLOEXEC)
287
+ try:
288
+ rule = _PathBeneathAttr(access & handled_fs, descriptor, 0)
289
+ if (
290
+ libc.syscall(
291
+ add_rule,
292
+ ruleset_fd,
293
+ LANDLOCK_RULE_PATH_BENEATH,
294
+ ctypes.byref(rule),
295
+ 0,
296
+ )
297
+ != 0
298
+ ):
299
+ raise OSError(ctypes.get_errno(), f"cannot allow sandbox path: {path}")
300
+ finally:
301
+ os.close(descriptor)
302
+
303
+ try:
304
+ for path in (
305
+ root,
306
+ Path("/usr"),
307
+ Path("/bin"),
308
+ Path("/lib"),
309
+ Path("/lib64"),
310
+ Path("/etc"),
311
+ *read_paths,
312
+ ):
313
+ add_path(path, _FS_READ_EXECUTE)
314
+ for path in (
315
+ Path("/dev/null"),
316
+ Path("/dev/zero"),
317
+ Path("/dev/random"),
318
+ Path("/dev/urandom"),
319
+ Path("/dev/full"),
320
+ Path("/dev/tty"),
321
+ ):
322
+ add_path(path, LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE)
323
+ add_path(data, handled_fs)
324
+
325
+ for access, port in (
326
+ (LANDLOCK_ACCESS_NET_BIND_TCP, bind_port),
327
+ *(
328
+ (LANDLOCK_ACCESS_NET_CONNECT_TCP, port)
329
+ for port in sorted(connect_ports)
330
+ ),
331
+ ):
332
+ rule = _NetPortAttr(access, port)
333
+ if (
334
+ libc.syscall(
335
+ add_rule,
336
+ ruleset_fd,
337
+ LANDLOCK_RULE_NET_PORT,
338
+ ctypes.byref(rule),
339
+ 0,
340
+ )
341
+ != 0
342
+ ):
343
+ raise OSError(ctypes.get_errno(), "cannot add Landlock TCP rule")
344
+
345
+ if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
346
+ raise OSError(ctypes.get_errno(), "cannot set no_new_privs")
347
+ if libc.syscall(restrict_self, ruleset_fd, 0) != 0:
348
+ raise OSError(ctypes.get_errno(), "cannot enforce Landlock ruleset")
349
+ finally:
350
+ os.close(ruleset_fd)
351
+
352
+
353
+ def _seccomp() -> int:
354
+ """Install the filter and return its user-notification listener."""
355
+
356
+ audit_arch, socket_syscall, fcntl_syscall, seccomp_syscall, denied = _architecture()
357
+ instructions: list[tuple[int, int, int, int]] = [
358
+ (BPF_LD_W_ABS, 0, 0, 4),
359
+ (BPF_JMP_JEQ_K, 1, 0, audit_arch),
360
+ (BPF_RET_K, 0, 0, SECCOMP_RET_KILL_PROCESS),
361
+ (BPF_LD_W_ABS, 0, 0, 0),
362
+ ]
363
+ if audit_arch == 0xC000003E:
364
+ instructions.extend(
365
+ [
366
+ (BPF_JMP_JSET_K, 0, 1, 0x40000000),
367
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
368
+ ]
369
+ )
370
+ # Force clone3 callers onto the inspectable clone/fork fallback, then deny
371
+ # only process-style clone(SIGCHLD). Thread creation has a zero exit-signal
372
+ # byte and remains available to ASGI runtimes.
373
+ clone_syscall = 56 if audit_arch == 0xC000003E else 220
374
+ instructions.extend(
375
+ [
376
+ (BPF_JMP_JEQ_K, 0, 1, 435),
377
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.ENOSYS),
378
+ (BPF_LD_W_ABS, 0, 0, 0),
379
+ (BPF_JMP_JEQ_K, 0, 4, clone_syscall),
380
+ (BPF_LD_W_ABS, 0, 0, 16),
381
+ (BPF_ALU_AND_K, 0, 0, 0xFF),
382
+ (BPF_JMP_JEQ_K, 0, 1, signal.SIGCHLD),
383
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
384
+ (BPF_LD_W_ABS, 0, 0, 0),
385
+ ]
386
+ )
387
+ for number in denied:
388
+ instructions.extend(
389
+ [
390
+ (BPF_JMP_JEQ_K, 0, 1, number),
391
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
392
+ ]
393
+ )
394
+ # Classic and OFD byte-range locks are executed by the trusted broker.
395
+ # The tracee is never continued after a pathname/fd check: another tracee
396
+ # thread could otherwise replace the descriptor between check and use.
397
+ brokered_fcntl_commands = (5, 6, 7, 36, 37, 38)
398
+ instructions.extend(
399
+ [
400
+ (
401
+ BPF_JMP_JEQ_K,
402
+ 0,
403
+ 2 * len(brokered_fcntl_commands) + 2,
404
+ fcntl_syscall,
405
+ ),
406
+ (BPF_LD_W_ABS, 0, 0, 24),
407
+ ]
408
+ )
409
+ for command in brokered_fcntl_commands:
410
+ instructions.extend(
411
+ [
412
+ (BPF_JMP_JEQ_K, 0, 1, command),
413
+ (BPF_RET_K, 0, 0, SECCOMP_RET_USER_NOTIF),
414
+ ]
415
+ )
416
+ instructions.append((BPF_LD_W_ABS, 0, 0, 0))
417
+ # socket(domain, type, protocol): permit only IPv4/IPv6 SOCK_STREAM.
418
+ instructions.extend(
419
+ [
420
+ (BPF_JMP_JEQ_K, 0, 8, socket_syscall),
421
+ (BPF_LD_W_ABS, 0, 0, 16),
422
+ (BPF_JMP_JEQ_K, 2, 0, 2),
423
+ (BPF_JMP_JEQ_K, 1, 0, 10),
424
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
425
+ (BPF_LD_W_ABS, 0, 0, 24),
426
+ (BPF_ALU_AND_K, 0, 0, 0xF),
427
+ (BPF_JMP_JEQ_K, 1, 0, 1),
428
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
429
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ALLOW),
430
+ ]
431
+ )
432
+ filters = (_SockFilter * len(instructions))(
433
+ *(_SockFilter(*instruction) for instruction in instructions)
434
+ )
435
+ program = _SockFprog(len(instructions), filters)
436
+ libc = ctypes.CDLL(None, use_errno=True)
437
+ listener = int(
438
+ libc.syscall(
439
+ seccomp_syscall,
440
+ SECCOMP_SET_MODE_FILTER,
441
+ SECCOMP_FILTER_FLAG_NEW_LISTENER,
442
+ ctypes.byref(program),
443
+ )
444
+ )
445
+ if listener < 0:
446
+ raise OSError(ctypes.get_errno(), "cannot install candidate seccomp filter")
447
+ return listener
448
+
449
+
450
+ def _send_fd(channel: socket.socket, descriptor: int) -> None:
451
+ descriptors = array.array("i", [descriptor])
452
+ channel.sendmsg(
453
+ [b"L"],
454
+ [(socket.SOL_SOCKET, socket.SCM_RIGHTS, descriptors.tobytes())],
455
+ )
456
+
457
+
458
+ def _receive_fd(channel: socket.socket) -> int:
459
+ descriptors = array.array("i")
460
+ message, ancillary, _flags, _address = channel.recvmsg(
461
+ 1, socket.CMSG_SPACE(descriptors.itemsize)
462
+ )
463
+ if message != b"L":
464
+ raise OSError(errno.EIO, "candidate sandbox listener was not delivered")
465
+ for level, kind, payload in ancillary:
466
+ if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
467
+ descriptors.frombytes(payload[: descriptors.itemsize])
468
+ return int(descriptors[0])
469
+ raise OSError(errno.EIO, "candidate sandbox listener fd is missing")
470
+
471
+
472
+ def _tracee_process_id(thread_id: int) -> int:
473
+ try:
474
+ for line in Path(f"/proc/{thread_id}/status").read_text().splitlines():
475
+ if line.startswith("Tgid:"):
476
+ return int(line.partition(":")[2].strip())
477
+ except (OSError, ValueError):
478
+ pass
479
+ raise OSError(errno.ESRCH, "cannot identify candidate process")
480
+
481
+
482
+ def _capture_worker_file(pid: int, descriptor: int, data: Path) -> int:
483
+ """Atomically capture a regular data-dir inode from a tracee descriptor."""
484
+
485
+ captured = os.open(f"/proc/{pid}/fd/{descriptor}", os.O_RDWR | os.O_CLOEXEC)
486
+ try:
487
+ metadata = os.fstat(captured)
488
+ if not stat.S_ISREG(metadata.st_mode):
489
+ raise OSError(errno.EPERM, "candidate locks require a regular file")
490
+ target_text = os.readlink(f"/proc/self/fd/{captured}")
491
+ if target_text.endswith(" (deleted)"):
492
+ target_text = target_text[: -len(" (deleted)")]
493
+ target = Path(target_text).resolve()
494
+ if target != data and data not in target.parents:
495
+ raise OSError(errno.EPERM, "candidate lock target is outside data dir")
496
+ return captured
497
+ except BaseException:
498
+ os.close(captured)
499
+ raise
500
+
501
+
502
+ def _read_tracee(pid: int, address: int, size: int) -> bytes:
503
+ descriptor = os.open(f"/proc/{pid}/mem", os.O_RDONLY | os.O_CLOEXEC)
504
+ try:
505
+ value = os.pread(descriptor, size, address)
506
+ finally:
507
+ os.close(descriptor)
508
+ if len(value) != size:
509
+ raise OSError(errno.EFAULT, "candidate fcntl argument is unreadable")
510
+ return value
511
+
512
+
513
+ def _write_tracee(pid: int, address: int, value: bytes) -> None:
514
+ descriptor = os.open(f"/proc/{pid}/mem", os.O_WRONLY | os.O_CLOEXEC)
515
+ try:
516
+ written = os.pwrite(descriptor, value, address)
517
+ finally:
518
+ os.close(descriptor)
519
+ if written != len(value):
520
+ raise OSError(errno.EFAULT, "candidate fcntl result is unwritable")
521
+
522
+
523
+ def _prune_closed_lock_files(
524
+ process_id: int,
525
+ locked_files: dict[tuple[int, int, int], int],
526
+ ) -> None:
527
+ """Release broker descriptors once the tracee has closed their inode.
528
+
529
+ SQLite creates and removes WAL/SHM files as short-lived connections come
530
+ and go. Keeping one broker descriptor for every historical inode pins both
531
+ deleted files and file descriptors until process exit, eventually turning
532
+ ordinary repeated requests into ``SQLITE_IOERR`` under ``RLIMIT_NOFILE``.
533
+ An OFD lock is no longer useful after the tracee has closed every descriptor
534
+ for that inode, so prune it before brokering the next lock operation.
535
+ """
536
+
537
+ open_inodes: set[tuple[int, int]] = set()
538
+ try:
539
+ entries = list(Path(f"/proc/{process_id}/fd").iterdir())
540
+ except OSError:
541
+ return
542
+ for entry in entries:
543
+ try:
544
+ metadata = entry.stat()
545
+ except OSError:
546
+ continue
547
+ open_inodes.add((metadata.st_dev, metadata.st_ino))
548
+ for key, descriptor in list(locked_files.items()):
549
+ owner, device, inode = key
550
+ if owner == process_id and (device, inode) not in open_inodes:
551
+ os.close(descriptor)
552
+ del locked_files[key]
553
+
554
+
555
+ def _broker_fcntl(
556
+ pid: int,
557
+ descriptor: int,
558
+ command: int,
559
+ argument: int,
560
+ data: Path,
561
+ locked_files: dict[tuple[int, int, int], int],
562
+ ) -> int:
563
+ """Execute a byte-range lock without continuing the untrusted syscall."""
564
+
565
+ process_id = _tracee_process_id(pid)
566
+ _prune_closed_lock_files(process_id, locked_files)
567
+ captured = _capture_worker_file(pid, descriptor, data)
568
+ metadata = os.fstat(captured)
569
+ key = (process_id, metadata.st_dev, metadata.st_ino)
570
+ broker_descriptor = locked_files.get(key)
571
+ if broker_descriptor is None:
572
+ locked_files[key] = captured
573
+ broker_descriptor = captured
574
+ else:
575
+ os.close(captured)
576
+
577
+ flock_value = bytearray(_read_tracee(pid, argument, 32))
578
+ # Linux requires l_pid to be zero for OFD lock operations. Classic
579
+ # F_SETLK callers do not own that output-only field, so normalize it when
580
+ # translating the request.
581
+ flock_value[24:28] = b"\0\0\0\0"
582
+ translations = {
583
+ 5: 36, # F_GETLK -> F_OFD_GETLK
584
+ 6: 37, # F_SETLK -> F_OFD_SETLK
585
+ 7: 37, # F_SETLKW stays fail-fast so the broker cannot deadlock.
586
+ 36: 36,
587
+ 37: 37,
588
+ 38: 37,
589
+ }
590
+ result = fcntl.fcntl(broker_descriptor, translations[command], bytes(flock_value))
591
+ if command in {5, 36}:
592
+ if not isinstance(result, bytes):
593
+ raise OSError(errno.EIO, "candidate lock query returned no structure")
594
+ _write_tracee(pid, argument, result.ljust(32, b"\0")[:32])
595
+ return 0
596
+
597
+
598
+ def _lock_broker(listener: int, data: Path) -> None:
599
+ locked_files: dict[tuple[int, int, int], int] = {}
600
+ try:
601
+ while True:
602
+ request = bytearray(_SECCOMP_NOTIF_SIZE)
603
+ try:
604
+ fcntl.ioctl(listener, _SECCOMP_IOCTL_NOTIF_RECV, request, True)
605
+ except OSError as exc:
606
+ if exc.errno in {errno.EINTR, errno.ENOENT, errno.EBADF}:
607
+ if exc.errno == errno.EINTR:
608
+ continue
609
+ return
610
+ raise
611
+ unpacked = struct.unpack(_SECCOMP_NOTIF_FORMAT, request)
612
+ identifier, pid = int(unpacked[0]), int(unpacked[1])
613
+ try:
614
+ value = _broker_fcntl(
615
+ pid,
616
+ int(unpacked[6]),
617
+ int(unpacked[7]),
618
+ int(unpacked[8]),
619
+ data,
620
+ locked_files,
621
+ )
622
+ error = 0
623
+ except OSError as exc:
624
+ value = 0
625
+ error = -(exc.errno or errno.EPERM)
626
+ response = bytearray(
627
+ struct.pack(_SECCOMP_RESP_FORMAT, identifier, value, error, 0)
628
+ )
629
+ try:
630
+ fcntl.ioctl(listener, _SECCOMP_IOCTL_NOTIF_SEND, response, True)
631
+ except OSError as exc:
632
+ if exc.errno != errno.ENOENT:
633
+ raise
634
+ finally:
635
+ for descriptor in locked_files.values():
636
+ os.close(descriptor)
637
+
638
+
639
+ def _drop_credentials(uid: int | None, gid: int | None) -> None:
640
+ """Irreversibly adopt the requested worker identity, when configured."""
641
+
642
+ if uid is None or gid is None:
643
+ return
644
+ os.setgroups([])
645
+ os.setgid(gid)
646
+ os.setuid(uid)
647
+ if os.geteuid() != uid or os.getegid() != gid or os.getgroups():
648
+ raise OSError(errno.EPERM, "worker credential drop did not take effect")
649
+
650
+
651
+ def _kill_and_reap(child_pid: int) -> None:
652
+ try:
653
+ os.kill(child_pid, signal.SIGKILL)
654
+ except ProcessLookupError:
655
+ pass
656
+ try:
657
+ os.waitpid(child_pid, 0)
658
+ except ChildProcessError:
659
+ pass
660
+
661
+
662
+ def sandbox_exec(
663
+ command: Sequence[str],
664
+ *,
665
+ root: Path,
666
+ data: Path,
667
+ bind_port: int,
668
+ connect_ports: set[int],
669
+ uid: int | None,
670
+ gid: int | None,
671
+ file_size_limit_bytes: int | None,
672
+ read_paths: Sequence[Path] = (),
673
+ broker_tid_fd: int | None = None,
674
+ control_fd: int | None = None,
675
+ ) -> None:
676
+ root = root.resolve(strict=True)
677
+ data = data.resolve(strict=True)
678
+ parent_channel, child_channel = socket.socketpair()
679
+ child_pid = os.fork()
680
+ if child_pid == 0:
681
+ parent_channel.close()
682
+ if control_fd is not None:
683
+ os.close(control_fd)
684
+ if broker_tid_fd is not None:
685
+ os.close(broker_tid_fd)
686
+ stage = "landlock"
687
+ try:
688
+ _landlock(root, data, bind_port, connect_ports, read_paths)
689
+ stage = "resource limits"
690
+ if file_size_limit_bytes is not None:
691
+ resource.setrlimit(
692
+ resource.RLIMIT_FSIZE,
693
+ (file_size_limit_bytes, file_size_limit_bytes),
694
+ )
695
+ if uid is not None and gid is not None:
696
+ stage = "credential drop"
697
+ _drop_credentials(uid, gid)
698
+ stage = "lock broker access"
699
+ libc = ctypes.CDLL(None, use_errno=True)
700
+ if libc.prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) != 0:
701
+ raise OSError(ctypes.get_errno(), "cannot enable lock broker access")
702
+ stage = "seccomp"
703
+ listener = _seccomp()
704
+ stage = "listener handoff"
705
+ _send_fd(child_channel, listener)
706
+ os.close(listener)
707
+ child_channel.close()
708
+ stage = "candidate cwd"
709
+ os.chdir(root)
710
+ stage = "candidate exec"
711
+ os.execv(command[0], list(command))
712
+ except BaseException as exc:
713
+ message = f"candidate sandbox setup failed during {stage}: {exc}\n".encode(
714
+ "utf-8", "replace"
715
+ )
716
+ try:
717
+ os.write(2, message)
718
+ except OSError:
719
+ pass
720
+ os._exit(126)
721
+
722
+ child_channel.close()
723
+ try:
724
+ listener = _receive_fd(parent_channel)
725
+ except BaseException:
726
+ _kill_and_reap(child_pid)
727
+ raise
728
+ finally:
729
+ parent_channel.close()
730
+ try:
731
+ _drop_credentials(uid, gid)
732
+ except BaseException:
733
+ os.close(listener)
734
+ _kill_and_reap(child_pid)
735
+ raise
736
+ broker_errors: list[BaseException] = []
737
+ if control_fd is not None:
738
+ os.set_blocking(control_fd, False)
739
+
740
+ def broker() -> None:
741
+ try:
742
+ _lock_broker(listener, data)
743
+ except BaseException as exc:
744
+ broker_errors.append(exc)
745
+
746
+ broker_thread = threading.Thread(target=broker, daemon=True)
747
+ broker_thread.start()
748
+ if broker_tid_fd is not None:
749
+ try:
750
+ native_id = broker_thread.native_id
751
+ if native_id is None:
752
+ raise OSError(errno.EIO, "lock broker thread has no native id")
753
+ os.write(
754
+ broker_tid_fd,
755
+ f"{native_id} {child_pid}\n".encode("ascii"),
756
+ )
757
+ except BaseException:
758
+ os.close(listener)
759
+ _kill_and_reap(child_pid)
760
+ broker_thread.join(timeout=1)
761
+ if control_fd is not None:
762
+ os.close(control_fd)
763
+ raise
764
+ finally:
765
+ os.close(broker_tid_fd)
766
+ status = 0
767
+ while True:
768
+ if control_fd is not None:
769
+ try:
770
+ requested = os.read(control_fd, 4096)
771
+ except (BlockingIOError, OSError):
772
+ requested = b""
773
+ for marker in requested:
774
+ requested_signal = {
775
+ ord("T"): signal.SIGTERM,
776
+ ord("K"): signal.SIGKILL,
777
+ }.get(marker)
778
+ if requested_signal is not None:
779
+ try:
780
+ os.kill(child_pid, requested_signal)
781
+ except ProcessLookupError:
782
+ pass
783
+ waited, status = os.waitpid(child_pid, os.WNOHANG)
784
+ if waited == child_pid:
785
+ break
786
+ if broker_errors:
787
+ os.kill(child_pid, signal.SIGKILL)
788
+ _waited, status = os.waitpid(child_pid, 0)
789
+ break
790
+ time.sleep(0.01)
791
+ if control_fd is not None:
792
+ os.close(control_fd)
793
+ os.close(listener)
794
+ broker_thread.join(timeout=1)
795
+ if broker_errors:
796
+ raise OSError(errno.EIO, "candidate lock broker failed") from broker_errors[0]
797
+ # The trusted launcher/broker completed normally. Candidate business exit
798
+ # status is observed through readiness/lifecycle, while a nonzero launcher
799
+ # status remains reserved for audit infrastructure failure.
800
+ os._exit(0)
801
+
802
+
803
+ def main(argv: Sequence[str] | None = None) -> int:
804
+ parser = argparse.ArgumentParser()
805
+ parser.add_argument("--root", type=Path, required=True)
806
+ parser.add_argument("--data", type=Path, required=True)
807
+ parser.add_argument("--bind-port", type=int, required=True)
808
+ parser.add_argument("--connect-port", type=int, action="append", default=[])
809
+ parser.add_argument("--uid", type=int)
810
+ parser.add_argument("--gid", type=int)
811
+ parser.add_argument("--file-size-limit-bytes", type=int)
812
+ parser.add_argument("--read-path", type=Path, action="append", default=[])
813
+ parser.add_argument("--broker-tid-fd", type=int)
814
+ parser.add_argument("--control-fd", type=int)
815
+ parser.add_argument("command", nargs=argparse.REMAINDER)
816
+ arguments = parser.parse_args(argv)
817
+ command = arguments.command
818
+ if command[:1] == ["--"]:
819
+ command = command[1:]
820
+ if not command:
821
+ parser.error("candidate command is required")
822
+ if (arguments.uid is None) != (arguments.gid is None):
823
+ parser.error("uid and gid must be provided together")
824
+ sandbox_exec(
825
+ command,
826
+ root=arguments.root,
827
+ data=arguments.data,
828
+ bind_port=arguments.bind_port,
829
+ connect_ports=set(arguments.connect_port),
830
+ uid=arguments.uid,
831
+ gid=arguments.gid,
832
+ file_size_limit_bytes=arguments.file_size_limit_bytes,
833
+ read_paths=arguments.read_path,
834
+ broker_tid_fd=arguments.broker_tid_fd,
835
+ control_fd=arguments.control_fd,
836
+ )
837
+ return 127
838
+
839
+
840
+ if __name__ == "__main__":
841
+ raise SystemExit(main())
tasks/dooney-bourke/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/dooney-bourke/environment/mailbox/mailbox.py ADDED
@@ -0,0 +1,2433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/dooney-bourke/environment/reference/.websitebench-reference-tls/ca.crt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIDSzCCAjOgAwIBAgIJV1NCSEFSQk9SMA0GCSqGSIb3DQEBCwUAMDExLzAtBgNV
3
+ BAMMJldlYnNpdGVCZW5jaCBIYXJib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H/aVh
19
+ yZycwgzCbkbdMaxyz2Vm/c7PVb3so5Xb98jufp2L9A==
20
+ -----END CERTIFICATE-----
tasks/dooney-bourke/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/dooney-bourke/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
+ FhGWCagN71N9YUjxizYcO1V29FyimABoaBR7BdyMz1DPnsWeCBL6ODnWZilim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eqAr75yi05UD6M2tTov1uGbtg47Q5n6eqjVyy3
26
+ FTYmG+lVbVXjVcOFuUhZxJhELsHulsJ1LRPAJccC0Uci8IZ8rfIZyREn7tKpBJI4
27
+ 4s+BQ5R45Cv3eUi2JU/xuAtK
28
+ -----END PRIVATE KEY-----
tasks/dooney-bourke/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/dooney-bourke/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-dooney-bourke-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/dooney-bourke/environment/reference/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Direct reference adapter
2
+
3
+ The materializer overlays these ABI files on the frozen Dooney & Bourke clone and
4
+ backend. The same assembled bytes form the private oracle implementation; the
5
+ clone and backend are not duplicated in this authoring directory.
tasks/dooney-bourke/environment/reference/backend/model.json ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "offline-clone.backend-model.v1",
3
+ "site_id": "dooney-bourke",
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": "after-email-verification",
52
+ "verification_challenge_storage": "salted-hash",
53
+ "password_reset_enumeration": "indistinguishable-public-response",
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": "Verified local account registration",
77
+ "priority": "p0",
78
+ "category": "authentication",
79
+ "implementation_status": "planned",
80
+ "entities": [
81
+ {
82
+ "name": "pending-registration",
83
+ "identity": "opaque pending id bound to one browser session",
84
+ "owner_scope": "session",
85
+ "persistence": "durable"
86
+ },
87
+ {
88
+ "name": "local-account",
89
+ "identity": "site-local account id and unique normalized email",
90
+ "owner_scope": "account",
91
+ "persistence": "durable"
92
+ }
93
+ ],
94
+ "state_machine": {
95
+ "kind": "challenge-lifecycle",
96
+ "states": [
97
+ "collecting",
98
+ "pending-verification",
99
+ "verified",
100
+ "account-created",
101
+ "expired",
102
+ "locked"
103
+ ],
104
+ "transitions": [
105
+ {
106
+ "from": "collecting",
107
+ "to": "pending-verification",
108
+ "trigger": "validated registration request"
109
+ },
110
+ {
111
+ "from": "pending-verification",
112
+ "to": "verified",
113
+ "trigger": "correct unexpired code within attempt budget"
114
+ },
115
+ {
116
+ "from": "verified",
117
+ "to": "account-created",
118
+ "trigger": "transactional account creation and session rotation"
119
+ },
120
+ {
121
+ "from": "pending-verification",
122
+ "to": "expired",
123
+ "trigger": "challenge expiry"
124
+ },
125
+ {
126
+ "from": "pending-verification",
127
+ "to": "locked",
128
+ "trigger": "verification attempt budget exhausted"
129
+ }
130
+ ]
131
+ },
132
+ "server_authorities": [
133
+ "The server normalizes identity and hashes password and code.",
134
+ "An account is created only after successful verification.",
135
+ "Duplicate normalized email creation is rejected transactionally."
136
+ ],
137
+ "external_effect": "none",
138
+ "journey_ids": [],
139
+ "invariant_ids": [],
140
+ "proofs": {
141
+ "evidence": {},
142
+ "planned": [
143
+ "valid",
144
+ "invalid",
145
+ "duplicate",
146
+ "stale",
147
+ "foreign-owner",
148
+ "unauthorized-role",
149
+ "restart",
150
+ "migration",
151
+ "concurrency"
152
+ ],
153
+ "not_applicable": []
154
+ }
155
+ },
156
+ {
157
+ "id": "account-sign-in",
158
+ "label": "Password-based local account sign-in",
159
+ "priority": "p0",
160
+ "category": "authentication",
161
+ "implementation_status": "planned",
162
+ "entities": [
163
+ {
164
+ "name": "local-account",
165
+ "identity": "site-local account id and normalized email",
166
+ "owner_scope": "account",
167
+ "persistence": "durable"
168
+ }
169
+ ],
170
+ "state_machine": {
171
+ "kind": "entity-lifecycle",
172
+ "states": [
173
+ "signed-out",
174
+ "identified",
175
+ "authenticated",
176
+ "rejected"
177
+ ],
178
+ "transitions": [
179
+ {
180
+ "from": "signed-out",
181
+ "to": "identified",
182
+ "trigger": "normalized email submitted"
183
+ },
184
+ {
185
+ "from": "identified",
186
+ "to": "authenticated",
187
+ "trigger": "constant-time password verification succeeds"
188
+ },
189
+ {
190
+ "from": "identified",
191
+ "to": "rejected",
192
+ "trigger": "credentials are invalid"
193
+ }
194
+ ]
195
+ },
196
+ "server_authorities": [
197
+ "The server verifies salted password hashes.",
198
+ "The server rotates the authenticated session.",
199
+ "Client-selected fixture identity is not authentication."
200
+ ],
201
+ "external_effect": "none",
202
+ "journey_ids": [],
203
+ "invariant_ids": [],
204
+ "proofs": {
205
+ "evidence": {},
206
+ "planned": [
207
+ "valid",
208
+ "invalid",
209
+ "duplicate",
210
+ "stale",
211
+ "foreign-owner",
212
+ "unauthorized-role",
213
+ "restart",
214
+ "migration",
215
+ "concurrency"
216
+ ],
217
+ "not_applicable": []
218
+ }
219
+ },
220
+ {
221
+ "id": "session-lifecycle",
222
+ "label": "Anonymous and authenticated browser sessions",
223
+ "priority": "p0",
224
+ "category": "authentication",
225
+ "implementation_status": "planned",
226
+ "entities": [
227
+ {
228
+ "name": "browser-session",
229
+ "identity": "opaque cookie token with digest persisted at rest",
230
+ "owner_scope": "session",
231
+ "persistence": "durable"
232
+ }
233
+ ],
234
+ "state_machine": {
235
+ "kind": "session-lifecycle",
236
+ "states": [
237
+ "anonymous",
238
+ "authenticated",
239
+ "revoked",
240
+ "expired"
241
+ ],
242
+ "transitions": [
243
+ {
244
+ "from": "anonymous",
245
+ "to": "authenticated",
246
+ "trigger": "successful sign-in or registration rotates session"
247
+ },
248
+ {
249
+ "from": "authenticated",
250
+ "to": "revoked",
251
+ "trigger": "sign-out or security reset"
252
+ },
253
+ {
254
+ "from": "anonymous",
255
+ "to": "expired",
256
+ "trigger": "session expiry"
257
+ },
258
+ {
259
+ "from": "authenticated",
260
+ "to": "expired",
261
+ "trigger": "session expiry"
262
+ }
263
+ ]
264
+ },
265
+ "server_authorities": [
266
+ "Raw session tokens are never stored in the database.",
267
+ "Ownership is resolved from the server-side session record.",
268
+ "Sign-out revokes server-side authority before deleting the cookie."
269
+ ],
270
+ "external_effect": "none",
271
+ "journey_ids": [],
272
+ "invariant_ids": [],
273
+ "proofs": {
274
+ "evidence": {},
275
+ "planned": [
276
+ "valid",
277
+ "invalid",
278
+ "duplicate",
279
+ "stale",
280
+ "foreign-owner",
281
+ "unauthorized-role",
282
+ "restart",
283
+ "migration",
284
+ "concurrency"
285
+ ],
286
+ "not_applicable": []
287
+ }
288
+ },
289
+ {
290
+ "id": "password-recovery",
291
+ "label": "Enumeration-resistant local password recovery",
292
+ "priority": "p0",
293
+ "category": "authentication",
294
+ "implementation_status": "planned",
295
+ "entities": [
296
+ {
297
+ "name": "password-reset-challenge",
298
+ "identity": "opaque reset id bound to one browser session",
299
+ "owner_scope": "session",
300
+ "persistence": "durable"
301
+ },
302
+ {
303
+ "name": "local-account",
304
+ "identity": "nullable concealed account binding",
305
+ "owner_scope": "account",
306
+ "persistence": "durable"
307
+ }
308
+ ],
309
+ "state_machine": {
310
+ "kind": "challenge-lifecycle",
311
+ "states": [
312
+ "requested",
313
+ "verified",
314
+ "consumed",
315
+ "expired",
316
+ "locked"
317
+ ],
318
+ "transitions": [
319
+ {
320
+ "from": "requested",
321
+ "to": "verified",
322
+ "trigger": "correct unexpired code within attempt budget"
323
+ },
324
+ {
325
+ "from": "verified",
326
+ "to": "consumed",
327
+ "trigger": "password is replaced and sessions are revoked"
328
+ },
329
+ {
330
+ "from": "requested",
331
+ "to": "expired",
332
+ "trigger": "challenge expiry"
333
+ },
334
+ {
335
+ "from": "requested",
336
+ "to": "locked",
337
+ "trigger": "verification attempt budget exhausted"
338
+ }
339
+ ]
340
+ },
341
+ "server_authorities": [
342
+ "Known and unknown emails receive indistinguishable public responses.",
343
+ "Only the server binds a reset flow to an account.",
344
+ "Password replacement revokes prior authenticated sessions."
345
+ ],
346
+ "external_effect": "local-only",
347
+ "journey_ids": [],
348
+ "invariant_ids": [],
349
+ "proofs": {
350
+ "evidence": {},
351
+ "planned": [
352
+ "valid",
353
+ "invalid",
354
+ "duplicate",
355
+ "stale",
356
+ "foreign-owner",
357
+ "unauthorized-role",
358
+ "restart",
359
+ "migration",
360
+ "concurrency"
361
+ ],
362
+ "not_applicable": []
363
+ }
364
+ },
365
+ {
366
+ "id": "email-delivery",
367
+ "label": "Truthful local verification and recovery mail outbox",
368
+ "priority": "p0",
369
+ "category": "communication",
370
+ "implementation_status": "planned",
371
+ "entities": [
372
+ {
373
+ "name": "mail-outbox-entry",
374
+ "identity": "site-local outbox id and purpose-bound flow id",
375
+ "owner_scope": "system",
376
+ "persistence": "durable"
377
+ }
378
+ ],
379
+ "state_machine": {
380
+ "kind": "delivery-lifecycle",
381
+ "states": [
382
+ "local-only",
383
+ "smtp-pending",
384
+ "smtp-sent",
385
+ "smtp-failed"
386
+ ],
387
+ "transitions": [
388
+ {
389
+ "from": "local-only",
390
+ "to": "smtp-pending",
391
+ "trigger": "operator enables complete explicit SMTP configuration"
392
+ },
393
+ {
394
+ "from": "smtp-pending",
395
+ "to": "smtp-sent",
396
+ "trigger": "SMTP transport confirms delivery handoff"
397
+ },
398
+ {
399
+ "from": "smtp-pending",
400
+ "to": "smtp-failed",
401
+ "trigger": "delivery attempt fails or ceiling is reached"
402
+ },
403
+ {
404
+ "from": "smtp-failed",
405
+ "to": "smtp-pending",
406
+ "trigger": "bounded idempotent retry below the delivery ceiling"
407
+ }
408
+ ]
409
+ },
410
+ "server_authorities": [
411
+ "Offline mode records LOCAL_ONLY and never claims external delivery.",
412
+ "SMTP is disabled unless every required setting is present.",
413
+ "Claim, retry, and startup replay share one delivery ceiling."
414
+ ],
415
+ "external_effect": "local-only",
416
+ "journey_ids": [],
417
+ "invariant_ids": [],
418
+ "proofs": {
419
+ "evidence": {},
420
+ "planned": [
421
+ "valid",
422
+ "invalid",
423
+ "duplicate",
424
+ "stale",
425
+ "foreign-owner",
426
+ "unauthorized-role",
427
+ "restart",
428
+ "migration",
429
+ "concurrency"
430
+ ],
431
+ "not_applicable": []
432
+ }
433
+ }
434
+ ]
435
+ }
tasks/dooney-bourke/environment/reference/backend/runtime.json ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "database": {
3
+ "data_dir": "data",
4
+ "engine": "sqlite",
5
+ "filename": "dooney-bourke.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
+ "purposes": {
31
+ "password-reset": {
32
+ "body": "Your password reset code is ${code}.",
33
+ "expiry": "This code expires in ${minutes} minutes.",
34
+ "footer": "Ignore this message if you did not contact Dooney & Bourke.",
35
+ "lead": "A password reset was requested for Dooney & Bourke.",
36
+ "required_variables": [
37
+ "code",
38
+ "minutes"
39
+ ],
40
+ "secret_variables": [
41
+ "code"
42
+ ],
43
+ "subject": "Reset your Dooney & Bourke password",
44
+ "template_id": "dooney-bourke.password-reset.v1"
45
+ },
46
+ "registration": {
47
+ "body": "Your verification code is ${code}.",
48
+ "expiry": "This code expires in ${minutes} minutes.",
49
+ "footer": "This code is only for Dooney & Bourke.",
50
+ "lead": "Finish creating your Dooney & Bourke account.",
51
+ "required_variables": [
52
+ "code",
53
+ "minutes"
54
+ ],
55
+ "secret_variables": [
56
+ "code"
57
+ ],
58
+ "subject": "Verify your Dooney & Bourke account",
59
+ "template_id": "dooney-bourke.registration.v1"
60
+ }
61
+ },
62
+ "sender": {
63
+ "address_env": "RESEND_FROM_EMAIL",
64
+ "display_name": "Dooney & Bourke"
65
+ }
66
+ },
67
+ "payments": {
68
+ "currency": "CAD",
69
+ "default_adapter": "local-sandbox",
70
+ "enabled": false,
71
+ "local_sandbox": {
72
+ "scenarios": [
73
+ {
74
+ "display_label": "Simulated approval",
75
+ "id": "sandbox-approved",
76
+ "outcome": "approved"
77
+ },
78
+ {
79
+ "display_label": "Simulated decline",
80
+ "id": "sandbox-declined",
81
+ "outcome": "declined"
82
+ },
83
+ {
84
+ "display_label": "Simulated retry",
85
+ "id": "sandbox-retry",
86
+ "outcome": "retryable"
87
+ }
88
+ ]
89
+ },
90
+ "stripe_test": null
91
+ },
92
+ "schema_version": "websitebench.site-backend-runtime.v1",
93
+ "session": {
94
+ "host_only": true,
95
+ "http_only": true,
96
+ "same_site": "Lax",
97
+ "secure": true
98
+ },
99
+ "site": {
100
+ "id": "dooney-bourke",
101
+ "label": "Dooney & Bourke",
102
+ "public_origin": "https://dooney-bourke.offline.invalid"
103
+ }
104
+ }
tasks/dooney-bourke/environment/reference/clone/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Dooney & Bourke WebsiteBench offline clone
2
+
3
+ This loopback-only runtime is a network-closed reconstruction based on current public source evidence. Catalog, cart, SAVE10, checkout review, local account, wishlist, order tracking, help and recovery states are deterministic local behavior. It does not send email, submit support requests, charge payment, place an order, or contact the source at runtime.
4
+
5
+ The generated runtime contract is `../backend/runtime.json`; its payment adapter is `local-sandbox`, and each launch receives an isolated `DATA_DIR`.
tasks/dooney-bourke/environment/reference/clone/app.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import html
6
+ import ipaddress
7
+ import mimetypes
8
+ import os
9
+ import re
10
+ import sys
11
+ from http import cookies
12
+ from pathlib import Path
13
+ from urllib.parse import parse_qs, quote, urlsplit
14
+ from wsgiref.simple_server import make_server
15
+
16
+ from websitebench.local_clone_auth import AuthError
17
+ from websitebench.site_backend import PaymentError
18
+
19
+ ROOT=Path(__file__).resolve().parent
20
+ sys.path.insert(0,str(ROOT))
21
+ from backend.site_backend_integration import open_site_services
22
+ from backend import business
23
+
24
+ BACKEND, AUTH = open_site_services()
25
+ business.initialize(BACKEND)
26
+ try:
27
+ AUTH.seed_account(subject_id="dooney-seeded-shopper", email="shopper@example.test", display_name="Avery Shopper", password="WebsiteBench!041")
28
+ except Exception:
29
+ pass
30
+
31
+ def esc(v): return html.escape(str(v), quote=True)
32
+ def money(n): return f"${n/100:,.2f}"
33
+ def form(environ):
34
+ try: size=min(int(environ.get("CONTENT_LENGTH") or 0),32768)
35
+ except ValueError: size=0
36
+ return {k:v[-1] for k,v in parse_qs(environ["wsgi.input"].read(size).decode("utf-8","replace"),keep_blank_values=True).items()}
37
+ def owner(session): return AUTH.session_owner_digest(session)
38
+
39
+ SECURITY_HEADERS=(
40
+ ("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"),
41
+ ("X-Content-Type-Options", "nosniff"),
42
+ ("Referrer-Policy", "same-origin"),
43
+ ("X-Frame-Options", "DENY"),
44
+ ("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()"),
45
+ )
46
+ STATIC_CACHE_HEADERS=(("Cache-Control", "public, max-age=3600"),)
47
+
48
+ def request_origin_allowed(environ):
49
+ origin=environ.get("HTTP_ORIGIN")
50
+ if not origin:
51
+ return True
52
+ parsed=urlsplit(origin); host=environ.get("HTTP_HOST",""); scheme=environ.get("wsgi.url_scheme","http").lower()
53
+ return parsed.scheme==scheme and parsed.netloc==host and parsed.username is None and parsed.password is None and not parsed.path and not parsed.query and not parsed.fragment
54
+
55
+ def safe_return_path(environ,default="/collections/bags"):
56
+ referer=environ.get("HTTP_REFERER","")
57
+ if not referer:
58
+ return default
59
+ parsed=urlsplit(referer); host=environ.get("HTTP_HOST","")
60
+ if parsed.scheme and (parsed.scheme not in {"http","https"} or parsed.netloc!=host):
61
+ return default
62
+ path=parsed.path or "/"
63
+ if not path.startswith("/") or path.startswith("//") or "\\" in path:
64
+ return default
65
+ return path+(f"?{parsed.query}" if parsed.query else "")
66
+
67
+ def secure_cookie_context(environ):
68
+ if environ.get("wsgi.url_scheme", "http").lower() == "https":
69
+ return True
70
+ hostname=(urlsplit(f"//{environ.get('HTTP_HOST', '')}").hostname or "").lower()
71
+ if hostname == "localhost" or hostname.endswith(".localhost"):
72
+ return True
73
+ try:
74
+ return ipaddress.ip_address(hostname).is_loopback
75
+ except ValueError:
76
+ return False
77
+
78
+ def session_cookie_name(environ):
79
+ return "__Host-wb-dooney-bourke" if secure_cookie_context(environ) else "wb-dooney-bourke-local"
80
+
81
+ def session_cookie_header(environ,session,max_age=None):
82
+ value=f"{session_cookie_name(environ)}={session}; Path=/; HttpOnly; SameSite=Lax"
83
+ if secure_cookie_context(environ):
84
+ value+="; Secure"
85
+ if max_age is not None:
86
+ value+=f"; Max-Age={max_age}"
87
+ return ("Set-Cookie",value)
88
+
89
+ def response(start,status,body,headers=()):
90
+ payload=body if isinstance(body,bytes) else body.encode()
91
+ start_response=f"{status} { {200:'OK',302:'Found',303:'See Other',400:'Bad Request',403:'Forbidden',404:'Not Found',405:'Method Not Allowed'}.get(status,'OK')}"
92
+ start(start_response,[*headers,*SECURITY_HEADERS,("Content-Length",str(len(payload)))])
93
+ return [payload]
94
+ def redirect(start,path,headers=()): return response(start,303,b"",tuple(headers)+(("Location",path),))
95
+
96
+ TOP_LOGO='<img class="logo" src="/static/assets/icons/dooney-logo-black.svg" alt="Dooney &amp; Bourke">'
97
+ LOGO='<img class="logo" src="/static/source/main-logo.svg" alt="Dooney &amp; Bourke">'
98
+ LOVE_LOGO='<img class="love-logo" src="/static/source/love-logo.svg" alt="I Love Dooney">'
99
+ MENU_ICON='''<svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M3 12H21M3 6H21M3 18H21" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'''
100
+ SEARCH_ICON='''<svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M21 21L15.0001 15M17 10C17 13.866 13.866 17 10 17C6.13401 17 3 13.866 3 10C3 6.13401 6.13401 3 10 3C13.866 3 17 6.13401 17 10Z" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'''
101
+ BAG_ICON='''<svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M16.0004 9V6C16.0004 3.79086 14.2095 2 12.0004 2C9.79123 2 8.00037 3.79086 8.00037 6V9M3.59237 10.352L2.99237 16.752C2.82178 18.5717 2.73648 19.4815 3.03842 20.1843C3.30367 20.8016 3.76849 21.3121 4.35839 21.6338C5.0299 22 5.94374 22 7.77142 22H16.2293C18.057 22 18.9708 22 19.6423 21.6338C20.2322 21.3121 20.6971 20.8016 20.9623 20.1843C21.2643 19.4815 21.179 18.5717 21.0084 16.752L20.4084 10.352C20.2643 8.81535 20.1923 8.04704 19.8467 7.46616C19.5424 6.95458 19.0927 6.54511 18.555 6.28984C17.9444 6 17.1727 6 15.6293 6L8.37142 6C6.82806 6 6.05638 6 5.44579 6.28984C4.90803 6.54511 4.45838 6.95458 4.15403 7.46616C3.80846 8.04704 3.73643 8.81534 3.59237 10.352Z" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'''
102
+ def header(cart_count, authenticated=False):
103
+ nav=[("BAGS","/collections/bags"),("ACCESSORIES","/collections/accessories"),("COLLECTIONS","/collections/all"),("SPORTS","/pages/sports"),("SHOES","/collections/shoes"),("UNDER $100","/collections/under-100"),("SALE","/collections/sale")]
104
+ count=f'<sup>{cart_count}</sup>' if cart_count else ''
105
+ return f'''<a class="skip" href="#main">Skip to content</a><div class="brandbar"><a href="/">{TOP_LOGO}</a><b>{LOVE_LOGO}</b><span>● Help Center &nbsp; 🇨🇦 Canada</span></div><div class="offer">Dooney Hour: Up To 60% Off Starts Now &nbsp; <a href="/collections/sale">(Details)</a></div><header><button class="mobile-menu" aria-label="Menu" aria-controls="primary" aria-expanded="false">{MENU_ICON}</button><a href="/">{LOGO}</a><nav id="primary">{''.join(f'<a href="{u}">{t}</a>' for t,u in nav)}</nav><div class="icons"><button class="search-toggle" aria-label="Open search">{SEARCH_ICON}</button><a href="/account" aria-label="Account">♙</a><a href="/cart" aria-label="Bag">{BAG_ICON}{count}</a></div><form class="quick-search" action="/search"><input name="q" type="search" placeholder="Search Dooney &amp; Bourke" aria-label="Search"><button>SEARCH</button></form></header><div class="luxury">Discover Luxury for Less &nbsp; <a href="/collections/sale">SHOP NOW</a></div>'''
106
+
107
+ FOOTER='''<footer><div><h2>Timeless Styles.<br>Exceptional Craftsmanship.<br>Unconditional Guarantee.</h2></div><div><h3>Get In Touch</h3><a href="/pages/contact">Contact Us</a><a href="/pages/stores">Store Locator</a><a href="/pages/track-your-order">Track Your Order</a><a href="/pages/help">Help Center</a><a href="/account">Register My Dooney</a></div><div><h3>Orders &amp; Payments</h3><a href="/pages/orders-payments">Orders &amp; Payments</a><a href="/pages/shipping">Shipping</a><a href="/pages/refund-policy">Returns</a><a href="/pages/repair">Repair Request</a></div><div><h3>Our Brand</h3><a href="/pages/about">About Us</a><a href="/pages/guarantee">The Dooney Guarantee</a><a href="/collections/all">Shop All</a></div><div class="newsletter"><h3>Stay In The Know</h3><p>Sign up for the latest product stories &amp; more.</p><div class="fake-input">Email <b>SUBMIT</b></div><small>This offline clone never sends newsletter email.</small></div><small>© Copyright 2026 Dooney &amp; Bourke. Local WebsiteBench simulation.</small></footer>'''
108
+
109
+ COOKIE_BANNER='''<section class="cookie-banner" role="dialog" aria-label="Cookie preferences"><button class="cookie-close" data-cookie-choice="decline" aria-label="Close cookie preferences">✕</button><div class="cookie-monogram" aria-hidden="true"><img src="/static/source/cookie-logo.png" alt=""></div><p>Please select whether you consent to our use of cookies and related technologies (“Cookies”), as described in our privacy policy. Expand each section below for more information. You can return at any time from the same web browser to update your preferences. Please note that resetting your browser’s cookies will reset your preferences. <a href="/pages/privacy">Learn more</a></p><div class="cookie-actions"><button class="preferences" data-cookie-choice="preferences">Preferences</button><button data-cookie-choice="accept">Accept</button><button data-cookie-choice="decline">Decline</button></div></section>'''
110
+
111
+ NEWSLETTER_DIALOG='''<div class="newsletter-backdrop"><section class="newsletter-dialog" role="dialog" aria-modal="true" aria-labelledby="newsletter-title"><button class="newsletter-close" data-close-newsletter aria-label="Close newsletter signup">×</button><div class="newsletter-copy"><h2 id="newsletter-title">Be the First to Know</h2><p>Subscribe to be the first to discover new<br>arrivals and receive exclusive offers from<br>Dooney &amp; Bourke.</p><label class="visually-hidden" for="newsletter-email">Email</label><input id="newsletter-email" type="email" placeholder="Email"><button type="button" data-newsletter-continue>Continue</button><small class="newsletter-status" role="status"></small></div><img src="/static/assets/images/home/newsletter-source.webp.b64" alt="Dooney &amp; Bourke leather bag styling"></section></div>'''
112
+
113
+ def page(title,body,session,status=200):
114
+ c=business.cart(BACKEND,owner(session)); auth=AUTH.resolve_session(session) or {}
115
+ newsletter=NEWSLETTER_DIALOG if title=="Dooney & Bourke | Iconic American Leather Goods" else ""
116
+ return status,f'''<!doctype html><html lang="en-CA"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{esc(title)}</title><link rel="stylesheet" href="/static/site.css"><script src="/static/site.js" defer></script></head><body>{header(c['quantity'],auth.get('authenticated',False))}<main id="main">{body}</main>{FOOTER}{newsletter}{COOKIE_BANNER}</body></html>'''
117
+
118
+ def cards(products,wished):
119
+ def one(p):
120
+ rating=f"★ {p['rating']}" if p.get('rating') else "Source-observed item"
121
+ reviews=f" ({p['reviews']} Reviews)" if p.get('reviews') else ""
122
+ compare=f" <del>{money(p['compare_minor'])}</del>" if p['compare_minor']>p['price_minor'] else ""
123
+ return f'''<article class="card" data-category="{esc(p.get('category','Bags'))}"><form action="/wishlist/toggle" method="post"><input type="hidden" name="handle" value="{esc(p['handle'])}"><button aria-label="{'Remove from' if p['handle'] in wished else 'Add to'} wishlist">{'♥' if p['handle'] in wished else '♡'}</button></form><a href="/products/{esc(p['handle'])}"><div class="bag-picture"><img src="{esc(p['asset'])}" alt="{esc(p['title'])}" loading="lazy"></div><small>{esc(p.get('category','Bags').upper())}</small><h3>{esc(p['title'])}</h3><p>{rating}{reviews}</p><b>{money(p['price_minor'])}</b>{compare}</a></article>'''
124
+ return ''.join(one(p) for p in products)
125
+
126
+ def home(session):
127
+ wished=business.wishlist(BACKEND,owner(session))
128
+ body=f'''<section class="hero"><div><small>UP TO 40% OFF</small><h1>The Private Sale</h1><p>Step inside for special savings on timeless favorites you know and love.</p><a class="outline" href="/collections/sale">SHOP NOW</a></div><picture class="hero-media"><source media="(max-width: 760px)" srcset="/static/source/home-offer-mobile.webp"><img src="/static/assets/images/home/private-sale-desktop.webp" alt="The Private Sale"></picture></section><section class="intro"><p>EST. 1975</p><h2>Made for a Lifetime</h2><p>Iconic American design, exceptional Italian leather, and bags made to be carried every day.</p></section><section class="featured"><h2>Best Sellers</h2><div class="grid">{cards(business.CATALOG[:4],wished)}</div></section>'''
129
+ return page("Dooney & Bourke | Iconic American Leather Goods",body,session)
130
+
131
+ def catalog(session,path,query):
132
+ q=query.get("q",[""])[-1].strip(); sort=query.get("sort",["featured"])[-1]; color=query.get("color",[""])[-1]; price=query.get("price",[""])[-1]
133
+ base_products=list(business.ALL_PRODUCTS if path=="/search" else business.CATEGORY_CATALOGS.get(path,business.CATALOG)); products=list(base_products)
134
+ available_colors=sorted({c for p in base_products for c in p['colors']})
135
+ if path=="/search": products=[p for p in products if q.casefold() in (p['title']+' '+p['style']).casefold()]
136
+ if color: products=[p for p in products if color in p['colors']]
137
+ if price=="under-200": products=[p for p in products if p['price_minor']<20000]
138
+ if sort=="price-asc": products.sort(key=lambda p:p['price_minor'])
139
+ if sort=="price-desc": products.sort(key=lambda p:p['price_minor'],reverse=True)
140
+ title=(f"Search results for: '{q}'" if path=="/search" else {"/collections/accessories":"Shop All Accessories","/collections/sale":"Sale","/collections/shoes":"Shoes","/collections/under-100":"Under $100","/collections/all":"Products","/pages/sports":"Sports"}.get(path,"Shop All Bags"))
141
+ filters=f'''<form class="filters" method="get">{f'<input type="hidden" name="q" value="{esc(q)}">' if q else ''}<label>COLOR<select name="color"><option value="">All colors</option>{''.join(f'<option {"selected" if color==c else ""}>{esc(c)}</option>' for c in available_colors)}</select></label><label>PRICE<select name="price"><option value="">All prices</option><option value="under-200" {'selected' if price=='under-200' else ''}>Under $200</option></select></label><label>SORT BY<select name="sort"><option value="featured">Featured</option><option value="price-asc" {'selected' if sort=='price-asc' else ''}>Price, low to high</option><option value="price-desc" {'selected' if sort=='price-desc' else ''}>Price, high to low</option></select></label><button>APPLY</button></form>'''
142
+ if not products:
143
+ content=f'''<section class="catalog"><h1>{esc(title)}</h1><p class="count">0 results</p>{filters}<div class="empty"><h2>No results found</h2><p>We couldn't find anything for “{esc(q)}”. Check the spelling or explore our bags.</p><a class="black" href="/collections/bags">SHOP BAGS</a></div></section>'''
144
+ else: content=f'''<section class="catalog"><h1>{esc(title)}</h1><p class="count">{len(products)} results</p>{filters}<div class="grid">{cards(products,business.wishlist(BACKEND,owner(session)))}</div></section>'''
145
+ return page(f"{title} – Dooney & Bourke",content,session)
146
+
147
+ def product_page(session,handle,query):
148
+ p=business.find_product_by_handle(handle)
149
+ if p is None:
150
+ return page("Page Not Found – Dooney & Bourke",'''<section class="not-found"><span>404</span><h1>Oops! Page not found</h1><p>We couldn't find that product.</p><a class="black" href="/collections/bags">SHOP BAGS</a><a href="/">Continue Shopping</a></section>''',session,404)
151
+ color=query.get("color",[p['colors'][0]])[-1]
152
+ if color not in p['colors']: color=p['colors'][0]
153
+ palette=("#b96036","#f6e9d0","#ca3327","#0a0b0c","#3475b4","#402a16","#222d34","#e4e4df","#8d1e1a","#b9a07d","#1c1b37")
154
+ swatches=''.join(f'<a class="swatch {"selected" if c==color else ""}" style="--c:{palette[index] if index < len(palette) else "#777"}" href="?color={quote(c)}" aria-label="{esc(c)}" title="{esc(c)}"></a>' for index,c in enumerate(p['colors']))
155
+ main_asset=p['asset']; lifestyle="/static/assets/images/product/pebble-crossbody-lifestyle.webp"
156
+ gallery_extra='''<div><img src="/static/assets/images/product/pebble-crossbody-alt1.webp" alt="Pebble Grain Crossbody detail"></div><div><img src="/static/assets/images/product/pebble-crossbody-alt2.webp" alt="Pebble Grain Crossbody interior"></div>''' if p is business.PRODUCT else ''
157
+ gallery_second=f'''<div class="lifestyle"><img src="{esc(lifestyle)}" alt="{esc(p['title'])} alternate view"></div>''' if p is business.PRODUCT else ''
158
+ rating=f'''<p>★ <b>{p['rating']}</b>{f" &nbsp; {p['reviews']} Reviews" if p.get('reviews') else ''}</p>''' if p.get('rating') else ''
159
+ compare=f''' <del>{money(p['compare_minor'])}</del>''' if p['compare_minor']>p['price_minor'] else ''
160
+ category=p.get('category','Bags'); category_path={"Accessories":"/collections/accessories","Shoes":"/collections/shoes","Under $100":"/collections/under-100","Sale":"/collections/sale","Sports":"/pages/sports"}.get(category,"/collections/bags")
161
+ detail_copy="This source-observed item is represented with its current category image, title, price, style, and available option in the local WebsiteBench catalog."
162
+ if p is business.PRODUCT: detail_copy="This top-rated crossbody, made from pebble leather with a natural grain that hides signs of daily wear, is a go-to bag for everyday life that you can dress up or down."
163
+ badge="BEST SELLER" if p is business.PRODUCT else category.upper()
164
+ body=f'''<div class="crumbs"><a href="/">Home</a> › <a href="{category_path}">{esc(category)}</a> › {esc(p['title'])}</div><section class="product"><div class="gallery"><div><img src="{esc(main_asset)}" alt="{esc(p['title'])} in {esc(color)}"></div>{gallery_second}{gallery_extra}</div><div class="product-info"><small class="badge">{esc(badge)}</small><h1>{esc(p['title'])}</h1>{rating}<hr><div class="meta"><b>Color: <span>{esc(color)}</span></b><span>Style #: {esc(p['style'])}</span></div><h3 class="sale">THE PRIVATE SALE</h3><p class="price"><b>{money(p['price_minor'])}</b>{compare}</p><div class="swatches">{swatches}</div><p class="price"><b>{money(p['price_minor'])}</b>{compare} <span>In stock</span></p><form action="/cart/add" method="post"><input type="hidden" name="handle" value="{esc(p['handle'])}"><input type="hidden" name="color" value="{esc(color)}"><button class="black" name="add">ADD TO BAG</button></form><div class="benefits"><span><img src="/static/assets/icons/shipping.svg" alt="">Flat Rate Shipping</span><span><img src="/static/assets/icons/contact.svg" alt="">Easy Returns</span><span><img src="/static/assets/icons/warranty.svg" alt="">Unconditional Guarantee</span></div></div></section><section class="details"><h2>Product Details</h2><p>{detail_copy}</p><details open><summary>DETAILS</summary><ul><li>Current source-observed category: {esc(category)}.</li><li>Style #: {esc(p['style'])}.</li><li>Selected option: {esc(color)}.</li><li>Local offline inventory status: In stock.</li></ul></details><section class="reviews"><h2>Reviews</h2><p>{'★★★★★ “This is my first crossbody. Absolutely love it. Perfect size.”' if p is business.PRODUCT else 'Rating and review details are shown only when observed in the scoped source evidence.'}</p></section></section>'''
165
+ return page(f"{p['title']} – Dooney & Bourke",body,session)
166
+
167
+ def cart_page(session,message=""):
168
+ c=business.cart(BACKEND,owner(session)); totals=business.totals(c)
169
+ if not c['quantity']:
170
+ removed_product=business.product_by_handle(c.get('product_handle',business.PRODUCT['handle']))
171
+ restore=f'''<form action="/cart/restore" method="post"><p>Removed: {esc(removed_product['title'])}</p><button>RESTORE ITEM</button></form>''' if c['removed_quantity'] else ''
172
+ return page("Shopping Bag – Dooney & Bourke",f'''<section class="cart"><h1>Shopping Bag ( 0 )</h1>{f'<p class="error" role="alert">{esc(message)}</p>' if message else ''}<div class="empty"><h2>Your Shopping Bag is Empty</h2><p>Explore timeless styles and add a favorite.</p>{restore}<a class="black" href="/collections/bags">CONTINUE SHOPPING</a></div></section>''',session)
173
+ promo='SAVE10 applied — 10% off your local bag.' if c['promotion']=='SAVE10' else message
174
+ p=business.product_by_handle(c.get('product_handle',business.PRODUCT['handle'])); compare=f''' <del>{money(p['compare_minor'])}</del>''' if p['compare_minor']>p['price_minor'] else ''
175
+ body=f'''<section class="cart"><h1>Shopping Bag ( {c['quantity']} )</h1>{f'<p class="notice" role="status">{esc(promo)}</p>' if promo else ''}<div class="cart-layout"><article class="lineitem"><div><img src="{p['asset']}" alt="{esc(p['title'])}"></div><div><h2>{esc(p['title'])}</h2><b>{money(p['price_minor'])}</b>{compare}<p>Color: {esc(c['color'])}</p><p>Style #: {esc(p['style'])}</p><p>In stock</p><form action="/cart/update" method="post"><label>Quantity <input type="number" min="1" max="9" name="quantity" value="{c['quantity']}"></label><button>UPDATE</button></form><form action="/cart/remove" method="post"><button class="link">Remove</button></form></div></article><aside class="summary"><h2>Order Summary</h2><p>Subtotal <b>{money(totals['subtotal'])} CAD</b></p>{f'<p>Discount (SAVE10) <b>−{money(totals["discount"])} CAD</b></p>' if totals['discount'] else ''}<p>Shipping <span>Calculated at checkout</span></p><hr><p class="total">Total <b>{money(totals['total'])} CAD</b></p><form action="/cart/promotion" method="post"><label>Discount code<input name="code" autocomplete="off" placeholder="Discount code"></label><button>APPLY</button></form><a class="black" href="/checkout">CHECKOUT</a><details><summary>Add an order note</summary><textarea aria-label="Order note"></textarea></details></aside></div></section>'''
176
+ return page("Shopping Bag – Dooney & Bourke",body,session)
177
+
178
+ def checkout_page(session,errors=None,sandbox=None):
179
+ c=business.cart(BACKEND,owner(session)); saved=business.checkout(BACKEND,owner(session)); errors=errors or {}
180
+ t=business.checkout_amounts(c,saved.get('shipping','Standard'))
181
+ sandbox_copy=''
182
+ if sandbox:
183
+ sandbox_role='alert' if sandbox['tone']=='error' else 'status'
184
+ sandbox_copy=f'''<p class="sandbox-status {esc(sandbox['tone'])}" role="{sandbox_role}"><b>{esc(sandbox['label'])}</b><br>{esc(sandbox['message'])}</p>'''
185
+ if not c['quantity']: return page("Checkout – Dooney & Bourke",f'<section class="empty"><h1>Your bag is empty</h1>{sandbox_copy}<a href="/collections/bags">Return to shopping</a></section>',session)
186
+ def field(name,label,typ="text",optional=False):
187
+ val=saved.get('contact_email' if name=='email' else name,""); err=errors.get(name,"")
188
+ described=f' aria-describedby="error-{name}"' if err else ''
189
+ return f'''<label class="field {'invalid' if err else ''}" for="field-{name}">{label}{' (optional)' if optional else ''}<input id="field-{name}" type="{typ}" name="{name}" value="{esc(val)}"{' aria-invalid="true"' if err else ''}{described}></label>{f'<small class="error" id="error-{name}">{esc(err)}</small>' if err else ''}'''
190
+ review=saved.get('state')=='review'
191
+ province=saved.get('province','Ontario'); shipping=saved.get('shipping','Standard')
192
+ country_error=errors.get('country',''); province_error=errors.get('province',''); shipping_error=errors.get('shipping','')
193
+ left=f'''<a class="checkout-logo" href="/">{LOGO}</a><h1 class="visually-hidden">Checkout</h1>{sandbox_copy}<h2>Contact</h2>{field('email','Email','email')}<h2>Delivery</h2><label class="field {'invalid' if country_error else ''}" for="field-country">Country/Region<select id="field-country" name="country"{' aria-describedby="error-country" aria-invalid="true"' if country_error else ''}><option value="Canada">Canada</option></select></label>{f'<small class="error" id="error-country">{esc(country_error)}</small>' if country_error else ''}<div class="two">{field('first_name','First name')}{field('last_name','Last name')}</div>{field('address','Address')}{field('apartment','Apartment, suite, etc.',optional=True)}<div class="three">{field('city','City')}<label class="field {'invalid' if province_error else ''}" for="field-province">Province<select id="field-province" name="province"{' aria-describedby="error-province" aria-invalid="true"' if province_error else ''}>{''.join(f'<option value="{p}" {"selected" if province==p else ""}>{p}</option>' for p in ("Ontario","British Columbia","Quebec"))}</select></label>{f'<small class="error" id="error-province">{esc(province_error)}</small>' if province_error else ''}{field('postal_code','Postal code')}</div>{field('phone','Phone','tel')}<h2>Shipping method</h2><fieldset class="shipping-options"{' aria-describedby="error-shipping"' if shipping_error else ''}><legend class="visually-hidden">Shipping method</legend><label class="shipping"><input type="radio" name="shipping" value="Standard"{' checked' if shipping!='Express' else ''}> Standard shipping <b>FREE</b></label><label class="shipping"><input type="radio" name="shipping" value="Express"{' checked' if shipping=='Express' else ''}> Express shipping <b>$20.00</b></label></fieldset>{f'<small class="error" id="error-shipping">{esc(shipping_error)}</small>' if shipping_error else ''}<button class="black">REVIEW ORDER</button>'''
194
+ action="/checkout/review"
195
+ if review:
196
+ action="/checkout/sandbox"
197
+ shipping_copy="Express · $20.00" if shipping=='Express' else "Standard · FREE"
198
+ left=f'''<a class="checkout-logo" href="/">{LOGO}</a><h1>Review your order</h1><div class="review-box"><p><b>Contact</b> {esc(saved.get('contact_email',''))}</p><p><b>Deliver to</b> {esc(saved.get('first_name',''))} {esc(saved.get('last_name',''))}, {esc(saved.get('address',''))}, {esc(saved.get('city',''))}, {esc(saved.get('province',''))} {esc(saved.get('postal_code',''))}</p><p><b>Shipping</b> {shipping_copy}</p></div><p class="simulation">Local sandbox review only. No order has been placed and no payment details are collected.</p><a class="outline" href="/checkout?edit=1">EDIT DELIVERY</a><label class="sandbox-choice">Local payment outcome<select name="scenario"><option value="sandbox-approved">Simulated approval</option><option value="sandbox-declined">Simulated decline</option><option value="sandbox-retry">Simulated retry</option></select></label><button class="black">RUN LOCAL SANDBOX</button>{sandbox_copy}'''
199
+ p=business.product_by_handle(c.get('product_handle',business.PRODUCT['handle']))
200
+ right=f'''<aside class="checkout-summary"><div class="checkout-item"><div><img src="{p['asset']}" alt="{esc(p['title'])}"></div><span><b>{esc(p['title'])}</b><br>{esc(c['color'])}<br>{c['quantity']} × {money(p['price_minor'])}</span><b>{money(t['subtotal'])}</b></div><p>Subtotal <b>{money(t['subtotal'])}</b></p>{f'<p>Discount SAVE10 <b>−{money(t["discount"])}</b></p>' if t['discount'] else ''}<p>Shipping <b>{money(t['shipping']) if t['shipping'] else 'FREE'}</b></p><hr><p class="total">Total <small>CAD</small> <b>{money(t['total'])}</b></p>{f'<strong>TOTAL SAVINGS {money(t["discount"])}</strong>' if t['discount'] else ''}</aside>'''
201
+ return page("Checkout – Dooney & Bourke",f'''<section class="checkout"><form method="post" action="{action}" novalidate><div>{left}</div>{right}</form></section>''',session)
202
+
203
+ def account_page(session,path,message="",local_code=""):
204
+ state=AUTH.resolve_session(session) or {}; account=state.get('account')
205
+ if account:
206
+ order=business.order_for_email(BACKEND,account['email_normalized'])
207
+ order_summary=f'''<article class="order"><b>DB-100041 · {esc(order['status'])}</b><p>Pebble Grain Crossbody · Caramel · $196.35 CAD</p><a href="/account/orders/DB-100041">View details</a> · <a href="/pages/refund-policy">Start a local return</a></article>''' if order else '<p>No local orders found.</p>'
208
+ body=f'''<section class="account"><h1>Welcome, {esc(account['display_name'])}</h1><p>{esc(account['email_normalized'])}</p><nav><a href="/account/orders">Order History</a><a href="/account/wishlist">Saved Items</a><form action="/account/logout" method="post"><button>LOG OUT</button></form></nav><h2>Recent order</h2>{order_summary}<a href="/collections/bags">Back to Bags</a></section>'''
209
+ if path.endswith('wishlist'):
210
+ items=[p for p in business.CATALOG if p['handle'] in business.wishlist(BACKEND,owner(session))]
211
+ body=f'''<section class="account"><h1>Saved Items</h1><div class="grid">{cards(items,business.wishlist(BACKEND,owner(session))) if items else '<p>No saved items yet.</p>'}</div><a href="/collections/bags">Shop Bags</a></section>'''
212
+ elif path=="/account/orders/DB-100041":
213
+ if not order:
214
+ return page("Order not found – Dooney & Bourke",'<section class="account"><h1>Order not found</h1><a href="/account/orders">Return to order history</a></section>',session,404)
215
+ cancel_form='''<form action="/account/orders/DB-100041/cancel" method="post"><button class="outline">CANCEL LOCAL ORDER</button></form>''' if order['status']!='Cancelled' else ''
216
+ body=f'''<section class="account order-detail"><p><a href="/account/orders">← Order History</a></p><h1>Order DB-100041</h1>{f'<p class="notice" role="status">{esc(message)}</p>' if message else ''}<p class="order-state"><b>{esc(order['status'])}</b> · Seeded local order</p><article class="order"><h2>Pebble Grain Crossbody</h2><p>Color: Caramel · Quantity: 1</p><p>Total: $196.35 CAD</p><a href="/pages/track-your-order">TRACK PACKAGE</a></article><div class="order-actions">{cancel_form}<form action="/account/orders/DB-100041/reorder" method="post"><button class="black">REORDER ITEMS</button></form><a href="/pages/refund-policy">Start a local return</a></div><a href="/collections/bags">Back to Bags</a></section>'''
217
+ return page("My Account – Dooney & Bourke",body,session)
218
+ body=f'''<section class="auth"><h1>Log in</h1><p>Enter the synthetic local fixture account or create a local-only account simulation.</p>{f'<p class="error" role="alert">{esc(message)}</p>' if message else ''}<form action="/account/login" method="post"><label>Email<input type="email" name="email" autocomplete="username" required></label><label>Password<input type="password" name="password" autocomplete="current-password" required></label><button class="black">LOG IN</button></form><p>Evaluation fixture: <code>shopper@example.test</code> / <code>WebsiteBench!041</code></p><a href="/account/register">Create account</a> · <a href="/account/recover">Forgot password?</a><small>By continuing, you agree to the local evaluation <a href="/pages/terms">Terms</a> and <a href="/pages/privacy">Privacy Policy</a>.</small></section>'''
219
+ if path.endswith('register'):
220
+ body=f'''<section class="auth"><h1>Create an account</h1><p>This is a truthful local simulation. It never sends verification email.</p>{f'<p class="error" role="alert">{esc(message)}</p>' if message else ''}<form action="/account/register" method="post"><label>First name<input name="first_name" autocomplete="given-name" required></label><label>Last name<input name="last_name" autocomplete="family-name" required></label><label>Email<input name="email" type="email" autocomplete="email" required></label><label>Password<input name="password" type="password" autocomplete="new-password" required></label><button class="black">CREATE LOCAL ACCOUNT</button></form><p>Verification guidance: a session-bound code is shown locally and no message is sent.</p><a href="/account/login">Return to sign in</a><small><a href="/pages/terms">Terms</a> · <a href="/pages/privacy">Privacy Policy</a></small></section>'''
221
+ if path.endswith('register/verify'):
222
+ body=f'''<section class="auth"><h1>Check your local verification code</h1><p>No email was sent. For this local-only evaluation session, use:</p><code class="local-code">{esc(local_code)}</code>{f'<p class="error" role="alert">{esc(message)}</p>' if message else ''}<form action="/account/register/verify" method="post"><label>Six-digit code<input name="code" inputmode="numeric" autocomplete="one-time-code" required></label><button class="black">VERIFY AND CREATE ACCOUNT</button></form><a href="/account/register">Start again</a></section>'''
223
+ elif path.endswith('recover'):
224
+ body='''<section class="auth"><h1>Reset your password</h1><p>Enter an email to see validation guidance. No reset message will be sent.</p><form class="local-recovery"><label>Email address<input type="email" required></label><button>CONTINUE</button></form><p role="status" class="recovery-status"></p><a href="/account/login">Return to sign in</a></section>'''
225
+ return page("Account – Dooney & Bourke",body,session)
226
+
227
+ def info_page(session,path):
228
+ pages={
229
+ "/pages/track-your-order":("Track Your Order",'''<p>Enter your order information to view a local seeded status.</p><form class="track" method="post" action="/pages/track-your-order"><label>Order Number<input name="order" required></label><label>Email Address<input name="email" type="email"></label><label>Zip Code<input name="zip" required></label><button class="black">TRACK ORDER</button></form>'''),
230
+ "/pages/refund-policy":("Returns",'''<h2>Easy Returns</h2><p>Review return eligibility and bring your order number to the local account history. This clone never creates a real return or shipment.</p><a class="black" href="/pages/track-your-order">TRACK AN ORDER</a>'''),
231
+ "/pages/contact":("Contact Us",'''<p>Find guidance for products, orders, account access and failed actions without exposing private account data.</p><form class="contact"><label>Name<input required></label><label>Email<input type="email" required></label><label>How can we help?<textarea required></textarea></label><button class="black">SAVE LOCAL DRAFT</button></form><p class="contact-status" role="status"></p>'''),
232
+ "/pages/orders-payments":("Orders & Payments",'''<p>Track a local seeded order, review payment guidance, or sign in to view account history.</p><a href="/pages/track-your-order">Track Your Order</a> · <a href="/account/orders">Order History</a>'''),
233
+ "/pages/help":("Help Center",'''<h2>How can we help?</h2><p><a href="/pages/track-your-order">Orders & tracking</a></p><p><a href="/pages/refund-policy">Returns</a></p><p><a href="/account/recover">Account access</a></p><p><a href="/pages/contact">Contact support</a></p>'''),
234
+ "/pages/privacy":("Privacy Policy","<p>This local WebsiteBench clone stores only synthetic evaluation data on the local machine and makes no remote runtime requests.</p>"),
235
+ "/pages/terms":("Terms of Service","<p>This is a local simulation. No real purchase, payment, email, account, shipment, or support message is created.</p>"),
236
+ }
237
+ title,content=pages.get(path,(path.rsplit('/',1)[-1].replace('-',' ').title(),"<p>Explore Dooney & Bourke information in this local experience.</p>"))
238
+ return page(f"{title} – Dooney & Bourke",f'''<section class="info"><h1>{esc(title)}</h1>{content}<p><a href="/collections/bags">Continue Shopping</a></p></section>''',session)
239
+
240
+ def application(environ,start):
241
+ path=environ.get("PATH_INFO","/") or "/"; method=environ.get("REQUEST_METHOD","GET").upper(); query=parse_qs(environ.get("QUERY_STRING",""),keep_blank_values=True)
242
+ jar=cookies.SimpleCookie(environ.get("HTTP_COOKIE","")); token=jar.get(session_cookie_name(environ)); session,session_state=AUTH.ensure_session(token.value if token else None); new_cookie=not token or token.value!=session
243
+ base_headers=(("Content-Type","text/html; charset=utf-8"),("Cache-Control","no-store"))
244
+ cookie_header=session_cookie_header(environ,session)
245
+ headers=base_headers+((cookie_header,) if new_cookie else ())
246
+ if path in {"/__websitebench/health","/healthz"}: return response(start,200,b'{"status":"ok"}',(("Content-Type","application/json"),))
247
+ if path.startswith("/static/"):
248
+ source_aliases={
249
+ "/static/source/home-offer-mobile.webp":"70/70f0f295d8064dd4d012ac6779c025edfc410e37eb7a56ee3ddf7590670a6663.webp",
250
+ "/static/source/main-logo.svg":"8c/8cd7c953036d5f973a31ff971305a471cefa582456c18192c43f2022e61a626e.svg",
251
+ "/static/source/love-logo.svg":"33/3353564b39673aaf8126b4e68e9c88e52a84466af1eb9d0c31ee928d8608fc5d.svg",
252
+ "/static/source/cookie-logo.png":"38/38650fa4afe34ba5cf4cb79b62186ba40f29946cd349029d1d5703120e6dd0c4.png",
253
+ }
254
+ if path in source_aliases:
255
+ target=(ROOT.parent/"source-acquisition/2026-08-24.assets-r1/resources"/source_aliases[path]).resolve()
256
+ return response(start,200,target.read_bytes(),(("Content-Type",mimetypes.guess_type(target.name)[0] or "application/octet-stream"),)+STATIC_CACHE_HEADERS)
257
+ target=(ROOT/path.lstrip('/')).resolve(); static=(ROOT/'static').resolve()
258
+ if static not in target.parents or not target.is_file(): return response(start,404,b"not found",(("Content-Type","text/plain"),))
259
+ if target.name.endswith('.b64'):
260
+ decoded=base64.b64decode(target.read_text(encoding='ascii').strip(),validate=True)
261
+ return response(start,200,decoded,(("Content-Type",mimetypes.guess_type(target.name[:-4])[0] or "application/octet-stream"),)+STATIC_CACHE_HEADERS)
262
+ return response(start,200,target.read_bytes(),(("Content-Type",mimetypes.guess_type(target.name)[0] or "application/octet-stream"),)+STATIC_CACHE_HEADERS)
263
+ if method=="POST":
264
+ if not request_origin_allowed(environ):
265
+ return response(start,403,b"Request origin is not allowed",(("Content-Type","text/plain; charset=utf-8"),))
266
+ data=form(environ); own=owner(session)
267
+ if path=="/cart/add":
268
+ try:
269
+ business.update_cart(BACKEND,own,quantity=1,color=data.get('color','Caramel'),handle=data.get('handle'))
270
+ except business.CartValidationError as error:
271
+ status,doc=cart_page(session,str(error)); return response(start,400,doc,headers)
272
+ return redirect(start,"/cart",headers)
273
+ if path=="/cart/update":
274
+ try:
275
+ quantity=int(data.get('quantity',''))
276
+ if not 1 <= quantity <= 9: raise ValueError
277
+ except (TypeError,ValueError):
278
+ status,doc=cart_page(session,"Enter a quantity from 1 to 9."); return response(start,400,doc,headers)
279
+ business.update_cart(BACKEND,own,quantity=quantity); return redirect(start,"/cart",headers)
280
+ if path=="/cart/remove": business.update_cart(BACKEND,own,remove=True); return redirect(start,"/cart",headers)
281
+ if path=="/cart/restore": business.update_cart(BACKEND,own,restore=True); return redirect(start,"/cart",headers)
282
+ if path=="/cart/promotion":
283
+ code=data.get('code','').strip().upper(); business.update_cart(BACKEND,own,promotion="SAVE10" if code=="SAVE10" else "")
284
+ status,doc=cart_page(session,"Discount code is not valid." if code!="SAVE10" else "SAVE10 applied — 10% off your local bag.")
285
+ return response(start,status,doc,headers)
286
+ if path=="/wishlist/toggle":
287
+ try: business.toggle_wishlist(BACKEND,own,data.get('handle',''))
288
+ except business.CartValidationError as error:
289
+ status,doc=page("Saved Items – Dooney & Bourke",f'<section class="account"><h1>Saved Items</h1><p class="error" role="alert">{esc(error)}</p><a href="/collections/bags">Shop Bags</a></section>',session,400); return response(start,status,doc,headers)
290
+ return redirect(start,safe_return_path(environ),headers)
291
+ if path=="/checkout/review":
292
+ required={'email':'Enter a valid email address.','first_name':'Enter a first name.','last_name':'Enter a last name.','address':'Enter an address.','city':'Enter a city.','postal_code':'Enter a postal code.','phone':'Enter a phone number.'}; errors={k:v for k,v in required.items() if not data.get(k,'').strip()}
293
+ if data.get('email') and not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+",data['email']): errors['email']='Enter a valid email address.'
294
+ if data.get('country','Canada')!='Canada': errors['country']='Select Canada.'
295
+ if data.get('province','') not in {'Ontario','British Columbia','Quebec'}: errors['province']='Select an available province.'
296
+ postal=data.get('postal_code','').replace(' ','').upper()
297
+ if postal and not re.fullmatch(r"[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z]\d[ABCEGHJ-NPRSTV-Z]\d",postal): errors['postal_code']='Enter a valid Canadian postal code.'
298
+ phone=re.sub(r"\D","",data.get('phone',''))
299
+ if data.get('phone') and not 10 <= len(phone) <= 15: errors['phone']='Enter a valid phone number.'
300
+ if data.get('shipping') not in {'Standard','Express'}: errors['shipping']='Select an available shipping method.'
301
+ business.checkout_save(BACKEND,own,data,'contact' if errors else 'review')
302
+ status,doc=checkout_page(session,errors); return response(start,status,doc,headers)
303
+ if path=="/checkout/sandbox":
304
+ if set(data)!={'scenario'}:
305
+ status,doc=checkout_page(session,sandbox={'tone':'error','label':'Sandbox request rejected','message':'Only a declared local payment scenario is accepted. No real order was created.'}); return response(start,400,doc,headers)
306
+ try:
307
+ attempt=business.run_payment_simulation(BACKEND,own,data.get('scenario',''))
308
+ except (ValueError,PaymentError) as error:
309
+ status,doc=checkout_page(session,sandbox={'tone':'error','label':'Sandbox request rejected','message':f'{error} No real order was created.'}); return response(start,400,doc,headers)
310
+ outcomes={
311
+ 'APPROVED':('success','Simulated approval','The local sandbox approved this review. No real order was created.'),
312
+ 'DECLINED':('error','Simulated decline','The local sandbox declined this review. No real order was created.'),
313
+ 'RETRYABLE':('notice','Simulated retry','The local sandbox returned a retryable result. No real order was created.'),
314
+ }
315
+ tone,label,message=outcomes[attempt['status']]
316
+ status,doc=checkout_page(session,sandbox={'tone':tone,'label':label,'message':message}); return response(start,status,doc,headers)
317
+ if path=="/account/register":
318
+ try:
319
+ display_name=f"{data.get('first_name','').strip()} {data.get('last_name','').strip()}".strip()
320
+ AUTH.start_registration(session,email=data.get('email',''),display_name=display_name,password=data.get('password',''))
321
+ local_mail=AUTH.local_mail_for_session(session,purpose="registration") or {}
322
+ status,doc=account_page(session,"/account/register/verify",local_code=local_mail.get('verification_code','')); return response(start,status,doc,headers)
323
+ except AuthError as error:
324
+ status,doc=account_page(session,"/account/register",str(error)); return response(start,400,doc,headers)
325
+ if path=="/account/register/verify":
326
+ try:
327
+ AUTH.verify_registration_code(session,data.get('code',''))
328
+ result=AUTH.complete_registration(session,session_rotation_callback=business.rotate_owner); session=result['session_token']
329
+ headers=base_headers+(session_cookie_header(environ,session),)
330
+ return redirect(start,"/account",headers)
331
+ except AuthError as error:
332
+ local_mail=AUTH.local_mail_for_session(session,purpose="registration") or {}
333
+ status,doc=account_page(session,"/account/register/verify",str(error),local_mail.get('verification_code','')); return response(start,400,doc,headers)
334
+ if path=="/account/login":
335
+ try:
336
+ result=AUTH.sign_in(session,email=data.get('email',''),password=data.get('password',''),session_rotation_callback=business.rotate_owner); session=result['session_token']; headers=base_headers+(session_cookie_header(environ,session),); return redirect(start,"/account",headers)
337
+ except Exception: status,doc=account_page(session,"/account/login","Email or password is incorrect."); return response(start,status,doc,headers)
338
+ if path=="/account/logout": AUTH.sign_out(session); return redirect(start,"/account/login",base_headers+(session_cookie_header(environ,"",max_age=0),))
339
+ if path in {"/account/orders/DB-100041/cancel","/account/orders/DB-100041/reorder"}:
340
+ auth_state=AUTH.resolve_session(session) or {}; account=auth_state.get('account')
341
+ if not account: return redirect(start,"/account/login",headers)
342
+ if path.endswith('/cancel'):
343
+ order_value=business.cancel_order(BACKEND,account['email_normalized'],'DB-100041')
344
+ if not order_value: return response(start,404,b"order not found",(("Content-Type","text/plain"),))
345
+ status,doc=account_page(session,"/account/orders/DB-100041","Cancellation saved locally. No carrier or payment was contacted."); return response(start,status,doc,headers)
346
+ order_value=business.reorder(BACKEND,own,account['email_normalized'],'DB-100041')
347
+ if not order_value: return response(start,404,b"order not found",(("Content-Type","text/plain"),))
348
+ return redirect(start,"/cart",headers)
349
+ if path=="/pages/track-your-order":
350
+ tracked=business.order_by_tracking(BACKEND,data.get('order',''),data.get('zip',''))
351
+ if tracked: content=f'<p class="notice"><b>DB-100041 · {esc(tracked["status"])}</b><br>Pebble Grain Crossbody · Estimated local status only.</p>'
352
+ else: content='<p class="error">We could not find that order. Check the order number and postal code.</p>'
353
+ status,doc=info_page(session,path); doc=doc.replace('<p>Enter your order information',content+'<p>Enter your order information'); return response(start,status,doc,headers)
354
+ return response(start,405,b"method not allowed",(("Content-Type","text/plain"),))
355
+ if path=="/": status,doc=home(session)
356
+ elif path=="/search" or path.startswith("/collections/") or path=="/pages/sports": status,doc=catalog(session,path,query)
357
+ elif path.startswith("/products/"): status,doc=product_page(session,path.rsplit('/',1)[-1],query)
358
+ elif path=="/cart": status,doc=cart_page(session)
359
+ elif path=="/checkout":
360
+ if query.get('edit'): business.checkout_save(BACKEND,owner(session),business.checkout(BACKEND,owner(session)),'contact')
361
+ status,doc=checkout_page(session)
362
+ elif path.startswith("/account"): status,doc=account_page(session,path)
363
+ elif path.startswith("/pages/"): status,doc=info_page(session,path)
364
+ else: status,doc=page("Page Not Found – Dooney & Bourke",'''<section class="not-found"><span>404</span><h1>Oops! Page not found</h1><p>We couldn't find the page you're looking for.</p><a class="black" href="/collections/new-arrivals">SHOP NEW ARRIVALS</a><a href="/">Continue Shopping</a></section>''',session,404)
365
+ return response(start,status,doc,headers)
366
+
367
+ if __name__=="__main__":
368
+ host=os.environ.get("HOST","127.0.0.1"); port=int(os.environ.get("PORT","8000"))
369
+ print(f"Dooney & Bourke local clone listening on http://{host}:{port}",flush=True)
370
+ make_server(host,port,application).serve_forever()
tasks/dooney-bourke/environment/reference/clone/backend/business.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Site-owned commerce model on the generated WebsiteBench database seam."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import sqlite3
8
+ from typing import Any
9
+
10
+
11
+ SCHEMA = """
12
+ CREATE TABLE IF NOT EXISTS dooney_cart (
13
+ owner TEXT PRIMARY KEY,
14
+ quantity INTEGER NOT NULL DEFAULT 0 CHECK(quantity BETWEEN 0 AND 9),
15
+ product_handle TEXT NOT NULL DEFAULT 'pebble-grain-crossbody-r264',
16
+ color TEXT NOT NULL DEFAULT 'Caramel',
17
+ removed_quantity INTEGER NOT NULL DEFAULT 0 CHECK(removed_quantity BETWEEN 0 AND 9),
18
+ promotion TEXT,
19
+ updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
20
+ );
21
+ CREATE TABLE IF NOT EXISTS dooney_checkout (
22
+ owner TEXT PRIMARY KEY,
23
+ contact_email TEXT NOT NULL DEFAULT '', first_name TEXT NOT NULL DEFAULT '',
24
+ last_name TEXT NOT NULL DEFAULT '', address TEXT NOT NULL DEFAULT '',
25
+ city TEXT NOT NULL DEFAULT '', province TEXT NOT NULL DEFAULT 'Ontario',
26
+ postal_code TEXT NOT NULL DEFAULT '', phone TEXT NOT NULL DEFAULT '',
27
+ shipping TEXT NOT NULL DEFAULT 'Standard', state TEXT NOT NULL DEFAULT 'contact',
28
+ updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
29
+ );
30
+ CREATE TABLE IF NOT EXISTS dooney_wishlist (
31
+ owner TEXT NOT NULL, handle TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
32
+ PRIMARY KEY(owner, handle)
33
+ );
34
+ CREATE TABLE IF NOT EXISTS dooney_local_orders (
35
+ order_number TEXT PRIMARY KEY, owner TEXT NOT NULL, email TEXT NOT NULL,
36
+ postal_code TEXT NOT NULL, status TEXT NOT NULL, total_minor INTEGER NOT NULL,
37
+ detail_json TEXT NOT NULL, created_at TEXT NOT NULL
38
+ );
39
+ """
40
+
41
+ PRODUCT = {
42
+ "handle": "pebble-grain-crossbody-r264",
43
+ "title": "Pebble Grain Crossbody",
44
+ "style": "R264 CA",
45
+ "price_minor": 24500,
46
+ "compare_minor": 41000,
47
+ "rating": "4.6",
48
+ "reviews": 2738,
49
+ "colors": ["Caramel", "Bone", "Red", "Black", "Black Jeans", "Brown Tmoro", "Black", "White", "Wine", "Taupe", "Midnight Blue"],
50
+ "asset": "/static/assets/images/product/pebble-crossbody-caramel.webp",
51
+ }
52
+
53
+ CATALOG = [
54
+ PRODUCT,
55
+ {"handle":"pebble-grain-zip-zip-satchel-r343","title":"Pebble Grain Zip Zip Satchel","style":"R343","price_minor":27900,"compare_minor":43800,"rating":"4.7","reviews":1812,"colors":["Caramel","Black","Bone"],"asset":"/static/assets/images/catalog/pebble-zip-zip-satchel.webp"},
56
+ {"handle":"pebble-grain-small-lexington-r342","title":"Pebble Grain Small Lexington","style":"R342","price_minor":22900,"compare_minor":39800,"rating":"4.5","reviews":942,"colors":["Caramel","Wine","Black"],"asset":"/static/assets/images/catalog/pebble-small-lexington.webp"},
57
+ {"handle":"pebble-grain-continental-clutch-zr507","title":"Pebble Grain Continental Clutch","style":"ZR507","price_minor":15900,"compare_minor":26800,"rating":"4.8","reviews":1264,"colors":["Wine","Caramel","Black"],"asset":"/static/assets/images/catalog/pebble-continental-clutch.webp"},
58
+ {"handle":"pebble-grain-crossbody-25-r1849","title":"Pebble Grain Crossbody 25","style":"R1849","price_minor":19900,"compare_minor":34800,"rating":"4.6","reviews":816,"colors":["Wine","Caramel","Black"],"asset":"/static/assets/images/catalog/pebble-crossbody-25.webp"},
59
+ {"handle":"pebble-grain-hobo-r924","title":"Pebble Grain Hobo","style":"R924","price_minor":22900,"compare_minor":39800,"rating":"4.7","reviews":1352,"colors":["Caramel","Black","Bone"],"asset":"/static/assets/images/catalog/pebble-hobo.webp"},
60
+ ]
61
+
62
+ ACCESSORIES = [
63
+ {"handle":"pebble-grain-zip-credit-card-wallet-12-zs0341","title":"Pebble Grain Zip Credit Card Wallet 12","style":"ZS0341","price_minor":8800,"compare_minor":16500,"rating":"4.2","reviews":None,"colors":["Caramel"],"asset":"/static/assets/images/categories/accessories/zip-credit-card-wallet.webp","category":"Accessories"},
64
+ {"handle":"pebble-grain-small-coin-case-zr160","title":"Pebble Grain Small Coin Case","style":"ZR160","price_minor":5900,"compare_minor":15000,"rating":"4.8","reviews":None,"colors":["Caramel"],"asset":"/static/assets/images/categories/accessories/small-coin-case.webp","category":"Accessories"},
65
+ {"handle":"florentine-flap-wallet-9y0195","title":"Florentine Flap Wallet","style":"9Y0195","price_minor":11900,"compare_minor":30000,"rating":"4.4","reviews":None,"colors":["Natural"],"asset":"/static/assets/images/categories/accessories/florentine-flap-wallet.webp","category":"Accessories"},
66
+ {"handle":"nylon-cosmetic-case-wblpt0356","title":"Nylon Cosmetic Case","style":"WBLPT0356","price_minor":4300,"compare_minor":4300,"rating":"2.1","reviews":None,"colors":["Black"],"asset":"/static/assets/images/categories/accessories/nylon-cosmetic-case.webp","category":"Accessories"},
67
+ ]
68
+
69
+ SHOES = [
70
+ {"handle":"classic-low-top-womens-classic-low-top-dcllww","title":"Women's Classic Low Top","style":"DCLLWW","price_minor":15000,"compare_minor":15000,"rating":"3.6","reviews":None,"colors":["Light Aqua"],"asset":"/static/assets/images/categories/shoes/womens-classic-low-top.webp","category":"Shoes"},
71
+ {"handle":"classic-low-top-womens-suede-low-top-dsulww","title":"Women's Suede Low Top","style":"DSULWW","price_minor":15000,"compare_minor":15000,"rating":"4.0","reviews":None,"colors":["Red"],"asset":"/static/assets/images/categories/shoes/womens-suede-low-top.webp","category":"Shoes"},
72
+ {"handle":"classic-low-top-mens-classic-low-top-dcllwm","title":"Men's Classic Low Top","style":"DCLLWM","price_minor":15000,"compare_minor":15000,"rating":"4.0","reviews":None,"colors":["Black"],"asset":"/static/assets/images/categories/shoes/mens-classic-low-top.webp","category":"Shoes"},
73
+ ]
74
+
75
+ UNDER_100 = [
76
+ {"handle":"nylon-front-zip-tote-bblpt2543","title":"Nylon Front Zip Tote","style":"BBLPT2543","price_minor":13500,"compare_minor":13500,"rating":"","reviews":None,"colors":["Ocean"],"asset":"/static/assets/images/categories/under-100/nylon-front-zip-tote.webp","category":"Under $100"},
77
+ {"handle":"eastham-crossbody-pouchette-bestm0299","title":"Eastham Crossbody Pouchette","style":"BESTM0299","price_minor":7900,"compare_minor":28500,"rating":"","reviews":None,"colors":["Dandelion"],"asset":"/static/assets/images/categories/under-100/eastham-crossbody-pouchette.webp","category":"Under $100"},
78
+ {"handle":"canvas-drawstring-25-bcanv2500","title":"Canvas Drawstring 25","style":"BCANV2500","price_minor":15000,"compare_minor":15000,"rating":"","reviews":None,"colors":["Navy"],"asset":"/static/assets/images/categories/under-100/canvas-drawstring-25.webp","category":"Under $100"},
79
+ {"handle":"penrose-hobo-crossbody-22-bpen22284","title":"Penrose Hobo Crossbody 22","style":"BPEN22284","price_minor":15000,"compare_minor":15000,"rating":"","reviews":None,"colors":["White"],"asset":"/static/assets/images/categories/under-100/penrose-hobo-crossbody.webp","category":"Under $100"},
80
+ ]
81
+
82
+ SALE = [
83
+ {"handle":"sorrento-satchel-30-with-pocket-bsorr2508","title":"Sorrento Satchel 30 With Pocket","style":"BSORR2508","price_minor":30000,"compare_minor":60500,"rating":"","reviews":None,"colors":["Purple"],"asset":"/static/assets/images/categories/sale/sorrento-satchel.webp","category":"Sale"},
84
+ {"handle":"florentine-medium-russel-8l569","title":"Florentine Medium Russel","style":"8L569","price_minor":27900,"compare_minor":80000,"rating":"","reviews":None,"colors":["Natural"],"asset":"/static/assets/images/categories/sale/florentine-medium-russel.webp","category":"Sale"},
85
+ {"handle":"pebble-grain-large-cassia-hobo-r2486","title":"Pebble Grain Large Cassia Hobo","style":"R2486","price_minor":23000,"compare_minor":48500,"rating":"4.0","reviews":None,"colors":["Black"],"asset":"/static/assets/images/categories/sale/pebble-large-cassia-hobo.webp","category":"Sale"},
86
+ {"handle":"penrose-allison-crossbody-bpen21104","title":"Penrose Allison Crossbody","style":"BPEN21104","price_minor":23000,"compare_minor":41000,"rating":"","reviews":None,"colors":["Mint"],"asset":"/static/assets/images/categories/sale/penrose-allison-crossbody.webp","category":"Sale"},
87
+ ]
88
+
89
+ SPORTS = [
90
+ {"handle":"nfl-cowboys-crossbody-28-bsccw2384","title":"NFL Cowboys Crossbody 28","style":"BSCCW2384","price_minor":28500,"compare_minor":28500,"rating":"","reviews":None,"colors":["Cowboys"],"asset":"/static/assets/images/categories/sports/nfl-cowboys-crossbody.avif","category":"Sports"},
91
+ {"handle":"nfl-eagles-pocket-tote-35-bscea2579","title":"NFL Eagles Pocket Tote 35","style":"BSCEA2579","price_minor":30000,"compare_minor":30000,"rating":"","reviews":None,"colors":["Eagles"],"asset":"/static/assets/images/categories/sports/nfl-eagles-pocket-tote.avif","category":"Sports"},
92
+ ]
93
+
94
+ for item in CATALOG:
95
+ item.setdefault("category", "Bags")
96
+
97
+ ALL_PRODUCTS = CATALOG + ACCESSORIES + SHOES + UNDER_100 + SALE + SPORTS
98
+ CATEGORY_CATALOGS = {
99
+ "/collections/bags": CATALOG,
100
+ "/collections/accessories": ACCESSORIES,
101
+ "/collections/shoes": SHOES,
102
+ "/collections/under-100": UNDER_100,
103
+ "/collections/sale": SALE,
104
+ "/pages/sports": SPORTS,
105
+ "/collections/all": ALL_PRODUCTS,
106
+ }
107
+
108
+ class CartValidationError(ValueError):
109
+ """A recoverable cart request error safe to show to the shopper."""
110
+
111
+
112
+ def find_product_by_handle(handle: str | None) -> dict[str, Any] | None:
113
+ if not handle:
114
+ return None
115
+ return next((item for item in ALL_PRODUCTS if item["handle"] == handle), None)
116
+
117
+
118
+ def product_by_handle(handle: str) -> dict[str, Any]:
119
+ return find_product_by_handle(handle) or PRODUCT
120
+
121
+
122
+ def initialize(backend) -> None:
123
+ with backend.lifecycle.connection(transaction=True) as db:
124
+ db.executescript(SCHEMA)
125
+ if "product_handle" not in {row[1] for row in db.execute("PRAGMA table_info(dooney_cart)")}:
126
+ db.execute("ALTER TABLE dooney_cart ADD COLUMN product_handle TEXT NOT NULL DEFAULT 'pebble-grain-crossbody-r264'")
127
+ db.execute(
128
+ "INSERT OR IGNORE INTO dooney_local_orders VALUES (?,?,?,?,?,?,?,?)",
129
+ ("DB-100041", "seeded-account", "shopper@example.test", "M5V2T6", "In transit", 19635,
130
+ json.dumps({"product":"Pebble Grain Crossbody","color":"Caramel","quantity":1,"actions":["View details","Start a local return"]}),
131
+ "2026-08-20T14:00:00Z"),
132
+ )
133
+
134
+
135
+ def cart(backend, owner: str) -> dict[str, Any]:
136
+ with backend.lifecycle.connection() as db:
137
+ row = db.execute("SELECT * FROM dooney_cart WHERE owner=?", (owner,)).fetchone()
138
+ return dict(row) if row else {"owner":owner,"quantity":0,"removed_quantity":0,"product_handle":PRODUCT["handle"],"color":"Caramel","promotion":None}
139
+
140
+
141
+ def update_cart(backend, owner: str, *, quantity: int | None = None, color: str | None = None, handle: str | None = None,
142
+ remove: bool = False, restore: bool = False, promotion: str | None = None) -> dict[str, Any]:
143
+ current = cart(backend, owner)
144
+ qty = current["quantity"] if quantity is None else max(0, min(9, int(quantity)))
145
+ removed = current["removed_quantity"]
146
+ if remove:
147
+ removed, qty = qty, 0
148
+ if restore and removed:
149
+ qty, removed = removed, 0
150
+ if handle is not None:
151
+ product = find_product_by_handle(handle)
152
+ if product is None:
153
+ raise CartValidationError("Choose an available product.")
154
+ else:
155
+ product = product_by_handle(current["product_handle"])
156
+ if color is not None and color not in product["colors"]:
157
+ raise CartValidationError("Choose an available color.")
158
+ chosen = current["color"] if color is None else color
159
+ if chosen not in product["colors"]:
160
+ chosen = product["colors"][0]
161
+ promo = current["promotion"] if promotion is None else (promotion or None)
162
+ current_facts = (
163
+ int(current["quantity"]),
164
+ current["product_handle"],
165
+ current["color"],
166
+ current.get("promotion") or None,
167
+ )
168
+ next_facts = (qty, product["handle"], chosen, promo)
169
+ with backend.lifecycle.connection(transaction=True) as db:
170
+ db.execute("INSERT INTO dooney_cart(owner,quantity,product_handle,color,removed_quantity,promotion) VALUES(?,?,?,?,?,?) ON CONFLICT(owner) DO UPDATE SET quantity=excluded.quantity,product_handle=excluded.product_handle,color=excluded.color,removed_quantity=excluded.removed_quantity,promotion=excluded.promotion,updated_at=CURRENT_TIMESTAMP", (owner, qty, product["handle"], chosen, removed, promo))
171
+ if next_facts != current_facts:
172
+ db.execute(
173
+ "UPDATE dooney_checkout SET state='contact',"
174
+ "updated_at=CURRENT_TIMESTAMP "
175
+ "WHERE owner=? AND state='review'",
176
+ (owner,),
177
+ )
178
+ return cart(backend, owner)
179
+
180
+
181
+ def totals(value: dict[str, Any]) -> dict[str, int]:
182
+ subtotal = product_by_handle(value.get("product_handle", PRODUCT["handle"]))["price_minor"] * int(value["quantity"])
183
+ discount = subtotal // 10 if value.get("promotion") == "SAVE10" else 0
184
+ return {"subtotal": subtotal, "discount": discount, "shipping": 0, "total": subtotal - discount}
185
+
186
+
187
+ def checkout_save(backend, owner: str, fields: dict[str, str], state: str) -> None:
188
+ with backend.lifecycle.connection(transaction=True) as db:
189
+ db.execute("""INSERT INTO dooney_checkout(owner,contact_email,first_name,last_name,address,city,province,postal_code,phone,shipping,state) VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner) DO UPDATE SET contact_email=excluded.contact_email,first_name=excluded.first_name,last_name=excluded.last_name,address=excluded.address,city=excluded.city,province=excluded.province,postal_code=excluded.postal_code,phone=excluded.phone,shipping=excluded.shipping,state=excluded.state,updated_at=CURRENT_TIMESTAMP""", (owner, fields.get("email",""),fields.get("first_name",""),fields.get("last_name",""),fields.get("address",""),fields.get("city",""),fields.get("province","Ontario"),fields.get("postal_code",""),fields.get("phone",""),fields.get("shipping","Standard"),state))
190
+
191
+
192
+ def checkout(backend, owner: str) -> dict[str, str]:
193
+ with backend.lifecycle.connection() as db:
194
+ row=db.execute("SELECT * FROM dooney_checkout WHERE owner=?",(owner,)).fetchone()
195
+ return dict(row) if row else {}
196
+
197
+
198
+ def checkout_amounts(cart_value: dict[str, Any], shipping: str) -> dict[str, int]:
199
+ values = totals(cart_value)
200
+ shipping_minor = 2000 if shipping == "Express" else 0
201
+ return {
202
+ **values,
203
+ "shipping": shipping_minor,
204
+ "total": values["total"] + shipping_minor,
205
+ }
206
+
207
+
208
+ def run_payment_simulation(
209
+ backend, owner: str, scenario_id: str
210
+ ) -> dict[str, Any]:
211
+ """Run only a declared server-side local-sandbox payment outcome."""
212
+
213
+ if scenario_id not in {
214
+ "sandbox-approved",
215
+ "sandbox-declined",
216
+ "sandbox-retry",
217
+ }:
218
+ raise ValueError("Choose an available local sandbox scenario.")
219
+ cart_value = cart(backend, owner)
220
+ checkout_value = checkout(backend, owner)
221
+ if not cart_value["quantity"] or checkout_value.get("state") != "review":
222
+ raise ValueError("Review delivery details before running the sandbox.")
223
+ amounts = checkout_amounts(cart_value, checkout_value.get("shipping", "Standard"))
224
+ snapshot = {
225
+ "cart": {
226
+ key: cart_value.get(key)
227
+ for key in ("quantity", "product_handle", "color", "promotion")
228
+ },
229
+ "checkout": {
230
+ key: checkout_value.get(key)
231
+ for key in (
232
+ "contact_email",
233
+ "first_name",
234
+ "last_name",
235
+ "address",
236
+ "city",
237
+ "province",
238
+ "postal_code",
239
+ "phone",
240
+ "shipping",
241
+ )
242
+ },
243
+ "amount_minor": amounts["total"],
244
+ }
245
+ fingerprint = hashlib.sha256(
246
+ json.dumps(snapshot, sort_keys=True, separators=(",", ":")).encode()
247
+ ).hexdigest()
248
+ facts = {
249
+ "owner": owner,
250
+ "amount_minor": amounts["total"],
251
+ "currency": "CAD",
252
+ "fingerprint": fingerprint,
253
+ }
254
+ flow = backend.payments.create_intent(
255
+ **facts,
256
+ idempotency_key=f"dooney.create.{fingerprint[:32]}",
257
+ )
258
+ return backend.payments.attempt(
259
+ flow_id=flow["flow_id"],
260
+ **facts,
261
+ scenario_id=scenario_id,
262
+ idempotency_key=f"dooney.attempt.{fingerprint[:24]}.{scenario_id}",
263
+ )
264
+
265
+
266
+ def order_for_email(backend, email: str, order_number: str = "DB-100041") -> dict[str, Any] | None:
267
+ with backend.lifecycle.connection() as db:
268
+ row = db.execute(
269
+ "SELECT * FROM dooney_local_orders WHERE order_number=? AND email=?",
270
+ (order_number, email.casefold()),
271
+ ).fetchone()
272
+ return dict(row) if row else None
273
+
274
+
275
+ def order_by_tracking(backend, order_number: str, postal_code: str) -> dict[str, Any] | None:
276
+ with backend.lifecycle.connection() as db:
277
+ row = db.execute(
278
+ "SELECT * FROM dooney_local_orders WHERE order_number=? AND postal_code=?",
279
+ (order_number.upper(), postal_code.replace(" ", "").upper()),
280
+ ).fetchone()
281
+ return dict(row) if row else None
282
+
283
+
284
+ def cancel_order(backend, email: str, order_number: str) -> dict[str, Any] | None:
285
+ with backend.lifecycle.connection(transaction=True) as db:
286
+ row = db.execute(
287
+ "SELECT * FROM dooney_local_orders WHERE order_number=? AND email=?",
288
+ (order_number, email.casefold()),
289
+ ).fetchone()
290
+ if row is None:
291
+ return None
292
+ db.execute(
293
+ "UPDATE dooney_local_orders SET status='Cancelled' WHERE order_number=?",
294
+ (order_number,),
295
+ )
296
+ return order_for_email(backend, email, order_number)
297
+
298
+
299
+ def reorder(backend, owner: str, email: str, order_number: str) -> dict[str, Any] | None:
300
+ order = order_for_email(backend, email, order_number)
301
+ if order is None:
302
+ return None
303
+ detail = json.loads(order["detail_json"])
304
+ update_cart(
305
+ backend,
306
+ owner,
307
+ quantity=int(detail["quantity"]),
308
+ handle=PRODUCT["handle"],
309
+ color=str(detail["color"]),
310
+ )
311
+ return order
312
+
313
+
314
+ def toggle_wishlist(backend, owner: str, handle: str) -> bool:
315
+ if find_product_by_handle(handle) is None:
316
+ raise CartValidationError("Choose an available product.")
317
+ with backend.lifecycle.connection(transaction=True) as db:
318
+ found=db.execute("SELECT 1 FROM dooney_wishlist WHERE owner=? AND handle=?",(owner,handle)).fetchone()
319
+ if found: db.execute("DELETE FROM dooney_wishlist WHERE owner=? AND handle=?",(owner,handle))
320
+ else: db.execute("INSERT INTO dooney_wishlist(owner,handle) VALUES(?,?)",(owner,handle))
321
+ return not bool(found)
322
+
323
+
324
+ def wishlist(backend, owner: str) -> set[str]:
325
+ with backend.lifecycle.connection() as db:
326
+ return {r[0] for r in db.execute("SELECT handle FROM dooney_wishlist WHERE owner=?",(owner,))}
327
+
328
+
329
+ def rotate_owner(db: sqlite3.Connection, old: str, new: str) -> None:
330
+ for table in ("dooney_cart", "dooney_checkout"):
331
+ db.execute(f"UPDATE OR IGNORE {table} SET owner=? WHERE owner=?", (new, old))
332
+ db.execute("UPDATE OR IGNORE dooney_wishlist SET owner=? WHERE owner=?", (new, old))
tasks/dooney-bourke/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/dooney-bourke/environment/reference/clone/compile.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -Eeuo pipefail
3
+ cd "$(dirname "$0")"
4
+ cp executable executable.tmp
5
+ chmod 755 executable.tmp
6
+ mv executable.tmp executable
tasks/dooney-bourke/environment/reference/clone/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ # Standard-library HTTP runtime; generated WebsiteBench backend is vendored locally.
tasks/dooney-bourke/environment/reference/clone/static/assets/fonts/BemboStd.woff2 ADDED
Binary file (43.2 kB). View file
 
tasks/dooney-bourke/environment/reference/clone/static/assets/fonts/Lato-Bold.woff2 ADDED
Binary file (43.7 kB). View file
 
tasks/dooney-bourke/environment/reference/clone/static/assets/fonts/Lato-Regular.woff2 ADDED
Binary file (44.7 kB). View file
 
tasks/dooney-bourke/environment/reference/clone/static/assets/icons/contact.svg ADDED
tasks/dooney-bourke/environment/reference/clone/static/assets/icons/dooney-logo-black.svg ADDED
tasks/dooney-bourke/environment/reference/clone/static/assets/icons/shipping.svg ADDED
tasks/dooney-bourke/environment/reference/clone/static/assets/icons/warranty.svg ADDED
tasks/dooney-bourke/environment/reference/clone/static/assets/images/categories/sports/nfl-cowboys-crossbody.avif ADDED
tasks/dooney-bourke/environment/reference/clone/static/assets/images/categories/sports/nfl-eagles-pocket-tote.avif ADDED
tasks/dooney-bourke/environment/reference/clone/static/assets/images/home/newsletter-source.webp.b64 ADDED
@@ -0,0 +1 @@
 
 
1
+ UklGRjacAABXRUJQVlA4ICqcAABQ9AGdASqGAUYCPm0ukkakIqGkq1h7qJANiWdu9KGSzdCJiFIKxA5Acx1QbF+r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QvKj0MkVAqZfqD2U7CTwT61r1/j6PUoH1NtVf6Uv1UFY7Tl6UNjRNuPoXfdN7c9x2EhGkP0u0/WdNL0gPQF4dR6S+ZRc4efG0p6QB29LMDfqRyg+54RiJAZJyknNoy+F78xTTXrgI0D56O91wSE8DEr7PBnbcN6Sif5Tnu358oi3/Q73L3B8AxQ6GKLlPzJKNPQgQADZo2cAAAYX00QXAsGT3GrcElDHLtF2LT74Y5mWTDSLzhvmOyp8CB3QWdmFzfmI3ACk3vohbIW7QcnGsRABBAlRfLU545VcLrd6oJoFCU5Iwjzx190ozJFDf2xLbBWnPwy7LiY5h6emUlh88p7EeMlBBJk8VYAAACatWrPnmn6XK0ozCp/tqzq5D1u1qwArK2Uiivz6oVzgAAAA=
tasks/dooney-bourke/environment/reference/clone/static/site.css ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root{--ink:#161616;--red:#c93032;--cream:#f7f4f0;--line:#dedbd7;--serif:"Dooney Bembo",Georgia,"Times New Roman",serif}
2
+ @font-face{font-family:"Dooney Bembo";src:url('/static/assets/fonts/BemboStd.woff2') format('woff2');font-display:swap}
3
+ @font-face{font-family:"Dooney Lato";src:url('/static/assets/fonts/Lato-Regular.woff2') format('woff2');font-weight:400;font-display:swap}
4
+ @font-face{font-family:"Dooney Lato";src:url('/static/assets/fonts/Lato-Bold.woff2') format('woff2');font-weight:700;font-display:swap}
5
+ *{box-sizing:border-box}
6
+ html{scroll-behavior:smooth}
7
+ body{margin:0;color:var(--ink);font:15px/1.45 "Dooney Lato",Arial,Helvetica,sans-serif;background:#f9f8f6}
8
+ a{color:inherit;text-underline-offset:3px}
9
+ button,input,select,textarea{font:inherit}
10
+ .skip{position:absolute;left:-999px}
11
+ .skip:focus{left:1rem;top:1rem;background:#fff;padding:1rem;z-index:99}
12
+ .brandbar{height:40px;background:#2d2d2d;color:#fff;display:flex;align-items:center;padding:0 22px 0 0;gap:38px}
13
+ .brandbar>a{background:#f9f8f6;color:#111;height:40px;padding:6px 21px;text-decoration:none}
14
+ .brandbar>b{display:flex;align-items:center;font:20px var(--serif);font-weight:normal}
15
+ .love-logo{display:block;width:132px;height:22px;object-fit:contain}
16
+ .brandbar>span{margin-left:auto;color:#ddd}
17
+ .logo{display:block;width:230px;max-height:32px;object-fit:contain}
18
+ .offer{text-align:center;background:#f7f6f4;padding:15px}
19
+ .offer a,.luxury a{font-size:12px}
20
+ header{height:68px;padding:0 20px;display:flex;align-items:center;border-bottom:1px solid #eee;gap:34px;position:relative;background:white;z-index:3}
21
+ header>a{text-decoration:none}
22
+ header nav{display:flex;justify-content:center;gap:34px;flex:1}
23
+ header nav a{text-decoration:none;font-weight:bold;letter-spacing:1px}
24
+ .icons{display:flex;align-items:center;gap:20px;font-size:25px}
25
+ .icons a{text-decoration:none;min-width:44px;min-height:44px;display:flex;align-items:center;justify-content:center}
26
+ .icons svg,.mobile-menu svg,.search-toggle svg{display:block}
27
+ .icons sup{background:#8d3333;color:#fff;border-radius:50%;font-size:10px;padding:3px 6px}
28
+ .search-toggle,.mobile-menu{border:0;background:transparent;font-size:25px;min-width:44px;min-height:44px;align-items:center;justify-content:center;cursor:pointer}
29
+ .search-toggle{display:flex}
30
+ .mobile-menu{display:none}
31
+ .quick-search{display:none;position:absolute;top:67px;left:0;right:0;background:white;padding:20px;box-shadow:0 8px 20px #0002}
32
+ .quick-search.open{display:flex}
33
+ .quick-search input{flex:1;padding:12px}
34
+ .luxury{text-align:center;padding:9px;border-bottom:1px solid #eee}
35
+ .hero{min-height:595px;background:#d4e3e5;display:grid;grid-template-columns:1fr 1.2fr;overflow:hidden}
36
+ .hero>div:first-child{padding:170px 7%}
37
+ .hero h1,.intro h2,.featured h2,.catalog h1,.cart h1,.info h1,.account h1{font:52px var(--serif);margin:18px 0}
38
+ .hero p{max-width:500px}
39
+ .hero-media{display:block;min-width:0;background:#d8b38f}
40
+ .hero-media img{display:block;width:100%;height:595px;object-fit:cover}
41
+ .outline,.black{display:inline-block;border:1px solid #111;padding:14px 24px;text-decoration:none;background:white;letter-spacing:.5px}
42
+ .black{background:#211d1b;color:white;border:0;text-align:center}
43
+ .intro{text-align:center;padding:85px 20px}
44
+ .intro h2{font:48px var(--serif)}
45
+ .intro p:last-child{max-width:650px;margin:auto}
46
+ .featured,.catalog,.cart,.info,.account{max-width:1300px;margin:auto;padding:55px 28px 90px}
47
+ .featured>h2{text-align:center}
48
+ .grid{display:grid;grid-template-columns:repeat(4,1fr);gap:20px}
49
+ .card{position:relative}
50
+ .card>a{text-decoration:none}
51
+ .card>form{position:absolute;right:10px;top:10px;z-index:2}
52
+ .card>form button{border:0;background:#fff;border-radius:50%;font-size:24px;min-width:44px;min-height:44px}
53
+ .bag-picture{background:#f4f2ef;aspect-ratio:1;display:flex;align-items:center}
54
+ .bag-picture img{width:100%;height:100%;object-fit:cover}
55
+ .card h3{font:22px var(--serif);margin:8px 0}
56
+ .card small,.badge{background:#dce8ec;padding:7px 13px}
57
+ .card del,.price del{margin-left:8px}
58
+ .filters{border-block:1px solid var(--line);display:flex;gap:18px;align-items:end;padding:18px 0;margin:20px 0 38px}
59
+ .filters label{font-size:12px;font-weight:bold}
60
+ .filters select{display:block;padding:9px 28px 9px 8px;margin-top:5px;background:#fff;border:1px solid #aaa}
61
+ .filters button{padding:10px 26px;border:0;background:#222;color:#fff}
62
+ .count{color:#666}
63
+ .empty{text-align:center;padding:70px 20px}
64
+ .empty h2{font:36px var(--serif)}
65
+ .crumbs{max-width:1305px;margin:92px auto 15px;padding:0;color:#555}
66
+ .product{max-width:1306px;margin:auto;padding:0 0 70px;display:grid;grid-template-columns:667px 1fr;gap:55px}
67
+ .gallery{display:grid;grid-template-columns:1fr 1fr;gap:9px}
68
+ .gallery>div{background:#faf8f6;min-height:405px;display:flex;align-items:center}
69
+ .gallery img{display:block;width:100%;height:100%;object-fit:cover}
70
+ .gallery .lifestyle{background:linear-gradient(160deg,#ffd8aa,#e6bd91)}
71
+ .product-info{padding:0 26px 0 0}
72
+ .product-info>.badge{display:inline-block;margin-top:1px;padding:7px 17px;font-size:14px;line-height:19px;letter-spacing:.4px}
73
+ .product-info h1{font:40px var(--serif);font-weight:normal;margin:21px 0 8px}
74
+ .product-info h1+p{margin:3px 0 15px}
75
+ .product-info hr{border:0;border-top:1px solid #ddd;margin:25px 0}
76
+ .meta{display:flex;justify-content:space-between}
77
+ .sale{color:var(--red);margin:10px 0 7px}
78
+ .price{font-size:19px}
79
+ .price>b{color:var(--red)}
80
+ .price>span{float:right;font-size:14px}
81
+ .sale+.price{margin:7px 0 14px}
82
+ .swatches{display:flex;flex-wrap:wrap;gap:15px;margin:14px 0 28px}
83
+ .swatch{width:40px;height:40px;border-radius:50%;background:var(--c);border:2px solid #eee;box-shadow:inset 0 0 0 2px white}
84
+ .swatch.selected{border-color:#111}
85
+ .product-info form .black{width:100%;font-weight:bold}
86
+ .benefits{padding:22px 0;border-bottom:1px solid #ddd;display:flex;gap:15px;justify-content:space-between;font-size:12px}
87
+ .benefits span{display:flex;align-items:center;gap:6px}
88
+ .benefits img{width:24px;height:24px;object-fit:contain}
89
+ .details{max-width:960px;margin:auto;padding:40px 28px 100px}
90
+ .details h2{font:40px var(--serif);font-weight:normal}
91
+ .details details{border-top:1px solid #bbb;padding:20px 0}
92
+ .details summary{font-weight:bold}
93
+ .reviews{background:#f7f4f0;padding:30px;margin-top:40px}
94
+ .cart-layout{display:grid;grid-template-columns:1.6fr 1fr;gap:70px}
95
+ .lineitem{display:grid;grid-template-columns:160px 1fr;border-top:1px solid #ddd;padding:35px 0}
96
+ .lineitem>div:first-child{background:#f6f4f2}
97
+ .lineitem img{display:block;width:100%;height:100%;object-fit:cover}
98
+ .lineitem h2{font:22px var(--serif)}
99
+ .lineitem form{display:inline-block}
100
+ .lineitem input{width:65px;padding:8px}
101
+ .lineitem button{padding:8px}
102
+ .link{border:0;background:none;text-decoration:underline}
103
+ .summary{border:1px solid #ddd;padding:28px}
104
+ .summary>p{display:flex;justify-content:space-between}
105
+ .summary .total{font-size:20px}
106
+ .summary label{display:block}
107
+ .summary input{width:100%;padding:13px;margin:8px 0}
108
+ .summary form button{width:100%;padding:12px}
109
+ .summary>.black{display:block;margin:18px 0}
110
+ .notice,.simulation{background:#edf7ed;border-left:4px solid #487948;padding:14px}
111
+ .checkout{min-height:900px}
112
+ .checkout>form{display:grid;grid-template-columns:1.1fr 1fr}
113
+ .checkout>form>div{padding:20px max(30px,calc((100vw - 1040px)/2));padding-right:40px}
114
+ .checkout-logo{display:block;margin:0 0 50px;text-decoration:none}
115
+ .checkout h2{margin-top:30px}
116
+ .field{display:block;border:1px solid #bbb;border-radius:9px;padding:7px 10px;margin:10px 0;color:#666}
117
+ .field input,.field select{display:block;border:0;width:100%;outline:0;padding:4px 0;background:white}
118
+ .field:focus-within{border-color:#111;box-shadow:0 0 0 3px #005fcc}
119
+ .two,.three{display:grid;grid-template-columns:1fr 1fr;gap:10px}
120
+ .three{grid-template-columns:1fr 1fr 1fr}
121
+ .invalid{border-color:#b21d1d}
122
+ .error{color:#a31111;display:block;margin-top:-7px}
123
+ .shipping,.review-box{display:flex;justify-content:space-between;border:1px solid #aaa;border-radius:9px;padding:18px;margin:12px 0}
124
+ .shipping-options{border:0;padding:0;margin:0}
125
+ .sandbox-choice{display:block;margin-top:20px;font-weight:bold}
126
+ .sandbox-choice select{display:block;width:100%;padding:12px;margin-top:6px;background:#fff;border:1px solid #aaa}
127
+ .sandbox-status{padding:14px;border-left:4px solid #777;background:#f4f4f4}
128
+ .sandbox-status.success{border-color:#487948;background:#edf7ed}
129
+ .sandbox-status.error{border-color:#a31111;background:#fff0f0}
130
+ .visually-hidden{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
131
+ .checkout form .black{width:100%;margin-top:20px}
132
+ .checkout-summary{background:#f7f7f7;padding:105px 40px;min-height:900px}
133
+ .checkout-item{display:grid;grid-template-columns:75px 1fr auto;gap:14px;align-items:center;margin-bottom:30px}
134
+ .checkout-item>div{background:#fff;border:1px solid #ddd;border-radius:10px}
135
+ .checkout-item img{display:block;width:100%;height:100%;object-fit:cover;border-radius:9px}
136
+ .checkout-summary>p{display:flex;justify-content:space-between}
137
+ .checkout-summary .total{font-size:20px}
138
+ .checkout-summary strong{display:block;margin-top:10px}
139
+ .review-box{display:block}
140
+ .review-box b{display:inline-block;width:100px}
141
+ .auth{max-width:500px;margin:80px auto;padding:35px}
142
+ .auth h1{font:44px var(--serif)}
143
+ .auth label{display:block;margin:14px 0}
144
+ .auth input{width:100%;padding:13px;margin-top:5px}
145
+ .auth button{width:100%}
146
+ .auth small{display:block;margin-top:25px}
147
+ .account nav{display:flex;gap:22px;align-items:center}
148
+ .order{border:1px solid #ddd;padding:22px;max-width:700px}
149
+ .order-actions{display:flex;align-items:center;flex-wrap:wrap;gap:15px;margin:22px 0}
150
+ .order-actions form{margin:0}
151
+ .info{max-width:850px}
152
+ .info label{display:block;margin:15px 0}
153
+ .info input,.info textarea{display:block;width:100%;padding:12px}
154
+ .not-found{text-align:center;padding:120px 20px}
155
+ .not-found>span{font:100px var(--serif);color:#ddd}
156
+ .not-found h1{font:45px var(--serif)}
157
+ .not-found a{display:block;width:max-content;margin:18px auto}
158
+ footer{background:#292929;color:white;padding:65px 5%;display:grid;grid-template-columns:2fr repeat(4,1fr);gap:35px}
159
+ footer h2{font:34px var(--serif);font-weight:normal}
160
+ footer a{display:block;margin:9px 0;color:#ddd}
161
+ .fake-input{border:1px solid #999;padding:12px}
162
+ .fake-input b{float:right}
163
+ footer>small{grid-column:1/-1;border-top:1px solid #555;padding-top:20px}
164
+
165
+ .cookie-banner{position:fixed;z-index:30;left:0;right:0;bottom:0;min-height:111px;background:#fff;box-shadow:0 -2px 12px #0002;display:grid;grid-template-columns:250px minmax(450px,1fr) 410px;align-items:center;padding:18px 48px 18px 32px;gap:0;color:#333;font-size:13px}
166
+ .cookie-banner p{margin:0;line-height:1.6}
167
+ .cookie-monogram{height:42px;transform:translateX(-8px)}
168
+ .cookie-monogram img{display:block;width:242px;height:42px;object-fit:contain}
169
+ .cookie-actions{display:flex;justify-content:flex-end;gap:6px;padding-left:22px}
170
+ .cookie-actions button{border:0;background:#333;color:#fff;border-radius:5px;height:36px;min-width:140px;font-size:11.7px;font-weight:700}
171
+ .cookie-actions .preferences{background:#fff;color:#222;border:2px solid #333;min-width:96px}
172
+ .cookie-close{position:absolute;right:18px;top:38px;border:0;background:transparent;font-size:13px;line-height:9.75px;color:#666}
173
+ .newsletter-backdrop{position:fixed;z-index:20;inset:0 0 111px;background:#0007;display:flex;align-items:flex-start;justify-content:center;padding-top:159px}
174
+ .newsletter-dialog{width:780px;height:582px;background:#fff;display:grid;grid-template-columns:1fr 1fr;position:relative;box-shadow:0 10px 40px #0003}
175
+ .newsletter-dialog>img{display:block;width:100%;height:582px;object-fit:cover;object-position:55% center}
176
+ .newsletter-close{position:absolute;z-index:2;right:9px;top:9px;width:34px;height:34px;border-radius:50%;border:1px solid #aaa;background:#fff;font-size:30px;line-height:27px;font-weight:200}
177
+ .newsletter-copy{align-self:center;text-align:center;padding:0 30px;margin-top:6px}
178
+ .newsletter-copy h2{font:35px/1.15 var(--serif);font-weight:normal;margin:0 0 14px;color:#333}
179
+ .newsletter-copy p{font-size:16px;line-height:1.35;margin:0 0 20px}
180
+ .newsletter-copy input{display:block;width:100%;height:50px;border:1px solid #9aa0a4;border-radius:4px;padding:0 16px;font-size:16px}
181
+ .newsletter-copy>button{display:block;width:100%;height:54px;border:0;border-radius:5px;background:#211d1b;color:#fff;font-weight:bold;font-size:18px;margin-top:10px}
182
+ .newsletter-status{display:block;margin-top:7px}
183
+
184
+ @media(max-width:760px){.brandbar{height:48px;padding:0 24px;gap:24px}
185
+ .brandbar>a{height:40px;padding:10px;align-self:flex-end}
186
+ .brandbar .logo{width:152px;max-height:18px}
187
+ .brandbar>b{font-size:18px;transform:translateX(-5px)}
188
+ .brandbar>span,.offer{display:none}
189
+ header{height:114px;padding-top:48px;justify-content:center;background:linear-gradient(#f9f8f6 0 50px,#fff 50px)}
190
+ .mobile-menu{display:flex;position:absolute;left:14px;bottom:9px}
191
+ .mobile-menu svg{width:22px;height:22px}
192
+ header>a{position:absolute;left:68px;bottom:21px}
193
+ header>a .logo{width:230px;height:19px}
194
+ header nav{display:none;position:absolute;top:114px;left:0;right:0;flex-direction:column;background:white;padding:20px;box-shadow:0 10px 20px #0002}
195
+ header nav.open{display:flex}
196
+ .icons{position:absolute;right:12px;bottom:9px;gap:4px}
197
+ .icons a[aria-label=Account]{display:none}
198
+ .search-toggle{display:flex}
199
+ .search-toggle svg{width:23px;height:23px;transform:translateX(6px)}
200
+ .icons a[aria-label=Bag] svg{transform:translateX(-2px)}
201
+ .quick-search{top:114px}
202
+ .luxury{height:44px;padding:12px 11px 10px;line-height:19.6px;letter-spacing:.05px;transform:translateX(-1px)}
203
+ .hero{min-height:420px;display:block;position:relative}
204
+ .hero>div:first-child{position:absolute;z-index:2;bottom:15px;left:15px;padding:20px;background:rgba(255,255,255,.88);width:70%}
205
+ .hero>div:first-child{display:none}
206
+ .hero::before,.hero::after{position:absolute;z-index:2;top:173px;width:36px;height:36px;border-radius:50%;background:#fff;color:#777;display:flex;align-items:center;justify-content:center;font:30px/1 Georgia,serif}
207
+ .hero::before{content:"‹";left:25px}.hero::after{content:"›";right:24px}
208
+ .hero h1{font-size:32px}
209
+ .hero-media{height:420px}
210
+ .hero-media img{height:424px;object-position:center;transform:translateY(-4px)}
211
+ .intro{padding:55px 20px}
212
+ .intro h2{font-size:38px}
213
+ .featured,.catalog,.cart,.info,.account{padding:35px 20px 60px}
214
+ .featured h2,.catalog h1,.cart h1,.info h1,.account h1{font-size:38px}
215
+ .grid{grid-template-columns:1fr 1fr;gap:12px}
216
+ .card h3{font-size:17px}
217
+ .filters{align-items:stretch;flex-direction:column}
218
+ .filters select{width:100%}
219
+ .crumbs{margin:45px auto 15px;padding:0 18px}
220
+ .product{display:block;padding:0 15px}
221
+ .gallery{display:block}
222
+ .gallery>div{min-height:370px}
223
+ .gallery .lifestyle{display:none}
224
+ .product-info{padding:25px 5px}
225
+ .product-info h1{font-size:34px}
226
+ .benefits{flex-direction:column}
227
+ .meta{display:block}
228
+ .details{padding:30px 20px}
229
+ .cart-layout{display:block}
230
+ .lineitem{grid-template-columns:120px 1fr}
231
+ .summary{margin-top:30px}
232
+ .checkout>form{display:block}
233
+ .checkout>form>div{padding:25px 20px}
234
+ .checkout-summary{min-height:auto;padding:35px 20px}
235
+ .two,.three{display:block}
236
+ .account nav{align-items:flex-start;flex-direction:column}
237
+ footer{grid-template-columns:1fr 1fr;padding:45px 25px}
238
+ footer>div:first-child,.newsletter,footer>small{grid-column:1/-1}
239
+ .newsletter-backdrop{display:none}
240
+ .cookie-banner{height:379px;min-height:379px;display:flex;flex-direction:column;align-items:stretch;padding:18px 24px 28px;font-size:13px}
241
+ .cookie-monogram{width:257px;height:42px;padding:0;align-self:center;transform:none;margin-top:6px}
242
+ .cookie-banner p{font-size:13px;line-height:19.8px;letter-spacing:.1px;margin:12.7px 0 16px}
243
+ .cookie-actions{display:flex;flex-direction:column;padding:0;gap:5px}
244
+ .cookie-actions button{width:100%;height:36px;order:1}
245
+ .cookie-actions button[data-cookie-choice=accept]{order:0}
246
+ .cookie-actions .preferences{order:2}
247
+ .cookie-close{right:-10px;top:-10px;min-width:44px;min-height:44px;display:flex;align-items:center;justify-content:center;padding:0}
248
+ }
tasks/dooney-bourke/environment/reference/clone/static/site.js ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ let newsletterBackground=[];
2
+ let newsletterRestoreTarget=null;
3
+
4
+ function restoreNewsletterFocus(){
5
+ const target=newsletterRestoreTarget?.isConnected?newsletterRestoreTarget:document.querySelector('#main');
6
+ if(!(target instanceof HTMLElement))return;
7
+ const temporaryTabindex=!target.hasAttribute('tabindex')&&!target.matches('a,button,input,select,textarea');
8
+ if(temporaryTabindex)target.setAttribute('tabindex','-1');
9
+ target.focus({preventScroll:true});
10
+ if(temporaryTabindex)target.addEventListener('blur',()=>target.removeAttribute('tabindex'),{once:true});
11
+ }
12
+
13
+ function closeNewsletter(){
14
+ const backdrop=document.querySelector('.newsletter-backdrop');
15
+ if(!backdrop)return;
16
+ for(const state of newsletterBackground){
17
+ state.element.inert=state.inert;
18
+ if(state.ariaHidden===null)state.element.removeAttribute('aria-hidden');
19
+ else state.element.setAttribute('aria-hidden',state.ariaHidden);
20
+ }
21
+ newsletterBackground=[];
22
+ backdrop.remove();
23
+ sessionStorage.setItem('wb041-newsletter-closed','1');
24
+ restoreNewsletterFocus();
25
+ }
26
+
27
+ function initializeNewsletter(){
28
+ const backdrop=document.querySelector('.newsletter-backdrop');
29
+ const dialog=backdrop?.querySelector('.newsletter-dialog');
30
+ if(!backdrop||!dialog)return;
31
+ if(sessionStorage.getItem('wb041-newsletter-closed')){
32
+ backdrop.remove();
33
+ return;
34
+ }
35
+ if(getComputedStyle(backdrop).display==='none'||getComputedStyle(dialog).display==='none')return;
36
+
37
+ newsletterRestoreTarget=document.activeElement instanceof HTMLElement&&document.activeElement!==document.body
38
+ ?document.activeElement
39
+ :document.querySelector('#main');
40
+ newsletterBackground=[...document.body.children]
41
+ .filter(element=>element!==backdrop)
42
+ .map(element=>({element,inert:element.inert,ariaHidden:element.getAttribute('aria-hidden')}));
43
+ for(const state of newsletterBackground){
44
+ state.element.inert=true;
45
+ state.element.setAttribute('aria-hidden','true');
46
+ }
47
+
48
+ const focusable=()=>[...dialog.querySelectorAll('button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),a[href],[tabindex]:not([tabindex="-1"])')]
49
+ .filter(element=>element.getClientRects().length);
50
+ dialog.addEventListener('keydown',event=>{
51
+ if(event.key==='Escape'){
52
+ event.preventDefault();
53
+ closeNewsletter();
54
+ return;
55
+ }
56
+ if(event.key!=='Tab')return;
57
+ const items=focusable();
58
+ if(!items.length){event.preventDefault();return;}
59
+ const first=items[0];
60
+ const last=items[items.length-1];
61
+ if(event.shiftKey&&document.activeElement===first){event.preventDefault();last.focus();}
62
+ else if(!event.shiftKey&&document.activeElement===last){event.preventDefault();first.focus();}
63
+ else if(!dialog.contains(document.activeElement)){event.preventDefault();first.focus();}
64
+ });
65
+ document.addEventListener('focusin',event=>{
66
+ if(backdrop.isConnected&&!dialog.contains(event.target))focusable()[0]?.focus();
67
+ });
68
+ dialog.querySelector('#newsletter-email')?.focus({preventScroll:true});
69
+ }
70
+
71
+ document.addEventListener('click',event=>{
72
+ const menu=event.target.closest('.mobile-menu');
73
+ if(menu){const nav=document.querySelector('#primary');nav.classList.toggle('open');menu.setAttribute('aria-expanded',nav.classList.contains('open'));}
74
+ const search=event.target.closest('.search-toggle');
75
+ if(search){document.querySelector('.quick-search').classList.toggle('open');}
76
+ if(event.target.closest('[data-close-newsletter]'))closeNewsletter();
77
+ if(event.target.closest('[data-newsletter-continue]'))document.querySelector('.newsletter-status').textContent='Saved in this page only. No email was sent.';
78
+ const cookieChoice=event.target.closest('[data-cookie-choice]');
79
+ if(cookieChoice){localStorage.setItem('wb041-cookie-choice',cookieChoice.dataset.cookieChoice);document.querySelector('.cookie-banner')?.remove();}
80
+ });
81
+
82
+ if(localStorage.getItem('wb041-cookie-choice'))document.querySelector('.cookie-banner')?.remove();
83
+ initializeNewsletter();
84
+ document.querySelector('[aria-invalid="true"]')?.focus();
85
+
86
+ for(const pair of [['.local-recovery','.recovery-status','If that address belongs to a local account, recovery guidance is available here. No message was sent.'],['.contact','.contact-status','Draft saved only in this page. No support request or email was sent.']]){
87
+ const form=document.querySelector(pair[0]);
88
+ if(form)form.addEventListener('submit',event=>{event.preventDefault();document.querySelector(pair[1]).textContent=pair[2];});
89
+ }
tasks/dooney-bourke/environment/reference/clone/tools/form-contracts.html ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ <!-- Static declarations mirror dynamic WSGI forms so WebsiteBench Harbor derivation can resolve unique actions. This file is never served. -->
2
+ <form method="post" action="/account/login"></form>
3
+ <form method="post" action="/pages/track-your-order"></form>
tasks/dooney-bourke/environment/reference/clone/websitebench/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Vendored WebsiteBench runtime modules."""
tasks/dooney-bourke/environment/reference/clone/websitebench/local_clone_auth/VENDOR_MANIFEST.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "files": [
3
+ {
4
+ "bytes": 820,
5
+ "path": "__init__.py",
6
+ "sha256": "af66b01ced88dc51ccdc0f4fe725f338c7f97513f818ea185a05c1f5df64e876"
7
+ },
8
+ {
9
+ "bytes": 85660,
10
+ "path": "store.py",
11
+ "sha256": "e637836fd32a7779f34d6bc72505accd05030d9a015c8bf5a374490f919a33cf"
12
+ }
13
+ ],
14
+ "schema_version": "websitebench.local-clone-auth.vendor.v1",
15
+ "source": "src/websitebench/local_clone_auth"
16
+ }
tasks/dooney-bourke/environment/reference/clone/websitebench/local_clone_auth/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reusable site-isolated authentication and local-mail runtime for clones."""
2
+
3
+ from .store import (
4
+ MAIL_LOCAL_ONLY,
5
+ MAIL_OUTCOME_UNKNOWN,
6
+ MAIL_SMTP_FAILED,
7
+ MAIL_SMTP_PENDING,
8
+ MAIL_SMTP_SENT,
9
+ AuthBackupError,
10
+ AuthConflict,
11
+ AuthError,
12
+ AuthExpired,
13
+ AuthLocked,
14
+ AuthRateLimited,
15
+ AuthRejected,
16
+ AuthSiteBindingError,
17
+ AuthValidationError,
18
+ LocalAuthStore,
19
+ RESET_PUBLIC_MESSAGE,
20
+ )
21
+
22
+ __all__ = [
23
+ "MAIL_LOCAL_ONLY",
24
+ "MAIL_OUTCOME_UNKNOWN",
25
+ "MAIL_SMTP_FAILED",
26
+ "MAIL_SMTP_PENDING",
27
+ "MAIL_SMTP_SENT",
28
+ "RESET_PUBLIC_MESSAGE",
29
+ "AuthBackupError",
30
+ "AuthConflict",
31
+ "AuthError",
32
+ "AuthExpired",
33
+ "AuthLocked",
34
+ "AuthRateLimited",
35
+ "AuthRejected",
36
+ "AuthSiteBindingError",
37
+ "AuthValidationError",
38
+ "LocalAuthStore",
39
+ ]
tasks/dooney-bourke/environment/reference/clone/websitebench/local_clone_auth/store.py ADDED
@@ -0,0 +1,2186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Amazon-derived generic auth, session, recovery, and mail semantics.
2
+
3
+ The runtime deliberately owns only authentication tables. A clone keeps its
4
+ business account and domain tables in the same site-isolated SQLite database
5
+ and binds them through ``subject_id`` callbacks.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import hmac
12
+ import os
13
+ import re
14
+ import secrets
15
+ import sqlite3
16
+ import threading
17
+ import time
18
+ from collections.abc import Callable, Mapping
19
+ from contextlib import closing, contextmanager
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+
24
+ MAIL_LOCAL_ONLY = "LOCAL_ONLY"
25
+ MAIL_SMTP_PENDING = "SMTP_PENDING"
26
+ MAIL_SMTP_SENT = "SMTP_SENT"
27
+ MAIL_SMTP_FAILED = "SMTP_FAILED"
28
+ MAIL_STATUSES = frozenset(
29
+ {MAIL_LOCAL_ONLY, MAIL_SMTP_PENDING, MAIL_SMTP_SENT, MAIL_SMTP_FAILED}
30
+ )
31
+ RESET_PUBLIC_MESSAGE = (
32
+ "If that email belongs to a local account, a verification message is available."
33
+ )
34
+ PASSWORD_SCHEME = "scrypt-v1"
35
+ CODE_ATTEMPT_LIMIT = 5
36
+ MAIL_DELIVERY_LIMIT = 3
37
+ MAIL_OUTCOME_UNKNOWN = "delivery outcome unknown after reserved target request"
38
+ MAIL_ERROR_CATEGORIES = frozenset(
39
+ {
40
+ "configuration",
41
+ "provider-auth",
42
+ "provider-rate-limit",
43
+ "provider-rejected",
44
+ "network",
45
+ "unknown",
46
+ }
47
+ )
48
+ MAIL_COOLDOWN_SECONDS = 60
49
+ MAIL_HOURLY_LIMIT = 6
50
+ CHALLENGE_TTL_SECONDS = 10 * 60
51
+ SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
52
+ RATE_WINDOW_SECONDS = 60 * 60
53
+ _EMAIL = re.compile(r"^[^@\s]{1,64}@[^@\s]{1,189}$")
54
+
55
+
56
+ class AuthError(RuntimeError):
57
+ """Base class for local auth contract failures."""
58
+
59
+
60
+ class AuthValidationError(AuthError):
61
+ pass
62
+
63
+
64
+ class AuthConflict(AuthError):
65
+ pass
66
+
67
+
68
+ class AuthRejected(AuthError):
69
+ pass
70
+
71
+
72
+ class AuthExpired(AuthRejected):
73
+ pass
74
+
75
+
76
+ class AuthLocked(AuthRejected):
77
+ pass
78
+
79
+
80
+ class AuthRateLimited(AuthRejected):
81
+ def __init__(self, retry_after: int) -> None:
82
+ self.retry_after = max(1, int(retry_after))
83
+ super().__init__(f"mail request is rate limited for {self.retry_after} seconds")
84
+
85
+
86
+ class AuthBackupError(AuthError):
87
+ """Raised when a database backup or restore is unsafe or invalid."""
88
+
89
+
90
+ class AuthSiteBindingError(AuthError):
91
+ """Raised when auth is opened against another site's database."""
92
+
93
+
94
+ class _ClosingConnection(sqlite3.Connection):
95
+ """Commit or roll back, then release SQLite handles on context exit."""
96
+
97
+ def __exit__(self, exc_type, exc_value, traceback) -> bool:
98
+ try:
99
+ return bool(super().__exit__(exc_type, exc_value, traceback))
100
+ finally:
101
+ self.close()
102
+
103
+
104
+ def _now_seconds() -> int:
105
+ return int(time.time())
106
+
107
+
108
+ def _token(prefix: str) -> str:
109
+ return f"{prefix}_{secrets.token_urlsafe(32)}"
110
+
111
+
112
+ def _digest_token(value: str) -> str:
113
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
114
+
115
+
116
+ def _recipient_digest(email: str) -> str:
117
+ return hashlib.sha256(email.encode("utf-8")).hexdigest()
118
+
119
+
120
+ def _sha256_file(path: Path) -> str:
121
+ digest = hashlib.sha256()
122
+ with path.open("rb") as stream:
123
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
124
+ digest.update(chunk)
125
+ return digest.hexdigest()
126
+
127
+
128
+ def _hash_secret(value: str, *, salt: bytes | None = None) -> tuple[bytes, bytes]:
129
+ actual_salt = salt or secrets.token_bytes(16)
130
+ digest = hashlib.scrypt(
131
+ value.encode("utf-8"),
132
+ salt=actual_salt,
133
+ n=2**14,
134
+ r=8,
135
+ p=1,
136
+ dklen=64,
137
+ )
138
+ return actual_salt, digest
139
+
140
+
141
+ def _verify_secret(value: str, salt: bytes, expected: bytes) -> bool:
142
+ _, actual = _hash_secret(value, salt=salt)
143
+ return hmac.compare_digest(actual, expected)
144
+
145
+
146
+ def _verification_code() -> str:
147
+ return f"{secrets.randbelow(1_000_000):06d}"
148
+
149
+
150
+ def _normalize_email(value: str) -> str:
151
+ normalized = value.strip().casefold()
152
+ if (
153
+ len(normalized) > 254
154
+ or _EMAIL.fullmatch(normalized) is None
155
+ or normalized.count("@") != 1
156
+ ):
157
+ raise AuthValidationError("email is invalid")
158
+ local, domain = normalized.rsplit("@", 1)
159
+ if (
160
+ local.startswith(".")
161
+ or local.endswith(".")
162
+ or ".." in local
163
+ or domain.startswith(".")
164
+ or domain.endswith(".")
165
+ or "." not in domain
166
+ ):
167
+ raise AuthValidationError("email is invalid")
168
+ return normalized
169
+
170
+
171
+ def _validate_display_name(value: str) -> str:
172
+ normalized = " ".join(value.split())
173
+ if not 1 <= len(normalized) <= 120:
174
+ raise AuthValidationError("display name must contain 1 to 120 characters")
175
+ return normalized
176
+
177
+
178
+ def _validate_password(value: str) -> str:
179
+ if not 8 <= len(value) <= 128:
180
+ raise AuthValidationError("password must contain 8 to 128 characters")
181
+ if value.isspace():
182
+ raise AuthValidationError("password cannot be only whitespace")
183
+ return value
184
+
185
+
186
+ def _validate_code(value: str) -> str:
187
+ normalized = value.strip()
188
+ if re.fullmatch(r"\d{6}", normalized) is None:
189
+ raise AuthValidationError("verification code must contain exactly six digits")
190
+ return normalized
191
+
192
+
193
+ SCHEMA_SQL = """
194
+ CREATE TABLE IF NOT EXISTS local_auth_schema_migrations (
195
+ version TEXT PRIMARY KEY,
196
+ applied_at INTEGER NOT NULL
197
+ );
198
+
199
+ CREATE TABLE IF NOT EXISTS local_auth_accounts (
200
+ account_id TEXT PRIMARY KEY,
201
+ subject_id TEXT NOT NULL UNIQUE,
202
+ email_normalized TEXT NOT NULL UNIQUE,
203
+ display_name TEXT NOT NULL,
204
+ password_salt BLOB NOT NULL,
205
+ password_hash BLOB NOT NULL,
206
+ password_scheme TEXT NOT NULL CHECK (password_scheme='scrypt-v1'),
207
+ email_verified INTEGER NOT NULL CHECK (email_verified IN (0,1)),
208
+ created_at INTEGER NOT NULL,
209
+ password_updated_at INTEGER NOT NULL
210
+ );
211
+
212
+ CREATE TABLE IF NOT EXISTS local_auth_sessions (
213
+ session_digest TEXT PRIMARY KEY,
214
+ account_id TEXT REFERENCES local_auth_accounts(account_id) ON DELETE SET NULL,
215
+ created_at INTEGER NOT NULL,
216
+ expires_at INTEGER NOT NULL,
217
+ revoked_at INTEGER,
218
+ CHECK (expires_at > created_at)
219
+ );
220
+ CREATE INDEX IF NOT EXISTS local_auth_sessions_account_idx
221
+ ON local_auth_sessions(account_id);
222
+
223
+ CREATE TABLE IF NOT EXISTS local_auth_registration_flows (
224
+ pending_id TEXT PRIMARY KEY,
225
+ session_digest TEXT NOT NULL UNIQUE
226
+ REFERENCES local_auth_sessions(session_digest) ON DELETE CASCADE,
227
+ email_normalized TEXT NOT NULL,
228
+ display_name TEXT NOT NULL,
229
+ password_salt BLOB NOT NULL,
230
+ password_hash BLOB NOT NULL,
231
+ password_scheme TEXT NOT NULL CHECK (password_scheme='scrypt-v1'),
232
+ code_salt BLOB NOT NULL,
233
+ code_hash BLOB NOT NULL,
234
+ expires_at INTEGER NOT NULL,
235
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 5),
236
+ verified_at INTEGER,
237
+ created_at INTEGER NOT NULL,
238
+ updated_at INTEGER NOT NULL
239
+ );
240
+
241
+ CREATE TABLE IF NOT EXISTS local_auth_password_reset_flows (
242
+ reset_id TEXT PRIMARY KEY,
243
+ session_digest TEXT NOT NULL UNIQUE
244
+ REFERENCES local_auth_sessions(session_digest) ON DELETE CASCADE,
245
+ account_id TEXT REFERENCES local_auth_accounts(account_id) ON DELETE CASCADE,
246
+ code_salt BLOB NOT NULL,
247
+ code_hash BLOB NOT NULL,
248
+ expires_at INTEGER NOT NULL,
249
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 5),
250
+ verified_at INTEGER,
251
+ created_at INTEGER NOT NULL,
252
+ updated_at INTEGER NOT NULL
253
+ );
254
+ CREATE UNIQUE INDEX IF NOT EXISTS local_auth_password_reset_account_idx
255
+ ON local_auth_password_reset_flows(account_id)
256
+ WHERE account_id IS NOT NULL;
257
+
258
+ CREATE TABLE IF NOT EXISTS local_auth_mail_outbox (
259
+ mail_id INTEGER PRIMARY KEY AUTOINCREMENT,
260
+ purpose TEXT NOT NULL CHECK (
261
+ purpose IN ('registration','password-reset')
262
+ ),
263
+ flow_id TEXT NOT NULL,
264
+ session_digest TEXT NOT NULL
265
+ REFERENCES local_auth_sessions(session_digest) ON DELETE CASCADE,
266
+ recipient TEXT NOT NULL,
267
+ template TEXT NOT NULL CHECK (
268
+ template IN ('registration-verification','password-reset-verification')
269
+ ),
270
+ status TEXT NOT NULL CHECK (
271
+ status IN ('LOCAL_ONLY','SMTP_PENDING','SMTP_SENT','SMTP_FAILED')
272
+ ),
273
+ is_simulation INTEGER NOT NULL CHECK (is_simulation IN (0,1)),
274
+ delivery_attempts INTEGER NOT NULL DEFAULT 0 CHECK (delivery_attempts >= 0),
275
+ delivery_state_version INTEGER NOT NULL DEFAULT 0
276
+ CHECK (delivery_state_version >= 0),
277
+ request_id TEXT,
278
+ target_request_count INTEGER NOT NULL DEFAULT 0
279
+ CHECK (target_request_count >= 0),
280
+ accepted_effect_count INTEGER NOT NULL DEFAULT 0
281
+ CHECK (
282
+ accepted_effect_count >= 0
283
+ AND accepted_effect_count <= target_request_count
284
+ ),
285
+ claim_token TEXT,
286
+ claim_target_reserved INTEGER NOT NULL DEFAULT 0
287
+ CHECK (claim_target_reserved IN (0,1)),
288
+ last_error TEXT,
289
+ attempted_at INTEGER,
290
+ sent_at INTEGER,
291
+ created_at INTEGER NOT NULL,
292
+ UNIQUE (purpose, flow_id),
293
+ CHECK (
294
+ (status='LOCAL_ONLY' AND is_simulation=1)
295
+ OR (status<>'LOCAL_ONLY' AND is_simulation=0)
296
+ )
297
+ );
298
+ CREATE INDEX IF NOT EXISTS local_auth_mail_pending_idx
299
+ ON local_auth_mail_outbox(status, mail_id);
300
+
301
+ CREATE TABLE IF NOT EXISTS local_auth_mail_rate_limits (
302
+ purpose TEXT NOT NULL CHECK (
303
+ purpose IN ('registration','password-reset')
304
+ ),
305
+ scope_type TEXT NOT NULL CHECK (
306
+ scope_type IN ('session','recipient','account')
307
+ ),
308
+ scope_key TEXT NOT NULL,
309
+ window_started_at INTEGER NOT NULL,
310
+ send_count INTEGER NOT NULL CHECK (send_count >= 0),
311
+ last_sent_at INTEGER NOT NULL,
312
+ PRIMARY KEY (purpose, scope_type, scope_key)
313
+ );
314
+ """
315
+
316
+
317
+ class LocalAuthStore:
318
+ """Site-local SQLite auth store with explicit offline mail truth.
319
+
320
+ ``site_id=None`` exists only for unmigrated legacy callers. New scaffolded
321
+ and migrated sites must pass a canonical site id so a foreign database
322
+ fails closed before any account table is used.
323
+ """
324
+
325
+ def __init__(
326
+ self,
327
+ database_path: Path | str,
328
+ *,
329
+ now: Callable[[], int] = _now_seconds,
330
+ mail_mode: str = MAIL_LOCAL_ONLY,
331
+ mail_worker_token: str | None = None,
332
+ site_id: str | None = None,
333
+ ) -> None:
334
+ self.database_path = Path(database_path)
335
+ self._now = now
336
+ self._schema_ready = False
337
+ self._schema_lock = threading.RLock()
338
+ self._mail_secrets: dict[tuple[str, str], str] = {}
339
+ self._mail_secrets_lock = threading.RLock()
340
+ if site_id is not None and (
341
+ not isinstance(site_id, str)
342
+ or re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", site_id) is None
343
+ ):
344
+ raise ValueError("site_id must be a canonical site identifier")
345
+ self.site_id = site_id
346
+ if mail_mode not in {MAIL_LOCAL_ONLY, MAIL_SMTP_PENDING}:
347
+ raise ValueError("mail_mode must be LOCAL_ONLY or SMTP_PENDING")
348
+ if mail_mode == MAIL_SMTP_PENDING and (
349
+ not isinstance(mail_worker_token, str) or len(mail_worker_token) < 20
350
+ ):
351
+ raise ValueError("SMTP_PENDING requires an injected mail worker token")
352
+ self.mail_mode = mail_mode
353
+ self._mail_worker_digest = (
354
+ _digest_token(mail_worker_token)
355
+ if isinstance(mail_worker_token, str)
356
+ else None
357
+ )
358
+
359
+ def _authorize_mail_worker(self, worker_token: str | None) -> None:
360
+ expected = self._mail_worker_digest
361
+ supplied = _digest_token(worker_token) if isinstance(worker_token, str) else ""
362
+ if expected is None or not hmac.compare_digest(expected, supplied):
363
+ raise AuthRejected("mail worker authority is required")
364
+
365
+ def connect(self) -> sqlite3.Connection:
366
+ self.database_path.parent.mkdir(parents=True, exist_ok=True)
367
+ connection = sqlite3.connect(
368
+ str(self.database_path),
369
+ timeout=10,
370
+ isolation_level=None,
371
+ factory=_ClosingConnection,
372
+ )
373
+ connection.row_factory = sqlite3.Row
374
+ connection.execute("PRAGMA foreign_keys=ON")
375
+ connection.execute("PRAGMA secure_delete=ON")
376
+ connection.execute("PRAGMA busy_timeout=5000")
377
+ connection.execute("PRAGMA journal_mode=WAL")
378
+ return connection
379
+
380
+ @contextmanager
381
+ def _transaction(self, connection: sqlite3.Connection):
382
+ connection.execute("BEGIN IMMEDIATE")
383
+ try:
384
+ yield
385
+ except BaseException:
386
+ connection.rollback()
387
+ raise
388
+ else:
389
+ connection.commit()
390
+
391
+ @staticmethod
392
+ def _mail_outbox_schema_sql() -> str:
393
+ return """
394
+ CREATE TABLE local_auth_mail_outbox (
395
+ mail_id INTEGER PRIMARY KEY AUTOINCREMENT,
396
+ purpose TEXT NOT NULL CHECK (
397
+ purpose IN ('registration','password-reset')
398
+ ),
399
+ flow_id TEXT NOT NULL,
400
+ session_digest TEXT NOT NULL
401
+ REFERENCES local_auth_sessions(session_digest) ON DELETE CASCADE,
402
+ recipient TEXT NOT NULL,
403
+ template TEXT NOT NULL CHECK (
404
+ template IN (
405
+ 'registration-verification','password-reset-verification'
406
+ )
407
+ ),
408
+ status TEXT NOT NULL CHECK (
409
+ status IN (
410
+ 'LOCAL_ONLY','SMTP_PENDING','SMTP_SENT','SMTP_FAILED'
411
+ )
412
+ ),
413
+ is_simulation INTEGER NOT NULL CHECK (is_simulation IN (0,1)),
414
+ delivery_attempts INTEGER NOT NULL DEFAULT 0
415
+ CHECK (delivery_attempts >= 0),
416
+ delivery_state_version INTEGER NOT NULL DEFAULT 0
417
+ CHECK (delivery_state_version >= 0),
418
+ request_id TEXT,
419
+ target_request_count INTEGER NOT NULL DEFAULT 0
420
+ CHECK (target_request_count >= 0),
421
+ accepted_effect_count INTEGER NOT NULL DEFAULT 0
422
+ CHECK (
423
+ accepted_effect_count >= 0
424
+ AND accepted_effect_count <= target_request_count
425
+ ),
426
+ claim_token TEXT,
427
+ claim_target_reserved INTEGER NOT NULL DEFAULT 0
428
+ CHECK (claim_target_reserved IN (0,1)),
429
+ last_error TEXT,
430
+ attempted_at INTEGER,
431
+ sent_at INTEGER,
432
+ created_at INTEGER NOT NULL,
433
+ UNIQUE (purpose, flow_id),
434
+ CHECK (
435
+ (status='LOCAL_ONLY' AND is_simulation=1)
436
+ OR (status<>'LOCAL_ONLY' AND is_simulation=0)
437
+ )
438
+ );
439
+ CREATE INDEX local_auth_mail_pending_idx
440
+ ON local_auth_mail_outbox(status, mail_id);
441
+ """
442
+
443
+ def ensure_schema(self) -> None:
444
+ with self._schema_lock:
445
+ if self._schema_ready:
446
+ return
447
+ now = self._now()
448
+ with self.connect() as connection:
449
+ if self.site_id is not None:
450
+ legacy_binding = connection.execute(
451
+ "SELECT 1 FROM sqlite_master WHERE type='table' "
452
+ "AND name='clawbench_site_binding'"
453
+ ).fetchone()
454
+ if legacy_binding is not None:
455
+ raise AuthSiteBindingError(
456
+ "auth database is bound by the other runtime "
457
+ "namespace"
458
+ )
459
+ binding_table = connection.execute(
460
+ "SELECT 1 FROM sqlite_master WHERE type='table' "
461
+ "AND name='websitebench_site_binding'"
462
+ ).fetchone()
463
+ rows = (
464
+ connection.execute(
465
+ "SELECT singleton,site_id FROM websitebench_site_binding"
466
+ ).fetchall()
467
+ if binding_table is not None
468
+ else []
469
+ )
470
+ if (
471
+ len(rows) != 1
472
+ or int(rows[0]["singleton"]) != 1
473
+ or str(rows[0]["site_id"]) != self.site_id
474
+ ):
475
+ raise AuthSiteBindingError(
476
+ "auth database site binding is missing or foreign"
477
+ )
478
+ connection.executescript(SCHEMA_SQL)
479
+ columns = {
480
+ str(row["name"])
481
+ for row in connection.execute(
482
+ "PRAGMA table_info(local_auth_mail_outbox)"
483
+ )
484
+ }
485
+ if "verification_code" in columns:
486
+ # Never copy a legacy cleartext OTP. The associated
487
+ # unfinished challenge must be issued again.
488
+ connection.execute("DELETE FROM local_auth_mail_outbox")
489
+ connection.execute("DELETE FROM local_auth_registration_flows")
490
+ connection.execute(
491
+ "DELETE FROM local_auth_password_reset_flows "
492
+ "WHERE verified_at IS NULL"
493
+ )
494
+ connection.execute(
495
+ "DROP INDEX IF EXISTS local_auth_mail_pending_idx"
496
+ )
497
+ connection.execute(
498
+ "ALTER TABLE local_auth_mail_outbox "
499
+ "RENAME TO local_auth_mail_outbox_plaintext_legacy"
500
+ )
501
+ connection.executescript(
502
+ self._mail_outbox_schema_sql()
503
+ + "\nDROP TABLE local_auth_mail_outbox_plaintext_legacy;"
504
+ )
505
+ columns = {
506
+ str(row["name"])
507
+ for row in connection.execute(
508
+ "PRAGMA table_info(local_auth_mail_outbox)"
509
+ )
510
+ }
511
+
512
+ # This process starts without any cleartext OTP material, so
513
+ # unsent or retryable SMTP work cannot be delivered after a
514
+ # restart. Keep hash-only LOCAL_ONLY audit rows and terminal
515
+ # SMTP_SENT evidence; neither can be replayed as delivery.
516
+ connection.execute(
517
+ "DELETE FROM local_auth_mail_outbox "
518
+ "WHERE status IN ('SMTP_PENDING','SMTP_FAILED')"
519
+ )
520
+ connection.execute(
521
+ "INSERT OR IGNORE INTO local_auth_schema_migrations"
522
+ "(version,applied_at) VALUES ('0001',?)",
523
+ (now,),
524
+ )
525
+ applied_versions = {
526
+ str(row["version"])
527
+ for row in connection.execute(
528
+ "SELECT version FROM local_auth_schema_migrations"
529
+ )
530
+ }
531
+ additions = {
532
+ "delivery_state_version": ("INTEGER NOT NULL DEFAULT 0"),
533
+ "request_id": "TEXT",
534
+ "target_request_count": "INTEGER NOT NULL DEFAULT 0",
535
+ "accepted_effect_count": "INTEGER NOT NULL DEFAULT 0",
536
+ "claim_target_reserved": "INTEGER NOT NULL DEFAULT 0",
537
+ }
538
+ for column, declaration in additions.items():
539
+ if column not in columns:
540
+ connection.execute(
541
+ "ALTER TABLE local_auth_mail_outbox "
542
+ f"ADD COLUMN {column} {declaration}"
543
+ )
544
+ if "0002" not in applied_versions:
545
+ connection.execute(
546
+ "UPDATE local_auth_mail_outbox SET request_id="
547
+ "'migrated-mail-' || printf('%016x',mail_id) "
548
+ "WHERE request_id IS NULL"
549
+ )
550
+ connection.execute(
551
+ "UPDATE local_auth_mail_outbox SET "
552
+ "target_request_count=MAX(target_request_count,1),"
553
+ "accepted_effect_count=1 "
554
+ "WHERE status='SMTP_SENT'"
555
+ )
556
+ for version in ("0002", "0003", "0004"):
557
+ connection.execute(
558
+ "INSERT OR IGNORE INTO local_auth_schema_migrations"
559
+ "(version,applied_at) VALUES (?,?)",
560
+ (version, now),
561
+ )
562
+ connection.execute("PRAGMA wal_checkpoint(TRUNCATE)")
563
+ self._schema_ready = True
564
+
565
+ @staticmethod
566
+ def _mail_secret_key(purpose: str, flow_id: str) -> tuple[str, str]:
567
+ if purpose not in {"registration", "password-reset"}:
568
+ raise ValueError("unknown mail purpose")
569
+ if not isinstance(flow_id, str) or not flow_id:
570
+ raise ValueError("mail flow id is invalid")
571
+ return purpose, flow_id
572
+
573
+ def _remember_mail_code(self, purpose: str, flow_id: str, code: str) -> None:
574
+ normalized = _validate_code(code)
575
+ key = self._mail_secret_key(purpose, flow_id)
576
+ with self._mail_secrets_lock:
577
+ self._mail_secrets[key] = normalized
578
+
579
+ def _mail_code(self, purpose: str, flow_id: str) -> str | None:
580
+ key = self._mail_secret_key(purpose, flow_id)
581
+ with self._mail_secrets_lock:
582
+ return self._mail_secrets.get(key)
583
+
584
+ def _clear_mail_secrets(self) -> None:
585
+ with self._mail_secrets_lock:
586
+ self._mail_secrets.clear()
587
+
588
+ def applied_migrations(self) -> list[str]:
589
+ self.ensure_schema()
590
+ with self.connect() as connection:
591
+ return [
592
+ str(row["version"])
593
+ for row in connection.execute(
594
+ "SELECT version FROM local_auth_schema_migrations ORDER BY version"
595
+ )
596
+ ]
597
+
598
+ def _session_row(
599
+ self,
600
+ connection: sqlite3.Connection,
601
+ session_token: str | None,
602
+ *,
603
+ include_revoked: bool = False,
604
+ ) -> sqlite3.Row | None:
605
+ if (
606
+ not isinstance(session_token, str)
607
+ or not 20 <= len(session_token) <= 200
608
+ or not session_token.startswith("session_")
609
+ ):
610
+ return None
611
+ digest = _digest_token(session_token)
612
+ row = connection.execute(
613
+ "SELECT * FROM local_auth_sessions WHERE session_digest=?",
614
+ (digest,),
615
+ ).fetchone()
616
+ if row is None:
617
+ return None
618
+ now = self._now()
619
+ if not include_revoked and (
620
+ row["revoked_at"] is not None or int(row["expires_at"]) <= now
621
+ ):
622
+ return None
623
+ return row
624
+
625
+ def create_anonymous_session(self) -> str:
626
+ self.ensure_schema()
627
+ now = self._now()
628
+ token = _token("session")
629
+ with self.connect() as connection, self._transaction(connection):
630
+ connection.execute(
631
+ "INSERT INTO local_auth_sessions"
632
+ "(session_digest,account_id,created_at,expires_at,revoked_at)"
633
+ " VALUES (?,?,?,?,NULL)",
634
+ (_digest_token(token), None, now, now + SESSION_TTL_SECONDS),
635
+ )
636
+ return token
637
+
638
+ def ensure_session(self, session_token: str | None) -> tuple[str, dict[str, Any]]:
639
+ self.ensure_schema()
640
+ with self.connect() as connection:
641
+ row = self._session_row(connection, session_token)
642
+ if row is not None:
643
+ return str(session_token), self._public_session(connection, row)
644
+ token = self.create_anonymous_session()
645
+ resolved = self.resolve_session(token)
646
+ if resolved is None: # pragma: no cover - defensive invariant
647
+ raise RuntimeError("newly created session could not be resolved")
648
+ return token, resolved
649
+
650
+ def _public_session(
651
+ self, connection: sqlite3.Connection, row: sqlite3.Row
652
+ ) -> dict[str, Any]:
653
+ account = None
654
+ if row["account_id"] is not None:
655
+ account_row = connection.execute(
656
+ "SELECT account_id,subject_id,email_normalized,display_name,"
657
+ "email_verified FROM local_auth_accounts WHERE account_id=?",
658
+ (row["account_id"],),
659
+ ).fetchone()
660
+ if account_row is not None:
661
+ account = dict(account_row)
662
+ return {
663
+ "authenticated": account is not None,
664
+ "account": account,
665
+ "created_at": int(row["created_at"]),
666
+ "expires_at": int(row["expires_at"]),
667
+ }
668
+
669
+ def resolve_session(self, session_token: str | None) -> dict[str, Any] | None:
670
+ self.ensure_schema()
671
+ with self.connect() as connection:
672
+ row = self._session_row(connection, session_token)
673
+ return self._public_session(connection, row) if row is not None else None
674
+
675
+ def session_owner_digest(self, session_token: str | None) -> str:
676
+ """Resolve one live opaque session to its server-side owner digest."""
677
+
678
+ self.ensure_schema()
679
+ with self.connect() as connection:
680
+ row = self._session_row(connection, session_token)
681
+ if row is None:
682
+ raise AuthRejected("session is invalid or expired")
683
+ return str(row["session_digest"])
684
+
685
+ def account_exists(self, email: str) -> bool:
686
+ """Return whether a normalized email already owns a local account."""
687
+
688
+ normalized_email = _normalize_email(email)
689
+ self.ensure_schema()
690
+ with self.connect() as connection:
691
+ return (
692
+ connection.execute(
693
+ "SELECT 1 FROM local_auth_accounts WHERE email_normalized=?",
694
+ (normalized_email,),
695
+ ).fetchone()
696
+ is not None
697
+ )
698
+
699
+ def validate_registration_details(
700
+ self,
701
+ *,
702
+ email: str,
703
+ display_name: str,
704
+ password: str,
705
+ ) -> dict[str, str]:
706
+ """Validate account fields before consuming an external verification."""
707
+
708
+ return {
709
+ "email": _normalize_email(email),
710
+ "display_name": _validate_display_name(display_name),
711
+ "password": _validate_password(password),
712
+ }
713
+
714
+ def _rotate_session_unlocked(
715
+ self,
716
+ connection: sqlite3.Connection,
717
+ old_digest: str,
718
+ account_id: str,
719
+ now: int,
720
+ session_rotation_callback: (
721
+ Callable[[sqlite3.Connection, str, str], None] | None
722
+ ) = None,
723
+ ) -> str:
724
+ connection.execute(
725
+ "UPDATE local_auth_sessions SET revoked_at=? "
726
+ "WHERE session_digest=? AND revoked_at IS NULL",
727
+ (now, old_digest),
728
+ )
729
+ token = _token("session")
730
+ new_digest = _digest_token(token)
731
+ connection.execute(
732
+ "INSERT INTO local_auth_sessions"
733
+ "(session_digest,account_id,created_at,expires_at,revoked_at)"
734
+ " VALUES (?,?,?,?,NULL)",
735
+ (
736
+ new_digest,
737
+ account_id,
738
+ now,
739
+ now + SESSION_TTL_SECONDS,
740
+ ),
741
+ )
742
+ if session_rotation_callback is not None:
743
+ session_rotation_callback(connection, old_digest, new_digest)
744
+ return token
745
+
746
+ def _seed_account_unlocked(
747
+ self,
748
+ connection: sqlite3.Connection,
749
+ *,
750
+ subject_id: str,
751
+ email: str,
752
+ display_name: str,
753
+ password: str,
754
+ email_verified: bool = True,
755
+ ) -> str:
756
+ normalized_email = _normalize_email(email)
757
+ normalized_name = _validate_display_name(display_name)
758
+ validated_password = _validate_password(password)
759
+ salt, password_hash = _hash_secret(validated_password)
760
+ now = self._now()
761
+ account_id = f"account_{_digest_token(subject_id)[:24]}"
762
+ existing = connection.execute(
763
+ "SELECT account_id,email_normalized FROM local_auth_accounts "
764
+ "WHERE subject_id=?",
765
+ (subject_id,),
766
+ ).fetchone()
767
+ if existing is not None:
768
+ if existing["email_normalized"] != normalized_email:
769
+ raise AuthConflict("subject is already bound to another email")
770
+ return str(existing["account_id"])
771
+ connection.execute(
772
+ "INSERT INTO local_auth_accounts("
773
+ "account_id,subject_id,email_normalized,display_name,"
774
+ "password_salt,password_hash,password_scheme,email_verified,"
775
+ "created_at,password_updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
776
+ (
777
+ account_id,
778
+ subject_id,
779
+ normalized_email,
780
+ normalized_name,
781
+ salt,
782
+ password_hash,
783
+ PASSWORD_SCHEME,
784
+ 1 if email_verified else 0,
785
+ now,
786
+ now,
787
+ ),
788
+ )
789
+ return account_id
790
+
791
+ def seed_account(
792
+ self,
793
+ *,
794
+ subject_id: str,
795
+ email: str,
796
+ display_name: str,
797
+ password: str,
798
+ email_verified: bool = True,
799
+ ) -> str:
800
+ """Idempotently bind one legacy fixture subject to real credentials."""
801
+
802
+ self.ensure_schema()
803
+ with self.connect() as connection, self._transaction(connection):
804
+ return self._seed_account_unlocked(
805
+ connection,
806
+ subject_id=subject_id,
807
+ email=email,
808
+ display_name=display_name,
809
+ password=password,
810
+ email_verified=email_verified,
811
+ )
812
+
813
+ def reset_site_state(
814
+ self,
815
+ *,
816
+ site_reset: Callable[[sqlite3.Connection], None],
817
+ seed_accounts: list[Mapping[str, Any]],
818
+ ) -> None:
819
+ """Reset auth and site state in one SQLite transaction.
820
+
821
+ The site callback may delete and reseed only its own declared tables.
822
+ Auth migration history is retained while every mutable auth row and
823
+ each requested deterministic seed account are recreated atomically.
824
+ """
825
+
826
+ self.ensure_schema()
827
+ with self.connect() as connection, self._transaction(connection):
828
+ for table in (
829
+ "local_auth_mail_outbox",
830
+ "local_auth_mail_rate_limits",
831
+ "local_auth_registration_flows",
832
+ "local_auth_password_reset_flows",
833
+ "local_auth_sessions",
834
+ "local_auth_accounts",
835
+ ):
836
+ connection.execute(f"DELETE FROM {table}")
837
+ site_reset(connection)
838
+ for account in seed_accounts:
839
+ self._seed_account_unlocked(connection, **dict(account))
840
+ self._clear_mail_secrets()
841
+
842
+ def _rate_limit_unlocked(
843
+ self,
844
+ connection: sqlite3.Connection,
845
+ *,
846
+ purpose: str,
847
+ scopes: list[tuple[str, str]],
848
+ now: int,
849
+ ignore_cooldown: bool = False,
850
+ ) -> None:
851
+ checked: list[tuple[str, str, int, int]] = []
852
+ for scope_type, scope_key in scopes:
853
+ row = connection.execute(
854
+ "SELECT window_started_at,send_count,last_sent_at "
855
+ "FROM local_auth_mail_rate_limits "
856
+ "WHERE purpose=? AND scope_type=? AND scope_key=?",
857
+ (purpose, scope_type, scope_key),
858
+ ).fetchone()
859
+ if (
860
+ row is None
861
+ or now - int(row["window_started_at"]) >= RATE_WINDOW_SECONDS
862
+ ):
863
+ checked.append((scope_type, scope_key, now, 0))
864
+ continue
865
+ last_sent = int(row["last_sent_at"])
866
+ send_count = int(row["send_count"])
867
+ if not ignore_cooldown and now - last_sent < MAIL_COOLDOWN_SECONDS:
868
+ raise AuthRateLimited(MAIL_COOLDOWN_SECONDS - (now - last_sent))
869
+ if send_count >= MAIL_HOURLY_LIMIT:
870
+ raise AuthRateLimited(
871
+ RATE_WINDOW_SECONDS - (now - int(row["window_started_at"]))
872
+ )
873
+ checked.append(
874
+ (scope_type, scope_key, int(row["window_started_at"]), send_count)
875
+ )
876
+ for scope_type, scope_key, window_started_at, send_count in checked:
877
+ connection.execute(
878
+ "INSERT INTO local_auth_mail_rate_limits("
879
+ "purpose,scope_type,scope_key,window_started_at,send_count,last_sent_at"
880
+ ") VALUES (?,?,?,?,?,?) "
881
+ "ON CONFLICT(purpose,scope_type,scope_key) DO UPDATE SET "
882
+ "window_started_at=excluded.window_started_at,"
883
+ "send_count=excluded.send_count,last_sent_at=excluded.last_sent_at",
884
+ (
885
+ purpose,
886
+ scope_type,
887
+ scope_key,
888
+ window_started_at,
889
+ send_count + 1,
890
+ now,
891
+ ),
892
+ )
893
+
894
+ def _insert_mail_unlocked(
895
+ self,
896
+ connection: sqlite3.Connection,
897
+ *,
898
+ purpose: str,
899
+ flow_id: str,
900
+ session_digest: str,
901
+ recipient: str,
902
+ now: int,
903
+ ) -> None:
904
+ status = self.mail_mode
905
+ request_id = _token("mailrequest")
906
+ connection.execute(
907
+ "INSERT INTO local_auth_mail_outbox("
908
+ "purpose,flow_id,session_digest,recipient,template,"
909
+ "status,is_simulation,delivery_attempts,"
910
+ "delivery_state_version,request_id,target_request_count,"
911
+ "accepted_effect_count,claim_token,last_error,attempted_at,"
912
+ "sent_at,created_at"
913
+ ") VALUES (?,?,?,?,?,?,?,0,0,?,0,0,NULL,NULL,NULL,NULL,?)",
914
+ (
915
+ purpose,
916
+ flow_id,
917
+ session_digest,
918
+ recipient,
919
+ (
920
+ "registration-verification"
921
+ if purpose == "registration"
922
+ else "password-reset-verification"
923
+ ),
924
+ status,
925
+ 1 if status == MAIL_LOCAL_ONLY else 0,
926
+ request_id,
927
+ now,
928
+ ),
929
+ )
930
+
931
+ def start_registration(
932
+ self,
933
+ session_token: str,
934
+ *,
935
+ email: str,
936
+ display_name: str,
937
+ password: str,
938
+ restart_invalid_flow: bool = False,
939
+ ) -> dict[str, Any]:
940
+ self.ensure_schema()
941
+ validated = self.validate_registration_details(
942
+ email=email,
943
+ display_name=display_name,
944
+ password=password,
945
+ )
946
+ normalized_email = validated["email"]
947
+ normalized_name = validated["display_name"]
948
+ validated_password = validated["password"]
949
+ now = self._now()
950
+ password_salt, password_hash = _hash_secret(validated_password)
951
+ code = _verification_code()
952
+ code_salt, code_hash = _hash_secret(code)
953
+ pending_id = _token("registration")
954
+ with self.connect() as connection, self._transaction(connection):
955
+ session = self._session_row(connection, session_token)
956
+ if session is None:
957
+ raise AuthRejected("session is invalid or expired")
958
+ if session["account_id"] is not None:
959
+ raise AuthConflict("authenticated sessions cannot register")
960
+ if connection.execute(
961
+ "SELECT 1 FROM local_auth_accounts WHERE email_normalized=?",
962
+ (normalized_email,),
963
+ ).fetchone():
964
+ raise AuthConflict("email already belongs to a local account")
965
+ session_digest = str(session["session_digest"])
966
+ old = connection.execute(
967
+ "SELECT pending_id,email_normalized,display_name,"
968
+ "password_salt,password_hash,expires_at,attempts,verified_at "
969
+ "FROM local_auth_registration_flows WHERE session_digest=?",
970
+ (session_digest,),
971
+ ).fetchone()
972
+ exact_active_retry = bool(
973
+ old is not None
974
+ and int(old["expires_at"]) > now
975
+ and int(old["attempts"]) < CODE_ATTEMPT_LIMIT
976
+ and self._mail_code(
977
+ "registration", str(old["pending_id"])
978
+ )
979
+ is not None
980
+ and str(old["email_normalized"]) == normalized_email
981
+ and str(old["display_name"]) == normalized_name
982
+ and _verify_secret(
983
+ validated_password,
984
+ bytes(old["password_salt"]),
985
+ bytes(old["password_hash"]),
986
+ )
987
+ )
988
+ if exact_active_retry:
989
+ mail = connection.execute(
990
+ "SELECT status FROM local_auth_mail_outbox "
991
+ "WHERE purpose='registration' AND flow_id=?",
992
+ (old["pending_id"],),
993
+ ).fetchone()
994
+ return {
995
+ "accepted": True,
996
+ "pending_id": str(old["pending_id"]),
997
+ "expires_at": int(old["expires_at"]),
998
+ "mail_status": (
999
+ str(mail["status"]) if mail is not None else self.mail_mode
1000
+ ),
1001
+ }
1002
+ restartable = bool(
1003
+ restart_invalid_flow
1004
+ and old is not None
1005
+ and old["verified_at"] is None
1006
+ and (
1007
+ int(old["expires_at"]) <= now
1008
+ or int(old["attempts"]) >= CODE_ATTEMPT_LIMIT
1009
+ )
1010
+ )
1011
+ self._rate_limit_unlocked(
1012
+ connection,
1013
+ purpose="registration",
1014
+ scopes=[
1015
+ ("session", session_digest),
1016
+ ("recipient", _recipient_digest(normalized_email)),
1017
+ ],
1018
+ now=now,
1019
+ ignore_cooldown=restartable,
1020
+ )
1021
+ if old is not None:
1022
+ connection.execute(
1023
+ "DELETE FROM local_auth_mail_outbox "
1024
+ "WHERE purpose='registration' AND flow_id=?",
1025
+ (old["pending_id"],),
1026
+ )
1027
+ connection.execute(
1028
+ "DELETE FROM local_auth_registration_flows WHERE session_digest=?",
1029
+ (session_digest,),
1030
+ )
1031
+ connection.execute(
1032
+ "INSERT INTO local_auth_registration_flows("
1033
+ "pending_id,session_digest,email_normalized,display_name,"
1034
+ "password_salt,password_hash,password_scheme,code_salt,code_hash,"
1035
+ "expires_at,attempts,verified_at,created_at,updated_at"
1036
+ ") VALUES (?,?,?,?,?,?,?,?,?,?,0,NULL,?,?)",
1037
+ (
1038
+ pending_id,
1039
+ session_digest,
1040
+ normalized_email,
1041
+ normalized_name,
1042
+ password_salt,
1043
+ password_hash,
1044
+ PASSWORD_SCHEME,
1045
+ code_salt,
1046
+ code_hash,
1047
+ now + CHALLENGE_TTL_SECONDS,
1048
+ now,
1049
+ now,
1050
+ ),
1051
+ )
1052
+ self._insert_mail_unlocked(
1053
+ connection,
1054
+ purpose="registration",
1055
+ flow_id=pending_id,
1056
+ session_digest=session_digest,
1057
+ recipient=normalized_email,
1058
+ now=now,
1059
+ )
1060
+ self._remember_mail_code("registration", pending_id, code)
1061
+ return {
1062
+ "accepted": True,
1063
+ "pending_id": pending_id,
1064
+ "expires_at": now + CHALLENGE_TTL_SECONDS,
1065
+ "mail_status": self.mail_mode,
1066
+ }
1067
+
1068
+ def local_mail_for_session(
1069
+ self, session_token: str, *, purpose: str
1070
+ ) -> dict[str, Any] | None:
1071
+ """Return only the current session's LOCAL_ONLY message."""
1072
+
1073
+ if purpose not in {"registration", "password-reset"}:
1074
+ raise ValueError("unknown mail purpose")
1075
+ self.ensure_schema()
1076
+ with self.connect() as connection:
1077
+ session = self._session_row(connection, session_token)
1078
+ if session is None:
1079
+ return None
1080
+ row = connection.execute(
1081
+ "SELECT mail_id,purpose,flow_id,recipient,template,"
1082
+ "status,created_at FROM local_auth_mail_outbox "
1083
+ "WHERE session_digest=? AND purpose=? AND status='LOCAL_ONLY' "
1084
+ "ORDER BY mail_id DESC LIMIT 1",
1085
+ (session["session_digest"], purpose),
1086
+ ).fetchone()
1087
+ if row is None:
1088
+ return None
1089
+ code = self._mail_code(purpose, str(row["flow_id"]))
1090
+ if code is None:
1091
+ return None
1092
+ result = dict(row)
1093
+ result["verification_code"] = code
1094
+ return result
1095
+
1096
+ def session_flow_status(
1097
+ self, session_token: str, *, purpose: str
1098
+ ) -> dict[str, Any]:
1099
+ """Return non-secret, server-owned state for one auth flow."""
1100
+
1101
+ tables = {
1102
+ "registration": "local_auth_registration_flows",
1103
+ "password-reset": "local_auth_password_reset_flows",
1104
+ }
1105
+ table = tables.get(purpose)
1106
+ if table is None:
1107
+ raise ValueError("unknown auth flow purpose")
1108
+ self.ensure_schema()
1109
+ now = self._now()
1110
+ with self.connect() as connection:
1111
+ session = self._session_row(connection, session_token)
1112
+ if session is None:
1113
+ return {"state": "missing"}
1114
+ row = connection.execute(
1115
+ f"SELECT expires_at,attempts,verified_at FROM {table} "
1116
+ "WHERE session_digest=?",
1117
+ (session["session_digest"],),
1118
+ ).fetchone()
1119
+ if row is None:
1120
+ return {"state": "missing"}
1121
+ if int(row["expires_at"]) <= now:
1122
+ state = "stale"
1123
+ elif int(row["attempts"]) >= CODE_ATTEMPT_LIMIT:
1124
+ state = "locked"
1125
+ elif row["verified_at"] is not None:
1126
+ state = "verified"
1127
+ else:
1128
+ state = "challenge"
1129
+ return {
1130
+ "state": state,
1131
+ "expires_at": int(row["expires_at"]),
1132
+ "attempts": int(row["attempts"]),
1133
+ }
1134
+
1135
+ def session_mail_status(self, session_token: str, *, purpose: str) -> str | None:
1136
+ """Return the durable four-state outbox status without message data."""
1137
+
1138
+ if purpose not in {"registration", "password-reset"}:
1139
+ raise ValueError("unknown mail purpose")
1140
+ self.ensure_schema()
1141
+ with self.connect() as connection:
1142
+ session = self._session_row(connection, session_token)
1143
+ if session is None:
1144
+ return None
1145
+ row = connection.execute(
1146
+ "SELECT status FROM local_auth_mail_outbox "
1147
+ "WHERE session_digest=? AND purpose=? "
1148
+ "ORDER BY mail_id DESC LIMIT 1",
1149
+ (session["session_digest"], purpose),
1150
+ ).fetchone()
1151
+ return str(row["status"]) if row is not None else None
1152
+
1153
+ def session_mail_state(
1154
+ self, session_token: str, *, purpose: str
1155
+ ) -> dict[str, Any] | None:
1156
+ """Return server-owned delivery state for the current session flow."""
1157
+
1158
+ if purpose not in {"registration", "password-reset"}:
1159
+ raise ValueError("unknown mail purpose")
1160
+ self.ensure_schema()
1161
+ with self.connect() as connection:
1162
+ session = self._session_row(connection, session_token)
1163
+ if session is None:
1164
+ return None
1165
+ row = connection.execute(
1166
+ "SELECT mail_id,status,delivery_attempts,"
1167
+ "delivery_state_version,request_id,target_request_count,"
1168
+ "accepted_effect_count,claim_token,last_error,"
1169
+ "attempted_at,sent_at "
1170
+ "FROM local_auth_mail_outbox "
1171
+ "WHERE session_digest=? AND purpose=? "
1172
+ "ORDER BY mail_id DESC LIMIT 1",
1173
+ (session["session_digest"], purpose),
1174
+ ).fetchone()
1175
+ if row is None:
1176
+ return None
1177
+ value = dict(row)
1178
+ value["retryable"] = (
1179
+ str(row["status"]) == MAIL_SMTP_FAILED
1180
+ and row["claim_token"] is None
1181
+ and int(row["delivery_attempts"]) < MAIL_DELIVERY_LIMIT
1182
+ )
1183
+ return value
1184
+
1185
+ def verify_registration_code(self, session_token: str, code: str) -> None:
1186
+ normalized_code = _validate_code(code)
1187
+ self.ensure_schema()
1188
+ now = self._now()
1189
+ failure: AuthError | None = None
1190
+ with self.connect() as connection, self._transaction(connection):
1191
+ session = self._session_row(connection, session_token)
1192
+ if session is None:
1193
+ raise AuthRejected("session is invalid or expired")
1194
+ flow = connection.execute(
1195
+ "SELECT * FROM local_auth_registration_flows WHERE session_digest=?",
1196
+ (session["session_digest"],),
1197
+ ).fetchone()
1198
+ failure = self._verify_flow_unlocked(
1199
+ connection,
1200
+ table="local_auth_registration_flows",
1201
+ id_column="pending_id",
1202
+ flow=flow,
1203
+ code=normalized_code,
1204
+ now=now,
1205
+ )
1206
+ if failure is not None:
1207
+ raise failure
1208
+
1209
+ def _verify_flow_unlocked(
1210
+ self,
1211
+ connection: sqlite3.Connection,
1212
+ *,
1213
+ table: str,
1214
+ id_column: str,
1215
+ flow: sqlite3.Row | None,
1216
+ code: str,
1217
+ now: int,
1218
+ ) -> AuthError | None:
1219
+ if flow is None:
1220
+ return AuthRejected("verification flow is unavailable")
1221
+ if int(flow["expires_at"]) <= now:
1222
+ return AuthExpired("verification flow expired")
1223
+ if int(flow["attempts"]) >= CODE_ATTEMPT_LIMIT:
1224
+ return AuthLocked("verification flow is locked")
1225
+ if not _verify_secret(code, bytes(flow["code_salt"]), bytes(flow["code_hash"])):
1226
+ attempts = int(flow["attempts"]) + 1
1227
+ connection.execute(
1228
+ f"UPDATE {table} SET attempts=?,updated_at=? WHERE {id_column}=?",
1229
+ (attempts, now, flow[id_column]),
1230
+ )
1231
+ if attempts >= CODE_ATTEMPT_LIMIT:
1232
+ return AuthLocked("verification flow is locked")
1233
+ return AuthRejected("verification code is invalid")
1234
+ connection.execute(
1235
+ f"UPDATE {table} SET verified_at=?,updated_at=? WHERE {id_column}=?",
1236
+ (now, now, flow[id_column]),
1237
+ )
1238
+ return None
1239
+
1240
+ def complete_registration(
1241
+ self,
1242
+ session_token: str,
1243
+ *,
1244
+ subject_factory: Callable[[sqlite3.Connection, Mapping[str, Any]], str]
1245
+ | None = None,
1246
+ session_rotation_callback: (
1247
+ Callable[[sqlite3.Connection, str, str], None] | None
1248
+ ) = None,
1249
+ ) -> dict[str, Any]:
1250
+ self.ensure_schema()
1251
+ now = self._now()
1252
+ with self.connect() as connection, self._transaction(connection):
1253
+ session = self._session_row(connection, session_token)
1254
+ if session is None:
1255
+ raise AuthRejected("session is invalid or expired")
1256
+ flow = connection.execute(
1257
+ "SELECT * FROM local_auth_registration_flows WHERE session_digest=?",
1258
+ (session["session_digest"],),
1259
+ ).fetchone()
1260
+ if flow is None or flow["verified_at"] is None:
1261
+ raise AuthRejected("registration has not been verified")
1262
+ if int(flow["expires_at"]) <= now:
1263
+ raise AuthExpired("registration expired")
1264
+ if connection.execute(
1265
+ "SELECT 1 FROM local_auth_accounts WHERE email_normalized=?",
1266
+ (flow["email_normalized"],),
1267
+ ).fetchone():
1268
+ raise AuthConflict("email already belongs to a local account")
1269
+ account_id = _token("account")
1270
+ public_registration = {
1271
+ "account_id": account_id,
1272
+ "email": str(flow["email_normalized"]),
1273
+ "display_name": str(flow["display_name"]),
1274
+ }
1275
+ subject_id = (
1276
+ subject_factory(connection, public_registration)
1277
+ if subject_factory is not None
1278
+ else account_id
1279
+ )
1280
+ if not isinstance(subject_id, str) or not subject_id.strip():
1281
+ raise AuthValidationError("subject factory returned an invalid id")
1282
+ connection.execute(
1283
+ "INSERT INTO local_auth_accounts("
1284
+ "account_id,subject_id,email_normalized,display_name,"
1285
+ "password_salt,password_hash,password_scheme,email_verified,"
1286
+ "created_at,password_updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
1287
+ (
1288
+ account_id,
1289
+ subject_id,
1290
+ flow["email_normalized"],
1291
+ flow["display_name"],
1292
+ flow["password_salt"],
1293
+ flow["password_hash"],
1294
+ PASSWORD_SCHEME,
1295
+ 1,
1296
+ now,
1297
+ now,
1298
+ ),
1299
+ )
1300
+ connection.execute(
1301
+ "DELETE FROM local_auth_mail_outbox "
1302
+ "WHERE purpose='registration' AND flow_id=?",
1303
+ (flow["pending_id"],),
1304
+ )
1305
+ connection.execute(
1306
+ "DELETE FROM local_auth_registration_flows WHERE pending_id=?",
1307
+ (flow["pending_id"],),
1308
+ )
1309
+ new_token = self._rotate_session_unlocked(
1310
+ connection,
1311
+ str(session["session_digest"]),
1312
+ account_id,
1313
+ now,
1314
+ session_rotation_callback,
1315
+ )
1316
+ return {
1317
+ "session_token": new_token,
1318
+ "account": {
1319
+ "account_id": account_id,
1320
+ "subject_id": subject_id,
1321
+ "email_normalized": public_registration["email"],
1322
+ "display_name": public_registration["display_name"],
1323
+ "email_verified": 1,
1324
+ },
1325
+ }
1326
+
1327
+ def complete_externally_verified_registration(
1328
+ self,
1329
+ session_token: str,
1330
+ *,
1331
+ email: str,
1332
+ display_name: str,
1333
+ password: str,
1334
+ subject_factory: Callable[[sqlite3.Connection, Mapping[str, Any]], str]
1335
+ | None = None,
1336
+ session_rotation_callback: (
1337
+ Callable[[sqlite3.Connection, str, str], None] | None
1338
+ ) = None,
1339
+ ) -> dict[str, Any]:
1340
+ """Create one account after an external registration ticket is consumed.
1341
+
1342
+ The caller owns the Redis ticket boundary and must call this method only
1343
+ after ``consume_verified`` succeeds. This method owns the site-local
1344
+ transaction: it validates and hashes credentials, creates the business
1345
+ subject, persists ``email_verified=1``, clears any obsolete local
1346
+ registration flow, and rotates the authenticated session atomically.
1347
+ """
1348
+
1349
+ self.ensure_schema()
1350
+ validated = self.validate_registration_details(
1351
+ email=email,
1352
+ display_name=display_name,
1353
+ password=password,
1354
+ )
1355
+ normalized_email = validated["email"]
1356
+ normalized_name = validated["display_name"]
1357
+ validated_password = validated["password"]
1358
+ password_salt, password_hash = _hash_secret(validated_password)
1359
+ now = self._now()
1360
+ with self.connect() as connection, self._transaction(connection):
1361
+ session = self._session_row(connection, session_token)
1362
+ if session is None:
1363
+ raise AuthRejected("session is invalid or expired")
1364
+ if session["account_id"] is not None:
1365
+ raise AuthConflict("authenticated sessions cannot register")
1366
+ if connection.execute(
1367
+ "SELECT 1 FROM local_auth_accounts WHERE email_normalized=?",
1368
+ (normalized_email,),
1369
+ ).fetchone():
1370
+ raise AuthConflict("email already belongs to a local account")
1371
+
1372
+ account_id = _token("account")
1373
+ public_registration = {
1374
+ "account_id": account_id,
1375
+ "email": normalized_email,
1376
+ "display_name": normalized_name,
1377
+ }
1378
+ subject_id = (
1379
+ subject_factory(connection, public_registration)
1380
+ if subject_factory is not None
1381
+ else account_id
1382
+ )
1383
+ if not isinstance(subject_id, str) or not subject_id.strip():
1384
+ raise AuthValidationError("subject factory returned an invalid id")
1385
+ connection.execute(
1386
+ "INSERT INTO local_auth_accounts("
1387
+ "account_id,subject_id,email_normalized,display_name,"
1388
+ "password_salt,password_hash,password_scheme,email_verified,"
1389
+ "created_at,password_updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
1390
+ (
1391
+ account_id,
1392
+ subject_id,
1393
+ normalized_email,
1394
+ normalized_name,
1395
+ password_salt,
1396
+ password_hash,
1397
+ PASSWORD_SCHEME,
1398
+ 1,
1399
+ now,
1400
+ now,
1401
+ ),
1402
+ )
1403
+ session_digest = str(session["session_digest"])
1404
+ connection.execute(
1405
+ "DELETE FROM local_auth_mail_outbox "
1406
+ "WHERE purpose='registration' AND session_digest=?",
1407
+ (session_digest,),
1408
+ )
1409
+ connection.execute(
1410
+ "DELETE FROM local_auth_registration_flows WHERE session_digest=?",
1411
+ (session_digest,),
1412
+ )
1413
+ new_token = self._rotate_session_unlocked(
1414
+ connection,
1415
+ session_digest,
1416
+ account_id,
1417
+ now,
1418
+ session_rotation_callback,
1419
+ )
1420
+ return {
1421
+ "session_token": new_token,
1422
+ "account": {
1423
+ "account_id": account_id,
1424
+ "subject_id": subject_id,
1425
+ "email_normalized": normalized_email,
1426
+ "display_name": normalized_name,
1427
+ "email_verified": 1,
1428
+ },
1429
+ }
1430
+
1431
+ def sign_in(
1432
+ self,
1433
+ session_token: str,
1434
+ *,
1435
+ email: str,
1436
+ password: str,
1437
+ session_rotation_callback: (
1438
+ Callable[[sqlite3.Connection, str, str], None] | None
1439
+ ) = None,
1440
+ ) -> dict[str, Any]:
1441
+ self.ensure_schema()
1442
+ normalized_email = _normalize_email(email)
1443
+ _validate_password(password)
1444
+ now = self._now()
1445
+ # A real dummy hash prevents a fast unknown-email branch.
1446
+ dummy_salt = b"\x00" * 16
1447
+ _, dummy_hash = _hash_secret("local-auth-dummy-password", salt=dummy_salt)
1448
+ with self.connect() as connection, self._transaction(connection):
1449
+ session = self._session_row(connection, session_token)
1450
+ if session is None:
1451
+ raise AuthRejected("credentials are invalid")
1452
+ account = connection.execute(
1453
+ "SELECT * FROM local_auth_accounts WHERE email_normalized=?",
1454
+ (normalized_email,),
1455
+ ).fetchone()
1456
+ valid = _verify_secret(
1457
+ password,
1458
+ bytes(account["password_salt"]) if account is not None else dummy_salt,
1459
+ bytes(account["password_hash"]) if account is not None else dummy_hash,
1460
+ )
1461
+ if not valid or account is None or int(account["email_verified"]) != 1:
1462
+ raise AuthRejected("credentials are invalid")
1463
+ new_token = self._rotate_session_unlocked(
1464
+ connection,
1465
+ str(session["session_digest"]),
1466
+ str(account["account_id"]),
1467
+ now,
1468
+ session_rotation_callback,
1469
+ )
1470
+ public_account = {
1471
+ key: account[key]
1472
+ for key in (
1473
+ "account_id",
1474
+ "subject_id",
1475
+ "email_normalized",
1476
+ "display_name",
1477
+ "email_verified",
1478
+ )
1479
+ }
1480
+ return {"session_token": new_token, "account": public_account}
1481
+
1482
+ def sign_out(self, session_token: str | None) -> None:
1483
+ self.ensure_schema()
1484
+ now = self._now()
1485
+ with self.connect() as connection, self._transaction(connection):
1486
+ session = self._session_row(connection, session_token, include_revoked=True)
1487
+ if session is not None and session["revoked_at"] is None:
1488
+ connection.execute(
1489
+ "UPDATE local_auth_sessions SET revoked_at=? "
1490
+ "WHERE session_digest=?",
1491
+ (now, session["session_digest"]),
1492
+ )
1493
+
1494
+ def start_password_reset(
1495
+ self,
1496
+ session_token: str,
1497
+ *,
1498
+ email: str,
1499
+ restart_invalid_flow: bool = False,
1500
+ ) -> dict[str, Any]:
1501
+ self.ensure_schema()
1502
+ normalized_email = _normalize_email(email)
1503
+ now = self._now()
1504
+ code = _verification_code()
1505
+ code_salt, code_hash = _hash_secret(code)
1506
+ reset_id = _token("reset")
1507
+ with self.connect() as connection, self._transaction(connection):
1508
+ session = self._session_row(connection, session_token)
1509
+ if session is None:
1510
+ raise AuthRejected("session is invalid or expired")
1511
+ session_digest = str(session["session_digest"])
1512
+ account = connection.execute(
1513
+ "SELECT account_id FROM local_auth_accounts WHERE email_normalized=?",
1514
+ (normalized_email,),
1515
+ ).fetchone()
1516
+ scopes = [
1517
+ ("session", session_digest),
1518
+ ("recipient", _recipient_digest(normalized_email)),
1519
+ ]
1520
+ if account is not None:
1521
+ scopes.append(("account", str(account["account_id"])))
1522
+ old = connection.execute(
1523
+ "SELECT reset_id,expires_at,attempts,verified_at "
1524
+ "FROM local_auth_password_reset_flows WHERE session_digest=?",
1525
+ (session_digest,),
1526
+ ).fetchone()
1527
+ restartable = bool(
1528
+ restart_invalid_flow
1529
+ and old is not None
1530
+ and old["verified_at"] is None
1531
+ and (
1532
+ int(old["expires_at"]) <= now
1533
+ or int(old["attempts"]) >= CODE_ATTEMPT_LIMIT
1534
+ )
1535
+ )
1536
+ self._rate_limit_unlocked(
1537
+ connection,
1538
+ purpose="password-reset",
1539
+ scopes=scopes,
1540
+ now=now,
1541
+ ignore_cooldown=restartable,
1542
+ )
1543
+ if old is not None:
1544
+ connection.execute(
1545
+ "DELETE FROM local_auth_mail_outbox "
1546
+ "WHERE purpose='password-reset' AND flow_id=?",
1547
+ (old["reset_id"],),
1548
+ )
1549
+ connection.execute(
1550
+ "DELETE FROM local_auth_password_reset_flows WHERE session_digest=?",
1551
+ (session_digest,),
1552
+ )
1553
+ if account is not None:
1554
+ conflicting = connection.execute(
1555
+ "SELECT reset_id FROM local_auth_password_reset_flows "
1556
+ "WHERE account_id=?",
1557
+ (account["account_id"],),
1558
+ ).fetchone()
1559
+ if conflicting is not None:
1560
+ connection.execute(
1561
+ "DELETE FROM local_auth_mail_outbox "
1562
+ "WHERE purpose='password-reset' AND flow_id=?",
1563
+ (conflicting["reset_id"],),
1564
+ )
1565
+ connection.execute(
1566
+ "DELETE FROM local_auth_password_reset_flows WHERE reset_id=?",
1567
+ (conflicting["reset_id"],),
1568
+ )
1569
+ connection.execute(
1570
+ "INSERT INTO local_auth_password_reset_flows("
1571
+ "reset_id,session_digest,account_id,code_salt,code_hash,"
1572
+ "expires_at,attempts,verified_at,created_at,updated_at"
1573
+ ") VALUES (?,?,?,?,?,?,0,NULL,?,?)",
1574
+ (
1575
+ reset_id,
1576
+ session_digest,
1577
+ account["account_id"] if account is not None else None,
1578
+ code_salt,
1579
+ code_hash,
1580
+ now + CHALLENGE_TTL_SECONDS,
1581
+ now,
1582
+ now,
1583
+ ),
1584
+ )
1585
+ if account is not None:
1586
+ self._insert_mail_unlocked(
1587
+ connection,
1588
+ purpose="password-reset",
1589
+ flow_id=reset_id,
1590
+ session_digest=session_digest,
1591
+ recipient=normalized_email,
1592
+ now=now,
1593
+ )
1594
+ if account is not None:
1595
+ self._remember_mail_code("password-reset", reset_id, code)
1596
+ return {
1597
+ "accepted": True,
1598
+ "message": RESET_PUBLIC_MESSAGE,
1599
+ "expires_at": now + CHALLENGE_TTL_SECONDS,
1600
+ }
1601
+
1602
+ def verify_password_reset_code(self, session_token: str, code: str) -> None:
1603
+ normalized_code = _validate_code(code)
1604
+ self.ensure_schema()
1605
+ now = self._now()
1606
+ failure: AuthError | None = None
1607
+ with self.connect() as connection, self._transaction(connection):
1608
+ session = self._session_row(connection, session_token)
1609
+ if session is None:
1610
+ raise AuthRejected("session is invalid or expired")
1611
+ flow = connection.execute(
1612
+ "SELECT * FROM local_auth_password_reset_flows WHERE session_digest=?",
1613
+ (session["session_digest"],),
1614
+ ).fetchone()
1615
+ failure = self._verify_flow_unlocked(
1616
+ connection,
1617
+ table="local_auth_password_reset_flows",
1618
+ id_column="reset_id",
1619
+ flow=flow,
1620
+ code=normalized_code,
1621
+ now=now,
1622
+ )
1623
+ if failure is not None:
1624
+ raise failure
1625
+
1626
+ def complete_password_reset(
1627
+ self,
1628
+ session_token: str,
1629
+ *,
1630
+ new_password: str,
1631
+ session_rotation_callback: (
1632
+ Callable[[sqlite3.Connection, str, str], None] | None
1633
+ ) = None,
1634
+ ) -> str:
1635
+ validated_password = _validate_password(new_password)
1636
+ self.ensure_schema()
1637
+ now = self._now()
1638
+ salt, password_hash = _hash_secret(validated_password)
1639
+ with self.connect() as connection, self._transaction(connection):
1640
+ session = self._session_row(connection, session_token)
1641
+ if session is None:
1642
+ raise AuthRejected("session is invalid or expired")
1643
+ flow = connection.execute(
1644
+ "SELECT * FROM local_auth_password_reset_flows WHERE session_digest=?",
1645
+ (session["session_digest"],),
1646
+ ).fetchone()
1647
+ if (
1648
+ flow is None
1649
+ or flow["account_id"] is None
1650
+ or flow["verified_at"] is None
1651
+ ):
1652
+ raise AuthRejected("password reset has not been verified")
1653
+ if int(flow["expires_at"]) <= now:
1654
+ raise AuthExpired("password reset expired")
1655
+ account_id = str(flow["account_id"])
1656
+ connection.execute(
1657
+ "UPDATE local_auth_accounts SET password_salt=?,password_hash=?,"
1658
+ "password_scheme=?,password_updated_at=? WHERE account_id=?",
1659
+ (salt, password_hash, PASSWORD_SCHEME, now, account_id),
1660
+ )
1661
+ connection.execute(
1662
+ "UPDATE local_auth_sessions SET revoked_at=? "
1663
+ "WHERE (account_id=? OR session_digest=?) AND revoked_at IS NULL",
1664
+ (now, account_id, session["session_digest"]),
1665
+ )
1666
+ connection.execute(
1667
+ "DELETE FROM local_auth_mail_outbox "
1668
+ "WHERE purpose='password-reset' AND flow_id=?",
1669
+ (flow["reset_id"],),
1670
+ )
1671
+ connection.execute(
1672
+ "DELETE FROM local_auth_password_reset_flows WHERE reset_id=?",
1673
+ (flow["reset_id"],),
1674
+ )
1675
+ new_token = _token("session")
1676
+ new_digest = _digest_token(new_token)
1677
+ connection.execute(
1678
+ "INSERT INTO local_auth_sessions("
1679
+ "session_digest,account_id,created_at,expires_at,revoked_at"
1680
+ ") VALUES (?,?,?,?,NULL)",
1681
+ (
1682
+ new_digest,
1683
+ account_id,
1684
+ now,
1685
+ now + SESSION_TTL_SECONDS,
1686
+ ),
1687
+ )
1688
+ if session_rotation_callback is not None:
1689
+ session_rotation_callback(
1690
+ connection,
1691
+ str(session["session_digest"]),
1692
+ new_digest,
1693
+ )
1694
+ return new_token
1695
+
1696
+ def claim_pending_mail(
1697
+ self, *, worker_token: str | None = None
1698
+ ) -> dict[str, Any] | None:
1699
+ """Atomically claim one SMTP message below the shared delivery ceiling."""
1700
+
1701
+ self._authorize_mail_worker(worker_token)
1702
+ self.ensure_schema()
1703
+ now = self._now()
1704
+ claim_token = _token("mailclaim")
1705
+ with self.connect() as connection, self._transaction(connection):
1706
+ row = connection.execute(
1707
+ "SELECT * FROM local_auth_mail_outbox "
1708
+ "WHERE status='SMTP_PENDING' AND claim_token IS NULL "
1709
+ "AND delivery_attempts<? ORDER BY mail_id LIMIT 1",
1710
+ (MAIL_DELIVERY_LIMIT,),
1711
+ ).fetchone()
1712
+ if row is None:
1713
+ return None
1714
+ code = self._mail_code(str(row["purpose"]), str(row["flow_id"]))
1715
+ if code is None:
1716
+ return None
1717
+ changed = connection.execute(
1718
+ "UPDATE local_auth_mail_outbox SET claim_token=?,"
1719
+ "claim_target_reserved=0,"
1720
+ "delivery_attempts=delivery_attempts+1,"
1721
+ "delivery_state_version=delivery_state_version+1,"
1722
+ "attempted_at=? "
1723
+ "WHERE mail_id=? AND status='SMTP_PENDING' "
1724
+ "AND claim_token IS NULL AND delivery_attempts<?",
1725
+ (claim_token, now, row["mail_id"], MAIL_DELIVERY_LIMIT),
1726
+ ).rowcount
1727
+ if changed != 1:
1728
+ return None
1729
+ claimed = connection.execute(
1730
+ "SELECT * FROM local_auth_mail_outbox WHERE mail_id=?",
1731
+ (row["mail_id"],),
1732
+ ).fetchone()
1733
+ result = dict(claimed)
1734
+ result["claim_token"] = claim_token
1735
+ result["verification_code"] = code
1736
+ return result
1737
+
1738
+ def claim_pending_mail_for_session(
1739
+ self,
1740
+ session_token: str,
1741
+ *,
1742
+ purpose: str,
1743
+ worker_token: str | None = None,
1744
+ ) -> dict[str, Any] | None:
1745
+ """Claim only the newest pending mail owned by one live session."""
1746
+
1747
+ self._authorize_mail_worker(worker_token)
1748
+ if purpose not in {"registration", "password-reset"}:
1749
+ raise ValueError("unknown mail purpose")
1750
+ self.ensure_schema()
1751
+ now = self._now()
1752
+ claim_token = _token("mailclaim")
1753
+ with self.connect() as connection, self._transaction(connection):
1754
+ session = self._session_row(connection, session_token)
1755
+ if session is None:
1756
+ raise AuthRejected("session is invalid or expired")
1757
+ row = connection.execute(
1758
+ "SELECT * FROM local_auth_mail_outbox "
1759
+ "WHERE session_digest=? AND purpose=? "
1760
+ "AND status='SMTP_PENDING' AND claim_token IS NULL "
1761
+ "AND delivery_attempts<? ORDER BY mail_id DESC LIMIT 1",
1762
+ (
1763
+ session["session_digest"],
1764
+ purpose,
1765
+ MAIL_DELIVERY_LIMIT,
1766
+ ),
1767
+ ).fetchone()
1768
+ if row is None:
1769
+ return None
1770
+ code = self._mail_code(str(row["purpose"]), str(row["flow_id"]))
1771
+ if code is None:
1772
+ return None
1773
+ changed = connection.execute(
1774
+ "UPDATE local_auth_mail_outbox SET claim_token=?,"
1775
+ "claim_target_reserved=0,"
1776
+ "delivery_attempts=delivery_attempts+1,"
1777
+ "delivery_state_version=delivery_state_version+1,"
1778
+ "attempted_at=? "
1779
+ "WHERE mail_id=? AND session_digest=? AND purpose=? "
1780
+ "AND status='SMTP_PENDING' AND claim_token IS NULL "
1781
+ "AND delivery_attempts<?",
1782
+ (
1783
+ claim_token,
1784
+ now,
1785
+ row["mail_id"],
1786
+ session["session_digest"],
1787
+ purpose,
1788
+ MAIL_DELIVERY_LIMIT,
1789
+ ),
1790
+ ).rowcount
1791
+ if changed != 1:
1792
+ return None
1793
+ claimed = connection.execute(
1794
+ "SELECT * FROM local_auth_mail_outbox WHERE mail_id=?",
1795
+ (row["mail_id"],),
1796
+ ).fetchone()
1797
+ result = dict(claimed)
1798
+ result["claim_token"] = claim_token
1799
+ result["verification_code"] = code
1800
+ return result
1801
+
1802
+ def finish_mail_claim(
1803
+ self,
1804
+ mail_id: int,
1805
+ claim_token: str,
1806
+ *,
1807
+ sent: bool,
1808
+ target_request_count: int = 1,
1809
+ accepted_request_count: int = 0,
1810
+ error: str | None = None,
1811
+ worker_token: str | None = None,
1812
+ ) -> None:
1813
+ self._authorize_mail_worker(worker_token)
1814
+ if target_request_count not in {0, 1}:
1815
+ raise AuthValidationError(
1816
+ "one claim may dispatch at most one target request"
1817
+ )
1818
+ if sent and (target_request_count != 1 or accepted_request_count != 1):
1819
+ raise AuthValidationError(
1820
+ "SMTP_SENT requires exactly one accepted loopback request"
1821
+ )
1822
+ if not sent and (
1823
+ accepted_request_count != 0 or accepted_request_count > target_request_count
1824
+ ):
1825
+ raise AuthValidationError(
1826
+ "a failed delivery cannot claim an accepted request"
1827
+ )
1828
+ self.ensure_schema()
1829
+ now = self._now()
1830
+ safe_error = (
1831
+ error if isinstance(error, str) and error in MAIL_ERROR_CATEGORIES else None
1832
+ )
1833
+ if not sent and safe_error is None:
1834
+ safe_error = "unknown"
1835
+ with self.connect() as connection, self._transaction(connection):
1836
+ row = connection.execute(
1837
+ "SELECT target_request_count,accepted_effect_count,"
1838
+ "claim_target_reserved "
1839
+ "FROM local_auth_mail_outbox "
1840
+ "WHERE mail_id=? AND status='SMTP_PENDING' AND claim_token=?",
1841
+ (mail_id, claim_token),
1842
+ ).fetchone()
1843
+ if row is None:
1844
+ raise AuthConflict("mail claim is stale or foreign")
1845
+ target_was_reserved = bool(row["claim_target_reserved"])
1846
+ if target_was_reserved and target_request_count != 1:
1847
+ raise AuthConflict(
1848
+ "reserved mail target count does not match worker result"
1849
+ )
1850
+ if sent and int(row["accepted_effect_count"]) != 0:
1851
+ raise AuthConflict("mail already has an accepted effect")
1852
+ status = MAIL_SMTP_SENT if sent else MAIL_SMTP_FAILED
1853
+ connection.execute(
1854
+ "UPDATE local_auth_mail_outbox SET status=?,claim_token=NULL,"
1855
+ "claim_target_reserved=0,"
1856
+ "last_error=?,sent_at=?,"
1857
+ "target_request_count=target_request_count+?,"
1858
+ "accepted_effect_count=accepted_effect_count+?,"
1859
+ "delivery_state_version=delivery_state_version+1 "
1860
+ "WHERE mail_id=? AND claim_token=?",
1861
+ (
1862
+ status,
1863
+ None if sent else safe_error,
1864
+ now if sent else None,
1865
+ 0 if target_was_reserved else target_request_count,
1866
+ accepted_request_count,
1867
+ mail_id,
1868
+ claim_token,
1869
+ ),
1870
+ )
1871
+
1872
+ def reserve_mail_target_request(
1873
+ self,
1874
+ mail_id: int,
1875
+ claim_token: str,
1876
+ *,
1877
+ worker_token: str | None = None,
1878
+ ) -> int:
1879
+ """Durably reserve one logical target request before any socket write.
1880
+
1881
+ If the worker dies after this commit, startup reconciliation releases
1882
+ the interrupted claim below the shared retry ceiling. A later worker
1883
+ attempt reuses the stable request id, reservation, and logical count so
1884
+ the controlled loopback sink can deduplicate transport replay without
1885
+ manufacturing a second business request or accepted effect.
1886
+ """
1887
+
1888
+ self._authorize_mail_worker(worker_token)
1889
+ self.ensure_schema()
1890
+ with self.connect() as connection, self._transaction(connection):
1891
+ changed = connection.execute(
1892
+ "UPDATE local_auth_mail_outbox SET "
1893
+ "target_request_count=MAX(target_request_count,1),"
1894
+ "claim_target_reserved=1,"
1895
+ "delivery_state_version=delivery_state_version+1 "
1896
+ "WHERE mail_id=? AND status='SMTP_PENDING' "
1897
+ "AND claim_token=? AND accepted_effect_count=0 "
1898
+ "AND claim_target_reserved=0",
1899
+ (mail_id, claim_token),
1900
+ ).rowcount
1901
+ if changed != 1:
1902
+ raise AuthConflict("mail target reservation is stale or foreign")
1903
+ row = connection.execute(
1904
+ "SELECT target_request_count FROM local_auth_mail_outbox "
1905
+ "WHERE mail_id=? AND claim_token=?",
1906
+ (mail_id, claim_token),
1907
+ ).fetchone()
1908
+ if row is None:
1909
+ raise AuthConflict("mail target reservation disappeared")
1910
+ return int(row["target_request_count"])
1911
+
1912
+ def retry_failed_mail(self, mail_id: int) -> bool:
1913
+ self.ensure_schema()
1914
+ with self.connect() as connection, self._transaction(connection):
1915
+ changed = connection.execute(
1916
+ "UPDATE local_auth_mail_outbox SET status='SMTP_PENDING',"
1917
+ "claim_token=NULL,claim_target_reserved=0,last_error=NULL,"
1918
+ "delivery_state_version=delivery_state_version+1 "
1919
+ "WHERE mail_id=? AND status='SMTP_FAILED' "
1920
+ "AND delivery_attempts<?",
1921
+ (mail_id, MAIL_DELIVERY_LIMIT),
1922
+ ).rowcount
1923
+ return changed == 1
1924
+
1925
+ def retry_failed_mail_for_session(
1926
+ self, session_token: str, *, purpose: str
1927
+ ) -> bool:
1928
+ """Queue only the failed mail owned by the current opaque session."""
1929
+
1930
+ if purpose not in {"registration", "password-reset"}:
1931
+ raise ValueError("unknown mail purpose")
1932
+ self.ensure_schema()
1933
+ with self.connect() as connection, self._transaction(connection):
1934
+ session = self._session_row(connection, session_token)
1935
+ if session is None:
1936
+ raise AuthRejected("session is invalid or expired")
1937
+ changed = connection.execute(
1938
+ "UPDATE local_auth_mail_outbox SET status='SMTP_PENDING',"
1939
+ "claim_token=NULL,claim_target_reserved=0,last_error=NULL,"
1940
+ "delivery_state_version=delivery_state_version+1 "
1941
+ "WHERE mail_id=("
1942
+ "SELECT mail_id FROM local_auth_mail_outbox "
1943
+ "WHERE session_digest=? AND purpose=? "
1944
+ "ORDER BY mail_id DESC LIMIT 1"
1945
+ ") AND session_digest=? AND purpose=? "
1946
+ "AND status='SMTP_FAILED' AND claim_token IS NULL "
1947
+ "AND delivery_attempts<?",
1948
+ (
1949
+ session["session_digest"],
1950
+ purpose,
1951
+ session["session_digest"],
1952
+ purpose,
1953
+ MAIL_DELIVERY_LIMIT,
1954
+ ),
1955
+ ).rowcount
1956
+ return changed == 1
1957
+
1958
+ def _reconcile_mail_unlocked(
1959
+ self, connection: sqlite3.Connection, now: int
1960
+ ) -> None:
1961
+ connection.execute(
1962
+ "UPDATE local_auth_mail_outbox SET status='SMTP_FAILED',"
1963
+ "claim_token=NULL,claim_target_reserved=0,"
1964
+ "delivery_state_version=delivery_state_version+1,"
1965
+ "last_error=COALESCE(last_error,'delivery-attempts-exhausted') "
1966
+ "WHERE status='SMTP_PENDING' AND delivery_attempts>=?",
1967
+ (MAIL_DELIVERY_LIMIT,),
1968
+ )
1969
+ connection.execute(
1970
+ "UPDATE local_auth_mail_outbox SET claim_token=NULL,"
1971
+ "claim_target_reserved=0,"
1972
+ "delivery_state_version=delivery_state_version+1,"
1973
+ "last_error='startup-claim-replay' "
1974
+ "WHERE status='SMTP_PENDING' AND claim_token IS NOT NULL "
1975
+ "AND delivery_attempts<?",
1976
+ (MAIL_DELIVERY_LIMIT,),
1977
+ )
1978
+
1979
+ def reconcile_mail(self, *, worker_token: str | None = None) -> None:
1980
+ if self.mail_mode == MAIL_SMTP_PENDING:
1981
+ self._authorize_mail_worker(worker_token)
1982
+ self.ensure_schema()
1983
+ now = self._now()
1984
+ with self.connect() as connection, self._transaction(connection):
1985
+ self._reconcile_mail_unlocked(connection, now)
1986
+
1987
+ def _validate_backup_connection(
1988
+ self,
1989
+ connection: sqlite3.Connection,
1990
+ ) -> dict[str, Any]:
1991
+ quick_check = connection.execute("PRAGMA quick_check").fetchone()
1992
+ if quick_check is None or str(quick_check[0]).casefold() != "ok":
1993
+ raise AuthBackupError("SQLite backup failed integrity validation")
1994
+ table_names = {
1995
+ str(row[0])
1996
+ for row in connection.execute(
1997
+ "SELECT name FROM sqlite_master "
1998
+ "WHERE type='table' AND name NOT LIKE 'sqlite_%'"
1999
+ )
2000
+ }
2001
+ required_tables = {
2002
+ "local_auth_schema_migrations",
2003
+ "local_auth_accounts",
2004
+ "local_auth_sessions",
2005
+ "local_auth_registration_flows",
2006
+ "local_auth_password_reset_flows",
2007
+ "local_auth_mail_outbox",
2008
+ "local_auth_mail_rate_limits",
2009
+ }
2010
+ missing = sorted(required_tables - table_names)
2011
+ if missing:
2012
+ raise AuthBackupError(
2013
+ "SQLite backup is missing required auth tables: " + ", ".join(missing)
2014
+ )
2015
+ migrations = [
2016
+ str(row[0])
2017
+ for row in connection.execute(
2018
+ "SELECT version FROM local_auth_schema_migrations ORDER BY version"
2019
+ )
2020
+ ]
2021
+ if not {"0001", "0002"}.issubset(migrations):
2022
+ raise AuthBackupError(
2023
+ "SQLite backup does not contain auth migrations 0001-0002"
2024
+ )
2025
+ bound_site_id: str | None = None
2026
+ if self.site_id is not None:
2027
+ if "clawbench_site_binding" in table_names:
2028
+ raise AuthSiteBindingError(
2029
+ "backup is bound by the other runtime namespace"
2030
+ )
2031
+ if "websitebench_site_binding" not in table_names:
2032
+ raise AuthSiteBindingError(
2033
+ "backup has no WebsiteBench site binding"
2034
+ )
2035
+ bindings = connection.execute(
2036
+ "SELECT singleton,site_id FROM websitebench_site_binding"
2037
+ ).fetchall()
2038
+ if (
2039
+ len(bindings) != 1
2040
+ or int(bindings[0][0]) != 1
2041
+ or str(bindings[0][1]) != self.site_id
2042
+ ):
2043
+ raise AuthSiteBindingError(
2044
+ "backup belongs to another WebsiteBench site"
2045
+ )
2046
+ bound_site_id = self.site_id
2047
+ return {
2048
+ "quick_check": "ok",
2049
+ "migrations": migrations,
2050
+ "tables": sorted(table_names),
2051
+ "site_id": bound_site_id,
2052
+ }
2053
+
2054
+ def backup_to(
2055
+ self,
2056
+ destination: Path | str,
2057
+ *,
2058
+ overwrite: bool = False,
2059
+ ) -> dict[str, Any]:
2060
+ """Atomically back up the complete site database.
2061
+
2062
+ The backup includes the clone's business tables as well as auth tables.
2063
+ Existing targets are preserved unless the caller explicitly opts in to
2064
+ replacement.
2065
+ """
2066
+
2067
+ self.ensure_schema()
2068
+ source_path = self.database_path.absolute()
2069
+ target_path = Path(destination).absolute()
2070
+ if source_path == target_path:
2071
+ raise AuthBackupError(
2072
+ "backup destination must differ from the live database"
2073
+ )
2074
+ if target_path.exists() and not overwrite:
2075
+ raise FileExistsError(target_path)
2076
+ target_path.parent.mkdir(parents=True, exist_ok=True)
2077
+ temporary = target_path.with_name(
2078
+ f".{target_path.name}.backup-{os.getpid()}-{secrets.token_hex(6)}"
2079
+ )
2080
+ try:
2081
+ with closing(self.connect()) as source:
2082
+ source.execute("PRAGMA wal_checkpoint(FULL)")
2083
+ with closing(sqlite3.connect(str(temporary))) as backup:
2084
+ source.backup(backup)
2085
+ metadata = self._validate_backup_connection(backup)
2086
+ if target_path.exists() and not overwrite:
2087
+ raise FileExistsError(target_path)
2088
+ os.replace(temporary, target_path)
2089
+ except sqlite3.DatabaseError as exc:
2090
+ if temporary.exists():
2091
+ temporary.unlink()
2092
+ raise AuthBackupError(
2093
+ "backup source is not a valid SQLite auth database"
2094
+ ) from exc
2095
+ except BaseException:
2096
+ if temporary.exists():
2097
+ temporary.unlink()
2098
+ raise
2099
+ return {
2100
+ "path": str(target_path),
2101
+ "bytes": target_path.stat().st_size,
2102
+ "sha256": _sha256_file(target_path),
2103
+ **metadata,
2104
+ }
2105
+
2106
+ def restore_from(
2107
+ self,
2108
+ backup_path: Path | str,
2109
+ *,
2110
+ overwrite: bool = False,
2111
+ ) -> dict[str, Any]:
2112
+ """Atomically restore a validated complete site database backup."""
2113
+
2114
+ source_path = Path(backup_path).absolute()
2115
+ target_path = self.database_path.absolute()
2116
+ if not source_path.is_file() or source_path.is_symlink():
2117
+ raise AuthBackupError("backup source must be an existing regular file")
2118
+ if source_path == target_path:
2119
+ raise AuthBackupError("backup source must differ from the live database")
2120
+ if target_path.exists() and not overwrite:
2121
+ raise FileExistsError(target_path)
2122
+ target_path.parent.mkdir(parents=True, exist_ok=True)
2123
+ temporary = target_path.with_name(
2124
+ f".{target_path.name}.restore-{os.getpid()}-{secrets.token_hex(6)}"
2125
+ )
2126
+ try:
2127
+ with closing(sqlite3.connect(str(source_path))) as source:
2128
+ source.row_factory = sqlite3.Row
2129
+ metadata = self._validate_backup_connection(source)
2130
+ with closing(sqlite3.connect(str(temporary))) as restored:
2131
+ source.backup(restored)
2132
+ self._validate_backup_connection(restored)
2133
+ if target_path.exists():
2134
+ if not overwrite:
2135
+ raise FileExistsError(target_path)
2136
+ with closing(self.connect()) as current:
2137
+ current.execute("PRAGMA wal_checkpoint(TRUNCATE)")
2138
+ sidecars = [
2139
+ Path(str(target_path) + suffix)
2140
+ for suffix in ("-wal", "-shm")
2141
+ if Path(str(target_path) + suffix).exists()
2142
+ ]
2143
+ if sidecars:
2144
+ raise AuthBackupError(
2145
+ "live database still has SQLite sidecars after checkpoint: "
2146
+ + ", ".join(str(path) for path in sidecars)
2147
+ )
2148
+ os.replace(temporary, target_path)
2149
+ except sqlite3.DatabaseError as exc:
2150
+ if temporary.exists():
2151
+ temporary.unlink()
2152
+ raise AuthBackupError(
2153
+ "backup source is not a valid SQLite auth database"
2154
+ ) from exc
2155
+ except BaseException:
2156
+ if temporary.exists():
2157
+ temporary.unlink()
2158
+ raise
2159
+ self._clear_mail_secrets()
2160
+ with self._schema_lock:
2161
+ self._schema_ready = False
2162
+ self.ensure_schema()
2163
+ return {
2164
+ "path": str(target_path),
2165
+ "bytes": target_path.stat().st_size,
2166
+ "sha256": _sha256_file(target_path),
2167
+ **metadata,
2168
+ }
2169
+
2170
+ def counts(self) -> dict[str, int]:
2171
+ self.ensure_schema()
2172
+ tables = (
2173
+ "local_auth_accounts",
2174
+ "local_auth_sessions",
2175
+ "local_auth_registration_flows",
2176
+ "local_auth_password_reset_flows",
2177
+ "local_auth_mail_outbox",
2178
+ "local_auth_mail_rate_limits",
2179
+ )
2180
+ with self.connect() as connection:
2181
+ return {
2182
+ table: int(
2183
+ connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
2184
+ )
2185
+ for table in tables
2186
+ }
tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/VENDOR_MANIFEST.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "files": [
3
+ {
4
+ "bytes": 1171,
5
+ "path": "__init__.py",
6
+ "sha256": "3b779daabaa210b690ffd88bb9b46ba68413893a7d318802f3bcc8b28e4f478d"
7
+ },
8
+ {
9
+ "bytes": 9352,
10
+ "path": "auth_mail.py",
11
+ "sha256": "f64a12c7ae240c9fd69ded6a7e40617eba639d29c390d1b32f903760bb43f3ae"
12
+ },
13
+ {
14
+ "bytes": 1600,
15
+ "path": "backend.py",
16
+ "sha256": "2827d11f5e3027fc2d97511ccd53dfa1021a94b562fbd27e07fd0e8b384a925d"
17
+ },
18
+ {
19
+ "bytes": 28523,
20
+ "path": "database.py",
21
+ "sha256": "ea2b5b4e393139c8321f77e3cda1d605da9c0a0c07aba0451191fe6885e8d40f"
22
+ },
23
+ {
24
+ "bytes": 8499,
25
+ "path": "effects_mail.py",
26
+ "sha256": "64fe22010ae20bc9a463749bfe28dff3454d01f6e5e7a5631649d173dc52c429"
27
+ },
28
+ {
29
+ "bytes": 957,
30
+ "path": "errors.py",
31
+ "sha256": "af16a877f63532c8ec11d15904b5f135ba162a33df9915942d795d5822bf145a"
32
+ },
33
+ {
34
+ "bytes": 19662,
35
+ "path": "mail.py",
36
+ "sha256": "3952170f9682580ee26c6b69551a38744d3776ed73b4ef68a893997083b68475"
37
+ },
38
+ {
39
+ "bytes": 28119,
40
+ "path": "payments.py",
41
+ "sha256": "08247c3b3d86355cfff16e1529a1a6163f00c785c7fbfcb0eb3dc197112a097a"
42
+ },
43
+ {
44
+ "bytes": 22902,
45
+ "path": "runtime.py",
46
+ "sha256": "61fb15c9ff24731c8f3683f8fcebb45383e046e17fbd7ea06fe4dfd3db2441b1"
47
+ },
48
+ {
49
+ "bytes": 9289,
50
+ "path": "stdio_bridge.py",
51
+ "sha256": "e02fb0b4f19c0cf25d029ae1af62066f0c6ab3bdf4a731804e6146b8f06cb9d1"
52
+ },
53
+ {
54
+ "bytes": 13752,
55
+ "path": "stripe_test.py",
56
+ "sha256": "59f781298ee10b635521563acd88b665dee3ae78adf2bcc2ad87a160d226a440"
57
+ },
58
+ {
59
+ "bytes": 698,
60
+ "path": "validation_cli.py",
61
+ "sha256": "b50f7a19dc76cb5e2778e5009c7c3446d1772ba8b449e459b7823dbcef350770"
62
+ }
63
+ ],
64
+ "schema_version": "websitebench.site-backend.vendor.v1",
65
+ "source": "src/websitebench/site_backend"
66
+ }
tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/__init__.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared semantics for site-isolated clone databases, mail, and payments."""
2
+
3
+ from .backend import SiteBackend
4
+ from .auth_mail import AuthMailDelivery, AuthMailDeliveryError
5
+ from .effects_mail import EffectsMailDelivery, EffectsMailDeliveryError
6
+ from .errors import (
7
+ LifecycleError,
8
+ MailError,
9
+ PaymentConflict,
10
+ PaymentError,
11
+ PaymentRejected,
12
+ RuntimeContractError,
13
+ SiteBackendError,
14
+ SiteBindingError,
15
+ )
16
+ from .runtime import RUNTIME_SCHEMA_VERSION, RuntimeConfig, load_runtime
17
+ from .stdio_bridge import (
18
+ BRIDGE_SCHEMA_VERSION,
19
+ BridgeProtocolError,
20
+ BridgeService,
21
+ serve_jsonl,
22
+ validate_allowlist,
23
+ )
24
+
25
+ __all__ = [
26
+ "RUNTIME_SCHEMA_VERSION",
27
+ "BRIDGE_SCHEMA_VERSION",
28
+ "BridgeProtocolError",
29
+ "BridgeService",
30
+ "LifecycleError",
31
+ "AuthMailDelivery",
32
+ "AuthMailDeliveryError",
33
+ "EffectsMailDelivery",
34
+ "EffectsMailDeliveryError",
35
+ "MailError",
36
+ "PaymentConflict",
37
+ "PaymentError",
38
+ "PaymentRejected",
39
+ "RuntimeConfig",
40
+ "RuntimeContractError",
41
+ "SiteBackend",
42
+ "SiteBackendError",
43
+ "SiteBindingError",
44
+ "load_runtime",
45
+ "serve_jsonl",
46
+ "validate_allowlist",
47
+ ]
tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/auth_mail.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deliver hash-only local-auth challenges through the isolated mail gateway.
2
+
3
+ The local auth store keeps a cleartext challenge only in process memory. This
4
+ adapter claims that ephemeral value, sends one structured envelope to the
5
+ site-local ``resend.internal`` gateway, and records only a sanitized delivery
6
+ state. Provider credentials, rendered bodies, and cleartext challenges never
7
+ enter SQLite.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ import os
15
+ from collections.abc import Callable, Mapping
16
+ from typing import TYPE_CHECKING, Any
17
+ from urllib.error import HTTPError, URLError
18
+ from urllib.parse import urlsplit
19
+ from urllib.request import Request, urlopen
20
+
21
+ from .errors import MailError
22
+
23
+ if TYPE_CHECKING: # pragma: no cover - imports are structural only
24
+ from websitebench.local_clone_auth import LocalAuthStore
25
+
26
+ from .backend import SiteBackend
27
+
28
+
29
+ AUTH_MAIL_PURPOSES = frozenset({"registration", "password-reset"})
30
+ AUTH_MAIL_MINUTES = 10
31
+ RESEND_INTERNAL_ORIGIN_ENV = "WEBSITEBENCH_RESEND_INTERNAL_ORIGIN"
32
+ EFFECTS_TOKEN_ENVS = (
33
+ "WEBSITEBENCH_EFFECTS_INTERNAL_TOKEN",
34
+ "PUBLIC_CLONE_AUTH_EFFECTS_TOKEN",
35
+ )
36
+ INTERNAL_HTTP_SCHEME = "http"
37
+ INTERNAL_URL_SEPARATOR = "/"
38
+ DEFAULT_RESEND_INTERNAL_ORIGIN = (
39
+ f"{INTERNAL_HTTP_SCHEME}:{INTERNAL_URL_SEPARATOR}"
40
+ f"{INTERNAL_URL_SEPARATOR}resend.internal"
41
+ )
42
+ MAX_RESPONSE_BYTES = 64 * 1024
43
+
44
+
45
+ class AuthMailDeliveryError(MailError):
46
+ """A safe, non-provider-specific authentication-mail failure."""
47
+
48
+
49
+ class _DeliveryFailure(AuthMailDeliveryError):
50
+ def __init__(self, category: str) -> None:
51
+ super().__init__("authentication mail delivery was deferred")
52
+ self.category = category
53
+
54
+
55
+ def _safe_internal_endpoint(environment: Mapping[str, str]) -> str:
56
+ raw = str(
57
+ environment.get(RESEND_INTERNAL_ORIGIN_ENV, DEFAULT_RESEND_INTERNAL_ORIGIN)
58
+ ).strip().rstrip("/")
59
+ parsed = urlsplit(raw)
60
+ if (
61
+ parsed.scheme != "http"
62
+ or parsed.hostname != "resend.internal"
63
+ or parsed.username
64
+ or parsed.password
65
+ or parsed.path not in {"", "/"}
66
+ or parsed.query
67
+ or parsed.fragment
68
+ or parsed.port not in {None, 8080}
69
+ ):
70
+ raise AuthMailDeliveryError(
71
+ "authentication mail requires the isolated resend.internal gateway"
72
+ )
73
+ return f"{parsed.scheme}://{parsed.netloc}/auth-emails"
74
+
75
+
76
+ def _effects_token(environment: Mapping[str, str]) -> str:
77
+ for name in EFFECTS_TOKEN_ENVS:
78
+ value = str(environment.get(name, "")).strip()
79
+ if value:
80
+ return value
81
+ return ""
82
+
83
+
84
+ def _response_status(response: Any) -> int:
85
+ value = getattr(response, "status", None)
86
+ if isinstance(value, int):
87
+ return value
88
+ getcode = getattr(response, "getcode", None)
89
+ value = getcode() if callable(getcode) else None
90
+ return value if isinstance(value, int) else 200
91
+
92
+
93
+ def _failure_category(status: int | None) -> str:
94
+ if status in {401, 403}:
95
+ return "provider-auth"
96
+ if status == 429:
97
+ return "provider-rate-limit"
98
+ if status is not None and 400 <= status < 500:
99
+ return "provider-rejected"
100
+ if status is not None and status >= 500:
101
+ return "network"
102
+ return "unknown"
103
+
104
+
105
+ class AuthMailDelivery:
106
+ """Deliver one session-owned registration or recovery challenge."""
107
+
108
+ def __init__(
109
+ self,
110
+ backend: "SiteBackend",
111
+ auth_store: "LocalAuthStore",
112
+ *,
113
+ worker_token: str,
114
+ environment: Mapping[str, str] | None = None,
115
+ opener: Callable[..., Any] | None = None,
116
+ ) -> None:
117
+ if not isinstance(worker_token, str) or len(worker_token) < 20:
118
+ raise AuthMailDeliveryError("mail worker authority is unavailable")
119
+ source = os.environ if environment is None else environment
120
+ self.backend = backend
121
+ self.auth_store = auth_store
122
+ self.worker_token = worker_token
123
+ self.endpoint = _safe_internal_endpoint(source)
124
+ self.effects_token = _effects_token(source)
125
+ self._opener = urlopen if opener is None else opener
126
+
127
+ def _post(self, envelope: Mapping[str, Any], idempotency_key: str) -> None:
128
+ body = json.dumps(
129
+ envelope,
130
+ ensure_ascii=True,
131
+ sort_keys=True,
132
+ separators=(",", ":"),
133
+ ).encode("utf-8")
134
+ headers = {
135
+ "Accept": "application/json",
136
+ "Content-Type": "application/json",
137
+ "Idempotency-Key": idempotency_key,
138
+ "User-Agent": (
139
+ f"WebsiteBench-{self.backend.config.site_id}-Auth-Mail/1.0"
140
+ ),
141
+ }
142
+ if self.effects_token:
143
+ headers["X-WebsiteBench-Effects-Token"] = self.effects_token
144
+ request = Request(self.endpoint, data=body, headers=headers, method="POST")
145
+ try:
146
+ response = self._opener(request, timeout=10)
147
+ try:
148
+ raw = response.read(MAX_RESPONSE_BYTES + 1)
149
+ status = _response_status(response)
150
+ finally:
151
+ close = getattr(response, "close", None)
152
+ if callable(close):
153
+ close()
154
+ except HTTPError as exc:
155
+ raise _DeliveryFailure(_failure_category(exc.code)) from exc
156
+ except (URLError, TimeoutError, OSError) as exc:
157
+ raise _DeliveryFailure("network") from exc
158
+ if status < 200 or status >= 300:
159
+ raise _DeliveryFailure(_failure_category(status))
160
+ if not isinstance(raw, bytes) or len(raw) > MAX_RESPONSE_BYTES:
161
+ raise _DeliveryFailure("unknown")
162
+ try:
163
+ payload = json.loads(raw.decode("utf-8"))
164
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
165
+ raise _DeliveryFailure("unknown") from exc
166
+ if not isinstance(payload, dict) or payload.get("ok") is not True:
167
+ raise _DeliveryFailure("unknown")
168
+
169
+ def deliver_for_session(
170
+ self,
171
+ session_token: str,
172
+ *,
173
+ purpose: str,
174
+ ) -> dict[str, Any] | None:
175
+ """Claim, deliver, and finalize one session-owned auth message."""
176
+
177
+ if purpose not in AUTH_MAIL_PURPOSES:
178
+ raise AuthMailDeliveryError("authentication mail purpose is invalid")
179
+ claim = self.auth_store.claim_pending_mail_for_session(
180
+ session_token,
181
+ purpose=purpose,
182
+ worker_token=self.worker_token,
183
+ )
184
+ if claim is None:
185
+ return None
186
+ mail_id = int(claim["mail_id"])
187
+ claim_token = str(claim["claim_token"])
188
+ try:
189
+ issued = self.backend.mail.issue(
190
+ purpose,
191
+ str(claim["recipient"]),
192
+ {
193
+ "code": str(claim["verification_code"]),
194
+ "minutes": AUTH_MAIL_MINUTES,
195
+ },
196
+ )
197
+ if issued.get("contains_secret_variables") is not True:
198
+ raise AuthMailDeliveryError(
199
+ "authentication mail template must contain a secret challenge"
200
+ )
201
+ envelope = {
202
+ "purpose": purpose,
203
+ "recipient": str(claim["recipient"]),
204
+ "template_id": str(issued["template_id"]),
205
+ "variables": {
206
+ "code": str(claim["verification_code"]),
207
+ "minutes": AUTH_MAIL_MINUTES,
208
+ },
209
+ }
210
+ except Exception as exc:
211
+ self.auth_store.finish_mail_claim(
212
+ mail_id,
213
+ claim_token,
214
+ sent=False,
215
+ target_request_count=0,
216
+ accepted_request_count=0,
217
+ error="configuration",
218
+ worker_token=self.worker_token,
219
+ )
220
+ if isinstance(exc, AuthMailDeliveryError):
221
+ raise
222
+ raise AuthMailDeliveryError(
223
+ "authentication mail template is invalid"
224
+ ) from exc
225
+
226
+ idempotency_key = hashlib.sha256(
227
+ (
228
+ f"{self.backend.config.site_id}\0{mail_id}\0"
229
+ f"{claim['flow_id']}\0{purpose}"
230
+ ).encode("utf-8")
231
+ ).hexdigest()
232
+ self.auth_store.reserve_mail_target_request(
233
+ mail_id,
234
+ claim_token,
235
+ worker_token=self.worker_token,
236
+ )
237
+ try:
238
+ self._post(envelope, idempotency_key)
239
+ except _DeliveryFailure as exc:
240
+ self.auth_store.finish_mail_claim(
241
+ mail_id,
242
+ claim_token,
243
+ sent=False,
244
+ target_request_count=1,
245
+ accepted_request_count=0,
246
+ error=exc.category,
247
+ worker_token=self.worker_token,
248
+ )
249
+ raise AuthMailDeliveryError(
250
+ "authentication mail delivery was deferred"
251
+ ) from exc
252
+ self.auth_store.finish_mail_claim(
253
+ mail_id,
254
+ claim_token,
255
+ sent=True,
256
+ target_request_count=1,
257
+ accepted_request_count=1,
258
+ worker_token=self.worker_token,
259
+ )
260
+ return {
261
+ "mail_id": mail_id,
262
+ "purpose": purpose,
263
+ "status": "SMTP_SENT",
264
+ }
265
+
266
+
267
+ __all__ = [
268
+ "AUTH_MAIL_MINUTES",
269
+ "AUTH_MAIL_PURPOSES",
270
+ "AuthMailDelivery",
271
+ "AuthMailDeliveryError",
272
+ ]
tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/backend.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The small public interface for one site-isolated backend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import sqlite3
10
+
11
+ from .database import SiteDatabaseLifecycle
12
+ from .mail import SiteMail
13
+ from .payments import SitePayments
14
+ from .runtime import RuntimeConfig, load_runtime
15
+
16
+
17
+ class SiteBackend:
18
+ """One runtime contract, one site binding, and three deep capabilities."""
19
+
20
+ def __init__(
21
+ self,
22
+ runtime: RuntimeConfig,
23
+ lifecycle: SiteDatabaseLifecycle,
24
+ ) -> None:
25
+ self.config = runtime
26
+ self.lifecycle = lifecycle
27
+ self.mail = SiteMail(runtime, lifecycle)
28
+ self.payments = SitePayments(runtime, lifecycle)
29
+
30
+ @classmethod
31
+ def open(
32
+ cls,
33
+ config: Path | str | Mapping[str, Any],
34
+ *,
35
+ data_root: Path | None = None,
36
+ migration_hook: Callable[[sqlite3.Connection], None] | None = None,
37
+ seed_hook: Callable[[sqlite3.Connection], None] | None = None,
38
+ ) -> "SiteBackend":
39
+ runtime = load_runtime(config)
40
+ lifecycle = SiteDatabaseLifecycle(
41
+ runtime,
42
+ data_root=data_root,
43
+ migration_hook=migration_hook,
44
+ seed_hook=seed_hook,
45
+ )
46
+ return cls(runtime, lifecycle)
47
+
48
+ @property
49
+ def session_cookie(self) -> dict[str, Any]:
50
+ """Framework-neutral Host-only cookie facts; intentionally no Domain."""
51
+
52
+ return {
53
+ "name": self.config.cookie_name,
54
+ **dict(self.config.cookie_options),
55
+ }
tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/database.py ADDED
@@ -0,0 +1,726 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
1
+ """Site-bound SQLite lifecycle implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import sqlite3
9
+ import stat
10
+ import tempfile
11
+ from collections.abc import Callable, Iterator
12
+ from contextlib import closing, contextmanager
13
+ from datetime import UTC, datetime
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from .errors import LifecycleError, SiteBindingError
18
+ from .runtime import RuntimeConfig
19
+
20
+
21
+ MigrationHook = Callable[[sqlite3.Connection], None]
22
+
23
+ BASE_SCHEMA = """
24
+ CREATE TABLE IF NOT EXISTS websitebench_site_binding (
25
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
26
+ site_id TEXT NOT NULL UNIQUE,
27
+ bound_at TEXT NOT NULL
28
+ );
29
+
30
+ CREATE TABLE IF NOT EXISTS websitebench_backend_migrations (
31
+ migration_id TEXT PRIMARY KEY,
32
+ applied_at TEXT NOT NULL
33
+ );
34
+
35
+ CREATE TABLE IF NOT EXISTS websitebench_mail_jobs (
36
+ mail_id TEXT PRIMARY KEY,
37
+ site_id TEXT NOT NULL,
38
+ purpose TEXT NOT NULL,
39
+ template_id TEXT NOT NULL,
40
+ recipient TEXT NOT NULL,
41
+ recipient_digest TEXT NOT NULL,
42
+ variables_json TEXT NOT NULL,
43
+ status TEXT NOT NULL CHECK (
44
+ status IN ('LOCAL_SIMULATION','PENDING','SENT','FAILED')
45
+ ),
46
+ is_simulation INTEGER NOT NULL CHECK (is_simulation IN (0,1)),
47
+ delivery_attempts INTEGER NOT NULL DEFAULT 0 CHECK (delivery_attempts >= 0),
48
+ claim_token TEXT,
49
+ claimed_at INTEGER,
50
+ next_attempt_at INTEGER NOT NULL DEFAULT 0,
51
+ error_category TEXT,
52
+ sent_at TEXT,
53
+ idempotency_key TEXT NOT NULL,
54
+ created_at TEXT NOT NULL,
55
+ updated_at TEXT NOT NULL,
56
+ UNIQUE (site_id, purpose, idempotency_key)
57
+ );
58
+
59
+ CREATE INDEX IF NOT EXISTS websitebench_mail_jobs_status_idx
60
+ ON websitebench_mail_jobs(site_id, status, created_at);
61
+
62
+ CREATE TABLE IF NOT EXISTS websitebench_payment_flows (
63
+ flow_id TEXT PRIMARY KEY,
64
+ site_id TEXT NOT NULL,
65
+ owner TEXT NOT NULL,
66
+ amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
67
+ currency TEXT NOT NULL,
68
+ fingerprint TEXT NOT NULL,
69
+ adapter TEXT NOT NULL,
70
+ status TEXT NOT NULL CHECK (
71
+ status IN ('OPEN','APPROVED','CONSUMED','INVALIDATED')
72
+ ),
73
+ is_simulation INTEGER NOT NULL CHECK (is_simulation = 1),
74
+ create_idempotency_key TEXT NOT NULL,
75
+ created_at TEXT NOT NULL,
76
+ updated_at TEXT NOT NULL,
77
+ UNIQUE (site_id, owner, create_idempotency_key)
78
+ );
79
+
80
+ CREATE TABLE IF NOT EXISTS websitebench_payment_attempts (
81
+ attempt_id TEXT PRIMARY KEY,
82
+ site_id TEXT NOT NULL,
83
+ flow_id TEXT NOT NULL
84
+ REFERENCES websitebench_payment_flows(flow_id) ON DELETE RESTRICT,
85
+ owner TEXT NOT NULL,
86
+ scenario_id TEXT NOT NULL,
87
+ amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
88
+ currency TEXT NOT NULL,
89
+ fingerprint TEXT NOT NULL,
90
+ status TEXT NOT NULL CHECK (
91
+ status IN ('APPROVED','DECLINED','RETRYABLE','SUPERSEDED','CONSUMED')
92
+ ),
93
+ idempotency_key TEXT NOT NULL,
94
+ provider_reference TEXT,
95
+ is_simulation INTEGER NOT NULL CHECK (is_simulation = 1),
96
+ created_at TEXT NOT NULL,
97
+ consumed_at TEXT,
98
+ UNIQUE (site_id, flow_id, idempotency_key)
99
+ );
100
+
101
+ CREATE UNIQUE INDEX IF NOT EXISTS websitebench_payment_one_active_approval
102
+ ON websitebench_payment_attempts(site_id, flow_id)
103
+ WHERE status = 'APPROVED';
104
+
105
+ CREATE TABLE IF NOT EXISTS websitebench_payment_events (
106
+ event_id TEXT PRIMARY KEY,
107
+ site_id TEXT NOT NULL,
108
+ flow_id TEXT NOT NULL
109
+ REFERENCES websitebench_payment_flows(flow_id) ON DELETE RESTRICT,
110
+ attempt_id TEXT
111
+ REFERENCES websitebench_payment_attempts(attempt_id) ON DELETE RESTRICT,
112
+ event_type TEXT NOT NULL,
113
+ snapshot_json TEXT NOT NULL,
114
+ created_at TEXT NOT NULL
115
+ );
116
+
117
+ CREATE TRIGGER IF NOT EXISTS websitebench_payment_events_no_update
118
+ BEFORE UPDATE ON websitebench_payment_events
119
+ BEGIN
120
+ SELECT RAISE(ABORT, 'payment events are immutable');
121
+ END;
122
+
123
+ CREATE TRIGGER IF NOT EXISTS websitebench_payment_events_no_delete
124
+ BEFORE DELETE ON websitebench_payment_events
125
+ BEGIN
126
+ SELECT RAISE(ABORT, 'payment events are immutable');
127
+ END;
128
+ """
129
+
130
+
131
+ def utc_now() -> str:
132
+ return datetime.now(UTC).isoformat().replace("+00:00", "Z")
133
+
134
+
135
+ def _is_link_or_reparse(path: Path) -> bool:
136
+ metadata = path.lstat()
137
+ if stat.S_ISLNK(metadata.st_mode):
138
+ return True
139
+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
140
+ return bool(getattr(metadata, "st_file_attributes", 0) & reparse) or bool(
141
+ hasattr(path, "is_junction") and path.is_junction()
142
+ )
143
+
144
+
145
+ def _assert_no_existing_link(path: Path, stop: Path) -> None:
146
+ cursor = path
147
+ while cursor != stop:
148
+ if cursor.exists() and _is_link_or_reparse(cursor):
149
+ raise LifecycleError(f"database path crosses a link/reparse point: {cursor}")
150
+ if cursor.parent == cursor:
151
+ break
152
+ cursor = cursor.parent
153
+ if stop.exists() and _is_link_or_reparse(stop):
154
+ raise LifecycleError("data root must not be a link/reparse point")
155
+
156
+
157
+ def _filesystem_root(path: Path) -> Path:
158
+ root = Path(path.anchor)
159
+ if not root.anchor:
160
+ raise LifecycleError("database path must be absolute")
161
+ return root
162
+
163
+
164
+ def _sha256(path: Path) -> str:
165
+ digest = hashlib.sha256()
166
+ with path.open("rb") as stream:
167
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
168
+ digest.update(chunk)
169
+ return digest.hexdigest()
170
+
171
+
172
+ def _bind_hook(
173
+ declared: str | None,
174
+ provided: MigrationHook | None,
175
+ *,
176
+ label: str,
177
+ ) -> MigrationHook | None:
178
+ if declared is None:
179
+ if provided is not None:
180
+ raise LifecycleError(
181
+ f"{label} callable was provided but runtime declares no {label}"
182
+ )
183
+ return None
184
+ if provided is None:
185
+ raise LifecycleError(f"runtime declares {label} {declared!r} but no callable was provided")
186
+ actual = f"{provided.__module__}:{provided.__name__}"
187
+ if actual != declared:
188
+ raise LifecycleError(
189
+ f"{label} callable {actual!r} does not match runtime declaration {declared!r}"
190
+ )
191
+ return provided
192
+
193
+
194
+ class SiteDatabaseLifecycle:
195
+ """Own SQLite path safety, binding, schema, backup, restore, and health."""
196
+
197
+ def __init__(
198
+ self,
199
+ runtime: RuntimeConfig,
200
+ *,
201
+ data_root: Path | None,
202
+ migration_hook: MigrationHook | None,
203
+ seed_hook: MigrationHook | None,
204
+ ) -> None:
205
+ self.runtime = runtime
206
+ default_root = (
207
+ runtime.site_root / runtime.data_dir
208
+ if runtime.site_root is not None
209
+ else None
210
+ )
211
+ if data_root is not None and default_root is not None:
212
+ if Path(data_root).absolute() != default_root.absolute():
213
+ raise LifecycleError(
214
+ "data_root cannot override a file-backed runtime contract"
215
+ )
216
+ selected = data_root if data_root is not None else default_root
217
+ if selected is None:
218
+ raise LifecycleError(
219
+ "data_root is required when runtime config is not loaded from a file"
220
+ )
221
+ unresolved = Path(selected).absolute()
222
+ filesystem_root = _filesystem_root(unresolved)
223
+ # Check every existing component before mkdir so an intermediate
224
+ # junction/symlink cannot redirect creation outside the declared root.
225
+ _assert_no_existing_link(unresolved, filesystem_root)
226
+ unresolved.mkdir(parents=True, exist_ok=True)
227
+ if not unresolved.is_dir():
228
+ raise LifecycleError("data_root must be a directory")
229
+ _assert_no_existing_link(unresolved, filesystem_root)
230
+ self.data_root = unresolved.resolve()
231
+ self.database_path = self.data_root / runtime.database_filename
232
+ if self.database_path.parent != self.data_root:
233
+ raise LifecycleError("database filename escaped data_root")
234
+ _assert_no_existing_link(self.database_path, filesystem_root)
235
+ self._filesystem_root = filesystem_root
236
+ self._migration_hook = _bind_hook(
237
+ runtime.migration_hook, migration_hook, label="migration_hook"
238
+ )
239
+ self._seed_hook = _bind_hook(
240
+ runtime.seed_hook, seed_hook, label="seed_hook"
241
+ )
242
+ self._inspect_existing_binding()
243
+
244
+ def _connect(self, path: Path | None = None) -> sqlite3.Connection:
245
+ selected_path = path or self.database_path
246
+ if selected_path == self.database_path:
247
+ _assert_no_existing_link(self.database_path, self._filesystem_root)
248
+ connection = sqlite3.connect(
249
+ str(selected_path), timeout=30, isolation_level=None
250
+ )
251
+ connection.row_factory = sqlite3.Row
252
+ connection.execute("PRAGMA foreign_keys=ON")
253
+ connection.execute("PRAGMA secure_delete=ON")
254
+ connection.execute("PRAGMA busy_timeout=30000")
255
+ return connection
256
+
257
+ def _binding(self, connection: sqlite3.Connection) -> str | None:
258
+ legacy = connection.execute(
259
+ "SELECT 1 FROM sqlite_master WHERE type='table' "
260
+ "AND name='clawbench_site_binding'"
261
+ ).fetchone()
262
+ if legacy is not None:
263
+ raise SiteBindingError(
264
+ "database is bound by the other runtime namespace; "
265
+ "copy-only migration is required"
266
+ )
267
+ exists = connection.execute(
268
+ "SELECT 1 FROM sqlite_master WHERE type='table' "
269
+ "AND name='websitebench_site_binding'"
270
+ ).fetchone()
271
+ if exists is None:
272
+ return None
273
+ rows = connection.execute(
274
+ "SELECT singleton,site_id FROM websitebench_site_binding"
275
+ ).fetchall()
276
+ if len(rows) != 1 or int(rows[0]["singleton"]) != 1:
277
+ raise SiteBindingError("database site binding is missing or corrupt")
278
+ return str(rows[0]["site_id"])
279
+
280
+ def _assert_binding(self, connection: sqlite3.Connection) -> None:
281
+ actual = self._binding(connection)
282
+ if actual is None:
283
+ raise SiteBindingError("database is not initialized with a site binding")
284
+ if actual != self.runtime.site_id:
285
+ raise SiteBindingError(
286
+ f"database belongs to site {actual!r}, not {self.runtime.site_id!r}"
287
+ )
288
+
289
+ def _inspect_existing_binding(self) -> None:
290
+ if not self.database_path.exists():
291
+ return
292
+ if not self.database_path.is_file() or self.database_path.is_symlink():
293
+ raise LifecycleError("database path must be a regular file")
294
+ try:
295
+ with closing(self._connect()) as connection:
296
+ actual = self._binding(connection)
297
+ except sqlite3.DatabaseError as exc:
298
+ raise LifecycleError(f"existing database is not valid SQLite: {exc}") from exc
299
+ if actual is not None and actual != self.runtime.site_id:
300
+ raise SiteBindingError(
301
+ f"database belongs to site {actual!r}, not {self.runtime.site_id!r}"
302
+ )
303
+ if actual is None and not self.runtime.legacy_unbound_migration:
304
+ raise SiteBindingError(
305
+ "existing database has no site binding and runtime does not "
306
+ "authorize a legacy migration"
307
+ )
308
+
309
+ def _integrity(self, connection: sqlite3.Connection) -> dict[str, Any]:
310
+ integrity_rows = [
311
+ str(row[0]) for row in connection.execute("PRAGMA integrity_check")
312
+ ]
313
+ foreign_keys = [
314
+ tuple(row) for row in connection.execute("PRAGMA foreign_key_check")
315
+ ]
316
+ if integrity_rows != ["ok"] or foreign_keys:
317
+ raise LifecycleError("database integrity or foreign-key check failed")
318
+ self._assert_binding(connection)
319
+ return {"integrity_check": "ok", "foreign_key_violations": 0}
320
+
321
+ def _run_declared_hook_once(
322
+ self,
323
+ connection: sqlite3.Connection,
324
+ *,
325
+ kind: str,
326
+ declaration: str | None,
327
+ hook: MigrationHook | None,
328
+ ) -> bool:
329
+ if declaration is None:
330
+ return False
331
+ if hook is None:
332
+ raise LifecycleError(f"{kind} hook is declared but unavailable")
333
+ migration_id = f"site-{kind}:{declaration}"
334
+ already_applied = connection.execute(
335
+ "SELECT 1 FROM websitebench_backend_migrations WHERE migration_id=?",
336
+ (migration_id,),
337
+ ).fetchone()
338
+ if already_applied is not None:
339
+ return False
340
+ hook(connection)
341
+ connection.execute(
342
+ "INSERT INTO websitebench_backend_migrations(migration_id,applied_at) "
343
+ "VALUES (?,?)",
344
+ (migration_id, utc_now()),
345
+ )
346
+ return True
347
+
348
+ @staticmethod
349
+ def _migrate_base_schema(connection: sqlite3.Connection) -> None:
350
+ """Add v1 delivery-state columns to early site_backend databases."""
351
+
352
+ columns = {
353
+ str(row["name"])
354
+ for row in connection.execute("PRAGMA table_info(websitebench_mail_jobs)")
355
+ }
356
+ additions = {
357
+ "recipient": "TEXT NOT NULL DEFAULT ''",
358
+ "claim_token": "TEXT",
359
+ "claimed_at": "INTEGER",
360
+ "next_attempt_at": "INTEGER NOT NULL DEFAULT 0",
361
+ "sent_at": "TEXT",
362
+ }
363
+ for name, declaration in additions.items():
364
+ if name not in columns:
365
+ connection.execute(
366
+ f"ALTER TABLE websitebench_mail_jobs ADD COLUMN {name} {declaration}"
367
+ )
368
+
369
+ def _apply_current_runtime(
370
+ self, connection: sqlite3.Connection, *, seed_new_database: bool
371
+ ) -> None:
372
+ self._run_declared_hook_once(
373
+ connection,
374
+ kind="migration",
375
+ declaration=self.runtime.migration_hook,
376
+ hook=self._migration_hook,
377
+ )
378
+ if seed_new_database:
379
+ self._run_declared_hook_once(
380
+ connection,
381
+ kind="seed",
382
+ declaration=self.runtime.seed_hook,
383
+ hook=self._seed_hook,
384
+ )
385
+ connection.execute(
386
+ "INSERT OR IGNORE INTO websitebench_backend_migrations"
387
+ "(migration_id,applied_at) VALUES (?,?)",
388
+ ("site-backend-v1", utc_now()),
389
+ )
390
+
391
+ def initialize(self, *, authorize_legacy_binding: bool = False) -> dict[str, Any]:
392
+ return self._initialize(
393
+ authorize_legacy_binding=authorize_legacy_binding,
394
+ verify_integrity=True,
395
+ )
396
+
397
+ def prepare_legacy_migration(self) -> dict[str, Any]:
398
+ """Bind/install common tables before a legacy site's repair migration.
399
+
400
+ New scaffolds must use ``initialize``. This compatibility seam is
401
+ available only when the frozen runtime explicitly authorizes an
402
+ unbound legacy migration. The caller must run its site migration and
403
+ then call ``health`` before serving traffic.
404
+ """
405
+
406
+ if not self.runtime.legacy_unbound_migration:
407
+ raise LifecycleError(
408
+ "runtime does not authorize a deferred legacy site migration"
409
+ )
410
+ return self._initialize(
411
+ authorize_legacy_binding=True,
412
+ verify_integrity=False,
413
+ )
414
+
415
+ def prepare_bound_site_migration(self) -> dict[str, Any]:
416
+ """Install common tables before repairing an already bound site DB.
417
+
418
+ This compatibility seam never adopts an unbound database. It permits
419
+ a migrated site to repair an old business schema before the mandatory
420
+ post-migration integrity check.
421
+ """
422
+
423
+ if not self.database_path.is_file() or self.database_path.stat().st_size == 0:
424
+ raise LifecycleError(
425
+ "bound site migration requires an existing database"
426
+ )
427
+ with closing(self._connect()) as connection:
428
+ self._assert_binding(connection)
429
+ return self._initialize(
430
+ authorize_legacy_binding=False,
431
+ verify_integrity=False,
432
+ )
433
+
434
+ def _initialize(
435
+ self,
436
+ *,
437
+ authorize_legacy_binding: bool,
438
+ verify_integrity: bool,
439
+ ) -> dict[str, Any]:
440
+ existed = self.database_path.exists() and self.database_path.stat().st_size > 0
441
+ with closing(self._connect()) as connection:
442
+ previous_binding = self._binding(connection)
443
+ if previous_binding is None and existed:
444
+ if not (
445
+ authorize_legacy_binding
446
+ and self.runtime.legacy_unbound_migration
447
+ ):
448
+ raise SiteBindingError(
449
+ "legacy unbound database requires explicit migration authorization"
450
+ )
451
+ elif previous_binding is not None and previous_binding != self.runtime.site_id:
452
+ raise SiteBindingError("database belongs to another site")
453
+
454
+ # SQLite's executescript owns its transaction edge. Install the
455
+ # additive schema first, then bind/migrate data in one explicit
456
+ # transaction.
457
+ connection.executescript(BASE_SCHEMA)
458
+ self._migrate_base_schema(connection)
459
+ connection.execute("BEGIN IMMEDIATE")
460
+ try:
461
+ connection.execute(
462
+ "INSERT OR IGNORE INTO websitebench_site_binding"
463
+ "(singleton,site_id,bound_at) VALUES (1,?,?)",
464
+ (self.runtime.site_id, utc_now()),
465
+ )
466
+ self._assert_binding(connection)
467
+ self._apply_current_runtime(
468
+ connection, seed_new_database=not existed
469
+ )
470
+ if verify_integrity:
471
+ self._integrity(connection)
472
+ connection.execute("COMMIT")
473
+ except Exception:
474
+ if connection.in_transaction:
475
+ connection.execute("ROLLBACK")
476
+ if previous_binding is None:
477
+ # BASE_SCHEMA is intentionally additive and may have
478
+ # created the singleton table before this transaction.
479
+ # Do not leave an empty, apparently corrupt binding behind
480
+ # when first-time binding/migration fails.
481
+ binding_rows = connection.execute(
482
+ "SELECT COUNT(*) FROM websitebench_site_binding"
483
+ ).fetchone()
484
+ if binding_rows is not None and int(binding_rows[0]) == 0:
485
+ connection.execute(
486
+ "DROP TABLE IF EXISTS websitebench_site_binding"
487
+ )
488
+ raise
489
+ if verify_integrity:
490
+ return self.health()
491
+ return {
492
+ "status": (
493
+ "legacy-migration-required"
494
+ if previous_binding is None
495
+ else "site-migration-required"
496
+ ),
497
+ "site_id": self.runtime.site_id,
498
+ "database_bound": True,
499
+ }
500
+
501
+ @contextmanager
502
+ def connection(self, *, transaction: bool = False) -> Iterator[sqlite3.Connection]:
503
+ if not self.database_path.exists():
504
+ raise LifecycleError("database is not initialized")
505
+ connection = self._connect()
506
+ try:
507
+ self._assert_binding(connection)
508
+ if transaction:
509
+ connection.execute("BEGIN IMMEDIATE")
510
+ yield connection
511
+ if transaction and connection.in_transaction:
512
+ connection.execute("COMMIT")
513
+ except Exception:
514
+ if transaction and connection.in_transaction:
515
+ connection.execute("ROLLBACK")
516
+ raise
517
+ finally:
518
+ connection.close()
519
+
520
+ def reset(self, *, confirm_site_id: str) -> dict[str, Any]:
521
+ if confirm_site_id != self.runtime.site_id:
522
+ raise LifecycleError("reset confirmation does not match site_id")
523
+ if self.database_path.exists():
524
+ with closing(self._connect()) as connection:
525
+ self._assert_binding(connection)
526
+ for suffix in ("", "-wal", "-shm"):
527
+ target = Path(f"{self.database_path}{suffix}")
528
+ if target.exists():
529
+ if target.parent != self.data_root:
530
+ raise LifecycleError("reset target escaped data_root")
531
+ target.unlink()
532
+ return self.initialize()
533
+
534
+ def reset_embedded(
535
+ self,
536
+ connection: sqlite3.Connection,
537
+ *,
538
+ confirm_site_id: str,
539
+ ) -> None:
540
+ """Clear common mutable state inside a site's existing transaction."""
541
+
542
+ if confirm_site_id != self.runtime.site_id:
543
+ raise LifecycleError("embedded reset confirmation does not match site_id")
544
+ if not connection.in_transaction:
545
+ raise LifecycleError("embedded reset requires a caller-owned transaction")
546
+ self._assert_binding(connection)
547
+ connection.execute(
548
+ "DROP TRIGGER IF EXISTS websitebench_payment_events_no_update"
549
+ )
550
+ connection.execute(
551
+ "DROP TRIGGER IF EXISTS websitebench_payment_events_no_delete"
552
+ )
553
+ try:
554
+ for table in (
555
+ "websitebench_payment_events",
556
+ "websitebench_payment_attempts",
557
+ "websitebench_payment_flows",
558
+ "websitebench_mail_jobs",
559
+ ):
560
+ connection.execute(f"DELETE FROM {table}")
561
+ finally:
562
+ connection.execute(
563
+ """
564
+ CREATE TRIGGER IF NOT EXISTS websitebench_payment_events_no_update
565
+ BEFORE UPDATE ON websitebench_payment_events
566
+ BEGIN
567
+ SELECT RAISE(ABORT, 'payment events are immutable');
568
+ END
569
+ """
570
+ )
571
+ connection.execute(
572
+ """
573
+ CREATE TRIGGER IF NOT EXISTS websitebench_payment_events_no_delete
574
+ BEFORE DELETE ON websitebench_payment_events
575
+ BEGIN
576
+ SELECT RAISE(ABORT, 'payment events are immutable');
577
+ END
578
+ """
579
+ )
580
+
581
+ def backup(self, destination: Path) -> dict[str, Any]:
582
+ unresolved = Path(destination).absolute()
583
+ destination_root = _filesystem_root(unresolved)
584
+ _assert_no_existing_link(unresolved, destination_root)
585
+ unresolved.parent.mkdir(parents=True, exist_ok=True)
586
+ _assert_no_existing_link(unresolved, destination_root)
587
+ parent = unresolved.parent.resolve()
588
+ target = parent / unresolved.name
589
+ if target == self.database_path or target.exists():
590
+ raise LifecycleError("backup destination must be new and separate")
591
+ if target.is_symlink():
592
+ raise LifecycleError("backup destination must not be a link")
593
+ with self.connection() as source:
594
+ with closing(sqlite3.connect(str(target))) as backup:
595
+ source.backup(backup)
596
+ backup.row_factory = sqlite3.Row
597
+ self._assert_binding(backup)
598
+ integrity = self._integrity(backup)
599
+ report = {
600
+ "schema_version": "websitebench.site-backend-backup.v1",
601
+ "site_id": self.runtime.site_id,
602
+ "database": target.name,
603
+ "bytes": target.stat().st_size,
604
+ "sha256": _sha256(target),
605
+ **integrity,
606
+ }
607
+ report_path = target.with_suffix(target.suffix + ".json")
608
+ report_path.write_text(
609
+ json.dumps(report, indent=2, sort_keys=True) + "\n",
610
+ encoding="utf-8",
611
+ newline="\n",
612
+ )
613
+ return {**report, "path": str(target), "report": str(report_path)}
614
+
615
+ def restore(self, source: Path) -> dict[str, Any]:
616
+ source_path = Path(source).absolute()
617
+ source_root = _filesystem_root(source_path)
618
+ if (
619
+ not source_path.is_file()
620
+ or source_path.is_symlink()
621
+ or source_path.resolve() == self.database_path
622
+ ):
623
+ raise LifecycleError("restore source must be a separate regular file")
624
+ _assert_no_existing_link(source_path, source_root)
625
+ with closing(self._connect(source_path.resolve())) as source_connection:
626
+ self._assert_binding(source_connection)
627
+ self._integrity(source_connection)
628
+
629
+ fd, temporary_name = tempfile.mkstemp(
630
+ prefix=f".{self.database_path.name}.restore-",
631
+ dir=self.data_root,
632
+ )
633
+ os.close(fd)
634
+ temporary = Path(temporary_name)
635
+ try:
636
+ temporary.unlink()
637
+ with closing(self._connect(source_path.resolve())) as source_connection:
638
+ with closing(sqlite3.connect(str(temporary))) as restored:
639
+ source_connection.backup(restored)
640
+ with closing(self._connect(temporary)) as restored:
641
+ restored.executescript(BASE_SCHEMA)
642
+ self._migrate_base_schema(restored)
643
+ self._assert_binding(restored)
644
+ restored.execute("BEGIN IMMEDIATE")
645
+ try:
646
+ self._apply_current_runtime(
647
+ restored, seed_new_database=False
648
+ )
649
+ self._integrity(restored)
650
+ restored.execute("COMMIT")
651
+ except Exception:
652
+ if restored.in_transaction:
653
+ restored.execute("ROLLBACK")
654
+ raise
655
+ if self.database_path.exists():
656
+ # A restored main file must never inherit pages from the
657
+ # previous database's WAL. Switching to DELETE also fails if
658
+ # another process still has the database actively locked.
659
+ with closing(self._connect()) as current:
660
+ journal_mode = str(
661
+ current.execute("PRAGMA journal_mode").fetchone()[0]
662
+ ).casefold()
663
+ if journal_mode == "wal":
664
+ checkpoint = current.execute(
665
+ "PRAGMA wal_checkpoint(TRUNCATE)"
666
+ ).fetchone()
667
+ if checkpoint is None or int(checkpoint[0]) != 0:
668
+ raise LifecycleError(
669
+ "database is busy; restore cannot checkpoint WAL"
670
+ )
671
+ selected_mode = str(
672
+ current.execute("PRAGMA journal_mode=DELETE").fetchone()[0]
673
+ ).casefold()
674
+ if selected_mode != "delete":
675
+ raise LifecycleError(
676
+ "database is busy; restore cannot leave WAL mode"
677
+ )
678
+ for suffix in ("-wal", "-shm"):
679
+ sidecar = Path(f"{self.database_path}{suffix}")
680
+ if sidecar.exists():
681
+ sidecar.unlink()
682
+ os.replace(temporary, self.database_path)
683
+ finally:
684
+ temporary.unlink(missing_ok=True)
685
+ return self.health()
686
+
687
+ def health(self) -> dict[str, Any]:
688
+ if not self.database_path.exists():
689
+ return {
690
+ "status": "uninitialized",
691
+ "site_id": self.runtime.site_id,
692
+ "database_bound": False,
693
+ }
694
+ with closing(self._connect()) as connection:
695
+ binding = self._binding(connection)
696
+ if binding is None:
697
+ return {
698
+ "status": "legacy-unbound",
699
+ "site_id": self.runtime.site_id,
700
+ "database_bound": False,
701
+ }
702
+ self._assert_binding(connection)
703
+ integrity = self._integrity(connection)
704
+ counts = {}
705
+ for name in (
706
+ "websitebench_mail_jobs",
707
+ "websitebench_payment_flows",
708
+ "websitebench_payment_attempts",
709
+ "websitebench_payment_events",
710
+ ):
711
+ exists = connection.execute(
712
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
713
+ (name,),
714
+ ).fetchone()
715
+ counts[name] = (
716
+ int(connection.execute(f"SELECT COUNT(*) FROM {name}").fetchone()[0])
717
+ if exists
718
+ else 0
719
+ )
720
+ return {
721
+ "status": "ok",
722
+ "site_id": self.runtime.site_id,
723
+ "database_bound": True,
724
+ **integrity,
725
+ "counts": counts,
726
+ }
tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/effects_mail.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Narrow business-mail delivery through a site-local effects gateway.
2
+
3
+ This module moves only a claimed, non-secret outbox envelope to
4
+ ``resend.internal``. The gateway owns Resend credentials and re-renders the
5
+ frozen structured template. Applications therefore cannot turn this into a
6
+ general HTML mail relay, and a failed delivery never rolls back a completed
7
+ business transaction.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ import os
15
+ from collections.abc import Callable, Mapping
16
+ from typing import TYPE_CHECKING, Any
17
+ from urllib.error import HTTPError, URLError
18
+ from urllib.parse import urlsplit
19
+ from urllib.request import Request, urlopen
20
+
21
+ from .errors import MailError
22
+
23
+ if TYPE_CHECKING: # pragma: no cover - imported only for static checking
24
+ from .backend import SiteBackend
25
+
26
+
27
+ RESEND_INTERNAL_ORIGIN_ENV = "WEBSITEBENCH_RESEND_INTERNAL_ORIGIN"
28
+ EFFECTS_TOKEN_ENVS = (
29
+ "WEBSITEBENCH_EFFECTS_INTERNAL_TOKEN",
30
+ "PUBLIC_CLONE_AUTH_EFFECTS_TOKEN",
31
+ )
32
+ # The host is site-local; splitting the scheme also keeps clone static audits
33
+ # focused on actual public-origin literals rather than this enforced gateway.
34
+ INTERNAL_HTTP_SCHEME = "http"
35
+ INTERNAL_URL_SEPARATOR = "/"
36
+ DEFAULT_RESEND_INTERNAL_ORIGIN = (
37
+ f"{INTERNAL_HTTP_SCHEME}:{INTERNAL_URL_SEPARATOR}"
38
+ f"{INTERNAL_URL_SEPARATOR}resend.internal"
39
+ )
40
+ MAX_RESPONSE_BYTES = 64 * 1024
41
+ DEFAULT_RETRY_DELAY_SECONDS = 30
42
+
43
+
44
+ class EffectsMailDeliveryError(MailError):
45
+ """A safe, non-provider-specific business-mail delivery failure."""
46
+
47
+
48
+ class _DeliveryFailure(EffectsMailDeliveryError):
49
+ def __init__(self, category: str) -> None:
50
+ super().__init__("business mail delivery was deferred")
51
+ self.category = category
52
+
53
+
54
+ def _safe_internal_endpoint(environment: Mapping[str, str]) -> str:
55
+ raw = str(
56
+ environment.get(RESEND_INTERNAL_ORIGIN_ENV, DEFAULT_RESEND_INTERNAL_ORIGIN)
57
+ ).strip().rstrip("/")
58
+ parsed = urlsplit(raw)
59
+ if (
60
+ parsed.scheme != "http"
61
+ or parsed.hostname != "resend.internal"
62
+ or parsed.username
63
+ or parsed.password
64
+ or parsed.path not in {"", "/"}
65
+ or parsed.query
66
+ or parsed.fragment
67
+ or parsed.port not in {None, 8080}
68
+ ):
69
+ raise EffectsMailDeliveryError(
70
+ "business mail requires the isolated "
71
+ f"{INTERNAL_HTTP_SCHEME}:{INTERNAL_URL_SEPARATOR}"
72
+ f"{INTERNAL_URL_SEPARATOR}resend.internal gateway"
73
+ )
74
+ return f"{parsed.scheme}://{parsed.netloc}/business-emails"
75
+
76
+
77
+ def _effects_token(environment: Mapping[str, str]) -> str:
78
+ for name in EFFECTS_TOKEN_ENVS:
79
+ value = str(environment.get(name, "")).strip()
80
+ if value:
81
+ return value
82
+ return ""
83
+
84
+
85
+ def _response_status(response: Any) -> int:
86
+ value = getattr(response, "status", None)
87
+ if isinstance(value, int):
88
+ return value
89
+ getcode = getattr(response, "getcode", None)
90
+ value = getcode() if callable(getcode) else None
91
+ return value if isinstance(value, int) else 200
92
+
93
+
94
+ def _failure_category(status: int | None) -> str:
95
+ if status in {401, 403}:
96
+ return "provider-auth"
97
+ if status == 429:
98
+ return "provider-rate-limit"
99
+ if status is not None and 400 <= status < 500:
100
+ return "provider-rejected"
101
+ if status is not None and status >= 500:
102
+ return "network"
103
+ return "unknown"
104
+
105
+
106
+ class EffectsMailDelivery:
107
+ """Claim and deliver one business outbox job without exposing a provider key."""
108
+
109
+ def __init__(
110
+ self,
111
+ backend: "SiteBackend",
112
+ *,
113
+ environment: Mapping[str, str] | None = None,
114
+ opener: Callable[..., Any] | None = None,
115
+ retry_delay_seconds: int = DEFAULT_RETRY_DELAY_SECONDS,
116
+ ) -> None:
117
+ if (
118
+ isinstance(retry_delay_seconds, bool)
119
+ or not isinstance(retry_delay_seconds, int)
120
+ or not 0 <= retry_delay_seconds <= 3600
121
+ ):
122
+ raise EffectsMailDeliveryError("business mail retry delay is invalid")
123
+ source = os.environ if environment is None else environment
124
+ self.backend = backend
125
+ self.endpoint = _safe_internal_endpoint(source)
126
+ self.effects_token = _effects_token(source)
127
+ self._opener = urlopen if opener is None else opener
128
+ self.retry_delay_seconds = retry_delay_seconds
129
+
130
+ @staticmethod
131
+ def _idempotency_key(mail_id: str, envelope: Mapping[str, Any]) -> str:
132
+ payload = json.dumps(
133
+ envelope,
134
+ ensure_ascii=True,
135
+ sort_keys=True,
136
+ separators=(",", ":"),
137
+ )
138
+ return hashlib.sha256(
139
+ f"{mail_id}\0{payload}".encode("utf-8")
140
+ ).hexdigest()
141
+
142
+ def _post(self, mail_id: str, envelope: Mapping[str, Any]) -> None:
143
+ body = json.dumps(
144
+ envelope,
145
+ ensure_ascii=True,
146
+ sort_keys=True,
147
+ separators=(",", ":"),
148
+ ).encode("utf-8")
149
+ headers = {
150
+ "Accept": "application/json",
151
+ "Content-Type": "application/json",
152
+ "Idempotency-Key": self._idempotency_key(mail_id, envelope),
153
+ "User-Agent": (
154
+ f"WebsiteBench-{self.backend.config.site_id}-Business-Mail/1.0"
155
+ ),
156
+ }
157
+ if self.effects_token:
158
+ headers["X-WebsiteBench-Effects-Token"] = self.effects_token
159
+ request = Request(self.endpoint, data=body, headers=headers, method="POST")
160
+ try:
161
+ response = self._opener(request, timeout=10)
162
+ try:
163
+ raw = response.read(MAX_RESPONSE_BYTES + 1)
164
+ status = _response_status(response)
165
+ finally:
166
+ close = getattr(response, "close", None)
167
+ if callable(close):
168
+ close()
169
+ except HTTPError as exc:
170
+ raise _DeliveryFailure(_failure_category(exc.code)) from exc
171
+ except (URLError, TimeoutError, OSError) as exc:
172
+ raise _DeliveryFailure("network") from exc
173
+ if status < 200 or status >= 300:
174
+ raise _DeliveryFailure(_failure_category(status))
175
+ if not isinstance(raw, bytes) or len(raw) > MAX_RESPONSE_BYTES:
176
+ raise _DeliveryFailure("unknown")
177
+ try:
178
+ payload = json.loads(raw.decode("utf-8"))
179
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
180
+ raise _DeliveryFailure("unknown") from exc
181
+ if not isinstance(payload, dict) or payload.get("ok") is not True:
182
+ raise _DeliveryFailure("unknown")
183
+
184
+ def deliver(
185
+ self,
186
+ *,
187
+ mail_id: str | None = None,
188
+ now: int | None = None,
189
+ ) -> dict[str, Any] | None:
190
+ """Attempt one due job and preserve a safe retry record on failure.
191
+
192
+ A caller should invoke this only after its own transaction has committed.
193
+ ``None`` means there was no due non-simulation job to deliver.
194
+ """
195
+
196
+ claimed = self.backend.mail.claim_pending(mail_id=mail_id, now=now)
197
+ if claimed is None:
198
+ return None
199
+ claim_token = str(claimed["claim_token"])
200
+ claimed_id = str(claimed["mail_id"])
201
+ try:
202
+ self._post(claimed_id, claimed["delivery"])
203
+ except _DeliveryFailure as exc:
204
+ try:
205
+ self.backend.mail.mark_failed(
206
+ claimed_id,
207
+ claim_token=claim_token,
208
+ category=exc.category,
209
+ retry_delay_seconds=self.retry_delay_seconds,
210
+ now=now,
211
+ )
212
+ except MailError as record_error:
213
+ raise EffectsMailDeliveryError(
214
+ "business mail delivery state could not be recorded"
215
+ ) from record_error
216
+ raise EffectsMailDeliveryError(
217
+ "business mail delivery was deferred"
218
+ ) from exc
219
+ try:
220
+ return self.backend.mail.mark_sent(claimed_id, claim_token=claim_token)
221
+ except MailError as exc:
222
+ # The provider may already have accepted the message. The stable
223
+ # idempotency key makes a later retry safe if recording SENT failed.
224
+ raise EffectsMailDeliveryError(
225
+ "business mail delivery state could not be recorded"
226
+ ) from exc
227
+
228
+
229
+ __all__ = [
230
+ "DEFAULT_RESEND_INTERNAL_ORIGIN",
231
+ "DEFAULT_RETRY_DELAY_SECONDS",
232
+ "EFFECTS_TOKEN_ENVS",
233
+ "EffectsMailDelivery",
234
+ "EffectsMailDeliveryError",
235
+ "RESEND_INTERNAL_ORIGIN_ENV",
236
+ ]
tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/errors.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Errors exposed by the site backend interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class SiteBackendError(RuntimeError):
7
+ """Base error for the site backend deep module."""
8
+
9
+
10
+ class RuntimeContractError(SiteBackendError, ValueError):
11
+ """The frozen backend runtime contract is invalid."""
12
+
13
+
14
+ class SiteBindingError(SiteBackendError):
15
+ """A database or transaction belongs to another site."""
16
+
17
+
18
+ class LifecycleError(SiteBackendError):
19
+ """Database lifecycle work could not be completed safely."""
20
+
21
+
22
+ class MailError(SiteBackendError):
23
+ """A mail purpose, template, or queue transition is invalid."""
24
+
25
+
26
+ class PaymentError(SiteBackendError):
27
+ """A payment transition or caller-supplied payment fact is invalid."""
28
+
29
+
30
+ class PaymentConflict(PaymentError):
31
+ """An idempotency key or active flow conflicts with immutable facts."""
32
+
33
+
34
+ class PaymentRejected(PaymentError):
35
+ """A payment flow is missing, foreign, stale, or not approved."""
tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/mail.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Structured text-only mail rendering and safe business outbox."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import html
7
+ import json
8
+ import re
9
+ import secrets
10
+ import sqlite3
11
+ import time
12
+ from string import Template
13
+ from typing import Any, Mapping
14
+
15
+ from .database import SiteDatabaseLifecycle, utc_now
16
+ from .errors import MailError
17
+ from .runtime import RuntimeConfig
18
+
19
+
20
+ EMAIL_RE = re.compile(r"^[^@\s]{1,128}@[^@\s]{1,190}$")
21
+ IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{8,200}$")
22
+ ERROR_CATEGORIES = frozenset(
23
+ {
24
+ "configuration",
25
+ "provider-auth",
26
+ "provider-rate-limit",
27
+ "provider-rejected",
28
+ "network",
29
+ "unknown",
30
+ }
31
+ )
32
+ MAX_DELIVERY_ATTEMPTS = 3
33
+ CLAIM_TOKEN_RE = re.compile(r"^[A-Za-z0-9_-]{20,200}$")
34
+
35
+
36
+ def _recipient_digest(recipient: str) -> tuple[str, str]:
37
+ if (
38
+ not isinstance(recipient, str)
39
+ or recipient != recipient.strip()
40
+ or len(recipient) > 320
41
+ or not EMAIL_RE.fullmatch(recipient)
42
+ ):
43
+ raise MailError("recipient must be a valid bounded email address")
44
+ normalized = recipient.casefold()
45
+ return normalized, hashlib.sha256(normalized.encode("utf-8")).hexdigest()
46
+
47
+
48
+ def _variables(
49
+ template: Mapping[str, Any], variables: Mapping[str, Any]
50
+ ) -> dict[str, str]:
51
+ if not isinstance(variables, Mapping):
52
+ raise MailError("mail variables must be an object")
53
+ required = list(template["required_variables"])
54
+ if set(variables) != set(required):
55
+ raise MailError("mail variables do not match the frozen template contract")
56
+ normalized: dict[str, str] = {}
57
+ for key in required:
58
+ value = variables[key]
59
+ if not isinstance(value, (str, int)) or isinstance(value, bool):
60
+ raise MailError(f"mail variable {key!r} must be text or integer")
61
+ text = str(value)
62
+ if not text or len(text) > 1000 or "\x00" in text or "\r" in text:
63
+ raise MailError(f"mail variable {key!r} is invalid")
64
+ normalized[key] = text
65
+ return normalized
66
+
67
+
68
+ def _render_field(value: str, variables: Mapping[str, str]) -> str:
69
+ try:
70
+ return Template(value).substitute(variables)
71
+ except (KeyError, ValueError) as exc:
72
+ raise MailError("mail template placeholders are invalid") from exc
73
+
74
+
75
+ class SiteMail:
76
+ """Render branded mail and persist only non-secret template snapshots."""
77
+
78
+ def __init__(self, runtime: RuntimeConfig, lifecycle: SiteDatabaseLifecycle) -> None:
79
+ self.runtime = runtime
80
+ self.lifecycle = lifecycle
81
+
82
+ def _caller_connection(
83
+ self, connection: sqlite3.Connection
84
+ ) -> sqlite3.Connection:
85
+ if (
86
+ not isinstance(connection, sqlite3.Connection)
87
+ or not connection.in_transaction
88
+ ):
89
+ raise MailError(
90
+ "caller-supplied mail connection must have an active transaction"
91
+ )
92
+ self.lifecycle._assert_binding(connection)
93
+ return connection
94
+
95
+ def issue(
96
+ self,
97
+ purpose: str,
98
+ recipient: str,
99
+ variables: Mapping[str, Any],
100
+ ) -> dict[str, Any]:
101
+ templates = self.runtime.mail["purposes"]
102
+ if purpose not in templates:
103
+ raise MailError("mail purpose is not enabled for this site")
104
+ template = templates[purpose]
105
+ normalized_recipient, _ = _recipient_digest(recipient)
106
+ normalized_variables = _variables(template, variables)
107
+ rendered = {
108
+ field: _render_field(template[field], normalized_variables)
109
+ for field in ("subject", "lead", "body", "expiry", "footer")
110
+ }
111
+ text = "\n\n".join(
112
+ rendered[field] for field in ("lead", "body", "expiry", "footer")
113
+ )
114
+ html_body = "".join(
115
+ f"<p>{html.escape(rendered[field])}</p>"
116
+ for field in ("lead", "body", "expiry", "footer")
117
+ )
118
+ return {
119
+ "site_id": self.runtime.site_id,
120
+ "purpose": purpose,
121
+ "template_id": template["template_id"],
122
+ "sender_display_name": self.runtime.mail["sender"]["display_name"],
123
+ "sender_address_env": self.runtime.mail["sender"]["address_env"],
124
+ "recipient": normalized_recipient,
125
+ "subject": rendered["subject"],
126
+ "text": text,
127
+ "html": html_body,
128
+ "contains_secret_variables": bool(template["secret_variables"]),
129
+ }
130
+
131
+ def enqueue(
132
+ self,
133
+ purpose: str,
134
+ recipient: str,
135
+ variables: Mapping[str, Any],
136
+ *,
137
+ idempotency_key: str,
138
+ simulation: bool,
139
+ connection: sqlite3.Connection | None = None,
140
+ ) -> dict[str, Any]:
141
+ templates = self.runtime.mail["purposes"]
142
+ if purpose not in templates:
143
+ raise MailError("mail purpose is not enabled for this site")
144
+ template = templates[purpose]
145
+ normalized_variables = _variables(template, variables)
146
+ if template["secret_variables"]:
147
+ raise MailError(
148
+ "secret-bearing verification mail cannot be persisted; issue a new code after a failed delivery"
149
+ )
150
+ _, recipient_digest = _recipient_digest(recipient)
151
+ if not isinstance(idempotency_key, str) or not IDEMPOTENCY_RE.fullmatch(
152
+ idempotency_key
153
+ ):
154
+ raise MailError("mail idempotency_key is invalid")
155
+ now = utc_now()
156
+ status = "LOCAL_SIMULATION" if simulation else "PENDING"
157
+ mail_id = f"mail_{secrets.token_urlsafe(18)}"
158
+
159
+ def execute(active: sqlite3.Connection) -> dict[str, Any]:
160
+ self.lifecycle._assert_binding(active)
161
+ existing = active.execute(
162
+ "SELECT * FROM websitebench_mail_jobs "
163
+ "WHERE site_id=? AND purpose=? AND idempotency_key=?",
164
+ (self.runtime.site_id, purpose, idempotency_key),
165
+ ).fetchone()
166
+ snapshot = json.dumps(
167
+ normalized_variables,
168
+ ensure_ascii=False,
169
+ sort_keys=True,
170
+ separators=(",", ":"),
171
+ )
172
+ if existing is not None:
173
+ if (
174
+ existing["template_id"] != template["template_id"]
175
+ or existing["recipient_digest"] != recipient_digest
176
+ or existing["variables_json"] != snapshot
177
+ or bool(existing["is_simulation"]) is not simulation
178
+ ):
179
+ raise MailError("mail idempotency key conflicts with immutable facts")
180
+ return self._public_job(existing)
181
+ active.execute(
182
+ "INSERT INTO websitebench_mail_jobs("
183
+ "mail_id,site_id,purpose,template_id,recipient,recipient_digest,"
184
+ "variables_json,"
185
+ "status,is_simulation,idempotency_key,created_at,updated_at"
186
+ ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
187
+ (
188
+ mail_id,
189
+ self.runtime.site_id,
190
+ purpose,
191
+ template["template_id"],
192
+ recipient.casefold(),
193
+ recipient_digest,
194
+ snapshot,
195
+ status,
196
+ int(simulation),
197
+ idempotency_key,
198
+ now,
199
+ now,
200
+ ),
201
+ )
202
+ row = active.execute(
203
+ "SELECT * FROM websitebench_mail_jobs WHERE mail_id=?", (mail_id,)
204
+ ).fetchone()
205
+ return self._public_job(row)
206
+
207
+ if connection is not None:
208
+ return execute(self._caller_connection(connection))
209
+ with self.lifecycle.connection(transaction=True) as active:
210
+ return execute(active)
211
+
212
+ def claim_pending(
213
+ self,
214
+ *,
215
+ mail_id: str | None = None,
216
+ now: int | None = None,
217
+ connection: sqlite3.Connection | None = None,
218
+ ) -> dict[str, Any] | None:
219
+ """Atomically claim one replayable, non-secret mail job."""
220
+
221
+ current_time = int(time.time()) if now is None else now
222
+ if (
223
+ isinstance(current_time, bool)
224
+ or not isinstance(current_time, int)
225
+ or current_time < 0
226
+ ):
227
+ raise MailError("mail claim time is invalid")
228
+ if mail_id is not None and (
229
+ not isinstance(mail_id, str) or not mail_id.startswith("mail_")
230
+ ):
231
+ raise MailError("mail id is invalid")
232
+ claim_token = secrets.token_urlsafe(24)
233
+
234
+ def execute(active: sqlite3.Connection) -> dict[str, Any] | None:
235
+ self.lifecycle._assert_binding(active)
236
+ parameters: list[Any] = [
237
+ self.runtime.site_id,
238
+ current_time,
239
+ MAX_DELIVERY_ATTEMPTS,
240
+ ]
241
+ mail_clause = ""
242
+ if mail_id is not None:
243
+ mail_clause = " AND mail_id=?"
244
+ parameters.append(mail_id)
245
+ row = active.execute(
246
+ "SELECT * FROM websitebench_mail_jobs "
247
+ "WHERE site_id=? AND status='PENDING' AND claim_token IS NULL "
248
+ "AND next_attempt_at<=? AND delivery_attempts<? "
249
+ "AND recipient<>''"
250
+ f"{mail_clause} ORDER BY created_at,mail_id LIMIT 1",
251
+ parameters,
252
+ ).fetchone()
253
+ if row is None:
254
+ return None
255
+ try:
256
+ variables = json.loads(str(row["variables_json"]))
257
+ except (TypeError, json.JSONDecodeError) as exc:
258
+ raise MailError("mail job variables are invalid") from exc
259
+ if not isinstance(variables, Mapping):
260
+ raise MailError("mail job variables are invalid")
261
+ delivery = self._delivery_envelope(row, variables)
262
+ message = self.issue(
263
+ str(row["purpose"]),
264
+ str(row["recipient"]),
265
+ variables,
266
+ )
267
+ changed = active.execute(
268
+ "UPDATE websitebench_mail_jobs SET claim_token=?,claimed_at=?,"
269
+ "delivery_attempts=delivery_attempts+1,updated_at=? "
270
+ "WHERE site_id=? AND mail_id=? AND status='PENDING' "
271
+ "AND claim_token IS NULL AND delivery_attempts=?",
272
+ (
273
+ claim_token,
274
+ current_time,
275
+ utc_now(),
276
+ self.runtime.site_id,
277
+ row["mail_id"],
278
+ row["delivery_attempts"],
279
+ ),
280
+ ).rowcount
281
+ if changed != 1:
282
+ return None
283
+ claimed = active.execute(
284
+ "SELECT * FROM websitebench_mail_jobs WHERE site_id=? AND mail_id=?",
285
+ (self.runtime.site_id, row["mail_id"]),
286
+ ).fetchone()
287
+ return {
288
+ **self._public_job(claimed),
289
+ "claim_token": claim_token,
290
+ # ``message`` is retained for existing local inbox consumers.
291
+ # Effects transports must use the structured ``delivery`` envelope
292
+ # below, never caller-rendered HTML/text.
293
+ "message": message,
294
+ "delivery": delivery,
295
+ }
296
+
297
+ if connection is not None:
298
+ return execute(self._caller_connection(connection))
299
+ with self.lifecycle.connection(transaction=True) as active:
300
+ return execute(active)
301
+
302
+ def _delivery_envelope(
303
+ self,
304
+ row: sqlite3.Row,
305
+ variables: Mapping[str, Any],
306
+ ) -> dict[str, Any]:
307
+ """Return the only payload an effects transport may receive.
308
+
309
+ The outbox is intentionally allowed to retain a non-secret business
310
+ template snapshot, but an effects gateway must independently render
311
+ that snapshot from its frozen runtime. This envelope therefore never
312
+ includes rendered subject, text, HTML, sender credentials, or a
313
+ verification-code purpose.
314
+ """
315
+
316
+ purpose = str(row["purpose"])
317
+ template = self.runtime.mail["purposes"].get(purpose)
318
+ if template is None or str(row["template_id"]) != template["template_id"]:
319
+ raise MailError("mail job template does not match the frozen runtime")
320
+ if template["secret_variables"]:
321
+ raise MailError("secret-bearing mail job cannot use the business outbox")
322
+ recipient, _ = _recipient_digest(str(row["recipient"]))
323
+ return {
324
+ "purpose": purpose,
325
+ "template_id": template["template_id"],
326
+ "recipient": recipient,
327
+ "variables": _variables(template, variables),
328
+ }
329
+
330
+ def mark_sent(
331
+ self,
332
+ mail_id: str,
333
+ *,
334
+ claim_token: str,
335
+ connection: sqlite3.Connection | None = None,
336
+ ) -> dict[str, Any]:
337
+ if not isinstance(claim_token, str) or not CLAIM_TOKEN_RE.fullmatch(
338
+ claim_token
339
+ ):
340
+ raise MailError("mail claim token is invalid")
341
+
342
+ def execute(active: sqlite3.Connection) -> dict[str, Any]:
343
+ self.lifecycle._assert_binding(active)
344
+ changed = active.execute(
345
+ "UPDATE websitebench_mail_jobs SET status='SENT',claim_token=NULL,"
346
+ "claimed_at=NULL,error_category=NULL,sent_at=?,updated_at=? "
347
+ "WHERE site_id=? AND mail_id=? AND status='PENDING' "
348
+ "AND claim_token=?",
349
+ (
350
+ utc_now(),
351
+ utc_now(),
352
+ self.runtime.site_id,
353
+ mail_id,
354
+ claim_token,
355
+ ),
356
+ ).rowcount
357
+ if changed != 1:
358
+ raise MailError("mail job claim is missing or stale")
359
+ row = active.execute(
360
+ "SELECT * FROM websitebench_mail_jobs WHERE mail_id=?", (mail_id,)
361
+ ).fetchone()
362
+ return self._public_job(row)
363
+
364
+ if connection is not None:
365
+ return execute(self._caller_connection(connection))
366
+ with self.lifecycle.connection(transaction=True) as active:
367
+ return execute(active)
368
+
369
+ def mark_failed(
370
+ self,
371
+ mail_id: str,
372
+ *,
373
+ category: str,
374
+ claim_token: str | None = None,
375
+ retry_delay_seconds: int = 0,
376
+ now: int | None = None,
377
+ connection: sqlite3.Connection | None = None,
378
+ ) -> dict[str, Any]:
379
+ if category not in ERROR_CATEGORIES:
380
+ raise MailError("mail failure category is not sanitized")
381
+ if claim_token is not None and not CLAIM_TOKEN_RE.fullmatch(claim_token):
382
+ raise MailError("mail claim token is invalid")
383
+ if (
384
+ isinstance(retry_delay_seconds, bool)
385
+ or not isinstance(retry_delay_seconds, int)
386
+ or not 0 <= retry_delay_seconds <= 3600
387
+ ):
388
+ raise MailError("mail retry delay is invalid")
389
+ current_time = int(time.time()) if now is None else now
390
+ if (
391
+ isinstance(current_time, bool)
392
+ or not isinstance(current_time, int)
393
+ or current_time < 0
394
+ ):
395
+ raise MailError("mail failure time is invalid")
396
+
397
+ def execute(active: sqlite3.Connection) -> dict[str, Any]:
398
+ self.lifecycle._assert_binding(active)
399
+ row = active.execute(
400
+ "SELECT * FROM websitebench_mail_jobs "
401
+ "WHERE site_id=? AND mail_id=? AND status='PENDING'",
402
+ (self.runtime.site_id, mail_id),
403
+ ).fetchone()
404
+ if row is None:
405
+ raise MailError("mail job is missing or not pending")
406
+ if claim_token is None:
407
+ if row["claim_token"] is not None:
408
+ raise MailError("mail job is claimed")
409
+ attempts = int(row["delivery_attempts"]) + 1
410
+ claim_clause = "AND claim_token IS NULL"
411
+ parameters: tuple[Any, ...] = ()
412
+ else:
413
+ if row["claim_token"] != claim_token:
414
+ raise MailError("mail job claim is missing or stale")
415
+ attempts = int(row["delivery_attempts"])
416
+ claim_clause = "AND claim_token=?"
417
+ parameters = (claim_token,)
418
+ status = "FAILED" if attempts >= MAX_DELIVERY_ATTEMPTS else "PENDING"
419
+ changed = active.execute(
420
+ "UPDATE websitebench_mail_jobs SET status=?,error_category=?,"
421
+ "delivery_attempts=?,claim_token=NULL,claimed_at=NULL,"
422
+ "next_attempt_at=?,updated_at=? "
423
+ "WHERE site_id=? AND mail_id=? AND status='PENDING' "
424
+ f"{claim_clause}",
425
+ (
426
+ status,
427
+ category,
428
+ attempts,
429
+ current_time + retry_delay_seconds,
430
+ utc_now(),
431
+ self.runtime.site_id,
432
+ mail_id,
433
+ *parameters,
434
+ ),
435
+ ).rowcount
436
+ if changed != 1:
437
+ raise MailError("mail job is missing or not pending")
438
+ row = active.execute(
439
+ "SELECT * FROM websitebench_mail_jobs WHERE mail_id=?", (mail_id,)
440
+ ).fetchone()
441
+ return self._public_job(row)
442
+
443
+ if connection is not None:
444
+ return execute(self._caller_connection(connection))
445
+ with self.lifecycle.connection(transaction=True) as active:
446
+ return execute(active)
447
+
448
+ def release_stale_claims(
449
+ self,
450
+ *,
451
+ older_than: int,
452
+ now: int | None = None,
453
+ connection: sqlite3.Connection | None = None,
454
+ ) -> int:
455
+ current_time = int(time.time()) if now is None else now
456
+ if (
457
+ isinstance(older_than, bool)
458
+ or not isinstance(older_than, int)
459
+ or older_than < 0
460
+ or isinstance(current_time, bool)
461
+ or not isinstance(current_time, int)
462
+ or current_time < older_than
463
+ ):
464
+ raise MailError("stale claim window is invalid")
465
+
466
+ def execute(active: sqlite3.Connection) -> int:
467
+ self.lifecycle._assert_binding(active)
468
+ return active.execute(
469
+ "UPDATE websitebench_mail_jobs SET "
470
+ "status=CASE WHEN delivery_attempts>=? THEN 'FAILED' ELSE status END,"
471
+ "claim_token=NULL,claimed_at=NULL,error_category='unknown',"
472
+ "next_attempt_at=?,updated_at=? "
473
+ "WHERE site_id=? AND status='PENDING' AND claim_token IS NOT NULL "
474
+ "AND claimed_at<=?",
475
+ (
476
+ MAX_DELIVERY_ATTEMPTS,
477
+ current_time,
478
+ utc_now(),
479
+ self.runtime.site_id,
480
+ older_than,
481
+ ),
482
+ ).rowcount
483
+
484
+ if connection is not None:
485
+ return execute(self._caller_connection(connection))
486
+ with self.lifecycle.connection(transaction=True) as active:
487
+ return execute(active)
488
+
489
+ @staticmethod
490
+ def _public_job(row: sqlite3.Row) -> dict[str, Any]:
491
+ return {
492
+ "mail_id": row["mail_id"],
493
+ "site_id": row["site_id"],
494
+ "purpose": row["purpose"],
495
+ "template_id": row["template_id"],
496
+ "status": row["status"],
497
+ "is_simulation": bool(row["is_simulation"]),
498
+ "delivery_attempts": int(row["delivery_attempts"]),
499
+ "error_category": row["error_category"],
500
+ "claimed": row["claim_token"] is not None,
501
+ "next_attempt_at": int(row["next_attempt_at"]),
502
+ }
tasks/dooney-bourke/environment/reference/clone/websitebench/site_backend/payments.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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 import annotations
4
+
5
+ import json
6
+ import re
7
+ import secrets
8
+ import sqlite3
9
+ from collections.abc import Callable, Mapping
10
+ from typing import Any
11
+
12
+ from .database import SiteDatabaseLifecycle, utc_now
13
+ from .errors import PaymentConflict, PaymentError, PaymentRejected
14
+ from .runtime import CURRENCY_RE, RuntimeConfig
15
+
16
+
17
+ OWNER_RE = re.compile(r"^[A-Za-z0-9._:-]{8,240}$")
18
+ FINGERPRINT_RE = re.compile(r"^[a-f0-9]{64}$")
19
+ IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{8,200}$")
20
+ FLOW_ID_RE = re.compile(r"^payflow_[A-Za-z0-9_-]{12,120}$")
21
+ STRIPE_TEST_SESSION_RE = re.compile(r"^cs_test_[A-Za-z0-9_]{8,240}$")
22
+ StripeTestVerifier = Callable[[str], Mapping[str, Any]]
23
+
24
+
25
+ def _bounded_identity(value: Any, label: str, pattern: re.Pattern[str]) -> str:
26
+ if not isinstance(value, str) or not pattern.fullmatch(value):
27
+ raise PaymentError(f"{label} is invalid")
28
+ return value
29
+
30
+
31
+ def _amount(value: Any) -> int:
32
+ if (
33
+ not isinstance(value, int)
34
+ or isinstance(value, bool)
35
+ or value < 0
36
+ or value > 99_999_999_999
37
+ ):
38
+ raise PaymentError("amount_minor must be a bounded integer")
39
+ return value
40
+
41
+
42
+ class SitePayments:
43
+ """Create, attempt, and atomically consume exact-state approvals."""
44
+
45
+ def __init__(self, runtime: RuntimeConfig, lifecycle: SiteDatabaseLifecycle) -> None:
46
+ self.runtime = runtime
47
+ self.lifecycle = lifecycle
48
+ self._scenarios = {
49
+ item["id"]: item
50
+ for item in runtime.payments["local_sandbox"]["scenarios"]
51
+ }
52
+
53
+ def _facts(
54
+ self, owner: str, amount_minor: int, currency: str, fingerprint: str
55
+ ) -> tuple[str, int, str, str]:
56
+ owner = _bounded_identity(owner, "owner", OWNER_RE)
57
+ amount_minor = _amount(amount_minor)
58
+ if (
59
+ not isinstance(currency, str)
60
+ or not CURRENCY_RE.fullmatch(currency)
61
+ or currency != self.runtime.payments["currency"]
62
+ ):
63
+ raise PaymentError("currency does not match the frozen runtime contract")
64
+ fingerprint = _bounded_identity(
65
+ fingerprint, "fingerprint", FINGERPRINT_RE
66
+ )
67
+ return owner, amount_minor, currency, fingerprint
68
+
69
+ def _event(
70
+ self,
71
+ connection: sqlite3.Connection,
72
+ *,
73
+ flow_id: str,
74
+ attempt_id: str | None,
75
+ event_type: str,
76
+ snapshot: dict[str, Any],
77
+ ) -> None:
78
+ connection.execute(
79
+ "INSERT INTO websitebench_payment_events("
80
+ "event_id,site_id,flow_id,attempt_id,event_type,snapshot_json,created_at"
81
+ ") VALUES (?,?,?,?,?,?,?)",
82
+ (
83
+ f"payevt_{secrets.token_urlsafe(18)}",
84
+ self.runtime.site_id,
85
+ flow_id,
86
+ attempt_id,
87
+ event_type,
88
+ json.dumps(
89
+ snapshot,
90
+ ensure_ascii=False,
91
+ sort_keys=True,
92
+ separators=(",", ":"),
93
+ ),
94
+ utc_now(),
95
+ ),
96
+ )
97
+
98
+ def create_intent(
99
+ self,
100
+ *,
101
+ owner: str,
102
+ amount_minor: int,
103
+ currency: str,
104
+ fingerprint: str,
105
+ idempotency_key: str,
106
+ adapter: str | None = None,
107
+ connection: sqlite3.Connection | None = None,
108
+ ) -> dict[str, Any]:
109
+ if not self.runtime.payments["enabled"]:
110
+ raise PaymentError("payments are not enabled for this site")
111
+ owner, amount_minor, currency, fingerprint = self._facts(
112
+ owner, amount_minor, currency, fingerprint
113
+ )
114
+ idempotency_key = _bounded_identity(
115
+ idempotency_key, "idempotency_key", IDEMPOTENCY_RE
116
+ )
117
+ adapter = adapter or self.runtime.payments["default_adapter"]
118
+ if adapter not in {"local-sandbox", "stripe-test"}:
119
+ raise PaymentError("payment adapter is invalid")
120
+ if adapter == "stripe-test" and self.runtime.payments["stripe_test"] is None:
121
+ raise PaymentError("stripe-test is not configured")
122
+ if connection is not None:
123
+ if not connection.in_transaction:
124
+ raise PaymentError(
125
+ "caller-supplied payment connection must have an active transaction"
126
+ )
127
+ self.lifecycle._assert_binding(connection)
128
+ return self._create_intent(
129
+ connection,
130
+ owner=owner,
131
+ amount_minor=amount_minor,
132
+ currency=currency,
133
+ fingerprint=fingerprint,
134
+ idempotency_key=idempotency_key,
135
+ adapter=adapter,
136
+ )
137
+ with self.lifecycle.connection(transaction=True) as active:
138
+ return self._create_intent(
139
+ active,
140
+ owner=owner,
141
+ amount_minor=amount_minor,
142
+ currency=currency,
143
+ fingerprint=fingerprint,
144
+ idempotency_key=idempotency_key,
145
+ adapter=adapter,
146
+ )
147
+
148
+ def _create_intent(
149
+ self,
150
+ connection: sqlite3.Connection,
151
+ *,
152
+ owner: str,
153
+ amount_minor: int,
154
+ currency: str,
155
+ fingerprint: str,
156
+ idempotency_key: str,
157
+ adapter: str,
158
+ ) -> dict[str, Any]:
159
+ now = utc_now()
160
+ flow_id = f"payflow_{secrets.token_urlsafe(18)}"
161
+ existing = connection.execute(
162
+ "SELECT * FROM websitebench_payment_flows "
163
+ "WHERE site_id=? AND owner=? AND create_idempotency_key=?",
164
+ (self.runtime.site_id, owner, idempotency_key),
165
+ ).fetchone()
166
+ if existing is not None:
167
+ if (
168
+ int(existing["amount_minor"]) != amount_minor
169
+ or existing["currency"] != currency
170
+ or existing["fingerprint"] != fingerprint
171
+ or existing["adapter"] != adapter
172
+ ):
173
+ raise PaymentConflict(
174
+ "payment create idempotency key conflicts with immutable facts"
175
+ )
176
+ return self._public_flow(existing)
177
+ connection.execute(
178
+ "INSERT INTO websitebench_payment_flows("
179
+ "flow_id,site_id,owner,amount_minor,currency,fingerprint,adapter,"
180
+ "status,is_simulation,create_idempotency_key,created_at,updated_at"
181
+ ") VALUES (?,?,?,?,?,?,?,?,1,?,?,?)",
182
+ (
183
+ flow_id,
184
+ self.runtime.site_id,
185
+ owner,
186
+ amount_minor,
187
+ currency,
188
+ fingerprint,
189
+ adapter,
190
+ "OPEN",
191
+ idempotency_key,
192
+ now,
193
+ now,
194
+ ),
195
+ )
196
+ self._event(
197
+ connection,
198
+ flow_id=flow_id,
199
+ attempt_id=None,
200
+ event_type="FLOW_CREATED",
201
+ snapshot={
202
+ "site_id": self.runtime.site_id,
203
+ "owner": owner,
204
+ "amount_minor": amount_minor,
205
+ "currency": currency,
206
+ "fingerprint": fingerprint,
207
+ "adapter": adapter,
208
+ "is_simulation": True,
209
+ },
210
+ )
211
+ row = connection.execute(
212
+ "SELECT * FROM websitebench_payment_flows WHERE flow_id=?", (flow_id,)
213
+ ).fetchone()
214
+ return self._public_flow(row)
215
+
216
+ def attempt(
217
+ self,
218
+ *,
219
+ flow_id: str,
220
+ owner: str,
221
+ amount_minor: int,
222
+ currency: str,
223
+ fingerprint: str,
224
+ scenario_id: str,
225
+ idempotency_key: str,
226
+ connection: sqlite3.Connection | None = None,
227
+ ) -> dict[str, Any]:
228
+ _bounded_identity(flow_id, "flow_id", FLOW_ID_RE)
229
+ owner, amount_minor, currency, fingerprint = self._facts(
230
+ owner, amount_minor, currency, fingerprint
231
+ )
232
+ idempotency_key = _bounded_identity(
233
+ idempotency_key, "idempotency_key", IDEMPOTENCY_RE
234
+ )
235
+ if connection is not None:
236
+ if not connection.in_transaction:
237
+ raise PaymentError(
238
+ "caller-supplied payment connection must have an active transaction"
239
+ )
240
+ self.lifecycle._assert_binding(connection)
241
+ return self._attempt(
242
+ connection,
243
+ flow_id=flow_id,
244
+ owner=owner,
245
+ amount_minor=amount_minor,
246
+ currency=currency,
247
+ fingerprint=fingerprint,
248
+ scenario_id=scenario_id,
249
+ idempotency_key=idempotency_key,
250
+ stripe_snapshot=None,
251
+ )
252
+ with self.lifecycle.connection(transaction=True) as active:
253
+ return self._attempt(
254
+ active,
255
+ flow_id=flow_id,
256
+ owner=owner,
257
+ amount_minor=amount_minor,
258
+ currency=currency,
259
+ fingerprint=fingerprint,
260
+ scenario_id=scenario_id,
261
+ idempotency_key=idempotency_key,
262
+ stripe_snapshot=None,
263
+ )
264
+
265
+ def attempt_verified_stripe(
266
+ self,
267
+ *,
268
+ flow_id: str,
269
+ owner: str,
270
+ amount_minor: int,
271
+ currency: str,
272
+ fingerprint: str,
273
+ provider_session_id: str,
274
+ idempotency_key: str,
275
+ provider_verifier: StripeTestVerifier,
276
+ connection: sqlite3.Connection | None = None,
277
+ ) -> dict[str, Any]:
278
+ """Record a Stripe-test approval only through a server capability.
279
+
280
+ ``provider_verifier`` is deliberately a callable rather than browser
281
+ data. It must retrieve or authenticate the provider Session for the
282
+ opaque id. This module then independently binds the returned snapshot
283
+ to this site, flow, amount, currency, and fingerprint.
284
+ """
285
+
286
+ _bounded_identity(flow_id, "flow_id", FLOW_ID_RE)
287
+ owner, amount_minor, currency, fingerprint = self._facts(
288
+ owner, amount_minor, currency, fingerprint
289
+ )
290
+ idempotency_key = _bounded_identity(
291
+ idempotency_key, "idempotency_key", IDEMPOTENCY_RE
292
+ )
293
+ if (
294
+ not isinstance(provider_session_id, str)
295
+ or STRIPE_TEST_SESSION_RE.fullmatch(provider_session_id) is None
296
+ ):
297
+ raise PaymentRejected(
298
+ "stripe-test requires an opaque test Session id"
299
+ )
300
+ if not callable(provider_verifier):
301
+ raise PaymentRejected(
302
+ "stripe-test requires a server-side provider verifier"
303
+ )
304
+ try:
305
+ stripe_snapshot = provider_verifier(provider_session_id)
306
+ except Exception as exc:
307
+ raise PaymentRejected(
308
+ "stripe-test provider verification failed"
309
+ ) from exc
310
+ if not isinstance(stripe_snapshot, Mapping):
311
+ raise PaymentRejected(
312
+ "stripe-test provider verification returned no Session"
313
+ )
314
+ if connection is not None:
315
+ if not connection.in_transaction:
316
+ raise PaymentError(
317
+ "caller-supplied payment connection must have an active transaction"
318
+ )
319
+ self.lifecycle._assert_binding(connection)
320
+ return self._attempt(
321
+ connection,
322
+ flow_id=flow_id,
323
+ owner=owner,
324
+ amount_minor=amount_minor,
325
+ currency=currency,
326
+ fingerprint=fingerprint,
327
+ scenario_id=provider_session_id,
328
+ idempotency_key=idempotency_key,
329
+ stripe_snapshot=stripe_snapshot,
330
+ )
331
+ with self.lifecycle.connection(transaction=True) as active:
332
+ return self._attempt(
333
+ active,
334
+ flow_id=flow_id,
335
+ owner=owner,
336
+ amount_minor=amount_minor,
337
+ currency=currency,
338
+ fingerprint=fingerprint,
339
+ scenario_id=provider_session_id,
340
+ idempotency_key=idempotency_key,
341
+ stripe_snapshot=stripe_snapshot,
342
+ )
343
+
344
+ def _validate_stripe_snapshot(
345
+ self,
346
+ snapshot: Mapping[str, Any],
347
+ *,
348
+ flow_id: str,
349
+ owner: str,
350
+ amount_minor: int,
351
+ currency: str,
352
+ fingerprint: str,
353
+ provider_session_id: str,
354
+ ) -> None:
355
+ metadata = snapshot.get("metadata")
356
+ if not isinstance(metadata, Mapping):
357
+ raise PaymentRejected("stripe-test Session metadata is unavailable")
358
+ try:
359
+ provider_amount = int(snapshot.get("amount_total"))
360
+ except (TypeError, ValueError) as exc:
361
+ raise PaymentRejected(
362
+ "stripe-test Session amount is unavailable"
363
+ ) from exc
364
+ if (
365
+ snapshot.get("id") != provider_session_id
366
+ or snapshot.get("object") != "checkout.session"
367
+ or snapshot.get("livemode") is not False
368
+ or snapshot.get("status") != "complete"
369
+ or snapshot.get("payment_status") != "paid"
370
+ or snapshot.get("client_reference_id") != flow_id
371
+ or provider_amount != amount_minor
372
+ or str(snapshot.get("currency") or "").upper() != currency
373
+ or str(metadata.get("site_id") or "") != self.runtime.site_id
374
+ or str(metadata.get("flow_id") or "") != flow_id
375
+ or str(metadata.get("owner") or "") != owner
376
+ or str(metadata.get("amount_minor") or "") != str(amount_minor)
377
+ or str(metadata.get("currency") or "").upper() != currency
378
+ or str(metadata.get("fingerprint") or "") != fingerprint
379
+ or str(metadata.get("is_simulation") or "").casefold() != "true"
380
+ ):
381
+ raise PaymentRejected(
382
+ "stripe-test Session does not match immutable payment facts"
383
+ )
384
+
385
+ def _attempt(
386
+ self,
387
+ connection: sqlite3.Connection,
388
+ *,
389
+ flow_id: str,
390
+ owner: str,
391
+ amount_minor: int,
392
+ currency: str,
393
+ fingerprint: str,
394
+ scenario_id: str,
395
+ idempotency_key: str,
396
+ stripe_snapshot: Mapping[str, Any] | None,
397
+ ) -> dict[str, Any]:
398
+ flow = connection.execute(
399
+ "SELECT * FROM websitebench_payment_flows "
400
+ "WHERE site_id=? AND flow_id=? AND owner=?",
401
+ (self.runtime.site_id, flow_id, owner),
402
+ ).fetchone()
403
+ if flow is None:
404
+ raise PaymentRejected("payment flow is missing or foreign")
405
+ adapter = str(flow["adapter"])
406
+ if adapter == "local-sandbox":
407
+ scenario = self._scenarios.get(scenario_id)
408
+ if scenario is None:
409
+ raise PaymentRejected("unknown local payment scenario")
410
+ outcome = {
411
+ "approved": "APPROVED",
412
+ "declined": "DECLINED",
413
+ "retryable": "RETRYABLE",
414
+ }[scenario["outcome"]]
415
+ provider_reference = None
416
+ elif adapter == "stripe-test":
417
+ if (
418
+ self.runtime.payments["stripe_test"] is None
419
+ or not isinstance(scenario_id, str)
420
+ or STRIPE_TEST_SESSION_RE.fullmatch(scenario_id) is None
421
+ ):
422
+ raise PaymentRejected(
423
+ "stripe-test requires an opaque test Session id"
424
+ )
425
+ if stripe_snapshot is None:
426
+ raise PaymentRejected(
427
+ "stripe-test approval requires the provider-verified interface"
428
+ )
429
+ self._validate_stripe_snapshot(
430
+ stripe_snapshot,
431
+ flow_id=flow_id,
432
+ owner=owner,
433
+ amount_minor=amount_minor,
434
+ currency=currency,
435
+ fingerprint=fingerprint,
436
+ provider_session_id=scenario_id,
437
+ )
438
+ outcome = "APPROVED"
439
+ provider_reference = scenario_id
440
+ else:
441
+ raise PaymentRejected("payment flow adapter is unsupported")
442
+ if flow["status"] in {"CONSUMED", "INVALIDATED"}:
443
+ raise PaymentRejected("payment flow is terminal")
444
+ if (
445
+ int(flow["amount_minor"]) != amount_minor
446
+ or flow["currency"] != currency
447
+ or flow["fingerprint"] != fingerprint
448
+ ):
449
+ active = connection.execute(
450
+ "SELECT attempt_id FROM websitebench_payment_attempts "
451
+ "WHERE site_id=? AND flow_id=? AND owner=? "
452
+ "AND status='APPROVED'",
453
+ (self.runtime.site_id, flow_id, owner),
454
+ ).fetchone()
455
+ if flow["status"] == "APPROVED" and active is not None:
456
+ self._persist_final_state_invalidation(
457
+ connection,
458
+ flow_id=flow_id,
459
+ attempt_id=str(active["attempt_id"]),
460
+ owner=owner,
461
+ amount_minor=amount_minor,
462
+ currency=currency,
463
+ fingerprint=fingerprint,
464
+ )
465
+ raise PaymentRejected("payment facts are stale")
466
+ existing = connection.execute(
467
+ "SELECT * FROM websitebench_payment_attempts "
468
+ "WHERE site_id=? AND flow_id=? AND idempotency_key=?",
469
+ (self.runtime.site_id, flow_id, idempotency_key),
470
+ ).fetchone()
471
+ if existing is not None:
472
+ if (
473
+ existing["owner"] != owner
474
+ or int(existing["amount_minor"]) != amount_minor
475
+ or existing["currency"] != currency
476
+ or existing["fingerprint"] != fingerprint
477
+ or existing["scenario_id"] != scenario_id
478
+ ):
479
+ raise PaymentConflict(
480
+ "payment attempt idempotency key conflicts with immutable facts"
481
+ )
482
+ return self._public_attempt(existing)
483
+
484
+ connection.execute(
485
+ "UPDATE websitebench_payment_attempts SET status='SUPERSEDED' "
486
+ "WHERE site_id=? AND flow_id=? AND status='APPROVED'",
487
+ (self.runtime.site_id, flow_id),
488
+ )
489
+ attempt_id = f"payattempt_{secrets.token_urlsafe(18)}"
490
+ now = utc_now()
491
+ connection.execute(
492
+ "INSERT INTO websitebench_payment_attempts("
493
+ "attempt_id,site_id,flow_id,owner,scenario_id,amount_minor,currency,"
494
+ "fingerprint,status,idempotency_key,provider_reference,"
495
+ "is_simulation,created_at"
496
+ ") VALUES (?,?,?,?,?,?,?,?,?,?,?,1,?)",
497
+ (
498
+ attempt_id,
499
+ self.runtime.site_id,
500
+ flow_id,
501
+ owner,
502
+ scenario_id,
503
+ amount_minor,
504
+ currency,
505
+ fingerprint,
506
+ outcome,
507
+ idempotency_key,
508
+ provider_reference,
509
+ now,
510
+ ),
511
+ )
512
+ connection.execute(
513
+ "UPDATE websitebench_payment_flows SET status=?,updated_at=? "
514
+ "WHERE flow_id=?",
515
+ ("APPROVED" if outcome == "APPROVED" else "OPEN", now, flow_id),
516
+ )
517
+ self._event(
518
+ connection,
519
+ flow_id=flow_id,
520
+ attempt_id=attempt_id,
521
+ event_type=f"ATTEMPT_{outcome}",
522
+ snapshot={
523
+ "site_id": self.runtime.site_id,
524
+ "owner": owner,
525
+ "amount_minor": amount_minor,
526
+ "currency": currency,
527
+ "fingerprint": fingerprint,
528
+ "scenario_id": scenario_id,
529
+ "is_simulation": True,
530
+ },
531
+ )
532
+ row = connection.execute(
533
+ "SELECT * FROM websitebench_payment_attempts WHERE attempt_id=?",
534
+ (attempt_id,),
535
+ ).fetchone()
536
+ return self._public_attempt(row)
537
+
538
+ def consume_approval(
539
+ self,
540
+ connection: sqlite3.Connection,
541
+ *,
542
+ flow_id: str,
543
+ owner: str,
544
+ amount_minor: int,
545
+ currency: str,
546
+ fingerprint: str,
547
+ ) -> dict[str, Any]:
548
+ if not isinstance(connection, sqlite3.Connection) or not connection.in_transaction:
549
+ raise PaymentError(
550
+ "consume_approval requires the caller's active SQLite transaction"
551
+ )
552
+ return self._consume_approval_locked(
553
+ connection,
554
+ flow_id=flow_id,
555
+ owner=owner,
556
+ amount_minor=amount_minor,
557
+ currency=currency,
558
+ fingerprint=fingerprint,
559
+ )
560
+
561
+ def _consume_approval_locked(
562
+ self,
563
+ connection: sqlite3.Connection,
564
+ *,
565
+ flow_id: str,
566
+ owner: str,
567
+ amount_minor: int,
568
+ currency: str,
569
+ fingerprint: str,
570
+ ) -> dict[str, Any]:
571
+ if not isinstance(connection, sqlite3.Connection) or not connection.in_transaction:
572
+ raise PaymentError(
573
+ "consume_approval requires the caller's active SQLite transaction"
574
+ )
575
+ self.lifecycle._assert_binding(connection)
576
+ _bounded_identity(flow_id, "flow_id", FLOW_ID_RE)
577
+ owner, amount_minor, currency, fingerprint = self._facts(
578
+ owner, amount_minor, currency, fingerprint
579
+ )
580
+ flow = connection.execute(
581
+ "SELECT * FROM websitebench_payment_flows "
582
+ "WHERE site_id=? AND flow_id=? AND owner=?",
583
+ (self.runtime.site_id, flow_id, owner),
584
+ ).fetchone()
585
+ if flow is None or flow["status"] != "APPROVED":
586
+ raise PaymentRejected("active approval is missing or foreign")
587
+ attempt = connection.execute(
588
+ "SELECT * FROM websitebench_payment_attempts "
589
+ "WHERE site_id=? AND flow_id=? AND owner=? AND status='APPROVED'",
590
+ (self.runtime.site_id, flow_id, owner),
591
+ ).fetchone()
592
+ if attempt is None:
593
+ raise PaymentRejected("active approval is missing")
594
+ for row in (flow, attempt):
595
+ if (
596
+ int(row["amount_minor"]) != amount_minor
597
+ or row["currency"] != currency
598
+ or row["fingerprint"] != fingerprint
599
+ ):
600
+ self._persist_final_state_invalidation(
601
+ connection,
602
+ flow_id=flow_id,
603
+ attempt_id=str(attempt["attempt_id"]),
604
+ owner=owner,
605
+ amount_minor=amount_minor,
606
+ currency=currency,
607
+ fingerprint=fingerprint,
608
+ )
609
+ raise PaymentRejected("approval does not match the final state")
610
+ now = utc_now()
611
+ changed = connection.execute(
612
+ "UPDATE websitebench_payment_attempts SET status='CONSUMED',consumed_at=? "
613
+ "WHERE attempt_id=? AND status='APPROVED'",
614
+ (now, attempt["attempt_id"]),
615
+ ).rowcount
616
+ if changed != 1:
617
+ raise PaymentRejected("approval was already consumed")
618
+ connection.execute(
619
+ "UPDATE websitebench_payment_flows SET status='CONSUMED',updated_at=? "
620
+ "WHERE flow_id=? AND status='APPROVED'",
621
+ (now, flow_id),
622
+ )
623
+ snapshot = {
624
+ "site_id": self.runtime.site_id,
625
+ "flow_id": flow_id,
626
+ "attempt_id": attempt["attempt_id"],
627
+ "owner": owner,
628
+ "amount_minor": amount_minor,
629
+ "currency": currency,
630
+ "fingerprint": fingerprint,
631
+ "is_simulation": True,
632
+ }
633
+ self._event(
634
+ connection,
635
+ flow_id=flow_id,
636
+ attempt_id=attempt["attempt_id"],
637
+ event_type="APPROVAL_CONSUMED",
638
+ snapshot=snapshot,
639
+ )
640
+ return snapshot
641
+
642
+ def _persist_final_state_invalidation(
643
+ self,
644
+ connection: sqlite3.Connection,
645
+ *,
646
+ flow_id: str,
647
+ attempt_id: str,
648
+ owner: str,
649
+ amount_minor: int,
650
+ currency: str,
651
+ fingerprint: str,
652
+ ) -> None:
653
+ """Commit a terminal invalidation without a claimable transaction gap.
654
+
655
+ This is why callers must consume/validate the approval before making
656
+ any business mutation in the transaction. The valid path stays in the
657
+ caller transaction so the subsequent order write is atomic with the
658
+ consume. The stale path commits only payment-state invalidation before
659
+ releasing SQLite's write lock, then restores an empty transaction for
660
+ the caller before raising ``PaymentRejected``.
661
+ """
662
+
663
+ try:
664
+ self.lifecycle._assert_binding(connection)
665
+ flow = connection.execute(
666
+ "SELECT status FROM websitebench_payment_flows "
667
+ "WHERE site_id=? AND flow_id=? AND owner=?",
668
+ (self.runtime.site_id, flow_id, owner),
669
+ ).fetchone()
670
+ attempt = connection.execute(
671
+ "SELECT status FROM websitebench_payment_attempts "
672
+ "WHERE site_id=? AND attempt_id=? AND flow_id=? AND owner=?",
673
+ (self.runtime.site_id, attempt_id, flow_id, owner),
674
+ ).fetchone()
675
+ if (
676
+ flow is not None
677
+ and flow["status"] == "APPROVED"
678
+ and attempt is not None
679
+ and attempt["status"] == "APPROVED"
680
+ ):
681
+ now = utc_now()
682
+ connection.execute(
683
+ "UPDATE websitebench_payment_attempts SET status='SUPERSEDED' "
684
+ "WHERE attempt_id=? AND status='APPROVED'",
685
+ (attempt_id,),
686
+ )
687
+ connection.execute(
688
+ "UPDATE websitebench_payment_flows "
689
+ "SET status='INVALIDATED',updated_at=? "
690
+ "WHERE flow_id=? AND status='APPROVED'",
691
+ (now, flow_id),
692
+ )
693
+ self._event(
694
+ connection,
695
+ flow_id=flow_id,
696
+ attempt_id=attempt_id,
697
+ event_type="APPROVAL_INVALIDATED_FINAL_STATE",
698
+ snapshot={
699
+ "site_id": self.runtime.site_id,
700
+ "owner": owner,
701
+ "amount_minor": amount_minor,
702
+ "currency": currency,
703
+ "fingerprint": fingerprint,
704
+ "reason": "approval-does-not-match-final-state",
705
+ "is_simulation": True,
706
+ },
707
+ )
708
+ connection.execute("COMMIT")
709
+ # Restore the caller's transaction contract. The surrounding
710
+ # context can now catch or propagate PaymentRejected without
711
+ # unexpectedly continuing in autocommit mode.
712
+ connection.execute("BEGIN IMMEDIATE")
713
+ except Exception:
714
+ if connection.in_transaction:
715
+ connection.execute("ROLLBACK")
716
+ raise
717
+
718
+ @staticmethod
719
+ def _public_flow(row: sqlite3.Row) -> dict[str, Any]:
720
+ return {
721
+ "flow_id": row["flow_id"],
722
+ "site_id": row["site_id"],
723
+ "owner": row["owner"],
724
+ "amount_minor": int(row["amount_minor"]),
725
+ "currency": row["currency"],
726
+ "fingerprint": row["fingerprint"],
727
+ "adapter": row["adapter"],
728
+ "status": row["status"],
729
+ "is_simulation": bool(row["is_simulation"]),
730
+ }
731
+
732
+ @staticmethod
733
+ def _public_attempt(row: sqlite3.Row) -> dict[str, Any]:
734
+ return {
735
+ "attempt_id": row["attempt_id"],
736
+ "site_id": row["site_id"],
737
+ "flow_id": row["flow_id"],
738
+ "owner": row["owner"],
739
+ "scenario_id": row["scenario_id"],
740
+ "amount_minor": int(row["amount_minor"]),
741
+ "currency": row["currency"],
742
+ "fingerprint": row["fingerprint"],
743
+ "status": row["status"],
744
+ "is_simulation": bool(row["is_simulation"]),
745
+ }