omnispindle 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Omnispindle/auth.py ADDED
@@ -0,0 +1,117 @@
1
+
2
+ import json
3
+ import logging
4
+ from functools import lru_cache
5
+ from typing import Optional
6
+
7
+ import httpx
8
+ from fastapi import Depends, HTTPException, status
9
+ from fastapi.security import OAuth2PasswordBearer, SecurityScopes
10
+ from jose import jwt
11
+ from jose.exceptions import JWTError
12
+
13
+ from .models.config import AuthConfig
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
18
+
19
+ AUTH_CONFIG = AuthConfig(
20
+ domain="dev-eoi0koiaujjbib20.us.auth0.com",
21
+ audience="https://madnessinteractive.cc/api",
22
+ client_id="U43kJwbd1xPcCzJsu3kZIIeNV1ygS7x1",
23
+ )
24
+
25
+
26
+ @lru_cache(maxsize=1)
27
+ def get_jwks():
28
+ """
29
+ Fetches the JSON Web Key Set (JWKS) from the Auth0 domain.
30
+ The result is cached to avoid repeated HTTP requests.
31
+ """
32
+ try:
33
+ url = f"https://{AUTH_CONFIG.domain}/.well-known/jwks.json"
34
+ with httpx.Client() as client:
35
+ response = client.get(url)
36
+ response.raise_for_status()
37
+ return response.json()
38
+ except httpx.RequestError as e:
39
+ logger.error(f"Error requesting JWKS: {e}")
40
+ raise
41
+ except httpx.HTTPStatusError as e:
42
+ logger.error(f"HTTP error fetching JWKS: {e.response.status_code} - {e.response.text}")
43
+ raise
44
+
45
+
46
+ async def get_current_user(security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)) -> Optional[dict]:
47
+ """
48
+ Dependency to get the current user from the Auth0-signed JWT.
49
+ """
50
+ if token is None:
51
+ raise HTTPException(
52
+ status_code=status.HTTP_401_UNAUTHORIZED,
53
+ detail="Authentication token is missing",
54
+ headers={"WWW-Authenticate": "Bearer"},
55
+ )
56
+
57
+ unverified_header = jwt.get_unverified_header(token)
58
+ jwks = get_jwks()
59
+ rsa_key = {}
60
+ for key in jwks["keys"]:
61
+ if key["kid"] == unverified_header["kid"]:
62
+ rsa_key = {
63
+ "kty": key["kty"],
64
+ "kid": key["kid"],
65
+ "use": key["use"],
66
+ "n": key["n"],
67
+ "e": key["e"],
68
+ }
69
+ break
70
+
71
+ if not rsa_key:
72
+ raise HTTPException(
73
+ status_code=status.HTTP_401_UNAUTHORIZED,
74
+ detail="Unable to find appropriate key",
75
+ headers={"WWW-Authenticate": "Bearer"},
76
+ )
77
+
78
+ try:
79
+ payload = jwt.decode(
80
+ token,
81
+ rsa_key,
82
+ algorithms=["RS256"],
83
+ audience=AUTH_CONFIG.audience,
84
+ issuer=f"https://{AUTH_CONFIG.domain}/",
85
+ )
86
+ except JWTError as e:
87
+ logger.error(f"JWT Error: {e}")
88
+ raise HTTPException(
89
+ status_code=status.HTTP_401_UNAUTHORIZED,
90
+ detail=str(e),
91
+ headers={"WWW-Authenticate": "Bearer"},
92
+ )
93
+
94
+ if security_scopes.scopes:
95
+ token_scopes = set(payload.get("scope", "").split())
96
+ if not token_scopes.issuperset(set(security_scopes.scopes)):
97
+ raise HTTPException(
98
+ status_code=status.HTTP_403_FORBIDDEN,
99
+ detail="Not enough permissions",
100
+ headers={"WWW-Authenticate": "Bearer"},
101
+ )
102
+
103
+ return payload
104
+
105
+
106
+ async def get_current_user_from_query(token: str) -> Optional[dict]:
107
+ """
108
+ A dependency that extracts the user from a token passed as a query parameter.
109
+ Used for streaming endpoints where headers might not be as convenient.
110
+ """
111
+ if not token:
112
+ raise HTTPException(
113
+ status_code=status.HTTP_401_UNAUTHORIZED,
114
+ detail="Authentication token is missing from query.",
115
+ )
116
+ # Re-use the same logic as the header-based dependency
117
+ return await get_current_user(SecurityScopes([]), token)
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Auth0 Custom Token Exchange Action for Omnispindle
3
+ *
4
+ * This action handles the exchange of locally-generated tokens for Auth0 tokens.
5
+ * It validates the token format and creates/links users based on the local machine identity.
6
+ *
7
+ * To deploy:
8
+ * 1. Create a new Action in Auth0 Dashboard with Custom Token Exchange trigger
9
+ * 2. Copy this code into the Action editor
10
+ * 3. Deploy the Action
11
+ * 4. Create a Custom Token Exchange Profile with subject_token_type: "urn:omnispindle:local-auth"
12
+ */
13
+
14
+ /**
15
+ * Handler to be executed while executing a custom token exchange request
16
+ * @param {Event} event - Details about the incoming token exchange request.
17
+ * @param {CustomTokenExchangeAPI} api - Methods and utilities to define token exchange process.
18
+ */
19
+ exports.onExecuteCustomTokenExchange = async (event, api) => {
20
+ const subjectToken = event.transaction.subject_token;
21
+
22
+ // Validate token format: local.{username}.{timestamp}.{hash}
23
+ const tokenParts = subjectToken.split('.');
24
+
25
+ if (tokenParts.length !== 4 || tokenParts[0] !== 'local') {
26
+ api.access.rejectInvalidSubjectToken('Invalid token format');
27
+ return;
28
+ }
29
+
30
+ const [_, username, timestamp, hash] = tokenParts;
31
+
32
+ // Validate timestamp (not older than 5 minutes)
33
+ const tokenTime = parseInt(timestamp);
34
+ const currentTime = Math.floor(Date.now() / 1000);
35
+ const maxAge = 300; // 5 minutes
36
+
37
+ if (isNaN(tokenTime) || currentTime - tokenTime > maxAge) {
38
+ api.access.rejectInvalidSubjectToken('Token expired');
39
+ return;
40
+ }
41
+
42
+ // Validate hash format (should be 64 hex chars for SHA256)
43
+ if (!/^[a-f0-9]{64}$/i.test(hash)) {
44
+ api.access.rejectInvalidSubjectToken('Invalid token hash');
45
+ return;
46
+ }
47
+
48
+ // Create a unique user ID based on the machine identity
49
+ // We use the hash as it contains machine-specific information
50
+ const userId = `local_${username}_${hash.substring(0, 12)}`;
51
+
52
+ // Set the user in Auth0
53
+ // This will create the user if they don't exist, or link to existing
54
+ api.authentication.setUserByConnection(
55
+ 'Username-Password-Authentication', // Your database connection name
56
+ {
57
+ user_id: userId,
58
+ email: `${username}@local.omnispindle`,
59
+ username: username,
60
+ name: username,
61
+ user_metadata: {
62
+ auth_method: 'local_token_exchange',
63
+ machine_hash: hash.substring(0, 12),
64
+ last_exchange: new Date().toISOString()
65
+ }
66
+ },
67
+ {
68
+ creationBehavior: 'setUserIdIfNotExists',
69
+ updateBehavior: 'update_user_metadata'
70
+ }
71
+ );
72
+
73
+ // Add custom claims to the token
74
+ api.accessToken.setCustomClaim('auth_method', 'local_token_exchange');
75
+ api.accessToken.setCustomClaim('local_user', username);
76
+ api.idToken.setCustomClaim('auth_method', 'local_token_exchange');
77
+ api.idToken.setCustomClaim('local_user', username);
78
+ };
@@ -0,0 +1,173 @@
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ import os
5
+ import sys
6
+ import webbrowser
7
+ from pathlib import Path
8
+ from typing import Optional
9
+ from http.server import HTTPServer, BaseHTTPRequestHandler
10
+ import threading
11
+ import time
12
+
13
+ # Auth0 configuration - Reads from environment variables
14
+ CALLBACK_PORT = 8765
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ def run_async_in_thread(coro):
20
+ """
21
+ Run an async coroutine in a separate thread, managing the event loop.
22
+ """
23
+ def thread_target():
24
+ try:
25
+ loop = asyncio.get_running_loop()
26
+ except RuntimeError: # 'RuntimeError: There is no current event loop...'
27
+ loop = asyncio.new_event_loop()
28
+ asyncio.set_event_loop(loop)
29
+
30
+ return loop.run_until_complete(coro)
31
+
32
+ thread = threading.Thread(target=thread_target)
33
+ thread.start()
34
+ thread.join()
35
+
36
+
37
+ class CallbackHandler(BaseHTTPRequestHandler):
38
+ """HTTP handler for Auth0 callback"""
39
+
40
+ def do_GET(self):
41
+ """Handle the OAuth callback from Auth0"""
42
+ if self.path.startswith('/callback'):
43
+ self.send_response(200)
44
+ self.send_header('Content-type', 'text/html')
45
+ self.end_headers()
46
+
47
+ success_html = """
48
+ <!DOCTYPE html><html><head><title>Success</title>
49
+ <script>
50
+ const hash = window.location.hash.substring(1);
51
+ const params = new URLSearchParams(hash);
52
+ const token = params.get('access_token');
53
+ if (token) {
54
+ fetch('/token', {
55
+ method: 'POST',
56
+ headers: {'Content-Type': 'application/json'},
57
+ body: JSON.stringify({access_token: token})
58
+ }).then(() => setTimeout(() => window.close(), 1000));
59
+ }
60
+ </script>
61
+ </head><body><h1>Authenticated!</h1><p>You can close this window.</p></body></html>
62
+ """
63
+ self.wfile.write(success_html.encode())
64
+
65
+ def do_POST(self):
66
+ """Handle token submission from JavaScript"""
67
+ if self.path == '/token':
68
+ content_length = int(self.headers['Content-Length'])
69
+ post_data = self.rfile.read(content_length)
70
+ data = json.loads(post_data)
71
+ self.server.token = data.get('access_token')
72
+ self.send_response(200)
73
+ self.end_headers()
74
+
75
+ def log_message(self, format, *args):
76
+ pass
77
+
78
+ class AuthCallbackServer(HTTPServer):
79
+ """Extended HTTPServer that can store the received token"""
80
+ def __init__(self, *args, **kwargs):
81
+ super().__init__(*args, **kwargs)
82
+ self.token = None
83
+
84
+ def start_callback_server() -> AuthCallbackServer:
85
+ """Start a local HTTP server to handle the Auth0 callback"""
86
+ server = AuthCallbackServer(('localhost', CALLBACK_PORT), CallbackHandler)
87
+ thread = threading.Thread(target=server.serve_forever)
88
+ thread.daemon = True
89
+ thread.start()
90
+ return server
91
+
92
+ def open_auth0_login():
93
+ """Open the Auth0 login page in the user's browser"""
94
+ auth0_domain = os.getenv("AUTH0_DOMAIN")
95
+ auth0_client_id = os.getenv("AUTH0_CLIENT_ID")
96
+ auth0_audience = os.getenv("AUTH0_AUDIENCE", "https://madnessinteractive.cc/api")
97
+
98
+ auth_url = (
99
+ f"https://{auth0_domain}/authorize"
100
+ f"?client_id={auth0_client_id}"
101
+ f"&response_type=token"
102
+ f"&redirect_uri=http://localhost:{CALLBACK_PORT}/callback"
103
+ f"&audience={auth0_audience}"
104
+ f"&scope=openid%20profile%20email" # URL Encoded scope
105
+ )
106
+
107
+ print(f"Opening browser to: {auth_url}", file=sys.stderr)
108
+ webbrowser.open(auth_url)
109
+
110
+ def save_token_to_env(token: str) -> Path:
111
+ """Save the Auth0 token to a .env file"""
112
+ env_path = Path(__file__).parent.parent.parent / '.env'
113
+
114
+ env_lines = []
115
+ if env_path.exists():
116
+ with open(env_path, 'r') as f:
117
+ env_lines = f.readlines()
118
+
119
+ token_line = f"AUTH0_TOKEN={token}\n"
120
+ token_found = False
121
+
122
+ for i, line in enumerate(env_lines):
123
+ if line.startswith('AUTH0_TOKEN='):
124
+ env_lines[i] = token_line
125
+ token_found = True
126
+ break
127
+
128
+ if not token_found:
129
+ env_lines.append(token_line)
130
+
131
+ with open(env_path, 'w') as f:
132
+ f.writelines(env_lines)
133
+
134
+ os.environ['AUTH0_TOKEN'] = token
135
+ return env_path
136
+
137
+ async def authenticate_user() -> Optional[str]:
138
+ """Perform browser-based authentication flow."""
139
+ existing_token = os.environ.get('AUTH0_TOKEN')
140
+ if existing_token:
141
+ return existing_token
142
+
143
+ server = start_callback_server()
144
+ open_auth0_login()
145
+
146
+ timeout = 120
147
+ start_time = time.time()
148
+
149
+ while server.token is None and (time.time() - start_time) < timeout:
150
+ await asyncio.sleep(0.5)
151
+
152
+ server.shutdown()
153
+
154
+ if server.token:
155
+ save_token_to_env(server.token)
156
+ return server.token
157
+ else:
158
+ return None
159
+
160
+ async def ensure_authenticated() -> str:
161
+ """Ensure the user is authenticated, prompting for login if needed."""
162
+ token = await authenticate_user()
163
+ if not token:
164
+ raise RuntimeError("Authentication failed.")
165
+ return token
166
+
167
+ if __name__ == "__main__":
168
+ try:
169
+ token = asyncio.run(ensure_authenticated())
170
+ print(f"Token: {token}")
171
+ except RuntimeError as e:
172
+ print(f"Error: {e}", file=sys.stderr)
173
+ sys.exit(1)
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Auth0 CLI setup for Omnispindle MCP client configuration.
4
+
5
+ This module provides a command-line interface for users to authenticate with Auth0
6
+ and retrieve their credentials for MCP client setup (Claude Desktop, etc.).
7
+ """
8
+
9
+ import asyncio
10
+ import base64
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import secrets
15
+ import urllib.parse
16
+ import webbrowser
17
+ from typing import Dict, Any, Optional
18
+ import logging
19
+
20
+ import requests
21
+ from dotenv import load_dotenv
22
+
23
+ # Load environment variables
24
+ load_dotenv()
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ class Auth0CLISetup:
30
+ """Handles Auth0 device flow authentication for MCP setup."""
31
+
32
+ def __init__(self):
33
+ # Use same Auth0 config as main application
34
+ self.auth0_domain = "dev-eoi0koiaujjbib20.us.auth0.com"
35
+ self.client_id = "U43kJwbd1xPcCzJsu3kZIIeNV1ygS7x1"
36
+ self.audience = "https://madnessinteractive.cc/api"
37
+
38
+ def generate_pkce_pair(self) -> tuple[str, str]:
39
+ """Generate PKCE code verifier and challenge for secure auth flow."""
40
+ # Generate code verifier (43-128 characters)
41
+ code_verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode('utf-8').rstrip('=')
42
+
43
+ # Generate code challenge
44
+ challenge_bytes = hashlib.sha256(code_verifier.encode('utf-8')).digest()
45
+ code_challenge = base64.urlsafe_b64encode(challenge_bytes).decode('utf-8').rstrip('=')
46
+
47
+ return code_verifier, code_challenge
48
+
49
+ def start_device_flow(self) -> Dict[str, Any]:
50
+ """Initiate Auth0 device authorization flow."""
51
+ device_code_url = f"https://{self.auth0_domain}/oauth/device/code"
52
+
53
+ data = {
54
+ "client_id": self.client_id,
55
+ "scope": "openid profile email",
56
+ "audience": self.audience
57
+ }
58
+
59
+ response = requests.post(device_code_url, data=data)
60
+ response.raise_for_status()
61
+
62
+ return response.json()
63
+
64
+ def poll_for_token(self, device_code: str, interval: int = 5) -> Dict[str, Any]:
65
+ """Poll Auth0 for access token after user authorization."""
66
+ token_url = f"https://{self.auth0_domain}/oauth/token"
67
+
68
+ data = {
69
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
70
+ "device_code": device_code,
71
+ "client_id": self.client_id
72
+ }
73
+
74
+ while True:
75
+ response = requests.post(token_url, data=data)
76
+
77
+ if response.status_code == 200:
78
+ return response.json()
79
+
80
+ result = response.json()
81
+ error = result.get("error")
82
+
83
+ if error == "authorization_pending":
84
+ print("ā³ Waiting for user authorization...")
85
+ asyncio.sleep(interval)
86
+ continue
87
+ elif error == "slow_down":
88
+ interval += 5
89
+ asyncio.sleep(interval)
90
+ continue
91
+ elif error == "expired_token":
92
+ raise Exception("āŒ Authorization expired. Please run setup again.")
93
+ elif error == "access_denied":
94
+ raise Exception("āŒ Access denied. User cancelled authorization.")
95
+ else:
96
+ raise Exception(f"āŒ Token exchange failed: {error}")
97
+
98
+ def get_user_info(self, access_token: str) -> Dict[str, Any]:
99
+ """Get user profile information from Auth0."""
100
+ userinfo_url = f"https://{self.auth0_domain}/userinfo"
101
+
102
+ headers = {"Authorization": f"Bearer {access_token}"}
103
+ response = requests.get(userinfo_url, headers=headers)
104
+ response.raise_for_status()
105
+
106
+ return response.json()
107
+
108
+ def generate_mcp_config(self, user_info: Dict[str, Any]) -> Dict[str, Any]:
109
+ """Generate Claude Desktop MCP configuration."""
110
+ omnispindle_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
111
+
112
+ config = {
113
+ "mcpServers": {
114
+ "omnispindle": {
115
+ "command": "python",
116
+ "args": ["stdio_main.py"],
117
+ "cwd": omnispindle_path,
118
+ "env": {
119
+ "MONGODB_URI": os.getenv("MONGODB_URI", "mongodb://localhost:27017"),
120
+ "MONGODB_DB": os.getenv("MONGODB_DB", "swarmonomicon"),
121
+ "OMNISPINDLE_TOOL_LOADOUT": "basic",
122
+ "MCP_USER_EMAIL": user_info.get("email"),
123
+ "MCP_USER_ID": user_info.get("sub")
124
+ }
125
+ }
126
+ }
127
+ }
128
+
129
+ return config
130
+
131
+ def save_config(self, config: Dict[str, Any], output_path: Optional[str] = None) -> str:
132
+ """Save MCP configuration to file."""
133
+ if output_path is None:
134
+ home_dir = os.path.expanduser("~")
135
+ output_path = os.path.join(home_dir, "omnispindle_mcp_config.json")
136
+
137
+ with open(output_path, 'w') as f:
138
+ json.dump(config, f, indent=2)
139
+
140
+ return output_path
141
+
142
+ async def run_setup(self, save_config: bool = True) -> Dict[str, Any]:
143
+ """Run the complete Auth0 setup flow."""
144
+ print("šŸ” Omnispindle Auth0 MCP Setup")
145
+ print("=" * 40)
146
+ print()
147
+
148
+ try:
149
+ # Start device flow
150
+ print("šŸ“± Starting Auth0 device authorization...")
151
+ device_info = self.start_device_flow()
152
+
153
+ # Show user instructions
154
+ verification_uri = device_info["verification_uri_complete"]
155
+ user_code = device_info["user_code"]
156
+
157
+ print(f"🌐 Opening browser to: {verification_uri}")
158
+ print(f"šŸ“ Your code is: {user_code}")
159
+ print()
160
+ print("Please complete the authorization in your browser...")
161
+
162
+ # Open browser
163
+ webbrowser.open(verification_uri)
164
+
165
+ # Poll for token
166
+ print("ā³ Waiting for authorization...")
167
+ token_info = self.poll_for_token(
168
+ device_info["device_code"],
169
+ device_info.get("interval", 5)
170
+ )
171
+
172
+ # Get user info
173
+ print("āœ… Authorization successful! Getting user info...")
174
+ user_info = self.get_user_info(token_info["access_token"])
175
+
176
+ # Generate MCP config
177
+ print("āš™ļø Generating MCP configuration...")
178
+ mcp_config = self.generate_mcp_config(user_info)
179
+
180
+ # Display results
181
+ print()
182
+ print("šŸŽ‰ Setup Complete!")
183
+ print("=" * 40)
184
+ print(f"šŸ‘¤ User: {user_info.get('email', 'Unknown')}")
185
+ print(f"šŸ†” User ID: {user_info.get('sub', 'Unknown')}")
186
+ print()
187
+
188
+ if save_config:
189
+ config_path = self.save_config(mcp_config)
190
+ print(f"šŸ’¾ Configuration saved to: {config_path}")
191
+ print()
192
+ print("šŸ“‹ To use with Claude Desktop:")
193
+ print(f"1. Copy the contents of {config_path}")
194
+ print("2. Paste into your Claude Desktop settings")
195
+ print("3. Restart Claude Desktop")
196
+ else:
197
+ print("šŸ“‹ MCP Configuration:")
198
+ print(json.dumps(mcp_config, indent=2))
199
+
200
+ print()
201
+ print("šŸš€ You're ready to use Omnispindle with MCP!")
202
+
203
+ return {
204
+ "user_info": user_info,
205
+ "mcp_config": mcp_config,
206
+ "config_path": config_path if save_config else None
207
+ }
208
+
209
+ except Exception as e:
210
+ print(f"āŒ Setup failed: {e}")
211
+ raise
212
+
213
+
214
+ async def main():
215
+ """Main entry point for CLI setup."""
216
+ import argparse
217
+
218
+ parser = argparse.ArgumentParser(description="Setup Auth0 authentication for Omnispindle MCP")
219
+ parser.add_argument("--no-save", action="store_true", help="Don't save config file, just display")
220
+ parser.add_argument("--output", "-o", help="Output path for config file")
221
+
222
+ args = parser.parse_args()
223
+
224
+ try:
225
+ setup = Auth0CLISetup()
226
+ result = await setup.run_setup(save_config=not args.no_save)
227
+
228
+ if args.output and not args.no_save:
229
+ setup.save_config(result["mcp_config"], args.output)
230
+ print(f"šŸ’¾ Config also saved to: {args.output}")
231
+
232
+ except KeyboardInterrupt:
233
+ print("\nāŒ Setup cancelled by user")
234
+ except Exception as e:
235
+ print(f"āŒ Setup failed: {e}")
236
+ exit(1)
237
+
238
+
239
+ if __name__ == "__main__":
240
+ asyncio.run(main())
@@ -0,0 +1,80 @@
1
+ """
2
+ Authentication utilities shared between stdio and HTTP servers.
3
+ """
4
+
5
+ import os
6
+ import httpx
7
+ import json
8
+ from jose import jwt
9
+ from typing import Optional, Dict, Any
10
+ import logging
11
+ from dotenv import load_dotenv
12
+ from dataclasses import dataclass
13
+
14
+ load_dotenv()
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ @dataclass
19
+ class Auth0Config:
20
+ domain: str
21
+ client_id: str
22
+ audience: str
23
+
24
+
25
+ # Auth0 configuration
26
+ AUTH_CONFIG = Auth0Config(
27
+ domain=os.getenv("AUTH0_DOMAIN", "dev-eoi0koiaujjbib20.us.auth0.com"),
28
+ client_id=os.getenv("AUTH0_CLIENT_ID", "U43kJwbd1xPcCzJsu3kZIIeNV1ygS7x1"),
29
+ audience=os.getenv("AUTH0_AUDIENCE", "https://madnessinteractive.cc/api")
30
+ )
31
+
32
+
33
+ async def get_jwks() -> Dict[str, Any]:
34
+ """Fetches JWKS from Auth0."""
35
+ jwks_url = f"https://{AUTH_CONFIG.domain}/.well-known/jwks.json"
36
+ async with httpx.AsyncClient() as client:
37
+ response = await client.get(jwks_url)
38
+ response.raise_for_status()
39
+ return response.json()
40
+
41
+
42
+ async def verify_auth0_token(token: str) -> Optional[Dict[str, Any]]:
43
+ """Verifies an Auth0 token and returns the payload."""
44
+ try:
45
+ unverified_header = jwt.get_unverified_header(token)
46
+ jwks = await get_jwks()
47
+ rsa_key = {}
48
+ for key in jwks["keys"]:
49
+ if key["kid"] == unverified_header["kid"]:
50
+ rsa_key = {
51
+ "kty": key["kty"],
52
+ "kid": key["kid"],
53
+ "use": key["use"],
54
+ "n": key["n"],
55
+ "e": key["e"],
56
+ }
57
+ break
58
+
59
+ if not rsa_key:
60
+ logger.error("Unable to find appropriate key in JWKS")
61
+ return None
62
+
63
+ payload = jwt.decode(
64
+ token,
65
+ rsa_key,
66
+ algorithms=["RS256"],
67
+ audience=AUTH_CONFIG.audience,
68
+ issuer=f"https://{AUTH_CONFIG.domain}/",
69
+ )
70
+ return payload
71
+
72
+ except jwt.ExpiredSignatureError:
73
+ logger.error("JWT Error: Signature has expired.")
74
+ return None
75
+ except jwt.JWTClaimsError as e:
76
+ logger.error(f"JWT Error: {e}")
77
+ return None
78
+ except Exception as e:
79
+ logger.error(f"JWT Verification Error: {e}")
80
+ return None