Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat(sessions): add agent session auth with PINCHTAB_SESSION env var

Bosch2b6608c47454
diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.go
index a47fbde7..b2150f48 100644
--- a/cmd/pinchtab/cmd_cli_runtime.go
+++ b/cmd/pinchtab/cmd_cli_runtime.go
@@ -57,6 +57,10 @@ func resolveCLIBase(cfg *config.RuntimeConfig) string {
}
func resolveCLIToken(cfg *config.RuntimeConfig) string {
+ // PINCHTAB_SESSION takes precedence: use session auth
+ if sessionToken := os.Getenv("PINCHTAB_SESSION"); sessionToken != "" {
+ return sessionToken
+ }
token := cfg.Token
if envToken := os.Getenv("PINCHTAB_TOKEN"); envToken != "" {
token = envToken
@@ -64,6 +68,7 @@ func resolveCLIToken(cfg *config.RuntimeConfig) string {
return token
}
+
func resolveCLIAgentID() string {
if trimmed := strings.TrimSpace(cliAgentID); trimmed != "" {
return trimmed
diff --git a/cmd/pinchtab/cmd_session.go b/cmd/pinchtab/cmd_session.go
new file mode 100644
index 00000000..baec73e6
--- /dev/null
+++ b/cmd/pinchtab/cmd_session.go
@@ -0,0 +1,26 @@
+package main
+
+import (
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/spf13/cobra"
+)
+
+func init() {
+ sessionCmd := &cobra.Command{
+ Use: "session",
+ Short: "Agent session management",
+ }
+
+ infoCmd := &cobra.Command{
+ Use: "info",
+ Short: "Show current agent session details",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ apiclient.DoGet(rt.client, rt.base, rt.token, "/api/agent-sessions/me", nil)
+ })
+ },
+ }
+
+ sessionCmd.AddCommand(infoCmd)
+ rootCmd.AddCommand(sessionCmd)
+}
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 79abf62d..4faa16a5 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -387,6 +387,21 @@ Activity attribution and source behavior:
Scheduler routes are only present when `scheduler.enabled` is true.
+## Agent Sessions
+
+| Method | Path | Description |
+|--------|------|-------------|
+| `POST` | `/api/agent-sessions` | Create a new agent session (body: `{agentId, label?}`) |
+| `GET` | `/api/agent-sessions` | List all agent sessions |
+| `GET` | `/api/agent-sessions/me` | Get current session (requires `Authorization: Session` auth) |
+| `GET` | `/api/agent-sessions/{id}` | Get session details by ID |
+| `POST` | `/api/agent-sessions/{id}/rotate` | Rotate session token |
+| `POST` | `/api/agent-sessions/{id}/revoke` | Revoke session |
+
+All endpoints except `/me` require dashboard auth (bearer or cookie). The `/me` endpoint requires session auth.
+
+Create and rotate return `sessionToken` — the plaintext token shown only once.
+
## Feature Gates
Some endpoints are intentionally disabled unless the matching config allows them:
diff --git a/docs/guides/security.md b/docs/guides/security.md
index 2c59ed3c..3819b492 100644
--- a/docs/guides/security.md
+++ b/docs/guides/security.md
@@ -275,3 +275,14 @@ For a secure local setup:
```
If you intentionally expose PinchTab beyond localhost, treat the token as mandatory and keep the sensitive endpoint families disabled unless you have a specific reason to enable them. For anything more exposed than a single-machine local setup, assume you are operating an advanced deployment and review each security control explicitly.
+
+## Agent Sessions
+
+For automated agents, use **agent sessions** instead of sharing the server bearer token. Each agent gets a dedicated session token (`PINCHTAB_SESSION`) that:
+
+- Maps to a specific `agentId` for activity tracking
+- Can be individually revoked without affecting other agents
+- Has configurable idle timeout and max lifetime
+- Never exposes the server bearer token to agents
+
+See [Reference: Agent Sessions](../reference/sessions.md) for configuration and API details.
diff --git a/docs/reference/sessions.md b/docs/reference/sessions.md
new file mode 100644
index 00000000..d33813e2
--- /dev/null
+++ b/docs/reference/sessions.md
@@ -0,0 +1,67 @@
+# Agent Sessions
+
+Agent sessions provide durable, revocable authentication for automated agents. Instead of sharing the server bearer token, each agent gets its own session token that maps to a specific `agentId`.
+
+## Overview
+
+- **Session token**: `pts_<48 hex chars>` — high-entropy, never stored raw (only SHA-256 hash persisted)
+- **Session ID**: `pts_<16 hex chars>` — public identifier for management
+- **Auth header**: `Authorization: Session <token>`
+- **Env var**: `PINCHTAB_SESSION` — CLI auto-detects and uses session auth
+
+## Configuration
+
+In `config.json`:
+
+```json
+{
+ "sessions": {
+ "agent": {
+ "enabled": true,
+ "mode": "preferred",
+ "idleTimeoutSec": 1800,
+ "maxLifetimeSec": 86400
+ }
+ }
+}
+```
+
+### Modes
+
+| Mode | Behavior |
+|------|----------|
+| `off` | Agent sessions disabled |
+| `preferred` | Both bearer and session auth accepted (default) |
+| `required` | Only session auth accepted for agents |
+
+## Lifecycle
+
+1. **Create** — via dashboard API: `POST /api/agent-sessions`
+2. **Use** — agent sends `Authorization: Session pts_...` with each request
+3. **Rotate** — generate a new token, old one invalidated: `POST /api/agent-sessions/{id}/rotate`
+4. **Revoke** — permanently disable: `POST /api/agent-sessions/{id}/revoke`
+
+## Security
+
+- Tokens are never logged or persisted in plaintext
+- SHA-256 hash comparison using `crypto/subtle.ConstantTimeCompare`
+- Idle timeout (default 30m) and max lifetime (default 24h)
+- Sessions persisted to `agent-sessions.json` (atomic writes)
+- Each session bound to a specific agentId for activity tracking
+
+## CLI Usage
+
+```bash
+# Set session token
+export PINCHTAB_SESSION=pts_abc123...
+
+# CLI automatically uses session auth
+pinchtab snap
+
+# Check session info
+pinchtab session info
+```
+
+## API Endpoints
+
+See [endpoints.md](../endpoints.md) for full API reference.
diff --git a/internal/agentsession/store.go b/internal/agentsession/store.go
new file mode 100644
index 00000000..902a4cc9
--- /dev/null
+++ b/internal/agentsession/store.go
@@ -0,0 +1,404 @@
+// Package agentsession provides durable, revocable session-based
+// authentication for automated agents. 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
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Session represents a durable, revocable agent session.
+type Session struct {
+ ID string `json:"id"`
+ AgentID string `json:"agentId"`
+ Label string `json:"label,omitempty"`
+ TokenHash [32]byte `json:"-"`
+ CreatedAt time.Time `json:"createdAt"`
+ LastSeenAt time.Time `json:"lastSeenAt"`
+ ExpiresAt time.Time `json:"expiresAt,omitempty"`
+ IdleTimeout time.Duration `json:"-"`
+ Status string `json:"status"`
+ Grants []string `json:"grants,omitempty"`
+}
+
+// Config controls store behavior.
+type Config struct {
+ Enabled bool
+ Mode string // "off", "preferred", "required"
+ IdleTimeout time.Duration
+ MaxLifetime time.Duration
+ PersistPath string
+}
+
+// Store manages agent sessions with persistence.
+type Store struct {
+ mu sync.Mutex
+ sessions map[string]*Session // keyed by session ID
+ cfg Config
+ now func() time.Time
+}
+
+const (
+ DefaultIdleTimeout = 30 * time.Minute
+ DefaultMaxLifetime = 24 * time.Hour
+
+ StatusActive = "active"
+ StatusRevoked = "revoked"
+ StatusExpired = "expired"
+)
+
+// NewStore creates a new agent session store.
+func NewStore(cfg Config) *Store {
+ s := &Store{
+ sessions: make(map[string]*Session),
+ now: time.Now,
+ }
+ s.applyConfig(cfg)
+ s.loadPersisted()
+ return s
+}
+
+func (s *Store) applyConfig(cfg Config) {
+ if cfg.IdleTimeout <= 0 {
+ cfg.IdleTimeout = DefaultIdleTimeout
+ }
+ if cfg.MaxLifetime <= 0 {
+ cfg.MaxLifetime = DefaultMaxLifetime
+ }
+ if cfg.Mode == "" {
+ cfg.Mode = "preferred"
+ }
+ s.cfg = cfg
+}
+
+// Create generates a new agent 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 {
+ return "", "", fmt.Errorf("store is nil")
+ }
+
+ id, err := generateSessionID()
+ if err != nil {
+ return "", "", err
+ }
+ token, err := generateToken()
+ if err != nil {
+ return "", "", err
+ }
+
+ now := s.now()
+ session := &Session{
+ ID: id,
+ AgentID: strings.TrimSpace(agentID),
+ Label: strings.TrimSpace(label),
+ TokenHash: hashToken(token),
+ CreatedAt: now,
+ LastSeenAt: now,
+ ExpiresAt: now.Add(s.cfg.MaxLifetime),
+ IdleTimeout: s.cfg.IdleTimeout,
+ Status: StatusActive,
+ }
+
+ s.mu.Lock()
+ s.sessions[id] = session
+ s.saveLocked()
+ s.mu.Unlock()
+
+ return id, token, nil
+}
+
+// Authenticate validates a token and returns the associated session.
+// It updates LastSeenAt on success.
+func (s *Store) Authenticate(token string) (*Session, bool) {
+ if s == nil {
+ return nil, false
+ }
+ token = strings.TrimSpace(token)
+ if token == "" {
+ return nil, false
+ }
+
+ hash := hashToken(token)
+ now := s.now()
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ for _, sess := range s.sessions {
+ if sess.Status != StatusActive {
+ continue
+ }
+ if subtle.ConstantTimeCompare(hash[:], sess.TokenHash[:]) != 1 {
+ continue
+ }
+ if s.isExpired(sess, now) {
+ sess.Status = StatusExpired
+ s.saveLocked()
+ return nil, false
+ }
+ sess.LastSeenAt = now
+ s.saveLocked()
+ return sess, true
+ }
+ return nil, false
+}
+
+// Get returns a session by its public ID.
+func (s *Store) Get(sessionID string) (*Session, bool) {
+ if s == nil {
+ return nil, false
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ sess, ok := s.sessions[strings.TrimSpace(sessionID)]
+ if !ok {
+ return nil, false
+ }
+ return sess, true
+}
+
+// List returns all sessions.
+func (s *Store) List() []Session {
+ if s == nil {
+ return nil
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ out := make([]Session, 0, len(s.sessions))
+ for _, sess := range s.sessions {
+ out = append(out, *sess)
+ }
+ return out
+}
+
+// Revoke marks a session as revoked.
+func (s *Store) Revoke(sessionID string) bool {
+ if s == nil {
+ return false
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ sess, ok := s.sessions[strings.TrimSpace(sessionID)]
+ if !ok {
+ return false
+ }
+ sess.Status = StatusRevoked
+ s.saveLocked()
+ return true
+}
+
+// Rotate invalidates the current token and returns a new one.
+func (s *Store) Rotate(sessionID string) (string, error) {
+ if s == nil {
+ return "", fmt.Errorf("store is nil")
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ sess, ok := s.sessions[strings.TrimSpace(sessionID)]
+ if !ok {
+ return "", fmt.Errorf("session not found")
+ }
+ if sess.Status != StatusActive {
+ return "", fmt.Errorf("session is %s", sess.Status)
+ }
+
+ token, err := generateToken()
+ if err != nil {
+ return "", err
+ }
+ sess.TokenHash = hashToken(token)
+ sess.LastSeenAt = s.now()
+ s.saveLocked()
+ return token, nil
+}
+
+// UpdateConfig applies new configuration.
+func (s *Store) UpdateConfig(cfg Config) {
+ if s == nil {
+ return
+ }
+ s.mu.Lock()
+ s.applyConfig(cfg)
+ s.pruneExpiredLocked()
+ s.saveLocked()
+ s.mu.Unlock()
+}
+
+// Enabled reports whether agent sessions are enabled.
+func (s *Store) Enabled() bool {
+ if s == nil {
+ return false
+ }
+ return s.cfg.Enabled
+}
+
+// Mode returns the current auth mode.
+func (s *Store) Mode() string {
+ if s == nil {
+ return "off"
+ }
+ return s.cfg.Mode
+}
+
+func (s *Store) isExpired(sess *Session, now time.Time) bool {
+ if !sess.ExpiresAt.IsZero() && now.After(sess.ExpiresAt) {
+ return true
+ }
+ if s.cfg.IdleTimeout > 0 && now.Sub(sess.LastSeenAt) > s.cfg.IdleTimeout {
+ return true
+ }
+ return false
+}
+
+func (s *Store) pruneExpiredLocked() {
+ now := s.now()
+ for id, sess := range s.sessions {
+ if sess.Status == StatusRevoked {
+ delete(s.sessions, id)
+ continue
+ }
+ if s.isExpired(sess, now) {
+ delete(s.sessions, id)
+ }
+ }
+}
+
+// persistence types
+
+type persistedStore struct {
+ SavedAt time.Time `json:"savedAt"`
+ Sessions []persistedAgentSession `json:"sessions"`
+}
+
+type persistedAgentSession struct {
+ ID string `json:"id"`
+ AgentID string `json:"agentId"`
+ Label string `json:"label,omitempty"`
+ TokenHash string `json:"tokenHash"`
+ CreatedAt time.Time `json:"createdAt"`
+ LastSeenAt time.Time `json:"lastSeenAt"`
+ ExpiresAt time.Time `json:"expiresAt,omitempty"`
+ Status string `json:"status"`
+ Grants []string `json:"grants,omitempty"`
+}
+
+func (s *Store) loadPersisted() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.cfg.PersistPath == "" {
+ return
+ }
+
+ data, err := os.ReadFile(s.cfg.PersistPath)
+ if err != nil {
+ return
+ }
+ var persisted persistedStore
+ if err := json.Unmarshal(data, &persisted); err != nil {
+ return
+ }
+
+ now := s.now()
+ for _, rec := range persisted.Sessions {
+ tokenHash, err := hex.DecodeString(strings.TrimSpace(rec.TokenHash))
+ if err != nil || len(tokenHash) != sha256.Size {
+ continue
+ }
+ var hash [32]byte
+ copy(hash[:], tokenHash)
+
+ sess := &Session{
+ ID: rec.ID,
+ AgentID: rec.AgentID,
+ Label: rec.Label,
+ TokenHash: hash,
+ CreatedAt: rec.CreatedAt,
+ LastSeenAt: rec.LastSeenAt,
+ ExpiresAt: rec.ExpiresAt,
+ IdleTimeout: s.cfg.IdleTimeout,
+ Status: rec.Status,
+ Grants: rec.Grants,
+ }
+ if sess.Status != StatusActive {
+ continue
+ }
+ if s.isExpired(sess, now) {
+ continue
+ }
+ s.sessions[sess.ID] = sess
+ }
+}
+
+func (s *Store) saveLocked() {
+ if s.cfg.PersistPath == "" {
+ return
+ }
+
+ snapshot := persistedStore{
+ SavedAt: s.now().UTC(),
+ Sessions: make([]persistedAgentSession, 0, len(s.sessions)),
+ }
+ for _, sess := range s.sessions {
+ snapshot.Sessions = append(snapshot.Sessions, persistedAgentSession{
+ ID: sess.ID,
+ AgentID: sess.AgentID,
+ Label: sess.Label,
+ TokenHash: hex.EncodeToString(sess.TokenHash[:]),
+ CreatedAt: sess.CreatedAt,
+ LastSeenAt: sess.LastSeenAt,
+ ExpiresAt: sess.ExpiresAt,
+ Status: sess.Status,
+ Grants: sess.Grants,
+ })
+ }
+
+ data, err := json.MarshalIndent(snapshot, "", " ")
+ if err != nil {
+ return
+ }
+ if err := os.MkdirAll(filepath.Dir(s.cfg.PersistPath), 0755); err != nil {
+ return
+ }
+ // Atomic write: temp file + rename
+ tmpPath := s.cfg.PersistPath + ".tmp"
+ if err := os.WriteFile(tmpPath, data, 0600); err != nil {
+ return
+ }
+ _ = os.Rename(tmpPath, s.cfg.PersistPath)
+}
+
+func generateSessionID() (string, error) {
+ buf := make([]byte, 8)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ return "pts_" + hex.EncodeToString(buf), nil
+}
+
+func generateToken() (string, error) {
+ buf := make([]byte, 24)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ return "pts_" + hex.EncodeToString(buf), nil
+}
+
+func hashToken(token string) [32]byte {
+ return sha256.Sum256([]byte(strings.TrimSpace(token)))
+}
diff --git a/internal/agentsession/store_test.go b/internal/agentsession/store_test.go
new file mode 100644
index 00000000..a8a49567
--- /dev/null
+++ b/internal/agentsession/store_test.go
@@ -0,0 +1,276 @@
+package agentsession
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestCreateAndAuthenticate(t *testing.T) {
+ s := NewStore(Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})
+ id, token, err := s.Create("agent-1", "test session")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.HasPrefix(id, "pts_") {
+ t.Fatalf("session ID should start with pts_, got %q", id)
+ }
+ if !strings.HasPrefix(token, "pts_") {
+ t.Fatalf("token should start with pts_, got %q", token)
+ }
+ if len(token) != 4+48 { // pts_ + 48 hex chars
+ t.Fatalf("token length should be 52, got %d", len(token))
+ }
+ if len(id) != 4+16 { // pts_ + 16 hex chars
+ t.Fatalf("session ID length should be 20, got %d", len(id))
+ }
+
+ sess, ok := s.Authenticate(token)
+ if !ok || sess == nil {
+ t.Fatal("expected successful authentication")
+ }
+ if sess.AgentID != "agent-1" {
+ t.Fatalf("expected agentId agent-1, got %q", sess.AgentID)
+ }
+ if sess.Label != "test session" {
+ t.Fatalf("expected label 'test session', got %q", sess.Label)
+ }
+}
+
+func TestAuthenticateInvalidToken(t *testing.T) {
+ s := NewStore(Config{Enabled: true})
+ _, _, _ = s.Create("agent-1", "")
+ sess, ok := s.Authenticate("pts_invalidtoken")
+ if ok || sess != nil {
+ t.Fatal("expected failed authentication for invalid token")
+ }
+}
+
+func TestAuthenticateEmptyToken(t *testing.T) {
+ s := NewStore(Config{Enabled: true})
+ sess, ok := s.Authenticate("")
+ if ok || sess != nil {
+ t.Fatal("expected failed authentication for empty token")
+ }
+}
+
+func TestExpiry(t *testing.T) {
+ s := NewStore(Config{Enabled: true, MaxLifetime: 1 * time.Hour, IdleTimeout: 30 * time.Minute})
+ now := time.Now()
+ s.now = func() time.Time { return now }
+
+ _, token, _ := s.Create("agent-1", "")
+
+ // Advance past max lifetime
+ s.now = func() time.Time { return now.Add(2 * time.Hour) }
+ sess, ok := s.Authenticate(token)
+ if ok || sess != nil {
+ t.Fatal("expected authentication to fail after expiry")
+ }
+}
+
+func TestIdleTimeout(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 }
+
+ _, token, _ := s.Create("agent-1", "")
+
+ // Advance past idle timeout
+ s.now = func() time.Time { return now.Add(15 * time.Minute) }
+ sess, ok := s.Authenticate(token)
+ if ok || sess != nil {
+ t.Fatal("expected authentication to fail after idle timeout")
+ }
+}
+
+func TestIdleTimeoutReset(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 }
+
+ _, token, _ := s.Create("agent-1", "")
+
+ // Advance 8 minutes and authenticate (resets idle)
+ s.now = func() time.Time { return now.Add(8 * time.Minute) }
+ sess, ok := s.Authenticate(token)
+ if !ok || sess == nil {
+ t.Fatal("expected auth to succeed within idle window")
+ }
+
+ // Another 8 minutes from the last auth (total 16 from create, but only 8 from last use)
+ 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 idle reset")
+ }
+}
+
+func TestRevoke(t *testing.T) {
+ s := NewStore(Config{Enabled: true})
+ id, token, _ := s.Create("agent-1", "")
+
+ ok := s.Revoke(id)
+ if !ok {
+ t.Fatal("expected revoke to succeed")
+ }
+
+ sess, ok := s.Authenticate(token)
+ if ok || sess != nil {
+ t.Fatal("expected authentication to fail after revoke")
+ }
+}
+
+func TestRevokeNotFound(t *testing.T) {
+ s := NewStore(Config{Enabled: true})
+ if s.Revoke("pts_nonexistent") {
+ t.Fatal("expected revoke to return false for non-existent session")
+ }
+}
+
+func TestRotate(t *testing.T) {
+ s := NewStore(Config{Enabled: true})
+ id, oldToken, _ := s.Create("agent-1", "")
+
+ newToken, err := s.Rotate(id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if newToken == oldToken {
+ t.Fatal("expected new token to differ from old")
+ }
+
+ // Old token should fail
+ sess, ok := s.Authenticate(oldToken)
+ if ok || sess != nil {
+ t.Fatal("expected old token to fail after rotation")
+ }
+
+ // New token should succeed
+ sess, ok = s.Authenticate(newToken)
+ if !ok || sess == nil {
+ t.Fatal("expected new token to succeed after rotation")
+ }
+}
+
+func TestRotateRevoked(t *testing.T) {
+ s := NewStore(Config{Enabled: true})
+ id, _, _ := s.Create("agent-1", "")
+ s.Revoke(id)
+
+ _, err := s.Rotate(id)
+ if err == nil {
+ t.Fatal("expected rotate to fail on revoked session")
+ }
+}
+
+func TestGet(t *testing.T) {
+ s := NewStore(Config{Enabled: true})
+ id, _, _ := s.Create("agent-1", "my label")
+
+ sess, ok := s.Get(id)
+ if !ok || sess == nil {
+ t.Fatal("expected Get to find session")
+ }
+ if sess.AgentID != "agent-1" || sess.Label != "my label" {
+ t.Fatal("unexpected session data")
+ }
+}
+
+func TestList(t *testing.T) {
+ s := NewStore(Config{Enabled: true})
+ s.Create("agent-1", "")
+ s.Create("agent-2", "")
+
+ list := s.List()
+ if len(list) != 2 {
+ t.Fatalf("expected 2 sessions, got %d", len(list))
+ }
+}
+
+func TestPersistAndLoad(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "sessions.json")
+
+ s1 := NewStore(Config{Enabled: true, PersistPath: path, IdleTimeout: 1 * time.Hour, MaxLifetime: 24 * time.Hour})
+ _, token, _ := s1.Create("agent-1", "persist test")
+
+ // Create a new store from the same file
+ s2 := NewStore(Config{Enabled: true, PersistPath: path, IdleTimeout: 1 * time.Hour, MaxLifetime: 24 * time.Hour})
+
+ sess, ok := s2.Authenticate(token)
+ if !ok || sess == nil {
+ t.Fatal("expected session to survive persistence round-trip")
+ }
+ if sess.AgentID != "agent-1" {
+ t.Fatalf("expected agent-1, got %q", sess.AgentID)
+ }
+}
+
+func TestPrunedOnLoad(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "sessions.json")
+
+ s1 := NewStore(Config{Enabled: true, PersistPath: path, MaxLifetime: 1 * time.Hour, IdleTimeout: 30 * time.Minute})
+ now := time.Now()
+ s1.now = func() time.Time { return now }
+ s1.Create("agent-1", "will expire")
+
+ // Load with time advanced past expiry — set now before NewStore calls loadPersisted
+ futureTime := now.Add(2 * time.Hour)
+ s2 := &Store{
+ sessions: make(map[string]*Session),
+ now: func() time.Time { return futureTime },
+ }
+ s2.applyConfig(Config{Enabled: true, PersistPath: path, MaxLifetime: 1 * time.Hour, IdleTimeout: 30 * time.Minute})
+ s2.loadPersisted()
+
+ if len(s2.List()) != 0 {
+ t.Fatal("expected expired sessions to be pruned on load")
+ }
+}
+
+func TestAtomicWrite(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "sessions.json")
+
+ s := NewStore(Config{Enabled: true, PersistPath: path})
+ s.Create("agent-1", "")
+
+ // Verify file exists and is valid JSON
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var store persistedStore
+ if err := json.Unmarshal(data, &store); err != nil {
+ t.Fatalf("persisted file is not valid JSON: %v", err)
+ }
+ if len(store.Sessions) != 1 {
+ t.Fatalf("expected 1 persisted session, got %d", len(store.Sessions))
+ }
+ // Verify no raw token in persisted data
+ if strings.Contains(string(data), "pts_") && strings.Contains(string(data), `"token"`) {
+ t.Fatal("raw token found in persisted data")
+ }
+}
+
+func TestNilStore(t *testing.T) {
+ var s *Store
+ _, ok := s.Authenticate("token")
+ if ok {
+ t.Fatal("nil store should not authenticate")
+ }
+ if s.Revoke("id") {
+ t.Fatal("nil store should not revoke")
+ }
+ if s.Enabled() {
+ t.Fatal("nil store should not be enabled")
+ }
+ if s.List() != nil {
+ t.Fatal("nil store should return nil list")
+ }
+}
diff --git a/internal/authn/request.go b/internal/authn/request.go
index 30e049a6..00c6179c 100644
--- a/internal/authn/request.go
+++ b/internal/authn/request.go
@@ -10,9 +10,10 @@ import (
type Method string
const (
- MethodNone Method = ""
- MethodHeader Method = "header"
- MethodCookie Method = "cookie"
+ MethodNone Method = ""
+ MethodHeader Method = "header"
+ MethodCookie Method = "cookie"
+ MethodSession Method = "session"
)
type Credentials struct {
@@ -31,8 +32,15 @@ func CredentialsFromRequest(r *http.Request) Credentials {
return Credentials{}
}
- if token := tokenFromAuthorizationHeader(r.Header.Get("Authorization")); token != "" {
- return Credentials{Value: token, Method: MethodHeader}
+ bearer, session := parseAuthorizationHeader(r.Header.Get("Authorization"))
+ if bearer != "" && session != "" {
+ return Credentials{}
+ }
+ if session != "" {
+ return Credentials{Value: session, Method: MethodSession}
+ }
+ if bearer != "" {
+ return Credentials{Value: bearer, Method: MethodHeader}
}
cookie, err := r.Cookie(CookieName)
@@ -75,9 +83,28 @@ func tokenFromAuthorizationHeader(auth string) string {
if strings.HasPrefix(strings.ToLower(auth), "bearer ") {
return strings.TrimSpace(auth[7:])
}
+ if strings.HasPrefix(strings.ToLower(auth), "session ") {
+ return ""
+ }
return auth
}
+func parseAuthorizationHeader(auth string) (bearer, session string) {
+ auth = strings.TrimSpace(auth)
+ if auth == "" {
+ return "", ""
+ }
+ lower := strings.ToLower(auth)
+ if strings.HasPrefix(lower, "session ") {
+ return "", strings.TrimSpace(auth[8:])
+ }
+ if strings.HasPrefix(lower, "bearer ") {
+ return strings.TrimSpace(auth[7:]), ""
+ }
+ // Bare token treated as bearer
+ return auth, ""
+}
+
func normalizeCookieValue(value string) string {
value = strings.TrimSpace(value)
if value == "" {
diff --git a/internal/authn/request_test.go b/internal/authn/request_test.go
index 39c318d0..12efeaf4 100644
--- a/internal/authn/request_test.go
+++ b/internal/authn/request_test.go
@@ -70,3 +70,52 @@ func TestClientIP_FallsBackToRawRemoteAddr(t *testing.T) {
t.Fatalf("ClientIP() = %q, want %q", got, "198.51.100.10")
}
}
+
+func TestCredentialsFromRequest_SessionAuth(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.Header.Set("Authorization", "Session pts_abc123")
+
+ creds := CredentialsFromRequest(req)
+ if creds.Method != MethodSession {
+ t.Fatalf("Method = %q, want %q", creds.Method, MethodSession)
+ }
+ if creds.Value != "pts_abc123" {
+ t.Fatalf("Value = %q, want %q", creds.Value, "pts_abc123")
+ }
+}
+
+func TestCredentialsFromRequest_SessionAuthCaseInsensitive(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.Header.Set("Authorization", "SESSION pts_token")
+
+ creds := CredentialsFromRequest(req)
+ if creds.Method != MethodSession {
+ t.Fatalf("Method = %q, want %q", creds.Method, MethodSession)
+ }
+}
+
+func TestCredentialsFromRequest_BearerStillWorks(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.Header.Set("Authorization", "Bearer my-token")
+
+ creds := CredentialsFromRequest(req)
+ if creds.Method != MethodHeader {
+ t.Fatalf("Method = %q, want %q", creds.Method, MethodHeader)
+ }
+ if creds.Value != "my-token" {
+ t.Fatalf("Value = %q, want %q", creds.Value, "my-token")
+ }
+}
+
+func TestCredentialsFromRequest_BareTokenIsBearerNotSession(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.Header.Set("Authorization", "raw-token-value")
+
+ creds := CredentialsFromRequest(req)
+ if creds.Method != MethodHeader {
+ t.Fatalf("Method = %q, want %q", creds.Method, MethodHeader)
+ }
+ if creds.Value != "raw-token-value" {
+ t.Fatalf("Value = %q, want %q", creds.Value, "raw-token-value")
+ }
+}
diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.go
index a82c2d99..d0de4a92 100644
--- a/internal/cli/apiclient/client.go
+++ b/internal/cli/apiclient/client.go
@@ -9,6 +9,7 @@ import (
"net/http"
"net/url"
"os"
+ "strings"
"time"
"github.com/pinchtab/pinchtab/internal/activity"
@@ -20,9 +21,7 @@ func DoGet(client *http.Client, base, token, path string, params url.Values) map
u += "?" + params.Encode()
}
req, _ := http.NewRequest("GET", u, nil)
- if token != "" {
- req.Header.Set("Authorization", "Bearer "+token)
- }
+ setAuthHeader(req, token)
req.Header.Set(activity.HeaderAgentID, "cli")
resp, err := client.Do(req)
if err != nil {
@@ -58,9 +57,7 @@ func DoGetRaw(client *http.Client, base, token, path string, params url.Values)
u += "?" + params.Encode()
}
req, _ := http.NewRequest("GET", u, nil)
- if token != "" {
- req.Header.Set("Authorization", "Bearer "+token)
- }
+ setAuthHeader(req, token)
req.Header.Set(activity.HeaderAgentID, "cli")
resp, err := client.Do(req)
if err != nil {
@@ -80,9 +77,7 @@ func DoPost(client *http.Client, base, token, path string, body map[string]any)
data, _ := json.Marshal(body)
req, _ := http.NewRequest("POST", base+path, bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
- if token != "" {
- req.Header.Set("Authorization", "Bearer "+token)
- }
+ setAuthHeader(req, token)
req.Header.Set(activity.HeaderAgentID, "cli")
resp, err := client.Do(req)
if err != nil {
@@ -129,6 +124,17 @@ func ResolveInstanceBase(orchBase, token, instanceID, bind string) string {
return fmt.Sprintf("http://%s:%s", bind, inst.Port)
}
+func setAuthHeader(req *http.Request, token string) {
+ if token == "" {
+ return
+ }
+ if strings.HasPrefix(token, "pts_") {
+ req.Header.Set("Authorization", "Session "+token)
+ } else {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+}
+
func fatal(format string, args ...any) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
os.Exit(1)
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index 1e3475fb..161ff118 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -98,8 +98,14 @@ func Load() *RuntimeConfig {
},
},
- // Dashboard session defaults
+ // Session defaults
Sessions: SessionsRuntimeConfig{
+ Agent: AgentSessionRuntimeConfig{
+ Enabled: true,
+ Mode: "preferred",
+ IdleTimeout: 30 * time.Minute,
+ MaxLifetime: 24 * time.Hour,
+ },
Dashboard: DashboardSessionRuntimeConfig{
Persist: true,
IdleTimeout: 7 * 24 * time.Hour,
@@ -285,6 +291,20 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
cfg.Sessions.Dashboard.RequireElevation = *fc.Sessions.Dashboard.RequireElevation
}
+ // Agent sessions
+ if fc.Sessions.Agent.Enabled != nil {
+ cfg.Sessions.Agent.Enabled = *fc.Sessions.Agent.Enabled
+ }
+ if fc.Sessions.Agent.Mode != "" {
+ cfg.Sessions.Agent.Mode = fc.Sessions.Agent.Mode
+ }
+ if fc.Sessions.Agent.IdleTimeoutSec != nil && *fc.Sessions.Agent.IdleTimeoutSec > 0 {
+ cfg.Sessions.Agent.IdleTimeout = time.Duration(*fc.Sessions.Agent.IdleTimeoutSec) * time.Second
+ }
+ if fc.Sessions.Agent.MaxLifetimeSec != nil && *fc.Sessions.Agent.MaxLifetimeSec > 0 {
+ cfg.Sessions.Agent.MaxLifetime = time.Duration(*fc.Sessions.Agent.MaxLifetimeSec) * time.Second
+ }
+
// Browser
if fc.Browser.ChromeVersion != "" {
cfg.ChromeVersion = fc.Browser.ChromeVersion
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index 305fb5ff..9f969eec 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -100,6 +100,14 @@ type RuntimeConfig struct {
type SessionsRuntimeConfig struct {
Dashboard DashboardSessionRuntimeConfig `json:"dashboard,omitempty"`
+ Agent AgentSessionRuntimeConfig `json:"agent,omitempty"`
+}
+
+type AgentSessionRuntimeConfig struct {
+ Enabled bool `json:"enabled,omitempty"`
+ Mode string `json:"mode,omitempty"`
+ IdleTimeout time.Duration `json:"idleTimeout,omitempty"`
+ MaxLifetime time.Duration `json:"maxLifetime,omitempty"`
}
type DashboardSessionRuntimeConfig struct {
@@ -190,6 +198,14 @@ type ServerConfig struct {
type SessionsFileConfig struct {
Dashboard DashboardSessionFileConfig `json:"dashboard,omitempty"`
+ Agent AgentSessionFileConfig `json:"agent,omitempty"`
+}
+
+type AgentSessionFileConfig struct {
+ Enabled *bool `json:"enabled,omitempty"`
+ Mode string `json:"mode,omitempty"`
+ IdleTimeoutSec *int `json:"idleTimeoutSec,omitempty"`
+ MaxLifetimeSec *int `json:"maxLifetimeSec,omitempty"`
}
type DashboardSessionFileConfig struct {
diff --git a/internal/dashboard/agent_session_api.go b/internal/dashboard/agent_session_api.go
new file mode 100644
index 00000000..c1f4e23c
--- /dev/null
+++ b/internal/dashboard/agent_session_api.go
@@ -0,0 +1,120 @@
+package dashboard
+
+import (
+ "encoding/json"
+ "net/http"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/agentsession"
+ "github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+// AgentSessionAPI handles CRUD operations for agent sessions.
+type AgentSessionAPI struct {
+ store *agentsession.Store
+}
+
+// NewAgentSessionAPI creates a new agent session API handler.
+func NewAgentSessionAPI(store *agentsession.Store) *AgentSessionAPI {
+ return &AgentSessionAPI{store: store}
+}
+
+// RegisterHandlers registers agent session API routes.
+func (a *AgentSessionAPI) RegisterHandlers(mux *http.ServeMux) {
+ mux.HandleFunc("POST /api/agent-sessions", a.handleCreate)
+ mux.HandleFunc("GET /api/agent-sessions", a.handleList)
+ mux.HandleFunc("GET /api/agent-sessions/me", a.handleMe)
+ mux.HandleFunc("GET /api/agent-sessions/{id}", a.handleGet)
+ mux.HandleFunc("POST /api/agent-sessions/{id}/rotate", a.handleRotate)
+ mux.HandleFunc("POST /api/agent-sessions/{id}/revoke", a.handleRevoke)
+}
+
+func (a *AgentSessionAPI) handleCreate(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ AgentID string `json:"agentId"`
+ Label string `json:"label,omitempty"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&req); err != nil {
+ httpx.ErrorCode(w, http.StatusBadRequest, "bad_request", "invalid request body", false, nil)
+ return
+ }
+ if strings.TrimSpace(req.AgentID) == "" {
+ httpx.ErrorCode(w, http.StatusBadRequest, "missing_agent_id", "agentId is required", false, nil)
+ return
+ }
+
+ 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)
+ return
+ }
+
+ sess, _ := a.store.Get(sessionID)
+ httpx.JSON(w, http.StatusCreated, map[string]any{
+ "id": sessionID,
+ "agentId": sess.AgentID,
+ "label": sess.Label,
+ "sessionToken": token,
+ "createdAt": sess.CreatedAt,
+ "expiresAt": sess.ExpiresAt,
+ "status": sess.Status,
+ })
+}
+
+func (a *AgentSessionAPI) handleList(w http.ResponseWriter, _ *http.Request) {
+ sessions := a.store.List()
+ if sessions == nil {
+ sessions = []agentsession.Session{}
+ }
+ httpx.JSON(w, http.StatusOK, sessions)
+}
+
+func (a *AgentSessionAPI) 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)
+ return
+ }
+ httpx.JSON(w, http.StatusOK, sess)
+}
+
+func (a *AgentSessionAPI) handleMe(w http.ResponseWriter, r *http.Request) {
+ creds := authn.CredentialsFromRequest(r)
+ if creds.Method != authn.MethodSession {
+ httpx.ErrorCode(w, http.StatusBadRequest, "session_auth_required", "this endpoint requires session authentication", false, nil)
+ return
+ }
+ sess, ok := a.store.Authenticate(creds.Value)
+ if !ok || sess == nil {
+ httpx.ErrorCode(w, http.StatusUnauthorized, "bad_session", "invalid or expired agent session", false, nil)
+ return
+ }
+ httpx.JSON(w, http.StatusOK, sess)
+}
+
+func (a *AgentSessionAPI) handleRotate(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ newToken, err := a.store.Rotate(id)
+ if err != nil {
+ httpx.ErrorCode(w, http.StatusBadRequest, "rotate_failed", err.Error(), false, nil)
+ return
+ }
+ sess, _ := a.store.Get(id)
+ httpx.JSON(w, http.StatusOK, map[string]any{
+ "id": sess.ID,
+ "agentId": sess.AgentID,
+ "sessionToken": newToken,
+ "status": sess.Status,
+ })
+}
+
+func (a *AgentSessionAPI) handleRevoke(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ if !a.store.Revoke(id) {
+ httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "agent session not found", false, nil)
+ return
+ }
+ httpx.JSON(w, http.StatusOK, map[string]string{"status": "ok"})
+}
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
index e32ce9e0..bcd43d79 100644
--- a/internal/handlers/middleware.go
+++ b/internal/handlers/middleware.go
@@ -12,6 +12,8 @@ import (
"sync/atomic"
"time"
+ "github.com/pinchtab/pinchtab/internal/activity"
+ "github.com/pinchtab/pinchtab/internal/agentsession"
"github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/httpx"
@@ -80,10 +82,10 @@ func SecurityHeadersMiddleware(cfg *config.RuntimeConfig, next http.Handler) htt
}
func AuthMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {
- return AuthMiddlewareWithSessions(cfg, nil, next)
+ return AuthMiddlewareWithSessions(cfg, nil, nil, next)
}
-func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.SessionManager, next http.Handler) http.Handler {
+func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.SessionManager, agentSessions *agentsession.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)
@@ -104,6 +106,20 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessi
}
switch creds.Method {
+ case authn.MethodSession:
+ if agentSessions == nil || !agentSessions.Enabled() {
+ httpx.ErrorCode(w, 401, "session_auth_unavailable", "agent session authentication is not enabled", false, nil)
+ return
+ }
+ sess, ok := agentSessions.Authenticate(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
+ }
+ // Inject agent identity into request headers for activity tracking
+ r.Header.Set(activity.HeaderAgentID, sess.AgentID)
+ r.Header.Set(activity.HeaderPTSessionID, sess.ID)
case authn.MethodHeader:
if subtle.ConstantTimeCompare([]byte(creds.Value), []byte(token)) != 1 {
authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))
@@ -173,6 +189,8 @@ func cookieAuthAllowed(r *http.Request) bool {
path == "/api/agents",
path == "/api/events",
path == "/api/config",
+ path == "/api/agent-sessions",
+ strings.HasPrefix(path, "/api/agent-sessions/"),
path == "/profiles",
path == "/instances",
path == "/instances/tabs",
@@ -192,6 +210,10 @@ func cookieAuthAllowed(r *http.Request) bool {
switch {
case path == "/api/auth/elevate":
return true
+ case path == "/api/agent-sessions":
+ return true
+ case strings.HasPrefix(path, "/api/agent-sessions/"):
+ return true
case strings.HasPrefix(path, "/api/agents/") && strings.HasSuffix(path, "/events"):
return true
case path == "/action":
diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.go
index c1b4d978..9dbebf95 100644
--- a/internal/handlers/middleware_test.go
+++ b/internal/handlers/middleware_test.go
@@ -7,6 +7,7 @@ import (
"testing"
"time"
+ "github.com/pinchtab/pinchtab/internal/agentsession"
"github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/httpx"
@@ -167,7 +168,7 @@ func TestAuthMiddleware_ValidCookie(t *testing.T) {
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(200)
}))
@@ -194,7 +195,7 @@ func TestAuthMiddleware_CookieRestrictedEndpointRejected(t *testing.T) {
t.Fatalf("Create() error = %v", err)
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(200)
}))
@@ -221,7 +222,7 @@ func TestAuthMiddleware_CookieAllowsTabCloseEndpoint(t *testing.T) {
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
@@ -249,7 +250,7 @@ func TestAuthMiddleware_CookieAllowsActionEndpoint(t *testing.T) {
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
@@ -277,7 +278,7 @@ func TestAuthMiddleware_CookieCrossOriginRejected(t *testing.T) {
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
@@ -305,7 +306,7 @@ func TestAuthMiddleware_CookieRequestWithoutOriginOrRefererRejected(t *testing.T
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
@@ -332,7 +333,7 @@ func TestAuthMiddleware_CookieSameOriginRefererAccepted(t *testing.T) {
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
@@ -360,7 +361,7 @@ func TestAuthMiddleware_CookieIgnoresForwardedOriginHints(t *testing.T) {
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
@@ -391,7 +392,7 @@ func TestAuthMiddleware_CookieWebSocketRequiresSameOrigin(t *testing.T) {
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
@@ -443,7 +444,7 @@ func TestAuthMiddleware_CookieElevatedEndpointRequiresElevation(t *testing.T) {
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
@@ -489,7 +490,7 @@ func TestAuthMiddleware_CookieConfigEndpointDoesNotRequireElevationByDefault(t *
}
called := false
- handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
@@ -989,3 +990,69 @@ func TestStatusWriter(t *testing.T) {
t.Errorf("expected 404, got %d", sw.Code)
}
}
+
+func TestAuthMiddleware_SessionAuth(t *testing.T) {
+ store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})
+ _, token, _ := store.Create("test-agent", "test")
+
+ cfg := &config.RuntimeConfig{Token: "server-token"}
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest("GET", "/health", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ rr := httptest.NewRecorder()
+ handler.ServeHTTP(rr, req)
+
+ if !called {
+ t.Fatal("expected handler to be called with valid session token")
+ }
+ if rr.Code != 200 {
+ t.Fatalf("expected 200, got %d", rr.Code)
+ }
+}
+
+func TestAuthMiddleware_SessionAuthInvalid(t *testing.T) {
+ store := agentsession.NewStore(agentsession.Config{Enabled: true})
+
+ cfg := &config.RuntimeConfig{Token: "server-token"}
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ }))
+
+ req := httptest.NewRequest("GET", "/health", nil)
+ req.Header.Set("Authorization", "Session pts_invalidtoken")
+ rr := httptest.NewRecorder()
+ handler.ServeHTTP(rr, req)
+
+ if called {
+ t.Fatal("handler should not be called with invalid session token")
+ }
+ if rr.Code != 401 {
+ t.Fatalf("expected 401, got %d", rr.Code)
+ }
+}
+
+func TestAuthMiddleware_SessionAuthDisabled(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "server-token"}
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, nil, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ }))
+
+ req := httptest.NewRequest("GET", "/health", nil)
+ req.Header.Set("Authorization", "Session pts_sometoken")
+ rr := httptest.NewRecorder()
+ handler.ServeHTTP(rr, req)
+
+ if called {
+ t.Fatal("handler should not be called when agent sessions disabled")
+ }
+ if rr.Code != 401 {
+ t.Fatalf("expected 401, got %d", rr.Code)
+ }
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index 9249a1e7..ae822ec0 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -6,12 +6,14 @@ import (
"log/slog"
"net/http"
"os"
+ "path/filepath"
"os/signal"
"sync"
"syscall"
"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/cli"
@@ -68,6 +70,16 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
configAPI.SetSessionManager(sessions)
authAPI := dashboard.NewAuthAPI(cfg, sessions)
+ // Agent sessions
+ agentSessionStore := agentsession.NewStore(agentsession.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, "agent-sessions.json"),
+ })
+ agentSessionAPI := dashboard.NewAgentSessionAPI(agentSessionStore)
+
// Wire up instance events to SSE broadcast
orch.OnEvent(func(evt orchestrator.InstanceEvent) {
dash.BroadcastSystemEvent(dashboard.SystemEvent{
@@ -95,6 +107,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
dash.RegisterHandlers(mux)
configAPI.RegisterHandlers(mux)
authAPI.RegisterHandlers(mux)
+ agentSessionAPI.RegisterHandlers(mux)
profMgr.RegisterHandlers(mux)
liveActivity := newDashboardActivityRecorder(actStore, dash)
activity.RegisterHandlers(mux, liveActivity)
@@ -215,7 +228,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
liveActivity,
"server",
handlers.SecurityHeadersMiddleware(cfg,
- handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, mux)))),
+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, agentSessionStore, mux)))),
),
),
)
diff --git a/internal/server/timeouts_test.go b/internal/server/timeouts_test.go
index 4de2910a..d71ffd91 100644
--- a/internal/server/timeouts_test.go
+++ b/internal/server/timeouts_test.go
@@ -41,7 +41,7 @@ func TestDashboardHandlerChainAppliesRateLimit(t *testing.T) {
activity.Middleware(
nil,
"server",
- handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, mux)))),
+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, nil, mux)))),
),
)
diff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.md
index b107582d..5199316a 100644
--- a/skills/pinchtab/SKILL.md
+++ b/skills/pinchtab/SKILL.md
@@ -258,6 +258,8 @@ curl -X POST http://localhost:9868/action \
If the server is exposed beyond localhost, require a token and use a dedicated automation profile. See [TRUST.md](./TRUST.md) and [config.md](../../docs/reference/config.md).
+**Agent sessions**: Instead of sharing the server token, use `PINCHTAB_SESSION=pts_...` for per-agent identity with revocable tokens. Create sessions via `POST /api/agent-sessions`. See [sessions reference](../../docs/reference/sessions.md).
+
## Essential Commands
### Server and targeting
diff --git a/skills/pinchtab/references/api.md b/skills/pinchtab/references/api.md
index 5c1d2b64..03a7443e 100644
--- a/skills/pinchtab/references/api.md
+++ b/skills/pinchtab/references/api.md
@@ -445,3 +445,22 @@ curl -X POST /fingerprint/rotate -H 'Content-Type: application/json' \
```bash
curl /health
```
+
+## Agent Sessions
+
+```bash
+# Create agent session (requires bearer/cookie auth)
+curl -X POST /api/agent-sessions -d '{"agentId":"my-agent","label":"dev"}'
+
+# List sessions
+curl /api/agent-sessions
+
+# Get current session (requires Session auth)
+curl -H "Authorization: Session pts_..." /api/agent-sessions/me
+
+# Rotate token
+curl -X POST /api/agent-sessions/{id}/rotate
+
+# Revoke session
+curl -X POST /api/agent-sessions/{id}/revoke
+```
diff --git a/skills/pinchtab/references/env.md b/skills/pinchtab/references/env.md
index 00e78a04..169910c5 100644
--- a/skills/pinchtab/references/env.md
+++ b/skills/pinchtab/references/env.md
@@ -33,4 +33,12 @@ For most agent tasks, the only variable you need is:
PINCHTAB_TOKEN=...
```
+Or use agent sessions for per-agent identity and revocability:
+
+```bash
+PINCHTAB_SESSION=pts_...
+```
+
+When `PINCHTAB_SESSION` is set, the CLI uses `Authorization: Session <token>` instead of bearer auth. The session maps to a specific agentId server-side and can be revoked independently.
+
Everything else should be handled through config, profiles, instances, and the `--server` flag.