High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: harden agent sessions and restore dashboard activity flows
Luigi Agosti057b42d3ddb1
diff --git a/dashboard/src/activities/AgentActivityWorkspace.tsx b/dashboard/src/activities/AgentActivityWorkspace.tsxindex 88225042..93aac30f 100644--- a/dashboard/src/activities/AgentActivityWorkspace.tsx+++ b/dashboard/src/activities/AgentActivityWorkspace.tsx@@ -185,7 +185,8 @@ export default function AgentActivityWorkspace({useAgentEventStore = false,clearToInitialFilters = false,}: Props) {- const { instances, profiles, agents, agentEventsById } = useAppStore();+ const { instances, profiles, agents, agentEventsById, hydrateAgentEvents } =+ useAppStore();const normalizedHiddenSources = useMemo(() => [...hiddenSources],[hiddenSources],@@ -221,6 +222,7 @@ export default function AgentActivityWorkspace({const usesAgentThreadView = useAgentEventStore && sidebarTab === "agents";const deferredFilters = useDeferredValue(filters);+ const threadAgentId = deferredFilters.agentId.trim();const catalogQuery = useMemo(() => {const q = buildActivityQuery(deferredFilters);if (usesAgentThreadView) {@@ -232,13 +234,13 @@ export default function AgentActivityWorkspace({}, [deferredFilters, usesAgentThreadView]);const catalogQueryKey = JSON.stringify(catalogQuery);const threadQuery = useMemo(() => {- if (!usesAgentThreadView || !deferredFilters.agentId.trim()) {+ if (!usesAgentThreadView || !threadAgentId) {return null;}const q = buildActivityQuery(withClearedSessionFilter(deferredFilters));q.source = "client";return q;- }, [deferredFilters, usesAgentThreadView]);+ }, [deferredFilters, threadAgentId, usesAgentThreadView]);const threadQueryKey = JSON.stringify(threadQuery);useEffect(() => {@@ -318,7 +320,7 @@ export default function AgentActivityWorkspace({}, [catalogQuery, catalogQueryKey, refreshNonce]);useEffect(() => {- if (!usesAgentThreadView || !threadQuery) {+ if (!usesAgentThreadView || !threadAgentId) {setThreadEvents([]);setAgentLoading(false);return;@@ -329,10 +331,16 @@ export default function AgentActivityWorkspace({setAgentLoading(true);setError("");try {- const response = await fetchActivity(threadQuery);+ const [detail, response] = await Promise.all([+ api.fetchAgent(threadAgentId),+ threadQuery+ ? fetchActivity(threadQuery)+ : Promise.resolve({ count: 0, events: [] }),+ ]);if (cancelled) {return;}+ hydrateAgentEvents(detail.agent.id, detail.events);setThreadEvents(response.events.map(normalizeDashboardActivityEvent));} catch (err) {if (cancelled) {@@ -352,7 +360,14 @@ export default function AgentActivityWorkspace({return () => {cancelled = true;};- }, [refreshNonce, threadQuery, threadQueryKey, usesAgentThreadView]);+ }, [+ hydrateAgentEvents,+ refreshNonce,+ threadAgentId,+ threadQuery,+ threadQueryKey,+ usesAgentThreadView,+ ]);const filteredInstances = useMemo(() =>diff --git a/dashboard/src/activities/AgentsPage.test.tsx b/dashboard/src/activities/AgentsPage.test.tsxindex 8bb8247f..85e019b4 100644--- a/dashboard/src/activities/AgentsPage.test.tsx+++ b/dashboard/src/activities/AgentsPage.test.tsx@@ -11,11 +11,12 @@ vi.mock("./api", () => ({vi.mock("../services/api", () => ({fetchAllTabs: vi.fn(),+ fetchAgent: vi.fn(),fetchSessions: vi.fn(),}));import { fetchActivity } from "./api";-import { fetchSessions, fetchAllTabs } from "../services/api";+import { fetchAgent, fetchSessions, fetchAllTabs } from "../services/api";describe("AgentsPage", () => {beforeEach(() => {@@ -47,6 +48,16 @@ describe("AgentsPage", () => {status: "active",},]);+ vi.mocked(fetchAgent).mockResolvedValue({+ agent: {+ id: "cli",+ name: "CLI",+ connectedAt: "2026-03-16T08:00:00Z",+ lastActivity: "2026-03-16T08:10:00Z",+ requestCount: 3,+ },+ events: [],+ });vi.mocked(fetchActivity).mockResolvedValue({count: 4,events: [@@ -387,6 +398,10 @@ describe("AgentsPage", () => {</MemoryRouter>,);+ await waitFor(() => {+ expect(fetchAgent).toHaveBeenCalledWith("cli");+ });+await waitFor(() => {expect(fetchActivity).toHaveBeenCalledWith(expect.objectContaining({@@ -399,4 +414,53 @@ describe("AgentsPage", () => {expect(screen.getByText("Extract text from page")).toBeInTheDocument();});++ it("hydrates older agent history from the agent detail endpoint", async () => {+ vi.mocked(fetchAgent).mockResolvedValue({+ agent: {+ id: "cli",+ name: "CLI",+ connectedAt: "2026-03-16T08:00:00Z",+ lastActivity: "2026-03-16T08:10:00Z",+ requestCount: 3,+ },+ events: [+ {+ id: "evt_thread_history",+ timestamp: "2026-03-16T07:45:00Z",+ agentId: "cli",+ channel: "tool_call",+ type: "text",+ method: "GET",+ path: "/text",+ message: "",+ details: {+ source: "client",+ requestId: "req_thread_history",+ sessionId: "ses_789",+ status: 200,+ durationMs: 14,+ tabId: "tab_123",+ action: "text",+ },+ },+ ],+ });+ vi.mocked(fetchActivity).mockResolvedValue({+ count: 0,+ events: [],+ });++ render(+ <MemoryRouter>+ <AgentsPage />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(fetchAgent).toHaveBeenCalledWith("cli");+ });++ expect(screen.getByText("Extract text from page")).toBeInTheDocument();+ });});diff --git a/internal/agentsession/store.go b/internal/agentsession/store.goindex 64948aef..60c99cff 100644--- a/internal/agentsession/store.go+++ b/internal/agentsession/store.go@@ -122,6 +122,15 @@ func (s *Store) Create(agentID, label string) (sessionID, sessionToken string, e// Authenticate validates a token and returns the associated session.// It updates LastSeenAt on success.func (s *Store) Authenticate(token string) (*Session, bool) {+ return s.authenticate(token, true)+}++// AuthenticateWithoutTouch validates a token without updating LastSeenAt.+func (s *Store) AuthenticateWithoutTouch(token string) (*Session, bool) {+ return s.authenticate(token, false)+}++func (s *Store) authenticate(token string, touch bool) (*Session, bool) {if s == nil {return nil, false}@@ -148,13 +157,40 @@ func (s *Store) Authenticate(token string) (*Session, bool) {s.saveLocked()return nil, false}- sess.LastSeenAt = now- s.saveLocked()+ if touch {+ sess.LastSeenAt = now+ s.saveLocked()+ }return sess, true}return nil, false}+// Touch updates LastSeenAt for an active, unexpired session.+func (s *Store) Touch(sessionID string) bool {+ if s == nil {+ return false+ }++ now := s.now()++ s.mu.Lock()+ defer s.mu.Unlock()++ sess, ok := s.sessions[strings.TrimSpace(sessionID)]+ if !ok || sess.Status != StatusActive {+ return false+ }+ if s.isExpired(sess, now) {+ sess.Status = StatusExpired+ s.saveLocked()+ return false+ }+ sess.LastSeenAt = now+ s.saveLocked()+ return true+}+// Get returns a session by its public ID.func (s *Store) Get(sessionID string) (*Session, bool) {if s == nil {diff --git a/internal/agentsession/store_test.go b/internal/agentsession/store_test.goindex 31211fcf..fc697b0d 100644--- a/internal/agentsession/store_test.go+++ b/internal/agentsession/store_test.go@@ -109,6 +109,57 @@ func TestIdleTimeoutReset(t *testing.T) {}}+func TestAuthenticateWithoutTouchDoesNotResetIdleTimeout(t *testing.T) {+ s := NewStore(Config{Enabled: true, MaxLifetime: 24 * time.Hour, IdleTimeout: 10 * time.Minute})+ now := time.Now()+ s.now = func() time.Time { return now }++ id, token, _ := s.Create("agent-1", "")+ sess, ok := s.Get(id)+ if !ok || sess == nil {+ t.Fatal("expected session to exist")+ }+ initialLastSeen := sess.LastSeenAt++ s.now = func() time.Time { return now.Add(8 * time.Minute) }+ sess, ok = s.AuthenticateWithoutTouch(token)+ if !ok || sess == nil {+ t.Fatal("expected auth without touch to succeed within idle window")+ }+ if !sess.LastSeenAt.Equal(initialLastSeen) {+ t.Fatal("AuthenticateWithoutTouch should not update LastSeenAt")+ }++ s.now = func() time.Time { return now.Add(11 * time.Minute) }+ sess, ok = s.Authenticate(token)+ if ok || sess != nil {+ t.Fatal("expected session to expire when it was never touched")+ }+}++func TestTouchResetsIdleTimeout(t *testing.T) {+ s := NewStore(Config{Enabled: true, MaxLifetime: 24 * time.Hour, IdleTimeout: 10 * time.Minute})+ now := time.Now()+ s.now = func() time.Time { return now }++ id, token, _ := s.Create("agent-1", "")++ s.now = func() time.Time { return now.Add(8 * time.Minute) }+ sess, ok := s.AuthenticateWithoutTouch(token)+ if !ok || sess == nil {+ t.Fatal("expected auth without touch to succeed")+ }+ if !s.Touch(id) {+ t.Fatal("expected touch to succeed")+ }++ s.now = func() time.Time { return now.Add(16 * time.Minute) }+ sess, ok = s.Authenticate(token)+ if !ok || sess == nil {+ t.Fatal("expected auth to succeed after touch reset")+ }+}+func TestRevoke(t *testing.T) {s := NewStore(Config{Enabled: true})id, token, _ := s.Create("agent-1", "")diff --git a/internal/dashboard/agent_session_api.go b/internal/dashboard/agent_session_api.goindex 7e13644b..1812a81b 100644--- a/internal/dashboard/agent_session_api.go+++ b/internal/dashboard/agent_session_api.go@@ -23,6 +23,9 @@ func NewAgentSessionAPI(store *agentsession.Store) *AgentSessionAPI {// RegisterHandlers registers agent session API routes.func (a *AgentSessionAPI) RegisterHandlers(mux *http.ServeMux) {+ if a == nil || a.store == nil || !a.store.Enabled() {+ return+ }mux.HandleFunc("POST /sessions", a.handleCreate)mux.HandleFunc("GET /sessions", a.handleList)mux.HandleFunc("GET /sessions/me", a.handleMe)diff --git a/internal/dashboard/agent_session_api_test.go b/internal/dashboard/agent_session_api_test.goindex bc7a24af..987c422c 100644--- a/internal/dashboard/agent_session_api_test.go+++ b/internal/dashboard/agent_session_api_test.go@@ -300,3 +300,22 @@ func TestAgentSessionAPI_Revoke_RejectsUnauthenticatedCaller(t *testing.T) {t.Fatalf("status = %d, want %d", w.Code, http.StatusForbidden)}}++func TestAgentSessionAPI_RegisterHandlers_NoOpsWhenDisabled(t *testing.T) {+ store := agentsession.NewStore(agentsession.Config{+ Enabled: false,+ Mode: "off",+ IdleTimeout: 30 * time.Minute,+ MaxLifetime: 24 * time.Hour,+ })+ mux := newTestSessionMux(store)++ req := httptest.NewRequest("POST", "/sessions", strings.NewReader(`{"agentId":"agent-1"}`))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)+ }+}diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex bc361167..2f4d3a4d 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -111,12 +111,23 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessihttpx.ErrorCode(w, 401, "session_auth_unavailable", "agent session authentication is not enabled", false, nil)return}- sess, ok := agentSessions.Authenticate(creds.Value)+ sess, ok := agentSessions.AuthenticateWithoutTouch(creds.Value)if !ok || sess == nil {w.Header().Set("WWW-Authenticate", `Session realm="pinchtab", error="bad_session"`)httpx.ErrorCode(w, 401, "bad_session", "invalid or expired agent session", false, nil)return}+ if !sessionRequestAllowed(r, sess) {+ httpx.ErrorCode(w, http.StatusForbidden, "session_scope_forbidden", "agent session is not allowed to access this endpoint", false, map[string]any{+ "safeControlledEnvironmentOnly": true,+ })+ return+ }+ if !agentSessions.Touch(sess.ID) {+ w.Header().Set("WWW-Authenticate", `Session realm="pinchtab", error="bad_session"`)+ httpx.ErrorCode(w, 401, "bad_session", "invalid or expired agent session", false, nil)+ return+ }// Inject agent identity into request headers for activity trackingr.Header.Set(activity.HeaderAgentID, sess.AgentID)r.Header.Set(activity.HeaderPTSessionID, sess.ID)@@ -124,12 +135,6 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.SessiAgentID: sess.AgentID,SessionID: sess.ID,})- if !sessionRequestAllowed(r, sess) {- httpx.ErrorCode(w, http.StatusForbidden, "session_scope_forbidden", "agent session is not allowed to access this endpoint", false, map[string]any{- "safeControlledEnvironmentOnly": true,- })- return- }case authn.MethodHeader:if subtle.ConstantTimeCompare([]byte(creds.Value), []byte(token)) != 1 {authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.goindex dfb8b66c..e1b943d8 100644--- a/internal/handlers/middleware_test.go+++ b/internal/handlers/middleware_test.go@@ -1161,6 +1161,43 @@ 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})+ sessionID, token, _ := store.Create("test-agent", "test")+ sess, ok := store.Get(sessionID)+ if !ok || sess == nil {+ t.Fatal("expected session to exist")+ }+ sess.Grants = []string{"browse"}++ cfg := &config.RuntimeConfig{Token: "server-token"}+ handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))++ time.Sleep(30 * time.Millisecond)++ req := httptest.NewRequest(http.MethodGet, "/clipboard/read", nil)+ req.Header.Set("Authorization", "Session "+token)+ rr := httptest.NewRecorder()+ handler.ServeHTTP(rr, req)++ if rr.Code != http.StatusForbidden {+ t.Fatalf("expected 403, got %d", rr.Code)+ }++ time.Sleep(90 * time.Millisecond)++ req = httptest.NewRequest(http.MethodGet, "/text", nil)+ req.Header.Set("Authorization", "Session "+token)+ rr = httptest.NewRecorder()+ handler.ServeHTTP(rr, req)++ if rr.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401 after idle timeout, got %d", rr.Code)+ }+}+func TestAuthMiddleware_SessionAuthEnrichesActivity(t *testing.T) {store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})sessionID, token, _ := store.Create("test-agent", "test")diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex b72b7b68..4796d729 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -355,6 +355,29 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {switch req.Action {case tabActionNew:+ var target *validatedNavigateTarget+ trustedCIDRs := parseCIDRs(h.Config.TrustedProxyCIDRs)+ if req.URL != "" && req.URL != "about:blank" {+ if err := validateNavigateURL(req.URL); err != nil {+ httpx.Error(w, 400, err)+ return+ }+ domainResult := h.IDPIGuard.CheckDomain(req.URL)+ if domainResult.Blocked {+ httpx.Error(w, http.StatusForbidden, fmt.Errorf("navigation blocked by IDPI: %s", domainResult.Reason))+ return+ }+ if domainResult.Threat {+ w.Header().Set("X-IDPI-Warning", domainResult.Reason)+ }+ var err error+ target, err = validateNavigateTarget(req.URL, h.IDPIGuard.DomainAllowed(req.URL))+ if err != nil {+ httpx.Error(w, http.StatusForbidden, err)+ return+ }+ }+// Create a blank tab first so the requested URL becomes the first// real history entry.newTabID, ctx, _, err := h.Bridge.CreateTab("")@@ -366,7 +389,21 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {if req.URL != "" && req.URL != "about:blank" {tCtx, tCancel := context.WithTimeout(ctx, h.Config.NavigateTimeout)defer tCancel()+ go httpx.CancelOnClientDone(r.Context(), tCancel)+ navGuard, err := installNavigateRuntimeGuard(tCtx, tCancel, target, trustedCIDRs)+ if err != nil {+ _ = h.Bridge.CloseTab(newTabID)+ httpx.Error(w, 500, fmt.Errorf("navigation guard: %w", err))+ return+ }if err := bridge.NavigatePageWithRedirectLimit(tCtx, req.URL, h.Config.MaxRedirects); err != nil {+ if navGuard != nil {+ if blockedErr := navGuard.blocked(); blockedErr != nil {+ _ = h.Bridge.CloseTab(newTabID)+ httpx.Error(w, http.StatusForbidden, blockedErr)+ return+ }+ }_ = h.Bridge.CloseTab(newTabID)code := 500if errors.Is(err, bridge.ErrTooManyRedirects) {diff --git a/internal/handlers/navigation_test.go b/internal/handlers/navigation_test.goindex 1e5997b7..68351eae 100644--- a/internal/handlers/navigation_test.go+++ b/internal/handlers/navigation_test.go@@ -287,6 +287,74 @@ func TestHandleTab_CloseMissingID(t *testing.T) {}}+func TestHandleTab_RejectsUnsupportedScheme(t *testing.T) {+ for _, scheme := range []string{"file:///etc/passwd", "javascript:alert(1)", "chrome://settings"} {+ m := &mockBridge{}+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)+ body := `{"action":"new","url":"` + scheme + `"}`+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleTab(w, req)+ if w.Code != 400 {+ t.Errorf("scheme %q: expected 400, got %d: %s", scheme, w.Code, w.Body.String())+ }+ if len(m.createTabURLs) != 0 {+ t.Errorf("scheme %q: CreateTab should not be called but was", scheme)+ }+ }+}++func TestHandleTab_RejectsPrivateLiteralIP(t *testing.T) {+ m := &mockBridge{}+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)+ body := `{"action":"new","url":"http://192.168.1.1/"}`+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleTab(w, req)+ if w.Code != 403 {+ t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())+ }+ if len(m.createTabURLs) != 0 {+ t.Fatalf("CreateTab should not be called for blocked targets")+ }+}++func TestHandleTab_RejectsResolvedPrivateIP(t *testing.T) {+ stubNavigateHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {+ return []net.IP{net.ParseIP("10.0.0.5")}, nil+ })+ m := &mockBridge{}+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)+ body := `{"action":"new","url":"https://example.com"}`+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleTab(w, req)+ if w.Code != 403 {+ t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())+ }+ if len(m.createTabURLs) != 0 {+ t.Fatalf("CreateTab should not be called for blocked targets")+ }+}++func TestHandleTab_AllowsValidURL(t *testing.T) {+ stubNavigateHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {+ return []net.IP{net.ParseIP("93.184.216.34")}, nil+ })+ m := &mockBridge{}+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)+ body := `{"action":"new","url":"https://example.com"}`+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleTab(w, req)+ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected valid URL to proceed, got %d: %s", w.Code, w.Body.String())+ }+ if len(m.createTabURLs) == 0 {+ t.Fatal("expected CreateTab to be called for valid URL")+ }+}+func TestIsNavigateAbortedOnBinary(t *testing.T) {tests := []struct {name stringdiff --git a/internal/server/server.go b/internal/server/server.goindex a15b3829..707540c9 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -75,7 +75,10 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {MaxLifetime: cfg.Sessions.Agent.MaxLifetime,PersistPath: filepath.Join(cfg.StateDir, "sessions.json"),})- agentSessionAPI := dashboard.NewAgentSessionAPI(agentSessionStore)+ var agentSessionAPI *dashboard.AgentSessionAPI+ if agentSessionStore.Enabled() {+ agentSessionAPI = dashboard.NewAgentSessionAPI(agentSessionStore)+ }// Wire up instance events to SSE broadcastorch.OnEvent(func(evt orchestrator.InstanceEvent) {