Skip to content
Open
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
1 change: 1 addition & 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

- 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.
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 8 additions & 1 deletion cmd/refract/hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
7 changes: 7 additions & 0 deletions cmd/refract/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion cmd/refract/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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()) {

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.

The documented Caddy and nginx setups also proxy to a loopback listener. In that setup, clicking Connect GitHub can launch the browser on the server and return opened: true, so the user has to open GitHub manually from the link in Settings. Could we enable the native browser opener only when Refract is started with refract local, including from the Mac app?

ra.openBrowser = openBrowser
}
pa.svc.OnCommit = ra.AutoPush
pa.svc.GitHubToken = ra.Token
pa.svc.HoldTurns = asa.svc.Hold
Expand Down
11 changes: 10 additions & 1 deletion cmd/refract/remote_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"log/slog"
"net/http"
"regexp"
"strings"
"sync"
"time"

Expand All @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
43 changes: 43 additions & 0 deletions cmd/refract/remote_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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")
}
}
27 changes: 22 additions & 5 deletions web/src/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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<GitHubState | null>(null)
const [device, setDevice] = useState<Device | null>(null)
const [copied, setCopied] = useState(false)
const [busy, setBusy] = useState(false)

const load = () => api<GitHubState>('/api/github').then(setGh, (e) => toast.error(errorText(e)))
Expand Down Expand Up @@ -1053,10 +1055,16 @@ function Integrations() {

async function connect() {
setBusy(true)
const start = api<Device>('/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<Device>('/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 {
Expand Down Expand Up @@ -1105,7 +1113,11 @@ function Integrations() {
<SettingsRow
stacked
label={t('Enter this code on GitHub')}
description={t('Waiting for you to approve Refract on github.com…')}
description={
copied
? t('The code is copied: paste it on GitHub and approve Refract.')
: t('Waiting for you to approve Refract on github.com…')
}
>
<span className="flex items-center gap-2">
<code className="rounded-md border bg-muted px-3 py-1.5 font-mono text-lg tracking-widest">
Expand All @@ -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')),
)
}
>
<Copy />
</Button>
Expand Down
23 changes: 23 additions & 0 deletions web/src/lib/clipboard.ts
Original file line number Diff line number Diff line change
@@ -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<string>): Promise<boolean> {
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()
}
4 changes: 4 additions & 0 deletions web/src/locales/es/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Loading