-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathopenai-auth.ts
671 lines (590 loc) · 17.1 KB
/
openai-auth.ts
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
import * as url from 'node:url'
import delay from 'delay'
import { TimeoutError } from 'p-timeout'
import { Browser, Page, Protocol, PuppeteerLaunchOptions } from 'puppeteer'
import puppeteer from 'puppeteer-extra'
import RecaptchaPlugin from 'puppeteer-extra-plugin-recaptcha'
import StealthPlugin from 'puppeteer-extra-plugin-stealth'
import random from 'random'
import * as types from './types'
import { minimizePage } from './utils'
puppeteer.use(StealthPlugin())
let hasRecaptchaPlugin = false
let hasNopechaExtension = false
const __dirname = url.fileURLToPath(new URL('.', import.meta.url))
const DEFAULT_TIMEOUT_MS = 3 * 60 * 1000 // 3 minutes
/**
* Represents everything that's required to pass into `ChatGPTAPI` in order
* to authenticate with the unofficial ChatGPT API.
*/
export type OpenAIAuth = {
userAgent: string
clearanceToken: string
sessionToken: string
}
/**
* Bypasses OpenAI's use of Cloudflare to get the cookies required to use
* ChatGPT. Uses Puppeteer with a stealth plugin under the hood.
*
* If you pass `email` and `password`, then it will log into the account and
* include a `sessionToken` in the response.
*
* If you don't pass `email` and `password`, then it will just return a valid
* `clearanceToken`.
*
* This can be useful because `clearanceToken` expires after ~2 hours, whereas
* `sessionToken` generally lasts much longer. We recommend renewing your
* `clearanceToken` every hour or so and creating a new instance of `ChatGPTAPI`
* with your updated credentials.
*/
export async function getOpenAIAuth({
email,
password,
browser,
page,
timeoutMs = DEFAULT_TIMEOUT_MS,
isGoogleLogin = false,
isMicrosoftLogin = false,
captchaToken = process.env.CAPTCHA_TOKEN,
nopechaKey = process.env.NOPECHA_KEY,
executablePath,
proxyServer = process.env.PROXY_SERVER,
minimize = false
}: {
email?: string
password?: string
browser?: Browser
page?: Page
timeoutMs?: number
isGoogleLogin?: boolean
isMicrosoftLogin?: boolean
minimize?: boolean
captchaToken?: string
nopechaKey?: string
executablePath?: string
proxyServer?: string
}): Promise<OpenAIAuth> {
const origBrowser = browser
const origPage = page
try {
if (!browser) {
browser = await getBrowser({
captchaToken,
nopechaKey,
executablePath,
proxyServer,
timeoutMs
})
}
const userAgent = await browser.userAgent()
if (!page) {
page = await getPage(browser, { proxyServer })
page.setDefaultTimeout(timeoutMs)
if (minimize) {
await minimizePage(page)
}
}
await page.goto('https://chat.openai.com/auth/login', {
waitUntil: 'networkidle2'
})
// NOTE: this is where you may encounter a CAPTCHA
await checkForChatGPTAtCapacity(page, { timeoutMs })
if (hasRecaptchaPlugin) {
const captchas = await page.findRecaptchas()
if (captchas?.filtered?.length) {
console.log('solving captchas using 2captcha...')
const res = await page.solveRecaptchas()
console.log('captcha result', res)
}
}
// once we get to this point, the Cloudflare cookies should be available
// login as well (optional)
if (email && password) {
await waitForConditionOrAtCapacity(page, () =>
page.waitForSelector('#__next .btn-primary', { timeout: timeoutMs })
)
await delay(500)
// click login button and wait for navigation to finish
do {
await Promise.all([
page.waitForNavigation({
waitUntil: 'networkidle2',
timeout: timeoutMs
}),
page.click('#__next .btn-primary')
])
await delay(500)
} while (page.url().endsWith('/auth/login'))
await checkForChatGPTAtCapacity(page, { timeoutMs })
let submitP: () => Promise<void>
if (isGoogleLogin) {
await page.waitForSelector('button[data-provider="google"]', {
timeout: timeoutMs
})
await page.click('button[data-provider="google"]')
await page.waitForSelector('input[type="email"]')
await page.type('input[type="email"]', email)
await Promise.all([
page.waitForNavigation(),
await page.keyboard.press('Enter')
])
await page.waitForSelector('input[type="password"]', { visible: true })
await page.type('input[type="password"]', password)
await delay(50)
submitP = () => page.keyboard.press('Enter')
} else if (isMicrosoftLogin) {
await page.click('button[data-provider="windowslive"]')
await page.waitForSelector('input[type="email"]')
await page.type('input[type="email"]', email)
await Promise.all([
page.waitForNavigation(),
await page.keyboard.press('Enter')
])
await delay(1500)
await page.waitForSelector('input[type="password"]', { visible: true })
await page.type('input[type="password"]', password)
await delay(50)
submitP = () => page.keyboard.press('Enter')
await Promise.all([
page.waitForNavigation(),
await page.keyboard.press('Enter')
])
await delay(1000)
} else {
await page.waitForSelector('#username')
await page.type('#username', email)
await delay(100)
// NOTE: this is where you may encounter a CAPTCHA
if (hasNopechaExtension) {
await waitForRecaptcha(page, { timeoutMs })
} else if (hasRecaptchaPlugin) {
console.log('solving captchas using 2captcha...')
// Add retries in case network is unstable
const retries = 3
for (let i = 0; i < retries; i++) {
try {
const res = await page.solveRecaptchas()
if (res.captchas?.length) {
console.log('captchas result', res)
break
} else {
console.log('no captchas found')
await delay(500)
}
} catch (e) {
console.log('captcha error', e)
}
}
}
await delay(2000)
const frame = page.mainFrame()
const submit = await page.waitForSelector('button[type="submit"]', {
timeout: timeoutMs
})
await frame.focus('button[type="submit"]')
await submit.focus()
await submit.click()
await page.waitForSelector('#password', { timeout: timeoutMs })
await page.type('#password', password)
await delay(50)
submitP = () => page.click('button[type="submit"]')
}
await Promise.all([
waitForConditionOrAtCapacity(page, () =>
page.waitForNavigation({
waitUntil: 'networkidle2',
timeout: timeoutMs
})
),
submitP()
])
} else {
await delay(2000)
await checkForChatGPTAtCapacity(page, { timeoutMs })
}
const pageCookies = await page.cookies()
const cookies = pageCookies.reduce(
(map, cookie) => ({ ...map, [cookie.name]: cookie }),
{}
)
const authInfo: OpenAIAuth = {
userAgent,
clearanceToken: cookies['cf_clearance']?.value,
sessionToken: cookies['__Secure-next-auth.session-token']?.value
}
return authInfo
} catch (err) {
throw err
} finally {
if (origBrowser) {
if (page && page !== origPage) {
await page.close()
}
} else if (browser) {
await browser.close()
}
page = null
browser = null
}
}
export async function getPage(
browser: Browser,
opts: {
proxyServer?: string
}
) {
const { proxyServer = process.env.PROXY_SERVER } = opts
const page = (await browser.pages())[0] || (await browser.newPage())
if (proxyServer && proxyServer.includes('@')) {
const proxyAuth = proxyServer.split('@')[0].split(':')
const proxyUsername = proxyAuth[0]
const proxyPassword = proxyAuth[1]
try {
await page.authenticate({
username: proxyUsername,
password: proxyPassword
})
} catch (err) {
console.error(
`ChatGPT "${this._email}" error authenticating proxy "${this._proxyServer}"`,
err.toString()
)
throw err
}
}
return page
}
/**
* Launches a non-puppeteer instance of Chrome. Note that in my testing, I wasn't
* able to use the built-in `puppeteer` version of Chromium because Cloudflare
* recognizes it and blocks access.
*/
export async function getBrowser(
opts: PuppeteerLaunchOptions & {
captchaToken?: string
nopechaKey?: string
proxyServer?: string
minimize?: boolean
debug?: boolean
timeoutMs?: number
} = {}
) {
const {
captchaToken = process.env.CAPTCHA_TOKEN,
nopechaKey = process.env.NOPECHA_KEY,
executablePath = defaultChromeExecutablePath(),
proxyServer = process.env.PROXY_SERVER,
minimize = false,
debug = false,
timeoutMs = DEFAULT_TIMEOUT_MS,
...launchOptions
} = opts
if (captchaToken && !hasRecaptchaPlugin) {
hasRecaptchaPlugin = true
// console.log('use captcha', captchaToken)
puppeteer.use(
RecaptchaPlugin({
provider: {
id: '2captcha',
token: captchaToken
},
visualFeedback: true // colorize reCAPTCHAs (violet = detected, green = solved)
})
)
}
// https://peter.sh/experiments/chromium-command-line-switches/
const puppeteerArgs = [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-infobars',
'--disable-dev-shm-usage',
'--disable-blink-features=AutomationControlled',
'--ignore-certificate-errors',
'--no-first-run',
'--no-service-autorun',
'--password-store=basic',
'--system-developer-mode',
// the following flags all try to reduce memory
// '--single-process',
'--mute-audio',
'--disable-default-apps',
'--no-zygote',
'--disable-accelerated-2d-canvas',
'--disable-web-security'
// '--disable-gpu'
// '--js-flags="--max-old-space-size=1024"'
]
if (nopechaKey) {
const nopechaPath = path.join(
__dirname,
'..',
'third-party',
'nopecha-chrome-extension'
)
puppeteerArgs.push(`--disable-extensions-except=${nopechaPath}`)
puppeteerArgs.push(`--load-extension=${nopechaPath}`)
hasNopechaExtension = true
}
if (proxyServer) {
const ipPort = proxyServer.includes('@')
? proxyServer.split('@')[1]
: proxyServer
puppeteerArgs.push(`--proxy-server=${ipPort}`)
}
const browser = await puppeteer.launch({
headless: false,
// devtools: true,
args: puppeteerArgs,
ignoreDefaultArgs: [
'--disable-extensions',
'--enable-automation',
'--disable-component-extensions-with-background-pages'
],
ignoreHTTPSErrors: true,
executablePath,
...launchOptions
})
if (process.env.PROXY_VALIDATE_IP) {
const page = await getPage(browser, { proxyServer })
if (minimize) {
await minimizePage(page)
}
// Send a fetch request to https://ifconfig.co using page.evaluate() and
// verify that the IP matches
let ip: string
try {
const res = await page.evaluate(() => {
return fetch('https://ifconfig.co', {
headers: {
Accept: 'application/json'
}
}).then((res) => res.json())
})
ip = res?.ip
} catch (err) {
throw new Error(`Proxy IP validation failed: ${err.toString()}`, {
cause: err
})
}
if (!ip || ip !== process.env.PROXY_VALIDATE_IP) {
throw new Error(
`Proxy IP mismatch: ${ip} !== ${process.env.PROXY_VALIDATE_IP}`
)
}
}
await initializeNopechaExtension(browser, {
nopechaKey,
minimize,
debug,
timeoutMs,
proxyServer
})
return browser
}
export async function initializeNopechaExtension(
browser: Browser,
opts: {
proxyServer?: string
nopechaKey?: string
minimize?: boolean
debug?: boolean
timeoutMs?: number
}
) {
const { minimize = false, debug = false, nopechaKey, proxyServer } = opts
if (hasNopechaExtension) {
const page = await getPage(browser, { proxyServer })
if (minimize) {
await minimizePage(page)
}
if (debug) {
console.log('initializing nopecha extension with key', nopechaKey, '...')
}
// TODO: setting the nopecha extension key is really, really error prone...
for (let i = 0; i < 5; ++i) {
await page.goto(`https://nopecha.com/setup#${nopechaKey}`, {
waitUntil: 'networkidle0'
})
await delay(500)
}
}
}
/**
* Gets the default path to chrome's executable for the current platform.
*/
export const defaultChromeExecutablePath = (): string => {
// return executablePath()
if (process.env.PUPPETEER_EXECUTABLE_PATH) {
return process.env.PUPPETEER_EXECUTABLE_PATH
}
switch (os.platform()) {
case 'win32':
return 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'
case 'darwin':
return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
default: {
/**
* Since two (2) separate chrome releases exist on linux, we first do a
* check to ensure we're executing the right one.
*/
const chromeExists = fs.existsSync('/usr/bin/google-chrome')
return chromeExists
? '/usr/bin/google-chrome'
: '/usr/bin/google-chrome-stable'
}
}
}
async function checkForChatGPTAtCapacity(
page: Page,
opts: {
timeoutMs?: number
pollingIntervalMs?: number
retries?: number
} = {}
) {
const {
timeoutMs = 2 * 60 * 1000, // 2 minutes
pollingIntervalMs = 3000,
retries = 10
} = opts
// console.log('checkForChatGPTAtCapacity', page.url())
let isAtCapacity = false
let numTries = 0
do {
try {
await solveSimpleCaptchas(page)
const res = await page.$x("//div[contains(., 'ChatGPT is at capacity')]")
isAtCapacity = !!res?.length
if (isAtCapacity) {
if (++numTries >= retries) {
break
}
// try refreshing the page if chatgpt is at capacity
await page.reload({
waitUntil: 'networkidle2',
timeout: timeoutMs
})
await delay(pollingIntervalMs)
}
} catch (err) {
// ignore errors likely due to navigation
++numTries
break
}
} while (isAtCapacity)
if (isAtCapacity) {
const error = new types.ChatGPTError('ChatGPT is at capacity')
error.statusCode = 503
throw error
}
}
async function waitForConditionOrAtCapacity(
page: Page,
condition: () => Promise<any>,
opts: {
pollingIntervalMs?: number
} = {}
) {
const { pollingIntervalMs = 500 } = opts
return new Promise<void>((resolve, reject) => {
let resolved = false
async function waitForCapacityText() {
if (resolved) {
return
}
try {
await checkForChatGPTAtCapacity(page)
if (!resolved) {
setTimeout(waitForCapacityText, pollingIntervalMs)
}
} catch (err) {
if (!resolved) {
resolved = true
return reject(err)
}
}
}
condition()
.then(() => {
if (!resolved) {
resolved = true
resolve()
}
})
.catch((err) => {
if (!resolved) {
resolved = true
reject(err)
}
})
setTimeout(waitForCapacityText, pollingIntervalMs)
})
}
async function solveSimpleCaptchas(page: Page) {
try {
const verifyYouAreHuman = await page.$('text=Verify you are human')
if (verifyYouAreHuman) {
await delay(2000)
await verifyYouAreHuman.click({
delay: random.int(5, 25)
})
await delay(1000)
}
const cloudflareButton = await page.$('.hcaptcha-box')
if (cloudflareButton) {
await delay(2000)
await cloudflareButton.click({
delay: random.int(5, 25)
})
await delay(1000)
}
} catch (err) {
// ignore errors
}
}
async function waitForRecaptcha(
page: Page,
opts: {
pollingIntervalMs?: number
timeoutMs?: number
} = {}
) {
await solveSimpleCaptchas(page)
if (!hasNopechaExtension) {
return
}
const { pollingIntervalMs = 100, timeoutMs } = opts
const captcha = await page.$('textarea#g-recaptcha-response')
const startTime = Date.now()
if (captcha) {
console.log('waiting to solve recaptcha...')
do {
try {
const captcha = await page.$('textarea#g-recaptcha-response')
if (!captcha) {
// the user may have gone past the page manually
console.log('captcha no longer found; continuing')
break
}
const value = (await captcha.evaluate((el) => el.value))?.trim()
if (value?.length) {
// recaptcha has been solved!
console.log('captcha solved; continuing')
break
}
} catch (err) {
// catch navigation-related page context errors
}
if (timeoutMs) {
const now = Date.now()
if (now - startTime >= timeoutMs) {
throw new TimeoutError('Timed out waiting to solve Recaptcha')
}
}
await delay(pollingIntervalMs)
} while (true)
}
}