High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: persist dashboard auth sessions and make elevation configurable
Luigi Agostiddaae40f909e
diff --git a/dashboard/src/pages/LoginPage.tsx b/dashboard/src/pages/LoginPage.tsxindex b939f1a6..5c7f68ad 100644--- a/dashboard/src/pages/LoginPage.tsx+++ b/dashboard/src/pages/LoginPage.tsx@@ -3,11 +3,7 @@ import type { ComponentProps } from "react";import { useLocation, useNavigate } from "react-router-dom";import { Button, Card } from "../components/atoms";import * as api from "../services/api";-import {- credentialUsername,- dispatchAuthStateChanged,- storeTokenCredential,-} from "../services/auth";+import { dispatchAuthStateChanged } from "../services/auth";export default function LoginPage() {const navigate = useNavigate();@@ -15,7 +11,6 @@ export default function LoginPage() {const [token, setToken] = useState("");const [error, setError] = useState("");const [submitting, setSubmitting] = useState(false);- const savedCredentialUsername = credentialUsername();const from =(location.state as { from?: string } | null)?.from ||@@ -29,7 +24,6 @@ export default function LoginPage() {setError("");try {await api.login(token);- await storeTokenCredential(token, event.currentTarget);dispatchAuthStateChanged();navigate(from, { replace: true });} catch (e) {@@ -56,26 +50,14 @@ export default function LoginPage() {<formid="login-form"className="space-y-4"- autoComplete="on"+ autoComplete="off"onSubmit={handleSubmit}>- <input- id="login-username"- type="text"- name="username"- autoComplete="username"- value={savedCredentialUsername}- readOnly- tabIndex={-1}- aria-hidden="true"- className="sr-only"- /><inputid="login-password"type="password"autoFocus- name="password"- autoComplete="current-password"+ autoComplete="off"value={token}onChange={(e) => setToken(e.target.value)}className="w-full rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"diff --git a/dashboard/src/pages/SettingsPage.tsx b/dashboard/src/pages/SettingsPage.tsxindex 217b2229..ebf9ff59 100644--- a/dashboard/src/pages/SettingsPage.tsx+++ b/dashboard/src/pages/SettingsPage.tsx@@ -1,7 +1,6 @@import type { Dispatch, FormEvent, SetStateAction } from "react";import { useEffect, useMemo, useState } from "react";import { Button, Card, Input, Modal } from "../components/atoms";-import { credentialUsername, storeTokenCredential } from "../services/auth";import * as api from "../services/api";import { useAppStore } from "../stores/useAppStore";import type {@@ -148,7 +147,6 @@ export default function SettingsPage() {const [elevationToken, setElevationToken] = useState("");const [elevationError, setElevationError] = useState("");const [elevating, setElevating] = useState(false);- const savedCredentialUsername = useMemo(() => credentialUsername(), []);useEffect(() => {setLocalSettings(settings);@@ -316,7 +314,6 @@ export default function SettingsPage() {try {await api.elevate(elevationToken);- await storeTokenCredential(elevationToken, event.currentTarget);setPendingElevatedAction(null);setElevationToken("");@@ -411,7 +408,7 @@ export default function SettingsPage() {<formid="settings-elevation-form"className="space-y-4"- autoComplete="on"+ autoComplete="off"onSubmit={handleElevationSubmit}><p className="leading-6 text-text-muted">@@ -419,22 +416,10 @@ export default function SettingsPage() {elevated session stays active briefly so you do not need to repeatthis for every admin action.</p>- <input- id="settings-elevation-username"- type="text"- name="username"- autoComplete="username"- value={savedCredentialUsername}- readOnly- tabIndex={-1}- aria-hidden="true"- className="sr-only"- /><Inputid="settings-elevation-password"type="password"- name="password"- autoComplete="current-password"+ autoComplete="off"label="API token"placeholder="Paste API token"value={elevationToken}diff --git a/dashboard/src/pages/settings/NetworkSettingsSection.tsx b/dashboard/src/pages/settings/NetworkSettingsSection.tsxindex 46b28b22..76eea6fe 100644--- a/dashboard/src/pages/settings/NetworkSettingsSection.tsx+++ b/dashboard/src/pages/settings/NetworkSettingsSection.tsx@@ -120,6 +120,90 @@ export function NetworkSettingsSection({{backendConfig.server.trustProxyHeaders ? "Enabled" : "Disabled"}</label></SettingRow>+ <SettingRow+ label="Persist dashboard sessions"+ description="Keep dashboard login sessions across server restarts. Disable this if you want every restart to force a fresh login."+ >+ <label className="flex items-center justify-end gap-3 text-sm text-text-secondary">+ <input+ type="checkbox"+ checked={backendConfig.sessions.dashboard.persist}+ onChange={(e) =>+ updateBackendSection("sessions", {+ dashboard: {+ ...backendConfig.sessions.dashboard,+ persist: e.target.checked,+ },+ })+ }+ className="accent-primary"+ />+ {backendConfig.sessions.dashboard.persist ? "Enabled" : "Disabled"}+ </label>+ </SettingRow>+ <SettingRow+ label="Session idle timeout"+ description="How long an unused dashboard session stays valid. This is stored in seconds in config."+ >+ <input+ type="number"+ min={60}+ step={60}+ value={backendConfig.sessions.dashboard.idleTimeoutSec}+ onChange={(e) =>+ updateBackendSection("sessions", {+ dashboard: {+ ...backendConfig.sessions.dashboard,+ idleTimeoutSec: Number(e.target.value),+ },+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Session max lifetime"+ description="Absolute lifetime for a dashboard session before it must be re-created, even if active."+ >+ <input+ type="number"+ min={60}+ step={60}+ value={backendConfig.sessions.dashboard.maxLifetimeSec}+ onChange={(e) =>+ updateBackendSection("sessions", {+ dashboard: {+ ...backendConfig.sessions.dashboard,+ maxLifetimeSec: Number(e.target.value),+ },+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Require elevation for config saves"+ description="Ask for API token re-entry before saving backend config changes. Disabled by default."+ >+ <label className="flex items-center justify-end gap-3 text-sm text-text-secondary">+ <input+ type="checkbox"+ checked={backendConfig.sessions.dashboard.requireElevation}+ onChange={(e) =>+ updateBackendSection("sessions", {+ dashboard: {+ ...backendConfig.sessions.dashboard,+ requireElevation: e.target.checked,+ },+ })+ }+ className="accent-primary"+ />+ {backendConfig.sessions.dashboard.requireElevation+ ? "Enabled"+ : "Disabled"}+ </label>+ </SettingRow><SettingRowlabel="Allow attach"description="Permit attaching PinchTab to externally managed Chrome sessions."diff --git a/dashboard/src/services/auth.test.ts b/dashboard/src/services/auth.test.tsindex f18777af..55a63222 100644--- a/dashboard/src/services/auth.test.ts+++ b/dashboard/src/services/auth.test.ts@@ -2,7 +2,6 @@ import { describe, expect, it, vi } from "vitest";import {AUTH_REQUIRED_EVENT,AUTH_STATE_CHANGED_EVENT,- credentialUsername,dispatchAuthRequired,dispatchAuthStateChanged,sameOriginUrl,@@ -38,12 +37,4 @@ describe("auth helpers", () => {vi.unstubAllGlobals();});-- it("builds a stable credential username for password managers", () => {- vi.stubGlobal("location", new URL("https://pinchtab.example/dashboard"));-- expect(credentialUsername()).toBe("[email protected]");-- vi.unstubAllGlobals();- });});diff --git a/dashboard/src/services/auth.ts b/dashboard/src/services/auth.tsindex d4c977c9..70141eb0 100644--- a/dashboard/src/services/auth.ts+++ b/dashboard/src/services/auth.ts@@ -1,6 +1,5 @@const AUTH_REQUIRED_EVENT = "pinchtab-auth-required";const AUTH_STATE_CHANGED_EVENT = "pinchtab-auth-state-changed";-const CREDENTIAL_USERNAME_PREFIX = "pinchtab";export function dispatchAuthRequired(reason: string): void {window.dispatchEvent(@@ -19,86 +18,4 @@ export function sameOriginUrl(url: string): string {return absolute.pathname + absolute.search;}-export function credentialUsername(): string {- if (typeof window === "undefined") {- return CREDENTIAL_USERNAME_PREFIX;- }- return `${CREDENTIAL_USERNAME_PREFIX}@${window.location.host}`;-}--type PasswordCredentialData = {- id: string;- password: string;- name?: string;-};--type PasswordCredentialConstructor = {- new (form: HTMLFormElement): Credential;- new (data: PasswordCredentialData): Credential;-};--function setCredentialFormValues(- form: HTMLFormElement,- token: string,-): PasswordCredentialData {- const id = credentialUsername();- const usernameField = form.elements.namedItem("username");- if (usernameField instanceof HTMLInputElement) {- usernameField.value = id;- }-- const passwordField = form.elements.namedItem("password");- if (passwordField instanceof HTMLInputElement) {- passwordField.value = token;- }-- return {- id,- password: token,- name: `PinchTab ${window.location.host}`,- };-}--export async function storeTokenCredential(- token: string,- form?: HTMLFormElement,-): Promise<void> {- const trimmed = token.trim();- if (- trimmed === "" ||- typeof window === "undefined" ||- navigator.credentials?.store === undefined- ) {- return;- }-- const PasswordCredentialImpl = (- window as Window & { PasswordCredential?: PasswordCredentialConstructor }- ).PasswordCredential;- if (!PasswordCredentialImpl) {- return;- }-- try {- let credential: Credential;- if (form) {- const fallback = setCredentialFormValues(form, trimmed);- try {- credential = new PasswordCredentialImpl(form);- } catch {- credential = new PasswordCredentialImpl(fallback);- }- } else {- credential = new PasswordCredentialImpl({- id: credentialUsername(),- password: trimmed,- name: `PinchTab ${window.location.host}`,- });- }- await navigator.credentials.store(credential);- } catch {- // Ignore password-manager failures and continue with the session flow.- }-}-export { AUTH_REQUIRED_EVENT, AUTH_STATE_CHANGED_EVENT };diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.tsindex f58445a5..4a9f44c9 100644--- a/dashboard/src/types/index.ts+++ b/dashboard/src/types/index.ts@@ -61,6 +61,19 @@ export interface BackendServerConfig {trustProxyHeaders: boolean;}+export interface BackendDashboardSessionConfig {+ persist: boolean;+ idleTimeoutSec: number;+ maxLifetimeSec: number;+ elevationWindowSec: number;+ persistElevationAcrossRestart: boolean;+ requireElevation: boolean;+}++export interface BackendSessionsConfig {+ dashboard: BackendDashboardSessionConfig;+}+export interface BackendBrowserConfig {version: string;binary: string;@@ -156,6 +169,7 @@ export interface BackendConfig {profiles: BackendProfilesConfig;multiInstance: BackendMultiInstanceConfig;timeouts: BackendTimeoutsConfig;+ sessions: BackendSessionsConfig;autoSolver: BackendAutoSolverConfig;}@@ -237,6 +251,16 @@ export const defaultBackendConfig: BackendConfig = {shutdownSec: 10,waitNavMs: 1000,},+ sessions: {+ dashboard: {+ persist: true,+ idleTimeoutSec: 7 * 24 * 60 * 60,+ maxLifetimeSec: 7 * 24 * 60 * 60,+ elevationWindowSec: 15 * 60,+ persistElevationAcrossRestart: false,+ requireElevation: false,+ },+ },autoSolver: {enabled: false,maxAttempts: 8,@@ -301,6 +325,14 @@ export function normalizeBackendConfig(...defaultBackendConfig.timeouts,...(input?.timeouts ?? {}),},+ sessions: {+ ...defaultBackendConfig.sessions,+ ...(input?.sessions ?? {}),+ dashboard: {+ ...defaultBackendConfig.sessions.dashboard,+ ...(input?.sessions?.dashboard ?? {}),+ },+ },autoSolver: {...defaultBackendConfig.autoSolver,...(input?.autoSolver ?? {}),diff --git a/internal/authn/session.go b/internal/authn/session.goindex 96d3027b..e577c9bb 100644--- a/internal/authn/session.go+++ b/internal/authn/session.go@@ -4,30 +4,39 @@ import ("crypto/rand""crypto/sha256""encoding/hex"+ "encoding/json"+ "os"+ "path/filepath""strings""sync""time")const (- DefaultSessionIdleTimeout = 12 * time.Hour+ DefaultSessionIdleTimeout = 7 * 24 * time.HourDefaultSessionMaxLifetime = 7 * 24 * time.HourDefaultSessionElevationWindow = 15 * time.Minute)type SessionConfig struct {- IdleTimeout time.Duration- MaxLifetime time.Duration- ElevationWindow time.Duration+ IdleTimeout time.Duration+ MaxLifetime time.Duration+ ElevationWindow time.Duration+ Persist bool+ PersistPath string+ PersistElevationAcrossRestart bool}type SessionManager struct {- mu sync.Mutex- sessions map[string]sessionState- idleTimeout time.Duration- maxLifetime time.Duration- elevationWindow time.Duration- now func() time.Time+ mu sync.Mutex+ sessions map[string]sessionState+ idleTimeout time.Duration+ maxLifetime time.Duration+ elevationWindow time.Duration+ persist bool+ persistPath string+ persistElevationAcrossRestart bool+ now func() time.Time}type sessionState struct {@@ -37,26 +46,29 @@ type sessionState struct {TokenHash [32]byte}+type persistedSessions struct {+ SavedAt time.Time `json:"savedAt"`+ Sessions []persistedSessionRecord `json:"sessions"`+}++type persistedSessionRecord struct {+ ID string `json:"id"`+ CreatedAt time.Time `json:"createdAt"`+ LastSeen time.Time `json:"lastSeen"`+ ElevatedUntil time.Time `json:"elevatedUntil,omitempty"`+ TokenHash string `json:"tokenHash"`+}+func NewSessionManager(cfg SessionConfig) *SessionManager {- idle := cfg.IdleTimeout- if idle <= 0 {- idle = DefaultSessionIdleTimeout- }- maxLifetime := cfg.MaxLifetime- if maxLifetime <= 0 {- maxLifetime = DefaultSessionMaxLifetime- }- elevationWindow := cfg.ElevationWindow- if elevationWindow <= 0 {- elevationWindow = DefaultSessionElevationWindow- }- return &SessionManager{- sessions: make(map[string]sessionState),- idleTimeout: idle,- maxLifetime: maxLifetime,- elevationWindow: elevationWindow,- now: time.Now,+ m := &SessionManager{+ sessions: make(map[string]sessionState),+ now: time.Now,}+ m.mu.Lock()+ m.applyConfigLocked(cfg)+ m.mu.Unlock()+ m.loadPersisted()+ return m}func (m *SessionManager) Create(token string) (string, error) {@@ -74,6 +86,7 @@ func (m *SessionManager) Create(token string) (string, error) {LastSeen: now,TokenHash: hashToken(token),}+ m.saveLocked()m.mu.Unlock()return id, nil}@@ -99,10 +112,12 @@ func (m *SessionManager) Validate(sessionID, token string) bool {}if !m.sessionValid(state, now, expected) {delete(m.sessions, sessionID)+ m.saveLocked()return false}state.LastSeen = nowm.sessions[sessionID] = state+ m.saveLocked()return true}@@ -127,11 +142,13 @@ func (m *SessionManager) Elevate(sessionID, token string) bool {}if !m.sessionValid(state, now, expected) {delete(m.sessions, sessionID)+ m.saveLocked()return false}state.LastSeen = nowstate.ElevatedUntil = now.Add(m.elevationWindow)m.sessions[sessionID] = state+ m.saveLocked()return true}@@ -171,6 +188,7 @@ func (m *SessionManager) Revoke(sessionID string) {}m.mu.Lock()delete(m.sessions, sessionID)+ m.saveLocked()m.mu.Unlock()}@@ -181,6 +199,13 @@ func (m *SessionManager) MaxLifetime() time.Duration {return m.maxLifetime}+func (m *SessionManager) IdleTimeout() time.Duration {+ if m == nil {+ return DefaultSessionIdleTimeout+ }+ return m.idleTimeout+}+func (m *SessionManager) ElevationWindow() time.Duration {if m == nil {return DefaultSessionElevationWindow@@ -188,10 +213,166 @@ func (m *SessionManager) ElevationWindow() time.Duration {return m.elevationWindow}+func (m *SessionManager) UpdateConfig(cfg SessionConfig) {+ if m == nil {+ return+ }++ idle := cfg.IdleTimeout+ if idle <= 0 {+ idle = DefaultSessionIdleTimeout+ }+ maxLifetime := cfg.MaxLifetime+ if maxLifetime <= 0 {+ maxLifetime = DefaultSessionMaxLifetime+ }+ elevationWindow := cfg.ElevationWindow+ if elevationWindow <= 0 {+ elevationWindow = DefaultSessionElevationWindow+ }+ persistPath := strings.TrimSpace(cfg.PersistPath)+ persist := cfg.Persist && persistPath != ""++ m.mu.Lock()+ oldPath := m.persistPath+ oldPersist := m.persist+ m.applyConfigLocked(cfg)+ m.pruneExpiredLocked(m.now())+ m.saveLocked()+ m.mu.Unlock()++ if oldPersist && oldPath != "" && (!persist || oldPath != persistPath) {+ _ = os.Remove(oldPath)+ }+}++func (m *SessionManager) applyConfigLocked(cfg SessionConfig) {+ idle := cfg.IdleTimeout+ if idle <= 0 {+ idle = DefaultSessionIdleTimeout+ }+ maxLifetime := cfg.MaxLifetime+ if maxLifetime <= 0 {+ maxLifetime = DefaultSessionMaxLifetime+ }+ elevationWindow := cfg.ElevationWindow+ if elevationWindow <= 0 {+ elevationWindow = DefaultSessionElevationWindow+ }+ persistPath := strings.TrimSpace(cfg.PersistPath)+ persist := cfg.Persist && persistPath != ""++ m.idleTimeout = idle+ m.maxLifetime = maxLifetime+ m.elevationWindow = elevationWindow+ m.persist = persist+ m.persistPath = persistPath+ m.persistElevationAcrossRestart = cfg.PersistElevationAcrossRestart+}+func (m *SessionManager) 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 {return now.Sub(state.LastSeen) <= m.idleTimeout &&- now.Sub(state.CreatedAt) <= m.maxLifetime &&- state.TokenHash == expected+ now.Sub(state.CreatedAt) <= m.maxLifetime+}++func (m *SessionManager) pruneExpiredLocked(now time.Time) {+ for id, state := range m.sessions {+ if !m.sessionTimeValid(state, now) {+ delete(m.sessions, id)+ }+ }+}++func (m *SessionManager) loadPersisted() {+ if m == nil {+ return+ }++ m.mu.Lock()+ defer m.mu.Unlock()++ if !m.persist || m.persistPath == "" {+ return+ }++ data, err := os.ReadFile(m.persistPath)+ if err != nil {+ return+ }+ var persisted persistedSessions+ if err := json.Unmarshal(data, &persisted); err != nil {+ return+ }++ now := m.now()+ loaded := make(map[string]sessionState, len(persisted.Sessions))+ for _, record := range persisted.Sessions {+ tokenHash, err := hex.DecodeString(strings.TrimSpace(record.TokenHash))+ if err != nil || len(tokenHash) != sha256.Size {+ continue+ }+ var hash [32]byte+ copy(hash[:], tokenHash)++ state := sessionState{+ CreatedAt: record.CreatedAt,+ LastSeen: record.LastSeen,+ ElevatedUntil: record.ElevatedUntil,+ TokenHash: hash,+ }+ if !m.persistElevationAcrossRestart {+ state.ElevatedUntil = time.Time{}+ }+ if !m.sessionTimeValid(state, now) {+ continue+ }+ recordID := strings.TrimSpace(record.ID)+ if recordID == "" {+ continue+ }+ loaded[recordID] = state+ }+ m.sessions = loaded+ m.saveLocked()+}++func (m *SessionManager) saveLocked() {+ if !m.persist || m.persistPath == "" {+ return+ }++ snapshot := persistedSessions{+ SavedAt: m.now().UTC(),+ Sessions: make([]persistedSessionRecord, 0, len(m.sessions)),+ }+ for id, state := range m.sessions {+ record := persistedSessionRecord{+ ID: id,+ CreatedAt: state.CreatedAt,+ LastSeen: state.LastSeen,+ ElevatedUntil: state.ElevatedUntil,+ TokenHash: hex.EncodeToString(state.TokenHash[:]),+ }+ if !m.persistElevationAcrossRestart {+ record.ElevatedUntil = time.Time{}+ }+ snapshot.Sessions = append(snapshot.Sessions, record)+ }++ data, err := json.MarshalIndent(snapshot, "", " ")+ if err != nil {+ return+ }+ if err := os.MkdirAll(filepath.Dir(m.persistPath), 0755); err != nil {+ return+ }+ if err := os.WriteFile(m.persistPath, data, 0644); err != nil {+ return+ }}func randomSessionID() (string, error) {diff --git a/internal/authn/session_test.go b/internal/authn/session_test.goindex fd64331d..955579ef 100644--- a/internal/authn/session_test.go+++ b/internal/authn/session_test.go@@ -1,6 +1,7 @@package authnimport (+ "path/filepath""testing""time")@@ -72,3 +73,71 @@ func TestSessionManagerElevationWindow(t *testing.T) {t.Fatal("IsElevated() after elevation expiry = true, want false")}}++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{+ IdleTimeout: 365 * 24 * time.Hour,+ MaxLifetime: 365 * 24 * time.Hour,+ Persist: true,+ PersistPath: path,+ })+ mgr.now = func() time.Time { return now }++ sessionID, err := mgr.Create("secret")+ if err != nil {+ t.Fatalf("Create() error = %v", err)+ }+ if !mgr.Validate(sessionID, "secret") {+ t.Fatal("Validate() before restart = false, want true")+ }++ restarted := NewSessionManager(SessionConfig{+ IdleTimeout: 365 * 24 * time.Hour,+ MaxLifetime: 365 * 24 * time.Hour,+ Persist: true,+ PersistPath: path,+ })+ restarted.now = func() time.Time { return now }++ if !restarted.Validate(sessionID, "secret") {+ t.Fatal("Validate() after restart = false, want true")+ }+}++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{+ IdleTimeout: 365 * 24 * time.Hour,+ MaxLifetime: 365 * 24 * time.Hour,+ ElevationWindow: 15 * time.Minute,+ Persist: true,+ PersistPath: path,+ })+ mgr.now = func() time.Time { return now }++ sessionID, err := mgr.Create("secret")+ if err != nil {+ t.Fatalf("Create() error = %v", err)+ }+ if !mgr.Elevate(sessionID, "secret") {+ t.Fatal("Elevate() = false, want true")+ }++ restarted := NewSessionManager(SessionConfig{+ IdleTimeout: 365 * 24 * time.Hour,+ MaxLifetime: 365 * 24 * time.Hour,+ ElevationWindow: 15 * time.Minute,+ Persist: true,+ PersistPath: path,+ })+ restarted.now = func() time.Time { return now }++ if restarted.IsElevated(sessionID, "secret") {+ t.Fatal("IsElevated() after restart = true, want false when persistence across restart is disabled")+ }+}diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex 6ad12a95..f9c2f895 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -35,6 +35,12 @@ func DefaultFileConfig() FileConfig {activityEnabled := trueactivitySessionIdleSec := 1800activityRetentionDays := 1+ dashboardSessionPersist := true+ dashboardSessionIdleSec := 7 * 24 * 60 * 60+ dashboardSessionMaxLifetimeSec := 7 * 24 * 60 * 60+ dashboardSessionElevationWindowSec := 15 * 60+ dashboardSessionPersistElevationAcrossRestart := false+ dashboardSessionRequireElevation := falsereturn FileConfig{ConfigVersion: CurrentConfigVersion,Server: ServerConfig{@@ -108,6 +114,16 @@ func DefaultFileConfig() FileConfig {RetentionDays: &activityRetentionDays,},},+ Sessions: SessionsFileConfig{+ Dashboard: DashboardSessionFileConfig{+ Persist: &dashboardSessionPersist,+ IdleTimeoutSec: &dashboardSessionIdleSec,+ MaxLifetimeSec: &dashboardSessionMaxLifetimeSec,+ ElevationWindowSec: &dashboardSessionElevationWindowSec,+ PersistElevationAcrossRestart: &dashboardSessionPersistElevationAcrossRestart,+ RequireElevation: &dashboardSessionRequireElevation,+ },+ },}}@@ -122,6 +138,7 @@ type fileConfigJSON struct {Timeouts timeoutsConfigJSON `json:"timeouts"`Scheduler schedulerFileConfigJSON `json:"scheduler"`Observability observabilityFileConfigJSON `json:"observability"`+ Sessions sessionsFileConfigJSON `json:"sessions"`AutoSolver autoSolverFileConfigJSON `json:"autoSolver,omitempty"`}@@ -243,6 +260,19 @@ type activityConfigJSON struct {RetentionDays *int `json:"retentionDays"`}+type sessionsFileConfigJSON struct {+ Dashboard dashboardSessionConfigJSON `json:"dashboard"`+}++type dashboardSessionConfigJSON struct {+ Persist *bool `json:"persist,omitempty"`+ IdleTimeoutSec *int `json:"idleTimeoutSec,omitempty"`+ MaxLifetimeSec *int `json:"maxLifetimeSec,omitempty"`+ ElevationWindowSec *int `json:"elevationWindowSec,omitempty"`+ PersistElevationAcrossRestart *bool `json:"persistElevationAcrossRestart,omitempty"`+ RequireElevation *bool `json:"requireElevation,omitempty"`+}+type autoSolverFileConfigJSON struct {Enabled *bool `json:"enabled,omitempty"`MaxAttempts *int `json:"maxAttempts,omitempty"`@@ -371,6 +401,16 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {RetentionDays: fc.Observability.Activity.RetentionDays,},},+ Sessions: sessionsFileConfigJSON{+ Dashboard: dashboardSessionConfigJSON{+ Persist: fc.Sessions.Dashboard.Persist,+ IdleTimeoutSec: fc.Sessions.Dashboard.IdleTimeoutSec,+ MaxLifetimeSec: fc.Sessions.Dashboard.MaxLifetimeSec,+ ElevationWindowSec: fc.Sessions.Dashboard.ElevationWindowSec,+ PersistElevationAcrossRestart: fc.Sessions.Dashboard.PersistElevationAcrossRestart,+ RequireElevation: fc.Sessions.Dashboard.RequireElevation,+ },+ },AutoSolver: autoSolverFileConfigJSON{Enabled: fc.AutoSolver.Enabled,MaxAttempts: fc.AutoSolver.MaxAttempts,@@ -422,6 +462,12 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {activityEnabled := cfg.Observability.Activity.EnabledactivitySessionIdleSec := cfg.Observability.Activity.SessionIdleSecactivityRetentionDays := cfg.Observability.Activity.RetentionDays+ dashboardSessionPersist := cfg.Sessions.Dashboard.Persist+ dashboardSessionIdleSec := int(cfg.Sessions.Dashboard.IdleTimeout / time.Second)+ dashboardSessionMaxLifetimeSec := int(cfg.Sessions.Dashboard.MaxLifetime / time.Second)+ dashboardSessionElevationWindowSec := int(cfg.Sessions.Dashboard.ElevationWindow / time.Second)+ dashboardSessionPersistElevationAcrossRestart := cfg.Sessions.Dashboard.PersistElevationAcrossRestart+ dashboardSessionRequireElevation := cfg.Sessions.Dashboard.RequireElevationmode := "headless"if !cfg.Headless {@@ -517,6 +563,16 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {RetentionDays: &activityRetentionDays,},},+ Sessions: SessionsFileConfig{+ Dashboard: DashboardSessionFileConfig{+ Persist: &dashboardSessionPersist,+ IdleTimeoutSec: &dashboardSessionIdleSec,+ MaxLifetimeSec: &dashboardSessionMaxLifetimeSec,+ ElevationWindowSec: &dashboardSessionElevationWindowSec,+ PersistElevationAcrossRestart: &dashboardSessionPersistElevationAcrossRestart,+ RequireElevation: &dashboardSessionRequireElevation,+ },+ },}return fc@@ -607,7 +663,7 @@ func isLegacyConfig(data []byte) bool {}// If any new nested keys exist, it's new format- newKeys := []string{"server", "browser", "instanceDefaults", "profiles", "multiInstance", "security", "attach", "timeouts"}+ newKeys := []string{"server", "browser", "instanceDefaults", "profiles", "multiInstance", "security", "attach", "timeouts", "sessions"}for _, key := range newKeys {if _, has := probe[key]; has {return falsediff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.goindex b7a68ce9..98fd53af 100644--- a/internal/config/config_file_test.go+++ b/internal/config/config_file_test.go@@ -76,6 +76,18 @@ func TestDefaultFileConfig(t *testing.T) {if !fc.Security.IDPI.WrapContent {t.Errorf("DefaultFileConfig.Security.IDPI.WrapContent = %v, want true", fc.Security.IDPI.WrapContent)}+ if fc.Sessions.Dashboard.Persist == nil || !*fc.Sessions.Dashboard.Persist {+ t.Errorf("DefaultFileConfig.Sessions.Dashboard.Persist = %v, want explicit true", formatBoolPtr(fc.Sessions.Dashboard.Persist))+ }+ if fc.Sessions.Dashboard.IdleTimeoutSec == nil || *fc.Sessions.Dashboard.IdleTimeoutSec != 7*24*60*60 {+ t.Errorf("DefaultFileConfig.Sessions.Dashboard.IdleTimeoutSec = %v, want %d", formatIntPtr(fc.Sessions.Dashboard.IdleTimeoutSec), 7*24*60*60)+ }+ if fc.Sessions.Dashboard.MaxLifetimeSec == nil || *fc.Sessions.Dashboard.MaxLifetimeSec != 7*24*60*60 {+ t.Errorf("DefaultFileConfig.Sessions.Dashboard.MaxLifetimeSec = %v, want %d", formatIntPtr(fc.Sessions.Dashboard.MaxLifetimeSec), 7*24*60*60)+ }+ if fc.Sessions.Dashboard.RequireElevation == nil || *fc.Sessions.Dashboard.RequireElevation {+ t.Errorf("DefaultFileConfig.Sessions.Dashboard.RequireElevation = %v, want explicit false", formatBoolPtr(fc.Sessions.Dashboard.RequireElevation))+ }}// TestIsLegacyConfig tests the format detection logic.diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 254f7daf..eac493d8 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -96,6 +96,18 @@ func Load() *RuntimeConfig {},},+ // Dashboard session defaults+ Sessions: SessionsRuntimeConfig{+ Dashboard: DashboardSessionRuntimeConfig{+ Persist: true,+ IdleTimeout: 7 * 24 * time.Hour,+ MaxLifetime: 7 * 24 * time.Hour,+ ElevationWindow: 15 * time.Minute,+ PersistElevationAcrossRestart: false,+ RequireElevation: false,+ },+ },+// AutoSolver defaults (disabled by default)AutoSolver: AutoSolverConfig{Enabled: false,@@ -249,6 +261,24 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {if fc.Observability.Activity.RetentionDays != nil {cfg.Observability.Activity.RetentionDays = *fc.Observability.Activity.RetentionDays}+ if fc.Sessions.Dashboard.Persist != nil {+ cfg.Sessions.Dashboard.Persist = *fc.Sessions.Dashboard.Persist+ }+ if fc.Sessions.Dashboard.IdleTimeoutSec != nil && *fc.Sessions.Dashboard.IdleTimeoutSec > 0 {+ cfg.Sessions.Dashboard.IdleTimeout = time.Duration(*fc.Sessions.Dashboard.IdleTimeoutSec) * time.Second+ }+ if fc.Sessions.Dashboard.MaxLifetimeSec != nil && *fc.Sessions.Dashboard.MaxLifetimeSec > 0 {+ cfg.Sessions.Dashboard.MaxLifetime = time.Duration(*fc.Sessions.Dashboard.MaxLifetimeSec) * time.Second+ }+ if fc.Sessions.Dashboard.ElevationWindowSec != nil && *fc.Sessions.Dashboard.ElevationWindowSec > 0 {+ cfg.Sessions.Dashboard.ElevationWindow = time.Duration(*fc.Sessions.Dashboard.ElevationWindowSec) * time.Second+ }+ if fc.Sessions.Dashboard.PersistElevationAcrossRestart != nil {+ cfg.Sessions.Dashboard.PersistElevationAcrossRestart = *fc.Sessions.Dashboard.PersistElevationAcrossRestart+ }+ if fc.Sessions.Dashboard.RequireElevation != nil {+ cfg.Sessions.Dashboard.RequireElevation = *fc.Sessions.Dashboard.RequireElevation+ }// Browserif fc.Browser.ChromeVersion != "" {diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex fa0b7ff4..23e6ea3b 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -4,6 +4,7 @@ import ("os""path/filepath""testing"+ "time")func TestEnvOr(t *testing.T) {@@ -99,6 +100,18 @@ func TestLoadConfigDefaults(t *testing.T) {if cfg.Observability.Activity.RetentionDays != 1 {t.Errorf("default Observability.Activity.RetentionDays = %d, want 1", cfg.Observability.Activity.RetentionDays)}+ if !cfg.Sessions.Dashboard.Persist {+ t.Errorf("default Sessions.Dashboard.Persist = %v, want true", cfg.Sessions.Dashboard.Persist)+ }+ if cfg.Sessions.Dashboard.IdleTimeout != 7*24*time.Hour {+ t.Errorf("default Sessions.Dashboard.IdleTimeout = %v, want %v", cfg.Sessions.Dashboard.IdleTimeout, 7*24*time.Hour)+ }+ if cfg.Sessions.Dashboard.MaxLifetime != 7*24*time.Hour {+ t.Errorf("default Sessions.Dashboard.MaxLifetime = %v, want %v", cfg.Sessions.Dashboard.MaxLifetime, 7*24*time.Hour)+ }+ if cfg.Sessions.Dashboard.RequireElevation {+ t.Errorf("default Sessions.Dashboard.RequireElevation = %v, want false", cfg.Sessions.Dashboard.RequireElevation)+ }}func TestLoadConfigTokenEnvOverride(t *testing.T) {diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex 15e87529..c0c19d81 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -90,10 +90,26 @@ type RuntimeConfig struct {// Observability settingsObservability ObservabilityConfig+ // Session settings+ Sessions SessionsRuntimeConfig+// AutoSolver settingsAutoSolver AutoSolverConfig}+type SessionsRuntimeConfig struct {+ Dashboard DashboardSessionRuntimeConfig `json:"dashboard,omitempty"`+}++type DashboardSessionRuntimeConfig struct {+ Persist bool `json:"persist,omitempty"`+ IdleTimeout time.Duration `json:"idleTimeout,omitempty"`+ MaxLifetime time.Duration `json:"maxLifetime,omitempty"`+ ElevationWindow time.Duration `json:"elevationWindow,omitempty"`+ PersistElevationAcrossRestart bool `json:"persistElevationAcrossRestart,omitempty"`+ RequireElevation bool `json:"requireElevation,omitempty"`+}+// IDPIConfig holds the configuration for the Indirect Prompt Injection (IDPI)// defense layer.type IDPIConfig struct {@@ -155,6 +171,7 @@ type FileConfig struct {Timeouts TimeoutsConfig `json:"timeouts,omitempty"`Scheduler SchedulerFileConfig `json:"scheduler,omitempty"`Observability ObservabilityFileConfig `json:"observability,omitempty"`+ Sessions SessionsFileConfig `json:"sessions,omitempty"`AutoSolver AutoSolverFileConfig `json:"autoSolver,omitempty"`}@@ -169,6 +186,19 @@ type ServerConfig struct {CookieSecure *bool `json:"cookieSecure,omitempty"`}+type SessionsFileConfig struct {+ Dashboard DashboardSessionFileConfig `json:"dashboard,omitempty"`+}++type DashboardSessionFileConfig struct {+ Persist *bool `json:"persist,omitempty"`+ IdleTimeoutSec *int `json:"idleTimeoutSec,omitempty"`+ MaxLifetimeSec *int `json:"maxLifetimeSec,omitempty"`+ ElevationWindowSec *int `json:"elevationWindowSec,omitempty"`+ PersistElevationAcrossRestart *bool `json:"persistElevationAcrossRestart,omitempty"`+ RequireElevation *bool `json:"requireElevation,omitempty"`+}+type BrowserConfig struct {ChromeVersion string `json:"version,omitempty"`ChromeBinary string `json:"binary,omitempty"`diff --git a/internal/config/editor_get.go b/internal/config/editor_get.goindex f4f50635..7be65443 100644--- a/internal/config/editor_get.go+++ b/internal/config/editor_get.go@@ -31,8 +31,10 @@ func GetConfigValue(fc *FileConfig, path string) (string, error) {return getMultiInstanceField(&fc.MultiInstance, field)case "timeouts":return getTimeoutsField(&fc.Timeouts, field)+ case "sessions":+ return getSessionsField(&fc.Sessions, field)default:- return "", fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts)", section)+ return "", fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts, sessions)", section)}}@@ -68,6 +70,32 @@ func getBrowserField(b *BrowserConfig, field string) (string, error) {}}+func getSessionsField(s *SessionsFileConfig, field string) (string, error) {+ if strings.HasPrefix(field, "dashboard.") {+ return getDashboardSessionField(&s.Dashboard, strings.TrimPrefix(field, "dashboard."))+ }+ return "", fmt.Errorf("unknown field sessions.%s", field)+}++func getDashboardSessionField(s *DashboardSessionFileConfig, field string) (string, error) {+ switch field {+ case "persist":+ return formatBoolPtr(s.Persist), nil+ case "idleTimeoutSec":+ return formatIntPtr(s.IdleTimeoutSec), nil+ case "maxLifetimeSec":+ return formatIntPtr(s.MaxLifetimeSec), nil+ case "elevationWindowSec":+ return formatIntPtr(s.ElevationWindowSec), nil+ case "persistElevationAcrossRestart":+ return formatBoolPtr(s.PersistElevationAcrossRestart), nil+ case "requireElevation":+ return formatBoolPtr(s.RequireElevation), nil+ default:+ return "", fmt.Errorf("unknown field sessions.dashboard.%s", field)+ }+}+func getInstanceDefaultsField(c *InstanceDefaultsConfig, field string) (string, error) {switch field {case "mode":diff --git a/internal/config/editor_get_test.go b/internal/config/editor_get_test.goindex 1590ec19..11f9fea6 100644--- a/internal/config/editor_get_test.go+++ b/internal/config/editor_get_test.go@@ -15,6 +15,8 @@ func TestGetConfigValue_RoundTrip(t *testing.T) {{"server.token", "s3cr3t", "s3cr3t"},{"server.stateDir", "/tmp/state", "/tmp/state"},{"server.cookieSecure", "false", "false"},+ {"sessions.dashboard.persist", "true", "true"},+ {"sessions.dashboard.maxLifetimeSec", "604800", "604800"},{"browser.version", "120.0", "120.0"},{"browser.binary", "/usr/bin/chrome", "/usr/bin/chrome"},{"instanceDefaults.mode", "headed", "headed"},@@ -103,6 +105,8 @@ func TestGetConfigValue_NilPointerReturnsEmpty(t *testing.T) {"multiInstance.instancePortEnd","security.attach.enabled","server.cookieSecure",+ "sessions.dashboard.persist",+ "sessions.dashboard.maxLifetimeSec",}for _, path := range ptrs {t.Run(path, func(t *testing.T) {diff --git a/internal/config/editor_set.go b/internal/config/editor_set.goindex 023d35bf..831dce13 100644--- a/internal/config/editor_set.go+++ b/internal/config/editor_set.go@@ -30,8 +30,10 @@ func SetConfigValue(fc *FileConfig, path string, value string) error {return setMultiInstanceField(&fc.MultiInstance, field, value)case "timeouts":return setTimeoutsField(&fc.Timeouts, field, value)+ case "sessions":+ return setSessionsField(&fc.Sessions, field, value)default:- return fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts)", section)+ return fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts, sessions)", section)}}@@ -83,6 +85,57 @@ func setBrowserField(b *BrowserConfig, field, value string) error {return nil}+func setSessionsField(s *SessionsFileConfig, field, value string) error {+ if strings.HasPrefix(field, "dashboard.") {+ return setDashboardSessionField(&s.Dashboard, strings.TrimPrefix(field, "dashboard."), value)+ }+ return fmt.Errorf("unknown field sessions.%s", field)+}++func setDashboardSessionField(s *DashboardSessionFileConfig, field, value string) error {+ switch field {+ case "persist":+ b, err := parseBool(value)+ if err != nil {+ return fmt.Errorf("sessions.dashboard.persist: %w", err)+ }+ s.Persist = &b+ case "idleTimeoutSec":+ n, err := strconv.Atoi(value)+ if err != nil {+ return fmt.Errorf("sessions.dashboard.idleTimeoutSec must be a number: %w", err)+ }+ s.IdleTimeoutSec = &n+ case "maxLifetimeSec":+ n, err := strconv.Atoi(value)+ if err != nil {+ return fmt.Errorf("sessions.dashboard.maxLifetimeSec must be a number: %w", err)+ }+ s.MaxLifetimeSec = &n+ case "elevationWindowSec":+ n, err := strconv.Atoi(value)+ if err != nil {+ return fmt.Errorf("sessions.dashboard.elevationWindowSec must be a number: %w", err)+ }+ s.ElevationWindowSec = &n+ case "persistElevationAcrossRestart":+ b, err := parseBool(value)+ if err != nil {+ return fmt.Errorf("sessions.dashboard.persistElevationAcrossRestart: %w", err)+ }+ s.PersistElevationAcrossRestart = &b+ case "requireElevation":+ b, err := parseBool(value)+ if err != nil {+ return fmt.Errorf("sessions.dashboard.requireElevation: %w", err)+ }+ s.RequireElevation = &b+ default:+ return fmt.Errorf("unknown field sessions.dashboard.%s", field)+ }+ return nil+}+func setInstanceDefaultsField(c *InstanceDefaultsConfig, field, value string) error {switch field {case "mode":diff --git a/internal/config/editor_set_test.go b/internal/config/editor_set_test.goindex a051eb37..fcad8830 100644--- a/internal/config/editor_set_test.go+++ b/internal/config/editor_set_test.go@@ -14,6 +14,12 @@ func TestSetConfigValue_ServerFields(t *testing.T) {{"server.token", "secret", func(fc *FileConfig) bool { return fc.Server.Token == "secret" }, false},{"server.stateDir", "/tmp/state", func(fc *FileConfig) bool { return fc.Server.StateDir == "/tmp/state" }, false},{"server.cookieSecure", "false", func(fc *FileConfig) bool { return fc.Server.CookieSecure != nil && *fc.Server.CookieSecure == false }, false},+ {"sessions.dashboard.persist", "true", func(fc *FileConfig) bool {+ return fc.Sessions.Dashboard.Persist != nil && *fc.Sessions.Dashboard.Persist+ }, false},+ {"sessions.dashboard.maxLifetimeSec", "604800", func(fc *FileConfig) bool {+ return fc.Sessions.Dashboard.MaxLifetimeSec != nil && *fc.Sessions.Dashboard.MaxLifetimeSec == 604800+ }, false},{"server.unknown", "value", nil, true},}diff --git a/internal/config/validate.go b/internal/config/validate.goindex ac04c95d..569b805b 100644--- a/internal/config/validate.go+++ b/internal/config/validate.go@@ -203,6 +203,31 @@ func ValidateFileConfig(fc *FileConfig) []error {Message: fmt.Sprintf("must be > 0 (got %d)", *fc.Observability.Activity.RetentionDays),})}+ if fc.Sessions.Dashboard.IdleTimeoutSec != nil && *fc.Sessions.Dashboard.IdleTimeoutSec <= 0 {+ errs = append(errs, ValidationError{+ Field: "sessions.dashboard.idleTimeoutSec",+ Message: fmt.Sprintf("must be > 0 (got %d)", *fc.Sessions.Dashboard.IdleTimeoutSec),+ })+ }+ if fc.Sessions.Dashboard.MaxLifetimeSec != nil && *fc.Sessions.Dashboard.MaxLifetimeSec <= 0 {+ errs = append(errs, ValidationError{+ Field: "sessions.dashboard.maxLifetimeSec",+ Message: fmt.Sprintf("must be > 0 (got %d)", *fc.Sessions.Dashboard.MaxLifetimeSec),+ })+ }+ if fc.Sessions.Dashboard.ElevationWindowSec != nil && *fc.Sessions.Dashboard.ElevationWindowSec <= 0 {+ errs = append(errs, ValidationError{+ Field: "sessions.dashboard.elevationWindowSec",+ Message: fmt.Sprintf("must be > 0 (got %d)", *fc.Sessions.Dashboard.ElevationWindowSec),+ })+ }+ if fc.Sessions.Dashboard.IdleTimeoutSec != nil && fc.Sessions.Dashboard.MaxLifetimeSec != nil &&+ *fc.Sessions.Dashboard.IdleTimeoutSec > *fc.Sessions.Dashboard.MaxLifetimeSec {+ errs = append(errs, ValidationError{+ Field: "sessions.dashboard.idleTimeoutSec/maxLifetimeSec",+ Message: fmt.Sprintf("idle timeout (%d) must be <= max lifetime (%d)", *fc.Sessions.Dashboard.IdleTimeoutSec, *fc.Sessions.Dashboard.MaxLifetimeSec),+ })+ }return errs}diff --git a/internal/dashboard/auth_api.go b/internal/dashboard/auth_api.goindex b66ea78e..19faaeba 100644--- a/internal/dashboard/auth_api.go+++ b/internal/dashboard/auth_api.go@@ -109,7 +109,7 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {}authn.SetSessionCookie(w, r, sessionID, a.sessions.MaxLifetime(), a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))authn.AuditLog(r, "auth.session_created",- "sessionIdleSec", int(authn.DefaultSessionIdleTimeout.Seconds()),+ "sessionIdleSec", int(a.sessions.IdleTimeout().Seconds()),"sessionMaxLifetimeSec", int(a.sessions.MaxLifetime().Seconds()),)httpx.JSON(w, http.StatusOK, map[string]string{"status": "ok"})diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.goindex 0fb9dc17..bd0687b9 100644--- a/internal/dashboard/config_api.go+++ b/internal/dashboard/config_api.go@@ -33,6 +33,7 @@ type ConfigAPI struct {profiles profileListerapplier runtimeConfigApplieragents agentCounter+ sessions *authn.SessionManagerversion stringstartedAt time.Timeboot config.FileConfig@@ -93,6 +94,13 @@ func NewConfigAPI(}}+func (c *ConfigAPI) SetSessionManager(sessions *authn.SessionManager) {+ if c == nil {+ return+ }+ c.sessions = sessions+}+func (c *ConfigAPI) RegisterHandlers(mux *http.ServeMux) {mux.HandleFunc("GET /api/config", c.HandleGetConfig)mux.HandleFunc("PUT /api/config", c.HandlePutConfig)@@ -169,6 +177,9 @@ 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))+ }if c.applier != nil {c.applier.ApplyRuntimeConfig(c.runtime)}diff --git a/internal/dashboard/session_config.go b/internal/dashboard/session_config.gonew file mode 100644index 00000000..46d60490--- /dev/null+++ b/internal/dashboard/session_config.go@@ -0,0 +1,24 @@+package dashboard++import (+ "path/filepath"++ "github.com/pinchtab/pinchtab/internal/authn"+ "github.com/pinchtab/pinchtab/internal/config"+)++const dashboardSessionStateFile = "dashboard-auth-sessions.json"++func SessionManagerConfig(runtime *config.RuntimeConfig) authn.SessionConfig {+ if runtime == nil {+ return authn.SessionConfig{}+ }+ return authn.SessionConfig{+ IdleTimeout: runtime.Sessions.Dashboard.IdleTimeout,+ MaxLifetime: runtime.Sessions.Dashboard.MaxLifetime,+ ElevationWindow: runtime.Sessions.Dashboard.ElevationWindow,+ Persist: runtime.Sessions.Dashboard.Persist,+ PersistPath: filepath.Join(runtime.StateDir, dashboardSessionStateFile),+ PersistElevationAcrossRestart: runtime.Sessions.Dashboard.PersistElevationAcrossRestart,+ }+}diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex 1b3a66e6..2612e24a 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -121,7 +121,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessihttpx.ErrorCode(w, 403, "header_auth_required", "authorization header required for this endpoint", false, nil)return}- if cookieElevationRequired(r) && !sessions.IsElevated(creds.Value, token) {+ if cookieElevationRequired(r, cfg) && !sessions.IsElevated(creds.Value, token) {authn.AuditWarn(r, "auth.elevation_required", "elevationWindowSec", int(sessions.ElevationWindow().Seconds()))httpx.ErrorCode(w, 403, "elevation_required", "re-enter API token to continue", false, map[string]any{"elevationWindowSec": int(sessions.ElevationWindow().Seconds()),@@ -208,7 +208,10 @@ func cookieAuthAllowed(r *http.Request) bool {return false}-func cookieElevationRequired(r *http.Request) bool {+func cookieElevationRequired(r *http.Request, cfg *config.RuntimeConfig) bool {+ if cfg == nil || !cfg.Sessions.Dashboard.RequireElevation {+ return false+ }path := strings.TrimSpace(r.URL.Path)switch r.Method {case http.MethodPut:diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.goindex 539ce8c6..661e6aa7 100644--- a/internal/handlers/middleware_test.go+++ b/internal/handlers/middleware_test.go@@ -424,7 +424,14 @@ func TestAuthMiddleware_CookieWebSocketRequiresSameOrigin(t *testing.T) {}func TestAuthMiddleware_CookieElevatedEndpointRequiresElevation(t *testing.T) {- cfg := &config.RuntimeConfig{Token: "secret123"}+ cfg := &config.RuntimeConfig{+ Token: "secret123",+ Sessions: config.SessionsRuntimeConfig{+ Dashboard: config.DashboardSessionRuntimeConfig{+ RequireElevation: true,+ },+ },+ }sessions := authn.NewSessionManager(authn.SessionConfig{})sessionID, err := sessions.Create(cfg.Token)if err != nil {@@ -469,6 +476,34 @@ func TestAuthMiddleware_CookieElevatedEndpointRequiresElevation(t *testing.T) {}}+func TestAuthMiddleware_CookieConfigEndpointDoesNotRequireElevationByDefault(t *testing.T) {+ cfg := &config.RuntimeConfig{Token: "secret123"}+ sessions := authn.NewSessionManager(authn.SessionConfig{})+ sessionID, err := sessions.Create(cfg.Token)+ if err != nil {+ t.Fatalf("Create() error = %v", err)+ }++ called := false+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ called = true+ w.WriteHeader(http.StatusOK)+ }))++ req := httptest.NewRequest(http.MethodPut, "/api/config", nil)+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})+ req.Header.Set("Referer", "http://example.com/dashboard")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if !called {+ t.Fatal("handler should allow config endpoint without elevation when requireElevation is disabled")+ }+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", w.Code)+ }+}+func TestAuthMiddleware_HeaderAllowsRestrictedEndpoint(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}called := falsediff --git a/internal/server/server.go b/internal/server/server.goindex 31118c85..0fd5fa22 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -64,10 +64,8 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {}})configAPI := dashboard.NewConfigAPI(cfg, orch, profMgr, orch, dash, version, startedAt)- sessions := authn.NewSessionManager(authn.SessionConfig{- IdleTimeout: authn.DefaultSessionIdleTimeout,- MaxLifetime: authn.DefaultSessionMaxLifetime,- })+ sessions := authn.NewSessionManager(dashboard.SessionManagerConfig(cfg))+ configAPI.SetSessionManager(sessions)authAPI := dashboard.NewAuthAPI(cfg, sessions)// Wire up instance events to SSE broadcastdiff --git a/tests/e2e/scenarios-api/auth-full.sh b/tests/e2e/scenarios-api/auth-full.shindex de8e5d41..01a5fe0c 100644--- a/tests/e2e/scenarios-api/auth-full.sh+++ b/tests/e2e/scenarios-api/auth-full.sh@@ -190,29 +190,38 @@ assert_json_exists "$RESULT" ".config" "config payload returned"end_test# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-start_test "auth: sensitive dashboard config update requires elevation"+start_test "auth: dashboard config update does not require elevation by default"auth_reset_sessionauth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"assert_http_status 200 "login succeeds"-auth_put_json /api/config '{"server":{"token":"forbidden-from-dashboard"}}' -H "Origin: ${E2E_SERVER}"-assert_http_status 403 "config update requires elevation"-assert_contains "$RESULT" "elevation_required" "elevation error code returned"+auth_put_json /api/config '{"server":{"trustProxyHeaders":true}}' -H "Origin: ${E2E_SERVER}"+assert_http_status 200 "config update succeeds without elevation"+assert_json_exists "$RESULT" ".config" "config payload returned"end_test# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-start_test "auth: elevation unlocks sensitive dashboard config update"+start_test "auth: elevation unlocks config update when elevation is enabled"++pt PUT /api/config -d '{"sessions":{"dashboard":{"requireElevation":true}}}'+assert_http_status 200 "header auth enables elevation requirement"auth_reset_sessionauth_post_json /api/auth/login "{\"token\":\"${E2E_SERVER_TOKEN}\"}"assert_http_status 200 "login succeeds"+auth_put_json /api/config '{"server":{"trustProxyHeaders":false}}' -H "Origin: ${E2E_SERVER}"+assert_http_status 403 "config update requires elevation when enabled"+assert_contains "$RESULT" "elevation_required" "elevation error code returned"auth_post_json /api/auth/elevate "{\"token\":\"${E2E_SERVER_TOKEN}\"}" -H "Origin: ${E2E_SERVER}"assert_http_status 200 "session elevated"assert_json_exists "$RESULT" ".elevationWindowSec" "elevation window returned"-auth_put_json /api/config '{"server":{"token":"forbidden-from-dashboard"}}' -H "Origin: ${E2E_SERVER}"-assert_http_status 400 "elevated request reaches config handler"-assert_contains "$RESULT" "token_write_only" "write-only token guard returned"+auth_put_json /api/config '{"server":{"trustProxyHeaders":false}}' -H "Origin: ${E2E_SERVER}"+assert_http_status 200 "elevated request reaches config handler"+assert_json_exists "$RESULT" ".config" "config payload returned"++pt PUT /api/config -d '{"sessions":{"dashboard":{"requireElevation":false}}}'+assert_http_status 200 "header auth disables elevation requirement"end_test