Commit ·
488d5ee
1
Parent(s): ba53187
added onboarding logic. better mimic behavior. support preflight packages. support x-google authentication for cherry studio
Browse files3 unmodified lines456789101112132 unmodified lines1617181920215 unmodified lines2728293031323334353637383940414243444546471 unmodified line495051525354555657589 unmodified lines6869707172737446 unmodified lines1211221231241251261271281291301311321331341351361371381391401411426 unmodified lines1491501511521531541551561571581591601611621631641651661679 unmodified lines1771781791801811821833 unmodified lines18718818919019119219319419519619719819920020110 unmodified lines2122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762 unmodified lines2792802812822832842852862872884 unmodified lines29329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832962 unmodified lines392393394395396397398399172 unmodified lines5725735745755765775783 unmodified linesimport reimport uvicornimport base64from datetime import datetimefrom fastapi import FastAPI, Request, Response, HTTPException, Dependsfrom fastapi.responses import StreamingResponsefrom fastapi.security import HTTPBasic, HTTPBasicCredentialsfrom http.server import BaseHTTPRequestHandler, HTTPServerfrom urllib.parse import urlparse, parse_qsimport ijson2 unmodified linesfrom google.oauth2.credentials import Credentialsfrom google_auth_oauthlib.flow import Flowfrom google.auth.transport.requests import Request as GoogleAuthRequest# Load environment variables from .env fileload_dotenv()5 unmodified lines"https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","openid",]GEMINI_DIR = os.path.dirname(os.path.abspath(__file__)) # Same directory as the scriptCREDENTIAL_FILE = os.path.join(GEMINI_DIR, "oauth_creds.json")CODE_ASSIST_ENDPOINT = "https://cloudcode-pa.googleapis.com"GEMINI_PORT = int(os.getenv("GEMINI_PORT", "8888")) # Default to 8888 if not setGEMINI_AUTH_PASSWORD = os.getenv("GEMINI_AUTH_PASSWORD", "123456") # Default password# --- Global State ---credentials = Noneuser_project_id = Noneapp = FastAPI()security = HTTPBasic()def authenticate_user(request: Request):"""Authenticate the user with multiple methods."""# Check for API key in query parameters first (for Gemini client compatibility)1 unmodified lineif api_key and api_key == GEMINI_AUTH_PASSWORD:return "api_key_user"# Check for API key in Authorization header (Bearer token format)auth_header = request.headers.get("authorization", "")if auth_header.startswith("Bearer ") and auth_header[7:] == GEMINI_AUTH_PASSWORD:return "bearer_user"# Check for HTTP Basic Authenticationif auth_header.startswith("Basic "):9 unmodified lines# If none of the authentication methods workraise HTTPException(status_code=401,detail="Invalid authentication credentials. Use HTTP Basic Auth, Bearer token, or 'key' query parameter.",headers={"WWW-Authenticate": "Basic"},)46 unmodified linesself.end_headers()self.wfile.write(b"<h1>Authentication failed.</h1><p>Please try again.</p>")def get_user_project_id(creds):"""Gets the user's project ID from environment variable, cache, or by probing the API."""global user_project_idif user_project_id:return user_project_id# First, check for environment variable overrideenv_project_id = os.getenv("GEMINI_PROJECT_ID")if env_project_id:user_project_id = env_project_idprint(f"Using project ID from environment variable: {user_project_id}")# Save the environment project ID to cache for consistencysave_credentials(creds, user_project_id)return user_project_id# Second, try to load project ID from credential fileif os.path.exists(CREDENTIAL_FILE):try:with open(CREDENTIAL_FILE, "r") as f:6 unmodified linesexcept Exception as e:print(f"Could not load project ID from cache: {e}")# If not found in environment or cache, probe for itprint("Project ID not found in environment or cache. Probing for user project ID...")headers = {"Authorization": f"Bearer {creds.token}","Content-Type": "application/json",}probe_payload = {"cloudaicompanionProject": "gcp-project","metadata": {"ideType": "VSCODE","pluginType": "GEMINI"}}try:9 unmodified linesraise ValueError("Could not find 'cloudaicompanionProject' in loadCodeAssist response.")print(f"Successfully fetched user project ID: {user_project_id}")# Save the project ID to the credential file for future usesave_credentials(creds, user_project_id)print("Project ID saved to credential file for future use.")3 unmodified linesraisedef save_credentials(creds, project_id=None):os.makedirs(GEMINI_DIR, exist_ok=True)creds_data = {"access_token": creds.token,"refresh_token": creds.refresh_token,"scope": " ".join(creds.scopes),"token_type": "Bearer","expiry_date": creds.expiry.isoformat() if creds.expiry else None,}# If project_id is provided, save it; otherwise preserve existing project_idif project_id:creds_data["project_id"] = project_id10 unmodified linesjson.dump(creds_data, f)def get_credentials():"""Loads credentials from cache or initiates the OAuth 2.0 flow."""global credentialsif credentials:if credentials.valid:return credentialsif credentials.expired and credentials.refresh_token:print("Refreshing expired credentials...")try:credentials.refresh(GoogleAuthRequest())save_credentials(credentials)print("Credentials refreshed successfully.")return credentialsexcept Exception as e:print(f"Could not refresh token: {e}. Attempting to load from file.")if os.path.exists(CREDENTIAL_FILE):try:with open(CREDENTIAL_FILE, "r") as f:creds_data = json.load(f)# Load project ID if availableglobal user_project_idcached_project_id = creds_data.get("project_id")if cached_project_id:user_project_id = cached_project_idprint(f"Loaded project ID from credential file: {user_project_id}")expiry = Noneexpiry_str = creds_data.get("expiry_date")if expiry_str:if not isinstance(expiry_str, str) or not expiry_str.strip():expiry = Noneelif expiry_str.endswith('Z'):expiry_str = expiry_str[:-1] + '+00:00'expiry = datetime.fromisoformat(expiry_str)else:expiry = datetime.fromisoformat(expiry_str)credentials = Credentials(token=creds_data.get("access_token"),refresh_token=creds_data.get("refresh_token"),token_uri="https://oauth2.googleapis.com/token",client_id=CLIENT_ID,client_secret=CLIENT_SECRET,scopes=SCOPES,expiry=expiry)if credentials.expired and credentials.refresh_token:print("Loaded credentials from file are expired. Refreshing...")credentials.refresh(GoogleAuthRequest())save_credentials(credentials)print("Successfully loaded credentials from cache.")return credentialsexcept Exception as e:print(f"Could not load cached credentials: {e}. Starting new login.")client_config = {"installed": {"client_id": CLIENT_ID,2 unmodified lines"token_uri": "https://oauth2.googleapis.com/token",}}flow = Flow.from_client_config(client_config, scopes=SCOPES, redirect_uri="http://localhost:8080")auth_url, _ = flow.authorization_url(access_type="offline", prompt="consent")print(f"\nPlease open this URL in your browser to log in:\n{auth_url}\n")server = HTTPServer(("", 8080), _OAuthCallbackHandler)4 unmodified linesprint("Failed to retrieve authorization code.")return Noneflow.fetch_token(code=auth_code)credentials = flow.credentialssave_credentials(credentials)print("Authentication successful! Credentials saved.")return credentials@app.post("/{full_path:path}")async def proxy_request(request: Request, full_path: str, username: str = Depends(authenticate_user)):creds = get_credentials()if not creds:return Response(content="Authentication failed. Please restart the proxy to log in.", status_code=500)# Only check if credentials are properly formed and not expired locallyif not creds.valid:if creds.expired and creds.refresh_token:print("Credentials expired locally. Refreshing...")try:creds.refresh(GoogleAuthRequest())save_credentials(creds)print("Credentials refreshed successfully.")except Exception as e:print(f"Could not refresh token during request: {e}")return Response(content="Token refresh failed. Please restart the proxy to re-authenticate.", status_code=500)else:print("Credentials are invalid locally and cannot be refreshed.")return Response(content="Invalid credentials. Please restart the proxy to re-authenticate.", status_code=500)proj_id = get_user_project_id(creds)if not proj_id:return Response(content="Failed to get user project ID.", status_code=500)post_data = await request.body()path = f"/{full_path}"62 unmodified linesheaders = {"Authorization": f"Bearer {creds.token}","Content-Type": "application/json",# We remove 'Accept-Encoding' to allow the server to send gzip,# which it seems to stream correctly. We will decompress on the fly.}if is_streaming:172 unmodified linesprint("Initializing credentials...")creds = get_credentials()if creds:get_user_project_id(creds)print(f"\nStarting Gemini proxy server on http://localhost:{GEMINI_PORT}")print("Send your Gemini API requests to this address.")print(f"Authentication required - Password: {GEMINI_AUTH_PASSWORD}")3 unmodified lines456789101112131415162 unmodified lines192021222324255 unmodified lines31323334353637383940414243444546474849505152535455565758596061626364656667681 unmodified line70717273747576777879808182838485869 unmodified lines9697989910010110246 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033046 unmodified lines3113123133143153163173183193203213223233243253263273283293303313323333343353363373389 unmodified lines3483493503513523533 unmodified lines35735835936036136236336436536636736836937037137237337437537610 unmodified lines3873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684692 unmodified lines4724734744754764774784794804814824834844854864874884894904914924934 unmodified lines49849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057162 unmodified lines634635636637638639640172 unmodified lines8138148158168178188198208213 unmodified linesimport reimport uvicornimport base64import platformimport timefrom datetime import datetimefrom fastapi import FastAPI, Request, Response, HTTPException, Dependsfrom fastapi.responses import StreamingResponsefrom fastapi.security import HTTPBasic, HTTPBasicCredentialsfrom fastapi.middleware.cors import CORSMiddlewarefrom http.server import BaseHTTPRequestHandler, HTTPServerfrom urllib.parse import urlparse, parse_qsimport ijson2 unmodified linesfrom google.oauth2.credentials import Credentialsfrom google_auth_oauthlib.flow import Flowfrom google.auth.transport.requests import Request as GoogleAuthRequestfrom google.auth.exceptions import RefreshError# Load environment variables from .env fileload_dotenv()5 unmodified lines"https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile",]SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))CREDENTIAL_FILE = os.path.join(SCRIPT_DIR, "oauth_creds.json")CODE_ASSIST_ENDPOINT = "https://cloudcode-pa.googleapis.com"GEMINI_PORT = int(os.getenv("GEMINI_PORT", "8888")) # Default to 8888 if not setGEMINI_AUTH_PASSWORD = os.getenv("GEMINI_AUTH_PASSWORD", "123456") # Default passwordCLI_VERSION = "0.1.5" # Match current gemini-cli version# --- Global State ---credentials = Noneuser_project_id = Noneonboarding_complete = Falseapp = FastAPI()security = HTTPBasic()# Add CORS middleware for preflight requestsapp.add_middleware(CORSMiddleware,allow_origins=["*"], # Allow all originsallow_credentials=True,allow_methods=["*"], # Allow all methodsallow_headers=["*"], # Allow all headers)def get_user_agent():"""Generate User-Agent string matching gemini-cli format."""version = CLI_VERSIONsystem = platform.system()arch = platform.machine()return f"GeminiCLI/{version} ({system}; {arch})"def authenticate_user(request: Request):"""Authenticate the user with multiple methods."""# Check for API key in query parameters first (for Gemini client compatibility)1 unmodified lineif api_key and api_key == GEMINI_AUTH_PASSWORD:return "api_key_user"# Check for API key in x-goog-api-key header (Google SDK format)goog_api_key = request.headers.get("x-goog-api-key", "")if goog_api_key and goog_api_key == GEMINI_AUTH_PASSWORD:return "goog_api_key_user"# Check for API key in Authorization header (Bearer token format)auth_header = request.headers.get("authorization", "")if auth_header.startswith("Bearer "):bearer_token = auth_header[7:]if bearer_token == GEMINI_AUTH_PASSWORD:return "bearer_user"# Check for HTTP Basic Authenticationif auth_header.startswith("Basic "):9 unmodified lines# If none of the authentication methods workraise HTTPException(status_code=401,detail="Invalid authentication credentials. Use HTTP Basic Auth, Bearer token, 'key' query parameter, or 'x-goog-api-key' header.",headers={"WWW-Authenticate": "Basic"},)46 unmodified linesself.end_headers()self.wfile.write(b"<h1>Authentication failed.</h1><p>Please try again.</p>")def get_platform_string():"""Generate platform string matching gemini-cli format."""system = platform.system().upper()arch = platform.machine().upper()# Map to gemini-cli platform formatif system == "DARWIN":if arch in ["ARM64", "AARCH64"]:return "DARWIN_ARM64"else:return "DARWIN_AMD64"elif system == "LINUX":if arch in ["ARM64", "AARCH64"]:return "LINUX_ARM64"else:return "LINUX_AMD64"elif system == "WINDOWS":return "WINDOWS_AMD64"else:return "PLATFORM_UNSPECIFIED"def get_client_metadata(project_id=None):return {"ideType": "IDE_UNSPECIFIED","platform": get_platform_string(),"pluginType": "GEMINI","duetProject": project_id,}def onboard_user(creds, project_id):"""Ensures the user is onboarded, matching gemini-cli setupUser behavior."""global onboarding_completeif onboarding_complete:return# Refresh credentials if expired before making API callsif creds.expired and creds.refresh_token:print("Credentials expired. Refreshing before onboarding...")try:creds.refresh(GoogleAuthRequest())save_credentials(creds)print("Credentials refreshed successfully.")except Exception as e:print(f"Could not refresh credentials: {e}")raiseprint("Checking user onboarding status...")headers = {"Authorization": f"Bearer {creds.token}","Content-Type": "application/json","User-Agent": get_user_agent(),}# 1. Call loadCodeAssist to check current statusload_assist_payload = {"cloudaicompanionProject": project_id,"metadata": get_client_metadata(project_id),}try:resp = requests.post(f"{CODE_ASSIST_ENDPOINT}/v1internal:loadCodeAssist",data=json.dumps(load_assist_payload),headers=headers,)resp.raise_for_status()load_data = resp.json()# Determine the tier to use (current or default)tier = Noneif load_data.get("currentTier"):tier = load_data["currentTier"]print("User is already onboarded.")else:# Find default tier for onboardingfor allowed_tier in load_data.get("allowedTiers", []):if allowed_tier.get("isDefault"):tier = allowed_tierbreakif not tier:# Fallback tier if no default found (matching gemini-cli logic)tier = {"name": "","description": "","id": "legacy-tier","userDefinedCloudaicompanionProject": True,}# Check if project ID is required but missingif tier.get("userDefinedCloudaicompanionProject") and not project_id:raise ValueError("This account requires setting the GOOGLE_CLOUD_PROJECT env var.")# If already onboarded, skip the onboarding processif load_data.get("currentTier"):onboarding_complete = Truereturnprint(f"Onboarding user to tier: {tier.get('name', 'legacy-tier')}")onboard_req_payload = {"tierId": tier.get("id"),"cloudaicompanionProject": project_id,"metadata": get_client_metadata(project_id),}# 2. Poll onboardUser until complete (matching gemini-cli polling logic)while True:onboard_resp = requests.post(f"{CODE_ASSIST_ENDPOINT}/v1internal:onboardUser",data=json.dumps(onboard_req_payload),headers=headers,)onboard_resp.raise_for_status()lro_data = onboard_resp.json()if lro_data.get("done"):print("Onboarding successful.")onboarding_complete = Truebreakprint("Onboarding in progress, waiting 5 seconds...")time.sleep(5)except requests.exceptions.HTTPError as e:print(f"Error during onboarding: {e.response.text}")raisedef get_user_project_id(creds):"""Gets the user's project ID matching gemini-cli setupUser logic."""global user_project_idif user_project_id:return user_project_id# First, check for GOOGLE_CLOUD_PROJECT environment variable (matching gemini-cli)env_project_id = os.getenv("GOOGLE_CLOUD_PROJECT")if env_project_id:user_project_id = env_project_idprint(f"Using project ID from GOOGLE_CLOUD_PROJECT: {user_project_id}")save_credentials(creds, user_project_id)return user_project_id# Second, check for GEMINI_PROJECT_ID as fallbackgemini_env_project_id = os.getenv("GEMINI_PROJECT_ID")if gemini_env_project_id:user_project_id = gemini_env_project_idprint(f"Using project ID from GEMINI_PROJECT_ID: {user_project_id}")save_credentials(creds, user_project_id)return user_project_id# Third, try to load project ID from credential fileif os.path.exists(CREDENTIAL_FILE):try:with open(CREDENTIAL_FILE, "r") as f:6 unmodified linesexcept Exception as e:print(f"Could not load project ID from cache: {e}")# If not found in environment or cache, probe for it via loadCodeAssistprint("Project ID not found in environment or cache. Probing for user project ID...")# Refresh credentials if expired before making API callsif creds.expired and creds.refresh_token:print("Credentials expired. Refreshing before project ID probe...")try:creds.refresh(GoogleAuthRequest())save_credentials(creds)print("Credentials refreshed successfully.")except Exception as e:print(f"Could not refresh credentials: {e}")raiseheaders = {"Authorization": f"Bearer {creds.token}","Content-Type": "application/json","User-Agent": get_user_agent(),}probe_payload = {"metadata": get_client_metadata(),}try:9 unmodified linesraise ValueError("Could not find 'cloudaicompanionProject' in loadCodeAssist response.")print(f"Successfully fetched user project ID: {user_project_id}")save_credentials(creds, user_project_id)print("Project ID saved to credential file for future use.")3 unmodified linesraisedef save_credentials(creds, project_id=None):creds_data = {"client_id": CLIENT_ID,"client_secret": CLIENT_SECRET,"access_token": creds.token,"refresh_token": creds.refresh_token,"scope": " ".join(creds.scopes) if creds.scopes else " ".join(SCOPES),"token_type": "Bearer","token_uri": "https://oauth2.googleapis.com/token",}# Add expiry if availableif creds.expiry:creds_data["expiry"] = creds.expiry.isoformat()# If project_id is provided, save it; otherwise preserve existing project_idif project_id:creds_data["project_id"] = project_id10 unmodified linesjson.dump(creds_data, f)def get_credentials():"""Loads credentials matching gemini-cli OAuth2 flow."""global credentials# Check environment for credentials firstenv_creds = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")if env_creds and os.path.exists(env_creds):try:with open(env_creds, "r") as f:creds_data = json.load(f)credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)print("Loaded credentials from GOOGLE_APPLICATION_CREDENTIALS.")if credentials.expired and credentials.refresh_token:print("Refreshing expired credentials...")credentials.refresh(GoogleAuthRequest())save_credentials(credentials)return credentialsexcept Exception as e:print(f"Could not load credentials from GOOGLE_APPLICATION_CREDENTIALS: {e}")# Fallback to cached credentialsif os.path.exists(CREDENTIAL_FILE):try:with open(CREDENTIAL_FILE, "r") as f:creds_data = json.load(f)credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)print("Loaded credentials from cache.")# Try to refresh if we have refresh token but no access tokenif not credentials.token and credentials.refresh_token:print("Attempting to refresh credentials...")try:from google.auth.transport.requests import Request as AuthRequestauth_request = AuthRequest()credentials.refresh(auth_request)print("Credentials refreshed successfully!")# Save refreshed credentialsupdated_creds_data = {'client_id': credentials.client_id,'client_secret': credentials.client_secret,'access_token': credentials.token,'refresh_token': credentials.refresh_token,'scope': credentials.scopes,'token_type': 'Bearer','token_uri': credentials.token_uri,'expiry': credentials.expiry.isoformat() if credentials.expiry else None,'project_id': creds_data.get('project_id')}with open(CREDENTIAL_FILE, 'w') as f:json.dump(updated_creds_data, f, indent=2)print("Refreshed credentials saved.")except Exception as e:print(f"Failed to refresh credentials: {e}")return None# Check if we have a valid token after potential refreshif not credentials.token:print("No access token available after refresh attempt. Starting new login.")return Noneif credentials.expired and credentials.refresh_token:print("Refreshing expired credentials...")try:credentials.refresh(GoogleAuthRequest())save_credentials(credentials)print("Credentials refreshed and saved.")except Exception as refresh_error:print(f"Failed to refresh credentials: {refresh_error}. Starting new login.")return Nonereturn credentialsexcept Exception as e:print(f"Could not load cached credentials: {e}. Starting new login.")# If no valid credentials, start new login flowclient_config = {"installed": {"client_id": CLIENT_ID,2 unmodified lines"token_uri": "https://oauth2.googleapis.com/token",}}# Create flow with include_granted_scopes to handle scope changesflow = Flow.from_client_config(client_config,scopes=SCOPES,redirect_uri="http://localhost:8080")# Set include_granted_scopes to handle additional scopes gracefullyflow.oauth2session.scope = SCOPESauth_url, _ = flow.authorization_url(access_type="offline",prompt="consent",include_granted_scopes='true')print(f"\nPlease open this URL in your browser to log in:\n{auth_url}\n")server = HTTPServer(("", 8080), _OAuthCallbackHandler)4 unmodified linesprint("Failed to retrieve authorization code.")return None# Monkey patch to handle scope validation warningsimport oauthlib.oauth2.rfc6749.parametersoriginal_validate = oauthlib.oauth2.rfc6749.parameters.validate_token_parametersdef patched_validate(params):try:return original_validate(params)except Warning:# Ignore scope change warningspassoauthlib.oauth2.rfc6749.parameters.validate_token_parameters = patched_validatetry:flow.fetch_token(code=auth_code)credentials = flow.credentialssave_credentials(credentials)print("Authentication successful! Credentials saved.")return credentialsexcept Exception as e:print(f"Authentication failed: {e}")return Nonefinally:# Restore original functionoauthlib.oauth2.rfc6749.parameters.validate_token_parameters = original_validate@app.options("/{full_path:path}")async def handle_preflight(request: Request, full_path: str):"""Handle CORS preflight requests without authentication."""return Response(status_code=200,headers={"Access-Control-Allow-Origin": "*","Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers": "*","Access-Control-Allow-Credentials": "true",})@app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])async def proxy_request(request: Request, full_path: str, username: str = Depends(authenticate_user)):print(f"[{request.method}] /{full_path} - User: {username}")creds = get_credentials()if not creds:print("❌ No credentials available")return Response(content="Authentication failed. Please restart the proxy to log in.", status_code=500)# Check if credentials need refreshing (more lenient validation)if creds.expired and creds.refresh_token:print("Credentials expired. Refreshing...")try:creds.refresh(GoogleAuthRequest())save_credentials(creds)print("Credentials refreshed successfully.")except Exception as e:print(f"Could not refresh token during request: {e}")return Response(content="Token refresh failed. Please restart the proxy to re-authenticate.", status_code=500)elif not creds.token:print("No access token available.")return Response(content="No access token. Please restart the proxy to re-authenticate.", status_code=500)proj_id = get_user_project_id(creds)if not proj_id:return Response(content="Failed to get user project ID.", status_code=500)onboard_user(creds, proj_id)post_data = await request.body()path = f"/{full_path}"62 unmodified linesheaders = {"Authorization": f"Bearer {creds.token}","Content-Type": "application/json","User-Agent": get_user_agent(),}if is_streaming:172 unmodified linesprint("Initializing credentials...")creds = get_credentials()if creds:proj_id = get_user_project_id(creds)if proj_id:onboard_user(creds, proj_id)print(f"\nStarting Gemini proxy server on http://localhost:{GEMINI_PORT}")print("Send your Gemini API requests to this address.")print(f"Authentication required - Password: {GEMINI_AUTH_PASSWORD}")
gemini_proxy.py+337-94