"""Server-rendered /login page (no React, no SPA bundle, no injected token). Providers come from the registry; an OAuth provider renders an anchor to ``/auth/login?provider=``, a ``supports_password`` provider renders a credential form wired by :data:`_PASSWORD_FORM_SCRIPT`. Styling mirrors the ``@nous-research/ui`` design system; fonts load from the SPA's ``/fonts/`` mount, which the gate allowlists pre-auth. The ``class="provider-btn"`` anchor is test-stable: the suite extracts its href to walk the OAuth flow. """ from __future__ import annotations import html from urllib.parse import quote, urlencode from hermes_cli.dashboard_auth import list_interactive_providers, list_session_providers # Single curly braces are ``str.format`` placeholders; CSS curlies are doubled. _LOGIN_HTML_TEMPLATE = """\ Sign in — Hermes Agent
NousResearch

Sign in

Choose a sign-in method to continue to the Hermes Agent dashboard.

{provider_buttons}
Public bind · Auth required
{password_script} """ _EMPTY_HTML = """\ Sign-in unavailable — Hermes Agent

Sign-in unavailable

This dashboard is bound to a non-loopback host but no authentication providers are available.

Configure the bundled username/password provider or an OAuth provider. See the dashboard authentication documentation for setup instructions.

For auth-free local use, bind to 127.0.0.1 and connect through an SSH tunnel or Tailscale.

""" # Token-gated deployment (every registered provider is provisioned-credential-only): # there is nothing to click, so the page explains the credential channel instead of # rendering an empty options list. {provider_names} / {note} are pre-escaped HTML. _TOKEN_MODE_HTML = """\ Token-gated dashboard — Hermes Agent

Token-gated dashboard

This deployment authenticates with a provisioned credential ({provider_names}), not a browser sign-in.

{note}

""" # Emitted ONLY when a ``supports_password`` provider is listed, so OAuth-only # login pages stay script-free. Plain string (not ``str.format``): braces are # literal. One delegated submit handler covers every form; the provider name # comes from the form's ``data-provider`` attribute. # # Reverse-proxy prefix support: the script reads ``data-prefix`` from the # ``
`` element (set by :func:`render_login_html`) and prepends it # to the POST target and the post-login landing path so the login flow # works behind ``X-Forwarded-Prefix`` proxies. _PASSWORD_FORM_SCRIPT = """\ """ def render_login_html(*, next_path: str = "", prefix: str = "") -> str: """Return the full HTML for ``GET /login``. ``next_path`` is threaded into each provider button/form so the OAuth round trip carries it end-to-end. The caller validates it same-origin; it is HTML-escaped here as defence in depth. ``prefix`` — when set, the path prefix from ``X-Forwarded-Prefix`` (e.g. ``"/hermes"``). Prepended to all auth URLs so the login page works behind a reverse proxy that mounts the dashboard at a sub-path. Empty string (default) means no prefix — bare-root deploys are unaffected. """ providers = list_session_providers() if not providers: return _EMPTY_HTML # URL-encode then HTML-escape, matching the gate's ``_safe_next_target`` # shape so a round-tripped value is byte-identical. next_qs = f"&next={html.escape(quote(next_path, safe=''), quote=True)}" if next_path else "" interactive = list_interactive_providers() if not interactive: # A deployment authenticated by a provisioned credential (e.g. the # session-token provider): there is nothing to click. Say so instead of # rendering a page with no sign-in options. names = ", ".join(html.escape(p.display_name) for p in providers) # str.replace, not str.format: the template's CSS braces are literal. return (_TOKEN_MODE_HTML .replace("{provider_names}", names) .replace("{note}", "Clients authenticate with the deployment’s provisioned " "credential (Authorization: Bearer, or " "?token= on the /api/ws upgrade) — e.g. Hermes " "Desktop’s “Session token” remote-gateway field. " "There is no browser sign-in flow.")) buttons = [ _render_password_form(p, next_path, prefix=prefix) if getattr(p, "supports_password", False) else f' ' f'Sign in with {html.escape(p.display_name)}' for p in interactive ] needs_password_script = any(getattr(p, "supports_password", False) for p in interactive) html_out = _LOGIN_HTML_TEMPLATE.format( provider_buttons="\n".join(buttons), password_script=_PASSWORD_FORM_SCRIPT if needs_password_script else "", ) # Inject the reverse-proxy prefix so the password-login JS can read # it from the
element's data attribute, and rewrite the font # URLs to stay inside the mount. ``str.replace`` after ``str.format`` # avoids interfering with the CSS ``{{ }}`` doubling in the template. return _apply_proxy_prefix(html_out, prefix) def _apply_proxy_prefix(html_out: str, prefix: str) -> str: """Rewrite a rendered login-family page for a reverse-proxy sub-path. Two rewrites, both no-ops when *prefix* is empty (bare-root deploys are byte-for-byte unaffected): * ``
`` gains ``data-prefix`` so the password-login JS (a plain string, never ``str.format``-aware) can prepend the prefix to its fetch target and post-login landing. * ``@font-face`` ``url('/fonts/...')`` becomes ``url('/fonts/...')`` so the fonts load from the mount instead of the origin root (404 behind a prefix-stripping proxy). """ if not prefix: return html_out html_out = html_out.replace("
", f'
', 1) html_out = html_out.replace("url('/fonts/", f"url('{prefix}/fonts/") return html_out def render_native_provider_choice_html( *, providers, authorize_path: str, code_challenge: str, code_challenge_method: str, redirect_uri: str, state: str, prefix: str = "") -> str: """Provider picker for a native authorize request with more than one interactive provider. Every link re-enters ``/auth/native/authorize`` with the SAME desktop PKCE inputs plus an explicit ``provider``, so the choice never leaves the validated native flow. ``prefix`` (from ``X-Forwarded-Prefix``) rewrites the template's font URLs so the page works behind a reverse-proxy sub-path; the buttons' ``authorize_path`` is already prefixed by the caller. """ common = {"code_challenge": code_challenge, "code_challenge_method": code_challenge_method, "redirect_uri": redirect_uri, "state": state} buttons = [] for p in providers: href = html.escape(f"{authorize_path}?{urlencode({**common, 'provider': p.name})}", quote=True) buttons.append(f' ' f'Sign in with {html.escape(p.display_name)}') if not buttons: return _EMPTY_HTML return _apply_proxy_prefix( _LOGIN_HTML_TEMPLATE.format( provider_buttons="\n".join(buttons), password_script=""), prefix) def _render_password_form(provider, next_path: str, *, prefix: str = "") -> str: """Username/password form for a ``supports_password`` provider. ``next_path`` rides in a hidden field (already validated by the caller, HTML-escaped here). The provider name is a ``data-`` attribute so the script does not depend on field ordering. ``prefix`` — reverse-proxy path prefix (e.g. ``"/hermes"``); kept for interface parity with the other renderers (the submit handler reads the prefix from ``
``). """ pname = html.escape(provider.name, quote=True) plabel = html.escape(provider.display_name) safe_next = html.escape(next_path, quote=True) if next_path else "" return ( f'
\n' f'
Sign in with {plabel}
\n' f' \n' f' \n' f' \n' f' \n' f' \n' f'
' )