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-google-code-login.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### English

- FreeMilk sign-in follows the app: Google returns an authorization code to the registered redirect, and that code is exchanged before the account login.

### 中文

- FreeMilk 登录与应用一致:Google 把授权码回到已登记的回调地址,再用这个授权码完成账号登录。
23 changes: 23 additions & 0 deletions internal/auth/loopback.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,26 @@ 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) }()
}
100 changes: 97 additions & 3 deletions internal/providers/freemilk/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package freemilk
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
Expand Down Expand Up @@ -40,13 +42,105 @@ type limitRow struct {
Used float64
}

func (c *Client) exchangeGoogle(ctx context.Context, client *http.Client, identityToken, deviceID string) (Credential, error) {
body := map[string]string{"identity_token": identityToken}
type googleUserInfo struct {
Email string `json:"email,omitempty"`
Name string `json:"name,omitempty"`
}

type googleTokenResponse struct {
IDToken string `json:"id_token"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
Error string `json:"error"`
ErrorDesc string `json:"error_description"`
}

// exchangeGoogle repeats the app's two calls: the authorization code becomes a
// Google identity token, then that token is posted to /auth/google. DeviceCheck
// is omitted; the account API accepts the request without it.
func (c *Client) exchangeGoogle(ctx context.Context, client *http.Client, code, verifier, deviceID string) (Credential, error) {
identity, err := c.googleIdentityToken(ctx, client, code, verifier)
if err != nil {
return Credential{}, err
}
body := map[string]any{"identity_token": identity.IDToken}
if identity.Email != "" || identity.Name != "" {
body["user_info"] = googleUserInfo{Email: identity.Email, Name: identity.Name}
}
var token tokenResponse
if err := c.postJSON(ctx, client, deviceID, "", "/auth/google", body, &token); err != nil {
return Credential{}, err
}
return credentialFromToken(token, deviceID), nil
credential := credentialFromToken(token, deviceID)
if credential.Email == "" {
credential.Email = identity.Email
}
if credential.Name == "" {
credential.Name = identity.Name
}
return credential, nil
}

type googleIdentity struct {
IDToken string
Email string
Name string
}

func (c *Client) googleIdentityToken(ctx context.Context, client *http.Client, code, verifier string) (googleIdentity, error) {
form := url.Values{}
form.Set("client_id", GoogleClientID)
form.Set("code", code)
form.Set("code_verifier", verifier)
form.Set("grant_type", "authorization_code")
form.Set("redirect_uri", GoogleRedirectURI)
request, err := http.NewRequestWithContext(ctx, http.MethodPost, GoogleTokenURL, strings.NewReader(form.Encode()))
if err != nil {
return googleIdentity{}, err
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.Header.Set("Accept", "*/*")
request.Header.Set("User-Agent", UserAgent)
request.Header.Set("Accept-Language", "en-US,en;q=0.9")
response, err := client.Do(request)
if err != nil {
return googleIdentity{}, err
}
defer response.Body.Close()
payload, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
if err != nil {
return googleIdentity{}, err
}
var token googleTokenResponse
if err := json.Unmarshal(payload, &token); err != nil {
return googleIdentity{}, fmt.Errorf("google token response is not json")
}
if response.StatusCode >= 300 || token.IDToken == "" {
message := firstNonEmpty(token.ErrorDesc, token.Error, errorMessage(string(payload)))
return googleIdentity{}, fmt.Errorf("google token exchange failed: %s", firstNonEmpty(message, "no identity token"))
}
email, name := identityClaims(token.IDToken)
return googleIdentity{IDToken: token.IDToken, Email: email, Name: name}, nil
}

func identityClaims(idToken string) (email, name string) {
parts := strings.Split(idToken, ".")
if len(parts) < 2 {
return "", ""
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return "", ""
}
var claims struct {
Email string `json:"email"`
Name string `json:"name"`
}
if err := json.Unmarshal(payload, &claims); err != nil {
return "", ""
}
return strings.TrimSpace(claims.Email), strings.TrimSpace(claims.Name)
}

func (c *Client) refresh(ctx context.Context, client *http.Client, credential Credential) (Credential, error) {
Expand Down
7 changes: 7 additions & 0 deletions internal/providers/freemilk/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ const (
// Google client id is the one embedded in FreeMilk 2.4.0. The identity
// 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.
GoogleRedirectURI = "com.googleusercontent.apps.311745113120-qptt8h4kcsb3p2tbd8bpg3n9etvjf3km:/oauth2callback"

// UserAgent matches the signed-in Mac app (build 1179). The account API
// rejects other clients before it looks at the token.
Expand All @@ -40,3 +44,6 @@ type hostedModel struct {
Premium bool
Reasoning bool
}

// GoogleTokenURL is the authorization-code token endpoint. Tests replace it.
var GoogleTokenURL = "https://oauth2.googleapis.com/token"
27 changes: 20 additions & 7 deletions internal/providers/freemilk/freemilk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package freemilk

import (
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
Expand Down Expand Up @@ -55,20 +56,24 @@ func (s *memoryStore) GetSecret(_ context.Context, key string) (string, bool, er
return value, ok, nil
}

func TestCallbackKeepsIdentityTokenFromFragment(t *testing.T) {
token, state, err := parseCallback("http://127.0.0.1:1234/callback#id_token=abc.def&state=xyz")
func TestCallbackReadsAuthorizationCode(t *testing.T) {
code, state, err := parseCallback("com.googleusercontent.apps.example:/oauth2callback?code=abc&state=xyz")
if err != nil {
t.Fatal(err)
}
if token != "abc.def" || state != "xyz" {
t.Fatalf("token %q state %q", token, state)
if code != "abc" || state != "xyz" {
t.Fatalf("code %q state %q", code, state)
}
}

func TestGoogleExchangeStoresRefreshableSession(t *testing.T) {
var gotHeader, gotBody string
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/token") {
_ = json.NewEncoder(w).Encode(map[string]string{"id_token": testIdentityToken("a@example.com", "Ada")})
return
}
if r.URL.Path != "/auth/google" && r.URL.Path != "/auth/me" {
return
}
Expand Down Expand Up @@ -99,19 +104,22 @@ func TestGoogleExchangeStoresRefreshableSession(t *testing.T) {
client := NewClient(store)
client.apiBase = server.URL
client.http = server.Client()
savedTokenURL := GoogleTokenURL
GoogleTokenURL = server.URL + "/token"
t.Cleanup(func() { GoogleTokenURL = savedTokenURL })

session, err := client.StartLogin(context.Background(), "acc")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(session.AuthURL, "accounts.google.com") || !strings.Contains(session.AuthURL, "id_token") {
if !strings.Contains(session.AuthURL, "127.0.0.1") || !strings.Contains(session.AuthURL, "/launch") {
t.Fatalf("auth url %s", session.AuthURL)
}
callback := "http://127.0.0.1/callback#id_token=google-token&state=" + session.State
callback := GoogleRedirectURI + "?code=auth-code&state=" + session.State
if err := client.CompleteLogin(context.Background(), "acc", callback); err != nil {
t.Fatal(err)
}
if gotHeader != ClientType || !strings.Contains(gotBody, "identity_token") {
if gotHeader != ClientType || !strings.Contains(gotBody, "identity_token") || !strings.Contains(gotBody, "user_info") {
t.Fatalf("header %q body %s", gotHeader, gotBody)
}
credential, err := DecodeCredential(store.credentials["acc"])
Expand Down Expand Up @@ -225,3 +233,8 @@ func TestClassifyAllowanceAsQuota(t *testing.T) {
t.Fatalf("auth %+v", auth)
}
}

func testIdentityToken(email, name string) string {
payload, _ := json.Marshal(map[string]string{"email": email, "name": name})
return "header." + base64.RawURLEncoding.EncodeToString(payload) + ".sig"
}
Loading
Loading