File size: 3,473 Bytes
a209d07
 
 
 
 
 
 
 
 
7885ccd
a209d07
 
 
 
 
 
fb296e1
 
c2bc1ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a209d07
 
034d344
a209d07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7885ccd
 
 
 
 
 
fb296e1
a209d07
 
 
 
fb296e1
a209d07
 
 
fb296e1
a209d07
 
fb296e1
a209d07
 
 
 
 
 
fb296e1
a209d07
 
 
7885ccd
 
a209d07
7885ccd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
from flask import Flask, request, jsonify
from flask_cors import CORS
import jwt
import time
import uuid
import requests
import os

app = Flask(__name__)
CORS(app, origins=["https://catptain-coze-api-01.hf.space"] + [
    "https://x-raremeta.com",
    "https://cybercity.top",
    "https://play-1.x-raremeta.com",
    "https://play.cybercity.top",
    "https://play.x-raremeta.com",
    "https://www.x-raremeta.com",
    "https://www.cybercity.top"
])
# Add this debug endpoint
@app.route('/debug', methods=['GET'])
def debug():
    current_dir = os.getcwd()
    file_dir = os.path.dirname(os.path.abspath(__file__))
    expected_path = os.path.join(file_dir, "private_key.pem")
    
    files_in_current = os.listdir(current_dir)
    files_in_file_dir = os.listdir(file_dir) if os.path.exists(file_dir) else []
    
    return jsonify({
        "current_directory": current_dir,
        "file_directory": file_dir,
        "expected_path": expected_path,
        "files_in_current_dir": files_in_current,
        "files_in_file_dir": files_in_file_dir,
        "__file__": __file__,
        "exists_at_expected_path": os.path.exists(expected_path),
        "exists_in_current_dir": os.path.exists("private_key.pem")
    })
# 你的配置信息
CLIENT_ID = "1243934778935"
PRIVATE_KEY_FILE_PATH = "private_key.pem"
KID = "tlrohMMZyKMrrpP3GtxF_3_cerDhVIMINs0LOW91m7w"
VALIDATION_TOKEN = "cybercity2025"

def generate_jwt(client_id, private_key, kid):
    header = {
        "alg": "RS256",
        "typ": "JWT",
        "kid": kid
    }
    payload = {
        "iss": client_id,
        "aud": "api.coze.cn",
        "iat": int(time.time()),
        "exp": int(time.time()) + 3600,  # JWT 有效期为 1 小时
        "jti": uuid.uuid4().hex  # 防止重放攻击
    }
    return jwt.encode(payload, private_key, algorithm="RS256", headers=header)

def get_access_token(jwt_token):
    url = "https://api.coze.cn/api/permission/oauth2/token"
    data = {
        "duration_seconds": 86399,
        "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer"
    }
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {jwt_token}"
    }
    response = requests.post(url, json=data, headers=headers)
    return response.json()

# 添加根路由,帮助Hugging Face识别应用已经就绪
@app.route('/', methods=['GET'])
def index():
    return jsonify({"status": "Service is running", "endpoints": ["/get_token"]}), 200

# 正确的token获取路由
@app.route('/get_token', methods=['GET'])
def get_token_from_flask():
    auth_header = request.headers.get('Authorization')
    if auth_header != VALIDATION_TOKEN:
        return jsonify({"error": "Invalid authorization token"}), 401
    
    try:
        with open(PRIVATE_KEY_FILE_PATH, "r") as f:
            private_key = f.read()
        
        jwt_token = generate_jwt(CLIENT_ID, private_key, KID)
        response = get_access_token(jwt_token)
        
        if "access_token" in response:
            return jsonify({
                "access_token": response["access_token"],
                "expires_in": response["expires_in"]
            })
        else:
            return jsonify({"error": "Failed to get access token", "details": response}), 500
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 使用环境变量设置端口
port = int(os.environ.get("PORT", 7860))
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=port)