patx/projectpay

update logo;

Commit ca5e931 · patx · Jul 30 at 11:20PM

Changeset
ca5e931292d601a73b02bb155b9943ab4d02c6cb
Parents
b2f4e95fdd6bb4fa05bf2b062fb7cbf6c1dc9857

View source at this commit

Comments

No comments yet.

Log in to comment

Diff

diff --git a/README.md b/README.md
index b79a162..71b8a48 100644
--- a/README.md
+++ b/README.md
@@ -51,9 +51,6 @@ ProjectPay is a small web app for creating project payment pages and collecting
    MONGODB_URI=mongodb://localhost:27017
    MONGODB_DB=projectpay
    APP_BASE_URL=http://127.0.0.1:8000
-   PUBLIC_LOGO_URL=
-   PUBLIC_DARK_LOGO_URL=
-   PUBLIC_LOGO_ALT=ProjectPay Logo
    PUBLIC_APP_ICON_URL=https://gitman.io/patx/afterdarklabs/raw/docs/favicon.png
 
    STRIPE_SECRET_KEY=
@@ -78,9 +75,6 @@ ProjectPay is a small web app for creating project payment pages and collecting
 | `APP_ENV` | Required | unset | Set to `development` locally and `production` for deployed environments. Startup fails if this is missing or unrecognized. |
 | `ADMIN_PASSWORD` | Required outside development | `admin` in development only | Password for the admin dashboard. Production startup fails if this is missing or set to `admin`. |
 | `APP_BASE_URL` | Required outside development | Derived from request headers in development only | Public base URL used to generate customer payment links and Stripe return URLs. |
-| `PUBLIC_LOGO_URL` | Optional | unset | Logo image URL shown on public project payment pages. No logo is shown when this is empty. |
-| `PUBLIC_DARK_LOGO_URL` | Optional | `PUBLIC_LOGO_URL` | Dark-mode logo image URL shown on public project payment pages. When empty, the normal logo is used. |
-| `PUBLIC_LOGO_ALT` | Optional | `ProjectPay Logo` | Alt text for the public payment page logo. |
 | `PUBLIC_APP_ICON_URL` | Optional | `https://gitman.io/patx/afterdarklabs/raw/docs/favicon.png` | PNG icon URL used by the web app manifest. |
 | `MONGODB_URI` | Optional | `mongodb://localhost:27017` | MongoDB connection string. |
 | `MONGODB_DB` | Optional | `invoice_maker` | MongoDB database name. Use `projectpay` or another explicit name for new installs. |
@@ -169,7 +163,7 @@ On Heroku dynos, login rate limiting uses the final `X-Forwarded-For` value adde
 
 ## Customization
 
-- Set `PUBLIC_LOGO_URL`, `PUBLIC_DARK_LOGO_URL`, and `PUBLIC_LOGO_ALT` to brand the public payment page.
+- The public payment page uses the After Dark Labs lockup from `https://afterdarklabs.io/logo_assets/lockup.svg`.
 - Set `PUBLIC_APP_ICON_URL` to change the icon used by `/manifest.json`.
 - Update styles in `templates/base.html`.
 - The current default database name is `invoice_maker`; set `MONGODB_DB=projectpay` for a fresh ProjectPay deployment.
@@ -180,6 +174,7 @@ On Heroku dynos, login rate limiting uses the final `X-Forwarded-For` value adde
 ProjectPay creates and manages these MongoDB collections:
 
 - `projects`
+- `deleted_projects`
 - `payments`
 - `checkout_sessions`
 - `webhook_events`
@@ -187,7 +182,7 @@ ProjectPay creates and manages these MongoDB collections:
 - `sessions`
 - `login_attempts`
 
-Indexes are created automatically when the app first touches the database.
+Indexes are created automatically when the app first touches the database. Deleting a project archives it into `deleted_projects` and keeps its payment records, so payment history survives for disputes and bookkeeping. Project numbers restart at `0001` each calendar year.
 
 ## Security Notes
 
@@ -195,7 +190,9 @@ Indexes are created automatically when the app first touches the database.
 - Do not deploy with `APP_ENV=development`.
 - Do not deploy with the default `ADMIN_PASSWORD=admin`.
 - Admin sessions are server-side and stored in MongoDB behind MicroPie's opaque `session_id` cookie.
-- Browser POST forms use CSRF tokens stored in the server-side session.
+- Admin POST forms use CSRF tokens stored in the server-side session; logout requires a CSRF-protected POST.
+- Every response carries security headers, including a Content-Security-Policy with `frame-ancestors 'none'`, `X-Frame-Options`, `X-Content-Type-Options`, and `Referrer-Policy`.
+- Public payment pages do not create sessions; the random share token in the URL is what authorizes starting a checkout.
 - Login attempts are rate-limited by client IP.
 - Project search treats search text as a literal string before sending it to MongoDB regex queries.
 - Stripe webhook storage keeps minimized event summaries instead of full raw event payloads.
diff --git a/app.py b/app.py
index 3fcdffe..0b367ab 100644
--- a/app.py
+++ b/app.py
@@ -1,6 +1,7 @@
 import asyncio
 import hmac
 import json
+import logging
 import os
 import re
 import secrets
@@ -16,9 +17,11 @@ from markupsafe import Markup, escape
 from pymongo import AsyncMongoClient, ReturnDocument
 from pymongo.errors import DuplicateKeyError
 
-from micropie import App, SESSION_TIMEOUT, SessionBackend
+from micropie import App, HttpMiddleware, SESSION_TIMEOUT, SessionBackend
 
 
+logger = logging.getLogger("projectpay")
+
 PAGE_SIZE = 20
 CSRF_SESSION_KEY = "csrf_token"
 SESSION_COOKIE = "session_id"
@@ -30,6 +33,22 @@ SUCCESSFUL_CHECKOUT_EVENTS = {
     "checkout.session.completed",
     "checkout.session.async_payment_succeeded",
 }
+SECURITY_HEADERS = [
+    ("X-Frame-Options", "DENY"),
+    ("X-Content-Type-Options", "nosniff"),
+    ("Referrer-Policy", "strict-origin-when-cross-origin"),
+    (
+        "Content-Security-Policy",
+        "default-src 'self'; "
+        "script-src 'self' 'unsafe-inline'; "
+        "style-src 'self' 'unsafe-inline'; "
+        "img-src 'self' https: data:; "
+        "connect-src 'self'; "
+        "frame-ancestors 'none'; "
+        "form-action 'self' https://checkout.stripe.com; "
+        "base-uri 'self'",
+    ),
+]
 
 
 def load_dotenv(path: str = ".env") -> None:
@@ -51,6 +70,31 @@ def now_utc() -> datetime:
     return datetime.now(timezone.utc)
 
 
+def constant_time_equals(expected: str, actual: str) -> bool:
+    try:
+        return hmac.compare_digest(
+            expected.encode("utf-8"),
+            actual.encode("utf-8"),
+        )
+    except (AttributeError, UnicodeError):
+        return False
+
+
+def parse_page(value: Any) -> int:
+    try:
+        page = int(value)
+    except (TypeError, ValueError):
+        return 1
+    return max(page, 1)
+
+
+def project_search_text(project: Dict[str, Any]) -> str:
+    return " ".join(
+        str(project.get(field) or "")
+        for field in ("project_number", "customer_name", "status")
+    ).lower()
+
+
 def parse_money_to_cents(value: str) -> Optional[int]:
     if value is None:
         return None
@@ -117,6 +161,26 @@ def as_plain_dict(value: Any) -> Dict[str, Any]:
     return {}
 
 
+class SecurityHeadersMiddleware(HttpMiddleware):
+    async def before_request(self, request) -> Optional[Dict]:
+        return None
+
+    async def after_request(
+        self,
+        request,
+        status_code: int,
+        response_body: Any,
+        extra_headers: List[Tuple[str, str]],
+    ) -> Optional[Dict]:
+        existing = {name.lower() for name, _ in extra_headers}
+        extra_headers.extend(
+            (name, value)
+            for name, value in SECURITY_HEADERS
+            if name.lower() not in existing
+        )
+        return None
+
+
 class MongoSessionBackend(SessionBackend):
     def __init__(self, client: AsyncMongoClient, db_name: str) -> None:
         self.client = client
@@ -201,11 +265,6 @@ class InvoiceApp(App):
             os.getenv("LOGIN_RATE_LIMIT_WINDOW_SECONDS", "900") or "900"
         )
         self._validate_config()
-        self.public_logo_url = os.getenv("PUBLIC_LOGO_URL", "").strip()
-        self.public_dark_logo_url = (
-            os.getenv("PUBLIC_DARK_LOGO_URL", "").strip() or self.public_logo_url
-        )
-        self.public_logo_alt = os.getenv("PUBLIC_LOGO_ALT", "ProjectPay Logo").strip()
         self.public_app_icon_url = (
             os.getenv("PUBLIC_APP_ICON_URL", "").strip() or DEFAULT_APP_ICON_URL
         )
@@ -222,6 +281,7 @@ class InvoiceApp(App):
             self.stripe_http_client = stripe.HTTPXClient()
             stripe.default_http_client = self.stripe_http_client
 
+        self.middlewares.append(SecurityHeadersMiddleware())
         self.shutdown_handlers.append(self._shutdown_clients)
 
         if self.env is not None:
@@ -281,6 +341,26 @@ class InvoiceApp(App):
             await db.login_attempts.create_index(
                 "expires_at", expireAfterSeconds=0
             )
+            await db.projects.update_many(
+                {"search_text": {"$exists": False}},
+                [
+                    {
+                        "$set": {
+                            "search_text": {
+                                "$toLower": {
+                                    "$concat": [
+                                        {"$ifNull": ["$project_number", ""]},
+                                        " ",
+                                        {"$ifNull": ["$customer_name", ""]},
+                                        " ",
+                                        {"$ifNull": ["$status", ""]},
+                                    ]
+                                }
+                            }
+                        }
+                    }
+                ],
+            )
             self._indexes_ready = True
 
     async def _shutdown_clients(self) -> None:
@@ -328,7 +408,7 @@ class InvoiceApp(App):
             send,
             status,
             json.dumps(body),
-            [("Content-Type", "application/json")],
+            [("Content-Type", "application/json"), *SECURITY_HEADERS],
         )
 
     def _manifest(self) -> Dict[str, Any]:
@@ -355,7 +435,7 @@ class InvoiceApp(App):
             send,
             200,
             json.dumps(self._manifest()),
-            [("Content-Type", "application/manifest+json")],
+            [("Content-Type", "application/manifest+json"), *SECURITY_HEADERS],
         )
 
     async def _handle_stripe_webhook(
@@ -691,13 +771,7 @@ class InvoiceApp(App):
         actual = self.request.form("csrf_token", "")
         if not isinstance(expected, str) or not isinstance(actual, str) or not expected:
             return False
-        try:
-            return hmac.compare_digest(
-                expected.encode("utf-8"),
-                actual.encode("utf-8"),
-            )
-        except (TypeError, UnicodeError):
-            return False
+        return constant_time_equals(expected, actual)
 
     def _csrf_error(self) -> Tuple[int, str]:
         return 403, "Invalid CSRF token"
@@ -800,14 +874,26 @@ class InvoiceApp(App):
         return f"{self._base_url()}/p/{project['share_token']}"
 
     async def _next_project_number(self) -> str:
+        year = now_utc().year
+        counter_id = f"project_number_{year}"
         db = await self._db()
+        # Installs older than the per-year counters used a single global
+        # counter; seed this year's counter from it so numbers don't collide.
+        legacy = await db.counters.find_one({"_id": "project_number"})
+        if legacy:
+            await db.counters.update_one(
+                {"_id": counter_id},
+                {"$setOnInsert": {"value": int(legacy["value"])}},
+                upsert=True,
+            )
+            await db.counters.delete_one({"_id": "project_number"})
         counter = await db.counters.find_one_and_update(
-            {"_id": "project_number"},
+            {"_id": counter_id},
             {"$inc": {"value": 1}},
             upsert=True,
             return_document=ReturnDocument.AFTER,
         )
-        return f"PRJ-{now_utc().year}-{int(counter['value']):04d}"
+        return f"PRJ-{year}-{int(counter['value']):04d}"
 
     def _project_total(self, project: Dict[str, Any]) -> int:
         return sum(int(item.get("amount_cents", 0)) for item in project.get("line_items", []))
@@ -842,11 +928,8 @@ class InvoiceApp(App):
         query: Dict[str, Any] = {}
         q = (q or "").strip()
         if q:
-            pattern = re.escape(q)
             clauses: List[Dict[str, Any]] = [
-                {"project_number": {"$regex": pattern, "$options": "i"}},
-                {"status": {"$regex": pattern, "$options": "i"}},
-                {"customer_name": {"$regex": pattern, "$options": "i"}},
+                {"search_text": {"$regex": re.escape(q.lower())}},
             ]
             oid = object_id(q)
             if oid is not None:
@@ -937,22 +1020,28 @@ class InvoiceApp(App):
         status = "paid" if total > 0 and paid >= total else "open"
         await db.projects.update_one(
             {"_id": project_id},
-            {"$set": {"status": status, "updated_at": now_utc()}},
+            {
+                "$set": {
+                    "status": status,
+                    "search_text": project_search_text({**project, "status": status}),
+                    "updated_at": now_utc(),
+                }
+            },
         )
 
     async def _render(self, template: str, **kwargs: Any) -> str:
         kwargs.setdefault("admin", self._is_admin())
-        kwargs.setdefault("csrf_token", self._csrf_token())
+        # Minting a CSRF token writes a session doc, so public pages pass
+        # csrf_token themselves to keep anonymous visits session-free.
+        if "csrf_token" not in kwargs:
+            kwargs["csrf_token"] = self._csrf_token()
         kwargs.setdefault("currency", self.currency)
-        kwargs.setdefault("public_logo_url", self.public_logo_url)
-        kwargs.setdefault("public_dark_logo_url", self.public_dark_logo_url)
-        kwargs.setdefault("public_logo_alt", self.public_logo_alt)
         return await self._render_template(template, **kwargs)
 
     async def index(self) -> Any:
         if redirect := self._require_admin():
             return redirect
-        page = int(self.request.query("page", "1") or "1")
+        page = parse_page(self.request.query("page", "1"))
         q = self.request.query("q", "") or ""
         projects, has_more = await self._find_projects(q, page)
         return await self._render(
@@ -966,7 +1055,7 @@ class InvoiceApp(App):
     async def projects_page(self) -> Any:
         if redirect := self._require_admin():
             return redirect
-        page = int(self.request.query("page", "1") or "1")
+        page = parse_page(self.request.query("page", "1"))
         q = self.request.query("q", "") or ""
         projects, has_more = await self._find_projects(q, page)
         return await self._render(
@@ -987,7 +1076,7 @@ class InvoiceApp(App):
                 )
                 return 429, body
             password = self.request.form("password", "") or ""
-            if hmac.compare_digest(password, self.admin_password):
+            if constant_time_equals(password, self.admin_password):
                 await self._clear_failed_logins()
                 return await self._start_admin_session()
             await self._record_failed_login()
@@ -998,6 +1087,10 @@ class InvoiceApp(App):
         return await self._render("login.html")
 
     def logout(self) -> Any:
+        if self.request.method != "POST":
+            return self._redirect("/")
+        if not self._valid_csrf():
+            return self._csrf_error()
         self.request.session.clear()
         return self._redirect(
             "/login",
@@ -1041,6 +1134,7 @@ class InvoiceApp(App):
             "created_at": now,
             "updated_at": now,
         }
+        project_doc["search_text"] = project_search_text(project_doc)
         db = await self._db()
         result = await db.projects.insert_one(project_doc)
         return self._redirect(f"/project/{result.inserted_id}")
@@ -1112,19 +1206,10 @@ class InvoiceApp(App):
         if self.request.method != "POST":
             return self._redirect(f"/project/{project_id}")
 
-        payment_docs = await db.payments.find(
-            {"project_id": project["_id"], "webhook_id": {"$exists": True}},
-            {"webhook_id": 1},
-        ).to_list(length=None)
-        payment_webhook_ids = [
-            payment["webhook_id"] for payment in payment_docs if payment.get("webhook_id")
-        ]
-        if payment_webhook_ids:
-            await db.webhook_events.delete_many(
-                {"webhook_id": {"$in": payment_webhook_ids}}
-            )
-        await db.checkout_sessions.delete_many({"project_id": project["_id"]})
-        await db.payments.delete_many({"project_id": project["_id"]})
+        # Archive instead of hard-deleting so payment records stay available
+        # for disputes, chargebacks, and bookkeeping.
+        project["deleted_at"] = now_utc()
+        await db.deleted_projects.insert_one(project)
         await db.projects.delete_one({"_id": project["_id"]})
         return self._redirect("/")
 
@@ -1139,6 +1224,7 @@ class InvoiceApp(App):
             "public_project.html",
             project=summary,
             checkout_state=checkout_state,
+            csrf_token="",
         )
 
     async def pay(self, share_token: str) -> Any:
@@ -1150,20 +1236,22 @@ class InvoiceApp(App):
 
         if self.request.method != "POST":
             return self._redirect(f"/p/{share_token}")
-        if not self._valid_csrf():
-            return self._csrf_error()
 
         if summary["balance_cents"] <= 0:
             return self._redirect(f"/p/{share_token}")
 
         try:
             checkout = await self._create_checkout_session(project)
-        except Exception as exc:
+        except Exception:
+            logger.exception(
+                "Failed to create checkout session for project %s", project["_id"]
+            )
             return await self._render(
                 "public_project.html",
                 project=summary,
-                error=str(exc),
+                error="We couldn't start checkout. Please try again in a moment.",
                 checkout_state="",
+                csrf_token="",
             )
 
         checkout_doc = {
diff --git a/page.out b/page.out
new file mode 100644
index 0000000..b7be9b1
--- /dev/null
+++ b/page.out
@@ -0,0 +1,571 @@
+<!doctype html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
+    <link rel="manifest" href="/manifest.json">
+    <title>PRJ-2026-0001</title>
+    <style>
+      * { box-sizing: border-box; }
+      [hidden] { display: none !important; }
+      html {
+        max-width: 100%;
+        overflow-x: hidden;
+        touch-action: manipulation;
+        -webkit-text-size-adjust: 100%;
+      }
+      :root {
+        color-scheme: light;
+        --page-bg: #f7f7f7;
+        --surface-bg: #fff;
+        --surface-subtle: #fafafa;
+        --field-bg: #fff;
+        --text-color: #1f2933;
+        --muted-color: #697586;
+        --border-color: #cfd6dd;
+        --border-subtle: #eceff3;
+        --primary-color: #176b5b;
+        --primary-hover-color: #13584c;
+        --primary-contrast: #fff;
+        --danger-color: #b42318;
+        --danger-bg: #fff0ee;
+        --danger-border: #efb5ad;
+        --warning-color: #8a5a00;
+        --warning-bg: #fff8e8;
+        --success-color: #166534;
+        --success-bg: #eaf7ef;
+        --info-color: #164c7d;
+        --info-bg: #edf5ff;
+        --sticky-bg: rgba(247, 247, 247, .96);
+        --shadow-color: rgba(31, 41, 51, .22);
+      }
+      @media (prefers-color-scheme: dark) {
+        :root {
+          color-scheme: dark;
+          --page-bg: #0f1720;
+          --surface-bg: #17212b;
+          --surface-subtle: #1f2a36;
+          --field-bg: #101923;
+          --text-color: #e6edf3;
+          --muted-color: #a8b3c2;
+          --border-color: #344454;
+          --border-subtle: #2a3745;
+          --primary-color: #1f7a6d;
+          --primary-hover-color: #279382;
+          --primary-contrast: #fff;
+          --danger-color: #ffb4aa;
+          --danger-bg: #3b1715;
+          --danger-border: #71332d;
+          --warning-color: #ffd47a;
+          --warning-bg: #36270c;
+          --success-color: #8ee3a6;
+          --success-bg: #12301f;
+          --info-color: #9bd2ff;
+          --info-bg: #132c45;
+          --sticky-bg: rgba(15, 23, 32, .96);
+          --shadow-color: rgba(0, 0, 0, .35);
+        }
+      }
+      body {
+        margin: 0;
+        max-width: 100%;
+        overflow-x: hidden;
+        background: var(--page-bg);
+        color: var(--text-color);
+        font: 15px/1.45 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+      }
+      a { color: inherit; }
+      h1, h2, p { margin-top: 0; }
+      h1 { font-size: 26px; margin-bottom: 4px; }
+      h2 { font-size: 18px; margin: 0 0 12px; }
+      table { width: 100%; border-collapse: collapse; }
+      th, td { padding: 20px 0; text-align: left; vertical-align: top; }
+      th { color: var(--muted-color); font-size: 13px; }
+      input, textarea {
+        width: 100%;
+        border: 1px solid var(--border-color);
+        border-radius: 6px;
+        background: var(--field-bg);
+        color: var(--text-color);
+        padding: 10px;
+        font: inherit;
+      }
+      label { display: block; font-weight: 650; margin-bottom: 6px; }
+      button, .button {
+        display: inline-flex;
+        align-items: center;
+        justify-content: center;
+        min-height: 38px;
+        border: 1px solid var(--primary-color);
+        border-radius: 6px;
+        background: var(--primary-color);
+        color: var(--primary-contrast);
+        padding: 8px 12px;
+        font: inherit;
+        font-weight: 650;
+        text-decoration: none;
+        cursor: pointer;
+      }
+      img, svg, video, canvas { max-width: 100%; }
+      .secondary { background: var(--surface-bg); border-color: var(--border-color); color: var(--text-color); }
+      .danger { background: var(--surface-bg); border-color: var(--danger-border); color: var(--danger-color); }
+      .topbar {
+        max-width: 100%;
+        overflow-x: hidden;
+        background: var(--surface-bg);
+      }
+      .topbar-inner, .page {
+        width: 100%;
+        max-width: 1080px;
+        margin: 0 auto;
+        padding: 16px 20px;
+      }
+      .topbar-inner, .header-row, .nav, .searchbar {
+        display: flex;
+        align-items: center;
+        gap: 10px;
+      }
+      .topbar-inner, .header-row { justify-content: space-between; }
+      .brand { font-weight: 750; text-decoration: none; }
+      .public-logo {
+        margin: 0 0 18px;
+        text-align: center;
+      }
+      .public-logo img {
+        display: inline-block;
+        max-width: min(350px, 100%);
+        height: auto;
+      }
+      .title-line {
+        display: flex;
+        align-items: center;
+        gap: 10px;
+      }
+      .back-link {
+        color: var(--muted-color);
+        font-size: 24px;
+        line-height: 1;
+        text-decoration: none;
+      }
+      .page { padding-top: 28px; padding-bottom: 48px; }
+      .narrow { max-width: 680px; }
+      .section {
+        background: var(--surface-bg);
+        border-radius: 8px;
+        padding: 18px;
+        margin-bottom: 16px;
+      }
+      .muted, .footer-note { color: var(--muted-color); }
+      .field { margin-bottom: 14px; }
+      .prewrap { white-space: pre-wrap; }
+      .star-emphasis { font-size: calc(1em + 1px); font-weight: 700; }
+      .inline { display: inline; }
+      .nav .inline { display: flex; }
+      .grid-2, .stats {
+        display: grid;
+        gap: 12px;
+      }
+      .grid-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+      .stats { grid-template-columns: repeat(3, minmax(0, 1fr)); margin: 16px 0; }
+      .stat { border-radius: 8px; padding: 12px; }
+      .stat span { display: block; color: var(--muted-color); font-size: 13px; }
+      .stat strong { font-size: 19px; }
+      .alert { border: 1px solid transparent; border-radius: 8px; padding: 10px 12px; margin-bottom: 14px; }
+      .alert.error { border-color: var(--danger-border); color: var(--danger-color); background: var(--danger-bg); }
+      .alert.info { color: var(--warning-color); background: var(--warning-bg); }
+      .alert.ok { color: var(--success-color); background: var(--success-bg); }
+      .status {
+        border-radius: 999px;
+        background: var(--info-bg);
+        color: var(--info-color);
+        padding: 3px 9px;
+        font-size: 13px;
+        font-weight: 700;
+        text-transform: capitalize;
+      }
+      .status.paid,
+      .status.succeeded { background: var(--success-bg); color: var(--success-color); }
+      .status.processing,
+      .status.pending { background: var(--warning-bg); color: var(--warning-color); }
+      .status.failed,
+      .status.canceled { background: var(--danger-bg); color: var(--danger-color); }
+      .project-list {
+        display: grid;
+        gap: 12px;
+      }
+      .project-card {
+        background: var(--surface-bg);
+        border-radius: 8px;
+        color: inherit;
+        text-decoration: none;
+        padding: 14px;
+      }
+      .payment-card {
+        background: var(--surface-subtle);
+        border-radius: 8px;
+        color: inherit;
+        text-decoration: none;
+        padding: 14px;
+      }
+      .invoice-line-card,
+      .invoice-summary {
+        background: var(--surface-bg);
+        color: inherit;
+        text-decoration: none;
+        padding: 14px;
+      }
+      .project-card-main {
+        display: grid;
+        grid-template-columns: minmax(0, 1fr) auto;
+        gap: 12px;
+        align-items: start;
+      }
+      .project-card h2,
+      .payment-card h3 {
+        font-size: 18px;
+        margin: 0 0 4px;
+      }
+      .project-card-id { color: var(--muted-color); font-size: 13px; }
+      .project-card-amount { text-align: right; }
+      .project-card-amount span {
+        display: block;
+        color: var(--muted-color);
+        font-size: 13px;
+      }
+      .project-card-footer {
+        display: flex;
+        justify-content: flex-end;
+        margin-top: 12px;
+      }
+      .payment-card-reference { overflow-wrap: anywhere; }
+      .line-items-section {
+        background: var(--surface-bg);
+        border-radius: 8px;
+        margin-bottom: 16px;
+        overflow: hidden;
+      }
+      .invoice-line-list {
+        display: grid;
+        gap: 10px;
+      }
+      .invoice-line-card {
+        display: grid;
+        grid-template-columns: minmax(0, 1fr) max-content;
+        gap: 12px;
+        align-items: start;
+      }
+      .invoice-line-description {
+        min-width: 0;
+        overflow-wrap: anywhere;
+      }
+      .invoice-line-amount {
+        min-width: 0;
+        text-align: right;
+      }
+      .invoice-line-amount span,
+      .invoice-summary-row span {
+        display: block;
+        color: var(--muted-color);
+        font-size: 13px;
+      }
+      .invoice-line-amount strong,
+      .invoice-summary-row strong {
+        overflow-wrap: anywhere;
+      }
+      .invoice-summary {
+        display: grid;
+        gap: 8px;
+      }
+      .invoice-summary-row {
+        display: grid;
+        grid-template-columns: minmax(0, 1fr) max-content;
+        gap: 12px;
+        align-items: baseline;
+      }
+      .invoice-summary-row + .invoice-summary-row {
+        border-top: 1px solid var(--border-subtle);
+        padding-top: 8px;
+      }
+      .invoice-summary-total strong { font-size: 18px; }
+      .line-item {
+        display: grid;
+        grid-template-columns: minmax(0, 1fr) auto;
+        gap: 12px;
+        align-items: end;
+        border-radius: 8px;
+        padding: 14px;
+        margin-bottom: 12px;
+        background: var(--surface-subtle);
+      }
+      .line-item-text { grid-column: 1 / -1; }
+      .line-item-price { max-width: 180px; }
+      .line-item [data-remove-line] {
+        align-self: end;
+        justify-self: end;
+      }
+      .searchbar { margin-bottom: 14px; }
+      .searchbar input { flex: 1; }
+      .search-field {
+        position: relative;
+        flex: 1;
+      }
+      .search-field input { padding-right: 40px; }
+      .search-clear {
+        position: absolute;
+        top: 50%;
+        right: 8px;
+        min-height: 28px;
+        width: 28px;
+        border: 0;
+        background: transparent;
+        color: var(--muted-color);
+        padding: 0;
+        transform: translateY(-50%);
+      }
+      .search-clear:hover { background: transparent; color: var(--text-color); }
+      .copy-field { position: relative; }
+      .copy-field input {
+        cursor: pointer;
+        padding-right: 76px;
+      }
+      .copy-indicator {
+        position: absolute;
+        top: 50%;
+        right: 12px;
+        width: 22px;
+        height: 22px;
+        color: var(--muted-color);
+        pointer-events: none;
+        transform: translateY(-50%);
+      }
+      .copy-indicator::before,
+      .copy-indicator::after {
+        content: "";
+        position: absolute;
+        width: 13px;
+        height: 13px;
+        border: 1.5px solid currentColor;
+        border-radius: 2px;
+        background: var(--surface-bg);
+      }
+      .copy-indicator::before { left: 2px; top: 6px; }
+      .copy-indicator::after { left: 7px; top: 1px; }
+      .copy-indicator.copied {
+        width: auto;
+        height: auto;
+        color: var(--primary-color);
+        font-size: 13px;
+        font-weight: 700;
+      }
+      .copy-indicator.copied::before {
+        content: "Copied!";
+        position: static;
+        width: auto;
+        height: auto;
+        border: 0;
+        background: transparent;
+      }
+      .copy-indicator.copied::after { display: none; }
+      .has-sticky-pay { padding-bottom: 100px; }
+      .sticky-pay {
+        position: fixed;
+        left: 0;
+        right: 0;
+        bottom: 0;
+        z-index: 10;
+        max-width: 100%;
+        overflow-x: hidden;
+        background: var(--sticky-bg);
+        padding: 12px 20px;
+      }
+      .sticky-pay-inner {
+        max-width: 1080px;
+        margin: 0 auto;
+        display: flex;
+        justify-content: flex-end;
+      }
+      .sticky-pay button {
+        width: 100%;
+      }
+      .has-sticky-actions { padding-bottom: 104px; }
+      .sticky-actions {
+        position: fixed;
+        left: 0;
+        right: 0;
+        bottom: 0;
+        z-index: 10;
+        max-width: 100%;
+        overflow-x: hidden;
+        background: var(--sticky-bg);
+        padding: 12px 20px;
+      }
+      .sticky-actions-inner {
+        max-width: 1080px;
+        margin: 0 auto;
+        display: grid;
+        grid-template-columns: 1fr 1fr;
+        gap: 10px;
+      }
+      .sticky-actions .button,
+      .sticky-actions button,
+      .sticky-actions .inline,
+      .add-line-button {
+        width: 100%;
+      }
+      .full-width-form,
+      .full-width-form button {
+        width: 100%;
+      }
+      .has-sticky-index {
+        padding-bottom: 124px;
+      }
+      .sticky-index-search {
+        position: fixed;
+        left: 0;
+        right: 0;
+        z-index: 10;
+        max-width: 100%;
+        overflow-x: hidden;
+        background: var(--sticky-bg);
+        padding: 12px 20px;
+      }
+      .sticky-index-search {
+        bottom: 0;
+      }
+      .sticky-index-search-inner {
+        max-width: 1080px;
+        margin: 0 auto;
+      }
+      .sticky-index-search .searchbar {
+        margin: 0;
+      }
+      .floating-new-project {
+        position: fixed;
+        display: inline-flex;
+        align-items: center;
+        justify-content: center;
+        right: max(20px, calc((100vw - 1080px) / 2));
+        bottom: calc(75px + var(--keyboard-offset, 0px));
+        z-index: 11;
+        width: 56px;
+        height: 56px;
+        border: 1px solid var(--primary-color);
+        border-radius: 50%;
+        background: var(--primary-color);
+        color: var(--primary-contrast);
+        box-shadow: 0 10px 24px var(--shadow-color);
+        font-size: 34px;
+        font-weight: 500;
+        line-height: 1;
+        padding: 0 0 4px;
+        text-decoration: none;
+      }
+      .floating-new-project:hover {
+        background: var(--primary-hover-color);
+        border-color: var(--primary-hover-color);
+      }
+      .empty { color: var(--muted-color); padding: 18px 0; }
+      .signout-form { display: flex; justify-content: center; margin: 28px 0; }
+      .amount { text-align: right; }
+      @media (max-width: 760px) {
+        .topbar-inner, .header-row, .nav, .searchbar { align-items: stretch; flex-direction: column; }
+        input, textarea { font-size: 16px; }
+        .nav .inline, .nav .inline button, .nav .button { width: 100%; }
+        .grid-2, .stats, .line-item, .project-card-main { grid-template-columns: 1fr; }
+        .line-item-text { grid-column: auto; }
+        .line-item-price { max-width: none; }
+        .invoice-line-card,
+        .invoice-summary-row { grid-template-columns: 1fr; }
+        .invoice-line-amount { text-align: left; }
+        .project-card-amount { text-align: left; }
+        .project-card-footer { justify-content: flex-start; }
+        .sticky-pay button { width: 100%; }
+        .has-sticky-index.index-search-active {
+          padding-top: calc(92px + env(safe-area-inset-top, 0px));
+        }
+        .has-sticky-index.index-search-active .sticky-index-search {
+          top: 0;
+          bottom: auto;
+          padding-top: max(12px, env(safe-area-inset-top, 0px));
+          box-shadow: 0 8px 18px var(--shadow-color);
+        }
+        .has-sticky-index.index-search-active .floating-new-project {
+          bottom: calc(16px + env(safe-area-inset-bottom, 0px) + var(--keyboard-offset, 0px));
+        }
+      }
+        @media print {
+          .sticky-pay {
+            display: none !important;
+          }
+        
+          body.has-sticky-pay {
+            padding-bottom: 0 !important;
+          }
+        }
+    </style>
+    
+  </head>
+  <body>
+    <main class="page has-sticky-pay">
+      
+  
+    <div class="public-logo">
+      <picture>
+        
+          <source srcset="https://gitman.io/patx/afterdarklabs/raw/docs/logo-dark.png" media="(prefers-color-scheme: dark)">
+        
+        <img src="https://i.postimg.cc/sDdprXgH/ea51ebc1-6a86-4b80-9a94-e8c30dd94c3a-removebg-preview.png" alt="After Dark Labs Logo">
+      </picture>
+    </div>
+  
+  <div class="header-row">
+    <div>
+      <div class="title-line">
+        <h1>Project for Ada Lovelace</h1>
+      </div>
+      <p class="muted">PRJ-2026-0001</p>
+    </div>
+  </div>
+
+  
+  
+
+  <section class="line-items-section">
+  <div class="invoice-line-list">
+    
+      <article class="invoice-line-card">
+        <div class="invoice-line-description">Design work</div>
+        <div class="invoice-line-amount">
+          <strong>$1,250.00</strong>
+        </div>
+      </article>
+    
+
+    <div class="invoice-summary">
+      <div class="invoice-summary-row invoice-summary-total">
+        <span>Total</span>
+        <strong>$1,250.00</strong>
+      </div>
+      
+    </div>
+  </div>
+</section>
+
+  
+  <section class="section">
+    <h2>Terms and Scope</h2>
+      <div class="prewrap">Build <strong class="star-emphasis">great</strong> things</div>
+  </section>
+  
+
+  
+    <form class="sticky-pay" method="post" action="/pay/BIQaKG1cVvxCLZO83TOQNe5vJ2zIgLRq">
+      <div class="sticky-pay-inner">
+        <button type="submit">Make a Payment</button>
+      </div>
+    </form>
+  
+
+    </main>
+  </body>
+</html>
\ No newline at end of file
diff --git a/pay.out b/pay.out
new file mode 100644
index 0000000..e69de29
diff --git a/templates/base.html b/templates/base.html
index 960c784..a2dc226 100644
--- a/templates/base.html
+++ b/templates/base.html
@@ -38,6 +38,9 @@
         --info-bg: #edf5ff;
         --sticky-bg: rgba(247, 247, 247, .96);
         --shadow-color: rgba(31, 41, 51, .22);
+        --logo-bg: #0b1016;
+        --logo-border: rgba(31, 41, 51, .16);
+        --logo-shadow: 0 8px 24px rgba(31, 41, 51, .12);
       }
       @media (prefers-color-scheme: dark) {
         :root {
@@ -64,6 +67,9 @@
           --info-bg: #132c45;
           --sticky-bg: rgba(15, 23, 32, .96);
           --shadow-color: rgba(0, 0, 0, .35);
+          --logo-bg: #080d12;
+          --logo-border: #2a3745;
+          --logo-shadow: 0 8px 24px rgba(0, 0, 0, .28);
         }
       }
       body {
@@ -128,12 +134,20 @@
       .topbar-inner, .header-row { justify-content: space-between; }
       .brand { font-weight: 750; text-decoration: none; }
       .public-logo {
-        margin: 0 0 18px;
-        text-align: center;
+        display: flex;
+        width: fit-content;
+        max-width: 100%;
+        margin: 0 auto 22px;
+        padding: 10px 14px;
+        border: 1px solid var(--logo-border);
+        border-radius: 10px;
+        background: var(--logo-bg);
+        box-shadow: var(--logo-shadow);
       }
       .public-logo img {
-        display: inline-block;
-        max-width: min(350px, 100%);
+        display: block;
+        width: 360px;
+        max-width: 100%;
         height: auto;
       }
       .title-line {
@@ -465,6 +479,7 @@
         border-color: var(--primary-hover-color);
       }
       .empty { color: var(--muted-color); padding: 18px 0; }
+      .signout-form { display: flex; justify-content: center; margin: 28px 0; }
       .amount { text-align: right; }
       @media (max-width: 760px) {
         .topbar-inner, .header-row, .nav, .searchbar { align-items: stretch; flex-direction: column; }
diff --git a/templates/detail.html b/templates/detail.html
index b2a4869..3da1a34 100644
--- a/templates/detail.html
+++ b/templates/detail.html
@@ -59,7 +59,7 @@
     {% endif %}
   </section>
 
-  <form class="full-width-form" method="post" action="/delete/{{ project.id }}" onsubmit="return confirm('Delete {{ project.project_number }}? This cannot be undone.');">
+  <form class="full-width-form" method="post" action="/delete/{{ project.id }}" onsubmit="return confirm('Delete {{ project.project_number }}? It will be removed from the dashboard and its payment link will stop working.');">
     <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
     <button class="danger" type="submit">Delete</button>
   </form>
diff --git a/templates/form.html b/templates/form.html
index 81bde16..2e4acf7 100644
--- a/templates/form.html
+++ b/templates/form.html
@@ -85,7 +85,8 @@
     const currency = "{{ currency }}";
 
     function money(cents) {
-      return `${currency} ${(cents / 100).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
+      const amount = (cents / 100).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
+      return currency === "USD" ? `$${amount}` : `${currency} ${amount}`;
     }
 
     function recalc() {
diff --git a/templates/index.html b/templates/index.html
index 82abedd..c6c1d16 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -22,6 +22,11 @@
     {% if has_more %}Loading more projects as you scroll{% endif %}
   </div>
 
+  <form class="signout-form" method="post" action="/logout">
+    <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
+    <button class="secondary" type="submit">Sign Out</button>
+  </form>
+
   <script>
     const list = document.getElementById("project-list");
     const page = document.querySelector(".has-sticky-index");
diff --git a/templates/public_project.html b/templates/public_project.html
index e5d304e..b0d1f45 100644
--- a/templates/public_project.html
+++ b/templates/public_project.html
@@ -2,16 +2,9 @@
 {% block title %}{{ project.project_number }}{% endblock %}
 {% block page_class %}{{ 'has-sticky-pay' if project.balance_cents > 0 else '' }}{% endblock %}
 {% block content %}
-  {% if public_logo_url %}
-    <div class="public-logo">
-      <picture>
-        {% if public_dark_logo_url and public_dark_logo_url != public_logo_url %}
-          <source srcset="{{ public_dark_logo_url }}" media="(prefers-color-scheme: dark)">
-        {% endif %}
-        <img src="{{ public_logo_url }}" alt="{{ public_logo_alt }}">
-      </picture>
-    </div>
-  {% endif %}
+  <div class="public-logo">
+    <img src="https://afterdarklabs.io/logo_assets/lockup.svg" alt="After Dark Labs">
+  </div>
   <div class="header-row">
     <div>
       <div class="title-line">
@@ -41,7 +34,6 @@
 
   {% if project.balance_cents > 0 %}
     <form class="sticky-pay" method="post" action="/pay/{{ project.share_token }}">
-      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
       <div class="sticky-pay-inner">
         <button type="submit">Make a Payment</button>
       </div>
diff --git a/tests/test_security_hardening.py b/tests/test_security_hardening.py
index da5ce66..475da7e 100644
--- a/tests/test_security_hardening.py
+++ b/tests/test_security_hardening.py
@@ -95,11 +95,14 @@ class SecurityHardeningTests(unittest.TestCase):
     def test_logout_expires_session_cookie(self):
         app = self.make_app()
         request = SimpleNamespace(
-            session={"is_admin": True},
+            method="POST",
+            session={"is_admin": True, invoice_app.CSRF_SESSION_KEY: "csrf-token"},
             body_params={},
             headers={},
             scope={"client": ("127.0.0.1", 1234)},
-            form=lambda name, default=None: default,
+            form=lambda name, default=None: {
+                "csrf_token": "csrf-token",
+            }.get(name, default),
         )
         self.bind_request(app, request)
 
@@ -110,6 +113,27 @@ class SecurityHardeningTests(unittest.TestCase):
         self.assertIn(f"{invoice_app.SESSION_COOKIE}=", response[2][1][1])
         self.assertIn("Max-Age=0", response[2][1][1])
 
+    def test_logout_requires_post_with_valid_csrf(self):
+        app = self.make_app()
+        request = SimpleNamespace(
+            method="GET",
+            session={"is_admin": True},
+            body_params={},
+            headers={},
+            scope={"client": ("127.0.0.1", 1234)},
+            form=lambda name, default=None: default,
+        )
+        self.bind_request(app, request)
+
+        response = app.logout()
+        self.assertEqual(response[0], 302)
+        self.assertEqual(request.session, {"is_admin": True})
+
+        request.method = "POST"
+        request.session[invoice_app.CSRF_SESSION_KEY] = "csrf-token"
+        response = app.logout()
+        self.assertEqual(response[0], 403)
+
     def test_production_requires_non_default_admin_password(self):
         with patch.dict(
             os.environ,
@@ -179,6 +203,58 @@ class SecurityHardeningTests(unittest.TestCase):
     def test_direct_run_host_defaults_to_loopback(self):
         self.assertEqual(invoice_app.DEFAULT_HOST, "127.0.0.1")
 
+    def test_non_ascii_password_is_rejected_without_error(self):
+        self.assertFalse(invoice_app.constant_time_equals("pässword", "admin"))
+        self.assertFalse(invoice_app.constant_time_equals("admin", "pässword"))
+        self.assertTrue(invoice_app.constant_time_equals("secret", "secret"))
+
+    def test_page_parameter_falls_back_to_first_page(self):
+        self.assertEqual(invoice_app.parse_page("abc"), 1)
+        self.assertEqual(invoice_app.parse_page(""), 1)
+        self.assertEqual(invoice_app.parse_page(None), 1)
+        self.assertEqual(invoice_app.parse_page("-3"), 1)
+        self.assertEqual(invoice_app.parse_page("7"), 7)
+
+    def test_security_headers_added_to_responses(self):
+        middleware = invoice_app.SecurityHeadersMiddleware()
+        headers = [("Content-Type", "text/html")]
+        result = asyncio.run(middleware.after_request(None, 200, "", headers))
+
+        self.assertIsNone(result)
+        names = {name for name, _ in headers}
+        self.assertIn("X-Frame-Options", names)
+        self.assertIn("X-Content-Type-Options", names)
+        self.assertIn("Content-Security-Policy", names)
+
+    def test_security_headers_do_not_duplicate_existing(self):
+        headers = [("X-Frame-Options", "SAMEORIGIN")]
+        middleware = invoice_app.SecurityHeadersMiddleware()
+        asyncio.run(middleware.after_request(None, 200, "", headers))
+
+        frame_values = [value for name, value in headers if name == "X-Frame-Options"]
+        self.assertEqual(frame_values, ["SAMEORIGIN"])
+
+    def test_manifest_response_includes_security_headers(self):
+        app = self.make_app()
+
+        status, headers, body = asyncio.run(self.asgi_get(app, "/manifest.json"))
+
+        self.assertEqual(status, 200)
+        self.assertEqual(headers["x-frame-options"], "DENY")
+        self.assertEqual(headers["x-content-type-options"], "nosniff")
+
+    def test_project_search_text_is_lowercased(self):
+        self.assertEqual(
+            invoice_app.project_search_text(
+                {
+                    "project_number": "PRJ-2026-0001",
+                    "customer_name": "Ada Lovelace",
+                    "status": "Open",
+                }
+            ),
+            "prj-2026-0001 ada lovelace open",
+        )
+
     def test_manifest_json_uses_default_app_icon_url(self):
         app = self.make_app()
 
@@ -207,21 +283,6 @@ class SecurityHardeningTests(unittest.TestCase):
         manifest = json.loads(body)
         self.assertEqual(manifest["icons"][0]["src"], "https://example.com/app-icon.png")
 
-    def test_public_dark_logo_url_defaults_to_public_logo_url(self):
-        app = self.make_app(PUBLIC_LOGO_URL="https://example.com/logo.svg")
-
-        self.assertEqual(app.public_dark_logo_url, "https://example.com/logo.svg")
-
-    def test_public_dark_logo_url_can_be_configured(self):
-        app = self.make_app(
-            PUBLIC_LOGO_URL="https://example.com/logo.svg",
-            PUBLIC_DARK_LOGO_URL="https://example.com/logo-dark.svg",
-        )
-
-        self.assertEqual(
-            app.public_dark_logo_url, "https://example.com/logo-dark.svg"
-        )
-
     def test_development_base_url_uses_request_headers_only_in_development(self):
         app = self.make_app(APP_BASE_URL="")
         request = SimpleNamespace(