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
7 changes: 7 additions & 0 deletions changelog/unreleased/freemilk-paste-callback-login.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### English

- FreeMilk login now opens Google directly and finishes when you paste the `com.googleusercontent.apps…:/oauth2callback?code=…` redirect URL into the wizard. The old 127.0.0.1 forwarder never received the app-scheme redirect and could not be reached from a remote console.

### 中文

- FreeMilk 登录现在直接打开 Google,把 `com.googleusercontent.apps…:/oauth2callback?code=…` 回调地址粘贴进向导即可完成。原来的 127.0.0.1 转发收不到 App scheme 回调,部署在服务器上时浏览器也访问不到。
10 changes: 6 additions & 4 deletions frontend/src/components/AddAccountModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ export function AddAccountModal({ isOpen, onClose, onAdded }: Props) {
// so the wizard opens on the PAT tab instead of the browser tab.
const hasBrowserLogin = activeOption?.descriptor.capabilities?.browser_login !== false
const showCallbackPaste = activeOption?.provider === 'trae' || activeOption?.provider === 'devin' || activeOption?.provider === 'codex' || activeOption?.provider === 'codearts' || activeOption?.provider === 'freemilk'
const callbackLeadKey = activeOption?.provider === 'freemilk' ? 'freemilkCallbackLead' : 'wizardCallbackLead'
const callbackPhKey = activeOption?.provider === 'freemilk' ? 'freemilkCallbackPh' : 'wizardCallbackPh'
const busy = phase === 'busy' || phase === 'polling'
const settingsLocked = Boolean(createdId.current) || busy
const isDone = phase === 'done'
Expand Down Expand Up @@ -398,7 +400,7 @@ export function AddAccountModal({ isOpen, onClose, onAdded }: Props) {
async function runCallback() {
const pasted = callbackUrl.trim()
if (!pasted) {
setMessage(t('wizardCallbackPh'))
setMessage(t(callbackPhKey))
return
}
try {
Expand Down Expand Up @@ -970,13 +972,13 @@ export function AddAccountModal({ isOpen, onClose, onAdded }: Props) {
) : null}
{showCallbackPaste ? (
<div className="space-y-2">
<p className="text-caption leading-4 text-muted">{t('wizardCallbackLead')}</p>
<p className="text-caption leading-4 text-muted">{t(callbackLeadKey)}</p>
<TextArea
className="h-28 w-full resize-none font-mono text-caption leading-5"
value={callbackUrl}
onChange={(event) => setCallbackUrl(event.target.value)}
placeholder={t('wizardCallbackPh')}
aria-label={t('wizardCallbackPh')}
placeholder={t(callbackPhKey)}
aria-label={t(callbackPhKey)}
disabled={isDone}
/>
<Button size="sm" variant="secondary" isPending={phase === 'busy' && Boolean(callbackUrl.trim())} onPress={() => void runCallback()} isDisabled={isDone}>
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/i18n/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1191,6 +1191,8 @@ export const messages: Record<Lang, Dict> = {
wizardWaitingBrowser: 'Waiting for authorization in the browser…',
wizardCallbackLead: 'If the browser stays on 127.0.0.1 and this console never finishes, copy the full address-bar URL here.',
wizardCallbackPh: 'Paste the full http://127.0.0.1…/authorize?… URL',
freemilkCallbackLead: 'Google sends the sign-in to the FreeMilk app scheme, so this console cannot receive it. Before you sign in, open DevTools > Network and turn on Preserve log. After sign-in, find the entry whose URL starts with com.googleusercontent.apps… (it may show as failed, or as the Location of an accounts.google.com redirect) and paste that full URL here.',
freemilkCallbackPh: 'Paste the com.googleusercontent.apps…:/oauth2callback?code=… URL',
wizardSubmitCallback: 'Submit callback URL',
wizardStartingWorker: 'Authorization received. Starting account session…',
wizardAccountReady: 'Account is ready.',
Expand Down Expand Up @@ -2471,6 +2473,8 @@ export const messages: Record<Lang, Dict> = {
wizardWaitingBrowser: '正在等待浏览器完成授权…',
wizardCallbackLead: '如果浏览器停在 127.0.0.1,而控制台一直没有完成,把地址栏完整 URL 粘贴到这里。',
wizardCallbackPh: '粘贴完整的 http://127.0.0.1…/authorize?… 地址',
freemilkCallbackLead: 'Google 会把登录结果交给 FreeMilk App 的自定义 scheme,控制台收不到。登录前先打开开发者工具 > Network,勾选 Preserve log。登录后找到以 com.googleusercontent.apps… 开头的那条记录(可能显示为失败,也可能是 accounts.google.com 跳转里的 Location),把完整 URL 粘贴到这里。',
freemilkCallbackPh: '粘贴 com.googleusercontent.apps…:/oauth2callback?code=… 地址',
wizardSubmitCallback: '提交回调地址',
wizardStartingWorker: '已收到授权,正在启动账号会话…',
wizardAccountReady: '账号已就绪。',
Expand Down
23 changes: 0 additions & 23 deletions internal/auth/loopback.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,26 +46,3 @@ func loopbackHandler(title string, callback func(context.Context, string) error)
_, _ = io.WriteString(w, fmt.Sprintf(`<!doctype html><meta charset="utf-8"><title>%s login</title><p>Login complete. You can close this tab.</p>`, html.EscapeString(title)))
}
}

// SchemeBridge redirects a browser from a loopback page to a custom-scheme
// authorization URL, then accepts the scheme callback forwarded back as a
// normal query. Provider code never sees the response writer.
type SchemeBridge struct {
Authorize func(state string) (string, error)
Callback func(context.Context, string) error
}

func ServeSchemeBridge(ln net.Listener, bridge SchemeBridge) {
mux := http.NewServeMux()
mux.HandleFunc("/launch", func(w http.ResponseWriter, r *http.Request) {
target, err := bridge.Authorize(r.URL.Query().Get("state"))
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
http.Redirect(w, r, target, http.StatusFound)
})
mux.HandleFunc("/oauth2callback", loopbackHandler("FreeMilk", bridge.Callback))
server := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
go func() { _ = server.Serve(ln) }()
}
5 changes: 1 addition & 4 deletions internal/providers/freemilk/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package freemilk
import (
"context"
"fmt"
"net"
"net/http"
"strings"
"sync"
Expand All @@ -27,15 +26,13 @@ type SecretReader interface {
GetSecret(context.Context, string) (string, bool, error)
}

// Client is one FreeMilk adapter. The loopback listener is shared by every
// login that is in progress.
// Client is one FreeMilk adapter. Pending logins are keyed by account id.
type Client struct {
store Store
http *http.Client
apiBase string
chatBase string
pending map[string]*loginPending
listener net.Listener
mu sync.Mutex
catalogs catalogCache
transports proxyutil.TransportCache
Expand Down
4 changes: 2 additions & 2 deletions internal/providers/freemilk/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ const (
// token's audience must be this client or /auth/google rejects it.
GoogleClientID = "311745113120-qptt8h4kcsb3p2tbd8bpg3n9etvjf3km.apps.googleusercontent.com"
// GoogleRedirectURI is the redirect registered for that client. It is the
// app's own URL scheme, not a loopback port, so the browser hands the
// authorization code back through a local forwarder.
// app's own URL scheme, not a loopback port, so the operator pastes the
// redirect URL back into the console.
GoogleRedirectURI = "com.googleusercontent.apps.311745113120-qptt8h4kcsb3p2tbd8bpg3n9etvjf3km:/oauth2callback"

// UserAgent matches the signed-in Mac app (build 1179). The account API
Expand Down
14 changes: 13 additions & 1 deletion internal/providers/freemilk/freemilk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -112,9 +113,20 @@ func TestGoogleExchangeStoresRefreshableSession(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if !strings.Contains(session.AuthURL, "127.0.0.1") || !strings.Contains(session.AuthURL, "/launch") {
authURL, err := url.Parse(session.AuthURL)
if err != nil {
t.Fatal(err)
}
query := authURL.Query()
if authURL.Host != "accounts.google.com" || query.Get("redirect_uri") != GoogleRedirectURI || query.Get("state") != session.State || query.Get("code_challenge_method") != "S256" {
t.Fatalf("auth url %s", session.AuthURL)
}
if done, _, err := client.PollLogin(context.Background(), "acc"); done || err != nil {
t.Fatalf("poll done %v err %v", done, err)
}
if err := client.CompleteLogin(context.Background(), "acc", GoogleRedirectURI+"?code=auth-code&state=other"); err == nil {
t.Fatal("state mismatch accepted")
}
callback := GoogleRedirectURI + "?code=auth-code&state=" + session.State
if err := client.CompleteLogin(context.Background(), "acc", callback); err != nil {
t.Fatal(err)
Expand Down
179 changes: 28 additions & 151 deletions internal/providers/freemilk/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,29 @@ import (
"encoding/base64"
"encoding/hex"
"fmt"
"net"
"net/url"
"strings"
"time"

"github.com/caigee-cmd/cli2api/internal/auth"
"github.com/caigee-cmd/cli2api/internal/providers"
)

type loginPending struct {
state string
verifier string
deviceID string
createdAt time.Time
done bool
failed bool
message string
credential Credential
state string
verifier string
deviceID string
createdAt time.Time
}

// StartLogin opens the same Google authorization request the FreeMilk app
// opens: an authorization code with S256 PKCE, sent back to the redirect URI
// registered for the app's Google client.
// StartLogin returns the same Google authorization request the FreeMilk app
// opens: an authorization code with S256 PKCE and the redirect URI registered
// for the app's Google client. That redirect is a custom scheme, so no local
// listener can receive it, and on a server 127.0.0.1 is not the operator's
// browser anyway. The operator copies the redirect URL (it carries code and
// state) and pastes it back; CompleteLogin finishes the exchange.
func (c *Client) StartLogin(ctx context.Context, accountID string) (providers.LoginSession, error) {
_ = ctx
verifier, _, err := codeVerifier()
verifier, challenge, err := codeVerifier()
if err != nil {
return providers.LoginSession{}, err
}
Expand All @@ -44,9 +41,6 @@ func (c *Client) StartLogin(ctx context.Context, accountID string) (providers.Lo
if err != nil {
return providers.LoginSession{}, err
}
if err := c.ensureCallback(); err != nil {
return providers.LoginSession{}, err
}
c.mu.Lock()
c.pending[accountID] = &loginPending{
state: state,
Expand All @@ -55,50 +49,29 @@ func (c *Client) StartLogin(ctx context.Context, accountID string) (providers.Lo
createdAt: time.Now(),
}
c.mu.Unlock()
port, err := c.callbackPort()
if err != nil {
return providers.LoginSession{}, err
}
authURL := fmt.Sprintf("http://127.0.0.1:%d/launch?state=%s", port, url.QueryEscape(state))
return providers.LoginSession{AuthURL: authURL, State: state}, nil
return providers.LoginSession{AuthURL: googleAuthURL(state, challenge), State: state}, nil
}

// PollLogin only reports whether the pending login is still alive. The login
// completes through CompleteLogin, never through polling.
func (c *Client) PollLogin(ctx context.Context, accountID string) (bool, string, error) {
_ = ctx
c.mu.Lock()
defer c.mu.Unlock()
pending := c.pending[accountID]
c.mu.Unlock()
if pending == nil {
return false, "", fmt.Errorf("login not started")
}
if time.Since(pending.createdAt) > loginPendingTTL {
c.mu.Lock()
delete(c.pending, accountID)
c.mu.Unlock()
return false, "", fmt.Errorf("login expired; start again")
}
c.mu.Lock()
done := pending.done
failed := pending.failed
message := pending.message
credential := pending.credential
c.mu.Unlock()
if failed {
return false, "", fmt.Errorf("%s", firstNonEmpty(message, "login failed"))
}
if !done {
return false, firstNonEmpty(message, "waiting for authorization"), nil
}
if err := c.finishCredential(ctx, accountID, credential); err != nil {
return false, "", err
}
c.mu.Lock()
delete(c.pending, accountID)
c.mu.Unlock()
return true, "login complete", nil
return false, "sign in with Google, then paste the com.googleusercontent.apps…:/oauth2callback?code=… URL", nil
}

// CompleteLogin accepts the callback URL copied from the browser when the
// custom-scheme redirect did not reach the local forwarder.
// CompleteLogin accepts the custom-scheme redirect URL copied from the
// browser, exchanges the code with the pending PKCE verifier, and stores the
// FreeMilk session on the account.
func (c *Client) CompleteLogin(ctx context.Context, accountID, callbackURL string) error {
code, state, err := parseCallback(callbackURL)
if err != nil {
Expand All @@ -110,8 +83,14 @@ func (c *Client) CompleteLogin(ctx context.Context, accountID, callbackURL strin
if pending == nil {
return fmt.Errorf("login not started")
}
if state != "" && pending.state != "" && state != pending.state {
return fmt.Errorf("oauth state mismatch")
if time.Since(pending.createdAt) > loginPendingTTL {
c.mu.Lock()
delete(c.pending, accountID)
c.mu.Unlock()
return fmt.Errorf("login expired; start again")
}
if state != pending.state {
return fmt.Errorf("oauth state mismatch; use the URL from the latest sign-in")
}
client, err := c.httpClient(ctx, accountID)
if err != nil {
Expand All @@ -130,108 +109,6 @@ func (c *Client) CompleteLogin(ctx context.Context, accountID, callbackURL strin
return nil
}

// ensureCallback serves the custom-scheme redirect on 127.0.0.1. The browser
// is sent there with a redirect to the registered app URI, and the page hands
// the authorization code back to this process.
func (c *Client) ensureCallback() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.listener != nil {
return nil
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return fmt.Errorf("freemilk callback listen: %w", err)
}
c.listener = listener
auth.ServeSchemeBridge(listener, auth.SchemeBridge{
Authorize: c.authorizeState,
Callback: c.acceptCallback,
})
return nil
}

func (c *Client) authorizeState(state string) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
for _, pending := range c.pending {
if pending.state == state && !pending.done && !pending.failed {
return googleAuthURL(pending.state, codeChallenge(pending.verifier)), nil
}
}
return "", fmt.Errorf("login not started")
}

func (c *Client) callbackPort() (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
addr, ok := c.listener.Addr().(*net.TCPAddr)
if !ok || addr == nil {
return 0, fmt.Errorf("freemilk callback is not listening")
}
return addr.Port, nil
}

func (c *Client) acceptCallback(ctx context.Context, rawURL string) error {
code, state, err := parseCallback(rawURL)
if err != nil {
c.failPending(err.Error())
return err
}
c.mu.Lock()
var pending *loginPending
for _, candidate := range c.pending {
if candidate.done || candidate.failed {
continue
}
if state != "" && candidate.state != "" && state != candidate.state {
continue
}
pending = candidate
pending.message = "authorization received"
break
}
verifier := ""
deviceID := ""
if pending != nil {
verifier = pending.verifier
deviceID = pending.deviceID
}
c.mu.Unlock()
if pending == nil {
return fmt.Errorf("no freemilk login is waiting")
}
client, err := c.httpClient(ctx, "")
if err != nil {
c.failPending(err.Error())
return err
}
credential, err := c.exchangeGoogle(ctx, client, code, verifier, deviceID)
if err != nil {
c.failPending(err.Error())
return err
}
c.mu.Lock()
pending.credential = credential
pending.done = true
pending.message = "authorization received"
c.mu.Unlock()
return nil
}

func (c *Client) failPending(message string) {
c.mu.Lock()
defer c.mu.Unlock()
for _, pending := range c.pending {
if pending.done || pending.failed {
continue
}
pending.failed = true
pending.message = message
return
}
}

func googleAuthURL(state, challenge string) string {
query := url.Values{}
query.Set("client_id", GoogleClientID)
Expand Down

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading