falseok 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
falseok/page.py ADDED
@@ -0,0 +1,768 @@
1
+ """Page check: is this "200 OK" page real content, or a block page in disguise?"""
2
+ from __future__ import annotations
3
+
4
+ import gzip
5
+ import json
6
+ import re
7
+ import sys
8
+ import zlib
9
+ from dataclasses import dataclass, field
10
+ from html import unescape
11
+ from importlib import resources
12
+ from typing import List, Optional, Union
13
+
14
+ # When several signals fire, the strongest category wins.
15
+ PRIORITY = [
16
+ "challenge",
17
+ "captcha",
18
+ "rate_limited",
19
+ "login_wall",
20
+ "consent_wall",
21
+ "soft_block",
22
+ "soft_404",
23
+ "empty_shell",
24
+ ]
25
+ VERDICTS = ["ok", "not_html", *PRIORITY, "http_error"]
26
+
27
+ # A rule without its own max_text only counts on pages with at most this much visible text.
28
+ # Real block pages measured so far carry 0 to ~2,000 characters; real content pages carry far more.
29
+ DEFAULT_MAX_TEXT = 3000
30
+
31
+ # Measured on 530 real pages: real content under 300 characters of text came with at most 19 scripts, while
32
+ # apps that never rendered (only their menu or footer visible) came with 24 to 52.
33
+ SHELL_TEXT = 300
34
+ SHELL_SCRIPTS = 20
35
+ # ... but a pile of scripts alone is no proof: on 438 more real pages three small ones (176 to 284 characters, 24 to 33
36
+ # scripts) were complete. Above min_text the page also has to show that its content is missing (_Page.not_rendered):
37
+ # the shells measured kept at most 89 characters outside header, menus and footer, the three real pages 176+.
38
+ SHELL_FRAME_TEXT = 120
39
+ # A login box beside the page's own content is not a login wall: on 438 real pages a home page carried 1,405
40
+ # characters outside its forms, the login-only pages at most 284.
41
+ LOGIN_SIDE_TEXT = 800
42
+ # The same failure with a menu and a footer around it: the page passes the text test only thanks to them, while its
43
+ # <main> holds next to no text and not one link. On 798 real pages every such page under MAIN_PAGE_TEXT characters was a skeleton waiting for its scripts (room,
44
+ # search and home pages of two travel sites, 694 to 1,744 characters); real pages that leave <main> empty carried 4,474+.
45
+ MAIN_PAGE_TEXT = 3000
46
+ # Content can also sit beside <main>: on 962 pages of 39 languages the skeletons carried at most 461 characters
47
+ # outside <main>, the page header, menus and footer (an app-install notice); a real home page with its weather
48
+ # report there, 804.
49
+ SIDE_TEXT = 600
50
+
51
+ # The page is read with a few regular expressions, not an HTML parser: same text, about 5 times faster, and the same
52
+ # result on every Python version (the standard library parser changed its rules for <script> and friends in 2025).
53
+
54
+
55
+ # Python 3.11 brought atomic groups and possessive quantifiers ("never give back what you matched"). Older versions get
56
+ # the same behaviour from a lookahead + backreference: the same matches, about a fifth slower on the tag passes.
57
+ _ATOMIC = sys.version_info >= (3, 11)
58
+
59
+
60
+ def _attrs(name: str) -> str:
61
+ """A tag's attributes, up to its ">". Quotes count only after "=" (a quoted value may hold ">"), like a browser.
62
+ The value match is atomic: no slow backtracking on a tag that never closes."""
63
+ if _ATOMIC:
64
+ return r"""[^>=]*+(?:=[\t\n\r\f ]*+(?>"[^"]*"|'[^']*'|)[^>=]*+)*+"""
65
+ return r"""[^>=]*(?:=[\t\n\r\f ]*(?=(?P<%s>"[^"]*"|'[^']*'|))(?P=%s)[^>=]*)*""" % (name, name)
66
+
67
+
68
+ def _anycase(names: str) -> str:
69
+ """Tag names as [sS][cC][rR]... instead of re.I: about a third faster, and HTML tag names are ASCII anyway."""
70
+ return re.sub(r"(?<!\\)[a-z]", lambda m: f"[{m.group(0)}{m.group(0).upper()}]", names)
71
+
72
+
73
+ # Elements whose content is never read as tags; a browser shows the text of the last five but not of script/style.
74
+ _RAW = ("script", "style", "xmp", "iframe", "noembed", "noframes", "textarea", "title")
75
+ # Every tag pattern below also ends at the end of the page (\Z): a tag that never closes runs to the end, as in a
76
+ # browser, and the search never restarts from each "<" (a page of 10,000 unclosed tags would take minutes).
77
+ # The first pass also finds noscript/template tags: their content is never shown (they nest: web components put
78
+ # templates in templates).
79
+ # (The names are written as a tree behind a first-letter check: this pattern is tried at every "<" of the page.)
80
+ _OPEN = re.compile(r"<(?:!--|(?=[sSxXiInNtT])(?P<raw>%s)(?=[\s/>])%s(?:>|\Z)"
81
+ r"|(?P<end>/?)(?=[nNtT])(?P<skip>%s)(?=[\s/>])[^>]*(?:>|\Z))"
82
+ % (_anycase(r"s(?:cript|tyle)|xmp|iframe|no(?:embed|frames)|t(?:extarea|itle)"), _attrs("a"),
83
+ _anycase("noscript|template")))
84
+ _CLOSE = {t: re.compile(r"</%s(?=[\s/>])[^>]*(?:>|\Z)" % _anycase(t)) for t in _RAW}
85
+ _COMMENT_END = re.compile(r"--!?>")
86
+ # Never shown either: an <svg> up to its end, or up to a page tag when it was never closed (atomic again).
87
+ _SVG = re.compile(
88
+ (r"<%s(?=[\s/>])(?:[^>]*?/>|(?:[^<]++|<(?!/%s|(?:%s)[\s/>]))*+(?:</%s[^>]*(?:>|\Z))?)" if _ATOMIC else
89
+ r"<%s(?=[\s/>])(?:[^>]*?/>|(?=(?P<s>(?:[^<]+|<(?!/%s|(?:%s)[\s/>]))*))(?P=s)(?:</%s[^>]*(?:>|\Z))?)")
90
+ % (_anycase("svg"), _anycase("svg"), _anycase("body|main|article|section|p|div|h1|h2|h3|ul|table|footer"), _anycase("svg")))
91
+ # Tags that break a line in a browser (written as a tree for speed): text on both sides must not glue together.
92
+ _BLOCK_TAG = re.compile(r"</?(?:%s)(?=[\t\n\r\f />])%s(?:>|\Z)" % (_anycase(
93
+ r"a(?:ddress|rticle|side)|b(?:lockquote|ody|r|utton)|d(?:d|etails|i(?:alog|v)|l|t)|f(?:i(?:eldset|g(?:caption|ure))"
94
+ r"|o(?:oter|rm))|h(?:[1-6]|eader|r|tml)|i(?:mg|nput)|l(?:abel|egend|i)|main|nav|o(?:l|ption)|p(?:re)?|s(?:e(?:ction|lect)"
95
+ r"|ummary)|t(?:able|body|d|extarea|foot|h(?:ead)?|itle|r)|ul"), _attrs("a")))
96
+ _ANY_TAG = re.compile(r"<(?:/?[a-zA-Z]|[!?])%s(?:>|\Z)|</(?![a-zA-Z])[^>]*(?:>|\Z)" % _attrs("a"))
97
+ # <input> tags, then their attributes one by one (name, optional value), the way a browser reads them.
98
+ _INPUT_TAG = re.compile(r"<%s(?=[\t\n\r\f />])(%s)(?:>|\Z)" % (_anycase("input"), _attrs("a")))
99
+ _MAIN_OPEN = re.compile(r"<%s(?=[\t\n\r\f />])%s(?:>|\Z)" % (_anycase("main"), _attrs("a")))
100
+ _MAIN_CLOSE = re.compile(r"</%s(?=[\t\n\r\f />])[^>]*(?:>|\Z)" % _anycase("main"))
101
+ # The page's frame around its content: header, menus, footer.
102
+ _FRAME_OPEN = re.compile(r"<(%s)(?=[\t\n\r\f />])%s(?:>|\Z)" % (_anycase("header|nav|footer"), _attrs("a")))
103
+ _FRAME_CLOSE = {t: re.compile(r"</%s(?=[\t\n\r\f />])[^>]*(?:>|\Z)" % _anycase(t)) for t in ("header", "nav", "footer")}
104
+ _PAGE_LANDMARK = re.compile(r"<(?:%s)(?=[\t\n\r\f />])" % _anycase("header|nav|footer|main|article"))
105
+ _ARTICLE_OPEN = re.compile(r"<%s(?=[\t\n\r\f />])" % _anycase("article"))
106
+ _ARTICLE_CLOSE = re.compile(r"</%s(?=[\t\n\r\f />])[^>]*(?:>|\Z)" % _anycase("article"))
107
+ # Input types that are not a field a visitor types into.
108
+ _NOT_FIELD = ("hidden", "submit", "button", "checkbox", "radio", "file", "image", "reset")
109
+ _HEADING_OPEN = re.compile(r"<[hH][12]%s>" % _attrs("a"))
110
+ _HEADING_END = re.compile(r"</[hH][1-6](?=[\t\n\r\f />])")
111
+ _LINK_TAG = re.compile(r"<[aA](?=[\t\n\r\f />])(%s)(?:>|\Z)" % _attrs("a"))
112
+ _ATTR = re.compile(r"""([^\t\n\r\f />"'=][^\t\n\r\f /=>]*)(?:[\t\n\r\f ]*=[\t\n\r\f ]*("[^"]*"|'[^']*'|[^>\t\n\r\f ]*))?""")
113
+ _MOUNT = re.compile(r"""id\s*=\s*["']?(?:root|app|__next|__nuxt|svelte|main-app)["'\s/>]""")
114
+ # Proof that a page's content never arrived: its app's mount point left empty, or a template never filled in.
115
+ _EMPTY_MOUNT = re.compile(r"""id\s*=\s*["']?(?:root|app|__next|__nuxt|svelte|main-app)["']?(?=[\s/>])[^>]*>\s*</""")
116
+ _NOT_RENDERED = re.compile(r"\{\{[^{}]{1,80}\}\}|\bloading\b", re.I)
117
+ # A loading note in the words real stuck pages used ("Loading...", Finnish "Ladataan").
118
+ _LOADING = re.compile(r"\bloading\.\.\.|\bladataan\b", re.I)
119
+ _FORM = re.compile(r"<%s(?=[\t\n\r\f />]).*?(?:</%s[^>]*>|\Z)" % (_anycase("form"), _anycase("form")), re.S)
120
+ # Curly quotes and "…" become plain ones, so "isn’t" matches a rule written as "isn't". (\s+ already turns nbsp into a space.)
121
+ _PLAIN = {"’": "'", "‘": "'", "ʼ": "'", "“": '"', "”": '"', "…": "...", "\u200b": ""}
122
+ _PLAIN_RX = re.compile("[%s]" % "".join(_PLAIN))
123
+ _BAD_CHAR = re.compile("[\x00-\x08\x0b\x0e-\x1f\ufffd]")
124
+
125
+ @dataclass
126
+ class Signal:
127
+ id: str
128
+ category: str
129
+ detail: str
130
+ vendor: Optional[str] = None
131
+
132
+
133
+ @dataclass
134
+ class PageResult:
135
+ verdict: str # one of VERDICTS
136
+ reason: str
137
+ signals: List[Signal] = field(default_factory=list)
138
+ vendor: Optional[str] = None
139
+ title: str = ""
140
+ text_length: int = 0
141
+
142
+ @property
143
+ def ok(self) -> bool:
144
+ return self.verdict == "ok"
145
+
146
+ def to_dict(self) -> dict:
147
+ return {
148
+ "verdict": self.verdict,
149
+ "reason": self.reason,
150
+ "vendor": self.vendor,
151
+ "title": self.title,
152
+ "text_length": self.text_length,
153
+ "signals": [s.__dict__ for s in self.signals],
154
+ }
155
+
156
+
157
+ class _Page:
158
+ """The page roughly as a browser shows it: the title, the visible text, a few counts."""
159
+
160
+ def __init__(self, raw: str) -> None:
161
+ out: List[str] = []
162
+ hidden: List[tuple] = [] # noscript/template parts, as (first, last) indexes into out
163
+ pos, n, title, depth, first, scripts = 0, len(raw), None, 0, 0, 0
164
+ search, append = _OPEN.search, out.append # local names: this loop runs hundreds of times a page
165
+ while True:
166
+ m = search(raw, pos)
167
+ if not m:
168
+ break
169
+ start, end = m.span()
170
+ append(raw[pos:start])
171
+ pos = end
172
+ kind = m.lastgroup # "skip" for noscript/template, "raw" for a raw element, None for a comment
173
+ if kind == "skip":
174
+ if not m.group("end"):
175
+ if not depth:
176
+ first = len(out)
177
+ depth += 1
178
+ append(m.group(0))
179
+ else:
180
+ append(m.group(0))
181
+ if depth:
182
+ depth -= 1
183
+ if not depth:
184
+ hidden.append((first, len(out)))
185
+ continue
186
+ if kind is None: # a comment
187
+ e = _COMMENT_END.search(raw, pos)
188
+ pos = e.end() if e else n
189
+ continue
190
+ tag = m.group("raw").lower()
191
+ e = _CLOSE[tag].search(raw, pos)
192
+ if e:
193
+ stop, pos = e.span()
194
+ else:
195
+ stop = pos = n
196
+ if tag == "script":
197
+ scripts += 1
198
+ append(m.group(0) + "</script>")
199
+ continue
200
+ body = raw[end:stop]
201
+ append(m.group(0))
202
+ if tag == "title" and title is None:
203
+ title = body
204
+ append(" ")
205
+ elif tag != "style":
206
+ # Shown as written, tags included: escaped here so the tag passes below leave it alone.
207
+ if tag != "textarea" and tag != "title": # raw text: its "&amp;" stays "&amp;"
208
+ body = body.replace("&", "&amp;")
209
+ append(body.replace("<", "&lt;"))
210
+ append(f"</{tag}>")
211
+ self.scripts = scripts
212
+ out.append(raw[pos:])
213
+ if depth:
214
+ hidden.append((first, len(out)))
215
+ self.markup = "".join(out) # the page without comments and without script/style content
216
+ shown = self.markup
217
+ if hidden:
218
+ parts, prev = [], 0
219
+ for a, b in hidden:
220
+ parts.append("".join(out[prev:a]))
221
+ # A hidden part still breaks the line if it holds a block tag.
222
+ parts.append(" " if _BLOCK_TAG.search("".join(out[a:b])) else "")
223
+ prev = b
224
+ parts.append("".join(out[prev:]))
225
+ shown = "".join(parts)
226
+ self.shown = shown # the markup a browser lays out: no comments, no script/style content, no hidden parts
227
+ self.title = _squash(unescape(title or ""))
228
+ self.text = _visible(shown)
229
+
230
+ @property
231
+ def headings(self) -> List[str]:
232
+ """The text of the page's first <h1> and <h2> headings (short ones: a heading is a line, not a paragraph).
233
+ Found with plain string search, and only a bounded number is looked at: cheap on any page."""
234
+ found: List[str] = []
235
+ shown, tries = self.shown, 0
236
+ for mark in ("<h", "<H"):
237
+ at = shown.find(mark)
238
+ while at >= 0 and tries < 400 and len(found) < 40:
239
+ if shown[at + 2:at + 3] in ("1", "2") and shown[at + 3:at + 4] in ("\t", "\n", "\r", "\f", " ", "/", ">"):
240
+ tries += 1
241
+ piece = shown[at:at + 700]
242
+ if ("<svg" in piece or "<SVG" in piece) and not _HEADING_END.search(piece):
243
+ # An inline icon is not text: measured without it, the heading may still be a short line.
244
+ piece = _SVG.sub(_hide, shown[at:at + 20000])[:700]
245
+ opened = _HEADING_OPEN.match(piece)
246
+ start, end = (opened.end() - 1 if opened else -1), _HEADING_END.search(piece)
247
+ if 0 < start and end and start < end.start():
248
+ text = _visible(piece[start + 1:end.start()])
249
+ if 0 < len(text) <= 120:
250
+ found.append(text)
251
+ at = shown.find(mark, at + 2)
252
+ return found
253
+
254
+ @property
255
+ def main_area(self) -> Optional[tuple]:
256
+ """(characters of visible text, links, typing fields) inside <main>, plus the characters of visible text
257
+ outside <main> and outside the page's header, menus and footer; None when the page has no <main>.
258
+ From the first <main> to the last </main> (or the end of the page): a second <main> counts too."""
259
+ start = _MAIN_OPEN.search(self.shown)
260
+ if not start:
261
+ return None
262
+ end = None
263
+ for end in _MAIN_CLOSE.finditer(self.shown, start.end()):
264
+ pass
265
+ stop = end.start() if end else len(self.shown)
266
+ area = self.shown[start.end():stop]
267
+ # A menu inside <main> is still the site's frame: its links are not content.
268
+ links = sum("href" in tag.group(1).lower() for tag in _LINK_TAG.finditer(_unframed(area)))
269
+ fields = 0 # a disabled field waits for its scripts too: it does not count
270
+ for tag in _INPUT_TAG.finditer(area):
271
+ attrs = {m.group(1).lower(): (m.group(2) or "").strip("\"'") for m in _ATTR.finditer(tag.group(1))}
272
+ fields += attrs.get("type", "").lower() not in _NOT_FIELD and "disabled" not in attrs
273
+ rest = self.shown[:start.start()] + " " + self.shown[end.end() if end else len(self.shown):]
274
+ return len(_visible(area)), links, fields, len(_visible(_unframed(rest)))
275
+
276
+ @property
277
+ def password_inputs(self) -> int:
278
+ found = 0
279
+ for tag in _INPUT_TAG.finditer(self.markup):
280
+ if not tag.group(0).endswith(">"): # cut off by the end of the page: a browser drops it
281
+ continue
282
+ attrs = {m.group(1).lower(): (m.group(2) or "").strip("\"'") for m in _ATTR.finditer(tag.group(1))}
283
+ found += attrs.get("type", "").lower() == "password"
284
+ return found
285
+
286
+ @property
287
+ def mount_point(self) -> bool:
288
+ return bool(_MOUNT.search(self.markup))
289
+
290
+ @property
291
+ def not_rendered(self) -> bool:
292
+ """Positive sign that the content never arrived: an empty mount point, a "loading" note, a {{placeholder}},
293
+ or (almost) no text outside the page's header, menus and footer."""
294
+ return bool(_EMPTY_MOUNT.search(self.markup) or _NOT_RENDERED.search(self.text)
295
+ or len(_visible(_unframed(self.shown))) < SHELL_FRAME_TEXT)
296
+
297
+ @property
298
+ def text_outside_forms(self) -> int:
299
+ """Characters of visible text outside the page's <form> elements: the page's own content beside a login box.
300
+ A form wrapped around the whole page (header, menus, main...; ASP.NET's __VIEWSTATE) is the page, not a box."""
301
+ return len(_visible(_FORM.sub(_form_box, self.shown)))
302
+
303
+
304
+ def _visible(markup: str) -> str:
305
+ return _squash(unescape(_ANY_TAG.sub("", _BLOCK_TAG.sub(" ", _SVG.sub(_hide, markup)))))
306
+
307
+
308
+ def _unframed(markup: str) -> str:
309
+ """The markup without its <header>, <nav> and <footer> elements (one that never closes is kept: no end to cut to;
310
+ a nested one of the same name closes inside it). The header and footer of an <article> are its own, not the site's."""
311
+ parts, pos, at, never = [], 0, 0, set()
312
+ articles = _article_spans(markup) if "<article" in markup or "<ARTICLE" in markup else ()
313
+ while True:
314
+ m = _FRAME_OPEN.search(markup, at)
315
+ if not m:
316
+ break
317
+ tag = m.group(1).lower()
318
+ if tag in never or (tag != "nav" and any(a < m.start() < b for a, b in articles)):
319
+ at = m.end()
320
+ continue
321
+ e = _close_of(markup, tag, m.end())
322
+ if not e:
323
+ never.add(tag) # no end further on either: no rescanning the page for each later one
324
+ at = m.end()
325
+ continue
326
+ parts.append(markup[pos:m.start()])
327
+ parts.append(" ")
328
+ pos = at = e
329
+ parts.append(markup[pos:])
330
+ return "".join(parts)
331
+
332
+
333
+ def _close_of(markup: str, tag: str, at: int) -> Optional[int]:
334
+ """Where the element opened just before `at` ends, counting nested elements of the same name; None if never."""
335
+ depth, close = 1, _FRAME_CLOSE[tag]
336
+ while True:
337
+ e = close.search(markup, at)
338
+ if not e:
339
+ return None
340
+ depth += sum(1 for o in _FRAME_OPEN.finditer(markup, at, e.start()) if o.group(1).lower() == tag) - 1
341
+ if depth <= 0:
342
+ return e.end()
343
+ at = e.end()
344
+
345
+
346
+ def _article_spans(markup: str) -> List[tuple]:
347
+ """(start, end) of each <article> element (one that never closes runs to the end of the page)."""
348
+ spans, at = [], 0
349
+ while True:
350
+ m = _ARTICLE_OPEN.search(markup, at)
351
+ if not m:
352
+ return spans
353
+ e = _ARTICLE_CLOSE.search(markup, m.end())
354
+ spans.append((m.start(), e.end() if e else len(markup)))
355
+ at = e.end() if e else len(markup)
356
+
357
+
358
+ def _unrendered(reader: "_Page", tlen: int) -> str:
359
+ """What shows that the app's content never arrived on a page with enough text: a loading note on a short page
360
+ under many scripts; "" if nothing. (Unfilled {{a.b}} templates were tried too: a real 2,988-character home page
361
+ kept four of them in a widget.)"""
362
+ if tlen < 600 and reader.scripts >= (4 if tlen < 300 else 10):
363
+ m = _LOADING.search(reader.text)
364
+ if m:
365
+ return f'loading note "{m.group(0)}"'
366
+ return ""
367
+
368
+
369
+ def _form_box(m: "re.Match") -> str:
370
+ """A <form> cut out as a box, unless it wraps the page itself (it holds the page's landmarks or ASP.NET state)."""
371
+ form = m.group(0)
372
+ return form if _PAGE_LANDMARK.search(form) or "__VIEWSTATE" in form else " "
373
+
374
+
375
+ def _hide(m: "re.Match") -> str:
376
+ # A hidden <svg> still breaks the line if it holds a block tag (a <title>, say).
377
+ return " " if _BLOCK_TAG.search(m.group(0)) else ""
378
+
379
+
380
+ def _squash(text: str) -> str:
381
+ text = " ".join(text.split()) # = re.sub(r"\s+", " ", text).strip() (same whitespace set, checked), 3x faster
382
+ if not text.isascii():
383
+ # Quotes after the spaces: the text is some ten times shorter by now. A removed zero-width space can leave
384
+ # two spaces side by side, so that (rare) case is squashed once more.
385
+ gap = "\u200b" in text
386
+ text = _PLAIN_RX.sub(lambda m: _PLAIN[m.group(0)], text)
387
+ if gap:
388
+ text = " ".join(text.split())
389
+ return text
390
+
391
+
392
+ # Names a server or a page may give for its character set, read the way browsers read them (the WHATWG encoding
393
+ # standard): "iso-8859-1" really means Windows-1252, "gb2312" means GBK, and so on.
394
+ _CHARSET_ALIAS = {
395
+ "iso-8859-1": "cp1252", "iso8859-1": "cp1252", "latin1": "cp1252", "latin-1": "cp1252", "ascii": "cp1252",
396
+ "us-ascii": "cp1252", "iso-8859-9": "cp1254", "iso-8859-11": "cp874", "tis-620": "cp874", "windows-874": "cp874",
397
+ "gb2312": "gbk", "gb_2312-80": "gbk", "x-gbk": "gbk", "shift_jis": "cp932", "shift-jis": "cp932", "sjis": "cp932",
398
+ "x-sjis": "cp932", "windows-31j": "cp932", "euc-kr": "cp949", "ks_c_5601-1987": "cp949", "x-euc-jp": "euc_jp",
399
+ }
400
+ _CHARSET_IN_TYPE = re.compile(r"""charset\s*=\s*["']?([\w.:-]+)""", re.I)
401
+
402
+
403
+ def decode_html(data: bytes, charset: Optional[str] = None) -> str:
404
+ """Turn the bytes of a page into text: gunzip if needed, then BOM, the declared character set, UTF-8, cp1252.
405
+
406
+ charset: what the server said (the `charset=` of its Content-Type header, or the whole header value). It comes
407
+ before the page's own <meta charset>, as in a browser. Bytes that are valid UTF-8 are read as UTF-8 whatever was
408
+ declared: servers and templates often announce a legacy character set they no longer use."""
409
+ if data[:2] == b"\x1f\x8b":
410
+ try:
411
+ data = gzip.decompress(data)
412
+ except (OSError, EOFError):
413
+ pass
414
+ elif data[:1] == b"\x78" and len(data) > 2 and (data[0] * 256 + data[1]) % 31 == 0: # zlib ("deflate") header
415
+ try:
416
+ data = zlib.decompress(data)
417
+ except zlib.error:
418
+ pass
419
+ if data[:3] == b"\xef\xbb\xbf":
420
+ return data[3:].decode("utf-8", errors="replace")
421
+ if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
422
+ return data.decode("utf-16", errors="replace")
423
+ declared = None
424
+ if charset and isinstance(charset, str):
425
+ m = _CHARSET_IN_TYPE.search(charset)
426
+ declared = m.group(1) if m else (charset.strip() if "/" not in charset and ";" not in charset else None)
427
+ if not declared:
428
+ m = re.search(rb"""<meta[^>]+charset=["']?([\w-]+)""", data[:4096], re.I)
429
+ declared = m.group(1).decode("ascii") if m else None
430
+ if declared:
431
+ declared = declared.strip().lower()
432
+ declared = _CHARSET_ALIAS.get(declared, declared)
433
+ if declared in ("utf-8", "utf8"):
434
+ return data.decode("utf-8", errors="replace")
435
+ try:
436
+ return data.decode("utf-8")
437
+ except UnicodeDecodeError:
438
+ pass
439
+ if declared:
440
+ try:
441
+ return data.decode(declared, errors="replace")
442
+ except (LookupError, ValueError):
443
+ pass
444
+ return data.decode("cp1252", errors="replace")
445
+
446
+
447
+ def _looks_binary(text: str) -> bool:
448
+ head = text[:4096]
449
+ if not head:
450
+ return False
451
+ # By share, not by presence: a real page can carry a stray NUL or a broken character.
452
+ return len(_BAD_CHAR.findall(head)) / len(head) > 0.05
453
+
454
+
455
+ def _is_document(text: str) -> bool:
456
+ """A PDF or an office file (Word, Excel, OpenDocument) by its own first bytes: the file asked for, not a block.
457
+ Only the magic bytes count, never the Content-Type: a proxy can label a block page application/pdf."""
458
+ if len(text) < 128:
459
+ return False
460
+ if text.startswith("%PDF-"):
461
+ return True
462
+ return text.startswith("PK\x03\x04") and ("[Content_Types].xml" in text[:1024]
463
+ or "mimetypeapplication/vnd.oasis" in text[:1024])
464
+
465
+
466
+ def _is_data(text: str, content_type: str) -> bool:
467
+ """A JSON or XML answer, not an HTML page: valid JSON, or an XML body sent or declared as such."""
468
+ body = text.strip()
469
+ low = body[:2048].lower()
470
+ if "<html" in low or "<body" in low or "<head" in low:
471
+ return False
472
+ ctype = content_type.lower()
473
+ if body[:1] in ("{", "["):
474
+ try:
475
+ json.loads(body)
476
+ return True
477
+ except ValueError:
478
+ return False
479
+ # Plain text is not trusted: sites answered "OK" or a two-line notice in place of their home page.
480
+ return low.startswith("<") and ("xml" in ctype and "xhtml" not in ctype or low.startswith("<?xml"))
481
+
482
+
483
+ def _needed_words(pattern: str) -> Optional[tuple]:
484
+ """(words, leading): lowercase ASCII words of which a match must contain at least one, and whether every match
485
+ starts with one of them. None if no word of 3+ characters can be told.
486
+
487
+ Searching a whole page case-insensitively is slow in Python (about 10 ns a character per rule); a plain search
488
+ for a lowercase word in the lowercased bytes is about 50 times faster. A rule whose words are all missing is
489
+ skipped, and a rule whose matches start with a word is searched from the first place a word appears: same
490
+ result, a fraction of the work."""
491
+ try:
492
+ try:
493
+ from re import _parser as sre # Python 3.11+
494
+ except ImportError: # pragma: no cover
495
+ import sre_parse as sre # type: ignore
496
+ tree = sre.parse(pattern, re.I)
497
+ except Exception: # pragma: no cover - any parser change just turns the shortcut off
498
+ return None
499
+
500
+ def literal(op, av) -> bool:
501
+ return op == sre.LITERAL and av < 128
502
+
503
+ def best(seq, at_start: bool):
504
+ found, cur, leading = [], [b""], at_start
505
+ for op, av in list(seq) + [(None, None)]: # the sentinel closes the last run
506
+ if literal(op, av):
507
+ cur = [c + bytes([av]).lower() for c in cur]
508
+ continue
509
+ if op == sre.BRANCH and len(cur) * len(av[1]) <= 16:
510
+ leads = []
511
+ for branch in av[1]:
512
+ lead = b""
513
+ for op2, av2 in branch:
514
+ if not literal(op2, av2):
515
+ break
516
+ lead += bytes([av2]).lower()
517
+ leads.append(lead)
518
+ cur = [c + lead for c in cur for lead in leads]
519
+ if min(map(len, cur)) >= 3:
520
+ found.append((min(map(len, cur)), cur, leading))
521
+ cur, leading = [b""], False
522
+ return max(found, key=lambda f: f[0])[1:] if found else None
523
+
524
+ items = list(tree)
525
+ if len(items) == 1 and items[0][0] == sre.BRANCH:
526
+ per_branch = [best(branch, True) for branch in items[0][1][1]]
527
+ if None in per_branch:
528
+ return None
529
+ return [w for words, _ in per_branch for w in words], all(lead for _, lead in per_branch)
530
+ return best(items, True)
531
+
532
+
533
+ def _find(low: bytes, word: bytes, seen: dict) -> int:
534
+ if word not in seen:
535
+ seen[word] = low.find(word)
536
+ return seen[word]
537
+
538
+
539
+ # re.I also matches these against k, s and i: a page holding one gets no shortcut.
540
+ _ODD_FOLDS = ("\u212a".encode(), "\u017f".encode(), "\u0130".encode(), "\u0131".encode())
541
+
542
+ def load_signatures(path: Optional[str] = None) -> List[dict]:
543
+ """Load the signature list (the bundled one, or your own JSON file). Raises ValueError on a bad file."""
544
+ if path:
545
+ with open(path, encoding="utf-8") as f:
546
+ try:
547
+ raw = json.load(f)
548
+ except json.JSONDecodeError as e:
549
+ raise ValueError(f"{path}: not valid JSON ({e})") from None
550
+ else:
551
+ raw = json.loads(resources.files("falseok").joinpath("signatures.json").read_text("utf-8"))
552
+ sigs = raw.get("signatures") if isinstance(raw, dict) else raw
553
+ if not isinstance(sigs, list):
554
+ raise ValueError("signatures: expected a list, or an object with a 'signatures' list")
555
+ for n, s in enumerate(sigs):
556
+ where = f"signature #{n + 1} ({s.get('id', 'no id') if isinstance(s, dict) else s!r})"
557
+ if not isinstance(s, dict) or not isinstance(s.get("pattern"), str) or not s["pattern"]:
558
+ raise ValueError(f"{where}: needs a non-empty 'pattern'")
559
+ if s.get("category") not in PRIORITY:
560
+ raise ValueError(f"{where}: 'category' must be one of {', '.join(PRIORITY)}")
561
+ if s.get("in", "text") not in ("title", "text", "html", "header", "heading"):
562
+ raise ValueError(f"{where}: 'in' must be title, text, html, header or heading")
563
+ if s.get("in") == "header":
564
+ if not isinstance(s.get("header"), str) or not s["header"].strip():
565
+ raise ValueError(f"{where}: a header rule needs 'header', the name of the response header to look at")
566
+ s["_header"] = s["header"].strip().lower()
567
+ try:
568
+ s["_rx"] = re.compile(s["pattern"] if s.get("regex") else re.escape(s["pattern"]), re.I)
569
+ s["_needs"] = _needed_words(s["_rx"].pattern)
570
+ s["_words"] = tuple(w.decode("ascii") for w in s["_needs"][0]) if s["_needs"] else ()
571
+ except re.error as e:
572
+ raise ValueError(f"{where}: bad regex ({e})") from None
573
+ s.setdefault("id", f"rule-{n + 1}")
574
+ return sigs
575
+
576
+
577
+ _DEFAULT: Optional[List[dict]] = None
578
+
579
+
580
+ def _status(status) -> Optional[int]:
581
+ if status is None:
582
+ return None
583
+ # Lenient on purpose: some HTTP clients report 0 or a string for a failed request; a check must not crash on it.
584
+ try:
585
+ code = int(str(status).strip())
586
+ except (TypeError, ValueError):
587
+ return None
588
+ return code if 100 <= code <= 599 else None
589
+
590
+
591
+ def _headers(headers) -> dict:
592
+ """Response headers as {lowercase name: value}, from whatever the HTTP client gives: a mapping (requests, httpx,
593
+ aiohttp), a list of (name, value) pairs, or the raw text ("Name: value" lines, as `curl -D` saves them; after
594
+ redirects the last block counts). Repeated headers are joined with ", ". Anything unreadable is skipped."""
595
+ if not headers:
596
+ return {}
597
+ if isinstance(headers, (bytes, bytearray)):
598
+ headers = bytes(headers).decode("latin-1")
599
+ out: dict = {}
600
+ if isinstance(headers, str):
601
+ pairs = []
602
+ for line in headers.splitlines():
603
+ if line[:5].upper() == "HTTP/": # a status line: a new response starts here
604
+ pairs = []
605
+ elif ":" in line:
606
+ pairs.append(line.split(":", 1))
607
+ else:
608
+ items = getattr(headers, "items", None)
609
+ try:
610
+ pairs = list(items() if callable(items) else headers)
611
+ except TypeError:
612
+ return {}
613
+ for pair in pairs:
614
+ try:
615
+ name, value = pair
616
+ except (TypeError, ValueError):
617
+ continue
618
+ if isinstance(name, bytes):
619
+ name = name.decode("latin-1")
620
+ if isinstance(value, bytes):
621
+ value = value.decode("latin-1")
622
+ if not isinstance(name, str) or value is None:
623
+ continue
624
+ name, value = name.strip().lower(), str(value).strip()
625
+ out[name] = f"{out[name]}, {value}" if name in out else value
626
+ return out
627
+
628
+
629
+ def check_page(
630
+ html: Union[str, bytes],
631
+ status: Optional[int] = None,
632
+ signatures: Optional[List[dict]] = None,
633
+ min_text: int = 150,
634
+ headers=None,
635
+ ) -> PageResult:
636
+ """Return a verdict for one HTML page.
637
+
638
+ html: the page, as text or as the raw bytes you received.
639
+ status: the HTTP status you got, if you know it. Strings like "404" work; values outside 100-599 are ignored.
640
+ min_text: below this many characters of visible text, a page counts as empty.
641
+ headers: the response headers, if you have them (a dict, your HTTP client's headers object, a list of pairs or
642
+ the raw text). Some anti-bot services mark a blocked response there, whatever the page looks like.
643
+ """
644
+ global _DEFAULT
645
+ if signatures is None:
646
+ if _DEFAULT is None:
647
+ _DEFAULT = load_signatures()
648
+ signatures = _DEFAULT
649
+ status = _status(status)
650
+ sent = _headers(headers)
651
+ if isinstance(html, (bytes, bytearray)):
652
+ html = bytes(html)
653
+ if "deflate" in sent.get("content-encoding", "").lower() and html[:1] != b"\x78":
654
+ try: # "deflate" sent without its zlib header, as some servers do
655
+ html = zlib.decompress(html, -15)
656
+ except zlib.error:
657
+ pass
658
+ html = decode_html(html, sent.get("content-type"))
659
+ raw = html or ""
660
+
661
+ if (status is None or status < 400) and _is_document(raw):
662
+ return PageResult("ok", "a whole document (PDF or office file), not an HTML page")
663
+ if _looks_binary(raw):
664
+ return PageResult("not_html", "binary or compressed data, not an HTML page")
665
+
666
+ reader = _Page(raw)
667
+ title, text = reader.title, reader.text
668
+ tlen = len(text)
669
+ both = f"{title} {text}"
670
+
671
+ signals: List[Signal] = []
672
+ low: Optional[bytes] = None
673
+ heads: Optional[List[str]] = None
674
+ lowered: Optional[str] = None
675
+ seen: dict = {}
676
+ for s in signatures:
677
+ where = s.get("in", "text")
678
+ if where == "header":
679
+ # The service's own word about this response: it counts on a page of any length.
680
+ value = sent.get(s.get("_header") or str(s.get("header", "")).strip().lower()) if sent else None
681
+ if value is not None and s["_rx"].search(value):
682
+ signals.append(Signal(s["id"], s["category"], f'header: "{s["header"]}: {value[:80]}"', s.get("vendor")))
683
+ continue
684
+ if tlen > s.get("max_text", DEFAULT_MAX_TEXT):
685
+ continue
686
+ if where != "html" and s.get("_words"):
687
+ # The same shortcut for title and text rules: no needed word on the page, no need to run the pattern.
688
+ if lowered is None:
689
+ lowered = both.lower()
690
+ if "\u017f" in lowered or "\u0131" in lowered: # re.I also matches these against s and i
691
+ lowered = ""
692
+ if lowered and not any(w in lowered for w in s["_words"]):
693
+ continue
694
+ if where == "heading":
695
+ if heads is None:
696
+ heads = reader.headings
697
+ for head in heads:
698
+ m = s["_rx"].search(head)
699
+ if m:
700
+ signals.append(Signal(s["id"], s["category"], f'heading: "{head[:80]}"', s.get("vendor")))
701
+ break
702
+ continue
703
+ hay = title if where == "title" else both if where == "text" else raw
704
+ needs, start = s.get("_needs"), 0
705
+ if where == "html" and needs:
706
+ if low is None:
707
+ low = raw.encode("utf-8", "surrogatepass").lower()
708
+ if not raw.isascii() and any(odd in low for odd in _ODD_FOLDS): # isascii() costs nothing on a str
709
+ low = b""
710
+ if low:
711
+ hits = [at for at in (_find(low, w, seen) for w in needs[0]) if at >= 0]
712
+ if not hits:
713
+ continue
714
+ if needs[1]: # every match starts with a word: search from the first one
715
+ start = min(hits) if raw.isascii() else len(low[:min(hits)].decode("utf-8", "surrogatepass"))
716
+ m = s["_rx"].search(hay, start)
717
+ if m:
718
+ detail = f'{where}: "{m.group(0)[:80]}"'
719
+ signals.append(Signal(s["id"], s["category"], detail, s.get("vendor")))
720
+
721
+ if status == 429:
722
+ signals.append(Signal("http-429", "rate_limited", "status 429"))
723
+ passwords = reader.password_inputs if tlen < 1500 or any(x.category == "captcha" for x in signals) else 0
724
+ if passwords >= 2:
725
+ # A password and its confirmation: a sign-up form, the page the visitor asked for. Its captcha box (and the
726
+ # "verify you're a human" label beside it) guards the form, it does not block the page.
727
+ signals = [x for x in signals if x.category != "captcha"]
728
+ elif tlen < 1500 and passwords and (tlen < LOGIN_SIDE_TEXT or reader.text_outside_forms < LOGIN_SIDE_TEXT):
729
+ signals.append(Signal("password-form", "login_wall", f"password field, only {tlen} chars of text"))
730
+ # An app that never rendered: a menu or a footer at most, under a pile of scripts, and a sign the content is missing.
731
+ app_shell = (min_text <= tlen < SHELL_TEXT and reader.scripts >= SHELL_SCRIPTS and reader.not_rendered)
732
+ if ((tlen < min_text or app_shell) and (status is None or status < 400) and raw.strip()
733
+ and _is_data(raw, sent.get("content-type", ""))):
734
+ pass # a short JSON, XML or plain-text answer is data, not an empty HTML page
735
+ elif tlen < min_text or app_shell:
736
+ if not raw.strip():
737
+ detail = "the response is empty"
738
+ elif reader.mount_point or reader.scripts:
739
+ detail = f"{tlen} chars of text, {reader.scripts} scripts: an app that never rendered"
740
+ else:
741
+ detail = f"only {tlen} chars of visible text"
742
+ signals.append(Signal("too-little-text", "empty_shell", detail))
743
+ elif tlen < MAIN_PAGE_TEXT and reader.scripts:
744
+ # Menu and footer arrived, the content did not: <main> is there, with (almost) no text, no link and no field
745
+ # to type into (a search box is content), and nothing but header, menus and footer around it.
746
+ area = reader.main_area
747
+ if (area and area[0] < min_text and not area[1] and not area[2] and area[3] < SIDE_TEXT
748
+ and tlen - area[0] >= min_text):
749
+ detail = f"only {area[0]} chars of text inside <main> ({tlen} on the page, {reader.scripts} scripts): the content never rendered"
750
+ signals.append(Signal("main-empty", "empty_shell", detail))
751
+ if tlen >= min_text and reader.scripts and not any(x.category == "empty_shell" for x in signals):
752
+ # The app said so itself: its "Loading..." note is still on the screen.
753
+ note = _unrendered(reader, tlen)
754
+ if note:
755
+ signals.append(Signal("not-rendered", "empty_shell", f"{note}, {tlen} chars, {reader.scripts} scripts"))
756
+
757
+ result = PageResult("ok", "no block signal found", signals, None, title, tlen)
758
+ if signals:
759
+ cats = {x.category for x in signals}
760
+ top = next(c for c in PRIORITY if c in cats)
761
+ in_top = [x for x in signals if x.category == top]
762
+ result.verdict = top
763
+ result.reason = f"{in_top[0].id} ({in_top[0].detail})"
764
+ result.vendor = next((x.vendor for x in in_top if x.vendor), None)
765
+ elif status is not None and status >= 400:
766
+ result.verdict = "http_error"
767
+ result.reason = f"HTTP status {status}"
768
+ return result