175 lines
8.1 KiB
Python
175 lines
8.1 KiB
Python
"""Windows DPAPI protects local CHSI cookies; passwords are never stored."""
|
|
import ctypes
|
|
import json
|
|
import os
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
from bs4 import BeautifulSoup
|
|
|
|
LOGIN_URL = "https://account.chsi.com.cn/passport/login?entrytype=yzgr&service=https%3A%2F%2Fyz.chsi.com.cn%2Fj_spring_cas_security_check"
|
|
|
|
|
|
class Blob(ctypes.Structure):
|
|
_fields_ = [("size", ctypes.c_ulong), ("data", ctypes.POINTER(ctypes.c_ubyte))]
|
|
|
|
|
|
def protect(payload, decrypt=False):
|
|
if os.name != "nt":
|
|
raise RuntimeError("凭据加密存储需要 Windows DPAPI")
|
|
memory = ctypes.create_string_buffer(payload)
|
|
source = Blob(len(payload), ctypes.cast(memory, ctypes.POINTER(ctypes.c_ubyte)))
|
|
result = Blob()
|
|
crypt = ctypes.windll.crypt32
|
|
fn = crypt.CryptUnprotectData if decrypt else crypt.CryptProtectData
|
|
# UI_FORBIDDEN prevents a modal system prompt in a background job.
|
|
if not fn(ctypes.byref(source), None, None, None, None, 1, ctypes.byref(result)):
|
|
raise RuntimeError("Windows 凭据加密失败,请使用当前 Windows 用户重新登录")
|
|
try:
|
|
return ctypes.string_at(result.data, result.size)
|
|
finally:
|
|
ctypes.windll.kernel32.LocalFree(result.data)
|
|
|
|
|
|
class CookieVault:
|
|
def __init__(self, directory):
|
|
self.path = Path(directory) / "chsi-cookie.enc"
|
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
def save(self, cookies):
|
|
temporary = self.path.with_suffix(".tmp")
|
|
temporary.write_bytes(protect(json.dumps(cookies, ensure_ascii=False).encode()))
|
|
temporary.replace(self.path)
|
|
|
|
def load(self):
|
|
if not self.path.exists():
|
|
return {}
|
|
return json.loads(protect(self.path.read_bytes(), decrypt=True))
|
|
|
|
def clear(self):
|
|
self.path.unlink(missing_ok=True)
|
|
|
|
|
|
class AuthService:
|
|
def __init__(self, transport, vault):
|
|
self.transport, self.vault = transport, vault
|
|
self.message = "尚未验证登录状态"
|
|
self.valid = False
|
|
self.browser_state = "idle"
|
|
self.browser_message = ""
|
|
self.browser_thread = None
|
|
try:
|
|
self._load(self.vault.load())
|
|
except (RuntimeError, OSError, ValueError):
|
|
self.message = "保存的 Cookie 无法解密,请重新登录"
|
|
|
|
def _load(self, cookies):
|
|
if isinstance(cookies, dict):
|
|
cookies = [{"name": name, "value": value, "domain": ".chsi.com.cn", "path": "/"} for name, value in cookies.items()]
|
|
with self.transport.lock:
|
|
self.transport.session.cookies.clear()
|
|
for cookie in cookies:
|
|
domain = str(cookie.get("domain", ".chsi.com.cn"))
|
|
if domain.lstrip(".") != "chsi.com.cn" and not domain.endswith(".chsi.com.cn"):
|
|
continue
|
|
expires = cookie.get("expires")
|
|
self.transport.session.cookies.set(cookie["name"], cookie["value"], domain=domain, path=cookie.get("path", "/"), secure=bool(cookie.get("secure")), expires=int(expires) if expires and expires > 0 else None)
|
|
|
|
def _snapshot(self):
|
|
with self.transport.lock:
|
|
return [{"name": c.name, "value": c.value, "domain": c.domain, "path": c.path, "secure": c.secure, "expires": c.expires} for c in self.transport.session.cookies]
|
|
|
|
def status(self):
|
|
return {"saved": self.vault.path.exists(), "valid": self.valid, "message": self.message, "browser_state": self.browser_state, "browser_message": self.browser_message}
|
|
|
|
def cookie(self, text):
|
|
if not text.strip() or "\n" in text or "\r" in text:
|
|
raise ValueError("请粘贴单行 Cookie 请求头")
|
|
text = text.removeprefix("Cookie:").strip()
|
|
cookies = {}
|
|
for token in text.split(";"):
|
|
if "=" in token:
|
|
name, value = token.strip().split("=", 1)
|
|
if name and value:
|
|
cookies[name] = value
|
|
if not cookies:
|
|
raise ValueError("未识别到 Cookie 键值")
|
|
self._load(cookies)
|
|
self.vault.save(cookies)
|
|
self.valid = False
|
|
self.message = "Cookie 已加密保存,点击验证确认目录访问权限"
|
|
return self.status()
|
|
|
|
def check(self):
|
|
# The school/major indexes can be public while direction details require login.
|
|
response = self.transport.request("POST", "https://yz.chsi.com.cn/zsml/rs/yjfxs.do", data={"dwdm": "10001", "zydm": "081200", "zymc": "计算机科学与技术", "curPage": 1, "start": 0, "pageSize": 1, "dwlxs[0]": "all"})
|
|
try:
|
|
body = response.json()
|
|
except ValueError:
|
|
self.valid = False
|
|
self.message = "目录接口未返回有效数据,可能需要登录或验证码"
|
|
return self.status()
|
|
self.valid = body.get("flag") is True and isinstance(body.get("msg"), dict)
|
|
self.message = "研招目录接口验证成功" if self.valid else "登录未生效或数据源限流,请在浏览器完成登录后重试"
|
|
if self.valid:
|
|
self.vault.save(self._snapshot())
|
|
return self.status()
|
|
|
|
def login(self, username, password):
|
|
if not username or not password:
|
|
raise ValueError("请输入学信网账号和密码")
|
|
response = self.transport.request("GET", LOGIN_URL)
|
|
soup = BeautifulSoup(response.text, "html.parser")
|
|
form = {node.get("name"): node.get("value", "") for node in soup.select("input[type=hidden][name]")}
|
|
if "lt" not in form or "execution" not in form:
|
|
raise ValueError("登录页面需要人工验证,请使用浏览器登录")
|
|
form.update(username=username, password=password, _eventId="submit")
|
|
self.transport.request("POST", LOGIN_URL, data=form)
|
|
return self.check()
|
|
|
|
def clear(self):
|
|
self._load({})
|
|
self.vault.clear()
|
|
self.valid = False
|
|
self.message = "已清除本项目保存的登录凭据"
|
|
return self.status()
|
|
|
|
def browser(self):
|
|
if self.browser_thread and self.browser_thread.is_alive():
|
|
return self.status()
|
|
proxy = self.transport.router.resolve()
|
|
self.browser_state = "opening"
|
|
self.browser_message = "正在打开独立 Edge 登录窗口,完成登录后可关闭窗口"
|
|
|
|
def run():
|
|
from playwright.sync_api import sync_playwright
|
|
try:
|
|
with sync_playwright() as playwright:
|
|
browser = playwright.chromium.launch(channel="msedge", headless=False, proxy={"server": proxy} if proxy else None)
|
|
context = browser.new_context()
|
|
page = context.new_page()
|
|
page.goto(LOGIN_URL, wait_until="domcontentloaded", timeout=60000)
|
|
self.browser_state = "waiting"
|
|
self.browser_message = "请在 Edge 完成学信网登录和验证码;窗口保持打开,工作台自动检测"
|
|
deadline = time.monotonic() + 300
|
|
while time.monotonic() < deadline:
|
|
page.wait_for_timeout(2000)
|
|
if "yz.chsi.com.cn" in page.url:
|
|
cookies = [c for c in context.cookies() if c["domain"].lstrip(".") == "chsi.com.cn" or c["domain"].endswith(".chsi.com.cn")]
|
|
if cookies:
|
|
self._load(cookies)
|
|
if self.check()["valid"]:
|
|
self.browser_state = "completed"
|
|
self.browser_message = "已获取登录 Cookie,目录接口验证成功"
|
|
browser.close()
|
|
return
|
|
browser.close()
|
|
self.browser_state = "expired"
|
|
self.browser_message = "登录等待超时,可再次打开浏览器"
|
|
except Exception:
|
|
self.browser_state = "failed"
|
|
self.browser_message = "登录窗口已关闭或连接失败,可重试或粘贴 Cookie"
|
|
self.browser_thread = threading.Thread(target=run, daemon=True, name="browser-login")
|
|
self.browser_thread.start()
|
|
return self.status()
|