Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
updates for browser-based auth and cloud credit tracking
Dane Schneider1f3f2cbc5c1d
diff --git a/app/_env b/app/_envindex b2aec51f..0754205c 100644--- a/app/_env+++ b/app/_env@@ -5,3 +5,4 @@ PGDATA_DIR=/var/lib/postgresql/dataPLANDEX_DATA_DIR=/var/lib/plandex/data # local path to store plandex data (outside container)GOENV=developmentPLANDEX_BASE_DIR=/plandex-server # container path to store plandex data (inside container)+API_HOST= # host of the api server in production mode - defaults to 'http://localhost:8080' in development mode\ No newline at end of filediff --git a/app/cli/api/clients.go b/app/cli/api/clients.goindex 2ba1c1fc..4c4a253b 100644--- a/app/cli/api/clients.go+++ b/app/cli/api/clients.go@@ -46,10 +46,6 @@ type authenticatedTransport struct {// RoundTrip executes a single HTTP transaction and adds a custom headerfunc (t *authenticatedTransport) RoundTrip(req *http.Request) (*http.Response, error) {- if os.Getenv("PLANDEX_ENV") == "development" {- req.Host = "api.localhost" // Set the Host header to api.localhost for local development- }-auth.SetAuthHeader(req)return t.underlyingTransport.RoundTrip(req)}@@ -59,10 +55,6 @@ type unauthenticatedTransport struct {}func (t *unauthenticatedTransport) RoundTrip(req *http.Request) (*http.Response, error) {- if os.Getenv("PLANDEX_ENV") == "development" {- req.Host = "api.localhost" // Set the Host header to api.localhost for local development- }-return t.underlyingTransport.RoundTrip(req)}diff --git a/app/cli/auth/account.go b/app/cli/auth/account.goindex a7fe2a13..063715ae 100644--- a/app/cli/auth/account.go+++ b/app/cli/auth/account.go@@ -202,7 +202,7 @@ func verifyEmail(email, host string) (bool, string, error) {return false, "", fmt.Errorf("error creating email verification: %v", apiErr.Msg)}- fmt.Println("✉️ You'll now receive a 6 character pin by email. It will be valid for 5 minutes.")+ fmt.Println("✉️ You'll now receive a 6 character pin by email. It will be valid for 10 minutes.")pin, err := term.GetUserPasswordInput("Please enter your pin:")diff --git a/app/cli/cmd/credits.go b/app/cli/cmd/credits.goindex aae5d725..705d5841 100644--- a/app/cli/cmd/credits.go+++ b/app/cli/cmd/credits.go@@ -40,8 +40,7 @@ func credits(cmd *cobra.Command, args []string) {}balance := org.CloudBillingFields.CreditsBalance- balanceFloat, _ := balance.Float64()- balanceStr := fmt.Sprintf("$%.4f", balanceFloat)+ balanceStr := fmt.Sprintf("$%s", balance.StringFixed(4))for i := 0; i < 2; i++ {if strings.HasSuffix(balanceStr, "0") {diff --git a/app/cli/cmd/credits_log.go b/app/cli/cmd/credits_log.goindex 44d3c164..0e144673 100644--- a/app/cli/cmd/credits_log.go+++ b/app/cli/cmd/credits_log.go@@ -98,6 +98,8 @@ func creditsLog(cmd *cobra.Command, args []string) {desc += "Started trial"case shared.CreditTypePurchase:desc += "Purchased credits"+ case shared.CreditTypeSwitch:+ desc += "Switched to Integrated Models mode"}}diff --git a/app/cli/go.mod b/app/cli/go.modindex 914fd671..e4cbeb43 100644--- a/app/cli/go.mod+++ b/app/cli/go.mod@@ -11,6 +11,7 @@ require (github.com/olekukonko/tablewriter v0.0.5github.com/plandex-ai/survey/v2 v2.3.7github.com/sashabaranov/go-openai v1.24.0+ github.com/shopspring/decimal v1.4.0github.com/spf13/cobra v1.8.0golang.org/x/term v0.19.0)@@ -37,7 +38,7 @@ require (github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirectgithub.com/muesli/cancelreader v0.2.2 // indirectgithub.com/rivo/uniseg v0.4.7 // indirect- github.com/shopspring/decimal v1.4.0 // indirect+ github.com/stripe/stripe-go/v79 v79.10.0 // indirectgithub.com/yuin/goldmark v1.6.0 // indirectgithub.com/yuin/goldmark-emoji v1.0.2 // indirectgolang.org/x/net v0.18.0 // indirectdiff --git a/app/cli/go.sum b/app/cli/go.sumindex 0cb8a28d..54db3076 100644--- a/app/cli/go.sum+++ b/app/cli/go.sum@@ -683,6 +683,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoOgithub.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=+github.com/stripe/stripe-go/v79 v79.10.0 h1:yaZ92m4gqxVlj/qFu2ImligxeKUvK5wVhTkXcetdx/8=+github.com/stripe/stripe-go/v79 v79.10.0/go.mod h1:cuH6X0zC8peY6f1AubHwgJ/fJSn2dh5pfiCr6CjyKVU=github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=@@ -822,6 +824,7 @@ golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdgolang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8=golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=+golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=diff --git a/app/docker-compose.yml b/app/docker-compose.ymlindex 2daf1023..e2102fee 100644--- a/app/docker-compose.yml+++ b/app/docker-compose.yml@@ -34,12 +34,7 @@ services:- plandex-networkdepends_on:- plandex-postgres- command:- [- "/bin/sh",- "-c",- "/scripts/wait-for-it.sh plandex-postgres:5432 -- ./plandex-server"- ]+ command: [ "/bin/sh", "-c", "/scripts/wait-for-it.sh plandex-postgres:5432 -- ./plandex-server" ]networks:plandex-network:diff --git a/app/server/db/auth_helpers.go b/app/server/db/auth_helpers.goindex d6fbc46b..d5ed3657 100644--- a/app/server/db/auth_helpers.go+++ b/app/server/db/auth_helpers.go@@ -73,12 +73,20 @@ func CreateEmailVerification(email string, userId, pinHash string) error {return nil}-// email verifications expire in 5 minutes-const emailVerificationExpirationMinutes = 5+// email verifications expire in 10 minutes+const emailVerificationExpirationMinutes = 10const InvalidOrExpiredPinError = "invalid or expired pin"func ValidateEmailVerification(email, pin string) (id string, err error) {+ return validateEmailVerification(email, pin, true, true)+}++func ValidateEmailPreviouslyVerified(email, pin string) (id string, err error) {+ return validateEmailVerification(email, pin, false, false)+}++func validateEmailVerification(email, pin string, enforceExpiration bool, errOnAlreadyVerified bool) (id string, err error) {pinHashBytes := sha256.Sum256([]byte(pin))pinHash := hex.EncodeToString(pinHashBytes[:])@@ -87,10 +95,15 @@ func ValidateEmailVerification(email, pin string) (id string, err error) {query := `SELECT id, auth_token_idFROM email_verificationsWHERE pin_hash = $1- AND email = $2- AND created_at > $3`+ AND email = $2`++ if enforceExpiration {+ query += ` AND created_at > $3`+ err = Conn.QueryRow(query, pinHash, email, time.Now().Add(-emailVerificationExpirationMinutes*time.Minute)).Scan(&id, &authTokenId)+ } else {+ err = Conn.QueryRow(query, pinHash, email).Scan(&id, &authTokenId)+ }- err = Conn.QueryRow(query, pinHash, email, time.Now().Add(-emailVerificationExpirationMinutes*time.Minute)).Scan(&id, &authTokenId)if err != nil {if err == sql.ErrNoRows {return "", errors.New(InvalidOrExpiredPinError)@@ -98,8 +111,10 @@ func ValidateEmailVerification(email, pin string) (id string, err error) {return "", fmt.Errorf("error validating email verification: %v", err)}- if authTokenId != nil {+ if authTokenId != nil && errOnAlreadyVerified {return "", errors.New("pin already verified")+ } else if authTokenId == nil && !errOnAlreadyVerified {+ return "", errors.New("pin not previously verified")}return id, nildiff --git a/app/server/db/db.go b/app/server/db/db.goindex f787d730..441863fe 100644--- a/app/server/db/db.go+++ b/app/server/db/db.go@@ -86,7 +86,7 @@ func migrationsUp(dir string) error {// Uncomment below (and update migration version) to reset migration state to a specific version after a failure// if os.Getenv("GOENV") == "development" {- // migrateVersion := 2024062100+ // migrateVersion := 2024082900// if err := m.Force(migrateVersion); err != nil {// return fmt.Errorf("error forcing migration version: %v", err)// }@@ -107,7 +107,7 @@ func migrationsUp(dir string) error {// Uncomment below and edit 'stepsBack' to go back a specific number of migrations// if os.Getenv("GOENV") == "development" {- // stepsBack := 2+ // stepsBack := 1// err = m.Steps(-stepsBack)// if err != nil {// return fmt.Errorf("error running down migrations: %v", err)diff --git a/app/server/db/user_helpers.go b/app/server/db/user_helpers.goindex 4cf0fd21..79a85b8d 100644--- a/app/server/db/user_helpers.go+++ b/app/server/db/user_helpers.go@@ -14,6 +14,10 @@ func GetUser(userId string) (*User, error) {err := Conn.Get(&user, "SELECT * FROM users WHERE id = $1", userId)if err != nil {+ if err == sql.ErrNoRows {+ return nil, nil+ }+return nil, fmt.Errorf("error getting user: %v", err)}diff --git a/app/server/email/verification.go b/app/server/email/verification.goindex bb57cc95..48196a6d 100644--- a/app/server/email/verification.go+++ b/app/server/email/verification.go@@ -14,8 +14,8 @@ func SendVerificationEmail(email string, pin string) error {if os.Getenv("GOENV") == "production" {// Production environment - send email using AWS SESsubject := "Your Plandex Pin"- htmlBody := fmt.Sprintf("<p>Hi there,</p><p>Welcome to Plandex!</p><p>Your pin is:<br><strong>%s</strong></p><p>It will be valid for the next 5 minutes. Please return to the terminal and paste in your pin.</p>", pin)- textBody := fmt.Sprintf("Hi there,\n\nWelcome to Plandex!\n\nYour pin is:\n%s\n\nIt will be valid for the next 5 minutes. Please return to the terminal and paste in your pin.", pin)+ htmlBody := fmt.Sprintf("<p>Hi there,</p><p>Welcome to Plandex!</p><p>Your pin is:<br><strong>%s</strong></p><p>It will be valid for the next 10 minutes. Please return to the terminal and paste in your pin.</p>", pin)+ textBody := fmt.Sprintf("Hi there,\n\nWelcome to Plandex!\n\nYour pin is:\n%s\n\nIt will be valid for the next 10 minutes. Please return to the terminal and paste in your pin.", pin)if os.Getenv("IS_CLOUD") == "" {return sendEmailViaSMTP(email, subject, htmlBody, textBody)diff --git a/app/server/go.mod b/app/server/go.modindex f4a1fcc3..30b9db7e 100644--- a/app/server/go.mod+++ b/app/server/go.mod@@ -26,6 +26,7 @@ require (github.com/pkoukk/tiktoken-go v0.1.7 // indirectgithub.com/rivo/uniseg v0.4.7 // indirectgithub.com/shopspring/decimal v1.4.0 // indirect+ github.com/stripe/stripe-go/v79 v79.10.0 // indirectgithub.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirectgo.uber.org/atomic v1.11.0 // indirectgolang.org/x/image v0.19.0 // indirectdiff --git a/app/server/go.sum b/app/server/go.sumindex 8a6d1e5f..4d75aef9 100644--- a/app/server/go.sum+++ b/app/server/go.sum@@ -95,10 +95,13 @@ github.com/smacker/go-tree-sitter v0.0.0-20240625050157-a31a98a7c0f6 h1:mtD4ESyOgithub.com/smacker/go-tree-sitter v0.0.0-20240625050157-a31a98a7c0f6/go.mod h1:q99oHDsbP0xRwmn7Vmob8gbSMNyvJ83OauXPSuHQuKE=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=+github.com/stripe/stripe-go/v79 v79.10.0 h1:yaZ92m4gqxVlj/qFu2ImligxeKUvK5wVhTkXcetdx/8=+github.com/stripe/stripe-go/v79 v79.10.0/go.mod h1:cuH6X0zC8peY6f1AubHwgJ/fJSn2dh5pfiCr6CjyKVU=github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk=github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=@@ -107,12 +110,20 @@ golang.org/x/image v0.19.0 h1:D9FX4QWkLfkeqaC62SonffIIuYdOk/UE2XKUBgRIBIQ=golang.org/x/image v0.19.0/go.mod h1:y0zrRqlQRWQ5PXaYCOMLTW2fpsxZ8Qh9I/ohnInJEys=golang.org/x/mod v0.11.0 h1:bUO06HqtnRcc/7l71XBe4WcqTZ+3AH1J59zWDDwLKgU=golang.org/x/mod v0.11.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=+golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=+golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=+golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=+golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=golang.org/x/tools v0.10.0 h1:tvDr/iQoUqNdohiYm0LmmKcBk+q86lb9EprIUFhHHGg=golang.org/x/tools v0.10.0/go.mod h1:UJwyiVBsOA2uwvK/e5OY3GTpDUJriEd+/YlqAwLPmyM=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=diff --git a/app/server/handlers/accounts.go b/app/server/handlers/accounts.goindex ce1066cc..3df4008c 100644--- a/app/server/handlers/accounts.go+++ b/app/server/handlers/accounts.go@@ -48,9 +48,11 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {return}+ var apiErr *shared.ApiError+// Ensure that rollback is attempted in case of failuredefer func() {- if err != nil {+ if err != nil || apiErr != nil {if rbErr := tx.Rollback(); rbErr != nil {log.Printf("transaction rollback error: %v\n", rbErr)} else {@@ -72,7 +74,7 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {token := res.TokenorgId := res.OrgId- _, apiErr := hooks.ExecHook(hooks.CreateAccount, hooks.HookParams{+ _, apiErr = hooks.ExecHook(hooks.CreateAccount, hooks.HookParams{User: user,OrgId: orgId,})diff --git a/app/server/handlers/auth_helpers.go b/app/server/handlers/auth_helpers.goindex 605b8218..103815eb 100644--- a/app/server/handlers/auth_helpers.go+++ b/app/server/handlers/auth_helpers.go@@ -6,6 +6,7 @@ import ("fmt""log""net/http"+ "os""plandex-server/db""plandex-server/types""strings"@@ -14,19 +15,31 @@ import ()func Authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *types.ServerAuth {+ return execAuthenticate(w, r, requireOrg, true)+}++func AuthenticateOptional(w http.ResponseWriter, r *http.Request, requireOrg bool) *types.ServerAuth {+ return execAuthenticate(w, r, requireOrg, false)+}++func execAuthenticate(w http.ResponseWriter, r *http.Request, requireOrg bool, raiseErr bool) *types.ServerAuth {log.Println("authenticating request")parsed, err := GetAuthHeader(r)if err != nil {log.Printf("error getting auth header: %v\n", err)- http.Error(w, "error getting auth header", http.StatusInternalServerError)+ if raiseErr {+ http.Error(w, "error getting auth header", http.StatusInternalServerError)+ }return nil}if parsed == nil {log.Println("no auth header")- http.Error(w, "no auth header", http.StatusUnauthorized)+ if raiseErr {+ http.Error(w, "no auth header", http.StatusUnauthorized)+ }return nil}@@ -48,7 +61,9 @@ func Authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *typeif err != nil {log.Printf("error getting user: %v\n", err)- http.Error(w, "error getting user", http.StatusInternalServerError)+ if raiseErr {+ http.Error(w, "error getting user", http.StatusInternalServerError)+ }return nil}@@ -61,7 +76,9 @@ func Authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *typeif parsed.OrgId == "" {log.Println("no org id")- http.Error(w, "no org id", http.StatusUnauthorized)+ if raiseErr {+ http.Error(w, "no org id", http.StatusUnauthorized)+ }return nil}@@ -70,7 +87,9 @@ func Authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *typeif err != nil {log.Printf("error validating org membership: %v\n", err)- http.Error(w, "error validating org membership", http.StatusInternalServerError)+ if raiseErr {+ http.Error(w, "error validating org membership", http.StatusInternalServerError)+ }return nil}@@ -80,7 +99,9 @@ func Authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *typeif err != nil {log.Printf("error getting invite for org user: %v\n", err)- http.Error(w, "error getting invite for org user", http.StatusInternalServerError)+ if raiseErr {+ http.Error(w, "error getting invite for org user", http.StatusInternalServerError)+ }return nil}@@ -91,13 +112,17 @@ func Authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *typeif err != nil {log.Printf("error accepting invite: %v\n", err)- http.Error(w, "error accepting invite", http.StatusInternalServerError)+ if raiseErr {+ http.Error(w, "error accepting invite", http.StatusInternalServerError)+ }return nil}} else {log.Println("user is not a member of the org")- http.Error(w, "not a member of org", http.StatusUnauthorized)+ if raiseErr {+ http.Error(w, "not a member of org", http.StatusUnauthorized)+ }return nil}}@@ -107,7 +132,9 @@ func Authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *typeif err != nil {log.Printf("error getting user permissions: %v\n", err)- http.Error(w, "error getting user permissions", http.StatusInternalServerError)+ if raiseErr {+ http.Error(w, "error getting user permissions", http.StatusInternalServerError)+ }return nil}@@ -133,16 +160,20 @@ func GetAuthHeader(r *http.Request) (*shared.AuthHeader, error) {// check for a cookie as well for ui requestsif authHeader == "" {+ log.Println("no auth header - checking for cookie")+// Try to get auth token from a cookie as a fallbackcookie, err := r.Cookie("authToken")if err != nil {if err == http.ErrNoCookie {+ log.Println("no auth cookie")return nil, nil}return nil, fmt.Errorf("error retrieving auth cookie: %v", err)}// Use the token from the cookie as the fallback authorization headerauthHeader = cookie.Value+ log.Println("got auth header from cookie")}if authHeader == "" {@@ -174,15 +205,85 @@ func GetAuthHeader(r *http.Request) (*shared.AuthHeader, error) {return &parsed, nil}-func SetAuthCookieIfBrowser(w http.ResponseWriter, r *http.Request, user *db.User, token, orgId string) error {- isBrowser := false+func ClearAuthCookieIfBrowser(w http.ResponseWriter, r *http.Request) error {acceptHeader := r.Header.Get("Accept")- if strings.Contains(acceptHeader, "text/html") {- isBrowser = true+ if acceptHeader == "" {+ // no accept header, not a browser request+ return nil}- if !isBrowser {++ // Check for existing auth cookie+ _, err := r.Cookie("authToken")+ if err == http.ErrNoCookie {+ // No auth cookie, nothing to clearreturn nil}+ if err != nil {+ return fmt.Errorf("error retrieving auth cookie: %v", err)+ }++ // Clear the authToken cookie+ http.SetCookie(w, &http.Cookie{+ Name: "authToken",+ Path: "/",+ Value: "",+ MaxAge: -1,+ Secure: os.Getenv("GOENV") != "development",+ HttpOnly: true,+ SameSite: http.SameSiteLaxMode,+ })++ return nil+}++func ClearAccountFromCookies(w http.ResponseWriter, r *http.Request, userId string) error {+ // Get stored accounts+ storedAccounts, err := GetAccountsFromCookie(r)+ if err != nil {+ return fmt.Errorf("error getting accounts from cookie: %v", err)+ }++ // Remove the account with the given userId+ for i, account := range storedAccounts {+ if account.UserId == userId {+ storedAccounts = append(storedAccounts[:i], storedAccounts[i+1:]...)+ break+ }+ }++ // Marshal the updated accounts+ updatedAccountsBytes, err := json.Marshal(storedAccounts)+ if err != nil {+ return fmt.Errorf("error marshalling updated accounts: %v", err)+ }++ // Encode to base64+ encodedAccounts := base64.StdEncoding.EncodeToString(updatedAccountsBytes)++ // Set the updated accounts cookie+ http.SetCookie(w, &http.Cookie{+ Name: "accounts",+ Path: "/",+ Value: encodedAccounts,+ Secure: os.Getenv("GOENV") != "development",+ HttpOnly: true,+ SameSite: http.SameSiteLaxMode,+ })++ return nil+}++func SetAuthCookieIfBrowser(w http.ResponseWriter, r *http.Request, user *db.User, token, orgId string) error {+ log.Println("setting auth cookie if browser")++ acceptHeader := r.Header.Get("Accept")+ if acceptHeader == "" {+ // no accept header, not a browser request+ log.Println("not a browser request")+ return nil+ }++ log.Println("is browser - setting auth cookie")if token == "" {authHeader, err := GetAuthHeader(r)@@ -213,10 +314,11 @@ func SetAuthCookieIfBrowser(w http.ResponseWriter, r *http.Request, user *db.Usehttp.SetCookie(w, &http.Cookie{Name: "authToken",+ Path: "/",Value: "Bearer " + token,- Secure: true,+ Secure: os.Getenv("GOENV") != "development",HttpOnly: true,- SameSite: http.SameSiteStrictMode,+ SameSite: http.SameSiteLaxMode,})storedAccounts, err := GetAccountsFromCookie(r)@@ -257,10 +359,11 @@ func SetAuthCookieIfBrowser(w http.ResponseWriter, r *http.Request, user *db.Usehttp.SetCookie(w, &http.Cookie{Name: "accounts",+ Path: "/",Value: accounts,- Secure: true,+ Secure: os.Getenv("GOENV") != "development",HttpOnly: true,- SameSite: http.SameSiteStrictMode,+ SameSite: http.SameSiteLaxMode,})return nildiff --git a/app/server/handlers/orgs.go b/app/server/handlers/orgs.goindex 98284bde..cfd8c65c 100644--- a/app/server/handlers/orgs.go+++ b/app/server/handlers/orgs.go@@ -81,6 +81,8 @@ func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {return}+ var apiErr *shared.ApiError+// start a transactiontx, err := db.Conn.Beginx()if err != nil {@@ -91,7 +93,7 @@ func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {// Ensure that rollback is attempted in case of failuredefer func() {- if err != nil {+ if err != nil || apiErr != nil {if rbErr := tx.Rollback(); rbErr != nil {log.Printf("transaction rollback error: %v\n", rbErr)} else {@@ -130,7 +132,7 @@ func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {}}- _, apiErr := hooks.ExecHook(hooks.CreateOrg, hooks.HookParams{+ _, apiErr = hooks.ExecHook(hooks.CreateOrg, hooks.HookParams{User: auth.User,Tx: tx,diff --git a/app/server/handlers/sessions.go b/app/server/handlers/sessions.goindex 6e218bc6..fe47190f 100644--- a/app/server/handlers/sessions.go+++ b/app/server/handlers/sessions.go@@ -11,6 +11,7 @@ import ("plandex-server/email""strings"+ "github.com/davecgh/go-spew/spew""github.com/plandex/plandex/shared")@@ -34,6 +35,51 @@ func CreateEmailVerificationHandler(w http.ResponseWriter, r *http.Request) {}req.Email = strings.ToLower(req.Email)+ var hasAccount bool+ if req.UserId == "" {+ user, err := db.GetUserByEmail(req.Email)++ if err != nil {+ log.Printf("Error getting user: %v\n", err)+ http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)+ return+ }++ hasAccount = user != nil+ } else {+ hasAccount = true++ user, err := db.GetUser(req.UserId)++ if err != nil {+ log.Printf("Error getting user: %v\n", err)+ http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if user == nil {+ log.Printf("User not found for id: %v\n", req.UserId)+ http.Error(w, "User not found", http.StatusNotFound)+ return+ }++ if user.Email != req.Email {+ log.Printf("User email does not match for id: %v\n", req.UserId)+ http.Error(w, "User email does not match", http.StatusBadRequest)+ return+ }+ }++ if req.RequireUser && !hasAccount {+ log.Printf("User not found for email: %v\n", req.Email)+ http.Error(w, "User not found", http.StatusNotFound)+ return+ } else if req.RequireNoUser && hasAccount {+ log.Printf("User already exists for email: %v\n", req.Email)+ http.Error(w, "User already exists", http.StatusConflict)+ return+ }+// create pin - 6 alphanumeric characterspinBytes, err := shared.GetRandomAlphanumeric(6)if err != nil {@@ -63,21 +109,6 @@ func CreateEmailVerificationHandler(w http.ResponseWriter, r *http.Request) {return}- var hasAccount bool- if req.UserId == "" {- user, err := db.GetUserByEmail(req.Email)-- if err != nil {- log.Printf("Error getting user: %v\n", err)- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)- return- }-- hasAccount = user != nil- } else {- hasAccount = true- }-res := shared.CreateEmailVerificationResponse{HasAccount: hasAccount,}@@ -115,6 +146,8 @@ func CheckEmailPinHandler(w http.ResponseWriter, r *http.Request) {}req.Email = strings.ToLower(req.Email)+ spew.Dump(req)+_, err = db.ValidateEmailVerification(req.Email, req.Pin)if err != nil {@@ -165,7 +198,7 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {return}- if user != nil && user.IsTrial {+ if user.IsTrial {log.Printf("Trial user can't sign in: %v\n", req.Email)http.Error(w, "Trial user can't sign in", http.StatusForbidden)return@@ -257,8 +290,14 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {return}- // org still needs to be selected- err = SetAuthCookieIfBrowser(w, r, user, token, "")+ // with a single org, set the orgId in the cookie+ // otherwise, the user will be prompted to select an org+ var orgId string+ if len(orgs) == 1 {+ orgId = orgs[0].Id+ }++ err = SetAuthCookieIfBrowser(w, r, user, token, orgId)if err != nil {log.Printf("Error setting auth cookie: %v\n", err)http.Error(w, "Error setting auth cookie: "+err.Error(), http.StatusInternalServerError)@@ -286,5 +325,21 @@ func SignOutHandler(w http.ResponseWriter, r *http.Request) {return}+ err = ClearAuthCookieIfBrowser(w, r)++ if err != nil {+ log.Printf("Error clearing auth cookie: %v\n", err)+ http.Error(w, "Error clearing auth cookie: "+err.Error(), http.StatusInternalServerError)+ return+ }++ err = ClearAccountFromCookies(w, r, auth.User.Id)++ if err != nil {+ log.Printf("Error clearing account from cookies: %v\n", err)+ http.Error(w, "Error clearing account from cookies: "+err.Error(), http.StatusInternalServerError)+ return+ }+log.Println("Successfully signed out")}diff --git a/app/server/main.go b/app/server/main.goindex d15348fd..e8b55c9f 100644--- a/app/server/main.go+++ b/app/server/main.go@@ -23,7 +23,13 @@ func main() {}r := mux.NewRouter()- apiRouter := r.Host("api." + domain).Subrouter()++ var apiRouter *mux.Router+ if os.Getenv("GOENV") == "development" {+ apiRouter = r+ } else {+ apiRouter = r.Host("api." + domain).Subrouter()+ }setup.MustLoadIp()setup.MustInitDb()diff --git a/app/server/setup/setup.go b/app/server/setup/setup.goindex 29070243..b4c31375 100644--- a/app/server/setup/setup.go+++ b/app/server/setup/setup.go@@ -1,7 +1,7 @@package setupimport (- "fmt"+ "context""log""net/http""os"@@ -46,6 +46,9 @@ func StartServer(r *mux.Router) {log.Println("In development mode.")}+ // Ensure database connection is closed+ defer db.Conn.Close()+// Get externalPort from the environment variable or default to 8080externalPort := os.Getenv("PORT")if externalPort == "" {@@ -72,33 +75,43 @@ func StartServer(r *mux.Router) {}).Handler(r)}- go startServer(externalPort, corsHandler)+ server := &http.Server{+ Addr: ":" + externalPort,+ Handler: corsHandler,+ }++ go func() {+ if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {+ log.Fatalf("Failed to start server: %v", err)+ }+ }()+log.Println("Started server on port " + externalPort)+ // Capture SIGTERM and SIGINT signalssigTermChan := make(chan os.Signal, 1)- signal.Notify(sigTermChan, syscall.SIGTERM)+ signal.Notify(sigTermChan, syscall.SIGTERM, syscall.SIGINT)- go func() {- <-sigTermChan-- for {- l := plan.NumActivePlans()- if l == 0 {- break- }- log.Printf("Waiting for %d active plans to finish...\n", l)- time.Sleep(1 * time.Second)- }+ <-sigTermChan+ log.Println("Shutting down server gracefully...")- os.Exit(0)- }()+ // Context with a 5-second timeout to allow ongoing requests to finish+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()- select {}-}+ if err := server.Shutdown(ctx); err != nil {+ log.Fatalf("Server forced to shutdown: %v", err)+ }-func startServer(port string, handler http.Handler) {- err := http.ListenAndServe(fmt.Sprintf(":%s", port), handler)- if err != nil {- log.Fatalf("Failed to start server on port %s: %v", port, err)+ // Wait for active plans to complete+ for {+ l := plan.NumActivePlans()+ if l == 0 {+ break+ }+ log.Printf("Waiting for %d active plans to finish...\n", l)+ time.Sleep(1 * time.Second)}++ log.Println("Shutdown complete")}diff --git a/app/shared/data_models.go b/app/shared/data_models.goindex c340318f..9f280f91 100644--- a/app/shared/data_models.go+++ b/app/shared/data_models.go@@ -365,7 +365,14 @@ type CloudBillingFields struct {NotifyThreshold decimal.Decimal `json:"notifyThreshold"`MaxThresholdPerMonth decimal.Decimal `json:"maxThresholdPerMonth"`BillingCycleStartedAt time.Time `json:"billingCycleStartedAt"`- TrialPaid bool `json:"trialPaid"`++ ChangedBillingMode bool `json:"changedBillingMode"`+ TrialPaid bool `json:"trialPaid"`++ StripeSubscriptionId *string `json:"stripeSubscriptionId"`+ SubscriptionStatus *string `json:"subscriptionStatus"`+ SubscriptionPausedAt *time.Time `json:"subscriptionPausedAt"`+ StripePaymentMethod *string `json:"stripePaymentMethod"`}type CreditsTransactionType string@@ -381,6 +388,7 @@ const (CreditTypeTrial CreditType = "trial"CreditTypeGrant CreditType = "grant"CreditTypePurchase CreditType = "purchase"+ CreditTypeSwitch CreditType = "switch")type DebitType string@@ -394,9 +402,9 @@ type CreditsTransaction struct {Id string `json:"id"`OrgId string `json:"orgId"`OrgName string `json:"orgName"`- UserId string `json:"userId"`- UserEmail string `json:"userEmail"`- UserName string `json:"userName"`+ UserId *string `json:"userId"`+ UserEmail *string `json:"userEmail"`+ UserName *string `json:"userName"`TransactionType CreditsTransactionType `json:"transactionType"`Amount decimal.Decimal `json:"amount"`StartBalance decimal.Decimal `json:"startBalance"`@@ -410,7 +418,8 @@ type CreditsTransaction struct {CreditStripeCustomerId *string `json:"creditStripeCustomerId,omitempty"`CreditStripeSubscriptionId *string `json:"creditStripeSubscriptionId,omitempty"`CreditStripePriceId *string `json:"creditStripePriceId,omitempty"`- CreditStripePaymentId *string `json:"creditStripePaymentId,omitempty"`+ CreditStripeInvoiceId *string `json:"creditStripeInvoiceId,omitempty"`+ CreditStripePaymentMethod *string `json:"creditStripePaymentMethod,omitempty"`DebitType *DebitType `json:"debitType,omitempty"`DebitTokens *int `json:"debitTokens,omitempty"`DebitBaseAmount *decimal.Decimal `json:"debitBaseAmount,omitempty"`diff --git a/app/shared/go.mod b/app/shared/go.modindex c4384fb6..53032a7a 100644--- a/app/shared/go.mod+++ b/app/shared/go.mod@@ -18,5 +18,6 @@ require (github.com/olekukonko/tablewriter v0.0.5github.com/sashabaranov/go-openai v1.24.0github.com/shopspring/decimal v1.4.0+ github.com/stripe/stripe-go/v79 v79.10.0golang.org/x/image v0.17.0)diff --git a/app/shared/go.sum b/app/shared/go.sumindex 245cde6d..731e6d47 100644--- a/app/shared/go.sum+++ b/app/shared/go.sum@@ -1,14 +1,10 @@+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsq0=-github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=-github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=-github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=-github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=@@ -18,21 +14,31 @@ github.com/pkoukk/tiktoken-go v0.1.6 h1:JF0TlJzhTbrI30wCvFuiw6FzP2+/bR+FIxUdgEAcgithub.com/pkoukk/tiktoken-go v0.1.6/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYdewGl6qVatpg=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=-github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=-github.com/sashabaranov/go-openai v1.19.4 h1:GbaDiqvgYCabyqzuIbcEeT6/ZX1nVfur+++oTBfOgks=-github.com/sashabaranov/go-openai v1.19.4/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=-github.com/sashabaranov/go-openai v1.21.0 h1:isAf3zPSD3VLd0pC2/2Q6ZyRK7jzPAaz+X3rjsviaYQ=-github.com/sashabaranov/go-openai v1.21.0/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=github.com/sashabaranov/go-openai v1.24.0 h1:4H4Pg8Bl2RH/YSnU8DYumZbuHnnkfioor/dtNlB20D4=github.com/sashabaranov/go-openai v1.24.0/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+github.com/stripe/stripe-go/v79 v79.10.0 h1:yaZ92m4gqxVlj/qFu2ImligxeKUvK5wVhTkXcetdx/8=+github.com/stripe/stripe-go/v79 v79.10.0/go.mod h1:cuH6X0zC8peY6f1AubHwgJ/fJSn2dh5pfiCr6CjyKVU=golang.org/x/image v0.17.0 h1:nTRVVdajgB8zCMZVsViyzhnMKPwYeroEERRC64JuLco=golang.org/x/image v0.17.0/go.mod h1:4yyo5vMFQjVjUcVk4jEQcU9MGy/rulF5WvUILseCM2E=+golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 h1:ADo5wSpq2gqaCGQWzk7S5vd//0iyyLeAratkEoG5dLE=+golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=+golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=+golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=+golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/app/shared/req_res.go b/app/shared/req_res.goindex f35e5a4b..7c1b0112 100644--- a/app/shared/req_res.go+++ b/app/shared/req_res.go@@ -7,8 +7,10 @@ import ()type CreateEmailVerificationRequest struct {- Email string `json:"email"`- UserId string `json:"userId"`+ Email string `json:"email"`+ UserId string `json:"userId"`+ RequireUser bool `json:"requireUser"`+ RequireNoUser bool `json:"requireNoUser"`}type CreateEmailVerificationResponse struct {@@ -250,15 +252,10 @@ type StartTrialRequest struct {}type StartTrialResponse struct {- UserId string `json:"userId"`- Token string `json:"token"`- OrgId string `json:"orgId"`- StripeCustomerId string `json:"stripeCustomerId"`- TrialPaymentAmountCents int `json:"trialPaymentAmount"`-}--type TrialPaymentRequest struct {- StripeToken string `json:"stripeToken"`+ UserId string `json:"userId"`+ Token string `json:"token"`+ OrgId string `json:"orgId"`+ StripeCustomerId string `json:"stripeCustomerId"`}type CreditsLogRequest struct {diff --git a/docs/docs/environment-variables.md b/docs/docs/environment-variables.mdindex 6b49722a..d301442a 100644--- a/docs/docs/environment-variables.md+++ b/docs/docs/environment-variables.md@@ -9,6 +9,13 @@ This is an overview of all the environment variables that can be used with Pland## CLI+### General++```bash+PLANDEX_ENV=development # Set this to 'development' to default to the local development server instead of Plandex Cloud when working on Plandex itself.+PLANDEX_API_HOST= # Defaults to 'http://localhost:8080' if PLANDEX_ENV is development, otherwise it's 'https://api.plandex.ai'—override this to use a different host.+```+### LLM Providers```bash@@ -32,8 +39,6 @@ PLANDEX_SKIP_UPGRADE= # Set this to '1' to skip the auto-upgrade check when runnCheck out the [Development Guide](./development.md) for more details.```bash-PLANDEX_ENV=development # Set this to 'development' to default to the local development server instead of Plandex Cloud when working on Plandex itself.-PLANDEX_API_HOST= # Defaults to http://localhost:8080 if PLANDEX_ENV is development, otherwise it's https://api.plandex.ai—override this to use a different host.PLANDEX_OUT_DIR=/usr/local/bin # Where the development binary should be output when using dev.shPLANDEX_DEV_CLI_OUT_DIR=/usr/local/bin # Where the development binary should be output when using dev.shPLANDEX_DEV_CLI_NAME=plandex-dev # The name of the development binary when using dev.sh@@ -50,6 +55,7 @@ Check out the [Self-Hosting Guide](./hosting/self-hosting.md) for more details.```bashGOENV=development # Whether to run in development or production mode. Must be 'development' or 'production'PLANDEX_BASE_DIR= # The base directory to read and write files. Defaults to '$HOME/plandex-server' in development mode, '/plandex-server' in production.+API_HOST= # The host the API server listens on. Defaults to 'http://localhost:$PORT'. In production mode, should be a host like 'https://api.your-domain.ai'.PORT=8080 # The port the server listens on. Defaults to 8080.```@@ -75,6 +81,13 @@ If you're *not* using docker-compose, you'll need a `DATABASE_URL` environment vDATABASE_URL=postgres://plandex:<password>@<host>:<port>/plandex?sslmode=disable```+If you're running in production mode, you'll also need to set `API_HOST` to the host the API server is running on.++```bash+API_HOST= https://api.your-domain.ai # The host of the API server in production mode. Defaults to 'http://localhost:$PORT' in development mode.+```++### SMTPIf you're running in production mode (with `GOENV=production`, typically on a remote server), you'll need SMTP credentials:diff --git a/docs/docs/hosting/self-hosting.md b/docs/docs/hosting/self-hosting.mdindex 48b34d49..e8774fcc 100644--- a/docs/docs/hosting/self-hosting.md+++ b/docs/docs/hosting/self-hosting.md@@ -94,7 +94,13 @@ You'll also need a `DATABASE_URL`:export DATABASE_URL=postgres://user:password@host:5432/plandex # replace with your own database URL```-If you're running in production mode, you'll need to connect to SMTP to send emails. Set the following environment variables:+If you're running in production mode, set `API_HOST` to the host the API server is running on:++```bash+export API_HOST=api.your-domain.ai+```++In production mode, you'll also need to connect to SMTP to send emails. Set the following environment variables:```bashexport SMTP_HOST=smtp.example.com@@ -125,6 +131,7 @@ docker run -p 8080:8080 \-v ~/plandex-server:/plandex-server \-e DATABASE_URL \-e GOENV \+ -e API_HOST \-e SMTP_HOST \-e SMTP_PORT \-e SMTP_USER \@@ -132,7 +139,7 @@ docker run -p 8080:8080 \plandex-server```-The SMTP environment variables above are only required if you're running in [production mode](#development-vs-production).+The API_HOST and SMTP environment variables above are only required if you're running in [production mode](#development-vs-production).### Run From Source@@ -144,6 +151,8 @@ cd plandex/VERSION=$(cat app/server/version.txt) # or use the version you wantgit checkout server/v$VERSIONcd app/server+export GOENV=development # or production+export DATABASE_URL=postgres://user:password@host:5432/plandex # replace with your own database URLexport PLANDEX_BASE_DIR=~/plandex-server # or another directory where you want to store filesgo run main.go```