Skip to content

Commit

Permalink
commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Antonio committed May 25, 2023
1 parent 2fc731f commit 6b751d7
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 181 deletions.
280 changes: 99 additions & 181 deletions auth/OpenAiAuth.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ package auth

import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/url"
"regexp"
"strings"

"crypto/rand"

http "github.com/bogdanfinn/fhttp"
tls_client "github.com/bogdanfinn/tls-client"
)
Expand All @@ -30,31 +33,74 @@ func NewError(location string, statusCode int, details string, err error) *Error
}

type Authenticator struct {
EmailAddress string
Password string
Proxy string
Session tls_client.HttpClient
AccessToken string
UserAgent string
EmailAddress string
Password string
Proxy string
Session tls_client.HttpClient
AccessToken string
UserAgent string
State string
URL string
Verifier_code string
Verifier_challenge string
AuthDetails AuthDetails
}

type AuthDetails struct {
ClientID string `json:"client_id"`
Scope string `json:"scope"`
ResponseType string `json:"response_type"`
RedirectURL string `json:"redirect_url"`
Audience string `json:"audience"`
Prompt string `json:"prompt"`
State string `json:"state"`
CodeChallenge string `json:"code_challenge"`
CodeChallengeMethod string `json:"code_challenge_method"`
}

func NewAuthDetails(challenge string) AuthDetails {
// Generate state (secrets.token_urlsafe(32))
b := make([]byte, 32)
rand.Read(b)
state := base64.URLEncoding.EncodeToString(b)
return AuthDetails{
ClientID: "pdlLIX2Y72MIl2rhLhTE9VV9bN905kBh",
Scope: "openid email profile offline_access model.request model.read organization.read",
ResponseType: "code",
RedirectURL: "com.openai.chat://auth0.openai.com/ios/com.openai.chat/callback",
Audience: "https://api.openai.com/v1",
Prompt: "login",
State: state,
CodeChallenge: challenge,
CodeChallengeMethod: "S256",
}
}

func NewAuthenticator(emailAddress, password, proxy string) *Authenticator {
auth := &Authenticator{
EmailAddress: emailAddress,
Password: password,
Proxy: proxy,
UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
}
jar := tls_client.NewCookieJar()
options := []tls_client.HttpClientOption{
tls_client.WithTimeoutSeconds(20),
tls_client.WithClientProfile(tls_client.Firefox_110),
tls_client.WithClientProfile(tls_client.Chrome_110),
tls_client.WithNotFollowRedirects(),
tls_client.WithCookieJar(jar), // create cookieJar instance and pass it as argument
// Proxy
tls_client.WithProxyUrl(proxy),
}
auth.Session, _ = tls_client.NewHttpClient(tls_client.NewNoopLogger(), options...)

// PKCE
// verifier, _ := pkce.CreateCodeVerifier()
auth.Verifier_code = "yGrXROHx_VazA0uovsxKfE263LMFcrSrdm4SlC-rob8"
auth.Verifier_challenge = "w6n3Ix420Xhhu-Q5-mOOEyuPZmAsJHUbBpO8Ub7xBCY"

auth.AuthDetails = NewAuthDetails(auth.Verifier_challenge)

return auth
}

Expand All @@ -63,55 +109,14 @@ func (auth *Authenticator) URLEncode(str string) string {
}

func (auth *Authenticator) Begin() Error {
// Just realized that the client id is hardcoded in the JS file

url := "https://chat.openai.com/api/auth/csrf"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return *NewError("begin", 0, "", err)
}

req.Header.Set("Host", "chat.openai.com")
req.Header.Set("Accept", "*/*")
req.Header.Set("Connection", "keep-alive")
req.Header.Set("User-Agent", auth.UserAgent)
req.Header.Set("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Set("Referer", "https://chat.openai.com/auth/login")
req.Header.Set("Accept-Encoding", "gzip, deflate, br")

resp, err := auth.Session.Do(req)
if err != nil {
return *NewError("begin", 0, "", err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return *NewError("begin", 0, "", err)
}

if resp.StatusCode == 200 && strings.Contains(resp.Header.Get("Content-Type"), "json") {

var csrfTokenResponse struct {
CsrfToken string `json:"csrfToken"`
}
err = json.Unmarshal(body, &csrfTokenResponse)
if err != nil {
return *NewError("begin", 0, "", err)
}

csrfToken := csrfTokenResponse.CsrfToken
return auth.partOne(csrfToken)
} else {
err := NewError("begin", resp.StatusCode, string(body), fmt.Errorf("error: Check details"))
return *err
}
return auth.partOne()
}
func (auth *Authenticator) partOne(token string) Error {
func (auth *Authenticator) partOne() Error {

url := "https://chat.openai.com/api/auth/signin/auth0?prompt=login"
payload := fmt.Sprintf("callbackUrl=%%2F&csrfToken=%s&json=true", token)
auth_url := "https://auth0.openai.com/authorize"
headers := map[string]string{
"Host": "chat.openai.com",
"User-Agent": auth.UserAgent,
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
Expand All @@ -124,8 +129,20 @@ func (auth *Authenticator) partOne(token string) Error {
"Referer": "https://chat.openai.com/auth/login",
"Accept-Encoding": "gzip, deflate",
}

req, err := http.NewRequest("POST", url, strings.NewReader(payload))
// Construct payload
payload := url.Values{
"client_id": {auth.AuthDetails.ClientID},
"scope": {auth.AuthDetails.Scope},
"response_type": {auth.AuthDetails.ResponseType},
"redirect_uri": {auth.AuthDetails.RedirectURL},
"audience": {auth.AuthDetails.Audience},
"prompt": {auth.AuthDetails.Prompt},
"state": {auth.AuthDetails.State},
"code_challenge": {auth.AuthDetails.CodeChallenge},
"code_challenge_method": {auth.AuthDetails.CodeChallengeMethod},
}
auth_url = auth_url + "?" + payload.Encode()
req, err := http.NewRequest("GET", auth_url, nil)
if err != nil {
return *NewError("part_one", 0, "", err)
}
Expand All @@ -144,23 +161,8 @@ func (auth *Authenticator) partOne(token string) Error {
return *NewError("part_one", 0, "", err)
}

if resp.StatusCode == 200 && strings.Contains(resp.Header.Get("Content-Type"), "json") {

var urlResponse struct {
URL string `json:"url"`
}
err = json.Unmarshal(body, &urlResponse)
if err != nil {
return *NewError("part_one", 0, "", err)
}

url := urlResponse.URL
if url == "https://chat.openai.com/api/auth/error?error=OAuthSignin" || strings.Contains(url, "error") {
err := NewError("part_one", resp.StatusCode, "You have been rate limited. Please try again later.", fmt.Errorf("error: Check details"))
return *err
}

return auth.partTwo(url)
if resp.StatusCode == 302 {
return auth.partTwo("https://auth0.openai.com" + resp.Header.Get("Location"))
} else {
err := NewError("part_one", resp.StatusCode, string(body), fmt.Errorf("error: Check details"))
return *err
Expand All @@ -175,7 +177,7 @@ func (auth *Authenticator) partTwo(url string) Error {
"Connection": "keep-alive",
"User-Agent": auth.UserAgent,
"Accept-Language": "en-US,en;q=0.9",
"Referer": "https://chat.openai.com/",
"Referer": "https://ios.chat.openai.com/",
}

req, err := http.NewRequest("GET", url, nil)
Expand Down Expand Up @@ -212,50 +214,8 @@ func (auth *Authenticator) partTwo(url string) Error {
return *err
}
}

func (auth *Authenticator) partThree(state string) Error {

url := fmt.Sprintf("https://auth0.openai.com/u/login/identifier?state=%s", state)

headers := map[string]string{
"Host": "auth0.openai.com",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Connection": "keep-alive",
"User-Agent": auth.UserAgent,
"Accept-Language": "en-US,en;q=0.9",
"Referer": "https://chat.openai.com/",
}

req, err := http.NewRequest("GET", url, nil)
if err != nil {
return *NewError("part_three", 0, "", err)
}

for k, v := range headers {
req.Header.Set(k, v)
}

resp, err := auth.Session.Do(req)
if err != nil {
return *NewError("part_three", 0, "", err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return *NewError("part_three", 0, "", err)
}

if resp.StatusCode == 200 {
return auth.partFour(state)
} else {
err := NewError("__part_three", resp.StatusCode, string(body), fmt.Errorf("error: Check details"))
return *err
}

}
func (auth *Authenticator) partFour(state string) Error {

url := fmt.Sprintf("https://auth0.openai.com/u/login/identifier?state=%s", state)
emailURLEncoded := auth.URLEncode(auth.EmailAddress)

Expand Down Expand Up @@ -374,84 +334,42 @@ func (auth *Authenticator) partSix(oldState string, redirectURL string) Error {
defer resp.Body.Close()

if resp.StatusCode == 302 {
redirectURL := resp.Header.Get("Location")
return auth.partSeven(redirectURL, url)
auth.URL = resp.Header.Get("Location")

return Error{}
} else {
err := NewError("__part_six", resp.StatusCode, resp.Status, fmt.Errorf("error: Check details"))
return *err
}

}
func (auth *Authenticator) partSeven(redirectURL string, previousURL string) Error {

url := redirectURL

headers := map[string]string{
"Host": "chat.openai.com",
"Accept": "application/json",
"Connection": "keep-alive",
"User-Agent": auth.UserAgent,
"Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
"Referer": previousURL,
}

req, err := http.NewRequest("GET", url, nil)
if err != nil {
return *NewError("part_seven", 0, "", err)
}

for k, v := range headers {
req.Header.Set(k, v)
}

resp, err := auth.Session.Do(req)
if err != nil {
return *NewError("part_seven", 0, "", err)
}
defer resp.Body.Close()

if resp.StatusCode == 200 || resp.StatusCode == 302 {
return Error{}
} else {
body, err := io.ReadAll(resp.Body)
if err != nil {
return *NewError("part_seven", 0, "", err)
}
return *NewError("__part_seven", resp.StatusCode, string(body), fmt.Errorf("error: Check details"))
}
}
func (auth *Authenticator) GetAccessToken() (string, Error) {
url := "https://chat.openai.com/api/auth/session"

req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", *NewError("get_access_token", 0, "", err)
// Parse auth.URL (Get code=7QEpWz_4irkvJSP29Pyx0-EguHDFhQd_L1rhaxdBbl3gT) using regex
code := regexp.MustCompile(`code=(.*)&`).FindStringSubmatch(auth.URL)[1]
payload, _ := json.Marshal(map[string]string{
"redirect_uri": "com.openai.chat://auth0.openai.com/ios/com.openai.chat/callback",
"grant_type": "authorization_code",
"client_id": "pdlLIX2Y72MIl2rhLhTE9VV9bN905kBh",
"code": code,
"code_verifier": auth.Verifier_code,
"state": auth.State,
})

req, _ := http.NewRequest("POST", "https://auth0.openai.com/oauth/token", strings.NewReader(string(payload)))
for k, v := range map[string]string{
"User-Agent": auth.UserAgent,
"context-type": "application/json",
} {
req.Header.Set(k, v)
}
// Set user agent
req.Header.Set("User-Agent", auth.UserAgent)

resp, err := auth.Session.Do(req)
if err != nil {
return "", *NewError("get_access_token", 0, "", err)
}
defer resp.Body.Close()
// Parse response
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))

if resp.StatusCode == 200 {
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", *NewError("get_access_token", 0, "", err)
}
if result["accessToken"] == nil {
return "", *NewError("get_access_token", 0, "", fmt.Errorf("error: accessToken is nil"))
}

auth.AccessToken = result["accessToken"].(string)
return auth.AccessToken, Error{}
} else {
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", *NewError("get_access_token", 0, "", err)
}
return "", *NewError("get_access_token", resp.StatusCode, string(body), fmt.Errorf("error: Check details"))
}
return "", Error{}
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.20
require (
github.com/bogdanfinn/fhttp v0.5.19
github.com/bogdanfinn/tls-client v1.3.8
github.com/nirasan/go-oauth-pkce-code-verifier v0.0.0-20220510032225-4f9f17eaec4c
)

require (
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ github.com/bogdanfinn/utls v1.5.15 h1:XUUMJZh2AptaouuwUrc/RQOYgyV89rstC5Nj3FSP43
github.com/bogdanfinn/utls v1.5.15/go.mod h1:mHeRCi69cUiEyVBkKONB1cAbLjRcZnlJbGzttmiuK4o=
github.com/klauspost/compress v1.15.12 h1:YClS/PImqYbn+UILDnqxQCZ3RehC9N318SU3kElDUEM=
github.com/klauspost/compress v1.15.12/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM=
github.com/nirasan/go-oauth-pkce-code-verifier v0.0.0-20220510032225-4f9f17eaec4c h1:4RYnE0ISVwRxm9Dfo7utw1dh0kdRDEmVYq2MFVLy5zI=
github.com/nirasan/go-oauth-pkce-code-verifier v0.0.0-20220510032225-4f9f17eaec4c/go.mod h1:DvuJJ/w1Y59rG8UTDxsMk5U+UJXJwuvUgbiJSm9yhX8=
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc=
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng=
golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU=
Expand Down

0 comments on commit 6b751d7

Please sign in to comment.