Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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.
Expand All @@ -18,6 +19,7 @@ Notable changes to Refract. The format follows [Keep a Changelog](https://keepac
### Changed

- Refract moved to the [Use-Refract](https://github.com/Use-Refract) organization: the repository is `Use-Refract/Refract`, and the Docker image is published as `ghcr.io/use-refract/refract` (images up to v0.2.0 stay at `ghcr.io/ponytojas/refract`). The macOS app looks for updates in the new repository; old links redirect. The Homebrew tap moved too: `brew install use-refract/tap/refract` (taps added as `ponytojas/tap` keep updating through GitHub's redirect).
- `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.
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,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. 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:**

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.
Expand Down
67 changes: 67 additions & 0 deletions cmd/refract/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.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)
rt.user("GET /api/models", a.models)
Expand Down Expand Up @@ -155,9 +165,62 @@ 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 && 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.
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
}
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, started)
}
}

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 {
Expand All @@ -173,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
Expand Down
150 changes: 149 additions & 1 deletion cmd/refract/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"path/filepath"
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -125,6 +133,146 @@ 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) {
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 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 := 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)
}
})
}
}

// 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)
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) {
Expand Down
39 changes: 39 additions & 0 deletions cmd/refract/hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -200,3 +202,40 @@ 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() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A loopback listener can also be the upstream for a reverse proxy, as in our deployment docs. In that setup, users see the sign-in button even though Refract opens the browser on the server and the callback needs to reach that same machine. Could we keep the credentials-file flow for users accessing Refract remotely?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. The decision is now per request: sign_in_here and the /api/chatgpt/login routes need a loopback peer, a loopback Host (localhost, *.localhost or a loopback IP) and no proxy headers (Forwarded, X-Forwarded-For, X-Forwarded-Host, X-Real-IP). A browser behind a reverse proxy gets the credentials-file flow, and the login routes answer 403. Covered by TestSignInHereOnlyFromThisComputer and TestFromThisComputer; the README says so too.

// 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
}

// 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")
}
5 changes: 4 additions & 1 deletion cmd/refract/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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
}

Expand Down
1 change: 1 addition & 0 deletions cmd/refract/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading
Loading