nya-proxy 0.3.6__tar.gz → 0.4.0__tar.gz

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.
Files changed (48) hide show
  1. {nya_proxy-0.3.6/nya_proxy.egg-info → nya_proxy-0.4.0}/PKG-INFO +26 -17
  2. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/README.md +25 -16
  3. nya_proxy-0.4.0/nya/_version.py +1 -0
  4. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/common/constants.py +0 -1
  5. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/core/control.py +1 -4
  6. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/core/handler.py +4 -4
  7. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/core/proxy.py +6 -9
  8. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/core/request.py +8 -18
  9. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/core/streaming.py +26 -9
  10. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/server/app.py +6 -31
  11. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/utils/header.py +0 -3
  12. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/utils/helper.py +5 -3
  13. {nya_proxy-0.3.6 → nya_proxy-0.4.0/nya_proxy.egg-info}/PKG-INFO +26 -17
  14. nya_proxy-0.4.0/nya_proxy.egg-info/top_level.txt +2 -0
  15. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/pyproject.toml +1 -1
  16. nya_proxy-0.3.6/nya/_version.py +0 -1
  17. nya_proxy-0.3.6/nya_proxy.egg-info/top_level.txt +0 -1
  18. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/LICENSE +0 -0
  19. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/__init__.py +0 -0
  20. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/common/__init__.py +0 -0
  21. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/common/exceptions.py +0 -0
  22. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/common/models.py +0 -0
  23. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/config/__init__.py +0 -0
  24. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/config/manager.py +0 -0
  25. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/config.yaml +0 -0
  26. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/core/__init__.py +0 -0
  27. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/core/queue.py +3 -3
  28. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/dashboard/__init__.py +0 -0
  29. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/dashboard/api.py +0 -0
  30. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/html/favicon.ico +0 -0
  31. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/html/index.html +0 -0
  32. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/html/login.html +0 -0
  33. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/html/static/css/styles.css +0 -0
  34. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/html/static/js/dashboard.js +0 -0
  35. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/html/static/logo.svg +0 -0
  36. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/schema.json +0 -0
  37. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/server/__init__.py +0 -0
  38. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/server/auth.py +0 -0
  39. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/services/__init__.py +0 -0
  40. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/services/lb.py +0 -0
  41. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/services/limit.py +0 -0
  42. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/services/metrics.py +0 -0
  43. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya/utils/__init__.py +0 -0
  44. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya_proxy.egg-info/SOURCES.txt +0 -0
  45. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya_proxy.egg-info/dependency_links.txt +0 -0
  46. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya_proxy.egg-info/entry_points.txt +0 -0
  47. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/nya_proxy.egg-info/requires.txt +0 -0
  48. {nya_proxy-0.3.6 → nya_proxy-0.4.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nya-proxy
3
- Version: 0.3.6
3
+ Version: 0.4.0
4
4
  Summary: A lightweight, flexible API proxy with dynamic token rotation, load balancing, and rate limiting capabilities.
5
5
  Author-email: "Nya Foundation Team (k3scat)" <k3scat@gmail.com>
6
6
  License-Expression: MIT
@@ -120,7 +120,7 @@ Pick your favorite platform and let's go!
120
120
  ### Local Deployment (For the DIY Enthusiasts!)
121
121
 
122
122
  #### Prerequisites
123
- - Python 3.11 or higher
123
+ - Python 3.10 or higher
124
124
  - Docker (optional, for containerized deployment)
125
125
 
126
126
  #### Installation
@@ -189,9 +189,10 @@ Configuration reference can be found under [Configs folder](configs/) folder
189
189
 
190
190
  ```yaml
191
191
  # Basic config.yaml example for OpenAI API Compatible Endpoints
192
+ # NyaProxy Configuration File
193
+ # This file contains server settings and API endpoint configurations
194
+
192
195
  server:
193
- host: 0.0.0.0
194
- port: 8080
195
196
  api_key:
196
197
  logging:
197
198
  enabled: true
@@ -202,23 +203,28 @@ server:
202
203
  address: socks5://username:password@proxy.example.com:1080
203
204
  dashboard:
204
205
  enabled: true
205
- queue:
206
- max_size: 200
207
- expiry_seconds: 300
208
206
  cors:
209
- allow_origins: ["*"] # Set to "*" to allow all origins, however, when allow_credentials is true, this must be set to a specific origin
207
+ # Allow all origins with "*", but specify exact origins when allow_credentials is true for security
208
+ allow_origins: ["*"]
210
209
  allow_credentials: true
211
210
  allow_methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
212
211
  allow_headers: ["*"]
213
212
 
214
- # Default settings for the all apis if not specified
213
+ # Default configuration applied to all API endpoints unless overridden
215
214
  default_settings:
216
215
  key_variable: keys
216
+ key_concurrency: true # Enable concurrent requests per API key for better performance
217
+ randomness: 0.0 # Random delay of (0.0-x)s to introduce variability in request timing and avoid detection
217
218
  load_balancing_strategy: round_robin
219
+ queue:
220
+ max_size: 200
221
+ expiry_seconds: 300
218
222
  rate_limit:
219
223
  enabled: true
220
- endpoint_rate_limit: 10/s # Default endpoint rate limit, can be overridden by each API
221
- key_rate_limit: 10/m # Default key rate limit, can be overridden by each API
224
+ endpoint_rate_limit: 10/s # Default endpoint rate limit - can be overridden per API
225
+ key_rate_limit: 10/m # Default key rate limit - can be overridden per API
226
+ ip_rate_limit: 1000/d # IP-based rate limit to protect against abuse and key redistribution
227
+ user_rate_limit: 1000/d # User-based rate limit per proxy API key defined in server section
222
228
  rate_limit_paths:
223
229
  - "*"
224
230
  retry:
@@ -248,11 +254,11 @@ default_settings:
248
254
  conditions:
249
255
  - field: "presence_penalty"
250
256
  operator: "exists"
251
-
252
257
  apis:
253
258
  gemini:
254
- # Any OpenAI-Compatible API
259
+ # OpenAI-compatible API endpoint
255
260
  name: Google Gemini API
261
+ # Supported endpoints:
256
262
  # Gemini: https://generativelanguage.googleapis.com/v1beta/openai
257
263
  # OpenAI: https://api.openai.com/v1
258
264
  # Anthropic: https://api.anthropic.com/v1
@@ -274,11 +280,11 @@ apis:
274
280
  load_balancing_strategy: least_requests
275
281
  rate_limit:
276
282
  enabled: true
277
- # For Gemini, the rate limits (gemini-2.5-pro-exp-03-25) for each key are 5 RPM and 25 RPD
278
- # Ideally, the endpoint rate limit should be n x Per-Key-RPD, where n is the number of keys
283
+ # For Gemini-2.5-pro-exp-03-25, rate limits per key are 5 RPM and 25 RPD
284
+ # Endpoint rate limit should be n × Per-Key-RPD, where n is the number of keys
279
285
  endpoint_rate_limit: 75/d
280
286
  key_rate_limit: 5/m
281
- # Rate limit paths are optional, but you can configure which paths to apply the rate limits to (regex supported), default is all paths "*"
287
+ # Paths to apply rate limits (regex supported) - defaults to all paths "*"
282
288
  rate_limit_paths:
283
289
  - "/chat/*"
284
290
  - "/images/*"
@@ -287,6 +293,7 @@ apis:
287
293
  name: Test API
288
294
  endpoint: http://127.0.0.1:8082
289
295
  key_variable: keys
296
+ randomness: 5
290
297
  headers:
291
298
  Authorization: 'Bearer ${{keys}}'
292
299
  User-Agent: ${{agents}}
@@ -303,7 +310,9 @@ apis:
303
310
  rate_limit:
304
311
  enabled: true
305
312
  endpoint_rate_limit: 20/m
306
- key_rate_limit: 1/10s
313
+ key_rate_limit: 5/m
314
+ ip_rate_limit: 1000/d
315
+ user_rate_limit: 1000/d
307
316
  rate_limit_paths:
308
317
  - "/v1/*"
309
318
 
@@ -78,7 +78,7 @@ Pick your favorite platform and let's go!
78
78
  ### Local Deployment (For the DIY Enthusiasts!)
79
79
 
80
80
  #### Prerequisites
81
- - Python 3.11 or higher
81
+ - Python 3.10 or higher
82
82
  - Docker (optional, for containerized deployment)
83
83
 
84
84
  #### Installation
@@ -147,9 +147,10 @@ Configuration reference can be found under [Configs folder](configs/) folder
147
147
 
148
148
  ```yaml
149
149
  # Basic config.yaml example for OpenAI API Compatible Endpoints
150
+ # NyaProxy Configuration File
151
+ # This file contains server settings and API endpoint configurations
152
+
150
153
  server:
151
- host: 0.0.0.0
152
- port: 8080
153
154
  api_key:
154
155
  logging:
155
156
  enabled: true
@@ -160,23 +161,28 @@ server:
160
161
  address: socks5://username:password@proxy.example.com:1080
161
162
  dashboard:
162
163
  enabled: true
163
- queue:
164
- max_size: 200
165
- expiry_seconds: 300
166
164
  cors:
167
- allow_origins: ["*"] # Set to "*" to allow all origins, however, when allow_credentials is true, this must be set to a specific origin
165
+ # Allow all origins with "*", but specify exact origins when allow_credentials is true for security
166
+ allow_origins: ["*"]
168
167
  allow_credentials: true
169
168
  allow_methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
170
169
  allow_headers: ["*"]
171
170
 
172
- # Default settings for the all apis if not specified
171
+ # Default configuration applied to all API endpoints unless overridden
173
172
  default_settings:
174
173
  key_variable: keys
174
+ key_concurrency: true # Enable concurrent requests per API key for better performance
175
+ randomness: 0.0 # Random delay of (0.0-x)s to introduce variability in request timing and avoid detection
175
176
  load_balancing_strategy: round_robin
177
+ queue:
178
+ max_size: 200
179
+ expiry_seconds: 300
176
180
  rate_limit:
177
181
  enabled: true
178
- endpoint_rate_limit: 10/s # Default endpoint rate limit, can be overridden by each API
179
- key_rate_limit: 10/m # Default key rate limit, can be overridden by each API
182
+ endpoint_rate_limit: 10/s # Default endpoint rate limit - can be overridden per API
183
+ key_rate_limit: 10/m # Default key rate limit - can be overridden per API
184
+ ip_rate_limit: 1000/d # IP-based rate limit to protect against abuse and key redistribution
185
+ user_rate_limit: 1000/d # User-based rate limit per proxy API key defined in server section
180
186
  rate_limit_paths:
181
187
  - "*"
182
188
  retry:
@@ -206,11 +212,11 @@ default_settings:
206
212
  conditions:
207
213
  - field: "presence_penalty"
208
214
  operator: "exists"
209
-
210
215
  apis:
211
216
  gemini:
212
- # Any OpenAI-Compatible API
217
+ # OpenAI-compatible API endpoint
213
218
  name: Google Gemini API
219
+ # Supported endpoints:
214
220
  # Gemini: https://generativelanguage.googleapis.com/v1beta/openai
215
221
  # OpenAI: https://api.openai.com/v1
216
222
  # Anthropic: https://api.anthropic.com/v1
@@ -232,11 +238,11 @@ apis:
232
238
  load_balancing_strategy: least_requests
233
239
  rate_limit:
234
240
  enabled: true
235
- # For Gemini, the rate limits (gemini-2.5-pro-exp-03-25) for each key are 5 RPM and 25 RPD
236
- # Ideally, the endpoint rate limit should be n x Per-Key-RPD, where n is the number of keys
241
+ # For Gemini-2.5-pro-exp-03-25, rate limits per key are 5 RPM and 25 RPD
242
+ # Endpoint rate limit should be n × Per-Key-RPD, where n is the number of keys
237
243
  endpoint_rate_limit: 75/d
238
244
  key_rate_limit: 5/m
239
- # Rate limit paths are optional, but you can configure which paths to apply the rate limits to (regex supported), default is all paths "*"
245
+ # Paths to apply rate limits (regex supported) - defaults to all paths "*"
240
246
  rate_limit_paths:
241
247
  - "/chat/*"
242
248
  - "/images/*"
@@ -245,6 +251,7 @@ apis:
245
251
  name: Test API
246
252
  endpoint: http://127.0.0.1:8082
247
253
  key_variable: keys
254
+ randomness: 5
248
255
  headers:
249
256
  Authorization: 'Bearer ${{keys}}'
250
257
  User-Agent: ${{agents}}
@@ -261,7 +268,9 @@ apis:
261
268
  rate_limit:
262
269
  enabled: true
263
270
  endpoint_rate_limit: 20/m
264
- key_rate_limit: 1/10s
271
+ key_rate_limit: 5/m
272
+ ip_rate_limit: 1000/d
273
+ user_rate_limit: 1000/d
265
274
  rate_limit_paths:
266
275
  - "/v1/*"
267
276
 
@@ -0,0 +1 @@
1
+ __version__ = "0.4.0"
@@ -19,7 +19,6 @@ API_PATH_PREFIX = "/api/"
19
19
  EXCLUDED_REQUEST_HEADERS = {
20
20
  "content-length",
21
21
  "connection",
22
- "transfer-encoding",
23
22
  "upgrade-insecure-requests",
24
23
  "proxy-connection",
25
24
  "x-forwarded-for",
@@ -3,15 +3,12 @@ Simplified key manager that focuses on key availability and rate limiting.
3
3
  """
4
4
 
5
5
  import asyncio
6
- import random
7
- from loguru import logger
8
6
  from typing import Dict, Optional, Tuple, Union
9
7
 
10
8
  from ..common.exceptions import APIKeyNotConfiguredError
11
-
9
+ from ..config.manager import ConfigManager
12
10
  from ..services.lb import LoadBalancer
13
11
  from ..services.limit import RateLimiter
14
- from ..config.manager import ConfigManager
15
12
 
16
13
 
17
14
  class TrafficManager:
@@ -99,10 +99,10 @@ class RequestHandler:
99
99
  return api_name, trail_path
100
100
 
101
101
  # Check for aliases in each API config
102
- for api_name in apis_config.keys():
103
- aliases = self.config.get_api_aliases(api_name)
104
- if aliases and parts[0] in aliases:
105
- return api_name, trail_path
102
+ for endpoint in apis_config.keys():
103
+ aliases = self.config.get_api_aliases(endpoint)
104
+ if aliases and api_name in aliases:
105
+ return endpoint, trail_path
106
106
 
107
107
  # No match found
108
108
  logger.warning(f"No API configuration found for endpoint: {api_name}")
@@ -3,8 +3,8 @@ The NyaProxyCore class handles the main proxy logic with queue-first architectur
3
3
  """
4
4
 
5
5
  import asyncio
6
- import traceback
7
6
  import random
7
+ import traceback
8
8
  from typing import TYPE_CHECKING, Optional, Union
9
9
 
10
10
  from loguru import logger
@@ -13,8 +13,8 @@ from starlette.responses import JSONResponse, Response, StreamingResponse
13
13
  from ..common.exceptions import (
14
14
  APIKeyNotConfiguredError,
15
15
  QueueFullError,
16
- ReachedMaxRetriesError,
17
16
  ReachedDailyQuotaError,
17
+ ReachedMaxRetriesError,
18
18
  )
19
19
  from ..common.models import ProxyRequest
20
20
  from ..config.manager import ConfigManager
@@ -84,12 +84,11 @@ class NyaProxyCore:
84
84
  future = await self.request_queue.enqueue_request(request)
85
85
  timeout = self.config.get_api_default_timeout(request.api_name)
86
86
  return await asyncio.wait_for(future, timeout=timeout)
87
- except ReachedDailyQuotaError as e:
88
- return self._error_response(e.message, status_code=429)
87
+
88
+ except (ReachedMaxRetriesError, ReachedDailyQuotaError) as e:
89
+ return self._error_response(e.message, 429)
89
90
  except APIKeyNotConfiguredError as e:
90
91
  return self._error_response(e.message, 500)
91
- except ReachedMaxRetriesError as e:
92
- return self._error_response(e.message, 429)
93
92
  except QueueFullError as e:
94
93
  return self._error_response(e.message, 503)
95
94
  except asyncio.TimeoutError:
@@ -100,9 +99,7 @@ class NyaProxyCore:
100
99
  )
101
100
  return self._error_response(str(e), 500)
102
101
 
103
- async def _process_queued_request(
104
- self, request: ProxyRequest
105
- ) -> Union[Response, JSONResponse, StreamingResponse]:
102
+ async def _process_queued_request(self, request: ProxyRequest) -> Response:
106
103
  """
107
104
  Process a request from the queue.
108
105
  """
@@ -89,9 +89,10 @@ class RequestExecutor:
89
89
 
90
90
  # Log request/response details on error response
91
91
  if response.status_code >= 400:
92
- logger.debug(f"[Request] Headers: {json_safe_dumps(request.headers)}")
93
92
  logger.debug(f"[Request] Content: {json_safe_dumps(request.content)}")
94
- logger.debug(f"[Response] Headers: {json_safe_dumps(response.headers)}")
93
+
94
+ logger.debug(f"[Request] Headers: {json_safe_dumps(request.headers)}")
95
+ logger.debug(f"[Response] Headers: {json_safe_dumps(response.headers)}")
95
96
 
96
97
  logger.debug(
97
98
  f"[Response] URL: {request.url}, Status: {response.status_code} "
@@ -168,7 +169,6 @@ class RequestExecutor:
168
169
  """
169
170
  Create the response to send back to client.
170
171
  """
171
- # Check if it's a streaming response
172
172
  try:
173
173
  content_type = response.headers.get("content-type", "")
174
174
  media_type = (
@@ -176,25 +176,15 @@ class RequestExecutor:
176
176
  if content_type
177
177
  else "application/json"
178
178
  )
179
- # Regular response
180
- content_chunks = []
181
- async for chunk in response.aiter_bytes():
182
- content_chunks.append(chunk)
183
- content = b"".join(content_chunks)
184
-
185
- content_encoding = response.headers.get("content-encoding", "").lower()
186
- content = decode_content(content, content_encoding)
187
-
188
- # Remove content-encoding header if present
189
- for header in ["transfer-encoding", "content-length", "content-encoding"]:
190
- if header in response.headers:
191
- del response.headers[header]
192
179
 
193
180
  logger.debug(
194
181
  f"Handling normal response: {response.status_code} {media_type}"
195
182
  )
196
- if "application/json" in response.headers.get("content-type", "").lower():
197
- logger.debug(f"[Response] Content: {json_safe_dumps(content)}")
183
+
184
+ # Read raw bytes without any decoding/processing
185
+ content = b""
186
+ async for chunk in response.aiter_raw():
187
+ content += chunk
198
188
 
199
189
  return Response(
200
190
  content=content,
@@ -42,7 +42,7 @@ class StreamingHandler:
42
42
 
43
43
  async def event_generator():
44
44
  try:
45
- async for chunk in response.aiter_bytes():
45
+ async for chunk in response.aiter_raw():
46
46
  if chunk:
47
47
  logger.debug(f"Forwarding stream chunk: {len(chunk)} bytes")
48
48
  yield chunk
@@ -74,15 +74,18 @@ class StreamingHandler:
74
74
  Processed headers for streaming
75
75
  """
76
76
 
77
- for header in ["content-encoding", "content-length", "accept-encoding"]:
78
- if header in headers:
79
- del headers[header]
77
+ # Remove content-length as it's not applicable for streaming
78
+ if "content-length" in headers:
79
+ del headers["content-length"]
80
+
81
+ # Remove date since fastapi will set it automatically
82
+ if "date" in headers:
83
+ del headers["date"]
80
84
 
81
- # Set SSE-specific headers according to standards
82
- headers["cache-control"] = "no-cache, no-transform"
83
85
  headers["connection"] = "keep-alive"
84
- headers["x-accel-buffering"] = "no"
86
+ headers["cache-control"] = "no-cache"
85
87
  headers["transfer-encoding"] = "chunked"
88
+ headers["x-accel-buffering"] = "no"
86
89
 
87
90
  @staticmethod
88
91
  def detect_streaming_content(headers: httpx.Headers) -> bool:
@@ -102,16 +105,24 @@ class StreamingHandler:
102
105
  no_length = cl is None
103
106
  supports_range = "bytes" in ar
104
107
 
108
+ exceptions = ("application/json",)
109
+
105
110
  sse_cts = {
106
111
  "text/event-stream",
107
112
  "application/x-ndjson",
108
113
  "multipart/x-mixed-replace",
109
114
  }
110
115
 
111
- media_prefixes = ("video/", "audio/")
116
+ media_prefixes = (
117
+ "video/",
118
+ "audio/",
119
+ )
112
120
  other_media_cts = {
113
121
  "application/vnd.apple.mpegurl", # .m3u8 (HLS)
114
122
  "application/dash+xml", # .mpd (DASH)
123
+ "application/zip",
124
+ "application/gzip",
125
+ "application/pdf",
115
126
  }
116
127
 
117
128
  is_sse = ct in sse_cts
@@ -119,10 +130,16 @@ class StreamingHandler:
119
130
  ct in other_media_cts
120
131
  )
121
132
 
133
+ if ct in exceptions:
134
+ return False
135
+
136
+ if no_length or uses_chunked:
137
+ return True
138
+
122
139
  if uses_chunked and is_sse:
123
140
  return True
124
141
 
125
- if is_media and (uses_chunked or supports_range or no_length):
142
+ if is_media and (uses_chunked or supports_range):
126
143
  return True
127
144
 
128
145
  return False
@@ -6,13 +6,11 @@ NyaProxy - A simple low-level API proxy with dynamic token rotation.
6
6
 
7
7
  import argparse
8
8
  import contextlib
9
- import logging
10
9
  import os
11
10
  import sys
12
- import traceback
13
11
 
14
12
  import uvicorn
15
- from fastapi import FastAPI, Request, Response
13
+ from fastapi import FastAPI, Request
16
14
  from loguru import logger
17
15
  from starlette.middleware.base import BaseHTTPMiddleware
18
16
  from starlette.middleware.cors import CORSMiddleware
@@ -119,6 +117,10 @@ class NyaProxyApp:
119
117
  allow_headers = self.config.get_cors_allow_headers()
120
118
  allow_credentials = self.config.get_cors_allow_credentials()
121
119
 
120
+ logger.info(
121
+ f"CORS settings: origins={allow_origins}, methods={allow_methods}, headers={allow_headers}, credentials={allow_credentials}"
122
+ )
123
+
122
124
  # Add CORS middleware
123
125
  app.add_middleware(
124
126
  CORSMiddleware,
@@ -252,11 +254,6 @@ class NyaProxyApp:
252
254
  "Config manager must be initialized before proxy handler"
253
255
  )
254
256
 
255
- if not logger:
256
- logging.warning(
257
- "Logger not initialized, proxy handler will use default logging"
258
- )
259
-
260
257
  # Use the service factory to create the core
261
258
  core = NyaProxyCore(
262
259
  config=self.config,
@@ -373,29 +370,6 @@ class NyaProxyApp:
373
370
  async def proxy_head_request(request: Request):
374
371
  return await self.generic_proxy_request(request)
375
372
 
376
- @self.app.options("/api/{path:path}", name="proxy_options")
377
- async def proxy_options_request(request: Request):
378
- # hijack the options request to handle CORS preflight requests
379
- origin = request.headers.get("origin", "*")
380
- acr_headers = request.headers.get(
381
- "access-control-request-headers", "Content-Type, Authorization"
382
- )
383
-
384
- logger.debug(
385
- f"Handling CORS preflight request from {origin} with headers {request.headers}"
386
- )
387
-
388
- return Response(
389
- content="",
390
- status_code=204,
391
- headers={
392
- "Access-Control-Allow-Origin": origin,
393
- "Access-Control-Allow-Headers": acr_headers,
394
- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS",
395
- "Access-Control-Max-Age": "86400",
396
- },
397
- )
398
-
399
373
  async def shutdown(self):
400
374
  """
401
375
  Clean up resources on shutdown.
@@ -491,6 +465,7 @@ def main():
491
465
  schema_path = None
492
466
 
493
467
  import importlib.resources as pkg_resources
468
+
494
469
  import nya
495
470
 
496
471
  with pkg_resources.path(nya, DEFAULT_SCHEMA_NAME) as default_schema:
@@ -127,9 +127,6 @@ class HeaderUtils:
127
127
  # Set header with original casing preserved
128
128
  final_headers[header_name] = header_value
129
129
 
130
- # patch accept-encoding header to avoid issues with httpx
131
- final_headers["accept-encoding"] = "identity"
132
-
133
130
  return final_headers
134
131
 
135
132
  @staticmethod
@@ -13,6 +13,7 @@ import brotli
13
13
  import jmespath
14
14
  import orjson # Faster JSON library
15
15
  from jmespath.exceptions import JMESPathError
16
+ from loguru import logger
16
17
 
17
18
  __all__ = [
18
19
  "mask_secret",
@@ -227,9 +228,10 @@ def apply_body_substitutions(
227
228
  # If body is a string, parse it to a dict
228
229
  if isinstance(body, str) or isinstance(body, bytes):
229
230
  try:
230
- body = json.loads(body)
231
- except json.JSONDecodeError:
231
+ body = orjson.loads(body)
232
+ except orjson.JSONDecodeError:
232
233
  # If the body isn't valid JSON, return it unchanged
234
+ logger.warning("Failed to decode body as JSON, returning unchanged.")
233
235
  return body
234
236
 
235
237
  # If no rules or body isn't a dict/list, return unchanged
@@ -237,7 +239,7 @@ def apply_body_substitutions(
237
239
  return body
238
240
 
239
241
  # Make a deep copy of the body to avoid unexpected side effects
240
- result = orjson.loads(orjson.dumps(body))
242
+ result = body
241
243
 
242
244
  # Apply each rule in sequence
243
245
  for rule in rules:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nya-proxy
3
- Version: 0.3.6
3
+ Version: 0.4.0
4
4
  Summary: A lightweight, flexible API proxy with dynamic token rotation, load balancing, and rate limiting capabilities.
5
5
  Author-email: "Nya Foundation Team (k3scat)" <k3scat@gmail.com>
6
6
  License-Expression: MIT
@@ -120,7 +120,7 @@ Pick your favorite platform and let's go!
120
120
  ### Local Deployment (For the DIY Enthusiasts!)
121
121
 
122
122
  #### Prerequisites
123
- - Python 3.11 or higher
123
+ - Python 3.10 or higher
124
124
  - Docker (optional, for containerized deployment)
125
125
 
126
126
  #### Installation
@@ -189,9 +189,10 @@ Configuration reference can be found under [Configs folder](configs/) folder
189
189
 
190
190
  ```yaml
191
191
  # Basic config.yaml example for OpenAI API Compatible Endpoints
192
+ # NyaProxy Configuration File
193
+ # This file contains server settings and API endpoint configurations
194
+
192
195
  server:
193
- host: 0.0.0.0
194
- port: 8080
195
196
  api_key:
196
197
  logging:
197
198
  enabled: true
@@ -202,23 +203,28 @@ server:
202
203
  address: socks5://username:password@proxy.example.com:1080
203
204
  dashboard:
204
205
  enabled: true
205
- queue:
206
- max_size: 200
207
- expiry_seconds: 300
208
206
  cors:
209
- allow_origins: ["*"] # Set to "*" to allow all origins, however, when allow_credentials is true, this must be set to a specific origin
207
+ # Allow all origins with "*", but specify exact origins when allow_credentials is true for security
208
+ allow_origins: ["*"]
210
209
  allow_credentials: true
211
210
  allow_methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
212
211
  allow_headers: ["*"]
213
212
 
214
- # Default settings for the all apis if not specified
213
+ # Default configuration applied to all API endpoints unless overridden
215
214
  default_settings:
216
215
  key_variable: keys
216
+ key_concurrency: true # Enable concurrent requests per API key for better performance
217
+ randomness: 0.0 # Random delay of (0.0-x)s to introduce variability in request timing and avoid detection
217
218
  load_balancing_strategy: round_robin
219
+ queue:
220
+ max_size: 200
221
+ expiry_seconds: 300
218
222
  rate_limit:
219
223
  enabled: true
220
- endpoint_rate_limit: 10/s # Default endpoint rate limit, can be overridden by each API
221
- key_rate_limit: 10/m # Default key rate limit, can be overridden by each API
224
+ endpoint_rate_limit: 10/s # Default endpoint rate limit - can be overridden per API
225
+ key_rate_limit: 10/m # Default key rate limit - can be overridden per API
226
+ ip_rate_limit: 1000/d # IP-based rate limit to protect against abuse and key redistribution
227
+ user_rate_limit: 1000/d # User-based rate limit per proxy API key defined in server section
222
228
  rate_limit_paths:
223
229
  - "*"
224
230
  retry:
@@ -248,11 +254,11 @@ default_settings:
248
254
  conditions:
249
255
  - field: "presence_penalty"
250
256
  operator: "exists"
251
-
252
257
  apis:
253
258
  gemini:
254
- # Any OpenAI-Compatible API
259
+ # OpenAI-compatible API endpoint
255
260
  name: Google Gemini API
261
+ # Supported endpoints:
256
262
  # Gemini: https://generativelanguage.googleapis.com/v1beta/openai
257
263
  # OpenAI: https://api.openai.com/v1
258
264
  # Anthropic: https://api.anthropic.com/v1
@@ -274,11 +280,11 @@ apis:
274
280
  load_balancing_strategy: least_requests
275
281
  rate_limit:
276
282
  enabled: true
277
- # For Gemini, the rate limits (gemini-2.5-pro-exp-03-25) for each key are 5 RPM and 25 RPD
278
- # Ideally, the endpoint rate limit should be n x Per-Key-RPD, where n is the number of keys
283
+ # For Gemini-2.5-pro-exp-03-25, rate limits per key are 5 RPM and 25 RPD
284
+ # Endpoint rate limit should be n × Per-Key-RPD, where n is the number of keys
279
285
  endpoint_rate_limit: 75/d
280
286
  key_rate_limit: 5/m
281
- # Rate limit paths are optional, but you can configure which paths to apply the rate limits to (regex supported), default is all paths "*"
287
+ # Paths to apply rate limits (regex supported) - defaults to all paths "*"
282
288
  rate_limit_paths:
283
289
  - "/chat/*"
284
290
  - "/images/*"
@@ -287,6 +293,7 @@ apis:
287
293
  name: Test API
288
294
  endpoint: http://127.0.0.1:8082
289
295
  key_variable: keys
296
+ randomness: 5
290
297
  headers:
291
298
  Authorization: 'Bearer ${{keys}}'
292
299
  User-Agent: ${{agents}}
@@ -303,7 +310,9 @@ apis:
303
310
  rate_limit:
304
311
  enabled: true
305
312
  endpoint_rate_limit: 20/m
306
- key_rate_limit: 1/10s
313
+ key_rate_limit: 5/m
314
+ ip_rate_limit: 1000/d
315
+ user_rate_limit: 1000/d
307
316
  rate_limit_paths:
308
317
  - "/v1/*"
309
318
 
@@ -0,0 +1,2 @@
1
+ nya
2
+ nya-app
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "nya-proxy"
7
- version = "0.3.6"
7
+ version = "0.4.0"
8
8
  description = "A lightweight, flexible API proxy with dynamic token rotation, load balancing, and rate limiting capabilities."
9
9
  readme = "README.md"
10
10
  authors = [
@@ -1 +0,0 @@
1
- __version__ = "0.3.6"
@@ -1 +0,0 @@
1
- nya
File without changes
File without changes
File without changes
@@ -3,8 +3,8 @@ Simple priority queue for handling requests with built-in retry priority.
3
3
  """
4
4
 
5
5
  import asyncio
6
- import time
7
6
  import random
7
+ import time
8
8
  import traceback
9
9
  from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional, Tuple
10
10
 
@@ -12,9 +12,9 @@ from loguru import logger
12
12
 
13
13
  from ..common.exceptions import (
14
14
  QueueFullError,
15
+ ReachedDailyQuotaError,
15
16
  ReachedMaxRetriesError,
16
17
  RequestExpiredError,
17
- ReachedDailyQuotaError,
18
18
  )
19
19
  from ..common.models import ProxyRequest
20
20
 
@@ -22,8 +22,8 @@ if TYPE_CHECKING:
22
22
  from starlette.responses import Response
23
23
 
24
24
  from ..config import ConfigManager
25
- from .control import TrafficManager
26
25
  from ..services.metrics import MetricsCollector
26
+ from .control import TrafficManager
27
27
 
28
28
 
29
29
  class RequestQueue:
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes