File size: 12,720 Bytes
7f8e190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Account, session and recovery flows for the LeetCode offline clone.

Every credential, challenge and session fact is owned by the vendored
``websitebench.local_clone_auth`` store opened through
``backend/site_backend_integration.py``. This module only adds the site's own
vocabulary on top of it: a username, the human-verification widget, and the
copy the pages show.
"""

from __future__ import annotations

import hmac
import hashlib
import re
import sqlite3
from typing import Any

from websitebench.local_clone_auth import (
    AuthConflict,
    AuthError,
    AuthExpired,
    AuthLocked,
    AuthRateLimited,
    AuthRejected,
    AuthValidationError,
)

from . import store


USERNAME_RE = re.compile(r"^[A-Za-z0-9_-]{3,30}$")
VERIFICATION_FIELD = "human_verification"
VERIFICATION_CHECKBOX = "human_check"

RESET_PUBLIC_MESSAGE = (
    "If that address belongs to a LeetCode account, a verification code is on "
    "its way."
)


class FormError(Exception):
    """A field-level validation failure to render back into the form."""

    def __init__(self, errors: dict[str, str]) -> None:
        self.errors = errors
        super().__init__("; ".join(f"{key}: {value}" for key, value in errors.items()))


def services() -> tuple[Any, Any]:
    return store.services()


def session_cookie_settings() -> dict[str, Any]:
    backend, _ = services()
    return dict(backend.session_cookie)


def mail_template(purpose: str) -> dict[str, Any]:
    backend, _ = services()
    return dict(backend.config.mail["purposes"][purpose])


def sender_display_name() -> str:
    backend, _ = services()
    return str(backend.config.mail["sender"]["display_name"])


# ---------------------------------------------------------------------------
# human verification widget (local only)
# ---------------------------------------------------------------------------


def verification_token(session_token: str) -> str:
    """A per-session token for the local human-verification widget.

    The widget reproduces the source page's challenge slot and its local
    semantics only: the server issues a token bound to this session and
    refuses a submission that does not carry it back. Nothing is fetched from,
    or validated against, any third-party challenge service.
    """

    _, auth = services()
    digest = auth.session_owner_digest(session_token)
    return hashlib.sha256(f"leetcode-verification\0{digest}".encode()).hexdigest()[:32]


def verification_ok(session_token: str, form: dict[str, str]) -> bool:
    supplied = str(form.get(VERIFICATION_FIELD, ""))
    checked = str(form.get(VERIFICATION_CHECKBOX, "")).strip().casefold()
    if checked not in {"on", "true", "1", "yes"}:
        return False
    try:
        expected = verification_token(session_token)
    except AuthError:
        return False
    return hmac.compare_digest(expected, supplied)


# ---------------------------------------------------------------------------
# sessions
# ---------------------------------------------------------------------------


def ensure_session(token: str | None) -> tuple[str, dict[str, Any]]:
    _, auth = services()
    return auth.ensure_session(token)


def current_member(session_info: dict[str, Any]) -> dict[str, Any] | None:
    account = session_info.get("account")
    if not account:
        return None
    profile = store.profile_for_subject(str(account["subject_id"]))
    if profile is None:
        return None
    return {
        "subject_id": profile["subject_id"],
        "username": profile["username"],
        "email": profile["email_normalized"],
    }


# ---------------------------------------------------------------------------
# registration
# ---------------------------------------------------------------------------


def validate_signup(form: dict[str, str]) -> dict[str, str]:
    username = str(form.get("username", "")).strip()
    password = str(form.get("password", ""))
    confirm = str(form.get("confirm_password", ""))
    email = str(form.get("email", "")).strip()
    errors: dict[str, str] = {}
    if not username:
        errors["username"] = "Username is required."
    elif USERNAME_RE.fullmatch(username) is None:
        errors["username"] = (
            "Use 3 to 30 letters, digits, hyphens or underscores."
        )
    elif store.username_taken(username):
        errors["username"] = "That username is already taken."
    if not password:
        errors["password"] = "Password is required."
    elif len(password) < 8:
        errors["password"] = "Password must contain at least 8 characters."
    if confirm != password:
        errors["confirm_password"] = "The two passwords do not match."
    if not email:
        errors["email"] = "E-mail address is required."
    if errors:
        raise FormError(errors)
    return {"username": username, "password": password, "email": email}


def start_signup(session_token: str, form: dict[str, str]) -> dict[str, Any]:
    values = validate_signup(form)
    _, auth = services()
    try:
        result = auth.start_registration(
            session_token,
            email=values["email"],
            display_name=values["username"],
            password=values["password"],
            restart_invalid_flow=True,
        )
    except AuthValidationError as error:
        raise FormError({"email": _readable(error)}) from error
    except AuthConflict:
        raise FormError(
            {"email": "An account already exists for that e-mail address."}
        ) from None
    except AuthRateLimited as error:
        raise FormError(
            {
                "email": (
                    "Please wait "
                    f"{error.retry_after} seconds before requesting another code."
                )
            }
        ) from None
    return {"pending_id": result["pending_id"], "email": values["email"]}


def confirm_signup(session_token: str, code: str) -> str:
    """Verify the emailed code and create the account plus its member row.

    The username the visitor chose is carried by the auth store's own pending
    registration record (its ``display_name``), so nothing about a half-finished
    sign-up has to live in a second cookie or table.
    """

    _, auth = services()
    try:
        auth.verify_registration_code(session_token, code)
    except AuthValidationError:
        raise FormError({"code": "Enter the six-digit verification code."}) from None
    except AuthLocked:
        raise FormError(
            {"code": "Too many attempts. Start the sign-up again."}
        ) from None
    except AuthExpired:
        raise FormError({"code": "That code expired. Request a new one."}) from None
    except AuthRejected:
        raise FormError({"code": "That code is not correct."}) from None

    def _subject_factory(
        connection: sqlite3.Connection, registration: dict[str, Any]
    ) -> str:
        return store.create_profile(
            connection,
            account_id=str(registration["account_id"]),
            username=str(registration["display_name"]),
            email=str(registration["email"]),
        )

    try:
        result = auth.complete_registration(
            session_token, subject_factory=_subject_factory
        )
    except sqlite3.IntegrityError:
        raise FormError({"username": "That username is already taken."}) from None
    except AuthConflict:
        raise FormError(
            {"email": "An account already exists for that e-mail address."}
        ) from None
    except AuthRejected as error:
        raise FormError({"code": _readable(error)}) from None
    return str(result["session_token"])


# ---------------------------------------------------------------------------
# sign in / sign out
# ---------------------------------------------------------------------------


def sign_in(session_token: str, form: dict[str, str]) -> str:
    identifier = str(form.get("login", "")).strip()
    password = str(form.get("password", ""))
    errors: dict[str, str] = {}
    if not identifier:
        errors["login"] = "Username or e-mail is required."
    if not password:
        errors["password"] = "Password is required."
    if errors:
        raise FormError(errors)
    _, auth = services()
    try:
        result = auth.sign_in(
            session_token,
            email=store.resolve_login_email(identifier),
            password=password,
        )
    except (AuthRejected, AuthValidationError):
        raise FormError(
            {"form": "The username, e-mail or password is not correct."}
        ) from None
    return str(result["session_token"])


def sign_out(session_token: str | None) -> None:
    _, auth = services()
    auth.sign_out(session_token)


# ---------------------------------------------------------------------------
# password recovery
# ---------------------------------------------------------------------------


def start_password_reset(session_token: str, email: str) -> None:
    _, auth = services()
    if not email.strip():
        raise FormError({"email": "E-mail address is required."})
    try:
        auth.start_password_reset(
            session_token, email=email, restart_invalid_flow=True
        )
    except AuthValidationError:
        raise FormError({"email": "Enter a valid e-mail address."}) from None
    except AuthRateLimited as error:
        raise FormError(
            {
                "email": (
                    "Please wait "
                    f"{error.retry_after} seconds before requesting another code."
                )
            }
        ) from None


def confirm_password_reset(session_token: str, code: str, new_password: str) -> str:
    errors: dict[str, str] = {}
    if not code.strip():
        errors["code"] = "Enter the six-digit verification code."
    if len(new_password) < 8:
        errors["password"] = "Password must contain at least 8 characters."
    if errors:
        raise FormError(errors)
    _, auth = services()
    try:
        auth.verify_password_reset_code(session_token, code)
    except AuthValidationError:
        raise FormError({"code": "Enter the six-digit verification code."}) from None
    except AuthLocked:
        raise FormError(
            {"code": "Too many attempts. Start the reset again."}
        ) from None
    except AuthExpired:
        raise FormError({"code": "That code expired. Request a new one."}) from None
    except AuthRejected:
        raise FormError({"code": "That code is not correct."}) from None
    try:
        return str(
            auth.complete_password_reset(session_token, new_password=new_password)
        )
    except AuthValidationError as error:
        raise FormError({"password": _readable(error)}) from None
    except AuthRejected as error:
        raise FormError({"code": _readable(error)}) from None


# ---------------------------------------------------------------------------
# local message delivery
# ---------------------------------------------------------------------------


def pending_signup_stage(session_token: str) -> bool:
    """Whether this session has a registration challenge waiting for a code."""

    return flow_status(session_token, "registration").get("state") in {
        "challenge",
        "verified",
    }


def pending_message(session_token: str, purpose: str) -> dict[str, Any] | None:
    """Render the message this device would receive for the current flow."""

    _, auth = services()
    record = auth.local_mail_for_session(session_token, purpose=purpose)
    if record is None:
        return None
    template = mail_template(purpose)
    variables = {"code": str(record["verification_code"]), "minutes": "10"}
    return {
        "purpose": purpose,
        "sender": sender_display_name(),
        "recipient": record["recipient"],
        "subject": _fill(template["subject"], variables),
        "lead": _fill(template["lead"], variables),
        "body": _fill(template["body"], variables),
        "expiry": _fill(template["expiry"], variables),
        "footer": _fill(template["footer"], variables),
        "code": variables["code"],
    }


def flow_status(session_token: str, purpose: str) -> dict[str, Any]:
    _, auth = services()
    return auth.session_flow_status(session_token, purpose=purpose)


def _fill(text: str, variables: dict[str, str]) -> str:
    filled = text
    for key, value in variables.items():
        filled = filled.replace("${" + key + "}", value).replace("$" + key, value)
    return filled


def _readable(error: Exception) -> str:
    message = str(error).strip()
    if not message:
        return "That value is not valid."
    return message[0].upper() + message[1:] + ("" if message.endswith(".") else ".")