Files
o2o-castad-backend/app/traffic/detect/paths.py
T

125 lines
4.7 KiB
Python

"""경로 분류 — 비콘 경로와 nginx 접근 로그 경로를 우리 페이지 종류로 바꾼다.
SPA 라우트는 프론트 `src/App.tsx` 의 pathname 분기와 같게 둔다. 라우트를 추가하면 여기도 고친다.
공유 페이지는 백엔드가 HTML 로 응답하며, 외부에서는 nginx 의 `/api` 접두사가 붙어 들어온다.
"""
import re
from dataclasses import dataclass
_MAX_PATH = 512
#: (콘텐츠 종류, SPA 상세 경로)
_CONTENT_PAGES: tuple[tuple[str, re.Pattern[str]], ...] = (
("video", re.compile(r"^/video/(\d+)$")),
("ssul", re.compile(r"^/ssul/(\d+)$")),
("p2v_f1", re.compile(r"^/p2v/f1/(\d+)$")),
("p2v_playreel", re.compile(r"^/p2v/playreel/(\d+)$")),
)
#: (콘텐츠 종류, 공유 HTML 경로 — /api 접두사는 있어도 없어도 된다)
_SHARE_PAGES: tuple[tuple[str, re.Pattern[str]], ...] = (
("video", re.compile(r"^(?:/api)?/video/share/(\d+)$")),
("ssul", re.compile(r"^(?:/api)?/ssul/share/(\d+)$")),
("p2v_f1", re.compile(r"^(?:/api)?/p2v/f1/share/(\d+)$")),
("p2v_playreel", re.compile(r"^(?:/api)?/p2v/playreel/share/(\d+)$")),
)
_STATIC_HTML = frozenset({"/faq.html", "/privacy.html", "/terms.html"})
_ROOT_FILES = {"/robots.txt": "robots", "/sitemap.xml": "sitemap", "/llms.txt": "llms"}
#: 통계에서 아예 빼는 경로 — OAuth 콜백 화면, 관리자
#: `/admin.php` · `/administrator` 같은 스캐너 요청까지 버리지 않도록 `/admin` 은 정확히 또는 `/admin/` 아래만 뺀다
_EXCLUDED_PREFIXES = ("/social/", "/admin/")
#: 접근 로그에서 버리는 정적 자원. 확장자 전체를 버리지 않는 이유: /.env · /wp-login.php 같은 스캐너 요청은 남겨야 한다
_ASSET_EXT = re.compile(
r"\.(?:js|mjs|css|map|png|jpe?g|gif|svg|webp|avif|ico|bmp|woff2?|ttf|otf|eot|mp4|webm|mp3|wav|m4a)$",
re.IGNORECASE,
)
@dataclass(frozen=True)
class PageInfo:
"""비콘 한 건의 페이지 종류."""
#: landing · video · ssul · p2v_f1 · p2v_playreel · static · other
page_kind: str
content_type: str | None
content_id: int | None
@dataclass(frozen=True)
class RequestInfo:
"""접근 로그 한 줄의 요청 종류."""
#: page · share · static_html · robots · sitemap · llms · other
kind: str
path: str
content_type: str | None
content_id: int | None
def normalize_path(raw: str) -> str:
"""쿼리·해시를 떼고, 끝 `/` 를 떼고(루트 제외), 512자로 자른다.
urlsplit 을 쓰지 않는다: 스캐너가 보내는 `//evil/x` 같은 값을 호스트로 읽어 경로를 잃는다.
"""
path = (raw or "").split("?", 1)[0].split("#", 1)[0] or "/"
if len(path) > 1:
path = path.rstrip("/") or "/"
return path[:_MAX_PATH]
def _is_excluded(path: str) -> bool:
return path == "/admin" or any(path.startswith(p) for p in _EXCLUDED_PREFIXES)
def _match_content(path: str, table: tuple[tuple[str, re.Pattern[str]], ...]) -> tuple[str, int] | None:
for content_type, pattern in table:
m = pattern.match(path)
if m:
return content_type, int(m.group(1))
return None
def page_of(path: str) -> PageInfo | None:
"""비콘 경로 → 페이지 종류. 통계에서 빼는 경로면 None."""
if _is_excluded(path):
return None
if path == "/":
return PageInfo("landing", None, None)
content = _match_content(path, _CONTENT_PAGES)
if content:
return PageInfo(content[0], content[0], content[1])
if path in _STATIC_HTML:
return PageInfo("static", None, None)
return PageInfo("other", None, None)
def request_of(uri: str) -> RequestInfo | None:
"""접근 로그의 `$request_uri` → 요청 종류. 정적 자원·API·관리자 요청이면 None."""
if not uri.startswith("/") or uri.startswith("//"):
# 프록시 시도(`http://evil.com/`)·`*`·깨진 요청 줄 — 스캐너로 남긴다
return RequestInfo("other", (uri or "-")[:_MAX_PATH], None, None)
path = normalize_path(uri)
share = _match_content(path, _SHARE_PAGES)
if share:
return RequestInfo("share", path, share[0], share[1])
if path.startswith("/api/") or path == "/api" or _is_excluded(path):
return None
if path in _ROOT_FILES:
return RequestInfo(_ROOT_FILES[path], path, None, None)
if path.startswith("/assets/") or _ASSET_EXT.search(path):
return None
page = page_of(path)
if page is None:
return None
if page.page_kind == "static":
return RequestInfo("static_html", path, None, None)
if page.page_kind == "other":
return RequestInfo("other", path, None, None)
return RequestInfo("page", path, page.content_type, page.content_id)