dingtalk_auth.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """DingTalk Device Flow authorization."""
  2. from __future__ import annotations
  3. import contextlib
  4. import os
  5. import sys
  6. import time
  7. from typing import Optional, Tuple
  8. import requests
  9. REGISTRATION_BASE_URL = os.environ.get("DINGTALK_REGISTRATION_BASE_URL", "https://oapi.dingtalk.com").rstrip("/")
  10. REGISTRATION_SOURCE = os.environ.get("DINGTALK_REGISTRATION_SOURCE", "openClaw")
  11. _POLL_STATUSES = {"WAITING", "SUCCESS", "FAIL", "EXPIRED"}
  12. _RETRY_WINDOW = 120 # seconds of transient errors / non-success statuses tolerated before giving up
  13. class RegistrationError(Exception):
  14. """Raised when a DingTalk registration API call fails."""
  15. def _api_post(path: str, payload: dict) -> dict:
  16. """POST to the registration API and return the parsed JSON body."""
  17. url = f"{REGISTRATION_BASE_URL}{path}"
  18. try:
  19. resp = requests.post(url, json=payload, timeout=15)
  20. resp.raise_for_status()
  21. data = resp.json()
  22. except requests.RequestException as exc:
  23. raise RegistrationError(f"Network error calling {url}: {exc}") from exc
  24. errcode = data.get("errcode", -1)
  25. if errcode != 0:
  26. raise RegistrationError(f"API error [{path}]: {data.get('errmsg', 'unknown error')} (errcode={errcode})")
  27. return data
  28. def begin_registration() -> dict:
  29. """Start a device-flow registration: init → nonce, begin → device_code + verification URL."""
  30. nonce = str(_api_post("/app/registration/init", {"source": REGISTRATION_SOURCE}).get("nonce", "")).strip()
  31. if not nonce:
  32. raise RegistrationError("init response missing nonce")
  33. begin_data = _api_post("/app/registration/begin", {"nonce": nonce})
  34. reg = {key: str(begin_data.get(key, "")).strip() for key in ("device_code", "verification_uri_complete")}
  35. for key, value in reg.items():
  36. if not value:
  37. raise RegistrationError(f"begin response missing {key}")
  38. reg["expires_in"] = int(begin_data.get("expires_in", 7200))
  39. reg["interval"] = max(int(begin_data.get("interval", 3)), 2)
  40. return reg
  41. def poll_registration(device_code: str) -> dict:
  42. """Poll the registration status once."""
  43. data = _api_post("/app/registration/poll", {"device_code": device_code})
  44. status_raw = str(data.get("status", "")).strip().upper()
  45. result = {"status": status_raw if status_raw in _POLL_STATUSES else "UNKNOWN"}
  46. result.update({key: str(data.get(key, "")).strip() or None for key in ("client_id", "client_secret", "fail_reason")})
  47. return result
  48. def wait_for_registration_success(
  49. device_code: str, interval: int = 3, expires_in: int = 7200, on_waiting: Optional[callable] = None,
  50. ) -> tuple[str, str]:
  51. """Block until the registration succeeds or times out.
  52. Transient errors and FAIL/EXPIRED/UNKNOWN statuses are retried for ``_RETRY_WINDOW`` seconds
  53. before being raised; a WAITING status resets that window.
  54. """
  55. deadline = time.monotonic() + expires_in
  56. retry_start = 0.0
  57. def _within_retry_window() -> bool:
  58. nonlocal retry_start
  59. if retry_start == 0:
  60. retry_start = time.monotonic()
  61. return time.monotonic() - retry_start < _RETRY_WINDOW
  62. while time.monotonic() < deadline:
  63. time.sleep(interval)
  64. try:
  65. result = poll_registration(device_code)
  66. except RegistrationError:
  67. if _within_retry_window():
  68. continue
  69. raise
  70. status = result["status"]
  71. if status == "WAITING":
  72. retry_start = 0
  73. if on_waiting:
  74. on_waiting()
  75. elif status == "SUCCESS":
  76. cid, csecret = result["client_id"], result["client_secret"]
  77. if not cid or not csecret:
  78. raise RegistrationError("authorization succeeded but credentials are missing")
  79. return cid, csecret
  80. elif not _within_retry_window():
  81. raise RegistrationError(f"authorization failed: {result.get('fail_reason') or status}")
  82. raise RegistrationError("authorization timed out, please retry")
  83. def _ensure_qrcode_installed() -> bool:
  84. """Enable DingTalk dependencies; only render QR codes importable in this process."""
  85. with contextlib.suppress(ImportError):
  86. import qrcode
  87. return True
  88. import pm
  89. with contextlib.suppress(pm.InstallError, OSError, ValueError):
  90. pm.sync_venv(["dingtalk"], explicit=True)
  91. # PM selects a new generation for the next launch, never this process.
  92. # The authorization link works without qrcode, so no restart is required here.
  93. return False
  94. def render_qr_to_terminal(url: str) -> bool:
  95. """Render *url* as a compact QR code (half-block glyphs, 2 rows per character) in the terminal."""
  96. try:
  97. import qrcode
  98. except ImportError:
  99. return False
  100. qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=1, border=1)
  101. qr.add_data(url)
  102. qr.make(fit=True)
  103. matrix = qr.get_matrix()
  104. glyph = {(True, True): "\u2588", (True, False): "\u2580", (False, True): "\u2584", (False, False): " "} # █ ▀ ▄ space
  105. lines = []
  106. for r in range(0, len(matrix), 2):
  107. bottom_row = matrix[r + 1] if r + 1 < len(matrix) else [False] * len(matrix[r])
  108. lines.append(" " + "".join(glyph[(bool(top), bool(bottom))] for top, bottom in zip(matrix[r], bottom_row)))
  109. print("\n".join(lines))
  110. return True
  111. def dingtalk_qr_auth() -> Optional[tuple[str, str]]:
  112. """Run the interactive QR-code device-flow authorization (setup wizard entry point)."""
  113. from hermes_cli.setup import print_info, print_success, print_warning, print_error
  114. print()
  115. print_info(" Initializing DingTalk device authorization...")
  116. print_info(" Note: the scan page is branded 'OpenClaw' — DingTalk's")
  117. print_info(" ecosystem onboarding bridge. Safe to use.")
  118. try:
  119. reg = begin_registration()
  120. except RegistrationError as exc:
  121. print_error(f" Authorization init failed: {exc}")
  122. return None
  123. url = reg["verification_uri_complete"]
  124. if not _ensure_qrcode_installed():
  125. print_warning(" QR rendering is unavailable in this process; using the authorization link.")
  126. print()
  127. print_info(" Please scan the QR code below with DingTalk to authorize:")
  128. print()
  129. if not render_qr_to_terminal(url):
  130. print_warning(" QR code render failed, please open the link below to authorize:")
  131. print()
  132. print_info(f" Or open this link manually: {url}")
  133. print()
  134. print_info(" Waiting for QR scan authorization... (timeout: 2 hours)")
  135. dot_count = 0
  136. def _on_waiting():
  137. nonlocal dot_count
  138. dot_count += 1
  139. if dot_count % 10 == 0:
  140. sys.stdout.write(".")
  141. sys.stdout.flush()
  142. try:
  143. client_id, client_secret = wait_for_registration_success(
  144. device_code=reg["device_code"], interval=reg["interval"], expires_in=reg["expires_in"],
  145. on_waiting=_on_waiting,
  146. )
  147. except RegistrationError as exc:
  148. print()
  149. print_error(f" Authorization failed: {exc}")
  150. return None
  151. print()
  152. print_success(" QR scan authorization successful!")
  153. print_success(f" Client ID: {client_id}")
  154. print_success(f" Client Secret: {client_secret[:8]}{'*' * (len(client_secret) - 8)}")
  155. return client_id, client_secret