|
| 1 | +import base64 |
| 2 | +import time |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +import requests |
| 6 | +import typer |
| 7 | +from cryptography.hazmat.primitives import hashes, serialization |
| 8 | +from cryptography.hazmat.primitives.asymmetric import padding as asym_padding |
| 9 | +from cryptography.hazmat.primitives.asymmetric import rsa |
| 10 | +from rich.console import Console |
| 11 | + |
| 12 | +from ..config import Config |
| 13 | + |
| 14 | +app = typer.Typer(help="Login to Prime Intellect") |
| 15 | +console = Console() |
| 16 | + |
| 17 | + |
| 18 | +def generate_ephemeral_keypair() -> tuple[rsa.RSAPrivateKey, str]: |
| 19 | + """Generate a temporary RSA key pair for secure communication""" |
| 20 | + try: |
| 21 | + private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) |
| 22 | + public_key = private_key.public_key() |
| 23 | + |
| 24 | + # Serialize public key to PEM format |
| 25 | + public_pem = public_key.public_bytes( |
| 26 | + encoding=serialization.Encoding.PEM, |
| 27 | + format=serialization.PublicFormat.SubjectPublicKeyInfo, |
| 28 | + ).decode("utf-8") |
| 29 | + |
| 30 | + return private_key, public_pem |
| 31 | + except Exception as e: |
| 32 | + console.print(f"[red]Error generating keypair: {str(e)}[/red]") |
| 33 | + raise typer.Exit(1) |
| 34 | + |
| 35 | + |
| 36 | +def decrypt_challenge_response( |
| 37 | + private_key: rsa.RSAPrivateKey, encrypted_response: bytes |
| 38 | +) -> Optional[bytes]: |
| 39 | + """Decrypt the challenge response using the private key""" |
| 40 | + try: |
| 41 | + decrypted: bytes = private_key.decrypt( |
| 42 | + encrypted_response, |
| 43 | + asym_padding.OAEP( |
| 44 | + mgf=asym_padding.MGF1(algorithm=hashes.SHA256()), |
| 45 | + algorithm=hashes.SHA256(), |
| 46 | + label=None, |
| 47 | + ), |
| 48 | + ) |
| 49 | + return decrypted |
| 50 | + except Exception as e: |
| 51 | + console.print(f"[red]Error decrypting response: {str(e)}[/red]") |
| 52 | + return None |
| 53 | + |
| 54 | + |
| 55 | +@app.callback(invoke_without_command=True) |
| 56 | +def login() -> None: |
| 57 | + """Login to Prime Intellect""" |
| 58 | + config = Config() |
| 59 | + settings = config.view() |
| 60 | + |
| 61 | + if not settings["base_url"]: |
| 62 | + console.print( |
| 63 | + "[red]Base URL not configured.", |
| 64 | + "Please run 'prime config set-base-url' first.", |
| 65 | + ) |
| 66 | + raise typer.Exit(1) |
| 67 | + |
| 68 | + private_key = None |
| 69 | + try: |
| 70 | + # Generate secure keypair |
| 71 | + private_key, public_pem = generate_ephemeral_keypair() |
| 72 | + |
| 73 | + response = requests.post( |
| 74 | + f"{settings['base_url']}/api/v1/auth_challenge/generate", |
| 75 | + json={ |
| 76 | + "encryptionPublicKey": public_pem, |
| 77 | + }, |
| 78 | + ) |
| 79 | + |
| 80 | + if response.status_code != 200: |
| 81 | + console.print( |
| 82 | + "[red]Failed to generate challenge:", |
| 83 | + f"{response.json().get('detail', 'Unknown error')}[/red]", |
| 84 | + ) |
| 85 | + raise typer.Exit(1) |
| 86 | + |
| 87 | + challenge_response = response.json() |
| 88 | + |
| 89 | + console.print("\n[bold blue]To login, please follow these steps:[/bold blue]") |
| 90 | + console.print( |
| 91 | + "1. Open ", |
| 92 | + "[link]https://app.primeintellect.ai/dashboard/tokens/challenge[/link]", |
| 93 | + ) |
| 94 | + console.print( |
| 95 | + "2. Enter this code:", |
| 96 | + f"[bold green]{challenge_response['challenge']}[/bold green]", |
| 97 | + ) |
| 98 | + console.print("\nWaiting for authentication...") |
| 99 | + |
| 100 | + challenge_auth_header = f"Bearer {challenge_response['status_auth_token']}" |
| 101 | + while True: |
| 102 | + try: |
| 103 | + status_response = requests.get( |
| 104 | + f"{settings['base_url']}/api/v1/auth_challenge/status", |
| 105 | + params={"challenge": challenge_response["challenge"]}, |
| 106 | + headers={"Authorization": challenge_auth_header}, |
| 107 | + ) |
| 108 | + |
| 109 | + if status_response.status_code == 404: |
| 110 | + console.print("[red]Challenge expired[/red]") |
| 111 | + break |
| 112 | + |
| 113 | + status_data = status_response.json() |
| 114 | + if status_data.get("result"): |
| 115 | + # Decrypt the result |
| 116 | + encrypted_result = base64.b64decode(status_data["result"]) |
| 117 | + decrypted_result = decrypt_challenge_response( |
| 118 | + private_key, encrypted_result |
| 119 | + ) |
| 120 | + if decrypted_result: |
| 121 | + # Update config with decrypted token |
| 122 | + config.set_api_key(decrypted_result.decode()) |
| 123 | + console.print("[green]Successfully logged in![/green]") |
| 124 | + else: |
| 125 | + console.print( |
| 126 | + "[red]Failed to decrypt authentication token[/red]" |
| 127 | + ) |
| 128 | + break |
| 129 | + |
| 130 | + time.sleep(5) |
| 131 | + except requests.exceptions.RequestException: |
| 132 | + console.print("[red]Failed to connect to server. Retrying...[/red]") |
| 133 | + time.sleep(5) |
| 134 | + continue |
| 135 | + |
| 136 | + except KeyboardInterrupt: |
| 137 | + console.print("\n[yellow]Login cancelled by user[/yellow]") |
| 138 | + raise typer.Exit(1) |
| 139 | + except Exception as e: |
| 140 | + console.print(f"[red]An error occurred: {str(e)}[/red]") |
| 141 | + raise typer.Exit(1) |
| 142 | + finally: |
| 143 | + # Ensure private key is securely wiped |
| 144 | + if private_key: |
| 145 | + del private_key |
0 commit comments