arcade-mcp/libs/arcade-cli/arcade_cli/authn.py
Sam Partee b6b4cd0a4c
🏗️ Restructure: Multi-Package Architecture + uv Migration (#412)
### Overview
Major restructuring from monolithic `arcade-ai` package to modular
library architecture with standardized uv-based dependency management.

![arcade-ai Monorepo
(2)](https://github.com/user-attachments/assets/25f102b0-bb87-4a04-9701-d227d05664b1)

### New Package Structure
- **`arcade-tdk`** - Lightweight toolkit development kit (core
decorators, auth)
- **`arcade-core`** - Core execution engine and catalog functionality  
- **`arcade-serve`** - FastAPI/MCP server components
- **`arcade-ai`** - Meta package that includes CLI functionality.
Optionally include evals via the `evals` extra. Optionally include all
packages via the `all` extra.

### Key Benefits
- **Lighter Dependencies**: Toolkits now depend only on `arcade-tdk` (~2
deps) vs full `arcade-ai` (~30+ deps)
- **Faster Builds**: uv provides 10-100x faster dependency resolution
and installation
- **Better Modularity**: Clear separation of concerns, consumers import
only what they need
- **Standard Tooling**: Eliminates custom poetry scripts, uses standard
Python packaging

### Migration Impact
- All 20 toolkits converted from poetry → uv with `arcade-tdk`
dependencies plus `arcade-ai[evals]` and `arcade-serve` dev
dependencies. When developing locally, devs should install toolkits via
`make install-local`.
- Modern Python 3.10+ type hints throughout
- Standardized build system with hatchling backend
- Enhanced Makefile with robust toolkit management commands
- Removed `arcade dev` CLI command
- Reduce the number of files created by `arcade new` and add an option
to not generate a tests and evals folder.

This foundation enables faster development cycles and cleaner dependency
chains for the growing toolkit ecosystem.

### Todo After this PR is merged
- [ ] Post-merge workflow(s) (release & publish containers, etc)
- [ ] Release order plan. @EricGustin suggests releasing in the
following order:
    1. `arcade-core` version 0.1.0
    2. `arcade-serve` version 0.1.0 and `arcade-tdk` version 0.1.0
    3. `arcade-ai` version 2.0.0
4. Patch release for all toolkits (all changes in toolkits are internal
refactors)
- [ ] [Update docs](https://github.com/ArcadeAI/docs/pull/318)

---------

Co-authored-by: Eric Gustin <eric@arcade.dev>
Co-authored-by: Eric Gustin <34000337+EricGustin@users.noreply.github.com>
2025-06-11 16:48:17 -07:00

148 lines
4.9 KiB
Python

import os
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import Any
from urllib.parse import parse_qs
import yaml
from rich.console import Console
from arcade_cli.constants import (
ARCADE_CONFIG_PATH,
CREDENTIALS_FILE_PATH,
LOGIN_FAILED_HTML,
LOGIN_SUCCESS_HTML,
)
console = Console()
class LoginCallbackHandler(BaseHTTPRequestHandler):
def __init__(self, *args, state: str, **kwargs): # type: ignore[no-untyped-def]
self.state = state # Simple CSRF protection
super().__init__(*args, **kwargs)
def log_message(self, format: str, *args: Any) -> None: # noqa: A002 Argument `format` is shadowing a Python builtin
# Override to suppress logging to stdout
pass
def _parse_login_response(self) -> tuple[str, str, str] | None:
# Parse the query string from the URL
query_string = self.path.split("?", 1)[-1]
params = parse_qs(query_string)
returned_state = params.get("state", [None])[0]
if returned_state != self.state:
console.print(
"❌ Login failed: Invalid login attempt. Please try again.", style="bold red"
)
return None
api_key = params.get("api_key", [None])[0] or ""
email = params.get("email", [None])[0] or ""
warning = params.get("warning", [None])[0] or ""
return api_key, email, warning
def _handle_login_response(self) -> bool:
result = self._parse_login_response()
if result is None:
return False
api_key, email, warning = result
if warning:
console.print(warning, style="bold yellow")
# If API key and email are received, store them in a file
if not api_key or not email:
console.print(
"❌ Login failed: No credentials received. Please try again.", style="bold red"
)
return False
# ensure the ARCADE_CONFIG_PATH directory exists
if not os.path.exists(ARCADE_CONFIG_PATH):
os.makedirs(ARCADE_CONFIG_PATH, exist_ok=True)
# TODO don't overwrite existing config
new_config = {"cloud": {"api": {"key": api_key}, "user": {"email": email}}}
with open(CREDENTIALS_FILE_PATH, "w") as f:
yaml.dump(new_config, f)
# Send a success response to the browser
console.print(
f"""✅ Hi there, {email}!
Your Arcade API key is: {api_key}
Stored in: {CREDENTIALS_FILE_PATH}""",
style="bold green",
)
return True
def do_GET(self) -> None: # This naming is correct, required by BaseHTTPRequestHandler
success = self._handle_login_response()
if success:
self.send_response(200)
self.end_headers()
self.wfile.write(LOGIN_SUCCESS_HTML)
else:
self.send_response(400)
self.end_headers()
self.wfile.write(LOGIN_FAILED_HTML)
# Always shut down the server so it doesn't keep running
threading.Thread(target=self.server.shutdown).start()
class LocalAuthCallbackServer:
def __init__(self, state: str, port: int = 9905):
self.state = state
self.port = port
self.httpd: HTTPServer | None = None
def run_server(self) -> None:
# Initialize and run the server
server_address = ("", self.port)
handler = lambda *args, **kwargs: LoginCallbackHandler(*args, state=self.state, **kwargs)
self.httpd = HTTPServer(server_address, handler)
self.httpd.serve_forever()
def shutdown_server(self) -> None:
# Shut down the server gracefully
if self.httpd:
self.httpd.shutdown()
def check_existing_login(suppress_message: bool = False) -> bool:
"""
Check if the user is already logged in by verifying the config file.
Args:
suppress_message (bool): If True, suppress the logged in message.
Returns:
bool: True if the user is already logged in, False otherwise.
"""
if not os.path.exists(CREDENTIALS_FILE_PATH):
return False
if os.path.exists(CREDENTIALS_FILE_PATH):
try:
with open(CREDENTIALS_FILE_PATH) as f:
config: dict[str, Any] = yaml.safe_load(f)
cloud_config = config.get("cloud", {})
api_key = cloud_config.get("api", {}).get("key")
email = cloud_config.get("user", {}).get("email")
if api_key and email:
if not suppress_message:
console.print(f"You're already logged in as {email}. ", style="bold green")
return True
except yaml.YAMLError:
console.print(
f"Error: Invalid configuration file at {CREDENTIALS_FILE_PATH}", style="bold red"
)
except Exception as e:
console.print(f"Error: Unable to read configuration file: {e!s}", style="bold red")
return True