返回提交历史
Modified
g4f/Provider/needs_auth/Azure.py
+18
-3
Modified
g4f/api/__init__.py
+26
-4
Modified
g4f/cli/client.py
+2
-5
Modified
g4f/client/stubs.py
+1
-1
Modified
g4f/gui/server/backend_api.py
+9
-14
Added
g4f/gui/server/crypto.py
+71
-0
XFEstudio/gpt4free
Add custom api_keys
9655954a
代码差异
6 个文件
+127
-27
@@ -1,19 +1,30 @@
1
1
from __future__ import annotations
2
2
3
3
import os
4
import json
4
5
5
6
from ...typing import Messages, AsyncResult
6
7
from ..template import OpenaiTemplate
7
8
8
9
class Azure(OpenaiTemplate):
10
api_base = "https://host.g4f.dev/api/Azure"
9
11
working = True
10
12
needs_auth = True
11
13
login_url = "https://ai.azure.com"
14
routes: dict[str, str] = {}
12
15
13
16
@classmethod
14
17
def get_models(cls, **kwargs) -> list[str]:
15
cls.default_model = os.environ.get("AZURE_DEFAULT_MODEL", cls.default_model)
16
return [cls.default_model]
18
routes = os.environ.get("AZURE_ROUTES")
19
if routes:
20
try:
21
routes = json.loads(routes)
22
except json.JSONDecodeError:
23
raise ValueError(f"Invalid AZURE_ROUTES environment variable format: {routes}")
24
cls.routes = routes
25
if cls.routes:
26
return list(cls.routes.keys())
27
return super().get_models(**kwargs)
17
28
18
29
@classmethod
19
30
async def create_async_generator(
@@ -31,7 +42,11 @@ class Azure(OpenaiTemplate):
31
42
if not api_endpoint:
32
43
api_endpoint = os.environ.get("AZURE_API_ENDPOINT")
33
44
if not api_endpoint:
34
raise ValueError("API endpoint is required for Azure provider")
45
if not cls.routes:
46
cls.get_models()
47
api_endpoint = cls.routes.get(model)
48
if cls.routes and not api_endpoint:
49
raise ValueError(f"No API endpoint found for model: {model}")
35
50
async for chunk in super().create_async_generator(
36
51
model=model,
37
52
messages=messages,
@@ -7,6 +7,7 @@ import secrets
7
7
import os
8
8
import re
9
9
import shutil
10
import time
10
11
from email.utils import formatdate
11
12
import os.path
12
13
import hashlib
@@ -80,6 +81,12 @@ from .stubs import (
80
81
)
81
82
from g4f import debug
82
83
84
try:
85
from g4f.gui.server.crypto import create_or_read_keys, decrypt_data
86
has_crypto = True
87
except ImportError:
88
has_crypto = False
89
83
90
logger = logging.getLogger(__name__)
84
91
85
92
DEFAULT_PORT = 1337
@@ -208,6 +215,8 @@ class Api:
208
215
def register_authorization(self):
209
216
if AppConfig.g4f_api_key:
210
217
print(f"Register authentication key: {''.join(['*' for _ in range(len(AppConfig.g4f_api_key))])}")
218
if has_crypto:
219
private_key, _ = create_or_read_keys()
211
220
@self.app.middleware("http")
212
221
async def authorization(request: Request, call_next):
213
222
if AppConfig.g4f_api_key is not None or AppConfig.demo:
@@ -217,23 +226,36 @@ class Api:
217
226
user_g4f_api_key = await self.security(request)
218
227
if hasattr(user_g4f_api_key, "credentials"):
219
228
user_g4f_api_key = user_g4f_api_key.credentials
229
user = None
230
if AppConfig.g4f_api_key is None or not secrets.compare_digest(AppConfig.g4f_api_key, user_g4f_api_key):
231
if has_crypto and user_g4f_api_key:
232
try:
233
expires, user = decrypt_data(private_key, user_g4f_api_key).split(":", 1)
234
expires = int(expires) - int(time.time())
235
debug.log(f"User: '{user}' G4F API key expires in {expires} seconds")
236
except Exception as e:
237
return ErrorResponse.from_message(f"Invalid G4F API key: {e}", HTTP_401_UNAUTHORIZED)
238
if expires < 0:
239
return ErrorResponse.from_message("G4F API key expired", HTTP_401_UNAUTHORIZED)
240
else:
241
user = "admin"
220
242
path = request.url.path
221
243
if path.startswith("/v1") or path.startswith("/api/") or (AppConfig.demo and path == '/backend-api/v2/upload_cookies'):
222
244
if user_g4f_api_key is None:
223
245
return ErrorResponse.from_message("G4F API key required", HTTP_401_UNAUTHORIZED)
224
if AppConfig.g4f_api_key is None or not secrets.compare_digest(AppConfig.g4f_api_key, user_g4f_api_key):
246
if AppConfig.g4f_api_key is None and user is None:
225
247
return ErrorResponse.from_message("Invalid G4F API key", HTTP_403_FORBIDDEN)
226
248
elif not AppConfig.demo and not path.startswith("/images/") and not path.startswith("/media/"):
227
249
if user_g4f_api_key is not None:
228
if not secrets.compare_digest(AppConfig.g4f_api_key, user_g4f_api_key):
250
if user is None:
229
251
return ErrorResponse.from_message("Invalid G4F API key", HTTP_403_FORBIDDEN)
230
252
elif path.startswith("/backend-api/") or path.startswith("/chat/") and path != "/chat/":
231
253
try:
232
username = await self.get_username(request)
254
user = await self.get_username(request)
233
255
except HTTPException as e:
234
256
return ErrorResponse.from_message(e.detail, e.status_code, e.headers)
235
257
response = await call_next(request)
236
response.headers["x-user"] = username
258
response.headers["x-user"] = user
237
259
return response
238
260
return await call_next(request)
239
261
@@ -121,10 +121,7 @@ async def stream_response(
121
121
if is_content(token):
122
122
response_content.append(token)
123
123
try:
124
for byte in str(token).encode('utf-8'):
125
sys.stdout.buffer.write(bytes([byte]))
126
sys.stdout.buffer.flush()
127
await asyncio.sleep(0.01)
124
print(token, end="", flush=True)
128
125
except (IOError, BrokenPipeError) as e:
129
126
print(f"\nError writing to stdout: {e}", file=sys.stderr)
130
127
break
@@ -227,7 +224,7 @@ def get_parser():
227
224
help="Clear conversation history before starting"
228
225
)
229
226
parser.add_argument(
230
'--no-config',
227
'-N', '--no-config',
231
228
action='store_true',
232
229
help="Do not load configuration from conversation file"
233
230
)
@@ -156,7 +156,7 @@ class ChatCompletionMessage(BaseModel):
156
156
with open(filepath, "wb") as f:
157
157
f.write(extract_data_uri(self.content))
158
158
return
159
content = filter_markdown(self.content, allowed_types)
159
content = filter_markdown(self.content, allowed_types, self.content if not allowed_types else None)
160
160
if content is not None:
161
161
with open(filepath, "w") as f:
162
162
f.write(content)
@@ -9,7 +9,7 @@ import asyncio
9
9
import shutil
10
10
import random
11
11
import datetime
12
import base64
12
from hashlib import sha256
13
13
from urllib.parse import quote_plus
14
14
from flask import Flask, Response, redirect, request, jsonify, send_from_directory
15
15
from werkzeug.exceptions import NotFound
@@ -29,8 +29,7 @@ try:
29
29
except ImportError as e:
30
30
has_markitdown = False
31
31
try:
32
from cryptography.hazmat.primitives import serialization
33
from cryptography.hazmat.primitives.asymmetric import padding, rsa
32
from .crypto import rsa, serialization, create_or_read_keys, decrypt_data, encrypt_data
34
33
has_crypto = True
35
34
except ImportError:
36
35
has_crypto = False
@@ -80,19 +79,13 @@ class Backend_Api(Api):
80
79
self.chat_cache = {}
81
80
82
81
if has_crypto:
83
private_key_obj = rsa.generate_private_key(public_exponent=65537, key_size=2048)
82
private_key_obj = rsa.generate_private_key(public_exponent=65537, key_size=4096)
84
83
public_key_obj = private_key_obj.public_key()
85
84
public_key_pem = public_key_obj.public_bytes(
86
85
encoding=serialization.Encoding.PEM,
87
86
format=serialization.PublicFormat.SubjectPublicKeyInfo
88
87
)
89
90
def decrypt_data(encrypted_data: str) -> str:
91
decrypted = private_key_obj.decrypt(
92
base64.b64decode(encrypted_data),
93
padding.PKCS1v15()
94
)
95
return decrypted.decode()
88
sub_private_key, sub_public_key = create_or_read_keys()
96
89
97
90
def validate_secret(secret: str) -> bool:
98
91
"""
@@ -105,8 +98,9 @@ class Backend_Api(Api):
105
98
bool: True if the secret is valid, False otherwise.
106
99
"""
107
100
try:
108
decrypted_secret = base64.b64decode(decrypt_data(secret).encode()).decode()
109
return int(decrypted_secret) >= time.time() - 3
101
decrypted_secret = decrypt_data(sub_private_key, decrypt_data(private_key_obj, secret))
102
timediff = time.time() - int(decrypted_secret)
103
return timediff <= 3 and timediff >= 0
110
104
except Exception as e:
111
105
logger.error(f"Secret validation failed: {e}")
112
106
return False
@@ -116,7 +110,7 @@ class Backend_Api(Api):
116
110
# Send the public key to the client for encryption
117
111
return jsonify({
118
112
"public_key": public_key_pem.decode(),
119
"data": base64.b64encode(str(int(time.time())).encode()).decode()
113
"data": encrypt_data(sub_public_key, str(int(time.time())))
120
114
})
121
115
122
116
@app.route('/backend-api/v2/models', methods=['GET'])
@@ -192,6 +186,7 @@ class Backend_Api(Api):
192
186
json_data["provider"] = models.HuggingFace
193
187
if app.demo:
194
188
ip = request.headers.get("X-Forwarded-For", "")
189
ip = sha256(ip.encode()).hexdigest()[:4] if ip else ""
195
190
user = request.headers.get("Cf-Ipcountry", "")
196
191
json_data["user"] = request.headers.get("x_user", f"{user}:{ip}")
197
192
json_data["referer"] = request.headers.get("referer", "")
@@ -0,0 +1,71 @@
1
from __future__ import annotations
2
3
import os
4
import base64
5
6
from cryptography.hazmat.primitives import serialization
7
from cryptography.hazmat.primitives.asymmetric import padding, rsa
8
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey, RSAPrivateKey
9
10
from ...cookies import get_cookies_dir
11
12
def create_or_read_keys() -> tuple[RSAPrivateKey, RSAPublicKey]:
13
private_key_file = os.path.join(get_cookies_dir(), "private_key.pem")
14
public_key_file = os.path.join(get_cookies_dir(), "public_key.pem")
15
16
if os.path.isfile(private_key_file) and os.path.isfile(public_key_file):
17
# Read private key
18
with open(private_key_file, 'rb') as f:
19
private_key_pem = f.read()
20
private_key = serialization.load_pem_private_key(
21
private_key_pem,
22
password=None # Use password=b'mypassword' here if the key is encrypted
23
)
24
25
# Read public key
26
with open(public_key_file, 'rb') as f:
27
public_key_pem = f.read()
28
public_key = serialization.load_pem_public_key(public_key_pem)
29
30
return private_key, public_key
31
32
# Generate keys
33
private_key_obj = rsa.generate_private_key(public_exponent=65537, key_size=1024)
34
public_key_obj = private_key_obj.public_key()
35
36
# Serialize private key
37
private_key_pem = private_key_obj.private_bytes(
38
encoding=serialization.Encoding.PEM,
39
format=serialization.PrivateFormat.PKCS8,
40
encryption_algorithm=serialization.NoEncryption()
41
)
42
43
# Serialize public key
44
public_key_pem = public_key_obj.public_bytes(
45
encoding=serialization.Encoding.PEM,
46
format=serialization.PublicFormat.SubjectPublicKeyInfo
47
)
48
49
# Write the private key PEM to a file
50
with open(private_key_file, 'wb') as f:
51
f.write(private_key_pem)
52
53
# Write the public key PEM to a file
54
with open(public_key_file, 'wb') as f:
55
f.write(public_key_pem)
56
57
return private_key_obj, public_key_obj
58
59
def decrypt_data(private_key_obj: RSAPrivateKey, encrypted_data: str) -> str:
60
decrypted = private_key_obj.decrypt(
61
base64.b64decode(encrypted_data),
62
padding.PKCS1v15()
63
)
64
return decrypted.decode()
65
66
def encrypt_data(public_key: RSAPublicKey, decrypted_data: str) -> str:
67
encrypted = public_key.encrypt(
68
decrypted_data.encode(),
69
padding.PKCS1v15()
70
)
71
return base64.b64encode(encrypted).decode()