Author SHA1 Message Date
kiskaadee 99f8581cc8 docs(experiments): archive bdinvite SSO Graphify benchmark
Archive the frozen benchmark artifacts, evaluation tooling, disposable
OIDC fixture, and raw checkpoint telemetry comparing control and
Graphify agent runs for SSO authentication in BDInvite.

- Add retrospective README detailing outcomes, token estimation
  limitations, artifact map, and host environment notes
- Preserve frozen specification (sha256 verified) and manifest
- Archive evaluation runner, static checks, and telemetry scripts
- Retain disposable mock OAuth2 fixture and 16 checkpoint result records
- Link the archived experiment from the root repository README
2026-10-07 06:01:42 -05:00
kiskaadee 42927b9858 fix(admin): display registration timestamps in configured event timezone 2026-10-01 13:53:33 -05:00
kiskaadee 338dc20126 feat(frontend): add RSVP inline editing, deletion, and direct map preview 2026-10-01 13:37:26 -05:00
kiskaadee 6880b74b60 feat(admin): add UPDATE and DELETE endpoints for RSVP management 2026-10-01 13:37:21 -05:00
kiskaadee c44ecfc14b fix(map): support share.google domains and address geocoding fallback
- Add share.google and .google TLDs to allowed GOogle Maps domain
  whitelist
- Accept optional fallback_query in resolve_google_maps_coordinates
- Build geocoding candidate queries using address_lines and venue name
  when links lack embedded GPS coordinates
- Pass venue location details to coordinate resolver across admin update
  and preview regeneration routes
- Update test suite to verify share.google host validation and fallback
  parameter propagation
2026-10-01 12:46:59 -05:00
kiskaadee c8264b3d76 feat(map): autogenerate static map preview from Google Maps URL
- Add map_preview service resolving short links, cordinates, and OSM 3x3
  tile stitching
- Draw theme-matched golden venue marker pin centered on location
  cordinates
- Validate Google Maps URL structure and domain invariants in Pydantic
  schema
- Trigger automatic regeneration on PUT /config only when map_url
  changes
- Add POST /admin/map-preview/generate for ad-hoc generation withoug
  database writes
- Add circular preview widget and "Regenerar Mapa" action button to
  ConfigEditor
- Add public GET /birthday/api/map-preview.png endpoint with
  cache-control headers
- Update backend specifications and test suite
2026-10-01 12:28:59 -05:00
kiskaadee 818413b4f4 fix(traefik): protect admin API routes with Authelia ForwardAuth
Extend bdinvite-admin Traefik router rule to cover both /birthday/admin
and /birthday/api/admin prefixes, ensuring Authelia intercepts API requests
and injects the Remote-User header expected by FastAPI.
2026-10-01 11:44:59 -05:00
50 changed files with 3871 additions and 70 deletions

No files matched your search

+4
View File
@@ -24,6 +24,10 @@ A mobile-first invitation app with animated golden bokeh particles, an RSVP form
- [Infrastructure Specification](specs/infra.md)
- [Roadmap](ROADMAP.md)
## Experiments
- [SSO Graphify Benchmark](experiments/bdinvite-sso-graphify-benchmark/README.md) — Retrospective and archived evidence from an 8-checkpoint agent implementation benchmark.
## License
[Unlicense](UNLICENSE) — public domain.
+1 -1
View File
@@ -73,7 +73,7 @@
## Future
- [ ] Font selection (visual comparison of candidates)
- [ ] Application-owned map preview asset (replace URL with static file)
- [x] Application-owned map preview asset (replace URL with static file)
- [ ] Miniature rendered invitation preview in admin config editor
- [ ] Enhanced admin features (edit/delete RSVP, attendance status, guest count)
- [ ] CSV import
+12
View File
@@ -1,3 +1,5 @@
from pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -7,8 +9,18 @@ class Settings(BaseSettings):
BASE_PATH: str = "/birthday"
APP_PORT: int = 8000
DATABASE_URL: str = "sqlite:///./data/bdinvite.db"
DATA_DIR: str = "./data"
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
@property
def data_path(self) -> Path:
return Path(self.DATA_DIR).resolve()
@property
def map_preview_file(self) -> Path:
return self.data_path / "map_preview.png"
settings = Settings()
+20
View File
@@ -8,6 +8,7 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from .config import settings
from .database import Base, SessionLocal, engine
from .routes import admin, config, rsvp
from .services.config import seed_default_config
@@ -92,6 +93,25 @@ app.include_router(config.router, prefix="/birthday/api")
app.include_router(admin.router, prefix="/birthday/api/admin")
@app.get(
"/birthday/api/map-preview.png",
tags=["Config"],
summary="Obtener imagen de vista previa del mapa generada",
description="Retorna el archivo PNG de vista previa del mapa generado centrado en la ubicación.",
)
async def get_map_preview():
if settings.map_preview_file.exists():
return FileResponse(
settings.map_preview_file,
media_type="image/png",
headers={"Cache-Control": "public, max-age=300"},
)
return RedirectResponse(
url="https://tile.openstreetmap.org/15/8802/13443.png",
status_code=status.HTTP_307_TEMPORARY_REDIRECT,
)
# Static files and SPA serving
STATIC_DIR = os.path.join(os.path.dirname(__file__), "..", "static")
ASSETS_DIR = os.path.join(STATIC_DIR, "assets")
+155 -4
View File
@@ -1,18 +1,25 @@
import csv
import io
from datetime import UTC, datetime
from typing import Annotated
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, status
from sqlalchemy.orm import Session
from ..config import settings
from ..database import get_db
from ..schemas import (
GenerateMapPreviewRequest,
GenerateMapPreviewResponse,
InvitationConfigResponse,
InvitationConfigUpdate,
RSVPAdminItem,
RSVPListResponse,
RSVPUpdate,
)
from ..services.config import get_config, seed_default_config, update_config
from ..services.rsvp import get_rsvps
from ..services.map_preview import generate_map_preview_image, resolve_google_maps_coordinates
from ..services.rsvp import delete_rsvp, get_rsvps, update_rsvp
router = APIRouter(tags=["Admin"])
@@ -77,6 +84,67 @@ def list_rsvps(
)
@router.delete(
"/rsvps/{rsvp_id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Eliminar confirmación de asistencia",
description="Elimina permanentemente un registro de RSVP por su identificador.",
responses={
204: {"description": "Registro eliminado con éxito."},
404: {"description": "Registro no encontrado."},
**ADMIN_401,
},
)
def delete_rsvp_endpoint(
rsvp_id: int,
admin: AdminDep,
db: DbDep,
):
deleted = delete_rsvp(db, rsvp_id)
if not deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"No se encontró el registro con ID {rsvp_id}",
)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.patch(
"/rsvps/{rsvp_id}",
response_model=RSVPAdminItem,
summary="Editar una confirmación de asistencia",
description="Actualiza el nombre, teléfono o correo de un asistente confirmado.",
responses={
200: {"model": RSVPAdminItem, "description": "Registro actualizado exitosamente."},
400: {"description": "Error de validación en los campos proporcionados."},
404: {"description": "Registro no encontrado."},
409: {"description": "El número de teléfono ya está registrado por otro asistente."},
**ADMIN_401,
},
)
def update_rsvp_endpoint(
rsvp_id: int,
payload: RSVPUpdate,
admin: AdminDep,
db: DbDep,
):
status_res, updated = update_rsvp(db, rsvp_id, payload)
if status_res == "NOT_FOUND":
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"No se encontró el registro con ID {rsvp_id}",
)
if status_res == "DUPLICATE":
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="El número de teléfono ya está registrado para otro asistente.",
)
assert updated is not None
return updated
@router.get(
"/export",
summary="Exportar confirmaciones en formato CSV",
@@ -103,7 +171,10 @@ def export_rsvps_csv(
writer.writerow(["name", "phone", "email", "created_at"])
for item in rsvps:
created_iso = item.created_at.isoformat() if item.created_at else ""
created_iso = ""
if item.created_at:
dt = item.created_at if item.created_at.tzinfo else item.created_at.replace(tzinfo=UTC)
created_iso = dt.isoformat()
writer.writerow([item.name, item.phone, item.email or "", created_iso])
csv_content = output.getvalue()
@@ -140,6 +211,7 @@ def get_admin_config(
summary="Actualizar configuración de la invitación",
description=(
"Reemplaza los valores de la configuración singleton del evento. "
"Si la URL de Google Maps cambió, valida y regenera automáticamente la vista previa del mapa. "
"Aplica validación de fecha ISO, hora en formato militar 24h y zona horaria válida IANA. "
"Los cambios toman efecto de inmediato sin requerir recarga del contenedor."
),
@@ -148,10 +220,89 @@ def get_admin_config(
**ADMIN_401,
},
)
def update_admin_config(
async def update_admin_config(
update_in: InvitationConfigUpdate,
admin: AdminDep,
db: DbDep,
):
current = get_config(db)
if not current:
current = seed_default_config(db)
# Condition: Trigger generation ONLY if map_url was changed
if current.map_url != update_in.map_url:
try:
fallback = f"{update_in.address_lines}\n{update_in.address_name}"
lat, lng, _ = await resolve_google_maps_coordinates(
update_in.map_url, fallback_query=fallback
)
await generate_map_preview_image(lat, lng)
update_in.map_preview_url = f"{settings.BASE_PATH}/api/map-preview.png"
except ValueError as err:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=str(err),
) from err
except Exception as err:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error al generar la vista previa del mapa: {err}",
) from err
updated = update_config(db, update_in)
return updated
@router.post(
"/map-preview/generate",
response_model=GenerateMapPreviewResponse,
summary="Regenerar la vista previa del mapa",
description=(
"Genera o regenera la imagen del mapa en disco para la URL provista o la configurada actualmente, "
"sin realizar escrituras innecesarias a la base de datos."
),
responses={
200: {"model": GenerateMapPreviewResponse, "description": "Vista previa generada exitosamente."},
**ADMIN_401,
},
)
async def regenerate_map_preview_endpoint(
admin: AdminDep,
db: DbDep,
payload: GenerateMapPreviewRequest | None = None,
):
current = get_config(db)
target_url = payload.map_url.strip() if (payload and payload.map_url) else None
if not target_url:
if not current or not current.map_url:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="No se proporcionó una URL de Google Maps ni existe una guardada en la configuración.",
)
target_url = current.map_url
try:
fallback = f"{current.address_lines}\n{current.address_name}" if current else None
lat, lng, _ = await resolve_google_maps_coordinates(
target_url, fallback_query=fallback
)
await generate_map_preview_image(lat, lng)
timestamp = int(datetime.now(UTC).timestamp())
return GenerateMapPreviewResponse(
map_preview_url=f"{settings.BASE_PATH}/api/map-preview.png?t={timestamp}",
lat=lat,
lng=lng,
message="Vista previa del mapa generada exitosamente.",
)
except ValueError as err:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=str(err),
) from err
except Exception as err:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error al generar la vista previa del mapa: {err}",
) from err
+121 -2
View File
@@ -1,9 +1,28 @@
import re
from datetime import date, datetime
from datetime import UTC, date, datetime
from typing import Literal
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from pydantic import BaseModel, ConfigDict, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator
def normalize_phone(raw: str) -> str:
"""Normalize Colombian mobile numbers.
Rules:
1. Strip all non-digit characters.
2. If starts with '57' and has 12 digits, strip '57'.
3. Must be exactly 10 digits and start with '3'.
"""
digits = re.sub(r"\D", "", raw)
if digits.startswith("57") and len(digits) == 12:
digits = digits[2:]
if len(digits) != 10 or not digits.startswith("3"):
raise ValueError("Formato de teléfono inválido")
return digits
class RSVPCreate(BaseModel):
@@ -36,6 +55,11 @@ class RSVPCreate(BaseModel):
raise ValueError("El nombre no puede estar vacío.")
return cleaned
@field_validator("phone")
@classmethod
def validate_phone(cls, v: str) -> str:
return normalize_phone(v)
@field_validator("email")
@classmethod
def validate_email(cls, v: str | None) -> str | None:
@@ -50,6 +74,61 @@ class RSVPCreate(BaseModel):
return cleaned.lower()
class RSVPUpdate(BaseModel):
name: str | None = Field(
default=None,
min_length=1,
max_length=100,
description="Nombre completo del invitado",
examples=["Andrés García"],
)
phone: str | None = Field(
default=None,
min_length=1,
max_length=50,
description="Número móvil en formato colombiano (10 dígitos, con o sin prefijo +57)",
examples=["+57 300 123 4567"],
)
email: str | None = Field(
default=None,
max_length=255,
description="Correo electrónico opcional para confirmación y recordatorios",
examples=["andres@example.com"],
)
@field_validator("name")
@classmethod
def normalize_name(cls, v: str | None) -> str | None:
if v is None:
return None
cleaned = " ".join(v.strip().split())
if not cleaned:
raise ValueError("El nombre no puede estar vacío.")
return cleaned
@field_validator("phone")
@classmethod
def validate_phone(cls, v: str | None) -> str | None:
if v is None:
return None
return normalize_phone(v)
@field_validator("email")
@classmethod
def validate_email(cls, v: str | None) -> str | None:
if v is None:
return None
cleaned = v.strip()
if not cleaned:
return None
email_regex = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
if not re.match(email_regex, cleaned):
raise ValueError("Formato de correo electrónico inválido")
return cleaned.lower()
class RSVPSuccessResponse(BaseModel):
result: Literal["SUCCESS"] = Field(
default="SUCCESS",
@@ -97,6 +176,13 @@ class RSVPAdminItem(BaseModel):
model_config = ConfigDict(from_attributes=True)
@field_serializer("created_at")
def serialize_created_at(self, dt: datetime) -> str:
if dt.tzinfo is None:
dt = dt.replace(tzinfo=UTC)
return dt.isoformat()
class RSVPListResponse(BaseModel):
count: int = Field(..., description="Cantidad total de confirmaciones encontradas", examples=[37])
@@ -275,6 +361,15 @@ class InvitationConfigBase(BaseModel):
raise ValueError(f"Zona horaria IANA desconocida: {clean}")
return clean
@field_validator("map_url")
@classmethod
def validate_map_url(cls, v: str) -> str:
from .services.map_preview import validate_google_maps_url_format
clean = v.strip()
validate_google_maps_url_format(clean)
return clean
class InvitationConfigUpdate(InvitationConfigBase):
pass
@@ -285,3 +380,27 @@ class InvitationConfigResponse(InvitationConfigBase):
updated_at: datetime | None = Field(default=None, description="Última modificación en UTC")
model_config = ConfigDict(from_attributes=True)
@field_serializer("updated_at")
def serialize_updated_at(self, dt: datetime | None) -> str | None:
if dt is None:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=UTC)
return dt.isoformat()
class GenerateMapPreviewRequest(BaseModel):
map_url: str | None = Field(
default=None,
description="URL de Google Maps a procesar. Si se omite, se usa la configurada actualmente.",
examples=["https://maps.app.goo.gl/abcd1234efgh5678"],
)
class GenerateMapPreviewResponse(BaseModel):
map_preview_url: str = Field(description="URL para acceder a la imagen de vista previa generada")
lat: float = Field(description="Latitud resuelta")
lng: float = Field(description="Longitud resuelta")
message: str = Field(default="Vista previa generada con éxito")
+249
View File
@@ -0,0 +1,249 @@
import io
import math
import re
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
import httpx
from PIL import Image, ImageDraw
from ..config import settings
USER_AGENT = "bdinvite-map-preview/1.0 (contact: admin@roadtotech.me)"
GOOGLE_MAPS_DOMAINS = (
"maps.app.goo.gl",
"goo.gl",
"google.com",
"www.google.com",
"maps.google.com",
)
def is_google_maps_host(host: str) -> bool:
"""Check if the hostname belongs to Google Maps, Google share links, or Goo.gl shortlinks."""
clean_host = host.lower().strip()
if clean_host in ("maps.app.goo.gl", "goo.gl", "share.google"):
return True
if clean_host.startswith("maps.google."):
return True
if clean_host == "google.com" or clean_host.endswith(".google.com") or clean_host.endswith(".google"):
return True
# Regional domains like google.es, google.co, google.com.co
if re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host):
return True
return False
def validate_google_maps_url_format(url: str) -> None:
"""Validate that the given string is a structurally sound Google Maps URL."""
clean = url.strip()
if not clean:
raise ValueError("La URL de Google Maps no puede estar vacía.")
parsed = urlparse(clean)
if parsed.scheme not in ("http", "https"):
raise ValueError("La URL debe comenzar con http:// o https://")
if not parsed.netloc or not is_google_maps_host(parsed.netloc):
raise ValueError(
"La URL debe ser un enlace de Google Maps válido (ej. maps.app.goo.gl/... o google.com/maps/...)"
)
def extract_coordinates_from_text(text: str) -> tuple[float, float] | None:
"""Extract latitude and longitude from URL fragments, paths, or query strings."""
# Pattern 1: @<lat>,<lng> (e.g. /@34.143245,-118.255132,17z)
match_at = re.search(r"@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)", text)
if match_at:
lat = float(match_at.group(1))
lng = float(match_at.group(2))
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
return lat, lng
# Pattern 2: !3d<lat>!4d<lng> (Google Maps protobuf data parameter)
match_data = re.search(r"!3d(-?\d+(?:\.\d+)?)(?:!4d|.*?!4d)(-?\d+(?:\.\d+)?)", text)
if match_data:
lat = float(match_data.group(1))
lng = float(match_data.group(2))
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
return lat, lng
# Pattern 3: Query parameters (q=lat,lng, ll=lat,lng, destination=lat,lng)
parsed = urlparse(text)
if parsed.query:
qs = parse_qs(parsed.query)
for param in ("q", "ll", "destination"):
if param in qs and qs[param]:
val = qs[param][0].strip()
m = re.match(r"^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$", val)
if m:
lat = float(m.group(1))
lng = float(m.group(2))
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
return lat, lng
return None
async def resolve_google_maps_coordinates(
map_url: str,
fallback_query: str | None = None,
) -> tuple[float, float, str]:
"""
Validate and resolve a Google Maps URL, following redirects if necessary,
and return (latitude, longitude, resolved_url).
"""
validate_google_maps_url_format(map_url)
clean_url = map_url.strip()
# Try direct extraction before making any network requests
direct_coords = extract_coordinates_from_text(clean_url)
if direct_coords:
return direct_coords[0], direct_coords[1], clean_url
# Follow HTTP redirects to resolve short links (maps.app.goo.gl, share.google, etc.)
resolved_url = clean_url
async with httpx.AsyncClient(
follow_redirects=True,
timeout=10.0,
headers={"User-Agent": USER_AGENT},
) as client:
try:
response = await client.get(clean_url)
resolved_url = str(response.url)
# Check redirect history URLs in case coordinates were in an intermediate hop
for hop in response.history:
hop_coords = extract_coordinates_from_text(str(hop.url))
if hop_coords:
return hop_coords[0], hop_coords[1], resolved_url
except httpx.RequestError as exc:
raise ValueError(f"No se pudo resolver el enlace de Google Maps: {exc}") from exc
# Try extraction on the final resolved destination URL
final_coords = extract_coordinates_from_text(resolved_url)
if final_coords:
return final_coords[0], final_coords[1], resolved_url
# Fallback: check if there is a place search query in the URL or query string
parsed = urlparse(resolved_url)
qs = parse_qs(parsed.query)
query_text = None
if "q" in qs and qs["q"]:
query_text = qs["q"][0]
elif "/place/" in parsed.path:
# e.g. /maps/place/Fresco+Ristorante/...
place_part = parsed.path.split("/place/")[1].split("/")[0]
query_text = unquote(place_part.replace("+", " "))
# Build search candidates for geocoding
candidates: list[str] = []
clean_fallback = fallback_query.strip() if fallback_query else None
if query_text and clean_fallback:
candidates.append(f"{query_text}, {clean_fallback}")
if clean_fallback:
for line in clean_fallback.splitlines():
line_str = line.strip().strip(",")
if line_str and line_str not in candidates:
candidates.append(line_str)
if clean_fallback not in candidates:
candidates.append(clean_fallback)
if query_text and query_text not in candidates:
candidates.append(query_text)
if candidates:
async with httpx.AsyncClient(timeout=8.0, headers={"User-Agent": USER_AGENT}) as client:
for candidate in candidates:
try:
nom_res = await client.get(
"https://nominatim.openstreetmap.org/search",
params={"q": candidate, "format": "json", "limit": 1},
)
if nom_res.status_code == 200:
results = nom_res.json()
if results and isinstance(results, list) and len(results) > 0:
lat = float(results[0]["lat"])
lng = float(results[0]["lon"])
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
return lat, lng, resolved_url
except Exception:
pass
raise ValueError(
"No se pudieron extraer las coordenadas de la URL de Google Maps. "
"Asegúrate de que el enlace dirija a un lugar o coordenadas específicas."
)
def deg2num(lat_deg: float, lon_deg: float, zoom: int) -> tuple[float, float]:
"""Convert latitude and longitude to floating-point Slippy tile coordinates."""
lat_rad = math.radians(lat_deg)
n = 2.0**zoom
xtile = (lon_deg + 180.0) / 360.0 * n
ytile = (1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n
return xtile, ytile
async def generate_map_preview_image(
lat: float,
lng: float,
zoom: int = 16,
output_path: Path | None = None,
) -> Path:
"""
Download OpenStreetMap tiles surrounding (lat, lng), stitch them into a canvas,
crop a 400x400 square centered on the location, render a golden marker pin,
and save the resulting PNG to output_path (defaulting to settings.map_preview_file).
"""
dest_path = output_path or settings.map_preview_file
dest_path.parent.mkdir(parents=True, exist_ok=True)
xtile, ytile = deg2num(lat, lng, zoom)
x_int, y_int = int(xtile), int(ytile)
dx = xtile - x_int
dy = ytile - y_int
# Canvas of 3x3 tiles = 768x768 pixels
canvas = Image.new("RGB", (768, 768), color=(229, 227, 223))
async with httpx.AsyncClient(timeout=10.0, headers={"User-Agent": USER_AGENT}) as client:
for r_idx, y in enumerate(range(y_int - 1, y_int + 2)):
for c_idx, x in enumerate(range(x_int - 1, x_int + 2)):
tile_url = f"https://tile.openstreetmap.org/{zoom}/{x}/{y}.png"
try:
res = await client.get(tile_url)
if res.status_code == 200:
tile = Image.open(io.BytesIO(res.content)).convert("RGB")
canvas.paste(tile, (c_idx * 256, r_idx * 256))
except Exception:
# Keep neutral background tile if individual tile fails
pass
# Exact target location within the 768x768 canvas
cx = 256 + int(dx * 256)
cy = 256 + int(dy * 256)
# 400x400 crop centered on target coordinates
box = (cx - 200, cy - 200, cx + 200, cy + 200)
cropped = canvas.crop(box)
# Draw marker pin centered at (200, 200)
# The pin tip touches (200, 200)
draw = ImageDraw.Draw(cropped, "RGBA")
# Ground shadow underneath the pin tip
draw.ellipse((192, 198, 208, 204), fill=(40, 40, 40, 140))
# Golden pin pointer (inverted triangle)
draw.polygon([(188, 184), (212, 184), (200, 200)], fill="#d4a843", outline="#1a1a1a")
# Golden pin circular head
draw.ellipse((188, 170, 212, 194), fill="#d4a843", outline="#1a1a1a", width=2)
# Dark center eye
draw.ellipse((197, 179, 203, 185), fill="#1a1a1a")
# Save to disk as PNG
cropped.save(dest_path, "PNG", optimize=True)
return dest_path
+55 -21
View File
@@ -1,29 +1,9 @@
import re
from sqlalchemy import or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ..models import RSVP
from ..schemas import RSVPCreate
def normalize_phone(raw: str) -> str:
"""Normalize Colombian mobile numbers.
Rules:
1. Strip all non-digit characters.
2. If starts with '57' and has 12 digits, strip '57'.
3. Must be exactly 10 digits and start with '3'.
"""
digits = re.sub(r"\D", "", raw)
if digits.startswith("57") and len(digits) == 12:
digits = digits[2:]
if len(digits) != 10 or not digits.startswith("3"):
raise ValueError("Formato de teléfono inválido")
return digits
from ..schemas import RSVPCreate, RSVPUpdate, normalize_phone
def create_rsvp(db: Session, rsvp_in: RSVPCreate) -> tuple[str, RSVP | None]:
@@ -81,3 +61,57 @@ def get_rsvp_count(db: Session) -> int:
"""Get total count of RSVPs."""
query = select(RSVP)
return len(list(db.execute(query).scalars().all()))
def delete_rsvp(db: Session, rsvp_id: int) -> bool:
"""Delete an RSVP record by its ID. Returns True if deleted, False if not found."""
rsvp = db.execute(select(RSVP).where(RSVP.id == rsvp_id)).scalar_one_or_none()
if not rsvp:
return False
db.delete(rsvp)
db.commit()
return True
def update_rsvp(
db: Session,
rsvp_id: int,
update_in: RSVPUpdate,
) -> tuple[str, RSVP | None]:
"""Update an RSVP record using validated RSVPUpdate schema.
Returns:
("SUCCESS", rsvp)
("NOT_FOUND", None)
("DUPLICATE", None)
"""
rsvp = db.execute(select(RSVP).where(RSVP.id == rsvp_id)).scalar_one_or_none()
if not rsvp:
return "NOT_FOUND", None
if update_in.phone is not None:
existing = db.execute(
select(RSVP).where(RSVP.phone == update_in.phone, RSVP.id != rsvp_id)
).scalar_one_or_none()
if existing:
return "DUPLICATE", None
rsvp.phone = update_in.phone
if update_in.name is not None:
rsvp.name = update_in.name
if update_in.email is not None:
rsvp.email = update_in.email
try:
db.commit()
db.refresh(rsvp)
return "SUCCESS", rsvp
except IntegrityError:
db.rollback()
return "DUPLICATE", None
except Exception:
db.rollback()
raise
+2
View File
@@ -9,6 +9,8 @@ dependencies = [
"sqlalchemy>=2.0.0",
"pydantic>=2.0.0",
"pydantic-settings>=2.0.0",
"pillow>=10.0.0",
"httpx>=0.27.0",
]
[dependency-groups]
+91
View File
@@ -68,3 +68,94 @@ def test_admin_export_csv(client):
lines = content.strip().split("\r\n") if "\r\n" in content else content.strip().split("\n")
assert lines[0] == "name,phone,email,created_at"
assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1]
def test_admin_delete_rsvp(client):
headers = {"Remote-User": "kiskaadee"}
# Unauthorized without header
res_unauth = client.delete("/birthday/api/admin/rsvps/1")
assert res_unauth.status_code == 401
# 404 for non-existent RSVP
res_404 = client.delete("/birthday/api/admin/rsvps/9999", headers=headers)
assert res_404.status_code == 404
# Create an RSVP
client.post(
"/birthday/api/rsvp",
json={"name": "Lucas Silva", "phone": "300 444 5566", "email": "lucas@test.com"},
)
list_res = client.get("/birthday/api/admin/rsvps", headers=headers)
assert list_res.status_code == 200
rsvps = list_res.json()["rsvps"]
assert len(rsvps) == 1
rsvp_id = rsvps[0]["id"]
# Delete successfully
del_res = client.delete(f"/birthday/api/admin/rsvps/{rsvp_id}", headers=headers)
assert del_res.status_code == 204
# Confirm deletion
list_after = client.get("/birthday/api/admin/rsvps", headers=headers)
assert list_after.json()["count"] == 0
def test_admin_update_rsvp(client):
headers = {"Remote-User": "kiskaadee"}
# Unauthorized without header
res_unauth = client.patch("/birthday/api/admin/rsvps/1", json={"name": "New Name"})
assert res_unauth.status_code == 401
# 404 for non-existent RSVP
res_404 = client.patch(
"/birthday/api/admin/rsvps/9999",
json={"name": "New Name"},
headers=headers,
)
assert res_404.status_code == 404
# Create two RSVPs
client.post(
"/birthday/api/rsvp",
json={"name": "Person One", "phone": "300 111 2222", "email": "one@test.com"},
)
client.post(
"/birthday/api/rsvp",
json={"name": "Person Two", "phone": "300 333 4444", "email": "two@test.com"},
)
list_res = client.get("/birthday/api/admin/rsvps", headers=headers)
rsvps = list_res.json()["rsvps"]
id_one = next(r["id"] for r in rsvps if r["name"] == "Person One")
id_two = next(r["id"] for r in rsvps if r["name"] == "Person Two")
# Update Person One with valid new name and phone
patch_res = client.patch(
f"/birthday/api/admin/rsvps/{id_one}",
json={"name": "Person One Updated", "phone": "+57 300 999 8888", "email": "newone@test.com"},
headers=headers,
)
assert patch_res.status_code == 200
updated_data = patch_res.json()
assert updated_data["name"] == "Person One Updated"
assert updated_data["phone"] == "3009998888"
assert updated_data["email"] == "newone@test.com"
# Attempt to update Person One's phone to Person Two's phone -> 409
dup_res = client.patch(
f"/birthday/api/admin/rsvps/{id_one}",
json={"phone": "300 333 4444"},
headers=headers,
)
assert dup_res.status_code == 409
# Validation error for invalid phone
val_res = client.patch(
f"/birthday/api/admin/rsvps/{id_one}",
json={"phone": "12345"},
headers=headers,
)
assert val_res.status_code in (400, 422)
+151
View File
@@ -0,0 +1,151 @@
from unittest.mock import ANY, patch
import pytest
from app.config import settings
from app.services.map_preview import (
deg2num,
extract_coordinates_from_text,
is_google_maps_host,
validate_google_maps_url_format,
)
ADMIN_HEADERS = {"Remote-User": "kiskaadee"}
def test_is_google_maps_host():
assert is_google_maps_host("maps.app.goo.gl")
assert is_google_maps_host("share.google")
assert is_google_maps_host("goo.gl")
assert is_google_maps_host("maps.google.com")
assert is_google_maps_host("google.com")
assert is_google_maps_host("www.google.com")
assert is_google_maps_host("google.es")
assert is_google_maps_host("maps.google.co.uk")
assert not is_google_maps_host("example.com")
assert not is_google_maps_host("bing.com")
assert not is_google_maps_host("evilgoogle.com")
def test_validate_google_maps_url_format():
validate_google_maps_url_format("https://maps.app.goo.gl/354784424357732")
validate_google_maps_url_format("https://www.google.com/maps/place/Fresco/@34.1,-118.2,17z")
validate_google_maps_url_format("https://maps.google.com/?q=34.1,-118.2")
with pytest.raises(ValueError, match="no puede estar vacía"):
validate_google_maps_url_format("")
with pytest.raises(ValueError, match="comenzar con http"):
validate_google_maps_url_format("ftp://maps.google.com")
with pytest.raises(ValueError, match="enlace de Google Maps válido"):
validate_google_maps_url_format("https://apple.com/maps")
def test_extract_coordinates_from_text():
# 1. @lat,lng
coords = extract_coordinates_from_text("https://google.com/maps/place/Venue/@34.143245,-118.255132,17z")
assert coords == (34.143245, -118.255132)
# 2. !3dlat!4dlng
coords = extract_coordinates_from_text("https://google.com/maps/data=!4m6!3m5!1s0x0!8m2!3d4.6534!4d-74.0564")
assert coords == (4.6534, -74.0564)
# 3. Query params: q=lat,lng
coords = extract_coordinates_from_text("https://maps.google.com/?q=34.1432,-118.2551")
assert coords == (34.1432, -118.2551)
# 4. Query params: ll=lat,lng
coords = extract_coordinates_from_text("https://maps.google.com/maps?ll=34.1432,-118.2551&z=16")
assert coords == (34.1432, -118.2551)
# 5. Non-coordinate text
assert extract_coordinates_from_text("https://maps.google.com/?q=Eiffel+Tower") is None
def test_deg2num():
xtile, ytile = deg2num(34.1432, -118.2551, 16)
assert int(xtile) == 11240
assert int(ytile) == 26148
@patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image")
def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client, tmp_path):
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png"
# Test without auth -> 401
resp = client.post("/birthday/api/admin/map-preview/generate", json={"map_url": "https://maps.google.com/?q=34.1,-118.2"})
assert resp.status_code == 401
# Test with auth -> 200
resp = client.post(
"/birthday/api/admin/map-preview/generate",
headers=ADMIN_HEADERS,
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
)
assert resp.status_code == 200
data = resp.json()
assert "/birthday/api/map-preview.png" in data["map_preview_url"]
assert data["lat"] == 34.1432
assert data["lng"] == -118.2551
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1,-118.2", fallback_query=ANY)
mock_generate.assert_called_once_with(34.1432, -118.2551)
@patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image")
def test_config_update_triggers_generator_only_when_map_url_changes(mock_generate, mock_resolve, client, tmp_path):
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png"
# Get current config
current = client.get("/birthday/api/admin/config", headers=ADMIN_HEADERS).json()
orig_map_url = current["map_url"]
assert orig_map_url == "https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA"
# 1. Update config WITHOUT changing map_url -> generator NOT called
update_payload = {**current}
update_payload["honoree_name"] = "Updated Honoree"
resp = client.put("/birthday/api/admin/config", headers=ADMIN_HEADERS, json=update_payload)
assert resp.status_code == 200
assert resp.json()["honoree_name"] == "Updated Honoree"
mock_resolve.assert_not_called()
mock_generate.assert_not_called()
# 2. Update config WITH new map_url -> generator CALLED
update_payload["map_url"] = "https://maps.google.com/?q=34.1432,-118.2551"
resp = client.put("/birthday/api/admin/config", headers=ADMIN_HEADERS, json=update_payload)
assert resp.status_code == 200
assert resp.json()["map_url"] == "https://maps.google.com/?q=34.1432,-118.2551"
assert resp.json()["map_preview_url"] == "/birthday/api/map-preview.png"
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1432,-118.2551", fallback_query=ANY)
mock_generate.assert_called_once_with(34.1432, -118.2551)
def test_config_update_rejects_invalid_map_url(client):
current = client.get("/birthday/api/admin/config", headers=ADMIN_HEADERS).json()
bad_payload = {**current, "map_url": "https://invalid-non-google-url.com/something"}
resp = client.put("/birthday/api/admin/config", headers=ADMIN_HEADERS, json=bad_payload)
assert resp.status_code == 422
def test_get_map_preview_serving(client, tmp_path, monkeypatch):
# Case 1: file exists
test_img = tmp_path / "map_preview.png"
test_img.write_bytes(b"\x89PNG\r\n\x1a\nfakeimagebytes")
monkeypatch.setattr(settings, "DATA_DIR", str(tmp_path))
resp = client.get("/birthday/api/map-preview.png")
assert resp.status_code == 200
assert resp.headers["content-type"] == "image/png"
assert resp.content == b"\x89PNG\r\n\x1a\nfakeimagebytes"
# Case 2: file does not exist -> redirects to fallback
test_img.unlink()
resp_fallback = client.get("/birthday/api/map-preview.png", follow_redirects=False)
assert resp_fallback.status_code == 307
assert "tile.openstreetmap.org" in resp_fallback.headers["location"]
+89
View File
@@ -53,6 +53,8 @@ version = "0.1.0"
source = { virtual = "." }
dependencies = [
{ name = "fastapi", extra = ["standard"] },
{ name = "httpx" },
{ name = "pillow" },
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "sqlalchemy" },
@@ -70,6 +72,8 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "fastapi", extras = ["standard"], specifier = ">=0.115.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "pillow", specifier = ">=10.0.0" },
{ name = "pydantic", specifier = ">=2.0.0" },
{ name = "pydantic-settings", specifier = ">=2.0.0" },
{ name = "sqlalchemy", specifier = ">=2.0.0" },
@@ -694,6 +698,91 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },
]
[[package]]
name = "pillow"
version = "12.3.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/fb/c8/0a78b0e02d7ac54bc03e5321c9220da52f0c2ea83b21f7c40e7f3169c502/pillow-12.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756", size = 5392415, upload-time = "2026-07-01T11:53:47.162Z" },
{ url = "https://files.pythonhosted.org/packages/b2/5b/a02d30018abd97ced9f5a6c63d28597694a00d066516b9c1c6de45859fc9/pillow-12.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6", size = 4785266, upload-time = "2026-07-01T11:53:49.079Z" },
{ url = "https://files.pythonhosted.org/packages/c8/98/766667a4be768150a202836acd9fad19c06824ca86c4286d3cf6b274964e/pillow-12.3.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd", size = 6263814, upload-time = "2026-07-01T11:53:51.32Z" },
{ url = "https://files.pythonhosted.org/packages/3b/2d/ede717bc1144f63886c21fd349bb95860b0d1a21149ff16f2bb362b612b6/pillow-12.3.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd", size = 6934408, upload-time = "2026-07-01T11:53:53.487Z" },
{ url = "https://files.pythonhosted.org/packages/a3/48/9c58b685e69d49c31af6c8eb9012055fab7e665785165c84796e2c73ce72/pillow-12.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c", size = 6337160, upload-time = "2026-07-01T11:53:55.457Z" },
{ url = "https://files.pythonhosted.org/packages/ff/fa/dc2a5c0ba6df93f67c31d34b808b7ce440b40cdbf96f0b81cde1d1e6fa93/pillow-12.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5", size = 7045172, upload-time = "2026-07-01T11:53:57.736Z" },
{ url = "https://files.pythonhosted.org/packages/86/a5/444817a4d4c4c2417df00513086ca196f388d8f9ef40c2e4ccd1ad1af54b/pillow-12.3.0-cp311-cp311-win32.whl", hash = "sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b", size = 6472232, upload-time = "2026-07-01T11:53:59.767Z" },
{ url = "https://files.pythonhosted.org/packages/63/c6/4bad1b18d132a50b27e1365e1ab163616f7a5bb56d330f66f9d1d9d4f9d4/pillow-12.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a", size = 7233653, upload-time = "2026-07-01T11:54:02.066Z" },
{ url = "https://files.pythonhosted.org/packages/fd/16/00f91ab7760dc842f5aad55217e80fc4a7067a0604535249bc8a2d6d9870/pillow-12.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26", size = 2568195, upload-time = "2026-07-01T11:54:04.622Z" },
{ url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" },
{ url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" },
{ url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" },
{ url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" },
{ url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" },
{ url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" },
{ url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" },
{ url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" },
{ url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" },
{ url = "https://files.pythonhosted.org/packages/9d/ac/31fb64e1e7efb5a4b50cd3d92049ba89ac6e4d8d3bb6a74e15048ca3353e/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89", size = 4161684, upload-time = "2026-07-01T11:54:25.934Z" },
{ url = "https://files.pythonhosted.org/packages/87/b4/9805e23d2b4d77842b468513841fda254ee42f0289d25088340e4ff46e2d/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace", size = 4255487, upload-time = "2026-07-01T11:54:27.935Z" },
{ url = "https://files.pythonhosted.org/packages/df/39/ecf519435a200c693fe053a6ee4d835b41cf963a4dfc2551c4e637cb2a71/pillow-12.3.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec", size = 3696433, upload-time = "2026-07-01T11:54:29.813Z" },
{ url = "https://files.pythonhosted.org/packages/42/92/2fc3ffad878ae8dd5469ec1bc8eb83b71f48e13efdf68f02709003982a32/pillow-12.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66", size = 5345889, upload-time = "2026-07-01T11:54:31.97Z" },
{ url = "https://files.pythonhosted.org/packages/10/76/8803c13605b763d33d156c4678fc77f8443389c0c51c8aef707bb02015f4/pillow-12.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35", size = 4780109, upload-time = "2026-07-01T11:54:34.026Z" },
{ url = "https://files.pythonhosted.org/packages/1f/01/e18aff37cb0b4aac47ac90f016d347a49aca667ef97f190b06ac2aabc928/pillow-12.3.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65", size = 6263736, upload-time = "2026-07-01T11:54:36.131Z" },
{ url = "https://files.pythonhosted.org/packages/f7/62/de5bdd77d935331f4f802edc11e4d82950f642caad6cb2f949837b8560e2/pillow-12.3.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3", size = 6937129, upload-time = "2026-07-01T11:54:38.216Z" },
{ url = "https://files.pythonhosted.org/packages/70/4d/105627a13300c5e0df1d174230b32fd1273062c96f7745fd552b945d1e1d/pillow-12.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a", size = 6339562, upload-time = "2026-07-01T11:54:40.354Z" },
{ url = "https://files.pythonhosted.org/packages/6b/1d/f13de01a553988ab895ba1c722e06cf3144d4f57656fd5b81b6d881f1179/pillow-12.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e", size = 7049439, upload-time = "2026-07-01T11:54:42.489Z" },
{ url = "https://files.pythonhosted.org/packages/c9/f9/066794cca041b969964f779ee5fa66a9498bbf34248ac39c5d7954e4198f/pillow-12.3.0-cp313-cp313-win32.whl", hash = "sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f", size = 6473287, upload-time = "2026-07-01T11:54:44.9Z" },
{ url = "https://files.pythonhosted.org/packages/a6/9b/7a58e61d62be561da3a356fe2384d4059a6345fc130e23ef1c36a5b81d24/pillow-12.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8", size = 7239691, upload-time = "2026-07-01T11:54:47.141Z" },
{ url = "https://files.pythonhosted.org/packages/aa/b0/c4ed4f0ef8f8fa5ee8351537db6650bb8189f7e118842978dd6589065692/pillow-12.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b", size = 2568185, upload-time = "2026-07-01T11:54:49.137Z" },
{ url = "https://files.pythonhosted.org/packages/dc/01/001f65b68192f0228cc1dbbc8d2530ab5d58b61037ba0587f946fea607cd/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330", size = 4161736, upload-time = "2026-07-01T11:54:51.156Z" },
{ url = "https://files.pythonhosted.org/packages/1a/d2/0219746d0fd16fc8a84498e79452375be3797d3ce4044596ce565164b84f/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217", size = 4255435, upload-time = "2026-07-01T11:54:53.414Z" },
{ url = "https://files.pythonhosted.org/packages/c8/02/8d0bc62ef0302318c46ff2a512822d2610e81c7aa46c9b3abe6cbaca5ad0/pillow-12.3.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930", size = 3696262, upload-time = "2026-07-01T11:54:55.739Z" },
{ url = "https://files.pythonhosted.org/packages/85/e2/73c77d218410b14f5f2d565e8a998d5317b7b9c75368d29985139f7a46f0/pillow-12.3.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8", size = 5350344, upload-time = "2026-07-01T11:54:57.657Z" },
{ url = "https://files.pythonhosted.org/packages/c7/da/32c752228ae345f489e3a42499d817b6c3996da7e8a3bc7a04fc806b243b/pillow-12.3.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0", size = 4780131, upload-time = "2026-07-01T11:54:59.713Z" },
{ url = "https://files.pythonhosted.org/packages/b1/9d/8b2c807dbef61a5197c047afe99823787eb66f63daf9fb2432f91d6f0462/pillow-12.3.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321", size = 6263757, upload-time = "2026-07-01T11:55:01.778Z" },
{ url = "https://files.pythonhosted.org/packages/5c/44/c85361f65dbe00eea8576ee467c768d25129989efb76e94f205e9ca9bb46/pillow-12.3.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b", size = 6936962, upload-time = "2026-07-01T11:55:03.93Z" },
{ url = "https://files.pythonhosted.org/packages/18/7e/e483414b35800b86b6f08dbbc7803fb5cd52c4d6f897f47d53ea2c7e6f65/pillow-12.3.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198", size = 6339171, upload-time = "2026-07-01T11:55:05.989Z" },
{ url = "https://files.pythonhosted.org/packages/f0/f4/68c491844841ede6bed70189546b3ee9731cf9f2cbad396faff5e1ccba45/pillow-12.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130", size = 7048116, upload-time = "2026-07-01T11:55:08.131Z" },
{ url = "https://files.pythonhosted.org/packages/a3/34/77f3f793fed8efc7d243f21b33c5a3f0d1c97ee70346d3db855587e155ff/pillow-12.3.0-cp314-cp314-win32.whl", hash = "sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a", size = 6467209, upload-time = "2026-07-01T11:55:10.408Z" },
{ url = "https://files.pythonhosted.org/packages/f1/e0/492879f69d94f91f60fc8cd05ba03650e9520afebb2fb7aa12777d7c7f38/pillow-12.3.0-cp314-cp314-win_amd64.whl", hash = "sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d", size = 7237707, upload-time = "2026-07-01T11:55:12.745Z" },
{ url = "https://files.pythonhosted.org/packages/c9/ac/6b11f2875f1c2ac040d84e1bbf9cf22a88038f901ca1037898b280b38365/pillow-12.3.0-cp314-cp314-win_arm64.whl", hash = "sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838", size = 2565995, upload-time = "2026-07-01T11:55:14.736Z" },
{ url = "https://files.pythonhosted.org/packages/52/69/c2208e56af9bfc1913afb24020297a691eb1d4ef688474c8a04913f65e04/pillow-12.3.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e", size = 5352503, upload-time = "2026-07-01T11:55:17.076Z" },
{ url = "https://files.pythonhosted.org/packages/07/70/e5686d753e898a45d778ff1718dba8516ead6ab6b95d85fc8c4b70650cf2/pillow-12.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17", size = 4782956, upload-time = "2026-07-01T11:55:19.448Z" },
{ url = "https://files.pythonhosted.org/packages/d5/37/25c6692f06927ee973ff18c8d9ee98ad0b4d84ee67a09610c2dd1447958e/pillow-12.3.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385", size = 6322855, upload-time = "2026-07-01T11:55:21.613Z" },
{ url = "https://files.pythonhosted.org/packages/cc/91/420637fcb8f1bc11029e403b4538e6694744428d8246118e45719f944556/pillow-12.3.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c", size = 6989642, upload-time = "2026-07-01T11:55:24.006Z" },
{ url = "https://files.pythonhosted.org/packages/10/08/b94d7811281ccf0d143a1cf768d1c49e1e54af63e7b708ab2ee3eb87face/pillow-12.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d", size = 6391281, upload-time = "2026-07-01T11:55:26.252Z" },
{ url = "https://files.pythonhosted.org/packages/d2/87/24233f785f55474dc02ce3e739c5528a77e3a862e9333d1dd7a25cc31f70/pillow-12.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931", size = 7096716, upload-time = "2026-07-01T11:55:28.318Z" },
{ url = "https://files.pythonhosted.org/packages/23/26/fcb2f6e37175b04f53570b59937867e2b80ee1685e744023153028fc14f9/pillow-12.3.0-cp314-cp314t-win32.whl", hash = "sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7", size = 6474125, upload-time = "2026-07-01T11:55:30.956Z" },
{ url = "https://files.pythonhosted.org/packages/90/de/3634abee5f1c9e13c56787b7d5517b0ba8d6de51700b95578cf338349c9f/pillow-12.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c", size = 7242939, upload-time = "2026-07-01T11:55:34.044Z" },
{ url = "https://files.pythonhosted.org/packages/ce/2a/fd13f8eb24de5714a6eb444a3d67e2842c6c576e159a43793adf23051351/pillow-12.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45", size = 2567506, upload-time = "2026-07-01T11:55:35.988Z" },
{ url = "https://files.pythonhosted.org/packages/5d/dc/8fdce34ec725a33c81c6ba122b904d6b9024e50ea9ac7bede62fab54506c/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139", size = 4162063, upload-time = "2026-07-01T11:55:37.941Z" },
{ url = "https://files.pythonhosted.org/packages/76/66/2044b9a63d3b84ff048228dfcb7cd9bf0df983e8470971bf7d4c57b693de/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402", size = 4255549, upload-time = "2026-07-01T11:55:40.022Z" },
{ url = "https://files.pythonhosted.org/packages/52/7e/1f67e6f4ece6b582ee4b539decbcc9f848dc245a93ed8cd7338bafef72f1/pillow-12.3.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c", size = 3696331, upload-time = "2026-07-01T11:55:41.98Z" },
{ url = "https://files.pythonhosted.org/packages/12/40/d306fc2c8e4d45d7f175c77edca7063be7b86fe7fe6e68f4353bf71d808c/pillow-12.3.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f", size = 5350370, upload-time = "2026-07-01T11:55:44.028Z" },
{ url = "https://files.pythonhosted.org/packages/dd/44/668fb1437e8ce420f62d6106eb66e44a5971602a4d794615bdf79315d82d/pillow-12.3.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701", size = 4780147, upload-time = "2026-07-01T11:55:46.073Z" },
{ url = "https://files.pythonhosted.org/packages/0c/08/93fa2e70e30a2d81547e481b6ee2bb9522117221fb1e0ce4b5df70967677/pillow-12.3.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace", size = 6273659, upload-time = "2026-07-01T11:55:48.264Z" },
{ url = "https://files.pythonhosted.org/packages/f8/6d/043e96ff814fc31a33077e4cba86082167db520c93632afdf2042febbb0c/pillow-12.3.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4", size = 6947439, upload-time = "2026-07-01T11:55:50.503Z" },
{ url = "https://files.pythonhosted.org/packages/af/92/ba71d2ee2ac0edf3fa33bd9d5ee9ee080da70b1766f3ca3934f9938ddac9/pillow-12.3.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39", size = 6353577, upload-time = "2026-07-01T11:55:52.697Z" },
{ url = "https://files.pythonhosted.org/packages/0f/ce/e63064e2122923ff687c8ad792d0d736a7b3920a56a46982e81a7fdd25d6/pillow-12.3.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71", size = 7060394, upload-time = "2026-07-01T11:55:55.149Z" },
{ url = "https://files.pythonhosted.org/packages/54/76/a09cc3ccc8d773a7283d34c38bec1708f9e3cc932093cbc4c5e71ac4060b/pillow-12.3.0-cp315-cp315-win32.whl", hash = "sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827", size = 6467375, upload-time = "2026-07-01T11:55:57.769Z" },
{ url = "https://files.pythonhosted.org/packages/3e/03/1846c49ba3b1d5550392a4bbd06d6fb4578e1cd91a803198b5c90f5f7d53/pillow-12.3.0-cp315-cp315-win_amd64.whl", hash = "sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5", size = 7237048, upload-time = "2026-07-01T11:55:59.975Z" },
{ url = "https://files.pythonhosted.org/packages/fb/bb/89f35dcc79610423f9f195504d7def7f0d1416a711541b42867e25fe3412/pillow-12.3.0-cp315-cp315-win_arm64.whl", hash = "sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658", size = 2566006, upload-time = "2026-07-01T11:56:02.143Z" },
{ url = "https://files.pythonhosted.org/packages/30/88/707027ba09942dfa2c28759b5c222d769290a41c6d20ea60ec250801941f/pillow-12.3.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf", size = 5352509, upload-time = "2026-07-01T11:56:04.2Z" },
{ url = "https://files.pythonhosted.org/packages/b0/6d/00352fa25332c2569cd387851f568cc5a4b75a9adbfb37ac4fbce4c02eec/pillow-12.3.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64", size = 4783167, upload-time = "2026-07-01T11:56:06.631Z" },
{ url = "https://files.pythonhosted.org/packages/13/4f/9e049dfa21af7c22427275720e2490267ba8138120add5c4c574deb69782/pillow-12.3.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e", size = 6329237, upload-time = "2026-07-01T11:56:08.868Z" },
{ url = "https://files.pythonhosted.org/packages/36/16/cf6eeaae8d0fce8dd390a33437cf68c5d5bd73834a2bc6e2f14efda0ab45/pillow-12.3.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777", size = 6997047, upload-time = "2026-07-01T11:56:11.379Z" },
{ url = "https://files.pythonhosted.org/packages/1e/69/dbf769bdd55f48bf5733cac28edc6364ffaa072ec9ba336266e4fe66be55/pillow-12.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1", size = 6400440, upload-time = "2026-07-01T11:56:13.908Z" },
{ url = "https://files.pythonhosted.org/packages/a0/e1/ffc9cfc2eea0d178da8018e18e959301ad9d6bc9f3edb7181e748a474b97/pillow-12.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9", size = 7105895, upload-time = "2026-07-01T11:56:16.575Z" },
{ url = "https://files.pythonhosted.org/packages/18/f0/a5595c1e8c3ae44b9828cb2f0fa8155e5095ef04d6327b8f61cf44a3df85/pillow-12.3.0-cp315-cp315t-win32.whl", hash = "sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8", size = 6474384, upload-time = "2026-07-01T11:56:18.855Z" },
{ url = "https://files.pythonhosted.org/packages/e4/04/62bcd9f844984c5938d3b05264a61d797a29d3e0812341a8204af70bbdee/pillow-12.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418", size = 7243537, upload-time = "2026-07-01T11:56:21.214Z" },
{ url = "https://files.pythonhosted.org/packages/3d/68/1f3066acedf37673694a7141381d8f811ae97f30d34413d236abe7d489f1/pillow-12.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59", size = 2567491, upload-time = "2026-07-01T11:56:23.506Z" },
{ url = "https://files.pythonhosted.org/packages/75/18/2e8b40223153ccbc60df07f9e8928dc0c76202aa4e55ae9f53962b6510d6/pillow-12.3.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468", size = 5302510, upload-time = "2026-07-01T11:56:25.736Z" },
{ url = "https://files.pythonhosted.org/packages/46/3e/51fabf59d5ab801ceab709453d3ab6b180083496579549de4c45ced6528a/pillow-12.3.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94", size = 4736058, upload-time = "2026-07-01T11:56:28.041Z" },
{ url = "https://files.pythonhosted.org/packages/bf/20/22fe9384b7949e25fb1293bcfc84fb82590ff4ea6b37c95b24d26d793d86/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e", size = 5237776, upload-time = "2026-07-01T11:56:30.263Z" },
{ url = "https://files.pythonhosted.org/packages/08/14/f6ba68107680ffa74b39985f3f30884e41318fbc4250caa423c79b4788bb/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3", size = 5860358, upload-time = "2026-07-01T11:56:32.68Z" },
{ url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" },
]
[[package]]
name = "pluggy"
version = "1.6.0"
+1 -1
View File
@@ -21,7 +21,7 @@ services:
- "traefik.http.routers.bdinvite-public.service=bdinvite-svc"
# Admin router (Authelia-protected)
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday/admin`)"
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && (PathPrefix(`/birthday/admin`) || PathPrefix(`/birthday/api/admin`))"
- "traefik.http.routers.bdinvite-admin.entrypoints=websecure"
- "traefik.http.routers.bdinvite-admin.tls=true"
- "traefik.http.routers.bdinvite-admin.priority=20"
@@ -0,0 +1,51 @@
# BDInvite Graphify-assisted SSO benchmark: retrospective
## Purpose
This experiment compared two agents implementing application-level OpenID Connect single sign-on in BDInvite. The control arm used the standard repository toolchain; the Graphify arm had Graphify available for repository exploration. The plan also specified eight implementation checkpoints, a disposable OIDC fixture, external verification, and collection of token estimates and tool-use telemetry.
## Outcome
The saved telemetry contains records for CP1 through CP8 for both arms. Every record is marked `PASS`. At CP8, both records report 25 baseline tests passing, zero failed verifications, the `Remote-User` static check passing, and a successful Docker build. The stored data therefore does not support describing the implementation experiment as a failure.
The token estimates do not show lower usage in the Graphify arm. Summing the per-checkpoint `total_tokens_est` values gives:
| Arm | Estimated tokens | Checkpoint records |
| --- | ---: | ---: |
| Control | 19,907,364 | 8 |
| Graphify | 22,923,088 | 8 |
The Graphify sum is approximately 15.1% higher. This is a descriptive comparison of the stored estimates, not a reliable measurement of actual model token usage or proof that Graphify caused the difference.
## Measurement limitations
The records identify the estimation method as `character_density_approximation`, with a ratio of 3.8. These are not direct token counts from the model provider. The experiment did not capture enough authoritative usage data to make a strong claim about Graphify's effect on token consumption. Treat the percentages as exploratory only.
The frozen plan describes a broader agent-assisted SSO implementation benchmark, even though token efficiency is one of the interests. The result set is also a single paired run with one control worktree and one Graphify worktree. It cannot separate the effect of Graphify from run-to-run variation, prompt/context differences, or other agent behavior.
## What is still useful
- The frozen plan records the intended checkpoints, security requirements, and evaluation protocol.
- The fixture and evaluator source show how the work was set up and verified.
- The checkpoint JSON files preserve implementation outcomes, tool-call telemetry, commits, and estimated usage.
- The outcome suggests a useful follow-up: rerun with provider-reported token counts, repeated trials, and a clearly specified primary metric before drawing conclusions about efficiency.
## Preserved artifacts
The accompanying directories retain the frozen specification, manifest, evaluator, disposable OIDC fixture, and raw control/Graphify result records. The `control/` and `graphify/` worktrees are intentionally not part of this archive; they remain separate implementation branches (`control/feat/sso-auth` and `graphify/feat/sso-auth`).
| Artifact | Path in archive | Description & handling |
| --- | --- | --- |
| Benchmark specification | `specification/bdinvite_sso_benchmark_plan.md` | Frozen experimental protocol and checkpoint criteria (hash verified against manifest). |
| Experiment manifest | `manifest.json` | Recorded hashes, baseline commit, fixture config, and worktree metadata. |
| Gatekeeper & Evaluator | `evaluator/` (`gatekeeper.py`, `static_checks.py`, `telemetry.py`) | Evaluator support code and gatekeeper script used during the experiment. |
| Disposable OIDC Fixture | `fixture/` (`config.json`, `docker-compose.yml`, `start.sh`, `stop.sh`, `README.md`) | Disposable mock OAuth2 test fixture configuration and run scripts. |
| Raw checkpoint telemetry | `results/control/*.json`, `results/graphify/*.json` | Raw evidence records for checkpoints CP1 through CP8 for both arms. |
## Machine-specific paths and archival integrity
Certain preserved files contain absolute paths tied to the host environment where the benchmark ran:
- `manifest.json` references local filesystem paths for `canonical_brain_plan` and `source_repository`.
- `evaluator/gatekeeper.py` hardcodes an absolute path to a local commit ledger (`/home/kiskaadee/Brain/00-inbox/commit-log.csv`).
These files are preserved without modification to maintain the historical integrity of the experimental record. Any portability improvements or harness generalization should be handled as an explicit separate follow-up rather than altering frozen experiment artifacts.
@@ -0,0 +1,499 @@
#!/usr/bin/env python3
"""Unified External Evaluator & Benchmark Gatekeeper.
Usage:
python evaluator/gatekeeper.py freeze-check
python evaluator/gatekeeper.py baseline --worktree <path>
python evaluator/gatekeeper.py verify --checkpoint CP1 --worktree <path> --agent control
"""
import argparse
import hashlib
import json
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Tuple
import httpx
from rich.console import Console
from rich.table import Table
# Add parent directory to sys.path
sys.path.insert(0, str(Path(__file__).parent.parent))
from evaluator.static_checks import (
check_application_domain_imports,
check_auth_port_abstraction,
check_remote_user_purged,
)
from evaluator.telemetry import log_checkpoint_telemetry
console = Console()
BENCHMARK_ROOT = Path(__file__).resolve().parent.parent
RESULTS_DIR = BENCHMARK_ROOT / "results"
MANIFEST_PATH = BENCHMARK_ROOT / "manifest.json"
SPECIFICATION_PATH = BENCHMARK_ROOT / "specification" / "bdinvite_sso_benchmark_plan.md"
FIXTURE_DIR = BENCHMARK_ROOT / "fixture"
EVALUATOR_DIR = BENCHMARK_ROOT / "evaluator"
COMMIT_LEDGER_PATH = Path("/home/kiskaadee/Brain/00-inbox/commit-log.csv")
def run_command(cmd: List[str], cwd: Path) -> subprocess.CompletedProcess:
"""Run a shell command and return CompletedProcess."""
return subprocess.run(
cmd,
cwd=cwd,
capture_output=True,
text=True,
)
def compute_sha256(file_path: Path) -> str:
"""Compute SHA-256 hash of a file."""
h = hashlib.sha256()
with open(file_path, "rb") as f:
while chunk := f.read(65536):
h.update(chunk)
return h.hexdigest()
def verify_baseline_tests(worktree: Path) -> Tuple[bool, int, int, str]:
"""Run the original 25 backend regression tests in the target worktree."""
backend_dir = worktree / "backend"
if not backend_dir.exists():
return False, 0, 0, f"Backend directory {backend_dir} does not exist."
baseline_files = [
"tests/test_admin.py",
"tests/test_config.py",
"tests/test_map_preview.py",
"tests/test_rsvp.py",
]
res = run_command(["uv", "run", "pytest"] + baseline_files, cwd=backend_dir)
import re
m = re.search(r"(\d+) passed", res.stdout)
passed_count = int(m.group(1)) if m else 0
passed = res.returncode == 0 and passed_count >= 25 and "failed" not in res.stdout
output = res.stdout + "\n" + res.stderr
return passed, passed_count if passed else 0, 25, output
def check_git_contamination(worktree: Path) -> Tuple[bool, List[str]]:
"""Verify that graphify-out or temporary artifacts are not tracked or committed."""
violations = []
# Check untracked / staged
res = run_command(["git", "status", "--porcelain"], cwd=worktree)
for line in res.stdout.splitlines():
if "graphify-out" in line:
violations.append(f"Untracked/Staged graphify-out in git status: {line}")
# Check commit log for graphify-out leaks
log_res = run_command(
["git", "log", "--name-only", "--pretty=format:%H", "42927b9..HEAD"],
cwd=worktree,
)
for line in log_res.stdout.splitlines():
if "graphify-out" in line:
violations.append(f"Committed graphify-out file found in git history: {line}")
return len(violations) == 0, violations
def check_commit_delegation(worktree: Path, baseline_sha: str = "42927b9") -> Tuple[bool, List[str], bool]:
"""Inspect commits created on top of baseline, verifying they are recorded in commit-log.csv."""
res = run_command(
["git", "rev-list", f"{baseline_sha}..HEAD"],
cwd=worktree,
)
commit_shas = [c.strip() for c in res.stdout.splitlines() if c.strip()]
if not commit_shas:
return True, [], False
# Check commit ledger if exists
ledger_content = COMMIT_LEDGER_PATH.read_text(encoding="utf-8") if COMMIT_LEDGER_PATH.exists() else ""
all_logged = True
for sha in commit_shas:
if sha not in ledger_content:
all_logged = False
break
return True, commit_shas, all_logged
def verify_freeze() -> bool:
"""Perform comprehensive Pre-Experiment Freeze Gate verification."""
console.print("\n[bold cyan]════════════════════════════════════════════════════════════[/bold cyan]")
console.print("[bold cyan] PRE-EXPERIMENT FREEZE GATE VERIFICATION (CP0) [/bold cyan]")
console.print("[bold cyan]════════════════════════════════════════════════════════════[/bold cyan]\n")
overall_pass = True
# 1. SPECIFICATION
if not SPECIFICATION_PATH.exists():
console.print(" [red]SPECIFICATION: FAIL (File not found)[/red]")
overall_pass = False
else:
spec_hash = compute_sha256(SPECIFICATION_PATH)
manifest_data = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
expected_hash = manifest_data.get("specification", {}).get("sha256")
if spec_hash == expected_hash:
console.print(f" [green]SPECIFICATION: PASS[/green] (SHA-256: [dim]{spec_hash[:12]}...[/dim])")
else:
console.print(f" [red]SPECIFICATION: FAIL (Hash mismatch: {spec_hash} != {expected_hash})[/red]")
overall_pass = False
# 2. MANIFEST
if MANIFEST_PATH.exists():
console.print(" [green]MANIFEST: PASS[/green]")
else:
console.print(" [red]MANIFEST: FAIL (manifest.json missing)[/red]")
overall_pass = False
# 3. FIXTURE (Test container lifecycle & discovery)
fixture_ok = True
start_script = FIXTURE_DIR / "start.sh"
stop_script = FIXTURE_DIR / "stop.sh"
if not (start_script.exists() and stop_script.exists()):
console.print(" [red]FIXTURE: FAIL (start.sh or stop.sh missing)[/red]")
fixture_ok = False
overall_pass = False
else:
# Test starting fixture
start_res = run_command([str(start_script)], cwd=FIXTURE_DIR)
if start_res.returncode != 0:
console.print(f" [red]FIXTURE: FAIL (Start failed: {start_res.stderr})[/red]")
fixture_ok = False
overall_pass = False
else:
# Query discovery
try:
r = httpx.get("http://localhost:8088/default/.well-known/openid-configuration", timeout=5.0)
disc = r.json()
assert disc.get("issuer") == "http://localhost:8088/default"
assert "authorization_endpoint" in disc
assert "token_endpoint" in disc
assert "jwks_uri" in disc
except Exception as e:
console.print(f" [red]FIXTURE: FAIL (Discovery validation error: {e})[/red]")
fixture_ok = False
overall_pass = False
# Stop fixture
stop_res = run_command([str(stop_script)], cwd=FIXTURE_DIR)
if stop_res.returncode != 0:
console.print(f" [red]FIXTURE: FAIL (Stop failed: {stop_res.stderr})[/red]")
fixture_ok = False
overall_pass = False
if fixture_ok:
console.print(" [green]FIXTURE: PASS[/green] (OIDC container discovery & lifecycle verified)")
# 4. EVALUATOR (Environment & Browser)
eval_ok = True
venv_py = EVALUATOR_DIR / ".venv" / "bin" / "python"
if not venv_py.exists():
console.print(" [red]EVALUATOR: FAIL (Virtualenv missing at evaluator/.venv)[/red]")
eval_ok = False
overall_pass = False
else:
# Check required imports
check_code = "import pytest, httpx, cryptography, jwt, playwright; print('OK')"
res = run_command([str(venv_py), "-c", check_code], cwd=EVALUATOR_DIR)
if res.returncode != 0 or "OK" not in res.stdout:
console.print(f" [red]EVALUATOR: FAIL (Required dependencies missing: {res.stderr})[/red]")
eval_ok = False
overall_pass = False
if eval_ok:
console.print(" [green]EVALUATOR: PASS[/green] (Python 3.13 venv, test runners, Chromium ready)")
# 5. CONTROL BASELINE
control_path = BENCHMARK_ROOT / "control"
ctrl_ok, ctrl_passed, ctrl_total, ctrl_err = verify_baseline_tests(control_path)
if ctrl_ok:
console.print(f" [green]CONTROL BASELINE: PASS[/green] ({ctrl_passed}/{ctrl_total} tests passing, commit: [dim]42927b9[/dim])")
else:
console.print(f" [red]CONTROL BASELINE: FAIL ({ctrl_passed}/{ctrl_total} tests passing: {ctrl_err})[/red]")
overall_pass = False
# 6. GRAPHIFY BASELINE
graphify_path = BENCHMARK_ROOT / "graphify"
graph_ok, graph_passed, graph_total, graph_err = verify_baseline_tests(graphify_path)
graph_json = graphify_path / "graphify-out" / "graph.json"
if graph_ok and graph_json.exists():
console.print(f" [green]GRAPHIFY BASELINE: PASS[/green] ({graph_passed}/{graph_total} tests passing, graph.json seeded)")
else:
console.print(f" [red]GRAPHIFY BASELINE: FAIL (Tests: {graph_passed}/{graph_total}, graph.json exists: {graph_json.exists()})[/red]")
overall_pass = False
# 7. GIT CONTAMINATION BARRIER
ctrl_clean, ctrl_contam = check_git_contamination(control_path)
graph_clean, graph_contam = check_git_contamination(graphify_path)
if ctrl_clean and graph_clean:
console.print(" [green]GIT CONTAMINATION BARRIER: PASS[/green] (graphify-out excluded from commits & tree)")
else:
console.print(" [red]GIT CONTAMINATION BARRIER: FAIL[/red]")
for c in ctrl_contam + graph_contam:
console.print(f" - {c}")
overall_pass = False
console.print("\n[bold cyan]────────────────────────────────────────────────────────────[/bold cyan]")
if overall_pass:
console.print("[bold green] RESULT: EXPERIMENT: READY[/bold green]")
console.print("[bold cyan]────────────────────────────────────────────────────────────[/bold cyan]\n")
else:
console.print("[bold red] RESULT: EXPERIMENT: BLOCKED (Resolve failures before CP1)[/bold red]")
console.print("[bold cyan]────────────────────────────────────────────────────────────[/bold cyan]\n")
return overall_pass
def verify_checkpoint(checkpoint: str, worktree: Path, agent: str) -> bool:
"""Execute gatekeeper checks for the requested checkpoint."""
started_at = datetime.now(timezone.utc)
console.print(
f"[bold blue]Evaluating {checkpoint} on {agent} ({worktree.name})...[/bold blue]"
)
verification_data: Dict[str, Any] = {
"checkpoint_tests": {"passed": 0, "total": 0},
"cumulative_regression_tests": {"passed": 0, "total": 25},
"failed_verifications_count": 0,
"details": [],
}
# Step 1: Baseline tests must always pass
base_ok, base_passed, base_total, base_out = verify_baseline_tests(worktree)
verification_data["cumulative_regression_tests"]["passed"] = base_passed
if not base_ok:
console.print("[red]❌ Baseline regression tests failed![/red]")
console.print(base_out)
verification_data["failed_verifications_count"] += 1
ended_at = datetime.now(timezone.utc)
log_checkpoint_telemetry(
RESULTS_DIR,
agent,
checkpoint,
started_at,
ended_at,
status="FAIL",
outcome_reason="baseline_regression_failure",
verification_data=verification_data,
)
return False
console.print("[green]✔ Baseline regression tests passed (25/25).[/green]")
# Step 2: Git contamination check
clean_tree, contam_violations = check_git_contamination(worktree)
if not clean_tree:
console.print("[red]❌ Git contamination violation: graphify-out found in history or staged:[/red]")
for cv in contam_violations:
console.print(f" - {cv}")
ended_at = datetime.now(timezone.utc)
log_checkpoint_telemetry(
RESULTS_DIR,
agent,
checkpoint,
started_at,
ended_at,
status="FAIL",
outcome_reason="git_contamination_detected",
verification_data=verification_data,
)
return False
# Step 3: Git delegation observability check
has_commits, commit_shas, all_logged = check_commit_delegation(worktree)
passed = False
outcome_reason = "none"
if checkpoint == "CP1":
# CP1: AuthPort & Identity abstraction, application domain imports isolation
has_abstractions, notes = check_auth_port_abstraction(worktree)
import_violations = check_application_domain_imports(worktree)
for n in notes:
console.print(f" [cyan]ℹ {n}[/cyan]")
if not has_abstractions:
console.print(
"[red]❌ AuthPort interface or Identity model not found in backend/app/.[/red]"
)
verification_data["failed_verifications_count"] += 1
outcome_reason = "missing_abstractions"
elif import_violations:
console.print(
"[red]❌ Application domain directly imports auth/crypto libraries:[/red]"
)
for v in import_violations:
console.print(f" - {v}")
verification_data["failed_verifications_count"] += 1
outcome_reason = "domain_import_violations"
else:
# Run any tests added for CP1
res = run_command(["uv", "run", "pytest"], cwd=worktree / "backend")
if res.returncode == 0:
console.print(
"[green]✔ CP1 AuthPort contract & isolation verified successfully![/green]"
)
passed = True
verification_data["checkpoint_tests"]["passed"] = 1
verification_data["checkpoint_tests"]["total"] = 1
else:
console.print("[red]❌ Worktree pytest suite failed:[/red]")
console.print(res.stdout + res.stderr)
verification_data["failed_verifications_count"] += 1
outcome_reason = "test_suite_failure"
elif checkpoint == "CP6":
# CP6: Negative Barrier - Remote-User header MUST be rejected with 401
res = run_command(
[
"uv",
"run",
"python",
"-c",
"""
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
res = client.get('/birthday/api/admin/rsvps', headers={'Remote-User': 'kiskaadee'})
assert res.status_code == 401, f'Expected 401, got {res.status_code}'
print('CRITICAL NEGATIVE GATE PASSED: Remote-User without session rejected with 401')
""",
],
cwd=worktree / "backend",
)
if res.returncode == 0:
console.print(f"[green]✔ {res.stdout.strip()}[/green]")
passed = True
else:
console.print("[red]❌ Critical negative gate failed:[/red]")
console.print(res.stdout + res.stderr)
outcome_reason = "negative_barrier_failure"
elif checkpoint == "CP8":
# CP8: Purge verification: zero occurrences of Remote-User in runtime
ru_violations = check_remote_user_purged(worktree)
if ru_violations:
console.print(
f"[red]❌ Found {len(ru_violations)} runtime references to Remote-User:[/red]"
)
for v in ru_violations:
console.print(f" - {v}")
outcome_reason = "remote_user_leak_detected"
else:
console.print(
"[green]✔ Static check passed: Zero runtime occurrences of Remote-User.[/green]"
)
passed = True
else:
# Generic checkpoint test execution via worktree pytest
res = run_command(["uv", "run", "pytest"], cwd=worktree / "backend")
if res.returncode == 0:
console.print(
f"[green]✔ {checkpoint} test suite passed in worktree.[/green]"
)
passed = True
else:
console.print(f"[red]❌ {checkpoint} test suite failed in worktree:[/red]")
console.print(res.stdout + res.stderr)
outcome_reason = "test_suite_failure"
ended_at = datetime.now(timezone.utc)
status_str = "PASS" if passed else "FAIL"
# Git commit telemetry
git_telemetry = {
"commits_created": len(commit_shas),
"commit_shas": commit_shas,
"checkpoint_commit_sha": commit_shas[0] if commit_shas else "",
"commit_delegate_logged": all_logged,
}
log_checkpoint_telemetry(
RESULTS_DIR,
agent,
checkpoint,
started_at,
ended_at,
status=status_str,
outcome_reason=outcome_reason,
verification_data=verification_data,
git_data=git_telemetry,
)
if passed:
console.print(
f"[bold green]🚀 Checkpoint {checkpoint} PASSED for {agent}![/bold green]"
)
else:
console.print(
f"[bold red]⛔ Checkpoint {checkpoint} FAILED for {agent}. Agent must iterate within this checkpoint.[/bold red]"
)
return passed
def main():
parser = argparse.ArgumentParser(description="BDInvite SSO Benchmark Gatekeeper")
subparsers = parser.add_subparsers(dest="command")
# Freeze-check command
subparsers.add_parser("freeze-check")
# Baseline command
base_parser = subparsers.add_parser("baseline")
base_parser.add_argument(
"--worktree", type=Path, required=True, help="Path to worktree"
)
# Verify command
verify_parser = subparsers.add_parser("verify")
verify_parser.add_argument(
"--checkpoint",
type=str,
required=True,
choices=[f"CP{i}" for i in range(1, 9)],
)
verify_parser.add_argument(
"--worktree", type=Path, required=True, help="Path to worktree"
)
verify_parser.add_argument(
"--agent",
type=str,
required=True,
choices=["control", "graphify"],
help="Agent name",
)
args = parser.parse_args()
if args.command == "freeze-check":
ok = verify_freeze()
sys.exit(0 if ok else 1)
elif args.command == "baseline":
ok, passed, total, out = verify_baseline_tests(args.worktree)
if ok:
console.print(f"[green]✔ Baseline passed: {passed}/{total}[/green]")
sys.exit(0)
else:
console.print(f"[red]❌ Baseline failed:\n{out}[/red]")
sys.exit(1)
elif args.command == "verify":
ok = verify_checkpoint(args.checkpoint, args.worktree, args.agent)
sys.exit(0 if ok else 1)
else:
parser.print_help()
if __name__ == "__main__":
main()
@@ -0,0 +1,116 @@
"""Static architectural assertion checks for BDInvite SSO Benchmark."""
import ast
import re
from pathlib import Path
from typing import List, Tuple
def check_remote_user_purged(worktree_path: Path) -> List[str]:
"""Verify that runtime code contains zero occurrences of Remote-User header checks."""
violations = []
target_dirs = [
worktree_path / "backend" / "app",
worktree_path / "frontend" / "src",
]
pattern = re.compile(r"remote[-_]user", re.IGNORECASE)
for target_dir in target_dirs:
if not target_dir.exists():
continue
for file_path in target_dir.rglob("*"):
if not file_path.is_file() or file_path.suffix not in {
".py",
".ts",
".tsx",
".js",
".jsx",
}:
continue
try:
content = file_path.read_text(encoding="utf-8")
for line_no, line in enumerate(content.splitlines(), start=1):
if pattern.search(line):
violations.append(
f"{file_path.relative_to(worktree_path)}:{line_no}: {line.strip()}"
)
except Exception as e:
violations.append(
f"Error reading {file_path.relative_to(worktree_path)}: {e}"
)
return violations
def check_application_domain_imports(worktree_path: Path) -> List[str]:
"""Verify application domain code does not import OIDC/OAuth/JWT/cryptography libraries directly."""
violations = []
app_dir = worktree_path / "backend" / "app"
forbidden_modules = {
"authlib",
"jwt",
"jose",
"cryptography",
"oauth2",
"oauthlib",
}
# Directories to inspect (routes, models, schemas, utils) excluding any dedicated auth module
for target in app_dir.rglob("*.py"):
rel_path = target.relative_to(app_dir)
# Skip auth module itself and tests
parts = rel_path.parts
if "auth" in parts or "tests" in parts:
continue
# Also skip auth route if named auth.py under routes
if rel_path.name in {"auth.py", "oidc.py"}:
continue
try:
tree = ast.parse(target.read_text(encoding="utf-8"), filename=str(target))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
base = alias.name.split(".")[0]
if base in forbidden_modules:
violations.append(
f"{target.relative_to(worktree_path)}:{node.lineno}: import {alias.name}"
)
elif isinstance(node, ast.ImportFrom) and node.module:
base = node.module.split(".")[0]
if base in forbidden_modules:
violations.append(
f"{target.relative_to(worktree_path)}:{node.lineno}: from {node.module} import ..."
)
except Exception as e:
violations.append(
f"Error parsing AST in {target.relative_to(worktree_path)}: {e}"
)
return violations
def check_auth_port_abstraction(worktree_path: Path) -> Tuple[bool, List[str]]:
"""Verify that AuthPort and Identity abstractions are defined."""
app_dir = worktree_path / "backend" / "app"
notes = []
has_identity = False
has_auth_port = False
for py_file in app_dir.rglob("*.py"):
try:
content = py_file.read_text(encoding="utf-8")
if "class Identity" in content:
has_identity = True
notes.append(
f"Found Identity class in {py_file.relative_to(worktree_path)}"
)
if "class AuthPort" in content or "class AuthenticationPort" in content or "class IAuth" in content:
has_auth_port = True
notes.append(
f"Found AuthPort interface in {py_file.relative_to(worktree_path)}"
)
except Exception:
pass
return (has_identity and has_auth_port), notes
@@ -0,0 +1,46 @@
"""Telemetry logging utility for BDInvite SSO Benchmark."""
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Optional
def log_checkpoint_telemetry(
results_dir: Path,
agent: str,
checkpoint: str,
started_at: datetime,
ended_at: datetime,
status: str,
outcome_reason: str = "none",
verification_data: Optional[Dict[str, Any]] = None,
git_data: Optional[Dict[str, Any]] = None,
tool_calls: Optional[Dict[str, Any]] = None,
tokens: Optional[Dict[str, Any]] = None,
rework_iterations: int = 0,
) -> Path:
"""Record structured telemetry for a completed checkpoint evaluation."""
agent_dir = results_dir / agent
agent_dir.mkdir(parents=True, exist_ok=True)
out_file = agent_dir / f"{checkpoint}.json"
duration_wall_clock = int((ended_at - started_at).total_seconds())
record = {
"agent": agent,
"checkpoint": checkpoint,
"started_at": started_at.isoformat(),
"ended_at": ended_at.isoformat(),
"duration_wall_clock_seconds": duration_wall_clock,
"rework_iterations": rework_iterations,
"status": status,
"outcome_reason": outcome_reason,
"verification": verification_data or {},
"git": git_data or {},
"tool_calls": tool_calls or {},
"tokens": tokens or {},
}
out_file.write_text(json.dumps(record, indent=2), encoding="utf-8")
return out_file
@@ -0,0 +1,37 @@
# OIDC Benchmark Fixture
This fixture provides a standards-compliant, disposable OpenID Connect (OIDC) identity provider using `ghcr.io/navikt/mock-oauth2-server:2.1.10`.
## Endpoints
* **Base Issuer**: `http://localhost:8088/default`
* **Discovery Endpoint**: `http://localhost:8088/default/.well-known/openid-configuration`
* **Authorization Endpoint**: `http://localhost:8088/default/authorize`
* **Token Endpoint**: `http://localhost:8088/default/token`
* **JWKS URI**: `http://localhost:8088/default/jwks`
* **Userinfo Endpoint**: `http://localhost:8088/default/userinfo`
## Pre-Seeded Test Users
| Username / Email | Password | Subject | Name | Groups Claim | Expected Role |
| :--- | :--- | :--- | :--- | :--- | :--- |
| `admin@example.com` | `password123` | `admin-001` | `Admin User` | `["bdinvite_admins"]` | Admin |
| `guest@example.com` | `password123` | `guest-001` | `Guest User` | `["guests"]` | Non-Admin |
## Client Configuration
* **Client ID**: `bdinvite-client` (or any string)
* **Client Secret**: `bdinvite-secret` (or any string)
* **Redirect URI**: `http://localhost:8000/birthday/api/auth/callback` (or configured callback)
* **Supported PKCE**: `S256` (RFC 7636)
* **Supported Signing Alg**: `RS256`
## Management
```bash
# Start container and await readiness
./start.sh
# Stop container
./stop.sh
```
@@ -0,0 +1,59 @@
{
"interactiveLogin": true,
"tokenCallbacks": [
{
"issuerId": "default",
"tokenExpiry": 3600,
"requestMappings": [
{
"requestParam": "username",
"match": "admin@example.com",
"claims": {
"sub": "admin-001",
"email": "admin@example.com",
"name": "Admin User",
"groups": [
"bdinvite_admins"
]
}
},
{
"requestParam": "subject",
"match": "admin@example.com",
"claims": {
"sub": "admin-001",
"email": "admin@example.com",
"name": "Admin User",
"groups": [
"bdinvite_admins"
]
}
},
{
"requestParam": "username",
"match": "guest@example.com",
"claims": {
"sub": "guest-001",
"email": "guest@example.com",
"name": "Guest User",
"groups": [
"guests"
]
}
},
{
"requestParam": "subject",
"match": "guest@example.com",
"claims": {
"sub": "guest-001",
"email": "guest@example.com",
"name": "Guest User",
"groups": [
"guests"
]
}
}
]
}
]
}
@@ -0,0 +1,12 @@
services:
oidc:
image: ghcr.io/navikt/mock-oauth2-server:2.1.10
container_name: bdinvite-benchmark-oidc
ports:
- "8088:8080"
volumes:
- ./config.json:/config.json:ro
environment:
- JSON_CONFIG_PATH=/config.json
- SERVER_PORT=8080
restart: unless-stopped
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
echo "Starting OIDC Test Container..."
docker compose up -d
echo "Waiting for OIDC Discovery Endpoint..."
RETRY=0
MAX_RETRIES=20
until curl -s -f http://localhost:8088/default/.well-known/openid-configuration > /dev/null 2>&1; do
RETRY=$((RETRY+1))
if [ "$RETRY" -ge "$MAX_RETRIES" ]; then
echo "ERROR: OIDC container failed to become ready in time."
docker compose logs
exit 1
fi
sleep 1
done
echo "✅ OIDC Test Container ready at http://localhost:8088/default"
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
echo "Stopping OIDC Test Container..."
docker compose down
echo "✅ OIDC Test Container stopped."
@@ -0,0 +1,51 @@
{
"benchmark_name": "bdinvite_sso_benchmark",
"frozen_at": "2026-10-02T22:35:40Z",
"specification": {
"path": "specification/bdinvite_sso_benchmark_plan.md",
"sha256": "4b520fb57f1c96a5d7ac492d16aaabd8accd50b5afe328a3b0066102b4f27453",
"canonical_brain_plan": "/home/kiskaadee/Brain/01-plans/bdinvite/sso-benchmark-roadmap.md"
},
"baseline": {
"source_repository": "/home/kiskaadee/Homelab/Sites/bdinvite",
"commit_sha": "42927b9858c1b091bb6e78d3abcf6f9500bd7547",
"tests_total": 25,
"tests_passed": 25,
"status": "VERIFIED_CLEAN"
},
"fixture": {
"image": "ghcr.io/navikt/mock-oauth2-server:2.1.10",
"issuer_url": "http://localhost:8088/default",
"discovery_url": "http://localhost:8088/default/.well-known/openid-configuration",
"client_id": "bdinvite-client",
"client_secret": "bdinvite-secret",
"pre_seeded_users": [
{
"username": "admin@example.com",
"groups": ["bdinvite_admins"]
},
{
"username": "guest@example.com",
"groups": ["guests"]
}
]
},
"evaluator": {
"runner": "evaluator/gatekeeper.py",
"python_env": "evaluator/.venv",
"playwright_browser": "chromium",
"checkpoints": ["CP1", "CP2", "CP3", "CP4", "CP5", "CP6", "CP7", "CP8"]
},
"worktrees": {
"control": {
"path": "control",
"branch": "control/feat/sso-auth",
"toolchain": ["grep", "find", "view_file", "git"]
},
"graphify": {
"path": "graphify",
"branch": "graphify/feat/sso-auth",
"toolchain": ["grep", "find", "view_file", "git", "graphify"]
}
}
}
@@ -0,0 +1,54 @@
{
"agent": "control",
"checkpoint": "CP1",
"started_at": "2026-10-03T03:49:18.283328+00:00",
"ended_at": "2026-10-03T03:49:35.113702+00:00",
"duration_wall_clock_seconds": 16,
"rework_iterations": 0,
"status": "PASS",
"outcome_reason": "none",
"verification": {
"checkpoint_tests": {
"passed": 1,
"total": 1
},
"cumulative_regression_tests": {
"passed": 25,
"total": 25
},
"failed_verifications_count": 0,
"details": []
},
"git": {
"commits_created": 1,
"commit_shas": [
"79c3e8252c0d2e5fc0c9694ffb876e59ec11bb1e"
],
"checkpoint_commit_sha": "79c3e8252c0d2e5fc0c9694ffb876e59ec11bb1e",
"commit_delegate_logged": false,
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 6,
"run_grep_or_find": 2
},
"implementation": {
"write_to_file": 4
},
"verification": {
"run_test_command": 5
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 480370,
"output_tokens_est": 8308,
"total_tokens_est": 488678
}
}
@@ -0,0 +1,43 @@
{
"agent": "control",
"checkpoint": "CP2",
"status": "PASS",
"outcome_reason": "none",
"turns": 61,
"verification": {
"cumulative_tests_passed": 47,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"b2cee2447286816b7ebeb35fd6b841ae6506d9ac"
],
"checkpoint_commit_sha": "b2cee2447286816b7ebeb35fd6b841ae6506d9ac",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 9
},
"implementation": {
"write_to_file": 3,
"replace_file_content": 3
},
"verification": {
"run_command": 42
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 1537210,
"output_tokens_est": 26807,
"total_tokens_est": 1564017
}
}
@@ -0,0 +1,44 @@
{
"agent": "control",
"checkpoint": "CP3",
"status": "PASS",
"outcome_reason": "none",
"turns": 62,
"verification": {
"cumulative_tests_passed": 62,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"670f4f836dc2829b313c068805b39d883651fad3"
],
"checkpoint_commit_sha": "670f4f836dc2829b313c068805b39d883651fad3",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 19,
"search_web": 3
},
"implementation": {
"write_to_file": 2,
"replace_file_content": 6
},
"verification": {
"run_command": 26
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 1954952,
"output_tokens_est": 21635,
"total_tokens_est": 1976587
}
}
@@ -0,0 +1,43 @@
{
"agent": "control",
"checkpoint": "CP4",
"status": "PASS",
"outcome_reason": "none",
"turns": 66,
"verification": {
"cumulative_tests_passed": 76,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"d7618d574ce334b6bd63fbe6967fdc30cdd13e32"
],
"checkpoint_commit_sha": "d7618d574ce334b6bd63fbe6967fdc30cdd13e32",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 28
},
"implementation": {
"write_to_file": 5,
"replace_file_content": 6
},
"verification": {
"run_command": 21
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 2592809,
"output_tokens_est": 27256,
"total_tokens_est": 2620065
}
}
@@ -0,0 +1,43 @@
{
"agent": "control",
"checkpoint": "CP5",
"status": "PASS",
"outcome_reason": "none",
"turns": 53,
"verification": {
"cumulative_tests_passed": 91,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"f20fb0fc980061a91ecdd419a975b10c754b07dc"
],
"checkpoint_commit_sha": "f20fb0fc980061a91ecdd419a975b10c754b07dc",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 27
},
"implementation": {
"write_to_file": 3,
"replace_file_content": 1
},
"verification": {
"run_command": 18
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 1431139,
"output_tokens_est": 18882,
"total_tokens_est": 1450022
}
}
@@ -0,0 +1,44 @@
{
"agent": "control",
"checkpoint": "CP6",
"status": "PASS",
"outcome_reason": "none",
"turns": 82,
"verification": {
"cumulative_tests_passed": 96,
"baseline_passed": 25,
"failed_verifications_count": 0,
"negative_barrier_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"b0dea63c3fdff5d1ebdb0637a0a9491091db7083"
],
"checkpoint_commit_sha": "b0dea63c3fdff5d1ebdb0637a0a9491091db7083",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 31
},
"implementation": {
"write_to_file": 1,
"replace_file_content": 16
},
"verification": {
"run_command": 28
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 3833921,
"output_tokens_est": 23609,
"total_tokens_est": 3857530
}
}
@@ -0,0 +1,45 @@
{
"agent": "control",
"checkpoint": "CP7",
"status": "PASS",
"outcome_reason": "none",
"turns": 112,
"verification": {
"cumulative_tests_passed": 97,
"baseline_passed": 25,
"failed_verifications_count": 0,
"playwright_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"d9b589ccdaf7a3089b4aa107c641d81ad1792d74"
],
"checkpoint_commit_sha": "d9b589ccdaf7a3089b4aa107c641d81ad1792d74",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 34
},
"implementation": {
"write_to_file": 1,
"replace_file_content": 10
},
"verification": {
"run_command": 57,
"manage_task": 6
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 4271564,
"output_tokens_est": 19886,
"total_tokens_est": 4291450
}
}
@@ -0,0 +1,45 @@
{
"agent": "control",
"checkpoint": "CP8",
"status": "PASS",
"outcome_reason": "none",
"turns": 96,
"verification": {
"cumulative_tests_passed": 110,
"baseline_passed": 25,
"failed_verifications_count": 0,
"static_remote_user_purged": true,
"docker_build_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"713a5827695539993ff0cb3d12e8b0c0ebccb9f1"
],
"checkpoint_commit_sha": "713a5827695539993ff0cb3d12e8b0c0ebccb9f1",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 35
},
"implementation": {
"write_to_file": 3,
"replace_file_content": 10
},
"verification": {
"run_command": 44
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 3636852,
"output_tokens_est": 22163,
"total_tokens_est": 3659015
}
}
@@ -0,0 +1,60 @@
{
"agent": "graphify",
"checkpoint": "CP1",
"started_at": "2026-10-03T03:49:39.232144+00:00",
"ended_at": "2026-10-03T03:49:56.661509+00:00",
"duration_wall_clock_seconds": 17,
"rework_iterations": 0,
"status": "PASS",
"outcome_reason": "none",
"verification": {
"checkpoint_tests": {
"passed": 1,
"total": 1
},
"cumulative_regression_tests": {
"passed": 25,
"total": 25
},
"failed_verifications_count": 0,
"details": []
},
"git": {
"commits_created": 1,
"commit_shas": [
"df498979d97a6ac2d58deb4f3f33b12556853217"
],
"checkpoint_commit_sha": "df498979d97a6ac2d58deb4f3f33b12556853217",
"commit_delegate_logged": false,
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 6,
"run_grep_or_find": 4,
"graphify_queries": 2,
"graphify_updates": 1
},
"implementation": {
"write_to_file": 3
},
"verification": {
"run_test_command": 6
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1,
"graph_queries": 2
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 402812,
"output_tokens_est": 8740,
"total_tokens_est": 411553
}
}
@@ -0,0 +1,47 @@
{
"agent": "graphify",
"checkpoint": "CP2",
"status": "PASS",
"outcome_reason": "none",
"turns": 52,
"verification": {
"cumulative_tests_passed": 44,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"0a4032a34489e46a4540c4d5f5d89ee8aad2ba20"
],
"checkpoint_commit_sha": "0a4032a34489e46a4540c4d5f5d89ee8aad2ba20",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 7,
"graphify_update": 1
},
"implementation": {
"write_to_file": 3,
"replace_file_content": 1
},
"verification": {
"run_command": 37
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 1041206,
"output_tokens_est": 24935,
"total_tokens_est": 1066142
}
}
@@ -0,0 +1,47 @@
{
"agent": "graphify",
"checkpoint": "CP3",
"status": "PASS",
"outcome_reason": "none",
"turns": 67,
"verification": {
"cumulative_tests_passed": 59,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"35be202adc7a8b93cf834ae68e2b592969abcc53"
],
"checkpoint_commit_sha": "35be202adc7a8b93cf834ae68e2b592969abcc53",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 20,
"graphify_update": 1
},
"implementation": {
"write_to_file": 1,
"replace_file_content": 5
},
"verification": {
"run_command": 28
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 2392589,
"output_tokens_est": 26065,
"total_tokens_est": 2418654
}
}
@@ -0,0 +1,47 @@
{
"agent": "graphify",
"checkpoint": "CP4",
"status": "PASS",
"outcome_reason": "none",
"turns": 101,
"verification": {
"cumulative_tests_passed": 70,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"815a5847c6b4b557a1e181af67af05ce9d933001"
],
"checkpoint_commit_sha": "815a5847c6b4b557a1e181af67af05ce9d933001",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 41,
"graphify_update": 1
},
"implementation": {
"write_to_file": 3,
"replace_file_content": 14
},
"verification": {
"run_command": 39
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 4542036,
"output_tokens_est": 32881,
"total_tokens_est": 4574917
}
}
@@ -0,0 +1,47 @@
{
"agent": "graphify",
"checkpoint": "CP5",
"status": "PASS",
"outcome_reason": "none",
"turns": 53,
"verification": {
"cumulative_tests_passed": 90,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"27015d0d72e248e779ce091b5aacd0d8f22475f3"
],
"checkpoint_commit_sha": "27015d0d72e248e779ce091b5aacd0d8f22475f3",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 15,
"graphify_update": 1
},
"implementation": {
"write_to_file": 2,
"replace_file_content": 4
},
"verification": {
"run_command": 25
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 1191995,
"output_tokens_est": 16039,
"total_tokens_est": 1208035
}
}
@@ -0,0 +1,48 @@
{
"agent": "graphify",
"checkpoint": "CP6",
"status": "PASS",
"outcome_reason": "none",
"turns": 79,
"verification": {
"cumulative_tests_passed": 95,
"baseline_passed": 25,
"failed_verifications_count": 0,
"negative_barrier_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"39ac42cfcea3bd379f7089bdf882703850ab3535"
],
"checkpoint_commit_sha": "39ac42cfcea3bd379f7089bdf882703850ab3535",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 32,
"graphify_update": 1
},
"implementation": {
"write_to_file": 1,
"replace_file_content": 11
},
"verification": {
"run_command": 31
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 3348307,
"output_tokens_est": 21892,
"total_tokens_est": 3370200
}
}
@@ -0,0 +1,53 @@
{
"agent": "graphify",
"checkpoint": "CP7",
"status": "PASS",
"outcome_reason": "none",
"turns": 147,
"verification": {
"cumulative_tests_passed": 96,
"baseline_passed": 25,
"failed_verifications_count": 0,
"playwright_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"e1f745608a9a00a27baaa014b2d631f91adcbecd"
],
"checkpoint_commit_sha": "e1f745608a9a00a27baaa014b2d631f91adcbecd",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 41,
"graphify_query": 1,
"graphify_update": 1,
"search_web": 1
},
"implementation": {
"write_to_file": 1,
"replace_file_content": 7
},
"verification": {
"run_command": 87,
"manage_task": 5,
"schedule": 1
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_queries": 1,
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 6747276,
"output_tokens_est": 26848,
"total_tokens_est": 6774124
}
}
@@ -0,0 +1,49 @@
{
"agent": "graphify",
"checkpoint": "CP8",
"status": "PASS",
"outcome_reason": "none",
"turns": 93,
"verification": {
"cumulative_tests_passed": 115,
"baseline_passed": 25,
"failed_verifications_count": 0,
"static_remote_user_purged": true,
"docker_build_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"30d9a889a351b53158c0da87491194fb3056943a"
],
"checkpoint_commit_sha": "30d9a889a351b53158c0da87491194fb3056943a",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 30,
"graphify_update": 2
},
"implementation": {
"write_to_file": 2,
"replace_file_content": 13
},
"verification": {
"run_command": 44
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 2
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 3079082,
"output_tokens_est": 20381,
"total_tokens_est": 3099463
}
}
@@ -0,0 +1,376 @@
# Implementation Plan: BDInvite SSO Benchmark & Checkpoint Roadmap (Frozen Specification v6)
## Goal Description
Establish a controlled, reproducible A/B benchmark comparing two autonomous agents implementing application-level OpenID Connect (OIDC) Single Sign-On (SSO) in the `bdinvite` repository:
1. **Control Agent**: Standard repository exploration and toolchain (`grep`, `find`, `view_file`, `git`, etc.).
2. **Treatment Agent (Graphify)**: Standard toolchain **plus** Graphify-augmented exploration (`graphify query`, `graphify path`, `graphify explain`, and `graphify update .`).
### Core Architectural Invariant: Hexagonal Authentication Boundary
The benchmark moves authentication from an infrastructure property (Traefik reverse proxy + Authelia ForwardAuth + `Remote-User` header inspection) into a **decoupled application port (`AuthPort`)**:
* **Strict Separation of Authentication vs. Authorization**:
- **Authentication ("Who are you?")**: Handled by `AuthPort`, which resolves requests into typed `Identity` objects carrying standard attributes and group memberships (`groups: list[str]`).
- **Authorization ("What are you allowed to do?")**: Handled exclusively by the **Application Domain**, which evaluates application policies against `identity.groups` (e.g., `"bdinvite_admins" in identity.groups`). `AuthPort` does not own authorization decisions.
* **Identity Origin Integrity**: `Identity` contains only claims authenticated and validated by the authentication module. Application code must **never** construct an authenticated `Identity` directly from unvalidated request-controlled data (headers, query parameters, body).
* **OIDC Authentication Module**: Implements `AuthPort` and communicates with any standards-compliant OIDC Provider through a generic OIDC client (discovery, PKCE/state/nonce, token exchange, JWKS signature validation).
* **Deployment Independence**: The exact same codebase runs:
- Locally / standalone against a disposable standards-compliant OIDC test container.
- In homelab production against **Authelia configured as an OIDC Provider**, reducing Traefik strictly to TLS termination and reverse-proxy routing (zero ForwardAuth middleware).
---
## Epistemic Roles of Benchmark Artifacts
The experiment maintains a strict division of artifact roles across three distinct locations:
| Artifact | Location | Epistemic Role | Mutability |
| :--- | :--- | :--- | :--- |
| **Canonical Engineering Plan** | `Brain/01-plans/bdinvite/sso-benchmark-roadmap.md` | Vault knowledge graph, project topology, roadmap | Mutable across project lifecycle |
| **Immutable Benchmark Snapshot** | `benchmark/specification/bdinvite_sso_benchmark_plan.md` | Concrete experimental input; hashed (SHA-256) | **Immutable / Frozen** |
| **Machine Event Ledger** | `Brain/00-inbox/commit-log.csv` | Lossless event capture from `commit-logger` | Append-only raw data |
---
## Frozen Experimental Invariants & Decisions
1. **Authentication vs. Authorization Separation**:
- `AuthPort` defines only authentication mechanics: `current_identity(request)`, `login(request)`, and `logout(request)`.
- `Identity` carries `subject`, `email`, `name`, and `groups: list[str]`.
- Group authorization is an application-domain policy: `require_group("bdinvite_admins")` verifies `"bdinvite_admins" in identity.groups`.
2. **Identity Origin Integrity**:
- Identity fields must be derived exclusively from claims contained in the cryptographically validated ID token / validated OIDC authentication result. Unvalidated userinfo or request data must not be used to construct `Identity`.
3. **Session Contract & Session Fixation Protection**:
- Browser session uses `HttpOnly: true` and an explicit `SameSite` policy. No bearer tokens exposed to JavaScript.
- Successful authentication must establish a **new session identifier**; an existing pre-authentication session identifier must not be promoted into an authenticated session (`pre_auth_session_id != post_auth_session_id`).
- `Secure` flag contract: `Secure=True` in production; configurable (`Secure=False`) in the local HTTP test environment so browsers do not reject cookies over local test ports.
- Internal storage (client-side encrypted/signed vs server-side SQLite table) is left to the agent's architectural discretion.
4. **Provider Model & Group Claim**:
- The test fixture uses a standards-compliant disposable OIDC provider container pre-seeded with discovery, JWKS, and standard users.
- The fixture's group claim is frozen as `"groups": ["bdinvite_admins"]` (for admin) and `"groups": ["guests"]` (for guest). The auth module maps this configured claim to `Identity.groups`.
5. **Git Workflow Invariant (Subagent Delegation)**:
- At every meaningful implementation milestone required by the roadmap, the primary implementation agent **must recruit the `git-commit` skill via subagent delegation** (`invoke_subagent` with Role: "Git History Custodian").
- **Both Control and Treatment agents MUST use the identical `git-commit` workflow.**
- **Graphify is explicitly excluded from the `git-commit` subagent's toolset and prompt.** The experimental variable remains strictly confined to the primary agent's repository exploration.
- The benchmark harness records the resulting commit SHA, parent SHA, subject, checkpoint, and timing. The harness itself **never** creates implementation commits.
- Commits created solely to manipulate benchmark metrics without meaningful code/test changes are prohibited.
6. **Graphify Lifecycle Rules**:
- The Graphify agent may run `graphify update .` whenever repository changes make the existing graph stale.
- Every graph update, query, path, and explanation is recorded in telemetry under `graph_lifecycle`.
- The prompt does **not** force the agent to use Graphify; Graphify is simply available as an additional capability alongside standard tools.
7. **Evaluator Immutability Barrier**:
- Neither agent may alter the roadmap, checkpoint definitions, verification test suite, test credentials, or telemetry logger. All evaluation occurs via an external test runner outside the agents' worktrees.
---
## Pre-Experiment Preparation & Freeze Phase
Before either implementation agent touches a worktree, the experiment harness executes the **Pre-Experiment Freeze Gate**:
```mermaid
flowchart TD
Start["Pre-Experiment Freeze Gate"] --> FreezeSpec["1. Write & Hash Specification<br/>benchmark/specification/bdinvite_sso_benchmark_plan.md<br/>Compute SHA-256"]
FreezeSpec --> FreezeHarness["2. Freeze Evaluator & Test Suite<br/>(External pytest + Playwright tests)"]
FreezeHarness --> FreezeFixture["3. Freeze OIDC Fixture & Credentials<br/>(Docker Compose + JWKS + Users)"]
FreezeFixture --> BaselineManifest["4. Generate baseline.json<br/>(Observed Commit SHA, 25 Passing Tests, Builds)"]
BaselineManifest --> Worktrees["5. Stand Up Isolated Worktrees<br/>control/ & graphify/<br/>Verify Identical Starting Commit"]
Worktrees --> CP0Done["CP0 Readiness Verified<br/>Launch Benchmark Execution"]
```
1. **Specification Hashing**:
- Write immutable snapshot to `/home/kiskaadee/Projects/tests/bdinvite-benchmark/specification/bdinvite_sso_benchmark_plan.md`.
- Calculate and record its SHA-256 hash in `manifest.json`.
2. **Evaluator Freeze**:
- Scaffold external evaluation scripts and test suites under `benchmark/evaluator/`.
3. **Fixture Freeze**:
- Stand up the disposable OIDC provider container (pre-seeded with discovery, JWKS, client credentials, and users).
4. **Baseline Manifest Generation**:
- Record observed starting commit (`42927b9858c1b091bb6e78d3abcf6f9500bd7547`), verify 25 passing backend tests, frontend build, and Docker container build.
5. **Worktree Provisioning**:
- Create worktree: `/home/kiskaadee/Projects/tests/bdinvite-benchmark/control` (branch `control/feat/sso-auth`).
- Create worktree: `/home/kiskaadee/Projects/tests/bdinvite-benchmark/graphify` (branch `graphify/feat/sso-auth`).
- Run initial `graphify extract . --code-only` inside the `graphify` worktree.
---
## Sequential Checkpoint Roadmap (CP1 – CP8)
```mermaid
flowchart LR
CP1["CP1: AuthPort Contract"] --> CP2["CP2: OIDC Client & PKCE"]
CP2 --> CP3["CP3: Identity Resolution"]
CP3 --> CP4["CP4: HttpOnly Session & Fixation"]
CP4 --> CP5["CP5: DI Dependencies"]
CP5 --> CP6["CP6: Admin Route Migration"]
CP6 --> CP7["CP7: Browser SSO Flow"]
CP7 --> CP8["CP8: Hardening & Independence"]
```
---
### Checkpoint 1 (CP1): The Authentication Port (`AuthPort`)
* **Objective**: Define the application-facing authentication boundary and identity domain models, decoupling the application domain completely from upstream protocols and proxies.
* **Behavioral Requirements**:
- Define domain abstraction: `Identity` (holding `subject: str`, `email: str`, `name: Optional[str]`, `groups: list[str]`).
- Identity Origin Integrity: `Identity` must only be constructed from validated authentication results, never raw client headers.
- Define `AuthPort` protocol establishing:
* `current_identity(request: Request) -> Optional[Identity]`
* `login(request: Request) -> Response`
* `logout(request: Request) -> Response`
- Zero application routes or domain models may import or reference OIDC, OAuth, JWT, or proxy headers.
* **Verification & Invariant**:
- Unit tests verifying `AuthPort` contract with a test mock implementation.
- **Behavioral Invariant**: **No externally observable application behavior changes during CP1.** (Minimal dependency wiring and unit tests are allowed; existing endpoints behave identically).
- All 25 baseline tests continue to pass.
* **Exit Criteria**:
- `AuthPort` abstraction established and testable in isolation.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 2 (CP2): Generic OIDC Client, PKCE & Cryptographic Verification
* **Objective**: Implement the generic OIDC protocol client capable of communicating with any OIDC provider with strict PKCE, CSRF state, and replay nonce validation.
* **Protocol Invariants & Behavioral Requirements**:
- Fetch and parse OIDC discovery document (`/.well-known/openid-configuration`).
- **PKCE (RFC 7636)**:
* Generate cryptographically random `code_verifier`.
* Derive `code_challenge` using SHA-256 (`code_challenge_method=S256`).
* Include `code_challenge` and `code_challenge_method` in the authorization request.
* Persist `code_verifier` across the transaction and supply it in the token exchange.
- **Transaction Correlation (`state`)**: Construct authorization URL with a cryptographic `state` parameter; validate `state` on callback to prevent CSRF attacks.
- **Replay Protection (`nonce`)**: Construct authorization URL with a cryptographic `nonce`; validate that the signed ID token's `nonce` claim matches the initiated request.
- Exchange authorization code for token response (`/token`).
- Cryptographically validate ID Token:
* Signature verification against provider's JWKS endpoint (`/jwks.json`).
* Issuer validation (`iss` == configured issuer).
* Audience validation (`aud` == configured client ID).
* Expiration validation (`exp` > current timestamp).
* **Verification**:
- Automated tests against the OIDC test container:
* Valid code exchange returns signed ID token.
* Authorization request verified to contain PKCE and `state`/`nonce` parameters.
* Invalid `state` rejected with 400.
* Mismatched `nonce`, missing PKCE verifier, or expired token rejected with 401.
* Tampered signature rejected with 401.
* **Exit Criteria**:
- OIDC exchange passes all cryptographic and protocol validation gates.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 3 (CP3): OIDC Identity & Group Extraction
* **Objective**: Connect the generic OIDC client to the `AuthPort` identity resolution lifecycle, deriving identity strictly from authenticated claims.
* **Behavioral Requirements**:
- Extract standard claims (`sub`, `email`, `name`).
- Extract group membership claims from the frozen fixture claim path (`"groups"`).
- Authoritative Provenance: `Identity` fields must be derived exclusively from claims contained in the cryptographically validated ID token / validated OIDC authentication result; unvalidated userinfo or request data must not be used to construct `Identity`.
- Confirm `admin@example.com` produces `groups: ["bdinvite_admins"]` and `guest@example.com` produces `groups: ["guests"]`.
* **Verification**:
- Test verifying end-to-end extraction from OIDC callback to typed `Identity`.
* **Exit Criteria**:
- Clean mapping from provider claims to application `Identity`.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 4 (CP4): Browser Session Management & Session Fixation Protection
* **Objective**: Establish and persist an application-level browser session following successful OIDC authentication with session fixation protection.
* **Behavioral Requirements**:
- Issue session identifier via `HttpOnly`, `SameSite` cookie upon successful authentication.
- **Session Fixation Barrier**: Successful authentication must establish a **new session identifier**; an existing pre-authentication session identifier must not be promoted into an authenticated session (`pre_auth_session_id != post_auth_session_id`).
- Cookie security configuration: `Secure=True` in production, configurable for local HTTP testing.
- Session resolution: identify returning requests from the session cookie.
- Expiration: reject expired sessions.
- Invalidation: `/birthday/api/auth/logout` revokes session and clears cookie.
- Security Invariant: Session token/cookie must not be readable by client-side JavaScript (`HttpOnly: true`).
* **Verification**:
- Tests verifying:
* Pre-authentication session ID is rotated upon login.
* Request with valid session cookie resolves to authenticated `Identity`.
* Request without cookie resolves to anonymous (`None`).
* Tampered cookie rejected (401).
* Logout clears session.
* **Exit Criteria**:
- Browser session contract fully functional and verified.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 5 (CP5): FastAPI Dependency Injection (Isolated Verification)
* **Objective**: Expose authentication and group authorization to FastAPI endpoints via standard dependency injection (`Depends`), verified independently on isolated test harnesses before modifying production admin routes.
* **Behavioral Requirements**:
- Implement FastAPI dependencies:
* `get_current_identity -> Optional[Identity]`
* `require_authenticated -> Identity` (401 if anonymous)
* `require_group(group_name: str) -> Callable[..., Identity]` (401 if anonymous, 403 if missing group)
- Application authorization policy:
* `require_admin = require_group("bdinvite_admins")`
* **Verification**:
- Verified on dedicated test routes / unit dependency harnesses:
* Anonymous request $\to$ 401 Unauthorized.
* Authenticated user without `bdinvite_admins` $\to$ 403 Forbidden.
* Authenticated user with `bdinvite_admins` $\to$ yields `Identity` object.
* **Exit Criteria**:
- Dependency injection contract verified in isolation without yet altering production admin routes.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 6 (CP6): Admin API Route Migration & Negative Barrier
* **Objective**: Migrate all endpoints in `backend/app/routes/admin.py` to use `Depends(require_group("bdinvite_admins"))`, purging `Remote-User` from runtime code.
* **Behavioral Requirements**:
- Update `/rsvps`, `/export`, `/config`, `/map-preview/generate` to consume the new group authorization dependency.
- Update `test_admin.py` test suite to use test session injection rather than mock headers.
- Anonymous requests receive 401 Unauthorized.
- Authenticated non-admin requests (`guest@example.com`) receive 403 Forbidden.
- Authenticated admin requests (`admin@example.com`) succeed.
- **CRITICAL NEGATIVE GATE**:
```python
def test_remote_user_header_strictly_ignored(client):
# A request containing Remote-User without a valid session MUST be rejected
res = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "kiskaadee"})
assert res.status_code == 401
```
* **Exit Criteria**:
- Negative gate passes.
- All existing admin functionality (RSVP listing, CSV export, config updates) passes cleanly.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 7 (CP7): Complete Browser SSO Flow (Playwright Acceptance)
* **Objective**: Integrate the React SPA in `frontend/src/admin` with the OIDC authentication flow and verify the complete browser lifecycle using a real browser automation suite (Playwright).
* **Deterministic Contract & Behavioral Requirements**:
- An unauthenticated navigation to `/birthday/admin` must initiate authentication by navigating to `/birthday/api/auth/login`.
- The login endpoint redirects to the configured OIDC authorization endpoint.
- Callback completes, sets `HttpOnly` cookie, and redirects user into `/birthday/admin`.
- Admin header displays authenticated user info and a working Logout button.
- Clicking Logout calls `/birthday/api/auth/logout` and returns UI to unauthenticated state.
* **Verification (Playwright Acceptance Suite)**:
- Real browser automation validating the entire interactive loop:
1. Navigate to `/birthday/admin` $\to$ redirected to OIDC login.
2. Submit test credentials (`admin@example.com` / `password123`).
3. Browser follows redirect to callback $\to$ receives `HttpOnly` session cookie $\to$ lands on Admin Dashboard.
4. Confirm RSVPs table renders live data.
5. Click Logout button $\to$ cookie invalidated $\to$ unauthenticated state confirmed.
- Frontend TypeScript build compiles with zero errors (`npm run build`).
* **Exit Criteria**:
- Playwright browser acceptance test passes 100%.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 8 (CP8): Security Hardening & Deployment Independence
* **Objective**: Subject the completed application to adversarial edge cases, verify cumulative test status, and verify dual-environment deployment.
* **Adversarial & Security Verification**:
1. Forged / invalid CSRF `state` $\to$ 400 Bad Request.
2. Forged / tampered ID token $\to$ 401 Unauthorized.
3. Mismatched / replayed `nonce` $\to$ 401 Unauthorized.
4. Missing or invalid PKCE `code_verifier` $\to$ 401 Unauthorized.
5. Expired ID token / expired session $\to$ 401 Unauthorized.
6. Non-admin user accessing admin APIs $\to$ 403 Forbidden.
7. Forged `Remote-User` header $\to$ 401 Unauthorized.
* **Deployment Independence Verification**:
1. **Direct Standalone Mode**: BDInvite + OIDC test container with NO Traefik and NO Authelia $\to$ **PASS**.
2. **Homelab Production Mode**: BDInvite deployed with Authelia acting as an OIDC provider, with Traefik providing pure TLS/ingress $\to$ **PASS**.
* **Cumulative Verification Definition**:
The cumulative suite requires 100% pass across:
- All checkpoint-specific suites (CP1–CP7).
- All baseline regression tests (25/25 original tests).
- Playwright end-to-end browser suite.
- CP8 adversarial security suite.
* **Exit Criteria**:
- All cumulative verification tests pass.
- Multi-stage Docker container builds successfully.
- Changes committed via `git-commit` subagent.
- Final checkpoint report generated.
---
## Enhanced Telemetry & Metric Capture Protocol
For each subagent across each checkpoint (CP1 to CP8), the experiment harness records granular telemetry into `results/<agent>/<checkpoint>.json`:
```json
{
"agent": "control | graphify",
"checkpoint": "CP4",
"started_at": "2026-10-02T22:30:00Z",
"ended_at": "2026-10-02T22:45:00Z",
"duration_wall_clock_seconds": 900,
"duration_active_seconds": 740,
"turns": 14,
"attempts": 2,
"rework_iterations": 1,
"status": "PASS | FAIL | BLOCKED",
"outcome_reason": "none | verification_failure | environment_failure | timeout",
"verification": {
"checkpoint_tests": {
"passed": 8,
"total": 8
},
"cumulative_regression_tests": {
"passed": 25,
"total": 25
},
"failed_verifications_count": 3
},
"git": {
"commits_created": 2,
"checkpoint_commit_sha": "a81f3c2...",
"commit_shas": ["91bc7de...", "a81f3c2..."]
},
"tool_calls": {
"exploration": {
"view_file": 8,
"run_grep_or_find": 4,
"graphify_query": 3,
"graphify_path": 2,
"graphify_explain": 1
},
"implementation": {
"replace_file_content": 5,
"write_to_file": 2
},
"verification": {
"run_test_command": 4
},
"graph_lifecycle": {
"graph_extractions": 1,
"graph_queries": 3,
"graph_paths": 2,
"graph_explains": 1
},
"other": {
"git_status": 2,
"env_checks": 1
}
},
"tokens": {
"input_tokens": 42100,
"output_tokens": 5400,
"total_tokens": 47500
}
}
```
---
## Final Independent Evaluation: Static & Behavioral Compliance
At the conclusion of the experiment, an independent evaluator analyzes both worktrees across three objective axes:
1. **Functional Correctness**:
- 100% pass rate on all cumulative checkpoint verification suites.
- 100% pass rate on the baseline regression suite (25/25 original tests).
- Playwright end-to-end browser acceptance suite passes.
2. **Static Architectural Assertions**:
- Runtime `Remote-User` occurrences across `backend/app/` and `frontend/src/` == 0.
- Application domain imports of OIDC, OAuth, JWT, or proxy libraries == 0.
- `Identity` construction sites enumerated and verified to originate strictly from validated claims.
- `AuthPort` interface implementation exists.
- Admin routes depend strictly on application group authorization.
- OIDC issuer is externalized and loaded from configuration.
- Traefik is strictly an ingress/TLS proxy with zero authentication middleware responsibilities.
3. **Exploration Efficiency**:
- Side-by-side comparison of exploration tool calls vs implementation tool calls.
- Total tokens and turns consumed per checkpoint.
- Frequency of rework iterations when encountering verification failures.
+138 -7
View File
@@ -1,5 +1,5 @@
import { type FormEvent, useEffect, useState } from "react";
import { fetchAdminConfig, updateAdminConfig } from "../api/client";
import { fetchAdminConfig, regenerateMapPreview, updateAdminConfig } from "../api/client";
import { Button } from "../components/Button";
import { Field } from "../components/Field";
import { Spinner } from "../components/Spinner";
@@ -9,6 +9,11 @@ export function ConfigEditor() {
const [formData, setFormData] = useState<InvitationConfig | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [regeneratingMap, setRegeneratingMap] = useState(false);
const [mapNotice, setMapNotice] = useState<{
type: "success" | "error";
msg: string;
} | null>(null);
const [feedback, setFeedback] = useState<{
type: "success" | "error";
msg: string;
@@ -58,6 +63,28 @@ export function ConfigEditor() {
}
}
async function handleRegenerateMap() {
if (!formData?.map_url || regeneratingMap) return;
setRegeneratingMap(true);
setMapNotice(null);
try {
const res = await regenerateMapPreview(formData.map_url);
setFormData({ ...formData, map_preview_url: res.map_preview_url });
setMapNotice({
type: "success",
msg: `¡Vista previa regenerada con éxito! (Coordenadas: ${res.lat.toFixed(4)}, ${res.lng.toFixed(4)})`,
});
} catch (err) {
setMapNotice({
type: "error",
msg: err instanceof Error ? err.message : "Error al regenerar el mapa.",
});
} finally {
setRegeneratingMap(false);
}
}
if (loading) {
return (
<div style={{ padding: "4rem", textAlign: "center" }}>
@@ -226,12 +253,116 @@ export function ConfigEditor() {
/>
</div>
<Field
label="URL de Imagen Previa del Mapa (map_preview_url)"
value={formData.map_preview_url}
onChange={(e) => handleChange("map_preview_url", e.target.value)}
required
/>
<div
style={{
backgroundColor: "rgba(255, 255, 255, 0.03)",
border: "1px solid rgba(212, 168, 67, 0.2)",
borderRadius: "6px",
padding: "1.2rem",
marginBottom: "1.4rem",
display: "flex",
flexWrap: "wrap",
gap: "1.5rem",
alignItems: "center",
}}
>
{/* Visual circular thumbnail preview */}
<div
style={{
width: "80px",
height: "80px",
borderRadius: "50%",
overflow: "hidden",
border: "1.5px solid var(--color-gold)",
backgroundColor: "#151515",
flexShrink: 0,
boxShadow: "0 2px 10px rgba(0,0,0,0.5)",
}}
>
{formData.map_preview_url ? (
<img
src={formData.map_preview_url}
alt="Vista previa mapa"
style={{
width: "100%",
height: "100%",
objectFit: "cover",
display: "block",
}}
/>
) : (
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
height: "100%",
fontSize: "0.7rem",
color: "var(--color-text-muted)",
}}
>
Sin mapa
</div>
)}
</div>
<div style={{ flex: 1, minWidth: "240px" }}>
<Field
label="URL de Imagen Previa del Mapa (map_preview_url)"
value={formData.map_preview_url}
onChange={(e) => handleChange("map_preview_url", e.target.value)}
required
/>
<div
style={{
marginTop: "0.8rem",
display: "flex",
alignItems: "center",
gap: "1rem",
flexWrap: "wrap",
}}
>
<Button
type="button"
variant="outline"
disabled={regeneratingMap || !formData.map_url}
onClick={handleRegenerateMap}
style={{ padding: "0.55rem 1.1rem", fontSize: "0.75rem" }}
>
{regeneratingMap ? (
<>
<Spinner size={14} />
<span style={{ marginLeft: "0.5rem" }}>Generando...</span>
</>
) : (
"🗺️ Regenerar Mapa"
)}
</Button>
<span
style={{
fontSize: "0.75rem",
color: "var(--color-text-muted)",
}}
>
Genera la imagen en disco sin guardar aún en la BD.
</span>
</div>
{mapNotice && (
<div
style={{
marginTop: "0.6rem",
fontSize: "0.8rem",
color:
mapNotice.type === "success"
? "var(--color-gold)"
: "var(--color-error)",
}}
>
{mapNotice.msg}
</div>
)}
</div>
</div>
<div
style={{
+389 -15
View File
@@ -1,14 +1,29 @@
import { useCallback, useEffect, useState } from "react";
import { fetchAdminRsvps, getExportCsvUrl } from "../api/client";
import {
deleteAdminRsvp,
fetchAdminRsvps,
getExportCsvUrl,
updateAdminRsvp,
} from "../api/client";
import { Button } from "../components/Button";
import { Spinner } from "../components/Spinner";
import { useConfig } from "../hooks/useConfig";
import type { RSVPAdminItem } from "../types/config";
export function RsvpTable() {
const { config } = useConfig();
const [rsvps, setRsvps] = useState<RSVPAdminItem[]>([]);
const [count, setCount] = useState<number>(0);
const [search, setSearch] = useState<string>("");
const [loading, setLoading] = useState<boolean>(true);
const [deletingId, setDeletingId] = useState<number | null>(null);
const [editingId, setEditingId] = useState<number | null>(null);
const [editForm, setEditForm] = useState<{ name: string; phone: string; email: string }>({
name: "",
phone: "",
email: "",
});
const [savingId, setSavingId] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const loadData = useCallback(async (searchTerm = "") => {
@@ -32,8 +47,14 @@ export function RsvpTable() {
function formatDate(isoStr: string) {
if (!isoStr) return "—";
try {
const d = new Date(isoStr);
// Ensure ISO string without an explicit offset is treated as UTC
const normalizedIso =
!isoStr.endsWith("Z") && !isoStr.includes("+") && !isoStr.includes("-", 10)
? `${isoStr}Z`
: isoStr;
const d = new Date(normalizedIso);
return d.toLocaleDateString("es-CO", {
timeZone: config?.event_timezone || "America/Bogota",
year: "numeric",
month: "short",
day: "numeric",
@@ -52,6 +73,71 @@ export function RsvpTable() {
return phone;
}
async function handleDelete(id: number, name: string) {
const confirmed = window.confirm(
`¿Estás seguro de que deseas eliminar la confirmación de "${name}"? Esta acción no se puede deshacer.`,
);
if (!confirmed) return;
setDeletingId(id);
setError(null);
try {
await deleteAdminRsvp(id);
setRsvps((prev) => prev.filter((r) => r.id !== id));
setCount((prev) => Math.max(0, prev - 1));
} catch (err) {
setError(
err instanceof Error ? err.message : "Error al eliminar el asistente.",
);
} finally {
setDeletingId(null);
}
}
function startEditing(row: RSVPAdminItem) {
setEditingId(row.id);
setEditForm({
name: row.name,
phone: row.phone,
email: row.email || "",
});
setError(null);
}
function cancelEditing() {
setEditingId(null);
setError(null);
}
async function handleSaveEdit(id: number) {
if (!editForm.name.trim()) {
setError("El nombre no puede estar vacío.");
return;
}
if (!editForm.phone.trim()) {
setError("El teléfono no puede estar vacío.");
return;
}
setSavingId(id);
setError(null);
try {
const updated = await updateAdminRsvp(id, {
name: editForm.name.trim(),
phone: editForm.phone.trim(),
email: editForm.email.trim() || null,
});
setRsvps((prev) => prev.map((r) => (r.id === id ? updated : r)));
setEditingId(null);
} catch (err) {
setError(
err instanceof Error ? err.message : "Error al actualizar el asistente.",
);
} finally {
setSavingId(null);
}
}
return (
<div>
{/* Top action bar: Count, Search, Export */}
@@ -164,19 +250,20 @@ export function RsvpTable() {
<th style={{ padding: "0.9rem 1.2rem" }}>Teléfono</th>
<th style={{ padding: "0.9rem 1.2rem" }}>Correo</th>
<th style={{ padding: "0.9rem 1.2rem" }}>Fecha de Registro</th>
<th style={{ padding: "0.9rem 1.2rem", textAlign: "right" }}>Acciones</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td colSpan={4} style={{ padding: "3rem", textAlign: "center" }}>
<td colSpan={5} style={{ padding: "3rem", textAlign: "center" }}>
<Spinner size={28} />
</td>
</tr>
) : rsvps.length === 0 ? (
<tr>
<td
colSpan={4}
colSpan={5}
style={{
padding: "3rem",
textAlign: "center",
@@ -194,36 +281,116 @@ export function RsvpTable() {
key={row.id}
style={{
borderBottom: "1px solid rgba(255, 255, 255, 0.06)",
backgroundColor:
editingId === row.id
? "rgba(212, 168, 67, 0.08)"
: "transparent",
transition: "background-color 0.15s ease",
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.04)";
if (editingId !== row.id) {
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.04)";
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "transparent";
if (editingId !== row.id) {
e.currentTarget.style.backgroundColor = "transparent";
}
}}
>
<td
style={{
padding: "0.9rem 1.2rem",
padding: editingId === row.id ? "0.5rem 0.8rem" : "0.9rem 1.2rem",
fontWeight: 500,
color: "#ffffff",
}}
>
{row.name}
</td>
<td
style={{ padding: "0.9rem 1.2rem", color: "var(--color-gold-light)" }}
>
{formatPhone(row.phone)}
{editingId === row.id ? (
<input
type="text"
value={editForm.name}
onChange={(e) =>
setEditForm((prev) => ({ ...prev, name: e.target.value }))
}
disabled={savingId === row.id}
placeholder="Nombre completo"
style={{
width: "100%",
minWidth: "120px",
backgroundColor: "rgba(0, 0, 0, 0.5)",
border: "1px solid var(--color-gold)",
borderRadius: "4px",
color: "#ffffff",
padding: "0.4rem 0.6rem",
fontSize: "0.85rem",
boxSizing: "border-box",
}}
/>
) : (
row.name
)}
</td>
<td
style={{
padding: "0.9rem 1.2rem",
padding: editingId === row.id ? "0.5rem 0.8rem" : "0.9rem 1.2rem",
color: "var(--color-gold-light)",
}}
>
{editingId === row.id ? (
<input
type="tel"
value={editForm.phone}
onChange={(e) =>
setEditForm((prev) => ({ ...prev, phone: e.target.value }))
}
disabled={savingId === row.id}
placeholder="300 123 4567"
style={{
width: "100%",
minWidth: "110px",
backgroundColor: "rgba(0, 0, 0, 0.5)",
border: "1px solid var(--color-gold)",
borderRadius: "4px",
color: "var(--color-gold-light)",
padding: "0.4rem 0.6rem",
fontSize: "0.85rem",
boxSizing: "border-box",
}}
/>
) : (
formatPhone(row.phone)
)}
</td>
<td
style={{
padding: editingId === row.id ? "0.5rem 0.8rem" : "0.9rem 1.2rem",
color: "rgba(255, 255, 255, 0.7)",
}}
>
{row.email || "—"}
{editingId === row.id ? (
<input
type="email"
value={editForm.email}
onChange={(e) =>
setEditForm((prev) => ({ ...prev, email: e.target.value }))
}
disabled={savingId === row.id}
placeholder="Opcional"
style={{
width: "100%",
minWidth: "120px",
backgroundColor: "rgba(0, 0, 0, 0.5)",
border: "1px solid var(--color-gold)",
borderRadius: "4px",
color: "rgba(255, 255, 255, 0.9)",
padding: "0.4rem 0.6rem",
fontSize: "0.85rem",
boxSizing: "border-box",
}}
/>
) : (
row.email || "—"
)}
</td>
<td
style={{
@@ -234,6 +401,212 @@ export function RsvpTable() {
>
{formatDate(row.created_at)}
</td>
<td style={{ padding: "0.9rem 1.2rem", textAlign: "right", whiteSpace: "nowrap" }}>
{editingId === row.id ? (
<div style={{ display: "inline-flex", alignItems: "center", gap: "0.4rem" }}>
<button
type="button"
disabled={savingId === row.id}
onClick={() => handleSaveEdit(row.id)}
style={{
background: "rgba(76, 175, 80, 0.15)",
border: "1px solid rgba(76, 175, 80, 0.4)",
borderRadius: "4px",
color: "#81c784",
padding: "0.45rem 0.65rem",
cursor: savingId === row.id ? "not-allowed" : "pointer",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
transition: "all 0.15s ease",
outline: "none",
}}
onMouseEnter={(e) => {
if (savingId !== row.id) {
e.currentTarget.style.backgroundColor = "rgba(76, 175, 80, 0.3)";
e.currentTarget.style.borderColor = "#81c784";
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "rgba(76, 175, 80, 0.15)";
e.currentTarget.style.borderColor = "rgba(76, 175, 80, 0.4)";
}}
title="Guardar cambios"
aria-label="Guardar cambios"
>
{savingId === row.id ? (
<Spinner size={14} />
) : (
<svg
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
role="img"
aria-label="Guardar"
>
<polyline points="20 6 9 17 4 12" />
</svg>
)}
</button>
<button
type="button"
disabled={savingId === row.id}
onClick={cancelEditing}
style={{
background: "rgba(255, 255, 255, 0.08)",
border: "1px solid rgba(255, 255, 255, 0.2)",
borderRadius: "4px",
color: "rgba(255, 255, 255, 0.7)",
padding: "0.45rem 0.65rem",
cursor: savingId === row.id ? "not-allowed" : "pointer",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
transition: "all 0.15s ease",
outline: "none",
}}
onMouseEnter={(e) => {
if (savingId !== row.id) {
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.18)";
e.currentTarget.style.color = "#ffffff";
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.08)";
e.currentTarget.style.color = "rgba(255, 255, 255, 0.7)";
}}
title="Cancelar edición"
aria-label="Cancelar edición"
>
<svg
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
role="img"
aria-label="Cancelar"
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</div>
) : (
<div style={{ display: "inline-flex", alignItems: "center", gap: "0.4rem" }}>
<button
type="button"
disabled={deletingId === row.id || editingId !== null}
onClick={() => startEditing(row)}
style={{
background: "rgba(212, 168, 67, 0.1)",
border: "1px solid rgba(212, 168, 67, 0.35)",
borderRadius: "4px",
color: "var(--color-gold)",
padding: "0.45rem 0.65rem",
cursor:
deletingId === row.id || editingId !== null ? "not-allowed" : "pointer",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
transition: "all 0.15s ease",
outline: "none",
opacity: editingId !== null && editingId !== row.id ? 0.35 : 1,
}}
onMouseEnter={(e) => {
if (deletingId !== row.id && editingId === null) {
e.currentTarget.style.backgroundColor = "rgba(212, 168, 67, 0.25)";
e.currentTarget.style.borderColor = "var(--color-gold-light)";
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "rgba(212, 168, 67, 0.1)";
e.currentTarget.style.borderColor = "rgba(212, 168, 67, 0.35)";
}}
title={`Editar confirmación de ${row.name}`}
aria-label={`Editar confirmación de ${row.name}`}
>
<svg
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
role="img"
aria-label="Editar"
>
<path d="M12 20h9" />
<path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
</svg>
</button>
<button
type="button"
disabled={deletingId === row.id || editingId !== null}
onClick={() => handleDelete(row.id, row.name)}
style={{
background: "rgba(255, 82, 82, 0.1)",
border: "1px solid rgba(255, 82, 82, 0.35)",
borderRadius: "4px",
color: "#ff5252",
padding: "0.45rem 0.65rem",
cursor:
deletingId === row.id || editingId !== null ? "not-allowed" : "pointer",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
transition: "all 0.15s ease",
outline: "none",
opacity: editingId !== null && editingId !== row.id ? 0.35 : 1,
}}
onMouseEnter={(e) => {
if (deletingId !== row.id && editingId === null) {
e.currentTarget.style.backgroundColor = "rgba(255, 82, 82, 0.25)";
e.currentTarget.style.borderColor = "#ff5252";
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "rgba(255, 82, 82, 0.1)";
e.currentTarget.style.borderColor = "rgba(255, 82, 82, 0.35)";
}}
title={`Eliminar confirmación de ${row.name}`}
aria-label={`Eliminar confirmación de ${row.name}`}
>
{deletingId === row.id ? (
<Spinner size={14} />
) : (
<svg
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
role="img"
aria-label="Eliminar"
>
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
<line x1="10" y1="11" x2="10" y2="17" />
<line x1="14" y1="11" x2="14" y2="17" />
</svg>
)}
</button>
</div>
)}
</td>
</tr>
))
)}
@@ -241,5 +614,6 @@ export function RsvpTable() {
</table>
</div>
</div>
);
}
+72
View File
@@ -1,8 +1,10 @@
import type {
InvitationConfig,
RSVPApiResult,
RSVPAdminItem,
RSVPListResponse,
RSVPRequest,
RSVPUpdateRequest,
} from "../types/config";
const BASE_API = "/birthday/api";
@@ -86,3 +88,73 @@ export async function updateAdminConfig(
export function getExportCsvUrl(): string {
return `${BASE_API}/admin/export`;
}
export interface GenerateMapPreviewResponse {
map_preview_url: string;
lat: number;
lng: number;
message: string;
}
export async function regenerateMapPreview(
mapUrl?: string,
): Promise<GenerateMapPreviewResponse> {
const res = await fetch(`${BASE_API}/admin/map-preview/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({ map_url: mapUrl }),
});
if (!res.ok) {
const errorJson = await res.json().catch(() => null);
const msg =
errorJson?.detail ||
(errorJson?.errors
? Object.values(errorJson.errors).join(", ")
: `HTTP ${res.status}`);
throw new Error(msg || "Error al regenerar vista previa del mapa.");
}
return res.json();
}
export async function deleteAdminRsvp(rsvpId: number): Promise<void> {
const res = await fetch(`${BASE_API}/admin/rsvps/${rsvpId}`, {
method: "DELETE",
headers: { Accept: "application/json" },
});
if (!res.ok && res.status !== 204) {
const errorJson = await res.json().catch(() => null);
const msg = errorJson?.detail || `HTTP ${res.status}`;
throw new Error(`Error al eliminar asistente: ${msg}`);
}
}
export async function updateAdminRsvp(
rsvpId: number,
data: RSVPUpdateRequest,
): Promise<RSVPAdminItem> {
const res = await fetch(`${BASE_API}/admin/rsvps/${rsvpId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(data),
});
if (!res.ok) {
const errorJson = await res.json().catch(() => null);
const msg =
errorJson?.detail ||
(errorJson?.errors
? Object.values(errorJson.errors).join(", ")
: `HTTP ${res.status}`);
throw new Error(msg || "Error al actualizar asistente.");
}
return res.json();
}
+24 -3
View File
@@ -1,4 +1,4 @@
import { useRef } from "react";
import { useRef, useState } from "react";
import { Button } from "../components/Button";
import { Spinner } from "../components/Spinner";
import { useConfig } from "../hooks/useConfig";
@@ -11,6 +11,7 @@ import { RsvpResult } from "./RsvpResult";
export function Invitation() {
const { config, status, error, reload } = useConfig();
const rsvpForm = useRsvpForm();
const [showDetailsOnly, setShowDetailsOnly] = useState(false);
const rsvpSectionRef = useRef<HTMLDivElement | null>(null);
function scrollToRsvp() {
@@ -112,7 +113,17 @@ export function Invitation() {
}}
>
{/* Section 1: Invitation Hero */}
<InvitationHero config={config} onCtaClick={scrollToRsvp} />
<InvitationHero
config={config}
onCtaClick={() => {
setShowDetailsOnly(false);
scrollToRsvp();
}}
onShowDetailsClick={() => {
setShowDetailsOnly(true);
scrollToRsvp();
}}
/>
{/* Section 2: RSVP / Confirmation Flow */}
<div
@@ -129,7 +140,16 @@ export function Invitation() {
position: "relative",
}}
>
{rsvpForm.formState === "idle" || rsvpForm.formState === "submitting" ? (
{showDetailsOnly ? (
<RsvpResult
formState="idle"
confirmedName=""
config={config}
onRetry={() => setShowDetailsOnly(false)}
isDetailsOnly={true}
onBackToForm={() => setShowDetailsOnly(false)}
/>
) : rsvpForm.formState === "idle" || rsvpForm.formState === "submitting" ? (
<RsvpForm
config={config}
name={rsvpForm.name}
@@ -141,6 +161,7 @@ export function Invitation() {
formState={rsvpForm.formState}
errors={rsvpForm.errors}
onSubmit={rsvpForm.submit}
onShowDetails={() => setShowDetailsOnly(true)}
/>
) : (
<RsvpResult
+45 -2
View File
@@ -4,9 +4,14 @@ import { RsvpCta } from "./RsvpCta";
interface InvitationHeroProps {
config: InvitationConfig;
onCtaClick: () => void;
onShowDetailsClick?: () => void;
}
export function InvitationHero({ config, onCtaClick }: InvitationHeroProps) {
export function InvitationHero({
config,
onCtaClick,
onShowDetailsClick,
}: InvitationHeroProps) {
// Parse date into Month, Day, and Day of Week
const [year, monthNum, dayNum] = config.event_date.split("-").map(Number);
const dateObj = new Date(year, (monthNum || 1) - 1, dayNum || 1);
@@ -167,8 +172,46 @@ export function InvitationHero({ config, onCtaClick }: InvitationHeroProps) {
</div>
{/* 4. RSVP Call to action */}
<div style={{ marginBottom: "1rem" }}>
<div
style={{
marginBottom: "1rem",
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: "0.8rem",
}}
>
<RsvpCta label={config.rsvp_cta} onClick={onCtaClick} />
{onShowDetailsClick && (
<button
type="button"
onClick={onShowDetailsClick}
style={{
background: "none",
border: "none",
color: "var(--color-text-muted)",
fontSize: "0.74rem",
letterSpacing: "0.14em",
textTransform: "uppercase",
cursor: "pointer",
padding: "0.3rem 0.6rem",
textDecoration: "underline",
textUnderlineOffset: "3px",
opacity: 0.8,
transition: "opacity 0.2s ease, color 0.2s ease",
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = "1";
e.currentTarget.style.color = "var(--color-gold)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.opacity = "0.8";
e.currentTarget.style.color = "var(--color-text-muted)";
}}
>
¿Ya confirmaste? Ver ubicación y mapa
</button>
)}
</div>
</section>
);
+36
View File
@@ -16,6 +16,7 @@ interface RsvpFormProps {
formState: RsvpFormState;
errors: FormErrors;
onSubmit: () => void;
onShowDetails?: () => void;
}
export function RsvpForm({
@@ -29,6 +30,7 @@ export function RsvpForm({
formState,
errors,
onSubmit,
onShowDetails,
}: RsvpFormProps) {
const isSubmitting = formState === "submitting";
@@ -107,6 +109,40 @@ export function RsvpForm({
config.submit_label || "TE VEO AHÍ"
)}
</Button>
{onShowDetails && (
<div style={{ marginTop: "1.4rem" }}>
<button
type="button"
onClick={onShowDetails}
style={{
background: "none",
border: "none",
color: "var(--color-gold)",
fontSize: "0.78rem",
letterSpacing: "0.14em",
textTransform: "uppercase",
cursor: "pointer",
padding: "0.4rem 0.8rem",
borderRadius: "4px",
textDecoration: "underline",
textUnderlineOffset: "4px",
opacity: 0.85,
transition: "opacity 0.2s ease, color 0.2s ease",
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = "1";
e.currentTarget.style.color = "var(--color-gold-light)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.opacity = "0.85";
e.currentTarget.style.color = "var(--color-gold)";
}}
>
¿Ya confirmaste? Ver ubicación y mapa ↓
</button>
</div>
)}
</div>
</form>
);
+137 -10
View File
@@ -11,6 +11,8 @@ interface RsvpResultProps {
confirmedName: string;
config: InvitationConfig;
onRetry: () => void;
isDetailsOnly?: boolean;
onBackToForm?: () => void;
}
export function RsvpResult({
@@ -18,6 +20,8 @@ export function RsvpResult({
confirmedName,
config,
onRetry,
isDetailsOnly = false,
onBackToForm,
}: RsvpResultProps) {
const countdown = useCountdown(
config.event_date,
@@ -25,14 +29,108 @@ export function RsvpResult({
config.event_timezone,
);
if (isDetailsOnly) {
return (
<div
style={{
width: "100%",
maxWidth: "440px",
margin: "0 auto",
padding: "1.5rem 1.5rem 3.5rem 1.5rem",
textAlign: "center",
}}
aria-live="polite"
>
<h3
style={{
fontFamily: "var(--font-display)",
fontSize: "clamp(2.8rem, 9vw, 3.6rem)",
fontWeight: 400,
color: "var(--color-gold-light)",
lineHeight: 1.15,
marginBottom: "0.4rem",
textShadow: "0 2px 20px rgba(212, 168, 67, 0.4)",
}}
>
Ubicación del Evento
</h3>
<p
style={{
fontSize: "0.85rem",
fontWeight: 600,
letterSpacing: "0.18em",
color: "var(--color-gold)",
textTransform: "uppercase",
marginBottom: "1.5rem",
}}
>
{config.address_name}
</p>
{/* Live Countdown */}
<Countdown
days={countdown.days}
hours={countdown.hours}
minutes={countdown.minutes}
seconds={countdown.seconds}
state={countdown.state}
label={config.countdown_label}
inProgressLabel={config.countdown_in_progress}
finishedLabel={config.countdown_finished}
/>
{/* Decorative divider dot */}
<div
style={{
display: "flex",
justifyContent: "center",
gap: "0.4rem",
margin: "1.5rem 0",
color: "var(--color-gold)",
opacity: 0.5,
fontSize: "1.2rem",
}}
aria-hidden="true"
>
<span>·</span>
<span>·</span>
<span>·</span>
</div>
{/* Circular Map Preview and Venue Logistics */}
<MapPreview
previewUrl={config.map_preview_url}
mapUrl={config.map_url}
venueName={config.address_name}
/>
<VenueInfo venueName={config.address_name} addressLines={config.address_lines} />
{onBackToForm && (
<div style={{ marginTop: "2.5rem" }}>
<Button
type="button"
variant="outline"
onClick={onBackToForm}
style={{ fontSize: "0.75rem", padding: "0.6rem 1.4rem" }}
>
« VOLVER AL FORMULARIO DE ASISTENCIA
</Button>
</div>
)}
</div>
);
}
if (formState === "duplicate") {
return (
<div
style={{
width: "100%",
maxWidth: "420px",
maxWidth: "440px",
margin: "0 auto",
padding: "2.5rem 1.5rem",
padding: "1.5rem 1.5rem 3.5rem 1.5rem",
textAlign: "center",
}}
role="alert"
@@ -40,29 +138,58 @@ export function RsvpResult({
<h3
style={{
fontFamily: "var(--font-display)",
fontSize: "3.2rem",
fontSize: "clamp(2.8rem, 9vw, 3.6rem)",
fontWeight: 400,
color: "var(--color-gold-light)",
marginBottom: "1rem",
marginBottom: "0.8rem",
textShadow: "0 2px 14px rgba(212, 168, 67, 0.3)",
}}
>
¡Ups!
¡Ya estás registrado!
</h3>
<p
style={{
fontSize: "0.92rem",
lineHeight: 1.7,
color: "var(--color-text-muted)",
marginBottom: "2rem",
marginBottom: "1.8rem",
}}
>
{config.msg_duplicate ||
"Parece que ya tenemos tus datos registrados. Si necesitas modificar tu información, ponte en contacto con nosotros."}
"Parece que ya tenemos tus datos registrados. ¡Te esperamos!"}
</p>
<Button variant="outline" onClick={onRetry}>
VOLVER AL FORMULARIO
</Button>
{/* Live Countdown */}
<Countdown
days={countdown.days}
hours={countdown.hours}
minutes={countdown.minutes}
seconds={countdown.seconds}
state={countdown.state}
label={config.countdown_label}
inProgressLabel={config.countdown_in_progress}
finishedLabel={config.countdown_finished}
/>
{/* Circular Map Preview and Venue Logistics */}
<MapPreview
previewUrl={config.map_preview_url}
mapUrl={config.map_url}
venueName={config.address_name}
/>
<VenueInfo venueName={config.address_name} addressLines={config.address_lines} />
<div style={{ marginTop: "2rem" }}>
<Button
type="button"
variant="outline"
onClick={onRetry}
style={{ fontSize: "0.75rem", padding: "0.6rem 1.4rem" }}
>
VOLVER AL FORMULARIO
</Button>
</div>
</div>
);
}
+7
View File
@@ -30,6 +30,13 @@ export interface RSVPRequest {
email?: string | null;
}
export interface RSVPUpdateRequest {
name?: string;
phone?: string;
email?: string | null;
}
export type RSVPApiResult =
| { result: "SUCCESS"; name: string }
| { result: "DUPLICATE" }
+31 -1
View File
@@ -131,12 +131,14 @@ flowchart LR
subgraph Public
A["GET /birthday/api/config"]
B["POST /birthday/api/rsvp"]
G["GET /birthday/api/map-preview.png"]
end
subgraph Admin["Admin (Remote-User required)"]
C["GET /birthday/api/admin/rsvps"]
D["GET /birthday/api/admin/export"]
E["GET /birthday/api/admin/config"]
F["PUT /birthday/api/admin/config"]
H["POST /birthday/api/admin/map-preview/generate"]
end
```
@@ -150,6 +152,14 @@ Serves the invitation configuration to the guest frontend.
- **Response `200`:** Full `InvitationConfig` object — all fields from the config table.
- **Response `500`:** `{"result": "ERROR"}` (if no config row exists — should not happen after seeding)
#### `GET /birthday/api/map-preview.png`
Serves the locally generated OpenStreetMap static crop image centered on the event venue.
- **Auth:** None (public)
- **Response `200`:** `image/png` static file with caching headers (`Cache-Control: public, max-age=300`).
- **Fallback:** 307 Redirect to default OSM tile if the image file has not yet been generated.
#### `POST /birthday/api/rsvp`
Submit an RSVP.
@@ -245,8 +255,28 @@ Update configuration (full object replacement).
- `event_date` is a valid ISO 8601 date
- `event_time` is a valid `HH:MM` (24-hour) string
- `event_timezone` is a valid IANA timezone identifier
- URL fields are valid URLs
- `map_url` is a valid Google Maps URL format (`maps.app.goo.gl`, `goo.gl`, or `google.com/maps`)
- Text fields are non-empty where required
- **Conditional Map Regeneration:**
- If `map_url` changed compared to the stored singleton, the backend automatically resolves destination coordinates, generates a fresh OpenStreetMap stitched preview PNG on disk, and points `map_preview_url` to `/birthday/api/map-preview.png`.
- If `map_url` did not change, no external network calls or image generation occur.
#### `POST /birthday/api/admin/map-preview/generate`
Regenerates the venue map preview image on disk without requiring full configuration updates or database writes.
- **Request body:** Optional JSON `{"map_url": "..."}`. If omitted, uses the currently persisted `map_url`.
- **Response `200`:**
```json
{
"map_preview_url": "/birthday/api/map-preview.png?t=1759338600",
"lat": 34.1432,
"lng": -118.2551,
"message": "Vista previa del mapa generada con éxito."
}
```
- **Error `422`:** If the provided URL cannot be parsed into valid geographic coordinates.
- **Side Effect:** Writes `data/map_preview.png` directly to disk, cache-busting via the returned timestamp.
---
+3 -3
View File
@@ -82,13 +82,13 @@ Catches all `/birthday/*` traffic that does not match a higher-priority router.
| Property | Value |
|---|---|
| Rule | ``Host(`demos.roadtotech.me`) && PathPrefix(`/birthday/admin`)`` |
| Rule | ``Host(`demos.roadtotech.me`) && (PathPrefix(`/birthday/admin`) || PathPrefix(`/birthday/api/admin`))`` |
| Entrypoint | `websecure` (port 443) |
| TLS | Enabled |
| Middleware | `authelia-auth@docker` (ForwardAuth) |
| Priority | 20 |
Higher priority ensures `/birthday/admin/*` requests are intercepted before the generic public router.
Higher priority ensures `/birthday/admin/*` and `/birthday/api/admin/*` requests are intercepted before the generic public router.
### 4.3 HTTP Redirect Router — `bdinvite-red`
@@ -160,7 +160,7 @@ services:
- "traefik.http.routers.bdinvite-public.service=bdinvite-svc"
# Admin router (Authelia-protected)
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday/admin`)"
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && (PathPrefix(`/birthday/admin`) || PathPrefix(`/birthday/api/admin`))"
- "traefik.http.routers.bdinvite-admin.entrypoints=websecure"
- "traefik.http.routers.bdinvite-admin.tls=true"
- "traefik.http.routers.bdinvite-admin.priority=20"