From 078ec328aa4da5c2e60cd8077153f4fd0c9bc33b Mon Sep 17 00:00:00 2001 From: Daniel Villalobos Date: Tue, 24 Nov 2026 17:45:29 +0100 Subject: [PATCH 1/3] Sign in with ChatGPT from Settings when Refract runs on this computer --- CHANGELOG.md | 2 + README.md | 6 +- cmd/refract/api.go | 49 +++++++ cmd/refract/api_test.go | 53 +++++++- cmd/refract/hosts.go | 13 ++ cmd/refract/login.go | 5 +- cmd/refract/main.go | 1 + internal/siwc/login.go | 11 +- internal/siwc/logins.go | 181 +++++++++++++++++++++++++ internal/siwc/logins_test.go | 218 ++++++++++++++++++++++++++++++ internal/siwc/session.go | 33 ++++- macos/README.md | 7 +- web/src/ChatGPTSignIn.tsx | 145 ++++++++++++++++++++ web/src/Settings.tsx | 28 +++- web/src/api.ts | 7 +- web/src/lib/chatgpt-login.test.ts | 23 ++++ web/src/lib/chatgpt-login.ts | 29 ++++ web/src/locales/es/app.ts | 23 ++++ web/src/locales/es/assistant.ts | 8 +- 19 files changed, 816 insertions(+), 26 deletions(-) create mode 100644 internal/siwc/logins.go create mode 100644 internal/siwc/logins_test.go create mode 100644 web/src/ChatGPTSignIn.tsx create mode 100644 web/src/lib/chatgpt-login.test.ts create mode 100644 web/src/lib/chatgpt-login.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index dc30280..1144e51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Notable changes to Refract. The format follows [Keep a Changelog](https://keepac ### Added +- **Sign in with ChatGPT** in Settings → Assistant when Refract runs on your own computer (it listens on loopback): the server runs the sign-in, waits for ChatGPT's redirect on `127.0.0.1:1455` and stores the credential, with no terminal or file. The desktop app opens the sign-in in the default browser. Uploading a credential file from `refract login` still works, and is the way for servers elsewhere. - Refract can read its encryption key, OpenID Connect client secret, SMTP URL and OpenAlex API key from files using the corresponding `REFRACT_*_FILE` variables. `refract users` and `refract local` also accept the encryption key from a file, and the systemd unit starts Refract directly with a systemd credential. - `REFRACT_OUTBOUND` (`any` by default, or `public`) chooses whether AI provider base URLs and git remotes may reach loopback and private networks. `public` does what `REFRACT_MODE=saas` did for outbound requests, and checks at startup that git is 2.37 or later. With `public`, provider requests and redirects must be https, and link-local git remotes are refused in every mode. `REFRACT_MODE=saas` no longer changes it. - Refract finds `tectonic`, `synctex`, `rg` and `git` in a bundled `libexec/refract` folder next to the executable (the executable's own folder on Windows) before the `PATH`, and runs them by absolute path; a bundled Git uses only its own helpers and templates. `REFRACT_TECTONIC_BIN`, `REFRACT_SYNCTEX_BIN`, `REFRACT_RG_BIN` and `REFRACT_GIT_BIN` override the lookup. The startup log shows where each was found, and the web app shows one notice when a tool is missing, saying what won't work, on whichever page opens first. On macOS and Linux a bundled tool in a folder that others can write, or that another user owns, is ignored. The same checks cover bundled Git's helpers and templates. @@ -17,6 +18,7 @@ Notable changes to Refract. The format follows [Keep a Changelog](https://keepac ### Changed +- `refract login` points to **Settings → Assistant** and no longer tells you to set `REFRACT_ALLOWED_SUBJECT`, which stays optional. When plan usage isn't granted, the app says to sign in again instead of naming the command. - Sign in with ChatGPT is stricter: the sign-in address no longer carries a token, token responses and refreshed ID tokens are verified (a rotation cut short by a restart or a key-server outage resumes without a new login), the local callback ignores stray or malformed requests, a failed code exchange reuses the issued registration, sign-out retries revocation once, and ChatGPT requests don't follow redirects or retry a usage limit. - A failed database upgrade now says that nothing was changed and where the copy from before the upgrade is (`refract.db.pre-upgrade`). - `refract local` keeps its secret key in the system credential store (macOS Keychain, Secret Service on Linux, Windows Credential Manager), one item per data folder, and falls back to an owner-only `secret.key` in the data folder when no store can be reached, saying so in the log. An existing `secret.key` is kept. If the key is gone from the store for a data folder that was used before, Refract logs that stored credentials can't be read instead of failing. diff --git a/README.md b/README.md index 9b199bc..cb87b9c 100644 --- a/README.md +++ b/README.md @@ -456,7 +456,11 @@ Each user connects their own AI in **Settings → Assistant**. Every connected m ### ChatGPT plan -Refract can use a ChatGPT subscription through "Sign in with ChatGPT", so requests count against your plan instead of an API bill. The sign-in runs on your own computer, because ChatGPT only accepts it from a local address: +Refract can use a ChatGPT subscription through "Sign in with ChatGPT", so requests count against your plan instead of an API bill. The sign-in runs on your own computer, because ChatGPT only accepts it from a local address. + +**Refract on your own computer** (the desktop app, `refract local`, `make dev`, or any server listening on `127.0.0.1` or `::1`): open **Settings → Assistant**, choose **Sign in with ChatGPT** and finish in the browser that opens. Refract waits for ChatGPT on `127.0.0.1:1455` and stores the credential itself; no file is written. One sign-in runs at a time per server, and it stops after 10 minutes or when you cancel it. A server listening on another address, including a container that listens on all its interfaces, doesn't offer the button. + +**Refract on a server:** 1. [Install the CLI](#install-the-cli) on your own computer, or run `make login` from a clone. 2. Run `refract login` and choose **Continue with ChatGPT** in the browser that opens. diff --git a/cmd/refract/api.go b/cmd/refract/api.go index 5db8a16..b3b40f6 100644 --- a/cmd/refract/api.go +++ b/cmd/refract/api.go @@ -34,6 +34,11 @@ type api struct { canSignOut bool // REFRACT_AUTH=builtin: Refract keeps the session + // logins runs the ChatGPT sign-in inside the server. Only set when it + // listens on loopback: the browser is then on this computer and OpenAI's + // redirect to 127.0.0.1 reaches us. + logins *siwc.Logins + missingTools []string // external programs not found at startup (internal/tools), for the UI notice providers *providers.Store // users' API-key providers @@ -95,6 +100,11 @@ func (a *api) routes(rt *router) { if a.mode.ChatGPT() { // elsewhere these fall through to a 404 rt.user("POST /api/chatgpt/credentials", a.importCredentials) rt.user("POST /api/chatgpt/signout", a.signOut) + if a.logins != nil { + rt.user("POST /api/chatgpt/login", a.startLogin) + rt.user("GET /api/chatgpt/login", a.loginStatus) + rt.user("DELETE /api/chatgpt/login", a.cancelLogin) + } } rt.user("POST /api/chatgpt/welcome-seen", a.welcomeSeen) rt.user("GET /api/models", a.models) @@ -155,9 +165,48 @@ func (a *api) status(w http.ResponseWriter, r *http.Request) { "welcome_seen": seen, "manage_usage": siwc.ManageUsage, "default_model": a.model, + "sign_in_here": a.mode.ChatGPT() && a.logins != nil, }) } +// startLogin begins the in-server ChatGPT sign-in and returns the authorize +// URL for the browser to open. {"new": true} registers another account. +func (a *api) startLogin(w http.ResponseWriter, r *http.Request) { + var in struct { + New bool `json:"new"` + } + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<10)).Decode(&in); err != nil && !errors.Is(err, io.EOF) { + httpError(w, err, http.StatusBadRequest) + return + } + u, err := a.logins.Start(r.Context(), a.forUser(r.Context()).session, in.New) + switch { + case errors.Is(err, siwc.ErrLoginBusy): + httpError(w, err, http.StatusConflict) + case err != nil: + writeLoginFailure(w, a.logins.Status(requestUser(r.Context()))) + default: + writeJSON(w, map[string]string{"url": u}) + } +} + +func (a *api) loginStatus(w http.ResponseWriter, r *http.Request) { + writeJSON(w, a.logins.Status(requestUser(r.Context()))) +} + +func (a *api) cancelLogin(w http.ResponseWriter, r *http.Request) { + a.logins.Cancel(requestUser(r.Context())) + w.WriteHeader(http.StatusNoContent) +} + +// writeLoginFailure answers a sign-in that failed before it could start +// (the callback port is taken) with its state, for the page to explain. +func writeLoginFailure(w http.ResponseWriter, st siwc.LoginState) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusServiceUnavailable) + json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"kind": st.Kind, "message": st.Message}}) +} + func (a *api) importCredentials(w http.ResponseWriter, r *http.Request) { raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<10)) if err != nil { diff --git a/cmd/refract/api_test.go b/cmd/refract/api_test.go index b9650d2..573f177 100644 --- a/cmd/refract/api_test.go +++ b/cmd/refract/api_test.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "encoding/json" + "net" "net/http" "net/http/httptest" "path/filepath" @@ -39,6 +40,12 @@ func newAIServerDB(t *testing.T, m mode.Mode) (http.Handler, *sql.DB) { // newAIServerOutbound is newAIServerDB with REFRACT_OUTBOUND chosen apart // from the mode. func newAIServerOutbound(t *testing.T, m mode.Mode, publicOnly bool) (http.Handler, *sql.DB) { + t.Helper() + return newAIServerWith(t, m, func(a *api) { a.publicOnly = publicOnly }) +} + +// newAIServerWith is newAIServerDB with the api adjusted by set. +func newAIServerWith(t *testing.T, m mode.Mode, set func(*api)) (http.Handler, *sql.DB) { t.Helper() db, err := store.Open(filepath.Join(t.TempDir(), "t.db")) if err != nil { @@ -59,7 +66,8 @@ func newAIServerOutbound(t *testing.T, m mode.Mode, publicOnly bool) (http.Handl t.Fatal(err) } - a := &api{base: &siwc.Session{DB: db, Key: key}, mode: m, publicOnly: publicOnly, providers: &providers.Store{DB: db, Key: key}, usage: &usage.Recorder{DB: db}} + a := &api{base: &siwc.Session{DB: db, Key: key}, mode: m, providers: &providers.Store{DB: db, Key: key}, usage: &usage.Recorder{DB: db}} + set(a) mux := http.NewServeMux() a.routes(&router{mux: mux, acc: &access.Checker{DB: db}}) mux.HandleFunc("/api/", http.NotFound) // as in main @@ -125,6 +133,49 @@ func TestSelfHostKeepsChatGPT(t *testing.T) { } } +// The in-server ChatGPT sign-in exists only where the server listens on +// loopback (a.logins set) and the plan is offered; the status says which. +func TestSignInHereRoutes(t *testing.T) { + type status struct { + SignInHere bool `json:"sign_in_here"` + } + for _, c := range []struct { + name string + m mode.Mode + logins bool + want bool + }{ + {"loopback", mode.SelfHost, true, true}, + {"reachable from other computers", mode.SelfHost, false, false}, + {"hosted service", mode.SaaS, true, false}, + } { + t.Run(c.name, func(t *testing.T) { + h, _ := newAIServerWith(t, c.m, func(a *api) { + if c.logins { + a.logins = &siwc.Logins{} + } + }) + var st status + if call(t, h, "GET", "/api/chatgpt/status", &st); st.SignInHere != c.want { + t.Errorf("sign_in_here = %v, want %v", st.SignInHere, c.want) + } + code := call(t, h, "GET", "/api/chatgpt/login", nil) + if want := map[bool]int{true: http.StatusOK, false: http.StatusNotFound}[c.want]; code != want { + t.Errorf("GET /api/chatgpt/login = %d, want %d", code, want) + } + }) + } +} + +func TestLoginsOnlyOnLoopback(t *testing.T) { + for addr, want := range map[string]bool{"127.0.0.1:8080": true, "[::1]:8080": true, "0.0.0.0:8080": false, "192.168.1.5:8080": false} { + a, _ := net.ResolveTCPAddr("tcp", addr) + if got := loginsFor(a) != nil; got != want { + t.Errorf("%s: in-server sign-in = %v, want %v", addr, got, want) + } + } +} + // GET /api/usage: the signed-in account's tokens per model from since, most // used first; nobody else's. func TestUsage(t *testing.T) { diff --git a/cmd/refract/hosts.go b/cmd/refract/hosts.go index b7b4df7..648c701 100644 --- a/cmd/refract/hosts.go +++ b/cmd/refract/hosts.go @@ -10,6 +10,8 @@ import ( "strconv" "strings" "time" + + "github.com/ponytojas/Refract/internal/siwc" ) // listenAddr is REFRACT_ADDR, or 127.0.0.1:8080 without it: this computer @@ -200,3 +202,14 @@ func newServer(mux http.Handler, hosts hostPolicy) *http.Server { DisableGeneralOptionsHandler: true, } } + +// loginsFor is the in-server ChatGPT sign-in for a server listening on addr: +// only on loopback, where the browser is on this computer. A container that +// listens on all its interfaces gets none: OpenAI's redirect to the host's +// 127.0.0.1 can't reach it. +func loginsFor(addr net.Addr) *siwc.Logins { + if tcp, ok := addr.(*net.TCPAddr); ok && tcp.IP.IsLoopback() { + return &siwc.Logins{} + } + return nil +} diff --git a/cmd/refract/login.go b/cmd/refract/login.go index 7a108e3..465e730 100644 --- a/cmd/refract/login.go +++ b/cmd/refract/login.go @@ -77,6 +77,9 @@ func runLogin(args []string) error { return writeFileAtomic(*out, raw) }, }) + if errors.Is(err, siwc.ErrOtherAccount) { + return fmt.Errorf("%w; use -new to register it separately", err) + } if err != nil { return err } @@ -90,7 +93,7 @@ func runLogin(args []string) error { fmt.Println("ChatGPT plan usage was NOT granted, so Refract cannot make AI requests.\nRun `refract login` again and allow plan usage.") return nil } - fmt.Printf("Next:\n 1. Set REFRACT_ALLOWED_SUBJECT=%s on the server.\n 2. Upload %s in Refract (Settings → ChatGPT).\n\nThe file holds live tokens: don't commit or share it.\n", c.Subject, *out) + fmt.Printf("Next: upload %s in Refract (Settings → Assistant).\nThe file holds live tokens: don't commit or share it.\n", *out) return nil } diff --git a/cmd/refract/main.go b/cmd/refract/main.go index 2f62b54..3f8b2c9 100644 --- a/cmd/refract/main.go +++ b/cmd/refract/main.go @@ -279,6 +279,7 @@ func run(ctx context.Context, opts runOptions) error { quick: os.Getenv("REFRACT_MODEL_QUICK"), canSignOut: login != nil, + logins: loginsFor(ln.Addr()), providers: &providers.Store{DB: db, Key: key}, outbound: providers.HTTPClient(!publicOnly), diff --git a/internal/siwc/login.go b/internal/siwc/login.go index 3e1f4c0..0bc5b0a 100644 --- a/internal/siwc/login.go +++ b/internal/siwc/login.go @@ -26,6 +26,13 @@ func NewHostID() string { return fmt.Sprintf("urn:uuid:%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) } +// ErrDenied means the person cancelled the sign-in or denied access in ChatGPT. +var ErrDenied = errors.New("sign-in was cancelled or denied") + +// ErrOtherAccount means the sign-in used another ChatGPT account than the +// saved registration (Saved) belongs to. +var ErrOtherAccount = errors.New("signed in with a different ChatGPT account than the saved one") + // LoginOptions configures the local loopback sign-in. type LoginOptions struct { HostID string @@ -120,7 +127,7 @@ func Login(ctx context.Context, o LoginOptions) (*Credentials, error) { var res result switch { case p.Get("error") == "access_denied": - res.err = errors.New("sign-in was cancelled or denied") + res.err = ErrDenied case p.Get("error") != "": res.err = fmt.Errorf("authorization failed: %s %s", p.Get("error"), p.Get("error_description")) case p.Get("code") == "": @@ -196,7 +203,7 @@ func Login(ctx context.Context, o LoginOptions) (*Credentials, error) { return nil, errors.New("id token: nonce mismatch") } if o.Saved != nil && o.Saved.Subject != "" && idt.Subject != o.Saved.Subject { - return nil, errors.New("signed in with a different ChatGPT account than the saved one; use -new to register it separately") + return nil, ErrOtherAccount } var claims struct { Email string `json:"email"` diff --git a/internal/siwc/logins.go b/internal/siwc/logins.go new file mode 100644 index 0000000..4d18e98 --- /dev/null +++ b/internal/siwc/logins.go @@ -0,0 +1,181 @@ +package siwc + +import ( + "cmp" + "context" + "errors" + "log/slog" + "sync" + "syscall" + "time" +) + +// ErrLoginBusy means another account on this server is signing in: the +// callback port is fixed, so only one sign-in can wait at a time. +var ErrLoginBusy = errors.New("someone else on this server is signing in to ChatGPT; try again in a few minutes") + +// Login states and failure kinds reported by Logins.Status. +const ( + LoginIdle = "idle" + LoginPending = "pending" + LoginDone = "done" + LoginFailed = "failed" + + FailCancelled = "cancelled" // cancelled in Refract or denied in ChatGPT + FailTimeout = "timeout" // nobody finished the sign-in in time + FailPortBusy = "port_busy" // another program holds the callback port + FailOtherAccount = "other_account" // a different account than the saved registration + FailOther = "other" +) + +// LoginState is one account's in-server sign-in, as the browser sees it. It +// never carries tokens. +type LoginState struct { + State string `json:"state"` + Kind string `json:"kind,omitempty"` // when failed + Message string `json:"message,omitempty"` // when failed with FailOther +} + +// Logins runs the ChatGPT sign-in inside the server, for a server on the +// same computer as the browser: the OpenAI redirect to 127.0.0.1 reaches it. +// The credential goes straight to the account's Session; no file is written. +type Logins struct { + Timeout time.Duration // 0 = 10 minutes + Port int // as LoginOptions.Port + AuthorizeURL string // "" = real endpoint + + mu sync.Mutex + cur *runningLogin + states map[string]LoginState // by account +} + +type runningLogin struct { + owner string + cancel context.CancelFunc + done chan struct{} +} + +// Start begins a sign-in for s's account and returns the authorize URL for +// the browser to open. A sign-in already running for the same account is +// replaced (a stale tab); one for another account answers ErrLoginBusy. +// fresh registers a new ChatGPT account instead of reusing the saved one. +func (l *Logins) Start(ctx context.Context, s *Session, fresh bool) (string, error) { + l.mu.Lock() + if cur := l.cur; cur != nil { + if cur.owner != s.Owner { + l.mu.Unlock() + return "", ErrLoginBusy + } + cur.cancel() + l.mu.Unlock() + <-cur.done // frees the port + l.mu.Lock() + if l.cur != nil { // another start won the race + l.mu.Unlock() + return "", ErrLoginBusy + } + } + hostID, err := s.HostID(ctx) + if err != nil { + l.mu.Unlock() + return "", err + } + var saved *Credentials + if !fresh { + if saved, err = s.Credentials(ctx); err != nil { + l.mu.Unlock() + return "", err + } + if saved != nil && saved.ClientID == "" { + saved = nil + } + } + run, cancel := context.WithTimeout(context.Background(), cmp.Or(l.Timeout, 10*time.Minute)) + cur := &runningLogin{owner: s.Owner, cancel: cancel, done: make(chan struct{})} + l.cur = cur + l.setState(s.Owner, LoginState{State: LoginPending}) + l.mu.Unlock() + + urls := make(chan string, 1) + failed := make(chan error, 1) + go func() { + gotURL := false + defer close(cur.done) + defer cancel() + c, err := Login(run, LoginOptions{ + HostID: hostID, Saved: saved, Port: l.Port, OAuth: s.OAuth, AuthorizeURL: l.AuthorizeURL, + OnURL: func(u string, _ error) { gotURL = true; urls <- u }, + OnRegistration: func(clientID string) error { return s.SaveRegistration(run, clientID) }, + }) + if err == nil { + err = s.Store(run, c) + } + st := LoginState{State: LoginDone} + if err != nil { + st = failure(run, err) + slog.Info("chatgpt sign-in did not complete", "kind", st.Kind) + if !gotURL { + failed <- err + } + } else { + slog.Info("chatgpt sign-in completed", "plan_granted", c.PlanGranted()) + } + l.mu.Lock() + if l.cur == cur { + l.cur = nil + } + l.setState(s.Owner, st) + l.mu.Unlock() + }() + select { + case u := <-urls: + return u, nil + case err := <-failed: // before the URL: the port is taken + return "", err + } +} + +// Status reports the account's latest sign-in. +func (l *Logins) Status(owner string) LoginState { + l.mu.Lock() + defer l.mu.Unlock() + if st, ok := l.states[owner]; ok { + return st + } + return LoginState{State: LoginIdle} +} + +// Cancel stops the account's running sign-in, if any, and frees the port. +func (l *Logins) Cancel(owner string) { + l.mu.Lock() + cur := l.cur + l.mu.Unlock() + if cur != nil && cur.owner == owner { + cur.cancel() + <-cur.done + } +} + +func (l *Logins) setState(owner string, st LoginState) { + if l.states == nil { + l.states = map[string]LoginState{} + } + l.states[owner] = st +} + +func failure(ctx context.Context, err error) LoginState { + st := LoginState{State: LoginFailed, Kind: FailOther} + switch { + case errors.Is(err, context.DeadlineExceeded) && ctx.Err() == context.DeadlineExceeded: + st.Kind = FailTimeout + case errors.Is(err, context.Canceled), errors.Is(err, ErrDenied): + st.Kind = FailCancelled + case errors.Is(err, syscall.EADDRINUSE): + st.Kind = FailPortBusy + case errors.Is(err, ErrOtherAccount): + st.Kind = FailOtherAccount + default: + st.Message = err.Error() + } + return st +} diff --git a/internal/siwc/logins_test.go b/internal/siwc/logins_test.go new file mode 100644 index 0000000..cedcce2 --- /dev/null +++ b/internal/siwc/logins_test.go @@ -0,0 +1,218 @@ +package siwc + +import ( + "bytes" + "context" + "errors" + "log/slog" + "net" + "net/http" + "net/url" + "strings" + "testing" + "time" +) + +// finish plays the browser for a URL from Logins.Start: it answers the +// callback with the fake server's code, or with overrides. +func finish(t *testing.T, f *fakeAuth, authURL string, override url.Values) { + t.Helper() + u, _ := url.Parse(authURL) + q := u.Query() + f.mu.Lock() + f.nonce = q.Get("nonce") + f.mu.Unlock() + cb := url.Values{"state": {q.Get("state")}, "code": {"the-code"}, "client_id": {testClient}} + for k, v := range override { + cb[k] = v + } + resp, err := http.Get(q.Get("redirect_uri") + "?" + cb.Encode()) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() +} + +func waitState(t *testing.T, l *Logins, owner, want string) LoginState { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + st := l.Status(owner) + if st.State == want { + return st + } + if time.Now().After(deadline) { + t.Fatalf("state = %+v, want %s", st, want) + } + time.Sleep(10 * time.Millisecond) + } +} + +func TestLoginsStoresTheCredential(t *testing.T) { + var logs bytes.Buffer + prev := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) + t.Cleanup(func() { slog.SetDefault(prev) }) + + f := newFakeAuth(t) + s := newSession(t, f) + s.Owner = "ana" + l := &Logins{Port: -1, AuthorizeURL: "https://auth.invalid/authorize"} + if st := l.Status("ana"); st.State != LoginIdle { + t.Fatalf("before = %+v", st) + } + u, err := l.Start(context.Background(), s, false) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(u, "https://auth.invalid/authorize?") || strings.Contains(u, "refresh") { + t.Fatalf("url = %s", u) + } + if st := l.Status("ana"); st.State != LoginPending { + t.Fatalf("while waiting = %+v", st) + } + finish(t, f, u, nil) + waitState(t, l, "ana", LoginDone) + c, err := s.Credentials(context.Background()) + if err != nil || c == nil || c.RefreshToken != "refresh-0" || c.Subject != "user-1" || c.Email != "u@example.com" { + t.Fatalf("stored = %+v, %v", c, err) + } + for _, tok := range []string{"access-0", "refresh-0", "the-code"} { + if strings.Contains(logs.String(), tok) { + t.Errorf("log contains %q:\n%s", tok, logs.String()) + } + } + + // Signing in again reuses the stored registration. + u, err = l.Start(context.Background(), s, false) + if err != nil { + t.Fatal(err) + } + if q, _ := url.Parse(u); q.Query().Get("client_id") != testClient || q.Query().Get("login_hint") != "u@example.com" { + t.Fatalf("second url = %s", u) + } + l.Cancel("ana") +} + +func TestLoginsOneAtATime(t *testing.T) { + f := newFakeAuth(t) + ana, bea := newSession(t, f), newSession(t, f) + ana.Owner, bea.Owner = "ana", "bea" + bea.DB, bea.Key = ana.DB, ana.Key + l := &Logins{Port: -1, AuthorizeURL: "https://auth.invalid/a"} + first, err := l.Start(context.Background(), ana, false) + if err != nil { + t.Fatal(err) + } + if _, err := l.Start(context.Background(), bea, false); !errors.Is(err, ErrLoginBusy) { + t.Fatalf("second account: err = %v, want busy", err) + } + // The same account starting again replaces its stale attempt. + second, err := l.Start(context.Background(), ana, false) + if err != nil || second == first { + t.Fatalf("restart: %v", err) + } + if st := l.Status("ana"); st.State != LoginPending { + t.Fatalf("after restart = %+v", st) + } + // Cancel frees the server for the other account. + l.Cancel("bea") // not bea's: no effect + if st := l.Status("ana"); st.State != LoginPending { + t.Fatalf("bea cancelled ana's sign-in: %+v", st) + } + l.Cancel("ana") + if st := l.Status("ana"); st.State != LoginFailed || st.Kind != FailCancelled { + t.Fatalf("after cancel = %+v", st) + } + if _, err := l.Start(context.Background(), bea, false); err != nil { + t.Fatalf("after cancel: %v", err) + } + l.Cancel("bea") +} + +func TestLoginsFailures(t *testing.T) { + t.Run("timeout", func(t *testing.T) { + f := newFakeAuth(t) + s := newSession(t, f) + l := &Logins{Port: -1, Timeout: 50 * time.Millisecond, AuthorizeURL: "https://auth.invalid/a"} + if _, err := l.Start(context.Background(), s, false); err != nil { + t.Fatal(err) + } + if st := waitState(t, l, "", LoginFailed); st.Kind != FailTimeout { + t.Fatalf("state = %+v", st) + } + }) + t.Run("denied", func(t *testing.T) { + f := newFakeAuth(t) + s := newSession(t, f) + l := &Logins{Port: -1, AuthorizeURL: "https://auth.invalid/a"} + u, err := l.Start(context.Background(), s, false) + if err != nil { + t.Fatal(err) + } + finish(t, f, u, url.Values{"error": {"access_denied"}, "code": nil}) + if st := waitState(t, l, "", LoginFailed); st.Kind != FailCancelled { + t.Fatalf("state = %+v", st) + } + }) + t.Run("port in use", func(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + f := newFakeAuth(t) + s := newSession(t, f) + l := &Logins{Port: ln.Addr().(*net.TCPAddr).Port} + if _, err := l.Start(context.Background(), s, false); err == nil { + t.Fatal("started on a taken port") + } + if st := l.Status(""); st.State != LoginFailed || st.Kind != FailPortBusy { + t.Fatalf("state = %+v", st) + } + }) + t.Run("another account than the saved one", func(t *testing.T) { + f := newFakeAuth(t) + s := newSession(t, f) + s.AllowedSubject = "" + if err := s.Store(context.Background(), &Credentials{ClientID: testClient, Subject: "someone-else"}); err != nil { + t.Fatal(err) + } + l := &Logins{Port: -1, AuthorizeURL: "https://auth.invalid/a"} + u, err := l.Start(context.Background(), s, false) + if err != nil { + t.Fatal(err) + } + finish(t, f, u, nil) + if st := waitState(t, l, "", LoginFailed); st.Kind != FailOtherAccount { + t.Fatalf("state = %+v", st) + } + // fresh registers the account that signed in. + if u, err = l.Start(context.Background(), s, true); err != nil { + t.Fatal(err) + } + finish(t, f, u, nil) + waitState(t, l, "", LoginDone) + if c, _ := s.Credentials(context.Background()); c.Subject != "user-1" { + t.Fatalf("stored subject = %q", c.Subject) + } + }) + t.Run("account not allowed", func(t *testing.T) { + f := newFakeAuth(t) + s := newSession(t, f) + s.AllowedSubject = "someone-else" + l := &Logins{Port: -1, AuthorizeURL: "https://auth.invalid/a"} + u, err := l.Start(context.Background(), s, false) + if err != nil { + t.Fatal(err) + } + finish(t, f, u, nil) + st := waitState(t, l, "", LoginFailed) + if st.Kind != FailOther || !strings.Contains(st.Message, "REFRACT_ALLOWED_SUBJECT") { + t.Fatalf("state = %+v", st) + } + if c, _ := s.Credentials(context.Background()); c != nil && c.RefreshToken != "" { + t.Fatal("stored a refused account's tokens") + } + }) +} diff --git a/internal/siwc/session.go b/internal/siwc/session.go index 3189998..62794c1 100644 --- a/internal/siwc/session.go +++ b/internal/siwc/session.go @@ -74,22 +74,43 @@ func (s *Session) Import(ctx context.Context, raw []byte) (*Credentials, error) if err != nil { return nil, fmt.Errorf("id token: %w", err) } - if s.AllowedSubject != "" && idt.Subject != s.AllowedSubject { - return nil, errors.New("this ChatGPT account is not allowed on this server (REFRACT_ALLOWED_SUBJECT)") - } c.Subject = idt.Subject // trust the signed token, not the file's field var claims struct { Email string `json:"email"` } idt.Claims(&claims) c.Email = claims.Email + if err := s.Store(ctx, &c); err != nil { + return nil, err + } + return &c, nil +} +// Store keeps credentials whose subject is already verified (Import, Login) +// for this user. With REFRACT_ALLOWED_SUBJECT set, only that account is accepted. +func (s *Session) Store(ctx context.Context, c *Credentials) error { + if s.AllowedSubject != "" && c.Subject != s.AllowedSubject { + return errors.New("this ChatGPT account is not allowed on this server (REFRACT_ALLOWED_SUBJECT)") + } s.mu.Lock() defer s.mu.Unlock() - if err := s.save(ctx, &c); err != nil { - return nil, err + return s.save(ctx, c) +} + +// SaveRegistration keeps a newly issued client id before the code exchange, +// so a sign-in that fails afterwards retries with the same registration. It +// never replaces credentials that still hold tokens. +func (s *Session) SaveRegistration(ctx context.Context, clientID string) error { + s.mu.Lock() + defer s.mu.Unlock() + c, err := s.load(ctx) + if err != nil { + return err } - return &c, nil + if c != nil && c.RefreshToken != "" { + return nil + } + return s.save(ctx, &Credentials{ClientID: clientID}) } // Credentials returns the stored record (nil if none) for status display. Never send tokens to the browser. diff --git a/macos/README.md b/macos/README.md index 97d2d76..0b6dd3a 100644 --- a/macos/README.md +++ b/macos/README.md @@ -448,9 +448,10 @@ What the web view does with things the page asks for (`WebViewController`; the p - **Clipboard.** `navigator.clipboard.writeText` works from the loopback origin (a secure context). Reading (`readText`, the editor's Paste menu entry) shows WebKit's own "Paste" prompt. -Signing in to ChatGPT inside the app is not done here: today Settings → Assistant asks the person to run -`refract login` and upload the credentials file (the file picker works). The one-click flow from Settings -needs the server side of #61; its sign-in page then opens in the browser by the rule above. +Signing in to ChatGPT needs no native code: **Settings → Assistant → Sign in with ChatGPT** asks the +embedded server (which listens on loopback) to start the sign-in, and the page's `window.open` of OpenAI's +address goes to the default browser by the rule above. ChatGPT redirects to `127.0.0.1:1455`, which the +server answers itself; the page polls until it's done. Uploading a credentials file still works. ## Left for later diff --git a/web/src/ChatGPTSignIn.tsx b/web/src/ChatGPTSignIn.tsx new file mode 100644 index 0000000..087c087 --- /dev/null +++ b/web/src/ChatGPTSignIn.tsx @@ -0,0 +1,145 @@ +import { useEffect, useState } from 'react' +import { ExternalLink, Loader2 } from 'lucide-react' +import { toast } from 'sonner' +import { api, errorText, RequestError, type ChatGPTStatus } from './api' +import { Button } from '@/components/ui/button' +import { SettingsRow } from '@/components/ui/chatcn/settings-panel' +import { failureText, settled, type LoginState } from '@/lib/chatgpt-login' +import { t } from '@/lib/i18n' + +type Props = { + // again: the account is connected and this signs in anew (to renew or switch). + again?: boolean + onChange: (s: ChatGPTStatus) => void +} + +// Sign in with ChatGPT inside Refract, for a server on this computer +// (status.sign_in_here): the server waits for OpenAI's redirect to +// 127.0.0.1 while the person finishes in their browser. +export default function ChatGPTSignIn({ again, onChange }: Props) { + const [login, setLogin] = useState(null) + const [url, setUrl] = useState('') + const [busy, setBusy] = useState(false) + + // A sign-in started before Settings was closed is still running on the server. + useEffect(() => { + api('/api/chatgpt/login').then( + (st) => st.state === 'pending' && setLogin(st), + () => {}, + ) + }, []) + + const pending = login?.state === 'pending' + useEffect(() => { + if (!pending) return + let stop = false + let timer: ReturnType + async function tick() { + try { + const st = await api('/api/chatgpt/login') + if (stop) return + if (settled(st)) { + setLogin(st) + if (st.state === 'done') { + onChange(await api('/api/chatgpt/status')) + toast.success(t('Signed in with ChatGPT')) + setLogin(null) + } + return + } + } catch { + // A missed poll is retried; the server keeps waiting. + } + if (!stop) timer = setTimeout(tick, 1500) + } + timer = setTimeout(tick, 1500) + return () => { + stop = true + clearTimeout(timer) + } + }, [pending, onChange]) + + async function start(fresh = false) { + setBusy(true) + try { + const r = await api<{ url: string }>('/api/chatgpt/login', { + method: 'POST', + body: { new: fresh }, + }) + setUrl(r.url) + setLogin({ state: 'pending' }) + // The desktop app sends this to the default browser; elsewhere a blocked + // window leaves the link below. + window.open(r.url, '_blank', 'noopener') + } catch (e) { + // 503: the sign-in failed before it could start (the callback port is taken). + if (e instanceof RequestError && e.status === 503) + setLogin({ state: 'failed', kind: e.error.kind as LoginState['kind'], message: e.error.message }) + else toast.error(errorText(e)) + } finally { + setBusy(false) + } + } + + async function cancel() { + setBusy(true) + await api('/api/chatgpt/login', { method: 'DELETE' }).catch(() => {}) + setLogin(null) + setBusy(false) + } + + if (pending) { + return ( + + + {t('Waiting for ChatGPT…')} + + } + description={ + <> + {t('Finish signing in in your browser, then come back here.')}{' '} + {url && ( + + {t('Open the sign-in page')} + + )} + + } + > + + + ) + } + + const failed = login?.state === 'failed' ? login : null + return ( + {failureText(failed, t)} + ) : again ? ( + t('To renew access or use another ChatGPT account.') + ) : ( + t('Use your ChatGPT plan for the assistant. Your browser opens to finish signing in.') + ) + } + > + {failed?.kind === 'other_account' ? ( + + ) : ( + + )} + + ) +} diff --git a/web/src/Settings.tsx b/web/src/Settings.tsx index c9c13df..ad3aedf 100644 --- a/web/src/Settings.tsx +++ b/web/src/Settings.tsx @@ -52,6 +52,7 @@ import { useMonthUsage } from '@/components/useMonthUsage' import { shortcutGroups } from '@/lib/shortcuts' import { setTheme, useTheme, type Theme } from '@/lib/theme' import PlanBadge from './PlanBadge' +import ChatGPTSignIn from './ChatGPTSignIn' import { useMe } from '@/components/AccountMenu' import { useAccount } from '@/components/useAccount' import { chatgptOffered } from '@/lib/mode' @@ -252,13 +253,20 @@ function AssistantPane({ status, onChange }: Props) { > {s.plan_granted && } + {status.sign_in_here && } - + {!status.sign_in_here && ( + + )} + + ) : ( s + +test('each failure kind has its own explanation', () => { + const kinds: LoginState['kind'][] = ['cancelled', 'timeout', 'port_busy', 'other_account'] + const texts = kinds.map((kind) => failureText({ state: 'failed', kind }, id)) + assert.equal(new Set(texts).size, kinds.length) + assert.match(failureText({ state: 'failed', kind: 'port_busy' }, id), /1455/) +}) + +test("an unexpected failure shows the server's message, or a generic one", () => { + assert.equal(failureText({ state: 'failed', kind: 'other', message: 'not allowed' }, id), 'not allowed') + assert.equal(failureText({ state: 'failed', kind: 'other' }, id), 'Sign-in did not complete.') +}) + +test('only a pending sign-in keeps polling', () => { + assert.equal(settled({ state: 'pending' }), false) + for (const state of ['idle', 'done', 'failed'] as const) assert.equal(settled({ state }), true) +}) diff --git a/web/src/lib/chatgpt-login.ts b/web/src/lib/chatgpt-login.ts new file mode 100644 index 0000000..9354b8b --- /dev/null +++ b/web/src/lib/chatgpt-login.ts @@ -0,0 +1,29 @@ +// The in-server ChatGPT sign-in (GET /api/chatgpt/login), as Settings shows it. + +export type LoginState = { + state: 'idle' | 'pending' | 'done' | 'failed' + kind?: 'cancelled' | 'timeout' | 'port_busy' | 'other_account' | 'other' + message?: string +} + +// failureText explains a failed sign-in in plain words; t is the translator +// (t), passed in so this stays testable without the locale. +export function failureText(st: LoginState, t: (s: string) => string): string { + switch (st.kind) { + case 'cancelled': + return t('Sign-in was cancelled.') + case 'timeout': + return t('Sign-in took too long and stopped. Try again when you are ready.') + case 'port_busy': + return t('Another app is signing in to ChatGPT on this computer (port 1455). Close it and try again.') + case 'other_account': + return t('You signed in with a different ChatGPT account than the one connected before.') + default: + return st.message || t('Sign-in did not complete.') + } +} + +// settled is whether polling can stop. +export function settled(st: LoginState): boolean { + return st.state !== 'pending' +} diff --git a/web/src/locales/es/app.ts b/web/src/locales/es/app.ts index fd7072e..555a6cb 100644 --- a/web/src/locales/es/app.ts +++ b/web/src/locales/es/app.ts @@ -72,6 +72,29 @@ export default { choose: 'elige', 'then upload the credentials file it writes.': 'y después sube el archivo de credenciales que genera.', 'Upload credentials…': 'Subir credenciales…', + 'Signed in with ChatGPT': 'Sesión iniciada con ChatGPT', + 'Waiting for ChatGPT…': 'Esperando a ChatGPT…', + 'Finish signing in in your browser, then come back here.': 'Termina de iniciar sesión en el navegador y vuelve aquí.', + 'Open the sign-in page': 'Abrir la página de inicio de sesión', + 'To renew access or use another ChatGPT account.': 'Para renovar el acceso o usar otra cuenta de ChatGPT.', + 'Use your ChatGPT plan for the assistant. Your browser opens to finish signing in.': + 'Usa tu plan de ChatGPT con el asistente. Se abrirá el navegador para terminar de iniciar sesión.', + 'Use the new account': 'Usar la cuenta nueva', + 'Sign in with ChatGPT': 'Iniciar sesión con ChatGPT', + 'Signing out disconnects Refract from this ChatGPT account.': + 'Al cerrar sesión, Refract se desconecta de esta cuenta de ChatGPT.', + 'Credentials file': 'Archivo de credenciales', + 'Signed in elsewhere with {cmd}? Upload the file it wrote.': + '¿Iniciaste sesión en otro sitio con {cmd}? Sube el archivo que generó.', + 'Upload…': 'Subir…', + 'Sign-in was cancelled.': 'Se canceló el inicio de sesión.', + 'Sign-in took too long and stopped. Try again when you are ready.': + 'El inicio de sesión tardó demasiado y se detuvo. Vuelve a intentarlo cuando quieras.', + 'Another app is signing in to ChatGPT on this computer (port 1455). Close it and try again.': + 'Otra aplicación está iniciando sesión en ChatGPT en este ordenador (puerto 1455). Ciérrala y vuelve a intentarlo.', + 'You signed in with a different ChatGPT account than the one connected before.': + 'Iniciaste sesión con una cuenta de ChatGPT distinta de la que estaba conectada.', + 'Sign-in did not complete.': 'No se completó el inicio de sesión.', Chat: 'Chat', 'When collapsed': 'Al contraerlo', 'Keep an input bar under the editor, or tuck the chat into a bubble.': diff --git a/web/src/locales/es/assistant.ts b/web/src/locales/es/assistant.ts index 95ae898..277193c 100644 --- a/web/src/locales/es/assistant.ts +++ b/web/src/locales/es/assistant.ts @@ -97,10 +97,10 @@ export default { Cite: 'Citar', // api.ts - 'No AI connected. Sign in with ChatGPT (run `refract login` and upload the credentials) or add an API provider in Settings → Assistant.': - 'No hay IA conectada. Inicia sesión con ChatGPT (ejecuta `refract login` y sube las credenciales) o añade un proveedor por API en Ajustes → Asistente.', - 'ChatGPT plan usage was not granted. Run `refract login` again and allow plan usage.': - 'No se concedió el uso del plan de ChatGPT. Vuelve a ejecutar `refract login` y permite el uso del plan.', + 'No AI connected. Sign in with ChatGPT or add an API provider in Settings → Assistant.': + 'No hay IA conectada. Inicia sesión con ChatGPT o añade un proveedor por API en Ajustes → Asistente.', + 'ChatGPT plan usage was not granted. Sign in again and allow plan usage.': + 'No se concedió el uso del plan de ChatGPT. Vuelve a iniciar sesión y permite el uso del plan.', 'You have reached a usage limit on your ChatGPT plan or for this app. Review it in ChatGPT settings → Usage.': 'Has alcanzado un límite de uso de tu plan de ChatGPT o de esta app. Revísalo en los ajustes de ChatGPT → Uso.', 'ChatGPT plan usage is not available for this account: {message}': From 548186b354213591b5f37d40824a1e501eb263ed Mon Sep 17 00:00:00 2001 From: Daniel Villalobos Date: Tue, 24 Nov 2026 18:11:45 +0100 Subject: [PATCH 2/3] Open the ChatGPT sign-in in the browser from the server --- CHANGELOG.md | 2 +- cmd/refract/api.go | 9 ++++---- cmd/refract/hosts.go | 4 +++- internal/siwc/logins.go | 40 +++++++++++++++++++++++------------ internal/siwc/logins_test.go | 41 +++++++++++++++++++++++++++++------- macos/README.md | 5 +++-- web/src/ChatGPTSignIn.tsx | 8 +++---- 7 files changed, 76 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1144e51..f5a77f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ Notable changes to Refract. The format follows [Keep a Changelog](https://keepac ### Added -- **Sign in with ChatGPT** in Settings → Assistant when Refract runs on your own computer (it listens on loopback): the server runs the sign-in, waits for ChatGPT's redirect on `127.0.0.1:1455` and stores the credential, with no terminal or file. The desktop app opens the sign-in in the default browser. Uploading a credential file from `refract login` still works, and is the way for servers elsewhere. +- **Sign in with ChatGPT** in Settings → Assistant when Refract runs on your own computer (it listens on loopback): the server runs the sign-in, waits for ChatGPT's redirect on `127.0.0.1:1455` and stores the credential, with no terminal or file. Refract opens the sign-in in the default browser, and shows the link if it can't. Uploading a credential file from `refract login` still works, and is the way for servers elsewhere. - Refract can read its encryption key, OpenID Connect client secret, SMTP URL and OpenAlex API key from files using the corresponding `REFRACT_*_FILE` variables. `refract users` and `refract local` also accept the encryption key from a file, and the systemd unit starts Refract directly with a systemd credential. - `REFRACT_OUTBOUND` (`any` by default, or `public`) chooses whether AI provider base URLs and git remotes may reach loopback and private networks. `public` does what `REFRACT_MODE=saas` did for outbound requests, and checks at startup that git is 2.37 or later. With `public`, provider requests and redirects must be https, and link-local git remotes are refused in every mode. `REFRACT_MODE=saas` no longer changes it. - Refract finds `tectonic`, `synctex`, `rg` and `git` in a bundled `libexec/refract` folder next to the executable (the executable's own folder on Windows) before the `PATH`, and runs them by absolute path; a bundled Git uses only its own helpers and templates. `REFRACT_TECTONIC_BIN`, `REFRACT_SYNCTEX_BIN`, `REFRACT_RG_BIN` and `REFRACT_GIT_BIN` override the lookup. The startup log shows where each was found, and the web app shows one notice when a tool is missing, saying what won't work, on whichever page opens first. On macOS and Linux a bundled tool in a folder that others can write, or that another user owns, is ignored. The same checks cover bundled Git's helpers and templates. diff --git a/cmd/refract/api.go b/cmd/refract/api.go index b3b40f6..2f79074 100644 --- a/cmd/refract/api.go +++ b/cmd/refract/api.go @@ -169,8 +169,9 @@ func (a *api) status(w http.ResponseWriter, r *http.Request) { }) } -// startLogin begins the in-server ChatGPT sign-in and returns the authorize -// URL for the browser to open. {"new": true} registers another account. +// startLogin begins the in-server ChatGPT sign-in. The server opens the +// browser itself (it is on this computer); the answer carries the authorize +// URL and whether that worked, so the page opens it otherwise. {"new": true} registers another account. func (a *api) startLogin(w http.ResponseWriter, r *http.Request) { var in struct { New bool `json:"new"` @@ -179,14 +180,14 @@ func (a *api) startLogin(w http.ResponseWriter, r *http.Request) { httpError(w, err, http.StatusBadRequest) return } - u, err := a.logins.Start(r.Context(), a.forUser(r.Context()).session, in.New) + started, err := a.logins.Start(r.Context(), a.forUser(r.Context()).session, in.New) switch { case errors.Is(err, siwc.ErrLoginBusy): httpError(w, err, http.StatusConflict) case err != nil: writeLoginFailure(w, a.logins.Status(requestUser(r.Context()))) default: - writeJSON(w, map[string]string{"url": u}) + writeJSON(w, started) } } diff --git a/cmd/refract/hosts.go b/cmd/refract/hosts.go index 648c701..da37c4e 100644 --- a/cmd/refract/hosts.go +++ b/cmd/refract/hosts.go @@ -209,7 +209,9 @@ func newServer(mux http.Handler, hosts hostPolicy) *http.Server { // 127.0.0.1 can't reach it. func loginsFor(addr net.Addr) *siwc.Logins { if tcp, ok := addr.(*net.TCPAddr); ok && tcp.IP.IsLoopback() { - return &siwc.Logins{} + // The server opens the browser itself: a page's window.open after a + // request is a popup that browsers and the desktop app's web view may drop. + return &siwc.Logins{OpenBrowser: openBrowser} } return nil } diff --git a/internal/siwc/logins.go b/internal/siwc/logins.go index 4d18e98..fc6593f 100644 --- a/internal/siwc/logins.go +++ b/internal/siwc/logins.go @@ -40,9 +40,12 @@ type LoginState struct { // same computer as the browser: the OpenAI redirect to 127.0.0.1 reaches it. // The credential goes straight to the account's Session; no file is written. type Logins struct { - Timeout time.Duration // 0 = 10 minutes - Port int // as LoginOptions.Port - AuthorizeURL string // "" = real endpoint + Timeout time.Duration // 0 = 10 minutes + // OpenBrowser opens the sign-in in this computer's default browser, as + // refract login does. nil, or an error, leaves it to the page. + OpenBrowser func(authURL string) error + Port int // as LoginOptions.Port + AuthorizeURL string // "" = real endpoint mu sync.Mutex cur *runningLogin @@ -55,16 +58,23 @@ type runningLogin struct { done chan struct{} } +// Started is a sign-in waiting for the person: the authorize URL, and +// whether the server already opened it in the browser. +type Started struct { + URL string `json:"url"` + Opened bool `json:"opened"` +} + // Start begins a sign-in for s's account and returns the authorize URL for // the browser to open. A sign-in already running for the same account is // replaced (a stale tab); one for another account answers ErrLoginBusy. // fresh registers a new ChatGPT account instead of reusing the saved one. -func (l *Logins) Start(ctx context.Context, s *Session, fresh bool) (string, error) { +func (l *Logins) Start(ctx context.Context, s *Session, fresh bool) (Started, error) { l.mu.Lock() if cur := l.cur; cur != nil { if cur.owner != s.Owner { l.mu.Unlock() - return "", ErrLoginBusy + return Started{}, ErrLoginBusy } cur.cancel() l.mu.Unlock() @@ -72,19 +82,19 @@ func (l *Logins) Start(ctx context.Context, s *Session, fresh bool) (string, err l.mu.Lock() if l.cur != nil { // another start won the race l.mu.Unlock() - return "", ErrLoginBusy + return Started{}, ErrLoginBusy } } hostID, err := s.HostID(ctx) if err != nil { l.mu.Unlock() - return "", err + return Started{}, err } var saved *Credentials if !fresh { if saved, err = s.Credentials(ctx); err != nil { l.mu.Unlock() - return "", err + return Started{}, err } if saved != nil && saved.ClientID == "" { saved = nil @@ -96,7 +106,7 @@ func (l *Logins) Start(ctx context.Context, s *Session, fresh bool) (string, err l.setState(s.Owner, LoginState{State: LoginPending}) l.mu.Unlock() - urls := make(chan string, 1) + urls := make(chan Started, 1) failed := make(chan error, 1) go func() { gotURL := false @@ -104,7 +114,11 @@ func (l *Logins) Start(ctx context.Context, s *Session, fresh bool) (string, err defer cancel() c, err := Login(run, LoginOptions{ HostID: hostID, Saved: saved, Port: l.Port, OAuth: s.OAuth, AuthorizeURL: l.AuthorizeURL, - OnURL: func(u string, _ error) { gotURL = true; urls <- u }, + OpenBrowser: l.OpenBrowser, + OnURL: func(u string, openErr error) { + gotURL = true + urls <- Started{URL: u, Opened: openErr == nil} + }, OnRegistration: func(clientID string) error { return s.SaveRegistration(run, clientID) }, }) if err == nil { @@ -128,10 +142,10 @@ func (l *Logins) Start(ctx context.Context, s *Session, fresh bool) (string, err l.mu.Unlock() }() select { - case u := <-urls: - return u, nil + case st := <-urls: + return st, nil case err := <-failed: // before the URL: the port is taken - return "", err + return Started{}, err } } diff --git a/internal/siwc/logins_test.go b/internal/siwc/logins_test.go index cedcce2..28b05ff 100644 --- a/internal/siwc/logins_test.go +++ b/internal/siwc/logins_test.go @@ -61,7 +61,8 @@ func TestLoginsStoresTheCredential(t *testing.T) { if st := l.Status("ana"); st.State != LoginIdle { t.Fatalf("before = %+v", st) } - u, err := l.Start(context.Background(), s, false) + started, err := l.Start(context.Background(), s, false) + u := started.URL if err != nil { t.Fatal(err) } @@ -84,7 +85,8 @@ func TestLoginsStoresTheCredential(t *testing.T) { } // Signing in again reuses the stored registration. - u, err = l.Start(context.Background(), s, false) + started, err = l.Start(context.Background(), s, false) + u = started.URL if err != nil { t.Fatal(err) } @@ -94,6 +96,26 @@ func TestLoginsStoresTheCredential(t *testing.T) { l.Cancel("ana") } +func TestLoginsOpensTheBrowser(t *testing.T) { + f := newFakeAuth(t) + s := newSession(t, f) + var opened string + l := &Logins{Port: -1, AuthorizeURL: "https://auth.invalid/a", OpenBrowser: func(u string) error { opened = u; return nil }} + started, err := l.Start(context.Background(), s, false) + if err != nil { + t.Fatal(err) + } + if !started.Opened || opened != started.URL { + t.Fatalf("started = %+v, opened %q", started, opened) + } + l.Cancel("") + l.OpenBrowser = func(string) error { return errors.New("no browser") } + if started, err = l.Start(context.Background(), s, false); err != nil || started.Opened { + t.Fatalf("a failed open must leave it to the page: %+v %v", started, err) + } + l.Cancel("") +} + func TestLoginsOneAtATime(t *testing.T) { f := newFakeAuth(t) ana, bea := newSession(t, f), newSession(t, f) @@ -109,7 +131,7 @@ func TestLoginsOneAtATime(t *testing.T) { } // The same account starting again replaces its stale attempt. second, err := l.Start(context.Background(), ana, false) - if err != nil || second == first { + if err != nil || second.URL == first.URL { t.Fatalf("restart: %v", err) } if st := l.Status("ana"); st.State != LoginPending { @@ -146,7 +168,8 @@ func TestLoginsFailures(t *testing.T) { f := newFakeAuth(t) s := newSession(t, f) l := &Logins{Port: -1, AuthorizeURL: "https://auth.invalid/a"} - u, err := l.Start(context.Background(), s, false) + started, err := l.Start(context.Background(), s, false) + u := started.URL if err != nil { t.Fatal(err) } @@ -179,7 +202,8 @@ func TestLoginsFailures(t *testing.T) { t.Fatal(err) } l := &Logins{Port: -1, AuthorizeURL: "https://auth.invalid/a"} - u, err := l.Start(context.Background(), s, false) + started, err := l.Start(context.Background(), s, false) + u := started.URL if err != nil { t.Fatal(err) } @@ -188,10 +212,10 @@ func TestLoginsFailures(t *testing.T) { t.Fatalf("state = %+v", st) } // fresh registers the account that signed in. - if u, err = l.Start(context.Background(), s, true); err != nil { + if started, err = l.Start(context.Background(), s, true); err != nil { t.Fatal(err) } - finish(t, f, u, nil) + finish(t, f, started.URL, nil) waitState(t, l, "", LoginDone) if c, _ := s.Credentials(context.Background()); c.Subject != "user-1" { t.Fatalf("stored subject = %q", c.Subject) @@ -202,7 +226,8 @@ func TestLoginsFailures(t *testing.T) { s := newSession(t, f) s.AllowedSubject = "someone-else" l := &Logins{Port: -1, AuthorizeURL: "https://auth.invalid/a"} - u, err := l.Start(context.Background(), s, false) + started, err := l.Start(context.Background(), s, false) + u := started.URL if err != nil { t.Fatal(err) } diff --git a/macos/README.md b/macos/README.md index 0b6dd3a..7f175be 100644 --- a/macos/README.md +++ b/macos/README.md @@ -449,8 +449,9 @@ What the web view does with things the page asks for (`WebViewController`; the p (`readText`, the editor's Paste menu entry) shows WebKit's own "Paste" prompt. Signing in to ChatGPT needs no native code: **Settings → Assistant → Sign in with ChatGPT** asks the -embedded server (which listens on loopback) to start the sign-in, and the page's `window.open` of OpenAI's -address goes to the default browser by the rule above. ChatGPT redirects to `127.0.0.1:1455`, which the +embedded server (which listens on loopback) to start the sign-in, and the server opens OpenAI's address in +the default browser itself, as `refract login` does: a `window.open` after the request is a popup that +WKWebView drops. The page shows the address as a link if the server couldn't open it. ChatGPT redirects to `127.0.0.1:1455`, which the server answers itself; the page polls until it's done. Uploading a credentials file still works. ## Left for later diff --git a/web/src/ChatGPTSignIn.tsx b/web/src/ChatGPTSignIn.tsx index 087c087..1c0205c 100644 --- a/web/src/ChatGPTSignIn.tsx +++ b/web/src/ChatGPTSignIn.tsx @@ -62,15 +62,15 @@ export default function ChatGPTSignIn({ again, onChange }: Props) { async function start(fresh = false) { setBusy(true) try { - const r = await api<{ url: string }>('/api/chatgpt/login', { + const r = await api<{ url: string; opened: boolean }>('/api/chatgpt/login', { method: 'POST', body: { new: fresh }, }) setUrl(r.url) setLogin({ state: 'pending' }) - // The desktop app sends this to the default browser; elsewhere a blocked - // window leaves the link below. - window.open(r.url, '_blank', 'noopener') + // The server opens the browser itself (it runs on this computer). If it + // couldn't, try from the page; a blocked window leaves the link below. + if (!r.opened) window.open(r.url, '_blank', 'noopener') } catch (e) { // 503: the sign-in failed before it could start (the callback port is taken). if (e instanceof RequestError && e.status === 503) From 191718684ab0d80772323fcafa4127bc1774dee7 Mon Sep 17 00:00:00 2001 From: Daniel Villalobos Date: Thu, 26 Nov 2026 14:34:40 +0100 Subject: [PATCH 3/3] Offer the ChatGPT sign-in only to browsers on this computer, cancel it on sign-out and refresh Settings when it finished --- CHANGELOG.md | 2 +- README.md | 2 +- cmd/refract/api.go | 25 ++++++-- cmd/refract/api_test.go | 101 ++++++++++++++++++++++++++++++++- cmd/refract/hosts.go | 24 ++++++++ web/e2e/chatgpt-signin.spec.ts | 52 +++++++++++++++++ web/src/ChatGPTSignIn.tsx | 23 ++++++-- 7 files changed, 215 insertions(+), 14 deletions(-) create mode 100644 web/e2e/chatgpt-signin.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 8faf0c6..a7d5593 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ Notable changes to Refract. The format follows [Keep a Changelog](https://keepac ### Added -- **Sign in with ChatGPT** in Settings → Assistant when Refract runs on your own computer (it listens on loopback): the server runs the sign-in, waits for ChatGPT's redirect on `127.0.0.1:1455` and stores the credential, with no terminal or file. Refract opens the sign-in in the default browser, and shows the link if it can't. Uploading a credential file from `refract login` still works, and is the way for servers elsewhere. +- **Sign in with ChatGPT** in Settings → Assistant when Refract runs on your own computer (it listens on loopback): the server runs the sign-in, waits for ChatGPT's redirect on `127.0.0.1:1455` and stores the credential, with no terminal or file. Refract opens the sign-in in the default browser, and shows the link if it can't. Uploading a credential file from `refract login` still works, and is the way for servers elsewhere, including a loopback server behind a reverse proxy. Signing out cancels a sign-in still waiting, and reopening Settings shows a sign-in that finished meanwhile. - Refract can read its encryption key, OpenID Connect client secret, SMTP URL and OpenAlex API key from files using the corresponding `REFRACT_*_FILE` variables. `refract users` and `refract local` also accept the encryption key from a file, and the systemd unit starts Refract directly with a systemd credential. - `REFRACT_OUTBOUND` (`any` by default, or `public`) chooses whether AI provider base URLs and git remotes may reach loopback and private networks. `public` does what `REFRACT_MODE=saas` did for outbound requests, and checks at startup that git is 2.37 or later. With `public`, provider requests and redirects must be https, and link-local git remotes are refused in every mode. `REFRACT_MODE=saas` no longer changes it. - Refract finds `tectonic`, `synctex`, `rg` and `git` in a bundled `libexec/refract` folder next to the executable (the executable's own folder on Windows) before the `PATH`, and runs them by absolute path; a bundled Git uses only its own helpers and templates. `REFRACT_TECTONIC_BIN`, `REFRACT_SYNCTEX_BIN`, `REFRACT_RG_BIN` and `REFRACT_GIT_BIN` override the lookup. The startup log shows where each was found, and the web app shows one notice when a tool is missing, saying what won't work, on whichever page opens first. On macOS and Linux a bundled tool in a folder that others can write, or that another user owns, is ignored. The same checks cover bundled Git's helpers and templates. diff --git a/README.md b/README.md index 560271c..ab44dba 100644 --- a/README.md +++ b/README.md @@ -460,7 +460,7 @@ Each user connects their own AI in **Settings → Assistant**. Every connected m Refract can use a ChatGPT subscription through "Sign in with ChatGPT", so requests count against your plan instead of an API bill. The sign-in runs on your own computer, because ChatGPT only accepts it from a local address. -**Refract on your own computer** (the desktop app, `refract local`, `make dev`, or any server listening on `127.0.0.1` or `::1`): open **Settings → Assistant**, choose **Sign in with ChatGPT** and finish in the browser that opens. Refract waits for ChatGPT on `127.0.0.1:1455` and stores the credential itself; no file is written. One sign-in runs at a time per server, and it stops after 10 minutes or when you cancel it. A server listening on another address, including a container that listens on all its interfaces, doesn't offer the button. +**Refract on your own computer** (the desktop app, `refract local`, `make dev`, or any server listening on `127.0.0.1` or `::1`): open **Settings → Assistant**, choose **Sign in with ChatGPT** and finish in the browser that opens. Refract waits for ChatGPT on `127.0.0.1:1455` and stores the credential itself; no file is written. One sign-in runs at a time per server, and it stops after 10 minutes or when you cancel it. A server listening on another address, including a container that listens on all its interfaces, doesn't offer the button. Neither does a loopback server reached through a reverse proxy (a request with `X-Forwarded-For`, `X-Forwarded-Host`, `Forwarded` or `X-Real-IP`, or a host name other than `localhost` or a loopback address): people opening it from elsewhere upload a credential file instead. Signing out of ChatGPT cancels a sign-in still waiting. **Refract on a server:** diff --git a/cmd/refract/api.go b/cmd/refract/api.go index 2f79074..2ba4132 100644 --- a/cmd/refract/api.go +++ b/cmd/refract/api.go @@ -101,9 +101,9 @@ func (a *api) routes(rt *router) { rt.user("POST /api/chatgpt/credentials", a.importCredentials) rt.user("POST /api/chatgpt/signout", a.signOut) if a.logins != nil { - rt.user("POST /api/chatgpt/login", a.startLogin) - rt.user("GET /api/chatgpt/login", a.loginStatus) - rt.user("DELETE /api/chatgpt/login", a.cancelLogin) + rt.user("POST /api/chatgpt/login", a.hereOnly(a.startLogin)) + rt.user("GET /api/chatgpt/login", a.hereOnly(a.loginStatus)) + rt.user("DELETE /api/chatgpt/login", a.hereOnly(a.cancelLogin)) } } rt.user("POST /api/chatgpt/welcome-seen", a.welcomeSeen) @@ -165,10 +165,23 @@ func (a *api) status(w http.ResponseWriter, r *http.Request) { "welcome_seen": seen, "manage_usage": siwc.ManageUsage, "default_model": a.model, - "sign_in_here": a.mode.ChatGPT() && a.logins != nil, + "sign_in_here": a.mode.ChatGPT() && a.logins != nil && fromThisComputer(r), }) } +// hereOnly refuses the in-server sign-in to browsers on other computers +// (behind a reverse proxy): OpenAI's redirect goes to this computer's +// 127.0.0.1, so they upload a credentials file instead. +func (a *api) hereOnly(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !fromThisComputer(r) { + httpError(w, errors.New("signing in to ChatGPT from Settings works only on the computer Refract runs on; upload a credentials file instead"), http.StatusForbidden) + return + } + next(w, r) + } +} + // startLogin begins the in-server ChatGPT sign-in. The server opens the // browser itself (it is on this computer); the answer carries the authorize // URL and whether that worked, so the page opens it otherwise. {"new": true} registers another account. @@ -223,6 +236,10 @@ func (a *api) importCredentials(w http.ResponseWriter, r *http.Request) { } func (a *api) signOut(w http.ResponseWriter, r *http.Request) { + // A sign-in still waiting would store new credentials after this. + if a.logins != nil { + a.logins.Cancel(requestUser(r.Context())) + } if err := a.forUser(r.Context()).session.SignOut(r.Context()); err != nil { httpError(w, err, http.StatusBadGateway) return diff --git a/cmd/refract/api_test.go b/cmd/refract/api_test.go index 573f177..a71f1fd 100644 --- a/cmd/refract/api_test.go +++ b/cmd/refract/api_test.go @@ -133,6 +133,24 @@ func TestSelfHostKeepsChatGPT(t *testing.T) { } } +// callLocal is call from a browser on this computer, straight to the server. +func callLocal(t *testing.T, h http.Handler, method, path string, out any, header ...string) int { + t.Helper() + w := httptest.NewRecorder() + r := httptest.NewRequest(method, path, strings.NewReader("{}")) + r.RemoteAddr, r.Host = "127.0.0.1:50000", "127.0.0.1:8080" + for i := 0; i+1 < len(header); i += 2 { + r.Header.Set(header[i], header[i+1]) + } + h.ServeHTTP(w, r) + if out != nil && w.Code == http.StatusOK { + if err := json.Unmarshal(w.Body.Bytes(), out); err != nil { + t.Fatalf("%s %s: %v", method, path, err) + } + } + return w.Code +} + // The in-server ChatGPT sign-in exists only where the server listens on // loopback (a.logins set) and the plan is offered; the status says which. func TestSignInHereRoutes(t *testing.T) { @@ -156,10 +174,10 @@ func TestSignInHereRoutes(t *testing.T) { } }) var st status - if call(t, h, "GET", "/api/chatgpt/status", &st); st.SignInHere != c.want { + if callLocal(t, h, "GET", "/api/chatgpt/status", &st); st.SignInHere != c.want { t.Errorf("sign_in_here = %v, want %v", st.SignInHere, c.want) } - code := call(t, h, "GET", "/api/chatgpt/login", nil) + code := callLocal(t, h, "GET", "/api/chatgpt/login", nil) if want := map[bool]int{true: http.StatusOK, false: http.StatusNotFound}[c.want]; code != want { t.Errorf("GET /api/chatgpt/login = %d, want %d", code, want) } @@ -167,6 +185,85 @@ func TestSignInHereRoutes(t *testing.T) { } } +// A loopback listener behind a reverse proxy serves people on other +// computers: their browser can't reach this computer's callback, so they get +// the credentials file instead of the in-server sign-in. +func TestSignInHereOnlyFromThisComputer(t *testing.T) { + h, _ := newAIServerWith(t, mode.SelfHost, func(a *api) { a.logins = &siwc.Logins{} }) + type status struct { + SignInHere bool `json:"sign_in_here"` + } + var st status + if callLocal(t, h, "GET", "/api/chatgpt/status", &st); !st.SignInHere { + t.Fatal("a browser on this computer should sign in here") + } + for name, header := range map[string][]string{ + "forwarded for": {"X-Forwarded-For", "203.0.113.7"}, + "forwarded host": {"X-Forwarded-Host", "refract.example.com"}, + "forwarded": {"Forwarded", "for=203.0.113.7"}, + "real ip": {"X-Real-Ip", "203.0.113.7"}, + } { + st = status{SignInHere: true} + if callLocal(t, h, "GET", "/api/chatgpt/status", &st, header...); st.SignInHere { + t.Errorf("%s: sign_in_here = true behind a proxy", name) + } + for _, m := range []string{"POST", "GET", "DELETE"} { + if code := callLocal(t, h, m, "/api/chatgpt/login", nil, header...); code != http.StatusForbidden { + t.Errorf("%s: %s /api/chatgpt/login = %d, want 403", name, m, code) + } + } + } + st = status{SignInHere: true} + if call(t, h, "GET", "/api/chatgpt/status", &st); st.SignInHere { + t.Error("a request from another address should not sign in here") + } +} + +func TestFromThisComputer(t *testing.T) { + for _, c := range []struct { + remote, host string + want bool + }{ + {"127.0.0.1:5000", "127.0.0.1:8080", true}, + {"[::1]:5000", "[::1]:8080", true}, + {"127.0.0.1:5000", "localhost:5173", true}, + {"127.0.0.1:5000", "refract.localhost", true}, + {"127.0.0.1:5000", "refract.example.com", false}, // a proxy on this computer passing the public name + {"192.168.1.5:5000", "127.0.0.1:8080", false}, + {"bad", "127.0.0.1:8080", false}, + } { + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr, r.Host = c.remote, c.host + if got := fromThisComputer(r); got != c.want { + t.Errorf("%s → %s: %v, want %v", c.remote, c.host, got, c.want) + } + } +} + +// Signing out cancels a sign-in still waiting, so it can't store new +// credentials afterwards. +func TestSignOutCancelsPendingSignIn(t *testing.T) { + revoke := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + t.Cleanup(revoke.Close) + h, _ := newAIServerWith(t, mode.SelfHost, func(a *api) { + a.base.OAuth = &siwc.OAuth{RevokeURL: revoke.URL, HTTP: revoke.Client()} + a.logins = &siwc.Logins{Port: -1, AuthorizeURL: "https://auth.invalid/authorize"} + }) + if code := callLocal(t, h, "POST", "/api/chatgpt/login", nil); code != http.StatusOK { + t.Fatalf("POST /api/chatgpt/login = %d", code) + } + var st siwc.LoginState + if callLocal(t, h, "GET", "/api/chatgpt/login", &st); st.State != siwc.LoginPending { + t.Fatalf("state = %+v, want pending", st) + } + if code := callLocal(t, h, "POST", "/api/chatgpt/signout", nil); code != http.StatusOK { + t.Fatalf("POST /api/chatgpt/signout = %d", code) + } + if callLocal(t, h, "GET", "/api/chatgpt/login", &st); st.State != siwc.LoginFailed || st.Kind != siwc.FailCancelled { + t.Errorf("state after sign-out = %+v, want failed/cancelled", st) + } +} + func TestLoginsOnlyOnLoopback(t *testing.T) { for addr, want := range map[string]bool{"127.0.0.1:8080": true, "[::1]:8080": true, "0.0.0.0:8080": false, "192.168.1.5:8080": false} { a, _ := net.ResolveTCPAddr("tcp", addr) diff --git a/cmd/refract/hosts.go b/cmd/refract/hosts.go index da37c4e..44d4da9 100644 --- a/cmd/refract/hosts.go +++ b/cmd/refract/hosts.go @@ -215,3 +215,27 @@ func loginsFor(addr net.Addr) *siwc.Logins { } return nil } + +// fromThisComputer reports whether a request comes straight from a browser on +// the computer Refract runs on: a loopback peer, a loopback host name and no +// proxy headers. A loopback listener can also sit behind a reverse proxy for +// people elsewhere, and their browser can't reach this computer's callback. +func fromThisComputer(r *http.Request) bool { + for _, h := range []string{"Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Real-Ip"} { + if r.Header.Get(h) != "" { + return false + } + } + peer, _, err := net.SplitHostPort(r.RemoteAddr) + if ip := net.ParseIP(peer); err != nil || ip == nil || !ip.IsLoopback() { + return false + } + host, ok := parseAuthority(r.Host) + if !ok { + return false + } + if ip := net.ParseIP(host); ip != nil { + return ip.IsLoopback() + } + return host == "localhost" || strings.HasSuffix(host, ".localhost") +} diff --git a/web/e2e/chatgpt-signin.spec.ts b/web/e2e/chatgpt-signin.spec.ts new file mode 100644 index 0000000..7296577 --- /dev/null +++ b/web/e2e/chatgpt-signin.spec.ts @@ -0,0 +1,52 @@ +import { expect, test, type Page } from '@playwright/test' + +const headers = { 'X-Refract': '1' } + +async function openAssistantSettings(page: Page) { + await page.getByRole('button', { name: 'Account menu', exact: true }).click() + await page.getByRole('menuitem', { name: 'Settings', exact: true }).click() + await page.getByRole('tab', { name: /^Assistant/ }).click() +} + +// The sign-in finishes in the browser while Settings is closed: reopening it +// shows the connected account without a reload. +test('reopening Settings after a sign-in finished elsewhere shows the account', async ({ page, request }) => { + let signedIn = false + let login = { state: 'pending' } + await page.addInitScript(() => { + if (!localStorage.getItem('refract-prefs')) + localStorage.setItem('refract-prefs', JSON.stringify({ language: 'en' })) + }) + await page.route('**/api/chatgpt/status', (route) => + route.fulfill({ + json: { + ai_ready: signedIn, + welcome_seen: true, + sign_in_here: true, + manage_usage: 'https://chatgpt.com', + default_model: '', + status: { + provider: 'chatgpt', + signed_in: signedIn, + plan_granted: signedIn, + email: signedIn ? 'ana@example.com' : undefined, + limit_reached: false, + }, + }, + }), + ) + await page.route('**/api/chatgpt/login', (route) => route.fulfill({ json: login })) + + const project = await (await request.post('/api/projects', { headers, data: { name: 'Sign in' } })).json() + await page.goto(`/p/${project.id}`) + await openAssistantSettings(page) + await expect(page.getByText('Waiting for ChatGPT…')).toBeVisible() + await page.keyboard.press('Escape') + await expect(page.getByRole('dialog')).toHaveCount(0) + + signedIn = true + login = { state: 'done' } + await openAssistantSettings(page) + await expect(page.getByRole('dialog').getByText('ana@example.com')).toBeVisible() + await expect(page.getByRole('dialog').getByText('Not connected')).toHaveCount(0) +}) diff --git a/web/src/ChatGPTSignIn.tsx b/web/src/ChatGPTSignIn.tsx index 1c0205c..4a167e5 100644 --- a/web/src/ChatGPTSignIn.tsx +++ b/web/src/ChatGPTSignIn.tsx @@ -21,13 +21,24 @@ export default function ChatGPTSignIn({ again, onChange }: Props) { const [url, setUrl] = useState('') const [busy, setBusy] = useState(false) - // A sign-in started before Settings was closed is still running on the server. + // A sign-in started before Settings was closed is still running on the + // server, or finished meanwhile: then the connection shown is stale. useEffect(() => { - api('/api/chatgpt/login').then( - (st) => st.state === 'pending' && setLogin(st), - () => {}, - ) - }, []) + let stop = false + api('/api/chatgpt/login') + .then(async (st) => { + if (stop) return + if (st.state === 'pending') setLogin(st) + else if (st.state === 'done') { + const status = await api('/api/chatgpt/status') + if (!stop) onChange(status) + } + }) + .catch(() => {}) + return () => { + stop = true + } + }, [onChange]) const pending = login?.state === 'pending' useEffect(() => {