Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,85 +5,133 @@ import time
|
|
5 |
import uuid
|
6 |
import requests
|
7 |
import os
|
|
|
|
|
|
|
8 |
|
9 |
app = Flask(__name__)
|
10 |
-
CORS(app, origins=
|
11 |
-
"https://x-raremeta.com",
|
12 |
-
"https://cybercity.top",
|
13 |
-
"https://play-1.x-raremeta.com",
|
14 |
-
"https://play.cybercity.top",
|
15 |
-
"https://play.x-raremeta.com",
|
16 |
-
"https://www.x-raremeta.com",
|
17 |
-
"https://www.cybercity.top"
|
18 |
-
])
|
19 |
|
20 |
-
#
|
21 |
-
CLIENT_ID =
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
header = {
|
28 |
"alg": "RS256",
|
29 |
"typ": "JWT",
|
30 |
-
"kid":
|
31 |
-
}
|
32 |
-
payload = {
|
33 |
-
"iss": client_id,
|
34 |
-
"aud": "api.coze.cn",
|
35 |
-
"iat": int(time.time()),
|
36 |
-
"exp": int(time.time()) + 3600, # JWT 有效期为 1 小时
|
37 |
-
"jti": uuid.uuid4().hex, # 防止重放攻击
|
38 |
-
"connector_id": "3723409317963603", # 根据实际要求设置
|
39 |
-
"user_id": "3723409317963603", # 根据实际要求设置
|
40 |
-
"UID": "3723409317963603", # 根据实际要求设置
|
41 |
}
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
def get_access_token(jwt_token):
|
|
|
45 |
url = "https://api.coze.cn/api/permission/oauth2/token"
|
46 |
data = {
|
47 |
-
"
|
48 |
-
"
|
49 |
}
|
50 |
headers = {
|
51 |
"Content-Type": "application/json",
|
52 |
"Authorization": f"Bearer {jwt_token}"
|
53 |
}
|
54 |
-
|
55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
-
#
|
58 |
-
@app.route('/', methods=['GET'])
|
59 |
-
def
|
60 |
-
return jsonify({"status": "
|
61 |
|
62 |
-
#
|
63 |
-
@app.route('/
|
64 |
-
def
|
65 |
-
|
66 |
-
if
|
67 |
-
return jsonify({"error": "
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
"expires_in": response["expires_in"]
|
80 |
})
|
81 |
-
|
82 |
-
return jsonify({"error": "
|
83 |
-
|
84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
-
# 使用环境变量设置端口
|
87 |
-
port = int(os.environ.get("PORT", 7860))
|
88 |
if __name__ == '__main__':
|
89 |
-
|
|
|
|
5 |
import uuid
|
6 |
import requests
|
7 |
import os
|
8 |
+
import base64
|
9 |
+
from functools import wraps
|
10 |
+
import logging
|
11 |
|
12 |
app = Flask(__name__)
|
13 |
+
CORS(app, origins=os.getenv('ALLOWED_ORIGINS', 'https://cybercity.top').split(','))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
# 环境变量配置
|
16 |
+
CLIENT_ID = os.getenv('COZE_CLIENT_ID', '1243934778935')
|
17 |
+
KID = os.getenv('COZE_KID', 'tlrohMMZyKMrrpP3GtxF_3_cerDhVIMINs0LOW91m7w')
|
18 |
+
PRIVATE_KEY = os.getenv('COZE_PRIVATE_KEY').replace('\\n', '\n') # 从环境变量获取并格式化
|
19 |
+
CLIENT_SECRET = os.getenv('COZE_CLIENT_SECRET', 'your_client_secret')
|
20 |
|
21 |
+
# 日志配置
|
22 |
+
logging.basicConfig(level=logging.INFO)
|
23 |
+
logger = logging.getLogger(__name__)
|
24 |
+
|
25 |
+
# JWT缓存机制(简易内存缓存)
|
26 |
+
jwt_cache = {'token': None, 'exp': 0}
|
27 |
+
|
28 |
+
def validate_basic_auth(auth_header):
|
29 |
+
"""实现RFC6749标准的Basic认证验证[10](@ref)"""
|
30 |
+
if not auth_header or not auth_header.startswith('Basic '):
|
31 |
+
return False
|
32 |
+
try:
|
33 |
+
credentials = base64.b64decode(auth_header[6:]).decode('utf-8')
|
34 |
+
client_id, client_secret = credentials.split(':', 1)
|
35 |
+
return client_id == CLIENT_ID and client_secret == CLIENT_SECRET
|
36 |
+
except Exception as e:
|
37 |
+
logger.error(f"Basic auth validation failed: {str(e)}")
|
38 |
+
return False
|
39 |
+
|
40 |
+
def generate_jwt():
|
41 |
+
"""生成符合RFC7519标准的JWT[1,3](@ref)"""
|
42 |
+
current_time = int(time.time())
|
43 |
+
payload = {
|
44 |
+
"iss": CLIENT_ID,
|
45 |
+
"sub": CLIENT_ID, # 必须包含sub字段[6](@ref)
|
46 |
+
"aud": "https://api.coze.cn", # 精确的URI格式
|
47 |
+
"iat": current_time,
|
48 |
+
"exp": current_time + 3600,
|
49 |
+
"jti": uuid.uuid4().hex,
|
50 |
+
"connector_id": CLIENT_ID, # 统一使用client_id
|
51 |
+
"user_id": CLIENT_ID
|
52 |
+
}
|
53 |
+
|
54 |
header = {
|
55 |
"alg": "RS256",
|
56 |
"typ": "JWT",
|
57 |
+
"kid": KID
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
}
|
59 |
+
|
60 |
+
try:
|
61 |
+
return jwt.encode(payload, PRIVATE_KEY, algorithm="RS256", headers=header)
|
62 |
+
except jwt.PyJWTError as e:
|
63 |
+
logger.error(f"JWT generation failed: {str(e)}")
|
64 |
+
raise
|
65 |
|
66 |
def get_access_token(jwt_token):
|
67 |
+
"""获取访问令牌(带重试机制)[3](@ref)"""
|
68 |
url = "https://api.coze.cn/api/permission/oauth2/token"
|
69 |
data = {
|
70 |
+
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
71 |
+
"duration_seconds": 86399
|
72 |
}
|
73 |
headers = {
|
74 |
"Content-Type": "application/json",
|
75 |
"Authorization": f"Bearer {jwt_token}"
|
76 |
}
|
77 |
+
|
78 |
+
try:
|
79 |
+
response = requests.post(url, json=data, headers=headers, timeout=10)
|
80 |
+
response.raise_for_status()
|
81 |
+
return response.json()
|
82 |
+
except requests.exceptions.RequestException as e:
|
83 |
+
logger.error(f"Access token request failed: {str(e)}")
|
84 |
+
return {"error": "coze_api_error"}
|
85 |
|
86 |
+
# 健康检查端点
|
87 |
+
@app.route('/health', methods=['GET'])
|
88 |
+
def health_check():
|
89 |
+
return jsonify({"status": "healthy", "timestamp": int(time.time())}), 200
|
90 |
|
91 |
+
# 令牌获取端点
|
92 |
+
@app.route('/api/token', methods=['POST'])
|
93 |
+
def get_coze_token():
|
94 |
+
# Basic认证验证
|
95 |
+
if not validate_basic_auth(request.headers.get('Authorization')):
|
96 |
+
return jsonify({"error": "invalid_client"}), 401
|
97 |
|
98 |
+
# 检查缓存中的有效JWT
|
99 |
+
current_time = time.time()
|
100 |
+
if jwt_cache['exp'] > current_time + 300: # 有效期剩余超过5分钟时复用
|
101 |
+
cached_token = jwt_cache['token']
|
102 |
+
else:
|
103 |
+
try:
|
104 |
+
cached_token = generate_jwt()
|
105 |
+
jwt_cache.update({
|
106 |
+
'token': cached_token,
|
107 |
+
'exp': current_time + 3600
|
|
|
108 |
})
|
109 |
+
except Exception as e:
|
110 |
+
return jsonify({"error": "jwt_generation_failed"}), 500
|
111 |
+
|
112 |
+
# 获取访问令牌
|
113 |
+
token_response = get_access_token(cached_token)
|
114 |
+
if 'error' in token_response:
|
115 |
+
return jsonify({
|
116 |
+
"error": "coze_oauth_error",
|
117 |
+
"details": token_response.get('error_description')
|
118 |
+
}), 502
|
119 |
+
|
120 |
+
return jsonify({
|
121 |
+
"access_token": token_response['access_token'],
|
122 |
+
"expires_in": token_response['expires_in'],
|
123 |
+
"token_type": "Bearer"
|
124 |
+
})
|
125 |
+
|
126 |
+
# 错误处理
|
127 |
+
@app.errorhandler(404)
|
128 |
+
def not_found(error):
|
129 |
+
return jsonify({"error": "endpoint_not_found"}), 404
|
130 |
+
|
131 |
+
@app.errorhandler(500)
|
132 |
+
def internal_error(error):
|
133 |
+
return jsonify({"error": "internal_server_error"}), 500
|
134 |
|
|
|
|
|
135 |
if __name__ == '__main__':
|
136 |
+
port = int(os.getenv('PORT', 7860))
|
137 |
+
app.run(host='0.0.0.0', port=port, debug=os.getenv('DEBUG', 'false').lower() == 'true')
|