Files
PunchLog/tools/extract_token.py
T

82 lines
2.9 KiB
Python

"""Extract the latest iEPMS auth token from captured traffic and update .env.
Why this exists: from-scratch pure-Python login is blocked by EMM device binding
("用户设备无效" / 100301). But the token (``X-Auth-Value``) is long-lived, and the
attendance read API does not enforce the request signature. So the practical refresh
path is: run the phone app through the capture proxy once, then grab the newest token
from the capture file here.
Usage:
python tools/extract_token.py # read default capture, print token
python tools/extract_token.py --write # also update ICENTER_TOKEN in .env
python tools/extract_token.py --captures path.jsonl
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_CAPTURES = ROOT / "data" / "captures" / "flows.jsonl"
ENV_PATH = ROOT / ".env"
TOKEN_HEADER = "x-auth-value"
def latest_token(captures: Path) -> tuple[str, str] | None:
"""Return (token, ts) from the most recent flow carrying an auth token."""
best: tuple[str, str] | None = None
for line in captures.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line:
continue
try:
fl = json.loads(line)
except json.JSONDecodeError:
continue
for k, v in (fl.get("req_headers") or []):
if k.lower() == TOKEN_HEADER and v and len(v) >= 16:
ts = str(fl.get("ts") or "")
if best is None or ts > best[1]:
best = (v, ts)
return best
def update_env(token: str, env_path: Path = ENV_PATH) -> None:
lines = env_path.read_text(encoding="utf-8").splitlines() if env_path.is_file() else []
out, found = [], False
for ln in lines:
if ln.strip().startswith("ICENTER_TOKEN="):
out.append(f"ICENTER_TOKEN={token}")
found = True
else:
out.append(ln)
if not found:
out.append(f"ICENTER_TOKEN={token}")
env_path.write_text("\n".join(out) + "\n", encoding="utf-8")
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="提取最新 iEPMS token")
ap.add_argument("--captures", default=str(DEFAULT_CAPTURES))
ap.add_argument("--write", action="store_true", help="写入 .env 的 ICENTER_TOKEN")
args = ap.parse_args(argv)
cap = Path(args.captures)
if not cap.is_file():
raise SystemExit(f"找不到抓包文件: {cap}")
res = latest_token(cap)
if not res:
raise SystemExit("未在抓包中找到 x-auth-value token。请先让手机 App 走代理发一次请求。")
token, ts = res
print(f"最新 token: {token} (ts={ts})")
if args.write:
update_env(token)
print(f"已写入 {ENV_PATH}")
return 0
if __name__ == "__main__":
raise SystemExit(main())