setup.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #!/usr/bin/env python3
  2. """Google Workspace OAuth2 setup for Hermes Agent.
  3. Fully non-interactive — designed to be driven by the agent via terminal commands.
  4. The agent mediates between this script and the user (works on CLI, Telegram, Discord, etc.)
  5. Commands:
  6. setup.py --check # Is auth valid? Exit 0 = yes, 1 = no
  7. setup.py --client-secret /path/to.json # Store OAuth client credentials
  8. setup.py --auth-url # Print the OAuth URL for user to visit
  9. setup.py --auth-code CODE # Exchange auth code for token
  10. setup.py --revoke # Revoke and delete stored token
  11. setup.py --install-deps # Install Python dependencies only
  12. Agent workflow:
  13. 1. Run --check. If exit 0, auth is good — skip setup.
  14. 2. Ask user for client_secret.json path. Run --client-secret PATH.
  15. 3. Run --auth-url. Send the printed URL to the user.
  16. 4. User opens URL, authorizes, gets redirected to a page with a code.
  17. 5. User pastes the code. Agent runs --auth-code CODE.
  18. 6. Run --check to verify. Done.
  19. """
  20. from __future__ import annotations # allow PEP 604 `X | None` on Python 3.9+
  21. import argparse
  22. import json
  23. import os
  24. import sys
  25. from pathlib import Path
  26. try:
  27. import pm
  28. except ImportError:
  29. # A copied skill must not install into an unrelated Python environment.
  30. pm = None
  31. # Ensure sibling modules (_hermes_home) are importable when run standalone.
  32. _SCRIPTS_DIR = str(Path(__file__).resolve().parent)
  33. if _SCRIPTS_DIR not in sys.path:
  34. sys.path.insert(0, _SCRIPTS_DIR)
  35. from _hermes_home import display_hermes_home, get_hermes_home
  36. HERMES_HOME = get_hermes_home()
  37. TOKEN_PATH = HERMES_HOME / "google_token.json"
  38. CLIENT_SECRET_PATH = HERMES_HOME / "google_client_secret.json"
  39. PENDING_AUTH_PATH = HERMES_HOME / "google_oauth_pending.json"
  40. SCOPES = [
  41. "https://www.googleapis.com/auth/gmail.readonly",
  42. "https://www.googleapis.com/auth/gmail.send",
  43. "https://www.googleapis.com/auth/gmail.modify",
  44. "https://www.googleapis.com/auth/calendar",
  45. "https://www.googleapis.com/auth/drive",
  46. "https://www.googleapis.com/auth/contacts.readonly",
  47. "https://www.googleapis.com/auth/spreadsheets",
  48. "https://www.googleapis.com/auth/documents",
  49. ]
  50. # OAuth redirect for "out of band" manual code copy flow.
  51. # Google deprecated OOB, so we use a localhost redirect and tell the user to
  52. # copy the code from the browser's URL bar (or the page body).
  53. REDIRECT_URI = "http://localhost:1"
  54. def _normalize_authorized_user_payload(payload: dict) -> dict:
  55. normalized = dict(payload)
  56. if not normalized.get("type"):
  57. normalized["type"] = "authorized_user"
  58. return normalized
  59. def _load_token_payload(path: Path = TOKEN_PATH) -> dict:
  60. try:
  61. return json.loads(path.read_text(encoding="utf-8"))
  62. except Exception:
  63. return {}
  64. def _missing_scopes_from_payload(payload: dict) -> list[str]:
  65. raw = payload.get("scopes") or payload.get("scope")
  66. if not raw:
  67. return []
  68. granted = {s.strip() for s in (raw.split() if isinstance(raw, str) else raw) if s.strip()}
  69. return sorted(scope for scope in SCOPES if scope not in granted)
  70. def _format_missing_scopes(missing_scopes: list[str]) -> str:
  71. bullets = "\n".join(f" - {scope}" for scope in missing_scopes)
  72. return (
  73. "Token is valid but missing required Google Workspace scopes:\n"
  74. f"{bullets}\n"
  75. "Run the Google Workspace setup again from this same Hermes profile to refresh consent."
  76. )
  77. def install_deps():
  78. """Sync Hermes' declared Google extra, ready for the next process."""
  79. if pm is None:
  80. print("ERROR: Run this script in the Hermes environment; use hermes setup first.")
  81. return False
  82. try:
  83. pm.sync_venv(["google"], explicit=True)
  84. except Exception as exc:
  85. print(f"ERROR: Failed to install Google dependencies: {exc}")
  86. return False
  87. print("Google dependencies synced. Restart Hermes, then rerun setup to continue OAuth.")
  88. return True
  89. def _ensure_deps():
  90. """Let PM check imports and stop if activation needs a new process."""
  91. if pm is None:
  92. print("ERROR: Run this script in the Hermes environment; use hermes setup first.")
  93. sys.exit(1)
  94. try:
  95. pm.ensure_import("google")
  96. except Exception as exc:
  97. print(f"ERROR: Google dependencies unavailable: {exc}")
  98. sys.exit(1)
  99. def check_auth_live():
  100. """Check auth with a real API call to detect disabled_client/account issues."""
  101. # quiet=True suppresses the "AUTHENTICATED" print from check_auth so the
  102. # final status line reflects the live-call outcome (OK or FAILED).
  103. if not check_auth(quiet=True):
  104. return False
  105. try:
  106. from googleapiclient.discovery import build
  107. from google.oauth2.credentials import Credentials
  108. creds = Credentials.from_authorized_user_file(str(TOKEN_PATH))
  109. service = build("calendar", "v3", credentials=creds)
  110. service.calendarList().list(maxResults=1).execute()
  111. print("LIVE_CHECK_OK: Real API call succeeded.")
  112. return True
  113. except Exception as e:
  114. err_str = str(e).lower()
  115. if "disabled_client" in err_str or "invalid_client" in err_str:
  116. print(f"LIVE_CHECK_FAILED: OAuth client or account disabled: {e}")
  117. print(" 1. Check Google Cloud Console for disabled OAuth client")
  118. print(" 2. Check myaccount.google.com for account status")
  119. print(" 3. Do NOT retry with a disabled account")
  120. else:
  121. print(f"LIVE_CHECK_FAILED: {e}")
  122. return False
  123. def check_auth(quiet: bool = False):
  124. """Check if stored credentials are valid. Prints status, exits 0 or 1."""
  125. if not TOKEN_PATH.exists():
  126. print(f"NOT_AUTHENTICATED: No token at {TOKEN_PATH}")
  127. return False
  128. _ensure_deps()
  129. from google.oauth2.credentials import Credentials
  130. from google.auth.transport.requests import Request
  131. try:
  132. # Don't pass scopes — user may have authorized only a subset.
  133. # Passing scopes forces google-auth to validate them on refresh,
  134. # which fails with invalid_scope if the token has fewer scopes
  135. # than requested.
  136. creds = Credentials.from_authorized_user_file(str(TOKEN_PATH))
  137. except Exception as e:
  138. print(f"TOKEN_CORRUPT: {e}")
  139. return False
  140. payload = _load_token_payload(TOKEN_PATH)
  141. if creds.valid:
  142. missing_scopes = _missing_scopes_from_payload(payload)
  143. if missing_scopes:
  144. print(f"AUTHENTICATED (partial): Token valid but missing {len(missing_scopes)} scopes:")
  145. for s in missing_scopes:
  146. print(f" - {s}")
  147. if not quiet:
  148. print(f"AUTHENTICATED: Token valid at {TOKEN_PATH}")
  149. return True
  150. if creds.expired and creds.refresh_token:
  151. try:
  152. creds.refresh(Request())
  153. TOKEN_PATH.write_text(
  154. json.dumps(
  155. _normalize_authorized_user_payload(json.loads(creds.to_json())),
  156. indent=2,
  157. ), encoding="utf-8"
  158. )
  159. missing_scopes = _missing_scopes_from_payload(_load_token_payload(TOKEN_PATH))
  160. if missing_scopes:
  161. print(f"AUTHENTICATED (partial): Token refreshed but missing {len(missing_scopes)} scopes:")
  162. for s in missing_scopes:
  163. print(f" - {s}")
  164. if not quiet:
  165. print(f"AUTHENTICATED: Token refreshed at {TOKEN_PATH}")
  166. return True
  167. except Exception as e:
  168. err_str = str(e).lower()
  169. if "disabled_client" in err_str or "invalid_client" in err_str:
  170. print(f"OAUTH_CLIENT_DISABLED: {e}")
  171. print(" The OAuth client or Google account has been disabled.")
  172. print(" Steps to resolve:")
  173. print(" 1. Check your Google Cloud Console — verify the OAuth client is not disabled")
  174. print(" 2. Check if your Google account itself has been disabled at myaccount.google.com")
  175. print(" 3. If the account is disabled, you can appeal at accounts.google.com/signin/recovery")
  176. print(" 4. Do NOT retry API calls with a disabled account — this may worsen the situation")
  177. print(" 5. If the OAuth client is disabled, create a new one in Google Cloud Console")
  178. elif "token_revoked" in err_str or "invalid_grant" in err_str:
  179. print(f"TOKEN_REVOKED: {e}")
  180. print(" Re-run setup to re-authenticate.")
  181. else:
  182. print(f"REFRESH_FAILED: {e}")
  183. return False
  184. print("TOKEN_INVALID: Re-run setup.")
  185. return False
  186. def store_client_secret(path: str):
  187. """Copy and validate client_secret.json to Hermes home."""
  188. src = Path(path).expanduser().resolve()
  189. if not src.exists():
  190. print(f"ERROR: File not found: {src}")
  191. sys.exit(1)
  192. try:
  193. data = json.loads(src.read_text(encoding="utf-8"))
  194. except json.JSONDecodeError:
  195. print("ERROR: File is not valid JSON.")
  196. sys.exit(1)
  197. if "installed" not in data and "web" not in data:
  198. print("ERROR: Not a Google OAuth client secret file (missing 'installed' key).")
  199. print("Download the correct file from: https://console.cloud.google.com/apis/credentials")
  200. sys.exit(1)
  201. CLIENT_SECRET_PATH.write_text(json.dumps(data, indent=2), encoding="utf-8")
  202. print(f"OK: Client secret saved to {CLIENT_SECRET_PATH}")
  203. def _save_pending_auth(*, state: str, code_verifier: str):
  204. """Persist the OAuth session bits needed for a later token exchange."""
  205. PENDING_AUTH_PATH.write_text(
  206. json.dumps(
  207. {
  208. "state": state,
  209. "code_verifier": code_verifier,
  210. "redirect_uri": REDIRECT_URI,
  211. },
  212. indent=2,
  213. ), encoding="utf-8"
  214. )
  215. def _load_pending_auth() -> dict:
  216. """Load the pending OAuth session created by get_auth_url()."""
  217. if not PENDING_AUTH_PATH.exists():
  218. print("ERROR: No pending OAuth session found. Run --auth-url first.")
  219. sys.exit(1)
  220. try:
  221. data = json.loads(PENDING_AUTH_PATH.read_text(encoding="utf-8"))
  222. except Exception as e:
  223. print(f"ERROR: Could not read pending OAuth session: {e}")
  224. print("Run --auth-url again to start a fresh OAuth session.")
  225. sys.exit(1)
  226. if not data.get("state") or not data.get("code_verifier"):
  227. print("ERROR: Pending OAuth session is missing PKCE data.")
  228. print("Run --auth-url again to start a fresh OAuth session.")
  229. sys.exit(1)
  230. return data
  231. def _extract_code_and_state(code_or_url: str) -> tuple[str, str | None]:
  232. """Accept either a raw auth code or the full redirect URL pasted by the user."""
  233. if not code_or_url.startswith("http"):
  234. return code_or_url, None
  235. from urllib.parse import parse_qs, urlparse
  236. parsed = urlparse(code_or_url)
  237. params = parse_qs(parsed.query)
  238. if "code" not in params:
  239. print("ERROR: No 'code' parameter found in URL.")
  240. sys.exit(1)
  241. state = params.get("state", [None])[0]
  242. return params["code"][0], state
  243. def get_auth_url():
  244. """Print the OAuth authorization URL. User visits this in a browser."""
  245. if not CLIENT_SECRET_PATH.exists():
  246. print("ERROR: No client secret stored. Run --client-secret first.")
  247. sys.exit(1)
  248. _ensure_deps()
  249. from google_auth_oauthlib.flow import Flow
  250. flow = Flow.from_client_secrets_file(
  251. str(CLIENT_SECRET_PATH),
  252. scopes=SCOPES,
  253. redirect_uri=REDIRECT_URI,
  254. autogenerate_code_verifier=True,
  255. )
  256. auth_url, state = flow.authorization_url(
  257. access_type="offline",
  258. prompt="consent",
  259. )
  260. _save_pending_auth(state=state, code_verifier=flow.code_verifier)
  261. # Print just the URL so the agent can extract it cleanly
  262. print(auth_url)
  263. def exchange_auth_code(code: str):
  264. """Exchange the authorization code for a token and save it."""
  265. if not CLIENT_SECRET_PATH.exists():
  266. print("ERROR: No client secret stored. Run --client-secret first.")
  267. sys.exit(1)
  268. pending_auth = _load_pending_auth()
  269. raw_callback = code
  270. code, returned_state = _extract_code_and_state(code)
  271. if returned_state and returned_state != pending_auth["state"]:
  272. print("ERROR: OAuth state mismatch. Run --auth-url again to start a fresh session.")
  273. sys.exit(1)
  274. _ensure_deps()
  275. from google_auth_oauthlib.flow import Flow
  276. from urllib.parse import parse_qs, urlparse
  277. # Extract granted scopes from the callback URL if the user pasted the full redirect URL.
  278. granted_scopes = list(SCOPES)
  279. if isinstance(raw_callback, str) and raw_callback.startswith("http"):
  280. params = parse_qs(urlparse(raw_callback).query)
  281. scope_val = (params.get("scope") or [""])[0].strip()
  282. if scope_val:
  283. granted_scopes = scope_val.split()
  284. flow = Flow.from_client_secrets_file(
  285. str(CLIENT_SECRET_PATH),
  286. scopes=granted_scopes,
  287. redirect_uri=pending_auth.get("redirect_uri", REDIRECT_URI),
  288. state=pending_auth["state"],
  289. code_verifier=pending_auth["code_verifier"],
  290. )
  291. try:
  292. # Accept partial scopes — user may deselect some permissions in the consent screen
  293. os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = "1"
  294. flow.fetch_token(code=code)
  295. except Exception as e:
  296. print(f"ERROR: Token exchange failed: {e}")
  297. print("The code may have expired. Run --auth-url to get a fresh URL.")
  298. sys.exit(1)
  299. creds = flow.credentials
  300. token_payload = _normalize_authorized_user_payload(json.loads(creds.to_json()))
  301. # Store only the scopes actually granted by the user, not what was requested.
  302. # creds.to_json() writes the requested scopes, which causes refresh to fail
  303. # with invalid_scope if the user only authorized a subset.
  304. actually_granted = list(creds.granted_scopes or []) if hasattr(creds, "granted_scopes") and creds.granted_scopes else []
  305. if actually_granted:
  306. token_payload["scopes"] = actually_granted
  307. elif granted_scopes != SCOPES:
  308. # granted_scopes was extracted from the callback URL
  309. token_payload["scopes"] = granted_scopes
  310. missing_scopes = _missing_scopes_from_payload(token_payload)
  311. if missing_scopes:
  312. print(f"WARNING: Token missing some Google Workspace scopes: {', '.join(missing_scopes)}")
  313. print("Some services may not be available.")
  314. TOKEN_PATH.write_text(json.dumps(token_payload, indent=2), encoding="utf-8")
  315. PENDING_AUTH_PATH.unlink(missing_ok=True)
  316. print(f"OK: Authenticated. Token saved to {TOKEN_PATH}")
  317. print(f"Profile-scoped token location: {display_hermes_home()}/google_token.json")
  318. def revoke():
  319. """Revoke stored token and delete it."""
  320. if not TOKEN_PATH.exists():
  321. print("No token to revoke.")
  322. return
  323. _ensure_deps()
  324. from google.oauth2.credentials import Credentials
  325. from google.auth.transport.requests import Request
  326. try:
  327. creds = Credentials.from_authorized_user_file(str(TOKEN_PATH), SCOPES)
  328. if creds.expired and creds.refresh_token:
  329. creds.refresh(Request())
  330. import urllib.request
  331. urllib.request.urlopen(
  332. urllib.request.Request(
  333. f"https://oauth2.googleapis.com/revoke?token={creds.token}",
  334. method="POST",
  335. headers={"Content-Type": "application/x-www-form-urlencoded"},
  336. ),
  337. timeout=15,
  338. )
  339. print("Token revoked with Google.")
  340. except Exception as e:
  341. print(f"Remote revocation failed (token may already be invalid): {e}")
  342. TOKEN_PATH.unlink(missing_ok=True)
  343. PENDING_AUTH_PATH.unlink(missing_ok=True)
  344. print(f"Deleted {TOKEN_PATH}")
  345. def main():
  346. parser = argparse.ArgumentParser(description="Google Workspace OAuth setup for Hermes")
  347. group = parser.add_mutually_exclusive_group(required=True)
  348. group.add_argument("--check", action="store_true", help="Check if auth is valid (exit 0=yes, 1=no)")
  349. group.add_argument("--check-live", action="store_true", help="Check auth with a real API call (detects disabled_client)")
  350. group.add_argument("--client-secret", metavar="PATH", help="Store OAuth client_secret.json")
  351. group.add_argument("--auth-url", action="store_true", help="Print OAuth URL for user to visit")
  352. group.add_argument("--auth-code", metavar="CODE", help="Exchange auth code for token")
  353. group.add_argument("--revoke", action="store_true", help="Revoke and delete stored token")
  354. group.add_argument("--install-deps", action="store_true", help="Install Python dependencies")
  355. args = parser.parse_args()
  356. if args.check:
  357. sys.exit(0 if check_auth() else 1)
  358. if getattr(args, "check_live", False):
  359. sys.exit(0 if check_auth_live() else 1)
  360. elif args.client_secret:
  361. store_client_secret(args.client_secret)
  362. elif args.auth_url:
  363. get_auth_url()
  364. elif args.auth_code:
  365. exchange_auth_code(args.auth_code)
  366. elif args.revoke:
  367. revoke()
  368. elif args.install_deps:
  369. sys.exit(0 if install_deps() else 1)
  370. if __name__ == "__main__":
  371. main()