1package auth
2
3import (
4 "context"
5 "fmt"
6 "html/template"
7 "net"
8 "net/http"
9 "net/url"
10 "strings"
11 "sync"
12 "time"
13)
14
15// LoginResult is delivered on the channel returned by Server.Result().
16type LoginResult struct {
17 Provider string
18 Method string // "apikey" | "oauth"
19 APIKey string // populated when Method == "apikey"
20 Code string // populated when Method == "oauth"
21 State string // OAuth state (caller should verify)
22 Err error
23}
24
25// Server is a tiny local HTTP server used by the login flows. It binds
26// to 127.0.0.1 on a random free port and serves:
27//
28// GET / landing page (menu)
29// GET /apikey?provider=... API key form
30// POST /apikey form submit -> probes -> stores via caller
31// GET /callback OAuth callback (query: code, state)
32// GET /success generic success page
33// GET /error generic error page
34//
35// The caller receives login events on Result(). The server stays up
36// until Shutdown() is called.
37type Server struct {
38 l net.Listener
39 srv *http.Server
40 baseURL string
41 results chan LoginResult
42 probeFn func(ctx context.Context, provider, key string) error
43 mu sync.Mutex
44 shutdown bool
45}
46
47// NewServer starts a new login server on a random free port bound to loopback.
48func NewServer() (*Server, error) {
49 l, err := net.Listen("tcp", "127.0.0.1:0")
50 if err != nil {
51 return nil, err
52 }
53 s := &Server{
54 l: l,
55 baseURL: "http://" + l.Addr().String(),
56 results: make(chan LoginResult, 4),
57 probeFn: ProbeAPIKey,
58 }
59 mux := http.NewServeMux()
60 mux.HandleFunc("/", s.handleIndex)
61 mux.HandleFunc("/apikey", s.handleAPIKey)
62 mux.HandleFunc("/callback", s.handleCallback)
63 mux.HandleFunc("/success", s.handleSuccess)
64 mux.HandleFunc("/error", s.handleError)
65 mux.HandleFunc("/logo.png", serveLogo)
66 s.srv = &http.Server{
67 Handler: mux,
68 ReadTimeout: 15 * time.Second,
69 WriteTimeout: 15 * time.Second,
70 }
71 go func() { _ = s.srv.Serve(l) }()
72 return s, nil
73}
74
75// URL returns the base URL the server is listening on.
76func (s *Server) URL() string { return s.baseURL }
77
78// Port returns the TCP port the server is bound to.
79func (s *Server) Port() int {
80 return s.l.Addr().(*net.TCPAddr).Port
81}
82
83// Result returns the channel receiving LoginResult events.
84func (s *Server) Result() <-chan LoginResult { return s.results }
85
86// Shutdown stops the server. It is safe to call multiple times.
87func (s *Server) Shutdown(ctx context.Context) error {
88 s.mu.Lock()
89 if s.shutdown {
90 s.mu.Unlock()
91 return nil
92 }
93 s.shutdown = true
94 s.mu.Unlock()
95 return s.srv.Shutdown(ctx)
96}
97
98// isKnownAPIKeyProvider reports whether the given provider supports
99// API-key login through the loopback flow. OAuth-only paths are handled
100// elsewhere (manager.StartOAuth).
101func isKnownAPIKeyProvider(p string) bool {
102 for _, provider := range APIKeyProviders() {
103 if p == provider {
104 return true
105 }
106 }
107 return false
108}
109
110func apiKeyProviderMessage() string {
111 return "provider must be one of: " + strings.Join(APIKeyProviders(), ", ")
112}
113
114// APIKeyProviders is the ordered list shown by /login -> api key.
115func APIKeyProviders() []string {
116 return []string{
117 "anthropic", "openai", "kimi", "deepseek", "google",
118 "moonshotai", "moonshotai-cn", "groq", "cerebras", "xai", "together",
119 "huggingface", "openrouter", "mistral", "zai",
120 "xiaomi", "xiaomi-token-plan-ams", "xiaomi-token-plan-cn", "xiaomi-token-plan-sgp",
121 "minimax", "minimax-cn", "fireworks", "vercel-ai-gateway",
122 "opencode", "opencode-go", "amazon-bedrock", "google-vertex", "azure-openai-responses",
123 "github-copilot", "cloudflare-workers-ai", "cloudflare-ai-gateway",
124 }
125}
126
127// ---- handlers ----
128
129func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
130 if r.URL.Path != "/" {
131 http.NotFound(w, r)
132 return
133 }
134 tpl.ExecuteTemplate(w, "index", map[string]any{
135 "Port": s.Port(),
136 })
137}
138
139func (s *Server) handleAPIKey(w http.ResponseWriter, r *http.Request) {
140 switch r.Method {
141 case http.MethodGet:
142 provider := r.URL.Query().Get("provider")
143 if !isKnownAPIKeyProvider(provider) {
144 http.Error(w, apiKeyProviderMessage(), http.StatusBadRequest)
145 return
146 }
147 tpl.ExecuteTemplate(w, "apikey", map[string]any{"Provider": provider})
148 case http.MethodPost:
149 if err := r.ParseForm(); err != nil {
150 http.Error(w, err.Error(), http.StatusBadRequest)
151 return
152 }
153 provider := strings.TrimSpace(r.FormValue("provider"))
154 key := strings.TrimSpace(r.FormValue("api_key"))
155 if provider == "" || key == "" {
156 s.errorPage(w, "missing provider or api key")
157 return
158 }
159 ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
160 defer cancel()
161 if err := s.probeFn(ctx, provider, key); err != nil {
162 s.errorPage(w, err.Error())
163 s.results <- LoginResult{Provider: provider, Method: "apikey", Err: err}
164 return
165 }
166 s.successPage(w, provider, "api key")
167 s.results <- LoginResult{Provider: provider, Method: "apikey", APIKey: key}
168 default:
169 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
170 }
171}
172
173func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
174 q := r.URL.Query()
175 provider := q.Get("provider")
176 if provider == "" {
177 // Some OAuth providers don't echo back custom params; try state-encoded form.
178 provider = decodeStateProvider(q.Get("state"))
179 }
180 if errParam := q.Get("error"); errParam != "" {
181 msg := errParam
182 if d := q.Get("error_description"); d != "" {
183 msg += ": " + d
184 }
185 s.errorPage(w, msg)
186 s.results <- LoginResult{Provider: provider, Method: "oauth", Err: fmt.Errorf(msg)}
187 return
188 }
189 code := q.Get("code")
190 state := q.Get("state")
191 if code == "" {
192 s.errorPage(w, "missing authorization code")
193 s.results <- LoginResult{Provider: provider, Method: "oauth", Err: fmt.Errorf("missing code")}
194 return
195 }
196 s.successPage(w, provider, "subscription")
197 s.results <- LoginResult{Provider: provider, Method: "oauth", Code: code, State: state}
198}
199
200func (s *Server) handleSuccess(w http.ResponseWriter, r *http.Request) {
201 q := r.URL.Query()
202 s.successPage(w, q.Get("provider"), q.Get("method"))
203}
204
205func (s *Server) handleError(w http.ResponseWriter, r *http.Request) {
206 s.errorPage(w, r.URL.Query().Get("message"))
207}
208
209func (s *Server) successPage(w http.ResponseWriter, provider, method string) {
210 w.Header().Set("content-type", "text/html; charset=utf-8")
211 tpl.ExecuteTemplate(w, "success", map[string]any{
212 "Provider": provider,
213 "Method": method,
214 })
215}
216
217func (s *Server) errorPage(w http.ResponseWriter, msg string) {
218 w.Header().Set("content-type", "text/html; charset=utf-8")
219 w.WriteHeader(http.StatusBadRequest)
220 tpl.ExecuteTemplate(w, "error", map[string]any{"Message": msg})
221}
222
223// decodeStateProvider extracts the provider from a state string of the
224// form "<provider>:<nonce>".
225func decodeStateProvider(state string) string {
226 if i := strings.IndexByte(state, ':'); i > 0 {
227 return state[:i]
228 }
229 return ""
230}
231
232// BuildRedirectURI returns the callback URL the OAuth server should
233// redirect to.
234func (s *Server) BuildRedirectURI() string {
235 return s.baseURL + "/callback"
236}
237
238// Redirect sends an HTTP redirect to u. Used by the TUI to tell the
239// browser to bounce through our local server. Not currently used; kept
240// for future flows.
241func Redirect(w http.ResponseWriter, r *http.Request, u *url.URL) {
242 http.Redirect(w, r, u.String(), http.StatusFound)
243}
244
245// ---- templates ----
246//
247// All pages share the monochrome monoStyle defined in callback.go so
248// the browser tab looks like the tui: black on white, monospace, thin
249// rules, no rounded boxes, no color.
250
251var tpl = template.Must(template.New("index").Parse(`<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>zot login</title>` + monoStyle + `</head><body>
252` + logoTag + `
253<h1><span class="zot">zot</span> login</h1>
254<hr class="rule">
255<p>paste an api key for anthropic, openai, kimi, deepseek, or google. <span class="zot">zot</span> probes the provider once, then saves the key to <span class="mono">~/Library/Application Support/zot/auth.json</span>.</p>
256<p>
257 <a href="/apikey?provider=anthropic">anthropic api key →</a><br>
258 <a href="/apikey?provider=openai">openai api key →</a><br>
259 <a href="/apikey?provider=kimi">kimi api key →</a><br>
260 <a href="/apikey?provider=deepseek">deepseek api key →</a><br>
261 <a href="/apikey?provider=google">google gemini api key →</a>
262</p>
263<hr class="rule">
264<p class="muted">for a subscription login (claude pro/max - chatgpt plus/pro - kimi code - github copilot), close this tab and run /login inside <span class="zot">zot</span>.</p>
265</body></html>`))
266
267func init() {
268 template.Must(tpl.New("apikey").Parse(`<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>zot login</title>` + monoStyle + `<style>
269 form { display: flex; flex-direction: column; gap: 0.75rem; }
270 label { font-size: 0.875rem; }
271</style></head><body>
272` + logoTag + `
273<h1><span class="zot">zot</span> login - {{.Provider}} api key</h1>
274<hr class="rule">
275<p>paste your {{.Provider}} api key. <span class="zot">zot</span> will probe the provider with it once, then save it if the key is accepted.</p>
276<form method="POST" action="/apikey">
277 <input type="hidden" name="provider" value="{{.Provider}}" />
278 <label for="api_key">api key</label>
279 <input id="api_key" name="api_key" type="password" autocomplete="off" autofocus />
280 <button type="submit">log in</button>
281</form>
282</body></html>`))
283
284 template.Must(tpl.New("success").Parse(`<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>zot - logged in</title>` + monoStyle + `</head><body>
285` + logoTag + `
286<h1><span class="mark">✓</span> logged in to {{.Provider}}</h1>
287<hr class="rule">
288<p class="msg">method: {{.Method}}</p>
289<p class="muted"><span class="zot">zot</span> received the callback. you can close this tab and return to the terminal.</p>
290</body></html>`))
291
292 template.Must(tpl.New("error").Parse(`<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>zot - error</title>` + monoStyle + `</head><body>
293` + logoTag + `
294<h1><span class="mark">✗</span> login failed</h1>
295<hr class="rule">
296<p class="msg mono">{{.Message}}</p>
297<p class="muted">go back to <span class="zot">zot</span> and try again.</p>
298</body></html>`))
299}