File size: 27,224 Bytes
393804b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Offline 1Password-inspired FastAPI application (loopback only)."""

from __future__ import annotations

import csv
import html
import io
import json
import os
import secrets
import sys
from pathlib import Path
from typing import Any

from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import (
    HTMLResponse,
    JSONResponse,
    StreamingResponse,
)
from fastapi.staticfiles import StaticFiles

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "backend"))
import business as biz  # noqa: E402
from site_backend_integration import open_site_services  # noqa: E402
from websitebench.local_clone_auth.store import AuthError  # noqa: E402

DATA = Path(
    os.environ.get(
        "WEBSITEBENCH_DATA_DIR", os.environ.get("TMPDIR", "/tmp") + "/wb-1password-data"
    )
)
(DATA / "data").mkdir(parents=True, exist_ok=True)
os.environ.setdefault(
    "WEBSITEBENCH_SITE_BACKEND_DATABASE", str(DATA / "data" / "1password-web.sqlite3")
)
backend, auth = open_site_services()

DEMO_OWNER = "owner@demo.1password.test"
DEMO_MEMBER = "member@demo.1password.test"
DEMO_PASSWORD = "DemoVault2026!"
for subject, email, name in [
    ("demo-owner", DEMO_OWNER, "Morgan Owner"),
    ("demo-member", DEMO_MEMBER, "Taylor Member"),
]:
    if not auth.account_exists(email):
        auth.seed_account(
            subject_id=subject,
            email=email,
            display_name=name,
            password=DEMO_PASSWORD,
            email_verified=True,
        )

app = FastAPI(title="1Password offline clone", docs_url=None, redoc_url=None)
app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static")
STRICT = backend.session_cookie
COOKIE = str(STRICT["name"])
TEST_COOKIE = "wb-1password-web-test-session"
INSECURE_TEST_COOKIE_ENV = "WEBSITEBENCH_INSECURE_TEST_COOKIE"


def insecure_test_cookie_enabled() -> bool:
    """Expose a second non-production cookie only in an explicit local fixture."""

    return os.environ.get(INSECURE_TEST_COOKIE_ENV) == "1"


def conn(transaction: bool = False):
    return backend.lifecycle.connection(transaction=transaction)


class Ctx:
    def __init__(self, req: Request):
        self.req = req
        raw = req.cookies.get(COOKIE)
        if raw is None and insecure_test_cookie_enabled():
            raw = req.cookies.get(TEST_COOKIE)
        self.token, self.session = auth.ensure_session(raw)
        self.new = self.token if raw != self.token else None
        self.account = self.session.get("account")

    def finish(self, res: Response) -> Response:
        if self.new:
            res.set_cookie(
                COOKIE,
                self.new,
                secure=bool(STRICT["secure"]),
                httponly=bool(STRICT["httponly"]),
                samesite=str(STRICT["samesite"]),
                path=str(STRICT["path"]),
            )
            if insecure_test_cookie_enabled():
                res.set_cookie(
                    TEST_COOKIE,
                    self.new,
                    secure=False,
                    httponly=True,
                    samesite="lax",
                    path="/",
                )
        return res

    def rotate(self, token: str):
        self.token = token
        self.new = token
        self.session = auth.resolve_session(token) or {}
        self.account = self.session.get("account")


def ok(ctx: Ctx, data: Any, status: int = 200) -> Response:
    return ctx.finish(JSONResponse({"ok": True, "data": data}, status_code=status))


def fail(ctx: Ctx, message: str, status: int = 400) -> Response:
    return ctx.finish(JSONResponse({"ok": False, "error": message}, status_code=status))


def require(ctx: Ctx) -> dict[str, Any]:
    if not ctx.account:
        raise HTTPException(401, "Sign in required")
    return ctx.account


async def body(req: Request) -> dict[str, Any]:
    try:
        return await req.json()
    except Exception:
        return {}


def wid_for(c, account):
    return biz.ensure_workspace(c, account)


def mapped_error(ctx: Ctx, e: Exception) -> Response:
    if isinstance(e, LookupError):
        return fail(ctx, str(e), 404)
    if isinstance(e, PermissionError):
        return fail(ctx, str(e), 403)
    if isinstance(e, (ValueError, AuthError)):
        return fail(ctx, str(e), 400)
    raise e


@app.get("/healthz")
def health():
    return {"ok": True, "site_id": "1password-web", "service": "offline-clone"}


PUBLIC = {
    "/": "home",
    "/pricing": "pricing",
    "/business": "business",
    "/business-security": "business",
    "/personal": "personal",
    "/personal-family-security": "personal",
    "/developers": "developers",
    "/developer-security": "developers",
    "/partners": "partners",
    "/partnerships": "partners",
    "/resources": "resources",
    "/support": "support",
    "/security": "security",
    "/downloads": "downloads",
    "/extension": "extension",
    "/login": "login",
    "/signup": "signup",
    "/verify": "verify",
    "/forgot-password": "forgot",
}
PUBLIC_FAMILIES = {
    "affiliate", "careers", "company", "compare", "contact-sales",
    "contact-support", "customer-stories", "demos", "developer-security",
    "developers", "downloads", "features", "legal", "managed-service-provider-security",
    "newsletter", "partnerships", "password-generator", "platform", "press",
    "pricing", "product", "research", "resources", "security", "solutions",
    "switch", "username-generator", "webinars",
}


@app.get("/api/session")
def session(req: Request):
    ctx = Ctx(req)
    data = {
        "authenticated": bool(ctx.account),
        "account": ctx.account,
    }
    if ctx.account:
        with conn(True) as c:
            wid = wid_for(c, ctx.account)
            data["workspace"] = dict(
                c.execute("SELECT * FROM op_workspaces WHERE id=?", (wid,)).fetchone()
            )
            data["membership"] = biz.membership(c, wid, str(ctx.account["account_id"]))
    return ok(ctx, data)


@app.post("/api/auth/signup")
async def signup(req: Request):
    ctx = Ctx(req)
    d = await body(req)
    try:
        result = auth.start_registration(
            ctx.token,
            email=str(d.get("email", "")),
            display_name=str(d.get("name", "")),
            password=str(d.get("password", "")),
        )
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(
        ctx, {**result, "message": "Verification is available in the local inbox."}, 202
    )


@app.get("/api/auth/local-mail/{purpose}")
def local_mail(req: Request, purpose: str):
    ctx = Ctx(req)
    if purpose not in {"registration", "password-reset"}:
        return fail(ctx, "unknown purpose", 404)
    mail = auth.local_mail_for_session(ctx.token, purpose=purpose)
    return ok(ctx, mail or {"status": "empty"})


@app.post("/api/auth/verify")
async def verify(req: Request):
    ctx = Ctx(req)
    d = await body(req)
    try:
        auth.verify_registration_code(ctx.token, str(d.get("code", "")))
        result = auth.complete_registration(ctx.token)
        ctx.rotate(str(result["session_token"]))
        with conn(True) as c:
            biz.ensure_workspace(c, result["account"])
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(
        ctx,
        {
            "account": result["account"],
            "message": "Account verified and Emergency Kit ready.",
        },
    )


@app.post("/api/auth/login")
async def login(req: Request):
    ctx = Ctx(req)
    d = await body(req)
    if not d:
        d = dict(await req.form())
    try:
        result = auth.sign_in(
            ctx.token,
            email=str(d.get("email", "")),
            password=str(d.get("password", "")),
        )
        ctx.rotate(str(result["session_token"]))
        with conn(True) as c:
            wid = biz.ensure_workspace(c, result["account"])
            if str(result["account"]["email_normalized"]) == DEMO_OWNER:
                member_row = c.execute(
                    "SELECT account_id FROM local_auth_accounts WHERE email_normalized=?",
                    (DEMO_MEMBER,),
                ).fetchone()
                if member_row:
                    mid = str(member_row[0])
                    c.execute(
                        "INSERT OR IGNORE INTO op_memberships VALUES (?,?,?,?,?,?)",
                        (wid, mid, DEMO_MEMBER, "Taylor Member", "member", "active"),
                    )
                    for v in c.execute(
                        "SELECT id FROM op_vaults WHERE workspace_id=? AND name='Shared'",
                        (wid,),
                    ):
                        c.execute(
                            "INSERT OR IGNORE INTO op_vault_access VALUES (?,?,?)",
                            (v[0], mid, "edit"),
                        )
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(ctx, {"account": result["account"], "redirect": "/app/vaults"})


@app.post("/api/auth/logout")
def logout(req: Request):
    ctx = Ctx(req)
    auth.sign_out(ctx.token)
    res = JSONResponse({"ok": True, "data": {"signed_out": True}})
    res.delete_cookie(
        COOKIE,
        path=str(STRICT["path"]),
        secure=bool(STRICT["secure"]),
        httponly=bool(STRICT["httponly"]),
        samesite=str(STRICT["samesite"]),
    )
    if insecure_test_cookie_enabled():
        res.delete_cookie(TEST_COOKIE, path="/", httponly=True, samesite="lax")
    return res


@app.post("/api/auth/reset/start")
async def reset_start(req: Request):
    ctx = Ctx(req)
    d = await body(req)
    try:
        result = auth.start_password_reset(ctx.token, email=str(d.get("email", "")))
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(ctx, result, 202)


@app.post("/api/auth/reset/complete")
async def reset_complete(req: Request):
    ctx = Ctx(req)
    d = await body(req)
    try:
        auth.verify_password_reset_code(ctx.token, str(d.get("code", "")))
        ctx.rotate(
            auth.complete_password_reset(
                ctx.token, new_password=str(d.get("password", ""))
            )
        )
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(ctx, {"message": "Password reset. Other sessions were revoked."})


@app.get("/api/workspace")
def workspace(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    with conn(True) as c:
        wid = wid_for(c, a)
        ws = dict(
            c.execute("SELECT * FROM op_workspaces WHERE id=?", (wid,)).fetchone()
        )
        members = [
            dict(r)
            for r in c.execute(
                "SELECT account_id,email,name,role,status FROM op_memberships WHERE workspace_id=? ORDER BY role,name",
                (wid,),
            )
        ]
    return ok(ctx, {"workspace": ws, "members": members})


@app.get("/api/vaults")
def vaults(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    with conn(True) as c:
        wid = wid_for(c, a)
        values = biz.list_vaults(c, wid, str(a["account_id"]))
    return ok(ctx, values)


@app.post("/api/vaults")
async def vault_create(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    d = await body(req)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            biz.require_workspace(c, wid, str(a["account_id"]), ("owner", "admin"))
            name = str(d.get("name", "")).strip()
            if not name:
                raise ValueError("Vault name is required")
            vid = biz.token("vault")
            c.execute(
                "INSERT INTO op_vaults VALUES (?,?,?,?,?,?)",
                (vid, wid, name, str(d.get("description", "")), 0, biz.now()),
            )
            c.execute(
                "INSERT INTO op_vault_access VALUES (?,?,?)",
                (vid, str(a["account_id"]), "manage"),
            )
            biz.activity(c, wid, str(a["account_id"]), "vault.created", vid)
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(ctx, {"id": vid, "name": name}, 201)


@app.get("/api/items")
def items(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    q = req.query_params
    with conn(True) as c:
        wid = wid_for(c, a)
        values = biz.list_items(
            c,
            wid,
            str(a["account_id"]),
            q.get("q", ""),
            q.get("state", "active"),
            q.get("vault", ""),
            q.get("tag", ""),
            q.get("sort", "updated"),
        )
    return ok(ctx, values)


@app.post("/api/items")
async def item_create(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    d = await body(req)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            value = biz.create_item(c, wid, str(a["account_id"]), d)
    except Exception as e:
        return mapped_error(ctx, e)
    value.pop("secret", None)
    return ok(ctx, value, 201)


@app.get("/api/items/{iid}")
def item_detail(req: Request, iid: str, reveal: int = 0):
    ctx = Ctx(req)
    a = require(ctx)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            value = biz.require_item(c, iid, wid, str(a["account_id"]))
            versions = [
                dict(r)
                for r in c.execute(
                    "SELECT version,created_at FROM op_item_versions WHERE item_id=? ORDER BY version DESC",
                    (iid,),
                )
            ]
    except Exception as e:
        return mapped_error(ctx, e)
    if not reveal:
        value["secret"] = "••••••••••••"
    value["versions"] = versions
    return ok(ctx, value)


@app.put("/api/items/{iid}")
async def item_update(req: Request, iid: str):
    ctx = Ctx(req)
    a = require(ctx)
    d = await body(req)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            value = biz.update_item(c, iid, wid, str(a["account_id"]), d)
    except Exception as e:
        return mapped_error(ctx, e)
    value.pop("secret", None)
    return ok(ctx, value)


@app.post("/api/items/{iid}/duplicate")
def item_duplicate(req: Request, iid: str):
    ctx = Ctx(req)
    a = require(ctx)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            value = biz.duplicate_item(c, iid, wid, str(a["account_id"]))
    except Exception as e:
        return mapped_error(ctx, e)
    value.pop("secret", None)
    return ok(ctx, value, 201)


@app.post("/api/items/{iid}/state/{state}")
def item_state(req: Request, iid: str, state: str):
    ctx = Ctx(req)
    a = require(ctx)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            biz.set_item_state(c, iid, wid, str(a["account_id"]), state)
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(ctx, {"id": iid, "state": state})


@app.delete("/api/items/{iid}")
def item_delete(req: Request, iid: str):
    ctx = Ctx(req)
    a = require(ctx)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            biz.delete_item(c, iid, wid, str(a["account_id"]))
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(ctx, {"deleted": iid})


@app.post("/api/items/{iid}/share")
async def share_item(req: Request, iid: str):
    ctx = Ctx(req)
    a = require(ctx)
    d = await body(req)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            biz.require_item(c, iid, wid, str(a["account_id"]), True)
            recipient = str(d.get("recipient", "")).strip().lower()
            if "@" not in recipient:
                raise ValueError("Recipient email is required")
            sid = biz.token("share")
            c.execute(
                "INSERT INTO op_shares VALUES (?,?,?,?,?,?,?)",
                (
                    sid,
                    iid,
                    wid,
                    recipient,
                    str(d.get("permission", "view")),
                    "local-only",
                    biz.now(),
                ),
            )
            biz.activity(c, wid, str(a["account_id"]), "item.shared", iid)
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(
        ctx,
        {
            "id": sid,
            "status": "local-only",
            "message": "Access recorded locally; no external message was sent.",
        },
        201,
    )


@app.post("/api/members/invite")
async def invite(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    d = await body(req)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            biz.require_workspace(c, wid, str(a["account_id"]), ("owner", "admin"))
            email = str(d.get("email", "")).lower()
            role = str(d.get("role", "member"))
            if "@" not in email or role not in {"admin", "member", "guest"}:
                raise ValueError("Valid email and role are required")
            iid = biz.token("invite")
            c.execute(
                "INSERT INTO op_memberships VALUES (?,?,?,?,?,?)",
                (wid, iid, email, email.split("@")[0], role, "invited"),
            )
            biz.activity(c, wid, str(a["account_id"]), "member.invited", iid)
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(
        ctx,
        {
            "id": iid,
            "status": "invited-local-only",
            "message": "Invitation staged locally; no email was sent.",
        },
        201,
    )


@app.put("/api/members/{mid}/role")
async def role(req: Request, mid: str):
    ctx = Ctx(req)
    a = require(ctx)
    d = await body(req)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            biz.require_workspace(c, wid, str(a["account_id"]), ("owner",))
            new = str(d.get("role", ""))
            if new not in {"admin", "member", "guest"}:
                raise ValueError("Invalid role")
            if mid == str(a["account_id"]):
                raise ValueError("Owner cannot demote self")
            cur = c.execute(
                "UPDATE op_memberships SET role=? WHERE workspace_id=? AND account_id=?",
                (new, wid, mid),
            )
            if cur.rowcount != 1:
                raise LookupError("member not found")
            biz.activity(c, wid, str(a["account_id"]), "member.role", mid)
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(ctx, {"account_id": mid, "role": new})


@app.get("/api/watchtower")
def watchtower(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    with conn(True) as c:
        wid = wid_for(c, a)
        value = biz.password_health(c, wid, str(a["account_id"]))
    return ok(ctx, value)


@app.get("/api/security")
def security(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    with conn(True) as c:
        wid = wid_for(c, a)
        devices = [
            dict(r)
            for r in c.execute(
                "SELECT * FROM op_devices WHERE account_id=? ORDER BY last_seen DESC",
                (a["account_id"],),
            )
        ]
        settings = c.execute(
            "SELECT payload_json FROM op_settings WHERE account_id=?",
            (a["account_id"],),
        ).fetchone()
        events = [
            dict(r)
            for r in c.execute(
                "SELECT action,target,created_at FROM op_activity WHERE workspace_id=? ORDER BY id DESC LIMIT 30",
                (wid,),
            )
        ]
    return ok(
        ctx,
        {
            "devices": devices,
            "settings": json.loads(settings[0])
            if settings
            else {"mfa": False, "alerts": True, "autoLock": 10},
            "activity": events,
        },
    )


@app.post("/api/security/device/{did}/revoke")
def revoke(req: Request, did: str):
    ctx = Ctx(req)
    a = require(ctx)
    with conn(True) as c:
        cur = c.execute(
            "UPDATE op_devices SET revoked=1 WHERE id=? AND account_id=?",
            (did, a["account_id"]),
        )
        if cur.rowcount != 1:
            return fail(ctx, "device not found", 404)
    return ok(ctx, {"id": did, "revoked": True})


@app.put("/api/settings")
async def settings(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    d = await body(req)
    with conn(True) as c:
        c.execute(
            "INSERT INTO op_settings VALUES (?,?,?) ON CONFLICT(account_id) DO UPDATE SET payload_json=excluded.payload_json,updated_at=excluded.updated_at",
            (a["account_id"], json.dumps(d), biz.now()),
        )
    return ok(ctx, d)


@app.get("/api/billing")
def billing(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    with conn(True) as c:
        wid = wid_for(c, a)
        biz.require_workspace(c, wid, str(a["account_id"]))
        value = dict(
            c.execute(
                "SELECT * FROM op_billing WHERE workspace_id=?", (wid,)
            ).fetchone()
        )
    return ok(ctx, {**value, "currency": "USD", "payment_adapter": "local-sandbox"})


@app.post("/api/billing/change")
async def billing_change(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    d = await body(req)
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            biz.require_workspace(c, wid, str(a["account_id"]), ("owner",))
            plan = str(d.get("plan", ""))
            scenario = str(d.get("scenario", "sandbox-approved"))
            if plan not in {"Individual", "Families", "Business"}:
                raise ValueError("Invalid plan")
            if scenario not in {
                "sandbox-approved",
                "sandbox-declined",
                "sandbox-retry",
            }:
                raise ValueError("Invalid sandbox scenario")
            if scenario == "sandbox-declined":
                return fail(ctx, "Simulated payment declined", 402)
            if scenario == "sandbox-retry":
                return fail(ctx, "Simulated temporary payment error; retry safely", 409)
            c.execute(
                "UPDATE op_billing SET plan=?,status='active',updated_at=? WHERE workspace_id=?",
                (plan, biz.now(), wid),
            )
            c.execute("UPDATE op_workspaces SET plan=? WHERE id=?", (plan, wid))
            biz.activity(c, wid, str(a["account_id"]), "billing.changed", plan)
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(ctx, {"plan": plan, "status": "active", "scenario": "sandbox-approved"})


@app.get("/api/export")
def export_items(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    with conn(True) as c:
        wid = wid_for(c, a)
        rows = biz.list_items(c, wid, str(a["account_id"]))
    out = io.StringIO()
    w = csv.writer(out)
    w.writerow(["title", "username", "url", "type", "tags"])
    for x in rows:
        w.writerow(
            [x["title"], x["username"], x["url"], x["type"], ";".join(x["tags"])]
        )
    return StreamingResponse(
        iter([out.getvalue()]),
        media_type="text/csv",
        headers={
            "Content-Disposition": "attachment; filename=1password-offline-export.csv"
        },
    )


@app.post("/api/import")
async def import_items(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    form = await req.form()
    file = form.get("file")
    if not file:
        return fail(ctx, "Choose a CSV file", 400)
    raw = await file.read()
    if len(raw) > 200000:
        return fail(ctx, "File is too large", 413)
    try:
        rows = list(csv.DictReader(io.StringIO(raw.decode("utf-8"))))
    except Exception:
        return fail(ctx, "Invalid UTF-8 CSV", 400)
    made = []
    try:
        with conn(True) as c:
            wid = wid_for(c, a)
            vault = biz.list_vaults(c, wid, str(a["account_id"]))[0]
            for r in rows[:100]:
                made.append(
                    biz.create_item(
                        c,
                        wid,
                        str(a["account_id"]),
                        {
                            "vault_id": vault["id"],
                            "type": r.get("type", "login"),
                            "title": r.get("title", "Imported item"),
                            "username": r.get("username", ""),
                            "url": r.get("url", ""),
                            "secret": "imported-synthetic-secret",
                            "tags": [x for x in r.get("tags", "").split(";") if x],
                        },
                    )
                )
    except Exception as e:
        return mapped_error(ctx, e)
    return ok(ctx, {"imported": len(made), "status": "complete"}, 201)


@app.get("/api/emergency-kit")
def emergency(req: Request):
    ctx = Ctx(req)
    a = require(ctx)
    text = f"1Password Offline Emergency Kit\nAccount: {a['email_normalized']}\nSign-in address: http://127.0.0.1\nSecret Key: LOCAL-DEMO-{secrets.token_hex(6).upper()}\nKeep this synthetic kit private."
    return StreamingResponse(
        iter([text]),
        media_type="text/plain",
        headers={
            "Content-Disposition": "attachment; filename=Emergency-Kit-demo.txt",
            "Cache-Control": "no-store",
        },
    )


@app.get("/api/generate-password")
def generate(length: int = 20, words: int = 0):
    if words:
        pool = [
            "anchor",
            "cobalt",
            "ember",
            "forest",
            "harbor",
            "juniper",
            "lantern",
            "meadow",
            "orbit",
            "quartz",
            "raven",
            "willow",
        ]
        return {
            "ok": True,
            "data": {
                "password": "-".join(
                    secrets.choice(pool) for _ in range(max(3, min(words, 8)))
                )
            },
        }
    alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%"
    return {
        "ok": True,
        "data": {
            "password": "".join(
                secrets.choice(alphabet) for _ in range(max(12, min(length, 64)))
            )
        },
    }


@app.get("/{path:path}", response_class=HTMLResponse)
def shell(request: Request, path: str = ""):
    route = "/" + path
    authenticated_routes = {
        "/home",
        "/app",
        "/billing",
        "/billing/payments",
        "/integrations",
        "/developer-tools",
        "/apps",
        "/import",
    }
    if (
        route in authenticated_routes
        or route.startswith("/app/")
        or route.startswith("/vaults/details/")
    ):
        page = "app"
    elif route in PUBLIC:
        page = PUBLIC[route]
    elif path in {"pricing/enterprise", "pricing/business", "pricing/personal"}:
        page = "pricing"
    elif path.split("/", 1)[0] in PUBLIC_FAMILIES:
        page = "generic"
    else:
        return HTMLResponse("<h1>404</h1><a href='/'>Return home</a>", 404)
    html = (ROOT / "index.html").read_text()
    return HTMLResponse(
        html.replace("__PAGE__", page).replace("__ROUTE__", html_escape(route))
    )


def html_escape(value: str) -> str:
    return html.escape(value, quote=True)