feat: update session cookie options and enhance authentication flow

- Changed SameSite attribute for session cookies from 'strict' to 'lax' to allow cross-origin fetches, improving compatibility with various client requests.
- Updated cookie clearing logic in the authentication route to use `res.cookie()` for better reliability in cross-origin environments.
- Refactored the login view to implement a state machine for managing authentication phases, enhancing clarity and maintainability.
- Introduced a new logged-out view to inform users of session expiration and provide options to log in or retry.
- Added account and security sections to the settings view, allowing users to manage their account and security preferences more effectively.
This commit is contained in:
webdevcody
2026-01-07 12:55:23 -05:00
parent 927451013c
commit 70c04b5a3f
20 changed files with 895 additions and 304 deletions

View File

@@ -0,0 +1,33 @@
import { useNavigate } from '@tanstack/react-router';
import { Button } from '@/components/ui/button';
import { LogOut, RefreshCcw } from 'lucide-react';
export function LoggedOutView() {
const navigate = useNavigate();
return (
<div className="flex min-h-screen items-center justify-center bg-background p-4">
<div className="w-full max-w-md space-y-8">
<div className="text-center">
<div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-primary/10">
<LogOut className="h-8 w-8 text-primary" />
</div>
<h1 className="mt-6 text-2xl font-bold tracking-tight">Youve been logged out</h1>
<p className="mt-2 text-sm text-muted-foreground">
Your session expired, or the server restarted. Please log in again.
</p>
</div>
<div className="space-y-3">
<Button className="w-full" onClick={() => navigate({ to: '/login' })}>
Go to login
</Button>
<Button className="w-full" variant="secondary" onClick={() => window.location.reload()}>
<RefreshCcw className="mr-2 h-4 w-4" />
Retry
</Button>
</div>
</div>
</div>
);
}

View File

@@ -1,110 +1,322 @@
/**
* Login View - Web mode authentication
*
* Prompts user to enter the API key shown in server console.
* On successful login, sets an HTTP-only session cookie.
* Uses a state machine for clear, maintainable flow:
*
* On mount, verifies if an existing session is valid using exponential backoff.
* This handles cases where server live reloads kick users back to login
* even though their session is still valid.
* States:
* checking_server → server_error (after 5 retries)
* checking_server → awaiting_login (401/unauthenticated)
* checking_server → checking_setup (authenticated)
* awaiting_login → logging_in → login_error | checking_setup
* checking_setup → redirecting
*/
import { useState, useEffect, useRef } from 'react';
import { useReducer, useEffect, useRef } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { login, verifySession } from '@/lib/http-api-client';
import { login, getHttpApiClient, getServerUrlSync } from '@/lib/http-api-client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { KeyRound, AlertCircle, Loader2 } from 'lucide-react';
import { KeyRound, AlertCircle, Loader2, RefreshCw, ServerCrash } from 'lucide-react';
import { useAuthStore } from '@/store/auth-store';
import { useSetupStore } from '@/store/setup-store';
// =============================================================================
// State Machine Types
// =============================================================================
type State =
| { phase: 'checking_server'; attempt: number }
| { phase: 'server_error'; message: string }
| { phase: 'awaiting_login'; apiKey: string; error: string | null }
| { phase: 'logging_in'; apiKey: string }
| { phase: 'checking_setup' }
| { phase: 'redirecting'; to: string };
type Action =
| { type: 'SERVER_CHECK_RETRY'; attempt: number }
| { type: 'SERVER_ERROR'; message: string }
| { type: 'AUTH_REQUIRED' }
| { type: 'AUTH_VALID' }
| { type: 'UPDATE_API_KEY'; value: string }
| { type: 'SUBMIT_LOGIN' }
| { type: 'LOGIN_ERROR'; message: string }
| { type: 'REDIRECT'; to: string }
| { type: 'RETRY_SERVER_CHECK' };
const initialState: State = { phase: 'checking_server', attempt: 1 };
// =============================================================================
// State Machine Reducer
// =============================================================================
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'SERVER_CHECK_RETRY':
return { phase: 'checking_server', attempt: action.attempt };
case 'SERVER_ERROR':
return { phase: 'server_error', message: action.message };
case 'AUTH_REQUIRED':
return { phase: 'awaiting_login', apiKey: '', error: null };
case 'AUTH_VALID':
return { phase: 'checking_setup' };
case 'UPDATE_API_KEY':
if (state.phase !== 'awaiting_login') return state;
return { ...state, apiKey: action.value };
case 'SUBMIT_LOGIN':
if (state.phase !== 'awaiting_login') return state;
return { phase: 'logging_in', apiKey: state.apiKey };
case 'LOGIN_ERROR':
if (state.phase !== 'logging_in') return state;
return { phase: 'awaiting_login', apiKey: state.apiKey, error: action.message };
case 'REDIRECT':
return { phase: 'redirecting', to: action.to };
case 'RETRY_SERVER_CHECK':
return { phase: 'checking_server', attempt: 1 };
default:
return state;
}
}
// =============================================================================
// Constants
// =============================================================================
const MAX_RETRIES = 5;
const BACKOFF_BASE_MS = 400;
// =============================================================================
// Imperative Flow Logic (runs once on mount)
// =============================================================================
/**
* Delay helper for exponential backoff
* Check auth status without triggering side effects.
* Unlike the httpClient methods, this does NOT call handleUnauthorized()
* which would navigate us away to /logged-out.
*
* Relies on HTTP-only session cookie being sent via credentials: 'include'.
*
* Returns: { authenticated: true } or { authenticated: false }
* Throws: on network errors (for retry logic)
*/
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function checkAuthStatusSafe(): Promise<{ authenticated: boolean }> {
const serverUrl = getServerUrlSync();
const response = await fetch(`${serverUrl}/api/auth/status`, {
credentials: 'include', // Send HTTP-only session cookie
signal: AbortSignal.timeout(5000),
});
// Any response means server is reachable
const data = await response.json();
return { authenticated: data.authenticated === true };
}
/**
* Check if server is reachable and if we have a valid session.
*/
async function checkServerAndSession(
dispatch: React.Dispatch<Action>,
setAuthState: (state: { isAuthenticated: boolean; authChecked: boolean }) => void
): Promise<void> {
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
dispatch({ type: 'SERVER_CHECK_RETRY', attempt });
try {
const result = await checkAuthStatusSafe();
if (result.authenticated) {
// Server is reachable and we're authenticated
setAuthState({ isAuthenticated: true, authChecked: true });
dispatch({ type: 'AUTH_VALID' });
return;
}
// Server is reachable but we need to login
dispatch({ type: 'AUTH_REQUIRED' });
return;
} catch (error: unknown) {
// Network error - server is not reachable
console.debug(`Server check attempt ${attempt}/${MAX_RETRIES} failed:`, error);
if (attempt === MAX_RETRIES) {
dispatch({
type: 'SERVER_ERROR',
message: 'Unable to connect to server. Please check that the server is running.',
});
return;
}
// Exponential backoff before retry
const backoffMs = BACKOFF_BASE_MS * Math.pow(2, attempt - 1);
await new Promise((resolve) => setTimeout(resolve, backoffMs));
}
}
}
async function checkSetupStatus(dispatch: React.Dispatch<Action>): Promise<void> {
const httpClient = getHttpApiClient();
try {
const result = await httpClient.settings.getGlobal();
if (result.success && result.settings) {
// Check the setupComplete field from settings
// This is set to true when user completes the setup wizard
const setupComplete = (result.settings as { setupComplete?: boolean }).setupComplete === true;
// IMPORTANT: Update the Zustand store BEFORE redirecting
// Otherwise __root.tsx routing effect will override our redirect
// because it reads setupComplete from the store (which defaults to false)
useSetupStore.getState().setSetupComplete(setupComplete);
dispatch({ type: 'REDIRECT', to: setupComplete ? '/' : '/setup' });
} else {
// No settings yet = first run = need setup
useSetupStore.getState().setSetupComplete(false);
dispatch({ type: 'REDIRECT', to: '/setup' });
}
} catch {
// If we can't get settings, go to setup to be safe
useSetupStore.getState().setSetupComplete(false);
dispatch({ type: 'REDIRECT', to: '/setup' });
}
}
async function performLogin(
apiKey: string,
dispatch: React.Dispatch<Action>,
setAuthState: (state: { isAuthenticated: boolean; authChecked: boolean }) => void
): Promise<void> {
try {
const result = await login(apiKey.trim());
if (result.success) {
setAuthState({ isAuthenticated: true, authChecked: true });
dispatch({ type: 'AUTH_VALID' });
} else {
dispatch({ type: 'LOGIN_ERROR', message: result.error || 'Invalid API key' });
}
} catch {
dispatch({ type: 'LOGIN_ERROR', message: 'Failed to connect to server' });
}
}
// =============================================================================
// Component
// =============================================================================
export function LoginView() {
const navigate = useNavigate();
const setAuthState = useAuthStore((s) => s.setAuthState);
const setupComplete = useSetupStore((s) => s.setupComplete);
const [apiKey, setApiKey] = useState('');
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isCheckingSession, setIsCheckingSession] = useState(true);
const sessionCheckRef = useRef(false);
const [state, dispatch] = useReducer(reducer, initialState);
const initialCheckDone = useRef(false);
// Check for existing valid session on mount with exponential backoff
// Run initial server/session check once on mount
useEffect(() => {
// Prevent duplicate checks in strict mode
if (sessionCheckRef.current) return;
sessionCheckRef.current = true;
if (initialCheckDone.current) return;
initialCheckDone.current = true;
const checkExistingSession = async () => {
const maxRetries = 5;
const baseDelay = 500; // Start with 500ms
checkServerAndSession(dispatch, setAuthState);
}, [setAuthState]);
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const isValid = await verifySession();
if (isValid) {
// Session is valid, redirect to the main app
setAuthState({ isAuthenticated: true, authChecked: true });
navigate({ to: setupComplete ? '/' : '/setup' });
return;
}
// Session is invalid, no need to retry - show login form
break;
} catch {
// Network error or server not ready, retry with exponential backoff
if (attempt < maxRetries - 1) {
const waitTime = baseDelay * Math.pow(2, attempt); // 500, 1000, 2000, 4000, 8000ms
await delay(waitTime);
}
}
}
// Session check complete (either invalid or all retries exhausted)
setIsCheckingSession(false);
};
checkExistingSession();
}, [navigate, setAuthState, setupComplete]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsLoading(true);
try {
const result = await login(apiKey.trim());
if (result.success) {
// Mark as authenticated for this session (cookie-based auth)
setAuthState({ isAuthenticated: true, authChecked: true });
// After auth, determine if setup is needed or go to app
navigate({ to: setupComplete ? '/' : '/setup' });
} else {
setError(result.error || 'Invalid API key');
}
} catch (err) {
setError('Failed to connect to server');
} finally {
setIsLoading(false);
// When we enter checking_setup phase, check setup status
useEffect(() => {
if (state.phase === 'checking_setup') {
checkSetupStatus(dispatch);
}
}, [state.phase]);
// When we enter redirecting phase, navigate
useEffect(() => {
if (state.phase === 'redirecting') {
navigate({ to: state.to });
}
}, [state.phase, state.phase === 'redirecting' ? state.to : null, navigate]);
// Handle login form submission
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (state.phase !== 'awaiting_login' || !state.apiKey.trim()) return;
dispatch({ type: 'SUBMIT_LOGIN' });
performLogin(state.apiKey, dispatch, setAuthState);
};
// Show loading state while checking existing session
if (isCheckingSession) {
// Handle retry button for server errors
const handleRetry = () => {
initialCheckDone.current = false;
dispatch({ type: 'RETRY_SERVER_CHECK' });
checkServerAndSession(dispatch, setAuthState);
};
// =============================================================================
// Render based on current state
// =============================================================================
// Checking server connectivity
if (state.phase === 'checking_server') {
return (
<div className="flex min-h-screen items-center justify-center bg-background p-4">
<div className="text-center space-y-4">
<Loader2 className="h-8 w-8 animate-spin mx-auto text-primary" />
<p className="text-sm text-muted-foreground">Checking session...</p>
<p className="text-sm text-muted-foreground">
Connecting to server
{state.attempt > 1 ? ` (attempt ${state.attempt}/${MAX_RETRIES})` : '...'}
</p>
</div>
</div>
);
}
// Server unreachable after retries
if (state.phase === 'server_error') {
return (
<div className="flex min-h-screen items-center justify-center bg-background p-4">
<div className="w-full max-w-md space-y-6 text-center">
<div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10">
<ServerCrash className="h-8 w-8 text-destructive" />
</div>
<div className="space-y-2">
<h1 className="text-2xl font-bold tracking-tight">Server Unavailable</h1>
<p className="text-sm text-muted-foreground">{state.message}</p>
</div>
<Button onClick={handleRetry} variant="outline" className="gap-2">
<RefreshCw className="h-4 w-4" />
Retry Connection
</Button>
</div>
</div>
);
}
// Checking setup status after auth
if (state.phase === 'checking_setup' || state.phase === 'redirecting') {
return (
<div className="flex min-h-screen items-center justify-center bg-background p-4">
<div className="text-center space-y-4">
<Loader2 className="h-8 w-8 animate-spin mx-auto text-primary" />
<p className="text-sm text-muted-foreground">
{state.phase === 'checking_setup' ? 'Loading settings...' : 'Redirecting...'}
</p>
</div>
</div>
);
}
// Login form (awaiting_login or logging_in)
const isLoggingIn = state.phase === 'logging_in';
const apiKey = state.phase === 'awaiting_login' ? state.apiKey : state.apiKey;
const error = state.phase === 'awaiting_login' ? state.error : null;
return (
<div className="flex min-h-screen items-center justify-center bg-background p-4">
<div className="w-full max-w-md space-y-8">
@@ -130,8 +342,8 @@ export function LoginView() {
type="password"
placeholder="Enter API key..."
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
disabled={isLoading}
onChange={(e) => dispatch({ type: 'UPDATE_API_KEY', value: e.target.value })}
disabled={isLoggingIn}
autoFocus
className="font-mono"
data-testid="login-api-key-input"
@@ -148,10 +360,10 @@ export function LoginView() {
<Button
type="submit"
className="w-full"
disabled={isLoading || !apiKey.trim()}
disabled={isLoggingIn || !apiKey.trim()}
data-testid="login-submit-button"
>
{isLoading ? (
{isLoggingIn ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Authenticating...

View File

@@ -16,6 +16,8 @@ import { AudioSection } from './settings-view/audio/audio-section';
import { KeyboardShortcutsSection } from './settings-view/keyboard-shortcuts/keyboard-shortcuts-section';
import { FeatureDefaultsSection } from './settings-view/feature-defaults/feature-defaults-section';
import { DangerZoneSection } from './settings-view/danger-zone/danger-zone-section';
import { AccountSection } from './settings-view/account';
import { SecuritySection } from './settings-view/security';
import { ProviderTabs } from './settings-view/providers';
import { MCPServersSection } from './settings-view/mcp-servers';
import { PromptCustomizationSection } from './settings-view/prompts';
@@ -146,13 +148,20 @@ export function SettingsView() {
onDefaultAIProfileIdChange={setDefaultAIProfileId}
/>
);
case 'account':
return <AccountSection />;
case 'security':
return (
<SecuritySection
skipSandboxWarning={skipSandboxWarning}
onSkipSandboxWarningChange={setSkipSandboxWarning}
/>
);
case 'danger':
return (
<DangerZoneSection
project={settingsProject}
onDeleteClick={() => setShowDeleteDialog(true)}
skipSandboxWarning={skipSandboxWarning}
onResetSandboxWarning={() => setSkipSandboxWarning(false)}
/>
);
default:

View File

@@ -0,0 +1,77 @@
import { useState } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { Button } from '@/components/ui/button';
import { LogOut, User } from 'lucide-react';
import { cn } from '@/lib/utils';
import { logout } from '@/lib/http-api-client';
import { useAuthStore } from '@/store/auth-store';
export function AccountSection() {
const navigate = useNavigate();
const [isLoggingOut, setIsLoggingOut] = useState(false);
const handleLogout = async () => {
setIsLoggingOut(true);
try {
await logout();
// Reset auth state
useAuthStore.getState().resetAuth();
// Navigate to logged out page
navigate({ to: '/logged-out' });
} catch (error) {
console.error('Logout failed:', error);
setIsLoggingOut(false);
}
};
return (
<div
className={cn(
'rounded-2xl overflow-hidden',
'border border-border/50',
'bg-gradient-to-br from-card/80 via-card/70 to-card/80 backdrop-blur-xl',
'shadow-sm'
)}
>
<div className="p-6 border-b border-border/30 bg-gradient-to-r from-primary/5 via-transparent to-transparent">
<div className="flex items-center gap-3 mb-2">
<div className="w-9 h-9 rounded-xl bg-gradient-to-br from-primary/20 to-primary/10 flex items-center justify-center border border-primary/20">
<User className="w-5 h-5 text-primary" />
</div>
<h2 className="text-lg font-semibold text-foreground tracking-tight">Account</h2>
</div>
<p className="text-sm text-muted-foreground/80 ml-12">Manage your session and account.</p>
</div>
<div className="p-6 space-y-4">
{/* Logout */}
<div className="flex items-center justify-between gap-4 p-4 rounded-xl bg-muted/30 border border-border/30">
<div className="flex items-center gap-3.5 min-w-0">
<div className="w-11 h-11 rounded-xl bg-gradient-to-br from-muted/50 to-muted/30 border border-border/30 flex items-center justify-center shrink-0">
<LogOut className="w-5 h-5 text-muted-foreground" />
</div>
<div className="min-w-0">
<p className="font-medium text-foreground">Log Out</p>
<p className="text-xs text-muted-foreground/70 mt-0.5">
End your current session and return to the login screen
</p>
</div>
</div>
<Button
variant="outline"
onClick={handleLogout}
disabled={isLoggingOut}
data-testid="logout-button"
className={cn(
'shrink-0 gap-2',
'transition-all duration-200 ease-out',
'hover:scale-[1.02] active:scale-[0.98]'
)}
>
<LogOut className="w-4 h-4" />
{isLoggingOut ? 'Logging out...' : 'Log Out'}
</Button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1 @@
export { AccountSection } from './account-section';

View File

@@ -1,6 +1,7 @@
import { cn } from '@/lib/utils';
import type { Project } from '@/lib/electron';
import type { NavigationItem } from '../config/navigation';
import { GLOBAL_NAV_ITEMS, PROJECT_NAV_ITEMS } from '../config/navigation';
import type { SettingsViewId } from '../hooks/use-settings-view';
interface SettingsNavigationProps {
@@ -10,8 +11,53 @@ interface SettingsNavigationProps {
onNavigate: (sectionId: SettingsViewId) => void;
}
function NavButton({
item,
isActive,
onNavigate,
}: {
item: NavigationItem;
isActive: boolean;
onNavigate: (sectionId: SettingsViewId) => void;
}) {
const Icon = item.icon;
return (
<button
key={item.id}
onClick={() => onNavigate(item.id)}
className={cn(
'group w-full flex items-center gap-2.5 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ease-out text-left relative overflow-hidden',
isActive
? [
'bg-gradient-to-r from-brand-500/15 via-brand-500/10 to-brand-600/5',
'text-foreground',
'border border-brand-500/25',
'shadow-sm shadow-brand-500/5',
]
: [
'text-muted-foreground hover:text-foreground',
'hover:bg-accent/50',
'border border-transparent hover:border-border/40',
],
'hover:scale-[1.01] active:scale-[0.98]'
)}
>
{/* Active indicator bar */}
{isActive && (
<div className="absolute inset-y-0 left-0 w-0.5 bg-gradient-to-b from-brand-400 via-brand-500 to-brand-600 rounded-r-full" />
)}
<Icon
className={cn(
'w-4 h-4 shrink-0 transition-all duration-200',
isActive ? 'text-brand-500' : 'group-hover:text-brand-400 group-hover:scale-110'
)}
/>
<span className="truncate">{item.label}</span>
</button>
);
}
export function SettingsNavigation({
navItems,
activeSection,
currentProject,
onNavigate,
@@ -19,52 +65,53 @@ export function SettingsNavigation({
return (
<nav
className={cn(
'hidden lg:block w-52 shrink-0',
'hidden lg:block w-52 shrink-0 overflow-y-auto',
'border-r border-border/50',
'bg-gradient-to-b from-card/80 via-card/60 to-card/40 backdrop-blur-xl'
)}
>
<div className="sticky top-0 p-4 space-y-1.5">
{navItems
.filter((item) => item.id !== 'danger' || currentProject)
.map((item) => {
const Icon = item.icon;
const isActive = activeSection === item.id;
return (
<button
key={item.id}
onClick={() => onNavigate(item.id)}
className={cn(
'group w-full flex items-center gap-2.5 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ease-out text-left relative overflow-hidden',
isActive
? [
'bg-gradient-to-r from-brand-500/15 via-brand-500/10 to-brand-600/5',
'text-foreground',
'border border-brand-500/25',
'shadow-sm shadow-brand-500/5',
]
: [
'text-muted-foreground hover:text-foreground',
'hover:bg-accent/50',
'border border-transparent hover:border-border/40',
],
'hover:scale-[1.01] active:scale-[0.98]'
)}
>
{/* Active indicator bar */}
{isActive && (
<div className="absolute inset-y-0 left-0 w-0.5 bg-gradient-to-b from-brand-400 via-brand-500 to-brand-600 rounded-r-full" />
)}
<Icon
className={cn(
'w-4 h-4 shrink-0 transition-all duration-200',
isActive ? 'text-brand-500' : 'group-hover:text-brand-400 group-hover:scale-110'
)}
<div className="sticky top-0 p-4 space-y-1">
{/* Global Settings Label */}
<div className="px-3 py-2 text-xs font-semibold text-muted-foreground/70 uppercase tracking-wider">
Global Settings
</div>
{/* Global Settings Items */}
<div className="space-y-1">
{GLOBAL_NAV_ITEMS.map((item) => (
<NavButton
key={item.id}
item={item}
isActive={activeSection === item.id}
onNavigate={onNavigate}
/>
))}
</div>
{/* Project Settings - only show when a project is selected */}
{currentProject && (
<>
{/* Divider */}
<div className="my-4 border-t border-border/50" />
{/* Project Settings Label */}
<div className="px-3 py-2 text-xs font-semibold text-muted-foreground/70 uppercase tracking-wider">
Project Settings
</div>
{/* Project Settings Items */}
<div className="space-y-1">
{PROJECT_NAV_ITEMS.map((item) => (
<NavButton
key={item.id}
item={item}
isActive={activeSection === item.id}
onNavigate={onNavigate}
/>
<span className="truncate">{item.label}</span>
</button>
);
})}
))}
</div>
</>
)}
</div>
</nav>
);

View File

@@ -11,6 +11,8 @@ import {
Workflow,
Plug,
MessageSquareText,
User,
Shield,
} from 'lucide-react';
import type { SettingsViewId } from '../hooks/use-settings-view';
@@ -20,8 +22,13 @@ export interface NavigationItem {
icon: LucideIcon;
}
// Navigation items for the settings side panel
export const NAV_ITEMS: NavigationItem[] = [
export interface NavigationGroup {
label: string;
items: NavigationItem[];
}
// Global settings - always visible
export const GLOBAL_NAV_ITEMS: NavigationItem[] = [
{ id: 'api-keys', label: 'API Keys', icon: Key },
{ id: 'providers', label: 'AI Providers', icon: Bot },
{ id: 'mcp-servers', label: 'MCP Servers', icon: Plug },
@@ -32,5 +39,14 @@ export const NAV_ITEMS: NavigationItem[] = [
{ id: 'keyboard', label: 'Keyboard Shortcuts', icon: Settings2 },
{ id: 'audio', label: 'Audio', icon: Volume2 },
{ id: 'defaults', label: 'Feature Defaults', icon: FlaskConical },
{ id: 'account', label: 'Account', icon: User },
{ id: 'security', label: 'Security', icon: Shield },
];
// Project-specific settings - only visible when a project is selected
export const PROJECT_NAV_ITEMS: NavigationItem[] = [
{ id: 'danger', label: 'Danger Zone', icon: Trash2 },
];
// Legacy export for backwards compatibility
export const NAV_ITEMS: NavigationItem[] = [...GLOBAL_NAV_ITEMS, ...PROJECT_NAV_ITEMS];

View File

@@ -1,21 +1,14 @@
import { Button } from '@/components/ui/button';
import { Trash2, Folder, AlertTriangle, Shield, RotateCcw } from 'lucide-react';
import { Trash2, Folder, AlertTriangle } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { Project } from '../shared/types';
interface DangerZoneSectionProps {
project: Project | null;
onDeleteClick: () => void;
skipSandboxWarning: boolean;
onResetSandboxWarning: () => void;
}
export function DangerZoneSection({
project,
onDeleteClick,
skipSandboxWarning,
onResetSandboxWarning,
}: DangerZoneSectionProps) {
export function DangerZoneSection({ project, onDeleteClick }: DangerZoneSectionProps) {
return (
<div
className={cn(
@@ -32,43 +25,11 @@ export function DangerZoneSection({
</div>
<h2 className="text-lg font-semibold text-foreground tracking-tight">Danger Zone</h2>
</div>
<p className="text-sm text-muted-foreground/80 ml-12">
Destructive actions and reset options.
</p>
<p className="text-sm text-muted-foreground/80 ml-12">Destructive project actions.</p>
</div>
<div className="p-6 space-y-4">
{/* Sandbox Warning Reset */}
{skipSandboxWarning && (
<div className="flex items-center justify-between gap-4 p-4 rounded-xl bg-destructive/5 border border-destructive/10">
<div className="flex items-center gap-3.5 min-w-0">
<div className="w-11 h-11 rounded-xl bg-gradient-to-br from-destructive/15 to-destructive/10 border border-destructive/20 flex items-center justify-center shrink-0">
<Shield className="w-5 h-5 text-destructive" />
</div>
<div className="min-w-0">
<p className="font-medium text-foreground">Sandbox Warning Disabled</p>
<p className="text-xs text-muted-foreground/70 mt-0.5">
The sandbox environment warning is hidden on startup
</p>
</div>
</div>
<Button
variant="outline"
onClick={onResetSandboxWarning}
data-testid="reset-sandbox-warning-button"
className={cn(
'shrink-0 gap-2',
'transition-all duration-200 ease-out',
'hover:scale-[1.02] active:scale-[0.98]'
)}
>
<RotateCcw className="w-4 h-4" />
Reset
</Button>
</div>
)}
{/* Project Delete */}
{project && (
{project ? (
<div className="flex items-center justify-between gap-4 p-4 rounded-xl bg-destructive/5 border border-destructive/10">
<div className="flex items-center gap-3.5 min-w-0">
<div className="w-11 h-11 rounded-xl bg-gradient-to-br from-brand-500/15 to-brand-600/10 border border-brand-500/20 flex items-center justify-center shrink-0">
@@ -94,13 +55,8 @@ export function DangerZoneSection({
Delete Project
</Button>
</div>
)}
{/* Empty state when nothing to show */}
{!skipSandboxWarning && !project && (
<p className="text-sm text-muted-foreground/60 text-center py-4">
No danger zone actions available.
</p>
) : (
<p className="text-sm text-muted-foreground/60 text-center py-4">No project selected.</p>
)}
</div>
</div>

View File

@@ -12,6 +12,8 @@ export type SettingsViewId =
| 'keyboard'
| 'audio'
| 'defaults'
| 'account'
| 'security'
| 'danger';
interface UseSettingsViewOptions {

View File

@@ -0,0 +1 @@
export { SecuritySection } from './security-section';

View File

@@ -0,0 +1,71 @@
import { Shield, AlertTriangle } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
interface SecuritySectionProps {
skipSandboxWarning: boolean;
onSkipSandboxWarningChange: (skip: boolean) => void;
}
export function SecuritySection({
skipSandboxWarning,
onSkipSandboxWarningChange,
}: SecuritySectionProps) {
return (
<div
className={cn(
'rounded-2xl overflow-hidden',
'border border-border/50',
'bg-gradient-to-br from-card/80 via-card/70 to-card/80 backdrop-blur-xl',
'shadow-sm'
)}
>
<div className="p-6 border-b border-border/30 bg-gradient-to-r from-primary/5 via-transparent to-transparent">
<div className="flex items-center gap-3 mb-2">
<div className="w-9 h-9 rounded-xl bg-gradient-to-br from-primary/20 to-primary/10 flex items-center justify-center border border-primary/20">
<Shield className="w-5 h-5 text-primary" />
</div>
<h2 className="text-lg font-semibold text-foreground tracking-tight">Security</h2>
</div>
<p className="text-sm text-muted-foreground/80 ml-12">
Configure security warnings and protections.
</p>
</div>
<div className="p-6 space-y-4">
{/* Sandbox Warning Toggle */}
<div className="flex items-center justify-between gap-4 p-4 rounded-xl bg-muted/30 border border-border/30">
<div className="flex items-center gap-3.5 min-w-0">
<div className="w-11 h-11 rounded-xl bg-gradient-to-br from-amber-500/15 to-amber-600/10 border border-amber-500/20 flex items-center justify-center shrink-0">
<AlertTriangle className="w-5 h-5 text-amber-500" />
</div>
<div className="min-w-0 flex-1">
<Label
htmlFor="sandbox-warning-toggle"
className="font-medium text-foreground cursor-pointer"
>
Show Sandbox Warning on Startup
</Label>
<p className="text-xs text-muted-foreground/70 mt-0.5">
Display a security warning when not running in a sandboxed environment
</p>
</div>
</div>
<Switch
id="sandbox-warning-toggle"
checked={!skipSandboxWarning}
onCheckedChange={(checked) => onSkipSandboxWarningChange(!checked)}
data-testid="sandbox-warning-toggle"
/>
</div>
{/* Info text */}
<p className="text-xs text-muted-foreground/60 px-4">
When enabled, you&apos;ll see a warning on app startup if you&apos;re not running in a
containerized environment (like Docker). This helps remind you to use proper isolation
when running AI agents.
</p>
</div>
</div>
);
}