File size: 22,144 Bytes
4fa4f63 | 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 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 | """Source-grounded Blue Apron offline review clone."""
from __future__ import annotations
import json
import re
import sqlite3
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from backend.site_backend_integration import open_site_services
from websitebench.local_clone_auth import AuthError
ROOT = Path(__file__).resolve().parent
RECIPES = json.loads((ROOT / "recipes.json").read_text(encoding="utf-8"))
BY_ID = {item["id"]: item for item in RECIPES}
BY_SLUG = {item["slug"]: item for item in RECIPES}
WEEKLY = RECIPES[:48]
ADDONS = {
"breakfast": {"name": "Blueberry Overnight Oats", "price": 8.99},
"snack": {"name": "Chocolate Chip Oat Cookies", "price": 6.99},
"protein": {"name": "Extra Garlic-Herb Chicken", "price": 11.99},
}
app = FastAPI(title="Blue Apron Offline Clone")
def database():
backend, _ = open_site_services()
connection = sqlite3.connect(backend.lifecycle.database_path)
connection.row_factory = sqlite3.Row
connection.executescript(
"""
CREATE TABLE IF NOT EXISTS ba_plan(
session TEXT PRIMARY KEY, servings INTEGER NOT NULL DEFAULT 2,
meals INTEGER NOT NULL DEFAULT 3, preference TEXT NOT NULL DEFAULT 'All'
);
CREATE TABLE IF NOT EXISTS ba_cart(
session TEXT NOT NULL, recipe_id TEXT NOT NULL, qty INTEGER NOT NULL DEFAULT 1,
upgrade TEXT NOT NULL DEFAULT '', PRIMARY KEY(session,recipe_id)
);
CREATE TABLE IF NOT EXISTS ba_addons(
session TEXT NOT NULL, addon_id TEXT NOT NULL, qty INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY(session,addon_id)
);
CREATE TABLE IF NOT EXISTS ba_delivery(
session TEXT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', address TEXT NOT NULL DEFAULT '',
city TEXT NOT NULL DEFAULT '', state TEXT NOT NULL DEFAULT '', zip TEXT NOT NULL DEFAULT '',
phone TEXT NOT NULL DEFAULT '', date TEXT NOT NULL DEFAULT 'September 21, 2026'
);
CREATE TABLE IF NOT EXISTS ba_subscription(
owner TEXT PRIMARY KEY, status TEXT NOT NULL DEFAULT 'active',
next_date TEXT NOT NULL DEFAULT 'September 21, 2026',
address TEXT NOT NULL DEFAULT '125 Offline Review Lane, New York, NY 10001',
skipped INTEGER NOT NULL DEFAULT 0, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
)
connection.commit()
return connection
def auth_context(request: Request):
current = request.cookies.get("__Host-blueapron-session") or request.cookies.get("blueapron_session")
_, auth = open_site_services()
token, session = auth.ensure_session(current)
return auth, token, session, token != current
def _claim_box(connection, token: str, account_id: str):
"""Adopt an anonymous/legacy box once; a saved account box wins on login."""
owner = "account:" + account_id
tables = ("ba_plan", "ba_cart", "ba_addons", "ba_delivery")
if connection.execute("SELECT 1 FROM ba_plan WHERE session=?", (owner,)).fetchone() is None:
for table in tables:
connection.execute(f"UPDATE {table} SET session=? WHERE session=?", (owner, token))
connection.execute("INSERT OR IGNORE INTO ba_plan(session) VALUES(?)", (owner,))
# Never leave an adopted guest box available through an old session.
for table in tables:
connection.execute(f"DELETE FROM {table} WHERE session=?", (token,))
return owner
def box_rotation(token: str):
# Ensure site tables exist before entering the auth store's transaction.
connection = database()
connection.close()
def rotated(connection, old_digest: str, new_digest: str):
previous = connection.execute("SELECT account_id FROM local_auth_sessions WHERE session_digest=?", (old_digest,)).fetchone()
current = connection.execute("SELECT account_id FROM local_auth_sessions WHERE session_digest=?", (new_digest,)).fetchone()
# Signing directly from A into B must never transfer A's legacy box to B.
owner = previous["account_id"] if previous["account_id"] is not None else current["account_id"]
_claim_box(connection, token, owner)
return rotated
def session_id(request: Request):
_, token, session, new = auth_context(request)
if session.get("authenticated"):
with database() as connection:
connection.execute("BEGIN IMMEDIATE")
owner = _claim_box(connection, token, session["account"]["account_id"])
connection.commit()
# The authenticated cookie already exists; the storage owner is never a cookie.
return owner, False
return token, new
class InvalidJsonObject(ValueError):
pass
@app.exception_handler(InvalidJsonObject)
async def invalid_json_object(_request: Request, exc: InvalidJsonObject):
return JSONResponse({"error": str(exc)}, 422)
async def request_object(request: Request):
try:
data = await request.json()
except (ValueError, UnicodeDecodeError) as exc:
raise InvalidJsonObject("Send a JSON object body.") from exc
if not isinstance(data, dict):
raise InvalidJsonObject("Send a JSON object body.")
return data
def set_cookie(response, request: Request, token: str):
if request.url.scheme == "https":
response.set_cookie("__Host-blueapron-session", token, secure=True, httponly=True, samesite="lax", path="/")
else:
response.set_cookie("blueapron_session", token, httponly=True, samesite="lax", path="/")
def ensure_plan(connection, session):
connection.execute("INSERT OR IGNORE INTO ba_plan(session) VALUES(?)", (session,))
connection.commit()
return dict(connection.execute("SELECT * FROM ba_plan WHERE session=?", (session,)).fetchone())
def cart_payload(session):
with database() as connection:
plan = ensure_plan(connection, session)
rows = [dict(row) for row in connection.execute("SELECT * FROM ba_cart WHERE session=? ORDER BY rowid", (session,))]
addons = [dict(row) for row in connection.execute("SELECT * FROM ba_addons WHERE session=? ORDER BY rowid", (session,))]
delivery_row = connection.execute("SELECT * FROM ba_delivery WHERE session=?", (session,)).fetchone()
meal_price = 11.99
for row in rows:
recipe = BY_ID.get(row["recipe_id"])
row.update(name=recipe["name"] if recipe else "Meal", image=recipe.get("image") if recipe else None)
row["unit_price"] = meal_price + (3.99 if row["upgrade"] else 0)
row["line_total"] = round(row["unit_price"] * plan["servings"] * row["qty"], 2)
for row in addons:
item = ADDONS[row["addon_id"]]
row.update(name=item["name"], unit_price=item["price"], line_total=round(item["price"] * row["qty"], 2))
subtotal = round(sum(row["line_total"] for row in rows) + sum(row["line_total"] for row in addons), 2)
discount = round(subtotal * 0.05, 2) if subtotal else 0
shipping = 9.99 if subtotal and subtotal < 100 else 0
tax = round((subtotal - discount + shipping) * 0.08875, 2) if subtotal else 0
return {
"plan": plan,
"items": rows,
"addons": addons,
"delivery": dict(delivery_row) if delivery_row else None,
"selected_meals": sum(row["qty"] for row in rows),
"minimum_met": sum(row["qty"] for row in rows) >= plan["meals"],
"subtotal": subtotal,
"discount": discount,
"shipping": shipping,
"tax": tax,
"total": round(subtotal - discount + shipping + tax, 2),
}
@app.get("/healthz")
def health():
return {"ok": True, "site_id": "blueapron"}
@app.get("/__websitebench/health")
def harbor_health():
return {"status": "ok"}
@app.get("/static/recipes/{name}")
def recipe_image(name: str):
if not re.fullmatch(r"recipe-\d{4}\.webp", name):
return JSONResponse({}, 404)
path = ROOT / "static" / "recipes" / name
return FileResponse(path) if path.is_file() else JSONResponse({}, 404)
@app.get("/static/{name}")
def static(name: str):
if name not in {"style.css", "source.css", "app.js", "logo.svg", "home-hero.png", "menu-hero.webp", "gifts-hero.png", "vision-hero.png", "detail-ingredients.png", "menu-current-01.png", "menu-current-02.png", "menu-current-03.png", "menu-current-04.png", "menu-side-01.png", "menu-side-02.png", "menu-side-03.png", "menu-side-04.png"}:
return JSONResponse({}, 404)
path = ROOT / "static" / name
return FileResponse(path) if path.is_file() else JSONResponse({}, 404)
@app.get("/api/recipes")
def recipes(q: str = "", category: str = "All", calories: int = 0, limit: int = 360):
query = q.casefold().strip()
result = RECIPES
if query:
result = [item for item in result if query in (item["name"] + " " + item["description"] + " " + " ".join(item["ingredients"])).casefold()]
if category != "All":
result = [item for item in result if item["category"] == category]
if calories:
result = [item for item in result if int(re.sub(r"\D", "", item.get("calories") or "99999") or 99999) <= calories]
return {"count": len(result), "recipes": result[: max(1, min(limit, 360))]}
@app.get("/api/recipes/{slug}")
def recipe(slug: str):
item = BY_SLUG.get(slug)
return item if item else JSONResponse({"error": "Recipe not found"}, 404)
@app.get("/api/cart")
def get_cart(request: Request):
session, new = session_id(request)
response = JSONResponse(cart_payload(session))
if new:
set_cookie(response, request, session)
return response
@app.put("/api/plan")
async def update_plan(request: Request):
session, new = session_id(request)
data = await request_object(request)
try:
servings, meals = int(data.get("servings")), int(data.get("meals"))
except (TypeError, ValueError):
return JSONResponse({"error": "Choose servings and meals per week."}, 422)
if servings not in {2, 4} or meals not in {2, 3, 4, 5}:
return JSONResponse({"error": "That plan combination is not available."}, 422)
preference = str(data.get("preference", "All"))
with database() as connection:
ensure_plan(connection, session)
connection.execute("UPDATE ba_plan SET servings=?,meals=?,preference=? WHERE session=?", (servings, meals, preference, session))
connection.commit()
response = JSONResponse(cart_payload(session))
if new:
set_cookie(response, request, session)
return response
@app.post("/api/cart")
async def add_cart(request: Request):
session, new = session_id(request)
data = await request_object(request)
recipe_id = str(data.get("recipe_id", ""))
if recipe_id not in BY_ID:
return JSONResponse({"error": "Choose an available meal."}, 422)
upgrade = str(data.get("upgrade", ""))
if upgrade not in {"", "Premium protein"}:
return JSONResponse({"error": "Unknown protein option."}, 422)
with database() as connection:
connection.execute("BEGIN IMMEDIATE")
existing = connection.execute("SELECT qty,upgrade FROM ba_cart WHERE session=? AND recipe_id=?", (session, recipe_id)).fetchone()
if existing and existing["upgrade"] != upgrade:
return JSONResponse({"error": "Remove the existing meal before choosing a different protein option."}, 409)
if existing and existing["qty"] >= 4:
return JSONResponse({"error": "Maximum quantity is 4."}, 409)
connection.execute(
"INSERT INTO ba_cart(session,recipe_id,qty,upgrade) VALUES(?,?,1,?) ON CONFLICT(session,recipe_id) DO UPDATE SET qty=MIN(ba_cart.qty+1,4),upgrade=excluded.upgrade",
(session, recipe_id, upgrade),
)
connection.commit()
response = JSONResponse(cart_payload(session))
if new:
set_cookie(response, request, session)
return response
@app.patch("/api/cart/{recipe_id}")
async def change_cart(recipe_id: str, request: Request):
session, _ = session_id(request)
data = await request_object(request)
raw_qty = data.get("qty", 0)
try:
if isinstance(raw_qty, bool) or not isinstance(raw_qty, (int, str)):
raise ValueError("not an integer")
qty = max(0, min(int(raw_qty), 4))
except (TypeError, ValueError):
return JSONResponse({"error": "Quantity must be an integer."}, 422)
with database() as connection:
if qty:
connection.execute("UPDATE ba_cart SET qty=? WHERE session=? AND recipe_id=?", (qty, session, recipe_id))
else:
connection.execute("DELETE FROM ba_cart WHERE session=? AND recipe_id=?", (session, recipe_id))
connection.commit()
return cart_payload(session)
@app.post("/api/addons")
async def add_addon(request: Request):
session, new = session_id(request)
data = await request_object(request)
addon_id = str(data.get("addon_id", ""))
if addon_id not in ADDONS:
return JSONResponse({"error": "Unknown add-on."}, 422)
with database() as connection:
connection.execute("BEGIN IMMEDIATE")
existing = connection.execute("SELECT qty FROM ba_addons WHERE session=? AND addon_id=?", (session, addon_id)).fetchone()
if existing and existing["qty"] >= 4:
return JSONResponse({"error": "Maximum add-on quantity is 4."}, 409)
connection.execute("INSERT INTO ba_addons(session,addon_id,qty) VALUES(?,?,1) ON CONFLICT(session,addon_id) DO UPDATE SET qty=MIN(ba_addons.qty+1,4)", (session, addon_id))
connection.commit()
response = JSONResponse(cart_payload(session))
if new:
set_cookie(response, request, session)
return response
@app.patch("/api/addons/{addon_id}")
async def change_addon(addon_id: str, request: Request):
session, _ = session_id(request)
data = await request_object(request)
quantity = data.get("qty")
if addon_id not in ADDONS:
return JSONResponse({"error": "Unknown add-on."}, 422)
if type(quantity) is not int or not 0 <= quantity <= 4:
return JSONResponse({"error": "Add-on quantity must be an integer from 0 to 4."}, 422)
with database() as connection:
if quantity:
connection.execute("UPDATE ba_addons SET qty=? WHERE session=? AND addon_id=?", (quantity, session, addon_id))
else:
connection.execute("DELETE FROM ba_addons WHERE session=? AND addon_id=?", (session, addon_id))
connection.commit()
return cart_payload(session)
@app.put("/api/delivery")
async def delivery(request: Request):
session, new = session_id(request)
data = await request_object(request)
required = ["name", "address", "city", "state", "zip", "phone"]
missing = [key for key in required if not str(data.get(key, "")).strip()]
if missing:
return JSONResponse({"error": "Complete all required delivery fields.", "fields": missing}, 422)
zip_code = str(data["zip"]).strip()
if not re.fullmatch(r"\d{5}", zip_code) or zip_code.startswith(("000", "999")):
return JSONResponse({"error": "We don't currently deliver to this ZIP code.", "fields": ["zip"]}, 422)
with database() as connection:
connection.execute(
"INSERT INTO ba_delivery(session,name,address,city,state,zip,phone,date) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(session) DO UPDATE SET name=excluded.name,address=excluded.address,city=excluded.city,state=excluded.state,zip=excluded.zip,phone=excluded.phone,date=excluded.date",
(session, *(str(data.get(key, "")).strip() for key in required), str(data.get("date", "September 21, 2026"))),
)
connection.commit()
response = JSONResponse(cart_payload(session))
if new:
set_cookie(response, request, session)
return response
@app.post("/api/checkout/review")
def checkout_review(request: Request):
session, _ = session_id(request)
payload = cart_payload(session)
if not payload["minimum_met"]:
return JSONResponse({"error": f"Select at least {payload['plan']['meals']} meals for this plan."}, 422)
if not payload["delivery"]:
return JSONResponse({"error": "Add a delivery address before continuing."}, 422)
return {**payload, "payment_adapter": "local-sandbox", "purchase_submitted": False}
@app.get("/api/auth/session")
def auth_session(request: Request):
_, token, session, new = auth_context(request)
response = JSONResponse(session)
if new:
set_cookie(response, request, token)
return response
@app.post("/api/auth/register/start")
async def register_start(request: Request):
auth, token, _, new = auth_context(request)
data = await request_object(request)
display_name = (str(data.get("first_name", "")) + " " + str(data.get("last_name", ""))).strip()
try:
result = auth.start_registration(token, email=str(data.get("email", "")), display_name=display_name, password=str(data.get("password", "")), restart_invalid_flow=True)
mail = auth.local_mail_for_session(token, purpose="registration")
except AuthError as exc:
return JSONResponse({"error": str(exc)}, 422)
response = JSONResponse({**result, "verification_code": mail.get("verification_code") if mail else None, "delivery": "local-sandbox"})
if new:
set_cookie(response, request, token)
return response
@app.post("/api/auth/register/verify")
async def register_verify(request: Request):
auth, token, _, _ = auth_context(request)
data = await request_object(request)
try:
auth.verify_registration_code(token, str(data.get("code", "")))
result = auth.complete_registration(token, session_rotation_callback=box_rotation(token))
except AuthError as exc:
return JSONResponse({"error": str(exc)}, 422)
response = JSONResponse({"authenticated": True, "account": result["account"]})
set_cookie(response, request, result["session_token"])
return response
@app.post("/api/auth/signin")
async def signin(request: Request):
auth, token, _, _ = auth_context(request)
data = await request_object(request)
try:
result = auth.sign_in(token, email=str(data.get("email", "")), password=str(data.get("password", "")), session_rotation_callback=box_rotation(token))
except AuthError as exc:
return JSONResponse({"error": str(exc)}, 401)
response = JSONResponse({"authenticated": True, "account": result["account"]})
set_cookie(response, request, result["session_token"])
return response
@app.post("/api/auth/signout")
def signout(request: Request):
auth, token, _, _ = auth_context(request)
auth.sign_out(token)
response = JSONResponse({"authenticated": False, "account": None})
response.delete_cookie("blueapron_session", path="/")
response.delete_cookie("__Host-blueapron-session", path="/", secure=True)
return response
def authenticated_owner(request: Request):
_, _, session, _ = auth_context(request)
if not session.get("authenticated"):
return None
account = session.get("account") or {}
return account.get("email_normalized") or account.get("email")
@app.get("/api/subscription")
def subscription(request: Request):
owner = authenticated_owner(request)
if not owner:
return JSONResponse({"error": "Sign in to manage your deliveries."}, 401)
with database() as connection:
connection.execute("INSERT OR IGNORE INTO ba_subscription(owner) VALUES(?)", (owner,))
connection.commit()
return dict(connection.execute("SELECT * FROM ba_subscription WHERE owner=?", (owner,)).fetchone())
@app.patch("/api/subscription")
async def update_subscription(request: Request):
owner = authenticated_owner(request)
if not owner:
return JSONResponse({"error": "Sign in to manage your deliveries."}, 401)
data = await request_object(request)
action = str(data.get("action", ""))
with database() as connection:
connection.execute("INSERT OR IGNORE INTO ba_subscription(owner) VALUES(?)", (owner,))
if action == "skip":
connection.execute("UPDATE ba_subscription SET skipped=1,updated_at=CURRENT_TIMESTAMP WHERE owner=?", (owner,))
elif action in {"pause", "cancel", "resume"}:
status = {"pause": "paused", "cancel": "cancelled", "resume": "active"}[action]
connection.execute("UPDATE ba_subscription SET status=?,updated_at=CURRENT_TIMESTAMP WHERE owner=?", (status, owner))
elif action == "address" and str(data.get("address", "")).strip():
connection.execute("UPDATE ba_subscription SET address=?,updated_at=CURRENT_TIMESTAMP WHERE owner=?", (str(data["address"]).strip(), owner))
elif action == "date" and str(data.get("date", "")).strip():
connection.execute("UPDATE ba_subscription SET next_date=?,updated_at=CURRENT_TIMESTAMP WHERE owner=?", (str(data["date"]).strip(), owner))
else:
return JSONResponse({"error": "Choose a valid subscription action."}, 422)
connection.commit()
return dict(connection.execute("SELECT * FROM ba_subscription WHERE owner=?", (owner,)).fetchone())
@app.post("/api/reset-request")
async def reset_request(request: Request):
data = await request_object(request)
if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", str(data.get("email", ""))):
return JSONResponse({"error": "Enter a valid email address."}, 422)
return {"accepted": False, "delivery": "disabled", "message": "Offline review: no reset email was sent."}
INDEX = """<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Blue Apron | Meal Kits, Oven-Ready & Ready-to-Eat Meals - No Subscription</title><link rel="stylesheet" href="/static/style.css"><link rel="stylesheet" href="/static/source.css"></head><body><div id="app"></div><script src="/static/app.js"></script></body></html>"""
@app.get("/{path:path}", response_class=HTMLResponse)
def frontend(path: str):
return INDEX
|