|
| 1 | +"""Browser session cookie authentication flow. |
| 2 | +
|
| 3 | +begin() — daemon-side: stash config in session payload. |
| 4 | +resume() — daemon-side: build ConnectionRecord from CLI-supplied cookies. |
| 5 | +run_login() — CLI-side: read Chrome cookie DB, open browser if needed, poll until valid. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import asyncio |
| 11 | +import webbrowser |
| 12 | +from datetime import timedelta |
| 13 | +from typing import TYPE_CHECKING, Any |
| 14 | + |
| 15 | +from loguru import logger |
| 16 | + |
| 17 | +from authsome.auth.browser_cookies import cookies_are_valid, normalize_jsessionid, read_chrome_cookies |
| 18 | +from authsome.auth.flows.base import AuthFlow, FlowResult |
| 19 | +from authsome.auth.models.connection import AccountInfo, ConnectionRecord |
| 20 | +from authsome.auth.models.enums import AuthType, ConnectionStatus |
| 21 | +from authsome.auth.models.provider import ProviderDefinition |
| 22 | +from authsome.errors import AuthenticationFailedError, RefreshFailedError |
| 23 | +from authsome.utils import utc_now |
| 24 | + |
| 25 | +if TYPE_CHECKING: |
| 26 | + from authsome.auth.sessions import AuthSession |
| 27 | + |
| 28 | +_POLL_INTERVAL = 4.0 |
| 29 | +_DEFAULT_TIMEOUT = 300.0 |
| 30 | + |
| 31 | + |
| 32 | +class BrowserFlow(AuthFlow): |
| 33 | + """Cookie-based browser SSO — reads Chrome's on-disk cookie database.""" |
| 34 | + |
| 35 | + async def begin( |
| 36 | + self, |
| 37 | + provider: ProviderDefinition, |
| 38 | + identity: str | None, |
| 39 | + connection_name: str, |
| 40 | + runtime_session: AuthSession, |
| 41 | + scopes: list[str] | None = None, |
| 42 | + client_id: str | None = None, |
| 43 | + client_secret: str | None = None, |
| 44 | + base_url: str | None = None, |
| 45 | + ) -> None: |
| 46 | + if provider.browser is None: |
| 47 | + raise AuthenticationFailedError("Provider missing 'browser' configuration", provider=provider.name) |
| 48 | + cfg = provider.browser |
| 49 | + runtime_session.state = "waiting_for_user" |
| 50 | + runtime_session.payload["browser_login"] = True |
| 51 | + runtime_session.payload["entry_url"] = cfg.entry_url |
| 52 | + runtime_session.payload["domains"] = cfg.domains |
| 53 | + runtime_session.payload["auth_cookies"] = cfg.auth_cookies |
| 54 | + |
| 55 | + async def resume( |
| 56 | + self, |
| 57 | + provider: ProviderDefinition, |
| 58 | + identity: str | None, |
| 59 | + connection_name: str, |
| 60 | + runtime_session: AuthSession, |
| 61 | + callback_data: dict[str, Any], |
| 62 | + client_id: str | None = None, |
| 63 | + client_secret: str | None = None, |
| 64 | + ) -> FlowResult | None: |
| 65 | + if provider.browser is None: |
| 66 | + raise AuthenticationFailedError("Provider missing 'browser' configuration", provider=provider.name) |
| 67 | + credentials = callback_data.get("credentials") |
| 68 | + if not credentials or not isinstance(credentials, dict): |
| 69 | + return None |
| 70 | + |
| 71 | + now = utc_now() |
| 72 | + return FlowResult( |
| 73 | + connection=ConnectionRecord( |
| 74 | + schema_version=2, |
| 75 | + provider=provider.name, |
| 76 | + identity=identity, |
| 77 | + connection_name=connection_name, |
| 78 | + auth_type=AuthType.BROWSER, |
| 79 | + status=ConnectionStatus.CONNECTED, |
| 80 | + credentials=credentials, |
| 81 | + expires_at=now + timedelta(hours=provider.browser.ttl_hours), |
| 82 | + obtained_at=now, |
| 83 | + account=AccountInfo(), |
| 84 | + ) |
| 85 | + ) |
| 86 | + |
| 87 | + def refresh( |
| 88 | + self, |
| 89 | + provider: ProviderDefinition, |
| 90 | + record: ConnectionRecord, |
| 91 | + client_id: str | None = None, |
| 92 | + client_secret: str | None = None, |
| 93 | + ) -> ConnectionRecord: |
| 94 | + raise RefreshFailedError( |
| 95 | + f"Browser cookies cannot be refreshed automatically — run: authsome login {record.provider}", |
| 96 | + provider=record.provider, |
| 97 | + ) |
| 98 | + |
| 99 | + @staticmethod |
| 100 | + async def run_login( |
| 101 | + action: dict[str, Any], |
| 102 | + provider_name: str, |
| 103 | + *, |
| 104 | + poll_interval: float = _POLL_INTERVAL, |
| 105 | + timeout: float = _DEFAULT_TIMEOUT, |
| 106 | + ) -> dict[str, str]: |
| 107 | + """CLI-side login: read Chrome cookies, open browser if needed, poll until valid. |
| 108 | +
|
| 109 | + Args: |
| 110 | + action: The ``BrowserAction`` payload from ``next_action``. |
| 111 | + provider_name: Provider name, used to select normalization (e.g. LinkedIn). |
| 112 | + poll_interval: Seconds between cookie DB reads. |
| 113 | + timeout: Total seconds before ``TimeoutError`` is raised. |
| 114 | +
|
| 115 | + Returns: |
| 116 | + Cookie name→value dict ready to POST to ``/auth/sessions/{id}/resume``. |
| 117 | + """ |
| 118 | + entry_url: str = action["entry_url"] |
| 119 | + domains: list[str] = action.get("domains", []) |
| 120 | + auth_cookies: list[str] = action.get("auth_cookies", []) |
| 121 | + |
| 122 | + def _read() -> dict[str, str] | None: |
| 123 | + try: |
| 124 | + cookies = read_chrome_cookies(domains) |
| 125 | + if provider_name == "linkedin-browser": |
| 126 | + cookies = normalize_jsessionid(cookies) |
| 127 | + if cookies_are_valid(cookies, auth_cookies): |
| 128 | + return cookies |
| 129 | + except Exception as exc: |
| 130 | + logger.debug("Cookie read failed: {}", exc) |
| 131 | + return None |
| 132 | + |
| 133 | + # Fast path: already logged in |
| 134 | + if result := _read(): |
| 135 | + logger.debug("authsome: existing cookies valid for {} — no browser open needed", provider_name) |
| 136 | + return result |
| 137 | + |
| 138 | + # Open browser for user to log in |
| 139 | + try: |
| 140 | + webbrowser.open(entry_url) |
| 141 | + except Exception as exc: |
| 142 | + logger.warning("Could not open browser: {}", exc) |
| 143 | + |
| 144 | + deadline = asyncio.get_event_loop().time() + timeout |
| 145 | + while True: |
| 146 | + await asyncio.sleep(poll_interval) |
| 147 | + if result := _read(): |
| 148 | + logger.info("authsome: browser cookies captured for {}", provider_name) |
| 149 | + return result |
| 150 | + if asyncio.get_event_loop().time() >= deadline: |
| 151 | + raise TimeoutError( |
| 152 | + f"Timed out waiting for browser login to {entry_url!r} after {int(timeout)}s. " |
| 153 | + "Please complete login in the browser window." |
| 154 | + ) |
0 commit comments