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// ---- handlers ----
99
100func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
101 if r.URL.Path != "/" {
102 http.NotFound(w, r)
103 return
104 }
105 tpl.ExecuteTemplate(w, "index", map[string]any{
106 "Port": s.Port(),
107 })
108}
109
110func (s *Server) handleAPIKey(w http.ResponseWriter, r *http.Request) {
111 switch r.Method {
112 case http.MethodGet:
113 provider := r.URL.Query().Get("provider")
114 if provider != "anthropic" && provider != "openai" {
115 http.Error(w, "provider must be anthropic or openai", http.StatusBadRequest)
116 return
117 }
118 tpl.ExecuteTemplate(w, "apikey", map[string]any{"Provider": provider})
119 case http.MethodPost:
120 if err := r.ParseForm(); err != nil {
121 http.Error(w, err.Error(), http.StatusBadRequest)
122 return
123 }
124 provider := strings.TrimSpace(r.FormValue("provider"))
125 key := strings.TrimSpace(r.FormValue("api_key"))
126 if provider == "" || key == "" {
127 s.errorPage(w, "missing provider or api key")
128 return
129 }
130 ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
131 defer cancel()
132 if err := s.probeFn(ctx, provider, key); err != nil {
133 s.errorPage(w, err.Error())
134 s.results <- LoginResult{Provider: provider, Method: "apikey", Err: err}
135 return
136 }
137 s.successPage(w, provider, "api key")
138 s.results <- LoginResult{Provider: provider, Method: "apikey", APIKey: key}
139 default:
140 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
141 }
142}
143
144func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
145 q := r.URL.Query()
146 provider := q.Get("provider")
147 if provider == "" {
148 // Some OAuth providers don't echo back custom params; try state-encoded form.
149 provider = decodeStateProvider(q.Get("state"))
150 }
151 if errParam := q.Get("error"); errParam != "" {
152 msg := errParam
153 if d := q.Get("error_description"); d != "" {
154 msg += ": " + d
155 }
156 s.errorPage(w, msg)
157 s.results <- LoginResult{Provider: provider, Method: "oauth", Err: fmt.Errorf(msg)}
158 return
159 }
160 code := q.Get("code")
161 state := q.Get("state")
162 if code == "" {
163 s.errorPage(w, "missing authorization code")
164 s.results <- LoginResult{Provider: provider, Method: "oauth", Err: fmt.Errorf("missing code")}
165 return
166 }
167 s.successPage(w, provider, "subscription")
168 s.results <- LoginResult{Provider: provider, Method: "oauth", Code: code, State: state}
169}
170
171func (s *Server) handleSuccess(w http.ResponseWriter, r *http.Request) {
172 q := r.URL.Query()
173 s.successPage(w, q.Get("provider"), q.Get("method"))
174}
175
176func (s *Server) handleError(w http.ResponseWriter, r *http.Request) {
177 s.errorPage(w, r.URL.Query().Get("message"))
178}
179
180func (s *Server) successPage(w http.ResponseWriter, provider, method string) {
181 w.Header().Set("content-type", "text/html; charset=utf-8")
182 tpl.ExecuteTemplate(w, "success", map[string]any{
183 "Provider": provider,
184 "Method": method,
185 })
186}
187
188func (s *Server) errorPage(w http.ResponseWriter, msg string) {
189 w.Header().Set("content-type", "text/html; charset=utf-8")
190 w.WriteHeader(http.StatusBadRequest)
191 tpl.ExecuteTemplate(w, "error", map[string]any{"Message": msg})
192}
193
194// decodeStateProvider extracts the provider from a state string of the
195// form "<provider>:<nonce>".
196func decodeStateProvider(state string) string {
197 if i := strings.IndexByte(state, ':'); i > 0 {
198 return state[:i]
199 }
200 return ""
201}
202
203// BuildRedirectURI returns the callback URL the OAuth server should
204// redirect to.
205func (s *Server) BuildRedirectURI() string {
206 return s.baseURL + "/callback"
207}
208
209// Redirect sends an HTTP redirect to u. Used by the TUI to tell the
210// browser to bounce through our local server. Not currently used; kept
211// for future flows.
212func Redirect(w http.ResponseWriter, r *http.Request, u *url.URL) {
213 http.Redirect(w, r, u.String(), http.StatusFound)
214}
215
216// ---- templates ----
217//
218// All pages share the monochrome monoStyle defined in callback.go so
219// the browser tab looks like the tui: black on white, monospace, thin
220// rules, no rounded boxes, no color.
221
222var tpl = template.Must(template.New("index").Parse(`<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>zot login</title>` + monoStyle + `</head><body>
223` + logoTag + `
224<h1>zot login</h1>
225<hr class="rule">
226<p>paste an api key for anthropic or openai. zot probes the provider once, then saves the key to <span class="mono">~/Library/Application Support/zot/auth.json</span>.</p>
227<p>
228 <a href="/apikey?provider=anthropic">anthropic api key →</a><br>
229 <a href="/apikey?provider=openai">openai api key →</a>
230</p>
231<hr class="rule">
232<p class="muted">for a subscription login (claude pro/max · chatgpt plus/pro), close this tab and run /login inside zot.</p>
233</body></html>`))
234
235func init() {
236 template.Must(tpl.New("apikey").Parse(`<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>zot login</title>` + monoStyle + `<style>
237 form { display: flex; flex-direction: column; gap: 0.75rem; }
238 label { font-size: 0.875rem; }
239</style></head><body>
240` + logoTag + `
241<h1>zot login · {{.Provider}} api key</h1>
242<hr class="rule">
243<p>paste your {{.Provider}} api key. zot will probe the provider with it once, then save it if the key is accepted.</p>
244<form method="POST" action="/apikey">
245 <input type="hidden" name="provider" value="{{.Provider}}" />
246 <label for="api_key">api key</label>
247 <input id="api_key" name="api_key" type="password" autocomplete="off" autofocus />
248 <button type="submit">log in</button>
249</form>
250</body></html>`))
251
252 template.Must(tpl.New("success").Parse(`<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>zot · logged in</title>` + monoStyle + `</head><body>
253` + logoTag + `
254<h1><span class="mark">✓</span> logged in to {{.Provider}}</h1>
255<hr class="rule">
256<p class="msg">method: {{.Method}}</p>
257<p class="muted">zot received the callback. you can close this tab and return to the terminal.</p>
258</body></html>`))
259
260 template.Must(tpl.New("error").Parse(`<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>zot · error</title>` + monoStyle + `</head><body>
261` + logoTag + `
262<h1><span class="mark">✗</span> login failed</h1>
263<hr class="rule">
264<p class="msg mono">{{.Message}}</p>
265<p class="muted">go back to zot and try again.</p>
266</body></html>`))
267}