auth.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. """Photon Dashboard API client + device-code login flow (pure Python, no spectrum-ts).
  2. Management calls hit ``https://app.photon.codes/api/...`` (OAuth 2.0 device flow, Bearer)
  3. like the official CLI. The dashboard project ``id`` *is* the Spectrum Cloud project id and
  4. Spectrum is always provisioned at create-time; the sidecar authenticates with
  5. ``(id, projectSecret)``. Storage: runtime SDK creds -> ``~/.hermes/.env``; management
  6. metadata -> ``auth.json`` under ``credential_pool.photon`` (device token), ``photon_project``
  7. (ids + secret for offline status) and ``photon_user`` (numbers).
  8. """
  9. from __future__ import annotations
  10. import json
  11. import logging
  12. import os
  13. import re
  14. import stat
  15. import time
  16. import uuid
  17. from base64 import b64encode
  18. from dataclasses import dataclass
  19. from pathlib import Path
  20. from typing import Any, Callable, Dict, List, Optional, Tuple
  21. try:
  22. import httpx
  23. except ImportError: # pragma: no cover - httpx is a hermes dependency
  24. httpx = None # type: ignore[assignment]
  25. from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret
  26. from hermes_constants import get_hermes_home
  27. import contextlib
  28. logger = logging.getLogger(__name__)
  29. class PhotonDashboardAuthError(RuntimeError):
  30. """Raised when Photon rejects a device-flow token for the dashboard API."""
  31. # Hosted Photon allowlists device clients (unregistered → 400 invalid_client); use Photon's
  32. # published CLI client until Hermes gets its own client_id.
  33. DEFAULT_CLIENT_ID = "photon-cli"
  34. DEFAULT_SCOPE = "openid profile email"
  35. DEFAULT_DASHBOARD_HOST = "https://app.photon.codes"
  36. DEFAULT_SPECTRUM_HOST = "https://spectrum.photon.codes"
  37. DEFAULT_PROJECT_NAME = "Hermes Agent"
  38. DEFAULT_POLL_INTERVAL = 5 # RFC 8628 polling defaults; Photon's `interval` / `expires_in` win
  39. DEFAULT_POLL_TIMEOUT = 1800
  40. E164_RE = re.compile(r"^\+[1-9]\d{6,14}$")
  41. # -- auth.json helpers (shares the file with the rest of hermes-agent) ------------
  42. def _auth_json_path() -> Path:
  43. """The active profile's ``auth.json`` (shared with the rest of hermes-agent)."""
  44. return get_hermes_home() / "auth.json"
  45. def _load_auth() -> dict[str, Any]:
  46. path = _auth_json_path()
  47. if not path.exists():
  48. return {}
  49. try:
  50. with path.open("r", encoding="utf-8-sig") as fh:
  51. return json.load(fh) or {}
  52. except (OSError, json.JSONDecodeError) as e:
  53. logger.warning("photon: could not read %s: %s", path, e)
  54. return {}
  55. def _save_auth(data: dict[str, Any]) -> None:
  56. path = _auth_json_path()
  57. path.parent.mkdir(parents=True, exist_ok=True)
  58. # Random per-process temp name (no collisions / pre-planted symlinks), created 0o600
  59. # atomically via O_EXCL so the bearer token is never world-readable at umask.
  60. tmp = path.with_name(f"{path.name}.tmp.{os.getpid()}.{uuid.uuid4().hex}")
  61. fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL, stat.S_IRUSR | stat.S_IWUSR)
  62. try:
  63. fh = os.fdopen(fd, "w", encoding="utf-8")
  64. except BaseException: # fdopen failed before owning the descriptor — nothing else will close it
  65. with contextlib.suppress(OSError):
  66. os.close(fd)
  67. with contextlib.suppress(OSError):
  68. tmp.unlink()
  69. raise
  70. try:
  71. with fh:
  72. json.dump(data, fh, indent=2, sort_keys=True)
  73. fh.flush()
  74. os.fsync(fh.fileno())
  75. tmp.replace(path)
  76. except BaseException:
  77. with contextlib.suppress(OSError):
  78. tmp.unlink()
  79. raise
  80. def _pool_first(auth: dict[str, Any], key: str) -> Any:
  81. """First entry of ``credential_pool.<key>`` (a list), or None."""
  82. pool = auth.get("credential_pool", {}).get(key) or []
  83. return pool[0] if isinstance(pool, list) and pool else None
  84. def _store_pool_record(key: str, record: dict[str, Any]) -> None:
  85. """Replace ``credential_pool.<key>`` with ``[record]`` under the cross-process lock."""
  86. from hermes_cli.auth import _auth_store_lock
  87. with _auth_store_lock():
  88. auth = _load_auth()
  89. auth.setdefault("credential_pool", {})[key] = [record]
  90. _save_auth(auth)
  91. def load_photon_token() -> Optional[str]:
  92. """Return the device-flow bearer token stored by ``login()`` or ``None``."""
  93. auth = _load_auth()
  94. entry = _pool_first(auth, "photon") or {}
  95. legacy = auth.get("providers", {}).get("photon", {}) # backwards-compat shape
  96. token = entry.get("access_token") or entry.get("token") or legacy.get("access_token")
  97. return str(token) if token else None
  98. def store_photon_token(token: str) -> None:
  99. """Persist a dashboard bearer token under ``credential_pool.photon``."""
  100. _store_pool_record("photon", {"access_token": token, "issued_at": int(time.time())})
  101. def clear_photon_token() -> None:
  102. """Remove any stored Photon dashboard token (before re-authentication)."""
  103. auth = _load_auth()
  104. pool = auth.get("credential_pool", {})
  105. photon = pool.get("photon", [])
  106. if isinstance(photon, list) and photon:
  107. pool["photon"] = []
  108. _save_auth(auth)
  109. providers = auth.get("providers", {}) # legacy shape
  110. if "photon" in providers:
  111. providers["photon"] = {}
  112. _save_auth(auth)
  113. def check_photon_token_valid(token: str) -> bool:
  114. """True if the dashboard API accepts the token; a definitive rejection is stale,
  115. transient failures (network, 5xx) count as valid so they don't force a re-login."""
  116. if not token:
  117. return False
  118. try:
  119. validate_photon_token(token)
  120. except PhotonDashboardAuthError:
  121. return False
  122. except Exception:
  123. pass
  124. return True
  125. def load_project_credentials() -> tuple[Optional[str], Optional[str]]:
  126. """Runtime SDK creds ``(spectrum_project_id, project_secret)``: process env wins
  127. (``.env`` is loaded at gateway startup), then ``auth.json`` for offline/status."""
  128. env_id = _get_scoped_secret("PHOTON_PROJECT_ID")
  129. env_sec = _get_scoped_secret("PHOTON_PROJECT_SECRET")
  130. if env_id and env_sec:
  131. return env_id, env_sec
  132. entry = _pool_first(_load_auth(), "photon_project")
  133. if entry is None:
  134. return env_id, env_sec
  135. # back-compat: old records used "project_id" for the spectrum id
  136. return env_id or entry.get("spectrum_project_id") or entry.get("project_id"), env_sec or entry.get("project_secret")
  137. def load_dashboard_project_id() -> Optional[str]:
  138. """Project id for management API calls — prefers ``spectrum_project_id`` (on
  139. pre-backfill installs the old ``dashboard_project_id`` is diverged and 404s)."""
  140. env_id = _get_scoped_secret("PHOTON_DASHBOARD_PROJECT_ID")
  141. if env_id:
  142. return env_id
  143. entry = _pool_first(_load_auth(), "photon_project") or {}
  144. return entry.get("spectrum_project_id") or entry.get("dashboard_project_id") or entry.get("project_id")
  145. def store_project_credentials(
  146. *, spectrum_project_id: str, project_secret: str,
  147. dashboard_project_id: Optional[str] = None, name: Optional[str] = None) -> None:
  148. """Persist project credentials to both .env (runtime) and auth.json (mgmt/offline status)."""
  149. record: dict[str, Any] = {
  150. "spectrum_project_id": spectrum_project_id, "project_secret": project_secret, "issued_at": int(time.time())}
  151. record.update({k: v for k, v in (("dashboard_project_id", dashboard_project_id), ("name", name)) if v})
  152. _store_pool_record("photon_project", record)
  153. _persist_runtime_env(spectrum_project_id, project_secret)
  154. def store_user_numbers(
  155. *, phone_number: Optional[str] = None, assigned_phone_number: Optional[str] = None,
  156. user_id: Optional[str] = None, dashboard_project_id: Optional[str] = None) -> None:
  157. """Persist non-secret Photon user numbers for offline ``status`` output."""
  158. if not phone_number and not assigned_phone_number:
  159. return
  160. record: dict[str, Any] = {"issued_at": int(time.time())}
  161. record.update({k: v for k, v in (
  162. ("phone_number", phone_number), ("assigned_phone_number", assigned_phone_number),
  163. ("user_id", user_id), ("dashboard_project_id", dashboard_project_id)) if v})
  164. _store_pool_record("photon_user", record)
  165. def _persist_runtime_env(spectrum_project_id: str, project_secret: str) -> None:
  166. """Write the SDK creds to ``~/.hermes/.env`` (secret never bound to a printable local
  167. in a caller — CodeQL clean flow)."""
  168. try:
  169. from hermes_cli.config import save_env_value
  170. except ImportError:
  171. logger.warning("photon: hermes_cli.config unavailable — skipping .env write")
  172. return
  173. try:
  174. save_env_value("PHOTON_PROJECT_ID", spectrum_project_id)
  175. save_env_value("PHOTON_PROJECT_SECRET", project_secret)
  176. except Exception as e: # pragma: no cover - defensive
  177. logger.warning("photon: could not write project creds to .env: %s", e)
  178. # -- HTTP plumbing ----------------------------------------------------------------
  179. def _dashboard_host() -> str:
  180. return (os.getenv("PHOTON_DASHBOARD_HOST") or DEFAULT_DASHBOARD_HOST).rstrip("/")
  181. def _spectrum_host() -> str:
  182. return (os.getenv("PHOTON_SPECTRUM_HOST") or DEFAULT_SPECTRUM_HOST).rstrip("/")
  183. def _bearer(token: str) -> dict[str, str]:
  184. return {"Authorization": f"Bearer {token}"}
  185. def _basic(project_id: str, project_secret: str) -> dict[str, str]:
  186. token = b64encode(f"{project_id}:{project_secret}".encode()).decode("ascii")
  187. return {"Authorization": f"Basic {token}"}
  188. def _require_httpx(what: str = "") -> None:
  189. if httpx is None:
  190. raise RuntimeError(f"httpx is required for Photon{what}")
  191. def _dashboard_get(path: str, token: str, *, what: str = " device login") -> Any:
  192. _require_httpx(what)
  193. return httpx.get(f"{_dashboard_host()}{path}", headers=_bearer(token), timeout=30.0)
  194. def _dashboard_post(path: str, body: dict[str, Any], token: str, *, what: str = "") -> Any:
  195. """POST to the dashboard, raise for HTTP errors, return the decoded body."""
  196. _require_httpx(what)
  197. resp = httpx.post(f"{_dashboard_host()}{path}", json=body, headers=_bearer(token), timeout=30.0)
  198. resp.raise_for_status()
  199. return resp.json() or {}
  200. def _response_error_detail(resp: Any) -> str:
  201. data = None
  202. with contextlib.suppress(Exception):
  203. data = resp.json()
  204. if isinstance(data, dict):
  205. for key in ("error", "message", "detail"):
  206. if data.get(key):
  207. return str(data[key])
  208. return json.dumps(data, sort_keys=True)[:500]
  209. text = getattr(resp, "text", "") or ""
  210. return text[:500] if text else "no response body"
  211. def _raise_for_status(resp: Any, action: str) -> None:
  212. status = getattr(resp, "status_code", 200)
  213. if status >= 400:
  214. raise RuntimeError(f"Photon {action} failed: HTTP {status}: {_response_error_detail(resp)}")
  215. def _safe(fn: Callable[[], None]) -> None:
  216. with contextlib.suppress(Exception):
  217. fn()
  218. # -- Device login flow (RFC 8628) ----------------------------------------------------
  219. @dataclass
  220. class DeviceCode:
  221. device_code: str
  222. user_code: str
  223. verification_uri: str
  224. verification_uri_complete: Optional[str]
  225. expires_in: int
  226. interval: int
  227. @dataclass(frozen=True)
  228. class _DeviceTokenCandidate:
  229. """A token-like value extracted from the device-token response."""
  230. source: str
  231. token: str
  232. def request_device_code(
  233. *, client_id: str = DEFAULT_CLIENT_ID, scope: Optional[str] = DEFAULT_SCOPE) -> DeviceCode:
  234. """POST ``/api/auth/device/code`` and return the device + user codes."""
  235. _require_httpx(" device login")
  236. body: dict[str, Any] = {"client_id": client_id}
  237. if scope:
  238. body["scope"] = scope
  239. resp = httpx.post(f"{_dashboard_host()}/api/auth/device/code", json=body, timeout=30.0)
  240. resp.raise_for_status()
  241. data = resp.json()
  242. return DeviceCode(
  243. device_code=data["device_code"], user_code=data["user_code"],
  244. verification_uri=data["verification_uri"],
  245. verification_uri_complete=data.get("verification_uri_complete"),
  246. expires_in=int(data.get("expires_in") or DEFAULT_POLL_TIMEOUT),
  247. interval=int(data.get("interval") or DEFAULT_POLL_INTERVAL))
  248. def poll_for_token(
  249. code: DeviceCode, *, client_id: str = DEFAULT_CLIENT_ID, timeout: Optional[int] = None,
  250. interval: Optional[int] = None, on_pending: Optional[Callable[[], None]] = None) -> str:
  251. """Poll ``/api/auth/device/token`` until approved (official-CLI semantics: sleep first;
  252. ``authorization_pending`` keeps the interval, ``slow_down`` +5s, HTTP 429 +10s,
  253. ``access_denied``/``expired_token`` abort)."""
  254. _require_httpx(" device login")
  255. url = f"{_dashboard_host()}/api/auth/device/token"
  256. deadline = time.time() + (timeout or code.expires_in or DEFAULT_POLL_TIMEOUT)
  257. sleep = interval if interval is not None else (code.interval or DEFAULT_POLL_INTERVAL)
  258. grant = {"grant_type": "urn:ietf:params:oauth:grant-type:device_code", "device_code": code.device_code,
  259. "client_id": client_id}
  260. def _pending() -> None:
  261. if on_pending:
  262. _safe(on_pending)
  263. while time.time() < deadline:
  264. time.sleep(sleep)
  265. try:
  266. resp = httpx.post(url, json=grant, timeout=30.0)
  267. except httpx.RequestError as e:
  268. logger.warning("photon: device-token poll failed: %s", e)
  269. continue
  270. if resp.status_code == 200:
  271. body: Any = {}
  272. with contextlib.suppress(TypeError, ValueError): # json.JSONDecodeError is a ValueError
  273. body = resp.json() or {}
  274. body = body if isinstance(body, dict) else {}
  275. candidates = _device_response_token_candidates(body, headers=getattr(resp, "headers", {}))
  276. if not candidates:
  277. raise RuntimeError(
  278. "Photon returned 200 but no token candidate in the device-token response "
  279. "(expected access_token, data.access_token, accessToken, or set-auth-token).")
  280. return candidates[0].token
  281. if resp.status_code == 429: # RFC 8628 §3.5 — treat as slow_down
  282. sleep += 10
  283. _pending()
  284. continue
  285. if resp.status_code == 400:
  286. body = {}
  287. with contextlib.suppress(json.JSONDecodeError):
  288. body = resp.json() or {}
  289. err = body.get("error") or body.get("message") or ""
  290. if err in ("authorization_pending", "slow_down"):
  291. if err == "slow_down":
  292. sleep += 5
  293. _pending()
  294. continue
  295. if err in ("expired_token", "access_denied"):
  296. raise RuntimeError(f"Photon login failed: {err}")
  297. raise RuntimeError(f"Photon device token error: {err or resp.text}")
  298. logger.warning("photon: device-token unexpected status %s: %s", resp.status_code, resp.text[:200])
  299. raise TimeoutError("Photon device login timed out")
  300. def _device_response_token_candidates(body: dict[str, Any], *, headers: Optional[Any] = None) -> list:
  301. """De-duplicated token candidates from a device-token response — Photon has returned
  302. tokens under several keys across versions plus the ``set-auth-token`` header, so
  303. collect every shape for validation."""
  304. session = body.get("session") if isinstance(body.get("session"), dict) else {}
  305. data = body.get("data") if isinstance(body.get("data"), dict) else {}
  306. raw = (
  307. ("access_token", body.get("access_token")), ("accessToken", body.get("accessToken")),
  308. ("session.access_token", session.get("access_token")),
  309. ("data.access_token", data.get("access_token")), ("data.accessToken", data.get("accessToken")),
  310. ("set-auth-token", _header_value(headers, "set-auth-token")))
  311. candidates: list = []
  312. seen: set = set()
  313. for source, value in raw:
  314. token = _clean_bearer_token(value)
  315. if token and token not in seen:
  316. seen.add(token)
  317. candidates.append(_DeviceTokenCandidate(source=source, token=token))
  318. return candidates
  319. def _clean_bearer_token(value: Any) -> Optional[str]:
  320. if not isinstance(value, str):
  321. return None
  322. token = value.strip()
  323. return (token[7:].strip() if token.lower().startswith("bearer ") else token) or None
  324. def _header_value(headers: Optional[Any], name: str) -> Optional[str]:
  325. if not headers:
  326. return None
  327. with contextlib.suppress(AttributeError):
  328. value = headers.get(name)
  329. if value:
  330. return str(value)
  331. with contextlib.suppress(TypeError, ValueError):
  332. for key, value in dict(headers).items():
  333. if str(key).lower() == name.lower() and value:
  334. return str(value)
  335. return None
  336. def validate_photon_token(token: str) -> dict[str, Any]:
  337. """Verify a device-flow token against ``/api/auth/get-session`` AND ``/api/projects/`` —
  338. the device flow can mint tokens that pass the session lookup but are rejected by the
  339. project APIs setup depends on."""
  340. def _get(path: str, rejected: str) -> Any:
  341. resp = _dashboard_get(path, token)
  342. if resp.status_code in (401, 403):
  343. raise PhotonDashboardAuthError(rejected)
  344. resp.raise_for_status()
  345. return resp
  346. data = _get("/api/auth/get-session",
  347. "Photon issued a device token, but the dashboard session lookup rejected it.").json()
  348. user = data.get("user") if isinstance(data, dict) else None
  349. if not isinstance(user, dict) or not user:
  350. raise PhotonDashboardAuthError(
  351. "Photon issued a device token, but the dashboard session lookup did not recognize it.")
  352. _get("/api/projects/", "Photon device token was accepted for the session lookup but rejected by the project API.")
  353. return user
  354. def _validated_dashboard_token(candidates: list) -> str:
  355. """Return the first candidate token that passes dashboard validation."""
  356. if not candidates:
  357. raise RuntimeError("Photon returned 200 but no token candidate in the device-token response.")
  358. dashboard_error: Optional[PhotonDashboardAuthError] = None
  359. last_error: Optional[BaseException] = None
  360. for candidate in candidates:
  361. try:
  362. validate_photon_token(candidate.token)
  363. return candidate.token
  364. except Exception as exc:
  365. last_error = exc
  366. if isinstance(exc, PhotonDashboardAuthError):
  367. dashboard_error = exc
  368. if dashboard_error is not None:
  369. sources = ", ".join(c.source for c in candidates) or "none"
  370. raise PhotonDashboardAuthError(
  371. f"{dashboard_error} Device login returned no project-valid dashboard token (tried: {sources})."
  372. ) from dashboard_error
  373. if last_error is not None:
  374. raise last_error
  375. raise RuntimeError("Photon did not return a usable dashboard token")
  376. def login_device_flow(
  377. *, client_id: str = DEFAULT_CLIENT_ID, open_browser: bool = True,
  378. on_user_code: Optional[Callable[[DeviceCode], None]] = None) -> str:
  379. """Run the full device-code login flow, validate the token against the dashboard API
  380. before persisting it, and return it. ``on_user_code`` receives the :class:`DeviceCode`."""
  381. code = request_device_code(client_id=client_id)
  382. if on_user_code:
  383. _safe(lambda: on_user_code(code))
  384. if open_browser:
  385. with contextlib.suppress(Exception):
  386. import webbrowser
  387. webbrowser.open(code.verification_uri_complete or code.verification_uri, new=2)
  388. first_token = poll_for_token(code, client_id=client_id)
  389. token = _validated_dashboard_token([_DeviceTokenCandidate(source="poll", token=first_token)])
  390. store_photon_token(token)
  391. return token
  392. # -- Dashboard API: projects --------------------------------------------------------
  393. def _unwrap_list(data: Any) -> list[dict[str, Any]]:
  394. if isinstance(data, list):
  395. return data
  396. if isinstance(data, dict):
  397. for key in ("data", "projects", "users", "lines", "items"):
  398. inner = data.get(key)
  399. if isinstance(inner, list):
  400. return inner
  401. if isinstance(inner, dict):
  402. nested = next((inner[k] for k in ("projects", "users", "lines", "items")
  403. if isinstance(inner.get(k), list)), None)
  404. if nested is not None:
  405. return nested
  406. return []
  407. def _dashboard_list(path: str, token: str) -> list[dict[str, Any]]:
  408. resp = _dashboard_get(path, token, what="")
  409. resp.raise_for_status()
  410. return _unwrap_list(resp.json())
  411. def _raise_on_error_key(data: dict[str, Any], action: str) -> None:
  412. if data.get("error"):
  413. raise RuntimeError(f"Photon {action} failed: {data['error']}")
  414. def list_projects(token: str) -> list[dict[str, Any]]:
  415. """GET ``/api/projects`` — return the caller's projects."""
  416. return _dashboard_list("/api/projects", token)
  417. def find_project_by_name(token: str, name: str) -> Optional[dict[str, Any]]:
  418. """First project whose name matches (case-insensitive)."""
  419. target = (name or "").strip().lower()
  420. for proj in list_projects(token):
  421. if (proj.get("name") or "").strip().lower() == target:
  422. return proj
  423. return None
  424. def create_project(
  425. token: str, *, name: str = DEFAULT_PROJECT_NAME, location: str = "United States") -> dict[str, Any]:
  426. """POST ``/api/projects`` and return the project (Spectrum is always provisioned;
  427. the request carries no ``spectrum`` flag)."""
  428. body: dict[str, Any] = {"name": name, "location": location, "template": False, "observability": False}
  429. data = _dashboard_post("/api/projects", body, token, what=" project creation")
  430. if not isinstance(data, dict):
  431. raise RuntimeError("Photon create-project returned an unexpected response")
  432. _raise_on_error_key(data, "create-project")
  433. if data.get("succeed") is False:
  434. raise RuntimeError(f"Photon create-project failed: {data.get('message') or data}")
  435. project: dict[str, Any] = data["data"] if isinstance(data.get("data"), dict) else data
  436. if not project.get("id"):
  437. raise RuntimeError("Photon create-project did not return a project id")
  438. return project
  439. def regenerate_project_secret(token: str, project_id: str) -> str:
  440. """POST ``/api/projects/{id}/regenerate-secret`` → the new secret (the only way to
  441. read one — persist it immediately)."""
  442. data = _dashboard_post(f"/api/projects/{project_id}/regenerate-secret", {}, token)
  443. _raise_on_error_key(data, "regenerate-secret")
  444. secret = data.get("projectSecret")
  445. if not secret:
  446. raise RuntimeError("Photon regenerate-secret returned no projectSecret")
  447. return str(secret)
  448. # -- Spectrum API: users -------------------------------------------------------------
  449. def _normalize_phone(phone: str) -> str:
  450. """Reduce a phone string to ``+`` and digits for dedup comparison."""
  451. return re.sub(r"[^\d+]", "", phone or "")
  452. def list_users(project_id: str, project_secret: str, *, timeout: float = 30.0) -> list[dict[str, Any]]:
  453. """GET Spectrum Cloud ``/projects/{id}/users/`` → ``SpectrumUser[]``."""
  454. _require_httpx()
  455. url = f"{_spectrum_host()}/projects/{project_id}/users/"
  456. resp = httpx.get(url, headers=_basic(project_id, project_secret), timeout=timeout)
  457. _raise_for_status(resp, "list-users")
  458. return _unwrap_list(resp.json())
  459. def find_user_by_phone(
  460. project_id: str, project_secret: str, phone_number: str, *, timeout: float = 30.0,
  461. ) -> Optional[dict[str, Any]]:
  462. """Existing Spectrum user with the given phone number (the routable one), or None."""
  463. return find_routable_user(list_users(project_id, project_secret, timeout=timeout), phone_number)
  464. def create_user(
  465. project_id: str, project_secret: str, *, phone_number: str, first_name: Optional[str] = None,
  466. last_name: Optional[str] = None, email: Optional[str] = None, send_invite: bool = False) -> dict[str, Any]:
  467. """POST Spectrum Cloud ``/projects/{id}/users/`` and return the user."""
  468. _require_httpx(" user creation")
  469. if not E164_RE.match(phone_number):
  470. raise ValueError(f"phone_number must be E.164 (e.g. +15551234567); got {phone_number!r}")
  471. url = f"{_spectrum_host()}/projects/{project_id}/users/"
  472. body: dict[str, Any] = {"type": "shared", "phoneNumber": phone_number}
  473. if send_invite:
  474. logger.debug("photon: send_invite is ignored by Spectrum shared-user creation")
  475. body.update({k: v for k, v in (("firstName", first_name), ("lastName", last_name), ("email", email)) if v})
  476. resp = httpx.post(url, json=body, headers=_basic(project_id, project_secret), timeout=30.0)
  477. _raise_for_status(resp, "create-user")
  478. data = resp.json() or {}
  479. _raise_on_error_key(data, "create-user")
  480. user = data.get("user") or data.get("data") or data
  481. if not isinstance(user, dict):
  482. raise RuntimeError("Photon create-user returned an unexpected response")
  483. return user
  484. def register_user_if_absent(
  485. project_id: str, project_secret: str, *, phone_number: str, first_name: Optional[str] = None,
  486. last_name: Optional[str] = None, email: Optional[str] = None) -> tuple[dict[str, Any], bool]:
  487. """Idempotently register a Spectrum user → ``(user, created)``; the official CLI does
  488. no dedup, so we add it to keep ``setup`` re-runnable."""
  489. existing = find_user_by_phone(project_id, project_secret, phone_number)
  490. if existing is not None:
  491. return existing, False
  492. return create_user(project_id, project_secret, phone_number=phone_number, first_name=first_name,
  493. last_name=last_name, email=email), True
  494. def user_assigned_line(user: Optional[dict[str, Any]]) -> Optional[str]:
  495. """The iMessage number a user texts to reach the agent (``assignedPhoneNumber``, the
  496. dashboard's "TEXTS ON" column). None when unset (freshly created user)."""
  497. val = user.get("assignedPhoneNumber") if user else None
  498. return str(val) if val else None
  499. def user_opted_in(user: Optional[dict[str, Any]]) -> bool:
  500. """True when the delivery plane routes this user: the row carries ``meta.opt_in``, which
  501. the service sets only after the human texts the row's ``assignedPhoneNumber`` once from
  502. ``phoneNumber``. Without it sends fail "Target not allowed for this project", and
  503. client-supplied meta is ignored on create, so the API cannot produce the flag."""
  504. meta = user.get("meta") if user else None
  505. return bool(isinstance(meta, dict) and meta.get("opt_in"))
  506. def find_routable_user(users: list[dict[str, Any]], phone_number: str) -> Optional[dict[str, Any]]:
  507. """The row that decides routing for ``phone_number``: an opted-in duplicate wins over list
  508. order (opt-in is scoped to one number/assigned-line pair), else the first match."""
  509. target = _normalize_phone(phone_number)
  510. matches = [u for u in users if _normalize_phone(u.get("phoneNumber") or "") == target]
  511. return next((u for u in matches if user_opted_in(u)), matches[0] if matches else None)
  512. def wait_for_opted_in_user(
  513. project_id: str, project_secret: str, phone_number: str, *, timeout_s: float = 300.0,
  514. interval_s: float = 5.0, on_waiting: Optional[Callable[[int], None]] = None,
  515. sleep_fn: Callable[[float], None] = time.sleep,
  516. clock: Callable[[], float] = time.monotonic) -> Optional[dict[str, Any]]:
  517. """Poll until ``phone_number``'s row is opted in; the opted-in row, or None at the bound.
  518. A failed list call is a missed poll (the wait rides out the operator's manual step). Two
  519. bounds: the attempt cap, and a wall-clock deadline so slow list calls (30 s HTTP timeout
  520. each) cannot stretch the promised wait far past ``timeout_s``."""
  521. deadline = clock() + timeout_s
  522. max_attempts = max(1, int(timeout_s / interval_s))
  523. for attempt in range(1, max_attempts + 1):
  524. try:
  525. user = find_user_by_phone(project_id, project_secret, phone_number)
  526. if user_opted_in(user):
  527. return user
  528. except (httpx.HTTPError, RuntimeError, ValueError) as exc: # transport / HTTP status / bad JSON
  529. logger.debug("photon: opt-in poll failed (attempt %d): %s", attempt, exc)
  530. if on_waiting is not None:
  531. on_waiting(attempt)
  532. if attempt == max_attempts or clock() + interval_s > deadline:
  533. break
  534. sleep_fn(interval_s)
  535. return None
  536. def load_user_numbers() -> tuple[Optional[str], Optional[str]]:
  537. """``(operator_phone_number, assigned_phone_number)`` for status."""
  538. entry = _pool_first(_load_auth(), "photon_user")
  539. entry = entry if isinstance(entry, dict) else {}
  540. phone = entry.get("phone_number") or entry.get("phoneNumber")
  541. assigned = entry.get("assigned_phone_number") or entry.get("assignedPhoneNumber")
  542. return (str(phone) if phone else _configured_operator_phone(), str(assigned) if assigned else None)
  543. def refresh_user_numbers(project_id: str, project_secret: str) -> tuple[Optional[str], Optional[str]]:
  544. """Refresh cached user numbers from Photon without provisioning anything."""
  545. phone, assigned = load_user_numbers()
  546. if phone:
  547. user = find_user_by_phone(project_id, project_secret, phone)
  548. else:
  549. users = list_users(project_id, project_secret)
  550. user = users[0] if len(users) == 1 else None
  551. user_id = None
  552. if user:
  553. user_id = user.get("id")
  554. dashboard_phone = _normalize_phone(str(user.get("phoneNumber") or ""))
  555. if E164_RE.match(dashboard_phone):
  556. phone = dashboard_phone
  557. assigned = user_assigned_line(user)
  558. dashboard_id = load_dashboard_project_id()
  559. dashboard_token = load_photon_token() if not assigned else None
  560. if dashboard_token and dashboard_id:
  561. try:
  562. line = get_imessage_line(dashboard_token, dashboard_id, create_if_missing=False)
  563. if line and line.get("phoneNumber"):
  564. assigned = str(line["phoneNumber"])
  565. except Exception as e:
  566. logger.debug("photon: could not refresh iMessage line for status: %s", e)
  567. store_user_numbers(phone_number=phone, assigned_phone_number=assigned,
  568. user_id=str(user_id) if user_id else None, dashboard_project_id=dashboard_id)
  569. return phone, assigned
  570. def _configured_operator_phone() -> Optional[str]:
  571. """Infer the operator's E.164 number from existing Photon env settings."""
  572. home = _normalize_phone(_get_config_env_value("PHOTON_HOME_CHANNEL") or "")
  573. if home and E164_RE.match(home):
  574. return home
  575. allowed = _get_config_env_value("PHOTON_ALLOWED_USERS") or ""
  576. candidates = [n for n in map(_normalize_phone, re.split(r"[,\s]+", allowed)) if E164_RE.match(n)]
  577. return candidates[0] if len(candidates) == 1 else None
  578. def _get_config_env_value(key: str) -> Optional[str]:
  579. try:
  580. from hermes_cli.config import get_env_value
  581. except Exception:
  582. return os.getenv(key)
  583. return get_env_value(key)
  584. # -- Dashboard API: iMessage lines (the assigned number inventory) --------------------
  585. def list_lines(token: str, project_id: str) -> list[dict[str, Any]]:
  586. """GET ``/api/projects/{id}/lines`` → ``[{id, platform, phoneNumber, status}]``."""
  587. return _dashboard_list(f"/api/projects/{project_id}/lines", token)
  588. def add_line(token: str, project_id: str, *, platform: str = "imessage") -> dict[str, Any]:
  589. """POST ``/api/projects/{id}/lines`` to provision a new line."""
  590. data = _dashboard_post(f"/api/projects/{project_id}/lines", {"platform": platform}, token)
  591. _raise_on_error_key(data, "add-line")
  592. return data.get("line") or data
  593. def get_imessage_line(
  594. token: str, project_id: str, *, create_if_missing: bool = True) -> Optional[dict[str, Any]]:
  595. """The project's iMessage line, provisioning one if absent and ``create_if_missing``;
  596. None if there is none and provisioning failed."""
  597. line = next((ln for ln in list_lines(token, project_id) if (ln.get("platform") or "").lower() == "imessage"), None)
  598. if line is not None or not create_if_missing:
  599. return line
  600. try:
  601. return add_line(token, project_id, platform="imessage")
  602. except Exception as e:
  603. logger.warning("photon: could not auto-provision iMessage line: %s", e)
  604. return None
  605. # -- Credential status (display-only — never emits raw secret material) ---------------
  606. def print_credential_summary(emit: Any = print) -> None:
  607. """Pretty-print the credential status table via *emit*. Every secret-bearing read is
  608. reduced to a display literal here; the callback only ever receives the assembled
  609. banner, so no tainted value escapes to the caller."""
  610. sid, sec = load_project_credentials()
  611. phone, assigned = load_user_numbers()
  612. rows = [
  613. "Photon iMessage status",
  614. "──────────────────────",
  615. " device token : " + (
  616. "✓ stored" if load_photon_token() else "✗ missing (run `hermes photon setup`)"),
  617. " project id : " + (sid if sid else "✗ missing"),
  618. " project secret : " + ("✓ stored" if sec else "✗ missing"),
  619. " my number : " + (phone if phone else "✗ missing (run `hermes photon setup --phone ...`)"),
  620. " assigned number : " + (assigned if assigned else "✗ missing (run `hermes photon setup`)")]
  621. emit("\n".join(rows))
  622. _STATUS_TIMEOUT_S = 5.0 # `photon status` stays quick when the API is unreachable
  623. def print_routing_status(emit: Any = print) -> None:
  624. """Live opt-in row for ``status``: a registered number that never texted its assigned line
  625. looks configured everywhere but never routes. Verified against the API, not local markers;
  626. lives here (with the credential reads) so the CLI sink only sees display text."""
  627. phone, assigned = load_user_numbers()
  628. sid, sec = load_project_credentials()
  629. if not (phone and sid and sec):
  630. return
  631. try:
  632. user = find_user_by_phone(sid, sec, phone, timeout=_STATUS_TIMEOUT_S)
  633. except (httpx.HTTPError, RuntimeError, ValueError) as e:
  634. emit(f" routing : ? could not verify ({str(e) or type(e).__name__})")
  635. return
  636. if user_opted_in(user):
  637. emit(" routing : ✓ opted in (verified live)")
  638. else:
  639. line = user_assigned_line(user) or assigned or "your assigned line"
  640. emit(f" routing : ✗ not opted in — text {line} once from {phone}, then re-check")