AgPerry commited on
Commit
9f517f2
·
verified ·
1 Parent(s): edec962

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/etsy/environment/candidate-abi/websitebench/__init__.py +1 -0
  2. tasks/etsy/environment/candidate-abi/websitebench/harbor/__init__.py +1 -0
  3. tasks/etsy/environment/candidate-abi/websitebench/harbor/candidate_preflight.py +178 -0
  4. tasks/etsy/environment/candidate-abi/websitebench/harbor/compiler.py +1041 -0
  5. tasks/etsy/environment/candidate-abi/websitebench/harbor/sandbox.py +841 -0
  6. tasks/etsy/environment/reference/.websitebench-reference-tls/ca.crt +20 -0
  7. tasks/etsy/environment/reference/.websitebench-reference-tls/reference.crt +20 -0
  8. tasks/etsy/environment/reference/.websitebench-reference-tls/reference.key +28 -0
  9. tasks/etsy/environment/reference/.websitebench-reference-tls/tls_proxy.py +164 -0
  10. tasks/etsy/environment/reference/backend/runtime.json +113 -0
  11. tasks/etsy/environment/reference/clone/app.py +0 -0
  12. tasks/etsy/environment/reference/clone/backend/__init__.py +1 -0
  13. tasks/etsy/environment/reference/clone/backend/db.py +1078 -0
  14. tasks/etsy/environment/reference/clone/backend/purchases.py +623 -0
  15. tasks/etsy/environment/reference/clone/backend/site_backend_integration.py +196 -0
  16. tasks/etsy/environment/reference/clone/frontend/templates/_auth_providers.html +42 -0
  17. tasks/etsy/environment/reference/clone/frontend/templates/base.html +168 -0
  18. tasks/etsy/environment/reference/clone/frontend/templates/cart.html +66 -0
  19. tasks/etsy/environment/reference/clone/frontend/templates/category.html +37 -0
  20. tasks/etsy/environment/reference/clone/frontend/templates/checkout.html +49 -0
  21. tasks/etsy/environment/reference/clone/frontend/templates/checkout_address.html +30 -0
  22. tasks/etsy/environment/reference/clone/frontend/templates/company.html +39 -0
  23. tasks/etsy/environment/reference/clone/frontend/templates/error.html +10 -0
  24. tasks/etsy/environment/reference/clone/frontend/templates/favorites.html +46 -0
  25. tasks/etsy/environment/reference/clone/frontend/templates/home.html +161 -0
  26. tasks/etsy/environment/reference/clone/frontend/templates/inbox.html +16 -0
  27. tasks/etsy/environment/reference/clone/frontend/templates/info.html +11 -0
  28. tasks/etsy/environment/reference/clone/frontend/templates/listing.html +104 -0
  29. tasks/etsy/environment/reference/clone/frontend/templates/order.html +22 -0
  30. tasks/etsy/environment/reference/clone/frontend/templates/purchases.html +14 -0
  31. tasks/etsy/environment/reference/clone/frontend/templates/recover.html +32 -0
  32. tasks/etsy/environment/reference/clone/frontend/templates/regions.html +32 -0
  33. tasks/etsy/environment/reference/clone/frontend/templates/register.html +52 -0
  34. tasks/etsy/environment/reference/clone/frontend/templates/search.html +74 -0
  35. tasks/etsy/environment/reference/clone/frontend/templates/signin.html +51 -0
  36. tasks/etsy/environment/reference/clone/frontend/templates/verify.html +20 -0
  37. tasks/etsy/environment/reference/clone/harbor_entry.py +157 -0
  38. tasks/etsy/environment/reference/clone/static/app.js +242 -0
  39. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-app-badge-01.png +3 -0
  40. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-app-badge-02.png +3 -0
  41. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-blog-22.jpg +3 -0
  42. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-blog-23.jpg +3 -0
  43. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-blog-24.jpg +3 -0
  44. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-11.jpg +3 -0
  45. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-12.jpg +3 -0
  46. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-13.jpg +3 -0
  47. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-14.jpg +3 -0
  48. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-15.jpg +3 -0
  49. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-16.jpg +3 -0
  50. tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-deal-and-shop-17.jpg +3 -0
tasks/etsy/environment/candidate-abi/websitebench/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Public WebsiteBench candidate ABI tooling."""
tasks/etsy/environment/candidate-abi/websitebench/harbor/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Public Harbor candidate ABI tooling."""
tasks/etsy/environment/candidate-abi/websitebench/harbor/candidate_preflight.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agent-visible preflight for the public Harbor candidate runtime ABI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import socket
8
+ import sys
9
+ import tempfile
10
+ from pathlib import Path
11
+ from typing import Sequence
12
+
13
+ from .compiler import (
14
+ CompilerSandboxError,
15
+ RuntimeInfrastructureError,
16
+ compile_candidate,
17
+ validate_runtime_lifecycle,
18
+ )
19
+
20
+
21
+ FORBIDDEN_PRIVATE_ROOT = b"/app/repo"
22
+ NONPORTABLE_PYTHON_SHEBANG = b"#!/usr/bin/python3"
23
+ PORTABLE_PYTHON_SHEBANG = b"#!/usr/bin/env python3"
24
+
25
+
26
+ def _first_line(path: Path) -> bytes:
27
+ with path.open("rb") as handle:
28
+ return handle.readline(4097).rstrip(b"\r\n")
29
+
30
+
31
+ def _contains(path: Path, needle: bytes) -> bool:
32
+ overlap = max(0, len(needle) - 1)
33
+ previous = b""
34
+ with path.open("rb") as handle:
35
+ while chunk := handle.read(1024 * 1024):
36
+ value = previous + chunk
37
+ if needle in value:
38
+ return True
39
+ previous = value[-overlap:] if overlap else b""
40
+ return False
41
+
42
+
43
+ def validate_portable_candidate_paths(
44
+ compile_script: Path, executable: Path | None = None
45
+ ) -> None:
46
+ """Reject paths that work in the Agent checkout but not the private build."""
47
+
48
+ if _contains(compile_script, FORBIDDEN_PRIVATE_ROOT):
49
+ raise CompilerSandboxError(
50
+ "compile.sh hard-codes /app/repo; the verifier relocates the candidate "
51
+ "to a private build root. Use paths relative to the current directory "
52
+ "or $WEBSITEBENCH_BUILD_ROOT."
53
+ )
54
+ if _first_line(compile_script) == NONPORTABLE_PYTHON_SHEBANG:
55
+ raise CompilerSandboxError(
56
+ "compile.sh uses the non-portable #!/usr/bin/python3 shebang; use "
57
+ "#!/usr/bin/env python3."
58
+ )
59
+ if executable is None:
60
+ return
61
+ if _first_line(executable) == NONPORTABLE_PYTHON_SHEBANG:
62
+ raise CompilerSandboxError(
63
+ "executable uses the non-portable #!/usr/bin/python3 shebang; use "
64
+ "#!/usr/bin/env python3."
65
+ )
66
+ if _contains(executable, FORBIDDEN_PRIVATE_ROOT):
67
+ raise CompilerSandboxError(
68
+ "executable contains /app/repo; runtime files live in the private "
69
+ "build root. Resolve resources relative to executable, not /app/repo."
70
+ )
71
+
72
+
73
+ def _free_port() -> int:
74
+ with socket.socket() as probe:
75
+ probe.bind(("127.0.0.1", 0))
76
+ return int(probe.getsockname()[1])
77
+
78
+
79
+ def _build_log(private_root: Path) -> str:
80
+ path = private_root / "build.log"
81
+ try:
82
+ value = path.read_text(encoding="utf-8", errors="replace")
83
+ except OSError:
84
+ return ""
85
+ return value[-65536:]
86
+
87
+
88
+ def run_preflight(
89
+ candidate_root: Path,
90
+ *,
91
+ timeout: float = 300.0,
92
+ seed: int = 0,
93
+ timezone: str = "UTC",
94
+ ) -> dict[str, object]:
95
+ candidate = candidate_root.resolve(strict=True)
96
+ compile_script = candidate / "compile.sh"
97
+ if not compile_script.is_file():
98
+ raise CompilerSandboxError("candidate root does not contain compile.sh")
99
+ validate_portable_candidate_paths(compile_script)
100
+ with tempfile.TemporaryDirectory(prefix="websitebench-candidate-preflight-") as raw:
101
+ working_root = Path(raw)
102
+ private_root = working_root / "compiler"
103
+ try:
104
+ artifact = compile_candidate(
105
+ candidate,
106
+ private_root,
107
+ timeout=timeout,
108
+ seed=seed,
109
+ timezone=timezone,
110
+ )
111
+ except CompilerSandboxError as exc:
112
+ log = _build_log(private_root)
113
+ if log:
114
+ raise CompilerSandboxError(f"{exc}\ncompiler output:\n{log}") from exc
115
+ raise
116
+ validate_portable_candidate_paths(
117
+ artifact.build_root / "compile.sh", artifact.executable
118
+ )
119
+ lifecycle = validate_runtime_lifecycle(
120
+ artifact,
121
+ port=_free_port(),
122
+ seed=seed,
123
+ working_root=working_root / "runtime-preflight",
124
+ timezone=timezone,
125
+ )
126
+ if lifecycle.get("valid") is not True:
127
+ failed = sorted(
128
+ key
129
+ for key, value in lifecycle.items()
130
+ if key not in {"deployment_abi", "tree_sha256", "valid"}
131
+ and value is not True
132
+ )
133
+ raise CompilerSandboxError(
134
+ "candidate runtime ABI lifecycle failed: " + ",".join(failed)
135
+ )
136
+ return {
137
+ "schema": "websitebench.harbor.candidate-preflight",
138
+ "status": "valid",
139
+ "candidate_root": str(candidate),
140
+ "tree_sha256": artifact.tree_sha256,
141
+ "lifecycle": lifecycle,
142
+ }
143
+
144
+
145
+ def _parser() -> argparse.ArgumentParser:
146
+ parser = argparse.ArgumentParser(
147
+ description="Check a candidate with the formal private compile/runtime ABI."
148
+ )
149
+ parser.add_argument("candidate_root", nargs="?", type=Path, default=Path.cwd())
150
+ parser.add_argument("--timeout", type=float, default=300.0)
151
+ parser.add_argument("--seed", type=int, default=0)
152
+ parser.add_argument("--timezone", default="UTC")
153
+ return parser
154
+
155
+
156
+ def main(arguments: Sequence[str] | None = None) -> int:
157
+ values = _parser().parse_args(arguments)
158
+ try:
159
+ report = run_preflight(
160
+ values.candidate_root,
161
+ timeout=values.timeout,
162
+ seed=values.seed,
163
+ timezone=values.timezone,
164
+ )
165
+ except (
166
+ CompilerSandboxError,
167
+ RuntimeInfrastructureError,
168
+ OSError,
169
+ ValueError,
170
+ ) as exc:
171
+ print(f"candidate ABI preflight failed: {exc}", file=sys.stderr)
172
+ return 2
173
+ print(json.dumps(report, indent=2, sort_keys=True))
174
+ return 0
175
+
176
+
177
+ if __name__ == "__main__":
178
+ raise SystemExit(main())
tasks/etsy/environment/candidate-abi/websitebench/harbor/compiler.py ADDED
@@ -0,0 +1,1041 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Quarantined compiler and runtime for the Harbor compile-executable ABI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import errno
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import shutil
11
+ import signal
12
+ import stat
13
+ import subprocess
14
+ import time
15
+ import urllib.error
16
+ import urllib.request
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Any, Iterable, Mapping, Sequence
20
+
21
+ try: # pragma: no cover - unavailable on Windows authoring hosts
22
+ import resource
23
+ except ImportError: # pragma: no cover
24
+ resource = None # type: ignore[assignment]
25
+
26
+ from . import sandbox
27
+
28
+
29
+ DEPLOYMENT_ABI = "websitebench.harbor.compile-executable"
30
+ COMPILE_ENTRYPOINT = "compile.sh"
31
+ EXECUTABLE_ENTRYPOINT = "executable"
32
+ HEALTH_PATH = "/healthz"
33
+ # The contract moved to /healthz (ADR-0010) because every reference site and
34
+ # every manifest already served that path, while nothing ever implemented the
35
+ # benchmark-private one. Candidates built against the old instruction text keep
36
+ # working: probing falls back to these.
37
+ LEGACY_HEALTH_PATHS = ("/__websitebench/health",)
38
+ HEALTH_PATHS = (HEALTH_PATH, *LEGACY_HEALTH_PATHS)
39
+ HEALTH_BODY = {"status": "ok"}
40
+ RUNTIME_PROCESS_MODEL = {
41
+ "kind": "single-process",
42
+ "process_fork": False,
43
+ "threads": True,
44
+ "launcher": "direct-exec-or-shell-builtins-only",
45
+ }
46
+ DEFAULT_COMPILE_TIMEOUT = 900.0
47
+ MAX_LOG_BYTES = 256 * 1024 * 1024
48
+ WORKER_OS_UID = 10001
49
+ WORKER_OS_GID = 10001
50
+ _RUNTIME_PRIVATE_DIRECTORIES = (
51
+ "home",
52
+ "tmp",
53
+ "xdg-cache",
54
+ "xdg-config",
55
+ "xdg-data",
56
+ )
57
+ CANDIDATE_MAIL_ENVIRONMENT = frozenset(
58
+ {
59
+ "WEBSITEBENCH_MAIL_API_URL",
60
+ "WEBSITEBENCH_MAIL_API_TOKEN",
61
+ "WEBSITEBENCH_MAIL_FROM",
62
+ "WEBSITEBENCH_SMTP_HOST",
63
+ "WEBSITEBENCH_SMTP_PORT",
64
+ "WEBSITEBENCH_SMTP_FROM",
65
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL",
66
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN",
67
+ }
68
+ )
69
+ CANDIDATE_EVALUATOR_ENVIRONMENT = frozenset(
70
+ {
71
+ "WEBSITEBENCH_VERIFIER_MODE",
72
+ "WEBSITEBENCH_VERIFIER_ALEX_SECRET",
73
+ "WEBSITEBENCH_VERIFIER_JORDAN_SECRET",
74
+ "WEBSITEBENCH_EVALUATOR_PRIMARY_SECRET",
75
+ "WEBSITEBENCH_EVALUATOR_SECONDARY_SECRET",
76
+ }
77
+ )
78
+
79
+
80
+ class CompilerSandboxError(RuntimeError):
81
+ """The candidate artifact, compiler, or compiled runtime broke the ABI."""
82
+
83
+
84
+ class RuntimeInfrastructureError(RuntimeError):
85
+ """The trusted runtime supervisor could not establish its worker boundary."""
86
+
87
+
88
+ def _runtime_worker_credentials() -> tuple[int, int] | None:
89
+ """Return the fixed worker identity only for a privileged supervisor."""
90
+
91
+ if os.geteuid() == 0:
92
+ return WORKER_OS_UID, WORKER_OS_GID
93
+ return None
94
+
95
+
96
+ def _make_worker_ancestors_traversable(path: Path, uid: int, gid: int) -> None:
97
+ """Grant only the execute bit needed to reach one private worker path."""
98
+
99
+ for ancestor in path.parents:
100
+ metadata = ancestor.stat()
101
+ mode = stat.S_IMODE(metadata.st_mode)
102
+ if metadata.st_uid == uid:
103
+ execute_bit = stat.S_IXUSR
104
+ elif metadata.st_gid == gid:
105
+ execute_bit = stat.S_IXGRP
106
+ else:
107
+ execute_bit = stat.S_IXOTH
108
+ if not mode & execute_bit:
109
+ ancestor.chmod(mode | execute_bit)
110
+
111
+
112
+ def _prepare_runtime_directories(
113
+ build: Path,
114
+ data: Path,
115
+ credentials: tuple[int, int] | None,
116
+ ) -> None:
117
+ """Create private runtime state and make it usable by the worker identity."""
118
+
119
+ data.mkdir(parents=True, exist_ok=True, mode=0o700)
120
+ private_directories = [data]
121
+ for name in _RUNTIME_PRIVATE_DIRECTORIES:
122
+ directory = data / name
123
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
124
+ private_directories.append(directory)
125
+
126
+ for directory in private_directories:
127
+ metadata = directory.lstat()
128
+ if not stat.S_ISDIR(metadata.st_mode):
129
+ raise OSError(
130
+ errno.ENOTDIR,
131
+ f"runtime private path is not a directory: {directory}",
132
+ )
133
+
134
+ if credentials is not None:
135
+ uid, gid = credentials
136
+ for directory in private_directories:
137
+ os.chown(directory, uid, gid, follow_symlinks=False)
138
+ _make_worker_ancestors_traversable(build, uid, gid)
139
+ _make_worker_ancestors_traversable(data, uid, gid)
140
+
141
+ for directory in private_directories:
142
+ directory.chmod(0o700)
143
+
144
+
145
+ def _proc_status_identity(path: Path) -> tuple[tuple[int, ...], tuple[int, ...], int]:
146
+ """Read real/effective/saved/fs IDs and PPid from a proc status file."""
147
+
148
+ fields: dict[str, tuple[int, ...]] = {}
149
+ try:
150
+ for line in path.read_text(encoding="ascii").splitlines():
151
+ name, separator, value = line.partition(":")
152
+ if separator and name in {"Uid", "Gid", "PPid"}:
153
+ fields[name] = tuple(int(item) for item in value.split())
154
+ except (OSError, UnicodeError, ValueError) as exc:
155
+ raise OSError(errno.EIO, f"process identity is unreadable: {path}") from exc
156
+ if len(fields.get("Uid", ())) != 4 or len(fields.get("Gid", ())) != 4:
157
+ raise OSError(errno.EIO, f"process identity is incomplete: {path}")
158
+ if len(fields.get("PPid", ())) != 1:
159
+ raise OSError(errno.EIO, f"process parent identity is incomplete: {path}")
160
+ return fields["Uid"], fields["Gid"], fields["PPid"][0]
161
+
162
+
163
+ @dataclass(frozen=True)
164
+ class CompiledArtifact:
165
+ source_root: Path
166
+ build_root: Path
167
+ executable: Path
168
+ tree_sha256: str
169
+ build_log: Path
170
+
171
+
172
+ def _safe_name(name: str) -> bool:
173
+ return (
174
+ bool(name)
175
+ and name not in {".", ".."}
176
+ and "/" not in name
177
+ and "\x00" not in name
178
+ )
179
+
180
+
181
+ def _tree_entries(root: Path) -> Iterable[tuple[Path, os.stat_result]]:
182
+ """Walk with lstat only; never follow candidate-authored links."""
183
+
184
+ stack = [root]
185
+ while stack:
186
+ directory = stack.pop()
187
+ with os.scandir(directory) as iterator:
188
+ entries = sorted(iterator, key=lambda item: os.fsencode(item.name))
189
+ subdirectories: list[Path] = []
190
+ for entry in entries:
191
+ if not _safe_name(entry.name):
192
+ raise CompilerSandboxError(f"unsafe artifact name: {entry.name!r}")
193
+ path = Path(entry.path)
194
+ metadata = entry.stat(follow_symlinks=False)
195
+ yield path, metadata
196
+ if stat.S_ISDIR(metadata.st_mode):
197
+ subdirectories.append(path)
198
+ stack.extend(reversed(subdirectories))
199
+
200
+
201
+ def validate_artifact_tree(root: Path | str) -> list[Path]:
202
+ """Reject links, special files, multiple links, and paths outside ``root``."""
203
+
204
+ resolved = Path(root).resolve(strict=True)
205
+ root_stat = resolved.lstat()
206
+ if not stat.S_ISDIR(root_stat.st_mode):
207
+ raise CompilerSandboxError("candidate artifact root must be a directory")
208
+ files: list[Path] = []
209
+ for path, metadata in _tree_entries(resolved):
210
+ try:
211
+ relative = path.relative_to(resolved)
212
+ except ValueError as exc: # defensive: scandir paths must remain below root
213
+ raise CompilerSandboxError(f"artifact path escapes root: {path}") from exc
214
+ if not relative.parts or any(
215
+ part in {"", ".", ".."} for part in relative.parts
216
+ ):
217
+ raise CompilerSandboxError(f"unsafe artifact path: {relative}")
218
+ if stat.S_ISLNK(metadata.st_mode):
219
+ raise CompilerSandboxError(f"symbolic links are forbidden: {relative}")
220
+ if stat.S_ISREG(metadata.st_mode):
221
+ if metadata.st_nlink != 1:
222
+ raise CompilerSandboxError(
223
+ f"hard-linked files are forbidden: {relative}"
224
+ )
225
+ files.append(path)
226
+ elif not stat.S_ISDIR(metadata.st_mode):
227
+ raise CompilerSandboxError(f"special files are forbidden: {relative}")
228
+ return files
229
+
230
+
231
+ def quarantine_artifact(source: Path | str, destination: Path | str) -> Path:
232
+ """Copy `/app/repo` into a fresh private build root without link semantics."""
233
+
234
+ source_root = Path(source).resolve(strict=True)
235
+ destination_root = Path(destination).resolve()
236
+ validate_artifact_tree(source_root)
237
+ if destination_root.exists():
238
+ raise FileExistsError(f"private build root already exists: {destination_root}")
239
+ destination_root.mkdir(parents=True, mode=0o700)
240
+ try:
241
+ for path, metadata in _tree_entries(source_root):
242
+ relative = path.relative_to(source_root)
243
+ target = destination_root / relative
244
+ if stat.S_ISDIR(metadata.st_mode):
245
+ target.mkdir(mode=stat.S_IMODE(metadata.st_mode) | 0o700)
246
+ else:
247
+ target.parent.mkdir(parents=True, exist_ok=True)
248
+ with (
249
+ path.open("rb") as source_handle,
250
+ target.open("xb") as target_handle,
251
+ ):
252
+ shutil.copyfileobj(source_handle, target_handle, length=1024 * 1024)
253
+ target_handle.flush()
254
+ os.fsync(target_handle.fileno())
255
+ target.chmod(stat.S_IMODE(metadata.st_mode))
256
+ validate_artifact_tree(destination_root)
257
+ except BaseException:
258
+ shutil.rmtree(destination_root, ignore_errors=True)
259
+ raise
260
+ return destination_root
261
+
262
+
263
+ def _compile_environment(
264
+ build_root: Path, data_root: Path, seed: int, timezone: str
265
+ ) -> dict[str, str]:
266
+ # This is an allowlist, not a copy of the verifier environment. In
267
+ # particular no provider, cloud, source, or hidden-fixture credential can
268
+ # reach compile.sh.
269
+ return {
270
+ "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
271
+ "LANG": "C.UTF-8",
272
+ "LC_ALL": "C.UTF-8",
273
+ "HOST": "127.0.0.1",
274
+ "PORT": "3000",
275
+ "DATA_DIR": str(data_root),
276
+ "SEED": str(seed),
277
+ "TZ": timezone,
278
+ "HOME": str(data_root / "home"),
279
+ "TMPDIR": str(data_root / "tmp"),
280
+ "XDG_CACHE_HOME": str(data_root / "xdg-cache"),
281
+ "XDG_CONFIG_HOME": str(data_root / "xdg-config"),
282
+ "XDG_DATA_HOME": str(data_root / "xdg-data"),
283
+ "WEBSITEBENCH_DEPLOYMENT_ABI": DEPLOYMENT_ABI,
284
+ "WEBSITEBENCH_BUILD_ROOT": str(build_root),
285
+ }
286
+
287
+
288
+ def _install_socket_deny_filter() -> None:
289
+ """Deny sockets and process-group escape while allowing compiler children."""
290
+
291
+ (
292
+ audit_arch,
293
+ socket_syscall,
294
+ _fcntl_syscall,
295
+ seccomp_syscall,
296
+ _denied,
297
+ ) = sandbox._architecture()
298
+ escape_syscalls = (109, 112) if audit_arch == 0xC000003E else (154, 157)
299
+ instructions = [
300
+ (sandbox.BPF_LD_W_ABS, 0, 0, 4),
301
+ (sandbox.BPF_JMP_JEQ_K, 1, 0, audit_arch),
302
+ (sandbox.BPF_RET_K, 0, 0, sandbox.SECCOMP_RET_KILL_PROCESS),
303
+ (sandbox.BPF_LD_W_ABS, 0, 0, 0),
304
+ (sandbox.BPF_JMP_JEQ_K, 0, 1, socket_syscall),
305
+ (
306
+ sandbox.BPF_RET_K,
307
+ 0,
308
+ 0,
309
+ sandbox.SECCOMP_RET_ERRNO | errno.EPERM,
310
+ ),
311
+ ]
312
+ for syscall_number in escape_syscalls:
313
+ instructions.extend(
314
+ [
315
+ (sandbox.BPF_JMP_JEQ_K, 0, 1, syscall_number),
316
+ (
317
+ sandbox.BPF_RET_K,
318
+ 0,
319
+ 0,
320
+ sandbox.SECCOMP_RET_ERRNO | errno.EPERM,
321
+ ),
322
+ ]
323
+ )
324
+ instructions.append((sandbox.BPF_RET_K, 0, 0, sandbox.SECCOMP_RET_ALLOW))
325
+ filters = (sandbox._SockFilter * len(instructions))(
326
+ *(sandbox._SockFilter(*instruction) for instruction in instructions)
327
+ )
328
+ program = sandbox._SockFprog(len(instructions), filters)
329
+ libc = ctypes.CDLL(None, use_errno=True)
330
+ if libc.prctl(sandbox.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
331
+ raise OSError(ctypes.get_errno(), "cannot set compiler no_new_privs")
332
+ result = int(
333
+ libc.syscall(
334
+ seccomp_syscall,
335
+ sandbox.SECCOMP_SET_MODE_FILTER,
336
+ 0,
337
+ ctypes.byref(program),
338
+ )
339
+ )
340
+ if result != 0:
341
+ raise OSError(ctypes.get_errno(), "cannot install compiler network filter")
342
+
343
+
344
+ def _compiler_preexec(
345
+ build_root: Path, data_root: Path, memory_mb: int, cpu_seconds: int
346
+ ) -> None:
347
+ os.umask(0o077)
348
+ if resource is not None:
349
+ memory = memory_mb * 1024 * 1024
350
+ resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
351
+ resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds + 5))
352
+ resource.setrlimit(resource.RLIMIT_NOFILE, (1024, 1024))
353
+ resource.setrlimit(resource.RLIMIT_FSIZE, (MAX_LOG_BYTES, MAX_LOG_BYTES))
354
+ # Root and data are deliberately the same writable private tree for
355
+ # compilation. Landlock grants system toolchains read/execute access and
356
+ # grants no TCP bind/connect ports. It also withholds shared filesystem
357
+ # socket locations such as /run and /tmp.
358
+ sandbox._landlock(build_root, data_root, 1, set())
359
+ _install_socket_deny_filter()
360
+
361
+
362
+ def _process_group_alive(group: int) -> bool:
363
+ proc = Path("/proc")
364
+ if proc.is_dir():
365
+ for status_path in proc.glob("[0-9]*/stat"):
366
+ try:
367
+ raw = status_path.read_text(encoding="ascii")
368
+ fields = raw[raw.rfind(")") + 2 :].split()
369
+ if int(fields[2]) == group and fields[0] != "Z":
370
+ return True
371
+ except (OSError, UnicodeError, ValueError, IndexError):
372
+ continue
373
+ return False
374
+ try:
375
+ os.killpg(group, 0)
376
+ except (ProcessLookupError, PermissionError):
377
+ return False
378
+ return True
379
+
380
+
381
+ def _terminate_group(process: subprocess.Popen[Any], timeout: float = 10.0) -> bool:
382
+ group = process.pid
383
+ if process.poll() is None:
384
+ try:
385
+ os.killpg(group, signal.SIGTERM)
386
+ except ProcessLookupError:
387
+ pass
388
+ deadline = time.monotonic() + timeout
389
+ while _process_group_alive(group) and time.monotonic() < deadline:
390
+ time.sleep(0.02)
391
+ graceful = not _process_group_alive(group)
392
+ if not graceful:
393
+ try:
394
+ os.killpg(group, signal.SIGKILL)
395
+ except ProcessLookupError:
396
+ pass
397
+ try:
398
+ process.wait(timeout=5)
399
+ except subprocess.TimeoutExpired:
400
+ return False
401
+ return graceful
402
+
403
+
404
+ def _stop_controlled_group(
405
+ process: subprocess.Popen[Any], control_fd: int, timeout: float = 10.0
406
+ ) -> bool:
407
+ """Ask the trusted sandbox launcher to stop its tracee, then reap the group."""
408
+
409
+ if process.poll() is None:
410
+ try:
411
+ os.write(control_fd, b"T")
412
+ except OSError:
413
+ pass
414
+ deadline = time.monotonic() + timeout
415
+ while _process_group_alive(process.pid) and time.monotonic() < deadline:
416
+ time.sleep(0.02)
417
+ graceful = not _process_group_alive(process.pid)
418
+ if not graceful:
419
+ try:
420
+ os.write(control_fd, b"K")
421
+ except OSError:
422
+ pass
423
+ time.sleep(0.1)
424
+ if _process_group_alive(process.pid):
425
+ try:
426
+ os.killpg(process.pid, signal.SIGKILL)
427
+ except ProcessLookupError:
428
+ pass
429
+ try:
430
+ process.wait(timeout=5)
431
+ except subprocess.TimeoutExpired:
432
+ return False
433
+ return graceful
434
+
435
+
436
+ def _processes_referencing(root: Path, *, exclude: Sequence[int] = ()) -> list[int]:
437
+ references: list[int] = []
438
+ root_text = str(root.resolve())
439
+ excluded = set(exclude)
440
+ for process in Path("/proc").glob("[0-9]*"):
441
+ try:
442
+ pid = int(process.name)
443
+ if pid in excluded:
444
+ continue
445
+ cwd = os.readlink(process / "cwd")
446
+ command = (
447
+ (process / "cmdline")
448
+ .read_bytes()
449
+ .replace(b"\x00", b" ")
450
+ .decode("utf-8", errors="replace")
451
+ )
452
+ except (OSError, ValueError):
453
+ continue
454
+ if (
455
+ cwd == root_text
456
+ or cwd.startswith(root_text + os.sep)
457
+ or root_text in command
458
+ ):
459
+ references.append(pid)
460
+ return sorted(references)
461
+
462
+
463
+ def tree_digest(root: Path | str) -> str:
464
+ resolved = Path(root).resolve(strict=True)
465
+ validate_artifact_tree(resolved)
466
+ digest = hashlib.sha256()
467
+ for path, metadata in _tree_entries(resolved):
468
+ relative = path.relative_to(resolved).as_posix().encode("utf-8")
469
+ kind = b"d" if stat.S_ISDIR(metadata.st_mode) else b"f"
470
+ digest.update(kind + b"\0" + relative + b"\0")
471
+ digest.update(f"{stat.S_IMODE(metadata.st_mode):04o}".encode("ascii") + b"\0")
472
+ if kind == b"f":
473
+ with path.open("rb") as handle:
474
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
475
+ digest.update(chunk)
476
+ digest.update(b"\0")
477
+ return digest.hexdigest()
478
+
479
+
480
+ def freeze_build_tree(root: Path | str) -> str:
481
+ resolved = Path(root).resolve(strict=True)
482
+ validate_artifact_tree(resolved)
483
+ entries = list(_tree_entries(resolved))
484
+ for path, metadata in entries:
485
+ if stat.S_ISREG(metadata.st_mode):
486
+ executable = bool(stat.S_IMODE(metadata.st_mode) & 0o111)
487
+ path.chmod(0o555 if executable else 0o444)
488
+ for path, metadata in reversed(entries):
489
+ if stat.S_ISDIR(metadata.st_mode):
490
+ path.chmod(0o555)
491
+ resolved.chmod(0o555)
492
+ return tree_digest(resolved)
493
+
494
+
495
+ def compile_candidate(
496
+ source_root: Path | str,
497
+ private_root: Path | str,
498
+ *,
499
+ timeout: float = DEFAULT_COMPILE_TIMEOUT,
500
+ seed: int = 0,
501
+ timezone: str = "UTC",
502
+ memory_mb: int = 8192,
503
+ ) -> CompiledArtifact:
504
+ """Quarantine, compile offline once, validate, freeze, and hash the build."""
505
+
506
+ source = Path(source_root).resolve(strict=True)
507
+ private = Path(private_root).resolve()
508
+ if private.exists():
509
+ raise FileExistsError(f"private compiler root already exists: {private}")
510
+ private.mkdir(parents=True, mode=0o700)
511
+ build = private / "build"
512
+ log = private / "build.log"
513
+ quarantine_artifact(source, build)
514
+ data = build / ".websitebench-compile-data"
515
+ if data.exists():
516
+ if data.is_dir() and not data.is_symlink():
517
+ shutil.rmtree(data)
518
+ else:
519
+ data.unlink()
520
+ data.mkdir(mode=0o700)
521
+ for name in ("home", "tmp", "xdg-cache", "xdg-config", "xdg-data"):
522
+ (data / name).mkdir(mode=0o700)
523
+ compile_script = build / COMPILE_ENTRYPOINT
524
+ if not compile_script.is_file() or compile_script.is_symlink():
525
+ raise CompilerSandboxError("candidate root must contain regular compile.sh")
526
+ if compile_script.stat().st_nlink != 1 or not os.access(compile_script, os.X_OK):
527
+ raise CompilerSandboxError("compile.sh must be an independent executable file")
528
+
529
+ # A submitted executable is never trusted as compiler output.
530
+ preexisting = build / EXECUTABLE_ENTRYPOINT
531
+ if preexisting.exists():
532
+ if preexisting.is_dir():
533
+ shutil.rmtree(preexisting)
534
+ else:
535
+ preexisting.unlink()
536
+
537
+ environment = _compile_environment(build, data, seed, timezone)
538
+ with log.open("wb") as log_handle:
539
+ try:
540
+ process = subprocess.Popen(
541
+ [str(compile_script)],
542
+ cwd=build,
543
+ env=environment,
544
+ stdin=subprocess.DEVNULL,
545
+ stdout=log_handle,
546
+ stderr=subprocess.STDOUT,
547
+ start_new_session=True,
548
+ preexec_fn=lambda: _compiler_preexec(
549
+ build, build, memory_mb, max(1, int(timeout))
550
+ ),
551
+ )
552
+ try:
553
+ return_code = process.wait(timeout=timeout)
554
+ except subprocess.TimeoutExpired as exc:
555
+ _terminate_group(process)
556
+ raise CompilerSandboxError(
557
+ f"compile.sh exceeded {timeout:g} seconds"
558
+ ) from exc
559
+ if _process_group_alive(process.pid):
560
+ _terminate_group(process)
561
+ raise CompilerSandboxError(
562
+ "compile.sh left a child process or listener alive"
563
+ )
564
+ if return_code != 0:
565
+ raise CompilerSandboxError(f"compile.sh exited {return_code}")
566
+ finally:
567
+ log_handle.flush()
568
+ os.fsync(log_handle.fileno())
569
+
570
+ leaked = _processes_referencing(build, exclude=(os.getpid(),))
571
+ if leaked:
572
+ for pid in leaked:
573
+ try:
574
+ os.kill(pid, signal.SIGKILL)
575
+ except ProcessLookupError:
576
+ pass
577
+ raise CompilerSandboxError(f"compiler left detached processes: {leaked}")
578
+ if log.stat().st_size > MAX_LOG_BYTES:
579
+ raise CompilerSandboxError("compiler log exceeded 256 MiB")
580
+
581
+ shutil.rmtree(data)
582
+ validate_artifact_tree(build)
583
+ executable = build / EXECUTABLE_ENTRYPOINT
584
+ try:
585
+ metadata = executable.lstat()
586
+ except OSError as exc:
587
+ raise CompilerSandboxError(
588
+ "compile.sh did not produce root executable"
589
+ ) from exc
590
+ if (
591
+ not stat.S_ISREG(metadata.st_mode)
592
+ or metadata.st_nlink != 1
593
+ or not stat.S_IMODE(metadata.st_mode) & 0o111
594
+ or executable.resolve() != executable
595
+ ):
596
+ raise CompilerSandboxError(
597
+ "executable must be an independent regular executable at the build root"
598
+ )
599
+ digest = freeze_build_tree(build)
600
+ return CompiledArtifact(
601
+ source_root=source,
602
+ build_root=build,
603
+ executable=executable,
604
+ tree_sha256=digest,
605
+ build_log=log,
606
+ )
607
+
608
+
609
+ @dataclass
610
+ class ExecutableRuntime:
611
+ """One foreground compiled candidate bound to one isolated DATA_DIR."""
612
+
613
+ build_root: Path
614
+ data_dir: Path
615
+ port: int
616
+ seed: int
617
+ timezone: str = "UTC"
618
+ log_path: Path | None = None
619
+ # RLIMIT_AS covers reserved virtual address space, not resident memory.
620
+ # Current Node/V8 runtimes reserve more than the 8192 MiB Harbor RSS
621
+ # budget before serving any request; keep the evaluator's cgroup budget
622
+ # authoritative while leaving enough address space for that reservation.
623
+ memory_mb: int = 16384
624
+ expected_tree_sha256: str | None = None
625
+ mailbox_environment: Mapping[str, str] | None = None
626
+ mailbox_connect_ports: frozenset[int] = frozenset()
627
+ evaluator_environment: Mapping[str, str] | None = None
628
+ process: subprocess.Popen[bytes] | None = None
629
+ _log_handle: Any | None = None
630
+ _cleanup_complete: bool = True
631
+ _control_write_fd: int | None = None
632
+ _broker_tid: int | None = None
633
+ _candidate_pid: int | None = None
634
+
635
+ def _environment(self) -> dict[str, str]:
636
+ data = self.data_dir.resolve()
637
+ environment = {
638
+ "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
639
+ "LANG": "C.UTF-8",
640
+ "LC_ALL": "C.UTF-8",
641
+ "HOST": "127.0.0.1",
642
+ "PORT": str(self.port),
643
+ "DATA_DIR": str(data),
644
+ "SEED": str(self.seed),
645
+ "TZ": self.timezone,
646
+ "HOME": str(data / "home"),
647
+ "TMPDIR": str(data / "tmp"),
648
+ "XDG_CACHE_HOME": str(data / "xdg-cache"),
649
+ "XDG_CONFIG_HOME": str(data / "xdg-config"),
650
+ "XDG_DATA_HOME": str(data / "xdg-data"),
651
+ "WEBSITEBENCH_DEPLOYMENT_ABI": DEPLOYMENT_ABI,
652
+ }
653
+ if self.mailbox_environment is not None:
654
+ unknown = set(self.mailbox_environment) - CANDIDATE_MAIL_ENVIRONMENT
655
+ if unknown:
656
+ raise CompilerSandboxError(
657
+ f"candidate mailbox environment has unknown names: {sorted(unknown)}"
658
+ )
659
+ environment.update(
660
+ {name: str(value) for name, value in self.mailbox_environment.items()}
661
+ )
662
+ if self.evaluator_environment is not None:
663
+ unknown = set(self.evaluator_environment) - CANDIDATE_EVALUATOR_ENVIRONMENT
664
+ if unknown:
665
+ raise CompilerSandboxError(
666
+ "candidate evaluator environment has unknown names: "
667
+ f"{sorted(unknown)}"
668
+ )
669
+ if any(not str(value) for value in self.evaluator_environment.values()):
670
+ raise CompilerSandboxError(
671
+ "candidate evaluator environment values must be non-empty"
672
+ )
673
+ environment.update(
674
+ {name: str(value) for name, value in self.evaluator_environment.items()}
675
+ )
676
+ return environment
677
+
678
+ def _sandbox_command(
679
+ self,
680
+ *,
681
+ build: Path,
682
+ executable: Path,
683
+ control_read_fd: int,
684
+ broker_write_fd: int,
685
+ credentials: tuple[int, int] | None,
686
+ ) -> list[str]:
687
+ sandbox_path = Path(sandbox.__file__).resolve(strict=True)
688
+ command = [
689
+ os.sys.executable,
690
+ str(sandbox_path),
691
+ "--root",
692
+ str(build),
693
+ "--data",
694
+ str(self.data_dir.resolve()),
695
+ "--bind-port",
696
+ str(self.port),
697
+ "--connect-port",
698
+ str(self.port),
699
+ ]
700
+ for connect_port in sorted(self.mailbox_connect_ports):
701
+ command.extend(("--connect-port", str(connect_port)))
702
+ if credentials is not None:
703
+ uid, gid = credentials
704
+ command.extend(("--uid", str(uid), "--gid", str(gid)))
705
+ command.extend(
706
+ (
707
+ "--file-size-limit-bytes",
708
+ str(MAX_LOG_BYTES),
709
+ "--broker-tid-fd",
710
+ str(broker_write_fd),
711
+ "--control-fd",
712
+ str(control_read_fd),
713
+ "--",
714
+ str(executable),
715
+ )
716
+ )
717
+ return command
718
+
719
+ def _attest_worker_identity(
720
+ self,
721
+ *,
722
+ expected_uid: int,
723
+ expected_gid: int,
724
+ ) -> None:
725
+ if self.process is None or self._broker_tid is None or self._candidate_pid is None:
726
+ raise OSError(errno.EIO, "sandbox identity proof is incomplete")
727
+ launcher_pid = self.process.pid
728
+ broker_status = Path(
729
+ f"/proc/{launcher_pid}/task/{self._broker_tid}/status"
730
+ )
731
+ candidate_status = Path(f"/proc/{self._candidate_pid}/status")
732
+ broker_uid, broker_gid, _broker_parent = _proc_status_identity(broker_status)
733
+ candidate_uid, candidate_gid, candidate_parent = _proc_status_identity(
734
+ candidate_status
735
+ )
736
+ expected_uids = (expected_uid,) * 4
737
+ expected_gids = (expected_gid,) * 4
738
+ if (
739
+ broker_uid != expected_uids
740
+ or broker_gid != expected_gids
741
+ or candidate_uid != expected_uids
742
+ or candidate_gid != expected_gids
743
+ or candidate_parent != launcher_pid
744
+ ):
745
+ raise OSError(
746
+ errno.EPERM,
747
+ "sandbox broker or candidate retained an unexpected OS identity",
748
+ )
749
+
750
+ def _preexec(self) -> None:
751
+ os.umask(0o077)
752
+ if resource is not None:
753
+ memory = self.memory_mb * 1024 * 1024
754
+ resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
755
+ resource.setrlimit(resource.RLIMIT_NOFILE, (1024, 1024))
756
+ resource.setrlimit(resource.RLIMIT_FSIZE, (MAX_LOG_BYTES, MAX_LOG_BYTES))
757
+
758
+ def start(self) -> None:
759
+ if not self._cleanup_complete:
760
+ raise CompilerSandboxError(
761
+ "runtime cleanup is incomplete; restart forbidden"
762
+ )
763
+ if self.process is not None and self.process.poll() is None:
764
+ raise CompilerSandboxError("compiled runtime is already running")
765
+ for connect_port in self.mailbox_connect_ports:
766
+ if not 1 <= connect_port <= 65535 or connect_port == self.port:
767
+ raise CompilerSandboxError("candidate mailbox connect port is invalid")
768
+ build = self.build_root.resolve(strict=True)
769
+ current_digest = tree_digest(build)
770
+ if current_digest == "": # pragma: no cover - digest is never empty
771
+ raise CompilerSandboxError("compiled build hash is unavailable")
772
+ if (
773
+ self.expected_tree_sha256 is not None
774
+ and current_digest != self.expected_tree_sha256
775
+ ):
776
+ raise CompilerSandboxError("compiled build tree changed after freezing")
777
+ executable = build / EXECUTABLE_ENTRYPOINT
778
+ metadata = executable.lstat()
779
+ if not stat.S_ISREG(metadata.st_mode) or not metadata.st_mode & 0o111:
780
+ raise CompilerSandboxError("compiled executable contract changed")
781
+ credentials = _runtime_worker_credentials()
782
+ try:
783
+ _prepare_runtime_directories(
784
+ build,
785
+ self.data_dir.resolve(),
786
+ credentials,
787
+ )
788
+ except OSError as exc:
789
+ raise RuntimeInfrastructureError(
790
+ "compiled runtime worker directories could not be prepared"
791
+ ) from exc
792
+ if self.log_path is not None:
793
+ log = self.log_path.resolve()
794
+ data = self.data_dir.resolve()
795
+ if data not in log.parents:
796
+ raise CompilerSandboxError("runtime log must be inside DATA_DIR")
797
+ log.parent.mkdir(parents=True, exist_ok=True)
798
+ self._log_handle = log.open("ab")
799
+ control_read_fd, control_write_fd = os.pipe()
800
+ broker_read_fd, broker_write_fd = os.pipe()
801
+ os.set_blocking(broker_read_fd, False)
802
+ command = self._sandbox_command(
803
+ build=build,
804
+ executable=executable,
805
+ control_read_fd=control_read_fd,
806
+ broker_write_fd=broker_write_fd,
807
+ credentials=credentials,
808
+ )
809
+ try:
810
+ self.process = subprocess.Popen(
811
+ command,
812
+ cwd=build,
813
+ env=self._environment(),
814
+ stdin=subprocess.DEVNULL,
815
+ stdout=self._log_handle or subprocess.DEVNULL,
816
+ stderr=self._log_handle or subprocess.DEVNULL,
817
+ start_new_session=True,
818
+ preexec_fn=self._preexec,
819
+ pass_fds=(control_read_fd, broker_write_fd),
820
+ )
821
+ except BaseException:
822
+ os.close(control_read_fd)
823
+ os.close(control_write_fd)
824
+ os.close(broker_read_fd)
825
+ os.close(broker_write_fd)
826
+ self._close_log()
827
+ raise
828
+ os.close(control_read_fd)
829
+ os.close(broker_write_fd)
830
+ self._control_write_fd = control_write_fd
831
+ self._cleanup_complete = False
832
+ proof = b""
833
+ deadline = time.monotonic() + 5.0
834
+ try:
835
+ while b"\n" not in proof and time.monotonic() < deadline:
836
+ try:
837
+ proof += os.read(broker_read_fd, 128)
838
+ except BlockingIOError:
839
+ pass
840
+ if self.process.poll() is not None:
841
+ break
842
+ time.sleep(0.01)
843
+ except OSError as exc:
844
+ self.stop(timeout=1.0)
845
+ raise RuntimeInfrastructureError(
846
+ "compiled runtime sandbox identity proof could not be read"
847
+ ) from exc
848
+ finally:
849
+ os.close(broker_read_fd)
850
+ try:
851
+ proof_fields = proof.splitlines()[0].split()
852
+ if len(proof_fields) != 2:
853
+ raise ValueError("sandbox proof must contain two process IDs")
854
+ self._broker_tid, self._candidate_pid = map(int, proof_fields)
855
+ except (ValueError, IndexError):
856
+ self._broker_tid = None
857
+ self._candidate_pid = None
858
+ if (
859
+ self._broker_tid is not None
860
+ and not Path(f"/proc/{self.process.pid}/task/{self._broker_tid}").is_dir()
861
+ ):
862
+ self._broker_tid = None
863
+ if self._broker_tid is None or self._candidate_pid is None:
864
+ self.stop(timeout=1.0)
865
+ raise RuntimeInfrastructureError(
866
+ "compiled runtime sandbox did not attest its broker and candidate IDs"
867
+ )
868
+ expected_uid, expected_gid = credentials or (os.geteuid(), os.getegid())
869
+ try:
870
+ self._attest_worker_identity(
871
+ expected_uid=expected_uid,
872
+ expected_gid=expected_gid,
873
+ )
874
+ except OSError as exc:
875
+ self.stop(timeout=1.0)
876
+ raise RuntimeInfrastructureError(
877
+ "compiled runtime sandbox worker identity could not be verified"
878
+ ) from exc
879
+
880
+ def ready(self, *, timeout: float = 30.0) -> bool:
881
+ deadline = time.monotonic() + timeout
882
+ urls = [f"http://127.0.0.1:{self.port}{path}" for path in HEALTH_PATHS]
883
+ while time.monotonic() < deadline:
884
+ if self.process is None or self.process.poll() is not None:
885
+ return False
886
+ for url in urls:
887
+ try:
888
+ request = urllib.request.Request(url, method="GET")
889
+ with urllib.request.urlopen(request, timeout=0.5) as response:
890
+ payload = response.read(4096)
891
+ if (
892
+ response.status == 200
893
+ and json.loads(payload) == HEALTH_BODY
894
+ ):
895
+ return self.process.poll() is None
896
+ except (
897
+ OSError,
898
+ ValueError,
899
+ urllib.error.URLError,
900
+ json.JSONDecodeError,
901
+ ):
902
+ pass
903
+ time.sleep(0.05)
904
+ return False
905
+
906
+ def stop(self, *, timeout: float = 10.0) -> bool:
907
+ if self.process is None:
908
+ self._close_control()
909
+ self._close_log()
910
+ self._cleanup_complete = True
911
+ return True
912
+ if self._control_write_fd is None:
913
+ graceful = _terminate_group(self.process, timeout)
914
+ else:
915
+ graceful = _stop_controlled_group(
916
+ self.process, self._control_write_fd, timeout
917
+ )
918
+ self._close_control()
919
+ self._close_log()
920
+ self._cleanup_complete = graceful
921
+ self._broker_tid = None
922
+ self._candidate_pid = None
923
+ return graceful
924
+
925
+ def _close_control(self) -> None:
926
+ if self._control_write_fd is not None:
927
+ try:
928
+ os.close(self._control_write_fd)
929
+ except OSError:
930
+ pass
931
+ self._control_write_fd = None
932
+
933
+ def _close_log(self) -> None:
934
+ if self._log_handle is not None:
935
+ self._log_handle.flush()
936
+ os.fsync(self._log_handle.fileno())
937
+ self._log_handle.close()
938
+ self._log_handle = None
939
+
940
+
941
+ def validate_runtime_lifecycle(
942
+ artifact: CompiledArtifact,
943
+ *,
944
+ port: int,
945
+ seed: int,
946
+ working_root: Path | str,
947
+ timezone: str = "UTC",
948
+ ) -> dict[str, Any]:
949
+ """Probe health, foreground/SIGTERM, restart persistence and new-dir isolation."""
950
+
951
+ root = Path(working_root).resolve()
952
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
953
+ first_data = root / "data-first"
954
+ second_data = root / "data-second"
955
+ first_data.mkdir(mode=0o700)
956
+ second_data.mkdir(mode=0o700)
957
+ sentinel = first_data / ".websitebench-persistence"
958
+ sentinel.write_text(f"{seed}\n", encoding="ascii")
959
+ first = ExecutableRuntime(
960
+ artifact.build_root,
961
+ first_data,
962
+ port,
963
+ seed,
964
+ timezone,
965
+ first_data / "runtime.log",
966
+ expected_tree_sha256=artifact.tree_sha256,
967
+ )
968
+ first.start()
969
+ healthy = first.ready()
970
+ graceful = first.stop(timeout=10.0)
971
+ sentinel_persisted = sentinel.read_text(encoding="ascii") == f"{seed}\n"
972
+ restarted = False
973
+ if graceful:
974
+ first.start()
975
+ restarted = first.ready()
976
+ graceful = first.stop(timeout=10.0) and graceful
977
+ second = ExecutableRuntime(
978
+ artifact.build_root,
979
+ second_data,
980
+ port,
981
+ seed,
982
+ timezone,
983
+ second_data / "runtime.log",
984
+ expected_tree_sha256=artifact.tree_sha256,
985
+ )
986
+ second.start()
987
+ second_healthy = second.ready()
988
+ second_graceful = second.stop(timeout=10.0)
989
+ isolated = (
990
+ second_healthy
991
+ and second_graceful
992
+ and not (second_data / sentinel.name).exists()
993
+ )
994
+ return {
995
+ "deployment_abi": DEPLOYMENT_ABI,
996
+ "health": healthy,
997
+ "foreground": healthy,
998
+ "sigterm": graceful,
999
+ "restart": restarted,
1000
+ "persistence": sentinel_persisted,
1001
+ "new_data_dir_health": second_healthy,
1002
+ "new_data_dir_isolation": isolated,
1003
+ "tree_sha256": artifact.tree_sha256,
1004
+ "valid": all(
1005
+ (
1006
+ healthy,
1007
+ graceful,
1008
+ restarted,
1009
+ sentinel_persisted,
1010
+ second_healthy,
1011
+ second_graceful,
1012
+ isolated,
1013
+ )
1014
+ ),
1015
+ }
1016
+
1017
+
1018
+ __all__ = [
1019
+ "COMPILE_ENTRYPOINT",
1020
+ "DEFAULT_COMPILE_TIMEOUT",
1021
+ "DEPLOYMENT_ABI",
1022
+ "EXECUTABLE_ENTRYPOINT",
1023
+ "HEALTH_BODY",
1024
+ "HEALTH_PATH",
1025
+ "HEALTH_PATHS",
1026
+ "LEGACY_HEALTH_PATHS",
1027
+ "MAX_LOG_BYTES",
1028
+ "RUNTIME_PROCESS_MODEL",
1029
+ "RuntimeInfrastructureError",
1030
+ "WORKER_OS_GID",
1031
+ "WORKER_OS_UID",
1032
+ "CompiledArtifact",
1033
+ "CompilerSandboxError",
1034
+ "ExecutableRuntime",
1035
+ "compile_candidate",
1036
+ "freeze_build_tree",
1037
+ "quarantine_artifact",
1038
+ "tree_digest",
1039
+ "validate_artifact_tree",
1040
+ "validate_runtime_lifecycle",
1041
+ ]
tasks/etsy/environment/candidate-abi/websitebench/harbor/sandbox.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Linux kernel sandbox launcher for untrusted Harbor candidates.
2
+
3
+ The launcher is executed by the privileged verifier, installs an irreversible
4
+ Landlock/seccomp policy, drops to the opaque worker UID, and only then execs the
5
+ candidate entrypoint. It deliberately has no dependency outside the standard
6
+ library so the formal verifier image has a small, inspectable trusted surface.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import array
13
+ import ctypes
14
+ import errno
15
+ import fcntl
16
+ import os
17
+ import platform
18
+ import resource
19
+ import signal
20
+ import socket
21
+ import stat
22
+ import struct
23
+ import threading
24
+ import time
25
+ from pathlib import Path
26
+ from typing import Sequence
27
+
28
+
29
+ PR_SET_NO_NEW_PRIVS = 38
30
+ PR_SET_DUMPABLE = 4
31
+ PR_SET_SECCOMP = 22
32
+ SECCOMP_MODE_FILTER = 2
33
+ SECCOMP_RET_KILL_PROCESS = 0x80000000
34
+ SECCOMP_RET_ERRNO = 0x00050000
35
+ SECCOMP_RET_USER_NOTIF = 0x7FC00000
36
+ SECCOMP_RET_ALLOW = 0x7FFF0000
37
+ SECCOMP_FILTER_FLAG_NEW_LISTENER = 1 << 3
38
+ SECCOMP_SET_MODE_FILTER = 1
39
+ SECCOMP_GET_ACTION_AVAIL = 2
40
+
41
+ BPF_LD_W_ABS = 0x20
42
+ BPF_JMP_JEQ_K = 0x15
43
+ BPF_JMP_JSET_K = 0x45
44
+ BPF_ALU_AND_K = 0x54
45
+ BPF_RET_K = 0x06
46
+
47
+ LANDLOCK_CREATE_RULESET_VERSION = 1
48
+ LANDLOCK_RULE_PATH_BENEATH = 1
49
+ LANDLOCK_RULE_NET_PORT = 2
50
+ LANDLOCK_ACCESS_FS_EXECUTE = 1 << 0
51
+ LANDLOCK_ACCESS_FS_WRITE_FILE = 1 << 1
52
+ LANDLOCK_ACCESS_FS_READ_FILE = 1 << 2
53
+ LANDLOCK_ACCESS_FS_READ_DIR = 1 << 3
54
+ LANDLOCK_ACCESS_FS_REMOVE_DIR = 1 << 4
55
+ LANDLOCK_ACCESS_FS_REMOVE_FILE = 1 << 5
56
+ LANDLOCK_ACCESS_FS_MAKE_CHAR = 1 << 6
57
+ LANDLOCK_ACCESS_FS_MAKE_DIR = 1 << 7
58
+ LANDLOCK_ACCESS_FS_MAKE_REG = 1 << 8
59
+ LANDLOCK_ACCESS_FS_MAKE_SOCK = 1 << 9
60
+ LANDLOCK_ACCESS_FS_MAKE_FIFO = 1 << 10
61
+ LANDLOCK_ACCESS_FS_MAKE_BLOCK = 1 << 11
62
+ LANDLOCK_ACCESS_FS_MAKE_SYM = 1 << 12
63
+ LANDLOCK_ACCESS_FS_REFER = 1 << 13
64
+ LANDLOCK_ACCESS_FS_TRUNCATE = 1 << 14
65
+ LANDLOCK_ACCESS_FS_IOCTL_DEV = 1 << 15
66
+ LANDLOCK_ACCESS_NET_BIND_TCP = 1 << 0
67
+ LANDLOCK_ACCESS_NET_CONNECT_TCP = 1 << 1
68
+
69
+ _FS_ABI_1 = (1 << 13) - 1
70
+ _FS_ABI_2 = _FS_ABI_1 | LANDLOCK_ACCESS_FS_REFER
71
+ _FS_ABI_3 = _FS_ABI_2 | LANDLOCK_ACCESS_FS_TRUNCATE
72
+ _FS_ABI_5 = _FS_ABI_3 | LANDLOCK_ACCESS_FS_IOCTL_DEV
73
+ _FS_READ_EXECUTE = (
74
+ LANDLOCK_ACCESS_FS_EXECUTE
75
+ | LANDLOCK_ACCESS_FS_READ_FILE
76
+ | LANDLOCK_ACCESS_FS_READ_DIR
77
+ )
78
+
79
+
80
+ class _RulesetAttr(ctypes.Structure):
81
+ _fields_ = [
82
+ ("handled_access_fs", ctypes.c_uint64),
83
+ ("handled_access_net", ctypes.c_uint64),
84
+ ]
85
+
86
+
87
+ class _PathBeneathAttr(ctypes.Structure):
88
+ _fields_ = [
89
+ ("allowed_access", ctypes.c_uint64),
90
+ ("parent_fd", ctypes.c_int32),
91
+ ("reserved", ctypes.c_uint32),
92
+ ]
93
+
94
+
95
+ class _NetPortAttr(ctypes.Structure):
96
+ _fields_ = [("allowed_access", ctypes.c_uint64), ("port", ctypes.c_uint64)]
97
+
98
+
99
+ class _SockFilter(ctypes.Structure):
100
+ _fields_ = [
101
+ ("code", ctypes.c_ushort),
102
+ ("jt", ctypes.c_ubyte),
103
+ ("jf", ctypes.c_ubyte),
104
+ ("k", ctypes.c_uint32),
105
+ ]
106
+
107
+
108
+ class _SockFprog(ctypes.Structure):
109
+ _fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.POINTER(_SockFilter))]
110
+
111
+
112
+ _SECCOMP_NOTIF_FORMAT = "=QIIiIQQQQQQQ"
113
+ _SECCOMP_RESP_FORMAT = "=QqiI"
114
+ _SECCOMP_NOTIF_SIZE = struct.calcsize(_SECCOMP_NOTIF_FORMAT)
115
+ _SECCOMP_RESP_SIZE = struct.calcsize(_SECCOMP_RESP_FORMAT)
116
+
117
+
118
+ def _iowr(kind: int, number: int, size: int) -> int:
119
+ return (3 << 30) | (size << 16) | (kind << 8) | number
120
+
121
+
122
+ _SECCOMP_IOCTL_NOTIF_RECV = _iowr(ord("!"), 0, _SECCOMP_NOTIF_SIZE)
123
+ _SECCOMP_IOCTL_NOTIF_SEND = _iowr(ord("!"), 1, _SECCOMP_RESP_SIZE)
124
+
125
+
126
+ def _architecture() -> tuple[int, int, int, int, tuple[int, ...]]:
127
+ machine = platform.machine().lower()
128
+ if machine in {"x86_64", "amd64"}:
129
+ # AUDIT_ARCH_X86_64, socket(2), and shared cross-process facilities.
130
+ return (
131
+ 0xC000003E,
132
+ 41,
133
+ 72,
134
+ 317,
135
+ (
136
+ 29,
137
+ 30,
138
+ 31,
139
+ 57,
140
+ 58,
141
+ 64,
142
+ 65,
143
+ 66,
144
+ 67,
145
+ 68,
146
+ 69,
147
+ 70,
148
+ 71,
149
+ 109,
150
+ 112,
151
+ 240,
152
+ 241,
153
+ 242,
154
+ 243,
155
+ 244,
156
+ 245,
157
+ 248,
158
+ 249,
159
+ 250,
160
+ 253,
161
+ 254,
162
+ 255,
163
+ 294,
164
+ 298,
165
+ 300,
166
+ 301,
167
+ 425,
168
+ 73,
169
+ ),
170
+ )
171
+ if machine in {"aarch64", "arm64"}:
172
+ return (
173
+ 0xC00000B7,
174
+ 198,
175
+ 25,
176
+ 277,
177
+ tuple(range(180, 198))
178
+ + (26, 27, 28, 32, 154, 157, 217, 218, 219, 241, 262, 263, 425),
179
+ )
180
+ raise OSError(errno.ENOTSUP, f"unsupported verifier architecture: {machine}")
181
+
182
+
183
+ def _syscalls() -> tuple[int, int, int]:
184
+ machine = platform.machine().lower()
185
+ if machine in {"x86_64", "amd64", "aarch64", "arm64"}:
186
+ return 444, 445, 446
187
+ raise OSError(errno.ENOTSUP, f"unsupported verifier architecture: {machine}")
188
+
189
+
190
+ def sandbox_runtime_fingerprint() -> dict[str, object]:
191
+ """Return trusted kernel capabilities required by the candidate sandbox."""
192
+
193
+ audit_arch, socket_syscall, _fcntl_syscall, seccomp_syscall, _denied = (
194
+ _architecture()
195
+ )
196
+ create_ruleset, _add_rule, _restrict_self = _syscalls()
197
+ libc = ctypes.CDLL(None, use_errno=True)
198
+ abi = int(libc.syscall(create_ruleset, 0, 0, LANDLOCK_CREATE_RULESET_VERSION))
199
+ action = ctypes.c_uint32(SECCOMP_RET_USER_NOTIF)
200
+ user_notification = (
201
+ libc.syscall(
202
+ seccomp_syscall,
203
+ SECCOMP_GET_ACTION_AVAIL,
204
+ 0,
205
+ ctypes.byref(action),
206
+ )
207
+ == 0
208
+ )
209
+ x32_unavailable = True
210
+ if audit_arch == 0xC000003E:
211
+ ctypes.set_errno(0)
212
+ result = libc.syscall(0x40000000 | socket_syscall, -1, -1, -1)
213
+ x32_unavailable = result == -1 and ctypes.get_errno() == errno.ENOSYS
214
+ return {
215
+ "schema": "websitebench.harbor.sandbox-runtime",
216
+ "architecture": platform.machine().lower(),
217
+ "landlock_abi": abi,
218
+ "seccomp_user_notification": user_notification,
219
+ "x32_unavailable": x32_unavailable,
220
+ }
221
+
222
+
223
+ def sandbox_preflight() -> dict[str, object]:
224
+ """Fail closed before scoring when the verifier kernel cannot sandbox."""
225
+
226
+ fingerprint = sandbox_runtime_fingerprint()
227
+ if (
228
+ int(fingerprint["landlock_abi"]) < 4
229
+ or fingerprint["seccomp_user_notification"] is not True
230
+ or fingerprint["x32_unavailable"] is not True
231
+ ):
232
+ raise OSError(errno.ENOTSUP, f"candidate sandbox unavailable: {fingerprint}")
233
+ child = os.fork()
234
+ if child == 0:
235
+ try:
236
+ _landlock(Path("/"), Path("/tmp"), 65534, {65534})
237
+ listener = _seccomp()
238
+ os.close(listener)
239
+ os._exit(0)
240
+ except BaseException:
241
+ os._exit(1)
242
+ _waited, status = os.waitpid(child, 0)
243
+ if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0:
244
+ raise OSError(errno.ENOTSUP, "candidate sandbox enforcement probe failed")
245
+ fingerprint["enforcement_probe_passed"] = True
246
+ return fingerprint
247
+
248
+
249
+ def _landlock(
250
+ root: Path,
251
+ data: Path,
252
+ bind_port: int,
253
+ connect_ports: set[int],
254
+ read_paths: Sequence[Path] = (),
255
+ ) -> None:
256
+ libc = ctypes.CDLL(None, use_errno=True)
257
+ create_ruleset, add_rule, restrict_self = _syscalls()
258
+ abi = int(libc.syscall(create_ruleset, 0, 0, LANDLOCK_CREATE_RULESET_VERSION))
259
+ if abi < 4:
260
+ code = ctypes.get_errno() if abi < 0 else errno.ENOTSUP
261
+ raise OSError(code, "Landlock ABI 4 or newer is required")
262
+
263
+ handled_fs = _FS_ABI_1
264
+ if abi >= 2:
265
+ handled_fs = _FS_ABI_2
266
+ if abi >= 3:
267
+ handled_fs = _FS_ABI_3
268
+ if abi >= 5:
269
+ handled_fs = _FS_ABI_5
270
+ handled_net = LANDLOCK_ACCESS_NET_BIND_TCP | LANDLOCK_ACCESS_NET_CONNECT_TCP
271
+ attributes = _RulesetAttr(handled_fs, handled_net)
272
+ ruleset_fd = int(
273
+ libc.syscall(
274
+ create_ruleset,
275
+ ctypes.byref(attributes),
276
+ ctypes.sizeof(attributes),
277
+ 0,
278
+ )
279
+ )
280
+ if ruleset_fd < 0:
281
+ raise OSError(ctypes.get_errno(), "cannot create Landlock ruleset")
282
+
283
+ def add_path(path: Path, access: int) -> None:
284
+ if not path.exists():
285
+ return
286
+ descriptor = os.open(path, os.O_PATH | os.O_CLOEXEC)
287
+ try:
288
+ rule = _PathBeneathAttr(access & handled_fs, descriptor, 0)
289
+ if (
290
+ libc.syscall(
291
+ add_rule,
292
+ ruleset_fd,
293
+ LANDLOCK_RULE_PATH_BENEATH,
294
+ ctypes.byref(rule),
295
+ 0,
296
+ )
297
+ != 0
298
+ ):
299
+ raise OSError(ctypes.get_errno(), f"cannot allow sandbox path: {path}")
300
+ finally:
301
+ os.close(descriptor)
302
+
303
+ try:
304
+ for path in (
305
+ root,
306
+ Path("/usr"),
307
+ Path("/bin"),
308
+ Path("/lib"),
309
+ Path("/lib64"),
310
+ Path("/etc"),
311
+ *read_paths,
312
+ ):
313
+ add_path(path, _FS_READ_EXECUTE)
314
+ for path in (
315
+ Path("/dev/null"),
316
+ Path("/dev/zero"),
317
+ Path("/dev/random"),
318
+ Path("/dev/urandom"),
319
+ Path("/dev/full"),
320
+ Path("/dev/tty"),
321
+ ):
322
+ add_path(path, LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE)
323
+ add_path(data, handled_fs)
324
+
325
+ for access, port in (
326
+ (LANDLOCK_ACCESS_NET_BIND_TCP, bind_port),
327
+ *(
328
+ (LANDLOCK_ACCESS_NET_CONNECT_TCP, port)
329
+ for port in sorted(connect_ports)
330
+ ),
331
+ ):
332
+ rule = _NetPortAttr(access, port)
333
+ if (
334
+ libc.syscall(
335
+ add_rule,
336
+ ruleset_fd,
337
+ LANDLOCK_RULE_NET_PORT,
338
+ ctypes.byref(rule),
339
+ 0,
340
+ )
341
+ != 0
342
+ ):
343
+ raise OSError(ctypes.get_errno(), "cannot add Landlock TCP rule")
344
+
345
+ if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
346
+ raise OSError(ctypes.get_errno(), "cannot set no_new_privs")
347
+ if libc.syscall(restrict_self, ruleset_fd, 0) != 0:
348
+ raise OSError(ctypes.get_errno(), "cannot enforce Landlock ruleset")
349
+ finally:
350
+ os.close(ruleset_fd)
351
+
352
+
353
+ def _seccomp() -> int:
354
+ """Install the filter and return its user-notification listener."""
355
+
356
+ audit_arch, socket_syscall, fcntl_syscall, seccomp_syscall, denied = _architecture()
357
+ instructions: list[tuple[int, int, int, int]] = [
358
+ (BPF_LD_W_ABS, 0, 0, 4),
359
+ (BPF_JMP_JEQ_K, 1, 0, audit_arch),
360
+ (BPF_RET_K, 0, 0, SECCOMP_RET_KILL_PROCESS),
361
+ (BPF_LD_W_ABS, 0, 0, 0),
362
+ ]
363
+ if audit_arch == 0xC000003E:
364
+ instructions.extend(
365
+ [
366
+ (BPF_JMP_JSET_K, 0, 1, 0x40000000),
367
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
368
+ ]
369
+ )
370
+ # Force clone3 callers onto the inspectable clone/fork fallback, then deny
371
+ # only process-style clone(SIGCHLD). Thread creation has a zero exit-signal
372
+ # byte and remains available to ASGI runtimes.
373
+ clone_syscall = 56 if audit_arch == 0xC000003E else 220
374
+ instructions.extend(
375
+ [
376
+ (BPF_JMP_JEQ_K, 0, 1, 435),
377
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.ENOSYS),
378
+ (BPF_LD_W_ABS, 0, 0, 0),
379
+ (BPF_JMP_JEQ_K, 0, 4, clone_syscall),
380
+ (BPF_LD_W_ABS, 0, 0, 16),
381
+ (BPF_ALU_AND_K, 0, 0, 0xFF),
382
+ (BPF_JMP_JEQ_K, 0, 1, signal.SIGCHLD),
383
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
384
+ (BPF_LD_W_ABS, 0, 0, 0),
385
+ ]
386
+ )
387
+ for number in denied:
388
+ instructions.extend(
389
+ [
390
+ (BPF_JMP_JEQ_K, 0, 1, number),
391
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
392
+ ]
393
+ )
394
+ # Classic and OFD byte-range locks are executed by the trusted broker.
395
+ # The tracee is never continued after a pathname/fd check: another tracee
396
+ # thread could otherwise replace the descriptor between check and use.
397
+ brokered_fcntl_commands = (5, 6, 7, 36, 37, 38)
398
+ instructions.extend(
399
+ [
400
+ (
401
+ BPF_JMP_JEQ_K,
402
+ 0,
403
+ 2 * len(brokered_fcntl_commands) + 2,
404
+ fcntl_syscall,
405
+ ),
406
+ (BPF_LD_W_ABS, 0, 0, 24),
407
+ ]
408
+ )
409
+ for command in brokered_fcntl_commands:
410
+ instructions.extend(
411
+ [
412
+ (BPF_JMP_JEQ_K, 0, 1, command),
413
+ (BPF_RET_K, 0, 0, SECCOMP_RET_USER_NOTIF),
414
+ ]
415
+ )
416
+ instructions.append((BPF_LD_W_ABS, 0, 0, 0))
417
+ # socket(domain, type, protocol): permit only IPv4/IPv6 SOCK_STREAM.
418
+ instructions.extend(
419
+ [
420
+ (BPF_JMP_JEQ_K, 0, 8, socket_syscall),
421
+ (BPF_LD_W_ABS, 0, 0, 16),
422
+ (BPF_JMP_JEQ_K, 2, 0, 2),
423
+ (BPF_JMP_JEQ_K, 1, 0, 10),
424
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
425
+ (BPF_LD_W_ABS, 0, 0, 24),
426
+ (BPF_ALU_AND_K, 0, 0, 0xF),
427
+ (BPF_JMP_JEQ_K, 1, 0, 1),
428
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
429
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ALLOW),
430
+ ]
431
+ )
432
+ filters = (_SockFilter * len(instructions))(
433
+ *(_SockFilter(*instruction) for instruction in instructions)
434
+ )
435
+ program = _SockFprog(len(instructions), filters)
436
+ libc = ctypes.CDLL(None, use_errno=True)
437
+ listener = int(
438
+ libc.syscall(
439
+ seccomp_syscall,
440
+ SECCOMP_SET_MODE_FILTER,
441
+ SECCOMP_FILTER_FLAG_NEW_LISTENER,
442
+ ctypes.byref(program),
443
+ )
444
+ )
445
+ if listener < 0:
446
+ raise OSError(ctypes.get_errno(), "cannot install candidate seccomp filter")
447
+ return listener
448
+
449
+
450
+ def _send_fd(channel: socket.socket, descriptor: int) -> None:
451
+ descriptors = array.array("i", [descriptor])
452
+ channel.sendmsg(
453
+ [b"L"],
454
+ [(socket.SOL_SOCKET, socket.SCM_RIGHTS, descriptors.tobytes())],
455
+ )
456
+
457
+
458
+ def _receive_fd(channel: socket.socket) -> int:
459
+ descriptors = array.array("i")
460
+ message, ancillary, _flags, _address = channel.recvmsg(
461
+ 1, socket.CMSG_SPACE(descriptors.itemsize)
462
+ )
463
+ if message != b"L":
464
+ raise OSError(errno.EIO, "candidate sandbox listener was not delivered")
465
+ for level, kind, payload in ancillary:
466
+ if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
467
+ descriptors.frombytes(payload[: descriptors.itemsize])
468
+ return int(descriptors[0])
469
+ raise OSError(errno.EIO, "candidate sandbox listener fd is missing")
470
+
471
+
472
+ def _tracee_process_id(thread_id: int) -> int:
473
+ try:
474
+ for line in Path(f"/proc/{thread_id}/status").read_text().splitlines():
475
+ if line.startswith("Tgid:"):
476
+ return int(line.partition(":")[2].strip())
477
+ except (OSError, ValueError):
478
+ pass
479
+ raise OSError(errno.ESRCH, "cannot identify candidate process")
480
+
481
+
482
+ def _capture_worker_file(pid: int, descriptor: int, data: Path) -> int:
483
+ """Atomically capture a regular data-dir inode from a tracee descriptor."""
484
+
485
+ captured = os.open(f"/proc/{pid}/fd/{descriptor}", os.O_RDWR | os.O_CLOEXEC)
486
+ try:
487
+ metadata = os.fstat(captured)
488
+ if not stat.S_ISREG(metadata.st_mode):
489
+ raise OSError(errno.EPERM, "candidate locks require a regular file")
490
+ target_text = os.readlink(f"/proc/self/fd/{captured}")
491
+ if target_text.endswith(" (deleted)"):
492
+ target_text = target_text[: -len(" (deleted)")]
493
+ target = Path(target_text).resolve()
494
+ if target != data and data not in target.parents:
495
+ raise OSError(errno.EPERM, "candidate lock target is outside data dir")
496
+ return captured
497
+ except BaseException:
498
+ os.close(captured)
499
+ raise
500
+
501
+
502
+ def _read_tracee(pid: int, address: int, size: int) -> bytes:
503
+ descriptor = os.open(f"/proc/{pid}/mem", os.O_RDONLY | os.O_CLOEXEC)
504
+ try:
505
+ value = os.pread(descriptor, size, address)
506
+ finally:
507
+ os.close(descriptor)
508
+ if len(value) != size:
509
+ raise OSError(errno.EFAULT, "candidate fcntl argument is unreadable")
510
+ return value
511
+
512
+
513
+ def _write_tracee(pid: int, address: int, value: bytes) -> None:
514
+ descriptor = os.open(f"/proc/{pid}/mem", os.O_WRONLY | os.O_CLOEXEC)
515
+ try:
516
+ written = os.pwrite(descriptor, value, address)
517
+ finally:
518
+ os.close(descriptor)
519
+ if written != len(value):
520
+ raise OSError(errno.EFAULT, "candidate fcntl result is unwritable")
521
+
522
+
523
+ def _prune_closed_lock_files(
524
+ process_id: int,
525
+ locked_files: dict[tuple[int, int, int], int],
526
+ ) -> None:
527
+ """Release broker descriptors once the tracee has closed their inode.
528
+
529
+ SQLite creates and removes WAL/SHM files as short-lived connections come
530
+ and go. Keeping one broker descriptor for every historical inode pins both
531
+ deleted files and file descriptors until process exit, eventually turning
532
+ ordinary repeated requests into ``SQLITE_IOERR`` under ``RLIMIT_NOFILE``.
533
+ An OFD lock is no longer useful after the tracee has closed every descriptor
534
+ for that inode, so prune it before brokering the next lock operation.
535
+ """
536
+
537
+ open_inodes: set[tuple[int, int]] = set()
538
+ try:
539
+ entries = list(Path(f"/proc/{process_id}/fd").iterdir())
540
+ except OSError:
541
+ return
542
+ for entry in entries:
543
+ try:
544
+ metadata = entry.stat()
545
+ except OSError:
546
+ continue
547
+ open_inodes.add((metadata.st_dev, metadata.st_ino))
548
+ for key, descriptor in list(locked_files.items()):
549
+ owner, device, inode = key
550
+ if owner == process_id and (device, inode) not in open_inodes:
551
+ os.close(descriptor)
552
+ del locked_files[key]
553
+
554
+
555
+ def _broker_fcntl(
556
+ pid: int,
557
+ descriptor: int,
558
+ command: int,
559
+ argument: int,
560
+ data: Path,
561
+ locked_files: dict[tuple[int, int, int], int],
562
+ ) -> int:
563
+ """Execute a byte-range lock without continuing the untrusted syscall."""
564
+
565
+ process_id = _tracee_process_id(pid)
566
+ _prune_closed_lock_files(process_id, locked_files)
567
+ captured = _capture_worker_file(pid, descriptor, data)
568
+ metadata = os.fstat(captured)
569
+ key = (process_id, metadata.st_dev, metadata.st_ino)
570
+ broker_descriptor = locked_files.get(key)
571
+ if broker_descriptor is None:
572
+ locked_files[key] = captured
573
+ broker_descriptor = captured
574
+ else:
575
+ os.close(captured)
576
+
577
+ flock_value = bytearray(_read_tracee(pid, argument, 32))
578
+ # Linux requires l_pid to be zero for OFD lock operations. Classic
579
+ # F_SETLK callers do not own that output-only field, so normalize it when
580
+ # translating the request.
581
+ flock_value[24:28] = b"\0\0\0\0"
582
+ translations = {
583
+ 5: 36, # F_GETLK -> F_OFD_GETLK
584
+ 6: 37, # F_SETLK -> F_OFD_SETLK
585
+ 7: 37, # F_SETLKW stays fail-fast so the broker cannot deadlock.
586
+ 36: 36,
587
+ 37: 37,
588
+ 38: 37,
589
+ }
590
+ result = fcntl.fcntl(broker_descriptor, translations[command], bytes(flock_value))
591
+ if command in {5, 36}:
592
+ if not isinstance(result, bytes):
593
+ raise OSError(errno.EIO, "candidate lock query returned no structure")
594
+ _write_tracee(pid, argument, result.ljust(32, b"\0")[:32])
595
+ return 0
596
+
597
+
598
+ def _lock_broker(listener: int, data: Path) -> None:
599
+ locked_files: dict[tuple[int, int, int], int] = {}
600
+ try:
601
+ while True:
602
+ request = bytearray(_SECCOMP_NOTIF_SIZE)
603
+ try:
604
+ fcntl.ioctl(listener, _SECCOMP_IOCTL_NOTIF_RECV, request, True)
605
+ except OSError as exc:
606
+ if exc.errno in {errno.EINTR, errno.ENOENT, errno.EBADF}:
607
+ if exc.errno == errno.EINTR:
608
+ continue
609
+ return
610
+ raise
611
+ unpacked = struct.unpack(_SECCOMP_NOTIF_FORMAT, request)
612
+ identifier, pid = int(unpacked[0]), int(unpacked[1])
613
+ try:
614
+ value = _broker_fcntl(
615
+ pid,
616
+ int(unpacked[6]),
617
+ int(unpacked[7]),
618
+ int(unpacked[8]),
619
+ data,
620
+ locked_files,
621
+ )
622
+ error = 0
623
+ except OSError as exc:
624
+ value = 0
625
+ error = -(exc.errno or errno.EPERM)
626
+ response = bytearray(
627
+ struct.pack(_SECCOMP_RESP_FORMAT, identifier, value, error, 0)
628
+ )
629
+ try:
630
+ fcntl.ioctl(listener, _SECCOMP_IOCTL_NOTIF_SEND, response, True)
631
+ except OSError as exc:
632
+ if exc.errno != errno.ENOENT:
633
+ raise
634
+ finally:
635
+ for descriptor in locked_files.values():
636
+ os.close(descriptor)
637
+
638
+
639
+ def _drop_credentials(uid: int | None, gid: int | None) -> None:
640
+ """Irreversibly adopt the requested worker identity, when configured."""
641
+
642
+ if uid is None or gid is None:
643
+ return
644
+ os.setgroups([])
645
+ os.setgid(gid)
646
+ os.setuid(uid)
647
+ if os.geteuid() != uid or os.getegid() != gid or os.getgroups():
648
+ raise OSError(errno.EPERM, "worker credential drop did not take effect")
649
+
650
+
651
+ def _kill_and_reap(child_pid: int) -> None:
652
+ try:
653
+ os.kill(child_pid, signal.SIGKILL)
654
+ except ProcessLookupError:
655
+ pass
656
+ try:
657
+ os.waitpid(child_pid, 0)
658
+ except ChildProcessError:
659
+ pass
660
+
661
+
662
+ def sandbox_exec(
663
+ command: Sequence[str],
664
+ *,
665
+ root: Path,
666
+ data: Path,
667
+ bind_port: int,
668
+ connect_ports: set[int],
669
+ uid: int | None,
670
+ gid: int | None,
671
+ file_size_limit_bytes: int | None,
672
+ read_paths: Sequence[Path] = (),
673
+ broker_tid_fd: int | None = None,
674
+ control_fd: int | None = None,
675
+ ) -> None:
676
+ root = root.resolve(strict=True)
677
+ data = data.resolve(strict=True)
678
+ parent_channel, child_channel = socket.socketpair()
679
+ child_pid = os.fork()
680
+ if child_pid == 0:
681
+ parent_channel.close()
682
+ if control_fd is not None:
683
+ os.close(control_fd)
684
+ if broker_tid_fd is not None:
685
+ os.close(broker_tid_fd)
686
+ stage = "landlock"
687
+ try:
688
+ _landlock(root, data, bind_port, connect_ports, read_paths)
689
+ stage = "resource limits"
690
+ if file_size_limit_bytes is not None:
691
+ resource.setrlimit(
692
+ resource.RLIMIT_FSIZE,
693
+ (file_size_limit_bytes, file_size_limit_bytes),
694
+ )
695
+ if uid is not None and gid is not None:
696
+ stage = "credential drop"
697
+ _drop_credentials(uid, gid)
698
+ stage = "lock broker access"
699
+ libc = ctypes.CDLL(None, use_errno=True)
700
+ if libc.prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) != 0:
701
+ raise OSError(ctypes.get_errno(), "cannot enable lock broker access")
702
+ stage = "seccomp"
703
+ listener = _seccomp()
704
+ stage = "listener handoff"
705
+ _send_fd(child_channel, listener)
706
+ os.close(listener)
707
+ child_channel.close()
708
+ stage = "candidate cwd"
709
+ os.chdir(root)
710
+ stage = "candidate exec"
711
+ os.execv(command[0], list(command))
712
+ except BaseException as exc:
713
+ message = f"candidate sandbox setup failed during {stage}: {exc}\n".encode(
714
+ "utf-8", "replace"
715
+ )
716
+ try:
717
+ os.write(2, message)
718
+ except OSError:
719
+ pass
720
+ os._exit(126)
721
+
722
+ child_channel.close()
723
+ try:
724
+ listener = _receive_fd(parent_channel)
725
+ except BaseException:
726
+ _kill_and_reap(child_pid)
727
+ raise
728
+ finally:
729
+ parent_channel.close()
730
+ try:
731
+ _drop_credentials(uid, gid)
732
+ except BaseException:
733
+ os.close(listener)
734
+ _kill_and_reap(child_pid)
735
+ raise
736
+ broker_errors: list[BaseException] = []
737
+ if control_fd is not None:
738
+ os.set_blocking(control_fd, False)
739
+
740
+ def broker() -> None:
741
+ try:
742
+ _lock_broker(listener, data)
743
+ except BaseException as exc:
744
+ broker_errors.append(exc)
745
+
746
+ broker_thread = threading.Thread(target=broker, daemon=True)
747
+ broker_thread.start()
748
+ if broker_tid_fd is not None:
749
+ try:
750
+ native_id = broker_thread.native_id
751
+ if native_id is None:
752
+ raise OSError(errno.EIO, "lock broker thread has no native id")
753
+ os.write(
754
+ broker_tid_fd,
755
+ f"{native_id} {child_pid}\n".encode("ascii"),
756
+ )
757
+ except BaseException:
758
+ os.close(listener)
759
+ _kill_and_reap(child_pid)
760
+ broker_thread.join(timeout=1)
761
+ if control_fd is not None:
762
+ os.close(control_fd)
763
+ raise
764
+ finally:
765
+ os.close(broker_tid_fd)
766
+ status = 0
767
+ while True:
768
+ if control_fd is not None:
769
+ try:
770
+ requested = os.read(control_fd, 4096)
771
+ except (BlockingIOError, OSError):
772
+ requested = b""
773
+ for marker in requested:
774
+ requested_signal = {
775
+ ord("T"): signal.SIGTERM,
776
+ ord("K"): signal.SIGKILL,
777
+ }.get(marker)
778
+ if requested_signal is not None:
779
+ try:
780
+ os.kill(child_pid, requested_signal)
781
+ except ProcessLookupError:
782
+ pass
783
+ waited, status = os.waitpid(child_pid, os.WNOHANG)
784
+ if waited == child_pid:
785
+ break
786
+ if broker_errors:
787
+ os.kill(child_pid, signal.SIGKILL)
788
+ _waited, status = os.waitpid(child_pid, 0)
789
+ break
790
+ time.sleep(0.01)
791
+ if control_fd is not None:
792
+ os.close(control_fd)
793
+ os.close(listener)
794
+ broker_thread.join(timeout=1)
795
+ if broker_errors:
796
+ raise OSError(errno.EIO, "candidate lock broker failed") from broker_errors[0]
797
+ # The trusted launcher/broker completed normally. Candidate business exit
798
+ # status is observed through readiness/lifecycle, while a nonzero launcher
799
+ # status remains reserved for audit infrastructure failure.
800
+ os._exit(0)
801
+
802
+
803
+ def main(argv: Sequence[str] | None = None) -> int:
804
+ parser = argparse.ArgumentParser()
805
+ parser.add_argument("--root", type=Path, required=True)
806
+ parser.add_argument("--data", type=Path, required=True)
807
+ parser.add_argument("--bind-port", type=int, required=True)
808
+ parser.add_argument("--connect-port", type=int, action="append", default=[])
809
+ parser.add_argument("--uid", type=int)
810
+ parser.add_argument("--gid", type=int)
811
+ parser.add_argument("--file-size-limit-bytes", type=int)
812
+ parser.add_argument("--read-path", type=Path, action="append", default=[])
813
+ parser.add_argument("--broker-tid-fd", type=int)
814
+ parser.add_argument("--control-fd", type=int)
815
+ parser.add_argument("command", nargs=argparse.REMAINDER)
816
+ arguments = parser.parse_args(argv)
817
+ command = arguments.command
818
+ if command[:1] == ["--"]:
819
+ command = command[1:]
820
+ if not command:
821
+ parser.error("candidate command is required")
822
+ if (arguments.uid is None) != (arguments.gid is None):
823
+ parser.error("uid and gid must be provided together")
824
+ sandbox_exec(
825
+ command,
826
+ root=arguments.root,
827
+ data=arguments.data,
828
+ bind_port=arguments.bind_port,
829
+ connect_ports=set(arguments.connect_port),
830
+ uid=arguments.uid,
831
+ gid=arguments.gid,
832
+ file_size_limit_bytes=arguments.file_size_limit_bytes,
833
+ read_paths=arguments.read_path,
834
+ broker_tid_fd=arguments.broker_tid_fd,
835
+ control_fd=arguments.control_fd,
836
+ )
837
+ return 127
838
+
839
+
840
+ if __name__ == "__main__":
841
+ raise SystemExit(main())
tasks/etsy/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/etsy/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/etsy/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/etsy/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/etsy/environment/reference/backend/runtime.json ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "database": {
3
+ "data_dir": "data",
4
+ "engine": "sqlite",
5
+ "filename": "websitebench-etsy.sqlite3",
6
+ "legacy_unbound_migration": false,
7
+ "migration_hook": null,
8
+ "seed_hook": null,
9
+ "volume_identity": "websitebench-etsy-data"
10
+ },
11
+ "deployment": {
12
+ "profiles": {
13
+ "cloudflare-review": {
14
+ "mail_adapter": "redis-resend",
15
+ "payment_adapter": "stripe-test",
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
+ "password-reset": {
34
+ "body": "Your password reset code is ${code}.",
35
+ "expiry": "This code expires in ${minutes} minutes.",
36
+ "footer": "Ignore this message if you did not contact Etsy Clone.",
37
+ "lead": "A password reset was requested for Etsy Clone.",
38
+ "required_variables": [
39
+ "code",
40
+ "minutes"
41
+ ],
42
+ "secret_variables": [
43
+ "code"
44
+ ],
45
+ "subject": "Reset your Etsy Clone password",
46
+ "template_id": "etsy.password-reset.v1"
47
+ },
48
+ "registration": {
49
+ "body": "Your verification code is ${code}.",
50
+ "expiry": "This code expires in ${minutes} minutes.",
51
+ "footer": "This code is only for Etsy Clone.",
52
+ "lead": "Finish creating your Etsy Clone account.",
53
+ "required_variables": [
54
+ "code",
55
+ "minutes"
56
+ ],
57
+ "secret_variables": [
58
+ "code"
59
+ ],
60
+ "subject": "Verify your Etsy Clone account",
61
+ "template_id": "etsy.registration.v1"
62
+ }
63
+ },
64
+ "sender": {
65
+ "address_env": "RESEND_FROM_EMAIL",
66
+ "display_name": "Etsy Clone"
67
+ }
68
+ },
69
+ "payments": {
70
+ "currency": "USD",
71
+ "default_adapter": "local-sandbox",
72
+ "enabled": true,
73
+ "local_sandbox": {
74
+ "scenarios": [
75
+ {
76
+ "display_label": "Simulated approval",
77
+ "id": "sandbox-approved",
78
+ "outcome": "approved"
79
+ },
80
+ {
81
+ "display_label": "Simulated decline",
82
+ "id": "sandbox-declined",
83
+ "outcome": "declined"
84
+ },
85
+ {
86
+ "display_label": "Simulated retry",
87
+ "id": "sandbox-retry",
88
+ "outcome": "retryable"
89
+ }
90
+ ]
91
+ },
92
+ "stripe_test": {
93
+ "max_line_items": 100,
94
+ "public_origin": "https://etsy.website-bench.com",
95
+ "return_path": "/checkout/stripe-return",
96
+ "secret_key_env": "STRIPE_TEST_SECRET_KEY",
97
+ "webhook_path": "/api/stripe/webhook",
98
+ "webhook_secret_env": "STRIPE_TEST_WEBHOOK_SECRET"
99
+ }
100
+ },
101
+ "schema_version": "websitebench.site-backend-runtime.v1",
102
+ "session": {
103
+ "host_only": true,
104
+ "http_only": true,
105
+ "same_site": "Lax",
106
+ "secure": true
107
+ },
108
+ "site": {
109
+ "id": "etsy",
110
+ "label": "Etsy Clone",
111
+ "public_origin": "https://etsy.website-bench.com"
112
+ }
113
+ }
tasks/etsy/environment/reference/clone/app.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/etsy/environment/reference/clone/backend/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Etsy offline clone backend package (persistent sqlite3 layer)."""
tasks/etsy/environment/reference/clone/backend/db.py ADDED
@@ -0,0 +1,1078 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Etsy offline clone - persistent SQLite layer (stage: backend, R3).
2
+
3
+ Owns the schema_migrations ledger, WAL configuration, the frozen seed
4
+ corpus, and the server-side price computation.
5
+
6
+ Data directory contract: CLAWBENCH_DATA_DIR (default: <site>/data, always
7
+ outside the candidate root clone/). The canonical database file is
8
+ websitebench-etsy.sqlite3.
9
+
10
+ Fidelity-first, decoupled from tasks: the schema and seed model generic
11
+ source-site behavior (sellers/shops, listings, variation axes + per-option
12
+ price data, per-combination prices and availability, per-listing
13
+ personalization rules, buyer accounts, session-scoped carts, account-owned
14
+ favorites). No benchmark task constant is validated for or branched on
15
+ anywhere; benchmark personalization values are ordinary inputs.
16
+
17
+ Duplicate-add policy (documented, applied generically): adding an identical
18
+ (listing, full variation tuple, personalization) line to the same cart
19
+ MERGES by summing quantities, capped by the per-listing maximum. This
20
+ mirrors the source site's cart merge behavior for identical configurations.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import hashlib
27
+ import os
28
+ import re
29
+ import sqlite3
30
+ import uuid
31
+ from decimal import Decimal
32
+ from pathlib import Path
33
+
34
+ PACKAGE_ROOT = Path(__file__).resolve().parent
35
+ CLONE_ROOT = PACKAGE_ROOT.parent
36
+ SITE_ROOT = CLONE_ROOT.parent
37
+ EMBEDDED = SITE_ROOT / "source-current" / "2026-07-25" / "embedded-browser"
38
+ ASSET_WEB_ROOT = "/static/assets/source-current/2026-07-25"
39
+
40
+ DB_FILENAME = "websitebench-etsy.sqlite3"
41
+ LEGACY_DB_FILENAME = "etsy.sqlite3"
42
+ FROZEN_CLOCK = "2026-07-25T12:00:00-04:00"
43
+ CURRENT_LISTING_VERSION = "2026-07-25"
44
+ SCHEMA_HEAD = "0007"
45
+
46
+ PRICE_RE = re.compile(r"\$([0-9][0-9,]*\.[0-9]{2})")
47
+ CURATION_BADGE_MARKERS = ("candidate", "task 5", "semantic match", "family")
48
+ PLACEHOLDER_OPTION = "Select an option"
49
+
50
+ _PAGE_FILES = {
51
+ "search-personalized-wallet": "search-personalized-wallet.json",
52
+ "search-dog-collar": "search-dog-collar.json",
53
+ "search-blue-vase": "search-blue-vase.json",
54
+ "search-bookshelf": "search-bookshelf.json",
55
+ }
56
+
57
+ # The four captured search queries; results are served from DB rows.
58
+ SEARCH_QUERY_SEED = {
59
+ "personalized leather wallet": "search-personalized-wallet",
60
+ "personalized leather bifold wallet initials": "search-personalized-wallet",
61
+ "custom dog collar": "search-dog-collar",
62
+ "leather dog collar custom name embroidery medium sized dog": "search-dog-collar",
63
+ "blue ceramic vase": "search-blue-vase",
64
+ "handmade blue ceramic flower vase": "search-blue-vase",
65
+ "wooden bookshelf": "search-bookshelf",
66
+ "mid century modern wooden bookshelf": "search-bookshelf",
67
+ }
68
+
69
+ _WALLET_ID = "870439619"
70
+ _COLLAR_ID = "839355276"
71
+ _VASE_ID = "4526658048"
72
+ _BOOKSHELF_ID = "1801448610"
73
+
74
+ # Fixture-authored seller identities: the 2026-07-25 capture surfaced only a
75
+ # "Made by seller" badge, never a shop name, so these synthetic shop records
76
+ # are fixture-authored, not Etsy source facts.
77
+ SELLERS = [
78
+ ("fixture-seller-wallet", "Fixture Leather Studio (synthetic)"),
79
+ ("fixture-seller-collar", "Fixture Collar Works (synthetic)"),
80
+ ("fixture-seller-vase", "Fixture Ceramics Shed (synthetic)"),
81
+ ("fixture-seller-bookshelf", "Fixture Woodshop (synthetic)"),
82
+ ("fixture-seller-corpus", "Fixture Marketplace Sellers (synthetic)"),
83
+ ]
84
+
85
+ # Synthetic local buyer accounts; never production credentials.
86
+ ACCOUNTS = [
87
+ ("alex", "alex-green-fixture", "Alex Green (synthetic)"),
88
+ ("jordan", "jordan-lee-fixture", "Jordan Lee (synthetic)"),
89
+ ]
90
+
91
+ # Fixture-authored collar size axis (the collar size axis was never directly
92
+ # captured; the option list is a generic small/medium/large ladder).
93
+ COLLAR_SIZE_OPTIONS = [PLACEHOLDER_OPTION, "Small", "Medium", "Large"]
94
+
95
+
96
+ def data_dir() -> Path:
97
+ raw = os.environ.get("WEBSITEBENCH_DATA_DIR", "").strip()
98
+ return Path(raw) if raw else SITE_ROOT / "data"
99
+
100
+
101
+ def db_path() -> Path:
102
+ return data_dir() / DB_FILENAME
103
+
104
+
105
+ def connect(path: Path | str | None = None) -> sqlite3.Connection:
106
+ selected = Path(path) if path is not None else db_path()
107
+ selected.parent.mkdir(parents=True, exist_ok=True)
108
+ conn = sqlite3.connect(str(selected))
109
+ conn.row_factory = sqlite3.Row
110
+ conn.execute("PRAGMA journal_mode=WAL")
111
+ conn.execute("PRAGMA foreign_keys=ON")
112
+ conn.execute("PRAGMA busy_timeout=5000")
113
+ return conn
114
+
115
+
116
+ def combo_key(variations: dict[str, str]) -> str:
117
+ """Canonical opaque key for a full variation tuple."""
118
+ return json.dumps(
119
+ {key: variations[key] for key in sorted(variations)},
120
+ separators=(",", ":"),
121
+ ensure_ascii=False,
122
+ )
123
+
124
+
125
+ # --- migrations (legacy 0001-0004 preserved verbatim, head 0005) --------------
126
+
127
+
128
+ _SQL_0001_CORE_CATALOG = """
129
+ CREATE TABLE sellers (
130
+ seller_id TEXT PRIMARY KEY,
131
+ shop_name TEXT NOT NULL,
132
+ provenance TEXT NOT NULL DEFAULT 'fixture-authored'
133
+ );
134
+ CREATE TABLE listings (
135
+ listing_id TEXT PRIMARY KEY,
136
+ seller_id TEXT NOT NULL REFERENCES sellers(seller_id),
137
+ family TEXT NOT NULL,
138
+ task TEXT,
139
+ title TEXT NOT NULL,
140
+ slug TEXT NOT NULL,
141
+ price_now TEXT NOT NULL,
142
+ price_original TEXT,
143
+ base_price_cents INTEGER,
144
+ image TEXT NOT NULL,
145
+ badges_json TEXT NOT NULL DEFAULT '[]',
146
+ cart_enabled INTEGER NOT NULL DEFAULT 0,
147
+ favorites_focused INTEGER NOT NULL DEFAULT 0,
148
+ version TEXT NOT NULL,
149
+ stock_state TEXT NOT NULL DEFAULT 'in-stock'
150
+ );
151
+ CREATE TABLE listing_options (
152
+ listing_id TEXT NOT NULL REFERENCES listings(listing_id),
153
+ axis TEXT NOT NULL,
154
+ position INTEGER NOT NULL,
155
+ value TEXT NOT NULL,
156
+ low_cents INTEGER,
157
+ high_cents INTEGER,
158
+ price_tier TEXT,
159
+ selectable INTEGER NOT NULL DEFAULT 1,
160
+ PRIMARY KEY (listing_id, axis, value)
161
+ );
162
+ CREATE TABLE search_pages (
163
+ page_id TEXT PRIMARY KEY,
164
+ title TEXT NOT NULL,
165
+ cards_count INTEGER NOT NULL
166
+ );
167
+ CREATE TABLE search_cards (
168
+ page_id TEXT NOT NULL REFERENCES search_pages(page_id),
169
+ position INTEGER NOT NULL,
170
+ listing_id TEXT NOT NULL,
171
+ title TEXT NOT NULL,
172
+ price_usd TEXT NOT NULL,
173
+ slug TEXT NOT NULL,
174
+ image TEXT NOT NULL,
175
+ badges_json TEXT NOT NULL DEFAULT '[]',
176
+ PRIMARY KEY (page_id, listing_id)
177
+ );
178
+ CREATE TABLE accounts (
179
+ account_id TEXT PRIMARY KEY,
180
+ owner_handle TEXT NOT NULL UNIQUE,
181
+ display_name TEXT NOT NULL
182
+ );
183
+ """
184
+
185
+ _SQL_0002_SESSIONS_AND_CART = """
186
+ CREATE TABLE sessions (
187
+ session_id TEXT PRIMARY KEY,
188
+ account_id TEXT REFERENCES accounts(account_id),
189
+ created_at TEXT NOT NULL
190
+ );
191
+ CREATE TABLE cart_lines (
192
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
193
+ owner_key TEXT NOT NULL,
194
+ listing_id TEXT NOT NULL REFERENCES listings(listing_id),
195
+ listing_version TEXT NOT NULL,
196
+ engraving TEXT NOT NULL DEFAULT '',
197
+ color TEXT NOT NULL DEFAULT '',
198
+ size TEXT NOT NULL DEFAULT '',
199
+ personalization TEXT NOT NULL DEFAULT '',
200
+ quantity INTEGER NOT NULL,
201
+ unit_price_cents INTEGER NOT NULL,
202
+ created_at TEXT NOT NULL,
203
+ UNIQUE (owner_key, listing_id, engraving, color, size, personalization, quantity)
204
+ );
205
+ """
206
+
207
+ _SQL_0003_FAVORITES = """
208
+ CREATE TABLE favorites (
209
+ account_id TEXT NOT NULL REFERENCES accounts(account_id),
210
+ listing_id TEXT NOT NULL,
211
+ created_at TEXT NOT NULL,
212
+ PRIMARY KEY (account_id, listing_id)
213
+ );
214
+ """
215
+
216
+
217
+ def _migrate_0004_opaque_line_tokens(conn: sqlite3.Connection) -> None:
218
+ """Cart line ids become opaque server tokens (legacy rows backfilled)."""
219
+ conn.execute("ALTER TABLE cart_lines ADD COLUMN line_token TEXT")
220
+ rows = conn.execute(
221
+ "SELECT id FROM cart_lines WHERE line_token IS NULL"
222
+ ).fetchall()
223
+ for row in rows:
224
+ conn.execute(
225
+ "UPDATE cart_lines SET line_token = ? WHERE id = ?",
226
+ (uuid.uuid4().hex, row["id"]),
227
+ )
228
+ conn.execute(
229
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_cart_lines_token "
230
+ "ON cart_lines(line_token)"
231
+ )
232
+
233
+
234
+ def _migrate_0005_generic_variation_model(conn: sqlite3.Connection) -> None:
235
+ """Head migration: generic variation axes, per-combination prices and
236
+ availability, per-listing personalization rules, per-listing quantity
237
+ max, DB-driven search queries, and a generic cart line shape
238
+ (variations_json instead of hardwired engraving/color/size columns).
239
+ """
240
+ conn.executescript(
241
+ """
242
+ DROP TABLE IF EXISTS listing_options;
243
+ CREATE TABLE listing_axes (
244
+ listing_id TEXT NOT NULL REFERENCES listings(listing_id),
245
+ position INTEGER NOT NULL,
246
+ axis_label TEXT NOT NULL,
247
+ PRIMARY KEY (listing_id, axis_label)
248
+ );
249
+ CREATE TABLE listing_options (
250
+ listing_id TEXT NOT NULL REFERENCES listings(listing_id),
251
+ axis_label TEXT NOT NULL,
252
+ position INTEGER NOT NULL,
253
+ value TEXT NOT NULL,
254
+ delta_cents INTEGER NOT NULL DEFAULT 0,
255
+ selectable INTEGER NOT NULL DEFAULT 1,
256
+ PRIMARY KEY (listing_id, axis_label, value)
257
+ );
258
+ CREATE TABLE listing_combo_prices (
259
+ listing_id TEXT NOT NULL REFERENCES listings(listing_id),
260
+ combo_key TEXT NOT NULL,
261
+ unit_price_cents INTEGER NOT NULL,
262
+ PRIMARY KEY (listing_id, combo_key)
263
+ );
264
+ CREATE TABLE listing_unavailable_combos (
265
+ listing_id TEXT NOT NULL REFERENCES listings(listing_id),
266
+ combo_key TEXT NOT NULL,
267
+ reason TEXT NOT NULL DEFAULT 'unavailable',
268
+ PRIMARY KEY (listing_id, combo_key)
269
+ );
270
+ CREATE TABLE listing_personalization (
271
+ listing_id TEXT PRIMARY KEY REFERENCES listings(listing_id),
272
+ enabled INTEGER NOT NULL DEFAULT 0,
273
+ required INTEGER NOT NULL DEFAULT 0,
274
+ char_limit INTEGER NOT NULL DEFAULT 256,
275
+ prompt TEXT NOT NULL DEFAULT 'Add your personalization'
276
+ );
277
+ CREATE TABLE search_queries (
278
+ query_norm TEXT PRIMARY KEY,
279
+ page_id TEXT NOT NULL REFERENCES search_pages(page_id)
280
+ );
281
+ ALTER TABLE listings ADD COLUMN max_quantity INTEGER NOT NULL DEFAULT 10;
282
+ CREATE TABLE cart_lines_v2 (
283
+ line_token TEXT PRIMARY KEY,
284
+ owner_key TEXT NOT NULL,
285
+ listing_id TEXT NOT NULL REFERENCES listings(listing_id),
286
+ listing_version TEXT NOT NULL,
287
+ variations_json TEXT NOT NULL DEFAULT '{}',
288
+ personalization TEXT NOT NULL DEFAULT '',
289
+ quantity INTEGER NOT NULL,
290
+ unit_price_cents INTEGER NOT NULL,
291
+ created_at TEXT NOT NULL,
292
+ updated_at TEXT NOT NULL,
293
+ UNIQUE (owner_key, listing_id, variations_json, personalization)
294
+ );
295
+ """
296
+ )
297
+ legacy = conn.execute(
298
+ "SELECT line_token, owner_key, listing_id, listing_version, engraving,"
299
+ " color, size, personalization, quantity, unit_price_cents, created_at"
300
+ " FROM cart_lines"
301
+ ).fetchall()
302
+ for row in legacy:
303
+ variations: dict[str, str] = {}
304
+ if row["engraving"]:
305
+ variations["Engraving Options"] = row["engraving"]
306
+ if row["color"]:
307
+ variations["Colors"] = row["color"]
308
+ if row["size"]:
309
+ variations["Size"] = row["size"]
310
+ conn.execute(
311
+ "INSERT OR IGNORE INTO cart_lines_v2 (line_token, owner_key,"
312
+ " listing_id, listing_version, variations_json, personalization,"
313
+ " quantity, unit_price_cents, created_at, updated_at)"
314
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
315
+ (
316
+ row["line_token"] or uuid.uuid4().hex,
317
+ row["owner_key"],
318
+ row["listing_id"],
319
+ row["listing_version"],
320
+ combo_key(variations),
321
+ row["personalization"],
322
+ row["quantity"],
323
+ row["unit_price_cents"],
324
+ row["created_at"],
325
+ row["created_at"],
326
+ ),
327
+ )
328
+ conn.executescript(
329
+ """
330
+ DROP TABLE cart_lines;
331
+ ALTER TABLE cart_lines_v2 RENAME TO cart_lines;
332
+ """
333
+ )
334
+
335
+
336
+ def _migrate_0006_command_authority(conn: sqlite3.Connection) -> None:
337
+ """Add durable command replay and optimistic-version authority.
338
+
339
+ The public forms never get to choose a price, owner, aggregate, or final
340
+ version. They may only present an idempotency key and an expected version;
341
+ this journal lets the server atomically replay an exact retry, reject
342
+ changed-payload key reuse, and serialize concurrent winners.
343
+ """
344
+ conn.executescript(
345
+ """
346
+ ALTER TABLE cart_lines ADD COLUMN version INTEGER NOT NULL DEFAULT 1;
347
+ ALTER TABLE favorites ADD COLUMN version INTEGER NOT NULL DEFAULT 1;
348
+ CREATE TABLE business_commands (
349
+ command_id TEXT PRIMARY KEY,
350
+ capability TEXT NOT NULL,
351
+ owner_scope TEXT NOT NULL,
352
+ idempotency_key TEXT NOT NULL,
353
+ payload_sha256 TEXT NOT NULL,
354
+ result_json TEXT NOT NULL,
355
+ created_at TEXT NOT NULL,
356
+ UNIQUE (capability, owner_scope, idempotency_key)
357
+ );
358
+ CREATE TABLE entity_versions (
359
+ capability TEXT NOT NULL,
360
+ entity_key TEXT NOT NULL,
361
+ version INTEGER NOT NULL,
362
+ command_id TEXT NOT NULL REFERENCES business_commands(command_id),
363
+ updated_at TEXT NOT NULL,
364
+ PRIMARY KEY (capability, entity_key)
365
+ );
366
+ """
367
+ )
368
+
369
+
370
+ def _migrate_0007_purchase_closure(conn: sqlite3.Connection) -> None:
371
+ """Add owner-bound checkout and immutable order snapshots.
372
+
373
+ The shared WebsiteBench runtime owns payment flows, attempts, and events.
374
+ These site-local tables own only Etsy checkout/address/cart snapshots and
375
+ the order committed when a matching shared approval is consumed.
376
+ """
377
+ conn.executescript(
378
+ """
379
+ CREATE TABLE checkouts (
380
+ checkout_id TEXT PRIMARY KEY,
381
+ account_id TEXT NOT NULL REFERENCES accounts(account_id),
382
+ status TEXT NOT NULL CHECK (
383
+ status IN ('pending-payment','payment-declined','payment-retry','completed','stale')
384
+ ),
385
+ currency TEXT NOT NULL CHECK (currency = 'USD'),
386
+ item_total_cents INTEGER NOT NULL CHECK (item_total_cents >= 0),
387
+ shipping_cents INTEGER NOT NULL CHECK (shipping_cents >= 0),
388
+ tax_cents INTEGER NOT NULL CHECK (tax_cents >= 0),
389
+ total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
390
+ cart_fingerprint TEXT NOT NULL,
391
+ address_json TEXT NOT NULL,
392
+ payment_flow_id TEXT,
393
+ version INTEGER NOT NULL DEFAULT 1,
394
+ created_at TEXT NOT NULL,
395
+ updated_at TEXT NOT NULL,
396
+ UNIQUE (account_id, cart_fingerprint)
397
+ );
398
+ CREATE TABLE checkout_lines (
399
+ checkout_id TEXT NOT NULL REFERENCES checkouts(checkout_id) ON DELETE RESTRICT,
400
+ position INTEGER NOT NULL,
401
+ cart_line_token TEXT NOT NULL,
402
+ listing_id TEXT NOT NULL,
403
+ listing_version TEXT NOT NULL,
404
+ title TEXT NOT NULL,
405
+ slug TEXT NOT NULL,
406
+ image TEXT NOT NULL,
407
+ variations_json TEXT NOT NULL,
408
+ personalization TEXT NOT NULL,
409
+ quantity INTEGER NOT NULL CHECK (quantity > 0),
410
+ unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0),
411
+ subtotal_cents INTEGER NOT NULL CHECK (subtotal_cents >= 0),
412
+ PRIMARY KEY (checkout_id, position),
413
+ UNIQUE (checkout_id, cart_line_token)
414
+ );
415
+ CREATE TABLE orders (
416
+ order_id TEXT PRIMARY KEY,
417
+ account_id TEXT NOT NULL REFERENCES accounts(account_id),
418
+ checkout_id TEXT NOT NULL UNIQUE REFERENCES checkouts(checkout_id),
419
+ payment_flow_id TEXT NOT NULL UNIQUE,
420
+ status TEXT NOT NULL CHECK (status = 'paid'),
421
+ currency TEXT NOT NULL CHECK (currency = 'USD'),
422
+ item_total_cents INTEGER NOT NULL CHECK (item_total_cents >= 0),
423
+ shipping_cents INTEGER NOT NULL CHECK (shipping_cents >= 0),
424
+ tax_cents INTEGER NOT NULL CHECK (tax_cents >= 0),
425
+ total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
426
+ address_json TEXT NOT NULL,
427
+ placed_at TEXT NOT NULL
428
+ );
429
+ CREATE TABLE order_lines (
430
+ order_id TEXT NOT NULL REFERENCES orders(order_id) ON DELETE RESTRICT,
431
+ position INTEGER NOT NULL,
432
+ listing_id TEXT NOT NULL,
433
+ listing_version TEXT NOT NULL,
434
+ title TEXT NOT NULL,
435
+ slug TEXT NOT NULL,
436
+ image TEXT NOT NULL,
437
+ variations_json TEXT NOT NULL,
438
+ personalization TEXT NOT NULL,
439
+ quantity INTEGER NOT NULL CHECK (quantity > 0),
440
+ unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0),
441
+ subtotal_cents INTEGER NOT NULL CHECK (subtotal_cents >= 0),
442
+ PRIMARY KEY (order_id, position)
443
+ );
444
+ CREATE TABLE order_events (
445
+ event_id TEXT PRIMARY KEY,
446
+ order_id TEXT NOT NULL REFERENCES orders(order_id) ON DELETE RESTRICT,
447
+ event_type TEXT NOT NULL CHECK (event_type = 'order-created'),
448
+ snapshot_json TEXT NOT NULL,
449
+ created_at TEXT NOT NULL
450
+ );
451
+ CREATE INDEX checkouts_owner_status_idx
452
+ ON checkouts(account_id, status, created_at);
453
+ CREATE INDEX orders_owner_placed_idx
454
+ ON orders(account_id, placed_at, order_id);
455
+ CREATE TRIGGER order_events_no_update
456
+ BEFORE UPDATE ON order_events
457
+ BEGIN
458
+ SELECT RAISE(ABORT, 'order events are immutable');
459
+ END;
460
+ CREATE TRIGGER order_events_no_delete
461
+ BEFORE DELETE ON order_events
462
+ BEGIN
463
+ SELECT RAISE(ABORT, 'order events are immutable');
464
+ END;
465
+ UPDATE listings SET cart_enabled = 1 WHERE stock_state = 'in-stock';
466
+ """
467
+ )
468
+
469
+
470
+ MIGRATIONS: list[tuple[str, str, object]] = [
471
+ ("0001", "core-catalog", _SQL_0001_CORE_CATALOG),
472
+ ("0002", "sessions-and-cart", _SQL_0002_SESSIONS_AND_CART),
473
+ ("0003", "favorites", _SQL_0003_FAVORITES),
474
+ ("0004", "opaque-cart-line-tokens", _migrate_0004_opaque_line_tokens),
475
+ ("0005", "generic-variation-model", _migrate_0005_generic_variation_model),
476
+ ("0006", "command-authority-and-versions", _migrate_0006_command_authority),
477
+ ("0007", "purchase-closure", _migrate_0007_purchase_closure),
478
+ ]
479
+
480
+
481
+ def migrate(conn: sqlite3.Connection, target: str | None = None) -> list[str]:
482
+ """Apply pending migrations up to target (default: head). Idempotent."""
483
+ conn.execute(
484
+ "CREATE TABLE IF NOT EXISTS schema_migrations ("
485
+ " version TEXT PRIMARY KEY,"
486
+ " name TEXT NOT NULL,"
487
+ " applied_at TEXT NOT NULL"
488
+ ")"
489
+ )
490
+ applied = {
491
+ row["version"]
492
+ for row in conn.execute("SELECT version FROM schema_migrations")
493
+ }
494
+ newly_applied: list[str] = []
495
+ for version, name, action in MIGRATIONS:
496
+ if target is not None and version > target:
497
+ break
498
+ if version in applied:
499
+ continue
500
+ if callable(action):
501
+ action(conn)
502
+ else:
503
+ conn.executescript(str(action))
504
+ conn.execute(
505
+ "INSERT INTO schema_migrations (version, name, applied_at) "
506
+ "VALUES (?, ?, ?)",
507
+ (version, name, FROZEN_CLOCK),
508
+ )
509
+ newly_applied.append(version)
510
+ migration_count = int(
511
+ conn.execute("SELECT COUNT(*) FROM schema_migrations").fetchone()[0]
512
+ )
513
+ conn.execute(f"PRAGMA user_version = {migration_count}")
514
+ conn.commit()
515
+ return newly_applied
516
+
517
+
518
+ def applied_migrations(conn: sqlite3.Connection) -> list[str]:
519
+ return [
520
+ row["version"]
521
+ for row in conn.execute(
522
+ "SELECT version FROM schema_migrations ORDER BY version"
523
+ )
524
+ ]
525
+
526
+
527
+ # --- frozen seed corpus --------------------------------------------------------
528
+
529
+
530
+ def _load_capture(name: str) -> dict:
531
+ return json.loads((EMBEDDED / name).read_text(encoding="utf-8"))
532
+
533
+
534
+ def _slug_from_href(href: str) -> str:
535
+ return href.rstrip("/").rsplit("/", 1)[-1]
536
+
537
+
538
+ def _public_badges(badges: list[str]) -> list[str]:
539
+ return [
540
+ badge
541
+ for badge in badges
542
+ if not any(marker in badge.casefold() for marker in CURATION_BADGE_MARKERS)
543
+ ]
544
+
545
+
546
+ def _cents(text: str) -> int:
547
+ return int(Decimal(text.replace(",", "")) * 100)
548
+
549
+
550
+ def _parse_range_cents(label: str) -> tuple[int, int] | None:
551
+ prices = PRICE_RE.findall(label)
552
+ if not prices:
553
+ return None
554
+ return _cents(prices[0]), _cents(prices[-1])
555
+
556
+
557
+ def _seed_search_corpus(conn: sqlite3.Connection) -> dict[str, dict]:
558
+ card_index: dict[str, dict] = {}
559
+ for page_id, file_name in _PAGE_FILES.items():
560
+ capture = _load_capture(file_name)
561
+ conn.execute(
562
+ "INSERT OR IGNORE INTO search_pages (page_id, title, cards_count) "
563
+ "VALUES (?, ?, ?)",
564
+ (page_id, capture["title"], capture["cards_count"]),
565
+ )
566
+ for position, raw in enumerate(capture["cards"]):
567
+ listing_id = raw["listing_id"]
568
+ if page_id == "search-personalized-wallet" and listing_id == _WALLET_ID:
569
+ image = (
570
+ f"{ASSET_WEB_ROOT}/{page_id}/"
571
+ f"listing-{listing_id}-wallet-hero.jpg"
572
+ )
573
+ else:
574
+ image = f"{ASSET_WEB_ROOT}/{page_id}/listing-{listing_id}-card.jpg"
575
+ card = {
576
+ "listing_id": listing_id,
577
+ "title": raw["title"],
578
+ "price_usd": raw["price_usd"],
579
+ "slug": _slug_from_href(raw["href"]),
580
+ "image": image,
581
+ "badges": _public_badges(raw.get("badges", [])),
582
+ }
583
+ card_index.setdefault(listing_id, card)
584
+ conn.execute(
585
+ "INSERT OR IGNORE INTO search_cards "
586
+ "(page_id, position, listing_id, title, price_usd, slug, "
587
+ " image, badges_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
588
+ (
589
+ page_id,
590
+ position,
591
+ listing_id,
592
+ card["title"],
593
+ card["price_usd"],
594
+ card["slug"],
595
+ card["image"],
596
+ json.dumps(card["badges"]),
597
+ ),
598
+ )
599
+ for query_norm, page_id in SEARCH_QUERY_SEED.items():
600
+ conn.execute(
601
+ "INSERT OR IGNORE INTO search_queries (query_norm, page_id) "
602
+ "VALUES (?, ?)",
603
+ (query_norm, page_id),
604
+ )
605
+ return card_index
606
+
607
+
608
+ def _seed_wallet(conn: sqlite3.Connection) -> None:
609
+ """Seed the wallet listing exactly from the 2026-07-25 embedded-browser
610
+ structural capture: variation axes, per-option price ranges, and the
611
+ derived per-combination price grid.
612
+
613
+ Grid derivation (data-driven, no option-name special-cases): every
614
+ engraving option label carries a captured ($low - $high) range; a color
615
+ whose own captured range starts at the listing base price resolves each
616
+ engraving to its low bound, any other color to its high bound. This
617
+ reproduces every captured range endpoint exactly.
618
+ """
619
+ capture = _load_capture("listing-personalized-wallet.json")
620
+ price_now = capture["buy_box"]["price_now"]
621
+ base_cents = _cents(PRICE_RE.findall(price_now)[0])
622
+ quantity_options = []
623
+ axes: list[tuple[str, list[str]]] = []
624
+ for variation in capture["variations"]:
625
+ if variation["label"] == "Quantity":
626
+ quantity_options = list(variation["options"])
627
+ else:
628
+ axes.append((variation["label"], list(variation["options"])))
629
+ max_quantity = max(int(value) for value in quantity_options) if quantity_options else 10
630
+
631
+ conn.execute(
632
+ "INSERT OR IGNORE INTO listings "
633
+ "(listing_id, seller_id, family, task, title, slug, price_now, "
634
+ " price_original, base_price_cents, image, badges_json, cart_enabled, "
635
+ " favorites_focused, version, stock_state, max_quantity) "
636
+ "VALUES (?, ?, 'wallet', '530', ?, ?, ?, ?, ?, ?, ?, 1, 0, ?, "
637
+ " 'in-stock', ?)",
638
+ (
639
+ _WALLET_ID,
640
+ "fixture-seller-wallet",
641
+ capture["h1"],
642
+ _slug_from_href(capture["final_url"]),
643
+ price_now,
644
+ capture["buy_box"]["price_original"],
645
+ base_cents,
646
+ f"{ASSET_WEB_ROOT}/search-personalized-wallet/"
647
+ f"listing-{_WALLET_ID}-wallet-hero.jpg",
648
+ json.dumps(list(capture["buy_box"]["badges"])),
649
+ CURRENT_LISTING_VERSION,
650
+ max_quantity,
651
+ ),
652
+ )
653
+ for axis_position, (label, options) in enumerate(axes):
654
+ conn.execute(
655
+ "INSERT OR IGNORE INTO listing_axes (listing_id, position, "
656
+ "axis_label) VALUES (?, ?, ?)",
657
+ (_WALLET_ID, axis_position, label),
658
+ )
659
+ for position, option in enumerate(options):
660
+ conn.execute(
661
+ "INSERT OR IGNORE INTO listing_options "
662
+ "(listing_id, axis_label, position, value, delta_cents, "
663
+ " selectable) VALUES (?, ?, ?, ?, 0, ?)",
664
+ (
665
+ _WALLET_ID,
666
+ label,
667
+ position,
668
+ option,
669
+ 0 if option == PLACEHOLDER_OPTION else 1,
670
+ ),
671
+ )
672
+
673
+ # Per-combination price grid from the captured per-option ranges.
674
+ axis_map = dict(axes)
675
+ engraving_axis = "Engraving Options"
676
+ color_axis = "Colors"
677
+ engraving_ranges = {
678
+ option: _parse_range_cents(option)
679
+ for option in axis_map[engraving_axis]
680
+ if option != PLACEHOLDER_OPTION
681
+ }
682
+ for color in axis_map[color_axis]:
683
+ if color == PLACEHOLDER_OPTION:
684
+ continue
685
+ color_range = _parse_range_cents(color)
686
+ resolves_low = color_range is not None and color_range[0] == base_cents
687
+ for engraving, engraving_range in engraving_ranges.items():
688
+ if engraving_range is None:
689
+ continue
690
+ unit = engraving_range[0] if resolves_low else engraving_range[1]
691
+ conn.execute(
692
+ "INSERT OR IGNORE INTO listing_combo_prices "
693
+ "(listing_id, combo_key, unit_price_cents) VALUES (?, ?, ?)",
694
+ (
695
+ _WALLET_ID,
696
+ combo_key({engraving_axis: engraving, color_axis: color}),
697
+ unit,
698
+ ),
699
+ )
700
+
701
+ # Personalization: the capture shows a '+ Add personalization'
702
+ # affordance separate from the variations (optional on the source
703
+ # listing). Any text within the limit is accepted verbatim.
704
+ conn.execute(
705
+ "INSERT OR IGNORE INTO listing_personalization "
706
+ "(listing_id, enabled, required, char_limit, prompt) "
707
+ "VALUES (?, 1, 0, 256, 'Add personalization (engraving text)')",
708
+ (_WALLET_ID,),
709
+ )
710
+
711
+
712
+ def _seed_simple_listing(
713
+ conn: sqlite3.Connection,
714
+ card: dict,
715
+ *,
716
+ seller_id: str,
717
+ family: str,
718
+ task: str | None,
719
+ cart_enabled: int = 1,
720
+ favorites_focused: int = 0,
721
+ max_quantity: int = 10,
722
+ ) -> None:
723
+ conn.execute(
724
+ "INSERT OR IGNORE INTO listings "
725
+ "(listing_id, seller_id, family, task, title, slug, price_now, "
726
+ " price_original, base_price_cents, image, badges_json, cart_enabled, "
727
+ " favorites_focused, version, stock_state, max_quantity) "
728
+ "VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, 'in-stock', ?)",
729
+ (
730
+ card["listing_id"],
731
+ seller_id,
732
+ family,
733
+ task,
734
+ card["title"],
735
+ card["slug"],
736
+ f"${card['price_usd']}",
737
+ _cents(card["price_usd"]),
738
+ card["image"],
739
+ json.dumps(card["badges"]),
740
+ cart_enabled,
741
+ favorites_focused,
742
+ CURRENT_LISTING_VERSION,
743
+ max_quantity,
744
+ ),
745
+ )
746
+
747
+
748
+ def seed(conn: sqlite3.Connection, *, commit: bool = True) -> None:
749
+ """Insert the frozen corpus. Idempotent (INSERT OR IGNORE keyed rows)."""
750
+ for seller_id, shop_name in SELLERS:
751
+ conn.execute(
752
+ "INSERT OR IGNORE INTO sellers (seller_id, shop_name, provenance) "
753
+ "VALUES (?, ?, 'fixture-authored')",
754
+ (seller_id, shop_name),
755
+ )
756
+ for account_id, owner_handle, display_name in ACCOUNTS:
757
+ conn.execute(
758
+ "INSERT OR IGNORE INTO accounts "
759
+ "(account_id, owner_handle, display_name) VALUES (?, ?, ?)",
760
+ (account_id, owner_handle, display_name),
761
+ )
762
+
763
+ card_index = _seed_search_corpus(conn)
764
+
765
+ _seed_wallet(conn)
766
+
767
+ # Dog collar: fixture-authored Size axis + required name personalization.
768
+ _seed_simple_listing(
769
+ conn,
770
+ card_index[_COLLAR_ID],
771
+ seller_id="fixture-seller-collar",
772
+ family="collar",
773
+ task="531",
774
+ max_quantity=10,
775
+ )
776
+ conn.execute(
777
+ "INSERT OR IGNORE INTO listing_axes (listing_id, position, axis_label) "
778
+ "VALUES (?, 0, 'Size')",
779
+ (_COLLAR_ID,),
780
+ )
781
+ for position, option in enumerate(COLLAR_SIZE_OPTIONS):
782
+ conn.execute(
783
+ "INSERT OR IGNORE INTO listing_options "
784
+ "(listing_id, axis_label, position, value, delta_cents, "
785
+ " selectable) VALUES (?, 'Size', ?, ?, 0, ?)",
786
+ (_COLLAR_ID, position, option, 0 if option == PLACEHOLDER_OPTION else 1),
787
+ )
788
+ conn.execute(
789
+ "INSERT OR IGNORE INTO listing_personalization "
790
+ "(listing_id, enabled, required, char_limit, prompt) "
791
+ "VALUES (?, 1, 1, 20, 'Name embroidery')",
792
+ (_COLLAR_ID,),
793
+ )
794
+
795
+ # Favorites-focused fixtures are still purchasable: every in-stock detail
796
+ # page exposes the same cart and Buy it now contract.
797
+ _seed_simple_listing(
798
+ conn,
799
+ card_index[_VASE_ID],
800
+ seller_id="fixture-seller-vase",
801
+ family="vase",
802
+ task="535",
803
+ cart_enabled=1,
804
+ favorites_focused=1,
805
+ )
806
+ _seed_simple_listing(
807
+ conn,
808
+ card_index[_BOOKSHELF_ID],
809
+ seller_id="fixture-seller-bookshelf",
810
+ family="bookshelf",
811
+ task="536",
812
+ cart_enabled=1,
813
+ favorites_focused=1,
814
+ )
815
+
816
+ # Every other captured card becomes an ordinary listing row.
817
+ for listing_id, card in card_index.items():
818
+ _seed_simple_listing(
819
+ conn,
820
+ card,
821
+ seller_id="fixture-seller-corpus",
822
+ family="corpus",
823
+ task=None,
824
+ cart_enabled=1,
825
+ )
826
+ if commit:
827
+ conn.commit()
828
+
829
+
830
+ def ensure_ready(path: Path | str | None = None) -> None:
831
+ """Migrate to head and seed the frozen corpus if absent."""
832
+ conn = connect(path)
833
+ try:
834
+ migrate(conn)
835
+ seed(conn)
836
+ finally:
837
+ conn.close()
838
+
839
+
840
+ def drop_order_event_guards(conn: sqlite3.Connection) -> None:
841
+ conn.execute("DROP TRIGGER IF EXISTS order_events_no_update")
842
+ conn.execute("DROP TRIGGER IF EXISTS order_events_no_delete")
843
+
844
+
845
+ def install_order_event_guards(conn: sqlite3.Connection) -> None:
846
+ conn.execute(
847
+ """
848
+ CREATE TRIGGER IF NOT EXISTS order_events_no_update
849
+ BEFORE UPDATE ON order_events
850
+ BEGIN
851
+ SELECT RAISE(ABORT, 'order events are immutable');
852
+ END
853
+ """
854
+ )
855
+ conn.execute(
856
+ """
857
+ CREATE TRIGGER IF NOT EXISTS order_events_no_delete
858
+ BEFORE DELETE ON order_events
859
+ BEGIN
860
+ SELECT RAISE(ABORT, 'order events are immutable');
861
+ END
862
+ """
863
+ )
864
+
865
+
866
+ RESET_TABLE_ORDER = (
867
+ "order_events",
868
+ "order_lines",
869
+ "orders",
870
+ "checkout_lines",
871
+ "checkouts",
872
+ "entity_versions",
873
+ "business_commands",
874
+ "favorites",
875
+ "cart_lines",
876
+ "sessions",
877
+ "listing_unavailable_combos",
878
+ "listing_combo_prices",
879
+ "listing_personalization",
880
+ "listing_options",
881
+ "listing_axes",
882
+ "search_queries",
883
+ "search_cards",
884
+ "search_pages",
885
+ "listings",
886
+ "sellers",
887
+ "accounts",
888
+ )
889
+
890
+
891
+ def reset(path: Path | str | None = None) -> dict:
892
+ """Wipe all mutable and catalog state, then reseed the frozen corpus."""
893
+ conn = connect(path)
894
+ try:
895
+ migrate(conn)
896
+ cleared = {}
897
+ drop_order_event_guards(conn)
898
+ try:
899
+ for table in RESET_TABLE_ORDER:
900
+ cleared[table] = conn.execute(f"DELETE FROM {table}").rowcount
901
+ finally:
902
+ install_order_event_guards(conn)
903
+ conn.commit()
904
+ seed(conn)
905
+ return {"cleared": cleared, "reseeded": True}
906
+ finally:
907
+ conn.close()
908
+
909
+
910
+ # --- server-side domain reads/writes used by the app --------------------------
911
+
912
+
913
+ def get_listing(conn: sqlite3.Connection, listing_id: str) -> sqlite3.Row | None:
914
+ return conn.execute(
915
+ "SELECT * FROM listings WHERE listing_id = ?", (listing_id,)
916
+ ).fetchone()
917
+
918
+
919
+ def listing_axes(conn: sqlite3.Connection, listing_id: str) -> list[dict]:
920
+ axes = []
921
+ for axis in conn.execute(
922
+ "SELECT axis_label, position FROM listing_axes WHERE listing_id = ? "
923
+ "ORDER BY position",
924
+ (listing_id,),
925
+ ):
926
+ options = conn.execute(
927
+ "SELECT value, selectable FROM listing_options "
928
+ "WHERE listing_id = ? AND axis_label = ? ORDER BY position",
929
+ (listing_id, axis["axis_label"]),
930
+ ).fetchall()
931
+ axes.append(
932
+ {
933
+ "label": axis["axis_label"],
934
+ "position": axis["position"],
935
+ "field": f"variation{axis['position']}",
936
+ "options": [
937
+ {"value": row["value"], "selectable": bool(row["selectable"])}
938
+ for row in options
939
+ ],
940
+ }
941
+ )
942
+ return axes
943
+
944
+
945
+ def personalization_config(
946
+ conn: sqlite3.Connection, listing_id: str
947
+ ) -> dict:
948
+ row = conn.execute(
949
+ "SELECT enabled, required, char_limit, prompt "
950
+ "FROM listing_personalization WHERE listing_id = ?",
951
+ (listing_id,),
952
+ ).fetchone()
953
+ if row is None:
954
+ return {"enabled": False, "required": False, "char_limit": 0, "prompt": ""}
955
+ return {
956
+ "enabled": bool(row["enabled"]),
957
+ "required": bool(row["required"]),
958
+ "char_limit": row["char_limit"],
959
+ "prompt": row["prompt"],
960
+ }
961
+
962
+
963
+ def combo_unavailable(
964
+ conn: sqlite3.Connection, listing_id: str, variations: dict[str, str]
965
+ ) -> bool:
966
+ row = conn.execute(
967
+ "SELECT 1 FROM listing_unavailable_combos "
968
+ "WHERE listing_id = ? AND combo_key = ?",
969
+ (listing_id, combo_key(variations)),
970
+ ).fetchone()
971
+ return row is not None
972
+
973
+
974
+ def unit_price_cents(
975
+ conn: sqlite3.Connection, listing_id: str, variations: dict[str, str]
976
+ ) -> int:
977
+ """Server-authoritative unit price: per-combination grid first, else
978
+ base price plus per-option deltas. Client-posted prices are never read."""
979
+ row = conn.execute(
980
+ "SELECT unit_price_cents FROM listing_combo_prices "
981
+ "WHERE listing_id = ? AND combo_key = ?",
982
+ (listing_id, combo_key(variations)),
983
+ ).fetchone()
984
+ if row is not None:
985
+ return row["unit_price_cents"]
986
+ listing = get_listing(conn, listing_id)
987
+ if listing is None:
988
+ raise ValueError(f"unknown listing {listing_id}")
989
+ total = listing["base_price_cents"] or 0
990
+ for axis_label, value in variations.items():
991
+ option = conn.execute(
992
+ "SELECT delta_cents FROM listing_options "
993
+ "WHERE listing_id = ? AND axis_label = ? AND value = ?",
994
+ (listing_id, axis_label, value),
995
+ ).fetchone()
996
+ if option is not None:
997
+ total += option["delta_cents"]
998
+ return total
999
+
1000
+
1001
+ def payload_sha256(payload: dict[str, object]) -> str:
1002
+ encoded = (
1003
+ json.dumps(
1004
+ payload,
1005
+ ensure_ascii=False,
1006
+ separators=(",", ":"),
1007
+ sort_keys=True,
1008
+ )
1009
+ + "\n"
1010
+ ).encode("utf-8")
1011
+ return hashlib.sha256(encoded).hexdigest()
1012
+
1013
+
1014
+ def prior_command(
1015
+ conn: sqlite3.Connection,
1016
+ *,
1017
+ capability: str,
1018
+ owner_scope: str,
1019
+ idempotency_key: str,
1020
+ ) -> sqlite3.Row | None:
1021
+ return conn.execute(
1022
+ "SELECT command_id, payload_sha256, result_json "
1023
+ "FROM business_commands WHERE capability = ? AND owner_scope = ? "
1024
+ "AND idempotency_key = ?",
1025
+ (capability, owner_scope, idempotency_key),
1026
+ ).fetchone()
1027
+
1028
+
1029
+ def entity_version(
1030
+ conn: sqlite3.Connection,
1031
+ *,
1032
+ capability: str,
1033
+ entity_key: str,
1034
+ ) -> int:
1035
+ row = conn.execute(
1036
+ "SELECT version FROM entity_versions "
1037
+ "WHERE capability = ? AND entity_key = ?",
1038
+ (capability, entity_key),
1039
+ ).fetchone()
1040
+ return int(row["version"]) if row is not None else 0
1041
+
1042
+
1043
+ def commit_command(
1044
+ conn: sqlite3.Connection,
1045
+ *,
1046
+ capability: str,
1047
+ owner_scope: str,
1048
+ idempotency_key: str,
1049
+ payload_digest: str,
1050
+ result: dict[str, object],
1051
+ entity_key: str,
1052
+ next_version: int,
1053
+ ) -> str:
1054
+ command_id = uuid.uuid4().hex
1055
+ conn.execute(
1056
+ "INSERT INTO business_commands "
1057
+ "(command_id, capability, owner_scope, idempotency_key, "
1058
+ "payload_sha256, result_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
1059
+ (
1060
+ command_id,
1061
+ capability,
1062
+ owner_scope,
1063
+ idempotency_key,
1064
+ payload_digest,
1065
+ json.dumps(result, ensure_ascii=False, separators=(",", ":"), sort_keys=True),
1066
+ FROZEN_CLOCK,
1067
+ ),
1068
+ )
1069
+ conn.execute(
1070
+ "INSERT INTO entity_versions "
1071
+ "(capability, entity_key, version, command_id, updated_at) "
1072
+ "VALUES (?, ?, ?, ?, ?) "
1073
+ "ON CONFLICT(capability, entity_key) DO UPDATE SET "
1074
+ "version = excluded.version, command_id = excluded.command_id, "
1075
+ "updated_at = excluded.updated_at",
1076
+ (capability, entity_key, next_version, command_id, FROZEN_CLOCK),
1077
+ )
1078
+ return command_id
tasks/etsy/environment/reference/clone/backend/purchases.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Etsy-specific checkout and order closure over the shared payment ledger.
2
+
3
+ The clone owns cart, checkout, address, and immutable order snapshots. The
4
+ vendored ``websitebench.site_backend`` runtime owns site binding and the
5
+ test-only payment state machine. A successful order always consumes the
6
+ matching approval inside the same SQLite transaction that creates the order.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import re
15
+ import secrets
16
+ import sqlite3
17
+ from collections.abc import Mapping
18
+ from typing import Any
19
+
20
+ from websitebench.site_backend import (
21
+ PaymentConflict,
22
+ PaymentError,
23
+ PaymentRejected,
24
+ SiteBackend,
25
+ )
26
+
27
+ from backend import db
28
+
29
+
30
+ SITE_ID = "etsy"
31
+ CURRENCY = "USD"
32
+ SHIPPING_CENTS = 0
33
+ TAX_BASIS_POINTS = 825
34
+ PAYMENT_ADAPTER_ENV = "WEBSITEBENCH_PAYMENT_ADAPTER"
35
+
36
+ _POSTAL_RE = re.compile(r"^[0-9]{5}(?:-[0-9]{4})?$")
37
+ _STATE_RE = re.compile(r"^[A-Z]{2}$")
38
+ _SAFE_SCENARIO_LABELS = {
39
+ "approved": "Approve test payment",
40
+ "declined": "Decline test payment",
41
+ "retryable": "Ask to retry test payment",
42
+ }
43
+
44
+
45
+ class PurchaseError(RuntimeError):
46
+ """The checkout is invalid, stale, foreign, or not payable."""
47
+
48
+
49
+ def _require_transaction(connection: sqlite3.Connection) -> None:
50
+ if not isinstance(connection, sqlite3.Connection) or not connection.in_transaction:
51
+ raise PurchaseError("purchase operation requires an active transaction")
52
+
53
+
54
+ def money(cents: int | str) -> str:
55
+ return f"${int(cents) / 100:.2f}"
56
+
57
+
58
+ def payment_owner(account_id: str) -> str:
59
+ return f"etsy-account:{account_id}"
60
+
61
+
62
+ def payment_adapter(backend: SiteBackend) -> str:
63
+ adapter = str(
64
+ os.environ.get(
65
+ PAYMENT_ADAPTER_ENV,
66
+ backend.config.payments["default_adapter"],
67
+ )
68
+ ).strip()
69
+ if adapter not in {"local-sandbox", "stripe-test"}:
70
+ raise PurchaseError("the configured test payment adapter is invalid")
71
+ if adapter == "stripe-test" and backend.config.payments["stripe_test"] is None:
72
+ raise PurchaseError("Stripe test Checkout is not configured")
73
+ return adapter
74
+
75
+
76
+ def payment_scenarios(backend: SiteBackend) -> tuple[dict[str, str], ...]:
77
+ if payment_adapter(backend) != "local-sandbox":
78
+ return ()
79
+ return tuple(
80
+ {
81
+ "id": str(item["id"]),
82
+ "outcome": str(item["outcome"]),
83
+ "label": _SAFE_SCENARIO_LABELS[str(item["outcome"])],
84
+ }
85
+ for item in backend.config.payments["local_sandbox"]["scenarios"]
86
+ )
87
+
88
+
89
+ def validate_address(values: Mapping[str, str]) -> tuple[dict[str, str], list[str]]:
90
+ address = {
91
+ "name": str(values.get("name", "")).strip(),
92
+ "address1": str(values.get("address1", "")).strip(),
93
+ "address2": str(values.get("address2", "")).strip(),
94
+ "city": str(values.get("city", "")).strip(),
95
+ "state": str(values.get("state", "")).strip().upper(),
96
+ "postal_code": str(values.get("postal_code", "")).strip(),
97
+ "country": "US",
98
+ }
99
+ errors: list[str] = []
100
+ for field, label, maximum in (
101
+ ("name", "Full name", 100),
102
+ ("address1", "Street address", 160),
103
+ ("city", "City", 100),
104
+ ):
105
+ value = address[field]
106
+ if not value or len(value) > maximum or any(ord(char) < 32 for char in value):
107
+ errors.append(f"{label} is required and must be {maximum} characters or fewer.")
108
+ if len(address["address2"]) > 160 or any(
109
+ ord(char) < 32 for char in address["address2"]
110
+ ):
111
+ errors.append("Apartment or suite must be 160 characters or fewer.")
112
+ if _STATE_RE.fullmatch(address["state"]) is None:
113
+ errors.append("State must be a two-letter US abbreviation.")
114
+ if _POSTAL_RE.fullmatch(address["postal_code"]) is None:
115
+ errors.append("ZIP code must be a valid five- or nine-digit US ZIP code.")
116
+ return address, errors
117
+
118
+
119
+ def _cart_rows(connection: sqlite3.Connection, owner_key: str) -> list[sqlite3.Row]:
120
+ return connection.execute(
121
+ "SELECT c.*,l.title,l.slug,l.image,l.stock_state,l.version AS current_version "
122
+ "FROM cart_lines c JOIN listings l ON l.listing_id=c.listing_id "
123
+ "WHERE c.owner_key=? ORDER BY c.rowid",
124
+ (owner_key,),
125
+ ).fetchall()
126
+
127
+
128
+ def _cart_snapshot(
129
+ connection: sqlite3.Connection,
130
+ *,
131
+ account_id: str,
132
+ owner_key: str,
133
+ address: Mapping[str, str],
134
+ ) -> dict[str, Any]:
135
+ rows = _cart_rows(connection, owner_key)
136
+ if not rows:
137
+ raise PurchaseError("Your cart is empty.")
138
+ lines: list[dict[str, Any]] = []
139
+ item_total = 0
140
+ for position, row in enumerate(rows):
141
+ if row["stock_state"] != "in-stock" or row["listing_version"] != row["current_version"]:
142
+ raise PurchaseError("Your cart changed. Refresh it before checkout.")
143
+ subtotal = int(row["unit_price_cents"]) * int(row["quantity"])
144
+ item_total += subtotal
145
+ lines.append(
146
+ {
147
+ "position": position,
148
+ "cart_line_token": str(row["line_token"]),
149
+ "listing_id": str(row["listing_id"]),
150
+ "listing_version": str(row["listing_version"]),
151
+ "title": str(row["title"]),
152
+ "slug": str(row["slug"]),
153
+ "image": str(row["image"]),
154
+ "variations_json": str(row["variations_json"]),
155
+ "personalization": str(row["personalization"]),
156
+ "quantity": int(row["quantity"]),
157
+ "unit_price_cents": int(row["unit_price_cents"]),
158
+ "subtotal_cents": subtotal,
159
+ }
160
+ )
161
+ tax = (item_total * TAX_BASIS_POINTS + 5_000) // 10_000
162
+ total = item_total + SHIPPING_CENTS + tax
163
+ canonical = {
164
+ "site_id": SITE_ID,
165
+ "account_id": account_id,
166
+ "currency": CURRENCY,
167
+ "address": dict(address),
168
+ "lines": lines,
169
+ "item_total_cents": item_total,
170
+ "shipping_cents": SHIPPING_CENTS,
171
+ "tax_cents": tax,
172
+ "total_cents": total,
173
+ }
174
+ fingerprint = hashlib.sha256(
175
+ json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode("utf-8")
176
+ ).hexdigest()
177
+ return {**canonical, "fingerprint": fingerprint}
178
+
179
+
180
+ def create_checkout(
181
+ connection: sqlite3.Connection,
182
+ backend: SiteBackend,
183
+ *,
184
+ account_id: str,
185
+ owner_key: str,
186
+ address: Mapping[str, str],
187
+ ) -> dict[str, Any]:
188
+ _require_transaction(connection)
189
+ snapshot = _cart_snapshot(
190
+ connection,
191
+ account_id=account_id,
192
+ owner_key=owner_key,
193
+ address=address,
194
+ )
195
+ existing = connection.execute(
196
+ "SELECT * FROM checkouts WHERE account_id=? AND cart_fingerprint=?",
197
+ (account_id, snapshot["fingerprint"]),
198
+ ).fetchone()
199
+ if existing is not None:
200
+ return dict(existing)
201
+
202
+ checkout_id = f"checkout_{secrets.token_urlsafe(18)}"
203
+ adapter = payment_adapter(backend)
204
+ try:
205
+ flow = backend.payments.create_intent(
206
+ owner=payment_owner(account_id),
207
+ amount_minor=int(snapshot["total_cents"]),
208
+ currency=CURRENCY,
209
+ fingerprint=str(snapshot["fingerprint"]),
210
+ idempotency_key=f"etsy-checkout:{snapshot['fingerprint'][:48]}",
211
+ adapter=adapter,
212
+ connection=connection,
213
+ )
214
+ except (PaymentConflict, PaymentError, PaymentRejected) as exc:
215
+ raise PurchaseError("The test payment flow could not be created.") from exc
216
+
217
+ address_json = json.dumps(dict(address), sort_keys=True, separators=(",", ":"))
218
+ connection.execute(
219
+ "INSERT INTO checkouts(checkout_id,account_id,status,currency,item_total_cents,"
220
+ "shipping_cents,tax_cents,total_cents,cart_fingerprint,address_json,"
221
+ "payment_flow_id,version,created_at,updated_at) "
222
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,1,?,?)",
223
+ (
224
+ checkout_id,
225
+ account_id,
226
+ "pending-payment",
227
+ CURRENCY,
228
+ snapshot["item_total_cents"],
229
+ snapshot["shipping_cents"],
230
+ snapshot["tax_cents"],
231
+ snapshot["total_cents"],
232
+ snapshot["fingerprint"],
233
+ address_json,
234
+ flow["flow_id"],
235
+ db.FROZEN_CLOCK,
236
+ db.FROZEN_CLOCK,
237
+ ),
238
+ )
239
+ for line in snapshot["lines"]:
240
+ connection.execute(
241
+ "INSERT INTO checkout_lines(checkout_id,position,cart_line_token,listing_id,"
242
+ "listing_version,title,slug,image,variations_json,personalization,quantity,"
243
+ "unit_price_cents,subtotal_cents) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
244
+ (
245
+ checkout_id,
246
+ line["position"],
247
+ line["cart_line_token"],
248
+ line["listing_id"],
249
+ line["listing_version"],
250
+ line["title"],
251
+ line["slug"],
252
+ line["image"],
253
+ line["variations_json"],
254
+ line["personalization"],
255
+ line["quantity"],
256
+ line["unit_price_cents"],
257
+ line["subtotal_cents"],
258
+ ),
259
+ )
260
+ return dict(
261
+ connection.execute(
262
+ "SELECT * FROM checkouts WHERE checkout_id=?", (checkout_id,)
263
+ ).fetchone()
264
+ )
265
+
266
+
267
+ def checkout_for_owner(
268
+ connection: sqlite3.Connection, account_id: str, checkout_id: str
269
+ ) -> dict[str, Any] | None:
270
+ row = connection.execute(
271
+ "SELECT * FROM checkouts WHERE checkout_id=? AND account_id=?",
272
+ (checkout_id, account_id),
273
+ ).fetchone()
274
+ return dict(row) if row is not None else None
275
+
276
+
277
+ def checkout_lines(connection: sqlite3.Connection, checkout_id: str) -> list[dict[str, Any]]:
278
+ return [
279
+ dict(row)
280
+ for row in connection.execute(
281
+ "SELECT * FROM checkout_lines WHERE checkout_id=? ORDER BY position",
282
+ (checkout_id,),
283
+ )
284
+ ]
285
+
286
+
287
+ def decorate_checkout(
288
+ connection: sqlite3.Connection, checkout: Mapping[str, Any]
289
+ ) -> dict[str, Any]:
290
+ value = dict(checkout)
291
+ value["address"] = json.loads(str(value["address_json"]))
292
+ value["lines"] = checkout_lines(connection, str(value["checkout_id"]))
293
+ for line in value["lines"]:
294
+ line["summary"] = _line_summary(line)
295
+ line["unit_price"] = money(line["unit_price_cents"])
296
+ line["subtotal"] = money(line["subtotal_cents"])
297
+ for key in ("item_total", "shipping", "tax", "total"):
298
+ value[key] = money(value[f"{key}_cents"])
299
+ return value
300
+
301
+
302
+ def _line_summary(line: Mapping[str, Any]) -> str:
303
+ variations = json.loads(str(line["variations_json"]))
304
+ parts = [f"{label}: {value}" for label, value in variations.items()]
305
+ if line.get("personalization"):
306
+ parts.append(f"Personalization: {line['personalization']}")
307
+ return " · ".join(parts)
308
+
309
+
310
+ def _checkout_is_current(
311
+ connection: sqlite3.Connection,
312
+ checkout: Mapping[str, Any],
313
+ ) -> bool:
314
+ expected = checkout_lines(connection, str(checkout["checkout_id"]))
315
+ owner_key = f"account:{checkout['account_id']}"
316
+ current = _cart_rows(connection, owner_key)
317
+ if len(current) != len(expected):
318
+ return False
319
+ for row, line in zip(current, expected, strict=True):
320
+ if (
321
+ str(row["line_token"]) != str(line["cart_line_token"])
322
+ or str(row["listing_id"]) != str(line["listing_id"])
323
+ or str(row["listing_version"]) != str(line["listing_version"])
324
+ or str(row["current_version"]) != str(line["listing_version"])
325
+ or str(row["stock_state"]) != "in-stock"
326
+ or str(row["variations_json"]) != str(line["variations_json"])
327
+ or str(row["personalization"]) != str(line["personalization"])
328
+ or int(row["quantity"]) != int(line["quantity"])
329
+ or int(row["unit_price_cents"]) != int(line["unit_price_cents"])
330
+ ):
331
+ return False
332
+ return True
333
+
334
+
335
+ def _mark_nonapproved(
336
+ connection: sqlite3.Connection, checkout_id: str, outcome: str
337
+ ) -> None:
338
+ status = "payment-declined" if outcome == "DECLINED" else "payment-retry"
339
+ connection.execute(
340
+ "UPDATE checkouts SET status=?,version=version+1,updated_at=? "
341
+ "WHERE checkout_id=? AND status!='completed'",
342
+ (status, db.FROZEN_CLOCK, checkout_id),
343
+ )
344
+
345
+
346
+ def _finalize_order(
347
+ connection: sqlite3.Connection,
348
+ backend: SiteBackend,
349
+ *,
350
+ checkout: Mapping[str, Any],
351
+ ) -> dict[str, Any]:
352
+ _require_transaction(connection)
353
+ existing = connection.execute(
354
+ "SELECT * FROM orders WHERE checkout_id=? AND account_id=?",
355
+ (checkout["checkout_id"], checkout["account_id"]),
356
+ ).fetchone()
357
+ if existing is not None:
358
+ return dict(existing)
359
+ if checkout["status"] == "completed" or not _checkout_is_current(connection, checkout):
360
+ raise PurchaseError("The checkout is stale or already completed.")
361
+ try:
362
+ payment = backend.payments.consume_approval(
363
+ connection,
364
+ flow_id=str(checkout["payment_flow_id"]),
365
+ owner=payment_owner(str(checkout["account_id"])),
366
+ amount_minor=int(checkout["total_cents"]),
367
+ currency=str(checkout["currency"]),
368
+ fingerprint=str(checkout["cart_fingerprint"]),
369
+ )
370
+ except (PaymentConflict, PaymentError, PaymentRejected) as exc:
371
+ raise PurchaseError("The test payment approval is missing or stale.") from exc
372
+
373
+ order_id = f"order_{secrets.token_urlsafe(18)}"
374
+ connection.execute(
375
+ "INSERT INTO orders(order_id,account_id,checkout_id,payment_flow_id,status,"
376
+ "currency,item_total_cents,shipping_cents,tax_cents,total_cents,address_json,placed_at) "
377
+ "VALUES (?,?,?,?, 'paid',?,?,?,?,?,?,?)",
378
+ (
379
+ order_id,
380
+ checkout["account_id"],
381
+ checkout["checkout_id"],
382
+ checkout["payment_flow_id"],
383
+ checkout["currency"],
384
+ checkout["item_total_cents"],
385
+ checkout["shipping_cents"],
386
+ checkout["tax_cents"],
387
+ checkout["total_cents"],
388
+ checkout["address_json"],
389
+ db.FROZEN_CLOCK,
390
+ ),
391
+ )
392
+ lines = checkout_lines(connection, str(checkout["checkout_id"]))
393
+ for line in lines:
394
+ connection.execute(
395
+ "INSERT INTO order_lines(order_id,position,listing_id,listing_version,title,"
396
+ "slug,image,variations_json,personalization,quantity,unit_price_cents,"
397
+ "subtotal_cents) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
398
+ (
399
+ order_id,
400
+ line["position"],
401
+ line["listing_id"],
402
+ line["listing_version"],
403
+ line["title"],
404
+ line["slug"],
405
+ line["image"],
406
+ line["variations_json"],
407
+ line["personalization"],
408
+ line["quantity"],
409
+ line["unit_price_cents"],
410
+ line["subtotal_cents"],
411
+ ),
412
+ )
413
+ connection.execute(
414
+ "DELETE FROM cart_lines WHERE line_token=? AND owner_key=?",
415
+ (line["cart_line_token"], f"account:{checkout['account_id']}"),
416
+ )
417
+ event_snapshot = {
418
+ "site_id": SITE_ID,
419
+ "order_id": order_id,
420
+ "checkout_id": checkout["checkout_id"],
421
+ "payment_flow_id": checkout["payment_flow_id"],
422
+ "payment_attempt_id": payment["attempt_id"],
423
+ "total_cents": int(checkout["total_cents"]),
424
+ "currency": CURRENCY,
425
+ "is_simulation": True,
426
+ }
427
+ connection.execute(
428
+ "INSERT INTO order_events(event_id,order_id,event_type,snapshot_json,created_at) "
429
+ "VALUES (?,?,'order-created',?,?)",
430
+ (
431
+ f"orderevt_{secrets.token_urlsafe(18)}",
432
+ order_id,
433
+ json.dumps(event_snapshot, sort_keys=True, separators=(",", ":")),
434
+ db.FROZEN_CLOCK,
435
+ ),
436
+ )
437
+ connection.execute(
438
+ "UPDATE checkouts SET status='completed',version=version+1,updated_at=? "
439
+ "WHERE checkout_id=?",
440
+ (db.FROZEN_CLOCK, checkout["checkout_id"]),
441
+ )
442
+ return dict(
443
+ connection.execute("SELECT * FROM orders WHERE order_id=?", (order_id,)).fetchone()
444
+ )
445
+
446
+
447
+ def attempt_local_payment(
448
+ connection: sqlite3.Connection,
449
+ backend: SiteBackend,
450
+ *,
451
+ account_id: str,
452
+ checkout_id: str,
453
+ scenario_id: str,
454
+ ) -> tuple[str, dict[str, Any] | None]:
455
+ _require_transaction(connection)
456
+ checkout = checkout_for_owner(connection, account_id, checkout_id)
457
+ if checkout is None:
458
+ raise PurchaseError("Checkout not found.")
459
+ existing = connection.execute(
460
+ "SELECT * FROM orders WHERE checkout_id=? AND account_id=?",
461
+ (checkout_id, account_id),
462
+ ).fetchone()
463
+ if existing is not None:
464
+ return "APPROVED", dict(existing)
465
+ if payment_adapter(backend) != "local-sandbox":
466
+ raise PurchaseError("Local test payment is not enabled.")
467
+ if not _checkout_is_current(connection, checkout):
468
+ connection.execute(
469
+ "UPDATE checkouts SET status='stale',version=version+1,updated_at=? "
470
+ "WHERE checkout_id=? AND status!='completed'",
471
+ (db.FROZEN_CLOCK, checkout_id),
472
+ )
473
+ raise PurchaseError("Your cart changed. Start checkout again.")
474
+ allowed = {item["id"] for item in payment_scenarios(backend)}
475
+ if scenario_id not in allowed:
476
+ raise PurchaseError("Choose a valid test payment outcome.")
477
+ try:
478
+ attempt = backend.payments.attempt(
479
+ flow_id=str(checkout["payment_flow_id"]),
480
+ owner=payment_owner(account_id),
481
+ amount_minor=int(checkout["total_cents"]),
482
+ currency=CURRENCY,
483
+ fingerprint=str(checkout["cart_fingerprint"]),
484
+ scenario_id=scenario_id,
485
+ idempotency_key=f"etsy-attempt:{checkout_id}:{scenario_id}",
486
+ connection=connection,
487
+ )
488
+ except (PaymentConflict, PaymentError, PaymentRejected) as exc:
489
+ raise PurchaseError("The test payment attempt was rejected.") from exc
490
+ outcome = str(attempt["status"])
491
+ if outcome == "APPROVED":
492
+ return outcome, _finalize_order(connection, backend, checkout=checkout)
493
+ _mark_nonapproved(connection, checkout_id, outcome)
494
+ return outcome, None
495
+
496
+
497
+ def approve_verified_stripe(
498
+ connection: sqlite3.Connection,
499
+ backend: SiteBackend,
500
+ *,
501
+ checkout: Mapping[str, Any],
502
+ provider_session_id: str,
503
+ provider_snapshot: Mapping[str, Any],
504
+ ) -> dict[str, Any]:
505
+ _require_transaction(connection)
506
+ account_id = str(checkout["account_id"])
507
+ existing = connection.execute(
508
+ "SELECT * FROM orders WHERE checkout_id=? AND account_id=?",
509
+ (checkout["checkout_id"], account_id),
510
+ ).fetchone()
511
+ if existing is not None:
512
+ return dict(existing)
513
+ if payment_adapter(backend) != "stripe-test" or not _checkout_is_current(
514
+ connection, checkout
515
+ ):
516
+ raise PurchaseError("Stripe test checkout is stale or unavailable.")
517
+ try:
518
+ attempt = backend.payments.attempt_verified_stripe(
519
+ flow_id=str(checkout["payment_flow_id"]),
520
+ owner=payment_owner(account_id),
521
+ amount_minor=int(checkout["total_cents"]),
522
+ currency=CURRENCY,
523
+ fingerprint=str(checkout["cart_fingerprint"]),
524
+ provider_session_id=provider_session_id,
525
+ idempotency_key=f"etsy-stripe:{checkout['checkout_id']}:{provider_session_id}",
526
+ provider_verifier=lambda _session_id: provider_snapshot,
527
+ connection=connection,
528
+ )
529
+ except (PaymentConflict, PaymentError, PaymentRejected) as exc:
530
+ raise PurchaseError("The Stripe test Session was rejected.") from exc
531
+ if str(attempt["status"]) != "APPROVED":
532
+ raise PurchaseError("The Stripe test Session was not paid.")
533
+ return _finalize_order(connection, backend, checkout=checkout)
534
+
535
+
536
+ def checkout_by_flow(
537
+ connection: sqlite3.Connection, flow_id: str
538
+ ) -> dict[str, Any] | None:
539
+ row = connection.execute(
540
+ "SELECT * FROM checkouts WHERE payment_flow_id=?", (flow_id,)
541
+ ).fetchone()
542
+ return dict(row) if row is not None else None
543
+
544
+
545
+ def payment_flow(
546
+ connection: sqlite3.Connection, checkout: Mapping[str, Any]
547
+ ) -> dict[str, Any]:
548
+ """Return the immutable public flow facts used by the Stripe gateway."""
549
+ row = connection.execute(
550
+ "SELECT flow_id,site_id,owner,amount_minor,currency,fingerprint,adapter,"
551
+ "status,is_simulation FROM websitebench_payment_flows "
552
+ "WHERE flow_id=? AND site_id=?",
553
+ (checkout["payment_flow_id"], SITE_ID),
554
+ ).fetchone()
555
+ if row is None:
556
+ raise PurchaseError("The test payment flow is missing.")
557
+ value = dict(row)
558
+ value["is_simulation"] = bool(value["is_simulation"])
559
+ return value
560
+
561
+
562
+ def order_for_owner(
563
+ connection: sqlite3.Connection, account_id: str, order_id: str
564
+ ) -> dict[str, Any] | None:
565
+ row = connection.execute(
566
+ "SELECT * FROM orders WHERE order_id=? AND account_id=?",
567
+ (order_id, account_id),
568
+ ).fetchone()
569
+ if row is None:
570
+ return None
571
+ value = dict(row)
572
+ value["address"] = json.loads(str(value["address_json"]))
573
+ value["lines"] = [
574
+ dict(line)
575
+ for line in connection.execute(
576
+ "SELECT * FROM order_lines WHERE order_id=? ORDER BY position", (order_id,)
577
+ )
578
+ ]
579
+ for line in value["lines"]:
580
+ line["summary"] = _line_summary(line)
581
+ line["unit_price"] = money(line["unit_price_cents"])
582
+ line["subtotal"] = money(line["subtotal_cents"])
583
+ for key in ("item_total", "shipping", "tax", "total"):
584
+ value[key] = money(value[f"{key}_cents"])
585
+ return value
586
+
587
+
588
+ def orders_for_owner(connection: sqlite3.Connection, account_id: str) -> list[dict[str, Any]]:
589
+ orders: list[dict[str, Any]] = []
590
+ for row in connection.execute(
591
+ "SELECT * FROM orders WHERE account_id=? ORDER BY placed_at DESC,order_id DESC",
592
+ (account_id,),
593
+ ):
594
+ order = dict(row)
595
+ order["total"] = money(order["total_cents"])
596
+ order["line_count"] = int(
597
+ connection.execute(
598
+ "SELECT COUNT(*) FROM order_lines WHERE order_id=?", (order["order_id"],)
599
+ ).fetchone()[0]
600
+ )
601
+ orders.append(order)
602
+ return orders
603
+
604
+
605
+ __all__ = [
606
+ "CURRENCY",
607
+ "PurchaseError",
608
+ "approve_verified_stripe",
609
+ "attempt_local_payment",
610
+ "checkout_by_flow",
611
+ "checkout_for_owner",
612
+ "checkout_lines",
613
+ "create_checkout",
614
+ "decorate_checkout",
615
+ "money",
616
+ "order_for_owner",
617
+ "orders_for_owner",
618
+ "payment_adapter",
619
+ "payment_flow",
620
+ "payment_owner",
621
+ "payment_scenarios",
622
+ "validate_address",
623
+ ]
tasks/etsy/environment/reference/clone/backend/site_backend_integration.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 contextlib import closing
10
+ from pathlib import Path
11
+ from typing import Any, Callable
12
+
13
+ from websitebench.local_clone_auth import LocalAuthStore
14
+ from websitebench.site_backend import SiteBackend, SiteBindingError, load_runtime
15
+ from websitebench.site_backend.copy_cutover import (
16
+ CopyCutoverError,
17
+ publish_transformed_sqlite_copy,
18
+ )
19
+ from websitebench.site_backend.database import BASE_SCHEMA, utc_now
20
+
21
+
22
+ DEFAULT_RUNTIME_PATH = Path(__file__).resolve().parents[2] / "backend" / "runtime.json"
23
+ LEGACY_DATABASE_FILENAME = "etsy.sqlite3"
24
+ CANONICAL_DATABASE_FILENAME = "websitebench-etsy.sqlite3"
25
+ LEGACY_BACKUP_SUFFIX = ".etsy-unbound-legacy"
26
+
27
+
28
+ def _declared_hook(
29
+ declaration: str | None,
30
+ ) -> Callable[[sqlite3.Connection], None] | None:
31
+ if declaration is None:
32
+ return None
33
+ module_name, function_name = declaration.split(":", 1)
34
+ module = importlib.import_module(module_name)
35
+ hook: Any = getattr(module, function_name, None)
36
+ if not callable(hook):
37
+ raise RuntimeError(f"declared backend hook is not callable: {declaration}")
38
+ actual = f"{hook.__module__}:{hook.__name__}"
39
+ if actual != declaration:
40
+ raise RuntimeError(
41
+ f"declared backend hook resolved as {actual!r}, expected {declaration!r}"
42
+ )
43
+ return hook
44
+
45
+
46
+ def _legacy_etsy_prefix_connection(connection: sqlite3.Connection) -> None:
47
+ """Verify Etsy's own ordered business migrations before copy binding."""
48
+
49
+ tables = {
50
+ str(row[0])
51
+ for row in connection.execute(
52
+ "SELECT name FROM sqlite_master WHERE type='table'"
53
+ )
54
+ }
55
+ if "websitebench_site_binding" in tables:
56
+ raise SiteBindingError("legacy Etsy source is already site-bound")
57
+ if "clawbench_site_binding" in tables:
58
+ raise SiteBindingError("Etsy database uses the other runtime namespace")
59
+ if not {"schema_migrations", "listings", "accounts"}.issubset(tables):
60
+ raise SiteBindingError(
61
+ "unbound database does not match the Etsy business schema"
62
+ )
63
+ rows = connection.execute(
64
+ "SELECT version,name FROM schema_migrations ORDER BY version"
65
+ ).fetchall()
66
+ from backend.db import MIGRATIONS
67
+
68
+ expected = [(version, name) for version, name, _action in MIGRATIONS]
69
+ actual = [(str(row[0]), str(row[1])) for row in rows]
70
+ if not actual or actual != expected[: len(actual)]:
71
+ raise SiteBindingError("unbound database has an invalid Etsy migration prefix")
72
+
73
+
74
+ def _bind_legacy_etsy_copy(
75
+ source: Path,
76
+ canonical: Path,
77
+ *,
78
+ site_id: str,
79
+ ) -> bool:
80
+ if not source.exists():
81
+ return False
82
+
83
+ def transform(database: Path) -> None:
84
+ with closing(sqlite3.connect(database, isolation_level=None)) as connection:
85
+ connection.execute("PRAGMA foreign_keys=ON")
86
+ connection.executescript(BASE_SCHEMA)
87
+ connection.execute("BEGIN IMMEDIATE")
88
+ try:
89
+ connection.execute(
90
+ "INSERT INTO websitebench_site_binding"
91
+ "(singleton,site_id,bound_at) VALUES (1,?,?)",
92
+ (site_id, utc_now()),
93
+ )
94
+ connection.execute(
95
+ "INSERT OR IGNORE INTO websitebench_backend_migrations"
96
+ "(migration_id,applied_at) VALUES ('site-backend-v1',?)",
97
+ (utc_now(),),
98
+ )
99
+ if connection.execute("PRAGMA foreign_key_check").fetchall():
100
+ raise SiteBindingError("Etsy copy has foreign-key violations")
101
+ connection.execute("COMMIT")
102
+ except BaseException:
103
+ if connection.in_transaction:
104
+ connection.execute("ROLLBACK")
105
+ raise
106
+
107
+ def validate_canonical(database: Path) -> None:
108
+ with closing(sqlite3.connect(database)) as connection:
109
+ binding = connection.execute(
110
+ "SELECT singleton,site_id FROM websitebench_site_binding"
111
+ ).fetchall()
112
+ integrity = connection.execute("PRAGMA integrity_check").fetchall()
113
+ foreign_keys = connection.execute("PRAGMA foreign_key_check").fetchall()
114
+ if binding != [(1, site_id)] or integrity != [("ok",)] or foreign_keys:
115
+ raise SiteBindingError("Etsy copy failed integrity validation")
116
+
117
+ try:
118
+ publish_transformed_sqlite_copy(
119
+ source,
120
+ canonical,
121
+ expected_source_name=LEGACY_DATABASE_FILENAME,
122
+ expected_canonical_name=CANONICAL_DATABASE_FILENAME,
123
+ transform=transform,
124
+ validate_source=_legacy_etsy_prefix_connection,
125
+ validate_canonical=validate_canonical,
126
+ reserved_paths=(source.with_name(source.name + LEGACY_BACKUP_SUFFIX),),
127
+ )
128
+ except CopyCutoverError as exc:
129
+ raise SiteBindingError(str(exc)) from exc
130
+ return True
131
+
132
+
133
+ def open_site_services(
134
+ database_path: Path | None = None,
135
+ ) -> tuple[SiteBackend, LocalAuthStore]:
136
+ """Open one bound database; never omit the site id for permanent auth.
137
+
138
+ Etsy predates the shared runtime. Its business schema is initialized
139
+ before this seam is called; the one-time legacy path binds that same file
140
+ to Etsy and adds the WebsiteBench payment ledger. Every later open fails
141
+ closed if the database belongs to another site.
142
+ """
143
+
144
+ runtime_path = Path(
145
+ os.environ.get(
146
+ "WEBSITEBENCH_SITE_BACKEND_RUNTIME",
147
+ str(DEFAULT_RUNTIME_PATH),
148
+ )
149
+ ).resolve()
150
+ runtime = load_runtime(runtime_path)
151
+ migration_hook = _declared_hook(runtime.migration_hook)
152
+ seed_hook = _declared_hook(runtime.seed_hook)
153
+ deployed_database = (
154
+ str(database_path.resolve())
155
+ if database_path is not None
156
+ else os.environ.get("WEBSITEBENCH_SITE_BACKEND_DATABASE")
157
+ )
158
+ if deployed_database is None:
159
+ backend = SiteBackend.open(
160
+ runtime_path,
161
+ migration_hook=migration_hook,
162
+ seed_hook=seed_hook,
163
+ )
164
+ else:
165
+ database_path = Path(deployed_database).resolve()
166
+ if database_path.name != runtime.database_filename:
167
+ raise RuntimeError(
168
+ "deployed database filename does not match runtime contract"
169
+ )
170
+ legacy_database = database_path.with_name(LEGACY_DATABASE_FILENAME)
171
+ if not database_path.exists() and legacy_database.exists():
172
+ _bind_legacy_etsy_copy(
173
+ legacy_database,
174
+ database_path,
175
+ site_id=runtime.site_id,
176
+ )
177
+ backend = SiteBackend.open(
178
+ json.loads(runtime_path.read_text(encoding="utf-8")),
179
+ data_root=database_path.parent,
180
+ migration_hook=migration_hook,
181
+ seed_hook=seed_hook,
182
+ )
183
+ if backend.lifecycle.database_path != database_path:
184
+ raise RuntimeError(
185
+ "deployed database path does not match backend preflight"
186
+ )
187
+ backend.lifecycle.initialize()
188
+ auth = LocalAuthStore(
189
+ backend.lifecycle.database_path,
190
+ site_id=backend.config.site_id,
191
+ )
192
+ # Etsy's existing clone auth runtime owns its historical local-auth
193
+ # schema. The WebsiteBench seam is opened here for site binding/payment,
194
+ # but must not pre-create a conflicting auth schema before the app opens
195
+ # its site-owned compatibility store.
196
+ return backend, auth
tasks/etsy/environment/reference/clone/frontend/templates/_auth_providers.html ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#
2
+ Provider row, in the order the 2026-08-06 capture records for both panes:
3
+ Google, Facebook, Apple. See
4
+ materials/etsy/artifacts/parity/auth/{signin,register}/desktop/structure.json.
5
+
6
+ Each is a real <a href>, keyboard reachable and working with scripting
7
+ unavailable. It lands on this site's existing honest terminus, /unavailable,
8
+ which states the control is not available here. Nothing here authenticates,
9
+ and no provider button is ever rendered as an inert element.
10
+ #}
11
+ <div class="auth-providers">
12
+ <a class="auth-provider auth-provider-google"
13
+ href="/unavailable?capability=third-party-sign-in&amp;label=Continue+with+Google">
14
+ <span class="auth-provider-glyph" aria-hidden="true">
15
+ <svg viewBox="0 0 18 18" width="18" height="18">
16
+ <path fill="#4285f4" d="M17.64 9.205c0-.638-.057-1.252-.164-1.841H9v3.482h4.844a4.14 4.14 0 0 1-1.797 2.715v2.258h2.909c1.702-1.567 2.684-3.875 2.684-6.614Z"/>
17
+ <path fill="#34a853" d="M9 18c2.43 0 4.468-.806 5.956-2.181l-2.909-2.258c-.806.54-1.835.859-3.047.859-2.344 0-4.328-1.585-5.037-3.714H.957v2.332A9 9 0 0 0 9 18Z"/>
18
+ <path fill="#fbbc05" d="M3.963 10.706A5.41 5.41 0 0 1 3.682 9c0-.592.102-1.168.281-1.706V4.962H.957A9 9 0 0 0 0 9c0 1.45.347 2.824.957 4.038l3.006-2.332Z"/>
19
+ <path fill="#ea4335" d="M9 3.58c1.321 0 2.508.454 3.441 1.346l2.581-2.582C13.464.892 11.426 0 9 0A9 9 0 0 0 .957 4.962l3.006 2.332C4.672 5.165 6.656 3.58 9 3.58Z"/>
20
+ </svg>
21
+ </span>
22
+ <span class="auth-provider-label">Continue with Google</span>
23
+ </a>
24
+ <a class="auth-provider auth-provider-facebook"
25
+ href="/unavailable?capability=third-party-sign-in&amp;label=Continue+with+Facebook">
26
+ <span class="auth-provider-glyph" aria-hidden="true">
27
+ <svg viewBox="0 0 24 24" width="18" height="18">
28
+ <path fill="#1877f2" d="M22 12C22 6.48 17.52 2 12 2C6.48 2 2 6.48 2 12C2 16.84 5.44 20.87 10 21.8V15H8V12H10V9.5C10 7.57 11.57 6 13.5 6H16V9H14C13.45 9 13 9.45 13 10V12H16V15H13V21.95C18.05 21.45 22 17.19 22 12Z"/>
29
+ </svg>
30
+ </span>
31
+ <span class="auth-provider-label">Continue with Facebook</span>
32
+ </a>
33
+ <a class="auth-provider auth-provider-apple"
34
+ href="/unavailable?capability=third-party-sign-in&amp;label=Continue+with+Apple">
35
+ <span class="auth-provider-glyph" aria-hidden="true">
36
+ <svg viewBox="0 0 24 24" width="18" height="18">
37
+ <path fill="currentColor" d="M16.365 1.43c0 1.14-.42 2.2-1.26 3.06-.9.93-1.98 1.47-3.15 1.38-.03-1.11.42-2.22 1.23-3.03.87-.9 2.07-1.5 3.18-1.41Zm3.9 16.02c-.57 1.29-.84 1.86-1.56 2.99-1.02 1.56-2.46 3.51-4.23 3.52-1.59.02-2-1.03-4.14-1.02-2.13.01-2.58 1.04-4.17 1.02-1.77-.02-3.15-1.77-4.17-3.33C-.72 16.29-1.02 11.1 1.14 8.34c1.02-1.32 2.64-2.16 4.14-2.16 1.53 0 2.49 1.02 4.11 1.02 1.56 0 2.31-1.02 4.14-1.02 1.35 0 2.79.72 3.81 1.98-3.36 1.83-2.82 6.6.93 8.16-.01.01-.01.02-.01.03Z"/>
38
+ </svg>
39
+ </span>
40
+ <span class="auth-provider-label">Continue with Apple</span>
41
+ </a>
42
+ </div>
tasks/etsy/environment/reference/clone/frontend/templates/base.html ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en-US" data-site="etsy" data-version="{{ version }}">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>{{ page_title }}</title>
7
+ <link rel="icon" type="image/png" sizes="32x32" href="/static/assets/source-current/2026-07-25/shared/etsy-favicon-32x32.png">
8
+ <link rel="icon" type="image/png" sizes="16x16" href="/static/assets/source-current/2026-07-25/shared/etsy-favicon-16x16.png">
9
+ <link rel="apple-touch-icon" href="/static/assets/source-current/2026-07-25/shared/etsy-logo-touch-icon.png">
10
+ <link rel="stylesheet" href="/static/styles.css">
11
+ <script defer src="/static/app.js"></script>
12
+ </head>
13
+ <body>
14
+ <a class="skip-link" href="#main-content">Skip to Content</a>
15
+ <header class="site-header">
16
+ <div class="header-row">
17
+ <a class="brand" href="/" aria-label="Etsy home">Etsy</a>
18
+ <div class="category-control">
19
+ <button class="cat-toggle" type="button" aria-expanded="false" aria-controls="category-menu">
20
+ <span class="menu-glyph" aria-hidden="true">☰</span> Categories
21
+ </button>
22
+ <nav id="category-menu" class="category-menu" aria-label="Shop categories" hidden>
23
+ {% for label, slug in category_menu %}
24
+ <a href="/c/{{ slug }}">{{ label }}</a>
25
+ {% endfor %}
26
+ </nav>
27
+ </div>
28
+ {#
29
+ A plain GET form that works with scripting unavailable. The
30
+ combobox wiring is enhancement only, and reads its endpoint from a
31
+ data- attribute so the route is never hardcoded in the script.
32
+ #}
33
+ <form class="header-search" action="/search" method="get" role="search"
34
+ data-search-band data-suggest-endpoint="/api/search/suggest">
35
+ <label class="sr-only" for="global-search">Search for items or shops</label>
36
+ <input id="global-search" name="q" type="search"
37
+ placeholder="Search for anything"
38
+ value="{{ query | default('') }}" autocomplete="off"
39
+ role="combobox" aria-expanded="false" aria-autocomplete="list"
40
+ aria-controls="global-search-suggestions"
41
+ data-search-input
42
+ {% if search_focused %}autofocus{% endif %}>
43
+ <button type="submit" aria-label="Search">
44
+ <svg aria-hidden="true" viewBox="0 0 24 24" width="24" height="24"><circle cx="10.5" cy="10.5" r="6.5"></circle><path d="m15.5 15.5 5 5"></path></svg>
45
+ </button>
46
+ <ul id="global-search-suggestions" class="search-suggestions" role="listbox"
47
+ aria-label="Search suggestions" hidden data-search-list></ul>
48
+ <p class="sr-only" role="status" aria-live="polite" data-search-status></p>
49
+ </form>
50
+ <nav class="account-nav" aria-label="Account">
51
+ {% if signed_in %}
52
+ <a href="/your/purchases">Purchases</a>
53
+ <form action="/auth/sign-out" method="post" class="inline-form">
54
+ <button class="link-button" type="submit">Sign out</button>
55
+ </form>
56
+ {% else %}
57
+ <a href="/signin?from_page={{ current_path }}">Sign in</a>
58
+ {% endif %}
59
+ {% if signed_in %}<a href="/your/favorites" class="icon-link" aria-label="Favorites">♡{% if favorites_count %} <span class="count-pill">{{ favorites_count }}</span>{% endif %}</a>{% endif %}
60
+ <a href="/cart" class="icon-link" aria-label="Cart">🛒{% if cart_count %} <span class="count-pill">{{ cart_count }}</span>{% endif %}</a>
61
+ </nav>
62
+ </div>
63
+ <nav class="category-nav" aria-label="Featured destinations">
64
+ {% for label, destination in top_navigation %}
65
+ <a class="category-chip" href="{{ destination }}">{{ label }}</a>
66
+ {% endfor %}
67
+ </nav>
68
+ </header>
69
+ <div class="category-scrim" hidden data-category-scrim></div>
70
+
71
+ <main id="main-content">
72
+ {% block content %}{% endblock %}
73
+ </main>
74
+
75
+ {% if compact_footer %}
76
+ <footer class="compact-footer">
77
+ <p><strong>Etsy Purchase Protection</strong> · Shop confidently from independent sellers.</p>
78
+ <nav aria-label="Cart footer">
79
+ <a href="/info/terms">Terms of Use</a>
80
+ <a href="/info/privacy">Privacy</a>
81
+ <a href="/info/interest-based-ads">Interest-based ads</a>
82
+ <a class="footer-region-link" href="/info/regions">{{ region_preference.country }} · {{ region_preference.language }} · {{ region_preference.symbol }} ({{ region_preference.currency }})</a>
83
+ <span>© 2026 Etsy, Inc.</span>
84
+ </nav>
85
+ </footer>
86
+ {% else %}
87
+ <aside class="footer-help" aria-labelledby="footer-help-title">
88
+ <h2 id="footer-help-title">Have a question? Well, we’ve got some answers.</h2>
89
+ <a href="/help">Go to Help Center</a>
90
+ </aside>
91
+
92
+ <footer class="site-footer">
93
+ <div class="footer-inner">
94
+ <h2>We're on a mission to keep commerce human.</h2>
95
+ <div class="footer-grid">
96
+ <section>
97
+ <h3>Shop</h3>
98
+ <a href="/giftcards">Gift cards</a>
99
+ <a href="/registry">Etsy Registry</a>
100
+ <a href="/info/sitemap">Sitemap</a>
101
+ <a href="/info/etsy-blog">Etsy blog</a>
102
+ <a href="/info/regions">Etsy United Kingdom</a>
103
+ <a href="/info/regions">Etsy Germany</a>
104
+ <a href="/info/regions">Etsy Canada</a>
105
+ </section>
106
+ <section>
107
+ <h3>Sell</h3>
108
+ <a href="/info/sell-on-etsy">Sell on Etsy</a>
109
+ <a href="/team">Teams</a>
110
+ <a href="/info/forums">Forums</a>
111
+ <a href="/info/affiliates-and-creators">Affiliates &amp; Creators</a>
112
+ </section>
113
+ <section>
114
+ <h3>About</h3>
115
+ <a href="/about">Etsy, Inc.</a>
116
+ <a href="/info/policies">Policies</a>
117
+ <a href="/investors">Investors</a>
118
+ <a href="/careers">Careers</a>
119
+ <a href="/press">Press</a>
120
+ <a href="/impact">Impact</a>
121
+ </section>
122
+ <section>
123
+ <h3>Help</h3>
124
+ <a href="/help">Help Center</a>
125
+ <a href="/info/privacy">Do not sell or share my<br>personal info</a>
126
+ </section>
127
+ </div>
128
+ <div class="footer-apps">
129
+ <a href="/info/mobile-apps"><img src="/static/assets/source-current/2026-07-25/home-media/home-app-badge-01.png" alt="Download on the App Store"></a>
130
+ <a href="/info/mobile-apps"><img src="/static/assets/source-current/2026-07-25/home-media/home-app-badge-02.png" alt="Get it on Google Play"></a>
131
+ </div>
132
+ <svg class="footer-illustration" aria-hidden="true" viewBox="0 0 310 210">
133
+ <path class="footer-line-orange" d="M31 193c-1-61 4-102 37-115 25-9 47 10 48 42 2 29-12 50-24 73M51 76c6-35 40-41 54-17 16 29-2 61-25 59-22-2-35-20-29-42Z"/>
134
+ <path class="footer-line-dark" d="M115 193c11-42 10-86 37-100 23-12 44 12 47 42 2 24-6 43-11 58M143 98l-8-75 119 13-7 91-52-6M153 38l82 9-5 58-74-8Z"/>
135
+ <path class="footer-fill-orange" d="m162 59 14 24 14-35 10 16 18-20-4 49-47-5Z"/>
136
+ <path class="footer-fill-dark" d="M182 109c49-31 97 7 96 84H168c-1-31-3-71 14-84Z"/>
137
+ </svg>
138
+ </div>
139
+ <div class="footer-bottom">
140
+ <div class="footer-locale-social">
141
+ <a class="footer-region-link" href="/info/regions">{{ region_preference.country }} · {{ region_preference.language }} · {{ region_preference.symbol }} ({{ region_preference.currency }})</a>
142
+ <a href="/info/social/instagram" aria-label="Instagram">◎</a>
143
+ <a href="/info/social/facebook" aria-label="Facebook">●</a>
144
+ <a href="/info/social/pinterest" aria-label="Pinterest">Ⓟ</a>
145
+ <a href="/info/social/youtube" aria-label="YouTube">▶</a>
146
+ </div>
147
+ <nav class="footer-legal" aria-label="Legal">
148
+ <span>© 2026 Etsy, Inc.</span>
149
+ <a href="/info/terms">Terms of Use</a>
150
+ <a href="/info/privacy">Privacy</a>
151
+ <a href="/info/interest-based-ads">Interest-based ads</a>
152
+ <a href="/info/local-shops">Local Shops</a>
153
+ <a href="/info/regions">Regions</a>
154
+ </nav>
155
+ </div>
156
+ </footer>
157
+ {% endif %}
158
+
159
+ <section id="cookie-overlay" class="cookie-overlay" role="dialog" aria-modal="true" aria-labelledby="cookie-title" hidden>
160
+ <div class="cookie-card">
161
+ <h2 id="cookie-title">How Etsy uses cookies</h2>
162
+ <p>We use cookies and similar technologies to give you a better experience,
163
+ enabling things like basic site functions and personalized content.</p>
164
+ <button class="cookie-okay" type="button">Okay</button>
165
+ </div>
166
+ </section>
167
+ </body>
168
+ </html>
tasks/etsy/environment/reference/clone/frontend/templates/cart.html ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="cart-page">
4
+ <h1>Your cart</h1>
5
+
6
+ {% if added %}
7
+ <div class="toast" role="status">Added listing {{ added }} to your cart.</div>
8
+ {% endif %}
9
+ {% if notice == "merged" %}
10
+ <div class="toast" role="status">This exact configuration was already in your
11
+ cart; the quantities were merged into one line — no duplicate was created.</div>
12
+ {% elif notice == "updated" %}
13
+ <div class="toast" role="status">Quantity updated.</div>
14
+ {% endif %}
15
+
16
+ {% if not lines %}
17
+ <div class="purchase-protection">
18
+ <strong>Etsy Purchase Protection</strong>
19
+ <span>Shop confidently, knowing eligible purchases are covered.</span>
20
+ </div>
21
+ <div class="cart-empty-state">
22
+ <h2>Your cart is empty.</h2>
23
+ <p>Discover something unique to fill it up</p>
24
+ <a class="cta" href="/c/gifts">Start shopping</a>
25
+ </div>
26
+ <div class="cart-impact-grid">
27
+ <p><strong>Etsy invests in climate solutions</strong><br>Supporting verified projects that reduce carbon emissions.</p>
28
+ <p><strong>The Uplift Fund supports nonprofits</strong><br>Helping create opportunities in communities around the world.</p>
29
+ </div>
30
+ {% else %}
31
+ <ol class="cart-lines">
32
+ {% for line in lines %}
33
+ <li class="cart-line" data-line-key="{{ line.line_token }}" data-listing-id="{{ line.listing_id }}">
34
+ <img src="{{ line.image }}" alt="{{ line.title }}" width="765" height="956">
35
+ <div class="cart-line-body">
36
+ <a href="/listing/{{ line.listing_id }}/{{ line.slug }}"><h2>{{ line.title }}</h2></a>
37
+ <p class="line-summary">{{ line.summary }}</p>
38
+ <p class="line-price">Qty {{ line.quantity }} × {{ line.unit_price }} =
39
+ <strong>{{ line.subtotal }}</strong></p>
40
+ <p class="muted">Selected options are included in the item total.</p>
41
+ <form action="/cart/update" method="post" class="inline-form">
42
+ <input type="hidden" name="line_token" value="{{ line.line_token }}">
43
+ <input type="hidden" name="expected_version" value="{{ line.version }}">
44
+ <label class="sr-only" for="qty-{{ line.line_token }}">Quantity</label>
45
+ <input id="qty-{{ line.line_token }}" name="quantity" type="number"
46
+ min="1" max="{{ line.max_quantity }}" value="{{ line.quantity }}">
47
+ <button type="submit" class="link-button">Update quantity</button>
48
+ </form>
49
+ <form action="/cart/remove" method="post" class="inline-form">
50
+ <input type="hidden" name="line_token" value="{{ line.line_token }}">
51
+ <input type="hidden" name="expected_version" value="{{ line.version }}">
52
+ <button type="submit" class="link-button">Remove</button>
53
+ </form>
54
+ </div>
55
+ </li>
56
+ {% endfor %}
57
+ </ol>
58
+ <div class="cart-totals">
59
+ <p class="item-total"><strong>Item total: {{ item_total }}</strong></p>
60
+ <p class="price-disclosure">Item total only — excludes shipping and tax.</p>
61
+ <p class="muted">Shipping and taxes are calculated at checkout.</p>
62
+ <a class="checkout-button" href="/checkout">Proceed to checkout</a>
63
+ </div>
64
+ {% endif %}
65
+ </section>
66
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/category.html ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="category-page">
4
+ <header class="category-heading">
5
+ <h1>{{ category.title }}</h1>
6
+ <p>{{ category.description }}</p>
7
+ </header>
8
+
9
+ <div class="subcategory-grid" aria-label="Browse {{ category.title }}">
10
+ {% for label, slug, image in category.subcategories %}
11
+ <a href="/c/{{ slug }}">
12
+ <img src="/static/assets/source-current/2026-07-25/home-media/{{ image }}" alt="">
13
+ <span>{{ label }}</span>
14
+ </a>
15
+ {% endfor %}
16
+ </div>
17
+
18
+ <div class="category-actions">
19
+ <a class="filter-button" href="{{ request.url.path }}?filters=all">☷ All Filters</a>
20
+ <span>Featured items from independent sellers</span>
21
+ <label>Sort by <select aria-label="Sort items"><option>Relevancy</option><option>Lowest Price</option><option>Highest Price</option></select></label>
22
+ </div>
23
+
24
+ <ol class="results-grid category-results">
25
+ {% for card in cards %}
26
+ <li class="listing-card" data-listing-id="{{ card.listing_id }}">
27
+ <a href="/listing/{{ card.listing_id }}/{{ card.slug }}">
28
+ <img src="{{ card.image }}" alt="{{ card.title }}" width="765" height="956" loading="lazy">
29
+ <h2 class="card-title">{{ card.title }}</h2>
30
+ </a>
31
+ <p class="card-price">${{ card.price_usd }}</p>
32
+ {% if card.badges %}<p class="category-badges">{{ card.badges | join(' · ') }}</p>{% endif %}
33
+ </li>
34
+ {% endfor %}
35
+ </ol>
36
+ </section>
37
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/checkout.html ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="checkout-shell" data-checkout-id="{{ checkout.checkout_id }}">
4
+ <h1>Review and pay</h1>
5
+ {% if cancelled %}<div class="toast" role="status">Stripe test Checkout was cancelled. Your cart is unchanged.</div>{% endif %}
6
+ {% if payment_error %}<div class="validation-errors" role="alert"><p>{{ payment_error }}</p></div>{% endif %}
7
+ <div class="checkout-grid">
8
+ <div>
9
+ <div class="checkout-card">
10
+ <h2>Shipping address</h2>
11
+ <p>{{ checkout.address.name }}<br>{{ checkout.address.address1 }}{% if checkout.address.address2 %}<br>{{ checkout.address.address2 }}{% endif %}<br>{{ checkout.address.city }}, {{ checkout.address.state }} {{ checkout.address.postal_code }}<br>United States</p>
12
+ </div>
13
+ <div class="checkout-card">
14
+ <h2>Items</h2>
15
+ <ul class="order-lines">
16
+ {% for line in checkout.lines %}
17
+ <li><img src="{{ line.image }}" alt=""><div><strong>{{ line.title }}</strong><p>{{ line.summary }}</p><p>Qty {{ line.quantity }}</p></div><strong>{{ line.subtotal }}</strong></li>
18
+ {% endfor %}
19
+ </ul>
20
+ </div>
21
+ </div>
22
+ <aside class="checkout-card">
23
+ <h2>Order total</h2>
24
+ <p class="summary-line"><span>Items</span><span>{{ checkout.item_total }}</span></p>
25
+ <p class="summary-line"><span>Shipping</span><span>{{ checkout.shipping }}</span></p>
26
+ <p class="summary-line"><span>Estimated tax</span><span>{{ checkout.tax }}</span></p>
27
+ <p class="summary-line summary-total"><strong>Total</strong><strong>{{ checkout.total }} USD</strong></p>
28
+ {% if adapter == "local-sandbox" %}
29
+ <p><strong>Choose a test-only outcome</strong></p>
30
+ <div class="payment-scenarios">
31
+ {% for scenario in scenarios %}
32
+ <form action="/checkout/{{ checkout.checkout_id }}/pay" method="post">
33
+ <input type="hidden" name="csrf" value="{{ csrf }}">
34
+ <input type="hidden" name="scenario_id" value="{{ scenario.id }}">
35
+ <button class="pay-button" type="submit">{{ scenario.label }}</button>
36
+ </form>
37
+ {% endfor %}
38
+ </div>
39
+ {% else %}
40
+ <form action="/checkout/{{ checkout.checkout_id }}/pay" method="post">
41
+ <input type="hidden" name="csrf" value="{{ csrf }}">
42
+ <button class="pay-button" type="submit">Pay with Stripe test Checkout</button>
43
+ </form>
44
+ {% endif %}
45
+ <p class="muted">Simulation only. No live charge, refund, shipment, or seller payout occurs.</p>
46
+ </aside>
47
+ </div>
48
+ </section>
49
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/checkout_address.html ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="checkout-shell">
4
+ <h1>Where should we send your order?</h1>
5
+ <p class="muted">This clone stores a server-owned shipping snapshot. No real shipment is created.</p>
6
+ {% if errors %}
7
+ <div class="validation-errors" role="alert"><ul>{% for error in errors %}<li>{{ error }}</li>{% endfor %}</ul></div>
8
+ {% endif %}
9
+ <div class="checkout-grid">
10
+ <form class="checkout-card address-form" action="/checkout" method="post">
11
+ <input type="hidden" name="csrf" value="{{ csrf }}">
12
+ <label>Full name <input name="name" required maxlength="100" value="{{ values.get('name', account_display_name) }}"></label>
13
+ <label>Street address <input name="address1" required maxlength="160" value="{{ values.get('address1', '') }}"></label>
14
+ <label>Apartment, suite, etc. <input name="address2" maxlength="160" value="{{ values.get('address2', '') }}"></label>
15
+ <div class="address-row">
16
+ <label>City <input name="city" required maxlength="100" value="{{ values.get('city', '') }}"></label>
17
+ <label>State <input name="state" required maxlength="2" value="{{ values.get('state', '') }}"></label>
18
+ <label>ZIP code <input name="postal_code" required maxlength="10" value="{{ values.get('postal_code', '') }}"></label>
19
+ </div>
20
+ <button class="checkout-button" type="submit">Review your order</button>
21
+ </form>
22
+ <aside class="checkout-card">
23
+ <h2>Cart summary</h2>
24
+ <p>{{ cart_count }} item configuration{% if cart_count != 1 %}s{% endif %}</p>
25
+ <p><strong>Item total: {{ item_total }}</strong></p>
26
+ <p class="muted">Tax is calculated in the review step.</p>
27
+ </aside>
28
+ </div>
29
+ </section>
30
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/company.html ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <div class="company-page">
4
+ <nav class="company-nav" aria-label="Company">
5
+ {% for label, destination, slug in company_navigation %}
6
+ <a href="{{ destination }}"{% if slug == active_company_page %} aria-current="page"{% endif %}>{{ label }}</a>
7
+ {% endfor %}
8
+ </nav>
9
+
10
+ <section class="company-intro" id="content">
11
+ <div class="company-art" aria-hidden="true">
12
+ <span class="company-art-screen"></span>
13
+ <span class="company-art-hand"></span>
14
+ <span class="company-art-spark company-art-spark-one"></span>
15
+ <span class="company-art-spark company-art-spark-two"></span>
16
+ </div>
17
+ <div class="company-copy">
18
+ <h1>{{ company_page.heading }}</h1>
19
+ <p class="company-lead">{{ company_page.lead }}</p>
20
+ {% for paragraph in company_page.body %}<p>{{ paragraph }}</p>{% endfor %}
21
+ </div>
22
+ </section>
23
+
24
+ <section class="company-how">
25
+ <h2>{{ company_page.section_heading }}</h2>
26
+ <p>{{ company_page.section_lead }}</p>
27
+ <div class="company-card-grid">
28
+ {% for heading, description, destination, action in company_page.cards %}
29
+ <article class="company-card">
30
+ <span class="company-card-icon" aria-hidden="true">{{ loop.index }}</span>
31
+ <h3>{{ heading }}</h3>
32
+ <p>{{ description }}</p>
33
+ <a href="{{ destination }}">{{ action }}</a>
34
+ </article>
35
+ {% endfor %}
36
+ </div>
37
+ </section>
38
+ </div>
39
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/error.html ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="error-page">
4
+ <h1>{{ page_title }}</h1>
5
+ <div class="state-panel state-error" role="alert">
6
+ <p>{{ message }}</p>
7
+ </div>
8
+ <p><a href="/">Back to home</a> · <a href="/cart">View cart</a></p>
9
+ </section>
10
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/favorites.html ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="favorites-page">
4
+ <h1>Your favorites</h1>
5
+
6
+ {% if toast == "favorited" %}
7
+ <div class="toast" role="status">Added to your favorites.</div>
8
+ {% elif toast == "already-favorited" %}
9
+ <div class="toast" role="status">Already in your favorites — the repeated
10
+ favorite was absorbed idempotently and no duplicate was created.</div>
11
+ {% elif toast == "removed" %}
12
+ <div class="toast" role="status">Removed from your favorites.</div>
13
+ {% endif %}
14
+
15
+ <p class="muted">Save the items you love and come back to them anytime.</p>
16
+ <p class="muted">Account-owned local favorites: they live with this account on
17
+ this site only and never reach etsy.com. Idempotent — repeating a favorite
18
+ never duplicates it.</p>
19
+
20
+ {% if not items %}
21
+ <div class="state-panel">
22
+ <p>No favorites yet.</p>
23
+ <a href="/search?q=handmade+blue+ceramic+flower+vase&amp;max=50">Find a blue ceramic vase under $50</a>
24
+ </div>
25
+ {% else %}
26
+ <ol class="results-grid">
27
+ {% for item in items %}
28
+ <li class="listing-card" data-listing-id="{{ item.listing_id }}">
29
+ <a href="/listing/{{ item.listing_id }}/{{ item.slug }}">
30
+ <img src="{{ item.image }}" alt="{{ item.title }}" width="765" height="956" loading="lazy">
31
+ <h2 class="card-title">{{ item.title }}</h2>
32
+ </a>
33
+ <p class="card-price">{{ item.price }}</p>
34
+ <form action="/favorites/toggle" method="post" class="inline-form">
35
+ <input type="hidden" name="listing_id" value="{{ item.listing_id }}">
36
+ <input type="hidden" name="action" value="remove">
37
+ <input type="hidden" name="expected_version" value="{{ item.version }}">
38
+ <input type="hidden" name="next" value="/your/favorites">
39
+ <button type="submit" class="fav-button">Remove favorite</button>
40
+ </form>
41
+ </li>
42
+ {% endfor %}
43
+ </ol>
44
+ {% endif %}
45
+ </section>
46
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/home.html ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="home-hero" data-hero-carousel aria-roledescription="carousel" aria-label="Featured Etsy collections">
4
+ <article class="home-hero-slide" data-hero-slide aria-label="1 of 3">
5
+ <div class="home-hero-copy">
6
+ <p class="eyebrow">Made with sellers</p>
7
+ <h1>Daisy Chain Fields Collection by Olivia Rodrigo</h1>
8
+ <p>Discover our standout shops of the week</p>
9
+ <a class="cta" href="/discover/standout-shops">Shop now</a>
10
+ </div>
11
+ <img src="/static/assets/source-current/2026-07-25/home-media/home-hero-01.jpg"
12
+ alt="Daisy Chain Fields collection">
13
+ </article>
14
+ <article class="home-hero-slide" data-hero-slide aria-label="2 of 3" hidden>
15
+ <div class="home-hero-copy home-hero-copy-lilac">
16
+ <p class="eyebrow">Editors' picks</p>
17
+ <h2>Fresh summer style from independent shops</h2>
18
+ <p>Find colorful pieces made for long, bright days</p>
19
+ <a class="cta" href="/discover/summer-style">Explore the edit</a>
20
+ </div>
21
+ <img src="/static/assets/source-current/2026-07-25/home-media/home-blog-23.jpg"
22
+ alt="Summer style collection">
23
+ </article>
24
+ <article class="home-hero-slide" data-hero-slide aria-label="3 of 3" hidden>
25
+ <div class="home-hero-copy home-hero-copy-blue">
26
+ <p class="eyebrow">One of a kind</p>
27
+ <h2>Vintage finds with a story to tell</h2>
28
+ <p>Discover distinctive pieces selected from independent shops</p>
29
+ <a class="cta" href="/r/curated/etsys-best-vintage-finds">Shop vintage</a>
30
+ </div>
31
+ <img src="/static/assets/source-current/2026-07-25/home-media/home-seasonal-06.jpg"
32
+ alt="Curated vintage finds">
33
+ </article>
34
+ <div class="carousel-controls" aria-label="Hero carousel controls">
35
+ <button type="button" data-carousel-direction="previous" aria-label="Previous feature">‹</button>
36
+ <button type="button" data-carousel-direction="next" aria-label="Next feature">›</button>
37
+ </div>
38
+ <p class="sr-only" data-carousel-status aria-live="polite">Feature 1 of 3</p>
39
+ </section>
40
+
41
+ <section class="home-section">
42
+ <h2>Jump into featured interests</h2>
43
+ <div class="home-media-grid home-media-grid-4">
44
+ {% for item in [
45
+ ('Bridal Day Gifts', 'home-featured-interest-02.jpg'),
46
+ ('New Home Ceramics', 'home-featured-interest-03.jpg'),
47
+ ('Baby Nursery Decor', 'home-featured-interest-04.jpg'),
48
+ ('Romantic Gifts', 'home-featured-interest-05.jpg')
49
+ ] %}
50
+ <a class="home-media-card" href="/discover/{{ item[0] | replace(' &amp; ', '-') | replace(' ', '-') | lower }}">
51
+ <img src="/static/assets/source-current/2026-07-25/home-media/{{ item[1] }}" alt="">
52
+ <span>{{ item[0] }}</span>
53
+ </a>
54
+ {% endfor %}
55
+ </div>
56
+ </section>
57
+
58
+ <section class="home-section">
59
+ <h2>Discover our best of summer 2026</h2>
60
+ <div class="home-media-grid home-media-grid-5">
61
+ {% for item in [
62
+ ('Sellers to Watch', 'home-seasonal-06.jpg'),
63
+ ('Creative Wedding Favors', 'home-seasonal-07.jpg'),
64
+ ('Unique Wall Art', 'home-seasonal-08.jpg'),
65
+ ('Creative Corsets', 'home-seasonal-09.jpg'),
66
+ ('July Birthstone Finds', 'home-seasonal-10.jpg')
67
+ ] %}
68
+ <a class="home-media-card round-media" href="/discover/{{ item[0] | replace(' &amp; ', '-') | replace(' ', '-') | lower }}">
69
+ <img src="/static/assets/source-current/2026-07-25/home-media/{{ item[1] }}" alt="">
70
+ <span>{{ item[0] }}</span>
71
+ </a>
72
+ {% endfor %}
73
+ </div>
74
+ </section>
75
+
76
+ <section class="home-section birthday-strip">
77
+ <div>
78
+ <h2>Etsy-special gifts for birthdays</h2>
79
+ <a class="text-cta" href="/featured/hub/gifts">Get inspired</a>
80
+ </div>
81
+ <div class="birthday-media" aria-hidden="true">
82
+ <img src="/static/assets/source-current/2026-07-25/home-media/home-category-11.jpg" alt="">
83
+ <img src="/static/assets/source-current/2026-07-25/home-media/home-category-12.jpg" alt="">
84
+ <img src="/static/assets/source-current/2026-07-25/home-media/home-category-13.jpg" alt="">
85
+ </div>
86
+ </section>
87
+
88
+ <section class="home-section">
89
+ <h2>Shop our most-loved categories</h2>
90
+ <div class="home-media-grid home-media-grid-6">
91
+ {% for item in [
92
+ ('Sewing patterns', 'home-category-11.jpg', 'craft-supplies-and-tools'),
93
+ ('Keychains', 'home-category-12.jpg', 'accessories'),
94
+ ('Necklaces', 'home-category-13.jpg', 'jewelry'),
95
+ ('Home and living', 'home-category-14.jpg', 'home-and-living'),
96
+ ('Car accessories', 'home-category-15.jpg', 'electronics-and-accessories'),
97
+ ('Stickers', 'home-category-16.jpg', 'paper-and-party-supplies')
98
+ ] %}
99
+ <a class="home-media-card" href="/c/{{ item[2] }}">
100
+ <img src="/static/assets/source-current/2026-07-25/home-media/{{ item[1] }}" alt="">
101
+ <span>{{ item[0] }}</span>
102
+ </a>
103
+ {% endfor %}
104
+ </div>
105
+ </section>
106
+
107
+ <section class="home-section deal-panel">
108
+ <div class="section-heading-row">
109
+ <div>
110
+ <h2>Today's big deals</h2>
111
+ <p class="muted">Limited-time finds from shops you'll love.</p>
112
+ </div>
113
+ <a class="text-cta" href="/featured/hub/gifts">See all</a>
114
+ </div>
115
+ <div class="home-media-grid home-media-grid-5">
116
+ {% for item in [
117
+ ('Personalized finds', 'home-deal-and-shop-17.jpg'),
118
+ ('Handmade jewelry', 'home-deal-and-shop-18.jpg'),
119
+ ('Wedding details', 'home-deal-and-shop-19.jpg'),
120
+ ('Home accents', 'home-deal-and-shop-20.jpg'),
121
+ ('Creative supplies', 'home-deal-and-shop-21.jpg')
122
+ ] %}
123
+ <a class="home-media-card deal-card" href="/discover/{{ item[0] | replace(' ', '-') | lower }}">
124
+ <img src="/static/assets/source-current/2026-07-25/home-media/{{ item[1] }}" alt="">
125
+ <span>{{ item[0] }}</span>
126
+ <small>Explore today's featured finds</small>
127
+ </a>
128
+ {% endfor %}
129
+ </div>
130
+ </section>
131
+
132
+ <section class="home-section task-links">
133
+ <p class="eyebrow">Popular right now</p>
134
+ <h2>Shop inspired searches</h2>
135
+ <ul class="task-entry-grid">
136
+ <li><a href="/search?q=personalized+leather+bifold+wallet+initials">Personalized leather bifold wallet · initials</a></li>
137
+ <li><a href="/search?q=leather+dog+collar+custom+name+embroidery+medium+sized+dog">Leather dog collar · custom embroidery · medium dog</a></li>
138
+ <li><a href="/search?q=handmade+blue+ceramic+flower+vase&amp;max=50">Handmade blue ceramic flower vase · under $50</a></li>
139
+ <li><a href="/search?q=mid+century+modern+wooden+bookshelf&amp;max=300">Mid-century modern wooden bookshelf · under $300</a></li>
140
+ </ul>
141
+ </section>
142
+
143
+ <section class="home-section editorial-row">
144
+ <div>
145
+ <p class="eyebrow">Editors' Picks</p>
146
+ <h2>Fresh ideas handpicked for you</h2>
147
+ <p class="muted">Discover seasonal inspiration from creative shops.</p>
148
+ </div>
149
+ {% for item in [
150
+ ('Outdoor Entertaining', 'home-blog-22.jpg'),
151
+ ('Summer Style', 'home-blog-23.jpg'),
152
+ ('Wedding Gifts', 'home-blog-24.jpg')
153
+ ] %}
154
+ <a class="editorial-card" href="/discover/{{ item[0] | replace(' ', '-') | lower }}">
155
+ <img src="/static/assets/source-current/2026-07-25/home-media/{{ item[1] }}" alt="">
156
+ <span>{{ item[0] }}</span>
157
+ </a>
158
+ {% endfor %}
159
+ </section>
160
+
161
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/inbox.html ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="signin-page">
4
+ <h1>Verification message</h1>
5
+ {% if message %}
6
+ <div class="state-panel" role="status">
7
+ <p><strong>{{ message.template | replace('-', ' ') | title }}</strong></p>
8
+ <p>Delivery status: <strong>{{ message.status }}</strong></p>
9
+ <p>Delivery status: {{ message.status }}</p>
10
+ </div>
11
+ {% else %}
12
+ <div class="state-panel"><p>No current {{ purpose }} message for this browser session.</p></div>
13
+ {% endif %}
14
+ <p>This message is available in this browser only. No external email delivery is claimed.</p>
15
+ </section>
16
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/info.html ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="info-page">
4
+ <p class="eyebrow">Etsy</p>
5
+ <h1>{{ heading }}</h1>
6
+ <p class="info-lead">{{ description }}</p>
7
+ <nav class="info-actions" aria-label="Continue browsing">
8
+ {% for label, destination in actions %}<a href="{{ destination }}">{{ label }}</a>{% endfor %}
9
+ </nav>
10
+ </section>
11
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/listing.html ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <article class="listing-page" data-listing-id="{{ listing.listing_id }}" data-state="{{ listing_state }}">
4
+ <div class="listing-layout">
5
+ <figure class="listing-gallery">
6
+ <img src="{{ listing.image }}" alt="{{ listing.title }}" width="765" height="956">
7
+ </figure>
8
+
9
+ <section class="buy-box">
10
+ <h1>{{ listing.title }}</h1>
11
+
12
+ {% if listing.badges %}
13
+ <ul class="listing-badges">
14
+ {% for badge in listing.badges %}<li>{{ badge }}</li>{% endfor %}
15
+ </ul>
16
+ {% endif %}
17
+
18
+ <p class="price-now">{{ listing.price_now }}
19
+ {% if listing.price_original %}
20
+ <s class="price-original">{{ listing.price_original }}</s>
21
+ {% endif %}
22
+ </p>
23
+ <p class="price-disclosure">Item price only — excludes shipping and tax.</p>
24
+
25
+ {% if listing_state == "out-of-stock" %}
26
+ <div class="state-panel state-error" role="alert">
27
+ <p>This item is currently out of stock and can't be added to your cart.</p>
28
+ <a href="/listing/{{ listing.listing_id }}/{{ listing.slug }}">Refresh listing</a>
29
+ </div>
30
+ {% elif listing_state == "stale-version" %}
31
+ <div class="state-panel state-error" role="alert">
32
+ <p>A newer version of this listing exists. Stale mutations are
33
+ refused; refresh to load the current server-owned version.</p>
34
+ <a href="/listing/{{ listing.listing_id }}/{{ listing.slug }}">Refresh listing</a>
35
+ </div>
36
+ {% endif %}
37
+
38
+ {% if errors %}
39
+ <div class="validation-errors" role="alert">
40
+ <p><strong>Please fix the following before adding to cart:</strong></p>
41
+ <ul>
42
+ {% for error in errors %}<li>{{ error }}</li>{% endfor %}
43
+ </ul>
44
+ </div>
45
+ {% endif %}
46
+
47
+ {% if listing.cart_enabled and listing_state == "loaded" %}
48
+ <form id="variations" class="variation-form" action="/cart/listing" method="post">
49
+ <input type="hidden" name="listing_id" value="{{ listing.listing_id }}">
50
+ <input type="hidden" name="listing_version" value="{{ listing.version }}">
51
+
52
+ {% for axis in axes %}
53
+ <label for="{{ axis.field }}">{{ axis.label }}</label>
54
+ <select id="{{ axis.field }}" name="{{ axis.field }}" required>
55
+ {% for option in axis.options %}
56
+ <option value="{{ option.value if option.selectable else '' }}"
57
+ {% if form_values.get(axis.field) == option.value %}selected{% endif %}>{{ option.value }}</option>
58
+ {% endfor %}
59
+ </select>
60
+ {% endfor %}
61
+
62
+ {% if personalization.enabled %}
63
+ <div class="personalization-box">
64
+ <label for="personalization">{{ personalization.prompt }}
65
+ {% if personalization.required %}(required){% else %}(optional){% endif %}</label>
66
+ <textarea id="personalization" name="personalization"
67
+ maxlength="{{ personalization.char_limit }}"
68
+ {% if personalization.required %}required{% endif %}
69
+ rows="2">{{ form_values.get('personalization', '') }}</textarea>
70
+ <p class="muted">Up to {{ personalization.char_limit }} characters;
71
+ your text is stored verbatim and rendered safely.</p>
72
+ </div>
73
+ {% endif %}
74
+
75
+ <label for="quantity">Quantity</label>
76
+ <select id="quantity" name="quantity">
77
+ {% for option in quantity_options %}
78
+ <option value="{{ option }}"
79
+ {% if form_values.get('quantity', '1') == option %}selected{% endif %}>{{ option }}</option>
80
+ {% endfor %}
81
+ </select>
82
+
83
+ <div class="purchase-actions">
84
+ <button class="add-to-cart" type="submit">Add to cart</button>
85
+ <button class="buy-now" type="submit" name="next_action" value="checkout">Buy it now</button>
86
+ </div>
87
+ <p class="muted">Your total will be calculated from the selected options and quantity.</p>
88
+ </form>
89
+ {% endif %}
90
+
91
+ <form action="/favorites/toggle" method="post" class="inline-form favorite-form">
92
+ <input type="hidden" name="listing_id" value="{{ listing.listing_id }}">
93
+ <input type="hidden" name="action" value="{{ 'remove' if favorited else 'add' }}">
94
+ <input type="hidden" name="expected_version" value="{{ favorite_version }}">
95
+ <input type="hidden" name="next" value="/listing/{{ listing.listing_id }}/{{ listing.slug }}">
96
+ <button type="submit" class="fav-button large">
97
+ {% if favorited %}♥ Favorited — remove{% else %}♡ Add to Favorites{% endif %}
98
+ </button>
99
+ <span class="sr-only" role="status" aria-live="polite" data-favorite-status></span>
100
+ </form>
101
+ </section>
102
+ </div>
103
+ </article>
104
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/order.html ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="checkout-shell" data-order-id="{{ order.order_id }}">
4
+ <div class="toast" role="status"><strong>Thank you — your test order is confirmed.</strong></div>
5
+ <h1>Order {{ order.order_id }}</h1>
6
+ <p>Paid in the test-only payment ledger on {{ order.placed_at }}.</p>
7
+ <div class="checkout-grid">
8
+ <div class="checkout-card">
9
+ <h2>Items</h2>
10
+ <ul class="order-lines">{% for line in order.lines %}<li><img src="{{ line.image }}" alt=""><div><strong>{{ line.title }}</strong><p>{{ line.summary }}</p><p>Qty {{ line.quantity }}</p></div><strong>{{ line.subtotal }}</strong></li>{% endfor %}</ul>
11
+ </div>
12
+ <aside class="checkout-card">
13
+ <h2>Total</h2>
14
+ <p class="summary-line"><span>Items</span><span>{{ order.item_total }}</span></p>
15
+ <p class="summary-line"><span>Shipping</span><span>{{ order.shipping }}</span></p>
16
+ <p class="summary-line"><span>Tax</span><span>{{ order.tax }}</span></p>
17
+ <p class="summary-line summary-total"><strong>Paid</strong><strong>{{ order.total }} USD</strong></p>
18
+ <a href="/your/purchases">View all purchases</a>
19
+ </aside>
20
+ </div>
21
+ </section>
22
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/purchases.html ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="checkout-shell">
4
+ <h1>Purchases</h1>
5
+ {% if not orders %}<div class="state-panel"><p>You have no test orders yet.</p><a href="/">Continue shopping</a></div>{% endif %}
6
+ {% for order in orders %}
7
+ <article class="checkout-card">
8
+ <h2><a href="/orders/{{ order.order_id }}">Order {{ order.order_id }}</a></h2>
9
+ <p>{{ order.line_count }} item configuration{% if order.line_count != 1 %}s{% endif %} · <strong>{{ order.total }} USD</strong></p>
10
+ <p class="muted">{{ order.placed_at }} · Test-only paid order</p>
11
+ </article>
12
+ {% endfor %}
13
+ </section>
14
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/recover.html ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="signin-page">
4
+ <h1>Reset your password</h1>
5
+ {% if message %}<div class="state-panel" role="status"><p>{{ message }}</p></div>{% endif %}
6
+ {% if errors %}
7
+ <div class="state-panel state-error" role="alert">
8
+ {% for error in errors %}<p>{{ error }}</p>{% endfor %}
9
+ </div>
10
+ {% endif %}
11
+ {% if state == "request" %}
12
+ <form class="signin-form" action="/recover" method="post">
13
+ <input type="hidden" name="csrf" value="{{ csrf }}">
14
+ <label for="recover-email">Email address</label>
15
+ <input id="recover-email" name="email" type="email" autocomplete="email" required>
16
+ <button type="submit">Send reset message</button>
17
+ </form>
18
+ {% else %}
19
+ <p><a href="/auth/inbox?purpose=password-reset">Open local reset message</a></p>
20
+ <form class="signin-form" action="/recover/complete" method="post">
21
+ <input type="hidden" name="csrf" value="{{ csrf }}">
22
+ <label for="recover-code">Six-digit code</label>
23
+ <input id="recover-code" name="code" inputmode="numeric"
24
+ pattern="[0-9]{6}" autocomplete="one-time-code" required>
25
+ <label for="recover-password">New password</label>
26
+ <input id="recover-password" name="new_password" type="password"
27
+ autocomplete="new-password" minlength="8" required>
28
+ <button type="submit">Set new password</button>
29
+ </form>
30
+ {% endif %}
31
+ </section>
32
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/regions.html ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="regions-page" data-selected-region="{{ selected_region_id }}">
4
+ <p class="eyebrow">Etsy</p>
5
+ <h1>Regions</h1>
6
+ <p class="info-lead">Choose a country, language, and currency preference.</p>
7
+
8
+ {% if saved %}
9
+ <div class="toast" role="status">Region preference saved.</div>
10
+ {% endif %}
11
+ {% if errors %}
12
+ <div class="validation-errors" role="alert"><ul>{% for error in errors %}<li>{{ error }}</li>{% endfor %}</ul></div>
13
+ {% endif %}
14
+
15
+ <div class="region-grid" aria-label="Available regions">
16
+ {% for id, region in regions.items() %}
17
+ <form class="region-card" action="/info/regions" method="post">
18
+ <input type="hidden" name="csrf" value="{{ csrf }}">
19
+ <button class="region-option" type="submit" name="region" value="{{ id }}"
20
+ aria-pressed="{{ 'true' if id == selected_region_id else 'false' }}">
21
+ <span class="region-country">{{ region.country }}</span>
22
+ <span class="region-details">{{ region.language }} · {{ region.symbol }} ({{ region.currency }})</span>
23
+ {% if id == selected_region_id %}<span class="sr-only">Currently selected</span>{% endif %}
24
+ </button>
25
+ </form>
26
+ {% endfor %}
27
+ </div>
28
+
29
+ <p class="muted region-disclosure">This setting is a local browsing preference. Catalog prices and the test-only checkout remain server-settled in USD; no live exchange rate or real charge is used.</p>
30
+ <a class="text-cta" href="/">Back to Etsy</a>
31
+ </section>
32
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/register.html ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ {#
4
+ Structure follows the 2026-08-06 capture of www.etsy.com/join: title
5
+ "Join | Etsy", heading "Welcome, let's get your account set up", form id
6
+ `join-neu-form`, and the provider row Google / Facebook / Apple. The source
7
+ pane carries a hidden `first_name` field and `initial_state=register`.
8
+
9
+ As on the sign-in pane, the captured surface paints no email or password
10
+ field; the form below is the working local registration this site requires.
11
+ #}
12
+ <section class="signin-page" data-auth-pane="register">
13
+ <h1>Welcome, let's get your account set up</h1>
14
+ {% if errors %}
15
+ <div class="state-panel state-error" role="alert">
16
+ {% for error in errors %}<p>{{ error }}</p>{% endfor %}
17
+ </div>
18
+ {% endif %}
19
+
20
+ {% include "_auth_providers.html" %}
21
+
22
+ <div class="auth-divider" role="separator"><span>or</span></div>
23
+
24
+ <form id="join-neu-form" class="signin-form" action="/register" method="post"{% if public_registration_enabled %} data-external-registration="true"{% endif %}>
25
+ <input type="hidden" name="csrf" value="{{ csrf }}">
26
+ <input type="hidden" name="next" value="{{ next_path }}">
27
+ <input type="hidden" name="initial_state" value="register">
28
+ <input type="hidden" name="verification_fallback" value="" data-auth-fallback>
29
+ <label for="register-email">Email address</label>
30
+ <input id="register-email" name="email" type="email" autocomplete="email" placeholder="Enter your email" required{% if public_registration_enabled %} data-auth-email{% endif %}>
31
+ <label for="register-name">First name</label>
32
+ <input id="register-name" name="display_name" autocomplete="given-name" placeholder="Enter your first name" required>
33
+ {% if public_registration_enabled %}
34
+ <button type="button" data-auth-send-code>Send verification code</button>
35
+ <section data-auth-code-panel hidden aria-label="Verify email address">
36
+ <label for="public-registration-code">Verification code</label>
37
+ <input id="public-registration-code" data-auth-code inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6">
38
+ <button type="button" data-auth-verify-code>Verify code</button>
39
+ </section>
40
+ <p data-auth-verification-status role="status" aria-live="polite"></p>
41
+ {% endif %}
42
+ <label for="register-password">Password</label>
43
+ <input id="register-password" name="password" type="password"
44
+ autocomplete="new-password" placeholder="Set password" minlength="8" required{% if public_registration_enabled %} data-auth-password{% endif %}>
45
+ {# Never `disabled`: with scripting unavailable this button is the only way
46
+ to submit, and the server runs the same verification step either way. #}
47
+ <button type="submit" name="submit_attempt" value="register"{% if public_registration_enabled %} data-auth-create-account{% endif %}>Create account</button>
48
+ </form>
49
+ <p>{% if public_registration_enabled %}We'll send a six-digit verification code to this email address.{% else %}We'll place a six-digit verification message in your browser inbox.{% endif %}</p>
50
+ {% if public_registration_enabled %}<script src="/static/auth-verification.js"></script>{% endif %}
51
+ </section>
52
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/search.html ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="search-page" data-state="{{ state }}">
4
+ <h1>Search results</h1>
5
+ {% if query %}<p class="search-query-heading">Results for <strong>{{ query }}</strong></p>{% endif %}
6
+
7
+ {% if chips %}
8
+ <div class="applied-filters" aria-label="Applied filters">
9
+ <span class="filters-label">Applied filters</span>
10
+ {% for chip in chips %}
11
+ <span class="filter-chip">{{ chip }}</span>
12
+ {% endfor %}
13
+ </div>
14
+ {% endif %}
15
+
16
+ {% if price_filterable %}
17
+ <form class="price-filter" action="/search" method="get">
18
+ <input type="hidden" name="q" value="{{ query }}">
19
+ <label for="max-price">Max item price (USD)</label>
20
+ <input id="max-price" name="max" type="number" min="0" step="1"
21
+ value="{{ max_price }}">
22
+ <button type="submit">Apply</button>
23
+ <p class="price-filter-note">Filters the server-owned item price only —
24
+ never shipping or tax.</p>
25
+ </form>
26
+ {% endif %}
27
+
28
+ {% if state == "loading" %}
29
+ <div class="state-panel" role="status" aria-live="polite">
30
+ <p>Loading results…</p>
31
+ <a href="/search?q={{ query | replace(' ', '+') }}{% if max_price %}&amp;max={{ max_price }}{% endif %}">Retry</a>
32
+ </div>
33
+ {% elif state == "error" %}
34
+ <div class="state-panel state-error" role="alert">
35
+ <p>Something went wrong loading results. Retry to keep your query and price filter.</p>
36
+ <a href="/search?q={{ query | replace(' ', '+') }}{% if max_price %}&amp;max={{ max_price }}{% endif %}">Retry search</a>
37
+ </div>
38
+ {% elif state == "empty" or not cards %}
39
+ <div class="state-panel">
40
+ <p>We couldn't find any results for this query.</p>
41
+ <p class="muted">Try searching for a personalized leather wallet,
42
+ custom dog collar, blue ceramic vase, or wooden bookshelf.</p>
43
+ <a href="/">Back to home</a>
44
+ </div>
45
+ {% else %}
46
+ <p class="results-note">{{ sampled_note }}</p>
47
+ {% if divergence_note %}
48
+ <p class="divergence-note muted" role="note">{{ divergence_note }}</p>
49
+ {% endif %}
50
+ <ol class="results-grid">
51
+ {% for card in cards %}
52
+ <li class="listing-card" data-listing-id="{{ card.listing_id }}">
53
+ <a href="/listing/{{ card.listing_id }}/{{ card.slug }}">
54
+ <img src="{{ card.image }}" alt="{{ card.title }}" width="765" height="956" loading="lazy">
55
+ <h2 class="card-title">{{ card.title }}</h2>
56
+ </a>
57
+ <p class="card-price" data-price-usd="{{ card.price_usd }}">${{ card.price_usd }}</p>
58
+ {% if card.badges %}
59
+ <ul class="card-badges">
60
+ {% for badge in card.badges %}<li>{{ badge }}</li>{% endfor %}
61
+ </ul>
62
+ {% endif %}
63
+ <form action="/favorites/toggle" method="post" class="inline-form">
64
+ <input type="hidden" name="listing_id" value="{{ card.listing_id }}">
65
+ <input type="hidden" name="action" value="add">
66
+ <input type="hidden" name="next" value="{{ request.url.path }}?q={{ query | replace(' ', '+') }}{% if max_price %}&amp;max={{ max_price }}{% endif %}">
67
+ <button type="submit" class="fav-button">Add to Favorites</button>
68
+ </form>
69
+ </li>
70
+ {% endfor %}
71
+ </ol>
72
+ {% endif %}
73
+ </section>
74
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/signin.html ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ {#
4
+ Structure follows the 2026-08-06 capture of www.etsy.com/signin:
5
+ title "Sign in | Etsy", lang en-US, heading
6
+ "Sign in or create an account to start shopping", form id `join-neu-form`
7
+ with method post, and the provider row Google / Facebook / Apple.
8
+
9
+ The captured surface is provider-first: every one of its inputs is
10
+ type="hidden" and no email or password field is painted on first load. The
11
+ email form below is therefore *not* captured structure — it is the working
12
+ local sign-in this site requires, and it is marked as such rather than being
13
+ presented as source fidelity.
14
+ #}
15
+ <section class="signin-page" data-auth-pane="sign-in">
16
+ {% if favorite_listing %}
17
+ <div class="favorite-auth-preview">
18
+ <img src="{{ favorite_listing.image }}" alt="">
19
+ <div><h1>Add to favorites</h1><p>{{ favorite_listing.title }}</p></div>
20
+ </div>
21
+ <h2>Before you can do that...</h2>
22
+ {% else %}
23
+ <div class="auth-heading-row"><h1>Sign in</h1><a href="/register?next={{ from_page }}">Register</a></div>
24
+ {% endif %}
25
+ {% if unauthorized %}
26
+ <div class="state-panel state-error" role="alert">
27
+ <p>Sign in to save and manage your favorite items.</p>
28
+ </div>
29
+ {% endif %}
30
+ {% if auth_error %}
31
+ <div class="state-panel state-error" role="alert"><p>{{ auth_error }}</p></div>
32
+ {% endif %}
33
+
34
+ {% include "_auth_providers.html" %}
35
+
36
+ <div class="auth-divider" role="separator"><span>or</span></div>
37
+
38
+ <form id="join-neu-form" class="signin-form" action="/auth/sign-in" method="post">
39
+ <input type="hidden" name="csrf" value="{{ csrf }}">
40
+ <input type="hidden" name="from_page" value="{{ from_page }}">
41
+ <input type="hidden" name="initial_state" value="sign-in">
42
+ <label for="signin-email">Email address</label>
43
+ <input id="signin-email" name="email" type="email" autocomplete="email" placeholder="Enter your email" required>
44
+ <label for="signin-password">Password</label>
45
+ <input id="signin-password" name="password" type="password"
46
+ autocomplete="current-password" placeholder="Enter password" required>
47
+ <button type="submit">Sign in</button>
48
+ </form>
49
+ <p><a href="/recover">Reset password</a> · <a href="/help">Trouble signing in?</a></p>
50
+ </section>
51
+ {% endblock %}
tasks/etsy/environment/reference/clone/frontend/templates/verify.html ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block content %}
3
+ <section class="signin-page">
4
+ <h1>Verify your email</h1>
5
+ {% if errors %}
6
+ <div class="state-panel state-error" role="alert">
7
+ {% for error in errors %}<p>{{ error }}</p>{% endfor %}
8
+ </div>
9
+ {% endif %}
10
+ <p><a href="/auth/inbox?purpose={{ purpose }}">Open verification message</a></p>
11
+ <form class="signin-form" action="/register/verify" method="post">
12
+ <input type="hidden" name="csrf" value="{{ csrf }}">
13
+ <input type="hidden" name="next" value="{{ next_path }}">
14
+ <label for="verify-code">Six-digit code</label>
15
+ <input id="verify-code" name="code" inputmode="numeric"
16
+ pattern="[0-9]{6}" autocomplete="one-time-code" required>
17
+ <button type="submit">Verify and create account</button>
18
+ </form>
19
+ </section>
20
+ {% endblock %}
tasks/etsy/environment/reference/clone/harbor_entry.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WebsiteBench Harbor foreground entrypoint for the frozen clone."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import secrets
9
+ import smtplib
10
+ import urllib.error
11
+ import urllib.parse
12
+ import urllib.request
13
+ from email.message import EmailMessage
14
+ from pathlib import Path
15
+
16
+ import uvicorn
17
+
18
+
19
+ ROOT = Path(__file__).resolve().parent
20
+ SITE_ROOT = ROOT.parent
21
+ RUNTIME = json.loads((SITE_ROOT / "backend" / "runtime.json").read_text(encoding="utf-8"))
22
+ SITE_ID = str(RUNTIME["site"]["id"])
23
+ DATA_DIR = Path(os.environ["DATA_DIR"])
24
+ if not DATA_DIR.is_absolute():
25
+ raise RuntimeError("DATA_DIR must be absolute")
26
+ DATA_DIR = DATA_DIR.resolve()
27
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
28
+ os.environ["WEBSITEBENCH_DATA_DIR"] = str(DATA_DIR)
29
+ os.environ["WEBSITEBENCH_SITE_BACKEND_RUNTIME"] = str(SITE_ROOT / "backend" / "runtime.json")
30
+ os.environ["WEBSITEBENCH_SITE_BACKEND_DATABASE"] = str(DATA_DIR / RUNTIME["database"]["filename"])
31
+ if os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL", "").strip():
32
+ os.environ["WEBSITEBENCH_DEPLOYMENT_PROFILE"] = "offline-harbor"
33
+ os.environ["WEBSITEBENCH_PAYMENT_PROFILE"] = "local-sandbox"
34
+
35
+
36
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
37
+ def redirect_request(self, request, fp, code, msg, headers, newurl):
38
+ del request, fp, code, msg, headers, newurl
39
+ return None
40
+
41
+
42
+ def _harbor_mailbox_identity() -> dict[str, object] | None:
43
+ bootstrap_url = os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL", "").strip()
44
+ bootstrap_token = os.environ.get(
45
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN", ""
46
+ ).strip()
47
+ if not bootstrap_url and not bootstrap_token:
48
+ return None
49
+ parsed = urllib.parse.urlsplit(bootstrap_url)
50
+ if (
51
+ parsed.scheme != "http"
52
+ or parsed.hostname not in {
53
+ "127.0.0.1",
54
+ "::1",
55
+ "localhost",
56
+ "mailbox-internal",
57
+ }
58
+ or parsed.username is not None
59
+ or parsed.password is not None
60
+ or len(bootstrap_token) < 32
61
+ ):
62
+ raise RuntimeError("Harbor mailbox bootstrap configuration is invalid")
63
+ request = urllib.request.Request(
64
+ bootstrap_url,
65
+ headers={
66
+ "Accept": "application/json",
67
+ "Authorization": f"Bearer {bootstrap_token}",
68
+ },
69
+ method="GET",
70
+ )
71
+ try:
72
+ with urllib.request.build_opener(_NoRedirect).open(
73
+ request, timeout=10
74
+ ) as response:
75
+ raw = response.read(64 * 1024 + 1)
76
+ except (OSError, urllib.error.URLError) as exc:
77
+ raise RuntimeError("Harbor mailbox bootstrap is unavailable") from exc
78
+ if len(raw) > 64 * 1024:
79
+ raise RuntimeError("Harbor mailbox bootstrap response is too large")
80
+ try:
81
+ identity = json.loads(raw.decode("utf-8"))
82
+ namespace = str(identity["namespace"])
83
+ capability = str(identity["capability"])
84
+ smtp_host = str(identity["smtp_host"])
85
+ smtp_port = int(identity["smtp_port"])
86
+ except (KeyError, TypeError, ValueError, UnicodeError, json.JSONDecodeError) as exc:
87
+ raise RuntimeError("Harbor mailbox bootstrap response is invalid") from exc
88
+ if (
89
+ re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", namespace) is None
90
+ or len(namespace) > 128
91
+ or len(capability) < 32
92
+ or smtp_host not in {"127.0.0.1", "::1", "localhost", "mailbox-internal"}
93
+ or not 1 <= smtp_port <= 65535
94
+ ):
95
+ raise RuntimeError("Harbor mailbox identity is invalid")
96
+ return {
97
+ "namespace": namespace,
98
+ "capability": capability,
99
+ "smtp_host": smtp_host,
100
+ "smtp_port": smtp_port,
101
+ }
102
+
103
+
104
+ MAILBOX_IDENTITY = _harbor_mailbox_identity()
105
+ MAIL_WORKER_TOKEN = secrets.token_hex(32) if MAILBOX_IDENTITY is not None else None
106
+ if MAIL_WORKER_TOKEN is not None:
107
+ os.environ["ETSY_HARBOR_MAIL_WORKER_TOKEN"] = MAIL_WORKER_TOKEN
108
+
109
+ import app as clone_module # noqa: E402
110
+
111
+ clone_app = clone_module.app
112
+
113
+
114
+ def _deliver_harbor_mail() -> None:
115
+ """Compatibility hook; the auth store delivers synchronously to Mailpit."""
116
+
117
+ return None
118
+
119
+ HEALTH_BODY = b'{"status":"ok"}'
120
+ # /healthz is the contract (ADR-0010); the private path stays mounted
121
+ # so bundles frozen before the migration keep answering.
122
+ HEALTH_PATHS = ("/healthz", "/__websitebench/health")
123
+
124
+
125
+ async def application(scope, receive, send):
126
+ if scope.get("type") == "http" and scope.get("path") in HEALTH_PATHS:
127
+ await send({
128
+ "type": "http.response.start",
129
+ "status": 200,
130
+ "headers": [
131
+ (b"content-type", b"application/json"),
132
+ (b"content-length", str(len(HEALTH_BODY)).encode("ascii")),
133
+ (b"cache-control", b"no-store"),
134
+ ],
135
+ })
136
+ await send({"type": "http.response.body", "body": HEALTH_BODY})
137
+ return
138
+
139
+ async def deliver_before_final_body(message):
140
+ if (
141
+ message.get("type") == "http.response.body"
142
+ and not message.get("more_body", False)
143
+ ):
144
+ _deliver_harbor_mail()
145
+ await send(message)
146
+
147
+ await clone_app(scope, receive, deliver_before_final_body)
148
+
149
+
150
+ if __name__ == "__main__":
151
+ uvicorn.run(
152
+ application,
153
+ host=os.environ["HOST"],
154
+ port=int(os.environ["PORT"]),
155
+ access_log=False,
156
+ timeout_graceful_shutdown=2,
157
+ )
tasks/etsy/environment/reference/clone/static/app.js ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Etsy storefront interactions. */
2
+
3
+ (function () {
4
+ "use strict";
5
+
6
+ function ready(fn) {
7
+ if (document.readyState !== "loading") { fn(); return; }
8
+ document.addEventListener("DOMContentLoaded", fn);
9
+ }
10
+
11
+ ready(function () {
12
+ // Source-faithful category menu. It is a real button/overlay on every
13
+ // viewport, closes on outside click or Escape, and leaves each menu item
14
+ // as a plain link when JavaScript is unavailable.
15
+ var toggle = document.querySelector(".cat-toggle");
16
+ var nav = document.getElementById("category-menu");
17
+ var scrim = document.querySelector("[data-category-scrim]");
18
+ if (toggle && nav) {
19
+ var setCategoryOpen = function (open) {
20
+ toggle.setAttribute("aria-expanded", String(open));
21
+ nav.hidden = !open;
22
+ if (scrim) { scrim.hidden = !open; }
23
+ };
24
+ toggle.addEventListener("click", function (event) {
25
+ event.stopPropagation();
26
+ setCategoryOpen(toggle.getAttribute("aria-expanded") !== "true");
27
+ });
28
+ if (scrim) { scrim.addEventListener("click", function () { setCategoryOpen(false); }); }
29
+ document.addEventListener("click", function (event) {
30
+ if (!nav.hidden && !nav.contains(event.target)) { setCategoryOpen(false); }
31
+ });
32
+ document.addEventListener("keydown", function (event) {
33
+ if (event.key === "Escape" && !nav.hidden) {
34
+ setCategoryOpen(false);
35
+ toggle.focus();
36
+ }
37
+ });
38
+ }
39
+
40
+ // Header search band: an ARIA combobox layered over the real GET form.
41
+ // Debounced, single-flight via AbortController, with a monotonic sequence
42
+ // guard so a slow early response cannot overwrite a newer one. Every
43
+ // suggestion is a query this database actually resolves, so choosing one
44
+ // always lands on a real results page. With scripting off the form
45
+ // submits to /search exactly as before.
46
+ var band = document.querySelector("[data-search-band]");
47
+ if (band) {
48
+ var input = band.querySelector("[data-search-input]");
49
+ var list = band.querySelector("[data-search-list]");
50
+ var status = band.querySelector("[data-search-status]");
51
+ var endpoint = band.getAttribute("data-suggest-endpoint");
52
+ var timer = null;
53
+ var controller = null;
54
+ var sequence = 0;
55
+ var settled = 0;
56
+ var active = -1;
57
+
58
+ var closeList = function () {
59
+ list.hidden = true;
60
+ list.innerHTML = "";
61
+ input.setAttribute("aria-expanded", "false");
62
+ input.removeAttribute("aria-activedescendant");
63
+ active = -1;
64
+ };
65
+
66
+ var highlight = function (next) {
67
+ var options = list.querySelectorAll("[role=option]");
68
+ if (!options.length) { return; }
69
+ if (next < 0) { next = options.length - 1; }
70
+ if (next >= options.length) { next = 0; }
71
+ active = next;
72
+ Array.prototype.forEach.call(options, function (option, index) {
73
+ var on = index === active;
74
+ option.setAttribute("aria-selected", String(on));
75
+ option.classList.toggle("active", on);
76
+ if (on) { input.setAttribute("aria-activedescendant", option.id); }
77
+ });
78
+ };
79
+
80
+ var draw = function (results) {
81
+ if (!results.length) {
82
+ closeList();
83
+ status.textContent = "No matching searches.";
84
+ return;
85
+ }
86
+ list.innerHTML = "";
87
+ results.forEach(function (result, index) {
88
+ var item = document.createElement("li");
89
+ item.id = "global-search-option-" + index;
90
+ item.setAttribute("role", "option");
91
+ item.setAttribute("aria-selected", "false");
92
+ var link = document.createElement("a");
93
+ link.href = "/search?q=" + encodeURIComponent(result.query);
94
+ link.textContent = result.query;
95
+ var count = document.createElement("span");
96
+ count.className = "suggestion-count";
97
+ count.textContent = result.results + " results";
98
+ link.appendChild(count);
99
+ item.appendChild(link);
100
+ list.appendChild(item);
101
+ });
102
+ list.hidden = false;
103
+ input.setAttribute("aria-expanded", "true");
104
+ active = -1;
105
+ status.textContent =
106
+ results.length + (results.length === 1 ? " search" : " searches") + " suggested.";
107
+ };
108
+
109
+ var fetchSuggestions = function (query) {
110
+ if (controller) { controller.abort(); }
111
+ controller = new AbortController();
112
+ var ticket = ++sequence;
113
+ fetch(endpoint + "?q=" + encodeURIComponent(query), {
114
+ signal: controller.signal,
115
+ headers: { "Accept": "application/json" }
116
+ })
117
+ .then(function (response) {
118
+ if (!response.ok) { throw new Error("suggest failed"); }
119
+ return response.json();
120
+ })
121
+ .then(function (payload) {
122
+ if (ticket <= settled) { return; }
123
+ settled = ticket;
124
+ draw((payload && payload.results) || []);
125
+ })
126
+ .catch(function (error) {
127
+ if (error && error.name === "AbortError") { return; }
128
+ closeList();
129
+ status.textContent = "Suggestions unavailable. Press Enter to search.";
130
+ });
131
+ };
132
+
133
+ input.addEventListener("input", function () {
134
+ var query = input.value.trim();
135
+ if (timer) { window.clearTimeout(timer); }
136
+ if (query.length < 2) {
137
+ if (controller) { controller.abort(); }
138
+ closeList();
139
+ status.textContent = "";
140
+ return;
141
+ }
142
+ timer = window.setTimeout(function () { fetchSuggestions(query); }, 180);
143
+ });
144
+
145
+ input.addEventListener("keydown", function (event) {
146
+ if (list.hidden) { return; }
147
+ if (event.key === "ArrowDown") { event.preventDefault(); highlight(active + 1); }
148
+ else if (event.key === "ArrowUp") { event.preventDefault(); highlight(active - 1); }
149
+ else if (event.key === "Escape") { closeList(); }
150
+ else if (event.key === "Enter" && active >= 0) {
151
+ var chosen = list.querySelectorAll("[role=option] a")[active];
152
+ if (chosen) { event.preventDefault(); window.location.assign(chosen.href); }
153
+ }
154
+ });
155
+
156
+ document.addEventListener("click", function (event) {
157
+ if (!band.contains(event.target)) { closeList(); }
158
+ });
159
+ closeList();
160
+ }
161
+
162
+ // Homepage feature carousel. The source controls are buttons that cycle
163
+ // through distinct image/copy/CTA panels without navigating away. There
164
+ // is deliberately no autoplay, so the page remains stable for keyboard,
165
+ // touch, and assistive-technology users.
166
+ var carousel = document.querySelector("[data-hero-carousel]");
167
+ if (carousel) {
168
+ var slides = Array.prototype.slice.call(
169
+ carousel.querySelectorAll("[data-hero-slide]")
170
+ );
171
+ var previous = carousel.querySelector('[data-carousel-direction="previous"]');
172
+ var next = carousel.querySelector('[data-carousel-direction="next"]');
173
+ var carouselStatus = carousel.querySelector("[data-carousel-status]");
174
+ var activeSlide = 0;
175
+
176
+ var showSlide = function (index) {
177
+ if (!slides.length) { return; }
178
+ activeSlide = (index + slides.length) % slides.length;
179
+ slides.forEach(function (slide, slideIndex) {
180
+ var active = slideIndex === activeSlide;
181
+ slide.hidden = !active;
182
+ slide.setAttribute("aria-hidden", String(!active));
183
+ });
184
+ if (carouselStatus) {
185
+ carouselStatus.textContent =
186
+ "Feature " + (activeSlide + 1) + " of " + slides.length;
187
+ }
188
+ };
189
+
190
+ if (previous) {
191
+ previous.addEventListener("click", function () { showSlide(activeSlide - 1); });
192
+ }
193
+ if (next) {
194
+ next.addEventListener("click", function () { showSlide(activeSlide + 1); });
195
+ }
196
+ showSlide(0);
197
+ }
198
+
199
+ // Favourite controls stay real POST forms — this only announces the
200
+ // outcome, which a full page navigation would otherwise leave silent for
201
+ // a screen-reader user, and marks the toggle state for assistive tech.
202
+ document.querySelectorAll(".favorite-form").forEach(function (form) {
203
+ var button = form.querySelector("button[type=submit]");
204
+ if (!button) { return; }
205
+ var action = form.querySelector("input[name=action]");
206
+ var adding = !action || action.value === "add";
207
+ button.setAttribute("aria-pressed", String(!adding));
208
+ form.addEventListener("submit", function () {
209
+ button.setAttribute("data-submitting", "true");
210
+ var live = form.querySelector("[data-favorite-status]");
211
+ if (live) {
212
+ live.textContent = adding ? "Adding to favorites…" : "Removing from favorites…";
213
+ }
214
+ });
215
+ });
216
+
217
+ // First-visit cookie-consent overlay reproduction. Session-scoped
218
+ // (sessionStorage) disposable UI state only; Escape and Okay dismiss it.
219
+ var overlay = document.getElementById("cookie-overlay");
220
+ if (overlay) {
221
+ var seen = false;
222
+ try { seen = window.sessionStorage.getItem("cookie-overlay") === "1"; }
223
+ catch (error) { seen = true; }
224
+ if (!seen) {
225
+ overlay.hidden = false;
226
+ var okay = overlay.querySelector(".cookie-okay");
227
+ var dismiss = function () {
228
+ overlay.hidden = true;
229
+ try { window.sessionStorage.setItem("cookie-overlay", "1"); }
230
+ catch (error) { /* disposable */ }
231
+ };
232
+ if (okay) {
233
+ okay.addEventListener("click", dismiss);
234
+ okay.focus();
235
+ }
236
+ document.addEventListener("keydown", function (event) {
237
+ if (event.key === "Escape" && !overlay.hidden) { dismiss(); }
238
+ });
239
+ }
240
+ }
241
+ });
242
+ })();
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-app-badge-01.png ADDED

Git LFS Details

  • SHA256: 5d83943af08e27a5eea5d7e1b6fa98d3583e30462305ef44c228d961e957429f
  • Pointer size: 129 Bytes
  • Size of remote file: 3.09 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-app-badge-02.png ADDED

Git LFS Details

  • SHA256: ae5631a93ecb4e5eb2f8c826deb0db946962ca458185e7134337828e50e906ee
  • Pointer size: 129 Bytes
  • Size of remote file: 2.59 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-blog-22.jpg ADDED

Git LFS Details

  • SHA256: c6b95db254937859ad30c7ce62992e44cf5cc0f690486511cd52a6117b6b5a20
  • Pointer size: 129 Bytes
  • Size of remote file: 4.38 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-blog-23.jpg ADDED

Git LFS Details

  • SHA256: 5b133f9bd18821f898ca3a42521111ab8c56954b8fe5136b07c20331bcc3b05a
  • Pointer size: 129 Bytes
  • Size of remote file: 3.46 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-blog-24.jpg ADDED

Git LFS Details

  • SHA256: 9ba20be7591cf00eb7db399691d90bdee3522eb8eae9adb688b37e0d7f39efa1
  • Pointer size: 129 Bytes
  • Size of remote file: 4.37 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-11.jpg ADDED

Git LFS Details

  • SHA256: 70efb489100dd1c0c8669a90dc8a836eb47d6178ec241f439dee57086576f4d0
  • Pointer size: 129 Bytes
  • Size of remote file: 7.72 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-12.jpg ADDED

Git LFS Details

  • SHA256: 6fd93eb560235abef416e0a121677f884561f2c516ade2e8bfdf88c798f47ed3
  • Pointer size: 130 Bytes
  • Size of remote file: 59 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-13.jpg ADDED

Git LFS Details

  • SHA256: 32b79a79c16ce9b21e26e5d9cc22d4fdf1f9eb7650bd3abfb46aca216aa63765
  • Pointer size: 130 Bytes
  • Size of remote file: 32.1 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-14.jpg ADDED

Git LFS Details

  • SHA256: 2394ce4a5a71bfcd2bbc0d21cd767f28516fce537bc63a0ee03e7755ce0dd524
  • Pointer size: 130 Bytes
  • Size of remote file: 74.9 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-15.jpg ADDED

Git LFS Details

  • SHA256: c961f88af7a893fc0f925860bbcc3e49282bf86e1d7a4da0e48124d16bef8096
  • Pointer size: 130 Bytes
  • Size of remote file: 85.6 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-category-16.jpg ADDED

Git LFS Details

  • SHA256: 7665ec8cd2c01d7cf832008cefaaf9884f2e8ac7eb35f95497fc86e670cd0ff6
  • Pointer size: 130 Bytes
  • Size of remote file: 42 kB
tasks/etsy/environment/reference/clone/static/assets/source-current/2026-07-25/home-media/home-deal-and-shop-17.jpg ADDED

Git LFS Details

  • SHA256: 27385933d235beb57b956ee0184b7f7e2fa5b9f945616d8e4e469cca2de6ea0a
  • Pointer size: 130 Bytes
  • Size of remote file: 56.5 kB