web_server_session_token.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """The dashboard session token: where its value comes from.
  2. The desktop shell mints the token via HERMES_DASHBOARD_SESSION_TOKEN; a
  3. "file:<path>" value instead names a file to read it from (the Nix modules
  4. render backend.sessionTokenFile this way, so a path -- not a secret -- sits
  5. in the service environment). With no variable, a fresh token is minted per
  6. server start. It dies with the process and is injected into the SPA HTML so
  7. only the web UI can use it.
  8. """
  9. import os
  10. import secrets
  11. from pathlib import Path
  12. def resolve_session_token() -> str:
  13. env_token = os.environ.get("HERMES_DASHBOARD_SESSION_TOKEN")
  14. if not env_token:
  15. return secrets.token_urlsafe(32)
  16. # A "file:" prefix means the value is a token-file path, not a token:
  17. # deployment managers (agenix, sops-nix, systemd credentials) hand a
  18. # secret over as a file, and a path -- unlike the token -- can sit in a
  19. # systemd Environment= or a launchd plist without putting anything
  20. # readable into a store path.
  21. if env_token.startswith("file:"):
  22. token_file = env_token[len("file:") :]
  23. try:
  24. token = Path(token_file).read_text(encoding="utf-8-sig").strip()
  25. except (OSError, UnicodeError) as exc:
  26. raise SystemExit(
  27. f"HERMES_DASHBOARD_SESSION_TOKEN names an unreadable token file ({token_file}): {exc}"
  28. ) from exc
  29. if not token:
  30. raise SystemExit(
  31. f"HERMES_DASHBOARD_SESSION_TOKEN names an empty token file ({token_file})"
  32. )
  33. return token
  34. return env_token