webscout 8.3.4__py3-none-any.whl → 8.3.5__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.

Potentially problematic release.


This version of webscout might be problematic. Click here for more details.

Files changed (55) hide show
  1. webscout/AIutel.py +52 -1016
  2. webscout/Provider/AISEARCH/__init__.py +11 -10
  3. webscout/Provider/AISEARCH/felo_search.py +7 -3
  4. webscout/Provider/AISEARCH/scira_search.py +2 -0
  5. webscout/Provider/AISEARCH/stellar_search.py +53 -8
  6. webscout/Provider/Deepinfra.py +7 -1
  7. webscout/Provider/OPENAI/TogetherAI.py +57 -48
  8. webscout/Provider/OPENAI/TwoAI.py +94 -1
  9. webscout/Provider/OPENAI/__init__.py +0 -2
  10. webscout/Provider/OPENAI/deepinfra.py +6 -0
  11. webscout/Provider/OPENAI/scirachat.py +4 -0
  12. webscout/Provider/OPENAI/textpollinations.py +11 -7
  13. webscout/Provider/OPENAI/venice.py +1 -0
  14. webscout/Provider/Perplexitylabs.py +163 -147
  15. webscout/Provider/Qodo.py +30 -6
  16. webscout/Provider/TTI/__init__.py +1 -0
  17. webscout/Provider/TTI/together.py +7 -6
  18. webscout/Provider/TTI/venice.py +368 -0
  19. webscout/Provider/TextPollinationsAI.py +11 -7
  20. webscout/Provider/TogetherAI.py +57 -44
  21. webscout/Provider/TwoAI.py +96 -2
  22. webscout/Provider/TypliAI.py +33 -27
  23. webscout/Provider/UNFINISHED/PERPLEXED_search.py +254 -0
  24. webscout/Provider/UNFINISHED/fetch_together_models.py +6 -11
  25. webscout/Provider/Venice.py +1 -0
  26. webscout/Provider/WiseCat.py +18 -20
  27. webscout/Provider/__init__.py +0 -6
  28. webscout/Provider/scira_chat.py +4 -0
  29. webscout/Provider/toolbaz.py +5 -10
  30. webscout/Provider/typefully.py +1 -11
  31. webscout/__init__.py +3 -15
  32. webscout/auth/__init__.py +19 -4
  33. webscout/auth/api_key_manager.py +189 -189
  34. webscout/auth/auth_system.py +25 -40
  35. webscout/auth/config.py +105 -6
  36. webscout/auth/database.py +377 -22
  37. webscout/auth/models.py +185 -130
  38. webscout/auth/request_processing.py +175 -11
  39. webscout/auth/routes.py +99 -2
  40. webscout/auth/server.py +9 -2
  41. webscout/auth/simple_logger.py +236 -0
  42. webscout/sanitize.py +1074 -0
  43. webscout/version.py +1 -1
  44. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/METADATA +9 -149
  45. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/RECORD +49 -51
  46. webscout/Provider/OPENAI/README_AUTOPROXY.md +0 -238
  47. webscout/Provider/OPENAI/typegpt.py +0 -368
  48. webscout/Provider/OPENAI/uncovrAI.py +0 -477
  49. webscout/Provider/WritingMate.py +0 -273
  50. webscout/Provider/typegpt.py +0 -284
  51. webscout/Provider/uncovr.py +0 -333
  52. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/WHEEL +0 -0
  53. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/entry_points.txt +0 -0
  54. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/licenses/LICENSE.md +0 -0
  55. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/top_level.txt +0 -0
webscout/auth/__init__.py CHANGED
@@ -26,9 +26,24 @@ def start_server(*args, **kwargs):
26
26
  from .server import start_server as _start_server
27
27
  return _start_server(*args, **kwargs)
28
28
  from .routes import Api
29
- from .config import ServerConfig, AppConfig
30
29
  from .exceptions import APIError
31
- from .providers import initialize_provider_map, initialize_tti_provider_map
30
+
31
+ # Lazy imports for config classes to avoid initialization issues
32
+ def get_server_config():
33
+ from .config import ServerConfig
34
+ return ServerConfig
35
+
36
+ def get_app_config():
37
+ from .config import AppConfig
38
+ return AppConfig
39
+
40
+ def initialize_provider_map():
41
+ from .providers import initialize_provider_map as _init_provider_map
42
+ return _init_provider_map()
43
+
44
+ def initialize_tti_provider_map():
45
+ from .providers import initialize_tti_provider_map as _init_tti_provider_map
46
+ return _init_tti_provider_map()
32
47
 
33
48
  __all__ = [
34
49
  "User",
@@ -47,8 +62,8 @@ __all__ = [
47
62
  "run_api",
48
63
  "start_server",
49
64
  "Api",
50
- "ServerConfig",
51
- "AppConfig",
65
+ "get_server_config",
66
+ "get_app_config",
52
67
  "APIError",
53
68
  "initialize_provider_map",
54
69
  "initialize_tti_provider_map"
@@ -1,189 +1,189 @@
1
- # webscout/auth/api_key_manager.py
2
-
3
- import secrets
4
- import string
5
- from datetime import datetime, timezone, timedelta
6
- from typing import Optional, Tuple
7
- import hashlib
8
- import logging
9
-
10
- from .models import User, APIKey
11
- from .database import DatabaseManager
12
-
13
- logger = logging.getLogger(__name__)
14
-
15
-
16
- class APIKeyManager:
17
- """Manages API key generation, validation, and lifecycle."""
18
-
19
- def __init__(self, database_manager: DatabaseManager):
20
- self.db = database_manager
21
- self.key_prefix = "ws_" # webscout prefix
22
- self.key_length = 32 # Length of the random part
23
-
24
- def generate_api_key(self) -> str:
25
- """Generate a secure API key."""
26
- # Generate random string
27
- alphabet = string.ascii_letters + string.digits
28
- random_part = ''.join(secrets.choice(alphabet) for _ in range(self.key_length))
29
-
30
- # Add prefix
31
- api_key = f"{self.key_prefix}{random_part}"
32
-
33
- return api_key
34
-
35
- def hash_api_key(self, api_key: str) -> str:
36
- """Hash an API key for secure storage (optional, for extra security)."""
37
- return hashlib.sha256(api_key.encode()).hexdigest()
38
-
39
- async def create_api_key(
40
- self,
41
- username: str,
42
- telegram_id: str,
43
- name: Optional[str] = None,
44
- rate_limit: int = 10,
45
- expires_in_days: Optional[int] = None
46
- ) -> Tuple[APIKey, User]:
47
- """Create a new API key and associated user if needed. Only one API key per user allowed."""
48
-
49
- # Check if user already exists by telegram_id
50
- user = await self.db.get_user_by_telegram_id(telegram_id)
51
-
52
- if user:
53
- # Check if user already has an API key
54
- existing_keys = await self.db.get_api_keys_by_user(user.id)
55
- active_keys = [key for key in existing_keys if key.is_active and not key.is_expired()]
56
-
57
- if active_keys:
58
- raise ValueError(f"User with Telegram ID {telegram_id} already has an active API key. Only one API key per user is allowed.")
59
- else:
60
- # Check if username is already taken
61
- existing_user = await self.db.get_user_by_username(username)
62
- if existing_user:
63
- raise ValueError(f"Username '{username}' is already taken")
64
-
65
- # Create new user
66
- user = User(
67
- username=username,
68
- telegram_id=telegram_id,
69
- created_at=datetime.now(timezone.utc),
70
- updated_at=datetime.now(timezone.utc)
71
- )
72
- try:
73
- user = await self.db.create_user(user)
74
- logger.info(f"Created new user: {user.username} (Telegram ID: {telegram_id})")
75
- except ValueError as e:
76
- # User might already exist, try to get it
77
- if "already exists" in str(e):
78
- user = await self.db.get_user_by_telegram_id(telegram_id)
79
- if not user:
80
- raise e
81
- else:
82
- raise e
83
-
84
- # Generate API key
85
- api_key_value = self.generate_api_key()
86
-
87
- # Calculate expiration
88
- expires_at = None
89
- if expires_in_days:
90
- expires_at = datetime.now(timezone.utc) + timedelta(days=expires_in_days)
91
-
92
- # Create API key object
93
- api_key = APIKey(
94
- key=api_key_value,
95
- user_id=user.id,
96
- name=name,
97
- created_at=datetime.now(timezone.utc),
98
- expires_at=expires_at,
99
- rate_limit=rate_limit,
100
- is_active=True
101
- )
102
-
103
- # Store in database
104
- try:
105
- api_key = await self.db.create_api_key(api_key)
106
- logger.info(f"Created API key for user {user.username}: {api_key.id}")
107
- return api_key, user
108
- except ValueError as e:
109
- # Key collision (very unlikely), try again
110
- if "already exists" in str(e):
111
- logger.warning("API key collision detected, regenerating...")
112
- return await self.create_api_key(username, telegram_id, name, rate_limit, expires_in_days)
113
- raise e
114
-
115
- async def validate_api_key(self, api_key: str) -> Tuple[bool, Optional[APIKey], Optional[str]]:
116
- """
117
- Validate an API key.
118
-
119
- Returns:
120
- Tuple of (is_valid, api_key_object, error_message)
121
- """
122
- if not api_key:
123
- return False, None, "API key is required"
124
-
125
- if not api_key.startswith(self.key_prefix):
126
- return False, None, "Invalid API key format"
127
-
128
- try:
129
- # Get API key from database
130
- key_obj = await self.db.get_api_key(api_key)
131
-
132
- if not key_obj:
133
- return False, None, "API key not found"
134
-
135
- if not key_obj.is_active:
136
- return False, None, "API key is inactive"
137
-
138
- if key_obj.is_expired():
139
- return False, None, "API key has expired"
140
-
141
- # Update last used timestamp
142
- key_obj.last_used_at = datetime.now(timezone.utc)
143
- key_obj.usage_count += 1
144
-
145
- try:
146
- await self.db.update_api_key(key_obj)
147
- except Exception as e:
148
- logger.warning(f"Failed to update API key usage: {e}")
149
-
150
- return True, key_obj, None
151
-
152
- except Exception as e:
153
- logger.error(f"Error validating API key: {e}")
154
- return False, None, "Internal error during validation"
155
-
156
- async def revoke_api_key(self, api_key: str) -> bool:
157
- """Revoke an API key by marking it as inactive."""
158
- try:
159
- key_obj = await self.db.get_api_key(api_key)
160
-
161
- if not key_obj:
162
- return False
163
-
164
- key_obj.is_active = False
165
- key_obj.updated_at = datetime.now(timezone.utc)
166
-
167
- await self.db.update_api_key(key_obj)
168
- logger.info(f"Revoked API key: {key_obj.id}")
169
- return True
170
-
171
- except Exception as e:
172
- logger.error(f"Error revoking API key: {e}")
173
- return False
174
-
175
- async def get_user_api_keys(self, user_id: str) -> list[APIKey]:
176
- """Get all API keys for a user."""
177
- try:
178
- return await self.db.get_api_keys_by_user(user_id)
179
- except Exception as e:
180
- logger.error(f"Error getting user API keys: {e}")
181
- return []
182
-
183
- async def cleanup_expired_keys(self) -> int:
184
- """Clean up expired API keys (mark as inactive)."""
185
- # This would require a method to get all API keys, which we haven't implemented
186
- # For now, we'll just return 0
187
- # In a production system, you'd want to implement this properly
188
- logger.info("Cleanup expired keys called (not implemented)")
189
- return 0
1
+ # webscout/auth/api_key_manager.py
2
+
3
+ import secrets
4
+ import string
5
+ from datetime import datetime, timezone, timedelta
6
+ from typing import Optional, Tuple
7
+ import hashlib
8
+ import logging
9
+
10
+ from .models import User, APIKey
11
+ from .database import DatabaseManager
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class APIKeyManager:
17
+ """Manages API key generation, validation, and lifecycle."""
18
+
19
+ def __init__(self, database_manager: DatabaseManager):
20
+ self.db = database_manager
21
+ self.key_prefix = "ws_" # webscout prefix
22
+ self.key_length = 32 # Length of the random part
23
+
24
+ def generate_api_key(self) -> str:
25
+ """Generate a secure API key."""
26
+ # Generate random string
27
+ alphabet = string.ascii_letters + string.digits
28
+ random_part = ''.join(secrets.choice(alphabet) for _ in range(self.key_length))
29
+
30
+ # Add prefix
31
+ api_key = f"{self.key_prefix}{random_part}"
32
+
33
+ return api_key
34
+
35
+ def hash_api_key(self, api_key: str) -> str:
36
+ """Hash an API key for secure storage (optional, for extra security)."""
37
+ return hashlib.sha256(api_key.encode()).hexdigest()
38
+
39
+ async def create_api_key(
40
+ self,
41
+ username: str,
42
+ telegram_id: str,
43
+ name: Optional[str] = None,
44
+ rate_limit: int = 10,
45
+ expires_in_days: Optional[int] = None
46
+ ) -> Tuple[APIKey, User]:
47
+ """Create a new API key and associated user if needed. Only one API key per user allowed."""
48
+
49
+ # Check if user already exists by telegram_id
50
+ user = await self.db.get_user_by_telegram_id(telegram_id)
51
+
52
+ if user:
53
+ # Check if user already has an API key
54
+ existing_keys = await self.db.get_api_keys_by_user(user.id)
55
+ active_keys = [key for key in existing_keys if key.is_active and not key.is_expired()]
56
+
57
+ if active_keys:
58
+ raise ValueError(f"User with Telegram ID {telegram_id} already has an active API key. Only one API key per user is allowed.")
59
+ else:
60
+ # Check if username is already taken
61
+ existing_user = await self.db.get_user_by_username(username)
62
+ if existing_user:
63
+ raise ValueError(f"Username '{username}' is already taken")
64
+
65
+ # Create new user
66
+ user = User(
67
+ username=username,
68
+ telegram_id=telegram_id,
69
+ created_at=datetime.now(timezone.utc),
70
+ updated_at=datetime.now(timezone.utc)
71
+ )
72
+ try:
73
+ user = await self.db.create_user(user)
74
+ logger.info(f"Created new user: {user.username} (Telegram ID: {telegram_id})")
75
+ except ValueError as e:
76
+ # User might already exist, try to get it
77
+ if "already exists" in str(e):
78
+ user = await self.db.get_user_by_telegram_id(telegram_id)
79
+ if not user:
80
+ raise e
81
+ else:
82
+ raise e
83
+
84
+ # Generate API key
85
+ api_key_value = self.generate_api_key()
86
+
87
+ # Calculate expiration
88
+ expires_at = None
89
+ if expires_in_days:
90
+ expires_at = datetime.now(timezone.utc) + timedelta(days=expires_in_days)
91
+
92
+ # Create API key object
93
+ api_key = APIKey(
94
+ key=api_key_value,
95
+ user_id=user.id,
96
+ name=name,
97
+ created_at=datetime.now(timezone.utc),
98
+ expires_at=expires_at,
99
+ rate_limit=rate_limit,
100
+ is_active=True
101
+ )
102
+
103
+ # Store in database
104
+ try:
105
+ api_key = await self.db.create_api_key(api_key)
106
+ logger.info(f"Created API key for user {user.username}: {api_key.id}")
107
+ return api_key, user
108
+ except ValueError as e:
109
+ # Key collision (very unlikely), try again
110
+ if "already exists" in str(e):
111
+ logger.warning("API key collision detected, regenerating...")
112
+ return await self.create_api_key(username, telegram_id, name, rate_limit, expires_in_days)
113
+ raise e
114
+
115
+ async def validate_api_key(self, api_key: str) -> Tuple[bool, Optional[APIKey], Optional[str]]:
116
+ """
117
+ Validate an API key.
118
+
119
+ Returns:
120
+ Tuple of (is_valid, api_key_object, error_message)
121
+ """
122
+ if not api_key:
123
+ return False, None, "API key is required"
124
+
125
+ if not api_key.startswith(self.key_prefix):
126
+ return False, None, "Invalid API key format"
127
+
128
+ try:
129
+ # Get API key from database
130
+ key_obj = await self.db.get_api_key(api_key)
131
+
132
+ if not key_obj:
133
+ return False, None, "API key not found"
134
+
135
+ if not key_obj.is_active:
136
+ return False, None, "API key is inactive"
137
+
138
+ if key_obj.is_expired():
139
+ return False, None, "API key has expired"
140
+
141
+ # Update last used timestamp
142
+ key_obj.last_used_at = datetime.now(timezone.utc)
143
+ key_obj.usage_count += 1
144
+
145
+ try:
146
+ await self.db.update_api_key(key_obj)
147
+ except Exception as e:
148
+ logger.warning(f"Failed to update API key usage: {e}")
149
+
150
+ return True, key_obj, None
151
+
152
+ except Exception as e:
153
+ logger.error(f"Error validating API key: {e}")
154
+ return False, None, "Internal error during validation"
155
+
156
+ async def revoke_api_key(self, api_key: str) -> bool:
157
+ """Revoke an API key by marking it as inactive."""
158
+ try:
159
+ key_obj = await self.db.get_api_key(api_key)
160
+
161
+ if not key_obj:
162
+ return False
163
+
164
+ key_obj.is_active = False
165
+ key_obj.updated_at = datetime.now(timezone.utc)
166
+
167
+ await self.db.update_api_key(key_obj)
168
+ logger.info(f"Revoked API key: {key_obj.id}")
169
+ return True
170
+
171
+ except Exception as e:
172
+ logger.error(f"Error revoking API key: {e}")
173
+ return False
174
+
175
+ async def get_user_api_keys(self, user_id: str) -> list[APIKey]:
176
+ """Get all API keys for a user."""
177
+ try:
178
+ return await self.db.get_api_keys_by_user(user_id)
179
+ except Exception as e:
180
+ logger.error(f"Error getting user API keys: {e}")
181
+ return []
182
+
183
+ async def cleanup_expired_keys(self) -> int:
184
+ """Clean up expired API keys (mark as inactive)."""
185
+ # This would require a method to get all API keys, which we haven't implemented
186
+ # For now, we'll just return 0
187
+ # In a production system, you'd want to implement this properly
188
+ logger.info("Cleanup expired keys called (not implemented)")
189
+ return 0
@@ -32,43 +32,41 @@ def initialize_auth_system(app: FastAPI, auth_required: bool = True, rate_limit_
32
32
  """Initialize the authentication system."""
33
33
  global db_manager, api_key_manager, rate_limiter, auth_middleware
34
34
 
35
- if not auth_required:
36
- logger.info("Auth system is disabled (no-auth mode): skipping DB and API key manager initialization.")
37
- db_manager = None
38
- api_key_manager = None
39
- rate_limiter = None
40
- auth_middleware = None
41
- return
42
-
43
35
  try:
44
- # Initialize database manager
36
+ # Initialize database manager (always needed for request logging)
45
37
  mongo_url = os.getenv("MONGODB_URL")
46
38
  data_dir = os.getenv("WEBSCOUT_DATA_DIR", "data")
47
39
 
48
40
  db_manager = DatabaseManager(mongo_url, data_dir)
49
41
 
50
- # Initialize API key manager
51
- api_key_manager = APIKeyManager(db_manager)
52
-
53
- # Initialize rate limiter
54
- rate_limiter = RateLimiter(db_manager)
55
-
56
- # Initialize auth middleware with configuration
57
- auth_middleware = AuthMiddleware(
58
- api_key_manager,
59
- rate_limiter,
60
- auth_required=auth_required,
61
- rate_limit_enabled=rate_limit_enabled
62
- )
63
-
64
- # Add auth middleware to app
65
- app.middleware("http")(auth_middleware)
42
+ if not auth_required:
43
+ logger.info("Auth system is disabled (no-auth mode): initializing only database for request logging.")
44
+ api_key_manager = None
45
+ rate_limiter = None
46
+ auth_middleware = None
47
+ else:
48
+ # Initialize API key manager
49
+ api_key_manager = APIKeyManager(db_manager)
50
+
51
+ # Initialize rate limiter
52
+ rate_limiter = RateLimiter(db_manager)
53
+
54
+ # Initialize auth middleware with configuration
55
+ auth_middleware = AuthMiddleware(
56
+ api_key_manager,
57
+ rate_limiter,
58
+ auth_required=auth_required,
59
+ rate_limit_enabled=rate_limit_enabled
60
+ )
61
+
62
+ # Add auth middleware to app
63
+ app.middleware("http")(auth_middleware)
66
64
 
67
65
  # Add startup event to initialize database
68
66
  async def startup_event():
69
67
  if db_manager:
70
68
  await db_manager.initialize()
71
- logger.info("Authentication system initialized successfully")
69
+ logger.info("Database system initialized successfully")
72
70
  logger.info(f"Auth required: {auth_required}, Rate limiting: {rate_limit_enabled}")
73
71
 
74
72
  # Store startup function for later use
@@ -84,17 +82,4 @@ def initialize_auth_system(app: FastAPI, auth_required: bool = True, rate_limit_
84
82
 
85
83
  def get_auth_components():
86
84
  """Get the initialized authentication components."""
87
- if db_manager is None:
88
- return {
89
- "db_manager": None,
90
- "api_key_manager": None,
91
- "rate_limiter": None,
92
- "auth_middleware": None
93
- }
94
-
95
- return {
96
- "db_manager": db_manager,
97
- "api_key_manager": api_key_manager,
98
- "rate_limiter": rate_limiter,
99
- "auth_middleware": auth_middleware
100
- }
85
+ return api_key_manager, db_manager, rate_limiter
webscout/auth/config.py CHANGED
@@ -2,6 +2,7 @@
2
2
  Configuration management for the Webscout API server.
3
3
  """
4
4
 
5
+ import os
5
6
  from typing import List, Dict, Optional, Any
6
7
  from webscout.Litlogger import Logger, LogLevel, LogFormat, ConsoleHandler
7
8
  import sys
@@ -19,6 +20,42 @@ logger = Logger(
19
20
  )
20
21
 
21
22
 
23
+ def _get_supabase_url() -> Optional[str]:
24
+ """Get Supabase URL from environment variables or GitHub secrets."""
25
+ # Try environment variable first
26
+ url = os.getenv("SUPABASE_URL")
27
+ if url:
28
+ logger.info("📍 Using SUPABASE_URL from environment")
29
+ return url
30
+
31
+ # Try to get from GitHub secrets (if running in GitHub Actions)
32
+ github_url = os.getenv("GITHUB_SUPABASE_URL") # GitHub Actions secret
33
+ if github_url:
34
+ logger.info("📍 Using SUPABASE_URL from GitHub secrets")
35
+ return github_url
36
+
37
+ # Don't log error during import - only when actually needed
38
+ return None
39
+
40
+
41
+ def _get_supabase_anon_key() -> Optional[str]:
42
+ """Get Supabase anon key from environment variables or GitHub secrets."""
43
+ # Try environment variable first
44
+ key = os.getenv("SUPABASE_ANON_KEY")
45
+ if key:
46
+ logger.info("🔑 Using SUPABASE_ANON_KEY from environment")
47
+ return key
48
+
49
+ # Try to get from GitHub secrets (if running in GitHub Actions)
50
+ github_key = os.getenv("GITHUB_SUPABASE_ANON_KEY") # GitHub Actions secret
51
+ if github_key:
52
+ logger.info("🔑 Using SUPABASE_ANON_KEY from GitHub secrets")
53
+ return github_key
54
+
55
+ # Don't log error during import - only when actually needed
56
+ return None
57
+
58
+
22
59
  class ServerConfig:
23
60
  """Centralized configuration management for the API server."""
24
61
 
@@ -33,9 +70,33 @@ class ServerConfig:
33
70
  self.cors_origins: List[str] = ["*"]
34
71
  self.max_request_size: int = 10 * 1024 * 1024 # 10MB
35
72
  self.request_timeout: int = 300 # 5 minutes
36
- self.auth_required: bool = True # New: Enable/disable authentication
37
- self.rate_limit_enabled: bool = True # New: Enable/disable rate limiting
73
+ self.auth_required: bool = os.getenv("WEBSCOUT_AUTH_REQUIRED", "false").lower() == "true" # Default to no auth
74
+ self.rate_limit_enabled: bool = os.getenv("WEBSCOUT_RATE_LIMIT_ENABLED", "false").lower() == "true" # Default to no rate limit
38
75
  self.default_rate_limit: int = 60 # Default rate limit for no-auth mode
76
+ self.request_logging_enabled: bool = os.getenv("WEBSCOUT_REQUEST_LOGGING", "true").lower() == "true" # Enable request logging by default
77
+
78
+ # Database configuration - lazy initialization
79
+ self._supabase_url: Optional[str] = None
80
+ self._supabase_anon_key: Optional[str] = None
81
+ self._supabase_url_checked: bool = False
82
+ self._supabase_anon_key_checked: bool = False
83
+ self.mongodb_url: Optional[str] = os.getenv("MONGODB_URL")
84
+
85
+ @property
86
+ def supabase_url(self) -> Optional[str]:
87
+ """Get Supabase URL with lazy initialization."""
88
+ if not self._supabase_url_checked:
89
+ self._supabase_url = _get_supabase_url()
90
+ self._supabase_url_checked = True
91
+ return self._supabase_url
92
+
93
+ @property
94
+ def supabase_anon_key(self) -> Optional[str]:
95
+ """Get Supabase anon key with lazy initialization."""
96
+ if not self._supabase_anon_key_checked:
97
+ self._supabase_anon_key = _get_supabase_anon_key()
98
+ self._supabase_anon_key_checked = True
99
+ return self._supabase_anon_key
39
100
 
40
101
  def update(self, **kwargs) -> None:
41
102
  """Update configuration with provided values."""
@@ -62,9 +123,42 @@ class AppConfig:
62
123
  default_provider = "ChatGPT"
63
124
  default_tti_provider = "PollinationsAI" # Add default TTI provider
64
125
  base_url: Optional[str] = None
65
- auth_required: bool = True # New: Enable/disable authentication
66
- rate_limit_enabled: bool = True # New: Enable/disable rate limiting
126
+ auth_required: bool = os.getenv("WEBSCOUT_AUTH_REQUIRED", "false").lower() == "true" # Default to no auth
127
+ rate_limit_enabled: bool = os.getenv("WEBSCOUT_RATE_LIMIT_ENABLED", "false").lower() == "true" # Default to no rate limit
67
128
  default_rate_limit: int = 60 # Default rate limit for no-auth mode
129
+ request_logging_enabled: bool = os.getenv("WEBSCOUT_REQUEST_LOGGING", "true").lower() == "true" # Enable request logging by default
130
+
131
+ # Database configuration - lazy initialization
132
+ _supabase_url: Optional[str] = None
133
+ _supabase_anon_key: Optional[str] = None
134
+ _supabase_url_checked: bool = False
135
+ _supabase_anon_key_checked: bool = False
136
+ mongodb_url: Optional[str] = os.getenv("MONGODB_URL")
137
+
138
+ @classmethod
139
+ def get_supabase_url(cls) -> Optional[str]:
140
+ """Get Supabase URL with lazy initialization."""
141
+ if not cls._supabase_url_checked:
142
+ cls._supabase_url = _get_supabase_url()
143
+ cls._supabase_url_checked = True
144
+ return cls._supabase_url
145
+
146
+ @classmethod
147
+ def get_supabase_anon_key(cls) -> Optional[str]:
148
+ """Get Supabase anon key with lazy initialization."""
149
+ if not cls._supabase_anon_key_checked:
150
+ cls._supabase_anon_key = _get_supabase_anon_key()
151
+ cls._supabase_anon_key_checked = True
152
+ return cls._supabase_anon_key
153
+
154
+ # For backward compatibility, provide properties that call the methods
155
+ @property
156
+ def supabase_url(self) -> Optional[str]:
157
+ return self.__class__.get_supabase_url()
158
+
159
+ @property
160
+ def supabase_anon_key(self) -> Optional[str]:
161
+ return self.__class__.get_supabase_anon_key()
68
162
 
69
163
  @classmethod
70
164
  def set_config(cls, **data):
@@ -72,5 +166,10 @@ class AppConfig:
72
166
  for key, value in data.items():
73
167
  setattr(cls, key, value)
74
168
  # Sync with new config system
75
- from .server import config
76
- config.update(**data)
169
+ try:
170
+ from .server import get_config
171
+ config = get_config()
172
+ config.update(**data)
173
+ except ImportError:
174
+ # Handle case where server module is not available
175
+ pass