Spaces:
Running

File size: 9,732 Bytes
25834e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

URL and input validators — framework-agnostic, pure functions.



All validators are stateless; any external data (e.g. blocked URL patterns)

must be passed in as arguments so the service/repository layer controls

caching and DB access.

"""

from __future__ import annotations

import re
from collections.abc import Sequence
from urllib.parse import unquote, urlparse

import emoji
import regex
import validators as _validators

from app.infrastructure.logging import get_logger

log = get_logger(__name__)

_ALLOWED_URL_SCHEMES = frozenset({"http", "https"})


def is_self_referential(host: str | None, blocked_self_domains: Sequence[str]) -> bool:
    """Return True when *host* is one of *blocked_self_domains* or a subdomain.



    Host-scoped on purpose. A destination is only a redirect loop when the

    request would come back to us, which is decided by the host alone — a

    blocked name appearing in a path or query string ("?filter=spoo.me") is

    someone else's URL that happens to mention us.

    """
    if not host:
        return False
    host = host.lower().rstrip(".")
    return any(
        host == domain or host.endswith(f".{domain}")
        for domain in (d.lower().strip().rstrip(".") for d in blocked_self_domains)
    )


def validate_url(

    url: str,

    blocked_self_domains: Sequence[str] = ("spoo.me",),

) -> bool:
    """Return True if *url* is a valid, non-self-referential http(s) URL.



    Args:

        url: The URL string to validate.

        blocked_self_domains: Bare hostnames that mark the URL as

            self-referential when they are the destination's HOST (or a

            parent of it). Defaults to ``("spoo.me",)`` to prevent redirect

            loops. Matching is host-scoped: a destination that merely

            mentions the name in its path or query is not a loop.

    """
    # Scheme allowlist defends against the validators package widening upstream;
    # urlparse raises on malformed bracket hosts ("https://x]:80/") — not a 500.
    try:
        parsed = urlparse(url)
    except ValueError:
        return False
    if parsed.scheme not in _ALLOWED_URL_SCHEMES:
        return False
    if not _validators.url(url, skip_ipv4_addr=True, skip_ipv6_addr=True):
        return False
    # hostname is already lowercased and strips any userinfo/port, so
    # "https://spoo.me:443@evil.com" can't smuggle the check either way.
    return not is_self_referential(parsed.hostname, blocked_self_domains)


def validate_url_password(password: str, min_length: int = 8) -> bool:
    """Validate a URL password.



    Rules:

    - At least *min_length* characters (default 8)

    - Contains at least one letter

    - Contains at least one digit

    - Contains at least one of ``@`` or ``.``

    - No two consecutive special characters (``@@``, ``..``, ``@.``, ``.@``)



    Returns:

        True if the password meets all requirements.

    """
    if len(password) < min_length:
        return False
    if not re.search(r"[a-zA-Z]", password):
        return False
    if not re.search(r"\d", password):
        return False
    if not re.search(r"[@.]", password):
        return False
    return not re.search(r"[@.]{2}", password)


def validate_alias(alias: str) -> bool:
    """Return True if *alias* contains only alphanumeric characters, ``-``, or ``_``."""
    return bool(re.search(r"^[a-zA-Z0-9_-]*$", alias))


def is_emoji_alias(alias: str) -> bool:
    """Return True if *alias* consists entirely of emoji characters.



    Deliberately lenient (no length cap, no policy): used for URL

    resolution/dispatch where any previously-created emoji alias must

    stay routable regardless of the current creation policy. Creation

    validation lives in ``shared.emoji_policy``.

    """
    decoded = unquote(alias)
    if not decoded:
        return False
    emoji_list = emoji.emoji_list(decoded)
    extracted = "".join([data["emoji"] for data in emoji_list])
    return extracted == decoded


def validate_account_password(

    password: str,

    min_length: int = 8,

    max_length: int = 128,

) -> tuple[bool, list[str], int]:
    """Validate a user account password.



    Args:

        password:   The password to validate.

        min_length: Minimum required length (default 8).

        max_length: Maximum allowed length (default 128).



    Returns:

        (is_valid, missing_requirements, strength_score)

    """
    if not password:
        return False, ["Password is required"], 0

    missing: list[str] = []
    strength_score = 0

    if len(password) < min_length:
        missing.append(f"At least {min_length} characters")
    else:
        strength_score += 20

    if len(password) > max_length:
        missing.append(f"Maximum {max_length} characters")
    else:
        strength_score += 10

    if not re.search(r"[A-Z]", password):
        missing.append("At least one uppercase letter")
    else:
        strength_score += 15

    if not re.search(r"[a-z]", password):
        missing.append("At least one lowercase letter")
    else:
        strength_score += 15

    if not re.search(r"[0-9]", password):
        missing.append("At least one number")
    else:
        strength_score += 15

    if not re.search(r'[!@#$%^&*()_+\-=\[\]{};\':"\\|,.<>\/?~`]', password):
        missing.append("At least one special character")
    else:
        strength_score += 15

    if not re.match(
        r'^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};\':"\\|,.<>\/?~`\s]+$', password
    ):
        missing.append("Contains invalid characters")
    else:
        strength_score += 10

    if len(password) >= 12:
        strength_score += 5
    if len(password) >= 16:
        strength_score += 5

    if re.search(r"(.)\1{2,}", password):
        strength_score -= 10

    if re.search(
        r"(012|123|234|345|456|567|678|789|890|abc|bcd|cde|def)", password.lower()
    ):
        strength_score -= 15

    for pattern in [r"password", r"123456", r"qwerty", r"admin", r"login", r"welcome"]:
        if re.search(pattern, password.lower()):
            strength_score -= 20
            break

    return len(missing) == 0, missing, strength_score


def validate_blocked_url(

    url: str, patterns: Sequence[str], timeout: float = 0.2

) -> bool:
    """Return True if *url* does NOT match any blocked pattern.



    This is a pure function — the caller is responsible for providing the

    list of blocked URL regex patterns (typically loaded from the database

    and cached by the repository layer).



    Uses the ``regex`` library with a per-pattern timeout to prevent ReDoS

    attacks on user-supplied patterns.



    Args:

        url:      The URL to check.

        patterns: Iterable of regex pattern strings to match against.

        timeout:  Per-pattern regex timeout in seconds (default 0.2).



    Returns:

        True if the URL is allowed (no pattern matched), False if blocked.

    """
    return matching_blocked_pattern(url, patterns, timeout=timeout) is None


def is_valid_pattern(pattern: str) -> bool:
    """Whether *pattern* compiles. Model- and operator-supplied regexes are

    never handed to the matcher unchecked: a bad one raises at enforcement

    time, after the verdict is already stored."""
    if not pattern:
        return False
    try:
        regex.compile(pattern)
    except Exception:
        return False
    return True


def matching_blocked_pattern(

    url: str, patterns: Sequence[str], timeout: float = 0.2

) -> str | None:
    """Return the first blocked pattern that matches *url*, or None; safety

    enforcement scopes its action to that pattern."""
    for pattern in patterns:
        try:
            if regex.search(pattern, url, timeout=timeout):
                return pattern
        except regex.error:
            log.warning("blocked_pattern_invalid", pattern=pattern)
        except TimeoutError:
            # Fail open (a pathological pattern must not take down link
            # creation) but never silently: a timing-out pattern is an
            # operator blocklist entry that has stopped enforcing.
            log.warning(
                "blocked_pattern_timeout", pattern=pattern, timeout_seconds=timeout
            )
    return None


def validate_safe_redirect(url: str, fallback: str = "/dashboard") -> str:
    """Return *url* if it's a safe relative path, otherwise *fallback*.



    Only allows paths starting with ``/`` that don't redirect to an external

    host. Blocks ``//evil.com``, ``/\\evil.com``, and scheme-prefixed URLs.

    """
    if not url or not url.startswith("/"):
        return fallback
    parsed = urlparse(url)
    if parsed.scheme or parsed.netloc:
        return fallback
    return url


_OBJECT_ID_RE = re.compile(r"^[0-9a-f]{24}$")


def normalise_object_ids(

    v: object, *, cap: int | None = None, noun: str = "ids"

) -> object:
    """Shape-check an id list for a DTO: 24-hex strings, deduped first-wins,

    optionally capped. Non-lists pass through so Pydantic reports the type."""
    if v is None or not isinstance(v, list):
        return v
    seen: set[str] = set()
    out: list[str] = []
    for item in v:
        if not isinstance(item, str) or not _OBJECT_ID_RE.fullmatch(item):
            raise ValueError(f"'{item}' is not a valid id")
        if item not in seen:
            seen.add(item)
            out.append(item)
    if cap is not None and len(out) > cap:
        raise ValueError(f"at most {cap} {noun}")
    return out