package server import ( "context" "crypto/sha256" "crypto/subtle" "encoding/base64" "errors" "net" "net/http" "net/url" "regexp" "strings" "time" "pageswiki/internal/store" ) var cliProofPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`) var cliVerifierPattern = regexp.MustCompile(`^[A-Za-z0-9._~-]{43,128}$`) func cliOrigin(r *http.Request) string { return strings.ToLower(externalURL(r, "")) } func cliSecureTransport(r *http.Request) bool { if requestIsHTTPS(r) { return true } host := r.Host if h, _, err := net.SplitHostPort(host); err == nil { host = h } return host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "[::1]" } func cliVerifyPath(id string) string { return "/_/auth/cli/verify?request=" + url.QueryEscape(id) } func cliConsentCSRF(token, id string) string { sum := sha256.Sum256([]byte("pages-cli-consent:" + token + ":" + id)) return base64.RawURLEncoding.EncodeToString(sum[:]) } func (s *Server) handleCLIAuth(w http.ResponseWriter, r *http.Request, action string) { w.Header().Set("Cache-Control", "private, no-store") w.Header().Set("Referrer-Policy", "no-referrer") w.Header().Set("X-Frame-Options", "DENY") if !cliSecureTransport(r) { writeEventJSON(w, 400, map[string]string{"error": "https_required"}) return } ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() r = r.WithContext(ctx) domain := s.domainUUIDForRequest(r) config, err := s.store.AuthProviderConfig(domain, "oidc") if err != nil || !config.Enabled { writeEventJSON(w, 403, map[string]string{"error": "oidc_disabled"}) return } if action == "cli/verify" { s.verifyCLIAuth(w, r) return } if r.Method != http.MethodPost { w.Header().Set("Allow", "POST") http.Error(w, "method not allowed", 405) return } r.Body = http.MaxBytesReader(w, r.Body, 4096) if err := r.ParseForm(); err != nil { writeEventJSON(w, 400, map[string]string{"error": "invalid_request"}) return } switch action { case "cli/start": challenge := r.PostForm.Get("code_challenge") if !cliProofPattern.MatchString(challenge) || r.PostForm.Get("code_challenge_method") != "S256" { writeEventJSON(w, 400, map[string]string{"error": "invalid_request"}) return } id, device, code, err := s.store.StartCLIAuth(ctx, domain, cliOrigin(r), challenge) if err != nil { cliAuthError(w, err) return } writeEventJSON(w, 200, map[string]any{"device_code": device, "verification_uri": cliVerifyPath(id), "user_code": code[:4] + "-" + code[4:], "expires_in": 300, "interval": 5}) case "cli/token": device, verifier := r.PostForm.Get("device_code"), r.PostForm.Get("code_verifier") if !cliProofPattern.MatchString(device) || !cliVerifierPattern.MatchString(verifier) { writeEventJSON(w, 400, map[string]string{"error": "invalid_request"}) return } token, name, expires, err := s.store.ExchangeCLIAuth(ctx, domain, cliOrigin(r), device, verifier) if err != nil { cliAuthError(w, err) return } writeEventJSON(w, 200, map[string]any{"access_token": token, "token_type": "Bearer", "username": name, "expires_in": max(1, (expires-time.Now().UnixMilli())/1000)}) default: http.NotFound(w, r) } } func cliAuthError(w http.ResponseWriter, err error) { code, status := "temporarily_unavailable", 503 switch { case errors.Is(err, store.ErrCLIPending): code, status = "authorization_pending", 400 case errors.Is(err, store.ErrCLISlowDown): code, status = "slow_down", 400 case errors.Is(err, store.ErrCLIExpired): code, status = "expired_token", 400 case errors.Is(err, store.ErrAccessDenied): code, status = "access_denied", 403 case errors.Is(err, store.ErrCLILimit): code, status = "too_many_requests", 429 } writeEventJSON(w, status, map[string]string{"error": code}) } func (s *Server) verifyCLIAuth(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet && r.Method != http.MethodPost { w.Header().Set("Allow", "GET, POST") http.Error(w, "method not allowed", 405) return } r.Body = http.MaxBytesReader(w, r.Body, 4096) if err := r.ParseForm(); err != nil { http.Error(w, "invalid request", 400) return } id := r.URL.Query().Get("request") if r.Method == http.MethodPost { id = r.PostForm.Get("request") } if !cliProofPattern.MatchString(id) { http.NotFound(w, r) return } domain := s.domainUUIDForRequest(r) grant, err := s.store.CLIAuthRequest(r.Context(), domain, cliOrigin(r), id) if err != nil { http.Error(w, "CLI request expired; restart pages login --oidc", 410) return } data := map[string]any{"CLIAuth": true, "CLIOrigin": grant.Origin, "CLIRequest": id} if grant.State != "pending" { data["CLIDone"] = true s.renderAuthPage(w, r, data) return } if grant.BrowserHash == "" { if r.Method != http.MethodGet { http.Error(w, "OIDC login required", 403) return } data["CLILogin"] = "/_/auth/oidc?cli=" + url.QueryEscape(id) s.renderAuthPage(w, r, data) return } token := s.authTokenFromRequest(r) sum := sha256.Sum256([]byte(token)) hash := base64.RawURLEncoding.EncodeToString(sum[:]) principal, err := s.store.PrincipalForSession(domain, token) if !strings.HasPrefix(token, "pw_browser_") || hash != grant.BrowserHash || err != nil { http.Error(w, "This request belongs to another browser. Restart CLI login.", 403) return } data["CLIUsername"] = principal.Username data["CLICSRF"] = cliConsentCSRF(token, id) data["CLITOTP"] = s.store.HasTOTP(principal.UUID) if r.Method == http.MethodPost { if !validBrowserMutationOrigin(r) || subtle.ConstantTimeCompare([]byte(r.PostForm.Get("csrf")), []byte(cliConsentCSRF(token, id))) != 1 { http.Error(w, "invalid approval origin or token", 403) return } decision := r.PostForm.Get("decision") if decision != "approve" && decision != "deny" { http.Error(w, "invalid decision", 400) return } err = s.store.DecideCLIAuth(r.Context(), domain, cliOrigin(r), id, token, r.PostForm.Get("user_code"), r.PostForm.Get("totp"), decision == "approve") if err != nil { data["Error"] = translate(s.getLocale(domain), "auth.cli_invalid") } else { data["CLIDone"] = true } } s.renderAuthPage(w, r, data) }