diff --git a/CHANGELOG.md b/CHANGELOG.md index f5a77f9..a038b26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Notable changes to Refract. The format follows [Keep a Changelog](https://keepac ### Added +- Connecting GitHub works with no setup in `refract local` and the Mac app: they use Refract's own OAuth App (device flow) unless `REFRACT_GITHUB_CLIENT_ID` names another. On your own computer, Refract opens GitHub's page in the browser itself. - **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. diff --git a/README.md b/README.md index cb87b9c..4a9b338 100644 --- a/README.md +++ b/README.md @@ -597,7 +597,9 @@ A missing tool doesn't stop Refract: it logs what won't work without it and the ### Connect GitHub -Without this, any project can still push to and pull from an https git remote with a personal access token. To let users pick or create GitHub repositories from Refract: +On your own computer (`refract local` and the Mac app) this works with no setup: Refract uses its own GitHub OAuth App, and **Settings → Integrations → Connect** opens GitHub in your browser. Each person authorizes it with their own account; the token stays sealed in their Refract. Set `REFRACT_GITHUB_CLIENT_ID` to use your own app instead. + +A server needs its own OAuth App. Without one, any project can still push to and pull from an https git remote with a personal access token. To let users pick or create GitHub repositories from Refract: 1. Create a [GitHub OAuth App](https://github.com/settings/developers) and check **Enable Device Flow**. The callback URL is not used, and no client secret is needed. 2. Set `REFRACT_GITHUB_CLIENT_ID` to its client ID. diff --git a/cmd/refract/hosts.go b/cmd/refract/hosts.go index da37c4e..3ad3a1f 100644 --- a/cmd/refract/hosts.go +++ b/cmd/refract/hosts.go @@ -208,10 +208,17 @@ func newServer(mux http.Handler, hosts hostPolicy) *http.Server { // 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() { + if onThisComputer(addr) { // 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 } + +// onThisComputer is whether a server listening on addr is reached only from +// this computer, where the person's browser is: it may open pages in it. +func onThisComputer(addr net.Addr) bool { + tcp, ok := addr.(*net.TCPAddr) + return ok && tcp.IP.IsLoopback() +} diff --git a/cmd/refract/local.go b/cmd/refract/local.go index 0c5b8b6..7c98986 100644 --- a/cmd/refract/local.go +++ b/cmd/refract/local.go @@ -261,6 +261,9 @@ func startLocal(ctx context.Context, o localOptions) error { key: key, authKind: "none", texSeed: true, + // Refract's OAuth App (device flow, public client id, no secret), owned + // by the Use-Refract organization. REFRACT_GITHUB_CLIENT_ID overrides it. + githubClientID: refractGitHubClientID, listen: func() (net.Listener, error) { if o.embedded && !o.portSet && o.getenv("REFRACT_ADDR") == "" { return listenTCP(&net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}) // a free port @@ -549,6 +552,10 @@ func writeAndSync(f *os.File, data []byte) error { return err } +// refractGitHubClientID is the client id of Refract's GitHub OAuth App. It is +// public: it names the app on GitHub's authorization page and grants nothing. +const refractGitHubClientID = "Ov23liYnkF9XAiPRni54" + func listenTCP(a *net.TCPAddr) (net.Listener, error) { return net.ListenTCP("tcp", a) } // listenLocal opens refract local's listener. REFRACT_ADDR and --port choose diff --git a/cmd/refract/main.go b/cmd/refract/main.go index 3f8b2c9..b607a34 100644 --- a/cmd/refract/main.go +++ b/cmd/refract/main.go @@ -152,6 +152,9 @@ type runOptions struct { texSeed bool // wrap, when set, goes around every route, inside the host check. wrap func(http.Handler) http.Handler + // githubClientID is used when REFRACT_GITHUB_CLIENT_ID is not set + // (refract local: Refract's own OAuth App, so Connect works with no setup). + githubClientID string } // run serves Refract until ctx ends, then shuts down gracefully. @@ -344,9 +347,12 @@ func run(ctx context.Context, opts runOptions) error { acc := &access.Checker{DB: db, SkipVerified: authKind != "builtin"} asa.svc.Access = acc ra := &remoteAPI{svc: pa.svc, db: db, key: key, acc: acc} - if id := os.Getenv("REFRACT_GITHUB_CLIENT_ID"); id != "" { + if id := cmp.Or(os.Getenv("REFRACT_GITHUB_CLIENT_ID"), opts.githubClientID); id != "" { ra.github = &github.Client{HTTP: outbound, ClientID: id, Web: "https://github.com", API: "https://api.github.com"} } + if onThisComputer(ln.Addr()) { + ra.openBrowser = openBrowser + } pa.svc.OnCommit = ra.AutoPush pa.svc.GitHubToken = ra.Token pa.svc.HoldTurns = asa.svc.Hold diff --git a/cmd/refract/remote_api.go b/cmd/refract/remote_api.go index 301ed78..259465b 100644 --- a/cmd/refract/remote_api.go +++ b/cmd/refract/remote_api.go @@ -9,6 +9,7 @@ import ( "log/slog" "net/http" "regexp" + "strings" "sync" "time" @@ -25,6 +26,10 @@ type remoteAPI struct { key []byte github *github.Client // nil when REFRACT_GITHUB_CLIENT_ID is not set acc *access.Checker // auto-push rechecks who may push + // openBrowser, set when the server runs on the person's computer, opens + // GitHub's device page there: a page's window.open after a request is a + // popup that browsers and the desktop app's web view may drop. + openBrowser func(url string) error mu sync.Mutex last map[string]syncStatus // project → last push/pull @@ -228,8 +233,12 @@ func (a *remoteAPI) githubStart(w http.ResponseWriter, r *http.Request) { } a.devices[requestUser(r.Context())] = d a.mu.Unlock() + // Only GitHub's own page: the address comes from GitHub's answer, and the + // opener would follow any scheme. + opened := a.openBrowser != nil && strings.HasPrefix(d.VerificationURI, a.github.Web+"/") && + a.openBrowser(d.VerificationURI) == nil // The device code stays on the server; the browser only shows the user code. - writeJSON(w, map[string]any{"user_code": d.UserCode, "verification_uri": d.VerificationURI, "interval": d.Interval, "expires_in": d.ExpiresIn}) + writeJSON(w, map[string]any{"user_code": d.UserCode, "verification_uri": d.VerificationURI, "interval": d.Interval, "expires_in": d.ExpiresIn, "opened": opened}) } func (a *remoteAPI) githubPoll(w http.ResponseWriter, r *http.Request) { diff --git a/cmd/refract/remote_api_test.go b/cmd/refract/remote_api_test.go index d0207f2..aadb9a5 100644 --- a/cmd/refract/remote_api_test.go +++ b/cmd/refract/remote_api_test.go @@ -13,6 +13,7 @@ import ( "github.com/ponytojas/Refract/internal/access" "github.com/ponytojas/Refract/internal/auth" + "github.com/ponytojas/Refract/internal/github" "github.com/ponytojas/Refract/internal/projects" "github.com/ponytojas/Refract/internal/store" ) @@ -100,3 +101,45 @@ func TestRemotePutIgnoresTokenOrigin(t *testing.T) { t.Errorf("sync status = %+v", st) } } + +// On this computer the server opens GitHub's device page itself, and only +// GitHub's own page; elsewhere it leaves that to the browser. +func TestGitHubStartOpensTheDevicePage(t *testing.T) { + verification := "" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(map[string]any{"device_code": "dc", "user_code": "ABCD-1234", "verification_uri": verification, "expires_in": 900, "interval": 5}) + })) + defer srv.Close() + start := func(open func(string) error) (opened bool) { + t.Helper() + a := &remoteAPI{github: &github.Client{HTTP: srv.Client(), ClientID: "cid", Web: srv.URL, API: srv.URL}, openBrowser: open} + w := httptest.NewRecorder() + r := httptest.NewRequest("POST", "/api/github/device", nil) + a.githubStart(w, r.WithContext(auth.WithUser(r.Context(), auth.User{ID: "ana"}))) + var out struct { + Opened bool `json:"opened"` + } + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil || w.Code != http.StatusOK { + t.Fatalf("%d %s", w.Code, w.Body) + } + return out.Opened + } + var got []string + open := func(u string) error { got = append(got, u); return nil } + + verification = srv.URL + "/login/device" + if !start(open) || len(got) != 1 || got[0] != verification { + t.Fatalf("opened %v", got) + } + verification = "file:///etc/passwd" + if start(open) || len(got) != 1 { + t.Fatalf("opened a page that isn't GitHub's: %v", got) + } + verification = srv.URL + "/login/device" + if start(nil) { + t.Fatal("reported opened without an opener (a server elsewhere)") + } + if start(func(string) error { return errors.New("no browser") }) { + t.Fatal("reported opened when the browser failed") + } +} diff --git a/web/src/Settings.tsx b/web/src/Settings.tsx index ad3aedf..8a9d121 100644 --- a/web/src/Settings.tsx +++ b/web/src/Settings.tsx @@ -47,6 +47,7 @@ import { import { getPrefs, openSettings, setPref, usePrefs, useSettingsSection, type Prefs } from '@/lib/prefs' import { lang, languageNames, t, tn } from '@/lib/i18n' import { reloadTo } from '@/lib/router' +import { copyWhenReady } from '@/lib/clipboard' import { compact, modelLabel, ownUsage, totalTokens } from '@/lib/usage' import { useMonthUsage } from '@/components/useMonthUsage' import { shortcutGroups } from '@/lib/shortcuts' @@ -1004,13 +1005,14 @@ function Providers({ onChange }: { onChange: () => void }) { } type GitHubState = { configured: boolean; connected: boolean; login?: string } -type Device = { user_code: string; verification_uri: string; interval: number; expires_in: number } +type Device = { user_code: string; verification_uri: string; interval: number; expires_in: number; opened?: boolean } // GitHub account, connected with the device flow: Refract shows a code, you // enter it on github.com, and the token stays sealed on the server. function Integrations() { const [gh, setGh] = useState(null) const [device, setDevice] = useState(null) + const [copied, setCopied] = useState(false) const [busy, setBusy] = useState(false) const load = () => api('/api/github').then(setGh, (e) => toast.error(errorText(e))) @@ -1053,10 +1055,16 @@ function Integrations() { async function connect() { setBusy(true) + const start = api('/api/github/device', { method: 'POST' }) + // Copied while the click still counts, so the code is ready to paste on GitHub. + const copying = copyWhenReady(start.then((d) => d.user_code)) try { - const d = await api('/api/github/device', { method: 'POST' }) + const d = await start setDevice(d) - window.open(d.verification_uri, '_blank', 'noopener') + setCopied(false) + copying.then(setCopied) + // The server opens GitHub's page itself when it runs on this computer. + if (!d.opened) window.open(d.verification_uri, '_blank', 'noopener') } catch (e) { toast.error(errorText(e)) } finally { @@ -1105,7 +1113,11 @@ function Integrations() { @@ -1115,7 +1127,12 @@ function Integrations() { size="icon-sm" variant="ghost" aria-label={t('Copy code')} - onClick={() => navigator.clipboard.writeText(device.user_code)} + onClick={() => + navigator.clipboard.writeText(device.user_code).then( + () => toast.success(t('Code copied')), + () => toast.error(t('Could not copy the code')), + ) + } > diff --git a/web/src/lib/clipboard.ts b/web/src/lib/clipboard.ts new file mode 100644 index 0000000..c7028d1 --- /dev/null +++ b/web/src/lib/clipboard.ts @@ -0,0 +1,23 @@ +// copyWhenReady puts text that is still on its way on the clipboard. Call it +// synchronously inside the click handler: the clipboard takes a promise of the +// text, so the write still counts as the person's gesture when the text +// arrives after a request (Safari and the desktop app's web view refuse a +// write made after an await). Resolves to whether the text was copied. +export function copyWhenReady(text: Promise): Promise { + const later = () => + text + .then((s) => navigator.clipboard.writeText(s)) + .then( + () => true, + () => false, + ) + try { + if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) { + const blob = text.then((s) => new Blob([s], { type: 'text/plain' })) + return navigator.clipboard.write([new ClipboardItem({ 'text/plain': blob })]).then(() => true, later) + } + } catch { + // No clipboard API here: try the plain write. + } + return later() +} diff --git a/web/src/locales/es/app.ts b/web/src/locales/es/app.ts index 555a6cb..0562dc0 100644 --- a/web/src/locales/es/app.ts +++ b/web/src/locales/es/app.ts @@ -240,6 +240,10 @@ export default { 'Enter this code on GitHub': 'Introduce este código en GitHub', 'Waiting for you to approve Refract on github.com…': 'Esperando a que apruebes Refract en github.com…', 'Copy code': 'Copiar código', + 'Code copied': 'Código copiado', + 'Could not copy the code': 'No se pudo copiar el código', + 'The code is copied: paste it on GitHub and approve Refract.': + 'El código está copiado: pégalo en GitHub y autoriza Refract.', 'Connect to push projects to your repositories, or create new ones.': 'Conéctala para enviar proyectos a tus repositorios o crear otros nuevos.', 'Connect GitHub': 'Conectar GitHub',