High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: auth session models and remove duplicate session re-auth
Luigi Agosti0c4d96edd3f4
diff --git a/internal/authn/cookie.go b/internal/authn/cookie.goindex 9b9f063b..796a3a1a 100644--- a/internal/authn/cookie.go+++ b/internal/authn/cookie.go@@ -7,12 +7,14 @@ import ("time")+const defaultSessionCookieLifetime = 7 * 24 * time.Hour+// SetSessionCookie stores the opaque dashboard session id in an HttpOnly// same-site cookie so browser APIs can authenticate without exposing the// underlying bearer token to JavaScript.func SetSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string, maxLifetime time.Duration, trustProxy bool, cookieSecure *bool) {if maxLifetime <= 0 {- maxLifetime = DefaultSessionMaxLifetime+ maxLifetime = defaultSessionCookieLifetime}http.SetCookie(w, &http.Cookie{Name: CookieName,diff --git a/internal/authn/session.go b/internal/browsersession/session.gosimilarity index 86%rename from internal/authn/session.gorename to internal/browsersession/session.goindex 1b0d4d6a..1edb7b16 100644--- a/internal/authn/session.go+++ b/internal/browsersession/session.go@@ -1,4 +1,4 @@-package authn+package browsersessionimport ("crypto/rand"@@ -18,7 +18,7 @@ const (DefaultSessionElevationWindow = 15 * time.Minute)-type SessionConfig struct {+type Config struct {IdleTimeout time.DurationMaxLifetime time.DurationElevationWindow time.Duration@@ -27,7 +27,7 @@ type SessionConfig struct {PersistElevationAcrossRestart bool}-type SessionManager struct {+type Manager struct {mu sync.Mutexsessions map[string]sessionStateidleTimeout time.Duration@@ -59,8 +59,8 @@ type persistedSessionRecord struct {TokenHash string `json:"tokenHash"`}-func NewSessionManager(cfg SessionConfig) *SessionManager {- m := &SessionManager{+func NewManager(cfg Config) *Manager {+ m := &Manager{sessions: make(map[string]sessionState),now: time.Now,}@@ -71,7 +71,7 @@ func NewSessionManager(cfg SessionConfig) *SessionManager {return m}-func (m *SessionManager) Create(token string) (string, error) {+func (m *Manager) Create(token string) (string, error) {if m == nil {return "", nil}@@ -91,7 +91,7 @@ func (m *SessionManager) Create(token string) (string, error) {return id, nil}-func (m *SessionManager) Validate(sessionID, token string) bool {+func (m *Manager) Validate(sessionID, token string) bool {if m == nil {return false}@@ -121,7 +121,7 @@ func (m *SessionManager) Validate(sessionID, token string) bool {return true}-func (m *SessionManager) Elevate(sessionID, token string) bool {+func (m *Manager) Elevate(sessionID, token string) bool {if m == nil {return false}@@ -152,7 +152,7 @@ func (m *SessionManager) Elevate(sessionID, token string) bool {return true}-func (m *SessionManager) IsElevated(sessionID, token string) bool {+func (m *Manager) IsElevated(sessionID, token string) bool {if m == nil {return false}@@ -178,7 +178,7 @@ func (m *SessionManager) IsElevated(sessionID, token string) bool {return !state.ElevatedUntil.IsZero() && !now.After(state.ElevatedUntil)}-func (m *SessionManager) Revoke(sessionID string) {+func (m *Manager) Revoke(sessionID string) {if m == nil {return}@@ -192,28 +192,28 @@ func (m *SessionManager) Revoke(sessionID string) {m.mu.Unlock()}-func (m *SessionManager) MaxLifetime() time.Duration {+func (m *Manager) MaxLifetime() time.Duration {if m == nil {return DefaultSessionMaxLifetime}return m.maxLifetime}-func (m *SessionManager) IdleTimeout() time.Duration {+func (m *Manager) IdleTimeout() time.Duration {if m == nil {return DefaultSessionIdleTimeout}return m.idleTimeout}-func (m *SessionManager) ElevationWindow() time.Duration {+func (m *Manager) ElevationWindow() time.Duration {if m == nil {return DefaultSessionElevationWindow}return m.elevationWindow}-func (m *SessionManager) UpdateConfig(cfg SessionConfig) {+func (m *Manager) UpdateConfig(cfg Config) {if m == nil {return}@@ -234,7 +234,7 @@ func (m *SessionManager) UpdateConfig(cfg SessionConfig) {}}-func (m *SessionManager) applyConfigLocked(cfg SessionConfig) {+func (m *Manager) applyConfigLocked(cfg Config) {idle := cfg.IdleTimeoutif idle <= 0 {idle = DefaultSessionIdleTimeout@@ -258,16 +258,16 @@ func (m *SessionManager) applyConfigLocked(cfg SessionConfig) {m.persistElevationAcrossRestart = cfg.PersistElevationAcrossRestart}-func (m *SessionManager) sessionValid(state sessionState, now time.Time, expected [32]byte) bool {+func (m *Manager) sessionValid(state sessionState, now time.Time, expected [32]byte) bool {return m.sessionTimeValid(state, now) && state.TokenHash == expected}-func (m *SessionManager) sessionTimeValid(state sessionState, now time.Time) bool {+func (m *Manager) sessionTimeValid(state sessionState, now time.Time) bool {return now.Sub(state.LastSeen) <= m.idleTimeout &&now.Sub(state.CreatedAt) <= m.maxLifetime}-func (m *SessionManager) pruneExpiredLocked(now time.Time) {+func (m *Manager) pruneExpiredLocked(now time.Time) {for id, state := range m.sessions {if !m.sessionTimeValid(state, now) {delete(m.sessions, id)@@ -275,7 +275,7 @@ func (m *SessionManager) pruneExpiredLocked(now time.Time) {}}-func (m *SessionManager) loadPersisted() {+func (m *Manager) loadPersisted() {if m == nil {return}@@ -328,7 +328,7 @@ func (m *SessionManager) loadPersisted() {m.saveLocked()}-func (m *SessionManager) saveLocked() {+func (m *Manager) saveLocked() {if !m.persist || m.persistPath == "" {return}diff --git a/internal/authn/session_test.go b/internal/browsersession/session_test.gosimilarity index 92%rename from internal/authn/session_test.gorename to internal/browsersession/session_test.goindex 955579ef..8566c453 100644--- a/internal/authn/session_test.go+++ b/internal/browsersession/session_test.go@@ -1,4 +1,4 @@-package authn+package browsersessionimport ("path/filepath"@@ -8,7 +8,7 @@ import (func TestSessionManagerValidateAndExpiry(t *testing.T) {now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)- mgr := NewSessionManager(SessionConfig{+ mgr := NewManager(Config{IdleTimeout: time.Hour,MaxLifetime: 24 * time.Hour,})@@ -34,7 +34,7 @@ func TestSessionManagerValidateAndExpiry(t *testing.T) {}func TestSessionManagerInvalidatesOnTokenChange(t *testing.T) {- mgr := NewSessionManager(SessionConfig{})+ mgr := NewManager(Config{})sessionID, err := mgr.Create("secret")if err != nil {t.Fatalf("Create() error = %v", err)@@ -47,7 +47,7 @@ func TestSessionManagerInvalidatesOnTokenChange(t *testing.T) {func TestSessionManagerElevationWindow(t *testing.T) {now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)- mgr := NewSessionManager(SessionConfig{+ mgr := NewManager(Config{IdleTimeout: time.Hour,MaxLifetime: 24 * time.Hour,ElevationWindow: 15 * time.Minute,@@ -78,7 +78,7 @@ func TestSessionManagerPersistsAcrossRestart(t *testing.T) {now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)path := filepath.Join(t.TempDir(), "dashboard-auth-sessions.json")- mgr := NewSessionManager(SessionConfig{+ mgr := NewManager(Config{IdleTimeout: 365 * 24 * time.Hour,MaxLifetime: 365 * 24 * time.Hour,Persist: true,@@ -94,7 +94,7 @@ func TestSessionManagerPersistsAcrossRestart(t *testing.T) {t.Fatal("Validate() before restart = false, want true")}- restarted := NewSessionManager(SessionConfig{+ restarted := NewManager(Config{IdleTimeout: 365 * 24 * time.Hour,MaxLifetime: 365 * 24 * time.Hour,Persist: true,@@ -111,7 +111,7 @@ func TestSessionManagerClearsElevationAcrossRestartByDefault(t *testing.T) {now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)path := filepath.Join(t.TempDir(), "dashboard-auth-sessions.json")- mgr := NewSessionManager(SessionConfig{+ mgr := NewManager(Config{IdleTimeout: 365 * 24 * time.Hour,MaxLifetime: 365 * 24 * time.Hour,ElevationWindow: 15 * time.Minute,@@ -128,7 +128,7 @@ func TestSessionManagerClearsElevationAcrossRestartByDefault(t *testing.T) {t.Fatal("Elevate() = false, want true")}- restarted := NewSessionManager(SessionConfig{+ restarted := NewManager(Config{IdleTimeout: 365 * 24 * time.Hour,MaxLifetime: 365 * 24 * time.Hour,ElevationWindow: 15 * time.Minute,diff --git a/internal/dashboard/admin.go b/internal/dashboard/admin.goindex bb39f3b2..b81a68e0 100644--- a/internal/dashboard/admin.go+++ b/internal/dashboard/admin.go@@ -9,11 +9,11 @@ import (// AdminDeps holds the components needed for dashboard admin route registration.type AdminDeps struct {- ConfigAPI *ConfigAPI- AuthAPI *AuthAPI- AgentSessionAPI *AgentSessionAPI- Activity activity.Recorder- ServerMetrics func() map[string]any+ ConfigAPI *ConfigAPI+ AuthAPI *AuthAPI+ SessionAPI *SessionAPI+ Activity activity.Recorder+ ServerMetrics func() map[string]any}// RegisterAdminRoutes registers all /api/* dashboard admin endpoints.@@ -21,8 +21,8 @@ func (d *Dashboard) RegisterAdminRoutes(mux *http.ServeMux, deps AdminDeps) {d.RegisterHandlers(mux)deps.ConfigAPI.RegisterHandlers(mux)deps.AuthAPI.RegisterHandlers(mux)- if deps.AgentSessionAPI != nil {- deps.AgentSessionAPI.RegisterHandlers(mux)+ if deps.SessionAPI != nil {+ deps.SessionAPI.RegisterHandlers(mux)}activity.RegisterHandlers(mux, deps.Activity)mux.HandleFunc("GET /api/metrics", func(w http.ResponseWriter, r *http.Request) {diff --git a/internal/dashboard/agent_session_api.go b/internal/dashboard/agent_session_api.goindex 1812a81b..af0a18b0 100644--- a/internal/dashboard/agent_session_api.go+++ b/internal/dashboard/agent_session_api.go@@ -6,23 +6,23 @@ import ("strings""github.com/pinchtab/pinchtab/internal/activity"- "github.com/pinchtab/pinchtab/internal/agentsession""github.com/pinchtab/pinchtab/internal/authn""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/session")-// AgentSessionAPI handles CRUD operations for agent sessions.-type AgentSessionAPI struct {- store *agentsession.Store+// SessionAPI handles CRUD operations for sessions.+type SessionAPI struct {+ store *session.Store}-// NewAgentSessionAPI creates a new agent session API handler.-func NewAgentSessionAPI(store *agentsession.Store) *AgentSessionAPI {- return &AgentSessionAPI{store: store}+// NewSessionAPI creates a new session API handler.+func NewSessionAPI(store *session.Store) *SessionAPI {+ return &SessionAPI{store: store}}-// RegisterHandlers registers agent session API routes.-func (a *AgentSessionAPI) RegisterHandlers(mux *http.ServeMux) {+// RegisterHandlers registers session API routes.+func (a *SessionAPI) RegisterHandlers(mux *http.ServeMux) {if a == nil || a.store == nil || !a.store.Enabled() {return}@@ -33,7 +33,7 @@ func (a *AgentSessionAPI) RegisterHandlers(mux *http.ServeMux) {mux.HandleFunc("POST /sessions/{id}/revoke", a.handleRevoke)}-func (a *AgentSessionAPI) handleCreate(w http.ResponseWriter, r *http.Request) {+func (a *SessionAPI) handleCreate(w http.ResponseWriter, r *http.Request) {var req struct {AgentID string `json:"agentId"`Label string `json:"label,omitempty"`@@ -49,7 +49,7 @@ func (a *AgentSessionAPI) handleCreate(w http.ResponseWriter, r *http.Request) {sessionID, token, err := a.store.Create(req.AgentID, req.Label)if err != nil {- httpx.ErrorCode(w, http.StatusInternalServerError, "create_failed", "failed to create agent session", false, nil)+ httpx.ErrorCode(w, http.StatusInternalServerError, "create_failed", "failed to create session", false, nil)return}@@ -72,46 +72,46 @@ func (a *AgentSessionAPI) handleCreate(w http.ResponseWriter, r *http.Request) {})}-func (a *AgentSessionAPI) handleList(w http.ResponseWriter, _ *http.Request) {+func (a *SessionAPI) handleList(w http.ResponseWriter, _ *http.Request) {sessions := a.store.List()if sessions == nil {- sessions = []agentsession.Session{}+ sessions = []session.Session{}}httpx.JSON(w, http.StatusOK, sessions)}-func (a *AgentSessionAPI) handleGet(w http.ResponseWriter, r *http.Request) {+func (a *SessionAPI) handleGet(w http.ResponseWriter, r *http.Request) {id := r.PathValue("id")sess, ok := a.store.Get(id)if !ok {- httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "agent session not found", false, nil)+ httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "session not found", false, nil)return}httpx.JSON(w, http.StatusOK, sess)}-func (a *AgentSessionAPI) handleMe(w http.ResponseWriter, r *http.Request) {+func (a *SessionAPI) handleMe(w http.ResponseWriter, r *http.Request) {creds := authn.CredentialsFromRequest(r)if creds.Method != authn.MethodSession {httpx.ErrorCode(w, http.StatusUnauthorized, "session_auth_required", "this endpoint requires session authentication", false, nil)return}- sess, ok := a.store.Authenticate(creds.Value)+ sess, ok := session.FromRequest(r)if !ok || sess == nil {- httpx.ErrorCode(w, http.StatusUnauthorized, "bad_session", "invalid or expired agent session", false, nil)+ httpx.ErrorCode(w, http.StatusUnauthorized, "bad_session", "invalid or expired session", false, nil)return}httpx.JSON(w, http.StatusOK, sess)}-func (a *AgentSessionAPI) handleRevoke(w http.ResponseWriter, r *http.Request) {+func (a *SessionAPI) handleRevoke(w http.ResponseWriter, r *http.Request) {id := r.PathValue("id")creds := authn.CredentialsFromRequest(r)switch creds.Method {case authn.MethodSession:- sess, ok := a.store.Authenticate(creds.Value)+ sess, ok := session.FromRequest(r)if !ok || sess == nil {- httpx.ErrorCode(w, http.StatusUnauthorized, "bad_session", "invalid or expired agent session", false, nil)+ httpx.ErrorCode(w, http.StatusUnauthorized, "bad_session", "invalid or expired session", false, nil)return}if sess.ID != id {@@ -125,7 +125,7 @@ func (a *AgentSessionAPI) handleRevoke(w http.ResponseWriter, r *http.Request) {return}if !a.store.Revoke(id) {- httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "agent session not found", false, nil)+ httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "session not found", false, nil)return}httpx.JSON(w, http.StatusOK, map[string]string{"status": "ok"})diff --git a/internal/dashboard/agent_session_api_integration_test.go b/internal/dashboard/agent_session_api_integration_test.gonew file mode 100644index 00000000..22ac3f9b--- /dev/null+++ b/internal/dashboard/agent_session_api_integration_test.go@@ -0,0 +1,91 @@+package dashboard_test++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/dashboard"+ "github.com/pinchtab/pinchtab/internal/handlers"+ "github.com/pinchtab/pinchtab/internal/session"+)++func newIntegrationSessionStore() *session.Store {+ return session.NewStore(session.Config{+ Enabled: true,+ IdleTimeout: 30 * time.Minute,+ MaxLifetime: 24 * time.Hour,+ })+}++func decodeIntegrationResponse(t *testing.T, w *httptest.ResponseRecorder) map[string]any {+ t.Helper()+ var m map[string]any+ if err := json.NewDecoder(w.Body).Decode(&m); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ return m+}++func TestAgentSessionAPI_Me_UsesContextSessionAfterMiddlewareAuth(t *testing.T) {+ store := newIntegrationSessionStore()+ mux := http.NewServeMux()+ dashboard.NewSessionAPI(store).RegisterHandlers(mux)++ sessionID, token, _ := store.Create("agent-1", "my-session")+ handler := handlers.AuthMiddlewareWithSessions(+ &config.RuntimeConfig{Token: "dashboard-token"},+ nil,+ store,+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if !store.Revoke(sessionID) {+ t.Fatal("expected middleware-authenticated session to exist")+ }+ mux.ServeHTTP(w, r)+ }),+ )++ req := httptest.NewRequest(http.MethodGet, "/sessions/me", nil)+ req.Header.Set("Authorization", "Session "+token)+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)+ }+ resp := decodeIntegrationResponse(t, w)+ if resp["id"] != sessionID {+ t.Fatalf("id = %q, want %q", resp["id"], sessionID)+ }+}++func TestAgentSessionAPI_Revoke_UsesContextSessionAfterMiddlewareAuth(t *testing.T) {+ store := newIntegrationSessionStore()+ mux := http.NewServeMux()+ dashboard.NewSessionAPI(store).RegisterHandlers(mux)++ sessionID, token, _ := store.Create("agent-1", "")+ handler := handlers.AuthMiddlewareWithSessions(+ &config.RuntimeConfig{Token: "dashboard-token"},+ nil,+ store,+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if !store.Revoke(sessionID) {+ t.Fatal("expected middleware-authenticated session to exist")+ }+ mux.ServeHTTP(w, r)+ }),+ )++ req := httptest.NewRequest(http.MethodPost, "/sessions/"+sessionID+"/revoke", nil)+ req.Header.Set("Authorization", "Session "+token)+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)+ }+}diff --git a/internal/dashboard/agent_session_api_test.go b/internal/dashboard/agent_session_api_test.goindex 987c422c..53bf6944 100644--- a/internal/dashboard/agent_session_api_test.go+++ b/internal/dashboard/agent_session_api_test.go@@ -8,20 +8,20 @@ import ("testing""time"- "github.com/pinchtab/pinchtab/internal/agentsession"+ "github.com/pinchtab/pinchtab/internal/session")-func newTestSessionStore() *agentsession.Store {- return agentsession.NewStore(agentsession.Config{+func newTestSessionStore() *session.Store {+ return session.NewStore(session.Config{Enabled: true,IdleTimeout: 30 * time.Minute,MaxLifetime: 24 * time.Hour,})}-func newTestSessionMux(store *agentsession.Store) *http.ServeMux {+func newTestSessionMux(store *session.Store) *http.ServeMux {mux := http.NewServeMux()- NewAgentSessionAPI(store).RegisterHandlers(mux)+ NewSessionAPI(store).RegisterHandlers(mux)return mux}@@ -174,10 +174,15 @@ func TestAgentSessionAPI_Me(t *testing.T) {store := newTestSessionStore()mux := newTestSessionMux(store)- _, token, _ := store.Create("agent-1", "my-session")+ sessionID, token, _ := store.Create("agent-1", "my-session")+ sess, ok := store.Get(sessionID)+ if !ok || sess == nil {+ t.Fatal("expected session to exist")+ }req := httptest.NewRequest("GET", "/sessions/me", nil)req.Header.Set("Authorization", "Session "+token)+ req = session.WithSession(req, sess)w := httptest.NewRecorder()mux.ServeHTTP(w, req)@@ -258,9 +263,14 @@ func TestAgentSessionAPI_Revoke_SessionOwnerAllowed(t *testing.T) {mux := newTestSessionMux(store)id, token, _ := store.Create("agent-1", "")+ sess, ok := store.Get(id)+ if !ok || sess == nil {+ t.Fatal("expected session to exist")+ }req := httptest.NewRequest("POST", "/sessions/"+id+"/revoke", nil)req.Header.Set("Authorization", "Session "+token)+ req = session.WithSession(req, sess)w := httptest.NewRecorder()mux.ServeHTTP(w, req)@@ -273,11 +283,16 @@ func TestAgentSessionAPI_Revoke_SessionCallerCannotRevokeOtherSession(t *testingstore := newTestSessionStore()mux := newTestSessionMux(store)- _, token, _ := store.Create("agent-1", "")+ id, token, _ := store.Create("agent-1", "")+ sess, ok := store.Get(id)+ if !ok || sess == nil {+ t.Fatal("expected session to exist")+ }otherID, _, _ := store.Create("agent-2", "")req := httptest.NewRequest("POST", "/sessions/"+otherID+"/revoke", nil)req.Header.Set("Authorization", "Session "+token)+ req = session.WithSession(req, sess)w := httptest.NewRecorder()mux.ServeHTTP(w, req)@@ -302,7 +317,7 @@ func TestAgentSessionAPI_Revoke_RejectsUnauthenticatedCaller(t *testing.T) {}func TestAgentSessionAPI_RegisterHandlers_NoOpsWhenDisabled(t *testing.T) {- store := agentsession.NewStore(agentsession.Config{+ store := session.NewStore(session.Config{Enabled: false,Mode: "off",IdleTimeout: 30 * time.Minute,diff --git a/internal/dashboard/auth_api.go b/internal/dashboard/auth_api.goindex 9468a532..df43b6ca 100644--- a/internal/dashboard/auth_api.go+++ b/internal/dashboard/auth_api.go@@ -9,17 +9,18 @@ import ("time""github.com/pinchtab/pinchtab/internal/authn"+ "github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx")type AuthAPI struct {runtime *config.RuntimeConfig- sessions *authn.SessionManager+ sessions *browsersession.ManagerloginLimiter *authn.AttemptLimiter}-func NewAuthAPI(runtime *config.RuntimeConfig, sessions *authn.SessionManager) *AuthAPI {+func NewAuthAPI(runtime *config.RuntimeConfig, sessions *browsersession.Manager) *AuthAPI {return &AuthAPI{runtime: runtime,sessions: sessions,diff --git a/internal/dashboard/auth_api_test.go b/internal/dashboard/auth_api_test.goindex 05312537..d06e87f4 100644--- a/internal/dashboard/auth_api_test.go+++ b/internal/dashboard/auth_api_test.go@@ -8,11 +8,12 @@ import ("time""github.com/pinchtab/pinchtab/internal/authn"+ "github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config")func TestAuthAPIHandleLogin(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)req := httptest.NewRequest("POST", "https://pinchtab.example/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))@@ -50,7 +51,7 @@ func TestAuthAPIHandleLogin(t *testing.T) {}func TestAuthAPIHandleLogin_LocalhostHTTPUsesNonSecureCookie(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)req := httptest.NewRequest("POST", "http://localhost:9867/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))@@ -73,7 +74,7 @@ func TestAuthAPIHandleLogin_LocalhostHTTPUsesNonSecureCookie(t *testing.T) {}func TestAuthAPIHandleLogin_LANHTTPUsesNonSecureCookie(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)req := httptest.NewRequest("POST", "http://192.168.1.50:9867/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))@@ -96,7 +97,7 @@ func TestAuthAPIHandleLogin_LANHTTPUsesNonSecureCookie(t *testing.T) {}func TestAuthAPIHandleLogin_TrustedProxyHTTPSUsesSecureCookie(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token",TrustProxyHeaders: true,@@ -124,7 +125,7 @@ func TestAuthAPIHandleLogin_TrustedProxyHTTPSUsesSecureCookie(t *testing.T) {}func TestAuthAPIHandleLogin_CookieSecureFalseOverridesHTTPS(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})forceInsecure := falseapi := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token",@@ -150,7 +151,7 @@ func TestAuthAPIHandleLogin_CookieSecureFalseOverridesHTTPS(t *testing.T) {}func TestAuthAPIHandleLogin_CookieSecureTrueRejectsPlainHTTP(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})forceSecure := trueapi := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token",@@ -176,7 +177,7 @@ func TestAuthAPIHandleLogin_CookieSecureTrueRejectsPlainHTTP(t *testing.T) {}func TestAuthAPIHandleLoginRejectsBadToken(t *testing.T) {- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, authn.NewSessionManager(authn.SessionConfig{}))+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, browsersession.NewManager(browsersession.Config{}))req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"token":"wrong"}`))req.Header.Set("Content-Type", "application/json")@@ -194,7 +195,7 @@ func TestAuthAPIHandleLoginRejectsBadToken(t *testing.T) {}func TestAuthAPIHandleLogoutClearsCookie(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create("secret-token")if err != nil {t.Fatalf("Create() error = %v", err)@@ -223,7 +224,7 @@ func TestAuthAPIHandleLogoutClearsCookie(t *testing.T) {}func TestAuthAPIHandleLogout_LocalhostHTTPClearsNonSecureCookie(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create("secret-token")if err != nil {t.Fatalf("Create() error = %v", err)@@ -250,7 +251,7 @@ func TestAuthAPIHandleLogout_LocalhostHTTPClearsNonSecureCookie(t *testing.T) {}func TestAuthAPIHandleLogout_LANHTTPClearsNonSecureCookie(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create("secret-token")if err != nil {t.Fatalf("Create() error = %v", err)@@ -277,7 +278,7 @@ func TestAuthAPIHandleLogout_LANHTTPClearsNonSecureCookie(t *testing.T) {}func TestAuthAPIHandleElevateMarksSessionElevated(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create("secret-token")if err != nil {t.Fatalf("Create() error = %v", err)@@ -300,7 +301,7 @@ func TestAuthAPIHandleElevateMarksSessionElevated(t *testing.T) {}func TestAuthAPIHandleElevateRejectsBadToken(t *testing.T) {- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create("secret-token")if err != nil {t.Fatalf("Create() error = %v", err)@@ -323,7 +324,7 @@ func TestAuthAPIHandleElevateRejectsBadToken(t *testing.T) {}func TestAuthAPIHandleLoginRateLimitsRepeatedFailures(t *testing.T) {- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, authn.NewSessionManager(authn.SessionConfig{}))+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, browsersession.NewManager(browsersession.Config{}))api.loginLimiter = authn.NewAttemptLimiter(authn.AttemptLimiterConfig{Window: time.Minute,MaxAttempts: 1,@@ -352,7 +353,7 @@ func TestAuthAPIHandleLoginRateLimitsRepeatedFailures(t *testing.T) {}func TestAuthAPIHandleLoginRateLimitIgnoresSpoofedForwardedHeaders(t *testing.T) {- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, authn.NewSessionManager(authn.SessionConfig{}))+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, browsersession.NewManager(browsersession.Config{}))api.loginLimiter = authn.NewAttemptLimiter(authn.AttemptLimiterConfig{Window: time.Minute,MaxAttempts: 1,diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.goindex c8336378..e16ff6ac 100644--- a/internal/dashboard/config_api.go+++ b/internal/dashboard/config_api.go@@ -11,6 +11,7 @@ import ("github.com/pinchtab/pinchtab/internal/authn""github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx")@@ -33,7 +34,7 @@ type ConfigAPI struct {profiles profileListerapplier runtimeConfigApplieragents agentCounter- sessions *authn.SessionManager+ sessions *browsersession.Managerversion stringstartedAt time.Timeboot config.FileConfig@@ -94,7 +95,7 @@ func NewConfigAPI(}}-func (c *ConfigAPI) SetSessionManager(sessions *authn.SessionManager) {+func (c *ConfigAPI) SetSessionManager(sessions *browsersession.Manager) {if c == nil {return}@@ -179,7 +180,7 @@ func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {config.ApplyFileConfigToRuntime(c.runtime, &normalized)if c.sessions != nil {- c.sessions.UpdateConfig(SessionManagerConfig(c.runtime))+ c.sessions.UpdateConfig(BrowserSessionConfig(c.runtime))}if c.applier != nil {c.applier.ApplyRuntimeConfig(c.runtime)diff --git a/internal/dashboard/session_config.go b/internal/dashboard/session_config.goindex 46d60490..838b578c 100644--- a/internal/dashboard/session_config.go+++ b/internal/dashboard/session_config.go@@ -3,17 +3,17 @@ package dashboardimport ("path/filepath"- "github.com/pinchtab/pinchtab/internal/authn"+ "github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config")const dashboardSessionStateFile = "dashboard-auth-sessions.json"-func SessionManagerConfig(runtime *config.RuntimeConfig) authn.SessionConfig {+func BrowserSessionConfig(runtime *config.RuntimeConfig) browsersession.Config {if runtime == nil {- return authn.SessionConfig{}+ return browsersession.Config{}}- return authn.SessionConfig{+ return browsersession.Config{IdleTimeout: runtime.Sessions.Dashboard.IdleTimeout,MaxLifetime: runtime.Sessions.Dashboard.MaxLifetime,ElevationWindow: runtime.Sessions.Dashboard.ElevationWindow,diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex 2f4d3a4d..99162bea 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -13,10 +13,11 @@ import ("time""github.com/pinchtab/pinchtab/internal/activity"- "github.com/pinchtab/pinchtab/internal/agentsession""github.com/pinchtab/pinchtab/internal/authn"+ "github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/session")var (@@ -85,7 +86,7 @@ func AuthMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {return AuthMiddlewareWithSessions(cfg, nil, nil, next)}-func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.SessionManager, agentSessions *agentsession.Store, next http.Handler) http.Handler {+func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *browsersession.Manager, agentSessions *session.Store, next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if isPublicDashboardPath(r.URL.Path) || isPublicAuthPath(r.URL.Path) {next.ServeHTTP(w, r)@@ -135,6 +136,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.SessiAgentID: sess.AgentID,SessionID: sess.ID,})+ r = session.WithSession(r, sess)case authn.MethodHeader:if subtle.ConstantTimeCompare([]byte(creds.Value), []byte(token)) != 1 {authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))@@ -176,7 +178,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessi})}-func sessionRequestAllowed(r *http.Request, sess *agentsession.Session) bool {+func sessionRequestAllowed(r *http.Request, sess *session.Session) bool {method := strings.ToUpper(strings.TrimSpace(r.Method))path := strings.TrimSpace(r.URL.Path)if method == http.MethodPost && sessionRevokePath(path) {diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.goindex e1b943d8..d4458f1d 100644--- a/internal/handlers/middleware_test.go+++ b/internal/handlers/middleware_test.go@@ -8,10 +8,11 @@ import ("time""github.com/pinchtab/pinchtab/internal/activity"- "github.com/pinchtab/pinchtab/internal/agentsession""github.com/pinchtab/pinchtab/internal/authn"+ "github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/session")type activityCaptureRecorder struct {@@ -177,7 +178,7 @@ func TestAuthMiddleware_MissingTokenHeader(t *testing.T) {func TestAuthMiddleware_ValidCookie(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -205,7 +206,7 @@ func TestAuthMiddleware_ValidCookie(t *testing.T) {func TestAuthMiddleware_CookieRestrictedEndpointRejected(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -231,7 +232,7 @@ func TestAuthMiddleware_CookieRestrictedEndpointRejected(t *testing.T) {func TestAuthMiddleware_CookieAllowsTabCloseEndpoint(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -259,7 +260,7 @@ func TestAuthMiddleware_CookieAllowsTabCloseEndpoint(t *testing.T) {func TestAuthMiddleware_CookieAllowsActionEndpoint(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -287,7 +288,7 @@ func TestAuthMiddleware_CookieAllowsActionEndpoint(t *testing.T) {func TestAuthMiddleware_CookieCrossOriginRejected(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -315,7 +316,7 @@ func TestAuthMiddleware_CookieCrossOriginRejected(t *testing.T) {func TestAuthMiddleware_CookieRequestWithoutOriginOrRefererRejected(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -342,7 +343,7 @@ func TestAuthMiddleware_CookieRequestWithoutOriginOrRefererRejected(t *testing.Tfunc TestAuthMiddleware_CookieSameOriginRefererAccepted(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -370,7 +371,7 @@ func TestAuthMiddleware_CookieSameOriginRefererAccepted(t *testing.T) {func TestAuthMiddleware_CookieIgnoresForwardedOriginHints(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -401,7 +402,7 @@ func TestAuthMiddleware_CookieIgnoresForwardedOriginHints(t *testing.T) {func TestAuthMiddleware_CookieWebSocketRequiresSameOrigin(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -453,7 +454,7 @@ func TestAuthMiddleware_CookieElevatedEndpointRequiresElevation(t *testing.T) {},},}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -499,7 +500,7 @@ func TestAuthMiddleware_CookieElevatedEndpointRequiresElevation(t *testing.T) {func TestAuthMiddleware_CookieConfigEndpointDoesNotRequireElevationByDefault(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})sessionID, err := sessions.Create(cfg.Token)if err != nil {t.Fatalf("Create() error = %v", err)@@ -1008,7 +1009,7 @@ func TestStatusWriter(t *testing.T) {}func TestAuthMiddleware_SessionAuth(t *testing.T) {- store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})+ store := session.NewStore(session.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})_, token, _ := store.Create("test-agent", "test")cfg := &config.RuntimeConfig{Token: "server-token"}@@ -1032,7 +1033,7 @@ func TestAuthMiddleware_SessionAuth(t *testing.T) {}func TestAuthMiddleware_SessionAuthRejectsDashboardAdminRoute(t *testing.T) {- store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})+ store := session.NewStore(session.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})_, token, _ := store.Create("test-agent", "test")cfg := &config.RuntimeConfig{Token: "server-token"}@@ -1056,7 +1057,7 @@ func TestAuthMiddleware_SessionAuthRejectsDashboardAdminRoute(t *testing.T) {}func TestAuthMiddleware_SessionAuthWithoutGrantsAllowsNonAdminRoutes(t *testing.T) {- store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})+ store := session.NewStore(session.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})_, token, _ := store.Create("test-agent", "test")cfg := &config.RuntimeConfig{Token: "server-token"}@@ -1080,7 +1081,7 @@ func TestAuthMiddleware_SessionAuthWithoutGrantsAllowsNonAdminRoutes(t *testing.}func TestAuthMiddleware_SessionAuthAllowsRevokeRouteToReachHandler(t *testing.T) {- store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})+ store := session.NewStore(session.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})sessionID, token, _ := store.Create("test-agent", "test")cfg := &config.RuntimeConfig{Token: "server-token"}@@ -1104,7 +1105,7 @@ func TestAuthMiddleware_SessionAuthAllowsRevokeRouteToReachHandler(t *testing.T)}func TestAuthMiddleware_SessionAuthHonorsBrowseGrant(t *testing.T) {- store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})+ store := session.NewStore(session.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})sessionID, token, _ := store.Create("test-agent", "test")sess, ok := store.Get(sessionID)if !ok || sess == nil {@@ -1133,7 +1134,7 @@ func TestAuthMiddleware_SessionAuthHonorsBrowseGrant(t *testing.T) {}func TestAuthMiddleware_SessionAuthRejectsRouteOutsideGrant(t *testing.T) {- store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})+ store := session.NewStore(session.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})sessionID, token, _ := store.Create("test-agent", "test")sess, ok := store.Get(sessionID)if !ok || sess == nil {@@ -1162,7 +1163,7 @@ func TestAuthMiddleware_SessionAuthRejectsRouteOutsideGrant(t *testing.T) {}func TestAuthMiddleware_ForbiddenSessionRequestDoesNotExtendIdleLifetime(t *testing.T) {- store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 100 * time.Millisecond, MaxLifetime: 24 * time.Hour})+ store := session.NewStore(session.Config{Enabled: true, IdleTimeout: 100 * time.Millisecond, MaxLifetime: 24 * time.Hour})sessionID, token, _ := store.Create("test-agent", "test")sess, ok := store.Get(sessionID)if !ok || sess == nil {@@ -1199,7 +1200,7 @@ func TestAuthMiddleware_ForbiddenSessionRequestDoesNotExtendIdleLifetime(t *test}func TestAuthMiddleware_SessionAuthEnrichesActivity(t *testing.T) {- store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})+ store := session.NewStore(session.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})sessionID, token, _ := store.Create("test-agent", "test")rec := &activityCaptureRecorder{}@@ -1227,8 +1228,64 @@ func TestAuthMiddleware_SessionAuthEnrichesActivity(t *testing.T) {}}+func TestAuthMiddleware_SessionAttachesAuthenticatedSessionToContext(t *testing.T) {+ store := session.NewStore(session.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})+ _, token, _ := store.Create("test-agent", "test")++ var (+ called bool+ gotSession *session.Session+ )+ cfg := &config.RuntimeConfig{Token: "server-token"}+ handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ called = true+ gotSession, _ = session.FromRequest(r)+ w.WriteHeader(http.StatusOK)+ }))++ req := httptest.NewRequest(http.MethodGet, "/sessions/me", nil)+ req.Header.Set("Authorization", "Session "+token)+ rr := httptest.NewRecorder()+ handler.ServeHTTP(rr, req)++ if !called {+ t.Fatal("handler should have been called with valid session auth")+ }+ if rr.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", rr.Code)+ }+ if gotSession == nil {+ t.Fatal("expected agent session on request context")+ }+ if gotSession.AgentID != "test-agent" {+ t.Fatalf("AgentID = %q, want test-agent", gotSession.AgentID)+ }+}++func TestAuthMiddleware_HeaderAuthDoesNotAttachAgentSessionToContext(t *testing.T) {+ cfg := &config.RuntimeConfig{Token: "server-token"}++ var gotSession *session.Session+ handler := AuthMiddlewareWithSessions(cfg, nil, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotSession, _ = session.FromRequest(r)+ w.WriteHeader(http.StatusOK)+ }))++ req := httptest.NewRequest(http.MethodGet, "/health", nil)+ req.Header.Set("Authorization", "Bearer server-token")+ rr := httptest.NewRecorder()+ handler.ServeHTTP(rr, req)++ if rr.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", rr.Code)+ }+ if gotSession != nil {+ t.Fatal("expected no agent session on request context for bearer auth")+ }+}+func TestAuthMiddleware_SessionAuthInvalid(t *testing.T) {- store := agentsession.NewStore(agentsession.Config{Enabled: true})+ store := session.NewStore(session.Config{Enabled: true})cfg := &config.RuntimeConfig{Token: "server-token"}called := falsediff --git a/internal/server/server.go b/internal/server/server.goindex 707540c9..696309da 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -13,9 +13,9 @@ import ("time""github.com/pinchtab/pinchtab/internal/activity"- "github.com/pinchtab/pinchtab/internal/agentsession""github.com/pinchtab/pinchtab/internal/authn""github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/cli""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/dashboard"@@ -24,6 +24,7 @@ import ("github.com/pinchtab/pinchtab/internal/orchestrator""github.com/pinchtab/pinchtab/internal/profiles""github.com/pinchtab/pinchtab/internal/scheduler"+ "github.com/pinchtab/pinchtab/internal/session""github.com/pinchtab/pinchtab/internal/strategy"// Register strategies@@ -63,21 +64,21 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {}})configAPI := dashboard.NewConfigAPI(cfg, orch, profMgr, orch, dash, version, startedAt)- sessions := authn.NewSessionManager(dashboard.SessionManagerConfig(cfg))+ sessions := browsersession.NewManager(dashboard.BrowserSessionConfig(cfg))configAPI.SetSessionManager(sessions)authAPI := dashboard.NewAuthAPI(cfg, sessions)- // Agent sessions- agentSessionStore := agentsession.NewStore(agentsession.Config{+ // API sessions+ sessionStore := session.NewStore(session.Config{Enabled: cfg.Sessions.Agent.Enabled,Mode: cfg.Sessions.Agent.Mode,IdleTimeout: cfg.Sessions.Agent.IdleTimeout,MaxLifetime: cfg.Sessions.Agent.MaxLifetime,PersistPath: filepath.Join(cfg.StateDir, "sessions.json"),})- var agentSessionAPI *dashboard.AgentSessionAPI- if agentSessionStore.Enabled() {- agentSessionAPI = dashboard.NewAgentSessionAPI(agentSessionStore)+ var sessionAPI *dashboard.SessionAPI+ if sessionStore.Enabled() {+ sessionAPI = dashboard.NewSessionAPI(sessionStore)}// Wire up instance events to SSE broadcast@@ -114,11 +115,11 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {liveActivity := newDashboardActivityRecorder(actStore, dash)dash.RegisterAdminRoutes(mux, dashboard.AdminDeps{- ConfigAPI: configAPI,- AuthAPI: authAPI,- AgentSessionAPI: agentSessionAPI,- Activity: liveActivity,- ServerMetrics: handlers.SnapshotMetrics,+ ConfigAPI: configAPI,+ AuthAPI: authAPI,+ SessionAPI: sessionAPI,+ Activity: liveActivity,+ ServerMetrics: handlers.SnapshotMetrics,})profMgr.RegisterHandlers(mux)@@ -235,7 +236,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {liveActivity,"server",handlers.SecurityHeadersMiddleware(cfg,- handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, agentSessionStore, mux)))),+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, sessionStore, mux)))),),),)diff --git a/internal/server/timeouts_test.go b/internal/server/timeouts_test.goindex eaede094..78876a98 100644--- a/internal/server/timeouts_test.go+++ b/internal/server/timeouts_test.go@@ -7,7 +7,7 @@ import ("time""github.com/pinchtab/pinchtab/internal/activity"- "github.com/pinchtab/pinchtab/internal/authn"+ "github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/handlers")@@ -31,7 +31,7 @@ func TestServerTimeoutOrdering(t *testing.T) {func TestDashboardHandlerChainAppliesRateLimit(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret"}- sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessions := browsersession.NewManager(browsersession.Config{})mux := http.NewServeMux()mux.HandleFunc("GET /protected", func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusOK)diff --git a/internal/session/context.go b/internal/session/context.gonew file mode 100644index 00000000..8844d359--- /dev/null+++ b/internal/session/context.go@@ -0,0 +1,25 @@+package session++import (+ "context"+ "net/http"+)++type contextKey struct{}++// WithSession stores an authenticated session on the request context.+func WithSession(r *http.Request, sess *Session) *http.Request {+ if r == nil || sess == nil {+ return r+ }+ return r.WithContext(context.WithValue(r.Context(), contextKey{}, sess))+}++// FromRequest returns the authenticated session stored on the request context.+func FromRequest(r *http.Request) (*Session, bool) {+ if r == nil {+ return nil, false+ }+ sess, ok := r.Context().Value(contextKey{}).(*Session)+ return sess, ok && sess != nil+}diff --git a/internal/agentsession/store.go b/internal/session/store.gosimilarity index 92%rename from internal/agentsession/store.gorename to internal/session/store.goindex 60c99cff..59bccfc5 100644--- a/internal/agentsession/store.go+++ b/internal/session/store.go@@ -1,8 +1,8 @@-// Package agentsession provides durable, revocable session-based-// authentication for automated agents. Each session maps a high-entropy+// Package session provides durable, revocable session-based+// authentication for automated clients. Each session maps a high-entropy// token to an agentId, allowing agents to authenticate with a single// environment variable (PINCHTAB_SESSION) instead of the server bearer token.-package agentsession+package sessionimport ("crypto/rand"@@ -18,7 +18,7 @@ import ("time")-// Session represents a durable, revocable agent session.+// Session represents a durable, revocable authenticated session.type Session struct {ID string `json:"id"`AgentID string `json:"agentId"`@@ -41,7 +41,7 @@ type Config struct {PersistPath string}-// Store manages agent sessions with persistence.+// Store manages authenticated sessions with persistence.type Store struct {mu sync.Mutexsessions map[string]*Session // keyed by session ID@@ -58,7 +58,7 @@ const (StatusExpired = "expired")-// NewStore creates a new agent session store.+// NewStore creates a new session store.func NewStore(cfg Config) *Store {s := &Store{sessions: make(map[string]*Session),@@ -82,7 +82,7 @@ func (s *Store) applyConfig(cfg Config) {s.cfg = cfg}-// Create generates a new agent session and returns the session ID and+// Create generates a new session and returns the session ID and// plaintext token. The token is returned exactly once and is never stored.func (s *Store) Create(agentID, label string) (sessionID, sessionToken string, err error) {if s == nil {@@ -249,7 +249,7 @@ func (s *Store) UpdateConfig(cfg Config) {s.mu.Unlock()}-// Enabled reports whether agent sessions are enabled.+// Enabled reports whether session auth is enabled.func (s *Store) Enabled() bool {if s == nil {return false@@ -291,11 +291,11 @@ func (s *Store) pruneExpiredLocked() {// persistence typestype persistedStore struct {- SavedAt time.Time `json:"savedAt"`- Sessions []persistedAgentSession `json:"sessions"`+ SavedAt time.Time `json:"savedAt"`+ Sessions []persistedSession `json:"sessions"`}-type persistedAgentSession struct {+type persistedSession struct {ID string `json:"id"`AgentID string `json:"agentId"`Label string `json:"label,omitempty"`@@ -362,10 +362,10 @@ func (s *Store) saveLocked() {snapshot := persistedStore{SavedAt: s.now().UTC(),- Sessions: make([]persistedAgentSession, 0, len(s.sessions)),+ Sessions: make([]persistedSession, 0, len(s.sessions)),}for _, sess := range s.sessions {- snapshot.Sessions = append(snapshot.Sessions, persistedAgentSession{+ snapshot.Sessions = append(snapshot.Sessions, persistedSession{ID: sess.ID,AgentID: sess.AgentID,Label: sess.Label,diff --git a/internal/agentsession/store_test.go b/internal/session/store_test.gosimilarity index 99%rename from internal/agentsession/store_test.gorename to internal/session/store_test.goindex fc697b0d..9758ef9c 100644--- a/internal/agentsession/store_test.go+++ b/internal/session/store_test.go@@ -1,4 +1,4 @@-package agentsession+package sessionimport ("encoding/json"