#!/usr/bin/env python3 """ Проверка «служба считает меня вошедшим?» по её собственному API. Код 200 у страницы ничего не доказывает; API — доказывает. Порядок: вхожу через домен как браузер, затем зову служебный адрес, который без входа отдаёт 401/403, а с входом — данные. """ import json import sys import urllib.parse import requests AK = "https://authentik.buryans.ru" USER = PW = None for line in open("/root/.buryan-sso-check-password", encoding="utf-8", errors="replace"): if line.startswith("SSO_CHECK_USER="): USER = line.split("=", 1)[1].strip() if line.startswith("SSO_CHECK_PASSWORD="): PW = line.split("=", 1)[1].strip() # домен -> (адрес проверки, что считается признаком входа) PROBES = { "git.buryans.ru": ("/api/v1/user", "json_login"), "media.buryans.ru": ("/Users/Me", "not401"), "music.buryans.ru": ("/auth/me", "not401"), "sonarr.buryans.ru": ("/api/v3/system/status", "not401"), "radarr.buryans.ru": ("/api/v3/system/status", "not401"), "prowlarr.buryans.ru": ("/api/v1/system/status", "not401"), "bazarr.buryans.ru": ("/api/system/status", "not401"), "docs.buryans.ru": ("/api/documents/", "not401"), "links.buryans.ru": ("/api/bookmarks/?limit=1", "not401"), "finance.buryans.ru": ("/api/v1/about/user", "not401"), "meals.buryans.ru": ("/api/users/self", "not401"), "adguard.buryans.ru": ("/control/stats", "not403"), "immich.buryans.ru": ("/api/users/me", "not401"), "ombi.buryans.ru": ("/api/v1/auth/me", "not401"), "vault.buryans.ru": ("/api/accounts/profile", "not401"), "status.buryans.ru": ("/api/status-page", "not401"), "backup.buryans.ru": ("/api/v1/serverstate", "not401"), "hub.buryans.ru": ("/", "any200"), "n8n.buryans.ru": ("/rest/login", "not401"), "flow.buryans.ru": ("/settings", "not401"), "openclaw.buryans.ru": ("/api/health", "not401"), } def csrf(s): h = {"Referer": f"{AK}/if/flow/default-authentication-flow/", "Origin": AK} for n in ("authentik_csrf", "csrftoken"): v = s.cookies.get(n) if v: h["X-CSRFToken"] = v break return h def flow(s, slug, params): api = f"{AK}/api/v3/flows/executor/{slug}/" s.get(f"{AK}/if/flow/{slug}/", params=params or {}, timeout=20) ch = s.get(api, params=params or {}, timeout=20).json() for _ in range(10): c = ch.get("component", "") if "identification" in c: b = {"uid_field": USER} elif "password" in c: b = {"password": PW} elif "consent" in c: b = {"token": ch.get("token")} if ch.get("token") else {} elif "redirect" in c: to = ch.get("to") or "/" s.get(AK + to if to.startswith("/") else to, timeout=20) return None else: return c r = s.post(api, json=b, timeout=20, headers=csrf(s)) if r.status_code >= 400: return f"{c}->{r.status_code}" ch = r.json() return "no-end" def login(domain): s = requests.Session() s.headers.update({"User-Agent": "Mozilla/5.0 (auth-api-check)", "Origin": AK, "Referer": f"{AK}/if/flow/default-authentication-flow/"}) url = f"https://{domain}/" done = set() for _ in range(6): r = s.get(url, allow_redirects=False, timeout=25) loc = r.headers.get("Location", "") if not loc or ("authentik" not in loc and "192.168.1.114" not in loc): return s, None r2 = s.get(loc, allow_redirects=False, timeout=25) loc2 = r2.headers.get("Location", "") if "code=" in loc2: s.get(loc2, allow_redirects=False, timeout=25) s.get(url, timeout=25) return s, None fu = loc2 if "/if/flow/" in loc2 else (r2.url if "/if/flow/" in r2.url else "") if not fu: return s, f"шаг {r2.status_code}" pu = urllib.parse.urlparse(fu) slug = pu.path.strip("/").split("/")[-1] if slug in done: return s, "поток повторяется" done.add(slug) e = flow(s, slug, dict(urllib.parse.parse_qsl(pu.query))) if e: return s, e return s, "много переходов" rows = [] for domain, (path, kind) in PROBES.items(): s, err = login(domain) if err: rows.append((domain, "ошибка входа", err)) continue try: r = s.get(f"https://{domain}{path}", allow_redirects=False, timeout=25) except requests.RequestException as e: rows.append((domain, "сеть", str(e)[:40])) continue code = r.status_code mark = "?" detail = "" if kind == "json_login": try: d = r.json() mark = "ДА " if d.get("login") else "НЕТ" detail = f"login={d.get('login')}" except Exception: mark = "НЕТ" detail = r.text[:40].replace("\n", " ") elif kind == "not401": mark = "НЕТ" if code in (401, 403) else "ДА " detail = f"код {code}" elif kind == "not403": mark = "НЕТ" if code in (401, 403) else "ДА " detail = f"код {code}" elif kind == "any200": mark = "ДА " if code == 200 else "НЕТ" detail = f"код {code}" rows.append((domain, mark, f"{path} → {detail}")) print(f" {'служба':<22} {'вошёл?':<7} доказательство") print(" " + "-" * 84) for d, m, det in rows: print(f" {d:<22} {m:<7} {det}")