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
80 changes: 78 additions & 2 deletions internal/command/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ package command

import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"syscall"
Expand Down Expand Up @@ -61,17 +64,19 @@ func NewWebCmd() *cobra.Command {
var port int
var host string
var openBrowser bool
var authToken string
cmd := &cobra.Command{
Use: "web",
Short: "Start the web server",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runWebServer(port, host, openBrowser)
return runWebServer(port, host, openBrowser, authToken)
},
}
cmd.Flags().IntVar(&port, "port", 8080, "HTTP server port")
cmd.Flags().StringVar(&host, "host", "127.0.0.1", "HTTP server host")
cmd.Flags().BoolVar(&openBrowser, "open", true, "Open browser after server starts")
cmd.Flags().StringVar(&authToken, "auth-token", "", "Bearer token required when bound to a non-loopback host (auto-generated if empty). Can also be set via JCODE_WEB_TOKEN.")
return cmd
}

Expand All @@ -97,7 +102,64 @@ func dropInteractiveTools(tools []tool.BaseTool) []tool.BaseTool {
return out
}

func runWebServer(port int, host string, openBrowser bool) error {
// resolveWebToken decides the web auth token and whether auth must be enforced.
//
// Auth is required when the bind host is non-loopback (exposed to the network),
// or when a token was explicitly supplied. Token source priority:
// 1. --auth-token flag / JCODE_WEB_TOKEN env — session-scoped, never written to disk
// 2. ~/.jcode/web_token — persisted (0600), reused across restarts
// 3. auto-generated (32 random bytes, base64url) when exposed and none of the
// above; persisted to ~/.jcode/web_token so the token is stable across restarts
func resolveWebToken(host, flagToken string) (token string, requireAuth bool, err error) {
explicit := flagToken
if explicit == "" {
explicit = os.Getenv("JCODE_WEB_TOKEN")
}
// Explicit token (flag/env): enforce auth, never touch disk (session-scoped).
if explicit != "" {
if !web.IsValidWSSubprotocolToken(explicit) {
return "", true, fmt.Errorf("auth token must be printable ASCII with no spaces or separators (it is sent as a WebSocket subprotocol)")
}
return explicit, true, nil
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
// Loopback bind with no explicit token: keep the existing no-auth behaviour.
if web.IsLoopbackBind(host) {
return "", false, nil
}
// Exposed bind, no explicit token: reuse a persisted token or generate one.
dir := config.ConfigDir()
path := filepath.Join(dir, "web_token")
if b, rerr := os.ReadFile(path); rerr == nil {
if t := strings.TrimSpace(string(b)); t != "" {
return t, true, nil
}
}
gen, gerr := generateWebToken()
if gerr != nil {
return "", true, fmt.Errorf("generate web token: %w", gerr)
}
// Ensure ~/.jcode exists before writing, otherwise a first remote start would
// fail with ENOENT and silently fall back to a session-scoped token.
if merr := os.MkdirAll(dir, 0o700); merr != nil {
config.Logger().Printf("[web] could not create config dir %s: %v", dir, merr)
} else if werr := os.WriteFile(path, []byte(gen), 0o600); werr != nil {
// Non-fatal: fall back to a session-scoped token (auth still enforced).
config.Logger().Printf("[web] could not persist web token to %s: %v", path, werr)
}
return gen, true, nil
}

// generateWebToken returns 32 cryptographically-random bytes as a URL-safe
// base64 string (no padding).
func generateWebToken() (string, error) {
var b [32]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b[:]), nil
}

func runWebServer(port int, host string, openBrowser bool, authToken string) error {
// Check if we need setup (no providers configured).
needsSetup := config.NeedsSetup()

Expand Down Expand Up @@ -540,6 +602,18 @@ func runWebServer(port int, host string, openBrowser bool) error {
}, nil
}

// Resolve the web auth token. Auth is enforced when bound to a non-loopback
// host (exposed to the network) or when a token was explicitly provided.
webToken, requireAuth, err := resolveWebToken(host, authToken)
if err != nil {
return err
}
if requireAuth {
fmt.Printf("\n🔐 Web access token (required when reaching %s):\n %s\n", host, webToken)
fmt.Printf(" Open http://%s:%d/ and paste this token to sign in.\n\n", host, port)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
config.Logger().Printf("[web] token auth enabled for non-loopback bind %q", host)
}

// Bootstrap engine for the initial task.
bootEC, err := buildWebTask("", pwd, startupMode.String(), nil, false)
if err != nil {
Expand Down Expand Up @@ -588,6 +662,8 @@ func runWebServer(port int, host string, openBrowser bool) error {
TokenUsage: bootEC.TokenUsage,
ContextBreakdownFn: bootEC.BreakdownFn,
Automations: autoStore,
AuthToken: webToken,
RequireAuth: requireAuth,
})

// Start the periodic automation scheduler. A single process owns periodic
Expand Down
147 changes: 147 additions & 0 deletions internal/web/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package web

import (
"crypto/subtle"
"net"
"net/http"
"strings"
)

// wsAuthSubprotocol is the WebSocket subprotocol name under which the bearer
// token rides on handshakes. Browsers cannot set custom headers on WebSocket
// connections, so the frontend sends ["jcode-auth", "<token>"] and the token is
// read from the second value. The server also advertises this subprotocol on
// the upgrader so gorilla echoes the protocol name back and the handshake
// completes cleanly.
const wsAuthSubprotocol = "jcode-auth"

// IsLoopbackBind reports whether the given bind host is loopback-only.
//
// An empty host, "0.0.0.0", or "::" binds all interfaces and is treated as
// exposed (non-loopback). "localhost" and any IP whose IsLoopback() is true are
// loopback. A hostname we cannot resolve statically is conservatively treated as
// exposed, so we fail safe (require auth) rather than fail open.
func IsLoopbackBind(host string) bool {
switch host {
case "", "0.0.0.0", "::":
return false
case "localhost":
return true
}
if ip := net.ParseIP(host); ip != nil {
return ip.IsLoopback()
}
return false // unknown hostname → assume exposed, require auth
}

// extractToken pulls the bearer token from a request, in priority order:
// 1. Authorization: Bearer <token>
// 2. Sec-WebSocket-Protocol: jcode-auth, <token> (browser WebSocket handshakes
// can't carry custom headers, so the token rides as the second subprotocol)
// 3. ?token=<token> (fallback for non-browser ws clients; discouraged because
// it lands in access logs, proxy logs and browser history)
func extractToken(r *http.Request) string {
if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") {
return strings.TrimSpace(strings.TrimPrefix(h, "Bearer "))
}
if protos := r.Header.Get("Sec-WebSocket-Protocol"); protos != "" {
parts := strings.Split(protos, ",")
for i, p := range parts {
if strings.TrimSpace(p) == wsAuthSubprotocol && i+1 < len(parts) {
return strings.TrimSpace(parts[i+1])
}
}
}
// The ?token= fallback exists only for non-browser WebSocket clients that can
// set neither a header nor a subprotocol. Restrict it to the WS endpoints so
// bearer tokens for normal HTTP APIs never land in access/proxy logs, the
// Referer header, or browser history.
if acceptsQueryToken(r.URL.Path) {
return r.URL.Query().Get("token")
}
return ""
}

// acceptsQueryToken reports whether the ?token= fallback is allowed for a path —
// only the WebSocket endpoints (the main event stream and the PTY sockets).
func acceptsQueryToken(path string) bool {
return path == "/api/ws" || (strings.HasPrefix(path, "/api/pty/") && strings.HasSuffix(path, "/ws"))
}

// IsValidWSSubprotocolToken reports whether s is usable as a WebSocket
// subprotocol value (RFC 6455 / RFC 7230 token): non-empty, printable ASCII with
// no spaces or separators. The frontend sends the token as the second WS
// subprotocol, so an explicit token containing such characters would make the
// browser's WebSocket constructor throw and break the connection at startup.
func IsValidWSSubprotocolToken(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if r < 0x21 || r > 0x7e {
return false // control chars, space, and non-ASCII
}
switch r {
case '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}':
return false // RFC 7230 separators
}
}
return true
}

// validToken compares the provided token against the expected one in constant
// time. An empty expected or provided token never validates.
func validToken(provided, expected string) bool {
if expected == "" || provided == "" {
return false
}
return subtle.ConstantTimeCompare([]byte(provided), []byte(expected)) == 1
}

// isAuthExempt reports whether a request may proceed without a token even when
// auth is required. It is a POSITIVE allowlist rather than a "/api/* needs auth"
// rule, so an unregistered /api path that falls through to the SPA handler can't
// sneak past: anything under /api/ requires a token unless explicitly listed.
func isAuthExempt(r *http.Request) bool {
if r.Method == http.MethodOptions {
return true // defensive: preflight is normally short-circuited by corsMiddleware
}
p := r.URL.Path
if r.Method == http.MethodGet && p == "/api/health" {
return true // the frontend probes this before it has a token
}
if r.Method == http.MethodPost && p == "/api/auth/verify" {
return true // the endpoint the login page calls to validate a typed token
}
// Everything outside /api/ is the SPA shell + embedded static assets: the
// login page itself must load before the user has a token.
return !strings.HasPrefix(p, "/api/")
}

// authMiddleware enforces token auth when requireAuth is set. corsMiddleware
// MUST wrap this — corsMiddleware(s.authMiddleware(mux)) — so OPTIONS preflights
// are answered by cors and never reach here without an Authorization header.
func (s *Server) authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !s.requireAuth || isAuthExempt(r) {
next.ServeHTTP(w, r)
return
}
if !validToken(extractToken(r), s.authToken) {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
return
}
next.ServeHTTP(w, r)
})
}

// handleAuthVerify lets the login page check a token the user typed in. It reads
// the token the same way the middleware does and returns 200 on a match, 401
// otherwise. When auth is not required it always succeeds.
func (s *Server) handleAuthVerify(w http.ResponseWriter, r *http.Request) {
if !s.requireAuth || validToken(extractToken(r), s.authToken) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
return
}
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid token"})
}
Loading
Loading