File size: 33,361 Bytes
187ef74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
"""ioby WebsiteBench offline clone.

Public pages follow anonymous archival captures from 2026-08-24.  Donation,
account, recovery, favorite, and recurring-plan behavior is an explicit local
simulation because the observed source was closed and exposed no usable live
transaction flow.  Runtime requests are same-origin and never leave the clone.
"""

from __future__ import annotations

import re
import sys
from pathlib import Path
from typing import Any
from urllib.parse import urlsplit

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles


ROOT = Path(__file__).resolve().parent
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from backend import business  # noqa: E402
from backend.site_backend_integration import open_site_services  # noqa: E402
import views  # noqa: E402
from websitebench.local_clone_auth import AuthConflict, AuthError, AuthRateLimited  # noqa: E402
from websitebench.site_backend import PaymentError, PaymentRejected  # noqa: E402


SITE_ID = "ioby"
PROJECT_SLUG = "make-block-bloom"
BACKEND, AUTH = open_site_services()
with BACKEND.lifecycle.connection(transaction=True) as connection:
    business.migrate(connection)

DEMO_ACCOUNT_ID = AUTH.seed_account(
    subject_id="ioby-demo-neighbor",
    email="demo@ioby.local",
    display_name="Morgan Neighbor",
    password="Neighbor123!",
)
with BACKEND.lifecycle.connection(transaction=True) as connection:
    business.seed_demo(connection, DEMO_ACCOUNT_ID)


APP = FastAPI(title="ioby offline clone", docs_url=None, redoc_url=None, openapi_url=None)
app = APP
APP.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static")

DEPLOYED_COOKIE = str(BACKEND.session_cookie["name"])
LOCAL_COOKIE = "websitebench-ioby-session"
CSP = (
    "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; "
    "connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'"
)
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")


def _loopback(request: Request) -> bool:
    return (request.url.hostname or "").casefold() in {
        "127.0.0.1",
        "localhost",
        "::1",
        "[::1]",
        "testserver",
    }


def _cookie_name(request: Request) -> str:
    return LOCAL_COOKIE if _loopback(request) else DEPLOYED_COOKIE


def _origin(value: str) -> tuple[str, str, int]:
    parsed = urlsplit(value)
    return (
        parsed.scheme.casefold(),
        (parsed.hostname or "").casefold(),
        parsed.port or (443 if parsed.scheme.casefold() == "https" else 80),
    )


def _request_origin(request: Request) -> tuple[str, str, int]:
    return (
        request.url.scheme.casefold(),
        (request.url.hostname or "").casefold(),
        request.url.port or (443 if request.url.scheme.casefold() == "https" else 80),
    )


def _set_cookie(request: Request, response: Response, token: str) -> None:
    response.set_cookie(
        _cookie_name(request),
        token,
        secure=not _loopback(request),
        httponly=True,
        samesite="lax",
        path="/",
    )


@APP.middleware("http")
async def runtime_boundary(request: Request, call_next):
    if request.method in {"POST", "PUT", "PATCH", "DELETE"}:
        source = request.headers.get("origin") or request.headers.get("referer")
        invalid = source == "null" and not _loopback(request)
        if source and source != "null":
            invalid = _origin(source) != _request_origin(request)
        elif not source:
            invalid = not _loopback(request)
        if invalid:
            return JSONResponse(
                {"error": "cross-origin state changes are not allowed"}, status_code=403
            )
    supplied = request.cookies.get(_cookie_name(request))
    token, session = AUTH.ensure_session(supplied)
    request.state.auth_token = token
    request.state.auth_info = session
    response = await call_next(request)
    if request.url.path.startswith("/static/assets/") and request.url.path.endswith(".svg"):
        # Captured first-party SVGs contain their own presentation rules.  The
        # narrowly scoped image response may apply those rules; HTML documents
        # retain the strict no-inline policy above.
        response.headers["Content-Security-Policy"] = (
            "default-src 'none'; style-src 'unsafe-inline'; sandbox"
        )
    else:
        response.headers["Content-Security-Policy"] = CSP
    response.headers["Referrer-Policy"] = "no-referrer"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    current = str(getattr(request.state, "auth_token", token))
    if current != supplied:
        _set_cookie(request, response, current)
    return response


def html(markup: str, status: int = 200) -> HTMLResponse:
    return HTMLResponse(markup, status_code=status)


def see_other(path: str) -> RedirectResponse:
    return RedirectResponse(path, status_code=303)


def db():
    return BACKEND.lifecycle.connection(transaction=True)


def account_of(request: Request) -> dict[str, Any] | None:
    session = getattr(request.state, "auth_info", {}) or {}
    if not session.get("authenticated"):
        return None
    return dict(session.get("account") or {})


def account_id_of(request: Request) -> str | None:
    account = account_of(request)
    return str(account["account_id"]) if account else None


def owner_key_of(request: Request) -> str:
    return f"session:{AUTH.session_owner_digest(str(request.state.auth_token))}"


def safe_next(value: Any) -> str:
    target = str(value or "/account")
    return target if target.startswith("/") and not target.startswith("//") else "/account"


def unexpected_fields(form: Any, allowed: set[str]) -> bool:
    """Fail closed when a mutation receives client-controlled fields it does not own."""

    return any(str(key) not in allowed for key in form.keys())


def _owned_donation(request: Request, donation_id: str) -> dict[str, Any] | None:
    with db() as connection:
        return business.get_donation(
            connection,
            donation_id,
            owner_key=owner_key_of(request),
            account_id=account_id_of(request),
        )


@APP.get("/favicon.ico", include_in_schema=False)
def favicon() -> Response:
    """The source links `/favicon.ico`; serve the captured ioby mark there so no page logs a 404."""
    icon = ROOT / "static" / "assets" / "ioby-logo.svg"
    return Response(icon.read_bytes(), media_type="image/svg+xml",
                    headers={"Cache-Control": "public, max-age=86400"})


@APP.get("/__websitebench/health", response_class=JSONResponse)
def websitebench_health() -> dict[str, str]:
    return {"status": "ok"}


@APP.get("/healthz", response_class=JSONResponse)
def healthz() -> dict[str, object]:
    return {"ok": True, "site_id": SITE_ID, "status": "ok"}


# Public source-grounded pages -------------------------------------------------


@APP.get("/", response_class=HTMLResponse)
def home(request: Request):
    return html(views.home(account_of(request)))


@APP.get("/project/", response_class=HTMLResponse)
def project_catalog(request: Request, q: str = "", state: str = "", impact: str = ""):
    return html(
        views.project_catalog(
            query=q, state=state, impact=impact, account=account_of(request)
        )
    )


@APP.get("/places/newyorkcity/", response_class=HTMLResponse)
def new_york(request: Request):
    return html(views.new_york(account_of(request)))


@APP.get("/project/make-block-bloom/", response_class=HTMLResponse)
def make_block_bloom(request: Request, notice: str = ""):
    account = account_of(request)
    saved = False
    if account:
        with db() as connection:
            saved = business.is_favorite(
                connection, str(account["account_id"]), PROJECT_SLUG
            )
    return html(views.project_detail(account, saved=saved, notice=notice))


@APP.get("/project/make-block-bloom/favorite")
def favorite_get(request: Request):
    """The favorite control posts here; a direct GET returns to the project."""
    return see_other("/project/make-block-bloom/")


@APP.post("/project/make-block-bloom/favorite")
async def favorite(request: Request):
    account = account_of(request)
    if account is None:
        return see_other("/login?next=/project/make-block-bloom/")
    form = await request.form()
    if unexpected_fields(form, {"saved"}):
        return html(views.not_found(account), 400)
    target = str(form.get("saved") or "")
    if target not in {"0", "1"}:
        return html(views.not_found(account), 400)
    with db() as connection:
        saved = business.set_favorite(
            connection,
            str(account["account_id"]),
            PROJECT_SLUG,
            saved=target == "1",
        )
    notice = "Project saved to your local account" if saved else "Project removed from saved items"
    return see_other(f"/project/make-block-bloom/?notice={notice.replace(' ', '+')}")


SIMPLE_PROJECTS = {
    "crystal-gardens-immersive-healing-art-exhibition": "The Crystal Gardens: An Immersive Healing Art Exhibition",
    "10th-street-neighborhood-resource-center": "10th Street Neighborhood Resource Center",
    "sweet-sassy-girls-lemonade-stand": "Sweet & Sassy Girls - Lemonade Stand",
}


@APP.get("/project/{slug}/", response_class=HTMLResponse)
def other_project(request: Request, slug: str):
    title = SIMPLE_PROJECTS.get(slug)
    if title is None:
        return html(views.not_found(account_of(request)), 404)
    return html(views.simple_project(title, account_of(request)))


@APP.get("/resources/", response_class=HTMLResponse)
@APP.get("/help", response_class=HTMLResponse)
def resources(request: Request):
    return html(views.resources(account_of(request)))


@APP.get("/places/", response_class=HTMLResponse)
def places(request: Request):
    return html(views.places(account_of(request)))


@APP.get("/match/", response_class=HTMLResponse)
def match_programs(request: Request):
    return html(views.match_programs(account_of(request)))


@APP.get("/how-it-works/", response_class=HTMLResponse)
def how_it_worked(request: Request):
    return html(views.how_it_worked(account_of(request)))


@APP.get("/about/", response_class=HTMLResponse)
def about(request: Request):
    return html(views.about(account_of(request)))


@APP.get("/resources/closing/", response_class=HTMLResponse)
def closing(request: Request):
    return html(
        views.generic_page(
            "ioby has closed", "ioby has closed its doors", "The public source is an archival site. This offline clone preserves observed pages and labels all new local simulations truthfully.", account_of(request)
        )
    )


@APP.get("/about/terms/", response_class=HTMLResponse)
def terms(request: Request):
    return html(
        views.generic_page(
            "Local terms", "Offline clone terms", "Accounts and donations created here are local test records only. No production service is contacted.", account_of(request)
        )
    )


REFERENCE_TITLES = {
    "match": {
        "2020-cuyahoga-arts-culture": "2020 Cuyahoga Arts & Culture Match Fund",
        "2020-doors-open-pittsburgh": "2020 Doors Open Pittsburgh Match Challenge",
        "2020-healthy-neighborhoods": "2020 Healthy Neighborhoods Challenge",
        "2021-con-edison-power-up": "2021 Con Edison Power Up Neighborhood Match",
        "2021-cuyahoga-arts-culture": "2021 Cuyahoga Arts & Culture Match Fund",
        "2021-detroit": "2021 Detroit Match Program",
    },
    "places": {
        "arkansas": "Arkansas",
        "cleveland": "Cleveland",
        "detroit": "Detroit",
        "pittsburgh": "Pittsburgh",
    },
    "how-it-works": {
        "currently-crowdfunding": "Currently Crowdfunding? Your questions answered here",
        "fees": "Fees",
        "criteria": "Criteria",
        "fiscal-sponsorship": "Fiscal Sponsorship",
        "match-funding": "Match Funding",
        "coaching": "Coaching",
    },
    "resources": {
        "making-it-rain": "Making It Rain",
        "recipes-for-change": "Recipes For Change",
        "leader-toolkit": "Leader Toolkit",
        "report-from-the-field-the-northwest-arkansas-neighborhood-match-program": "Report from The Field: The Northwest Arkansas Neighborhood Match Program",
        "10-climate-conscious-projects-we-love": "10 Climate-Conscious Projects We Love",
        "iobys-comprehensive-guide-to-end-of-year-fundraising": "ioby’s Comprehensive Guide to End-of-Year Fundraising",
        "active-transit-toolkit": "Active Transit Toolkit",
        "sustaining-justice-in-our-neighborhoods-block-by-block": "Sustaining Justice in our Neighborhoods, Block by Block",
    },
    "about": {
        "reports": "Reports",
        "transparency": "Transparency",
        "privacy": "Privacy Policy",
    },
}


# Donation journey -------------------------------------------------------------


@APP.get("/donate/{project_slug}", response_class=HTMLResponse)
def donation_start(request: Request, project_slug: str):
    if project_slug != PROJECT_SLUG:
        return html(views.not_found(account_of(request)), 404)
    return html(views.donation_amount(account_of(request)))


@APP.post("/donate/{project_slug}")
async def donation_start_post(request: Request, project_slug: str):
    if project_slug != PROJECT_SLUG:
        return html(views.not_found(account_of(request)), 404)
    form = await request.form()
    if unexpected_fields(form, {"amount", "cadence"}):
        return html(
            views.donation_amount(
                account_of(request),
                error="This donation step received an unsupported field.",
            ),
            400,
        )
    raw_amount = str(form.get("amount") or "").strip()
    cadence = str(form.get("cadence") or "")
    values = {"amount": raw_amount, "cadence": cadence}
    try:
        amount_cents = int(round(float(raw_amount) * 100))
    except (TypeError, ValueError):
        amount_cents = 0
    if amount_cents < 100 or amount_cents > 10_000_000:
        return html(
            views.donation_amount(
                account_of(request), error="Enter an amount from $1.00 to $100,000.00.", values=values
            ),
            400,
        )
    if cadence not in {"one-time", "monthly"}:
        return html(
            views.donation_amount(
                account_of(request), error="Choose one-time or monthly.", values=values
            ),
            400,
        )
    with db() as connection:
        donation = business.create_draft(
            connection,
            owner_key=owner_key_of(request),
            account_id=account_id_of(request),
            project_slug=project_slug,
            amount_cents=amount_cents,
            cadence=cadence,
        )
    return see_other(f"/donate/{project_slug}/details?donation_id={donation['id']}")


@APP.get("/donate/{project_slug}/details", response_class=HTMLResponse)
def donation_details(request: Request, project_slug: str, donation_id: str = ""):
    donation = _owned_donation(request, donation_id)
    if project_slug != PROJECT_SLUG or donation is None:
        return html(views.not_found(account_of(request)), 404)
    return html(views.donation_details(donation, account_of(request)))


@APP.post("/donate/{project_slug}/details")
async def donation_details_post(request: Request, project_slug: str, donation_id: str = ""):
    donation = _owned_donation(request, donation_id)
    if project_slug != PROJECT_SLUG or donation is None:
        return html(views.not_found(account_of(request)), 404)
    form = await request.form()
    if unexpected_fields(
        form, {"donor_name", "donor_email", "recognition", "dedication"}
    ):
        return html(
            views.donation_details(
                donation,
                account_of(request),
                error="This donation step received an unsupported field.",
            ),
            400,
        )
    values = {
        "donor_name": " ".join(str(form.get("donor_name") or "").split()),
        "donor_email": str(form.get("donor_email") or "").strip().casefold(),
        "recognition": str(form.get("recognition") or ""),
        "dedication": str(form.get("dedication") or "").strip(),
        "tip_cents": 0,
    }
    errors: list[str] = []
    if not 1 <= len(values["donor_name"]) <= 120:
        errors.append("Enter your full name.")
    if EMAIL_RE.fullmatch(values["donor_email"]) is None:
        errors.append("Enter a valid email for the local receipt.")
    if values["recognition"] not in {"public", "anonymous"}:
        errors.append("Choose a recognition preference.")
    if len(values["dedication"]) > 280:
        errors.append("Keep the dedication to 280 characters.")
    if errors:
        return html(
            views.donation_details(
                donation, account_of(request), error=" ".join(errors), values=values
            ),
            400,
        )
    with db() as connection:
        updated = business.update_details(
            connection,
            donation_id,
            values,
            owner_key=owner_key_of(request),
            account_id=account_id_of(request),
        )
    if updated is None:
        return html(views.not_found(account_of(request)), 404)
    return see_other(f"/donate/{project_slug}/payment?donation_id={donation_id}")


@APP.get("/donate/{project_slug}/payment", response_class=HTMLResponse)
def donation_payment(request: Request, project_slug: str, donation_id: str = ""):
    donation = _owned_donation(request, donation_id)
    if project_slug != PROJECT_SLUG or donation is None:
        return html(views.not_found(account_of(request)), 404)
    return html(views.donation_payment(donation, account_of(request)))


@APP.post("/donate/{project_slug}/payment")
async def donation_payment_post(request: Request, project_slug: str, donation_id: str = ""):
    donation = _owned_donation(request, donation_id)
    if project_slug != PROJECT_SLUG or donation is None:
        return html(views.not_found(account_of(request)), 404)
    form = await request.form()
    if unexpected_fields(form, {"scenario_id"}):
        return html(
            views.donation_payment(
                donation,
                account_of(request),
                error="Payment credentials and server-owned checkout fields are not accepted.",
            ),
            400,
        )
    scenario = str(form.get("scenario_id") or "")
    if scenario not in {"sandbox-approved", "sandbox-declined", "sandbox-retry"}:
        return html(
            views.donation_payment(
                donation, account_of(request), error="Choose one local sandbox outcome."
            ),
            400,
        )
    try:
        with db() as connection:
            current = business.get_donation(
                connection,
                donation_id,
                owner_key=owner_key_of(request),
                account_id=account_id_of(request),
            )
            if current is None or not current.get("donor_email"):
                return see_other(
                    f"/donate/{project_slug}/details?donation_id={donation_id}"
                )
            facts = business.payment_facts(current)
            flow = BACKEND.payments.create_intent(
                owner=facts["owner"],
                amount_minor=facts["amount_minor"],
                currency=facts["currency"],
                fingerprint=facts["fingerprint"],
                idempotency_key=f"ioby.create:{donation_id}",
                connection=connection,
            )
            attempt = BACKEND.payments.attempt(
                flow_id=flow["flow_id"],
                owner=facts["owner"],
                amount_minor=facts["amount_minor"],
                currency=facts["currency"],
                fingerprint=facts["fingerprint"],
                scenario_id=scenario,
                idempotency_key=f"ioby.attempt:{donation_id}:{scenario}",
                connection=connection,
            )
            if attempt["status"] != "APPROVED":
                label = "declined" if attempt["status"] == "DECLINED" else "temporarily unavailable"
                return html(
                    views.donation_payment(
                        current,
                        account_of(request),
                        error=f"The local sandbox result was {label}. No donation was created; choose a fresh outcome and retry.",
                    ),
                    400,
                )
            business.record_payment_approval(
                connection,
                donation_id,
                owner_key=owner_key_of(request),
                account_id=account_id_of(request),
                payment_flow_id=str(flow["flow_id"]),
                payment_attempt_id=str(attempt["attempt_id"]),
            )
    except (PaymentError, PaymentRejected) as exc:
        return html(
            views.donation_payment(
                donation,
                account_of(request),
                error=f"The local sandbox could not complete this attempt: {exc}",
            ),
            400,
        )
    return see_other(f"/donate/{project_slug}/review?donation_id={donation_id}")


@APP.get("/donate/{project_slug}/review", response_class=HTMLResponse)
def donation_review(request: Request, project_slug: str, donation_id: str = ""):
    donation = _owned_donation(request, donation_id)
    if project_slug != PROJECT_SLUG or donation is None:
        return html(views.not_found(account_of(request)), 404)
    if donation["status"] == "confirmed":
        return see_other(f"/donations/{donation_id}/receipt")
    if not donation.get("payment_flow_id"):
        return see_other(f"/donate/{project_slug}/payment?donation_id={donation_id}")
    return html(views.donation_review(donation, account_of(request)))


@APP.post("/donate/{project_slug}/review")
async def donation_review_post(request: Request, project_slug: str, donation_id: str = ""):
    form = await request.form()
    donation = _owned_donation(request, donation_id)
    if project_slug != PROJECT_SLUG or donation is None:
        return html(views.not_found(account_of(request)), 404)
    if unexpected_fields(form, {"confirm"}):
        return html(
            views.donation_review(
                donation,
                account_of(request),
                error="This confirmation received an unsupported field.",
            ),
            400,
        )
    if donation["status"] == "confirmed":
        return see_other(f"/donations/{donation_id}/receipt")
    if str(form.get("confirm") or "") != "1":
        return html(
            views.donation_review(
                donation,
                account_of(request),
                error="Confirm that you understand this is a local simulation.",
            ),
            400,
        )
    try:
        with db() as connection:
            current = business.get_donation(
                connection,
                donation_id,
                owner_key=owner_key_of(request),
                account_id=account_id_of(request),
            )
            if current is None:
                return html(views.not_found(account_of(request)), 404)
            if current["status"] == "confirmed":
                return see_other(f"/donations/{donation_id}/receipt")
            facts = business.payment_facts(current)
            consumed = BACKEND.payments.consume_approval(
                connection,
                flow_id=str(current["payment_flow_id"]),
                owner=facts["owner"],
                amount_minor=facts["amount_minor"],
                currency=facts["currency"],
                fingerprint=facts["fingerprint"],
            )
            confirmed = business.confirm_donation(
                connection,
                donation_id=donation_id,
                owner_key=owner_key_of(request),
                account_id=account_id_of(request),
                payment_flow_id=str(current["payment_flow_id"]),
                payment_attempt_id=str(consumed["attempt_id"]),
            )
            if confirmed is None:
                raise PaymentError("local donation transition was unavailable")
    except (PaymentError, PaymentRejected) as exc:
        return html(
            views.donation_review(
                donation,
                account_of(request),
                error=f"The local confirmation was not created: {exc}",
            ),
            400,
        )
    return see_other(f"/donations/{donation_id}/receipt")


@APP.get("/donations/{donation_id}/receipt", response_class=HTMLResponse)
def donation_receipt(request: Request, donation_id: str):
    donation = _owned_donation(request, donation_id)
    if donation is None or donation["status"] != "confirmed":
        return html(views.not_found(account_of(request)), 404)
    return html(views.receipt(donation, account_of(request)))


# Account, registration, and recovery -----------------------------------------


@APP.get("/login", response_class=HTMLResponse)
def login_page(request: Request, email: str = "", next: str = "/account"):
    if account_of(request):
        return see_other(safe_next(next))
    return html(views.sign_in(email=email, next_url=safe_next(next)))


@APP.post("/login")
async def login_post(request: Request):
    form = await request.form()
    email = str(form.get("email") or "").strip()
    next_url = safe_next(form.get("next"))
    old_owner = owner_key_of(request)
    try:
        result = AUTH.sign_in(
            str(request.state.auth_token),
            email=email,
            password=str(form.get("password") or ""),
        )
    except AuthError:
        return html(
            views.sign_in(
                email=email,
                error="The email or password is incorrect.",
                next_url=next_url,
            ),
            400,
        )
    request.state.auth_token = result["session_token"]
    request.state.auth_info = {"authenticated": True, "account": result["account"]}
    with db() as connection:
        business.claim_donations(
            connection,
            owner_key=old_owner,
            account_id=str(result["account"]["account_id"]),
        )
    return see_other(next_url)


@APP.get("/register", response_class=HTMLResponse)
def register_page(request: Request):
    if account_of(request):
        return see_other("/account")
    return html(views.register())


@APP.post("/register")
async def register_post(request: Request):
    form = await request.form()
    values = {
        "display_name": str(form.get("display_name") or "").strip(),
        "email": str(form.get("email") or "").strip(),
    }
    if str(form.get("terms") or "") != "1":
        return html(
            views.register(values=values, error="Accept the local terms to continue."),
            400,
        )
    try:
        AUTH.start_registration(
            str(request.state.auth_token),
            email=values["email"],
            display_name=values["display_name"],
            password=str(form.get("password") or ""),
            restart_invalid_flow=True,
        )
    except AuthRateLimited as exc:
        return html(
            views.register(values=values, error=f"Try again in {exc.retry_after} seconds."),
            429,
        )
    except (AuthConflict, AuthError) as exc:
        return html(views.register(values=values, error=str(exc)), 400)
    mail = AUTH.local_mail_for_session(
        str(request.state.auth_token), purpose="registration"
    )
    code = str(mail.get("verification_code") or "") if mail else ""
    return html(views.register(code=code))


@APP.post("/register/verify")
async def register_verify_post(request: Request):
    form = await request.form()
    old_owner = owner_key_of(request)
    try:
        AUTH.verify_registration_code(
            str(request.state.auth_token), str(form.get("code") or "")
        )
        result = AUTH.complete_registration(str(request.state.auth_token))
    except AuthError as exc:
        mail = AUTH.local_mail_for_session(
            str(request.state.auth_token), purpose="registration"
        )
        code = str(mail.get("verification_code") or "") if mail else ""
        return html(views.register(code=code, error=str(exc)), 400)
    request.state.auth_token = result["session_token"]
    request.state.auth_info = {"authenticated": True, "account": result["account"]}
    with db() as connection:
        business.claim_donations(
            connection,
            owner_key=old_owner,
            account_id=str(result["account"]["account_id"]),
        )
    return see_other("/account?notice=Account+created")


@APP.get("/forgot-password", response_class=HTMLResponse)
def forgot_password():
    return html(views.recover())


@APP.post("/forgot-password")
async def forgot_password_post(request: Request):
    form = await request.form()
    try:
        result = AUTH.start_password_reset(
            str(request.state.auth_token),
            email=str(form.get("email") or ""),
            restart_invalid_flow=True,
        )
    except AuthRateLimited as exc:
        return html(views.recover(error=f"Try again in {exc.retry_after} seconds."), 429)
    except AuthError as exc:
        return html(views.recover(error=str(exc)), 400)
    mail = AUTH.local_mail_for_session(
        str(request.state.auth_token), purpose="password-reset"
    )
    code = str(mail.get("verification_code") or "") if mail else ""
    return html(views.recover(message=str(result["message"]), code=code))


@APP.post("/forgot-password/complete")
async def forgot_password_complete(request: Request):
    form = await request.form()
    try:
        AUTH.verify_password_reset_code(
            str(request.state.auth_token), str(form.get("code") or "")
        )
        token = AUTH.complete_password_reset(
            str(request.state.auth_token),
            new_password=str(form.get("password") or ""),
        )
    except AuthError as exc:
        mail = AUTH.local_mail_for_session(
            str(request.state.auth_token), purpose="password-reset"
        )
        code = str(mail.get("verification_code") or "") if mail else ""
        return html(
            views.recover(
                message="Use the local reset code to choose a new password.",
                error=str(exc),
                code=code,
            ),
            400,
        )
    request.state.auth_token = token
    request.state.auth_info = AUTH.resolve_session(token) or {}
    return see_other("/account?notice=Password+updated")


@APP.post("/logout")
def logout(request: Request):
    AUTH.sign_out(str(request.state.auth_token))
    token = AUTH.create_anonymous_session()
    request.state.auth_token = token
    request.state.auth_info = {"authenticated": False, "account": None}
    return see_other("/")


@APP.get("/account", response_class=HTMLResponse)
def account_dashboard(request: Request, notice: str = ""):
    account = account_of(request)
    if account is None:
        return see_other("/login?next=/account")
    with db() as connection:
        donations = business.list_donations(connection, str(account["account_id"]))
        recurring = business.list_recurring(connection, str(account["account_id"]))
    return html(views.account_dashboard(account, donations, recurring, notice))


@APP.get("/account/donations", response_class=HTMLResponse)
def donation_history(request: Request):
    account = account_of(request)
    if account is None:
        return see_other("/login?next=/account/donations")
    with db() as connection:
        donations = business.list_donations(connection, str(account["account_id"]))
    return html(views.donation_history(account, donations))


@APP.get("/account/recurring", response_class=HTMLResponse)
def recurring_plans(request: Request, notice: str = ""):
    account = account_of(request)
    if account is None:
        return see_other("/login?next=/account/recurring")
    with db() as connection:
        plans = business.list_recurring(connection, str(account["account_id"]))
    return html(views.recurring_plans(account, plans, notice))


@APP.post("/account/recurring/{plan_id}/cancel")
def cancel_recurring(request: Request, plan_id: str):
    account = account_of(request)
    if account is None:
        return see_other("/login?next=/account/recurring")
    with db() as connection:
        result = business.cancel_recurring(
            connection, plan_id, str(account["account_id"])
        )
    if result is None:
        return html(views.not_found(account), 404)
    return see_other("/account/recurring?notice=Local+recurring+plan+canceled")


@APP.get("/{section}/{slug}/", response_class=HTMLResponse)
def reference_detail(request: Request, section: str, slug: str):
    title = REFERENCE_TITLES.get(section, {}).get(slug)
    if title is None:
        return html(views.not_found(account_of(request)), 404)
    return html(views.reference_detail(section, title, account_of(request)))


@APP.get("/{path:path}", response_class=HTMLResponse)
def not_found(request: Request, path: str):
    return html(views.not_found(account_of(request)), 404)