forked from Geniucker/Deploy-ChatGPT-to-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
346 lines (329 loc) · 13.7 KB
/
run.py
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from subprocess import getoutput, Popen, PIPE, STDOUT
import os
import base64
import hashlib
import requests
import shelve
import datetime
from urllib.parse import urlparse, parse_qs
from certifi import where
from datetime import datetime as dt
proxy = "localhost:7890" # if you don't use proxy, set it to ""
proxy_type = "socks5" # socks5 or http
accounts = {
"user1": "password1",
# "user2": "password2"
}
access_tokens = [
# "your access token",
# "your another access token"
]
server_host = "0.0.0.0"
server_port = "8080" # if deploy in docker, set it to "8080"
def ERROR(msg):
print("\033[31m[ERROR]\033[0m" + msg)
def INFO(msg):
print("\033[32m[INFO]\033[0m" + msg)
def WARNING(msg):
print("\033[33m[WARNING]\033[0m" + msg)
def generate_code_verifier():
# 随机生成一个长度为 32 的 code_verifier
token = os.urandom(32)
code_verifier = base64.urlsafe_b64encode(token).rstrip(b'=')
return code_verifier.decode('utf-8')
def generate_code_challenge(code_verifier):
# 对 code_verifier 进行哈希处理,然后再进行 base64url 编码,生成 code_challenge
m = hashlib.sha256()
m.update(code_verifier.encode('utf-8'))
code_challenge = base64.urlsafe_b64encode(m.digest()).rstrip(b'=')
return code_challenge.decode('utf-8')
code_verifier = generate_code_verifier()
code_challenge = generate_code_challenge(code_verifier)
class Auth0:
def __init__(self, email: str = None, password: str = None, access_token: str = None, proxy: str = None, code_verifier: str = None, code_challenge: str = None):
self.session_token = None
self.email = email
self.password = password
self.session = requests.Session()
self.code_verifier = code_verifier
self.code_challenge = code_challenge
self.expires = None
self.req_kwargs = {
'proxies': {
'http': proxy,
'https': proxy,
} if proxy else None,
'verify': where(),
'timeout': 100,
}
self.access_token = access_token
self.refresh_token = None
self.user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) ' \
'Chrome/109.0.0.0 Safari/537.36'
try:
self.load_cache()
except:
self.auth()
self.make_cache()
def __del__(self):
if self.refresh_token:
url = "https://auth0.openai.com/oauth/revoke"
headers = {
'User-Agent': self.user_agent
}
data = {
"client_id": "pdlLIX2Y72MIl2rhLhTE9VV9bN905kBh",
"token": self.refresh_token
}
self.session.post(url, headers=headers, data=data, **self.req_kwargs)
def make_cache(self):
if not os.path.exists('cache'):
os.mkdir('cache')
with shelve.open('cache/cache', writeback=True) as db:
db[self.email] = {
'access_token': self.access_token,
'expires': self.expires
}
def load_cache(self):
with shelve.open('cache/cache') as db:
self.access_token = db[self.email]['access_token'],
self.access_token = self.access_token[0]
self.expires = db[self.email]['expires']
INFO('Load cache of {} successfully.'.format(self.email))
def refresh(self) -> str:
if self.email is None or self.password is None and self.access_token is not None:
return self.access_token
if self.access_token and self.expires and self.expires > dt.now():
return self.access_token
elif self.refresh_token:
url = "https://auth0.openai.com/oauth/token"
headers = {
'User-Agent': self.user_agent
}
data = {
"redirect_uri": "com.openai.chat://auth0.openai.com/ios/com.openai.chat/callback",
"grant_type": "refresh_token",
"client_id": "pdlLIX2Y72MIl2rhLhTE9VV9bN905kBh",
"refresh_token": self.refresh_token
}
resp = self.session.post(url, headers=headers, data=data, **self.req_kwargs)
if resp.status_code == 200:
json = resp.json()
self.access_token = json['access_token']
self.expires = dt.utcnow() + datetime.timedelta(seconds=json['expires_in']) - datetime.timedelta(minutes=5)
self.make_cache()
INFO('Refresh token of {} successfully.'.format(self.email))
return self.access_token
else:
raise Exception('Error refresh token.')
else:
self.auth()
self.make_cache()
return self.access_token
def auth(self) -> str:
return self.__part_two()
def __part_two(self) -> str:
code_challenge = self.code_challenge
code_verifier = self.code_verifier
url = 'https://auth0.openai.com/authorize?client_id=pdlLIX2Y72MIl2rhLhTE9VV9bN905kBh&audience=https%3A%2F' \
'%2Fapi.openai.com%2Fv1&redirect_uri=com.openai.chat%3A%2F%2Fauth0.openai.com%2Fios%2Fcom.openai.chat' \
'%2Fcallback&scope=openid%20email%20profile%20offline_access%20model.request%20model.read' \
'%20organization.read%20offline&response_type=code&code_challenge={}' \
'&code_challenge_method=S256&prompt=login'.format(code_challenge)
return self.__part_three(code_verifier, url)
def __part_three(self, code_verifier, url: str) -> str:
headers = {
'User-Agent': self.user_agent,
'Referer': 'https://ios.chat.openai.com/',
}
resp = self.session.get(url, headers=headers, allow_redirects=True, **self.req_kwargs)
if resp.status_code == 200:
try:
url_params = parse_qs(urlparse(resp.url).query)
state = url_params['state'][0]
return self.__part_four(code_verifier, state)
except IndexError as exc:
raise Exception('Rate limit hit.') from exc
else:
raise Exception('Error request login url.')
def __part_four(self, code_verifier: str, state: str) -> str:
url = 'https://auth0.openai.com/u/login/identifier?state=' + state
headers = {
'User-Agent': self.user_agent,
'Referer': url,
'Origin': 'https://auth0.openai.com',
}
data = {
'state': state,
'username': self.email,
'js-available': 'true',
'webauthn-available': 'true',
'is-brave': 'false',
'webauthn-platform-available': 'false',
'action': 'default',
}
resp = self.session.post(url, headers=headers, data=data, allow_redirects=False, **self.req_kwargs)
if resp.status_code == 302:
return self.__part_five(code_verifier, state)
else:
raise Exception('Error check email.')
def __part_five(self, code_verifier: str, state: str) -> str:
url = 'https://auth0.openai.com/u/login/password?state=' + state
headers = {
'User-Agent': self.user_agent,
'Referer': url,
'Origin': 'https://auth0.openai.com',
}
data = {
'state': state,
'username': self.email,
'password': self.password,
'action': 'default',
}
resp = self.session.post(url, headers=headers, data=data, allow_redirects=False, **self.req_kwargs)
if resp.status_code == 302:
location = resp.headers['Location']
if not location.startswith('/authorize/resume?'):
raise Exception('Login failed.')
return self.__part_six(code_verifier, location, url)
if resp.status_code == 400:
raise Exception('Wrong email or password.')
else:
raise Exception('Error login.')
def __part_six(self, code_verifier: str, location: str, ref: str) -> str:
url = 'https://auth0.openai.com' + location
headers = {
'User-Agent': self.user_agent,
'Referer': ref,
}
resp = self.session.get(url, headers=headers, allow_redirects=False, **self.req_kwargs)
if resp.status_code == 302:
location = resp.headers['Location']
if location.startswith('/u/mfa-otp-challenge?'):
if not self.mfa:
raise Exception('MFA required.')
return self.__part_seven(code_verifier, location)
if not location.startswith('com.openai.chat://auth0.openai.com/ios/com.openai.chat/callback?'):
raise Exception('Login callback failed.')
return self.get_access_token(code_verifier, resp.headers['Location'])
raise Exception('Error login.')
def __part_seven(self, code_verifier: str, location: str) -> str:
url = 'https://auth0.openai.com' + location
data = {
'state': parse_qs(urlparse(url).query)['state'][0],
'code': self.mfa,
'action': 'default',
}
headers = {
'User-Agent': self.user_agent,
'Referer': url,
'Origin': 'https://auth0.openai.com',
}
resp = self.session.post(url, headers=headers, data=data, allow_redirects=False, **self.req_kwargs)
if resp.status_code == 302:
location = resp.headers['Location']
if not location.startswith('/authorize/resume?'):
raise Exception('MFA failed.')
return self.__part_six(code_verifier, location, url)
if resp.status_code == 400:
raise Exception('Wrong MFA code.')
else:
raise Exception('Error login.')
def get_access_token(self, code_verifier: str, callback_url: str) -> str:
url_params = parse_qs(urlparse(callback_url).query)
if 'error' in url_params:
error = url_params['error'][0]
error_description = url_params['error_description'][0] if 'error_description' in url_params else ''
raise Exception('{}: {}'.format(error, error_description))
if 'code' not in url_params:
raise Exception('Error get code from callback url.')
url = 'https://auth0.openai.com/oauth/token'
headers = {
'User-Agent': self.user_agent,
}
data = {
'redirect_uri': 'com.openai.chat://auth0.openai.com/ios/com.openai.chat/callback',
'grant_type': 'authorization_code',
'client_id': 'pdlLIX2Y72MIl2rhLhTE9VV9bN905kBh',
'code': url_params['code'][0],
'code_verifier': code_verifier,
}
resp = self.session.post(url, headers=headers, json=data, allow_redirects=False, **self.req_kwargs)
if resp.status_code == 200:
json = resp.json()
if 'access_token' not in json:
raise Exception('Get access token failed, maybe you need a proxy.')
self.access_token = json['access_token']
self.refresh_token = json['refresh_token']
self.expires = dt.utcnow() + datetime.timedelta(seconds=json['expires_in']) - datetime.timedelta(minutes=5)
INFO('Get access token of {} successfully.'.format(self.email))
return self.access_token
else:
raise Exception(resp.text)
if __name__=="__main__":
if proxy.split(":")[0] in ["127.0.0.1", "localhost", "::1"] and os.path.exists("/.dockerenv"):
proxy = "host.docker.internal:{}".format(proxy.split(":")[1])
if proxy != "":
with open("./proxies.txt", "w") as f:
f.write(proxy)
proxy = "{}://{}".format(proxy_type, proxy)
else: proxy = None
os.environ["SERVER_HOST"] = server_host
os.environ["SERVER_PORT"] = server_port
os.environ["GIN_MODE"] = "release"
accout_objs = []
for i in accounts:
accout_objs.append(
Auth0(
email=i,
password=accounts[i],
proxy=proxy,
code_challenge=code_challenge,
code_verifier=code_verifier
)
)
for i in access_tokens:
accout_objs.append(
Auth0(
access_token=i,
proxy=proxy,
code_challenge=code_challenge,
code_verifier=code_verifier
)
)
while True:
# config access_tokens
access_token = []
for i in accout_objs:
access_token.append(i.refresh())
for i in range(len(access_token)):
access_token[i] = access_token[i].strip()
access_token[i] = "\"{}\"".format(access_token[i])
with open("./access_tokens.json", "w") as f:
f.write("[")
f.write(",".join(access_token))
f.write("]")
# run
cmd = "./freechatgpt"
try:
screenData = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=False)
while True:
line = screenData.stdout.readline().decode("utf-8").strip()
if line.find("[GIN]") != -1:
status = line.split()[5].strip()
if status == "200":
INFO(line)
elif status[0] == "5":
ERROR(line)
ERROR("detected 5xx, restarting...")
screenData.terminate()
break
else:
WARNING(line)
else:
INFO(line)
except:
screenData.terminate()
exit()