File size: 47,212 Bytes
5b847ea | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | #!/usr/bin/env python3
from __future__ import annotations
import base64
import html
import ipaddress
import mimetypes
import os
import re
import sys
from http import cookies
from pathlib import Path
from urllib.parse import parse_qs, quote, urlsplit
from wsgiref.simple_server import make_server
from websitebench.local_clone_auth import AuthError
from websitebench.site_backend import PaymentError
ROOT=Path(__file__).resolve().parent
sys.path.insert(0,str(ROOT))
from backend.site_backend_integration import open_site_services
from backend import business
BACKEND, AUTH = open_site_services()
business.initialize(BACKEND)
try:
AUTH.seed_account(subject_id="dooney-seeded-shopper", email="shopper@example.test", display_name="Avery Shopper", password="WebsiteBench!041")
except Exception:
pass
def esc(v): return html.escape(str(v), quote=True)
def money(n): return f"${n/100:,.2f}"
def form(environ):
try: size=min(int(environ.get("CONTENT_LENGTH") or 0),32768)
except ValueError: size=0
return {k:v[-1] for k,v in parse_qs(environ["wsgi.input"].read(size).decode("utf-8","replace"),keep_blank_values=True).items()}
def owner(session): return AUTH.session_owner_digest(session)
SECURITY_HEADERS=(
("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"),
("X-Content-Type-Options", "nosniff"),
("Referrer-Policy", "same-origin"),
("X-Frame-Options", "DENY"),
("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()"),
)
STATIC_CACHE_HEADERS=(("Cache-Control", "public, max-age=3600"),)
def request_origin_allowed(environ):
origin=environ.get("HTTP_ORIGIN")
if not origin:
return True
parsed=urlsplit(origin); host=environ.get("HTTP_HOST",""); scheme=environ.get("wsgi.url_scheme","http").lower()
return parsed.scheme==scheme and parsed.netloc==host and parsed.username is None and parsed.password is None and not parsed.path and not parsed.query and not parsed.fragment
def safe_return_path(environ,default="/collections/bags"):
referer=environ.get("HTTP_REFERER","")
if not referer:
return default
parsed=urlsplit(referer); host=environ.get("HTTP_HOST","")
if parsed.scheme and (parsed.scheme not in {"http","https"} or parsed.netloc!=host):
return default
path=parsed.path or "/"
if not path.startswith("/") or path.startswith("//") or "\\" in path:
return default
return path+(f"?{parsed.query}" if parsed.query else "")
def secure_cookie_context(environ):
if environ.get("wsgi.url_scheme", "http").lower() == "https":
return True
hostname=(urlsplit(f"//{environ.get('HTTP_HOST', '')}").hostname or "").lower()
if hostname == "localhost" or hostname.endswith(".localhost"):
return True
try:
return ipaddress.ip_address(hostname).is_loopback
except ValueError:
return False
def session_cookie_name(environ):
return "__Host-wb-dooney-bourke" if secure_cookie_context(environ) else "wb-dooney-bourke-local"
def session_cookie_header(environ,session,max_age=None):
value=f"{session_cookie_name(environ)}={session}; Path=/; HttpOnly; SameSite=Lax"
if secure_cookie_context(environ):
value+="; Secure"
if max_age is not None:
value+=f"; Max-Age={max_age}"
return ("Set-Cookie",value)
def response(start,status,body,headers=()):
payload=body if isinstance(body,bytes) else body.encode()
start_response=f"{status} { {200:'OK',302:'Found',303:'See Other',400:'Bad Request',403:'Forbidden',404:'Not Found',405:'Method Not Allowed'}.get(status,'OK')}"
start(start_response,[*headers,*SECURITY_HEADERS,("Content-Length",str(len(payload)))])
return [payload]
def redirect(start,path,headers=()): return response(start,303,b"",tuple(headers)+(("Location",path),))
TOP_LOGO='<img class="logo" src="/static/assets/icons/dooney-logo-black.svg" alt="Dooney & Bourke">'
LOGO='<img class="logo" src="/static/source/main-logo.svg" alt="Dooney & Bourke">'
LOVE_LOGO='<img class="love-logo" src="/static/source/love-logo.svg" alt="I Love Dooney">'
MENU_ICON='''<svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M3 12H21M3 6H21M3 18H21" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'''
SEARCH_ICON='''<svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M21 21L15.0001 15M17 10C17 13.866 13.866 17 10 17C6.13401 17 3 13.866 3 10C3 6.13401 6.13401 3 10 3C13.866 3 17 6.13401 17 10Z" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'''
BAG_ICON='''<svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M16.0004 9V6C16.0004 3.79086 14.2095 2 12.0004 2C9.79123 2 8.00037 3.79086 8.00037 6V9M3.59237 10.352L2.99237 16.752C2.82178 18.5717 2.73648 19.4815 3.03842 20.1843C3.30367 20.8016 3.76849 21.3121 4.35839 21.6338C5.0299 22 5.94374 22 7.77142 22H16.2293C18.057 22 18.9708 22 19.6423 21.6338C20.2322 21.3121 20.6971 20.8016 20.9623 20.1843C21.2643 19.4815 21.179 18.5717 21.0084 16.752L20.4084 10.352C20.2643 8.81535 20.1923 8.04704 19.8467 7.46616C19.5424 6.95458 19.0927 6.54511 18.555 6.28984C17.9444 6 17.1727 6 15.6293 6L8.37142 6C6.82806 6 6.05638 6 5.44579 6.28984C4.90803 6.54511 4.45838 6.95458 4.15403 7.46616C3.80846 8.04704 3.73643 8.81534 3.59237 10.352Z" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'''
def header(cart_count, authenticated=False):
nav=[("BAGS","/collections/bags"),("ACCESSORIES","/collections/accessories"),("COLLECTIONS","/collections/all"),("SPORTS","/pages/sports"),("SHOES","/collections/shoes"),("UNDER $100","/collections/under-100"),("SALE","/collections/sale")]
count=f'<sup>{cart_count}</sup>' if cart_count else ''
return f'''<a class="skip" href="#main">Skip to content</a><div class="brandbar"><a href="/">{TOP_LOGO}</a><b>{LOVE_LOGO}</b><span>● Help Center 🇨🇦 Canada</span></div><div class="offer">Dooney Hour: Up To 60% Off Starts Now <a href="/collections/sale">(Details)</a></div><header><button class="mobile-menu" aria-label="Menu" aria-controls="primary" aria-expanded="false">{MENU_ICON}</button><a href="/">{LOGO}</a><nav id="primary">{''.join(f'<a href="{u}">{t}</a>' for t,u in nav)}</nav><div class="icons"><button class="search-toggle" aria-label="Open search">{SEARCH_ICON}</button><a href="/account" aria-label="Account">♙</a><a href="/cart" aria-label="Bag">{BAG_ICON}{count}</a></div><form class="quick-search" action="/search"><input name="q" type="search" placeholder="Search Dooney & Bourke" aria-label="Search"><button>SEARCH</button></form></header><div class="luxury">Discover Luxury for Less <a href="/collections/sale">SHOP NOW</a></div>'''
FOOTER='''<footer><div><h2>Timeless Styles.<br>Exceptional Craftsmanship.<br>Unconditional Guarantee.</h2></div><div><h3>Get In Touch</h3><a href="/pages/contact">Contact Us</a><a href="/pages/stores">Store Locator</a><a href="/pages/track-your-order">Track Your Order</a><a href="/pages/help">Help Center</a><a href="/account">Register My Dooney</a></div><div><h3>Orders & Payments</h3><a href="/pages/orders-payments">Orders & Payments</a><a href="/pages/shipping">Shipping</a><a href="/pages/refund-policy">Returns</a><a href="/pages/repair">Repair Request</a></div><div><h3>Our Brand</h3><a href="/pages/about">About Us</a><a href="/pages/guarantee">The Dooney Guarantee</a><a href="/collections/all">Shop All</a></div><div class="newsletter"><h3>Stay In The Know</h3><p>Sign up for the latest product stories & more.</p><div class="fake-input">Email <b>SUBMIT</b></div><small>This offline clone never sends newsletter email.</small></div><small>© Copyright 2026 Dooney & Bourke. Local WebsiteBench simulation.</small></footer>'''
COOKIE_BANNER='''<section class="cookie-banner" role="dialog" aria-label="Cookie preferences"><button class="cookie-close" data-cookie-choice="decline" aria-label="Close cookie preferences">✕</button><div class="cookie-monogram" aria-hidden="true"><img src="/static/source/cookie-logo.png" alt=""></div><p>Please select whether you consent to our use of cookies and related technologies (“Cookies”), as described in our privacy policy. Expand each section below for more information. You can return at any time from the same web browser to update your preferences. Please note that resetting your browser’s cookies will reset your preferences. <a href="/pages/privacy">Learn more</a></p><div class="cookie-actions"><button class="preferences" data-cookie-choice="preferences">Preferences</button><button data-cookie-choice="accept">Accept</button><button data-cookie-choice="decline">Decline</button></div></section>'''
NEWSLETTER_DIALOG='''<div class="newsletter-backdrop"><section class="newsletter-dialog" role="dialog" aria-modal="true" aria-labelledby="newsletter-title"><button class="newsletter-close" data-close-newsletter aria-label="Close newsletter signup">×</button><div class="newsletter-copy"><h2 id="newsletter-title">Be the First to Know</h2><p>Subscribe to be the first to discover new<br>arrivals and receive exclusive offers from<br>Dooney & Bourke.</p><label class="visually-hidden" for="newsletter-email">Email</label><input id="newsletter-email" type="email" placeholder="Email"><button type="button" data-newsletter-continue>Continue</button><small class="newsletter-status" role="status"></small></div><img src="/static/assets/images/home/newsletter-source.webp.b64" alt="Dooney & Bourke leather bag styling"></section></div>'''
def page(title,body,session,status=200):
c=business.cart(BACKEND,owner(session)); auth=AUTH.resolve_session(session) or {}
newsletter=NEWSLETTER_DIALOG if title=="Dooney & Bourke | Iconic American Leather Goods" else ""
return status,f'''<!doctype html><html lang="en-CA"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{esc(title)}</title><link rel="stylesheet" href="/static/site.css"><script src="/static/site.js" defer></script></head><body>{header(c['quantity'],auth.get('authenticated',False))}<main id="main">{body}</main>{FOOTER}{newsletter}{COOKIE_BANNER}</body></html>'''
def cards(products,wished):
def one(p):
rating=f"★ {p['rating']}" if p.get('rating') else "Source-observed item"
reviews=f" ({p['reviews']} Reviews)" if p.get('reviews') else ""
compare=f" <del>{money(p['compare_minor'])}</del>" if p['compare_minor']>p['price_minor'] else ""
return f'''<article class="card" data-category="{esc(p.get('category','Bags'))}"><form action="/wishlist/toggle" method="post"><input type="hidden" name="handle" value="{esc(p['handle'])}"><button aria-label="{'Remove from' if p['handle'] in wished else 'Add to'} wishlist">{'♥' if p['handle'] in wished else '♡'}</button></form><a href="/products/{esc(p['handle'])}"><div class="bag-picture"><img src="{esc(p['asset'])}" alt="{esc(p['title'])}" loading="lazy"></div><small>{esc(p.get('category','Bags').upper())}</small><h3>{esc(p['title'])}</h3><p>{rating}{reviews}</p><b>{money(p['price_minor'])}</b>{compare}</a></article>'''
return ''.join(one(p) for p in products)
def home(session):
wished=business.wishlist(BACKEND,owner(session))
body=f'''<section class="hero"><div><small>UP TO 40% OFF</small><h1>The Private Sale</h1><p>Step inside for special savings on timeless favorites you know and love.</p><a class="outline" href="/collections/sale">SHOP NOW</a></div><picture class="hero-media"><source media="(max-width: 760px)" srcset="/static/source/home-offer-mobile.webp"><img src="/static/assets/images/home/private-sale-desktop.webp" alt="The Private Sale"></picture></section><section class="intro"><p>EST. 1975</p><h2>Made for a Lifetime</h2><p>Iconic American design, exceptional Italian leather, and bags made to be carried every day.</p></section><section class="featured"><h2>Best Sellers</h2><div class="grid">{cards(business.CATALOG[:4],wished)}</div></section>'''
return page("Dooney & Bourke | Iconic American Leather Goods",body,session)
def catalog(session,path,query):
q=query.get("q",[""])[-1].strip(); sort=query.get("sort",["featured"])[-1]; color=query.get("color",[""])[-1]; price=query.get("price",[""])[-1]
base_products=list(business.ALL_PRODUCTS if path=="/search" else business.CATEGORY_CATALOGS.get(path,business.CATALOG)); products=list(base_products)
available_colors=sorted({c for p in base_products for c in p['colors']})
if path=="/search": products=[p for p in products if q.casefold() in (p['title']+' '+p['style']).casefold()]
if color: products=[p for p in products if color in p['colors']]
if price=="under-200": products=[p for p in products if p['price_minor']<20000]
if sort=="price-asc": products.sort(key=lambda p:p['price_minor'])
if sort=="price-desc": products.sort(key=lambda p:p['price_minor'],reverse=True)
title=(f"Search results for: '{q}'" if path=="/search" else {"/collections/accessories":"Shop All Accessories","/collections/sale":"Sale","/collections/shoes":"Shoes","/collections/under-100":"Under $100","/collections/all":"Products","/pages/sports":"Sports"}.get(path,"Shop All Bags"))
filters=f'''<form class="filters" method="get">{f'<input type="hidden" name="q" value="{esc(q)}">' if q else ''}<label>COLOR<select name="color"><option value="">All colors</option>{''.join(f'<option {"selected" if color==c else ""}>{esc(c)}</option>' for c in available_colors)}</select></label><label>PRICE<select name="price"><option value="">All prices</option><option value="under-200" {'selected' if price=='under-200' else ''}>Under $200</option></select></label><label>SORT BY<select name="sort"><option value="featured">Featured</option><option value="price-asc" {'selected' if sort=='price-asc' else ''}>Price, low to high</option><option value="price-desc" {'selected' if sort=='price-desc' else ''}>Price, high to low</option></select></label><button>APPLY</button></form>'''
if not products:
content=f'''<section class="catalog"><h1>{esc(title)}</h1><p class="count">0 results</p>{filters}<div class="empty"><h2>No results found</h2><p>We couldn't find anything for “{esc(q)}”. Check the spelling or explore our bags.</p><a class="black" href="/collections/bags">SHOP BAGS</a></div></section>'''
else: content=f'''<section class="catalog"><h1>{esc(title)}</h1><p class="count">{len(products)} results</p>{filters}<div class="grid">{cards(products,business.wishlist(BACKEND,owner(session)))}</div></section>'''
return page(f"{title} – Dooney & Bourke",content,session)
def product_page(session,handle,query):
p=business.find_product_by_handle(handle)
if p is None:
return page("Page Not Found – Dooney & Bourke",'''<section class="not-found"><span>404</span><h1>Oops! Page not found</h1><p>We couldn't find that product.</p><a class="black" href="/collections/bags">SHOP BAGS</a><a href="/">Continue Shopping</a></section>''',session,404)
color=query.get("color",[p['colors'][0]])[-1]
if color not in p['colors']: color=p['colors'][0]
palette=("#b96036","#f6e9d0","#ca3327","#0a0b0c","#3475b4","#402a16","#222d34","#e4e4df","#8d1e1a","#b9a07d","#1c1b37")
swatches=''.join(f'<a class="swatch {"selected" if c==color else ""}" style="--c:{palette[index] if index < len(palette) else "#777"}" href="?color={quote(c)}" aria-label="{esc(c)}" title="{esc(c)}"></a>' for index,c in enumerate(p['colors']))
main_asset=p['asset']; lifestyle="/static/assets/images/product/pebble-crossbody-lifestyle.webp"
gallery_extra='''<div><img src="/static/assets/images/product/pebble-crossbody-alt1.webp" alt="Pebble Grain Crossbody detail"></div><div><img src="/static/assets/images/product/pebble-crossbody-alt2.webp" alt="Pebble Grain Crossbody interior"></div>''' if p is business.PRODUCT else ''
gallery_second=f'''<div class="lifestyle"><img src="{esc(lifestyle)}" alt="{esc(p['title'])} alternate view"></div>''' if p is business.PRODUCT else ''
rating=f'''<p>★ <b>{p['rating']}</b>{f" {p['reviews']} Reviews" if p.get('reviews') else ''}</p>''' if p.get('rating') else ''
compare=f''' <del>{money(p['compare_minor'])}</del>''' if p['compare_minor']>p['price_minor'] else ''
category=p.get('category','Bags'); category_path={"Accessories":"/collections/accessories","Shoes":"/collections/shoes","Under $100":"/collections/under-100","Sale":"/collections/sale","Sports":"/pages/sports"}.get(category,"/collections/bags")
detail_copy="This source-observed item is represented with its current category image, title, price, style, and available option in the local WebsiteBench catalog."
if p is business.PRODUCT: detail_copy="This top-rated crossbody, made from pebble leather with a natural grain that hides signs of daily wear, is a go-to bag for everyday life that you can dress up or down."
badge="BEST SELLER" if p is business.PRODUCT else category.upper()
body=f'''<div class="crumbs"><a href="/">Home</a> › <a href="{category_path}">{esc(category)}</a> › {esc(p['title'])}</div><section class="product"><div class="gallery"><div><img src="{esc(main_asset)}" alt="{esc(p['title'])} in {esc(color)}"></div>{gallery_second}{gallery_extra}</div><div class="product-info"><small class="badge">{esc(badge)}</small><h1>{esc(p['title'])}</h1>{rating}<hr><div class="meta"><b>Color: <span>{esc(color)}</span></b><span>Style #: {esc(p['style'])}</span></div><h3 class="sale">THE PRIVATE SALE</h3><p class="price"><b>{money(p['price_minor'])}</b>{compare}</p><div class="swatches">{swatches}</div><p class="price"><b>{money(p['price_minor'])}</b>{compare} <span>In stock</span></p><form action="/cart/add" method="post"><input type="hidden" name="handle" value="{esc(p['handle'])}"><input type="hidden" name="color" value="{esc(color)}"><button class="black" name="add">ADD TO BAG</button></form><div class="benefits"><span><img src="/static/assets/icons/shipping.svg" alt="">Flat Rate Shipping</span><span><img src="/static/assets/icons/contact.svg" alt="">Easy Returns</span><span><img src="/static/assets/icons/warranty.svg" alt="">Unconditional Guarantee</span></div></div></section><section class="details"><h2>Product Details</h2><p>{detail_copy}</p><details open><summary>DETAILS</summary><ul><li>Current source-observed category: {esc(category)}.</li><li>Style #: {esc(p['style'])}.</li><li>Selected option: {esc(color)}.</li><li>Local offline inventory status: In stock.</li></ul></details><section class="reviews"><h2>Reviews</h2><p>{'★★★★★ “This is my first crossbody. Absolutely love it. Perfect size.”' if p is business.PRODUCT else 'Rating and review details are shown only when observed in the scoped source evidence.'}</p></section></section>'''
return page(f"{p['title']} – Dooney & Bourke",body,session)
def cart_page(session,message=""):
c=business.cart(BACKEND,owner(session)); totals=business.totals(c)
if not c['quantity']:
removed_product=business.product_by_handle(c.get('product_handle',business.PRODUCT['handle']))
restore=f'''<form action="/cart/restore" method="post"><p>Removed: {esc(removed_product['title'])}</p><button>RESTORE ITEM</button></form>''' if c['removed_quantity'] else ''
return page("Shopping Bag – Dooney & Bourke",f'''<section class="cart"><h1>Shopping Bag ( 0 )</h1>{f'<p class="error" role="alert">{esc(message)}</p>' if message else ''}<div class="empty"><h2>Your Shopping Bag is Empty</h2><p>Explore timeless styles and add a favorite.</p>{restore}<a class="black" href="/collections/bags">CONTINUE SHOPPING</a></div></section>''',session)
promo='SAVE10 applied — 10% off your local bag.' if c['promotion']=='SAVE10' else message
p=business.product_by_handle(c.get('product_handle',business.PRODUCT['handle'])); compare=f''' <del>{money(p['compare_minor'])}</del>''' if p['compare_minor']>p['price_minor'] else ''
body=f'''<section class="cart"><h1>Shopping Bag ( {c['quantity']} )</h1>{f'<p class="notice" role="status">{esc(promo)}</p>' if promo else ''}<div class="cart-layout"><article class="lineitem"><div><img src="{p['asset']}" alt="{esc(p['title'])}"></div><div><h2>{esc(p['title'])}</h2><b>{money(p['price_minor'])}</b>{compare}<p>Color: {esc(c['color'])}</p><p>Style #: {esc(p['style'])}</p><p>In stock</p><form action="/cart/update" method="post"><label>Quantity <input type="number" min="1" max="9" name="quantity" value="{c['quantity']}"></label><button>UPDATE</button></form><form action="/cart/remove" method="post"><button class="link">Remove</button></form></div></article><aside class="summary"><h2>Order Summary</h2><p>Subtotal <b>{money(totals['subtotal'])} CAD</b></p>{f'<p>Discount (SAVE10) <b>−{money(totals["discount"])} CAD</b></p>' if totals['discount'] else ''}<p>Shipping <span>Calculated at checkout</span></p><hr><p class="total">Total <b>{money(totals['total'])} CAD</b></p><form action="/cart/promotion" method="post"><label>Discount code<input name="code" autocomplete="off" placeholder="Discount code"></label><button>APPLY</button></form><a class="black" href="/checkout">CHECKOUT</a><details><summary>Add an order note</summary><textarea aria-label="Order note"></textarea></details></aside></div></section>'''
return page("Shopping Bag – Dooney & Bourke",body,session)
def checkout_page(session,errors=None,sandbox=None):
c=business.cart(BACKEND,owner(session)); saved=business.checkout(BACKEND,owner(session)); errors=errors or {}
t=business.checkout_amounts(c,saved.get('shipping','Standard'))
sandbox_copy=''
if sandbox:
sandbox_role='alert' if sandbox['tone']=='error' else 'status'
sandbox_copy=f'''<p class="sandbox-status {esc(sandbox['tone'])}" role="{sandbox_role}"><b>{esc(sandbox['label'])}</b><br>{esc(sandbox['message'])}</p>'''
if not c['quantity']: return page("Checkout – Dooney & Bourke",f'<section class="empty"><h1>Your bag is empty</h1>{sandbox_copy}<a href="/collections/bags">Return to shopping</a></section>',session)
def field(name,label,typ="text",optional=False):
val=saved.get('contact_email' if name=='email' else name,""); err=errors.get(name,"")
described=f' aria-describedby="error-{name}"' if err else ''
return f'''<label class="field {'invalid' if err else ''}" for="field-{name}">{label}{' (optional)' if optional else ''}<input id="field-{name}" type="{typ}" name="{name}" value="{esc(val)}"{' aria-invalid="true"' if err else ''}{described}></label>{f'<small class="error" id="error-{name}">{esc(err)}</small>' if err else ''}'''
review=saved.get('state')=='review'
province=saved.get('province','Ontario'); shipping=saved.get('shipping','Standard')
country_error=errors.get('country',''); province_error=errors.get('province',''); shipping_error=errors.get('shipping','')
left=f'''<a class="checkout-logo" href="/">{LOGO}</a><h1 class="visually-hidden">Checkout</h1>{sandbox_copy}<h2>Contact</h2>{field('email','Email','email')}<h2>Delivery</h2><label class="field {'invalid' if country_error else ''}" for="field-country">Country/Region<select id="field-country" name="country"{' aria-describedby="error-country" aria-invalid="true"' if country_error else ''}><option value="Canada">Canada</option></select></label>{f'<small class="error" id="error-country">{esc(country_error)}</small>' if country_error else ''}<div class="two">{field('first_name','First name')}{field('last_name','Last name')}</div>{field('address','Address')}{field('apartment','Apartment, suite, etc.',optional=True)}<div class="three">{field('city','City')}<label class="field {'invalid' if province_error else ''}" for="field-province">Province<select id="field-province" name="province"{' aria-describedby="error-province" aria-invalid="true"' if province_error else ''}>{''.join(f'<option value="{p}" {"selected" if province==p else ""}>{p}</option>' for p in ("Ontario","British Columbia","Quebec"))}</select></label>{f'<small class="error" id="error-province">{esc(province_error)}</small>' if province_error else ''}{field('postal_code','Postal code')}</div>{field('phone','Phone','tel')}<h2>Shipping method</h2><fieldset class="shipping-options"{' aria-describedby="error-shipping"' if shipping_error else ''}><legend class="visually-hidden">Shipping method</legend><label class="shipping"><input type="radio" name="shipping" value="Standard"{' checked' if shipping!='Express' else ''}> Standard shipping <b>FREE</b></label><label class="shipping"><input type="radio" name="shipping" value="Express"{' checked' if shipping=='Express' else ''}> Express shipping <b>$20.00</b></label></fieldset>{f'<small class="error" id="error-shipping">{esc(shipping_error)}</small>' if shipping_error else ''}<button class="black">REVIEW ORDER</button>'''
action="/checkout/review"
if review:
action="/checkout/sandbox"
shipping_copy="Express · $20.00" if shipping=='Express' else "Standard · FREE"
left=f'''<a class="checkout-logo" href="/">{LOGO}</a><h1>Review your order</h1><div class="review-box"><p><b>Contact</b> {esc(saved.get('contact_email',''))}</p><p><b>Deliver to</b> {esc(saved.get('first_name',''))} {esc(saved.get('last_name',''))}, {esc(saved.get('address',''))}, {esc(saved.get('city',''))}, {esc(saved.get('province',''))} {esc(saved.get('postal_code',''))}</p><p><b>Shipping</b> {shipping_copy}</p></div><p class="simulation">Local sandbox review only. No order has been placed and no payment details are collected.</p><a class="outline" href="/checkout?edit=1">EDIT DELIVERY</a><label class="sandbox-choice">Local payment outcome<select name="scenario"><option value="sandbox-approved">Simulated approval</option><option value="sandbox-declined">Simulated decline</option><option value="sandbox-retry">Simulated retry</option></select></label><button class="black">RUN LOCAL SANDBOX</button>{sandbox_copy}'''
p=business.product_by_handle(c.get('product_handle',business.PRODUCT['handle']))
right=f'''<aside class="checkout-summary"><div class="checkout-item"><div><img src="{p['asset']}" alt="{esc(p['title'])}"></div><span><b>{esc(p['title'])}</b><br>{esc(c['color'])}<br>{c['quantity']} × {money(p['price_minor'])}</span><b>{money(t['subtotal'])}</b></div><p>Subtotal <b>{money(t['subtotal'])}</b></p>{f'<p>Discount SAVE10 <b>−{money(t["discount"])}</b></p>' if t['discount'] else ''}<p>Shipping <b>{money(t['shipping']) if t['shipping'] else 'FREE'}</b></p><hr><p class="total">Total <small>CAD</small> <b>{money(t['total'])}</b></p>{f'<strong>TOTAL SAVINGS {money(t["discount"])}</strong>' if t['discount'] else ''}</aside>'''
return page("Checkout – Dooney & Bourke",f'''<section class="checkout"><form method="post" action="{action}" novalidate><div>{left}</div>{right}</form></section>''',session)
def account_page(session,path,message="",local_code=""):
state=AUTH.resolve_session(session) or {}; account=state.get('account')
if account:
order=business.order_for_email(BACKEND,account['email_normalized'])
order_summary=f'''<article class="order"><b>DB-100041 · {esc(order['status'])}</b><p>Pebble Grain Crossbody · Caramel · $196.35 CAD</p><a href="/account/orders/DB-100041">View details</a> · <a href="/pages/refund-policy">Start a local return</a></article>''' if order else '<p>No local orders found.</p>'
body=f'''<section class="account"><h1>Welcome, {esc(account['display_name'])}</h1><p>{esc(account['email_normalized'])}</p><nav><a href="/account/orders">Order History</a><a href="/account/wishlist">Saved Items</a><form action="/account/logout" method="post"><button>LOG OUT</button></form></nav><h2>Recent order</h2>{order_summary}<a href="/collections/bags">Back to Bags</a></section>'''
if path.endswith('wishlist'):
items=[p for p in business.CATALOG if p['handle'] in business.wishlist(BACKEND,owner(session))]
body=f'''<section class="account"><h1>Saved Items</h1><div class="grid">{cards(items,business.wishlist(BACKEND,owner(session))) if items else '<p>No saved items yet.</p>'}</div><a href="/collections/bags">Shop Bags</a></section>'''
elif path=="/account/orders/DB-100041":
if not order:
return page("Order not found – Dooney & Bourke",'<section class="account"><h1>Order not found</h1><a href="/account/orders">Return to order history</a></section>',session,404)
cancel_form='''<form action="/account/orders/DB-100041/cancel" method="post"><button class="outline">CANCEL LOCAL ORDER</button></form>''' if order['status']!='Cancelled' else ''
body=f'''<section class="account order-detail"><p><a href="/account/orders">← Order History</a></p><h1>Order DB-100041</h1>{f'<p class="notice" role="status">{esc(message)}</p>' if message else ''}<p class="order-state"><b>{esc(order['status'])}</b> · Seeded local order</p><article class="order"><h2>Pebble Grain Crossbody</h2><p>Color: Caramel · Quantity: 1</p><p>Total: $196.35 CAD</p><a href="/pages/track-your-order">TRACK PACKAGE</a></article><div class="order-actions">{cancel_form}<form action="/account/orders/DB-100041/reorder" method="post"><button class="black">REORDER ITEMS</button></form><a href="/pages/refund-policy">Start a local return</a></div><a href="/collections/bags">Back to Bags</a></section>'''
return page("My Account – Dooney & Bourke",body,session)
body=f'''<section class="auth"><h1>Log in</h1><p>Enter the synthetic local fixture account or create a local-only account simulation.</p>{f'<p class="error" role="alert">{esc(message)}</p>' if message else ''}<form action="/account/login" method="post"><label>Email<input type="email" name="email" autocomplete="username" required></label><label>Password<input type="password" name="password" autocomplete="current-password" required></label><button class="black">LOG IN</button></form><p>Evaluation fixture: <code>shopper@example.test</code> / <code>WebsiteBench!041</code></p><a href="/account/register">Create account</a> · <a href="/account/recover">Forgot password?</a><small>By continuing, you agree to the local evaluation <a href="/pages/terms">Terms</a> and <a href="/pages/privacy">Privacy Policy</a>.</small></section>'''
if path.endswith('register'):
body=f'''<section class="auth"><h1>Create an account</h1><p>This is a truthful local simulation. It never sends verification email.</p>{f'<p class="error" role="alert">{esc(message)}</p>' if message else ''}<form action="/account/register" method="post"><label>First name<input name="first_name" autocomplete="given-name" required></label><label>Last name<input name="last_name" autocomplete="family-name" required></label><label>Email<input name="email" type="email" autocomplete="email" required></label><label>Password<input name="password" type="password" autocomplete="new-password" required></label><button class="black">CREATE LOCAL ACCOUNT</button></form><p>Verification guidance: a session-bound code is shown locally and no message is sent.</p><a href="/account/login">Return to sign in</a><small><a href="/pages/terms">Terms</a> · <a href="/pages/privacy">Privacy Policy</a></small></section>'''
if path.endswith('register/verify'):
body=f'''<section class="auth"><h1>Check your local verification code</h1><p>No email was sent. For this local-only evaluation session, use:</p><code class="local-code">{esc(local_code)}</code>{f'<p class="error" role="alert">{esc(message)}</p>' if message else ''}<form action="/account/register/verify" method="post"><label>Six-digit code<input name="code" inputmode="numeric" autocomplete="one-time-code" required></label><button class="black">VERIFY AND CREATE ACCOUNT</button></form><a href="/account/register">Start again</a></section>'''
elif path.endswith('recover'):
body='''<section class="auth"><h1>Reset your password</h1><p>Enter an email to see validation guidance. No reset message will be sent.</p><form class="local-recovery"><label>Email address<input type="email" required></label><button>CONTINUE</button></form><p role="status" class="recovery-status"></p><a href="/account/login">Return to sign in</a></section>'''
return page("Account – Dooney & Bourke",body,session)
def info_page(session,path):
pages={
"/pages/track-your-order":("Track Your Order",'''<p>Enter your order information to view a local seeded status.</p><form class="track" method="post" action="/pages/track-your-order"><label>Order Number<input name="order" required></label><label>Email Address<input name="email" type="email"></label><label>Zip Code<input name="zip" required></label><button class="black">TRACK ORDER</button></form>'''),
"/pages/refund-policy":("Returns",'''<h2>Easy Returns</h2><p>Review return eligibility and bring your order number to the local account history. This clone never creates a real return or shipment.</p><a class="black" href="/pages/track-your-order">TRACK AN ORDER</a>'''),
"/pages/contact":("Contact Us",'''<p>Find guidance for products, orders, account access and failed actions without exposing private account data.</p><form class="contact"><label>Name<input required></label><label>Email<input type="email" required></label><label>How can we help?<textarea required></textarea></label><button class="black">SAVE LOCAL DRAFT</button></form><p class="contact-status" role="status"></p>'''),
"/pages/orders-payments":("Orders & Payments",'''<p>Track a local seeded order, review payment guidance, or sign in to view account history.</p><a href="/pages/track-your-order">Track Your Order</a> · <a href="/account/orders">Order History</a>'''),
"/pages/help":("Help Center",'''<h2>How can we help?</h2><p><a href="/pages/track-your-order">Orders & tracking</a></p><p><a href="/pages/refund-policy">Returns</a></p><p><a href="/account/recover">Account access</a></p><p><a href="/pages/contact">Contact support</a></p>'''),
"/pages/privacy":("Privacy Policy","<p>This local WebsiteBench clone stores only synthetic evaluation data on the local machine and makes no remote runtime requests.</p>"),
"/pages/terms":("Terms of Service","<p>This is a local simulation. No real purchase, payment, email, account, shipment, or support message is created.</p>"),
}
title,content=pages.get(path,(path.rsplit('/',1)[-1].replace('-',' ').title(),"<p>Explore Dooney & Bourke information in this local experience.</p>"))
return page(f"{title} – Dooney & Bourke",f'''<section class="info"><h1>{esc(title)}</h1>{content}<p><a href="/collections/bags">Continue Shopping</a></p></section>''',session)
def application(environ,start):
path=environ.get("PATH_INFO","/") or "/"; method=environ.get("REQUEST_METHOD","GET").upper(); query=parse_qs(environ.get("QUERY_STRING",""),keep_blank_values=True)
jar=cookies.SimpleCookie(environ.get("HTTP_COOKIE","")); token=jar.get(session_cookie_name(environ)); session,session_state=AUTH.ensure_session(token.value if token else None); new_cookie=not token or token.value!=session
base_headers=(("Content-Type","text/html; charset=utf-8"),("Cache-Control","no-store"))
cookie_header=session_cookie_header(environ,session)
headers=base_headers+((cookie_header,) if new_cookie else ())
if path in {"/__websitebench/health","/healthz"}: return response(start,200,b'{"status":"ok"}',(("Content-Type","application/json"),))
if path.startswith("/static/"):
source_aliases={
"/static/source/home-offer-mobile.webp":"70/70f0f295d8064dd4d012ac6779c025edfc410e37eb7a56ee3ddf7590670a6663.webp",
"/static/source/main-logo.svg":"8c/8cd7c953036d5f973a31ff971305a471cefa582456c18192c43f2022e61a626e.svg",
"/static/source/love-logo.svg":"33/3353564b39673aaf8126b4e68e9c88e52a84466af1eb9d0c31ee928d8608fc5d.svg",
"/static/source/cookie-logo.png":"38/38650fa4afe34ba5cf4cb79b62186ba40f29946cd349029d1d5703120e6dd0c4.png",
}
if path in source_aliases:
target=(ROOT.parent/"source-acquisition/2026-08-24.assets-r1/resources"/source_aliases[path]).resolve()
return response(start,200,target.read_bytes(),(("Content-Type",mimetypes.guess_type(target.name)[0] or "application/octet-stream"),)+STATIC_CACHE_HEADERS)
target=(ROOT/path.lstrip('/')).resolve(); static=(ROOT/'static').resolve()
if static not in target.parents or not target.is_file(): return response(start,404,b"not found",(("Content-Type","text/plain"),))
if target.name.endswith('.b64'):
decoded=base64.b64decode(target.read_text(encoding='ascii').strip(),validate=True)
return response(start,200,decoded,(("Content-Type",mimetypes.guess_type(target.name[:-4])[0] or "application/octet-stream"),)+STATIC_CACHE_HEADERS)
return response(start,200,target.read_bytes(),(("Content-Type",mimetypes.guess_type(target.name)[0] or "application/octet-stream"),)+STATIC_CACHE_HEADERS)
if method=="POST":
if not request_origin_allowed(environ):
return response(start,403,b"Request origin is not allowed",(("Content-Type","text/plain; charset=utf-8"),))
data=form(environ); own=owner(session)
if path=="/cart/add":
try:
business.update_cart(BACKEND,own,quantity=1,color=data.get('color','Caramel'),handle=data.get('handle'))
except business.CartValidationError as error:
status,doc=cart_page(session,str(error)); return response(start,400,doc,headers)
return redirect(start,"/cart",headers)
if path=="/cart/update":
try:
quantity=int(data.get('quantity',''))
if not 1 <= quantity <= 9: raise ValueError
except (TypeError,ValueError):
status,doc=cart_page(session,"Enter a quantity from 1 to 9."); return response(start,400,doc,headers)
business.update_cart(BACKEND,own,quantity=quantity); return redirect(start,"/cart",headers)
if path=="/cart/remove": business.update_cart(BACKEND,own,remove=True); return redirect(start,"/cart",headers)
if path=="/cart/restore": business.update_cart(BACKEND,own,restore=True); return redirect(start,"/cart",headers)
if path=="/cart/promotion":
code=data.get('code','').strip().upper(); business.update_cart(BACKEND,own,promotion="SAVE10" if code=="SAVE10" else "")
status,doc=cart_page(session,"Discount code is not valid." if code!="SAVE10" else "SAVE10 applied — 10% off your local bag.")
return response(start,status,doc,headers)
if path=="/wishlist/toggle":
try: business.toggle_wishlist(BACKEND,own,data.get('handle',''))
except business.CartValidationError as error:
status,doc=page("Saved Items – Dooney & Bourke",f'<section class="account"><h1>Saved Items</h1><p class="error" role="alert">{esc(error)}</p><a href="/collections/bags">Shop Bags</a></section>',session,400); return response(start,status,doc,headers)
return redirect(start,safe_return_path(environ),headers)
if path=="/checkout/review":
required={'email':'Enter a valid email address.','first_name':'Enter a first name.','last_name':'Enter a last name.','address':'Enter an address.','city':'Enter a city.','postal_code':'Enter a postal code.','phone':'Enter a phone number.'}; errors={k:v for k,v in required.items() if not data.get(k,'').strip()}
if data.get('email') and not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+",data['email']): errors['email']='Enter a valid email address.'
if data.get('country','Canada')!='Canada': errors['country']='Select Canada.'
if data.get('province','') not in {'Ontario','British Columbia','Quebec'}: errors['province']='Select an available province.'
postal=data.get('postal_code','').replace(' ','').upper()
if postal and not re.fullmatch(r"[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z]\d[ABCEGHJ-NPRSTV-Z]\d",postal): errors['postal_code']='Enter a valid Canadian postal code.'
phone=re.sub(r"\D","",data.get('phone',''))
if data.get('phone') and not 10 <= len(phone) <= 15: errors['phone']='Enter a valid phone number.'
if data.get('shipping') not in {'Standard','Express'}: errors['shipping']='Select an available shipping method.'
business.checkout_save(BACKEND,own,data,'contact' if errors else 'review')
status,doc=checkout_page(session,errors); return response(start,status,doc,headers)
if path=="/checkout/sandbox":
if set(data)!={'scenario'}:
status,doc=checkout_page(session,sandbox={'tone':'error','label':'Sandbox request rejected','message':'Only a declared local payment scenario is accepted. No real order was created.'}); return response(start,400,doc,headers)
try:
attempt=business.run_payment_simulation(BACKEND,own,data.get('scenario',''))
except (ValueError,PaymentError) as error:
status,doc=checkout_page(session,sandbox={'tone':'error','label':'Sandbox request rejected','message':f'{error} No real order was created.'}); return response(start,400,doc,headers)
outcomes={
'APPROVED':('success','Simulated approval','The local sandbox approved this review. No real order was created.'),
'DECLINED':('error','Simulated decline','The local sandbox declined this review. No real order was created.'),
'RETRYABLE':('notice','Simulated retry','The local sandbox returned a retryable result. No real order was created.'),
}
tone,label,message=outcomes[attempt['status']]
status,doc=checkout_page(session,sandbox={'tone':tone,'label':label,'message':message}); return response(start,status,doc,headers)
if path=="/account/register":
try:
display_name=f"{data.get('first_name','').strip()} {data.get('last_name','').strip()}".strip()
AUTH.start_registration(session,email=data.get('email',''),display_name=display_name,password=data.get('password',''))
local_mail=AUTH.local_mail_for_session(session,purpose="registration") or {}
status,doc=account_page(session,"/account/register/verify",local_code=local_mail.get('verification_code','')); return response(start,status,doc,headers)
except AuthError as error:
status,doc=account_page(session,"/account/register",str(error)); return response(start,400,doc,headers)
if path=="/account/register/verify":
try:
AUTH.verify_registration_code(session,data.get('code',''))
result=AUTH.complete_registration(session,session_rotation_callback=business.rotate_owner); session=result['session_token']
headers=base_headers+(session_cookie_header(environ,session),)
return redirect(start,"/account",headers)
except AuthError as error:
local_mail=AUTH.local_mail_for_session(session,purpose="registration") or {}
status,doc=account_page(session,"/account/register/verify",str(error),local_mail.get('verification_code','')); return response(start,400,doc,headers)
if path=="/account/login":
try:
result=AUTH.sign_in(session,email=data.get('email',''),password=data.get('password',''),session_rotation_callback=business.rotate_owner); session=result['session_token']; headers=base_headers+(session_cookie_header(environ,session),); return redirect(start,"/account",headers)
except Exception: status,doc=account_page(session,"/account/login","Email or password is incorrect."); return response(start,status,doc,headers)
if path=="/account/logout": AUTH.sign_out(session); return redirect(start,"/account/login",base_headers+(session_cookie_header(environ,"",max_age=0),))
if path in {"/account/orders/DB-100041/cancel","/account/orders/DB-100041/reorder"}:
auth_state=AUTH.resolve_session(session) or {}; account=auth_state.get('account')
if not account: return redirect(start,"/account/login",headers)
if path.endswith('/cancel'):
order_value=business.cancel_order(BACKEND,account['email_normalized'],'DB-100041')
if not order_value: return response(start,404,b"order not found",(("Content-Type","text/plain"),))
status,doc=account_page(session,"/account/orders/DB-100041","Cancellation saved locally. No carrier or payment was contacted."); return response(start,status,doc,headers)
order_value=business.reorder(BACKEND,own,account['email_normalized'],'DB-100041')
if not order_value: return response(start,404,b"order not found",(("Content-Type","text/plain"),))
return redirect(start,"/cart",headers)
if path=="/pages/track-your-order":
tracked=business.order_by_tracking(BACKEND,data.get('order',''),data.get('zip',''))
if tracked: content=f'<p class="notice"><b>DB-100041 · {esc(tracked["status"])}</b><br>Pebble Grain Crossbody · Estimated local status only.</p>'
else: content='<p class="error">We could not find that order. Check the order number and postal code.</p>'
status,doc=info_page(session,path); doc=doc.replace('<p>Enter your order information',content+'<p>Enter your order information'); return response(start,status,doc,headers)
return response(start,405,b"method not allowed",(("Content-Type","text/plain"),))
if path=="/": status,doc=home(session)
elif path=="/search" or path.startswith("/collections/") or path=="/pages/sports": status,doc=catalog(session,path,query)
elif path.startswith("/products/"): status,doc=product_page(session,path.rsplit('/',1)[-1],query)
elif path=="/cart": status,doc=cart_page(session)
elif path=="/checkout":
if query.get('edit'): business.checkout_save(BACKEND,owner(session),business.checkout(BACKEND,owner(session)),'contact')
status,doc=checkout_page(session)
elif path.startswith("/account"): status,doc=account_page(session,path)
elif path.startswith("/pages/"): status,doc=info_page(session,path)
else: status,doc=page("Page Not Found – Dooney & Bourke",'''<section class="not-found"><span>404</span><h1>Oops! Page not found</h1><p>We couldn't find the page you're looking for.</p><a class="black" href="/collections/new-arrivals">SHOP NEW ARRIVALS</a><a href="/">Continue Shopping</a></section>''',session,404)
return response(start,status,doc,headers)
if __name__=="__main__":
host=os.environ.get("HOST","127.0.0.1"); port=int(os.environ.get("PORT","8000"))
print(f"Dooney & Bourke local clone listening on http://{host}:{port}",flush=True)
make_server(host,port,application).serve_forever()
|