AgPerry commited on
Commit
a673e5e
·
verified ·
1 Parent(s): 9eee17e

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/aspca-pet-insurance/environment/agent-browser/browser-use +152 -0
  2. tasks/aspca-pet-insurance/environment/agent-browser/gateway.py +524 -0
  3. tasks/aspca-pet-insurance/environment/candidate-abi/websitebench-candidate-preflight +5 -0
  4. tasks/aspca-pet-insurance/environment/mailbox/Dockerfile +5 -0
  5. tasks/aspca-pet-insurance/environment/mailbox/mailbox.py +2433 -0
  6. tasks/aspca-pet-insurance/environment/reference/.websitebench-reference-tls/ca.crt +20 -0
  7. tasks/aspca-pet-insurance/environment/reference/.websitebench-reference-tls/reference.crt +20 -0
  8. tasks/aspca-pet-insurance/environment/reference/.websitebench-reference-tls/reference.key +28 -0
  9. tasks/aspca-pet-insurance/environment/reference/.websitebench-reference-tls/tls_proxy.py +164 -0
  10. tasks/aspca-pet-insurance/environment/reference/Dockerfile +19 -0
  11. tasks/aspca-pet-insurance/environment/reference/backend/model.json +379 -0
  12. tasks/aspca-pet-insurance/environment/reference/backend/runtime.json +92 -0
  13. tasks/aspca-pet-insurance/environment/reference/clone/app.py +536 -0
  14. tasks/aspca-pet-insurance/environment/reference/clone/backend/model.json +87 -0
  15. tasks/aspca-pet-insurance/environment/reference/clone/backend/quotes_db.py +756 -0
  16. tasks/aspca-pet-insurance/environment/reference/clone/backend/rating.py +144 -0
  17. tasks/aspca-pet-insurance/environment/reference/clone/backend/site_backend_integration.py +151 -0
  18. tasks/aspca-pet-insurance/environment/reference/clone/frontend/css-localize-report.json +257 -0
  19. tasks/aspca-pet-insurance/environment/reference/clone/frontend/rewrite-report.json +336 -0
  20. tasks/aspca-pet-insurance/environment/reference/clone/requirements.txt +2 -0
  21. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ads.nextdoor.com/public/pixel/ndp.js +2 -0
  22. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ads.nextdoor.com/v2/public/pixel/advmtch.js +2 -0
  23. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/cdn.mgln.ai/pixel.min.js +1 -0
  24. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ce.lijit.com/merge.q689bace5c5 +0 -0
  25. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/container.pepperjam.com/4193671694.js +3 -0
  26. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/d2hrivdxn8ekm8.cloudfront.net/tracker-latest.min.js +1 -0
  27. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q1d0a579494 +0 -0
  28. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q31e33274de +0 -0
  29. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q39d62ad71e +0 -0
  30. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q3ebd6b9491 +0 -0
  31. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q406aaf3c58 +0 -0
  32. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q51ef9d3e1e +0 -0
  33. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q5f64c5b90c +0 -0
  34. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q6fbfd7956c +0 -0
  35. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q93290827dc +0 -0
  36. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q942355de3f +0 -0
  37. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q9b23dd9b5e +0 -0
  38. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qa47cb055e1 +0 -0
  39. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qacc43b957d +0 -0
  40. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qb0b586dc36 +0 -0
  41. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qb34c55c17d +0 -0
  42. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qb6c1d17059 +0 -0
  43. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qcf75156b0d +0 -0
  44. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qe0a2cabe33 +0 -0
  45. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qe0e6e86a5e +0 -0
  46. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qeab56a9406 +0 -0
  47. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/idsync.rlcdn.com/449076.q1c22464946.gif +3 -0
  48. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/idsync.rlcdn.com/449076.q8e3626aa86.gif +3 -0
  49. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/load.server.aspcapetinsurance.com/2mkgflfjkuo.q74166a008d.js +0 -0
  50. tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/mgln.ai/init +0 -0
tasks/aspca-pet-insurance/environment/agent-browser/browser-use ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Forward the safe Browser Use CLI subset to the isolated browser sidecar."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ import shutil
9
+ import sys
10
+ import urllib.error
11
+ import urllib.request
12
+ import uuid
13
+ from pathlib import Path
14
+
15
+
16
+ GATEWAY_URL = os.environ.get(
17
+ "WEBSITEBENCH_BROWSER_GATEWAY_URL",
18
+ "http://browser:9224/v1/command",
19
+ )
20
+ SHARED_ROOT = Path("/browser-share")
21
+
22
+
23
+ def _translate_candidate_origin(arguments: list[str]) -> list[str]:
24
+ public_origin = os.environ.get(
25
+ "WEBSITEBENCH_CANDIDATE_URL", "http://127.0.0.1:3000"
26
+ ).rstrip("/")
27
+ browser_origin = os.environ.get(
28
+ "WEBSITEBENCH_BROWSER_CANDIDATE_URL", "http://candidate:3000"
29
+ ).rstrip("/")
30
+ return [
31
+ browser_origin + value[len(public_origin) :]
32
+ if value == public_origin or value.startswith(public_origin + "/")
33
+ else value
34
+ for value in arguments
35
+ ]
36
+
37
+
38
+ def _command_index(arguments: list[str]) -> int | None:
39
+ index = 0
40
+ while index < len(arguments):
41
+ value = arguments[index]
42
+ if value in {"--session"}:
43
+ index += 2
44
+ continue
45
+ if value.startswith("--session=") or value == "--json":
46
+ index += 1
47
+ continue
48
+ if value in {"-h", "--help"}:
49
+ return None
50
+ if value.startswith("-"):
51
+ return index
52
+ return index
53
+ return None
54
+
55
+
56
+ def _prepare_screenshot(arguments: list[str]) -> tuple[list[str], Path | None, Path | None]:
57
+ forwarded = list(arguments)
58
+ command_index = _command_index(forwarded)
59
+ if command_index is None or forwarded[command_index] != "screenshot":
60
+ return forwarded, None, None
61
+
62
+ local_path: Path | None = None
63
+ path_index: int | None = None
64
+ for index in range(command_index + 1, len(forwarded)):
65
+ if forwarded[index] == "--path" and index + 1 < len(forwarded):
66
+ path_index = index + 1
67
+ local_path = Path(forwarded[path_index])
68
+ break
69
+ if not forwarded[index].startswith("-"):
70
+ path_index = index
71
+ local_path = Path(forwarded[path_index])
72
+ break
73
+ if local_path is None:
74
+ local_path = Path("screenshot.png")
75
+ forwarded.append(str(local_path))
76
+ path_index = len(forwarded) - 1
77
+
78
+ shared_path = SHARED_ROOT / f"screenshot-{uuid.uuid4().hex}.png"
79
+ assert path_index is not None
80
+ forwarded[path_index] = str(shared_path)
81
+ return forwarded, local_path, shared_path
82
+
83
+
84
+ def _prepare_asset(arguments: list[str]) -> tuple[list[str], Path | None, Path | None]:
85
+ forwarded = list(arguments)
86
+ command_index = _command_index(forwarded)
87
+ if command_index is None or forwarded[command_index] != "save-asset":
88
+ return forwarded, None, None
89
+ tail = forwarded[command_index + 1 :]
90
+ if len(tail) != 2:
91
+ # Let the gateway reject the malformed command with its own message.
92
+ return forwarded, None, None
93
+ local_path = Path(tail[1])
94
+ shared_path = SHARED_ROOT / f"asset-{uuid.uuid4().hex}"
95
+ forwarded[command_index + 2] = str(shared_path)
96
+ return forwarded, local_path, shared_path
97
+
98
+
99
+ def main() -> int:
100
+ translated = _translate_candidate_origin(sys.argv[1:])
101
+ arguments, local_screenshot, shared_screenshot = _prepare_screenshot(translated)
102
+ if local_screenshot is None:
103
+ arguments, local_screenshot, shared_screenshot = _prepare_asset(arguments)
104
+ request = urllib.request.Request(
105
+ GATEWAY_URL,
106
+ data=json.dumps({"argv": arguments}, separators=(",", ":")).encode("utf-8"),
107
+ headers={"Content-Type": "application/json"},
108
+ method="POST",
109
+ )
110
+ try:
111
+ with urllib.request.urlopen(request, timeout=240) as response:
112
+ payload = json.load(response)
113
+ except urllib.error.HTTPError as exc:
114
+ try:
115
+ detail = json.loads(exc.read().decode("utf-8")).get("error")
116
+ except (UnicodeError, ValueError, AttributeError):
117
+ detail = None
118
+ print(detail or f"Browser Use gateway refused the command (HTTP {exc.code})", file=sys.stderr)
119
+ return 2
120
+ except (OSError, UnicodeError, ValueError) as exc:
121
+ print(f"Browser Use gateway unavailable: {exc}", file=sys.stderr)
122
+ return 2
123
+
124
+ stdout = payload.get("stdout", "")
125
+ stderr = payload.get("stderr", "")
126
+ if local_screenshot is not None and shared_screenshot is not None:
127
+ # The shared file is moved to the caller's path below; report that path, not the
128
+ # transient gateway-owned one, so a later read of the printed path succeeds.
129
+ if isinstance(stdout, str):
130
+ stdout = stdout.replace(str(shared_screenshot), str(local_screenshot))
131
+ if isinstance(stderr, str):
132
+ stderr = stderr.replace(str(shared_screenshot), str(local_screenshot))
133
+ if isinstance(stdout, str) and stdout:
134
+ print(stdout, end="" if stdout.endswith("\n") else "\n")
135
+ if isinstance(stderr, str) and stderr:
136
+ print(stderr, end="" if stderr.endswith("\n") else "\n", file=sys.stderr)
137
+
138
+ if local_screenshot is not None and shared_screenshot is not None and shared_screenshot.exists():
139
+ try:
140
+ local_screenshot.parent.mkdir(parents=True, exist_ok=True)
141
+ shutil.copyfile(shared_screenshot, local_screenshot)
142
+ shared_screenshot.unlink(missing_ok=True)
143
+ except OSError as exc:
144
+ print(f"Browser file transfer failed: {exc}", file=sys.stderr)
145
+ return 2
146
+
147
+ exit_code = payload.get("exit_code", 2)
148
+ return exit_code if isinstance(exit_code, int) and 0 <= exit_code <= 255 else 2
149
+
150
+
151
+ if __name__ == "__main__":
152
+ raise SystemExit(main())
tasks/aspca-pet-insurance/environment/agent-browser/gateway.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Constrained Browser Use command gateway for browser-only references.
3
+
4
+ The gateway is the only process that joins the reference network. It exposes
5
+ interactive browser actions, but deliberately excludes arbitrary Python,
6
+ JavaScript evaluation, DOM serialization, cloud/tunnel commands, and direct
7
+ CDP attachment. The Agent container can inspect the rendered site without
8
+ obtaining a general-purpose HTTP path to its source responses.
9
+
10
+ Static assets are the one exception to that boundary. ``assets`` lists the
11
+ reference-origin images, icons, fonts and media the current page uses, and
12
+ ``save-asset`` copies one of them into the Agent's repository. Stylesheets and
13
+ scripts are the reference's code: formal runs never hand them to the Agent, so
14
+ both commands refuse them, as they refuse documents and API responses.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import re
22
+ import ssl
23
+ import subprocess
24
+ import threading
25
+ import urllib.error
26
+ import urllib.parse
27
+ import urllib.request
28
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+
33
+ MAX_REQUEST_BYTES = 64 * 1024
34
+ MAX_OUTPUT_BYTES = 4 * 1024 * 1024
35
+ COMMAND_TIMEOUT_SEC = 180
36
+ SESSION_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\Z")
37
+ SHARED_ROOT = Path("/browser-share").resolve()
38
+ ASSET_MAX_BYTES = 32 * 1024 * 1024
39
+ ASSET_TIMEOUT_SEC = 60
40
+ ASSET_LIST_LIMIT = 2000
41
+ ASSET_SHARED_NAME = re.compile(r"asset-[0-9a-f]{32}\Z")
42
+ # Static media only: a document, JSON or other API body is never an asset, and neither is
43
+ # a stylesheet or script (the agent must not receive the reference's CSS or JavaScript).
44
+ STATIC_CONTENT_PREFIXES = ("image/", "font/", "audio/", "video/")
45
+ STATIC_CONTENT_TYPES = frozenset(
46
+ {
47
+ "application/font-woff",
48
+ "application/font-woff2",
49
+ "application/x-font-woff",
50
+ "application/x-font-ttf",
51
+ "application/x-font-otf",
52
+ "application/font-sfnt",
53
+ "application/vnd.ms-fontobject",
54
+ }
55
+ )
56
+ # Servers often label fonts and media application/octet-stream; accept that
57
+ # label only when the path itself names a static file.
58
+ STATIC_EXTENSIONS = frozenset(
59
+ {
60
+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".ico", ".bmp",
61
+ ".woff", ".woff2", ".ttf", ".otf", ".eot",
62
+ ".mp4", ".webm", ".ogv", ".mp3", ".ogg", ".wav", ".m4a",
63
+ }
64
+ )
65
+ # Reference code is refused whatever its declared type: a script served as octet-stream or a
66
+ # stylesheet under an image-like path must not pass.
67
+ CODE_CONTENT_TYPES = frozenset(
68
+ {
69
+ "text/css",
70
+ "text/javascript",
71
+ "text/ecmascript",
72
+ "application/javascript",
73
+ "application/x-javascript",
74
+ "application/ecmascript",
75
+ "application/wasm",
76
+ }
77
+ )
78
+ CODE_EXTENSIONS = frozenset({".css", ".scss", ".less", ".js", ".mjs", ".cjs", ".jsx", ".ts", ".tsx", ".map", ".wasm"})
79
+ # Gateway-owned inventory script: returns only URLs the page references or loaded.
80
+ ASSET_INVENTORY_JS = r"""JSON.stringify((() => {
81
+ const found = new Set();
82
+ const add = (value, base) => { try { if (value) found.add(new URL(value, base || location.href).href); } catch (e) {} };
83
+ const urls = (text, base) => { for (const m of String(text || '').matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/g)) add(m[1], base); };
84
+ for (const entry of performance.getEntriesByType('resource')) add(entry.name);
85
+ for (const image of document.images) { add(image.currentSrc); add(image.src); }
86
+ for (const node of document.querySelectorAll('link[href]')) add(node.href);
87
+ for (const node of document.querySelectorAll('script[src]')) add(node.src);
88
+ for (const node of document.querySelectorAll('source[src], source[srcset], video[src], video[poster], audio[src], img[srcset]')) {
89
+ add(node.src); add(node.poster);
90
+ for (const part of String(node.srcset || '').split(',')) add(part.trim().split(/\s+/)[0]);
91
+ }
92
+ let count = 0;
93
+ for (const element of document.querySelectorAll('*')) {
94
+ if (++count > 5000) break;
95
+ const style = getComputedStyle(element);
96
+ urls(style.backgroundImage); urls(style.listStyleImage); urls(style.content);
97
+ }
98
+ for (const sheet of document.styleSheets) {
99
+ try { for (const rule of sheet.cssRules) urls(rule.cssText, sheet.href || location.href); } catch (e) {}
100
+ }
101
+ return [...found];
102
+ })())"""
103
+ REAL_BROWSER_USE = os.environ.get(
104
+ "WEBSITEBENCH_BROWSER_USE_REAL",
105
+ "/usr/local/bin/browser-use-real",
106
+ )
107
+ SAFE_COMMANDS = frozenset(
108
+ {
109
+ "open",
110
+ "click",
111
+ "type",
112
+ "input",
113
+ "scroll",
114
+ "back",
115
+ "screenshot",
116
+ "state",
117
+ "switch",
118
+ "close-tab",
119
+ "keys",
120
+ "select",
121
+ "hover",
122
+ "dblclick",
123
+ "rightclick",
124
+ "cookies",
125
+ "close",
126
+ "sessions",
127
+ }
128
+ )
129
+ FORBIDDEN_COMMANDS = frozenset(
130
+ {
131
+ "install",
132
+ "init",
133
+ "setup",
134
+ "doctor",
135
+ "upload",
136
+ "eval",
137
+ "extract",
138
+ "get",
139
+ "python",
140
+ "tunnel",
141
+ "cloud",
142
+ "profile",
143
+ "wait",
144
+ }
145
+ )
146
+ FORBIDDEN_GLOBAL_OPTIONS = frozenset(
147
+ {"--headed", "--profile", "--cdp-url", "--connect", "--mcp", "--template"}
148
+ )
149
+
150
+
151
+ class CommandRejected(ValueError):
152
+ """Raised when an Agent command crosses the browser-only boundary."""
153
+
154
+
155
+ def _origin(value: str) -> tuple[str, str, int]:
156
+ parsed = urllib.parse.urlsplit(value)
157
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
158
+ raise ValueError(f"invalid browser origin: {value!r}")
159
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
160
+ return parsed.scheme, parsed.hostname.lower(), port
161
+
162
+
163
+ def allowed_origins() -> frozenset[tuple[str, str, int]]:
164
+ values = (
165
+ os.environ.get(
166
+ "WEBSITEBENCH_BROWSER_REFERENCE_URL", "https://reference:8080"
167
+ ),
168
+ os.environ.get(
169
+ "WEBSITEBENCH_BROWSER_CANDIDATE_URL", "http://candidate:3000"
170
+ ),
171
+ os.environ.get(
172
+ "WEBSITEBENCH_BROWSER_MAILBOX_URL", "http://mailbox:8026"
173
+ ),
174
+ )
175
+ return frozenset(_origin(value) for value in values)
176
+
177
+
178
+ def reference_origin() -> tuple[str, str, int]:
179
+ return _origin(
180
+ os.environ.get("WEBSITEBENCH_BROWSER_REFERENCE_URL", "https://reference:8080")
181
+ )
182
+
183
+
184
+ def _reference_asset_url(value: str) -> str:
185
+ try:
186
+ requested = _origin(value)
187
+ except (TypeError, ValueError) as exc:
188
+ raise CommandRejected(str(exc)) from exc
189
+ if requested != reference_origin():
190
+ raise CommandRejected("static assets can only be saved from the reference origin")
191
+ parsed = urllib.parse.urlsplit(value)
192
+ if parsed.username is not None or parsed.password is not None:
193
+ raise CommandRejected("asset URL must not carry credentials")
194
+ return urllib.parse.urlunsplit(parsed._replace(fragment=""))
195
+
196
+
197
+ def is_reference_code(url: str, content_type: str = "") -> bool:
198
+ media = content_type.split(";", 1)[0].strip().lower()
199
+ suffix = Path(urllib.parse.urlsplit(url).path).suffix.lower()
200
+ return media in CODE_CONTENT_TYPES or suffix in CODE_EXTENSIONS
201
+
202
+
203
+ def is_static_asset(url: str, content_type: str) -> bool:
204
+ if is_reference_code(url, content_type):
205
+ return False
206
+ media = content_type.split(";", 1)[0].strip().lower()
207
+ if media.startswith(STATIC_CONTENT_PREFIXES) or media in STATIC_CONTENT_TYPES:
208
+ return True
209
+ suffix = Path(urllib.parse.urlsplit(url).path).suffix.lower()
210
+ return media in {"application/octet-stream", "binary/octet-stream", ""} and suffix in STATIC_EXTENSIONS
211
+
212
+
213
+ def _parse_global_options(arguments: list[str]) -> tuple[str, int]:
214
+ session = "default"
215
+ index = 0
216
+ while index < len(arguments):
217
+ value = arguments[index]
218
+ if value == "--session":
219
+ if index + 1 >= len(arguments):
220
+ raise CommandRejected("--session requires a value")
221
+ session = arguments[index + 1]
222
+ index += 2
223
+ continue
224
+ if value.startswith("--session="):
225
+ session = value.partition("=")[2]
226
+ index += 1
227
+ continue
228
+ if value == "--json":
229
+ index += 1
230
+ continue
231
+ if value in {"-h", "--help"}:
232
+ break
233
+ if value in FORBIDDEN_GLOBAL_OPTIONS or any(
234
+ value.startswith(option + "=") for option in FORBIDDEN_GLOBAL_OPTIONS
235
+ ):
236
+ raise CommandRejected(f"Browser Use option {value!r} is disabled")
237
+ if value.startswith("-"):
238
+ raise CommandRejected(f"unsupported Browser Use option {value!r}")
239
+ break
240
+ if not SESSION_PATTERN.fullmatch(session):
241
+ raise CommandRejected("invalid Browser Use session name")
242
+ return session, index
243
+
244
+
245
+ def validate_command(raw_arguments: Any) -> list[str]:
246
+ if not isinstance(raw_arguments, list) or not raw_arguments:
247
+ raise CommandRejected("argv must be a non-empty string array")
248
+ if len(raw_arguments) > 128:
249
+ raise CommandRejected("too many Browser Use arguments")
250
+ arguments: list[str] = []
251
+ for value in raw_arguments:
252
+ if not isinstance(value, str) or "\x00" in value or len(value) > 16_384:
253
+ raise CommandRejected("invalid Browser Use argument")
254
+ arguments.append(value)
255
+
256
+ for value in arguments:
257
+ if value in FORBIDDEN_GLOBAL_OPTIONS or any(
258
+ value.startswith(option + "=") for option in FORBIDDEN_GLOBAL_OPTIONS
259
+ ):
260
+ raise CommandRejected(f"Browser Use option {value!r} is disabled")
261
+
262
+ _session, command_index = _parse_global_options(arguments)
263
+ if (
264
+ command_index == len(arguments) - 1
265
+ and arguments[command_index] in {"-h", "--help"}
266
+ ):
267
+ return arguments
268
+ if command_index >= len(arguments):
269
+ raise CommandRejected("missing Browser Use command")
270
+ command = arguments[command_index]
271
+ if command == "assets":
272
+ if len(arguments) != command_index + 1:
273
+ raise CommandRejected("assets takes no arguments; it lists the current page")
274
+ return arguments
275
+ if command == "save-asset":
276
+ tail = arguments[command_index + 1 :]
277
+ if len(tail) != 2:
278
+ raise CommandRejected("save-asset requires a reference asset URL and a destination path")
279
+ url = _reference_asset_url(tail[0])
280
+ if is_reference_code(url):
281
+ raise CommandRejected("reference stylesheets and scripts are not available to the agent")
282
+ destination = Path(tail[1]).resolve()
283
+ if destination.parent != SHARED_ROOT or ASSET_SHARED_NAME.fullmatch(destination.name) is None:
284
+ raise CommandRejected("saved assets must use one gateway-owned path")
285
+ return arguments[: command_index + 1] + [url, str(destination)]
286
+ if command in FORBIDDEN_COMMANDS:
287
+ raise CommandRejected(
288
+ f"Browser Use command {command!r} is disabled for browser-only references"
289
+ )
290
+ if command not in SAFE_COMMANDS:
291
+ raise CommandRejected(f"unsupported Browser Use command {command!r}")
292
+
293
+ if command == "open":
294
+ urls = [
295
+ value
296
+ for value in arguments[command_index + 1 :]
297
+ if "://" in value
298
+ ]
299
+ if len(urls) != 1:
300
+ raise CommandRejected("open requires exactly one absolute URL")
301
+ try:
302
+ requested_origin = _origin(urls[0])
303
+ except (TypeError, ValueError) as exc:
304
+ raise CommandRejected(str(exc)) from exc
305
+ if requested_origin not in allowed_origins():
306
+ raise CommandRejected("browser navigation target is outside task origins")
307
+
308
+ if command == "screenshot":
309
+ # The bundled Browser Use CLI is `screenshot [--full] [path]`; accept the spellings
310
+ # agents reach for (`--full-page`, `--path X`, `--path=X`) and hand the CLI its own.
311
+ path_values: list[str] = []
312
+ options: list[str] = []
313
+ tail = arguments[command_index + 1 :]
314
+ index = 0
315
+ while index < len(tail):
316
+ value = tail[index]
317
+ if value == "--path":
318
+ if index + 1 >= len(tail):
319
+ raise CommandRejected("screenshot --path requires a value")
320
+ path_values.append(tail[index + 1])
321
+ index += 2
322
+ continue
323
+ if value.startswith("--path="):
324
+ path_values.append(value.partition("=")[2])
325
+ index += 1
326
+ continue
327
+ if value in {"--full", "--full-page"}:
328
+ if "--full" not in options:
329
+ options.append("--full")
330
+ index += 1
331
+ continue
332
+ if value in {"--json", "-h", "--help"}:
333
+ options.append(value)
334
+ index += 1
335
+ continue
336
+ if value.startswith("-"):
337
+ raise CommandRejected(f"unsupported screenshot option {value!r}")
338
+ path_values.append(value)
339
+ index += 1
340
+ paths = [Path(value).resolve() for value in path_values]
341
+ if (
342
+ len(paths) != 1
343
+ or paths[0].parent != SHARED_ROOT
344
+ or re.fullmatch(r"screenshot-[0-9a-f]{32}\.png", paths[0].name) is None
345
+ ):
346
+ raise CommandRejected("screenshots must use one gateway-owned PNG path")
347
+ return arguments[: command_index + 1] + options + [str(paths[0])]
348
+
349
+ return arguments
350
+
351
+
352
+ _COMMAND_LOCK = threading.Lock()
353
+
354
+
355
+ def execute(arguments: list[str]) -> dict[str, Any]:
356
+ with _COMMAND_LOCK:
357
+ try:
358
+ completed = subprocess.run(
359
+ [REAL_BROWSER_USE, *arguments],
360
+ stdin=subprocess.DEVNULL,
361
+ stdout=subprocess.PIPE,
362
+ stderr=subprocess.PIPE,
363
+ timeout=COMMAND_TIMEOUT_SEC,
364
+ check=False,
365
+ )
366
+ except subprocess.TimeoutExpired as exc:
367
+ raise CommandRejected("Browser Use command exceeded 180 seconds") from exc
368
+ except OSError as exc:
369
+ raise CommandRejected(f"Browser Use runtime unavailable: {exc}") from exc
370
+ stdout = completed.stdout[:MAX_OUTPUT_BYTES]
371
+ stderr = completed.stderr[:MAX_OUTPUT_BYTES]
372
+ if len(completed.stdout) > MAX_OUTPUT_BYTES or len(completed.stderr) > MAX_OUTPUT_BYTES:
373
+ raise CommandRejected("Browser Use output exceeded the interactive limit")
374
+ return {
375
+ "exit_code": completed.returncode,
376
+ "stdout": stdout.decode("utf-8", errors="replace"),
377
+ "stderr": stderr.decode("utf-8", errors="replace"),
378
+ }
379
+
380
+
381
+ GATEWAY_HELP = """
382
+ WebsiteBench gateway commands:
383
+ assets List the reference-origin images, icons, fonts and media that the
384
+ current page references or loaded.
385
+ save-asset URL PATH Save one of those assets to PATH (for example under /app/repo).
386
+ Stylesheets, scripts, HTML documents, JSON and other API responses are refused.
387
+ """
388
+
389
+
390
+ def _find_result(value: Any) -> Any:
391
+ if isinstance(value, dict):
392
+ if "result" in value:
393
+ return value["result"]
394
+ for nested in value.values():
395
+ found = _find_result(nested)
396
+ if found is not None:
397
+ return found
398
+ return None
399
+
400
+
401
+ def list_assets(arguments: list[str], command_index: int) -> dict[str, Any]:
402
+ inventory = execute(arguments[:command_index] + ["--json", "eval", ASSET_INVENTORY_JS])
403
+ if inventory["exit_code"] != 0:
404
+ return {"exit_code": inventory["exit_code"], "stdout": "", "stderr": "could not list assets: " + inventory["stderr"][-400:]}
405
+ try:
406
+ urls = json.loads(_find_result(json.loads(inventory["stdout"])) or "[]")
407
+ except (TypeError, ValueError):
408
+ return {"exit_code": 1, "stdout": "", "stderr": "could not list assets: no page is open"}
409
+ origin = reference_origin()
410
+ assets = []
411
+ for url in urls if isinstance(urls, list) else []:
412
+ try:
413
+ if not isinstance(url, str) or _origin(url) != origin:
414
+ continue
415
+ except ValueError:
416
+ continue
417
+ path = urllib.parse.urlsplit(url).path
418
+ if is_reference_code(url):
419
+ continue
420
+ if Path(path).suffix.lower() in STATIC_EXTENSIONS or "/static/" in path or "/assets/" in path:
421
+ assets.append(urllib.parse.urlunsplit(urllib.parse.urlsplit(url)._replace(fragment="")))
422
+ assets = sorted(set(assets))[:ASSET_LIST_LIMIT]
423
+ text = "\n".join(assets) + ("\n" if assets else "no reference static assets found on the current page\n")
424
+ return {"exit_code": 0, "stdout": text, "stderr": ""}
425
+
426
+
427
+ class _SameOriginRedirect(urllib.request.HTTPRedirectHandler):
428
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[override]
429
+ _reference_asset_url(urllib.parse.urljoin(req.full_url, newurl))
430
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
431
+
432
+
433
+ def save_asset(url: str, destination: Path) -> dict[str, Any]:
434
+ opener = urllib.request.build_opener(
435
+ urllib.request.HTTPSHandler(context=ssl.create_default_context()), _SameOriginRedirect()
436
+ )
437
+ request = urllib.request.Request(url, headers={"User-Agent": "WebsiteBenchAssetGateway/1", "Accept": "*/*"})
438
+ try:
439
+ with opener.open(request, timeout=ASSET_TIMEOUT_SEC) as response:
440
+ content_type = response.headers.get("Content-Type", "")
441
+ final_url = response.geturl()
442
+ if is_reference_code(final_url, content_type):
443
+ raise CommandRejected(f"refused stylesheet or script ({content_type or 'no content type'}): reference CSS and JavaScript are not available to the agent")
444
+ if not is_static_asset(final_url, content_type):
445
+ raise CommandRejected(f"refused non-static response ({content_type or 'no content type'})")
446
+ body = response.read(ASSET_MAX_BYTES + 1)
447
+ except urllib.error.HTTPError as exc:
448
+ raise CommandRejected(f"reference returned HTTP {exc.code} for {url}") from exc
449
+ except (urllib.error.URLError, OSError) as exc:
450
+ raise CommandRejected(f"asset download failed: {exc}") from exc
451
+ if len(body) > ASSET_MAX_BYTES:
452
+ raise CommandRejected("asset exceeds the 32 MiB limit")
453
+ temporary = destination.with_name(destination.name + ".partial")
454
+ temporary.write_bytes(body)
455
+ os.replace(temporary, destination)
456
+ return {
457
+ "exit_code": 0,
458
+ "stdout": f"saved {url} -> {destination} ({len(body)} bytes, {content_type.split(';', 1)[0].strip() or 'unknown type'})\n",
459
+ "stderr": "",
460
+ }
461
+
462
+
463
+ def run(arguments: list[str]) -> dict[str, Any]:
464
+ _session, command_index = _parse_global_options(arguments)
465
+ command = arguments[command_index] if command_index < len(arguments) else None
466
+ if command == "assets":
467
+ return list_assets(arguments, command_index)
468
+ if command == "save-asset":
469
+ return save_asset(arguments[command_index + 1], Path(arguments[command_index + 2]))
470
+ result = execute(arguments)
471
+ if command in {None, "-h", "--help"}:
472
+ result["stdout"] = result["stdout"] + GATEWAY_HELP
473
+ return result
474
+
475
+
476
+ class Handler(BaseHTTPRequestHandler):
477
+ server_version = "WebsiteBenchBrowserGateway/1"
478
+
479
+ def log_message(self, _format: str, *_arguments: object) -> None:
480
+ return
481
+
482
+ def _send(self, status: int, value: dict[str, Any]) -> None:
483
+ body = json.dumps(value, separators=(",", ":")).encode("utf-8")
484
+ self.send_response(status)
485
+ self.send_header("Content-Type", "application/json")
486
+ self.send_header("Content-Length", str(len(body)))
487
+ self.send_header("Cache-Control", "no-store")
488
+ self.end_headers()
489
+ self.wfile.write(body)
490
+
491
+ def do_GET(self) -> None:
492
+ if self.path == "/healthz":
493
+ self._send(200, {"status": "ok"})
494
+ else:
495
+ self._send(404, {"error": "not_found"})
496
+
497
+ def do_POST(self) -> None:
498
+ if self.path != "/v1/command":
499
+ self._send(404, {"error": "not_found"})
500
+ return
501
+ try:
502
+ length = int(self.headers.get("Content-Length", ""))
503
+ if length <= 0 or length > MAX_REQUEST_BYTES:
504
+ raise CommandRejected("invalid request size")
505
+ payload = json.loads(self.rfile.read(length))
506
+ if not isinstance(payload, dict) or set(payload) != {"argv"}:
507
+ raise CommandRejected("request must contain only argv")
508
+ result = run(validate_command(payload["argv"]))
509
+ except (CommandRejected, json.JSONDecodeError, UnicodeError, ValueError) as exc:
510
+ self._send(400, {"error": str(exc)})
511
+ return
512
+ self._send(200, result)
513
+
514
+
515
+ def main() -> None:
516
+ bind = os.environ.get("WEBSITEBENCH_BROWSER_GATEWAY_BIND", "0.0.0.0")
517
+ port = int(os.environ.get("WEBSITEBENCH_BROWSER_GATEWAY_PORT", "9224"))
518
+ server = ThreadingHTTPServer((bind, port), Handler)
519
+ server.daemon_threads = True
520
+ server.serve_forever()
521
+
522
+
523
+ if __name__ == "__main__":
524
+ main()
tasks/aspca-pet-insurance/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/aspca-pet-insurance/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/aspca-pet-insurance/environment/mailbox/mailbox.py ADDED
@@ -0,0 +1,2433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local-only mail writers plus Inbox HTTP sidecar for deterministic tasks.
2
+
3
+ The sidecar serves two disjoint listeners so the agent and the evaluator never
4
+ share a surface:
5
+
6
+ ``api``
7
+ The Bearer-gated JSON API plus ``/internal/bootstrap``. The reference site
8
+ and the evaluator reach it; it is where every capability lives.
9
+ ``inbox``
10
+ An HTML-only inbox for exactly one namespace, reachable without a
11
+ credential because a browser has none to present. It exposes no JSON, no
12
+ capability, and no way to name a second namespace.
13
+
14
+ Formal candidates receive a separate per-case write listener. Its primary
15
+ surface is a text-only Resend-style ``POST /emails`` API; legacy SMTP and the
16
+ ``websitebench.site_backend`` bootstrap remain compatibility writers. None of
17
+ those surfaces exposes an inbox or a JSON read route.
18
+
19
+ This module is copied *alone* into the mailbox container build context, so it
20
+ must stay self-contained: no imports outside the standard library.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import email
26
+ import hashlib
27
+ import hmac
28
+ import html
29
+ import http.client
30
+ import json
31
+ import os
32
+ import re
33
+ import secrets
34
+ import shutil
35
+ import socket
36
+ import socketserver
37
+ import signal
38
+ import subprocess
39
+ import sys
40
+ import tempfile
41
+ import threading
42
+ import time
43
+ import urllib.parse
44
+ from collections.abc import Mapping
45
+ from dataclasses import dataclass, field, replace
46
+ from email.message import EmailMessage
47
+ from email.policy import default
48
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
49
+ from typing import Any
50
+
51
+
52
+ _NAMESPACE = re.compile(r"^[a-zA-Z0-9._-]{1,160}$")
53
+ _OTP = re.compile(r"(?<!\d)(\d{4,8})(?!\d)")
54
+ _MAX_MESSAGE_BYTES = 1024 * 1024
55
+ _MAX_MESSAGES_PER_NAMESPACE = 32
56
+ _MAX_STORED_BYTES_PER_NAMESPACE = 2 * 1024 * 1024
57
+ _MAX_RECIPIENTS = 16
58
+ _MAX_COMMANDS_PER_CONNECTION = 256
59
+ _CONNECTION_TIMEOUT_SECONDS = 10
60
+ _MAX_CONNECTION_LIFETIME_SECONDS = 30
61
+ _MAX_CONCURRENT_CONNECTIONS = 16
62
+ MAILPIT_IMAGE = (
63
+ "ghcr.io/axllent/mailpit:v1.30.6@"
64
+ "sha256:7f33095f80e901f6ad08028f06ca284aa58fe84942be5496008d041d3b9f4d4d"
65
+ )
66
+ #: The one variable that names the Mailpit a trial or capture must use. It is
67
+ #: read in exactly one place, :meth:`MailPlane.from_environment`.
68
+ MAILPIT_HTTP_SOCKET_ENV = "WEBSITEBENCH_MAILPIT_HTTP_SOCKET"
69
+ #: Where Mailpit's private sockets live inside the compose sidecar. A value
70
+ #: mentioning this path in a candidate environment is an evaluator-side leak.
71
+ MAILPIT_RUNTIME_DIR = "/run/websitebench-mailpit"
72
+ #: The envelope sender every benchmark mail writer presents. Some captured
73
+ #: runtimes pin this exact suffix before opening SMTP, so paired capture and a
74
+ #: scored candidate trial must agree on it to the byte.
75
+ CANDIDATE_MAIL_SENDER = "no-reply@candidate.websitebench.local"
76
+ #: The complete optional mail ABI a candidate runtime may be handed. Nothing
77
+ #: outside this set ever reaches a candidate process.
78
+ CANDIDATE_MAIL_ENVIRONMENT = frozenset(
79
+ {
80
+ "WEBSITEBENCH_MAIL_API_URL",
81
+ "WEBSITEBENCH_MAIL_API_TOKEN",
82
+ "WEBSITEBENCH_MAIL_FROM",
83
+ "WEBSITEBENCH_SMTP_HOST",
84
+ "WEBSITEBENCH_SMTP_PORT",
85
+ "WEBSITEBENCH_SMTP_FROM",
86
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL",
87
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN",
88
+ }
89
+ )
90
+ #: Every mail variable an authoring capture exports into its own process, so
91
+ #: capture can save and restore exactly this set around a shard.
92
+ AUTHORING_MAIL_ENVIRONMENT = (
93
+ "WEBSITEBENCH_MAIL_API_URL",
94
+ "WEBSITEBENCH_MAIL_API_TOKEN",
95
+ "WEBSITEBENCH_MAIL_FROM",
96
+ "WEBSITEBENCH_SMTP_FROM",
97
+ "WEBSITEBENCH_MAILBOX_URL",
98
+ "WEBSITEBENCH_MAILBOX_ALLOWLIST",
99
+ "WEBSITEBENCH_MAILBOX_NAMESPACE",
100
+ "WEBSITEBENCH_SMTP_HOST",
101
+ "WEBSITEBENCH_SMTP_PORT",
102
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL",
103
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN",
104
+ "WEBSITEBENCH_MAILBOX_CREDENTIAL",
105
+ )
106
+ _LOG_SECRET = re.compile(
107
+ r"(?i)(?:bearer\s+[^\s\"']+|"
108
+ r"(?:authorization|cookie|credential|password|secret|token|otp|"
109
+ r"verification[-_ ]?code|card[-_ ]?number)\s*[:=]\s*"
110
+ r"(?:bearer\s+)?[^\s,;]+)"
111
+ )
112
+
113
+
114
+ class MailpitInfrastructureError(RuntimeError):
115
+ """Mailpit is missing or unhealthy, as distinct from rejected candidate mail."""
116
+
117
+
118
+ class MailInfrastructureUnavailable(MailpitInfrastructureError):
119
+ """No Mailpit is configured for this process, or the configured one is down."""
120
+
121
+
122
+ class MailboxCapacityError(RuntimeError):
123
+ """A namespace exhausted its fixed message or submitted-byte quota."""
124
+
125
+
126
+ class _UnixHTTPConnection(http.client.HTTPConnection):
127
+ """A minimal HTTP/1.1 connection transported over one Unix socket."""
128
+
129
+ def __init__(self, socket_path: str, timeout: float) -> None:
130
+ super().__init__("localhost", timeout=timeout)
131
+ self._socket_path = socket_path
132
+
133
+ def connect(self) -> None:
134
+ connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
135
+ connection.settimeout(self.timeout)
136
+ connection.connect(self._socket_path)
137
+ self.sock = connection
138
+
139
+
140
+ class MailpitClient:
141
+ """Trusted Mailpit client: HTTP UDS reads and sibling SMTP UDS writes.
142
+
143
+ This is intentionally not a general Mailpit client. It never exposes the
144
+ UI, delete, release, tag-mutation, or remote-content endpoints. All
145
+ candidate-authored control headers are discarded and the SMTP writer adds
146
+ exactly one trusted tag.
147
+ """
148
+
149
+ _MAX_RESPONSE_BYTES = 8 * 1024 * 1024
150
+
151
+ def __init__(
152
+ self,
153
+ socket_path: str | os.PathLike[str],
154
+ *,
155
+ smtp_socket_path: str | os.PathLike[str] | None = None,
156
+ timeout: float = 5.0,
157
+ ) -> None:
158
+ self.socket_path = os.fspath(socket_path)
159
+ if not self.socket_path:
160
+ raise ValueError("Mailpit HTTP socket path must not be empty")
161
+ if timeout <= 0:
162
+ raise ValueError("Mailpit timeout must be positive")
163
+ self.smtp_socket_path = (
164
+ os.fspath(smtp_socket_path)
165
+ if smtp_socket_path is not None
166
+ else os.path.join(os.path.dirname(self.socket_path), "smtp.sock")
167
+ )
168
+ self.timeout = float(timeout)
169
+
170
+ def _request(
171
+ self, method: str, path: str, body: dict[str, Any] | None = None
172
+ ) -> tuple[int, bytes]:
173
+ encoded = None if body is None else json.dumps(body).encode("utf-8")
174
+ headers = {"Accept": "application/json", "Connection": "close"}
175
+ if encoded is not None:
176
+ headers["Content-Type"] = "application/json"
177
+ headers["Content-Length"] = str(len(encoded))
178
+ connection = _UnixHTTPConnection(self.socket_path, self.timeout)
179
+ try:
180
+ connection.request(method, path, body=encoded, headers=headers)
181
+ response = connection.getresponse()
182
+ length = response.getheader("Content-Length")
183
+ if length is not None and int(length) > self._MAX_RESPONSE_BYTES:
184
+ raise MailpitInfrastructureError("Mailpit response exceeded limit")
185
+ value = response.read(self._MAX_RESPONSE_BYTES + 1)
186
+ if len(value) > self._MAX_RESPONSE_BYTES:
187
+ raise MailpitInfrastructureError("Mailpit response exceeded limit")
188
+ return int(response.status), value
189
+ except (OSError, TimeoutError, http.client.HTTPException, ValueError) as error:
190
+ raise MailpitInfrastructureError(
191
+ f"Mailpit request failed: {redact_text(str(error))}"
192
+ ) from error
193
+ finally:
194
+ connection.close()
195
+
196
+ def _json(
197
+ self, method: str, path: str, body: dict[str, Any] | None = None
198
+ ) -> dict[str, Any]:
199
+ status, raw = self._request(method, path, body)
200
+ if not 200 <= status < 300:
201
+ raise MailpitInfrastructureError(f"Mailpit API returned HTTP {status}")
202
+ try:
203
+ value = json.loads(raw)
204
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
205
+ raise MailpitInfrastructureError("Mailpit returned invalid JSON") from error
206
+ if not isinstance(value, dict):
207
+ raise MailpitInfrastructureError("Mailpit returned an invalid response")
208
+ return value
209
+
210
+ def ready(self) -> bool:
211
+ """Return whether Mailpit's built-in readiness endpoint is healthy."""
212
+
213
+ try:
214
+ status, _body = self._request("GET", "/readyz")
215
+ except MailpitInfrastructureError:
216
+ return False
217
+ return status == 200
218
+
219
+ def send(
220
+ self,
221
+ raw: bytes,
222
+ envelope_from: str,
223
+ recipients: list[str],
224
+ *,
225
+ tag: str,
226
+ ) -> str:
227
+ """Store mail with one trusted tag, ignoring all untrusted X-headers."""
228
+
229
+ if any(
230
+ "\r" in value or "\n" in value for value in [envelope_from, *recipients]
231
+ ):
232
+ raise ValueError("invalid SMTP envelope")
233
+ message = email.message_from_bytes(raw, policy=default)
234
+ for part in message.walk():
235
+ for header in list(part.keys()):
236
+ lowered = header.lower()
237
+ if lowered == "x-tags" or lowered.startswith("x-websitebench-"):
238
+ del part[header]
239
+ for header in ("From", "To", "Cc", "Bcc"):
240
+ if message.get(header) is not None:
241
+ del message[header]
242
+ message["From"] = envelope_from
243
+ message["To"] = ", ".join(recipients)
244
+ message["X-Tags"] = tag
245
+ wire = message.as_bytes(policy=default.clone(linesep="\r\n"))
246
+
247
+ connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
248
+ connection.settimeout(self.timeout)
249
+ stream = None
250
+ try:
251
+ connection.connect(self.smtp_socket_path)
252
+ stream = connection.makefile("rb")
253
+
254
+ def response() -> tuple[int, str]:
255
+ lines: list[str] = []
256
+ while True:
257
+ line = stream.readline(65537)
258
+ if not line or len(line) > 65536:
259
+ raise MailpitInfrastructureError(
260
+ "invalid Mailpit SMTP response"
261
+ )
262
+ decoded = line.decode("utf-8", "replace").rstrip("\r\n")
263
+ lines.append(decoded)
264
+ if len(decoded) < 4 or decoded[3:4] != "-":
265
+ break
266
+ try:
267
+ return int(lines[-1][:3]), "\n".join(lines)
268
+ except ValueError as error:
269
+ raise MailpitInfrastructureError(
270
+ "invalid Mailpit SMTP status"
271
+ ) from error
272
+
273
+ def command(value: bytes, expected: set[int]) -> str:
274
+ connection.sendall(value + b"\r\n")
275
+ status, reply = response()
276
+ if status not in expected:
277
+ raise MailpitInfrastructureError(
278
+ f"Mailpit SMTP returned status {status}: "
279
+ f"{redact_text(reply)[:200]}"
280
+ )
281
+ return reply
282
+
283
+ status, _greeting = response()
284
+ if status != 220:
285
+ raise MailpitInfrastructureError(
286
+ "Mailpit SMTP did not greet the gateway"
287
+ )
288
+ command(b"EHLO websitebench.local", {250})
289
+ command(f"MAIL FROM:<{envelope_from}>".encode("utf-8"), {250})
290
+ for recipient in recipients:
291
+ command(f"RCPT TO:<{recipient}>".encode("utf-8"), {250})
292
+ command(b"DATA", {354})
293
+ stuffed = b"\r\n".join(
294
+ (b"." + line if line.startswith(b".") else line)
295
+ for line in wire.split(b"\r\n")
296
+ )
297
+ connection.sendall(stuffed + b"\r\n.\r\n")
298
+ status, reply = response()
299
+ if status != 250:
300
+ raise MailpitInfrastructureError(
301
+ f"Mailpit SMTP returned status {status}: {redact_text(reply)[:200]}"
302
+ )
303
+ match = re.search(r"queued as ([A-Za-z0-9_-]+)", reply)
304
+ return match.group(1) if match else hashlib.sha256(wire).hexdigest()[:24]
305
+ except (OSError, TimeoutError) as error:
306
+ raise MailpitInfrastructureError("Mailpit SMTP request failed") from error
307
+ finally:
308
+ if stream is not None:
309
+ stream.close()
310
+ connection.close()
311
+
312
+ @staticmethod
313
+ def _addresses(value: Any) -> list[str]:
314
+ if not isinstance(value, list):
315
+ return []
316
+ return [
317
+ str(item.get("Address", item.get("Email")))
318
+ for item in value
319
+ if isinstance(item, dict)
320
+ and isinstance(item.get("Address", item.get("Email")), str)
321
+ ]
322
+
323
+ def messages(self, *, tag: str, recipient: str) -> list[dict[str, Any]]:
324
+ """Read only exact-tag, exact-recipient messages, oldest first."""
325
+
326
+ query = urllib.parse.urlencode(
327
+ {"query": f"tag:{tag}", "start": "0", "limit": "512"}
328
+ )
329
+ listing = self._json("GET", f"/api/v1/search?{query}")
330
+ summaries = listing.get("messages", [])
331
+ if not isinstance(summaries, list):
332
+ raise MailpitInfrastructureError(
333
+ "Mailpit returned invalid message summaries"
334
+ )
335
+ values: list[dict[str, Any]] = []
336
+ for summary in reversed(summaries):
337
+ if not isinstance(summary, dict):
338
+ continue
339
+ tags = summary.get("Tags", [])
340
+ all_recipients = (
341
+ self._addresses(summary.get("To"))
342
+ + self._addresses(summary.get("Cc"))
343
+ + self._addresses(summary.get("Bcc"))
344
+ )
345
+ identifier = summary.get("ID")
346
+ if (
347
+ tag not in tags
348
+ or recipient not in all_recipients
349
+ or not isinstance(identifier, str)
350
+ ):
351
+ continue
352
+ detail = self._json(
353
+ "GET", "/api/v1/message/" + urllib.parse.quote(identifier, safe="")
354
+ )
355
+ # Recheck authorization against the detailed record. Search is an
356
+ # index, never an authorization decision.
357
+ detail_tags = detail.get("Tags", [])
358
+ detailed_recipients = (
359
+ self._addresses(detail.get("To"))
360
+ + self._addresses(detail.get("Cc"))
361
+ + self._addresses(detail.get("Bcc"))
362
+ )
363
+ if tag not in detail_tags or recipient not in detailed_recipients:
364
+ continue
365
+ sender = detail.get("From", {})
366
+ attachments = detail.get("Attachments", [])
367
+ inline = detail.get("Inline", [])
368
+ metadata = [
369
+ *(attachments if isinstance(attachments, list) else []),
370
+ *(inline if isinstance(inline, list) else []),
371
+ ]
372
+ values.append(
373
+ {
374
+ "mailpit_id": identifier,
375
+ "envelope_from": str(sender.get("Address", sender.get("Email", "")))
376
+ if isinstance(sender, dict)
377
+ else "",
378
+ "recipients": detailed_recipients,
379
+ "subject": str(detail.get("Subject", "")),
380
+ "text": str(detail.get("Text", "")),
381
+ "attachments": metadata,
382
+ "stored_bytes": int(detail.get("Size", 0)),
383
+ }
384
+ )
385
+ for index, item in enumerate(values, 1):
386
+ item["id"] = index
387
+ match = _OTP.search(str(item["text"]))
388
+ item["otp"] = match.group(1) if match else None
389
+ return values
390
+
391
+
392
+ @dataclass
393
+ class MailAccount:
394
+ """Internal ``websitebench.mail-account.v1`` logical account."""
395
+
396
+ account_id: str
397
+ tag: str
398
+ address: str
399
+ role: str
400
+ allowed_from: set[str]
401
+ allowed_to: set[str]
402
+ send_capability: str = field(repr=False)
403
+ read_capability: str = field(repr=False)
404
+ state: str = "active"
405
+ schema: str = field(default="websitebench.mail-account.v1", init=False)
406
+
407
+
408
+ class MailAccountBroker:
409
+ """Authorize logical accounts before calling the untrusted storage engine."""
410
+
411
+ _SEND_ROLES = frozenset(
412
+ {
413
+ "reference-backend",
414
+ "formal-candidate",
415
+ "capture-writer",
416
+ "gateway",
417
+ "selfhost-pair",
418
+ "formal-pair",
419
+ "capture-pair",
420
+ }
421
+ )
422
+ _READ_ROLES = frozenset(
423
+ {
424
+ "agent",
425
+ "formal-verifier",
426
+ "capture-reader",
427
+ "gateway",
428
+ "selfhost-pair",
429
+ "formal-pair",
430
+ "capture-pair",
431
+ }
432
+ )
433
+ _ROLES = _SEND_ROLES | _READ_ROLES
434
+
435
+ def __init__(self, client: MailpitClient) -> None:
436
+ self.client = client
437
+ self._accounts: dict[str, MailAccount] = {}
438
+ self._lock = threading.Lock()
439
+
440
+ def create_account(
441
+ self,
442
+ *,
443
+ address: str,
444
+ role: str,
445
+ allowed_from: Any = (),
446
+ allowed_to: Any = (),
447
+ ) -> MailAccount:
448
+ if address and ("@" not in address or "\r" in address or "\n" in address):
449
+ raise ValueError("invalid mail account address")
450
+ if role not in self._ROLES:
451
+ raise ValueError("invalid mail account role")
452
+ account = MailAccount(
453
+ account_id="acct_" + secrets.token_hex(24),
454
+ tag="wb-" + secrets.token_hex(24),
455
+ address=address,
456
+ role=role,
457
+ allowed_from=set(allowed_from),
458
+ allowed_to=set(allowed_to) | ({address} if address else set()),
459
+ send_capability="send_" + secrets.token_hex(32),
460
+ read_capability="read_" + secrets.token_hex(32),
461
+ )
462
+ with self._lock:
463
+ self._accounts[account.account_id] = account
464
+ return account
465
+
466
+ def _account(self, account_id: str) -> MailAccount:
467
+ with self._lock:
468
+ account = self._accounts.get(account_id)
469
+ if account is None or account.state == "destroyed":
470
+ raise PermissionError("mail account is unavailable")
471
+ return account
472
+
473
+ def send(
474
+ self,
475
+ account_id: str,
476
+ capability: str,
477
+ raw: bytes,
478
+ envelope_from: str,
479
+ recipients: list[str],
480
+ ) -> str:
481
+ account = self._account(account_id)
482
+ if (
483
+ account.role not in self._SEND_ROLES
484
+ or account.state != "active"
485
+ or not hmac.compare_digest(account.send_capability, capability)
486
+ ):
487
+ raise PermissionError("mail account cannot send")
488
+ if (
489
+ not envelope_from
490
+ or "@" not in envelope_from
491
+ or "\r" in envelope_from
492
+ or "\n" in envelope_from
493
+ or not 1 <= len(recipients) <= _MAX_RECIPIENTS
494
+ or len(raw) > _MAX_MESSAGE_BYTES
495
+ or any(
496
+ not recipient
497
+ or len(recipient) > 320
498
+ or "@" not in recipient
499
+ or "\r" in recipient
500
+ or "\n" in recipient
501
+ for recipient in recipients
502
+ )
503
+ ):
504
+ raise PermissionError("mail envelope is not allowed")
505
+ if account.allowed_from and envelope_from not in account.allowed_from:
506
+ raise PermissionError("mail sender is not allowed")
507
+ learn_recipients = account.role == "gateway" or not account.allowed_to
508
+ if account.role != "gateway" and account.allowed_to and any(
509
+ value not in account.allowed_to for value in recipients
510
+ ):
511
+ raise PermissionError("mail recipient is not allowed")
512
+ provider_id = self.client.send(raw, envelope_from, recipients, tag=account.tag)
513
+ if learn_recipients:
514
+ # A trial can legitimately exercise more than one authentication
515
+ # address. Namespace-scoped gateway accounts therefore learn every
516
+ # address from a Mailpit-accepted envelope; reads remain limited to
517
+ # those exact delivered addresses and still require the capability.
518
+ with self._lock:
519
+ account.allowed_to.update(recipients)
520
+ if not account.address and recipients:
521
+ account.address = recipients[0]
522
+ return provider_id
523
+
524
+ def messages(
525
+ self, account_id: str, capability: str, recipient: str | None = None
526
+ ) -> list[dict[str, Any]]:
527
+ account = self._account(account_id)
528
+ if account.role not in self._READ_ROLES or not hmac.compare_digest(
529
+ account.read_capability, capability
530
+ ):
531
+ raise PermissionError("mail account cannot read")
532
+ with self._lock:
533
+ allowed_to = set(account.allowed_to)
534
+ # SMTP delivery is asynchronous. A verifier can legitimately poll the
535
+ # exact recipient before the writer has learned its first envelope. An
536
+ # empty account therefore means "not delivered yet", not "forbidden".
537
+ # Once the first envelope arrives, the usual exact-recipient boundary
538
+ # applies and a different address is still rejected.
539
+ if recipient is not None and not allowed_to:
540
+ return []
541
+ targets = [recipient] if recipient is not None else sorted(allowed_to)
542
+ if any(target not in allowed_to for target in targets):
543
+ raise PermissionError("mail recipient is not allowed")
544
+ combined: dict[str, dict[str, Any]] = {}
545
+ for target in targets:
546
+ for message in self.client.messages(tag=account.tag, recipient=target):
547
+ combined[str(message["mailpit_id"])] = message
548
+ values = list(combined.values())
549
+ for index, item in enumerate(values, 1):
550
+ item["id"] = index
551
+ return values
552
+
553
+ def seal(self, account_id: str) -> None:
554
+ account = self._account(account_id)
555
+ with self._lock:
556
+ account.state = "sealed"
557
+
558
+ def destroy(self, account_id: str) -> None:
559
+ account = self._account(account_id)
560
+ with self._lock:
561
+ account.state = "destroyed"
562
+
563
+
564
+ class EphemeralMailpit:
565
+ """One pinned, networkless Mailpit container with a private UDS directory."""
566
+
567
+ def __init__(
568
+ self,
569
+ runtime_dir: str | os.PathLike[str] | None = None,
570
+ *,
571
+ docker_binary: str = "docker",
572
+ startup_timeout: float = 45.0,
573
+ ) -> None:
574
+ if startup_timeout <= 0:
575
+ raise ValueError("startup timeout must be positive")
576
+ self._owns_runtime_dir = runtime_dir is None
577
+ self.runtime_dir = (
578
+ tempfile.mkdtemp(prefix="websitebench-mailpit-")
579
+ if runtime_dir is None
580
+ else os.path.abspath(os.fspath(runtime_dir))
581
+ )
582
+ os.makedirs(self.runtime_dir, mode=0o700, exist_ok=True)
583
+ os.chmod(self.runtime_dir, 0o700)
584
+ self.docker_binary = docker_binary
585
+ self.startup_timeout = float(startup_timeout)
586
+ self.container_name = "websitebench-mailpit-" + secrets.token_hex(12)
587
+ self.client = MailpitClient(os.path.join(self.runtime_dir, "http.sock"))
588
+ self._process: subprocess.Popen[bytes] | None = None
589
+
590
+ def _uses_rootless_podman(self) -> bool:
591
+ """Detect the Podman Docker shim that needs the host uid preserved."""
592
+
593
+ try:
594
+ result = subprocess.run(
595
+ [self.docker_binary, "info"],
596
+ stdin=subprocess.DEVNULL,
597
+ stdout=subprocess.PIPE,
598
+ stderr=subprocess.STDOUT,
599
+ text=True,
600
+ timeout=5,
601
+ check=False,
602
+ )
603
+ except (OSError, subprocess.TimeoutExpired):
604
+ return False
605
+ output = result.stdout.casefold()
606
+ return result.returncode == 0 and "podman" in output and "rootless" in output
607
+
608
+ def start(self) -> "EphemeralMailpit":
609
+ if self._process is not None:
610
+ return self
611
+ command = [
612
+ self.docker_binary,
613
+ "run",
614
+ "--rm",
615
+ "--name",
616
+ self.container_name,
617
+ ]
618
+ if self._uses_rootless_podman():
619
+ command.append("--userns=keep-id")
620
+ command.extend(
621
+ [
622
+ "--user",
623
+ f"{os.getuid()}:{os.getgid()}",
624
+ "--network",
625
+ "none",
626
+ "--tmpfs",
627
+ "/tmp:rw,noexec,nosuid,nodev,size=64m",
628
+ "--mount",
629
+ f"type=bind,src={self.runtime_dir},dst=/run/websitebench-mailpit",
630
+ ]
631
+ )
632
+ settings = {
633
+ "MP_UI_BIND_ADDR": "unix:/run/websitebench-mailpit/http.sock:660",
634
+ "MP_SMTP_BIND_ADDR": "unix:/run/websitebench-mailpit/smtp.sock:660",
635
+ "MP_DATABASE": "/tmp/mailpit.db",
636
+ "MP_MAX_MESSAGES": "512",
637
+ "MP_MAX_MESSAGE_SIZE": "1",
638
+ "MP_SMTP_MAX_RECIPIENTS": "16",
639
+ "MP_POP3_BIND_ADDR": "",
640
+ "MP_POP3_AUTH_FILE": "",
641
+ "MP_SMTP_RELAY_CONFIG": "",
642
+ "MP_SMTP_RELAY_ALL": "false",
643
+ "MP_SMTP_FORWARD_CONFIG": "",
644
+ "MP_WEBHOOK_URL": "",
645
+ "MP_ENABLE_CHAOS": "false",
646
+ "MP_ENABLE_PROMETHEUS": "false",
647
+ "MP_DISABLE_VERSION_CHECK": "true",
648
+ "MP_BLOCK_REMOTE_CSS_AND_FONTS": "true",
649
+ "MP_ALLOW_INTERNAL_HTTP_REQUESTS": "false",
650
+ }
651
+ for key, value in settings.items():
652
+ command.extend(("--env", f"{key}={value}"))
653
+ command.append(MAILPIT_IMAGE)
654
+ try:
655
+ self._process = subprocess.Popen(
656
+ command,
657
+ stdin=subprocess.DEVNULL,
658
+ stdout=subprocess.DEVNULL,
659
+ stderr=subprocess.DEVNULL,
660
+ )
661
+ except OSError as error:
662
+ self.close()
663
+ raise MailpitInfrastructureError(
664
+ "Docker is unavailable for Mailpit"
665
+ ) from error
666
+ deadline = time.monotonic() + self.startup_timeout
667
+ while time.monotonic() < deadline:
668
+ if self._process.poll() is not None:
669
+ self.close()
670
+ raise MailpitInfrastructureError(
671
+ "Mailpit container exited during startup"
672
+ )
673
+ if self.client.ready():
674
+ return self
675
+ time.sleep(0.1)
676
+ self.close()
677
+ raise MailpitInfrastructureError("Mailpit did not become ready")
678
+
679
+ def close(self) -> None:
680
+ process, self._process = self._process, None
681
+ if process is not None and process.poll() is None:
682
+ try:
683
+ subprocess.run(
684
+ [self.docker_binary, "stop", "--time", "3", self.container_name],
685
+ stdin=subprocess.DEVNULL,
686
+ stdout=subprocess.DEVNULL,
687
+ stderr=subprocess.DEVNULL,
688
+ timeout=8,
689
+ check=False,
690
+ )
691
+ except (OSError, subprocess.TimeoutExpired):
692
+ process.terminate()
693
+ try:
694
+ process.wait(timeout=5)
695
+ except subprocess.TimeoutExpired:
696
+ process.kill()
697
+ process.wait(timeout=5)
698
+ if self._owns_runtime_dir:
699
+ shutil.rmtree(self.runtime_dir, ignore_errors=True)
700
+ else:
701
+ for name in ("http.sock", "smtp.sock"):
702
+ try:
703
+ os.unlink(os.path.join(self.runtime_dir, name))
704
+ except FileNotFoundError:
705
+ pass
706
+
707
+ def __enter__(self) -> "EphemeralMailpit":
708
+ return self.start()
709
+
710
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
711
+ self.close()
712
+
713
+
714
+ def redact_text(value: str) -> str:
715
+ """Redact secret-like log fragments without retaining the matched value."""
716
+
717
+ return _LOG_SECRET.sub("[REDACTED]", value)
718
+
719
+
720
+ def redact_log_file(path: str) -> None:
721
+ """Sanitize one UTF-8 verifier log in place before it is published."""
722
+
723
+ from pathlib import Path
724
+
725
+ target = Path(path)
726
+ if not target.is_file():
727
+ return
728
+ value = target.read_text(encoding="utf-8", errors="replace")
729
+ target.write_text(redact_text(value), encoding="utf-8", newline="\n")
730
+
731
+
732
+ def redact_evidence(value: Any) -> Any:
733
+ """Remove credentials and sensitive form values from retained evidence."""
734
+
735
+ sensitive = re.compile(
736
+ r"(?:authorization|cookie|credential|password|secret|token|otp|code|payment|card)",
737
+ re.IGNORECASE,
738
+ )
739
+ if isinstance(value, dict):
740
+ return {
741
+ str(key): "[REDACTED]"
742
+ if sensitive.search(str(key))
743
+ else redact_evidence(child)
744
+ for key, child in value.items()
745
+ }
746
+ if isinstance(value, list):
747
+ return [redact_evidence(child) for child in value]
748
+ return value
749
+
750
+
751
+ @dataclass
752
+ class MailboxStore:
753
+ mailpit_client: MailpitClient
754
+ _capabilities: dict[str, str] = field(default_factory=dict)
755
+ _idempotency: dict[tuple[str, str], str] = field(default_factory=dict)
756
+ _namespace_message_counts: dict[str, int] = field(default_factory=dict)
757
+ _namespace_stored_bytes: dict[str, int] = field(default_factory=dict)
758
+ _lock: threading.Lock = field(default_factory=threading.Lock)
759
+ _broker: MailAccountBroker = field(init=False)
760
+ _accounts: dict[str, MailAccount] = field(default_factory=dict, init=False)
761
+
762
+ def __post_init__(self) -> None:
763
+ if not isinstance(self.mailpit_client, MailpitClient):
764
+ raise MailpitInfrastructureError("Mailpit client is required")
765
+ self._broker = MailAccountBroker(self.mailpit_client)
766
+
767
+ def healthy(self) -> bool:
768
+ return self.mailpit_client.ready()
769
+
770
+ def register(
771
+ self,
772
+ namespace: str,
773
+ capability: str,
774
+ *,
775
+ allowed_from: tuple[str, ...] = (),
776
+ ) -> None:
777
+ if not _NAMESPACE.fullmatch(namespace) or len(capability) < 32:
778
+ raise ValueError("invalid mailbox namespace capability")
779
+ if any(
780
+ not value or "@" not in value or "\r" in value or "\n" in value
781
+ for value in allowed_from
782
+ ):
783
+ raise ValueError("invalid allowed mail sender")
784
+ allowed_senders = set(allowed_from)
785
+ with self._lock:
786
+ existing = self._capabilities.get(namespace)
787
+ if existing is not None and existing != capability:
788
+ raise ValueError("mailbox namespace is already registered")
789
+ self._capabilities[namespace] = capability
790
+ account = self._accounts.get(namespace)
791
+ if account is None:
792
+ self._accounts[namespace] = self._broker.create_account(
793
+ address="", role="gateway", allowed_from=allowed_senders
794
+ )
795
+ elif account.allowed_from != allowed_senders:
796
+ raise ValueError("mailbox namespace sender policy is already registered")
797
+
798
+ def authorized(self, namespace: str, capability: str | None) -> bool:
799
+ with self._lock:
800
+ expected = self._capabilities.get(namespace)
801
+ return (
802
+ expected is not None
803
+ and capability is not None
804
+ and hmac.compare_digest(expected, capability)
805
+ )
806
+
807
+ def seal_namespace(self, namespace: str) -> None:
808
+ """Retire one writer while retaining trusted reads until teardown."""
809
+
810
+ with self._lock:
811
+ self._capabilities.pop(namespace, None)
812
+ account = self._accounts.get(namespace)
813
+ self._namespace_message_counts.pop(namespace, None)
814
+ self._namespace_stored_bytes.pop(namespace, None)
815
+ self._idempotency = {
816
+ identity: provider_id
817
+ for identity, provider_id in self._idempotency.items()
818
+ if identity[0] != namespace
819
+ }
820
+ if account is not None:
821
+ self._broker.seal(account.account_id)
822
+
823
+ def destroy_namespaces(self) -> None:
824
+ """Revoke every logical account without deleting Mailpit messages."""
825
+
826
+ with self._lock:
827
+ accounts = list(self._accounts.values())
828
+ self._capabilities.clear()
829
+ self._accounts.clear()
830
+ self._namespace_message_counts.clear()
831
+ self._namespace_stored_bytes.clear()
832
+ self._idempotency.clear()
833
+ for account in accounts:
834
+ if account.state != "destroyed":
835
+ self._broker.destroy(account.account_id)
836
+
837
+ def _store_message(
838
+ self,
839
+ message: Any,
840
+ envelope_from: str,
841
+ recipients: list[str],
842
+ *,
843
+ namespace: str,
844
+ idempotency_key: str | None = None,
845
+ raw: bytes | None = None,
846
+ ) -> tuple[bool, str | None]:
847
+ with self._lock:
848
+ idempotency_identity = (
849
+ (namespace, idempotency_key) if idempotency_key else None
850
+ )
851
+ if idempotency_identity is not None:
852
+ previous = self._idempotency.get(idempotency_identity)
853
+ if previous is not None:
854
+ return True, previous
855
+ account = self._accounts.get(namespace)
856
+ if account is None:
857
+ return False, None
858
+ wire = raw if raw is not None else message.as_bytes()
859
+ message_count = self._namespace_message_counts.get(namespace, 0)
860
+ stored_bytes = self._namespace_stored_bytes.get(namespace, 0)
861
+ if (
862
+ message_count >= _MAX_MESSAGES_PER_NAMESPACE
863
+ or stored_bytes + len(wire) > _MAX_STORED_BYTES_PER_NAMESPACE
864
+ ):
865
+ raise MailboxCapacityError("mailbox namespace capacity exceeded")
866
+ # Keep the lock across the final hop so concurrent requests with
867
+ # one idempotency key cannot manufacture two accepted messages.
868
+ # No message body or code is retained after Mailpit acknowledges
869
+ # the SMTP DATA command.
870
+ provider_id = self._broker.send(
871
+ account.account_id,
872
+ account.send_capability,
873
+ wire,
874
+ envelope_from,
875
+ recipients,
876
+ )
877
+ self._namespace_message_counts[namespace] = message_count + 1
878
+ self._namespace_stored_bytes[namespace] = stored_bytes + len(wire)
879
+ if idempotency_identity is not None:
880
+ self._idempotency[idempotency_identity] = provider_id
881
+ return True, provider_id
882
+
883
+ def deliver(self, raw: bytes, envelope_from: str, recipients: list[str]) -> bool:
884
+ message = email.message_from_bytes(raw, policy=default)
885
+ namespace = str(message.get("X-WebsiteBench-Namespace", "default"))
886
+ capability = str(message.get("X-WebsiteBench-Capability", ""))
887
+ if not _NAMESPACE.fullmatch(namespace) or not self.authorized(
888
+ namespace, capability
889
+ ):
890
+ return False
891
+ accepted, _provider_id = self._store_message(
892
+ message,
893
+ envelope_from,
894
+ recipients,
895
+ namespace=namespace,
896
+ raw=raw,
897
+ )
898
+ return accepted
899
+
900
+ def deliver_to(
901
+ self,
902
+ namespace: str,
903
+ raw: bytes,
904
+ envelope_from: str,
905
+ recipients: list[str],
906
+ ) -> bool:
907
+ """Store mail on a listener already fixed to one registered namespace.
908
+
909
+ Formal candidate runtimes receive access to that write-only listener,
910
+ not to the namespace-selecting SMTP or JSON API used by reference
911
+ capture. The routing decision therefore belongs to trusted verifier
912
+ infrastructure rather than to candidate-authored message headers.
913
+ """
914
+
915
+ if not _NAMESPACE.fullmatch(namespace):
916
+ return False
917
+ with self._lock:
918
+ registered = namespace in self._capabilities
919
+ if not registered:
920
+ return False
921
+ message = email.message_from_bytes(raw, policy=default)
922
+ accepted, _provider_id = self._store_message(
923
+ message,
924
+ envelope_from,
925
+ recipients,
926
+ namespace=namespace,
927
+ raw=raw,
928
+ )
929
+ return accepted
930
+
931
+ def deliver_resend_style_to(
932
+ self,
933
+ namespace: str,
934
+ *,
935
+ envelope_from: str,
936
+ recipients: list[str],
937
+ subject: str,
938
+ text: str,
939
+ idempotency_key: str | None,
940
+ ) -> tuple[bool, str | None]:
941
+ """Store one text-only Resend-style request in a fixed namespace."""
942
+
943
+ if not _NAMESPACE.fullmatch(namespace):
944
+ return False, None
945
+ with self._lock:
946
+ registered = namespace in self._capabilities
947
+ if not registered:
948
+ return False, None
949
+ message = EmailMessage()
950
+ message["From"] = envelope_from
951
+ message["To"] = ", ".join(recipients)
952
+ message["Subject"] = subject
953
+ message.set_content(text)
954
+ return self._store_message(
955
+ message,
956
+ envelope_from,
957
+ recipients,
958
+ namespace=namespace,
959
+ idempotency_key=idempotency_key,
960
+ raw=message.as_bytes(),
961
+ )
962
+
963
+ def messages(
964
+ self, namespace: str, recipient: str | None = None
965
+ ) -> list[dict[str, Any]]:
966
+ with self._lock:
967
+ account = self._accounts.get(namespace)
968
+ if account is None:
969
+ return []
970
+ values = self._broker.messages(
971
+ account.account_id, account.read_capability, recipient
972
+ )
973
+ for item in values:
974
+ item["namespace"] = namespace
975
+ item.pop("stored_bytes", None)
976
+ item.pop("mailpit_id", None)
977
+ return values
978
+
979
+
980
+ _INBOX_STYLE = (
981
+ "body{font:16px/1.5 system-ui,sans-serif;margin:0;background:#f6f7f9;"
982
+ "color:#1b1f24}"
983
+ "header{background:#fff;border-bottom:1px solid #d8dee4;padding:16px 24px}"
984
+ "h1{font-size:20px;margin:0}"
985
+ "main{max-width:52rem;margin:0 auto;padding:24px}"
986
+ "a{color:#0b62d0}"
987
+ ".msg{background:#fff;border:1px solid #d8dee4;border-radius:8px;"
988
+ "padding:12px 16px;margin-bottom:12px}"
989
+ ".msg h2{font-size:16px;margin:0 0 4px}"
990
+ ".meta{color:#57606a;font-size:13px;margin:0}"
991
+ ".empty{color:#57606a}"
992
+ "pre{white-space:pre-wrap;word-break:break-word;background:#f6f8fa;"
993
+ "border-radius:6px;padding:12px;margin:12px 0 0}"
994
+ )
995
+
996
+
997
+ def _document(title: str, body: str) -> bytes:
998
+ """One self-contained HTML page. Every interpolated value is escaped."""
999
+
1000
+ return (
1001
+ "<!doctype html><html lang=en><meta charset=utf-8>"
1002
+ '<meta name=viewport content="width=device-width,initial-scale=1">'
1003
+ f"<title>{html.escape(title)}</title>"
1004
+ f"<style>{_INBOX_STYLE}</style>"
1005
+ f"<header><h1>{html.escape(title)}</h1></header><main>{body}</main>"
1006
+ "</html>"
1007
+ ).encode("utf-8")
1008
+
1009
+
1010
+ def _recipients(message: dict[str, Any]) -> str:
1011
+ return ", ".join(str(item) for item in message.get("recipients", []))
1012
+
1013
+
1014
+ def render_inbox(messages: list[dict[str, Any]], *, base_path: str = "") -> bytes:
1015
+ """The message list an agent reads in a browser.
1016
+
1017
+ The extracted ``otp`` is deliberately absent: an agent should read the code
1018
+ out of the body the way a person would. That field stays an evaluator-side
1019
+ convenience on the JSON API.
1020
+ """
1021
+
1022
+ if not messages:
1023
+ body = (
1024
+ "<p class=empty id=inbox-empty>No messages yet. Mail sent to this "
1025
+ "mailbox appears here.</p>"
1026
+ )
1027
+ else:
1028
+ body = "".join(
1029
+ "<article class=msg>"
1030
+ f'<h2><a href="{html.escape(base_path)}/messages/{int(item["id"])}">'
1031
+ f"{html.escape(str(item.get('subject', '')))}</a></h2>"
1032
+ f"<p class=meta>From {html.escape(str(item.get('envelope_from', '')))}"
1033
+ f" &middot; To {html.escape(_recipients(item))}"
1034
+ f" &middot; Message {int(item['id'])}</p>"
1035
+ "</article>"
1036
+ for item in messages
1037
+ )
1038
+ refresh = f'<p><a href="{html.escape(base_path)}" id=inbox-refresh>Refresh</a></p>'
1039
+ return _document("Inbox", body + refresh)
1040
+
1041
+
1042
+ def render_message(message: dict[str, Any], *, base_path: str = "") -> bytes:
1043
+ """One message, body included, for the agent to read the code out of."""
1044
+
1045
+ body = (
1046
+ "<article class=msg>"
1047
+ f"<h2>{html.escape(str(message.get('subject', '')))}</h2>"
1048
+ f"<p class=meta>From {html.escape(str(message.get('envelope_from', '')))}"
1049
+ f" &middot; To {html.escape(_recipients(message))}</p>"
1050
+ f"<pre id=message-body>{html.escape(str(message.get('text', '')))}</pre>"
1051
+ "</article>"
1052
+ f'<p><a href="{html.escape(base_path)}" id=inbox-back>Back to inbox</a></p>'
1053
+ )
1054
+ return _document("Message", body)
1055
+
1056
+
1057
+ class _SmtpHandler(socketserver.StreamRequestHandler):
1058
+ def handle(self) -> None:
1059
+ timer = threading.Timer(
1060
+ _MAX_CONNECTION_LIFETIME_SECONDS, self._expire_connection
1061
+ )
1062
+ timer.daemon = True
1063
+ timer.start()
1064
+ try:
1065
+ self._handle_session()
1066
+ finally:
1067
+ timer.cancel()
1068
+
1069
+ def _expire_connection(self) -> None:
1070
+ try:
1071
+ self.connection.shutdown(socket.SHUT_RDWR)
1072
+ except OSError:
1073
+ pass
1074
+
1075
+ def _handle_session(self) -> None:
1076
+ store: MailboxStore = self.server.store # type: ignore[attr-defined]
1077
+ self.connection.settimeout(_CONNECTION_TIMEOUT_SECONDS)
1078
+ self.wfile.write(b"220 websitebench.local ESMTP\r\n")
1079
+ envelope_from = ""
1080
+ recipients: list[str] = []
1081
+ for _command_count in range(_MAX_COMMANDS_PER_CONNECTION):
1082
+ try:
1083
+ line = self.rfile.readline(65537)
1084
+ except (TimeoutError, socket.timeout):
1085
+ return
1086
+ if not line:
1087
+ return
1088
+ if len(line) > 65536:
1089
+ self.wfile.write(b"500 Command line too long\r\n")
1090
+ return
1091
+ command = line.decode("utf-8", "replace").rstrip("\r\n")
1092
+ upper = command.upper()
1093
+ if upper.startswith(("EHLO", "HELO")):
1094
+ self.wfile.write(b"250-websitebench.local\r\n250 SIZE 1048576\r\n")
1095
+ elif upper.startswith("MAIL FROM:"):
1096
+ path = command.split(":", 1)[1].strip()
1097
+ envelope_from = (
1098
+ path[1:].split(">", 1)[0]
1099
+ if path.startswith("<") and ">" in path
1100
+ else path.split(None, 1)[0].strip("<>")
1101
+ )
1102
+ recipients = []
1103
+ self.wfile.write(b"250 OK\r\n")
1104
+ elif upper.startswith("RCPT TO:"):
1105
+ if len(recipients) >= _MAX_RECIPIENTS:
1106
+ self.wfile.write(b"452 Too many recipients\r\n")
1107
+ continue
1108
+ path = command.split(":", 1)[1].strip()
1109
+ recipients.append(
1110
+ path[1:].split(">", 1)[0]
1111
+ if path.startswith("<") and ">" in path
1112
+ else path.split(None, 1)[0].strip("<>")
1113
+ )
1114
+ self.wfile.write(b"250 OK\r\n")
1115
+ elif upper == "DATA":
1116
+ self.wfile.write(b"354 End data with <CR><LF>.<CR><LF>\r\n")
1117
+ chunks = bytearray()
1118
+ oversized = False
1119
+ while True:
1120
+ try:
1121
+ data_line = self.rfile.readline(65537)
1122
+ except (TimeoutError, socket.timeout):
1123
+ return
1124
+ if data_line in {b".\r\n", b".\n", b""}:
1125
+ break
1126
+ if len(data_line) > 65536:
1127
+ oversized = True
1128
+ value = data_line[1:] if data_line.startswith(b"..") else data_line
1129
+ if len(chunks) + len(value) > _MAX_MESSAGE_BYTES:
1130
+ oversized = True
1131
+ elif not oversized:
1132
+ chunks.extend(value)
1133
+ if oversized:
1134
+ self.wfile.write(b"552 Message exceeds fixed local limit\r\n")
1135
+ continue
1136
+ fixed_namespace = getattr(self.server, "fixed_namespace", None)
1137
+ try:
1138
+ accepted = (
1139
+ store.deliver_to(
1140
+ fixed_namespace,
1141
+ bytes(chunks),
1142
+ envelope_from,
1143
+ recipients,
1144
+ )
1145
+ if isinstance(fixed_namespace, str)
1146
+ else store.deliver(bytes(chunks), envelope_from, recipients)
1147
+ )
1148
+ except MailboxCapacityError:
1149
+ self.wfile.write(b"452 Mailbox capacity exceeded\r\n")
1150
+ continue
1151
+ except PermissionError:
1152
+ self.wfile.write(b"550 Mail sender or recipient is not allowed\r\n")
1153
+ continue
1154
+ except MailpitInfrastructureError:
1155
+ self.wfile.write(b"451 Mailpit delivery unavailable\r\n")
1156
+ continue
1157
+ self.wfile.write(
1158
+ b"250 Accepted by Mailpit\r\n"
1159
+ if accepted
1160
+ else b"550 Invalid namespace capability\r\n"
1161
+ )
1162
+ elif upper == "RSET":
1163
+ envelope_from, recipients = "", []
1164
+ self.wfile.write(b"250 OK\r\n")
1165
+ elif upper == "NOOP":
1166
+ self.wfile.write(b"250 OK\r\n")
1167
+ elif upper == "QUIT":
1168
+ self.wfile.write(b"221 Bye\r\n")
1169
+ return
1170
+ else:
1171
+ self.wfile.write(b"502 Command not implemented\r\n")
1172
+ self.wfile.write(b"421 Command limit exceeded\r\n")
1173
+
1174
+
1175
+ class _SmtpServer(socketserver.ThreadingTCPServer):
1176
+ allow_reuse_address = True
1177
+ daemon_threads = True
1178
+
1179
+ def __init__(
1180
+ self,
1181
+ address: tuple[str, int],
1182
+ store: MailboxStore,
1183
+ *,
1184
+ fixed_namespace: str | None = None,
1185
+ ) -> None:
1186
+ self.store = store
1187
+ self.fixed_namespace = fixed_namespace
1188
+ self._connection_slots = threading.BoundedSemaphore(_MAX_CONCURRENT_CONNECTIONS)
1189
+ super().__init__(address, _SmtpHandler)
1190
+
1191
+ def process_request(self, request: Any, client_address: Any) -> None:
1192
+ if not self._connection_slots.acquire(blocking=False):
1193
+ request.close()
1194
+ return
1195
+ super().process_request(request, client_address)
1196
+
1197
+ def process_request_thread(self, request: Any, client_address: Any) -> None:
1198
+ try:
1199
+ super().process_request_thread(request, client_address)
1200
+ finally:
1201
+ self._connection_slots.release()
1202
+
1203
+
1204
+ class _HttpServer(ThreadingHTTPServer):
1205
+ daemon_threads = True
1206
+
1207
+ def __init__(self, address: tuple[str, int], handler: Any) -> None:
1208
+ self._connection_slots = threading.BoundedSemaphore(_MAX_CONCURRENT_CONNECTIONS)
1209
+ super().__init__(address, handler)
1210
+
1211
+ def process_request(self, request: Any, client_address: Any) -> None:
1212
+ if not self._connection_slots.acquire(blocking=False):
1213
+ request.close()
1214
+ return
1215
+ super().process_request(request, client_address)
1216
+
1217
+ def process_request_thread(self, request: Any, client_address: Any) -> None:
1218
+ def expire() -> None:
1219
+ try:
1220
+ request.shutdown(socket.SHUT_RDWR)
1221
+ except OSError:
1222
+ pass
1223
+
1224
+ timer = threading.Timer(_MAX_CONNECTION_LIFETIME_SECONDS, expire)
1225
+ timer.daemon = True
1226
+ timer.start()
1227
+ try:
1228
+ request.settimeout(_CONNECTION_TIMEOUT_SECONDS)
1229
+ super().process_request_thread(request, client_address)
1230
+ finally:
1231
+ timer.cancel()
1232
+ self._connection_slots.release()
1233
+
1234
+
1235
+ def _http_handler(
1236
+ store: MailboxStore,
1237
+ bootstrap: "_Bootstrap | _BootstrapSlot | None" = None,
1238
+ ) -> type[BaseHTTPRequestHandler]:
1239
+ """The evaluator- and site-facing listener: JSON, Bearer-gated throughout."""
1240
+
1241
+ slot = (
1242
+ bootstrap
1243
+ if isinstance(bootstrap, _BootstrapSlot)
1244
+ else _BootstrapSlot(bootstrap)
1245
+ )
1246
+
1247
+ class Handler(BaseHTTPRequestHandler):
1248
+ def _authorized(self, namespace: str) -> bool:
1249
+ prefix = "Bearer "
1250
+ header = self.headers.get("Authorization", "")
1251
+ capability = header[len(prefix) :] if header.startswith(prefix) else None
1252
+ if store.authorized(namespace, capability):
1253
+ return True
1254
+ self._json(403, {"error": "forbidden"})
1255
+ return False
1256
+
1257
+ def _json(self, status: int, value: Any) -> None:
1258
+ body = json.dumps(value, ensure_ascii=False, sort_keys=True).encode("utf-8")
1259
+ self.send_response(status)
1260
+ self.send_header("Content-Type", "application/json; charset=utf-8")
1261
+ self.send_header("Content-Length", str(len(body)))
1262
+ self.end_headers()
1263
+ self.wfile.write(body)
1264
+
1265
+ def _html(self, status: int, body: bytes) -> None:
1266
+ self.send_response(status)
1267
+ self.send_header("Content-Type", "text/html; charset=utf-8")
1268
+ self.send_header("Content-Length", str(len(body)))
1269
+ self.end_headers()
1270
+ self.wfile.write(body)
1271
+
1272
+ def do_GET(self) -> None: # noqa: N802
1273
+ parsed = urllib.parse.urlsplit(self.path)
1274
+ if parsed.path == "/healthz":
1275
+ if store.healthy():
1276
+ self._json(200, {"status": "ok"})
1277
+ else:
1278
+ self._json(503, {"status": "unavailable"})
1279
+ return
1280
+ if parsed.path == "/internal/bootstrap":
1281
+ # The site process learns this trial's namespace and capability
1282
+ # here. It is gated on its own token so the route stays closed
1283
+ # even if the internal network were misrouted.
1284
+ identity = slot.get()
1285
+ if identity is None:
1286
+ self._json(404, {"error": "not_found"})
1287
+ return
1288
+ prefix = "Bearer "
1289
+ header = self.headers.get("Authorization", "")
1290
+ presented = header[len(prefix) :] if header.startswith(prefix) else ""
1291
+ if not hmac.compare_digest(identity.token, presented):
1292
+ self._json(403, {"error": "forbidden"})
1293
+ return
1294
+ self._json(200, identity.payload())
1295
+ return
1296
+ parts = parsed.path.strip("/").split("/")
1297
+ if (
1298
+ len(parts) >= 4
1299
+ and parts[:2] == ["api", "namespaces"]
1300
+ and parts[3] == "messages"
1301
+ ):
1302
+ namespace = urllib.parse.unquote(parts[2])
1303
+ if not _NAMESPACE.fullmatch(namespace):
1304
+ self._json(400, {"error": "invalid_namespace"})
1305
+ return
1306
+ if not self._authorized(namespace):
1307
+ return
1308
+ recipient = urllib.parse.parse_qs(parsed.query).get(
1309
+ "recipient", [None]
1310
+ )[0]
1311
+ try:
1312
+ values = store.messages(namespace, recipient)
1313
+ except PermissionError:
1314
+ self._json(403, {"error": "recipient_forbidden"})
1315
+ return
1316
+ except MailpitInfrastructureError:
1317
+ self._json(503, {"error": "mailpit_unavailable"})
1318
+ return
1319
+ if len(parts) == 5 and parts[4] == "latest":
1320
+ if not values:
1321
+ self._json(404, {"error": "message_not_found"})
1322
+ else:
1323
+ self._json(200, values[-1])
1324
+ else:
1325
+ self._json(200, {"messages": values})
1326
+ return
1327
+ if len(parts) == 2 and parts[0] == "inbox":
1328
+ namespace = urllib.parse.unquote(parts[1])
1329
+ if not _NAMESPACE.fullmatch(namespace):
1330
+ self._json(400, {"error": "invalid_namespace"})
1331
+ return
1332
+ if not self._authorized(namespace):
1333
+ return
1334
+ try:
1335
+ messages = store.messages(namespace)
1336
+ except PermissionError:
1337
+ self._json(403, {"error": "forbidden"})
1338
+ return
1339
+ except MailpitInfrastructureError:
1340
+ self._json(503, {"error": "mailpit_unavailable"})
1341
+ return
1342
+ body = render_inbox(
1343
+ messages, base_path=f"/inbox/{urllib.parse.quote(namespace)}"
1344
+ )
1345
+ self._html(200, body)
1346
+ return
1347
+ self._json(404, {"error": "not_found"})
1348
+
1349
+ def do_POST(self) -> None: # noqa: N802
1350
+ """Accept reference mail through a bootstrap-token write-only API."""
1351
+
1352
+ parsed = urllib.parse.urlsplit(self.path)
1353
+ if parsed.path != "/emails" or parsed.query or parsed.fragment:
1354
+ self._json(404, {"error": "not_found"})
1355
+ return
1356
+ identity = slot.get()
1357
+ if identity is None:
1358
+ self._json(404, {"error": "not_found"})
1359
+ return
1360
+ prefix = "Bearer "
1361
+ header = self.headers.get("Authorization", "")
1362
+ presented = header[len(prefix) :] if header.startswith(prefix) else ""
1363
+ if not hmac.compare_digest(identity.token, presented):
1364
+ self._json(401, {"error": "unauthorized"})
1365
+ return
1366
+ if self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() != "application/json":
1367
+ self._json(415, {"error": "application_json_required"})
1368
+ return
1369
+ try:
1370
+ content_length = int(self.headers.get("Content-Length", ""))
1371
+ except ValueError:
1372
+ self._json(411, {"error": "content_length_required"})
1373
+ return
1374
+ if content_length < 0 or content_length > _MAX_MESSAGE_BYTES:
1375
+ self._json(413, {"error": "message_too_large"})
1376
+ return
1377
+ try:
1378
+ value = json.loads(self.rfile.read(content_length).decode("utf-8"))
1379
+ except (UnicodeDecodeError, json.JSONDecodeError):
1380
+ self._json(400, {"error": "invalid_json"})
1381
+ return
1382
+ if not isinstance(value, dict) or set(value) != {"from", "to", "subject", "text"}:
1383
+ self._json(400, {"error": "invalid_message_fields"})
1384
+ return
1385
+ envelope_from = value.get("from")
1386
+ recipients = value.get("to")
1387
+ subject = value.get("subject")
1388
+ message_text = value.get("text")
1389
+ recipients = [recipients] if isinstance(recipients, str) else recipients
1390
+ if (
1391
+ not isinstance(envelope_from, str)
1392
+ or not envelope_from
1393
+ or "@" not in envelope_from
1394
+ or "\r" in envelope_from
1395
+ or "\n" in envelope_from
1396
+ or not isinstance(recipients, list)
1397
+ or not 1 <= len(recipients) <= _MAX_RECIPIENTS
1398
+ or any(
1399
+ not isinstance(recipient, str)
1400
+ or not recipient
1401
+ or len(recipient) > 320
1402
+ or "@" not in recipient
1403
+ or "\r" in recipient
1404
+ or "\n" in recipient
1405
+ for recipient in recipients
1406
+ )
1407
+ or not isinstance(subject, str)
1408
+ or len(subject) > 998
1409
+ or "\r" in subject
1410
+ or "\n" in subject
1411
+ or not isinstance(message_text, str)
1412
+ or len(message_text.encode("utf-8")) > _MAX_MESSAGE_BYTES
1413
+ ):
1414
+ self._json(400, {"error": "invalid_message"})
1415
+ return
1416
+ idempotency_key = self.headers.get("Idempotency-Key")
1417
+ if idempotency_key is not None and (
1418
+ not idempotency_key
1419
+ or len(idempotency_key) > 256
1420
+ or "\r" in idempotency_key
1421
+ or "\n" in idempotency_key
1422
+ ):
1423
+ self._json(400, {"error": "invalid_idempotency_key"})
1424
+ return
1425
+ try:
1426
+ accepted, provider_id = store.deliver_resend_style_to(
1427
+ identity.namespace,
1428
+ envelope_from=envelope_from,
1429
+ recipients=recipients,
1430
+ subject=subject,
1431
+ text=message_text,
1432
+ idempotency_key=idempotency_key,
1433
+ )
1434
+ except MailboxCapacityError:
1435
+ self._json(429, {"error": "mailbox_capacity"})
1436
+ return
1437
+ except MailpitInfrastructureError:
1438
+ self._json(503, {"error": "mailpit_unavailable"})
1439
+ return
1440
+ if not accepted or provider_id is None:
1441
+ self._json(503, {"error": "delivery_failed"})
1442
+ return
1443
+ self._json(200, {"id": provider_id})
1444
+
1445
+ def log_message(self, format: str, *args: Any) -> None:
1446
+ return
1447
+
1448
+ return Handler
1449
+
1450
+
1451
+ def _candidate_bootstrap_handler(
1452
+ *,
1453
+ store: MailboxStore,
1454
+ bootstrap_token: str,
1455
+ mail_api_token: str,
1456
+ namespace: str,
1457
+ capability: str,
1458
+ smtp_host: str,
1459
+ smtp_port: int,
1460
+ sender: str,
1461
+ ) -> type[BaseHTTPRequestHandler]:
1462
+ """Expose write-only mail paths without exposing the mailbox read API.
1463
+
1464
+ ``POST /emails`` is deliberately a small Resend-style subset: one fixed
1465
+ sender, one or more recipients, a subject, and a plain-text body. The
1466
+ endpoint owns the trial namespace, so candidate input can never select a
1467
+ second mailbox. The legacy bootstrap and SMTP coordinates remain here for
1468
+ candidates using the vendored ``websitebench.site_backend`` transport.
1469
+ """
1470
+
1471
+ payload = {
1472
+ "namespace": namespace,
1473
+ "capability": capability,
1474
+ "smtp_host": smtp_host,
1475
+ "smtp_port": smtp_port,
1476
+ }
1477
+
1478
+ class CandidateBootstrapHandler(BaseHTTPRequestHandler):
1479
+ def _json(self, status: int, value: Any) -> None:
1480
+ body = json.dumps(value, ensure_ascii=False, sort_keys=True).encode("utf-8")
1481
+ self.send_response(status)
1482
+ self.send_header("Content-Type", "application/json; charset=utf-8")
1483
+ self.send_header("Content-Length", str(len(body)))
1484
+ self.send_header("Cache-Control", "no-store")
1485
+ self.end_headers()
1486
+ self.wfile.write(body)
1487
+
1488
+ def do_GET(self) -> None: # noqa: N802
1489
+ parsed = urllib.parse.urlsplit(self.path)
1490
+ if parsed.path == "/healthz":
1491
+ healthy = store.healthy()
1492
+ self._json(200 if healthy else 503, {"status": "ok" if healthy else "unavailable"})
1493
+ return
1494
+ if parsed.path != "/internal/bootstrap":
1495
+ self._json(404, {"error": "not_found"})
1496
+ return
1497
+ prefix = "Bearer "
1498
+ header = self.headers.get("Authorization", "")
1499
+ presented = header[len(prefix) :] if header.startswith(prefix) else ""
1500
+ if not hmac.compare_digest(bootstrap_token, presented):
1501
+ self._json(403, {"error": "forbidden"})
1502
+ return
1503
+ self._json(200, payload)
1504
+
1505
+ def do_POST(self) -> None: # noqa: N802
1506
+ parsed = urllib.parse.urlsplit(self.path)
1507
+ if parsed.path != "/emails" or parsed.query or parsed.fragment:
1508
+ self._json(404, {"error": "not_found"})
1509
+ return
1510
+ prefix = "Bearer "
1511
+ header = self.headers.get("Authorization", "")
1512
+ presented = header[len(prefix) :] if header.startswith(prefix) else ""
1513
+ if not hmac.compare_digest(mail_api_token, presented):
1514
+ self._json(401, {"error": "unauthorized"})
1515
+ return
1516
+ content_type = self.headers.get("Content-Type", "").split(";", 1)[0]
1517
+ if content_type.strip().lower() != "application/json":
1518
+ self._json(415, {"error": "application_json_required"})
1519
+ return
1520
+ try:
1521
+ content_length = int(self.headers.get("Content-Length", ""))
1522
+ except ValueError:
1523
+ self._json(411, {"error": "content_length_required"})
1524
+ return
1525
+ if content_length < 0 or content_length > _MAX_MESSAGE_BYTES:
1526
+ self._json(413, {"error": "message_too_large"})
1527
+ return
1528
+ raw = self.rfile.read(content_length)
1529
+ if len(raw) != content_length:
1530
+ self._json(400, {"error": "incomplete_request"})
1531
+ return
1532
+ try:
1533
+ value = json.loads(raw.decode("utf-8"))
1534
+ except (UnicodeDecodeError, json.JSONDecodeError):
1535
+ self._json(400, {"error": "invalid_json"})
1536
+ return
1537
+ if not isinstance(value, dict) or set(value) != {
1538
+ "from",
1539
+ "to",
1540
+ "subject",
1541
+ "text",
1542
+ }:
1543
+ self._json(400, {"error": "invalid_message_fields"})
1544
+ return
1545
+ envelope_from = value.get("from")
1546
+ subject = value.get("subject")
1547
+ text = value.get("text")
1548
+ raw_recipients = value.get("to")
1549
+ recipients = (
1550
+ [raw_recipients] if isinstance(raw_recipients, str) else raw_recipients
1551
+ )
1552
+ if (
1553
+ envelope_from != sender
1554
+ or not isinstance(subject, str)
1555
+ or not isinstance(text, str)
1556
+ or not isinstance(recipients, list)
1557
+ or not 1 <= len(recipients) <= _MAX_RECIPIENTS
1558
+ or any(
1559
+ not isinstance(recipient, str)
1560
+ or not recipient
1561
+ or len(recipient) > 320
1562
+ or "@" not in recipient
1563
+ or "\r" in recipient
1564
+ or "\n" in recipient
1565
+ for recipient in recipients
1566
+ )
1567
+ or len(subject) > 998
1568
+ or "\r" in subject
1569
+ or "\n" in subject
1570
+ ):
1571
+ self._json(400, {"error": "invalid_message"})
1572
+ return
1573
+ try:
1574
+ encoded_text = text.encode("utf-8")
1575
+ subject.encode("utf-8")
1576
+ for recipient in recipients:
1577
+ recipient.encode("utf-8")
1578
+ except UnicodeEncodeError:
1579
+ self._json(400, {"error": "invalid_message"})
1580
+ return
1581
+ if len(encoded_text) > _MAX_MESSAGE_BYTES:
1582
+ self._json(413, {"error": "message_too_large"})
1583
+ return
1584
+ idempotency_key = self.headers.get("Idempotency-Key")
1585
+ if idempotency_key is not None and (
1586
+ not idempotency_key
1587
+ or len(idempotency_key) > 256
1588
+ or "\r" in idempotency_key
1589
+ or "\n" in idempotency_key
1590
+ ):
1591
+ self._json(400, {"error": "invalid_idempotency_key"})
1592
+ return
1593
+ try:
1594
+ accepted, provider_id = store.deliver_resend_style_to(
1595
+ namespace,
1596
+ envelope_from=envelope_from,
1597
+ recipients=recipients,
1598
+ subject=subject,
1599
+ text=text,
1600
+ idempotency_key=idempotency_key,
1601
+ )
1602
+ except MailboxCapacityError:
1603
+ self._json(429, {"error": "mailbox_capacity"})
1604
+ return
1605
+ except MailpitInfrastructureError:
1606
+ self._json(503, {"error": "mailpit_unavailable"})
1607
+ return
1608
+ if not accepted or provider_id is None:
1609
+ self._json(429, {"error": "mailbox_capacity"})
1610
+ return
1611
+ self._json(200, {"id": provider_id})
1612
+
1613
+ def log_message(self, format: str, *args: Any) -> None:
1614
+ return
1615
+
1616
+ return CandidateBootstrapHandler
1617
+
1618
+
1619
+ @dataclass(frozen=True, repr=False)
1620
+ class _Bootstrap:
1621
+ """What the site process is allowed to learn, and the token that gates it."""
1622
+
1623
+ token: str
1624
+ namespace: str
1625
+ capability: str
1626
+ smtp_host: str
1627
+ smtp_port: int
1628
+
1629
+ def __repr__(self) -> str:
1630
+ return f"_Bootstrap(namespace={self.namespace!r}, token=<redacted>)"
1631
+
1632
+ def payload(self) -> dict[str, Any]:
1633
+ return {
1634
+ "namespace": self.namespace,
1635
+ "capability": self.capability,
1636
+ "smtp_host": self.smtp_host,
1637
+ "smtp_port": self.smtp_port,
1638
+ }
1639
+
1640
+
1641
+ class _BootstrapSlot:
1642
+ """The identity ``/internal/bootstrap`` is serving right now.
1643
+
1644
+ A trial's mailbox identity is minted once and never moves, so the slot is
1645
+ written once and read forever. Reference capture is the exception that
1646
+ makes it a slot at all: it relaunches the reference between tasks, and each
1647
+ relaunch has to be its own trial -- same bootstrap token, because that is
1648
+ the site process's own credential and the site is what stays the same, but
1649
+ a namespace and capability nothing before it could have seen. Rotating
1650
+ behind the slot lets the operator do that without tearing down the listener
1651
+ the site is about to call.
1652
+ """
1653
+
1654
+ def __init__(self, bootstrap: "_Bootstrap | None" = None) -> None:
1655
+ self._lock = threading.Lock()
1656
+ self._value = bootstrap
1657
+
1658
+ def __repr__(self) -> str:
1659
+ return f"_BootstrapSlot({self._value!r})"
1660
+
1661
+ def get(self) -> "_Bootstrap | None":
1662
+ with self._lock:
1663
+ return self._value
1664
+
1665
+ def rotate(self, *, namespace: str, capability: str) -> "_Bootstrap":
1666
+ """Swap in a fresh namespace and capability, keeping the token."""
1667
+
1668
+ with self._lock:
1669
+ current = self._value
1670
+ if current is None:
1671
+ raise RuntimeError("this mailbox serves no bootstrap identity")
1672
+ rotated = replace(current, namespace=namespace, capability=capability)
1673
+ self._value = rotated
1674
+ return rotated
1675
+
1676
+
1677
+ def _inbox_handler(
1678
+ store: MailboxStore, namespace: str, token: str
1679
+ ) -> type[BaseHTTPRequestHandler]:
1680
+ """The agent-facing listener: one namespace, HTML only, no capability.
1681
+
1682
+ The namespace is closed over at construction, so there is no request-time
1683
+ parameter an agent could vary to reach a second mailbox. Requirement 5
1684
+ holds by construction rather than by a check that could be bypassed.
1685
+ """
1686
+
1687
+ inbox_path = "/inbox/" + urllib.parse.quote(token, safe="")
1688
+
1689
+ class InboxHandler(BaseHTTPRequestHandler):
1690
+ def _send(self, status: int, body: bytes, content_type: str) -> None:
1691
+ self.send_response(status)
1692
+ self.send_header("Content-Type", content_type)
1693
+ self.send_header("Content-Length", str(len(body)))
1694
+ # The inbox is per-trial and mutates; never let it be cached.
1695
+ self.send_header("Cache-Control", "no-store")
1696
+ self.send_header("Referrer-Policy", "no-referrer")
1697
+ self.end_headers()
1698
+ self.wfile.write(body)
1699
+
1700
+ def _not_found(self) -> None:
1701
+ self._send(
1702
+ 404,
1703
+ _document("Not found", "<p>No such page.</p>"),
1704
+ "text/html; charset=utf-8",
1705
+ )
1706
+
1707
+ def do_GET(self) -> None: # noqa: N802
1708
+ parsed = urllib.parse.urlsplit(self.path)
1709
+ if parsed.path == "/healthz":
1710
+ healthy = store.healthy()
1711
+ body = json.dumps(
1712
+ {"status": "ok" if healthy else "unavailable"}
1713
+ ).encode("utf-8")
1714
+ self._send(
1715
+ 200 if healthy else 503,
1716
+ body,
1717
+ "application/json; charset=utf-8",
1718
+ )
1719
+ return
1720
+ if parsed.path in {"", "/"}:
1721
+ self.send_response(302)
1722
+ self.send_header("Location", inbox_path)
1723
+ self.send_header("Content-Length", "0")
1724
+ self.end_headers()
1725
+ return
1726
+ parts = [
1727
+ urllib.parse.unquote(part) for part in parsed.path.strip("/").split("/")
1728
+ ]
1729
+ # Defence in depth for the shared-origin topology, where the path is
1730
+ # the only thing separating one trial's inbox from another's.
1731
+ if len(parts) < 2 or parts[0] != "inbox":
1732
+ self._not_found()
1733
+ return
1734
+ if not hmac.compare_digest(token, parts[1]):
1735
+ self._not_found()
1736
+ return
1737
+ try:
1738
+ values = store.messages(namespace)
1739
+ except MailpitInfrastructureError:
1740
+ body = json.dumps({"status": "unavailable"}).encode("utf-8")
1741
+ self._send(503, body, "application/json; charset=utf-8")
1742
+ return
1743
+ if len(parts) == 2:
1744
+ self._send(
1745
+ 200,
1746
+ render_inbox(values, base_path=inbox_path),
1747
+ "text/html; charset=utf-8",
1748
+ )
1749
+ return
1750
+ if len(parts) == 4 and parts[2] == "messages":
1751
+ try:
1752
+ identifier = int(parts[3])
1753
+ except ValueError:
1754
+ self._not_found()
1755
+ return
1756
+ for item in values:
1757
+ if int(item["id"]) == identifier:
1758
+ self._send(
1759
+ 200,
1760
+ render_message(item, base_path=inbox_path),
1761
+ "text/html; charset=utf-8",
1762
+ )
1763
+ return
1764
+ self._not_found()
1765
+
1766
+ def log_message(self, format: str, *args: Any) -> None:
1767
+ return
1768
+
1769
+ return InboxHandler
1770
+
1771
+
1772
+ class LocalMailboxSidecar:
1773
+ """A loopback-only SMTP and Inbox API pair with namespace isolation."""
1774
+
1775
+ def __init__(
1776
+ self,
1777
+ *,
1778
+ smtp_port: int = 0,
1779
+ http_port: int = 0,
1780
+ bind_host: str = "127.0.0.1",
1781
+ inbox_port: int | None = None,
1782
+ inbox_bind_host: str | None = None,
1783
+ inbox_namespace: str | None = None,
1784
+ inbox_token: str | None = None,
1785
+ bootstrap: "_Bootstrap | None" = None,
1786
+ mailpit_client: MailpitClient,
1787
+ ) -> None:
1788
+ self.store = MailboxStore(mailpit_client=mailpit_client)
1789
+ self._bootstrap = _BootstrapSlot(bootstrap)
1790
+ self.smtp = _SmtpServer((bind_host, smtp_port), self.store)
1791
+ self.http = _HttpServer(
1792
+ (bind_host, http_port), _http_handler(self.store, self._bootstrap)
1793
+ )
1794
+ self.inbox: _HttpServer | None = None
1795
+ self._inbox_token = inbox_token
1796
+ if inbox_namespace is not None or inbox_token is not None:
1797
+ if not inbox_namespace or not inbox_token:
1798
+ raise ValueError("an inbox listener needs both namespace and token")
1799
+ self.inbox = _HttpServer(
1800
+ (inbox_bind_host or bind_host, inbox_port or 0),
1801
+ _inbox_handler(self.store, inbox_namespace, inbox_token),
1802
+ )
1803
+ self._threads: list[threading.Thread] = []
1804
+
1805
+ @property
1806
+ def smtp_port(self) -> int:
1807
+ return int(self.smtp.server_address[1])
1808
+
1809
+ @property
1810
+ def http_port(self) -> int:
1811
+ return int(self.http.server_address[1])
1812
+
1813
+ @property
1814
+ def inbox_port(self) -> int:
1815
+ if self.inbox is None:
1816
+ raise RuntimeError("this sidecar has no inbox listener")
1817
+ return int(self.inbox.server_address[1])
1818
+
1819
+ @property
1820
+ def url(self) -> str:
1821
+ return f"http://127.0.0.1:{self.http_port}"
1822
+
1823
+ @property
1824
+ def inbox_url(self) -> str:
1825
+ """The bare origin an agent is handed. It carries no secret."""
1826
+
1827
+ return f"http://127.0.0.1:{self.inbox_port}"
1828
+
1829
+ @property
1830
+ def _servers(self) -> tuple[Any, ...]:
1831
+ return (
1832
+ (self.smtp, self.http)
1833
+ if self.inbox is None
1834
+ else (
1835
+ self.smtp,
1836
+ self.http,
1837
+ self.inbox,
1838
+ )
1839
+ )
1840
+
1841
+ def register_namespace(self, namespace: str, capability: str) -> None:
1842
+ """Bind one opaque namespace to its unguessable per-worker capability."""
1843
+
1844
+ self.store.register(namespace, capability)
1845
+
1846
+ def rotate_bootstrap(self, namespace: str, capability: str) -> None:
1847
+ """Point ``/internal/bootstrap`` at a freshly minted namespace.
1848
+
1849
+ Registration happens first on purpose: a site that fetched the new
1850
+ identity and sent before the store knew it would have its message
1851
+ dropped at the SMTP door, which reads as a flaky mailbox rather than
1852
+ the ordering bug it is.
1853
+ """
1854
+
1855
+ previous = self._bootstrap.get()
1856
+ self.register_namespace(namespace, capability)
1857
+ # Candidate trials route direct SMTP into one fixed namespace. Mirror
1858
+ # that ABI during paired reference capture so runtimes using the direct
1859
+ # writer do not need the structured transport's namespace headers.
1860
+ self.smtp.fixed_namespace = namespace
1861
+ self._bootstrap.rotate(namespace=namespace, capability=capability)
1862
+ if previous is not None and previous.namespace != namespace:
1863
+ self.store.seal_namespace(previous.namespace)
1864
+
1865
+ def start(self) -> "LocalMailboxSidecar":
1866
+ if not self.store.healthy():
1867
+ raise MailpitInfrastructureError("Mailpit is not ready")
1868
+ for server in self._servers:
1869
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
1870
+ thread.start()
1871
+ self._threads.append(thread)
1872
+ return self
1873
+
1874
+ def close(self) -> None:
1875
+ for server in self._servers:
1876
+ server.shutdown()
1877
+ server.server_close()
1878
+ for thread in self._threads:
1879
+ thread.join(timeout=5)
1880
+ self._threads.clear()
1881
+ self.store.destroy_namespaces()
1882
+
1883
+ def __enter__(self) -> "LocalMailboxSidecar":
1884
+ return self.start()
1885
+
1886
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
1887
+ self.close()
1888
+
1889
+
1890
+ class CandidateMailboxTrial:
1891
+ """One formal case's write-only candidate mailbox and trusted reader.
1892
+
1893
+ Candidate code prefers the Resend-style ``POST /emails`` endpoint and may
1894
+ use ``smtp``/``bootstrap`` for compatibility. Both writers are fixed to
1895
+ this trial's namespace. The verifier API listens on a third, unadvertised
1896
+ port that the candidate sandbox does not permit, and it uses a distinct
1897
+ read credential that never enters the candidate environment.
1898
+ """
1899
+
1900
+ def __init__(
1901
+ self,
1902
+ *,
1903
+ bind_host: str = "127.0.0.1",
1904
+ mailpit_client: MailpitClient | None = None,
1905
+ ) -> None:
1906
+ self._runtime = None if mailpit_client is not None else EphemeralMailpit()
1907
+ storage_client = (
1908
+ mailpit_client
1909
+ if mailpit_client is not None
1910
+ else self._runtime.client
1911
+ if self._runtime is not None
1912
+ else None
1913
+ )
1914
+ namespace, read_credential, _inbox_token = _mint_identity()
1915
+ self.namespace = namespace
1916
+ self.read_credential = read_credential
1917
+ self._write_capability = secrets.token_hex(32)
1918
+ self._bootstrap_token = secrets.token_hex(32)
1919
+ self._mail_api_token = secrets.token_hex(32)
1920
+ self._sender = CANDIDATE_MAIL_SENDER
1921
+ self.store = MailboxStore(mailpit_client=storage_client)
1922
+ self.store.register(
1923
+ namespace,
1924
+ read_credential,
1925
+ allowed_from=(self._sender,),
1926
+ )
1927
+ self.smtp = _SmtpServer(
1928
+ (bind_host, 0),
1929
+ self.store,
1930
+ fixed_namespace=namespace,
1931
+ )
1932
+ self.http = _HttpServer(
1933
+ (bind_host, 0),
1934
+ _http_handler(self.store),
1935
+ )
1936
+ self.bootstrap = _HttpServer(
1937
+ (bind_host, 0),
1938
+ _candidate_bootstrap_handler(
1939
+ store=self.store,
1940
+ bootstrap_token=self._bootstrap_token,
1941
+ mail_api_token=self._mail_api_token,
1942
+ namespace=namespace,
1943
+ capability=self._write_capability,
1944
+ smtp_host=bind_host,
1945
+ smtp_port=self.smtp_port,
1946
+ sender=self._sender,
1947
+ ),
1948
+ )
1949
+ self._threads: list[threading.Thread] = []
1950
+
1951
+ @property
1952
+ def smtp_port(self) -> int:
1953
+ return int(self.smtp.server_address[1])
1954
+
1955
+ @property
1956
+ def http_port(self) -> int:
1957
+ return int(self.http.server_address[1])
1958
+
1959
+ @property
1960
+ def bootstrap_port(self) -> int:
1961
+ return int(self.bootstrap.server_address[1])
1962
+
1963
+ @property
1964
+ def url(self) -> str:
1965
+ return f"http://127.0.0.1:{self.http_port}"
1966
+
1967
+ @property
1968
+ def candidate_environment(self) -> dict[str, str]:
1969
+ """The complete optional mail ABI handed to the candidate runtime."""
1970
+
1971
+ return {
1972
+ "WEBSITEBENCH_MAIL_API_URL": (
1973
+ f"http://127.0.0.1:{self.bootstrap_port}/emails"
1974
+ ),
1975
+ "WEBSITEBENCH_MAIL_API_TOKEN": self._mail_api_token,
1976
+ "WEBSITEBENCH_MAIL_FROM": self._sender,
1977
+ "WEBSITEBENCH_SMTP_HOST": "127.0.0.1",
1978
+ "WEBSITEBENCH_SMTP_PORT": str(self.smtp_port),
1979
+ "WEBSITEBENCH_SMTP_FROM": self._sender,
1980
+ # Compatibility seam for candidates using websitebench.site_backend.
1981
+ # It serves write coordinates only and has no read routes.
1982
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL": (
1983
+ f"http://127.0.0.1:{self.bootstrap_port}/internal/bootstrap"
1984
+ ),
1985
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN": self._bootstrap_token,
1986
+ }
1987
+
1988
+ @property
1989
+ def candidate_connect_ports(self) -> frozenset[int]:
1990
+ return frozenset({self.smtp_port, self.bootstrap_port})
1991
+
1992
+ def start(self) -> "CandidateMailboxTrial":
1993
+ if self._runtime is not None:
1994
+ try:
1995
+ self._runtime.start()
1996
+ except BaseException:
1997
+ for server in (self.smtp, self.http, self.bootstrap):
1998
+ server.server_close()
1999
+ raise
2000
+ if not self.store.healthy():
2001
+ for server in (self.smtp, self.http, self.bootstrap):
2002
+ server.server_close()
2003
+ if self._runtime is not None:
2004
+ self._runtime.close()
2005
+ raise MailpitInfrastructureError("Mailpit is not ready")
2006
+ for server in (self.smtp, self.http, self.bootstrap):
2007
+ thread = threading.Thread(
2008
+ target=server.serve_forever,
2009
+ name=f"candidate-mailbox-{server.server_address[1]}",
2010
+ daemon=True,
2011
+ )
2012
+ thread.start()
2013
+ self._threads.append(thread)
2014
+ return self
2015
+
2016
+ def close(self) -> None:
2017
+ for server in (self.smtp, self.http, self.bootstrap):
2018
+ server.shutdown()
2019
+ server.server_close()
2020
+ for thread in self._threads:
2021
+ thread.join(timeout=5)
2022
+ self._threads.clear()
2023
+ self.store.destroy_namespaces()
2024
+ if self._runtime is not None:
2025
+ self._runtime.close()
2026
+
2027
+ def __enter__(self) -> "CandidateMailboxTrial":
2028
+ return self.start()
2029
+
2030
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
2031
+ self.close()
2032
+
2033
+
2034
+ def _candidate_environment_problem(
2035
+ environment: Mapping[str, str], private_values: tuple[str, ...]
2036
+ ) -> str | None:
2037
+ """Return why ``environment`` may not be handed to a candidate, or ``None``.
2038
+
2039
+ The candidate mail ABI is a closed set of names carrying loopback
2040
+ coordinates only. A name outside the set, a Mailpit control variable, or
2041
+ any value naming the evaluator's own Mailpit socket would hand a candidate
2042
+ the trusted store instead of its write-only door.
2043
+ """
2044
+
2045
+ unknown = sorted(set(environment) - CANDIDATE_MAIL_ENVIRONMENT)
2046
+ if unknown:
2047
+ return f"candidate mailbox environment has unknown names: {unknown}"
2048
+ leaked = any(
2049
+ name.startswith("WEBSITEBENCH_MAILPIT_")
2050
+ or MAILPIT_RUNTIME_DIR in str(value)
2051
+ or any(private and private in str(value) for private in private_values)
2052
+ for name, value in environment.items()
2053
+ )
2054
+ if leaked:
2055
+ return "candidate mailbox environment exposed the Mailpit UDS"
2056
+ return None
2057
+
2058
+
2059
+ class MailTrial:
2060
+ """One case's candidate mailbox, as the rest of the evaluator sees it.
2061
+
2062
+ The candidate environment handed out here is already proved to be the
2063
+ closed mail ABI and free of evaluator-side coordinates, so no caller
2064
+ re-scans it. Reads stay on the trusted side: :meth:`deliveries` is the
2065
+ only way out of the store and it never leaves this trial's namespace.
2066
+ """
2067
+
2068
+ def __init__(
2069
+ self,
2070
+ trial: CandidateMailboxTrial,
2071
+ *,
2072
+ private_values: tuple[str, ...] = (),
2073
+ ) -> None:
2074
+ environment = dict(trial.candidate_environment)
2075
+ problem = _candidate_environment_problem(environment, private_values)
2076
+ if problem is not None:
2077
+ trial.close()
2078
+ raise MailpitInfrastructureError(problem)
2079
+ self._trial = trial
2080
+ self._environment = environment
2081
+
2082
+ @property
2083
+ def namespace(self) -> str:
2084
+ return self._trial.namespace
2085
+
2086
+ @property
2087
+ def read_credential(self) -> str:
2088
+ return self._trial.read_credential
2089
+
2090
+ @property
2091
+ def url(self) -> str:
2092
+ """The verifier-only reader origin; the candidate cannot reach it."""
2093
+
2094
+ return self._trial.url
2095
+
2096
+ @property
2097
+ def http_port(self) -> int:
2098
+ return self._trial.http_port
2099
+
2100
+ @property
2101
+ def store(self) -> MailboxStore:
2102
+ return self._trial.store
2103
+
2104
+ @property
2105
+ def candidate_environment(self) -> dict[str, str]:
2106
+ """The complete optional mail ABI this case's candidate receives."""
2107
+
2108
+ return dict(self._environment)
2109
+
2110
+ @property
2111
+ def candidate_connect_ports(self) -> frozenset[int]:
2112
+ """The loopback ports the candidate sandbox may connect out to."""
2113
+
2114
+ return self._trial.candidate_connect_ports
2115
+
2116
+ def healthy(self) -> bool:
2117
+ """Whether the backing store still answers, so an outage is not scored."""
2118
+
2119
+ return self._trial.store.healthy()
2120
+
2121
+ def deliveries(self) -> list[dict[str, Any]]:
2122
+ """Every message this trial's namespace received, newest first."""
2123
+
2124
+ return self._trial.store.messages(self._trial.namespace)
2125
+
2126
+ def close(self) -> None:
2127
+ self._trial.close()
2128
+
2129
+ def __enter__(self) -> "MailTrial":
2130
+ return self
2131
+
2132
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
2133
+ self.close()
2134
+
2135
+
2136
+ class MailPlane:
2137
+ """The evaluator's single door to Mailpit.
2138
+
2139
+ Everything that knows a socket path, a container lifetime, a namespace or
2140
+ the candidate mail ABI lives behind this facade. ``formal``,
2141
+ ``trusted_check`` and ``capture`` ask the plane for a trial, a runner
2142
+ passthrough or an authoring gateway; they never build a Mailpit client,
2143
+ read a Mailpit variable, or inspect what they hand a candidate.
2144
+ """
2145
+
2146
+ def __init__(
2147
+ self, client: MailpitClient, *, runtime: EphemeralMailpit | None = None
2148
+ ) -> None:
2149
+ self.client = client
2150
+ self._runtime = runtime
2151
+
2152
+ @staticmethod
2153
+ def _configured_socket(env: Mapping[str, str]) -> str:
2154
+ """The evaluator's only read of :data:`MAILPIT_HTTP_SOCKET_ENV`."""
2155
+
2156
+ return str(env.get(MAILPIT_HTTP_SOCKET_ENV, "") or "").strip()
2157
+
2158
+ @classmethod
2159
+ def from_environment(cls, env: Mapping[str, str] = os.environ) -> "MailPlane":
2160
+ """Open the Mailpit the environment advertises.
2161
+
2162
+ A missing variable and an unhealthy Mailpit are the same answer to the
2163
+ caller: this process has no mail plane.
2164
+ """
2165
+
2166
+ socket_path = cls._configured_socket(env)
2167
+ if not socket_path:
2168
+ raise MailInfrastructureUnavailable(
2169
+ f"{MAILPIT_HTTP_SOCKET_ENV} is not configured"
2170
+ )
2171
+ client = MailpitClient(socket_path)
2172
+ if not client.ready():
2173
+ raise MailInfrastructureUnavailable(
2174
+ "Mailpit is not ready on its configured HTTP socket"
2175
+ )
2176
+ return cls(client)
2177
+
2178
+ @classmethod
2179
+ def ephemeral(
2180
+ cls, runtime_dir: str | os.PathLike[str] | None = None
2181
+ ) -> "MailPlane":
2182
+ """Start a private, networkless Mailpit this plane owns and will stop.
2183
+
2184
+ Host-side only: a Harbor trial has no Docker binary, so a scored run
2185
+ always goes through :meth:`from_environment` instead.
2186
+ """
2187
+
2188
+ runtime = EphemeralMailpit(runtime_dir=runtime_dir).start()
2189
+ return cls(runtime.client, runtime=runtime)
2190
+
2191
+ @classmethod
2192
+ def open(
2193
+ cls,
2194
+ *,
2195
+ runtime_dir: str | os.PathLike[str] | None = None,
2196
+ env: Mapping[str, str] = os.environ,
2197
+ ) -> "MailPlane":
2198
+ """Prefer the advertised Mailpit; start a private one when there is none."""
2199
+
2200
+ if cls._configured_socket(env):
2201
+ return cls.from_environment(env)
2202
+ return cls.ephemeral(runtime_dir=runtime_dir)
2203
+
2204
+ @property
2205
+ def socket_path(self) -> str:
2206
+ return self.client.socket_path
2207
+
2208
+ @property
2209
+ def owns_runtime(self) -> bool:
2210
+ """Whether closing this plane stops a Mailpit container."""
2211
+
2212
+ return self._runtime is not None
2213
+
2214
+ def healthy(self) -> bool:
2215
+ return self.client.ready()
2216
+
2217
+ def trial(self, *, bind_host: str = "127.0.0.1") -> MailTrial:
2218
+ """Start one case's write-only candidate mailbox on this plane.
2219
+
2220
+ The result is a context manager, so a caller that owns the mailbox for
2221
+ the length of a ``with`` block needs no other cleanup; a caller that
2222
+ owns it for the length of a case calls :meth:`MailTrial.close`.
2223
+ """
2224
+
2225
+ trial = CandidateMailboxTrial(
2226
+ bind_host=bind_host, mailpit_client=self.client
2227
+ ).start()
2228
+ return MailTrial(trial, private_values=(self.socket_path,))
2229
+
2230
+ def runner_environment(self, base: Mapping[str, str]) -> dict[str, str]:
2231
+ """Add to ``base`` exactly what a child verifier runner needs.
2232
+
2233
+ A trusted CI/CD runner is launched with a scrubbed environment and has
2234
+ to find the same Mailpit; that is one variable, and no other mail
2235
+ coordinate crosses the boundary.
2236
+ """
2237
+
2238
+ return {**dict(base), MAILPIT_HTTP_SOCKET_ENV: self.socket_path}
2239
+
2240
+ def authoring_gateway(
2241
+ self,
2242
+ *,
2243
+ namespace: str,
2244
+ capability: str,
2245
+ bootstrap_token: str,
2246
+ smtp_port: int,
2247
+ bind_host: str = "127.0.0.1",
2248
+ ) -> LocalMailboxSidecar:
2249
+ """Expose the stable loopback writer ABI over this plane, for authoring.
2250
+
2251
+ Capture hands a reference site the same SMTP/bootstrap door a scored
2252
+ candidate gets, so what capture exercises is what a trial will run.
2253
+ There is intentionally no in-memory fallback.
2254
+ """
2255
+
2256
+ if not self.client.ready():
2257
+ raise MailInfrastructureUnavailable("Mailpit is not ready for capture")
2258
+ sidecar = LocalMailboxSidecar(
2259
+ smtp_port=smtp_port,
2260
+ bind_host=bind_host,
2261
+ bootstrap=_Bootstrap(
2262
+ token=bootstrap_token,
2263
+ namespace=namespace,
2264
+ capability=capability,
2265
+ smtp_host=bind_host,
2266
+ smtp_port=smtp_port,
2267
+ ),
2268
+ mailpit_client=self.client,
2269
+ )
2270
+ sidecar.register_namespace(namespace, capability)
2271
+ sidecar.start()
2272
+ return sidecar
2273
+
2274
+ def close(self) -> None:
2275
+ runtime, self._runtime = self._runtime, None
2276
+ if runtime is not None:
2277
+ runtime.close()
2278
+
2279
+ def __enter__(self) -> "MailPlane":
2280
+ return self
2281
+
2282
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
2283
+ self.close()
2284
+
2285
+
2286
+ def authoring_environment(
2287
+ sidecar: LocalMailboxSidecar,
2288
+ *,
2289
+ namespace: str,
2290
+ capability: str,
2291
+ bootstrap_token: str,
2292
+ smtp_port: int,
2293
+ smtp_host: str = "127.0.0.1",
2294
+ ) -> dict[str, str]:
2295
+ """The complete mail ABI an authoring capture exports around a reference site.
2296
+
2297
+ It is a superset of the candidate ABI: authoring also owns the read
2298
+ credential and the namespace, which a scored candidate never sees. The
2299
+ names are exactly :data:`AUTHORING_MAIL_ENVIRONMENT`.
2300
+ """
2301
+
2302
+ gateway = sidecar.url.rstrip("/")
2303
+ return {
2304
+ "WEBSITEBENCH_MAILBOX_URL": sidecar.url,
2305
+ "WEBSITEBENCH_MAILBOX_ALLOWLIST": "",
2306
+ "WEBSITEBENCH_MAILBOX_CREDENTIAL": capability,
2307
+ "WEBSITEBENCH_MAILBOX_NAMESPACE": namespace,
2308
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL": f"{gateway}/internal/bootstrap",
2309
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN": bootstrap_token,
2310
+ "WEBSITEBENCH_SMTP_HOST": smtp_host,
2311
+ "WEBSITEBENCH_SMTP_PORT": str(smtp_port),
2312
+ # Paired capture must present the same sender ABI as a formal candidate
2313
+ # trial: some runtimes pin this exact suffix before opening SMTP, so a
2314
+ # site-specific authoring sender would disable their only mail path.
2315
+ "WEBSITEBENCH_MAIL_API_URL": f"{gateway}/emails",
2316
+ "WEBSITEBENCH_MAIL_API_TOKEN": bootstrap_token,
2317
+ "WEBSITEBENCH_MAIL_FROM": CANDIDATE_MAIL_SENDER,
2318
+ "WEBSITEBENCH_SMTP_FROM": CANDIDATE_MAIL_SENDER,
2319
+ }
2320
+
2321
+
2322
+ def _mint_identity() -> tuple[str, str, str]:
2323
+ """Mint one trial's mailbox identity.
2324
+
2325
+ Minted from ``secrets``, never derived from the public ``seed-<seed>``
2326
+ trial ID, while the inbox token doubles as the browser's access token.
2327
+ Determinism is not lost, because scoring reads no mail.
2328
+ """
2329
+
2330
+ return (
2331
+ f"trial-{secrets.token_hex(16)}",
2332
+ secrets.token_hex(32),
2333
+ secrets.token_urlsafe(32),
2334
+ )
2335
+
2336
+
2337
+ def main(argv: list[str] | None = None) -> int:
2338
+ """Run one trial's mailbox, minting that trial's identity at boot.
2339
+
2340
+ ``materialize`` runs once per *bundle*; a trial is one *run* of that
2341
+ bundle, so a value written into ``docker-compose.yaml`` can never be
2342
+ per-trial. The identity is therefore minted here, by the one process that
2343
+ owns it, and each party learns only its own half over the listener it is
2344
+ allowed to reach: the site reads ``/internal/bootstrap`` on the API
2345
+ listener, the agent gets a bare inbox URL and no credential at all.
2346
+
2347
+ The values come from ``secrets`` rather than from the public
2348
+ ``seed-<seed>`` trial ID. Determinism is not lost, because formal scoring
2349
+ never reads mail.
2350
+ """
2351
+
2352
+ import argparse
2353
+
2354
+ parser = argparse.ArgumentParser(prog="websitebench-local-mailbox")
2355
+ parser.add_argument("--smtp-port", type=int, default=1025)
2356
+ parser.add_argument("--http-port", type=int, default=8025)
2357
+ parser.add_argument("--inbox-port", type=int, default=8026)
2358
+ parser.add_argument("--bind-host", default="127.0.0.1")
2359
+ parser.add_argument(
2360
+ "--api-bind-host",
2361
+ default=None,
2362
+ help="interface for the SMTP and JSON API listeners (defaults to --bind-host)",
2363
+ )
2364
+ parser.add_argument(
2365
+ "--inbox-bind-host",
2366
+ default=None,
2367
+ help="interface for the agent inbox listener (defaults to --bind-host)",
2368
+ )
2369
+ args = parser.parse_args(argv)
2370
+
2371
+ api_bind = (
2372
+ args.api_bind_host
2373
+ or os.environ.get("WEBSITEBENCH_MAILBOX_API_BIND")
2374
+ or args.bind_host
2375
+ )
2376
+ inbox_bind = (
2377
+ args.inbox_bind_host
2378
+ or os.environ.get("WEBSITEBENCH_MAILBOX_INBOX_BIND")
2379
+ or args.bind_host
2380
+ )
2381
+ smtp_advertise_host = (
2382
+ os.environ.get("WEBSITEBENCH_MAILBOX_SMTP_ADVERTISE_HOST", "").strip()
2383
+ or api_bind
2384
+ )
2385
+
2386
+ namespace, capability, inbox_token = _mint_identity()
2387
+ bootstrap_token = os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN", "")
2388
+ if len(bootstrap_token) < 32:
2389
+ raise SystemExit(
2390
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN must be at least 32 characters"
2391
+ )
2392
+ try:
2393
+ mailpit_client = MailPlane.from_environment().client
2394
+ except MailInfrastructureUnavailable as error:
2395
+ # The sidecar discovers its store the same way the evaluator does, and
2396
+ # refuses to serve an in-memory production mailbox when there is none.
2397
+ raise SystemExit(f"{error}; refusing an in-memory production mailbox")
2398
+
2399
+ stopped = threading.Event()
2400
+ signal.signal(signal.SIGTERM, lambda _signum, _frame: stopped.set())
2401
+ signal.signal(signal.SIGINT, lambda _signum, _frame: stopped.set())
2402
+ sidecar = LocalMailboxSidecar(
2403
+ smtp_port=args.smtp_port,
2404
+ http_port=args.http_port,
2405
+ bind_host=api_bind,
2406
+ inbox_port=args.inbox_port,
2407
+ inbox_bind_host=inbox_bind,
2408
+ inbox_namespace=namespace,
2409
+ inbox_token=inbox_token,
2410
+ bootstrap=_Bootstrap(
2411
+ token=bootstrap_token,
2412
+ namespace=namespace,
2413
+ capability=capability,
2414
+ smtp_host=smtp_advertise_host,
2415
+ smtp_port=args.smtp_port,
2416
+ ),
2417
+ mailpit_client=mailpit_client,
2418
+ )
2419
+ sidecar.register_namespace(namespace, capability)
2420
+ sidecar.start()
2421
+ # The inbox path is the agent's entry point and holds no secret beyond the
2422
+ # token that scopes it to this trial; nothing else about the trial is
2423
+ # printed, and the capability never is.
2424
+ print(f"inbox listening on {inbox_bind}:{args.inbox_port}", flush=True)
2425
+ try:
2426
+ stopped.wait()
2427
+ finally:
2428
+ sidecar.close()
2429
+ return 0
2430
+
2431
+
2432
+ if __name__ == "__main__":
2433
+ raise SystemExit(main(sys.argv[1:]))
tasks/aspca-pet-insurance/environment/reference/.websitebench-reference-tls/ca.crt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIDSzCCAjOgAwIBAgIJV1NCSEFSQk9SMA0GCSqGSIb3DQEBCwUAMDExLzAtBgNV
3
+ BAMMJldlYnNpdGVCZW5jaCBIYXJib3IgTG9jYWwgUmVmZXJlbmNlIENBMB4XDTI2
4
+ MDgyMjEzMDg1NloXDTQ2MDgyMjEzMDg1NlowMTEvMC0GA1UEAwwmV2Vic2l0ZUJl
5
+ bmNoIEhhcmJvciBMb2NhbCBSZWZlcmVuY2UgQ0EwggEiMA0GCSqGSIb3DQEBAQUA
6
+ A4IBDwAwggEKAoIBAQCnBZES7bXJo/hajL5T54GDV/FLmQxmk0dGN+aPwRrgpiN6
7
+ syddg/krh/dhiUzfxgJV+6ajnYuYyQ4BVo1rQGY0va95T8cjcHgC7EyEAaDUZF+i
8
+ qo3v/ucMmquZodezEkghWz6FDcGH3dDtz0bQyYgoGQKnioeYXsVlfvIzXJpE1VTW
9
+ iGUH83/APzvPInZ5jRRrCEnqj1WtSoi+Yycs/eaYueDomoZeT3xvK5MTz6tC6EvW
10
+ hAh8qyv2DjPZUSToiZH23X6qXYRkKkLDXHWHfhamRwlFoh9pp2s4D+Cq/Wke+o2f
11
+ /cj8KvAkTnMo4iMmZFpb/NRaGjhfy8UBPuM7SwMJAgMBAAGjZjBkMB0GA1UdDgQW
12
+ BBQn+U1eizvlvKbfavSxHoXFYQ/UfTAfBgNVHSMEGDAWgBQn+U1eizvlvKbfavSx
13
+ HoXFYQ/UfTASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjANBgkq
14
+ hkiG9w0BAQsFAAOCAQEAoSC3zzZEAs2eigloiDkdeh98+2cPmcs44TG+TU6sq6SP
15
+ EBEgHg/c6yzh74UijEImksT9aZ+LxtTNM+nfNFzWku1T3R7gSimP5TSnC4rTEhfM
16
+ Ih8fMoUbcAe/uFwVE9UHn/QQNsqRg6hg2jdUlmwr206e62/eBQXDNeuLcapAxcdU
17
+ VYno4HNi5gAaakS2dM/IgiorRqM7SVT+s8B9Fl0mzMdRNCUeOOU4q8zGtQGp4IV+
18
+ x/LZIMsLogP2Rpks8ecyanRSXYpGbqpZ+14rcO5bdWQ7P8B/sFssT3b1mR3H/aVh
19
+ yZycwgzCbkbdMaxyz2Vm/c7PVb3so5Xb98jufp2L9A==
20
+ -----END CERTIFICATE-----
tasks/aspca-pet-insurance/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/aspca-pet-insurance/environment/reference/.websitebench-reference-tls/reference.key ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN PRIVATE KEY-----
2
+ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDNJXc7onbK78Ri
3
+ LSAe3LjIeko9xNumYRejoB+kKFGLBL4U7vY+02coiXpne4e1CMzUVzRiaQ9i9XHB
4
+ e0Oq4CR1HW7wzMRV8XVM5/dVq+j0vZVarZbITyHSWHwypa7yPL7o/kBekdwi8ncd
5
+ Uy/mhYqw7sOdM4Nq0ifj+lcJ/rwSqjvcML4//4THY9CP5iB2YT+U+Z7F/JfLOJFZ
6
+ 12l4SglxRDf1awDLJpGfpX0kRgW7jYuWf49C5VcPjggTRl1WYy1qrgaNIFu75sre
7
+ sXYkDgRxuLiXfc/6wNwykh9fQo+GNFqBGy2lC8Ey425m4XEROraenAGMqVMfxJsJ
8
+ 5wjqRhlVAgMBAAECggEAIdiyWyGzKUjVVSBeWhEvII6CpL3Pwpvmz02KIuavC3l5
9
+ FhGWCagN71N9YUjxizYcO1V29FyimABoaBR7BdyMz1DPnsWeCBL6ODnWZilimkyU
10
+ MX2N8NcTfLWyKhYJbviERAM84g19LTvlWK6Cqu0yBH6kQhG/dzacs8G4LhM7+vUU
11
+ +43RFW4GFmYDXtfUEZuZ8IRzWxDdXQ9yVnKxKrhuYj4/UYgTTspOx87m++Ft6BJR
12
+ IQRw1dZ7dE2R8pZbYQdOXRXSjf59KisJSr9N2+mYZYNUWWv7zF8bmD17hxtsQk9C
13
+ wesyN3DqzoLHK3GfoG3ZuA+v3aEVKHRk8Tc1aosYyQKBgQD0ddALajm0XHictsG3
14
+ /JTC1RL0nj+SoVVgYdWccA7VUs68Cbpq1RYzUawDOhYlQjbJBJTQ9z5kwWP+50vH
15
+ VPjpU/cMFx4d63WwDEXcC2o09mh3OjkfujUdRroyn6rJgKXuSJeMAz0JrGCTIS91
16
+ 0t2cmoSqKSIaN2oU5IsONLg6SQKBgQDW1JBCiP1c6tYi9wKpEJLjlRqSIsLgLApg
17
+ h6o1sWFfUrbQ21ORS1jhLnCkJsyLWoyZkUgwaXbXoLoVw3kIdPLJ8TI1FJ+ZPYdt
18
+ EJcvvVjmJIrcq9um1qoKKpmiKuwRe4/OYdFQcdTRwob1wpoAi7T9CfiNgo53WHsR
19
+ mviPzSEGrQKBgQDnpL+YIXc+niU4MsFL6463NBq7Kz0IX9I7+1jj3RdhMw9tBTbd
20
+ Rr+7r1d001Tqx1yMjMfLX42DAfIUN+4Jm04mIwdFMJ68MUMap/aGtVZVi2ygFc7N
21
+ brAn5r5HfB7kw//31FeuN99dzDbTFC4Z0s9mNtEhQMrs1rexxoKx2mj76QKBgBi5
22
+ AZkGltG4nMgNURsPszfJkvM6WN7fcppFQotHTINhy3QhqW5RE3tmksPxSxzGYOPT
23
+ WlFn8atC7edPRYB5pO8keLivFObXs9wTSrLNwYtKrUhT5sU+cvcUi/WjpuMkKxp/
24
+ G018rBcvocRqjrp9WWi9WwM+ARMu9YrDINO7sY9JAoGBAJlTUtKVOOuaujK53Vnq
25
+ 2O5FrC/HcsUa1nTRO/WSDyUjGWeqAr75yi05UD6M2tTov1uGbtg47Q5n6eqjVyy3
26
+ FTYmG+lVbVXjVcOFuUhZxJhELsHulsJ1LRPAJccC0Uci8IZ8rfIZyREn7tKpBJI4
27
+ 4s+BQ5R45Cv3eUi2JU/xuAtK
28
+ -----END PRIVATE KEY-----
tasks/aspca-pet-insurance/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/aspca-pet-insurance/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-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/aspca-pet-insurance/environment/reference/backend/model.json ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "offline-clone.backend-model.v1",
3
+ "site_id": "aspca-pet-insurance",
4
+ "status": "verified",
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": "verified",
18
+ "evidence": [
19
+ "clone/tests/test_backend_lifecycle.py::test_database_path_and_migrations_are_site_bound_and_idempotent"
20
+ ]
21
+ },
22
+ {
23
+ "obligation": "schema-migration",
24
+ "status": "verified",
25
+ "evidence": [
26
+ "clone/tests/test_backend_lifecycle.py::test_database_path_and_migrations_are_site_bound_and_idempotent"
27
+ ]
28
+ },
29
+ {
30
+ "obligation": "deterministic-reset",
31
+ "status": "verified",
32
+ "evidence": [
33
+ "clone/tests/test_backend_lifecycle.py::test_reset_is_deterministic_and_preserves_the_schema",
34
+ "clone/tests/test_app_surface.py::test_admin_reset_requires_token"
35
+ ]
36
+ },
37
+ {
38
+ "obligation": "restart-persistence",
39
+ "status": "verified",
40
+ "evidence": [
41
+ "clone/tests/test_backend_lifecycle.py::test_quote_state_survives_service_restart",
42
+ "harbor/instances/aspca-pet-insurance/fixtures/hidden/cicd-suite.json#platform::deploy/restart-persistence"
43
+ ]
44
+ },
45
+ {
46
+ "obligation": "backup-restore",
47
+ "status": "verified",
48
+ "evidence": [
49
+ "clone/tests/test_backend_lifecycle.py::test_site_backend_backup_is_complete_and_readable"
50
+ ]
51
+ },
52
+ {
53
+ "obligation": "concurrency",
54
+ "status": "verified",
55
+ "evidence": [
56
+ "clone/tests/test_backend_lifecycle.py::test_concurrent_quote_creation_is_isolated_and_lossless",
57
+ "harbor/instances/aspca-pet-insurance/fixtures/hidden/cicd-suite.json#platform::deploy/concurrent-isolation"
58
+ ]
59
+ }
60
+ ]
61
+ },
62
+ "auth_semantics": {
63
+ "account_database_scope": "site-isolated",
64
+ "credential_storage": "salted-scrypt-hash",
65
+ "session_storage": "opaque-cookie-digest-at-rest",
66
+ "registration_account_creation": "direct-password",
67
+ "verification_challenge_storage": "not-applicable",
68
+ "password_reset_enumeration": "not-applicable",
69
+ "mail_default": "LOCAL_ONLY",
70
+ "mail_statuses": [
71
+ "LOCAL_ONLY",
72
+ "SMTP_PENDING",
73
+ "SMTP_SENT",
74
+ "SMTP_FAILED"
75
+ ],
76
+ "smtp_activation": "explicit-complete-config-only",
77
+ "smtp_delivery_ceiling": 3,
78
+ "rejected_secret_journaling": "forbidden",
79
+ "legacy_write_policy": "read-compatible-write-rejected"
80
+ },
81
+ "common_capabilities": {
82
+ "account_registration": "account-registration",
83
+ "account_sign_in": "account-sign-in",
84
+ "session_lifecycle": "session-lifecycle",
85
+ "password_recovery": "password-recovery",
86
+ "email_delivery": "email-delivery"
87
+ },
88
+ "capabilities": [
89
+ {
90
+ "id": "account-registration",
91
+ "label": "Fail-closed member registration boundary",
92
+ "priority": "p1",
93
+ "category": "authentication",
94
+ "implementation_status": "verified",
95
+ "entities": [
96
+ {
97
+ "name": "registration-attempt",
98
+ "identity": "one anonymous request with synthetic fields",
99
+ "owner_scope": "session",
100
+ "persistence": "ephemeral"
101
+ }
102
+ ],
103
+ "state_machine": {
104
+ "kind": "entity-lifecycle",
105
+ "states": ["collecting", "validated", "refused"],
106
+ "transitions": [
107
+ {"from": "collecting", "to": "validated", "trigger": "required fields pass validation"},
108
+ {"from": "validated", "to": "refused", "trigger": "member evidence boundary is enforced"}
109
+ ]
110
+ },
111
+ "server_authorities": [
112
+ "The server validates request shape and always refuses account creation.",
113
+ "No account, challenge, session, or mail row is created."
114
+ ],
115
+ "external_effect": "none",
116
+ "journey_ids": ["auth.register.unavailable"],
117
+ "invariant_ids": ["auth.member-operations-unavailable"],
118
+ "proofs": {
119
+ "evidence": {
120
+ "valid": ["clone/tests/test_portal_api.py::test_register_never_registers"],
121
+ "invalid": ["clone/tests/test_portal_api.py::test_register_never_registers"]
122
+ },
123
+ "not_applicable": [
124
+ {"obligation": "duplicate", "rationale": "No registration state can be created."},
125
+ {"obligation": "stale", "rationale": "No registration challenge can be created."},
126
+ {"obligation": "foreign-owner", "rationale": "No account or owner authority exists."},
127
+ {"obligation": "unauthorized-role", "rationale": "All anonymous callers receive the same refusal."},
128
+ {"obligation": "restart", "rationale": "The boundary creates no persistent state."},
129
+ {"obligation": "migration", "rationale": "The boundary creates no capability-specific schema."},
130
+ {"obligation": "concurrency", "rationale": "Concurrent refusals have no shared mutation."}
131
+ ]
132
+ }
133
+ },
134
+ {
135
+ "id": "account-sign-in",
136
+ "label": "Fail-closed member sign-in boundary",
137
+ "priority": "p1",
138
+ "category": "authentication",
139
+ "implementation_status": "verified",
140
+ "entities": [
141
+ {
142
+ "name": "sign-in-attempt",
143
+ "identity": "one anonymous request with synthetic credentials",
144
+ "owner_scope": "session",
145
+ "persistence": "ephemeral"
146
+ }
147
+ ],
148
+ "state_machine": {
149
+ "kind": "entity-lifecycle",
150
+ "states": ["collecting", "validated", "refused"],
151
+ "transitions": [
152
+ {"from": "collecting", "to": "validated", "trigger": "required fields pass validation"},
153
+ {"from": "validated", "to": "refused", "trigger": "member evidence boundary is enforced"}
154
+ ]
155
+ },
156
+ "server_authorities": [
157
+ "The server validates request shape and always refuses authentication.",
158
+ "No authenticated session or member authority is created."
159
+ ],
160
+ "external_effect": "none",
161
+ "journey_ids": ["auth.login.invalid"],
162
+ "invariant_ids": ["auth.member-operations-unavailable"],
163
+ "proofs": {
164
+ "evidence": {
165
+ "valid": ["clone/tests/test_portal_api.py::test_login_never_authenticates"],
166
+ "invalid": ["clone/tests/test_portal_api.py::test_login_empty_fields_are_validation_errors"]
167
+ },
168
+ "not_applicable": [
169
+ {"obligation": "duplicate", "rationale": "No sign-in state can be created."},
170
+ {"obligation": "stale", "rationale": "No authenticated session can become stale."},
171
+ {"obligation": "foreign-owner", "rationale": "No account or owner authority exists."},
172
+ {"obligation": "unauthorized-role", "rationale": "All anonymous callers receive the same refusal."},
173
+ {"obligation": "restart", "rationale": "The boundary creates no persistent state."},
174
+ {"obligation": "migration", "rationale": "The boundary creates no capability-specific schema."},
175
+ {"obligation": "concurrency", "rationale": "Concurrent refusals have no shared mutation."}
176
+ ]
177
+ }
178
+ },
179
+ {
180
+ "id": "session-lifecycle",
181
+ "label": "Anonymous-only session boundary",
182
+ "priority": "p1",
183
+ "category": "authentication",
184
+ "implementation_status": "verified",
185
+ "entities": [
186
+ {
187
+ "name": "anonymous-session-boundary",
188
+ "identity": "request-local anonymous state",
189
+ "owner_scope": "session",
190
+ "persistence": "ephemeral"
191
+ }
192
+ ],
193
+ "state_machine": {
194
+ "kind": "session-lifecycle",
195
+ "states": ["anonymous", "refused"],
196
+ "transitions": [
197
+ {"from": "anonymous", "to": "refused", "trigger": "a member operation is submitted"}
198
+ ]
199
+ },
200
+ "server_authorities": [
201
+ "Member submissions never elevate an anonymous request.",
202
+ "The clone never emits an authenticated session cookie."
203
+ ],
204
+ "external_effect": "none",
205
+ "journey_ids": ["auth.login.invalid"],
206
+ "invariant_ids": ["auth.member-operations-unavailable"],
207
+ "proofs": {
208
+ "evidence": {
209
+ "valid": ["clone/tests/test_portal_api.py::test_login_never_authenticates"],
210
+ "invalid": ["clone/tests/test_portal_api.py::test_login_empty_fields_are_validation_errors"]
211
+ },
212
+ "not_applicable": [
213
+ {"obligation": "duplicate", "rationale": "No server session is created."},
214
+ {"obligation": "stale", "rationale": "No authenticated session can expire or become stale."},
215
+ {"obligation": "foreign-owner", "rationale": "No owner-bound session exists."},
216
+ {"obligation": "unauthorized-role", "rationale": "No role elevation exists."},
217
+ {"obligation": "restart", "rationale": "The boundary creates no persistent state."},
218
+ {"obligation": "migration", "rationale": "The boundary creates no capability-specific schema."},
219
+ {"obligation": "concurrency", "rationale": "Concurrent refusals have no shared mutation."}
220
+ ]
221
+ }
222
+ },
223
+ {
224
+ "id": "password-recovery",
225
+ "label": "Fail-closed password-recovery boundary",
226
+ "priority": "p1",
227
+ "category": "authentication",
228
+ "implementation_status": "verified",
229
+ "entities": [
230
+ {
231
+ "name": "recovery-attempt",
232
+ "identity": "one anonymous request with a synthetic email",
233
+ "owner_scope": "session",
234
+ "persistence": "ephemeral"
235
+ }
236
+ ],
237
+ "state_machine": {
238
+ "kind": "challenge-lifecycle",
239
+ "states": ["collecting", "validated", "refused"],
240
+ "transitions": [
241
+ {"from": "collecting", "to": "validated", "trigger": "email passes validation"},
242
+ {"from": "validated", "to": "refused", "trigger": "member evidence boundary is enforced"}
243
+ ]
244
+ },
245
+ "server_authorities": [
246
+ "The server validates request shape and always refuses recovery.",
247
+ "No challenge, password mutation, session mutation, or mail row is created."
248
+ ],
249
+ "external_effect": "none",
250
+ "journey_ids": ["auth.forgot-password.unavailable"],
251
+ "invariant_ids": ["auth.member-operations-unavailable"],
252
+ "proofs": {
253
+ "evidence": {
254
+ "valid": ["clone/tests/test_portal_api.py::test_forgot_password_never_sends"],
255
+ "invalid": ["clone/tests/test_portal_api.py::test_forgot_password_requires_email"]
256
+ },
257
+ "not_applicable": [
258
+ {"obligation": "duplicate", "rationale": "No reset challenge is created."},
259
+ {"obligation": "stale", "rationale": "No reset challenge can become stale."},
260
+ {"obligation": "foreign-owner", "rationale": "No account binding exists."},
261
+ {"obligation": "unauthorized-role", "rationale": "All anonymous callers receive the same refusal."},
262
+ {"obligation": "restart", "rationale": "The boundary creates no persistent state."},
263
+ {"obligation": "migration", "rationale": "The boundary creates no capability-specific schema."},
264
+ {"obligation": "concurrency", "rationale": "Concurrent refusals have no shared mutation."}
265
+ ]
266
+ }
267
+ },
268
+ {
269
+ "id": "email-delivery",
270
+ "label": "Local policy-confirmation mail",
271
+ "priority": "p0",
272
+ "category": "communication",
273
+ "implementation_status": "verified",
274
+ "entities": [
275
+ {
276
+ "name": "policy-confirmation-mail",
277
+ "identity": "site-bound mail job idempotently keyed by the enrolled policy number",
278
+ "owner_scope": "account",
279
+ "persistence": "durable"
280
+ }
281
+ ],
282
+ "state_machine": {
283
+ "kind": "delivery-lifecycle",
284
+ "states": ["not-requested", "local-only"],
285
+ "transitions": [
286
+ {"from": "not-requested", "to": "local-only", "trigger": "an approved sandbox payment is consumed and its policy is inserted in the same transaction"}
287
+ ]
288
+ },
289
+ "server_authorities": [
290
+ "The server selects the frozen policy-confirmation template and exact non-secret variables.",
291
+ "The outbox row is idempotently created in the same transaction as payment consumption and policy insertion.",
292
+ "The job is always marked LOCAL_SIMULATION and no SMTP or production request is attempted.",
293
+ "Member registration and password recovery continue to create no mail."
294
+ ],
295
+ "external_effect": "local-only",
296
+ "external_effect_boundary": "A structured mail job is stored only in the site-exclusive local outbox; it is never rendered for or submitted to an external provider.",
297
+ "journey_ids": ["quote.payment.local-sandbox.success"],
298
+ "invariant_ids": ["mail.policy-confirmation-local-only", "payment.local-sandbox-atomic"],
299
+ "proofs": {
300
+ "evidence": {
301
+ "valid": ["clone/tests/test_payment_mail.py::test_approved_payment_enrolls_and_enqueues_one_local_mail"],
302
+ "invalid": ["clone/tests/test_payment_mail.py::test_mail_failure_rolls_back_payment_consumption_and_policy"],
303
+ "duplicate": ["clone/tests/test_payment_mail.py::test_retry_then_approval_converges_to_one_policy_and_mail"],
304
+ "foreign-owner": ["clone/tests/test_quotes_api.py::test_payment_credentials_and_server_facts_are_rejected_everywhere"],
305
+ "restart": ["clone/tests/test_backend_lifecycle.py::test_quote_state_survives_service_restart"],
306
+ "migration": ["clone/tests/test_backend_lifecycle.py::test_database_path_and_migrations_are_site_bound_and_idempotent"],
307
+ "concurrency": ["clone/tests/test_payment_mail.py::test_concurrent_approved_submissions_converge_to_one_policy_and_mail"]
308
+ },
309
+ "not_applicable": [
310
+ {"obligation": "stale", "rationale": "A LOCAL_SIMULATION job is an immutable transaction snapshot and has no later delivery claim or mutable approval state to become stale."},
311
+ {"obligation": "unauthorized-role", "rationale": "The anonymous quote flow has no roles; callers cannot select recipient, template, mail status, or provider authority."}
312
+ ]
313
+ }
314
+ },
315
+ {
316
+ "id": "payment-lifecycle",
317
+ "label": "Local-sandbox quote payment and enrollment",
318
+ "priority": "p0",
319
+ "category": "commerce",
320
+ "implementation_status": "verified",
321
+ "entities": [
322
+ {
323
+ "name": "payment-flow",
324
+ "identity": "site-bound flow id for a server-priced quote fingerprint",
325
+ "owner_scope": "account",
326
+ "persistence": "durable"
327
+ },
328
+ {
329
+ "name": "payment-attempt",
330
+ "identity": "site-bound attempt idempotently keyed by quote fingerprint and opaque scenario id",
331
+ "owner_scope": "account",
332
+ "persistence": "durable"
333
+ },
334
+ {
335
+ "name": "enrollment",
336
+ "identity": "one policy number bound to one consumed approved attempt and quote snapshot",
337
+ "owner_scope": "account",
338
+ "persistence": "durable"
339
+ }
340
+ ],
341
+ "state_machine": {
342
+ "kind": "entity-lifecycle",
343
+ "states": ["initialized", "approved", "declined", "retryable", "consumed"],
344
+ "transitions": [
345
+ {"from": "initialized", "to": "approved", "trigger": "the configured sandbox-approved scenario is attempted"},
346
+ {"from": "initialized", "to": "declined", "trigger": "the configured sandbox-declined scenario is attempted"},
347
+ {"from": "initialized", "to": "retryable", "trigger": "the configured sandbox-retry scenario is attempted"},
348
+ {"from": "approved", "to": "consumed", "trigger": "the current server fingerprint is validated and policy plus local mail are inserted in the same transaction"}
349
+ ]
350
+ },
351
+ "server_authorities": [
352
+ "The server derives integer USD minor units from the persisted quote selections and billing frequency.",
353
+ "The server binds owner and a canonical SHA-256 fingerprint to the current quote snapshot.",
354
+ "The client may provide only a configured opaque local-sandbox scenario id and never credentials, amount, currency, owner, or fingerprint.",
355
+ "Approval consumption, enrollment insertion, and policy-confirmation mail enqueue share one transaction.",
356
+ "Declined and retryable attempts create no enrollment or mail; duplicate approved submissions converge on one policy."
357
+ ],
358
+ "external_effect": "local-only",
359
+ "external_effect_boundary": "Only the site-exclusive SQLite payment ledger, enrollment table, and local simulated mail outbox are mutated; no provider or live-payment request exists.",
360
+ "journey_ids": ["quote.payment.local-sandbox.success", "quote.payment.local-sandbox.retry"],
361
+ "invariant_ids": ["payment.local-sandbox-atomic", "privacy.synthetic-inputs"],
362
+ "proofs": {
363
+ "evidence": {
364
+ "valid": ["clone/tests/test_payment_mail.py::test_approved_payment_enrolls_and_enqueues_one_local_mail"],
365
+ "invalid": ["clone/tests/test_quotes_api.py::test_payment_credentials_and_server_facts_are_rejected_everywhere", "clone/tests/test_payment_mail.py::test_unknown_sandbox_scenario_is_rejected"],
366
+ "duplicate": ["clone/tests/test_payment_mail.py::test_retry_then_approval_converges_to_one_policy_and_mail"],
367
+ "stale": ["clone/tests/test_payment_mail.py::test_foreign_owner_and_stale_fingerprint_cannot_consume_approval"],
368
+ "foreign-owner": ["clone/tests/test_payment_mail.py::test_foreign_owner_and_stale_fingerprint_cannot_consume_approval"],
369
+ "restart": ["clone/tests/test_backend_lifecycle.py::test_quote_state_survives_service_restart"],
370
+ "migration": ["clone/tests/test_backend_lifecycle.py::test_database_path_and_migrations_are_site_bound_and_idempotent"],
371
+ "concurrency": ["clone/tests/test_payment_mail.py::test_concurrent_approved_submissions_converge_to_one_policy_and_mail"]
372
+ },
373
+ "not_applicable": [
374
+ {"obligation": "unauthorized-role", "rationale": "The source-backed clone remains anonymous-only; no role can influence server-derived quote ownership or local-sandbox payment authority."}
375
+ ]
376
+ }
377
+ }
378
+ ]
379
+ }
tasks/aspca-pet-insurance/environment/reference/backend/runtime.json ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "database": {
3
+ "data_dir": "data",
4
+ "engine": "sqlite",
5
+ "filename": "aspca-pet-insurance.sqlite3",
6
+ "volume_identity": "websitebench-aspca-pet-insurance-data",
7
+ "legacy_unbound_migration": false,
8
+ "migration_hook": null,
9
+ "seed_hook": null
10
+ },
11
+ "deployment": {
12
+ "profiles": {
13
+ "cloudflare-review": {
14
+ "mail_adapter": "redis-resend",
15
+ "payment_adapter": "local-sandbox",
16
+ "persistence": "ephemeral-reset"
17
+ },
18
+ "docker-volume": {
19
+ "mail_adapter": "effects-gateway",
20
+ "payment_adapter": "local-sandbox",
21
+ "persistence": "persistent-volume"
22
+ },
23
+ "offline-harbor": {
24
+ "mail_adapter": "local-outbox",
25
+ "payment_adapter": "local-sandbox",
26
+ "persistence": "persistent"
27
+ }
28
+ }
29
+ },
30
+ "mail": {
31
+ "enabled": true,
32
+ "purposes": {
33
+ "policy-confirmation": {
34
+ "body": "Policy ${policy_number} for ${pet_name} was activated with a simulated ${frequency} payment of ${amount} ${currency}.",
35
+ "expiry": "This local simulation has no external billing effect.",
36
+ "footer": "ASPCA Pet Health Insurance offline clone — payment remains simulated; this confirmation was delivered only to the isolated benchmark mailbox.",
37
+ "lead": "Your local ASPCA Pet Health Insurance enrollment is complete.",
38
+ "required_variables": [
39
+ "policy_number",
40
+ "pet_name",
41
+ "frequency",
42
+ "amount",
43
+ "currency"
44
+ ],
45
+ "secret_variables": [],
46
+ "subject": "Your ASPCA Pet Insurance sandbox enrollment",
47
+ "template_id": "aspca-pet-insurance.policy-confirmation.v1"
48
+ }
49
+ },
50
+ "sender": {
51
+ "address_env": "RESEND_FROM_EMAIL",
52
+ "display_name": "ASPCA Pet Health Insurance"
53
+ }
54
+ },
55
+ "payments": {
56
+ "currency": "USD",
57
+ "default_adapter": "local-sandbox",
58
+ "enabled": true,
59
+ "local_sandbox": {
60
+ "scenarios": [
61
+ {
62
+ "display_label": "Simulated approval",
63
+ "id": "sandbox-approved",
64
+ "outcome": "approved"
65
+ },
66
+ {
67
+ "display_label": "Simulated decline",
68
+ "id": "sandbox-declined",
69
+ "outcome": "declined"
70
+ },
71
+ {
72
+ "display_label": "Simulated retry",
73
+ "id": "sandbox-retry",
74
+ "outcome": "retryable"
75
+ }
76
+ ]
77
+ },
78
+ "stripe_test": null
79
+ },
80
+ "schema_version": "websitebench.site-backend-runtime.v1",
81
+ "session": {
82
+ "host_only": true,
83
+ "http_only": true,
84
+ "same_site": "Lax",
85
+ "secure": true
86
+ },
87
+ "site": {
88
+ "id": "aspca-pet-insurance",
89
+ "label": "ASPCA Pet Health Insurance",
90
+ "public_origin": "https://aspca-pet-insurance.website-bench.com"
91
+ }
92
+ }
tasks/aspca-pet-insurance/environment/reference/clone/app.py ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ASPCA Pet Health Insurance offline clone — FastAPI composition root.
2
+
3
+ Layout (tripit golden-sample shape):
4
+
5
+ * Frozen localized marketing pages (``frontend/pages/*.html``) served at their
6
+ real source routes; every unmatched path renders the captured not-found page.
7
+ * The quote funnel (``/quote/`` + hash routes) and portal (``/portal/``) are
8
+ SPA shells whose view fragments were mechanically extracted from the capture
9
+ (``frontend/quote/views``, ``frontend/portal/views``); behavior is
10
+ re-implemented locally in ``static/site/{quote-app.js,portal-app.js}``
11
+ against the JSON API below.
12
+ * The JSON API prices plans with the frozen rating table
13
+ (``backend/model.json`` via ``backend/rating.py``) and persists quotes /
14
+ pets / enrollments through the vendored ``websitebench.site_backend``
15
+ runtime (``backend/quotes_db.py``). The source walk stopped before payment;
16
+ a clone-local local-sandbox step accepts only an opaque scenario id and
17
+ rejects credentials plus client-supplied payment facts.
18
+ * ``GET /healthz`` returns exactly ``{"ok":true,"site_id":"aspca-pet-insurance"}``.
19
+ * ``POST /__admin/reset`` is guarded by a constant-time admin-token compare.
20
+ * Every response carries a same-origin Content-Security-Policy; no remote
21
+ origin is reachable at runtime.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import hmac
27
+ import html
28
+ import json
29
+ import os
30
+ import re
31
+ import sys
32
+ import urllib.parse
33
+ from pathlib import Path
34
+
35
+ from fastapi import FastAPI, Request
36
+ from fastapi.responses import HTMLResponse, JSONResponse, Response
37
+ from starlette.staticfiles import StaticFiles
38
+
39
+ ROOT = Path(__file__).resolve().parent
40
+ if str(ROOT) not in sys.path: # vendored websitebench + backend imports
41
+ sys.path.insert(0, str(ROOT))
42
+
43
+ from backend import quotes_db as db # noqa: E402
44
+ from backend import rating # noqa: E402
45
+ from backend.quotes_db import PaymentFieldRejected # noqa: E402
46
+ from backend.rating import RatingError # noqa: E402
47
+ from websitebench.site_backend import ( # noqa: E402
48
+ EffectsMailDeliveryError,
49
+ MailError,
50
+ PaymentError,
51
+ )
52
+
53
+ SITE_ID = "aspca-pet-insurance"
54
+ PAGES_DIR = ROOT / "frontend" / "pages"
55
+ QUOTE_DIR = ROOT / "frontend" / "quote"
56
+ PORTAL_DIR = ROOT / "frontend" / "portal"
57
+ STATIC_DIR = ROOT / "static"
58
+
59
+ _HEALTH_BODY = json.dumps({"ok": True, "site_id": SITE_ID}, separators=(",", ":"))
60
+ _MARKETING_RUNTIME_TAG = (
61
+ '<script src="/static/site/marketing-app.js" defer></script>'
62
+ )
63
+
64
+ # Real source route -> frozen fixture page (captured anonymously, localized).
65
+ PAGE_ROUTES: dict[str, str] = {
66
+ "/": "home",
67
+ "/pet-insurance-plan/": "pet-insurance-plan",
68
+ "/cat-insurance/": "cat-insurance",
69
+ "/dog-insurance/": "dog-insurance",
70
+ "/why-us/": "why-us",
71
+ "/research-and-compare/": "research-and-compare",
72
+ "/about-us/": "about-us",
73
+ "/about-us/contact-us/": "support",
74
+ }
75
+
76
+ # Admin token for /__admin/reset. Non-secret dev default for local runs;
77
+ # deployments inject the real value via the environment. Never logged.
78
+ ADMIN_TOKEN = os.environ.get(
79
+ "WEBSITEBENCH_ASPCA_ADMIN_TOKEN", "aspca-local-admin"
80
+ )
81
+
82
+ BUILD_ID = os.environ.get("DEPLOYMENT_BUILD_ID") or os.environ.get(
83
+ "WEBSITEBENCH_BUILD_ID"
84
+ )
85
+
86
+ # Same-origin CSP: the captured documents carry inline styles, so
87
+ # 'unsafe-inline' stays; the load-bearing property is that no remote origin is
88
+ # reachable (default-src 'self') — zero remote runtime requests.
89
+ CONTENT_SECURITY_POLICY = (
90
+ "default-src 'self'; "
91
+ "img-src 'self' data:; "
92
+ "style-src 'self' 'unsafe-inline'; "
93
+ "script-src 'self' 'unsafe-inline'; "
94
+ "font-src 'self' data:; "
95
+ "connect-src 'self'; "
96
+ "frame-ancestors 'none'; "
97
+ "base-uri 'self'; "
98
+ "form-action 'self'"
99
+ )
100
+
101
+ _VIEW_NAME_RE = re.compile(r"^[a-z0-9-]{1,64}$")
102
+ # Exact ng-pattern from the captured quote-start form (views-report.json);
103
+ # Angular tests with JS RegExp.test, i.e. unanchored-start search semantics.
104
+ EMAIL_RE = re.compile(r"[a-z0-9A-Z._%+-]+@[a-z0-9A-Z.-]+\.[a-zA-Z]{2,4}$")
105
+ REQUIRED_PET_FIELDS = ("species", "name", "age_label", "gender", "breed")
106
+
107
+ _PAGE_CACHE: dict[str, str] = {}
108
+
109
+
110
+ def _load_page(name: str) -> str:
111
+ cached = _PAGE_CACHE.get(name)
112
+ if cached is None:
113
+ cached = (PAGES_DIR / f"{name}.html").read_text(encoding="utf-8")
114
+ if _MARKETING_RUNTIME_TAG not in cached:
115
+ if "</body>" in cached:
116
+ cached = cached.replace(
117
+ "</body>", f"{_MARKETING_RUNTIME_TAG}</body>", 1
118
+ )
119
+ else:
120
+ cached = f"{cached}{_MARKETING_RUNTIME_TAG}"
121
+ _PAGE_CACHE[name] = cached
122
+ return cached
123
+
124
+
125
+ def _fragment(directory: Path, name: str) -> Response:
126
+ if not _VIEW_NAME_RE.match(name):
127
+ return _not_found_response()
128
+ path = directory / "views" / f"{name}.html"
129
+ if not path.is_file():
130
+ return _not_found_response()
131
+ return HTMLResponse(path.read_text(encoding="utf-8"))
132
+
133
+
134
+ def _not_found_response() -> HTMLResponse:
135
+ try:
136
+ body = _load_page("not-found")
137
+ except FileNotFoundError: # pre-build fallback, never expected in release
138
+ body = "<!doctype html><title>Not found</title><h1>Not found</h1>"
139
+ return HTMLResponse(body, status_code=404)
140
+
141
+
142
+ _EXTERNAL_PAGE_TEMPLATE = """<!doctype html>
143
+ <html lang="en">
144
+ <head><meta charset="utf-8"><title>External link boundary</title></head>
145
+ <body style="font-family: sans-serif; max-width: 40rem; margin: 4rem auto;">
146
+ <h1>External link</h1>
147
+ <p>This offline clone does not open third-party destinations. The original
148
+ page linked to an external site ({slug}). No remote request was made.</p>
149
+ <p><a href="/">Return to the home page</a></p>
150
+ </body>
151
+ </html>
152
+ """
153
+
154
+ app = FastAPI(
155
+ title="ASPCA Pet Health Insurance offline clone",
156
+ docs_url=None,
157
+ redoc_url=None,
158
+ openapi_url=None,
159
+ )
160
+
161
+
162
+ class _MirrorStaticFiles(StaticFiles):
163
+ """StaticFiles that retries percent-encoded on-disk names.
164
+
165
+ The asset closure preserves the source URL's percent-encoding; Starlette
166
+ URL-decodes the request path before lookup, so the decoded name can miss
167
+ the byte-exact encoded file. Retry with each segment re-encoded; anything
168
+ else still 404s (never masks a genuine closure gap).
169
+ """
170
+
171
+ def lookup_path(self, path: str) -> "tuple[str, os.stat_result | None]":
172
+ full_path, stat_result = super().lookup_path(path)
173
+ if stat_result is not None:
174
+ return full_path, stat_result
175
+ requoted = "/".join(urllib.parse.quote(seg) for seg in path.split("/"))
176
+ if requoted != path:
177
+ retry_path, retry_stat = super().lookup_path(requoted)
178
+ if retry_stat is not None:
179
+ return retry_path, retry_stat
180
+ return full_path, stat_result
181
+
182
+
183
+ app.mount("/static", _MirrorStaticFiles(directory=str(STATIC_DIR)), name="static")
184
+
185
+
186
+ @app.middleware("http")
187
+ async def runtime_headers(request: Request, call_next):
188
+ response = await call_next(request)
189
+ response.headers["Content-Security-Policy"] = CONTENT_SECURITY_POLICY
190
+ response.headers["Referrer-Policy"] = "no-referrer"
191
+ response.headers["X-Content-Type-Options"] = "nosniff"
192
+ response.headers["X-Frame-Options"] = "DENY"
193
+ if BUILD_ID:
194
+ response.headers["X-WebsiteBench-Build-Id"] = BUILD_ID
195
+ return response
196
+
197
+
198
+ @app.get("/healthz", include_in_schema=False)
199
+ async def healthz() -> Response:
200
+ return Response(content=_HEALTH_BODY, media_type="application/json")
201
+
202
+
203
+ @app.post("/__admin/reset", include_in_schema=False)
204
+ async def admin_reset(request: Request) -> Response:
205
+ token = request.headers.get("X-WebsiteBench-Admin-Token", "")
206
+ if not hmac.compare_digest(token, ADMIN_TOKEN):
207
+ return JSONResponse({"error": "forbidden"}, status_code=403)
208
+ db.reset()
209
+ return JSONResponse({"reset": True, "site_id": SITE_ID})
210
+
211
+
212
+ @app.get("/external/{slug}", include_in_schema=False)
213
+ async def external_boundary(slug: str) -> HTMLResponse:
214
+ # Local boundary for third-party navigation targets: the clone never
215
+ # proxies out, so every off-site affordance lands on this same-origin page.
216
+ safe = html.escape(slug[:80])
217
+ return HTMLResponse(_EXTERNAL_PAGE_TEMPLATE.format(slug=safe))
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # frozen marketing pages
222
+ # ---------------------------------------------------------------------------
223
+
224
+
225
+ def _register_page(route: str, name: str) -> None:
226
+ @app.get(route, include_in_schema=False)
227
+ async def frozen_page(_name: str = name) -> HTMLResponse:
228
+ return HTMLResponse(_load_page(_name))
229
+
230
+
231
+ for _route, _name in PAGE_ROUTES.items():
232
+ _register_page(_route, _name)
233
+
234
+
235
+ @app.exception_handler(404)
236
+ async def not_found_handler(request: Request, exc: Exception) -> Response:
237
+ if request.url.path.startswith(("/api/", "/portal/api/")):
238
+ return JSONResponse({"error": "not-found"}, status_code=404)
239
+ return _not_found_response()
240
+
241
+
242
+ # ---------------------------------------------------------------------------
243
+ # SPA shells + captured view fragments
244
+ # ---------------------------------------------------------------------------
245
+
246
+
247
+ @app.get("/quote/", include_in_schema=False)
248
+ @app.get("/quote", include_in_schema=False)
249
+ async def quote_shell() -> HTMLResponse:
250
+ return HTMLResponse((QUOTE_DIR / "index.html").read_text(encoding="utf-8"))
251
+
252
+
253
+ @app.get("/quote/views/{name}", include_in_schema=False)
254
+ async def quote_view(name: str) -> Response:
255
+ return _fragment(QUOTE_DIR, name)
256
+
257
+
258
+ @app.get("/portal/", include_in_schema=False)
259
+ @app.get("/portal", include_in_schema=False)
260
+ async def portal_shell() -> HTMLResponse:
261
+ return HTMLResponse((PORTAL_DIR / "index.html").read_text(encoding="utf-8"))
262
+
263
+
264
+ @app.get("/portal/views/{name}", include_in_schema=False)
265
+ async def portal_view(name: str) -> Response:
266
+ return _fragment(PORTAL_DIR, name)
267
+
268
+
269
+ # ---------------------------------------------------------------------------
270
+ # quote-funnel JSON API
271
+ # ---------------------------------------------------------------------------
272
+
273
+
274
+ async def _json_body(request: Request) -> dict:
275
+ try:
276
+ body = await request.json()
277
+ except Exception:
278
+ return {}
279
+ return body if isinstance(body, dict) else {}
280
+
281
+
282
+ def _string(value: object) -> str:
283
+ return value.strip() if isinstance(value, str) else ""
284
+
285
+
286
+ def _pet_payload(body: dict) -> tuple[dict[str, str], dict[str, str]]:
287
+ """Validate pet fields; returns (pet, errors)."""
288
+
289
+ pet: dict[str, str] = {}
290
+ errors: dict[str, str] = {}
291
+ aliases = {"age_label": ("age_label", "age")}
292
+ for field in REQUIRED_PET_FIELDS:
293
+ value = ""
294
+ for key in aliases.get(field, (field,)):
295
+ value = _string(body.get(key))
296
+ if value:
297
+ break
298
+ if not value:
299
+ errors[field] = "This field is required."
300
+ else:
301
+ pet[field] = value[:120]
302
+ return pet, errors
303
+
304
+
305
+ def _rates_block(quote: dict) -> dict:
306
+ first = quote["pets"][0]["selection"] if quote["pets"] else None
307
+ return {"tiers": quote["tiers"], "selection": first}
308
+
309
+
310
+ @app.post("/api/quotes", include_in_schema=False)
311
+ async def create_quote(request: Request) -> JSONResponse:
312
+ body = await _json_body(request)
313
+ try:
314
+ db.reject_payment_keys(body)
315
+ except PaymentFieldRejected as exc:
316
+ return JSONResponse({"errors": {"payment": str(exc)}}, status_code=422)
317
+ pet, errors = _pet_payload(body)
318
+ email = _string(body.get("email"))
319
+ zip_code = _string(body.get("zip"))
320
+ if not email:
321
+ errors["email"] = "This field is required."
322
+ elif not EMAIL_RE.search(email):
323
+ errors["email"] = "Please enter a valid email address."
324
+ if not zip_code:
325
+ errors["zip"] = "This field is required."
326
+ elif not rating.valid_zip(zip_code):
327
+ return JSONResponse(
328
+ {
329
+ "eligible": False,
330
+ "errors": {"zip": rating.zip_error_message(zip_code)},
331
+ },
332
+ status_code=422,
333
+ )
334
+ if errors:
335
+ return JSONResponse({"errors": errors}, status_code=422)
336
+ quote = db.create_quote(pet, email, zip_code)
337
+ return JSONResponse(
338
+ {
339
+ "quote_id": quote["quote_id"],
340
+ "eligible": True,
341
+ "pet": quote["pets"][0],
342
+ "rates": _rates_block(quote),
343
+ },
344
+ status_code=201,
345
+ )
346
+
347
+
348
+ @app.get("/api/quotes/search", include_in_schema=False)
349
+ async def search_quotes(request: Request) -> JSONResponse:
350
+ email = _string(request.query_params.get("email"))
351
+ zip_code = _string(request.query_params.get("zip"))
352
+ if not email or not zip_code:
353
+ return JSONResponse(
354
+ {"errors": {"query": "email and zip are required"}}, status_code=422
355
+ )
356
+ quote = db.find_quote(email, zip_code)
357
+ if quote is None:
358
+ return JSONResponse({"error": "not-found"}, status_code=404)
359
+ return JSONResponse(quote)
360
+
361
+
362
+ @app.get("/api/quotes/{quote_id}", include_in_schema=False)
363
+ async def get_quote(quote_id: str) -> JSONResponse:
364
+ quote = db.get_quote(quote_id)
365
+ if quote is None:
366
+ return JSONResponse({"error": "not-found"}, status_code=404)
367
+ return JSONResponse(quote)
368
+
369
+
370
+ @app.post("/api/quotes/{quote_id}/rate", include_in_schema=False)
371
+ async def rate_quote(quote_id: str, request: Request) -> JSONResponse:
372
+ body = await _json_body(request)
373
+
374
+ def _intval(key: str, fallback: int) -> int:
375
+ raw = body.get(key, fallback)
376
+ try:
377
+ return int(str(raw).replace(",", "").replace("$", ""))
378
+ except ValueError:
379
+ return -1
380
+
381
+ preventive = body.get("preventive")
382
+ if preventive in ("", "none"):
383
+ preventive = None
384
+ pet_id = body.get("pet_id")
385
+ try:
386
+ priced = db.apply_rate(
387
+ quote_id,
388
+ _intval("limit", _intval("annual_limit", 5000)),
389
+ _intval("deductible", 500),
390
+ _intval("reimbursement", 80),
391
+ preventive,
392
+ pet_id=int(pet_id) if pet_id is not None else None,
393
+ )
394
+ except (RatingError, ValueError) as exc:
395
+ return JSONResponse({"errors": {"rate": str(exc)}}, status_code=422)
396
+ if priced is None:
397
+ return JSONResponse({"error": "not-found"}, status_code=404)
398
+ return JSONResponse(priced)
399
+
400
+
401
+ @app.post("/api/quotes/{quote_id}/pets", include_in_schema=False)
402
+ async def add_pet(quote_id: str, request: Request) -> JSONResponse:
403
+ body = await _json_body(request)
404
+ try:
405
+ db.reject_payment_keys(body)
406
+ except PaymentFieldRejected as exc:
407
+ return JSONResponse({"errors": {"payment": str(exc)}}, status_code=422)
408
+ pet, errors = _pet_payload(body)
409
+ if errors:
410
+ return JSONResponse({"errors": errors}, status_code=422)
411
+ quote = db.add_pet(quote_id, pet)
412
+ if quote is None:
413
+ return JSONResponse({"error": "not-found"}, status_code=404)
414
+ return JSONResponse(quote, status_code=201)
415
+
416
+
417
+ @app.post("/api/quotes/{quote_id}/enroll", include_in_schema=False)
418
+ async def enroll(quote_id: str, request: Request) -> JSONResponse:
419
+ body = await _json_body(request)
420
+ try:
421
+ db.reject_payment_keys(body)
422
+ except PaymentFieldRejected as exc:
423
+ return JSONResponse({"errors": {"payment": str(exc)}}, status_code=422)
424
+ frequency = _string(body.get("frequency")) or "Monthly"
425
+ scenario_id = _string(body.get("scenario_id"))
426
+ agree_terms = bool(body.get("agree_terms"))
427
+ paperless = bool(body.get("paperless"))
428
+ contact_source = body.get("contact")
429
+ if not isinstance(contact_source, dict):
430
+ contact_source = {
431
+ k: v
432
+ for k, v in body.items()
433
+ if k not in ("frequency", "agree_terms", "paperless", "scenario_id")
434
+ }
435
+ try:
436
+ db.reject_payment_keys(contact_source)
437
+ except PaymentFieldRejected as exc:
438
+ return JSONResponse({"errors": {"payment": str(exc)}}, status_code=422)
439
+ contact = {
440
+ str(k)[:64]: _string(v)[:200]
441
+ for k, v in contact_source.items()
442
+ if isinstance(v, (str, int, float, bool))
443
+ }
444
+ errors: dict[str, str] = {}
445
+ if not agree_terms:
446
+ errors["agreeTerms"] = "You must agree to the terms to continue."
447
+ if frequency not in ("Monthly", "Annually"):
448
+ errors["frequency"] = "Choose Monthly or Annually."
449
+ if not scenario_id:
450
+ errors["scenario_id"] = "Choose a local payment simulation."
451
+ if errors:
452
+ return JSONResponse({"errors": errors}, status_code=422)
453
+ try:
454
+ result = db.enroll(
455
+ quote_id,
456
+ contact,
457
+ frequency,
458
+ agree_terms,
459
+ paperless,
460
+ scenario_id,
461
+ )
462
+ except EffectsMailDeliveryError:
463
+ return JSONResponse(
464
+ {
465
+ "errors": {
466
+ "mail": "The policy was saved, but confirmation delivery was deferred. Retry the same enrollment."
467
+ }
468
+ },
469
+ status_code=503,
470
+ )
471
+ except (PaymentError, MailError, ValueError) as exc:
472
+ return JSONResponse({"errors": {"payment": str(exc)}}, status_code=422)
473
+ if result is None:
474
+ return JSONResponse({"error": "not-found"}, status_code=404)
475
+ if not result["enrolled"]:
476
+ status_code = 402 if result["payment"]["status"] == "DECLINED" else 409
477
+ return JSONResponse(result, status_code=status_code)
478
+ return JSONResponse(
479
+ {
480
+ "policy_number": result["policy_number"],
481
+ "payment": result["payment"],
482
+ "mail": result["mail"],
483
+ },
484
+ status_code=200 if result.get("already") else 201,
485
+ )
486
+
487
+
488
+ # ---------------------------------------------------------------------------
489
+ # portal API — anonymous-only clone; member area is not reproduced
490
+ # ---------------------------------------------------------------------------
491
+
492
+ _PORTAL_UNAVAILABLE = (
493
+ "Member account access is not available in this offline clone."
494
+ )
495
+
496
+
497
+ @app.post("/portal/api/login", include_in_schema=False)
498
+ async def portal_login(request: Request) -> JSONResponse:
499
+ body = await _json_body(request)
500
+ errors: dict[str, str] = {}
501
+ if not _string(body.get("email")) and not _string(body.get("username")):
502
+ errors["email"] = "This field is required."
503
+ if not _string(body.get("password")):
504
+ errors["password"] = "This field is required."
505
+ if errors:
506
+ return JSONResponse({"errors": errors}, status_code=422)
507
+ return JSONResponse(
508
+ {"authenticated": False, "message": _PORTAL_UNAVAILABLE}, status_code=403
509
+ )
510
+
511
+
512
+ @app.post("/portal/api/forgot-password", include_in_schema=False)
513
+ async def portal_forgot_password(request: Request) -> JSONResponse:
514
+ body = await _json_body(request)
515
+ email = _string(body.get("email"))
516
+ if not email:
517
+ return JSONResponse(
518
+ {"errors": {"email": "This field is required."}}, status_code=422
519
+ )
520
+ return JSONResponse(
521
+ {"sent": False, "message": _PORTAL_UNAVAILABLE}, status_code=403
522
+ )
523
+
524
+
525
+ @app.post("/portal/api/register", include_in_schema=False)
526
+ async def portal_register(request: Request) -> JSONResponse:
527
+ body = await _json_body(request)
528
+ errors: dict[str, str] = {}
529
+ for field in ("email", "password"):
530
+ if not _string(body.get(field)):
531
+ errors[field] = "This field is required."
532
+ if errors:
533
+ return JSONResponse({"errors": errors}, status_code=422)
534
+ return JSONResponse(
535
+ {"registered": False, "message": _PORTAL_UNAVAILABLE}, status_code=403
536
+ )
tasks/aspca-pet-insurance/environment/reference/clone/backend/model.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "aspca-pet-insurance.clone-rating-model.v1",
3
+ "site_id": "aspca-pet-insurance",
4
+ "capture_id": "2026-08-13.aspca-pet-insurance-r1",
5
+ "evidence": "source-current/2026-08-13.aspca-pet-insurance-r1/rating-claims.json",
6
+ "notes": [
7
+ "Cumulative directly-observed walk (scenario 'willow': Cat, 2 Years, ZIP 44301, Female, Domestic Shorthair):",
8
+ "tier ladder at deductible $500 / reimbursement 80%: $2,500->$8.48, $5,000->$16.74, $10,000->$23.19 per month;",
9
+ "custom plan base 5000/500/80 = $16.74; deductible->$250 = $23.65; then reimbursement->90% = $30.83;",
10
+ "annual-limit re-select $5,000 = no delta; preventive Basic $9.95/mo, Prime $24.95/mo billed separately.",
11
+ "monthly = round_half_up(base_monthly[annual_limit] * deductible_factor * reimbursement_factor, 2).",
12
+ "Cells marked 'derived' are mechanical extensions for UI options the walk did not price:",
13
+ "deductible factors extend the single observed ratio 23.65/16.74 with a sqrt(500/d) fit (log2(observed ratio) = 0.4985 ~= 0.5);",
14
+ "reimbursement 70% mirrors the observed 90% delta linearly; limit $7,000 interpolates linearly between $5,000 and $10,000.",
15
+ "Derived cells are never presented as observed source prices.",
16
+ "Single-profile simplification: the observed profile is the only rated profile; other pet inputs reuse the same table (derived)."
17
+ ],
18
+ "rating_profile": {
19
+ "observed_inputs": {
20
+ "species": "Cat",
21
+ "age_label": "2 Years",
22
+ "zip": "44301",
23
+ "gender": "Female",
24
+ "breed": "Domestic Shorthair"
25
+ },
26
+ "profile_invariance": "derived"
27
+ },
28
+ "rounding": "round_half_up_2",
29
+ "tiers": [
30
+ {"id": "tier-2500", "annual_limit": 2500, "deductible": 500, "reimbursement": 80, "monthly": "8.48", "provenance": "directly-observed"},
31
+ {"id": "tier-5000", "annual_limit": 5000, "deductible": 500, "reimbursement": 80, "monthly": "16.74", "provenance": "directly-observed"},
32
+ {"id": "tier-10000", "annual_limit": 10000, "deductible": 500, "reimbursement": 80, "monthly": "23.19", "provenance": "directly-observed"}
33
+ ],
34
+ "custom_plan": {
35
+ "base_monthly_by_annual_limit": {
36
+ "2500": {"monthly": "8.48", "provenance": "directly-observed"},
37
+ "5000": {"monthly": "16.74", "provenance": "directly-observed"},
38
+ "7000": {"monthly": "19.32", "provenance": "derived"},
39
+ "10000": {"monthly": "23.19", "provenance": "directly-observed"}
40
+ },
41
+ "deductible_factors": {
42
+ "100": {"factor": "2.236068", "provenance": "derived"},
43
+ "250": {"factor": "1.412784", "provenance": "directly-observed", "anchor": "23.65 / 16.74"},
44
+ "500": {"factor": "1.0", "provenance": "directly-observed", "anchor": "base"},
45
+ "750": {"factor": "0.816497", "provenance": "derived"}
46
+ },
47
+ "reimbursement_factors": {
48
+ "70": {"factor": "0.696406", "provenance": "derived"},
49
+ "80": {"factor": "1.0", "provenance": "directly-observed", "anchor": "base"},
50
+ "90": {"factor": "1.303594", "provenance": "directly-observed", "anchor": "30.83 / 23.65"}
51
+ },
52
+ "control_values": {
53
+ "annual_limit": {"control": "annualLimitl2", "values": {"2500": "Limit2500", "5000": "Limit5000", "7000": "Limit7000", "10000": "Limit10000"}},
54
+ "deductible": {"control": "annualDeductiblel2", "values": {"100": "Deductible100", "250": "Deductible250", "500": "Deductible500", "750": "Deductible750"}},
55
+ "reimbursement": {"control": "reimbursementPercentl2", "values": {"70": "Copay30", "80": "Copay20", "90": "Copay10"}}
56
+ },
57
+ "unpriced_options": {
58
+ "annual_limit": [
59
+ {
60
+ "label": "Unlimited",
61
+ "control": "annualLimitl2",
62
+ "control_value": "LimitUnlimited",
63
+ "control_id": "Unlimitedl2",
64
+ "provenance": "directly-observed-option",
65
+ "note": "Visible in the captured rates/customize views but never priced during the observed walk; no defensible derivation exists, so the clone rating engine rejects it as off-table."
66
+ }
67
+ ]
68
+ }
69
+ },
70
+ "preventive": {
71
+ "basic": {"monthly": "9.95", "provenance": "directly-observed"},
72
+ "prime": {"monthly": "24.95", "provenance": "directly-observed"},
73
+ "billing": "separate-line-item"
74
+ },
75
+ "observed_checks": [
76
+ {"annual_limit": 5000, "deductible": 500, "reimbursement": 80, "expected_monthly": "16.74"},
77
+ {"annual_limit": 5000, "deductible": 250, "reimbursement": 80, "expected_monthly": "23.65"},
78
+ {"annual_limit": 5000, "deductible": 250, "reimbursement": 90, "expected_monthly": "30.83"},
79
+ {"annual_limit": 2500, "deductible": 500, "reimbursement": 80, "expected_monthly": "8.48"},
80
+ {"annual_limit": 10000, "deductible": 500, "reimbursement": 80, "expected_monthly": "23.19"}
81
+ ],
82
+ "zip_validation": {
83
+ "observed": {"zip": "00000", "message": "00000 is not a valid zip code."},
84
+ "rule": "five digits, not all zeros; message pattern '{zip} is not a valid zip code.'",
85
+ "rule_provenance": "derived (message format observed for 00000 only)"
86
+ }
87
+ }
tasks/aspca-pet-insurance/environment/reference/clone/backend/quotes_db.py ADDED
@@ -0,0 +1,756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ASPCA Pet Health Insurance offline clone — quote/enrollment persistence.
2
+
3
+ Owns the site's business schema (quotes, pets, plan selections, enrollments)
4
+ on top of the vendored ``websitebench.site_backend`` runtime, which owns the
5
+ library tables (accounts / sessions / OTP / mail outbox / payment ledger) in
6
+ the same SQLite file. Mirrors the tripit golden-sample layering:
7
+
8
+ * the runtime contract stays ``backend/runtime.json`` with
9
+ ``migration_hook: null`` / ``seed_hook: null`` — migrations are owned here
10
+ and recorded in ``aspca_schema_migrations``;
11
+ * one bound database file (``aspca-pet-insurance.sqlite3``) holds all state;
12
+ * deterministic identity: quote numbers and policy numbers derive from the
13
+ row id, timestamps are pinned to the frozen capture clock — no wall clock,
14
+ no randomness — so identical operation sequences yield identical state;
15
+ * :func:`reset` clears business rows and the library auth state atomically
16
+ (called by the test harness and ``POST /__admin/reset``).
17
+
18
+ Payment boundary: the source funnel was never advanced to payment, so the
19
+ clone adds a clearly labeled local-sandbox contract of its own. The client may
20
+ submit one opaque scenario id; amount, owner, currency and fingerprint are
21
+ server-derived. No credential or provider field is accepted.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import hashlib
27
+ import json
28
+ import re
29
+ import sqlite3
30
+ import threading
31
+ from contextlib import closing
32
+ from decimal import Decimal
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ from websitebench.local_clone_auth import LocalAuthStore
37
+ from websitebench.site_backend import SiteBackend
38
+
39
+ from backend.site_backend_integration import deliver_business_mail, open_site_services
40
+ from backend import rating
41
+
42
+ SITE_ID = "aspca-pet-insurance"
43
+
44
+ # Single frozen clock for the whole clone (capture day, UTC).
45
+ FROZEN_CLOCK_UTC = "2026-08-13T12:00:00Z"
46
+
47
+ _MIGRATIONS: dict[str, str] = {
48
+ "0001_quotes_core": """
49
+ CREATE TABLE IF NOT EXISTS aspca_quotes (
50
+ id INTEGER PRIMARY KEY,
51
+ quote_number TEXT NOT NULL UNIQUE,
52
+ email TEXT NOT NULL,
53
+ zip TEXT NOT NULL,
54
+ status TEXT NOT NULL DEFAULT 'open'
55
+ CHECK (status IN ('open', 'enrolled')),
56
+ created_at TEXT NOT NULL
57
+ );
58
+ CREATE INDEX IF NOT EXISTS idx_aspca_quotes_email_zip
59
+ ON aspca_quotes (email, zip);
60
+ CREATE TABLE IF NOT EXISTS aspca_pets (
61
+ id INTEGER PRIMARY KEY,
62
+ quote_id INTEGER NOT NULL
63
+ REFERENCES aspca_quotes (id) ON DELETE CASCADE,
64
+ species TEXT NOT NULL,
65
+ name TEXT NOT NULL,
66
+ age_label TEXT NOT NULL,
67
+ gender TEXT NOT NULL,
68
+ breed TEXT NOT NULL,
69
+ created_at TEXT NOT NULL
70
+ );
71
+ CREATE INDEX IF NOT EXISTS idx_aspca_pets_quote
72
+ ON aspca_pets (quote_id);
73
+ """,
74
+ "0002_selections": """
75
+ CREATE TABLE IF NOT EXISTS aspca_selections (
76
+ pet_id INTEGER PRIMARY KEY
77
+ REFERENCES aspca_pets (id) ON DELETE CASCADE,
78
+ annual_limit INTEGER NOT NULL,
79
+ deductible INTEGER NOT NULL,
80
+ reimbursement INTEGER NOT NULL,
81
+ preventive TEXT
82
+ CHECK (preventive IN ('basic', 'prime') OR preventive IS NULL),
83
+ monthly TEXT NOT NULL,
84
+ preventive_monthly TEXT NOT NULL,
85
+ provenance TEXT NOT NULL,
86
+ updated_at TEXT NOT NULL
87
+ );
88
+ """,
89
+ "0003_enrollments": """
90
+ CREATE TABLE IF NOT EXISTS aspca_enrollments (
91
+ id INTEGER PRIMARY KEY,
92
+ quote_id INTEGER NOT NULL UNIQUE
93
+ REFERENCES aspca_quotes (id) ON DELETE CASCADE,
94
+ policy_number TEXT NOT NULL UNIQUE,
95
+ contact_json TEXT NOT NULL,
96
+ frequency TEXT NOT NULL
97
+ CHECK (frequency IN ('Monthly', 'Annually')),
98
+ agree_terms INTEGER NOT NULL CHECK (agree_terms = 1),
99
+ paperless INTEGER NOT NULL CHECK (paperless IN (0, 1)),
100
+ created_at TEXT NOT NULL
101
+ );
102
+ """,
103
+ "0004_payment_enrollment": """
104
+ ALTER TABLE aspca_enrollments ADD COLUMN payment_flow_id TEXT;
105
+ ALTER TABLE aspca_enrollments ADD COLUMN payment_attempt_id TEXT;
106
+ ALTER TABLE aspca_enrollments ADD COLUMN amount_minor INTEGER;
107
+ ALTER TABLE aspca_enrollments ADD COLUMN currency TEXT;
108
+ ALTER TABLE aspca_enrollments ADD COLUMN fingerprint TEXT;
109
+ ALTER TABLE aspca_enrollments ADD COLUMN mail_id TEXT;
110
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_aspca_enrollments_payment_flow
111
+ ON aspca_enrollments (payment_flow_id)
112
+ WHERE payment_flow_id IS NOT NULL;
113
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_aspca_enrollments_payment_attempt
114
+ ON aspca_enrollments (payment_attempt_id)
115
+ WHERE payment_attempt_id IS NOT NULL;
116
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_aspca_enrollments_mail
117
+ ON aspca_enrollments (mail_id)
118
+ WHERE mail_id IS NOT NULL;
119
+ """,
120
+ }
121
+
122
+ # Defensive payment-boundary guard: no key that looks like a payment field may
123
+ # ever enter the business tables (the source funnel stopped before payment).
124
+ _PAYMENT_KEY_RE = re.compile(
125
+ r"(?i)(card|cc[-_]?(num|number|exp)|cvv|cvc|pan\b|iban|routing|account[-_]?number"
126
+ r"|expir|security[-_]?code|payment[-_]?(method|token)|stripe|bank)"
127
+ )
128
+ _SERVER_PAYMENT_FACT_KEYS = {
129
+ "adapter",
130
+ "amountminor",
131
+ "attemptid",
132
+ "currency",
133
+ "fingerprint",
134
+ "flowid",
135
+ "owner",
136
+ "providerreference",
137
+ "providersessionid",
138
+ }
139
+
140
+
141
+ class PaymentFieldRejected(ValueError):
142
+ """A card/payment-like key reached a business insert path."""
143
+
144
+
145
+ def reject_payment_keys(payload: dict[str, Any]) -> None:
146
+ for key in payload:
147
+ normalized = re.sub(r"[^a-z0-9]", "", str(key).casefold())
148
+ if (
149
+ _PAYMENT_KEY_RE.search(str(key))
150
+ or normalized in _SERVER_PAYMENT_FACT_KEYS
151
+ ):
152
+ raise PaymentFieldRejected(
153
+ f"payment-like field {key!r} is outside this clone's scope"
154
+ )
155
+
156
+
157
+ _SERVICES_LOCK = threading.Lock()
158
+ _SERVICES: tuple[SiteBackend, LocalAuthStore] | None = None
159
+
160
+
161
+ def services() -> tuple[SiteBackend, LocalAuthStore]:
162
+ """Process-wide backend + auth pair (bound database, schema ensured)."""
163
+
164
+ global _SERVICES
165
+ with _SERVICES_LOCK:
166
+ if _SERVICES is None:
167
+ backend, auth = open_site_services()
168
+ _ensure_business_schema(backend.lifecycle.database_path)
169
+ _SERVICES = (backend, auth)
170
+ return _SERVICES
171
+
172
+
173
+ def close_services() -> None:
174
+ """Drop the cached pair (tests re-open against fresh env paths)."""
175
+
176
+ global _SERVICES
177
+ with _SERVICES_LOCK:
178
+ _SERVICES = None
179
+
180
+
181
+ def database_path() -> Path:
182
+ return services()[0].lifecycle.database_path
183
+
184
+
185
+ def _connect(path: Path) -> sqlite3.Connection:
186
+ connection = sqlite3.connect(path)
187
+ connection.row_factory = sqlite3.Row
188
+ connection.execute("PRAGMA foreign_keys = ON")
189
+ return connection
190
+
191
+
192
+ def connect() -> sqlite3.Connection:
193
+ return _connect(database_path())
194
+
195
+
196
+ def _ensure_business_schema(path: Path) -> None:
197
+ with closing(_connect(path)) as connection, connection:
198
+ connection.execute(
199
+ """
200
+ CREATE TABLE IF NOT EXISTS aspca_schema_migrations (
201
+ migration_id TEXT PRIMARY KEY,
202
+ applied_at TEXT NOT NULL
203
+ )
204
+ """
205
+ )
206
+ applied = {
207
+ row["migration_id"]
208
+ for row in connection.execute(
209
+ "SELECT migration_id FROM aspca_schema_migrations"
210
+ )
211
+ }
212
+ for migration_id, ddl in _MIGRATIONS.items():
213
+ if migration_id in applied:
214
+ continue
215
+ connection.executescript(ddl)
216
+ connection.execute(
217
+ "INSERT INTO aspca_schema_migrations (migration_id, applied_at)"
218
+ " VALUES (?, ?)",
219
+ (migration_id, FROZEN_CLOCK_UTC),
220
+ )
221
+
222
+
223
+ def reset() -> None:
224
+ """Delete all site business, payment, mail and auth rows atomically."""
225
+
226
+ backend, auth = services()
227
+
228
+ def _site_reset(connection: sqlite3.Connection) -> None:
229
+ connection.execute("DELETE FROM aspca_enrollments")
230
+ connection.execute("DELETE FROM aspca_selections")
231
+ connection.execute("DELETE FROM aspca_pets")
232
+ connection.execute("DELETE FROM aspca_quotes")
233
+ backend.lifecycle.reset_embedded(
234
+ connection,
235
+ confirm_site_id=SITE_ID,
236
+ )
237
+
238
+ auth.reset_site_state(site_reset=_site_reset, seed_accounts=[])
239
+
240
+
241
+ # ---------------------------------------------------------------------------
242
+ # quotes
243
+ # ---------------------------------------------------------------------------
244
+
245
+
246
+ def _quote_number(row_id: int) -> str:
247
+ return f"WB{100000 + row_id}"
248
+
249
+
250
+ def _policy_number(quote_row_id: int) -> str:
251
+ return f"APH-{quote_row_id:06d}"
252
+
253
+
254
+ def _pet_public(row: sqlite3.Row) -> dict[str, Any]:
255
+ return {
256
+ "pet_id": row["id"],
257
+ "species": row["species"],
258
+ "name": row["name"],
259
+ "age_label": row["age_label"],
260
+ "gender": row["gender"],
261
+ "breed": row["breed"],
262
+ }
263
+
264
+
265
+ def _selection_public(row: sqlite3.Row | None) -> dict[str, Any] | None:
266
+ if row is None:
267
+ return None
268
+ return {
269
+ "annual_limit": row["annual_limit"],
270
+ "deductible": row["deductible"],
271
+ "reimbursement": row["reimbursement"],
272
+ "preventive": row["preventive"],
273
+ "monthly": row["monthly"],
274
+ "preventive_monthly": row["preventive_monthly"],
275
+ "provenance": row["provenance"],
276
+ }
277
+
278
+
279
+ def create_quote(pet: dict[str, str], email: str, zip_code: str) -> dict[str, Any]:
280
+ """Create a quote with its first pet and the default rating selection."""
281
+
282
+ reject_payment_keys(pet)
283
+ default = rating.rate(5000, 500, 80, None)
284
+ with closing(connect()) as connection, connection:
285
+ cursor = connection.execute(
286
+ "INSERT INTO aspca_quotes (quote_number, email, zip, created_at)"
287
+ " VALUES ('', ?, ?, ?)",
288
+ (email, zip_code, FROZEN_CLOCK_UTC),
289
+ )
290
+ quote_row_id = cursor.lastrowid
291
+ connection.execute(
292
+ "UPDATE aspca_quotes SET quote_number = ? WHERE id = ?",
293
+ (_quote_number(quote_row_id), quote_row_id),
294
+ )
295
+ pet_row = connection.execute(
296
+ "INSERT INTO aspca_pets"
297
+ " (quote_id, species, name, age_label, gender, breed, created_at)"
298
+ " VALUES (?, ?, ?, ?, ?, ?, ?)",
299
+ (
300
+ quote_row_id,
301
+ pet["species"],
302
+ pet["name"],
303
+ pet["age_label"],
304
+ pet["gender"],
305
+ pet["breed"],
306
+ FROZEN_CLOCK_UTC,
307
+ ),
308
+ )
309
+ connection.execute(
310
+ "INSERT INTO aspca_selections"
311
+ " (pet_id, annual_limit, deductible, reimbursement, preventive,"
312
+ " monthly, preventive_monthly, provenance, updated_at)"
313
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
314
+ (
315
+ pet_row.lastrowid,
316
+ default["annual_limit"],
317
+ default["deductible"],
318
+ default["reimbursement"],
319
+ None,
320
+ default["monthly"],
321
+ default["preventive_monthly"],
322
+ default["provenance"],
323
+ FROZEN_CLOCK_UTC,
324
+ ),
325
+ )
326
+ return get_quote(_quote_number(quote_row_id)) # type: ignore[return-value]
327
+
328
+
329
+ def _quote_row(
330
+ connection: sqlite3.Connection, quote_number: str
331
+ ) -> sqlite3.Row | None:
332
+ return connection.execute(
333
+ "SELECT * FROM aspca_quotes WHERE quote_number = ?", (quote_number,)
334
+ ).fetchone()
335
+
336
+
337
+ def get_quote(quote_number: str) -> dict[str, Any] | None:
338
+ with closing(connect()) as connection:
339
+ quote = _quote_row(connection, quote_number)
340
+ if quote is None:
341
+ return None
342
+ pets = []
343
+ for pet_row in connection.execute(
344
+ "SELECT * FROM aspca_pets WHERE quote_id = ? ORDER BY id",
345
+ (quote["id"],),
346
+ ):
347
+ selection = connection.execute(
348
+ "SELECT * FROM aspca_selections WHERE pet_id = ?",
349
+ (pet_row["id"],),
350
+ ).fetchone()
351
+ entry = _pet_public(pet_row)
352
+ entry["selection"] = _selection_public(selection)
353
+ pets.append(entry)
354
+ enrollment = connection.execute(
355
+ "SELECT policy_number, frequency, paperless, created_at,"
356
+ " payment_flow_id, payment_attempt_id, amount_minor, currency, mail_id"
357
+ " FROM aspca_enrollments WHERE quote_id = ?",
358
+ (quote["id"],),
359
+ ).fetchone()
360
+ return {
361
+ "quote_id": quote["quote_number"],
362
+ "email": quote["email"],
363
+ "zip": quote["zip"],
364
+ "status": quote["status"],
365
+ "created_at": quote["created_at"],
366
+ "pets": pets,
367
+ "tiers": rating.tiers(),
368
+ "enrollment": (
369
+ {
370
+ "policy_number": enrollment["policy_number"],
371
+ "frequency": enrollment["frequency"],
372
+ "paperless": bool(enrollment["paperless"]),
373
+ "created_at": enrollment["created_at"],
374
+ "payment": {
375
+ "flow_id": enrollment["payment_flow_id"],
376
+ "attempt_id": enrollment["payment_attempt_id"],
377
+ "amount_minor": enrollment["amount_minor"],
378
+ "currency": enrollment["currency"],
379
+ "is_simulation": True,
380
+ },
381
+ "mail_id": enrollment["mail_id"],
382
+ }
383
+ if enrollment is not None
384
+ else None
385
+ ),
386
+ }
387
+
388
+
389
+ def find_quote(email: str, zip_code: str) -> dict[str, Any] | None:
390
+ """Resume lookup: newest open quote for the email + ZIP pair."""
391
+
392
+ with closing(connect()) as connection:
393
+ row = connection.execute(
394
+ "SELECT quote_number FROM aspca_quotes"
395
+ " WHERE email = ? AND zip = ? ORDER BY id DESC LIMIT 1",
396
+ (email, zip_code),
397
+ ).fetchone()
398
+ if row is None:
399
+ return None
400
+ return get_quote(row["quote_number"])
401
+
402
+
403
+ def add_pet(quote_number: str, pet: dict[str, str]) -> dict[str, Any] | None:
404
+ reject_payment_keys(pet)
405
+ default = rating.rate(5000, 500, 80, None)
406
+ with closing(connect()) as connection, connection:
407
+ quote = _quote_row(connection, quote_number)
408
+ if quote is None:
409
+ return None
410
+ pet_row = connection.execute(
411
+ "INSERT INTO aspca_pets"
412
+ " (quote_id, species, name, age_label, gender, breed, created_at)"
413
+ " VALUES (?, ?, ?, ?, ?, ?, ?)",
414
+ (
415
+ quote["id"],
416
+ pet["species"],
417
+ pet["name"],
418
+ pet["age_label"],
419
+ pet["gender"],
420
+ pet["breed"],
421
+ FROZEN_CLOCK_UTC,
422
+ ),
423
+ )
424
+ connection.execute(
425
+ "INSERT INTO aspca_selections"
426
+ " (pet_id, annual_limit, deductible, reimbursement, preventive,"
427
+ " monthly, preventive_monthly, provenance, updated_at)"
428
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
429
+ (
430
+ pet_row.lastrowid,
431
+ default["annual_limit"],
432
+ default["deductible"],
433
+ default["reimbursement"],
434
+ None,
435
+ default["monthly"],
436
+ default["preventive_monthly"],
437
+ default["provenance"],
438
+ FROZEN_CLOCK_UTC,
439
+ ),
440
+ )
441
+ return get_quote(quote_number)
442
+
443
+
444
+ def apply_rate(
445
+ quote_number: str,
446
+ annual_limit: int,
447
+ deductible: int,
448
+ reimbursement: int,
449
+ preventive: str | None,
450
+ pet_id: int | None = None,
451
+ ) -> dict[str, Any] | None:
452
+ """Re-price one pet's custom selection (defaults to the first pet)."""
453
+
454
+ priced = rating.rate(annual_limit, deductible, reimbursement, preventive)
455
+ with closing(connect()) as connection, connection:
456
+ quote = _quote_row(connection, quote_number)
457
+ if quote is None:
458
+ return None
459
+ if pet_id is None:
460
+ pet = connection.execute(
461
+ "SELECT id FROM aspca_pets WHERE quote_id = ? ORDER BY id LIMIT 1",
462
+ (quote["id"],),
463
+ ).fetchone()
464
+ else:
465
+ pet = connection.execute(
466
+ "SELECT id FROM aspca_pets WHERE quote_id = ? AND id = ?",
467
+ (quote["id"], pet_id),
468
+ ).fetchone()
469
+ if pet is None:
470
+ return None
471
+ connection.execute(
472
+ "UPDATE aspca_selections SET annual_limit = ?, deductible = ?,"
473
+ " reimbursement = ?, preventive = ?, monthly = ?,"
474
+ " preventive_monthly = ?, provenance = ?, updated_at = ?"
475
+ " WHERE pet_id = ?",
476
+ (
477
+ priced["annual_limit"],
478
+ priced["deductible"],
479
+ priced["reimbursement"],
480
+ priced["preventive"],
481
+ priced["monthly"],
482
+ priced["preventive_monthly"],
483
+ priced["provenance"],
484
+ FROZEN_CLOCK_UTC,
485
+ pet["id"],
486
+ ),
487
+ )
488
+ return priced
489
+
490
+
491
+ def enroll(
492
+ quote_number: str,
493
+ contact: dict[str, str],
494
+ frequency: str,
495
+ agree_terms: bool,
496
+ paperless: bool,
497
+ scenario_id: str,
498
+ ) -> dict[str, Any] | None:
499
+ """Commit a synthetic enrollment, then deliver its confirmation."""
500
+
501
+ result = _enroll_transaction(
502
+ quote_number,
503
+ contact,
504
+ frequency,
505
+ agree_terms,
506
+ paperless,
507
+ scenario_id,
508
+ )
509
+ if result is None or not result.get("enrolled"):
510
+ return result
511
+ backend, _auth = services()
512
+ settled = deliver_business_mail(backend, str(result["mail"]["mail_id"]))
513
+ if settled is not None:
514
+ result["mail"]["status"] = settled["status"]
515
+ result["mail"]["is_simulation"] = bool(settled["is_simulation"])
516
+ return result
517
+
518
+
519
+ def _enroll_transaction(
520
+ quote_number: str,
521
+ contact: dict[str, str],
522
+ frequency: str,
523
+ agree_terms: bool,
524
+ paperless: bool,
525
+ scenario_id: str,
526
+ ) -> dict[str, Any] | None:
527
+ """Attempt local payment and atomically create policy + local mail."""
528
+
529
+ reject_payment_keys(contact)
530
+ if frequency not in ("Monthly", "Annually"):
531
+ raise ValueError("frequency must be Monthly or Annually")
532
+ if not agree_terms:
533
+ raise ValueError("agree_terms must be accepted")
534
+ if not isinstance(scenario_id, str) or not scenario_id:
535
+ raise ValueError("scenario_id is required")
536
+
537
+ backend, _auth = services()
538
+ with backend.lifecycle.connection(transaction=True) as connection:
539
+ quote = _quote_row(connection, quote_number)
540
+ if quote is None:
541
+ return None
542
+ existing = connection.execute(
543
+ "SELECT * FROM aspca_enrollments WHERE quote_id = ?",
544
+ (quote["id"],),
545
+ ).fetchone()
546
+ if existing is not None:
547
+ return _enrollment_result(connection, existing, already=True)
548
+
549
+ facts = _payment_facts(
550
+ connection,
551
+ quote,
552
+ contact=contact,
553
+ frequency=frequency,
554
+ )
555
+ flow = backend.payments.create_intent(
556
+ owner=facts["owner"],
557
+ amount_minor=facts["amount_minor"],
558
+ currency=facts["currency"],
559
+ fingerprint=facts["fingerprint"],
560
+ idempotency_key=(
561
+ f"aspca.create:{quote_number}:{facts['fingerprint']}"
562
+ ),
563
+ connection=connection,
564
+ )
565
+ attempt = backend.payments.attempt(
566
+ flow_id=flow["flow_id"],
567
+ owner=facts["owner"],
568
+ amount_minor=facts["amount_minor"],
569
+ currency=facts["currency"],
570
+ fingerprint=facts["fingerprint"],
571
+ scenario_id=scenario_id,
572
+ idempotency_key=(
573
+ f"aspca.attempt:{quote_number}:"
574
+ f"{facts['fingerprint'][:32]}:{scenario_id}"
575
+ ),
576
+ connection=connection,
577
+ )
578
+ if attempt["status"] != "APPROVED":
579
+ return {
580
+ "enrolled": False,
581
+ "payment": _payment_result(flow, attempt),
582
+ }
583
+
584
+ consumed = backend.payments.consume_approval(
585
+ connection,
586
+ flow_id=flow["flow_id"],
587
+ owner=facts["owner"],
588
+ amount_minor=facts["amount_minor"],
589
+ currency=facts["currency"],
590
+ fingerprint=facts["fingerprint"],
591
+ )
592
+ policy_number = _policy_number(quote["id"])
593
+ connection.execute(
594
+ "INSERT INTO aspca_enrollments"
595
+ " (quote_id, policy_number, contact_json, frequency, agree_terms,"
596
+ " paperless, created_at, payment_flow_id, payment_attempt_id,"
597
+ " amount_minor, currency, fingerprint)"
598
+ " VALUES (?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?)",
599
+ (
600
+ quote["id"],
601
+ policy_number,
602
+ json.dumps(contact, sort_keys=True),
603
+ frequency,
604
+ 1 if paperless else 0,
605
+ FROZEN_CLOCK_UTC,
606
+ flow["flow_id"],
607
+ consumed["attempt_id"],
608
+ facts["amount_minor"],
609
+ facts["currency"],
610
+ facts["fingerprint"],
611
+ ),
612
+ )
613
+ connection.execute(
614
+ "UPDATE aspca_quotes SET status = 'enrolled' WHERE id = ?",
615
+ (quote["id"],),
616
+ )
617
+ mail = backend.mail.enqueue(
618
+ "policy-confirmation",
619
+ facts["recipient"],
620
+ {
621
+ "policy_number": policy_number,
622
+ "pet_name": facts["pet_name"],
623
+ "frequency": frequency,
624
+ "amount": f"{Decimal(facts['amount_minor']) / Decimal(100):.2f}",
625
+ "currency": facts["currency"],
626
+ },
627
+ idempotency_key=f"aspca.mail:{policy_number}",
628
+ simulation=False,
629
+ connection=connection,
630
+ )
631
+ connection.execute(
632
+ "UPDATE aspca_enrollments SET mail_id = ? WHERE quote_id = ?",
633
+ (mail["mail_id"], quote["id"]),
634
+ )
635
+ enrollment = connection.execute(
636
+ "SELECT * FROM aspca_enrollments WHERE quote_id = ?",
637
+ (quote["id"],),
638
+ ).fetchone()
639
+ return _enrollment_result(connection, enrollment, already=False)
640
+
641
+
642
+ def _minor_units(value: str) -> int:
643
+ amount = Decimal(value) * 100
644
+ if amount != amount.to_integral_value():
645
+ raise ValueError("quoted amount must have integer minor units")
646
+ return int(amount)
647
+
648
+
649
+ def _payment_facts(
650
+ connection: sqlite3.Connection,
651
+ quote: sqlite3.Row,
652
+ *,
653
+ contact: dict[str, str],
654
+ frequency: str,
655
+ ) -> dict[str, Any]:
656
+ rows = connection.execute(
657
+ "SELECT p.id, p.species, p.name, p.age_label, p.gender, p.breed,"
658
+ " s.annual_limit, s.deductible, s.reimbursement, s.preventive,"
659
+ " s.monthly, s.preventive_monthly"
660
+ " FROM aspca_pets AS p"
661
+ " JOIN aspca_selections AS s ON s.pet_id = p.id"
662
+ " WHERE p.quote_id = ? ORDER BY p.id",
663
+ (quote["id"],),
664
+ ).fetchall()
665
+ monthly_minor = sum(
666
+ _minor_units(row["monthly"]) + _minor_units(row["preventive_monthly"])
667
+ for row in rows
668
+ )
669
+ amount_minor = monthly_minor if frequency == "Monthly" else monthly_minor * 12
670
+ recipient = str(contact.get("email") or quote["email"]).strip().casefold()
671
+ snapshot = {
672
+ "site_id": SITE_ID,
673
+ "quote_id": quote["quote_number"],
674
+ "frequency": frequency,
675
+ "contact_email": recipient,
676
+ "pets": [
677
+ {
678
+ "pet_id": row["id"],
679
+ "species": row["species"],
680
+ "name": row["name"],
681
+ "age_label": row["age_label"],
682
+ "gender": row["gender"],
683
+ "breed": row["breed"],
684
+ "annual_limit": row["annual_limit"],
685
+ "deductible": row["deductible"],
686
+ "reimbursement": row["reimbursement"],
687
+ "preventive": row["preventive"],
688
+ "monthly": row["monthly"],
689
+ "preventive_monthly": row["preventive_monthly"],
690
+ }
691
+ for row in rows
692
+ ],
693
+ "amount_minor": amount_minor,
694
+ "currency": "USD",
695
+ }
696
+ canonical = json.dumps(
697
+ snapshot,
698
+ ensure_ascii=False,
699
+ sort_keys=True,
700
+ separators=(",", ":"),
701
+ )
702
+ names = [str(row["name"]) for row in rows]
703
+ return {
704
+ "owner": f"quote:{quote['quote_number']}",
705
+ "amount_minor": amount_minor,
706
+ "currency": "USD",
707
+ "fingerprint": hashlib.sha256(canonical.encode("utf-8")).hexdigest(),
708
+ "recipient": recipient,
709
+ "pet_name": names[0] if len(names) == 1 else f"{names[0]} + {len(names) - 1} more",
710
+ }
711
+
712
+
713
+ def _payment_result(flow: sqlite3.Row | dict, attempt: sqlite3.Row | dict) -> dict[str, Any]:
714
+ return {
715
+ "flow_id": flow["flow_id"],
716
+ "attempt_id": attempt["attempt_id"],
717
+ "status": attempt["status"],
718
+ "amount_minor": int(flow["amount_minor"]),
719
+ "currency": flow["currency"],
720
+ "is_simulation": bool(flow["is_simulation"]),
721
+ }
722
+
723
+
724
+ def _enrollment_result(
725
+ connection: sqlite3.Connection,
726
+ enrollment: sqlite3.Row,
727
+ *,
728
+ already: bool,
729
+ ) -> dict[str, Any]:
730
+ flow = connection.execute(
731
+ "SELECT * FROM websitebench_payment_flows WHERE flow_id = ?",
732
+ (enrollment["payment_flow_id"],),
733
+ ).fetchone()
734
+ attempt = connection.execute(
735
+ "SELECT * FROM websitebench_payment_attempts WHERE attempt_id = ?",
736
+ (enrollment["payment_attempt_id"],),
737
+ ).fetchone()
738
+ mail = connection.execute(
739
+ "SELECT * FROM websitebench_mail_jobs WHERE mail_id = ?",
740
+ (enrollment["mail_id"],),
741
+ ).fetchone()
742
+ return {
743
+ "policy_number": enrollment["policy_number"],
744
+ "already": already,
745
+ "enrolled": True,
746
+ "payment": {
747
+ **_payment_result(flow, attempt),
748
+ "status": flow["status"],
749
+ },
750
+ "mail": {
751
+ "mail_id": mail["mail_id"],
752
+ "purpose": mail["purpose"],
753
+ "status": mail["status"],
754
+ "is_simulation": bool(mail["is_simulation"]),
755
+ },
756
+ }
tasks/aspca-pet-insurance/environment/reference/clone/backend/rating.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ASPCA Pet Health Insurance offline clone — deterministic rating engine.
2
+
3
+ Encodes the rating table frozen in ``clone/backend/model.json``, which in turn
4
+ carries the directly-observed price walk from
5
+ ``source-current/2026-08-13.aspca-pet-insurance-r1/rating-claims.json``.
6
+
7
+ Model: ``monthly = round_half_up(base_monthly[annual_limit] * deductible_factor
8
+ * reimbursement_factor, 2)``. Cells the source walk did not price are marked
9
+ ``derived`` in the model and surfaced through :func:`provenance` so callers can
10
+ report honestly which prices were observed on the source site and which are
11
+ mechanical extensions.
12
+
13
+ No wall clock, no randomness: identical inputs always price identically.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ from decimal import ROUND_HALF_UP, Decimal
20
+ from functools import lru_cache
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ MODEL_PATH = Path(__file__).resolve().parent / "model.json"
25
+
26
+ _CENT = Decimal("0.01")
27
+
28
+
29
+ class RatingError(ValueError):
30
+ """Raised for an option value outside the frozen rating table."""
31
+
32
+
33
+ @lru_cache(maxsize=1)
34
+ def load_model() -> dict[str, Any]:
35
+ return json.loads(MODEL_PATH.read_text(encoding="utf-8"))
36
+
37
+
38
+ def _round_half_up(value: Decimal) -> Decimal:
39
+ return value.quantize(_CENT, rounding=ROUND_HALF_UP)
40
+
41
+
42
+ def annual_limits() -> list[int]:
43
+ model = load_model()
44
+ return sorted(int(k) for k in model["custom_plan"]["base_monthly_by_annual_limit"])
45
+
46
+
47
+ def deductibles() -> list[int]:
48
+ model = load_model()
49
+ return sorted(int(k) for k in model["custom_plan"]["deductible_factors"])
50
+
51
+
52
+ def reimbursements() -> list[int]:
53
+ model = load_model()
54
+ return sorted(int(k) for k in model["custom_plan"]["reimbursement_factors"])
55
+
56
+
57
+ def tiers() -> list[dict[str, Any]]:
58
+ """The three source tier cards (limit/deductible/reimbursement/monthly)."""
59
+
60
+ model = load_model()
61
+ return [
62
+ {
63
+ "id": tier["id"],
64
+ "annual_limit": tier["annual_limit"],
65
+ "deductible": tier["deductible"],
66
+ "reimbursement": tier["reimbursement"],
67
+ "monthly": tier["monthly"],
68
+ "provenance": tier["provenance"],
69
+ }
70
+ for tier in model["tiers"]
71
+ ]
72
+
73
+
74
+ def _cell(table: dict[str, Any], key: int, label: str) -> dict[str, Any]:
75
+ cell = table.get(str(key))
76
+ if cell is None:
77
+ raise RatingError(f"{label} {key} is not in the rating table")
78
+ return cell
79
+
80
+
81
+ def preventive_monthly(option: str | None) -> tuple[Decimal, str | None]:
82
+ """Monthly price of the separately-billed preventive add-on (0 if none)."""
83
+
84
+ if option in (None, "", "none"):
85
+ return Decimal("0.00"), None
86
+ model = load_model()
87
+ cell = model["preventive"].get(option)
88
+ if not isinstance(cell, dict):
89
+ raise RatingError(f"preventive option {option!r} is not in the rating table")
90
+ return Decimal(cell["monthly"]), cell["provenance"]
91
+
92
+
93
+ def rate(
94
+ annual_limit: int,
95
+ deductible: int,
96
+ reimbursement: int,
97
+ preventive: str | None = None,
98
+ ) -> dict[str, Any]:
99
+ """Price one custom-plan selection.
100
+
101
+ Returns monthly plan price, separately-billed preventive price, the total
102
+ of the two, and provenance (``directly-observed`` only when every factor in
103
+ the multiplication was observed on the source walk, else ``derived``).
104
+ """
105
+
106
+ model = load_model()
107
+ custom = model["custom_plan"]
108
+ base = _cell(custom["base_monthly_by_annual_limit"], annual_limit, "annual limit")
109
+ ded = _cell(custom["deductible_factors"], deductible, "deductible")
110
+ reimb = _cell(custom["reimbursement_factors"], reimbursement, "reimbursement")
111
+
112
+ monthly = _round_half_up(
113
+ Decimal(base["monthly"]) * Decimal(ded["factor"]) * Decimal(reimb["factor"])
114
+ )
115
+ parts = (base["provenance"], ded["provenance"], reimb["provenance"])
116
+ provenance = (
117
+ "directly-observed"
118
+ if all(p == "directly-observed" for p in parts)
119
+ else "derived"
120
+ )
121
+ preventive_price, preventive_provenance = preventive_monthly(preventive)
122
+ return {
123
+ "annual_limit": annual_limit,
124
+ "deductible": deductible,
125
+ "reimbursement": reimbursement,
126
+ "monthly": f"{monthly:.2f}",
127
+ "preventive": preventive if preventive not in ("", "none") else None,
128
+ "preventive_monthly": f"{preventive_price:.2f}",
129
+ "preventive_provenance": preventive_provenance,
130
+ "total_monthly": f"{_round_half_up(monthly + preventive_price):.2f}",
131
+ "provenance": provenance,
132
+ }
133
+
134
+
135
+ def valid_zip(zip_code: str) -> bool:
136
+ """Frozen ZIP rule: five digits, not all zeros (observed probe: 00000)."""
137
+
138
+ return len(zip_code) == 5 and zip_code.isdigit() and zip_code != "00000"
139
+
140
+
141
+ def zip_error_message(zip_code: str) -> str:
142
+ """Observed message format ('00000 is not a valid zip code.')."""
143
+
144
+ return f"{zip_code} is not a valid zip code."
tasks/aspca-pet-insurance/environment/reference/clone/backend/site_backend_integration.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ EffectsMailDelivery,
15
+ EffectsMailDeliveryError,
16
+ SiteBackend,
17
+ load_runtime,
18
+ serve_jsonl,
19
+ validate_allowlist,
20
+ )
21
+ from websitebench.site_backend.errors import MailError
22
+ from websitebench.site_backend.effects_mail import (
23
+ EFFECTS_GATEWAY_PATH,
24
+ EFFECTS_MAIL_USER_AGENT,
25
+ )
26
+ from websitebench.site_backend.transport import resolve_transport
27
+
28
+
29
+ DEFAULT_RUNTIME_PATH = (
30
+ Path(__file__).resolve().parents[2] / "backend" / "runtime.json"
31
+ )
32
+ BRIDGE_DESCRIPTOR_PATH = (
33
+ Path(__file__).resolve().parents[2] / "backend" / "node-bridge.json"
34
+ )
35
+ DEFAULT_DEPLOYMENT_PROFILE = "offline-harbor"
36
+ DEPLOYMENT_PROFILE_ENV = "WEBSITEBENCH_DEPLOYMENT_PROFILE"
37
+
38
+
39
+ def _declared_hook(
40
+ declaration: str | None,
41
+ ) -> Callable[[sqlite3.Connection], None] | None:
42
+ if declaration is None:
43
+ return None
44
+ module_name, function_name = declaration.split(":", 1)
45
+ module = importlib.import_module(module_name)
46
+ hook: Any = getattr(module, function_name, None)
47
+ if not callable(hook):
48
+ raise RuntimeError(f"declared backend hook is not callable: {declaration}")
49
+ actual = f"{hook.__module__}:{hook.__name__}"
50
+ if actual != declaration:
51
+ raise RuntimeError(
52
+ f"declared backend hook resolved as {actual!r}, expected {declaration!r}"
53
+ )
54
+ return hook
55
+
56
+
57
+ def open_site_services() -> tuple[SiteBackend, LocalAuthStore]:
58
+ """Open one bound database; never omit the site id for permanent auth."""
59
+
60
+ runtime_path = Path(
61
+ os.environ.get(
62
+ "WEBSITEBENCH_SITE_BACKEND_RUNTIME",
63
+ str(DEFAULT_RUNTIME_PATH),
64
+ )
65
+ ).resolve()
66
+ runtime = load_runtime(runtime_path)
67
+ migration_hook = _declared_hook(runtime.migration_hook)
68
+ seed_hook = _declared_hook(runtime.seed_hook)
69
+ deployed_database = os.environ.get(
70
+ "WEBSITEBENCH_SITE_BACKEND_DATABASE",
71
+ )
72
+ if deployed_database is None:
73
+ backend = SiteBackend.open(
74
+ runtime_path,
75
+ migration_hook=migration_hook,
76
+ seed_hook=seed_hook,
77
+ )
78
+ else:
79
+ database_path = Path(deployed_database).resolve()
80
+ if database_path.name != runtime.database_filename:
81
+ raise RuntimeError(
82
+ "deployed database filename does not match runtime contract"
83
+ )
84
+ backend = SiteBackend.open(
85
+ json.loads(runtime_path.read_text(encoding="utf-8")),
86
+ data_root=database_path.parent,
87
+ migration_hook=migration_hook,
88
+ seed_hook=seed_hook,
89
+ )
90
+ if backend.lifecycle.database_path != database_path:
91
+ raise RuntimeError(
92
+ "deployed database path does not match backend preflight"
93
+ )
94
+ backend.lifecycle.initialize()
95
+ auth = LocalAuthStore(
96
+ backend.lifecycle.database_path,
97
+ site_id=backend.config.site_id,
98
+ )
99
+ auth.ensure_schema()
100
+ return backend, auth
101
+
102
+
103
+ def deliver_business_mail(
104
+ backend: SiteBackend,
105
+ mail_id: str,
106
+ ) -> dict[str, Any] | None:
107
+ """Deliver one committed business-mail row through the frozen profile."""
108
+
109
+ profile = os.environ.get(
110
+ DEPLOYMENT_PROFILE_ENV, DEFAULT_DEPLOYMENT_PROFILE
111
+ ).strip() or DEFAULT_DEPLOYMENT_PROFILE
112
+ try:
113
+ transport = resolve_transport(
114
+ backend.mail,
115
+ profile,
116
+ user_agent=EFFECTS_MAIL_USER_AGENT.format(
117
+ site_id=backend.config.site_id
118
+ ),
119
+ gateway_path=EFFECTS_GATEWAY_PATH,
120
+ )
121
+ return EffectsMailDelivery(
122
+ backend,
123
+ transport=transport,
124
+ retry_delay_seconds=0,
125
+ ).deliver(mail_id=mail_id)
126
+ except MailError as exc:
127
+ raise EffectsMailDeliveryError(
128
+ "business mail delivery was deferred"
129
+ ) from exc
130
+
131
+
132
+ def run_stdio_bridge() -> None:
133
+ """Run only operations frozen in this site's descriptor."""
134
+
135
+ backend, auth = open_site_services()
136
+ descriptor = json.loads(BRIDGE_DESCRIPTOR_PATH.read_text(encoding="utf-8"))
137
+ allowed = validate_allowlist(
138
+ descriptor,
139
+ expected_site_id=backend.config.site_id,
140
+ )
141
+ serve_jsonl(backend, auth, allowed, sys.stdin, sys.stdout)
142
+
143
+
144
+ if __name__ == "__main__":
145
+ import argparse
146
+ import sys
147
+
148
+ parser = argparse.ArgumentParser(prog="websitebench-node-backend-bridge")
149
+ parser.add_argument("--stdio", action="store_true", required=True)
150
+ parser.parse_args()
151
+ run_stdio_bridge()
tasks/aspca-pet-insurance/environment/reference/clone/frontend/css-localize-report.json ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_totals": {
3
+ "files_rewritten": 9,
4
+ "mapped": 156,
5
+ "deterministic": 47,
6
+ "missing_payloads": 47,
7
+ "remaining_remote_total": 0
8
+ },
9
+ "static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/ezj2kxi.css": {
10
+ "mapped": 37,
11
+ "deterministic": 18,
12
+ "missing_payloads": [
13
+ {
14
+ "reference": "https://use.typekit.net/af/e3ed45/00000000000000007735e602/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
15
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/e3ed45/00000000000000007735e602/30/a"
16
+ },
17
+ {
18
+ "reference": "https://use.typekit.net/af/2555e1/00000000000000007735e603/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
19
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/2555e1/00000000000000007735e603/30/a"
20
+ },
21
+ {
22
+ "reference": "https://use.typekit.net/af/4de20a/00000000000000007735e604/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
23
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/4de20a/00000000000000007735e604/30/a"
24
+ },
25
+ {
26
+ "reference": "https://use.typekit.net/af/8738d8/00000000000000007735e611/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
27
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/8738d8/00000000000000007735e611/30/a"
28
+ },
29
+ {
30
+ "reference": "https://use.typekit.net/af/154cda/00000000000000007735e601/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
31
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/154cda/00000000000000007735e601/30/a"
32
+ },
33
+ {
34
+ "reference": "https://use.typekit.net/af/78aca8/00000000000000007735e60d/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
35
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/78aca8/00000000000000007735e60d/30/a"
36
+ },
37
+ {
38
+ "reference": "https://use.typekit.net/af/efe4a5/00000000000000007735e609/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
39
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/efe4a5/00000000000000007735e609/30/a"
40
+ },
41
+ {
42
+ "reference": "https://use.typekit.net/af/3322cc/00000000000000007735e616/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
43
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/3322cc/00000000000000007735e616/30/a"
44
+ },
45
+ {
46
+ "reference": "https://use.typekit.net/af/1be3c2/00000000000000007735e606/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
47
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/1be3c2/00000000000000007735e606/30/a"
48
+ },
49
+ {
50
+ "reference": "https://use.typekit.net/af/23e139/00000000000000007735e605/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
51
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/23e139/00000000000000007735e605/30/a"
52
+ },
53
+ {
54
+ "reference": "https://use.typekit.net/af/15606c/00000000000000007735e60c/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
55
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/15606c/00000000000000007735e60c/30/a"
56
+ },
57
+ {
58
+ "reference": "https://use.typekit.net/af/1ea53e/00000000000000007735e61d/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
59
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/1ea53e/00000000000000007735e61d/30/a"
60
+ },
61
+ {
62
+ "reference": "https://use.typekit.net/af/669f97/00000000000000007735e623/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
63
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/669f97/00000000000000007735e623/30/a"
64
+ },
65
+ {
66
+ "reference": "https://use.typekit.net/af/4d69d6/00000000000000007735e62c/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
67
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/4d69d6/00000000000000007735e62c/30/a"
68
+ },
69
+ {
70
+ "reference": "https://use.typekit.net/af/de3701/00000000000000007735e618/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
71
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/de3701/00000000000000007735e618/30/a"
72
+ },
73
+ {
74
+ "reference": "https://use.typekit.net/af/7cc641/00000000000000007735e60b/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
75
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/7cc641/00000000000000007735e60b/30/a"
76
+ },
77
+ {
78
+ "reference": "https://use.typekit.net/af/6a4fa5/00000000000000007735e629/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
79
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/6a4fa5/00000000000000007735e629/30/a"
80
+ },
81
+ {
82
+ "reference": "https://use.typekit.net/af/4c1fee/00000000000000007735e620/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
83
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/4c1fee/00000000000000007735e620/30/a"
84
+ }
85
+ ],
86
+ "remaining_remote_urls": 0
87
+ },
88
+ "static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/gqe1cfj.css": {
89
+ "mapped": 0,
90
+ "deterministic": 10,
91
+ "missing_payloads": [
92
+ {
93
+ "reference": "https://p.typekit.net/p.css?s=1&k=gqe1cfj&ht=tk&f=139.175.5474&a=731079&app=typekit&e=css",
94
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/p.typekit.net/p.css"
95
+ },
96
+ {
97
+ "reference": "https://use.typekit.net/af/71f83c/00000000000000003b9b093b/27/l?subset_id=2&fvd=n7&v=3",
98
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/71f83c/00000000000000003b9b093b/27/l"
99
+ },
100
+ {
101
+ "reference": "https://use.typekit.net/af/71f83c/00000000000000003b9b093b/27/d?subset_id=2&fvd=n7&v=3",
102
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/71f83c/00000000000000003b9b093b/27/d"
103
+ },
104
+ {
105
+ "reference": "https://use.typekit.net/af/71f83c/00000000000000003b9b093b/27/a?subset_id=2&fvd=n7&v=3",
106
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/71f83c/00000000000000003b9b093b/27/a"
107
+ },
108
+ {
109
+ "reference": "https://use.typekit.net/af/4838bd/00000000000000003b9b0934/27/l?subset_id=2&fvd=n4&v=3",
110
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/4838bd/00000000000000003b9b0934/27/l"
111
+ },
112
+ {
113
+ "reference": "https://use.typekit.net/af/4838bd/00000000000000003b9b0934/27/d?subset_id=2&fvd=n4&v=3",
114
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/4838bd/00000000000000003b9b0934/27/d"
115
+ },
116
+ {
117
+ "reference": "https://use.typekit.net/af/4838bd/00000000000000003b9b0934/27/a?subset_id=2&fvd=n4&v=3",
118
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/4838bd/00000000000000003b9b0934/27/a"
119
+ },
120
+ {
121
+ "reference": "https://use.typekit.net/af/437c3d/00000000000000003b9b0932/27/l?subset_id=2&fvd=n3&v=3",
122
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/437c3d/00000000000000003b9b0932/27/l"
123
+ },
124
+ {
125
+ "reference": "https://use.typekit.net/af/437c3d/00000000000000003b9b0932/27/d?subset_id=2&fvd=n3&v=3",
126
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/437c3d/00000000000000003b9b0932/27/d"
127
+ },
128
+ {
129
+ "reference": "https://use.typekit.net/af/437c3d/00000000000000003b9b0932/27/a?subset_id=2&fvd=n3&v=3",
130
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/437c3d/00000000000000003b9b0932/27/a"
131
+ }
132
+ ],
133
+ "remaining_remote_urls": 0
134
+ },
135
+ "static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/gvq8mju.css": {
136
+ "mapped": 25,
137
+ "deterministic": 12,
138
+ "missing_payloads": [
139
+ {
140
+ "reference": "https://use.typekit.net/af/949f99/00000000000000003b9b3068/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
141
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/949f99/00000000000000003b9b3068/27/a"
142
+ },
143
+ {
144
+ "reference": "https://use.typekit.net/af/4c4052/00000000000000003b9b3069/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
145
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/4c4052/00000000000000003b9b3069/27/a"
146
+ },
147
+ {
148
+ "reference": "https://use.typekit.net/af/705e94/00000000000000003b9b3062/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
149
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/705e94/00000000000000003b9b3062/27/a"
150
+ },
151
+ {
152
+ "reference": "https://use.typekit.net/af/5c70f2/00000000000000003b9b3063/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
153
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/5c70f2/00000000000000003b9b3063/27/a"
154
+ },
155
+ {
156
+ "reference": "https://use.typekit.net/af/0ff5e1/00000000000000003b9b3078/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
157
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/0ff5e1/00000000000000003b9b3078/27/a"
158
+ },
159
+ {
160
+ "reference": "https://use.typekit.net/af/519896/00000000000000003b9b3079/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
161
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/519896/00000000000000003b9b3079/27/a"
162
+ },
163
+ {
164
+ "reference": "https://use.typekit.net/af/8e2bbd/00000000000000003b9b3072/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
165
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/8e2bbd/00000000000000003b9b3072/27/a"
166
+ },
167
+ {
168
+ "reference": "https://use.typekit.net/af/5364bc/00000000000000003b9b3073/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
169
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/5364bc/00000000000000003b9b3073/27/a"
170
+ },
171
+ {
172
+ "reference": "https://use.typekit.net/af/4a329e/00000000000000003b9b3089/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
173
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/4a329e/00000000000000003b9b3089/27/a"
174
+ },
175
+ {
176
+ "reference": "https://use.typekit.net/af/7b18df/00000000000000003b9b3088/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
177
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/7b18df/00000000000000003b9b3088/27/a"
178
+ },
179
+ {
180
+ "reference": "https://use.typekit.net/af/bcf2f4/00000000000000003b9b3083/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
181
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/bcf2f4/00000000000000003b9b3083/27/a"
182
+ },
183
+ {
184
+ "reference": "https://use.typekit.net/af/0dfb3d/00000000000000003b9b3082/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
185
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/0dfb3d/00000000000000003b9b3082/27/a"
186
+ }
187
+ ],
188
+ "remaining_remote_urls": 0
189
+ },
190
+ "static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/lox4zmf.css": {
191
+ "mapped": 11,
192
+ "deterministic": 5,
193
+ "missing_payloads": [
194
+ {
195
+ "reference": "https://use.typekit.net/af/2555e1/00000000000000007735e603/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
196
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/2555e1/00000000000000007735e603/30/a"
197
+ },
198
+ {
199
+ "reference": "https://use.typekit.net/af/8738d8/00000000000000007735e611/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
200
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/8738d8/00000000000000007735e611/30/a"
201
+ },
202
+ {
203
+ "reference": "https://use.typekit.net/af/efe4a5/00000000000000007735e609/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
204
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/efe4a5/00000000000000007735e609/30/a"
205
+ },
206
+ {
207
+ "reference": "https://use.typekit.net/af/3322cc/00000000000000007735e616/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
208
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/3322cc/00000000000000007735e616/30/a"
209
+ },
210
+ {
211
+ "reference": "https://use.typekit.net/af/23e139/00000000000000007735e605/30/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=",
212
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/use.typekit.net/af/23e139/00000000000000007735e605/30/a"
213
+ }
214
+ ],
215
+ "remaining_remote_urls": 0
216
+ },
217
+ "static/assets/2026-08-13.aspca-pet-insurance-r1/www.aspcapetinsurance.com/css/aphi/cat-dog-insurance.min.css": {
218
+ "mapped": 2,
219
+ "deterministic": 0,
220
+ "missing_payloads": [],
221
+ "remaining_remote_urls": 0
222
+ },
223
+ "static/assets/2026-08-13.aspca-pet-insurance-r1/www.aspcapetinsurance.com/css/aphi.min.q635d786993.css": {
224
+ "mapped": 65,
225
+ "deterministic": 0,
226
+ "missing_payloads": [],
227
+ "remaining_remote_urls": 0
228
+ },
229
+ "static/assets/2026-08-13.aspca-pet-insurance-r1/www.aspcapetinsurance.com/portal/styles.qe4f056fd46.css": {
230
+ "mapped": 8,
231
+ "deterministic": 0,
232
+ "missing_payloads": [],
233
+ "remaining_remote_urls": 0
234
+ },
235
+ "static/assets/2026-08-13.aspca-pet-insurance-r1/www.aspcapetinsurance.com/z/lib/assets/dsr.css": {
236
+ "mapped": 4,
237
+ "deterministic": 1,
238
+ "missing_payloads": [
239
+ {
240
+ "reference": "http://aphi.hartvillesites.dev.corp.hartvillegroup.com/Images/icons/check.png",
241
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/aphi.hartvillesites.dev.corp.hartvillegroup.com/Images/icons/check.png"
242
+ }
243
+ ],
244
+ "remaining_remote_urls": 0
245
+ },
246
+ "static/assets/2026-08-13.aspca-pet-insurance-r1/www.aspcapetinsurance.com/z/lib/assets/dsr.q8f0ba73c3f.css": {
247
+ "mapped": 4,
248
+ "deterministic": 1,
249
+ "missing_payloads": [
250
+ {
251
+ "reference": "http://aphi.hartvillesites.dev.corp.hartvillegroup.com/Images/icons/check.png",
252
+ "local": "/static/assets/2026-08-13.aspca-pet-insurance-r1/aphi.hartvillesites.dev.corp.hartvillegroup.com/Images/icons/check.png"
253
+ }
254
+ ],
255
+ "remaining_remote_urls": 0
256
+ }
257
+ }
tasks/aspca-pet-insurance/environment/reference/clone/frontend/rewrite-report.json ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "home": {
3
+ "bytes": 151250,
4
+ "rewritten_refs": 57,
5
+ "script_blocks_dropped": 57,
6
+ "ld_json_dropped": 3,
7
+ "dropped_tags": [
8
+ "iframe:https://widget.trustpilot.com/trustboxes/54ad5defc6454f065c28af8b/index.html?templateId=54ad5defc645",
9
+ "iframe://nojscontainer.pepperjam.com/4193671694.html",
10
+ "img://googleads.g.doubleclick.net/pagead/viewthroughconversion/1064736661/?value=0&amp;guid=ON&amp;scrip",
11
+ "img:https://segment.prod.bidr.io/associate-segment?buzz_key=tatari&amp;segment_key=tatari-4528&amp;value",
12
+ "img:https://bat.bing.com/action/0?ti=26041831&amp;tm=gtm002&amp;Ver=2&amp;mid=0b7ed1d5-c76e-4b2b-a7e9-f7"
13
+ ],
14
+ "cdn_fallback_refs": [
15
+ "https://d3544la1u8djza.cloudfront.net/APHI/Blog/2021/09-20/german+shepherd+dog+resting+on+a+porch+in+the+woods-min.jpg",
16
+ "https://d3544la1u8djza.cloudfront.net/APHI/Blog/2022/11-07/young+woman+being+affectionate+with+cat+at+home-min.jpg",
17
+ "https://d3544la1u8djza.cloudfront.net/APHI/Blog/2023/June/house-training-puppy.jpg",
18
+ "https://d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/APHI-icons-cashback.svg",
19
+ "https://d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/APHI-icons-submitclaims.svg",
20
+ "https://d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/compare-no.svg",
21
+ "https://d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/compare-yes.svg",
22
+ "https://d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/dog-on-leash-md-2x.jpg",
23
+ "https://d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/dog-on-leash-xl-2x.jpg",
24
+ "https://d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/dog-on-leash-xs-3x.jpg",
25
+ "https://d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/girl-with-dog-275w.png",
26
+ "https://d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/girl-with-dog-641w.png",
27
+ "https://d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/girl-with-dog-771w.png",
28
+ "https://d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
29
+ ],
30
+ "first_party_localized": 5,
31
+ "external_boundaries": [
32
+ "https://pinterest.com/aspcapetins/",
33
+ "https://twitter.com/ASPCAPetIns",
34
+ "https://www.facebook.com/ASPCAPetInsurance",
35
+ "https://www.instagram.com/aspcapetinsurance/"
36
+ ],
37
+ "osano_state_reconciled": true,
38
+ "missing_static_paths": [
39
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Blog/2021/09-20/german+shepherd+dog+resting+on+a+porch+in+the+woods-min.jpg",
40
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Blog/2022/11-07/young+woman+being+affectionate+with+cat+at+home-min.jpg",
41
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Blog/2023/June/house-training-puppy.jpg",
42
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/APHI-icons-cashback.svg",
43
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/APHI-icons-submitclaims.svg",
44
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/compare-no.svg",
45
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/compare-yes.svg",
46
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/dog-on-leash-md-2x.jpg",
47
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/dog-on-leash-xl-2x.jpg",
48
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/dog-on-leash-xs-3x.jpg",
49
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/girl-with-dog-275w.png",
50
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/girl-with-dog-641w.png",
51
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/girl-with-dog-771w.png",
52
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
53
+ ],
54
+ "remaining_remote_refs": [],
55
+ "remaining_remote_count": 0
56
+ },
57
+ "about-us": {
58
+ "bytes": 110455,
59
+ "rewritten_refs": 17,
60
+ "script_blocks_dropped": 49,
61
+ "ld_json_dropped": 0,
62
+ "dropped_tags": [
63
+ "iframe://nojscontainer.pepperjam.com/4193671694.html",
64
+ "img://googleads.g.doubleclick.net/pagead/viewthroughconversion/1064736661/?value=0&amp;guid=ON&amp;scrip",
65
+ "img:https://bat.bing.com/action/0?ti=26041831&amp;tm=gtm002&amp;Ver=2&amp;mid=f759c687-8082-4044-a63d-64",
66
+ "img:https://segment.prod.bidr.io/associate-segment?buzz_key=tatari&amp;segment_key=tatari-4528&amp;value"
67
+ ],
68
+ "cdn_fallback_refs": [
69
+ "https://d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
70
+ ],
71
+ "first_party_localized": 5,
72
+ "external_boundaries": [
73
+ "https://pinterest.com/aspcapetins/",
74
+ "https://twitter.com/ASPCAPetIns",
75
+ "https://www.facebook.com/ASPCAPetInsurance",
76
+ "https://www.instagram.com/aspcapetinsurance/"
77
+ ],
78
+ "osano_state_reconciled": false,
79
+ "missing_static_paths": [
80
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
81
+ ],
82
+ "remaining_remote_refs": [],
83
+ "remaining_remote_count": 0
84
+ },
85
+ "cat-insurance": {
86
+ "bytes": 141380,
87
+ "rewritten_refs": 40,
88
+ "script_blocks_dropped": 58,
89
+ "ld_json_dropped": 3,
90
+ "dropped_tags": [
91
+ "iframe:https://www.youtube.com/embed/YWxK0Sox340?rel=0&amp;modestbranding=1&amp;enablejsapi=1&amp;origin=ht",
92
+ "iframe:https://widget.trustpilot.com/trustboxes/54ad5defc6454f065c28af8b/index.html?templateId=54ad5defc645",
93
+ "iframe://nojscontainer.pepperjam.com/4193671694.html",
94
+ "img://googleads.g.doubleclick.net/pagead/viewthroughconversion/1064736661/?value=0&amp;guid=ON&amp;scrip",
95
+ "img:https://bat.bing.com/action/0?ti=26041831&amp;tm=gtm002&amp;Ver=2&amp;mid=7fb3aa27-84ad-4662-a871-c2",
96
+ "img:https://segment.prod.bidr.io/associate-segment?buzz_key=tatari&amp;segment_key=tatari-4528&amp;value"
97
+ ],
98
+ "cdn_fallback_refs": [
99
+ "https://d3544la1u8djza.cloudfront.net/APHI/cat-dog-pages/cat-insurance/cat-hero-xs3.png",
100
+ "https://d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
101
+ ],
102
+ "first_party_localized": 7,
103
+ "external_boundaries": [
104
+ "https://pinterest.com/aspcapetins/",
105
+ "https://twitter.com/ASPCAPetIns",
106
+ "https://www.facebook.com/ASPCAPetInsurance",
107
+ "https://www.instagram.com/aspcapetinsurance/"
108
+ ],
109
+ "osano_state_reconciled": false,
110
+ "missing_static_paths": [
111
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/cat-dog-pages/cat-insurance/cat-hero-xs3.png",
112
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
113
+ ],
114
+ "remaining_remote_refs": [],
115
+ "remaining_remote_count": 0
116
+ },
117
+ "dog-insurance": {
118
+ "bytes": 140171,
119
+ "rewritten_refs": 40,
120
+ "script_blocks_dropped": 59,
121
+ "ld_json_dropped": 3,
122
+ "dropped_tags": [
123
+ "iframe:https://www.youtube.com/embed/T46u4dLp7xg?rel=0&amp;modestbranding=1&amp;enablejsapi=1&amp;origin=ht",
124
+ "iframe:https://widget.trustpilot.com/trustboxes/54ad5defc6454f065c28af8b/index.html?templateId=54ad5defc645",
125
+ "iframe://nojscontainer.pepperjam.com/4193671694.html",
126
+ "img://googleads.g.doubleclick.net/pagead/viewthroughconversion/1064736661/?value=0&amp;guid=ON&amp;scrip",
127
+ "img:https://bat.bing.com/action/0?ti=26041831&amp;tm=gtm002&amp;Ver=2&amp;mid=dfb55e5e-cbff-4431-837b-35",
128
+ "img:https://segment.prod.bidr.io/associate-segment?buzz_key=tatari&amp;segment_key=tatari-4528&amp;value"
129
+ ],
130
+ "cdn_fallback_refs": [
131
+ "https://d3544la1u8djza.cloudfront.net/APHI/cat-dog-pages/dog-insurance/dog-hero-xs@3x.png",
132
+ "https://d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
133
+ ],
134
+ "first_party_localized": 6,
135
+ "external_boundaries": [
136
+ "https://pinterest.com/aspcapetins/",
137
+ "https://twitter.com/ASPCAPetIns",
138
+ "https://www.facebook.com/ASPCAPetInsurance",
139
+ "https://www.instagram.com/aspcapetinsurance/"
140
+ ],
141
+ "osano_state_reconciled": false,
142
+ "missing_static_paths": [
143
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/cat-dog-pages/dog-insurance/dog-hero-xs@3x.png",
144
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
145
+ ],
146
+ "remaining_remote_refs": [],
147
+ "remaining_remote_count": 0
148
+ },
149
+ "pet-insurance-plan": {
150
+ "bytes": 133155,
151
+ "rewritten_refs": 46,
152
+ "script_blocks_dropped": 54,
153
+ "ld_json_dropped": 3,
154
+ "dropped_tags": [
155
+ "iframe:https://widget.trustpilot.com/trustboxes/54ad5defc6454f065c28af8b/index.html?templateId=54ad5defc645",
156
+ "iframe://nojscontainer.pepperjam.com/4193671694.html",
157
+ "img://googleads.g.doubleclick.net/pagead/viewthroughconversion/1064736661/?value=0&amp;guid=ON&amp;scrip",
158
+ "img:https://bat.bing.com/action/0?ti=26041831&amp;tm=gtm002&amp;Ver=2&amp;mid=000f4ee6-ad3a-44d6-9ee7-e4",
159
+ "img:https://segment.prod.bidr.io/associate-segment?buzz_key=tatari&amp;segment_key=tatari-4528&amp;value"
160
+ ],
161
+ "cdn_fallback_refs": [
162
+ "https://d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1200x525-iStock-1199435587-2.jpg",
163
+ "https://d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1200x525-iStock-1447241079.jpg",
164
+ "https://d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1350x900-iStock-1199435587-2.jpg",
165
+ "https://d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1350x900-iStock-1447241079-2.jpg",
166
+ "https://d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-326w.png",
167
+ "https://d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-660w.png",
168
+ "https://d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-784w.png",
169
+ "https://d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-901w.png",
170
+ "https://d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-978w.png",
171
+ "https://d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
172
+ ],
173
+ "first_party_localized": 5,
174
+ "external_boundaries": [
175
+ "https://pinterest.com/aspcapetins/",
176
+ "https://twitter.com/ASPCAPetIns",
177
+ "https://www.facebook.com/ASPCAPetInsurance",
178
+ "https://www.instagram.com/aspcapetinsurance/"
179
+ ],
180
+ "osano_state_reconciled": false,
181
+ "missing_static_paths": [
182
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1200x525-iStock-1199435587-2.jpg",
183
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1200x525-iStock-1447241079.jpg",
184
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1350x900-iStock-1199435587-2.jpg",
185
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1350x900-iStock-1447241079-2.jpg",
186
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-326w.png",
187
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-660w.png",
188
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-784w.png",
189
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-901w.png",
190
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-978w.png",
191
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
192
+ ],
193
+ "remaining_remote_refs": [],
194
+ "remaining_remote_count": 0
195
+ },
196
+ "research-and-compare": {
197
+ "bytes": 114590,
198
+ "rewritten_refs": 17,
199
+ "script_blocks_dropped": 51,
200
+ "ld_json_dropped": 2,
201
+ "dropped_tags": [
202
+ "iframe:https://bid.g.doubleclick.net/xbbe/pixel?d=KAE",
203
+ "iframe://nojscontainer.pepperjam.com/4193671694.html",
204
+ "img://googleads.g.doubleclick.net/pagead/viewthroughconversion/1064736661/?value=0&amp;guid=ON&amp;scrip",
205
+ "img:https://bat.bing.com/action/0?ti=26041831&amp;tm=gtm002&amp;Ver=2&amp;mid=cb539841-1d31-45cc-880d-51",
206
+ "img:https://segment.prod.bidr.io/associate-segment?buzz_key=tatari&amp;segment_key=tatari-4528&amp;value"
207
+ ],
208
+ "cdn_fallback_refs": [
209
+ "https://d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
210
+ ],
211
+ "first_party_localized": 5,
212
+ "external_boundaries": [
213
+ "https://pinterest.com/aspcapetins/",
214
+ "https://twitter.com/ASPCAPetIns",
215
+ "https://www.facebook.com/ASPCAPetInsurance",
216
+ "https://www.instagram.com/aspcapetinsurance/"
217
+ ],
218
+ "osano_state_reconciled": false,
219
+ "missing_static_paths": [
220
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
221
+ ],
222
+ "remaining_remote_refs": [],
223
+ "remaining_remote_count": 0
224
+ },
225
+ "support": {
226
+ "bytes": 114046,
227
+ "rewritten_refs": 18,
228
+ "script_blocks_dropped": 51,
229
+ "ld_json_dropped": 2,
230
+ "dropped_tags": [
231
+ "iframe://nojscontainer.pepperjam.com/4193671694.html",
232
+ "img://googleads.g.doubleclick.net/pagead/viewthroughconversion/1064736661/?value=0&amp;guid=ON&amp;scrip",
233
+ "img:https://segment.prod.bidr.io/associate-segment?buzz_key=tatari&amp;segment_key=tatari-4528&amp;value",
234
+ "img:https://bat.bing.com/action/0?ti=26041831&amp;tm=gtm002&amp;Ver=2&amp;mid=e5afed36-7dc0-42b0-95fa-bd"
235
+ ],
236
+ "cdn_fallback_refs": [
237
+ "https://d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
238
+ ],
239
+ "first_party_localized": 6,
240
+ "external_boundaries": [
241
+ "https://pinterest.com/aspcapetins/",
242
+ "https://twitter.com/ASPCAPetIns",
243
+ "https://www.facebook.com/ASPCAPetInsurance",
244
+ "https://www.instagram.com/aspcapetinsurance/"
245
+ ],
246
+ "osano_state_reconciled": false,
247
+ "missing_static_paths": [
248
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg"
249
+ ],
250
+ "remaining_remote_refs": [],
251
+ "remaining_remote_count": 0
252
+ },
253
+ "why-us": {
254
+ "bytes": 223240,
255
+ "rewritten_refs": 33,
256
+ "script_blocks_dropped": 51,
257
+ "ld_json_dropped": 0,
258
+ "dropped_tags": [
259
+ "iframe://nojscontainer.pepperjam.com/4193671694.html",
260
+ "img://googleads.g.doubleclick.net/pagead/viewthroughconversion/1064736661/?value=0&amp;guid=ON&amp;scrip",
261
+ "img:https://bat.bing.com/action/0?ti=26041831&amp;tm=gtm002&amp;Ver=2&amp;mid=1b41a871-dabd-489a-a13e-cf",
262
+ "img:https://segment.prod.bidr.io/associate-segment?buzz_key=tatari&amp;segment_key=tatari-4528&amp;value"
263
+ ],
264
+ "cdn_fallback_refs": [
265
+ "https://d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg",
266
+ "https://d3544la1u8djza.cloudfront.net/APHI/whyUs/3dogstudio-550x300.png",
267
+ "https://d3544la1u8djza.cloudfront.net/APHI/whyUs/catandgirl-nobg.png"
268
+ ],
269
+ "first_party_localized": 5,
270
+ "external_boundaries": [
271
+ "https://pinterest.com/aspcapetins/",
272
+ "https://twitter.com/ASPCAPetIns",
273
+ "https://www.facebook.com/ASPCAPetInsurance",
274
+ "https://www.instagram.com/aspcapetinsurance/",
275
+ "https://www.trustpilot.com/reviews/62ab79af266eedb3c15b68a4",
276
+ "https://www.trustpilot.com/users/61db86e065c2820013a91ade",
277
+ "https://www.trustpilot.com/users/62dffc432830990013474a2f"
278
+ ],
279
+ "osano_state_reconciled": false,
280
+ "missing_static_paths": [
281
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg",
282
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/whyUs/3dogstudio-550x300.png",
283
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/whyUs/catandgirl-nobg.png"
284
+ ],
285
+ "remaining_remote_refs": [],
286
+ "remaining_remote_count": 0
287
+ },
288
+ "not-found": {
289
+ "bytes": 12813,
290
+ "rewritten_refs": 3,
291
+ "script_blocks_dropped": 2,
292
+ "ld_json_dropped": 0,
293
+ "dropped_tags": [],
294
+ "cdn_fallback_refs": [],
295
+ "first_party_localized": 8,
296
+ "external_boundaries": [],
297
+ "osano_state_reconciled": false,
298
+ "missing_static_paths": [],
299
+ "remaining_remote_refs": [],
300
+ "remaining_remote_count": 0
301
+ },
302
+ "_totals": {
303
+ "pages": 9,
304
+ "remaining_remote_total": 0,
305
+ "missing_static_paths_union": [
306
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Blog/2021/09-20/german+shepherd+dog+resting+on+a+porch+in+the+woods-min.jpg",
307
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Blog/2022/11-07/young+woman+being+affectionate+with+cat+at+home-min.jpg",
308
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Blog/2023/June/house-training-puppy.jpg",
309
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1200x525-iStock-1199435587-2.jpg",
310
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1200x525-iStock-1447241079.jpg",
311
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1350x900-iStock-1199435587-2.jpg",
312
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/1350x900-iStock-1447241079-2.jpg",
313
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-326w.png",
314
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-660w.png",
315
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-784w.png",
316
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-901w.png",
317
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/Our+Plans/iStock-824855806-978w.png",
318
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/cat-dog-pages/cat-insurance/cat-hero-xs3.png",
319
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/cat-dog-pages/dog-insurance/dog-hero-xs@3x.png",
320
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/APHI-icons-cashback.svg",
321
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/APHI-icons-submitclaims.svg",
322
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/compare-no.svg",
323
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/compare-yes.svg",
324
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/dog-on-leash-md-2x.jpg",
325
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/dog-on-leash-xl-2x.jpg",
326
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/dog-on-leash-xs-3x.jpg",
327
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/girl-with-dog-275w.png",
328
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/girl-with-dog-641w.png",
329
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/homepage/02-23/girl-with-dog-771w.png",
330
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/socialMedia/fb-we-cover-that.jpg",
331
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/whyUs/3dogstudio-550x300.png",
332
+ "/static/assets/2026-08-13.aspca-pet-insurance-r1/d3544la1u8djza.cloudfront.net/APHI/whyUs/catandgirl-nobg.png"
333
+ ],
334
+ "all_pages_nonzero_and_remote_free": true
335
+ }
336
+ }
tasks/aspca-pet-insurance/environment/reference/clone/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastapi>=0.115
2
+ uvicorn>=0.30
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ads.nextdoor.com/public/pixel/ndp.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ (()=>{var xe=Object.defineProperty,Ee=Object.defineProperties;var _e=Object.getOwnPropertyDescriptors;var te=Object.getOwnPropertySymbols;var Le=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable;var V=(t,e,n)=>e in t?xe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,m=(t,e)=>{for(var n in e||(e={}))Le.call(e,n)&&V(t,n,e[n]);if(te)for(var n of te(e))Ae.call(e,n)&&V(t,n,e[n]);return t},ne=(t,e)=>Ee(t,_e(e));var E=(t,e,n)=>V(t,typeof e!="symbol"?e+"":e,n);var f=(t,e,n)=>new Promise((r,i)=>{var a=c=>{try{d(n.next(c))}catch(h){i(h)}},s=c=>{try{d(n.throw(c))}catch(h){i(h)}},d=c=>c.done?r(c.value):Promise.resolve(c.value).then(a,s);d((n=n.apply(t,e)).next())});var F="user_email_hash",B="user_email",_="ndclid",D="ndp_session_id",C="advertiser_pixel_test_id",re=["order_value","product_context","order_id"],ie=["email","phone_number","first_name","last_name","gender","street_address","city","state","zip_code","country"],U={email:0,phone_number:1,first_name:2,last_name:3,external_id:4,city:5,state:6,zip_code:7,country:8,street_address:9,gender:10},oe="GTM",ae="Manual",N="https://flask.nextdoor.com/pixel",se="https://flask.nextdoor.com/pixel-test";function O(){return`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,t=>{let e=crypto.getRandomValues(new Uint8Array(1))[0];return(+t^e&15>>+t/4).toString(16)})}var ce=t=>{let e=/^[a-fA-F0-9]+$/,n=t.length;return!!({32:"MD5",40:"SHA-1",64:"SHA-256",128:"SHA-512"}[n]&&e.test(t))};function q(t,e=!0){return f(this,null,function*(){if(!t)return"";e&&(t=t.toLowerCase());let n=new TextEncoder().encode(t),r=yield window.crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")})}var $=()=>/Safari/i.test(window.navigator.userAgent)&&!/Chrome/i.test(window.navigator.userAgent);function I(t,e){let n=e.split("&");for(let r=0;r<n.length;r++){let i=n[r].split("=");if(i[0]===t)return i[1]}return null}function de(){let t=localStorage.getItem("gpuInfo");if(t)try{return JSON.parse(t)}catch(d){}let e=document.createElement("canvas"),n=null;for(let d of["webgl2","webgl","experimental-webgl"])try{let c=e.getContext(d);if(c&&(c instanceof WebGLRenderingContext||c instanceof WebGL2RenderingContext)){n=c;break}}catch(c){}if(!n)return null;let r="N/A",i="N/A",a=n.getExtension("WEBGL_debug_renderer_info");try{a?(r=n.getParameter(a.UNMASKED_VENDOR_WEBGL)||"N/A",i=n.getParameter(a.UNMASKED_RENDERER_WEBGL)||"N/A"):(r=n.getParameter(n.VENDOR)||"N/A",i=n.getParameter(n.RENDERER)||"N/A")}catch(d){}let s={vendor:r,renderer:i};return localStorage.setItem("gpuInfo",JSON.stringify(s)),s}function z(t){if(!t)return!1;let e=t.replace(/[\s\-+().]/g,"");return/^\d+$/.test(e)?e.length>=7&&e.length<=15:!1}function le(t){return t.replace(/\D/g,"")}var W=t=>Object.entries(t).map(([e,n])=>(n&&typeof n=="object"&&(n=JSON.stringify(n)),`${e}=${encodeURIComponent(n)}`)).join("&");function j(t,e=!1,n={sensitive:0,validation:0,hash:0}){let r=0,i=0,a=0;e&&U.email!==void 0&&(r|=1<<U.email);for(let[b,u]of Object.entries(t)){if(!(u!=null&&u.value))continue;let p=U[b];if(p===void 0)continue;let S=1<<p;switch(u.source){case"manual":r|=S;break;case"auto":i|=S;break;case"url":a|=S;break}}let s=n.sensitive,d=n.validation,c=n.hash,h=s|d|c;return{am_m:r,am_a:i,am_u:a,am_d:h,am_ds:s,am_dv:d,am_dh:c}}var v=class v{constructor(){E(this,"config");let e=v.DEBUG_FLAG_KEY,n=null;try{let c=localStorage.getItem(v.STORAGE_LEVEL_KEY);if(c){let h=JSON.parse(c);Date.now()-h.ts<3e5?n=h.level:localStorage.removeItem(v.STORAGE_LEVEL_KEY)}}catch(c){}let r=(()=>{try{return localStorage.getItem(e)==="1"}catch(c){return!1}})(),i=(()=>{try{return new URLSearchParams(window.location.search).get(e)==="1"}catch(c){return!1}})(),a=(()=>{try{let c=localStorage.getItem(v.STORAGE_OPTS_KEY);return c?JSON.parse(c):null}catch(c){return null}})(),s=r||n&&n!=="off"||i,d=n&&n!=="off"?n:r||i?"debug":"error";this.config={enabled:s,level:s?d:"error",prefix:"[Nextdoor Pixel]",includeTimestamp:!!(a!=null&&a.includeTimestamp),includeLocation:!!(a!=null&&a.includeLocation)}}formatPrefix(e){let n=[this.config.prefix,`[${e.toUpperCase()}]`];if(this.config.includeTimestamp)try{n.push(new Date().toISOString())}catch(r){}if(this.config.includeLocation){let r=this.getCallerLocation();r&&n.push(`(${r})`)}return n.join(" ")}getCallerLocation(){try{let e=new Error;if(!e.stack)return null;let n=e.stack.split(`
2
+ `).map(r=>r.trim());for(let r=1;r<n.length;r++){let i=n[r];if(!i||i.includes("basic/logger"))continue;let a=i.match(/\(?([^()]+):(\d+):(\d+)\)?$/);if(a){let s=a[1],d=a[2];return`${s}:${d}`}}return null}catch(e){return null}}shouldLog(e){if(!this.config.enabled)return!1;let n=["debug","info","warn","error"],r=n.indexOf(this.config.level);return n.indexOf(e)>=r}debug(e,...n){this.shouldLog("debug")&&(console.groupCollapsed(`${this.formatPrefix("debug")} ${e}`,...n),console.trace(),console.groupEnd())}info(e,...n){this.shouldLog("info")&&console.log(`${this.formatPrefix("info")} ${e}`,...n)}warn(e,...n){this.shouldLog("warn")&&console.warn(`${this.formatPrefix("warn")} ${e}`,...n)}error(e,...n){this.shouldLog("error")&&console.error(`${this.formatPrefix("error")} ${e}`,...n)}enableDebug(){this.config.enabled=!0,this.config.level="debug";try{localStorage.setItem("ndp_debug","1");let e={level:"debug",ts:Date.now()};localStorage.setItem(v.STORAGE_LEVEL_KEY,JSON.stringify(e))}catch(e){}console.log(`${this.config.prefix} Debug mode enabled`)}disable(){this.config.enabled=!1;try{localStorage.removeItem("ndp_debug");let e={level:"off",ts:Date.now()};localStorage.setItem(v.STORAGE_LEVEL_KEY,JSON.stringify(e))}catch(e){}}setLevel(e){if(e==="off")this.disable();else{this.config.enabled=!0,this.config.level=e;try{let n={level:e,ts:Date.now()};localStorage.setItem(v.STORAGE_LEVEL_KEY,JSON.stringify(n))}catch(n){}console.log(`${this.config.prefix} Log level set to '${e}'`)}}setOptions(e){try{typeof e.includeTimestamp=="boolean"&&(this.config.includeTimestamp=e.includeTimestamp),typeof e.includeLocation=="boolean"&&(this.config.includeLocation=e.includeLocation);let n={includeTimestamp:this.config.includeTimestamp,includeLocation:this.config.includeLocation};localStorage.setItem(v.STORAGE_OPTS_KEY,JSON.stringify(n)),console.log(`${this.config.prefix} Log options updated`,n)}catch(n){}}};E(v,"STORAGE_LEVEL_KEY","ndp_log_level"),E(v,"DEBUG_FLAG_KEY","ndp_debug"),E(v,"STORAGE_OPTS_KEY","ndp_log_opts");var M=v,l=new M;typeof window!="undefined"&&(window.ndpDebug=()=>(l.enableDebug(),"Nextdoor Pixel debug mode enabled. Check console for detailed logs."),window.ndpLog=t=>(l.setLevel(t),`Nextdoor Pixel log level set to '${t}'.`),window.ndpLogOptions=t=>(l.setOptions(t),"Nextdoor Pixel log options updated."),window.ndpReset=t=>{try{let e=[],n=()=>{try{localStorage.removeItem(M.DEBUG_FLAG_KEY)}catch(i){}try{localStorage.removeItem(M.STORAGE_LEVEL_KEY)}catch(i){}l.disable(),e.push("debug flags")},r=()=>{try{sessionStorage.removeItem("ndp_settings")}catch(i){}try{sessionStorage.removeItem("ndp_settings_expiry")}catch(i){}e.push("settings cache")};if(t)t==="debug"?n():t==="setting"&&r();else{n();try{localStorage.removeItem("gpuInfo")}catch(i){}try{localStorage.removeItem("ndp_session_id")}catch(i){}try{localStorage.removeItem("ndclid")}catch(i){}r(),e.push("gpuInfo","ndp_session_id","ndclid")}return`Nextdoor Pixel reset completed: ${e.join(", ")||t||"none"}`}catch(e){return"Nextdoor Pixel reset encountered an error (see console)."}});var y={ssn:[/^\d{3}-\d{2}-\d{4}$/,/^\d{3}\s\d{2}\s\d{4}$/,/^\d{9}$/],creditCard:[/^4[0-9]{12}(?:[0-9]{3})?$/,/^5[1-5][0-9]{14}$/,/^3[47][0-9]{13}$/,/^3[0-9]{13}$/,/^6(?:011|5[0-9]{2})[0-9]{12}$/,/^\d{4}\s\d{4}\s\d{4}\s\d{4}$/,/^\d{4}-\d{4}-\d{4}-\d{4}$/],driversLicense:[/^[A-Z]\d{7,8}$/,/^[A-Z]{2}\d{6,7}$/,/^\d{8,9}$/,/^[A-Z]\d{3}-\d{3}-\d{3}$/],medicalId:[/^MRN\d{6,10}$/i,/^PAT\d{6,10}$/i,/^PID\d{6,10}$/i],bankAccount:[/^\d{12,17}$/,/^\d{4}\s\d{4}\s\d{4}$/],passport:[/^[A-Z]{2}\d{7}$/],taxId:[/^\d{2}-\d{7}$/,/^\d{3}-\d{2}-\d{4}$/],insurance:[/^[A-Z]{2,3}\d{8,12}$/,/^POL\d{6,10}$/i,/^INS\d{6,10}$/i],sensitiveNumeric:[/^\d{16}$/,/^\d{15}$/,/^\d{9}$/]},Te=[/ssn/i,/social.?security/i,/tax.?id/i,/credit.?card/i,/card.?number/i,/ccn/i,/cvv/i,/cvc/i,/expiry/i,/expiration/i,/security.?code/i,/card.?code/i,/account.?number/i,/routing.?number/i,/bank.?account/i,/iban/i,/swift/i,/drivers?.?license/i,/dl.?number/i,/license.?number/i,/medical.?record/i,/patient.?id/i,/mrn/i,/health.?id/i,/insurance.?id/i,/passport/i,/passport.?number/i,/confidential/i,/secret/i,/private.?key/i,/password/i,/pin/i],ke=[/payment/i,/billing/i,/checkout/i,/credit/i,/bank/i,/medical/i,/health/i,/insurance/i,/tax/i,/government/i,/identity/i,/verification/i,/kyc/i,/background.?check/i];function Ie(t){return t?Te.some(e=>e.test(t)):!1}var Re={phone_number:new Set([y.driversLicense[2],y.bankAccount[0],y.ssn[2],y.sensitiveNumeric[0],y.sensitiveNumeric[1],y.sensitiveNumeric[2]]),zip_code:new Set([y.ssn[2],y.sensitiveNumeric[2],y.driversLicense[2]])},De=new Set(["phone_number","zip_code"]);function Ne(t,e){if(!t)return!1;let n=t.replace(/[\s-.]/g,""),r=Re[e];for(let[i,a]of Object.entries(y))for(let s of a)if(!(r!=null&&r.has(s))&&(s.test(n)||s.test(t)))return l.warn(`Detected sensitive data pattern: ${i}`),!0;return!1}function Oe(){var e;let t=[document.title,document.URL,((e=document.querySelector('meta[name="description"]'))==null?void 0:e.getAttribute("content"))||""].join(" ").toLowerCase();return ke.some(n=>n.test(t))}function ue(t,e){if(Ie(t))return l.warn(`Blocked sensitive field: ${t}`),!0;if(Ne(e,t))return l.warn(`Blocked sensitive value in field: ${t}`),!0;let n=e.replace(/[\s-]/g,"");return!De.has(t)&&Oe()&&/^\d+$/.test(n)&&n.length>=8?(l.warn(`Blocked numeric data in sensitive context: ${t}`),!0):!1}function G(t,e,n="",r,i=!1){if(e==null)return;let a=[];a.push(`${t}=${e}`),n&&a.push(`expires=${n}`),a.push("path=/"),r&&a.push(`domain=${r}`),a.push("SameSite=Lax"),i&&a.push("Secure"),document.cookie=a.join(";")}function A(t){try{let e=document.cookie.split("; ").find(r=>r.startsWith(`${t}=`));return e?e.split("=")[1]:""}catch(e){return""}}function P(t,e,n,r=null){if(e==null)return;let i;r?i=r:(i=new Date,i.setMonth(i.getMonth()+1));let s=n.replace("www.","").split(".");if(s.length===1){G(t,e,i.toUTCString(),void 0,!0);return}let d=`.${s.slice(-2).join(".")}`;G(t,e,i.toUTCString(),d,!0),!A(t)&&s.length>2&&(d=`.${s.slice(-3).join(".")}`,G(t,e,i.toUTCString(),d,!0)),$()&&localStorage&&localStorage.setItem(t,e)}var K=class{constructor(){E(this,"pseudoMappings",{":nth-of-type(":":t(",":nth-last-child(":":l(",":nth-last-of-type(":":lt(",":nth-child(":":n("});E(this,"reverseMappings",this.buildReverseMappings());E(this,"regexCache",new Map)}buildReverseMappings(){let e={};for(let[n,r]of Object.entries(this.pseudoMappings))e[r]=n;return e["|"]=" ",e}getOrCreateRegex(e){this.regexCache.has(e)||this.regexCache.set(e,new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"));let n=this.regexCache.get(e);if(!n)throw new Error("Failed to create regex pattern");return n}toDSL(e){if(!e||e.trim()==="")return e;let n=e.trim();for(let[r,i]of Object.entries(this.pseudoMappings)){let a=this.getOrCreateRegex(r);n=n.replace(a,i)}return n=n.replace(/\s+/g,"|"),n=n.replace(/\s+/g,""),n}fromDSL(e){if(!e||e.trim()==="")return e;let n=e.trim(),r=Object.entries(this.pseudoMappings).map(([i,a])=>[a,i]).sort(([i],[a])=>a.length-i.length);for(let[i,a]of r)n=n.replace(new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),a);return n=n.replace(/\|/g," "),n}isValidDSL(e){return!e||e.trim()===""?!1:!/[$%^&*()_+={}[\]|\\:;"'<>?,./]/.test(e)}},ft=new K;var $e=0;function R(){return Date.now()<$e}var ge=new Set;function H(t){let e={promise:t.catch(()=>{}),timestamp:Date.now()};return ge.add(e),t.finally(()=>{ge.delete(e)}),t}var g={debug:(...t)=>{},info:(...t)=>{},warn:(...t)=>{},error:(...t)=>{}},L=!1;if(typeof document!="undefined")try{document.addEventListener("visibilitychange",()=>{switch(document.visibilityState){case"visible":L=!1,g.debug("[http] document visible: disable beacon-friendly transport");break;case"hidden":L=!0,g.debug("[http] document hidden: enable beacon-friendly transport");break;default:L=!1}})}catch(t){}if(typeof window!="undefined")try{window.addEventListener("pagehide",()=>{L=!0,g.debug("[http] pagehide fired: enable beacon-friendly transport")}),window.addEventListener("pageshow",()=>{L=!1,g.debug("[http] pageshow fired: disable beacon-friendly transport")})}catch(t){}function Me(t){if(typeof t=="string")return t;try{return new URLSearchParams(t).toString()}catch(e){return String(t!=null?t:"")}}function Y(t,e){return f(this,null,function*(){return typeof fetch!="function"?!1:(g.debug("[http] fetch keepalive attempt",{url:t,init:e}),fetch(t,e).then(()=>(g.debug("[http] fetch keepalive sent",{method:(e==null?void 0:e.method)||"GET",url:t,keepalive:(e==null?void 0:e.keepalive)===!0,pageHidden:L}),!0)).catch(n=>(g.debug("fetch keepalive failed:",n),!1)))})}function Ce(t,e=1500){return g.debug("[http] using image fallback",{url:t,timeoutMs:e}),new Promise(n=>{try{let r=He(t),i=!1,a=()=>{i||(i=!0,n())},s=setTimeout(a,e);r.onload=()=>{clearTimeout(s),a()},r.onerror=()=>{clearTimeout(s),a()}}catch(r){n()}})}function Ue(t,e,n="POST"){return g.debug("[http] using XHR fallback",{url:t,method:n}),new Promise(r=>{try{let i=new XMLHttpRequest;i.open(n,t),i.withCredentials=!0,i.onreadystatechange=function(){i.readyState===4&&(i.status!==204&&g.debug(`Request failed to ${t}.`),r())},i.onerror=()=>r(),n==="POST"?i.send(e!=null?e:""):i.send()}catch(i){r()}})}var Ge=(t,e)=>f(null,null,function*(){let n=e||N,r=f(null,null,function*(){if(g.debug("[http] POST requested",{src:n}),(L||R())&&typeof navigator!="undefined"&&"sendBeacon"in navigator)try{let a=new Blob([JSON.stringify(t)],{type:"application/json"}),s=navigator.sendBeacon(n,a);g.debug("[http] POST via sendBeacon",{ok:s,pageHidden:!0,preferBeacon:R()});return}catch(a){g.debug("[http] POST beacon failed, continue to fetch/xhr",a)}if(yield Y(n,{method:"POST",mode:"no-cors",credentials:"include",keepalive:!0,body:JSON.stringify(t)})){g.debug("[http] POST using fetch keepalive");return}return g.debug("[http] POST falling back to XHR"),Ue(n,JSON.stringify(t),"POST").catch(()=>{})});return H(r)}),He=t=>{let e=document.createElement("img");return e.src=t,e.alt="",e.style.display="none",e},Ve=(t,e)=>f(null,null,function*(){let n=e||N,r=Me(t),i=`${n}?${r}`,a=f(null,null,function*(){if(g.debug("[http] GET requested",{src:i}),(L||R())&&typeof navigator!="undefined"&&"sendBeacon"in navigator)try{let d=new Blob([r],{type:"application/x-www-form-urlencoded"}),c=navigator.sendBeacon(n,d);g.debug("[http] GET via sendBeacon (POST form body)",{ok:c,pageHidden:!0,preferBeacon:R()});return}catch(d){g.debug("[http] GET beacon failed, continue to fetch/img",d)}if(R()&&(yield Y(n,{method:"POST",mode:"no-cors",credentials:"include",keepalive:!0,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r}))){g.debug("[http] GET request sent as POST keepalive due to critical window");return}if(yield Y(i,{method:"GET",mode:"no-cors",credentials:"include",keepalive:!0})){g.debug("[http] GET using fetch keepalive");return}return g.debug("[http] GET falling back to IMG"),Ce(i,1500).catch(()=>{})});return H(a)}),fe=(t,e,n)=>f(null,null,function*(){g.debug("[http] execute called",{method:e,endpoint:n});let r;switch(e){case"POST":r=Ge(t,n);break;case"GET":r=Ve(t,n);break;default:return}return r.catch(()=>{})});var pe="10.30";var T={},k;function X(){return k}function he(t){return f(this,null,function*(){let e="advancedMatching";if(T[e]){T[e]instanceof Promise&&(yield T[e]),yield me(t);return}T[e]=Fe();try{let n=yield T[e];T[e]=n,n&&(yield me(t))}catch(n){l.warn("Failed to load advanced matching module:",n),T[e]=!1}})}function Fe(){return new Promise(t=>{if(window.NDPAdvancedMatching){l.debug("Advanced matching module already loaded"),k="ok",t(!0);return}let e=document.createElement("script"),n="js";e.src=`https://ads.nextdoor.com/v2/public/pixel/advmtch.${n}`,e.async=!0,e.onload=()=>{window.NDPAdvancedMatching?(l.debug("Advanced matching module loaded successfully"),k="ok",t(!0)):(l.warn("Advanced matching module loaded but global not available"),k="err",t(!1))},e.onerror=r=>{l.warn("Failed to load advanced matching script:",r),k="err",t(!1)},document.head.appendChild(e),setTimeout(()=>{!window.NDPAdvancedMatching&&k===void 0&&(l.warn("Advanced matching module load timeout"),k="timeout",t(!1))},1e4)})}function me(t){return f(this,null,function*(){if(!window.NDPAdvancedMatching){l.warn("Advanced matching module not available for initialization");return}try{(yield window.NDPAdvancedMatching.initAdvancedMatching(t))?l.debug("Advanced matching initialized successfully",{dataSourceId:t}):l.debug("Advanced matching initialization returned null (likely disabled)",{dataSourceId:t})}catch(e){l.warn("Advanced matching initialization failed:",e)}})}var o={ev:"",v:0,handleRequest:()=>{},ndclid:"",pid:"",pixelIdList:[],pl:"",cd:{},processQueue:()=>{},queue:[[]],rf:"",sem:"",ndclid_src:0,tz:"",screenWidth:0,screenHeight:0,gpuVendor:"",gpuRenderer:"",rdu:void 0,rduco:void 0,rdust:void 0},Be=t=>f(null,null,function*(){let e={},n={};if(t){Object.entries(t).filter(([p])=>re.includes(p)).forEach(([p,S])=>{e[p]=S});let u=Object.entries(t).filter(([p])=>ie.includes(p));if(u.length>0){let p=u.map(J=>f(null,[J],function*([w,x]){if(ce(x))return[w,x];{if(ue(w,x)||w==="phone_number"&&!z(x))return null;let ye=w==="phone_number"?le(x):x;return q(ye).then(ee=>[w,ee]).catch(ee=>null)}}));(yield Promise.allSettled(p)).forEach(w=>{if(w.status==="fulfilled"&&w.value){let[x,J]=w.value;e[x]=J,n[x]={value:J,source:"manual"}}})}}let r=!!o.sem&&!e.email,i=o.pixelIdList||[],a=null;if(window.NDPAdvancedMatching)for(let b of i){let u=window.NDPAdvancedMatching.getAdvancedMatchingInstance(b);if(u!=null&&u.isEnabled()){a=u;break}}l.debug("Checking advanced matching...",{hasAdvancedMatching:!!a,isEnabled:a==null?void 0:a.isEnabled()});let s={},d={sensitive:0,validation:0,hash:0};if(!a||!a.isEnabled()){l.debug("Advanced matching not available or not enabled. Empty custom data is sent.");let b=j(n,r);return m({cd:e},b)}l.debug("Getting advanced matching data...");try{let b=new Promise((p,S)=>setTimeout(()=>S(new Error("Advanced matching timeout")),2e3)),u=yield Promise.race([a.getProcessedData(),b]);l.debug("Advanced matching data received:",u),u&&u.data&&(s=u.sources||{},d={sensitive:u.droppedSensitiveBitmask||0,validation:u.droppedValidationBitmask||0,hash:u.droppedHashBitmask||0},Object.entries(u.data).forEach(([p,S])=>{!e[p]&&S&&(e[p]=S)}))}catch(b){l.debug("Advanced matching timeout or error:",b)}let c=m(m({},s),n),h=j(c,r,d);return m({cd:e},h)}),qe=()=>((!o.pageURL||o.pageURL!==window.location.href)&&(o.pageId=O(),o.pageURL=window.location.href),o.pageId),ze=()=>{let t="";return $()&&localStorage&&(t=localStorage.getItem(D)),t||(A(D)?t=A(D):(t=O(),P(D,t,window.location.hostname))),t},We=(t,e,n,r)=>f(null,null,function*(){let{cd:i,am_m:a,am_a:s,am_u:d,am_d:c,am_ds:h,am_dv:b,am_dh:u}=yield Be(r),p=W(m(m(m(m(m(m(m(m(m(m(m(ne(m({pid:t,vrs:pe,ev:e,pl:o.pl,v:o.v,ndclid:o.ndclid?o.ndclid:"",ndclid_src:o.ndclid_src||0,rf:o.rf,sem:o.sem||"",tm:o.sendPixelByGTM?oe:ae,iid:O(),pageid:qe(),sessionid:ze()},n&&n.event_id&&{eid:n.event_id}),{cd:i,tz:o.tz,sw:o.screenWidth||0,sh:o.screenHeight||0,gpuV:o.gpuVendor||"",gpuR:o.gpuRenderer||""}),o.rdu!==void 0&&{rdu:o.rdu}),o.rduco!==void 0&&{rduco:o.rduco}),o.rdust!==void 0&&{rdust:o.rdust}),a>0&&{am_m:a}),s>0&&{am_a:s}),d>0&&{am_u:d}),c>0&&{am_d:c}),h>0&&{am_ds:h}),b>0&&{am_dv:b}),u>0&&{am_dh:u}),X()&&{am_load:X()})),w=je()?se:N;o.sendPixelByGTM?o.sendPixelByGTM(`${w}?${p}`):yield fe(p,"GET",w)});function je(){let t;if(t=A(C),t)return t;if(t=I(C,location.search.substring(1)),t){let e=new Date;return e.setMinutes(e.getMinutes()+10),P(C,t,window.location.hostname,e),t}return""}function be(t){let e;return e=I(_,location.search.substring(1)),e?(P(_,e,window.location.hostname),{ndclid:e,ndclid_src:1}):(e=I(_,decodeURIComponent(location.href)),e?(P(_,e,window.location.hostname),{ndclid:e,ndclid_src:1}):(e=I("ndclid",document.referrer),e?(P(_,e!=null?e:"",window.location.hostname),{ndclid:e,ndclid_src:1}):t.sendPixelByGTM&&t.getCookieValues&&([e]=t.getCookieValues(_),e)?{ndclid:e,ndclid_src:2}:$()&&localStorage&&(e=localStorage.getItem(_),e)?{ndclid:e,ndclid_src:2}:(e=A(_),e?{ndclid:e,ndclid_src:2}:{ndclid:"",ndclid_src:0})))}var ve=t=>{o.rf=document.referrer,o.tz=Intl.DateTimeFormat().resolvedOptions().timeZone||"",o.screenHeight=window.screen.height,o.screenWidth=window.screen.width;let e=de();e?(o.gpuVendor=e.vendor,o.gpuRenderer=e.renderer):(o.gpuVendor="",o.gpuRenderer=""),F in t?o.sem=t[F]:B in t&&(o.em=t[B]),Object.assign(o,be(o))};function Q(t,e,n){return f(this,null,function*(){if(typeof t=="string"&&(o.pl=location.href,crypto.subtle&&o.em&&!o.sem&&(o.sem=yield q(o.em)),t)){let r=o.pixelIdList;Array.isArray(e==null?void 0:e.pixel_ids)&&(r=e.pixel_ids,r.forEach(i=>{o.pixelIdList.indexOf(i)===-1&&o.pixelIdList.push(i)}));for(let i=0;i<r.length;i++){let a=r[i];yield We(a,t,e,n)}}})}var Ke=(t,e)=>f(null,null,function*(){o.pixelIdList.indexOf(t)===-1&&o.pixelIdList.push(t),ve(e),yield he(t)}),Ye=(t,e,n)=>{t!==void 0&&(o.rdu=t),e!==void 0&&(o.rduco=e),n!==void 0&&(o.rdust=n)},Xe=t=>{t&&typeof t=="string"&&(o.ndclid=t,o.ndclid_src=1)},Qe=t=>{let[e,...n]=t;if(!(!e||typeof e!="string")){for(;n.length<3;)n.push({});switch(e.toLowerCase()){case"init":{let[r,i]=n;return Ke(r,i)}case"track":{let[r,i,a]=n;return Q(r,i,a)}case"restricteddatausage":{let[r,i,a]=n;return Ye(r,i,a)}case"ndclid":{let[r]=n;return Xe(r)}default:break}}},Se=()=>{if(Array.isArray(o.queue)&&o.queue.length>0){let t=o.queue.shift();if(t){let e=[...t];Qe(e),o.processQueue()}}},Z=(...t)=>{o.queue.push(t),o.processQueue()};var Ze=(t,e)=>{var n;return t.ndp&&Object.assign(o,t.ndp),o.v=o.v||((n=t.ndp)==null?void 0:n.v),o.pixelIdList=o.pixelIdList||[],o.processQueue=Se,o.handleRequest=Z,t.ndp=Z,{processQueue:o.processQueue}},we=Ze;try{we(window,document).processQueue()}catch(t){console.log(t),console.log("Problem with request")}})();
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ads.nextdoor.com/v2/public/pixel/advmtch.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ (()=>{var _e=Object.defineProperty;var Q=Object.getOwnPropertySymbols;var Ee=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable;var I=(n,e,t)=>e in n?_e(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,E=(n,e)=>{for(var t in e||(e={}))Ee.call(e,t)&&I(n,t,e[t]);if(Q)for(var t of Q(e))Ae.call(e,t)&&I(n,t,e[t]);return n};var m=(n,e,t)=>I(n,typeof e!="symbol"?e+"":e,t);var p=(n,e,t)=>new Promise((i,a)=>{var r=d=>{try{o(t.next(d))}catch(l){a(l)}},s=d=>{try{o(t.throw(d))}catch(l){a(l)}},o=d=>d.done?i(d.value):Promise.resolve(d.value).then(r,s);o((t=t.apply(n,e)).next())});var ee={c:"country",e:"email",g:"gender",i:"external_id",n:["first_name","last_name"],p:"phone_number",r:["city","state","zip_code"],s:"street_address"},te={email:["email","e-mail","mail"],phone_number:["phone","tel","telephone","mobile","cell"],first_name:["first","fname","firstname","given"],last_name:["last","lname","lastname","family","surname"],street_address:["address","street","addr"],city:["city","town","locality"],state:["state","province","region"],zip_code:["zip","postal","postcode"],country:["country","nation"],gender:["gender","sex"],external_id:["id","userid","customer_id","user_id","member_id","account_id","external_id","reference","tracking_id"]};function Se(n){return n in te}function v(n,e){if(!n)return null;let t=n.toLowerCase(),i=E(E({},te),e);for(let[a,r]of Object.entries(i))if(r&&r.some(s=>t.includes(s))){if(a==="street_address"&&t.includes("email"))continue;if(Se(a))return a}return null}function Te(n,e){let t=v(n.name,e);if(t)return t;let i=v(n.id,e);if(i)return i;let a=n.getAttribute("placeholder");if(a){let r=v(a,e);if(r)return r}return null}function H(n,e){if(!e)return!1;if(e==="1")return!0;if(e==="0")return!1;for(let[t,i]of Object.entries(ee))if(Array.isArray(i)){if(i.includes(n)&&e.includes(t))return!0}else if(i===n&&e.includes(t))return!0;return!1}var f=class f{constructor(){m(this,"config");let e=f.DEBUG_FLAG_KEY,t=null;try{let d=localStorage.getItem(f.STORAGE_LEVEL_KEY);if(d){let l=JSON.parse(d);Date.now()-l.ts<3e5?t=l.level:localStorage.removeItem(f.STORAGE_LEVEL_KEY)}}catch(d){}let i=(()=>{try{return localStorage.getItem(e)==="1"}catch(d){return!1}})(),a=(()=>{try{return new URLSearchParams(window.location.search).get(e)==="1"}catch(d){return!1}})(),r=(()=>{try{let d=localStorage.getItem(f.STORAGE_OPTS_KEY);return d?JSON.parse(d):null}catch(d){return null}})(),s=i||t&&t!=="off"||a,o=t&&t!=="off"?t:i||a?"debug":"error";this.config={enabled:s,level:s?o:"error",prefix:"[Nextdoor Pixel]",includeTimestamp:!!(r!=null&&r.includeTimestamp),includeLocation:!!(r!=null&&r.includeLocation)}}formatPrefix(e){let t=[this.config.prefix,`[${e.toUpperCase()}]`];if(this.config.includeTimestamp)try{t.push(new Date().toISOString())}catch(i){}if(this.config.includeLocation){let i=this.getCallerLocation();i&&t.push(`(${i})`)}return t.join(" ")}getCallerLocation(){try{let e=new Error;if(!e.stack)return null;let t=e.stack.split(`
2
+ `).map(i=>i.trim());for(let i=1;i<t.length;i++){let a=t[i];if(!a||a.includes("basic/logger"))continue;let r=a.match(/\(?([^()]+):(\d+):(\d+)\)?$/);if(r){let s=r[1],o=r[2];return`${s}:${o}`}}return null}catch(e){return null}}shouldLog(e){if(!this.config.enabled)return!1;let t=["debug","info","warn","error"],i=t.indexOf(this.config.level);return t.indexOf(e)>=i}debug(e,...t){this.shouldLog("debug")&&(console.groupCollapsed(`${this.formatPrefix("debug")} ${e}`,...t),console.trace(),console.groupEnd())}info(e,...t){this.shouldLog("info")&&console.log(`${this.formatPrefix("info")} ${e}`,...t)}warn(e,...t){this.shouldLog("warn")&&console.warn(`${this.formatPrefix("warn")} ${e}`,...t)}error(e,...t){this.shouldLog("error")&&console.error(`${this.formatPrefix("error")} ${e}`,...t)}enableDebug(){this.config.enabled=!0,this.config.level="debug";try{localStorage.setItem("ndp_debug","1");let e={level:"debug",ts:Date.now()};localStorage.setItem(f.STORAGE_LEVEL_KEY,JSON.stringify(e))}catch(e){}console.log(`${this.config.prefix} Debug mode enabled`)}disable(){this.config.enabled=!1;try{localStorage.removeItem("ndp_debug");let e={level:"off",ts:Date.now()};localStorage.setItem(f.STORAGE_LEVEL_KEY,JSON.stringify(e))}catch(e){}}setLevel(e){if(e==="off")this.disable();else{this.config.enabled=!0,this.config.level=e;try{let t={level:e,ts:Date.now()};localStorage.setItem(f.STORAGE_LEVEL_KEY,JSON.stringify(t))}catch(t){}console.log(`${this.config.prefix} Log level set to '${e}'`)}}setOptions(e){try{typeof e.includeTimestamp=="boolean"&&(this.config.includeTimestamp=e.includeTimestamp),typeof e.includeLocation=="boolean"&&(this.config.includeLocation=e.includeLocation);let t={includeTimestamp:this.config.includeTimestamp,includeLocation:this.config.includeLocation};localStorage.setItem(f.STORAGE_OPTS_KEY,JSON.stringify(t)),console.log(`${this.config.prefix} Log options updated`,t)}catch(t){}}};m(f,"STORAGE_LEVEL_KEY","ndp_log_level"),m(f,"DEBUG_FLAG_KEY","ndp_debug"),m(f,"STORAGE_OPTS_KEY","ndp_log_opts");var A=f,c=new A;typeof window!="undefined"&&(window.ndpDebug=()=>(c.enableDebug(),"Nextdoor Pixel debug mode enabled. Check console for detailed logs."),window.ndpLog=n=>(c.setLevel(n),`Nextdoor Pixel log level set to '${n}'.`),window.ndpLogOptions=n=>(c.setOptions(n),"Nextdoor Pixel log options updated."),window.ndpReset=n=>{try{let e=[],t=()=>{try{localStorage.removeItem(A.DEBUG_FLAG_KEY)}catch(a){}try{localStorage.removeItem(A.STORAGE_LEVEL_KEY)}catch(a){}c.disable(),e.push("debug flags")},i=()=>{try{sessionStorage.removeItem("ndp_settings")}catch(a){}try{sessionStorage.removeItem("ndp_settings_expiry")}catch(a){}e.push("settings cache")};if(n)n==="debug"?t():n==="setting"&&i();else{t();try{localStorage.removeItem("gpuInfo")}catch(a){}try{localStorage.removeItem("ndp_session_id")}catch(a){}try{localStorage.removeItem("ndclid")}catch(a){}i(),e.push("gpuInfo","ndp_session_id","ndclid")}return`Nextdoor Pixel reset completed: ${e.join(", ")||n||"none"}`}catch(e){return"Nextdoor Pixel reset encountered an error (see console)."}});var g={ssn:[/^\d{3}-\d{2}-\d{4}$/,/^\d{3}\s\d{2}\s\d{4}$/,/^\d{9}$/],creditCard:[/^4[0-9]{12}(?:[0-9]{3})?$/,/^5[1-5][0-9]{14}$/,/^3[47][0-9]{13}$/,/^3[0-9]{13}$/,/^6(?:011|5[0-9]{2})[0-9]{12}$/,/^\d{4}\s\d{4}\s\d{4}\s\d{4}$/,/^\d{4}-\d{4}-\d{4}-\d{4}$/],driversLicense:[/^[A-Z]\d{7,8}$/,/^[A-Z]{2}\d{6,7}$/,/^\d{8,9}$/,/^[A-Z]\d{3}-\d{3}-\d{3}$/],medicalId:[/^MRN\d{6,10}$/i,/^PAT\d{6,10}$/i,/^PID\d{6,10}$/i],bankAccount:[/^\d{12,17}$/,/^\d{4}\s\d{4}\s\d{4}$/],passport:[/^[A-Z]{2}\d{7}$/],taxId:[/^\d{2}-\d{7}$/,/^\d{3}-\d{2}-\d{4}$/],insurance:[/^[A-Z]{2,3}\d{8,12}$/,/^POL\d{6,10}$/i,/^INS\d{6,10}$/i],sensitiveNumeric:[/^\d{16}$/,/^\d{15}$/,/^\d{9}$/]},Le=[/ssn/i,/social.?security/i,/tax.?id/i,/credit.?card/i,/card.?number/i,/ccn/i,/cvv/i,/cvc/i,/expiry/i,/expiration/i,/security.?code/i,/card.?code/i,/account.?number/i,/routing.?number/i,/bank.?account/i,/iban/i,/swift/i,/drivers?.?license/i,/dl.?number/i,/license.?number/i,/medical.?record/i,/patient.?id/i,/mrn/i,/health.?id/i,/insurance.?id/i,/passport/i,/passport.?number/i,/confidential/i,/secret/i,/private.?key/i,/password/i,/pin/i],Me=[/payment/i,/billing/i,/checkout/i,/credit/i,/bank/i,/medical/i,/health/i,/insurance/i,/tax/i,/government/i,/identity/i,/verification/i,/kyc/i,/background.?check/i];function xe(n){return n?Le.some(e=>e.test(n)):!1}var De={phone_number:new Set([g.driversLicense[2],g.bankAccount[0],g.ssn[2],g.sensitiveNumeric[0],g.sensitiveNumeric[1],g.sensitiveNumeric[2]]),zip_code:new Set([g.ssn[2],g.sensitiveNumeric[2],g.driversLicense[2]])},Ie=new Set(["phone_number","zip_code"]);function He(n,e){if(!n)return!1;let t=n.replace(/[\s-.]/g,""),i=De[e];for(let[a,r]of Object.entries(g))for(let s of r)if(!(i!=null&&i.has(s))&&(s.test(t)||s.test(n)))return c.warn(`Detected sensitive data pattern: ${a}`),!0;return!1}function w(){var e;let n=[document.title,document.URL,((e=document.querySelector('meta[name="description"]'))==null?void 0:e.getAttribute("content"))||""].join(" ").toLowerCase();return Me.some(t=>t.test(n))}function M(n,e){if(xe(n))return c.warn(`Blocked sensitive field: ${n}`),!0;if(He(e,n))return c.warn(`Blocked sensitive value in field: ${n}`),!0;let t=e.replace(/[\s-]/g,"");return!Ie.has(n)&&w()&&/^\d+$/.test(t)&&t.length>=8?(c.warn(`Blocked numeric data in sensitive context: ${n}`),!0):!1}var F="ndp_session_id";var C=["email","phone_number","first_name","last_name","gender","street_address","city","state","zip_code","country"],x={email:0,phone_number:1,first_name:2,last_name:3,external_id:4,city:5,state:6,zip_code:7,country:8,street_address:9,gender:10};function ie(n,e=!0){return p(this,null,function*(){if(!n)return"";e&&(n=n.toLowerCase());let t=new TextEncoder().encode(n),i=yield window.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(s=>s.toString(16).padStart(2,"0")).join("")})}function _(n){if(!n||n.length>254)return!1;let e=n.split("@");if(e.length!==2)return!1;let[t,i]=e;return t.length>64||t.length===0||i.length>253||i.length===0?!1:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)}function S(n){if(!n)return!1;let e=n.replace(/[\s\-+().]/g,"");return/^\d+$/.test(e)?e.length>=7&&e.length<=15:!1}function ae(n){return n.replace(/\D/g,"")}var P={email:['input[type="email"]','input[name="email"]','input[id="email"]','input[name="user_email"]','input[name="customer_email"]','input[name="billing_email"]','input[name="contact_email"]','input[id="test_email"]','input[id*="contact-email"]','input[data-tid*="email"]','input[data-testid*="email"]','input[data-tag_item="email"]','input[formcontrolname*="email"]','input[aria-label*="email" i]','input[placeholder*="email" i]','input[name*="signInName"]'].join(", "),phone_number:['input[type="tel"]','input[name="phone"]','input[id="phone"]','input[name="phone_number"]','input[name="telephone"]','input[name="mobile"]','input[name="billing_phone"]','input[id="test_phone"]','input[id*="contact-phone"]','input[data-tid*="phone"]','input[data-testid*="phone"]','input[data-tag_item="phone_number"]','input[autocomplete="tel-national"]','input[name*="signInName"]'].join(", "),first_name:['input[name="first_name"]','input[id="first_name"]','input[name="fname"]','input[name="firstname"]','input[name="billing_first_name"]','input[id="test_first_name"]','input[name="fullName"]','input[data-testid*="name"]','input[autocomplete="name"]','input[data-tag_item="name"]'].join(", "),last_name:['input[name="last_name"]','input[id="last_name"]','input[name="lname"]','input[name="lastname"]','input[name="billing_last_name"]','input[id="test_last_name"]'].join(", "),street_address:['input[name="address"]','input[name="street_address"]','input[name="address_line_1"]','input[name="billing_address"]','input[name="shipping_address"]','input[id="test_street_address"]','input[formcontrolname="streetCtrl"]','input[placeholder*="street" i]','input[placeholder*="address" i]'].join(", "),city:['input[name="city"]','input[id="city"]','input[name="billing_city"]','input[name="shipping_city"]','input[id="test_city"]'].join(", "),state:['input[name="state"]','input[id="state"]','select[name="state"]','input[name="province"]','input[name="billing_state"]','input[name="shipping_state"]','input[id="test_state"]','select[data-testid*="state"]','select[formcontrolname*="state"]'].join(", "),zip_code:['input[name="zip"]','input[name="zip_code"]','input[name="postal_code"]','input[name="postcode"]','input[name="billing_zip"]','input[name="shipping_zip"]','input[id="test_zip_code"]','input[formcontrolname="zipCodeCtrl"]','input[data-testid*="zip"]','input[placeholder*="zip" i]','input[class*="zip-code"]'].join(", "),country:['select[name="country"]','input[name="country"]','select[name="billing_country"]','select[name="shipping_country"]','select[id="test_country"]'].join(", "),gender:['select[name="gender"]','input[name="gender"]','input[type="radio"][name="gender"]','select[id="test_gender"]'].join(", "),external_id:['input[name="user_id"]','input[name="customer_id"]','input[name="member_id"]','input[name="account_id"]','input[name="external_id"]','input[id="user_id"]','input[id="customer_id"]','input[id="member_id"]','input[name="reference_id"]','input[name="tracking_id"]','input[data-testid*="user-id"]','input[data-testid*="customer-id"]','input[placeholder*="id" i]','input[placeholder*="reference" i]'].join(", ")},k=['button[id="checkout"]','button[class*="checkout-btn"]','button[class*="checkout-button"]','input[type="submit"][value*="checkout"]','input[type="submit"][value*="order"]','button[id="purchase"]','button[class*="purchase-btn"]','button[class*="buy-now"]','input[type="submit"][value*="purchase"]'],re={email:"email",e:"email",phone:"phone_number",p:"phone_number",fname:"first_name",lname:"last_name",first_name:"first_name",last_name:"last_name",country:"country",user_id:"external_id",customer_id:"external_id",member_id:"external_id",account_id:"external_id",external_id:"external_id",uid:"external_id",ref:"external_id"};function N(n,e){new URLSearchParams(window.location.search).forEach((i,a)=>{let r=re[a.toLowerCase()];r&&n(r)&&e(r,i,"url")})}function O(n){var a,r,s,o;if(n.disabled)return!1;for(let d=n.parentElement;d;d=d.parentElement)if(d.tagName==="FIELDSET"&&d.disabled)return!1;let e=n;if(((a=n.type)==null?void 0:a.toLowerCase())==="hidden")return!0;if(((r=e.style)==null?void 0:r.display)==="none"||((s=e.style)==null?void 0:s.visibility)==="hidden")return!1;let i=e.offsetWidth;return!(e.offsetParent===null&&typeof i=="number"&&i===0&&typeof((o=document.body)==null?void 0:o.offsetHeight)=="number"&&document.body.offsetHeight>0)}function R(n,e,t){n.querySelectorAll("input, select, textarea").forEach(a=>{var l;let r=a;if(!O(r))return;let s=(l=r.type)==null?void 0:l.toLowerCase();if(s==="password"||s==="submit"||s==="reset"||s==="button"||s==="image"||s==="file"||(s==="radio"||s==="checkbox")&&!r.checked)return;let o=r.value||"";if(!o)return;if(!T(r,e,t)){let u=v(r.name||r.id);u&&e(u)&&t(u,o,"auto")}})}function $(n,e){document.querySelectorAll("form").forEach(i=>{i.querySelectorAll("input, select").forEach(r=>{let s=r;if(s.value){let o=v(s.name||s.id);if(o&&n(o)){if(M(o,s.value))return;e(o,s.value,"auto")}}})})}function se(n){var i,a,r,s,o,d,l,u,h,Z,J,X;let e={name:((i=n.name)==null?void 0:i.toLowerCase())||"",id:((a=n.id)==null?void 0:a.toLowerCase())||"",type:((r=n.type)==null?void 0:r.toLowerCase())||"",placeholder:((s=n.placeholder)==null?void 0:s.toLowerCase())||"",ariaLabel:((o=n.getAttribute("aria-label"))==null?void 0:o.toLowerCase())||"",dataTestId:((d=n.getAttribute("data-testid"))==null?void 0:d.toLowerCase())||"",dataTid:((l=n.getAttribute("data-tid"))==null?void 0:l.toLowerCase())||"",dataTagItem:((u=n.getAttribute("data-tag_item"))==null?void 0:u.toLowerCase())||"",formControlName:((h=n.getAttribute("formcontrolname"))==null?void 0:h.toLowerCase())||"",autocomplete:((Z=n.autocomplete)==null?void 0:Z.toLowerCase())||"",className:((J=n.className)==null?void 0:J.toLowerCase())||"",value:((X=n.value)==null?void 0:X.toLowerCase())||""},t=Object.values(e).join(" ");return e.type==="email"||e.dataTagItem==="email"||/email/.test(t)||e.value&&_(e.value)?"email":e.type==="tel"||e.dataTagItem==="phone_number"||/phone|tel/.test(t)||e.value&&S(e.value)?"phone_number":/\blastname\b|\blname\b|\bsurname\b|family[ _-]?name/.test(t)||e.autocomplete==="family-name"||e.dataTagItem==="last_name"?"last_name":e.dataTagItem==="name"||e.autocomplete==="given-name"||/fullname|firstname|\bfname\b|given.?name|\bname\b/.test(t)?"first_name":/zip|postal|postcode/.test(t)?"zip_code":/address|street/.test(t)?"street_address":n.tagName==="SELECT"&&/state/.test(t)?"state":/user.?id|customer.?id|member.?id|account.?id|external.?id|reference.?id|tracking.?id/.test(t)?"external_id":null}function oe(n){let e=n.options[n.selectedIndex];if(!(e!=null&&e.value)||e.disabled)return"";let t=Array.from(n.options).findIndex(s=>s.value&&!s.disabled)===n.selectedIndex,i=Array.from(n.options).slice(0,n.selectedIndex).some(s=>!s.value||s.disabled),a=n.hasAttribute("data-gtm-form-interact-field-id")||n.hasAttribute("data-analytics")||n.hasAttribute("data-track")||n.hasAttribute("data-ga")||n.hasAttribute("data-fb-track")||/track|analytics|gtm|ga-/.test(n.className)||/track|analytics|gtm|ga-/.test(n.id),r=/state/.test(n.name+n.id)&&(e.value==="AL"||e.value==="AB")||/country/.test(n.name+n.id)&&(e.value==="AF"||e.value==="US")||e.value&&e.value.length<=3&&e.textContent&&e.textContent.length>e.value.length*2;return t&&i&&(a||r)?"":e.value}function ce(n){let e=n.trim();if(!e)return{};let t=e.split(/\s+/).filter(i=>i.length>0);return t.length===1?{first_name:t[0]}:t.length===2?{first_name:t[0],last_name:t[1]}:{first_name:t[0],last_name:t.slice(1).join(" ")}}function T(n,e,t){let i=se(n);if(!i)return!1;if(!e(i))return!0;let a="";if(n.tagName==="SELECT"?a=oe(n):a=n.value||"",!a.trim())return!0;if(i==="first_name"&&a.includes(" ")){let r=ce(a);r.first_name&&t("first_name",r.first_name,"auto"),r.last_name&&e("last_name")&&t("last_name",r.last_name,"auto")}else t(i,a.trim(),"auto");return!0}function U(n,e){V(document,n,e)}function V(n,e,t){let i=n.querySelectorAll("input, select, textarea"),a=Array.from(i);n instanceof Element&&n.matches("input, select, textarea")&&a.unshift(n),a.forEach(r=>{let s=r;s.type!=="password"&&s.value&&T(s,e,t)})}var z="ndp_settings",j="ndp_settings_expiry",le=300*1e3,B=new Map;function we(n,e){try{let t=de();t[n]=e,sessionStorage.setItem(z,JSON.stringify(t)),sessionStorage.setItem(j,(Date.now()+le).toString());let i=Object.keys(t).filter(a=>!a.startsWith("_"));c.debug("Cached settings for pixel:",n,{cacheSize:i.length,expiryTime:new Date(Date.now()+le).toISOString()})}catch(t){c.warn("Failed to cache settings:",t)}}function Fe(n){try{let e=sessionStorage.getItem(j);if(!e||Date.now()>parseInt(e))return Ce(),null;let i=de()[n];return i&&typeof i=="object"&&!Array.isArray(i)?i:null}catch(e){return null}}function de(){try{let n=sessionStorage.getItem(z);if(!n)return{};let e=JSON.parse(n),t={};for(let i in e)e[i]&&typeof e[i]=="object"&&!Array.isArray(e[i])&&(t[i]=e[i]);return t}catch(n){return c.warn("Failed to parse cached settings:",n),{}}}function Ce(){try{sessionStorage.removeItem(z),sessionStorage.removeItem(j),c.debug("Cleared settings cache")}catch(n){c.warn("Failed to clear settings cache:",n)}}function ue(n,e=3,t=1e3,i="https://ads.nextdoor.com/v2/api/conversions/settings"){return p(this,null,function*(){let a=Fe(n);if(a)return c.debug("Using cached settings for pixel:",n),a;let r=B.get(n);if(r)return c.debug("Joining existing settings request for pixel:",n),r;let s=p(null,null,function*(){try{c.debug("Starting new settings request for pixel:",n);let o=yield Pe(n,e,t,i);return we(n,o),c.debug("Successfully fetched and cached settings for pixel:",n),o}catch(o){throw c.error("Failed to fetch settings for pixel:",n,o),o}finally{B.delete(n)}});return B.set(n,s),s})}function Pe(n,e=3,t=1e3,i="https://ads.nextdoor.com/v2/api/conversions/settings"){return p(this,null,function*(){let a=(r=0)=>p(null,null,function*(){try{c.debug("Fetching settings from server for pixel:",n);let s=typeof AbortSignal.timeout=="function"?AbortSignal.timeout(5e3):void 0,o=yield fetch(`${i}?id=${n}`,E({method:"GET",headers:{"Content-Type":"application/json"}},s&&{signal:s}));if(!o.ok)throw new Error(`Settings API returned ${o.status}: ${o.statusText}`);return yield o.json()}catch(s){return r<e?(c.debug(`Settings fetch failed, retrying... (${r+1}/${e})`),yield new Promise(o=>setTimeout(o,t)),a(r+1)):(c.warn("Unable to obtain settings from API. Falling back to default configuration."),{am:"0",em:{},t:Date.now()})}});return a()})}var G=class{constructor(e){m(this,"instances",new Map);m(this,"componentName");this.componentName=e,typeof window!="undefined"&&window.addEventListener("beforeunload",()=>{this.cleanup()})}getInstance(e,t){return p(this,null,function*(){if(!e)return c.warn(`No key provided for ${this.componentName} initialization`),null;let i=this.instances.get(e);if(i&&this.isInstanceValid(i))return c.debug(`Using existing ${this.componentName} instance for key:`,e),i;try{c.debug(`Starting ${this.componentName} initialization for key:`,e);let a=yield t();return this.isInstanceValid(a)?(this.instances.set(e,a),c.debug(`Successfully initialized ${this.componentName} for key:`,e),a):(c.warn(`${this.componentName} instance created but not valid for key:`,e),null)}catch(a){return c.error(`${this.componentName} initialization failed for key:`,e,a),null}})}getExistingInstance(e){let t=this.instances.get(e);return t&&this.isInstanceValid(t)?t:null}isInstanceValid(e){return typeof e.isEnabled=="function"?e.isEnabled():typeof e.isReady=="function"?e.isReady():!0}removeInstance(e){let t=this.instances.get(e);if(t){if(typeof t.cleanup=="function")try{t.cleanup()}catch(i){c.debug(`Failed to cleanup ${this.componentName} instance:`,i)}this.instances.delete(e),c.debug(`Removed ${this.componentName} instance for key:`,e)}}getInstanceCount(){return this.instances.size}getInstanceKeys(){return Array.from(this.instances.keys())}cleanup(){c.debug(`Cleaning up ${this.componentName} instances:`,this.instances.size),this.instances.forEach((e,t)=>{if(typeof e.cleanup=="function")try{e.cleanup()}catch(i){c.debug(`Failed to cleanup ${this.componentName} instance ${t}:`,i)}}),this.instances.clear(),c.debug(`${this.componentName} cleanup completed`)}};function me(n){return new G(n)}var ke="ndp_am_",Ne=1800*1e3;function K(){try{if(typeof localStorage!="undefined"){let n=localStorage.getItem(F);if(n)return n}if(typeof document!="undefined"&&document.cookie){let n=document.cookie.match(new RegExp("(?:^|; )"+F+"=([^;]*)"));if(n)return decodeURIComponent(n[1])}}catch(n){}return null}function W(n){return`${ke}${n}`}function pe(){let n;try{if(n=K(),!n||typeof sessionStorage=="undefined")return null;let e=sessionStorage.getItem(W(n));if(!e)return null;let t=JSON.parse(e);return typeof t.writtenAt!="number"||Date.now()-t.writtenAt>Ne?null:t}catch(e){return c.debug("persistedAmStore: read failed",e),null}}function Oe(n){try{let e=K();if(!e||typeof sessionStorage=="undefined")return;sessionStorage.setItem(W(e),JSON.stringify(n))}catch(e){c.debug("persistedAmStore: write failed",e)}}function he(){return pe()}function Y(n){if(!n.emailHash&&!n.phoneHash)return;let e=pe(),t={writtenAt:Date.now()};if(n.emailHash?t.emailHash=n.emailHash:e!=null&&e.emailHash&&(t.emailHash=e.emailHash),n.phoneHash?t.phoneHash=n.phoneHash:e!=null&&e.phoneHash&&(t.phoneHash=e.phoneHash),e){let i=n.emailHash&&e.emailHash&&n.emailHash!==e.emailHash,a=n.phoneHash&&e.phoneHash&&n.phoneHash!==e.phoneHash;(i||a)&&(n.emailHash||delete t.emailHash,n.phoneHash||delete t.phoneHash)}Oe(t)}function fe(){try{let n=K();if(!n||typeof sessionStorage=="undefined")return;sessionStorage.removeItem(W(n))}catch(n){c.debug("persistedAmStore: clear failed",n)}}var ge=/(checkout|log[ -]?in|sign[ -]?up|sign[ -]?in|register|create[ -]?account|submit|subscribe|place[ -]order|pay[ -]?now|complete[ -]?order|reserve)/i,ve=100;function Re(n,e){let t=n.closest("button, input");return!t||!e.contains(t)||t.disabled===!0?!1:t instanceof HTMLInputElement?t.type==="submit"||t.type==="image":t instanceof HTMLButtonElement?!t.type||t.type==="submit":!1}var $e=/^[a-fA-F0-9]{64}$/,b=n=>$e.test(n),D=me("AdvancedMatching"),y=class y{constructor(e){m(this,"config",null);m(this,"dataSourceId");m(this,"collectedData",{});m(this,"droppedSensitiveBitmask",0);m(this,"droppedValidationBitmask",0);m(this,"droppedHashBitmask",0);m(this,"getProcessedDataChain",Promise.resolve());m(this,"processingEnabled",!1);m(this,"inputDebounceTimers",new WeakMap);m(this,"pendingDebounceTimerIds",new Set);m(this,"listenersAttached",new WeakSet);m(this,"disposed",!1);m(this,"restoredHashes",new Map);m(this,"autoCollectionEnabled",!1);m(this,"mutationObserver",null);m(this,"pendingScanRoots",[]);m(this,"mutationScanTimer",null);m(this,"pageHideHandler",null);m(this,"pageShowHandler",null);m(this,"leaveFlushPagehide",null);m(this,"leaveFlushVisibility",null);this.dataSourceId=e}enableAutoCollection(){if(!this.processingEnabled||this.autoCollectionEnabled)return;this.autoCollectionEnabled=!0;let e=()=>{try{this.restoreFromPersistedStore(),U(()=>!0,(t,i,a)=>this.collectField(t,i,a)),this.scanDisplayTextForUserIdentity(),this.attachFormListeners(),this.collectFromUrlParams(),this.attachCheckoutListeners(),this.attachClickCapture(),this.attachFormSubmissionHooks(),this.observeDynamicMounts(),this.attachLeaveFlush()}catch(t){c.debug("AdvancedMatching setupListeners failed",t)}};if(document.readyState==="loading"){let t=()=>e();document.addEventListener("DOMContentLoaded",t)}else e()}attachClickCapture(){let e=t=>{var i;try{if(this.disposed)return;let a=t.target;if(!(a instanceof Element))return;let r=a.closest("form");if(!r)return;if(Re(a,r)){this.collectFromForm(r);return}let s=((i=a.textContent)!=null?i:"").trim().slice(0,ve),o=a instanceof HTMLInputElement&&a.value?a.value.slice(0,ve):"";if(!ge.test(s)&&!ge.test(o))return;this.collectFromForm(r)}catch(a){c.debug("AdvancedMatching click capture failed",a)}};document.addEventListener("click",e,{capture:!0})}attachFormSubmissionHooks(){let e=t=>{try{if(this.disposed)return;let i=t.formData;if(!i||typeof i.entries!="function")return;let a=t.target instanceof HTMLFormElement?t.target:null;if(!a)return;for(let[r,s]of i.entries()){if(typeof s!="string"||!s)continue;let o=a.querySelectorAll(`input[name="${CSS.escape(r)}"]`),d=!1;if(o.forEach(u=>{u instanceof HTMLInputElement&&u.type==="password"&&(d=!0)}),d)continue;let l=v(r);l&&this.collectField(l,s,"auto")}}catch(i){c.debug("AdvancedMatching formdata handler failed",i)}};document.addEventListener("formdata",e,{capture:!0});try{let t=window;if(t.__ndpRequestSubmitPatched)return;t.__ndpRequestSubmitPatched=!0;let i=HTMLFormElement.prototype.requestSubmit;if(typeof i!="function")return;HTMLFormElement.prototype.requestSubmit=function(a){try{for(let r of D.getInstanceKeys()){let s=D.getExistingInstance(r);s&&!s.disposed&&s.collectFromForm(this)}}catch(r){c.debug("AdvancedMatching requestSubmit hook failed",r)}return i.call(this,a!=null?a:null)}}catch(t){c.debug("AdvancedMatching requestSubmit patch failed",t)}}restoreFromPersistedStore(){try{let e=he();if(!e)return;e.emailHash&&b(e.emailHash)&&this.restoredHashes.set("email",e.emailHash),e.phoneHash&&b(e.phoneHash)&&this.restoredHashes.set("phone_number",e.phoneHash)}catch(e){c.debug("AdvancedMatching restore from persisted store failed",e)}}attachFormListeners(){this.attachListenersWithin(document)}attachListenersWithin(e){Object.entries(P).forEach(([t,i])=>{e.querySelectorAll(i).forEach(r=>{this.listenersAttached.has(r)||(this.listenersAttached.add(r),this.attachListenersToElement(r,t))}),e instanceof Element&&e.matches(i)&&!this.listenersAttached.has(e)&&(this.listenersAttached.add(e),this.attachListenersToElement(e,t))})}attachListenersWithinSubtree(e){this.attachListenersWithin(e)}attachListenersToElement(e,t){let i=r=>{if(this.disposed)return;let s=r.target;if(!(s!=null&&s.value)||!O(s))return;T(s,()=>!0,(d,l,u)=>this.collectField(d,l,u))||this.collectField(t,s.value,"auto")},a=r=>{if(this.disposed)return;let s=r.target,o=this.inputDebounceTimers.get(s);o!==void 0&&(clearTimeout(o),this.pendingDebounceTimerIds.delete(o));let d=setTimeout(()=>{this.inputDebounceTimers.delete(s),this.pendingDebounceTimerIds.delete(d),s.isConnected&&i(r)},y.INPUT_DEBOUNCE_MS);this.inputDebounceTimers.set(s,d),this.pendingDebounceTimerIds.add(d)};e.addEventListener("blur",i),e.addEventListener("change",i),e.addEventListener("input",a)}attachCheckoutListeners(){let e=t=>{let i=t.target;this.collectFromForm(i)};document.addEventListener("submit",e),k.forEach(t=>{document.querySelectorAll(t).forEach(a=>{let r=()=>{setTimeout(()=>{this.collectFromCurrentPage()},y.CHECKOUT_BUTTON_DELAY)};a.addEventListener("click",r)})})}collectFromUrlParams(){N(()=>!0,(e,t,i)=>this.collectField(e,t,i))}collectFromForm(e){R(e,()=>!0,(t,i,a)=>this.collectField(t,i,a))}collectFromCurrentPage(){$(()=>!0,(e,t,i)=>this.collectField(e,t,i))}scanDisplayTextForUserIdentity(){var e;try{if(this.disposed)return;let t=document.querySelectorAll('[class*="user-email" i], [class*="account-email" i], [class*="profile-email" i], [class*="member-email" i], [id*="user-email" i], [id*="account-email" i], [id*="profile-email" i], [id*="member-email" i], [data-testid*="email" i][data-testid*="user" i], [data-testid*="email" i][data-testid*="account" i], [data-testid*="email" i][data-testid*="profile" i], [class*="user-phone" i], [class*="account-phone" i], [data-testid*="phone" i][data-testid*="user" i]');if(t.length===0)return;let i=16,a=/support|contact|help|footer/i;for(let r=0;r<Math.min(t.length,i);r++){let s=t[r];if(s.closest('footer, [class*="footer" i], [class*="support" i], [class*="contact" i], [class*="help" i]'))continue;let o=(s.className+" "+s.id).toLowerCase();if(a.test(o))continue;let d=((e=s.textContent)!=null?e:"").trim();if(!d||d.length>100)continue;let l=d.match(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/);if(l&&_(l[0])){this.collectField("email",l[0],"auto");continue}let u=d.match(/[+]?[\d().\s-]{7,20}/);if(u){let h=u[0].replace(/\D/g,"");h.length>=7&&h.length<=15&&this.collectField("phone_number",u[0],"auto")}}}catch(t){c.debug("AdvancedMatching scanDisplayTextForUserIdentity failed",t)}}isFieldEnabled(e){var t;return H(e,(t=this.config)==null?void 0:t.am)}recordDrop(e,t){let i=x[e];if(i===void 0)return;let a=1<<i;t==="sensitive"?this.droppedSensitiveBitmask|=a:t==="validation"?this.droppedValidationBitmask|=a:this.droppedHashBitmask|=a}collectField(e,t,i="auto"){if(t){if(C.includes(e)&&b(t)){this.collectedData[e]={value:t,source:i};return}if(M(e,t)){c.warn(`Blocked sensitive data collection for field: ${e}`),this.recordDrop(e,"sensitive");return}if(e==="email"&&!_(t)){c.debug("Invalid email format rejected"),this.recordDrop(e,"validation");return}if(e==="phone_number"&&!S(t)){c.debug("Invalid phone format rejected"),this.recordDrop(e,"validation");return}if(e==="email"&&!_(t)){this.recordDrop(e,"validation");return}if(e==="phone_number"&&!S(t)){this.recordDrop(e,"validation");return}if(e==="zip_code"&&t.length>20){this.recordDrop(e,"validation");return}if(e==="external_id"&&!/^[a-zA-Z0-9_-]+$/.test(t)){this.recordDrop(e,"validation");return}if(e==="external_id"){if(t.length>100||t.length<2){c.debug(`External ID invalid length: ${t.length} characters`),this.recordDrop(e,"validation");return}if(!/^[a-zA-Z0-9_-]+$/.test(t)){c.debug("External ID contains invalid characters"),this.recordDrop(e,"validation");return}}if(w()&&this.isHighRiskField(e,t)){c.warn(`Blocked data collection in sensitive context for field: ${e}`),this.recordDrop(e,"sensitive");return}this.collectedData[e]={value:t,source:i}}}attachLeaveFlush(){if(this.leaveFlushPagehide||this.leaveFlushVisibility)return;let e=()=>{this.flushPersistOnLeave()};this.leaveFlushPagehide=e,this.leaveFlushVisibility=()=>{document.visibilityState==="hidden"&&e()},window.addEventListener("pagehide",this.leaveFlushPagehide),document.addEventListener("visibilitychange",this.leaveFlushVisibility)}flushPersistOnLeave(){return p(this,null,function*(){if(!this.disposed)try{let e=this.collectedData.email,t=this.collectedData.phone_number,i=(s,o)=>p(this,null,function*(){if(!s)return;if(b(s))return s;let d=yield this.safeDigestMessage(s,o);return d!==null&&b(d)?d:void 0}),[a,r]=yield Promise.all([i(e==null?void 0:e.value,"email"),i(t==null?void 0:t.value,"phone_number")]);if(this.disposed)return;(a||r)&&Y({emailHash:a,phoneHash:r})}catch(e){c.debug("AdvancedMatching flushPersistOnLeave failed",e)}})}isHighRiskField(e,t){return!!(e==="external_id"&&/^\d{6,}$/.test(t))}getProcessedData(){let e=this.getProcessedDataChain.catch(()=>{}).then(()=>this.getProcessedDataImpl());return this.getProcessedDataChain=e.catch(()=>{}),e}getProcessedDataImpl(){return p(this,null,function*(){let e=this.droppedSensitiveBitmask,t=this.droppedValidationBitmask,i=this.droppedHashBitmask;this.droppedSensitiveBitmask=0,this.droppedValidationBitmask=0,this.droppedHashBitmask=0,this.collectFromCurrentPage();let a={},r={},s=new Set,o=!1;for(let[l,u]of Object.entries(this.collectedData))if(u!=null&&u.value&&this.isFieldEnabled(l))if(C.includes(l))if(b(u.value))a[l]=u.value,r[l]=u,s.add(l);else{let h=yield this.safeDigestMessage(u.value,l);if(h===null){o=o||this.restoredHashes.has(l);continue}if(!b(h)){c.debug(`Hashing for field ${l} did not produce SHA-256; dropping`),this.recordDrop(l,"hash"),o=o||this.restoredHashes.has(l);continue}a[l]=h,r[l]=u,s.add(l)}else a[l]=u.value,r[l]=u,s.add(l);let d=o;if(!d)for(let[l,u]of this.restoredHashes){let h=a[l];if(typeof h=="string"&&h!==u){d=!0;break}}if(d){this.restoredHashes.clear();try{fe()}catch(l){c.debug("AdvancedMatching clearPersistedAm on identity conflict failed",l)}}for(let[l,u]of this.restoredHashes)s.has(l)||this.isFieldEnabled(l)&&(a[l]=u,r[l]={value:u,source:"auto"});try{let l=s.has("email")&&typeof a.email=="string"&&b(a.email)?a.email:void 0,u=s.has("phone_number")&&typeof a.phone_number=="string"&&b(a.phone_number)?a.phone_number:void 0;(l||u)&&Y({emailHash:l,phoneHash:u})}catch(l){c.debug("AdvancedMatching persistAm call failed",l)}e|=this.droppedSensitiveBitmask,t|=this.droppedValidationBitmask,i|=this.droppedHashBitmask,this.droppedSensitiveBitmask=0,this.droppedValidationBitmask=0,this.droppedHashBitmask=0;for(let l of Object.keys(a)){let u=x[l];if(u===void 0)continue;let h=~(1<<u);e&=h,t&=h,i&=h}return{data:a,sources:r,droppedSensitiveBitmask:e,droppedValidationBitmask:t,droppedHashBitmask:i}})}safeDigestMessage(e,t){return p(this,null,function*(){try{let i=t==="phone_number"?ae(e):e;return yield ie(i)}catch(i){return this.recordDrop(t,"hash"),null}})}getConfig(){return this.config}observeDynamicMounts(){if(typeof MutationObserver=="undefined"||!document.body)return;let e=new Set(["INPUT","SELECT","TEXTAREA","FORM"]),t=r=>{if(r.nodeType!==Node.ELEMENT_NODE)return!1;let s=r;return e.has(s.tagName)?!0:!!s.firstElementChild},i=()=>{if(this.mutationScanTimer=null,this.disposed){this.pendingScanRoots=[];return}let r=this.pendingScanRoots;this.pendingScanRoots=[];let s=[];for(let o of r)!o.isConnected||r.some(l=>l!==o&&l.contains(o))||s.includes(o)||s.push(o);for(let o of s)this.attachListenersWithinSubtree(o),V(o,()=>!0,(d,l,u)=>this.collectField(d,l,u))},a=r=>{this.pendingScanRoots.push(r),this.mutationScanTimer===null&&(this.mutationScanTimer=setTimeout(i,y.MUTATION_SCAN_DEBOUNCE_MS))};this.mutationObserver=new MutationObserver(r=>{if(!this.disposed)for(let s of r)s.type==="childList"&&s.addedNodes.forEach(o=>{t(o)&&a(o)})}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.pageHideHandler=()=>this.disconnectMutationObserver(),window.addEventListener("pagehide",this.pageHideHandler),this.pageShowHandler||(this.pageShowHandler=r=>{r.persisted&&this.mutationObserver===null&&this.observeDynamicMounts()},window.addEventListener("pageshow",this.pageShowHandler))}disconnectMutationObserver(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.mutationScanTimer!==null&&(clearTimeout(this.mutationScanTimer),this.mutationScanTimer=null),this.pendingScanRoots=[],this.pageHideHandler&&(window.removeEventListener("pagehide",this.pageHideHandler),this.pageHideHandler=null)}isEnabled(){return this.processingEnabled}initialize(){return p(this,null,function*(){try{c.debug("Initializing AdvancedMatching for pixel:",this.dataSourceId),this.config=yield ue(this.dataSourceId);let e=this.config.am;this.processingEnabled=!!e,c.debug("AdvancedMatching initialized",{dataSourceId:this.dataSourceId,enabled:this.processingEnabled,amConfig:e})}catch(e){c.warn("Advanced Matching initialization failed:",e),this.config={am:"0",em:{},t:Date.now()},this.processingEnabled=!1}})}cleanup(){this.disposed=!0,this.disconnectMutationObserver(),this.pageShowHandler&&(window.removeEventListener("pageshow",this.pageShowHandler),this.pageShowHandler=null),this.leaveFlushPagehide&&(window.removeEventListener("pagehide",this.leaveFlushPagehide),this.leaveFlushPagehide=null),this.leaveFlushVisibility&&(document.removeEventListener("visibilitychange",this.leaveFlushVisibility),this.leaveFlushVisibility=null);for(let e of this.pendingDebounceTimerIds)clearTimeout(e);this.pendingDebounceTimerIds.clear(),this.collectedData={},this.droppedSensitiveBitmask=0,this.droppedValidationBitmask=0,this.droppedHashBitmask=0,this.processingEnabled=!1,this.config=null,c.debug("AdvancedMatching cleanup completed for pixel:",this.dataSourceId)}};m(y,"CHECKOUT_BUTTON_DELAY",100),m(y,"INPUT_DEBOUNCE_MS",750),m(y,"MUTATION_SCAN_DEBOUNCE_MS",500);var L=y;function q(n){return p(this,null,function*(){c.debug("Initializing advanced matching",{dataSourceId:n});let e=new L(n);return yield e.initialize(),e.isEnabled()&&e.enableAutoCollection(),c.debug("Advanced Matching initialized",{dataSourceId:n}),e})}function be(n){return p(this,null,function*(){return D.getInstance(n,()=>p(null,null,function*(){return q(n)}))})}function ye(n){return D.getExistingInstance(n)}typeof window!="undefined"&&(window.NDPAdvancedMatching={AdvancedMatching:L,createAdvancedMatching:q,initAdvancedMatching:be,getAdvancedMatchingInstance:ye});})();
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/cdn.mgln.ai/pixel.min.js ADDED
@@ -0,0 +1 @@
 
 
1
+ (()=>{var l=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports);var p=l((f,h)=>{var u=class{constructor(t){this.schema=t}sanitize(t){return this.#n(t,this.schema)}#n(t,e){if(Array.isArray(e))return this.#r(t,e);if(e===String)return t?.toString();if(e===Number)return Number(t);if(e===Boolean)return!["0","false"].includes(t.toString());if(typeof e=="object")return this.#i(t,e);throw new Error(`Don't know how to sanitize ${typeof e} specified in schema`)}#i(t,e){return Object.keys(e).filter(n=>e.hasOwnProperty(n)&&t.hasOwnProperty(n)).reduce((n,i)=>(n[i]=this.#n(t[i],e[i]),n),{})}#r(t,e){if(e.length!==1)throw new Error("Schema arrays must contain exactly one type of field");return t.map(n=>this.#n(n,e[0]))}};h.exports=u});var S=l((C,g)=>{var a=p(),d=class r{static PIXEL_HOST="https://mgln.ai";static RESTRICTED_PIXEL_HOST="https://r.mgln.ai";static#n={value:Number,currency:String};static#i={productId:String,productName:String,productType:String,productVendor:String,variantId:String,variantName:String};static#r={url:String,userId:String};static#u={...r.#n,id:String,productId:String,quantity:Number,type:String,category:String};static#s={...r.#n,...r.#i};static#o={...r.#s,quantity:Number};static#a={...r.#n,quantity:Number,discountCode:String,id:String,lineItems:[r.#o]};static#d={...r.#a,isNewCustomer:Boolean};conf(t,e=!0,n=!1){if(this.token&&this.token.length){console.log("MAI SDK already configured; skipping reconfiguration.");return}this.token=t,this.restricted=n,this.onboardingSync=this.restricted?!1:e,this.host=n?r.RESTRICTED_PIXEL_HOST:r.PIXEL_HOST,this.debug=!1,this.gppConsentAuditData={},this.ready=new Promise((i,s)=>{let o=new XMLHttpRequest;o.open("GET",`${this.host}/init`,!0),o.withCredentials=!0,o.onload=i,o.onerror=s,o.send()}),this.gppConsent=this.#l(),this.onboardingSync&&Promise.all([this.ready,this.gppConsent]).then(()=>{let i=new Image;i.src=`${this.host}/pixel/sync.gif`})}identify(t){return this.#e("identify",{userId:t.toString()})}view(t={}){let e={...t,url:window.location.href},n=new a(r.#r);return this.#e("view",n.sanitize(e))}lead(t,e,n={}){let i={...n,value:t,currency:e},s=new a(r.#u);return this.#e("lead",s.sanitize(i))}product(t,e,n={}){let i={...n,value:t,currency:e},s=new a(r.#s);return this.#e("product",s.sanitize(i))}addToCart(t,e,n,i={}){let s={...i,value:t,currency:e,quantity:n},o=new a(r.#o);return this.#e("add_to_cart",o.sanitize(s))}checkout(t,e,n={}){let i={...n,value:t,currency:e},s=new a(r.#a);return this.#e("checkout",s.sanitize(i))}code(t,e){return this.#e("code",{code:t.toString(),type:e.toString()})}purchase(t,e,n,i={}){let s={...i,value:t,currency:e,id:n},o=new a(r.#d);return this.#e("purchase",o.sanitize(s))}emit(t,...e){if(["conf","view","identify","lead","product","addToCart","checkout","code","purchase"].includes(t))return this[t](...e)}#t(...t){this.debug&&console.log("[MAI GPP] ",...t)}async#l(){if(typeof window?.__gpp!="function")return this.#t("No CMP detected \u2014 allowing events"),!0;try{let t=await this.#h();return this.#t("Ping response:",t),t.signalStatus==="ready"?(this.#t("Signal ready \u2014 evaluating consent"),this.#c(t.parsedSections)):(this.#t("Signal not ready \u2014 waiting up to 1000ms"),this.#p())}catch{return this.#t("Ping failed \u2014 allowing events (service provider mode)"),!0}}#h(){return new Promise((t,e)=>{window.__gpp("ping",(n,i)=>{i?t(n):e()})})}#p(){let t=new Promise(n=>{setTimeout(()=>{this.#t("Signal timeout \u2014 allowing events (service provider mode)"),n(!0)},1e3)}),e=new Promise(n=>{window.__gpp("addEventListener",(i,s)=>{if(!s)return this.#t("addEventListener failed \u2014 firing events anyway"),n(!0);i.eventName==="signalStatus"&&i.data==="ready"&&(this.#t("Signal became ready \u2014 evaluating consent"),n(this.#c(i.pingData.parsedSections)))})});return Promise.race([t,e])}#c(t){let{allowed:e,reportSection:n}=this.#g(t);return this.#t("Consent decision:",e?"allow":"suppress"),n&&(this.gppConsentAuditData=this.#S(n.key,n.core,e)),e}#g(t){let e=!0,n=null,i=null;for(let s of["usnat","usca"]){let o=t[s],c=Array.isArray(o)?o[0]:o;c&&(this.#t(`Evaluating ${s} (format: ${Array.isArray(o)?"array":"flat"}):`,c),n||(n={key:s,core:c}),this.#w(s,c)||(i||(i={key:s,core:c}),e=!1))}return{allowed:e,reportSection:i||n}}#S(t,e,n){return{gpp_consent:{section:t,mspa_service_provider_mode:String(e.MspaServiceProviderMode),known_child_sensitive_data_consents:e.KnownChildSensitiveDataConsents.map(String),denied:String(!n),personal_data_consents:String(e.PersonalDataConsents)}}}#w(t,{MspaServiceProviderMode:e,KnownChildSensitiveDataConsents:n,PersonalDataConsents:i}){return e===1?(this.#t(`${t}: MspaServiceProviderMode=1 \u2014 skipping consent checks`),!0):n.includes(1)?(this.#t(`${t}: KnownChildSensitiveDataConsents contains a 1 \u2014 suppressing events`),!1):i===1?(this.#t(`${t}: PersonalDataConsents=1 \u2014 suppressing events`),!1):(this.#t(`${t}: no restrictions \u2014 allowing`),!0)}#e(t,e){if(!this.token||!this.token.length)throw new Error("MAI SDK has not been configured. Call conf() first.");return Promise.all([this.ready,this.gppConsent]).then(()=>{let n={...e,token:this.token,referrer:window.document.referrer,...this.gppConsentAuditData};this.debug&&console.log("Sending sanitized payload:",n);let i=new XMLHttpRequest;i.open("POST",`${this.host}/${t}`,!0),i.setRequestHeader("Content-Type","application/json"),i.withCredentials=!0,i.onload=this.#y,i.onerror=this.#f,i.send(JSON.stringify(n))})}#y(){this.debug&&console.log("OK")}#f(t){this.debug&&console.log("XHR error:",t)}};g.exports=d});var w=S();if(window.MAI===void 0){let r=document.currentScript,t=r.dataset,e=new URL(r.src).searchParams,n=t.hasOwnProperty("token")?t.token:e.get("token"),i=t.hasOwnProperty("onboardingSync")?t.onboardingSync!=="false":e.get("onboarding_sync")!=="false",s=t.hasOwnProperty("restricted")?t.restricted==="true":e.get("restricted")==="true";window.MAI=new w,window.MAI.conf(n,i,s)}else if(Array.isArray(window.MAI.q)){let r=window.MAI.q;window.MAI=new w,r.sort((t,e)=>(t[0]==="conf"?0:1)-(e[0]==="conf"?0:1)).forEach(t=>window.MAI.emit(...t))}})();
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ce.lijit.com/merge.q689bace5c5 ADDED
Binary file (43 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/container.pepperjam.com/4193671694.js ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ !function(){function o(t){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},o(t)}"object"===o(window.Pepperjam)&&null!==window.Pepperjam||(window.Pepperjam={})}();
2
+
3
+ !function(){"use strict";function t(e){if(this.constructor===t)throw new Error("Cannot instantiate abstract class");this._data=null,this.window=e}function e(e,i,a){t.call(this,e),this._cookieName=i,this._cookieMaxAge=a;var r=this;return this.getCookieName=function(){return this._cookieName},this.getCookieMaxAge=function(){return this._cookieMaxAge},this.saveData=function(t){this._data=t;for(var e=this.processHost(),i=0;i<e.length;i++){try{var a=r._cookieName+"="+t+";";a+="domain="+e[i]+";",a+="path=/;max-age="+r._cookieMaxAge,this.window.document.cookie=a}catch(t){continue}if(this.getData())return}},this.removeCookie=function(t,e){var i=r._cookieName+"=;path=";i+=e||"/",i+=";",t&&""!==t&&(i+="domain="+t+";"),i+="expires=Thu, 01 Jan 1970 00:00:00 UTC;",this.window.document.cookie=i},this.processHost=function(){for(var t=this.window.document.location.hostname.split("."),e=0;e<t.length;e++)t[e]=t[e].replace(/:\d+/,"");for(var i=[],a=t.length-2;a>=0;a--){var r=t.slice(a);r.length>1&&i.push(r.join("."))}return i},this.getData=function(){var t=null;return this.window.document.cookie.split(";").forEach((function(e){var i=(e=e.trim()).split("="),a=i[0],o=i[1];a===r._cookieName&&(t=o)})),t},this}function i(e,i){return t.call(this,e),this._storageKey=i,this.getStorageKey=function(){return this._storageKey},this.saveData=function(t){this._data=t,e.localStorage.setItem(this._storageKey,t)},this.getData=function(){return e.localStorage.getItem(this._storageKey)},this}function a(t,e,i){var a=t,r=e||"pjIframeParsed",o=i||[];function s(t){var e=a.document.createElement("a");return e.href=t,e}return this.getTrackingIframeUrls=function(){return function(){for(var t=[],e=a.document.querySelectorAll("iframe"),i=0;i<e.length;i++){var n=e[i],c=s(n.src),h=new RegExp(r),l=new RegExp("pjn-tracking");o.indexOf(c.hostname)>=0&&!n.className.match(h)&&!n.id.match(l)&&(t.push(c),""===n.className?n.className=r:n.className+=" "+r)}return t}()},this}function r(t){var e=t;return this.validateMessageOrigin=function(t,i){var a,r,o=(a=t.origin,(r=e.document.createElement("a")).href=a,r);return i.indexOf(o.hostname)>=0},this}t.prototype.getData=function(){return this._data},t.prototype.setData=function(t){this._data=t},e.prototype=Object.create(t.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,enumerable:!1,writable:!0}),i.prototype=Object.create(t.prototype),Object.defineProperty(i.prototype,"constructor",{value:i,enumerable:!1,writable:!0}),window.PepperjamTracking=function(t,o){var s=this;return this.window=t,this.clickIdQueryParamIframe="CLICK_ID",this.clickIdQueryParam=["clickId"],this.obfuscatedClickIdQueryParams=[],this.gclidQueryParam="gclid",this.cookieName="pjn-click",this.cookieMaxAge=5184e3,this.localStorageKey="pjnClickData",this.domains=["t.pepperjamnetwork.com"],this.messageNoCookies="pjn-no-cookies",this.messageCookiesOk="pjn-cookies-ok",this.pjPrefix="p",this.gclidPrefix="g",this.iframeAdded=!1,this.maxClicks=20,this.lookBackPeriod=60,this.platformKey="PLATFORM",this.platform="ITC2",this.parsedIframeClass="pjIframeParsed",this.invalidClickIdRegex=/[;%&#+=?,]/,this.invalidGclidRegex=/[;%&#+=?,]|{gclid}/i,this.cookieStorage=new e(this.window,this.cookieName,this.cookieMaxAge),this.localStorage=new i(this.window,this.localStorageKey),this.messageValidator=new r(this.window),this.getClickIdQueryParamUsed=function(t,e){var i=e.split("&");try{for(var a=0;a<t.length;a++)for(var r=0;r<i.length;r++){var o=i[r].split("=");if(t[a]===decodeURIComponent(o[0]))return decodeURIComponent(o[0])}}catch(t){return!1}return!1},this.getQueryParam=function(t,e){var i=e.split("&");try{if(Array.isArray(t))for(var a=0;a<t.length;a++)for(var r=0;r<i.length;r++){var o=i[r].split("=");if(t[a]===decodeURIComponent(o[0]))return decodeURIComponent(o[1])}else for(a=0;a<i.length;a++)if(o=i[a].split("="),decodeURIComponent(o[0])===t)return decodeURIComponent(o[1])}catch(t){return!1}return!1},this.getCookieData=function(){return this.cookieStorage.getData()},this.saveCookieData=function(t){this.cookieStorage.saveData(t)},this.processHost=function(){return this.cookieStorage.processHost()},this.removeCookie=function(t){return this.cookieStorage.removeCookie(t)},this.getLocalStorageData=function(){return this.localStorage.getData()},this.saveLocalStorageData=function(t){this.localStorage.saveData(t)},this.deleteDomainOrSubDomainCookie=function(){var t=this.processHost();try{this.removeCookie("")}catch(t){}for(var e=0;e<t.length;e++)try{this.removeCookie(t[e])}catch(t){}},this.getClickId=function(){return this.getQueryParam(this.obfuscatedClickIdQueryParams.concat(this.clickIdQueryParam),this.window.location.search.substring(1))},this.getGclid=function(){var t=this.getQueryParam(this.gclidQueryParam,this.window.location.search.substring(1));return!1!==t?t:""},this.transformClickId=function(t,e){return(e||this.pjPrefix)+t},this.getToday=function(){var t=Date.now();return Math.ceil(t/864e5)},this.getClickData=function(){var t=[],e=this.getCookieData(),i=this;if(e&&null!==e){var a=JSON.parse(e),r=this.getToday();a.forEach((function(e){i.clickWithinLookback(e,r)&&t.push(e)}))}return t},this.getPjClickData=function(){var t=this.getClickData(),e=[];return t.forEach((function(t){t.hasOwnProperty("type")&&t.type===s.pjPrefix&&e.push(t)})),e},this.clickDataToQueryParam=function(t){var e="",i=0;if("string"==typeof t&&"dynamic"===t.toLowerCase())var a=this.getClickData();else{var r=this.getClickData(),o=[];a=[],r.forEach((function(t){t.hasOwnProperty("type")&&t.type===s.gclidPrefix?a.push(t):o.push(t)})),a.push(o.pop())}return a.forEach((function(t){t&&(e+=0!==i&&t.id?","+encodeURIComponent(s.transformClickId(t.id,t.type)):encodeURIComponent(s.transformClickId(t.id,t.type)),i++)})),e||""},this.daySort=function(t,e){return(t.hasOwnProperty("days")&&t.days?t.days:0)-(e.hasOwnProperty("days")&&e.days?e.days:0)},this.mergeClickData=function(){var t=JSON.parse(this.getCookieData()),e=JSON.parse(this.getLocalStorageData()),i=this,a=[],r=[];return t&&(a=a.concat(t)),e&&(a=a.concat(e)),a.length>0&&(a=a.sort((function(t,e){return i.daySort(t,e)}))).forEach((function(t){var e=t.id,i=t.type;0===r.filter((function(t){return t.id===e&&t.type===i})).length&&r.push(t)})),this.trimCookie(r,!1)},this.handleClickId=function(t,e){var i=t,a="g"===e?this.invalidGclidRegex:this.invalidClickIdRegex;if(i&&!i.match(a)){for(var r=this.getToday(),o=this.getClickData(),s=!1,n=o,c=0;c<n.length;c++)if(i===n[c].id&&e===n[c].type){s=!0;break}s||(o.push({id:i,days:r,type:e}),o.length>this.maxClicks&&(o=this.trimCookie(o,!0)),this.deleteDomainOrSubDomainCookie(),this.saveCookieData(JSON.stringify(o)))}},this.trimCookie=function(t,e){return t.length>this.maxClicks&&(t=e?(t=t.reverse().splice(0,this.maxClicks)).reverse():t.splice(0,this.maxClicks)),t},this.clickWithinLookback=function(t,e){return Math.abs(e-t.days)<=this.lookBackPeriod},this.handleConversion=function(t){if((t.data===s.messageNoCookies||t.data===s.messageCookiesOk)&&s.messageValidator.validateMessageOrigin(t,s.domains)){var e=s.iframeParser.getTrackingIframeUrls();e.length&&!s.iframeAdded&&(e.forEach((function(t,e){var i=s.window.document.createElement("iframe"),a=t.href,r=a.split("?")[0],o=t.search.substring(1),n=s.clickDataToQueryParam(s.getQueryParam("INT",o)),c=[s.clickIdQueryParamIframe].concat(s.obfuscatedClickIdQueryParams),h=s.getClickIdQueryParamUsed(c,o),l=new RegExp("&"+h+"(=[^&]*)?|^"+h+"(=[^&]*)?&?","i"),u=s.getQueryParam(c,o);if(u){var d=u.split(","),f=n?n.split(","):[],m=[],g=d.length,k=f.length,p=s.getPjClickData();if(s.getQueryParam("INT",o)&&"dynamic"===s.getQueryParam("INT",o).toLowerCase()||0===p.length)for(var y=0;y<g;y++)m.push(s.transformClickId(d[y],s.pjPrefix));for(var C=0;C<k;C++)m.indexOf(f[C])<0&&m.push(f[C]);n="";for(var v=0;v<m.length;v++)n+=m[v]+",";n=n.substring(0,n.length-1),a=r+"?"+o.replace(l,"")}if(i.setAttribute("id","pjn-tracking-"+e),i.setAttribute("width","0"),i.setAttribute("height","0"),i.setAttribute("frameborder","0"),i.setAttribute("class",s.parsedIframeClass),t.href.match("/track/v2"))w=a;else var w=a.replace("/track","/track/v2");var I=w+"&"+(s.obfuscatedClickIdQueryParams.length>0&&""!==s.obfuscatedClickIdQueryParams[0]?s.obfuscatedClickIdQueryParams[0]:s.clickIdQueryParamIframe)+"="+n;I+="&"+s.platformKey+"="+s.platform,i.setAttribute("src",I),s.window.document.body.appendChild(i)})),s.iframeAdded=!0)}},this.handle=function(){var t=o.obfuscatedClickIdQueryParams.filter((function(t){return""!==t}));this.obfuscatedClickIdQueryParams=t,this.maxClicks=parseInt(o.maxClicks),this.domains=o.domains,this.iframeParser=new a(this.window,this.parsedIframeClass,this.domains),this.handleClickId(this.getClickId(),this.pjPrefix),this.handleClickId(this.getGclid(),this.gclidPrefix),this.window.addEventListener("message",this.handleConversion);var e=this.mergeClickData();e&&e.length>0&&(this.deleteDomainOrSubDomainCookie(),this.saveCookieData(JSON.stringify(e)),this.saveLocalStorageData(JSON.stringify(e)))},this.setIframeParser=function(t,e,i){this.iframeParser=new a(t,e,i)},this.handle()},new window.PepperjamTracking(window,{obfuscatedClickIdQueryParams:[""],domains:["t.pepperjamnetwork.com"],maxClicks:"20"})}();
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/d2hrivdxn8ekm8.cloudfront.net/tracker-latest.min.js ADDED
@@ -0,0 +1 @@
 
 
1
+ !function(){var e=this&&this.__assign||function(){return e=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++){t=arguments[r];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},e.apply(this,arguments)};try{!function(){var t,r="1.2.18",o=navigator.userAgent,i="https://tte-prod.telemetry.vaultdcr.com/5a28e627",n={Persist:"PERSIST",None:"NONE"};!function(e){e.Tie="_tie",e.Identify="identify",e.Pageview="pageview",e.SessionTie="_s_tie",e.AddToCart="e_add_to_cart",e.Purchase="e_purchase",e.CheckoutStarted="e_checkout_started",e.SearchSubmitted="e_search_submitted",e.SignUp="e_sign_up",e.Lead="e_lead",e.ProductViewed="e_product_viewed"}(t||(t={}));var s={pageview:!0,"page view":!0,"page-view":!0,page_view:!0},a=["address","ssn","phone","phone number","city","state","dob","first name","last name"],c=["@","%"],u="(999)999-9999|999-999-9999",d=RegExp("^("+u.replace(/([\(\)])/g,"\\$1").replace(/9/g,"\\d")+")$"),h={os:function(){return/Windows/i.test(o)?/Phone/.test(o)||/WPDesktop/.test(o)?"Windows Phone":"Windows":/(iPhone|iPad|iPod)/.test(o)?"iOS":/Android/.test(o)?"Android":/(BlackBerry|PlayBook|BB10)/i.test(o)?"BlackBerry":/Mac/i.test(o)?"Mac OS X":/Linux/.test(o)?"Linux":""},btoa:function(e){for(var t=String(e),r="",o=0,i=void 0,n=void 0,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.charAt(0|o)||o%1;r+=s.charAt(63&i>>8-o%1*8)){if(t.charAt(0|o)||(s="="),(n=t.charCodeAt(o+=.75))>255)return;i=i<<8|n}return r},isValidGuid:function(e){var t=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return e&&t.test(e.trim())},warnIfInvalidToken:function(e){var t=h.isValidGuid(e);return t||console.error("Token is not a valid GUID"),t},isValidUserId:function(e){if(!e)return!1;var t=function(e){return e.toString().toLowerCase().trim()},r=["undefined","null","n/a","","none",{},0,1,NaN,!0,!1,"0","1","missing-id"].map(t),o=t(e);return!(r.indexOf(o)>-1)}},m=function(){function o(e,t){this.sessionCookieTime=307584e6,this.userCookieTime=307584e6,this.sessionCookieName="tatari-session-cookie",this.sessionUrlParamName="tatari_session_id",this.sessionId="",this.userCookieName="tatari-user-cookie",this.userId="",this.version=r,this.util=h,this.debugCookieName="tatari-debug-cookie",this.debugCookieTime=864e5,this.debug=!1,this._i=e,this.url=i,this.cookieSupport=this.getCookieSupport(),this.config=t,this.checkDebugCookie(),this.checkSessionCookie(),this.checkUserCookie(),h.warnIfInvalidToken(e),this.debug&&(console.info("Debug: Tatari Tracker Lib Loaded",this),console.info("Debug: Tatari Tracker TLD",this.getDomain()))}return o.prototype.enableDebug=function(){this.createCookie(this.debugCookieName,"1",this.debugCookieTime),this.debug=!0,console.info("Debug: Tatari Tracker Debug Enabled")},o.prototype.init=function(e,t){this._i=e,this.config=t,h.warnIfInvalidToken(e)},o.prototype.flushCommandQueue=function(e){if(void 0===e&&(e=[]),e.length>0){var t=this;e.forEach(function(e){t[e[0]].apply(t,e.slice(1,e.length))})}},o.prototype.scrubParams=function(e){var t,r=this;if((null===(t=this.config)||void 0===t?void 0:t.queryParamScrubs)&&e){var o=document.createElement("a");o.setAttribute("href",e);var i=o.search;if(i){var n=[];i.replace(/^\?/,"").split("&").forEach(function(e){var t=decodeURIComponent(e.split("=")[0]);r.config.queryParamScrubs.some(function(e){return e===t})||n.push(e)});var s="?"+n.join("&");return e.replace(i,s)}}return e},o.prototype.scrubUrl=function(e){var t;if((null===(t=this.config)||void 0===t?void 0:t.urlScrubs)&&e){var r=e;return this.config.urlScrubs.forEach(function(t){var o=t.test(e)&&RegExp.$1;o&&(r=e.replace(o,"TATARI-SCRUBBED"))}),r}return e},o.prototype.scrub=function(e){return this.config?this.scrubUrl(this.scrubParams(e)):e},o.prototype.getProperties=function(){return{$os:h.os(),$referrer:this.scrub(document.referrer),$currentUrl:this.scrub(window.location.href)}},o.prototype.removePII=function(e,t){var r="";if(a.includes(e.toString().toLowerCase().trim()))return[e,""];if(d.test(t.toString()))return[e,""];for(r in c)if(t.toString().includes(c[r]))return[e,""];return[e,t]},o.prototype.removePIIFromArray=function(e){var t=this;return e.map(function(e){if("object"!=typeof e||null===e||Array.isArray(e)){if(Array.isArray(e))return t.removePIIFromArray(e);if("string"==typeof e){var r=t.removePII("arrayElement",e);return r[1]}return e}for(var o={},i=0,n=Object.entries(e);i<n.length;i++){var s=n[i],a=s[0],c=s[1];if(Array.isArray(c))o[a]=t.removePIIFromArray(c);else if("object"==typeof c&&null!==c){for(var u={},d=0,h=Object.entries(c);d<h.length;d++){var m=h[d],p=m[0],f=m[1],r=t.removePII(p,f.toString());u[r[0]]=r[1]}o[a]=u}else if("string"==typeof c){var r=t.removePII(a,c);o[r[0]]=r[1]}else o[a]=c}return o})},o.prototype._track=function(r,o){void 0===o&&(o="");try{r!==t.Tie&&r!==t.SessionTie&&this.checkSessionCookie();var i=o,n=[],s={};if("object"==typeof o)try{for(var a=0,c=Object.entries(o);a<c.length;a++){var u=c[a],d=u[0],h=u[1];Array.isArray(h)?s[d]=this.removePIIFromArray(h):(n=this.removePII(d,h.toString()),s[n[0]]=n[1])}i=JSON.stringify(s)}catch(e){i="",console.warn("Tatari Tracker arg should be a valid JSON object")}i.length>65535&&(console.warn("Tatari Tracker arg should be smaller than 65535 characters, was "+i.length+"."),"object"==typeof o&&console.warn("Tatari Tracker arg size was the result of large JSON serialization."));var m=e({version:this.version,token:this._i,sessionId:this.sessionId,cookieSupport:this.cookieSupport,userId:this.userId,arg:i,event:r},this.getProperties());this.removeEmptyKeys(m);var p=this.buildReqUrl(m);this.debug&&console.info("Debug: Tatari Tracker Event Fired",m),this.sendRequest(p)}catch(e){console.warn("Tatari's tracking library encountered an error when attempting to track.",e)}},o.prototype.sendRequest=function(e){if(this._i){var t=new XMLHttpRequest;t.open("GET",e,!0),t.send(null)}else this.debug&&console.info("Debug: Tatari Tracker suppressing request with invalid token")},o.prototype.removeEmptyKeys=function(e){Object.keys(e).forEach(function(t){return(void 0===e[t]||null===e[t]||""===e[t])&&delete e[t]})},o.prototype.buildReqUrl=function(e,t){void 0===t&&(t=this.url);var r=this.buildDataBlob(e);return t+"?data="+encodeURIComponent(r)+"&date="+ +new Date},o.prototype.buildDataBlob=function(e){var t=Object.keys(e).map(function(t){var r=encodeURIComponent;return"object"==typeof e[t]&&(r=function(e){return encodeURIComponent(JSON.stringify(e))}),encodeURIComponent(t)+"="+r(e[t])}).join("&");return""+this.util.btoa(t)},o.prototype.pageview=function(){this._track(t.Pageview),window.ttm&&window.ttm.onPageview&&window.ttm.onPageview()},o.prototype.track=function(e,t){return e?"string"==typeof e&&s[e.toLowerCase()]?void console.warn("Supressing event "+e):(this._track("e_"+e.toString(),t),void(window.ttm&&window.ttm.onTrack&&window.ttm.onTrack(e.toString(),t))):void console.error("Undefined event passed to track.")},o.prototype.identify=function(e){var r=this.userId;if(!h.isValidUserId(e))return void console.error("Invalid id passed to identify.");r&&e.toString()===r||(this.userId=e.toString(),this.createCookie(this.userCookieName,this.userId,this.userCookieTime),this._track(t.Tie)),this._track(t.Identify),window.ttm&&window.ttm.onIdentify&&window.ttm.onIdentify(e.toString())},o.prototype.addToCart=function(e){return e?"string"!=typeof e.productId?void console.error("AddToCart: productId must be a string."):"number"!=typeof e.quantity||e.quantity<=0?void console.error("AddToCart: quantity must be a number greater than 0."):"number"!=typeof e.price||e.price<0?void console.error("AddToCart: price must be a number >= 0."):e.name&&"string"!=typeof e.name?void console.error("AddToCart: name must be a string."):e.category&&"string"!=typeof e.category?void console.error("AddToCart: category must be a string."):void this._track(t.AddToCart,e):void console.error("AddToCart: params object is required.")},o.prototype.searchSubmitted=function(e){return e?e.searchTerm&&"string"==typeof e.searchTerm&&""!==e.searchTerm.trim()?void this._track(t.SearchSubmitted,e):void console.error("SearchSubmitted: searchTerm is required and must be a non-empty string."):void console.error("SearchSubmitted: params object is required.")},o.prototype.signUp=function(){this._track(t.SignUp)},o.prototype.leadSubmitted=function(){this._track(t.Lead)},o.prototype.productViewed=function(e){return e?e.name&&"string"==typeof e.name?"number"!=typeof e.price||e.price<0?void console.error("ProductViewed: price must be a number >= 0."):"number"!=typeof e.quantity||e.quantity<=0?void console.error("ProductViewed: quantity must be a number greater than 0."):e.category&&"string"!=typeof e.category?void console.error("ProductViewed: category must be a string."):e.productId&&"string"!=typeof e.productId?void console.error("ProductViewed: productId must be a string."):void this._track(t.ProductViewed,e):void console.error("ProductViewed: name is required and must be a string."):void console.error("ProductViewed: product object is required.")},o.prototype.checkoutStarted=function(r){if(!r)return void console.error("CheckoutStarted: params object is required.");if("number"!=typeof r.total||r.total<=0)return void console.error("CheckoutStarted: total must be a positive number.");if(!r.items||!Array.isArray(r.items))return void console.error("CheckoutStarted: items array is required.");if(0===r.items.length)return void console.error("CheckoutStarted: items array cannot be empty.");for(var o=0;o<r.items.length;o++){var i=r.items[o];if(!i.name||"string"!=typeof i.name)return void console.error("CheckoutStarted: item "+o+" must have a valid name.");if("number"!=typeof i.price||i.price<0)return void console.error("CheckoutStarted: item "+o+" must have a valid price.");if("number"!=typeof i.quantity||i.quantity<=0)return void console.error("CheckoutStarted: item "+o+" must have a valid quantity.")}if(r.currency&&"string"!=typeof r.currency)return void console.error("CheckoutStarted: currency must be a string.");var n=e(e({},r),r.currency&&{currency:r.currency.toUpperCase()});this._track(t.CheckoutStarted,n)},o.prototype.purchase=function(r){if(!r)return void console.error("Purchase: params object is required.");if("number"!=typeof r.total||r.total<=0)return void console.error("Purchase: total must be a positive number.");if(!r.currency||"string"!=typeof r.currency)return void console.error("Purchase: currency is required and must be a string.");if(!/^[A-Z]{3}$/.test(r.currency.toUpperCase()))return void console.error("Purchase: currency must be a 3-letter currency code (e.g., USD, EUR).");if(!r.orderId||"string"!=typeof r.orderId||""===r.orderId.trim())return void console.error("Purchase: orderId is required and must be a non-empty string.");if(!r.items||!Array.isArray(r.items))return void console.error("Purchase: items array is required.");if(0===r.items.length)return void console.error("Purchase: items array cannot be empty.");for(var o=0;o<r.items.length;o++){var i=r.items[o];if(!i.name||"string"!=typeof i.name)return void console.error("Purchase: item "+o+" must have a valid name.");if("number"!=typeof i.price||i.price<0)return void console.error("Purchase: item "+o+" must have a valid price.");if("number"!=typeof i.quantity||i.quantity<=0)return void console.error("Purchase: item "+o+" must have a valid quantity.")}var n=e(e({},r),{currency:r.currency.toUpperCase()});this._track(t.Purchase,n)},o.prototype.guid=function(){var e=function(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)};return""+e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()},o.prototype.createCookie=function(e,t,r){var o="",i=new Date,n="domain="+this.getDomain()+";";return i.setTime(i.getTime()+r),o="expires="+i.toUTCString()+";",document.cookie=e+"="+t+"; "+o+" "+n+" path=/",t},o.prototype.getDomain=function(){var e=document.location||{hostname:""},t=e.hostname.split("."),r="";return t.some(function(e,o){var i=t.slice(t.length-o-1).join(".");if(document.cookie="testTLD=test;domain="+i+";",-1!==document.cookie.indexOf("testTLD=test"))return r=i,document.cookie="testTLD=;domain="+r+";expires="+new Date(0).toUTCString()+";",!0}),r},o.prototype.getCookie=function(e){for(var t=e+"=",r=decodeURIComponent(document.cookie),o=r.split(";"),i=0,n=o;i<n.length;i++){for(var s=n[i];" "===s.charAt(0);)s=s.substring(1);if(0===s.indexOf(t))return s.substring(t.length,s.length)}},o.prototype.removeCookie=function(e){var t=this.getDomain();document.cookie=e+"=; Max-Age=-99999999;",t&&(document.cookie=e+"=; Max-Age=-99999999; domain="+t+";")},o.prototype.checkUserCookie=function(){var e=this.getCookie(this.userCookieName);e&&!h.isValidUserId(e)?this.removeCookie(this.userCookieName):(this.userId=e,this.userId&&(this.removeCookie(this.userCookieName),this.createCookie(this.userCookieName,this.userId,this.userCookieTime)))},o.prototype.checkSessionCookie=function(){var e=this;this.sessionId=this.getCookie(this.sessionCookieName);var r,o=window.location.search?window.location.search.replace(/^\?/,"").split("&").map(function(e){return e.split("=").map(decodeURIComponent)}):[];o.forEach(function(t){t&&2===t.length&&t[0]===e.sessionUrlParamName&&(r=t)});var i=r&&r[1];this.sessionId&&!h.isValidGuid(this.sessionId)&&(console.warn("Invalid stored session ID ("+this.sessionId+"). Ignoring."),this.removeCookie(this.sessionCookieName),this.sessionId=null),i&&!h.isValidGuid(i)&&(console.warn("Invalid parameter session ID ("+i+"). Ignoring."),i=null),i&&this.sessionId!==i&&(this.sessionId&&this._track(t.SessionTie,i),this.createCookie(this.sessionCookieName,i,this.sessionCookieTime),this.sessionId=i),this.sessionId?(this.removeCookie(this.sessionCookieName),this.createCookie(this.sessionCookieName,this.sessionId,this.sessionCookieTime)):this.sessionId=this.createCookie(this.sessionCookieName,this.guid(),this.sessionCookieTime)},o.prototype.checkDebugCookie=function(){var e=this.getCookie(this.debugCookieName);this.debug=!!e},o.prototype.getCookieSupport=function(){var e="tatari-cookie-test="+Math.floor(1e8*Math.random()),t=new Date;return t.setTime(t.getTime()+this.sessionCookieTime),document.cookie=e+"; expires="+t.toUTCString()+"; path=/",-1!==document.cookie.indexOf(e)?n.Persist:n.None},o}(),p=window.tatari||[],f=new m(p._i,p.config);window.tatari=f,f.flushCommandQueue(p)}()}catch(e){console.log(e)}}();
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q1d0a579494 ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q31e33274de ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q39d62ad71e ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q3ebd6b9491 ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q406aaf3c58 ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q51ef9d3e1e ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q5f64c5b90c ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q6fbfd7956c ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q93290827dc ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q942355de3f ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.q9b23dd9b5e ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qa47cb055e1 ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qacc43b957d ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qb0b586dc36 ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qb34c55c17d ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qb6c1d17059 ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qcf75156b0d ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qe0a2cabe33 ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qe0e6e86a5e ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/ib.adnxs.com/pixie.qeab56a9406 ADDED
Binary file (42 Bytes). View file
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/idsync.rlcdn.com/449076.q1c22464946.gif ADDED

Git LFS Details

  • SHA256: 7108aeb17d2e689a9bf29455d048dcdad42b1dfe2803181623fb2e4d1fdf791c
  • Pointer size: 128 Bytes
  • Size of remote file: 650 Bytes
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/idsync.rlcdn.com/449076.q8e3626aa86.gif ADDED

Git LFS Details

  • SHA256: ef1955ae757c8b966c83248350331bd3a30f658ced11f387f8ebf05ab3368629
  • Pointer size: 127 Bytes
  • Size of remote file: 42 Bytes
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/load.server.aspcapetinsurance.com/2mkgflfjkuo.q74166a008d.js ADDED
The diff for this file is too large to render. See raw diff
 
tasks/aspca-pet-insurance/environment/reference/clone/static/assets/2026-08-13.aspca-pet-insurance-r1/mgln.ai/init ADDED
Binary file (43 Bytes). View file