mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Add single-user authentication system with Better Auth integration (#76)
* Add Better Auth integration with session management - Implement user authentication using Better Auth library - Add login, register, and sign out functionality - Support passkey/WebAuthn authentication - Create database schema for users, sessions, accounts, passkeys - Add AuthProvider context and ProtectedRoute components - Add account settings page in settings dialog - Protect all API routes with authentication middleware - Update environment configuration for auth providers * Add single-user authentication system with admin setup - Add first-run Setup page for initial admin account creation - Add environment-based admin configuration (ADMIN_EMAIL, ADMIN_PASSWORD) - Add password reset capability via ADMIN_PASSWORD_RESET environment flag - Migrate to data routers with auth loaders, remove ProtectedRoute - Add change password functionality to account settings - Enforce AUTH_SECRET requirement in production - Auto-disable registration when admin is pre-configured via environment * Track busy/idle session status across hooks * Bump version to 0.7.5 * Update pnpm to 10.28.1
This commit is contained in:
1 parent
af292758c3
commit
81a66d2ddb
29 files changed
+2324
-149
No files matched your search
+76
-39
@@ -1,16 +1,21 @@
|
||||
import { useEffect } from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BrowserRouter, Routes, Route } from 'react-router-dom'
|
||||
import { createBrowserRouter, RouterProvider, Outlet } from 'react-router-dom'
|
||||
import { Toaster } from 'sonner'
|
||||
import { Repos } from './pages/Repos'
|
||||
import { RepoDetail } from './pages/RepoDetail'
|
||||
import { SessionDetail } from './pages/SessionDetail'
|
||||
import { Login } from './pages/Login'
|
||||
import { Register } from './pages/Register'
|
||||
import { Setup } from './pages/Setup'
|
||||
import { SettingsDialog } from './components/settings/SettingsDialog'
|
||||
import { useSettingsDialog } from './hooks/useSettingsDialog'
|
||||
import { useTheme } from './hooks/useTheme'
|
||||
import { TTSProvider } from './contexts/TTSContext'
|
||||
import { AuthProvider } from './contexts/AuthContext'
|
||||
import { EventProvider, usePermissions } from '@/contexts/EventContext'
|
||||
import { PermissionRequestDialog } from './components/session/PermissionRequestDialog'
|
||||
import { loginLoader, setupLoader, registerLoader, protectedLoader } from './lib/auth-loaders'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -21,38 +26,6 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
})
|
||||
|
||||
function RouterContent() {
|
||||
const { isOpen, close } = useSettingsDialog()
|
||||
useTheme()
|
||||
|
||||
useEffect(() => {
|
||||
const loader = document.getElementById('app-loader')
|
||||
if (loader) {
|
||||
loader.style.transition = 'opacity 0.2s ease-out'
|
||||
loader.style.opacity = '0'
|
||||
setTimeout(() => loader.remove(), 200)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<>
|
||||
<Routes>
|
||||
<Route path="/" element={<Repos />} />
|
||||
<Route path="/repos/:id" element={<RepoDetail />} />
|
||||
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
|
||||
</Routes>
|
||||
<SettingsDialog open={isOpen} onOpenChange={close} />
|
||||
<Toaster
|
||||
position="bottom-right"
|
||||
expand={false}
|
||||
richColors
|
||||
closeButton
|
||||
duration={2500}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function PermissionDialogWrapper() {
|
||||
const {
|
||||
current: currentPermission,
|
||||
@@ -75,16 +48,80 @@ function PermissionDialogWrapper() {
|
||||
)
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
const { isOpen, close } = useSettingsDialog()
|
||||
useTheme()
|
||||
|
||||
useEffect(() => {
|
||||
const loader = document.getElementById('app-loader')
|
||||
if (loader) {
|
||||
loader.style.transition = 'opacity 0.2s ease-out'
|
||||
loader.style.opacity = '0'
|
||||
setTimeout(() => loader.remove(), 200)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<AuthProvider>
|
||||
<EventProvider>
|
||||
<Outlet />
|
||||
<PermissionDialogWrapper />
|
||||
<SettingsDialog open={isOpen} onOpenChange={close} />
|
||||
<Toaster
|
||||
position="bottom-right"
|
||||
expand={false}
|
||||
richColors
|
||||
closeButton
|
||||
duration={2500}
|
||||
/>
|
||||
</EventProvider>
|
||||
</AuthProvider>
|
||||
)
|
||||
}
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
element: <AppShell />,
|
||||
children: [
|
||||
{
|
||||
path: '/login',
|
||||
element: <Login />,
|
||||
loader: loginLoader,
|
||||
},
|
||||
{
|
||||
path: '/register',
|
||||
element: <Register />,
|
||||
loader: registerLoader,
|
||||
},
|
||||
{
|
||||
path: '/setup',
|
||||
element: <Setup />,
|
||||
loader: setupLoader,
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
element: <Repos />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/repos/:id',
|
||||
element: <RepoDetail />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/repos/:id/sessions/:sessionId',
|
||||
element: <SessionDetail />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TTSProvider>
|
||||
<BrowserRouter>
|
||||
<EventProvider>
|
||||
<RouterContent />
|
||||
<PermissionDialogWrapper />
|
||||
</EventProvider>
|
||||
</BrowserRouter>
|
||||
<RouterProvider router={router} />
|
||||
</TTSProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
import { useState } from 'react'
|
||||
import { Edit2 } from 'lucide-react'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Loader2, User, KeyRound, LogOut, Plus, Trash2, AlertCircle, CheckCircle, Lock } from 'lucide-react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { passkey, changePassword } from '@/lib/auth-client'
|
||||
|
||||
interface Passkey {
|
||||
id: string
|
||||
name?: string
|
||||
credentialID: string
|
||||
createdAt: string
|
||||
deviceType: string
|
||||
}
|
||||
|
||||
export function AccountSettings() {
|
||||
const { user, addPasskey, logout } = useAuth()
|
||||
const queryClient = useQueryClient()
|
||||
const [passkeyName, setPasskeyName] = useState('')
|
||||
const [currentPassword, setCurrentPassword] = useState('')
|
||||
const [newPassword, setNewPassword] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [success, setSuccess] = useState<string | null>(null)
|
||||
const [showChangePassword, setShowChangePassword] = useState(false)
|
||||
const [editingProfile, setEditingProfile] = useState(false)
|
||||
|
||||
const { data: passkeys, isLoading: passkeysLoading } = useQuery({
|
||||
queryKey: ['passkeys'],
|
||||
queryFn: async () => {
|
||||
const response = await fetch('/api/auth/passkey/list-user-passkeys', {
|
||||
credentials: 'include',
|
||||
})
|
||||
if (!response.ok) return []
|
||||
return response.json() as Promise<Passkey[]>
|
||||
},
|
||||
enabled: !!user,
|
||||
})
|
||||
|
||||
const addPasskeyMutation = useMutation({
|
||||
mutationFn: async (name: string) => {
|
||||
return addPasskey(name || undefined)
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
if (result.error) {
|
||||
setError(result.error)
|
||||
} else {
|
||||
setSuccess('Passkey added successfully')
|
||||
setPasskeyName('')
|
||||
queryClient.invalidateQueries({ queryKey: ['passkeys'] })
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to add passkey')
|
||||
},
|
||||
})
|
||||
|
||||
const deletePasskeyMutation = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await passkey.deletePasskey({ id })
|
||||
if (response.error) {
|
||||
throw new Error(response.error.message || 'Failed to delete passkey')
|
||||
}
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
setSuccess('Passkey deleted successfully')
|
||||
queryClient.invalidateQueries({ queryKey: ['passkeys'] })
|
||||
},
|
||||
onError: (err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete passkey')
|
||||
},
|
||||
})
|
||||
|
||||
const changePasswordMutation = useMutation({
|
||||
mutationFn: async ({ currentPassword, newPassword }: { currentPassword: string; newPassword: string }) => {
|
||||
const response = await changePassword({ currentPassword, newPassword })
|
||||
if (response.error) {
|
||||
throw new Error(response.error.message || 'Failed to change password')
|
||||
}
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
setSuccess('Password changed successfully')
|
||||
setCurrentPassword('')
|
||||
setNewPassword('')
|
||||
setShowChangePassword(false)
|
||||
},
|
||||
onError: (err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to change password')
|
||||
},
|
||||
})
|
||||
|
||||
const handleAddPasskey = async () => {
|
||||
setError(null)
|
||||
setSuccess(null)
|
||||
addPasskeyMutation.mutate(passkeyName)
|
||||
}
|
||||
|
||||
const handleDeletePasskey = (id: string) => {
|
||||
setError(null)
|
||||
setSuccess(null)
|
||||
if (confirm('Are you sure you want to delete this passkey?')) {
|
||||
deletePasskeyMutation.mutate(id)
|
||||
}
|
||||
}
|
||||
|
||||
const handleChangePassword = () => {
|
||||
setError(null)
|
||||
setSuccess(null)
|
||||
if (newPassword.length < 8) {
|
||||
setError('New password must be at least 8 characters')
|
||||
return
|
||||
}
|
||||
changePasswordMutation.mutate({ currentPassword, newPassword })
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4 sm:space-y-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<Alert className="border-green-500 text-green-700 dark:text-green-400">
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>{success}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
|
||||
<Card className="border-0 shadow-none">
|
||||
<CardHeader className="pb-3 sm:pb-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<User className="h-4 w-4 sm:h-5 sm:w-5" />
|
||||
<CardTitle className="text-base sm:text-lg">Profile</CardTitle>
|
||||
</div>
|
||||
{!editingProfile && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditingProfile(true)} className="h-8">
|
||||
<Edit2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{editingProfile ? (
|
||||
<div className="space-y-3 sm:space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs sm:text-sm">Name</Label>
|
||||
<Input value={user.name} disabled className="h-9 sm:h-10 text-sm" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs sm:text-sm">Email</Label>
|
||||
<Input value={user.email} disabled className="h-9 sm:h-10 text-sm" />
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => setEditingProfile(false)} className="h-9 sm:h-10">
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 sm:space-y-3">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-4">
|
||||
<span className="text-xs sm:text-sm text-muted-foreground sm:w-20">Name</span>
|
||||
<span className="text-sm font-medium truncate">{user.name}</span>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-4">
|
||||
<span className="text-xs sm:text-sm text-muted-foreground sm:w-20">Email</span>
|
||||
<span className="text-sm truncate">{user.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-0 shadow-none">
|
||||
<CardHeader className="pb-2 sm:pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
|
||||
<Lock className="h-4 w-4 sm:h-5 sm:w-5" />
|
||||
Change Password
|
||||
</CardTitle>
|
||||
<CardDescription className="text-xs sm:text-sm">Update your account password</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!showChangePassword ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowChangePassword(true)}
|
||||
className="h-9 sm:h-10"
|
||||
>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Change Password
|
||||
</Button>
|
||||
) : (
|
||||
<div className="space-y-3 sm:space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="current-password" className="text-xs sm:text-sm">Current Password</Label>
|
||||
<Input
|
||||
id="current-password"
|
||||
type="password"
|
||||
value={currentPassword}
|
||||
onChange={(e) => setCurrentPassword(e.target.value)}
|
||||
placeholder="Enter current password"
|
||||
className="h-9 sm:h-10 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="new-password" className="text-xs sm:text-sm">New Password</Label>
|
||||
<Input
|
||||
id="new-password"
|
||||
type="password"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
placeholder="At least 8 characters"
|
||||
className="h-9 sm:h-10 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handleChangePassword}
|
||||
disabled={changePasswordMutation.isPending || !currentPassword || !newPassword}
|
||||
className="h-9 sm:h-10"
|
||||
>
|
||||
{changePasswordMutation.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Change Password
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => setShowChangePassword(false)}
|
||||
className="h-9 sm:h-10"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card className="border-0 shadow-none">
|
||||
<CardHeader className="pb-2 sm:pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
|
||||
<KeyRound className="h-4 w-4 sm:h-5 sm:w-5" />
|
||||
Passkeys
|
||||
</CardTitle>
|
||||
<CardDescription className="text-xs sm:text-sm">Manage passkeys for passwordless sign-in</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 sm:space-y-4">
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<Input
|
||||
placeholder="Passkey name (optional)"
|
||||
value={passkeyName}
|
||||
onChange={(e) => setPasskeyName(e.target.value)}
|
||||
className="h-9 sm:h-10 text-sm"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleAddPasskey}
|
||||
disabled={addPasskeyMutation.isPending}
|
||||
className="h-9 sm:h-10 whitespace-nowrap"
|
||||
>
|
||||
{addPasskeyMutation.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Add Passkey
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{passkeysLoading ? (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : passkeys && passkeys.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{passkeys.map((pk) => (
|
||||
<div
|
||||
key={pk.id}
|
||||
className="flex items-center justify-between p-2.5 sm:p-3 bg-muted rounded-lg"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="font-medium text-sm truncate">{pk.name || 'Unnamed Passkey'}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{pk.deviceType} - {new Date(pk.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 ml-2 flex-shrink-0"
|
||||
onClick={() => handleDeletePasskey(pk.id)}
|
||||
disabled={deletePasskeyMutation.isPending}
|
||||
>
|
||||
{deletePasskeyMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs sm:text-sm text-muted-foreground text-center py-3">
|
||||
No passkeys registered. Add one for passwordless sign-in.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-0 shadow-none">
|
||||
<CardHeader className="pb-2 sm:pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-base sm:text-lg text-destructive">
|
||||
<LogOut className="h-4 w-4 sm:h-5 sm:w-5" />
|
||||
Sign Out
|
||||
</CardTitle>
|
||||
<CardDescription className="text-xs sm:text-sm">Sign out of your account</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button variant="destructive" onClick={logout} className="h-9 sm:h-10">
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Sign Out
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -17,7 +17,7 @@ export function ProviderSettings() {
|
||||
const [oauthDialogOpen, setOauthDialogOpen] = useState(false)
|
||||
const [oauthCallbackDialogOpen, setOauthCallbackDialogOpen] = useState(false)
|
||||
const [oauthResponse, setOauthResponse] = useState<OAuthAuthorizeResponse | null>(null)
|
||||
const [connectedExpanded, setConnectedExpanded] = useState(true)
|
||||
const [connectedExpanded, setConnectedExpanded] = useState(false)
|
||||
const [availableExpanded, setAvailableExpanded] = useState(false)
|
||||
const [availableSearch, setAvailableSearch] = useState('')
|
||||
const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false)
|
||||
@@ -173,7 +173,7 @@ export function ProviderSettings() {
|
||||
|
||||
return (
|
||||
<Card key={provider.id} className="bg-card border-border">
|
||||
<CardHeader className="p-4">
|
||||
<CardHeader className="p-2">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<CardTitle className="text-base">
|
||||
@@ -357,39 +357,36 @@ export function ProviderSettings() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 max-h-64 overflow-y-auto">
|
||||
<div className="space-y-2 max-h-64 overflow-y-auto scrollbar-thin pt-4 pb-1 pr-1 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{filteredAvailableProviders.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground py-2">
|
||||
{availableSearch ? 'No providers match your search.' : 'No available providers.'}
|
||||
</p>
|
||||
) : (
|
||||
filteredAvailableProviders.map((provider) => {
|
||||
filteredAvailableProviders.map((provider, index) => {
|
||||
const modelCount = Object.keys(provider.models || {}).length
|
||||
return (
|
||||
<Card key={provider.id} className="bg-card border-border">
|
||||
<CardHeader className="p-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<CardTitle className="text-sm truncate">
|
||||
{provider.name || provider.id}
|
||||
</CardTitle>
|
||||
{modelCount > 0 && (
|
||||
<CardDescription className="text-xs">
|
||||
{modelCount} model{modelCount !== 1 ? 's' : ''}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleAddApiKey(provider)}
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 mr-1" />
|
||||
Add Key
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<div key={provider.id} className={`flex items-center justify-between gap-2 py-1.5 px-2 rounded-md hover:bg-accent/80 transition-colors ${index % 2 === 1 ? 'bg-accent/30' : ''}`}>
|
||||
<div className="flex-1 min-w-0">
|
||||
<span className="text-sm truncate block">
|
||||
{provider.name || provider.id}
|
||||
</span>
|
||||
{modelCount > 0 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{modelCount} model{modelCount !== 1 ? 's' : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleAddApiKey(provider)}
|
||||
className="h-7 px-2"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 mr-1" />
|
||||
Add Key
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
|
||||
@@ -4,9 +4,10 @@ import { GitSettings } from '@/components/settings/GitSettings'
|
||||
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
|
||||
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
|
||||
import { ProviderSettings } from '@/components/settings/ProviderSettings'
|
||||
import { AccountSettings } from '@/components/settings/AccountSettings'
|
||||
import { Dialog, DialogContent } from '@/components/ui/dialog'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Settings2, Keyboard, Code, ChevronLeft, X, Key, GitBranch } from 'lucide-react'
|
||||
import { Settings2, Keyboard, Code, ChevronLeft, X, Key, GitBranch, User } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useSwipeBack } from '@/hooks/useMobile'
|
||||
|
||||
@@ -15,7 +16,7 @@ interface SettingsDialogProps {
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers'
|
||||
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account'
|
||||
|
||||
export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
|
||||
const [mobileView, setMobileView] = useState<SettingsView>('menu')
|
||||
@@ -39,6 +40,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
|
||||
}, [bindSwipe])
|
||||
|
||||
const menuItems = [
|
||||
{ id: 'account', icon: User, label: 'Account', description: 'Profile, passkeys, and sign out' },
|
||||
{ id: 'general', icon: Settings2, label: 'General Settings', description: 'App preferences and behavior' },
|
||||
{ id: 'git', icon: GitBranch, label: 'Git', description: 'Git identity and credentials for repositories' },
|
||||
{ id: 'shortcuts', icon: Keyboard, label: 'Keyboard Shortcuts', description: 'Customize keyboard shortcuts' },
|
||||
@@ -65,9 +67,12 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
|
||||
Settings
|
||||
</h2>
|
||||
</div>
|
||||
<Tabs defaultValue="general" className="w-full flex flex-col flex-1 min-h-0">
|
||||
<Tabs defaultValue="account" className="w-full flex flex-col flex-1 min-h-0">
|
||||
<div className="px-6 pt-6 pb-4 flex-shrink-0">
|
||||
<TabsList className="grid w-full grid-cols-5 bg-card border border-border p-1">
|
||||
<TabsList className="grid w-full grid-cols-6 bg-card p-1">
|
||||
<TabsTrigger value="account" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
|
||||
Account
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="general" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
|
||||
General
|
||||
</TabsTrigger>
|
||||
@@ -88,6 +93,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="px-6 pb-6">
|
||||
<TabsContent value="account" className="mt-0"><AccountSettings /></TabsContent>
|
||||
<TabsContent value="general" className="mt-0"><GeneralSettings /></TabsContent>
|
||||
<TabsContent value="git" className="mt-0"><GitSettings /></TabsContent>
|
||||
<TabsContent value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
|
||||
@@ -148,6 +154,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{mobileView === 'account' && <AccountSettings />}
|
||||
{mobileView === 'general' && <GeneralSettings />}
|
||||
{mobileView === 'git' && <GitSettings />}
|
||||
{mobileView === 'shortcuts' && <KeyboardShortcuts />}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import { createContext, useEffect, useState, useCallback, type ReactNode } from 'react'
|
||||
import { useSession, signIn, signUp, signOut, authClient, type AuthUser } from '@/lib/auth-client'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
|
||||
interface AuthConfig {
|
||||
enabledProviders: string[]
|
||||
registrationEnabled: boolean
|
||||
isFirstUser: boolean
|
||||
adminConfigured: boolean
|
||||
}
|
||||
|
||||
interface AuthContextValue {
|
||||
user: AuthUser | null
|
||||
isAuthenticated: boolean
|
||||
isLoading: boolean
|
||||
config: AuthConfig | null
|
||||
signInWithEmail: (email: string, password: string) => Promise<{ error?: string }>
|
||||
signInWithProvider: (provider: 'github' | 'google' | 'discord') => Promise<{ error?: string }>
|
||||
signInWithPasskey: () => Promise<{ error?: string }>
|
||||
signUpWithEmail: (email: string, password: string, name: string) => Promise<{ error?: string }>
|
||||
addPasskey: (name?: string) => Promise<{ error?: string }>
|
||||
logout: () => Promise<void>
|
||||
refreshSession: () => Promise<void>
|
||||
}
|
||||
|
||||
export const AuthContext = createContext<AuthContextValue | null>(null)
|
||||
|
||||
export { useAuth } from '@/hooks/useAuth'
|
||||
|
||||
interface AuthProviderProps {
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: AuthProviderProps) {
|
||||
const { data: session, isPending, refetch } = useSession()
|
||||
const [config, setConfig] = useState<AuthConfig | null>(null)
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
|
||||
useEffect(() => {
|
||||
const fetchConfig = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/auth-info/config')
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setConfig(data)
|
||||
}
|
||||
} catch {
|
||||
setConfig({
|
||||
enabledProviders: ['credentials'],
|
||||
registrationEnabled: true,
|
||||
isFirstUser: true,
|
||||
adminConfigured: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
fetchConfig()
|
||||
}, [])
|
||||
|
||||
const signInWithEmail = useCallback(async (email: string, password: string) => {
|
||||
const result = await signIn.email({ email, password })
|
||||
if (result.error) {
|
||||
return { error: result.error.message || 'Sign in failed' }
|
||||
}
|
||||
await refetch()
|
||||
const from = (location.state as { from?: string })?.from || '/'
|
||||
navigate(from, { replace: true })
|
||||
return {}
|
||||
}, [refetch, navigate, location])
|
||||
|
||||
const signInWithProvider = useCallback(async (provider: 'github' | 'google' | 'discord') => {
|
||||
try {
|
||||
await signIn.social({ provider, callbackURL: '/' })
|
||||
return {}
|
||||
} catch (err) {
|
||||
return { error: err instanceof Error ? err.message : 'OAuth sign in failed' }
|
||||
}
|
||||
}, [])
|
||||
|
||||
const signInWithPasskey = useCallback(async () => {
|
||||
try {
|
||||
const result = await authClient.signIn.passkey()
|
||||
if (result.error) {
|
||||
return { error: result.error.message || 'Passkey sign in failed' }
|
||||
}
|
||||
await refetch()
|
||||
const from = (location.state as { from?: string })?.from || '/'
|
||||
navigate(from, { replace: true })
|
||||
return {}
|
||||
} catch (err) {
|
||||
return { error: err instanceof Error ? err.message : 'Passkey sign in failed' }
|
||||
}
|
||||
}, [refetch, navigate, location])
|
||||
|
||||
const signUpWithEmail = useCallback(async (email: string, password: string, name: string) => {
|
||||
const result = await signUp.email({ email, password, name })
|
||||
if (result.error) {
|
||||
return { error: result.error.message || 'Sign up failed' }
|
||||
}
|
||||
await refetch()
|
||||
navigate('/', { replace: true })
|
||||
return {}
|
||||
}, [refetch, navigate])
|
||||
|
||||
const addPasskey = useCallback(async (name?: string) => {
|
||||
const result = await authClient.passkey.addPasskey({ name })
|
||||
if (result.error) {
|
||||
return { error: result.error.message || 'Failed to add passkey' }
|
||||
}
|
||||
return {}
|
||||
}, [])
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
useSettingsDialog.getState().close()
|
||||
await signOut()
|
||||
await refetch()
|
||||
navigate('/login', { replace: true })
|
||||
}, [refetch, navigate])
|
||||
|
||||
const refreshSession = useCallback(async () => {
|
||||
await refetch()
|
||||
}, [refetch])
|
||||
|
||||
const value: AuthContextValue = {
|
||||
user: session?.user ?? null,
|
||||
isAuthenticated: !!session?.user,
|
||||
isLoading: isPending,
|
||||
config,
|
||||
signInWithEmail,
|
||||
signInWithProvider,
|
||||
signInWithPasskey,
|
||||
signUpWithEmail,
|
||||
addPasskey,
|
||||
logout,
|
||||
refreshSession,
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={value}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useContext } from 'react'
|
||||
import { AuthContext } from '@/contexts/AuthContext'
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext)
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider')
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
import type { paths, components } from "../api/opencode-types";
|
||||
import { parseNetworkError } from "../lib/opencode-errors";
|
||||
import { showToast } from "../lib/toast";
|
||||
import { useSessionStatus } from "../stores/sessionStatusStore";
|
||||
|
||||
const titleGeneratingSessionsState = new Set<string>();
|
||||
const titleGeneratingListeners = new Set<() => void>();
|
||||
@@ -209,6 +210,7 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
const hasInitializedRef = useRef<Set<string>>(new Set());
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
|
||||
const generateSessionTitle = async (sessionID: string, userPromptText: string) => {
|
||||
if (!client || hasInitializedRef.current.has(sessionID)) return;
|
||||
@@ -265,6 +267,8 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
}) => {
|
||||
if (!client) throw new Error("No client available");
|
||||
|
||||
setSessionStatus(sessionID, { type: "busy" });
|
||||
|
||||
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
|
||||
|
||||
const contentParts = parts || [{ type: "text" as const, content: prompt || "", name: "" }];
|
||||
@@ -326,6 +330,7 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
},
|
||||
onError: (error, variables) => {
|
||||
const { sessionID } = variables;
|
||||
setSessionStatus(sessionID, { type: "idle" });
|
||||
queryClient.setQueryData<MessageListResponse>(
|
||||
["opencode", "messages", opcodeUrl, sessionID, directory],
|
||||
(old) => old?.filter((msg) => !msg.info.id.startsWith("optimistic_")),
|
||||
@@ -483,6 +488,7 @@ export const useAbortSession = (
|
||||
export const useSendShell = (opcodeUrl: string | null | undefined, directory?: string) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
@@ -496,6 +502,8 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s
|
||||
}) => {
|
||||
if (!client) throw new Error("No client available");
|
||||
|
||||
setSessionStatus(sessionID, { type: "busy" });
|
||||
|
||||
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
|
||||
|
||||
const userMessage = createOptimisticUserMessage(
|
||||
@@ -517,6 +525,7 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s
|
||||
},
|
||||
onError: (_, variables) => {
|
||||
const { sessionID } = variables;
|
||||
setSessionStatus(sessionID, { type: "idle" });
|
||||
queryClient.setQueryData<MessageListResponse>(
|
||||
["opencode", "messages", opcodeUrl, sessionID, directory],
|
||||
(old) => old?.filter((msg) => !msg.info.id.startsWith("optimistic_")),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { createOpenCodeClient } from '@/api/opencode'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import type { MessageWithParts, MessageListResponse } from '@/api/types'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
|
||||
interface UseRemoveMessageOptions {
|
||||
opcodeUrl: string | null
|
||||
@@ -68,6 +69,7 @@ interface UseRefreshMessageOptions {
|
||||
export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefreshMessageOptions) {
|
||||
const queryClient = useQueryClient()
|
||||
const removeMessage = useRemoveMessage({ opcodeUrl, sessionId, directory })
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus)
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
@@ -83,6 +85,8 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres
|
||||
}) => {
|
||||
if (!opcodeUrl) throw new Error('OpenCode URL not available')
|
||||
|
||||
setSessionStatus(sessionId, { type: 'busy' })
|
||||
|
||||
await removeMessage.mutateAsync({ messageID: assistantMessageID })
|
||||
|
||||
const client = createOpenCodeClient(opcodeUrl, directory)
|
||||
@@ -142,8 +146,9 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres
|
||||
queryKey: ['opencode', 'session', opcodeUrl, sessionId, directory]
|
||||
})
|
||||
},
|
||||
onError: (error, variables) => {
|
||||
onError: (_, variables) => {
|
||||
void variables
|
||||
setSessionStatus(sessionId, { type: 'idle' })
|
||||
queryClient.setQueryData<MessageListResponse>(
|
||||
['opencode', 'messages', opcodeUrl, sessionId, directory],
|
||||
(old) => {
|
||||
@@ -155,7 +160,6 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres
|
||||
return messages
|
||||
}
|
||||
)
|
||||
console.error('Failed to refresh message:', error)
|
||||
showToast.error('Failed to refresh message')
|
||||
}
|
||||
})
|
||||
|
||||
@@ -333,3 +333,27 @@ body {
|
||||
color: var(--color-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
/* Custom scrollbar styling */
|
||||
.scrollbar-thin {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--color-border) transparent;
|
||||
}
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar-thumb {
|
||||
background-color: var(--color-border);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.scrollbar-thin::-webkit-scrollbar-thumb:hover {
|
||||
background-color: var(--color-muted-foreground);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { createAuthClient } from 'better-auth/react'
|
||||
import { passkeyClient } from '@better-auth/passkey/client'
|
||||
|
||||
const getBaseUrl = () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
return `${window.location.origin}/api/auth`
|
||||
}
|
||||
return 'http://localhost:5001/api/auth'
|
||||
}
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: getBaseUrl(),
|
||||
plugins: [passkeyClient()],
|
||||
})
|
||||
|
||||
export const {
|
||||
signIn,
|
||||
signUp,
|
||||
signOut,
|
||||
useSession,
|
||||
getSession,
|
||||
changePassword,
|
||||
} = authClient
|
||||
|
||||
export const passkey = authClient.passkey
|
||||
|
||||
export type AuthSession = typeof authClient.$Infer.Session
|
||||
export type AuthUser = AuthSession['user']
|
||||
@@ -0,0 +1,87 @@
|
||||
import { redirect } from 'react-router-dom'
|
||||
import { getSession } from './auth-client'
|
||||
|
||||
export interface AuthConfig {
|
||||
enabledProviders: string[]
|
||||
registrationEnabled: boolean
|
||||
isFirstUser: boolean
|
||||
adminConfigured: boolean
|
||||
}
|
||||
|
||||
async function fetchAuthConfig(): Promise<AuthConfig> {
|
||||
const response = await fetch('/api/auth-info/config')
|
||||
if (!response.ok) {
|
||||
return {
|
||||
enabledProviders: ['credentials'],
|
||||
registrationEnabled: true,
|
||||
isFirstUser: false,
|
||||
adminConfigured: false,
|
||||
}
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
export async function loginLoader() {
|
||||
const [config, session] = await Promise.all([
|
||||
fetchAuthConfig(),
|
||||
getSession(),
|
||||
])
|
||||
|
||||
if (session.data?.user) {
|
||||
return redirect('/')
|
||||
}
|
||||
|
||||
if (config.isFirstUser && !config.adminConfigured) {
|
||||
return redirect('/setup')
|
||||
}
|
||||
|
||||
return { config }
|
||||
}
|
||||
|
||||
export async function setupLoader() {
|
||||
const [config, session] = await Promise.all([
|
||||
fetchAuthConfig(),
|
||||
getSession(),
|
||||
])
|
||||
|
||||
if (session.data?.user) {
|
||||
return redirect('/')
|
||||
}
|
||||
|
||||
if (!config.isFirstUser || config.adminConfigured) {
|
||||
return redirect('/login')
|
||||
}
|
||||
|
||||
return { config }
|
||||
}
|
||||
|
||||
export async function registerLoader() {
|
||||
const [config, session] = await Promise.all([
|
||||
fetchAuthConfig(),
|
||||
getSession(),
|
||||
])
|
||||
|
||||
if (session.data?.user) {
|
||||
return redirect('/')
|
||||
}
|
||||
|
||||
if (!config.registrationEnabled) {
|
||||
return redirect('/login')
|
||||
}
|
||||
|
||||
if (config.isFirstUser && !config.adminConfigured) {
|
||||
return redirect('/setup')
|
||||
}
|
||||
|
||||
return { config }
|
||||
}
|
||||
|
||||
export async function protectedLoader() {
|
||||
const session = await getSession()
|
||||
|
||||
if (!session.data?.user) {
|
||||
return redirect('/login')
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import { useState } from 'react'
|
||||
import { Link, useLoaderData } from 'react-router-dom'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useTheme } from '@/hooks/useTheme'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Loader2, Github, KeyRound, Mail, AlertCircle } from 'lucide-react'
|
||||
import type { AuthConfig } from '@/lib/auth-loaders'
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email('Invalid email address'),
|
||||
password: z.string().min(1, 'Password is required'),
|
||||
})
|
||||
|
||||
type LoginFormData = z.infer<typeof loginSchema>
|
||||
|
||||
export function Login() {
|
||||
const { signInWithEmail, signInWithProvider, signInWithPasskey } = useAuth()
|
||||
const { config } = useLoaderData() as { config: AuthConfig }
|
||||
const theme = useTheme()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [oauthLoading, setOauthLoading] = useState<string | null>(null)
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<LoginFormData>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
})
|
||||
|
||||
const onSubmit = async (data: LoginFormData) => {
|
||||
setError(null)
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const result = await signInWithEmail(data.email, data.password)
|
||||
if (result.error) {
|
||||
setError(result.error)
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleOAuth = async (provider: 'github' | 'google' | 'discord') => {
|
||||
setError(null)
|
||||
setOauthLoading(provider)
|
||||
try {
|
||||
const result = await signInWithProvider(provider)
|
||||
if (result.error) {
|
||||
setError(result.error)
|
||||
}
|
||||
} finally {
|
||||
setOauthLoading(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePasskey = async () => {
|
||||
setError(null)
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const result = await signInWithPasskey()
|
||||
if (result.error) {
|
||||
setError(result.error)
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const hasOAuth = config.enabledProviders.some(p => ['github', 'google', 'discord'].includes(p))
|
||||
const hasPasskey = config.enabledProviders.includes('passkey')
|
||||
const hasCredentials = config.enabledProviders.includes('credentials')
|
||||
|
||||
return (
|
||||
<div className="h-dvh flex flex-col items-center justify-center bg-gradient-to-br from-background via-background to-background p-4">
|
||||
<div className="w-full max-w-sm space-y-6">
|
||||
<div className="flex flex-col items-center space-y-2">
|
||||
<img
|
||||
src={theme === 'light' ? "/opencode-wordmark-light.svg" : "/opencode-wordmark-dark.svg"}
|
||||
alt="OpenCode"
|
||||
className="h-8 w-auto"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">Sign in to continue</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-border bg-card p-6 space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{hasPasskey && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full border-border hover:bg-accent transition-all duration-200"
|
||||
onClick={handlePasskey}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<KeyRound className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Sign in with Passkey
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{hasOAuth && (
|
||||
<div className="space-y-2">
|
||||
{config.enabledProviders.includes('github') && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full border-border hover:bg-accent transition-all duration-200"
|
||||
onClick={() => handleOAuth('github')}
|
||||
disabled={!!oauthLoading}
|
||||
>
|
||||
{oauthLoading === 'github' ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Github className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Continue with GitHub
|
||||
</Button>
|
||||
)}
|
||||
{config.enabledProviders.includes('google') && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full border-border hover:bg-accent transition-all duration-200"
|
||||
onClick={() => handleOAuth('google')}
|
||||
disabled={!!oauthLoading}
|
||||
>
|
||||
{oauthLoading === 'google' ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<svg className="mr-2 h-4 w-4" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
|
||||
/>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
|
||||
/>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
|
||||
/>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
Continue with Google
|
||||
</Button>
|
||||
)}
|
||||
{config.enabledProviders.includes('discord') && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full border-border hover:bg-accent transition-all duration-200"
|
||||
onClick={() => handleOAuth('discord')}
|
||||
disabled={!!oauthLoading}
|
||||
>
|
||||
{oauthLoading === 'discord' ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<svg className="mr-2 h-4 w-4" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
Continue with Discord
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasCredentials && (hasOAuth || hasPasskey) && (
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t border-border" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-card px-2 text-muted-foreground">Or continue with email</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasCredentials && (
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email" className="text-sm text-muted-foreground">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
className="bg-input border-border focus:border-primary"
|
||||
{...register('email')}
|
||||
aria-invalid={!!errors.email}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p className="text-sm text-destructive">{errors.email.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password" className="text-sm text-muted-foreground">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Enter your password"
|
||||
className="bg-input border-border focus:border-primary"
|
||||
{...register('password')}
|
||||
aria-invalid={!!errors.password}
|
||||
/>
|
||||
{errors.password && (
|
||||
<p className="text-sm text-destructive">{errors.password.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={isSubmitting}>
|
||||
{isSubmitting ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Mail className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Sign In
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{config.registrationEnabled && (
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
Don't have an account?{' '}
|
||||
<Link to="/register" className="text-primary hover:underline transition-colors">
|
||||
Sign up
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useState } from 'react'
|
||||
import { Link, useLoaderData } from 'react-router-dom'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useTheme } from '@/hooks/useTheme'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Loader2, UserPlus, AlertCircle } from 'lucide-react'
|
||||
import type { AuthConfig } from '@/lib/auth-loaders'
|
||||
|
||||
const registerSchema = z.object({
|
||||
name: z.string().min(2, 'Name must be at least 2 characters'),
|
||||
email: z.string().email('Invalid email address'),
|
||||
password: z.string().min(8, 'Password must be at least 8 characters'),
|
||||
confirmPassword: z.string(),
|
||||
}).refine((data) => data.password === data.confirmPassword, {
|
||||
message: "Passwords don't match",
|
||||
path: ['confirmPassword'],
|
||||
})
|
||||
|
||||
type RegisterFormData = z.infer<typeof registerSchema>
|
||||
|
||||
export function Register() {
|
||||
const { signUpWithEmail } = useAuth()
|
||||
const { config } = useLoaderData() as { config: AuthConfig }
|
||||
const theme = useTheme()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<RegisterFormData>({
|
||||
resolver: zodResolver(registerSchema),
|
||||
})
|
||||
|
||||
const onSubmit = async (data: RegisterFormData) => {
|
||||
setError(null)
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const result = await signUpWithEmail(data.email, data.password, data.name)
|
||||
if (result.error) {
|
||||
setError(result.error)
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-dvh flex flex-col items-center justify-center bg-gradient-to-br from-background via-background to-background p-4">
|
||||
<div className="w-full max-w-sm space-y-6">
|
||||
<div className="flex flex-col items-center space-y-2">
|
||||
<img
|
||||
src={theme === 'light' ? "/opencode-wordmark-light.svg" : "/opencode-wordmark-dark.svg"}
|
||||
alt="OpenCode"
|
||||
className="h-8 w-auto"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{config.isFirstUser
|
||||
? 'Create the first admin account'
|
||||
: 'Create your account'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-border bg-card p-6 space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name" className="text-sm text-muted-foreground">Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
type="text"
|
||||
placeholder="Your name"
|
||||
className="bg-input border-border focus:border-primary"
|
||||
{...register('name')}
|
||||
aria-invalid={!!errors.name}
|
||||
/>
|
||||
{errors.name && (
|
||||
<p className="text-sm text-destructive">{errors.name.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email" className="text-sm text-muted-foreground">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
className="bg-input border-border focus:border-primary"
|
||||
{...register('email')}
|
||||
aria-invalid={!!errors.email}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p className="text-sm text-destructive">{errors.email.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password" className="text-sm text-muted-foreground">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="At least 8 characters"
|
||||
className="bg-input border-border focus:border-primary"
|
||||
{...register('password')}
|
||||
aria-invalid={!!errors.password}
|
||||
/>
|
||||
{errors.password && (
|
||||
<p className="text-sm text-destructive">{errors.password.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword" className="text-sm text-muted-foreground">Confirm Password</Label>
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
placeholder="Confirm your password"
|
||||
className="bg-input border-border focus:border-primary"
|
||||
{...register('confirmPassword')}
|
||||
aria-invalid={!!errors.confirmPassword}
|
||||
/>
|
||||
{errors.confirmPassword && (
|
||||
<p className="text-sm text-destructive">{errors.confirmPassword.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={isSubmitting}>
|
||||
{isSubmitting ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<UserPlus className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{config.isFirstUser ? 'Create Admin Account' : 'Create Account'}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
Already have an account?{' '}
|
||||
<Link to="/login" className="text-primary hover:underline transition-colors">
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Header } from '@/components/ui/header'
|
||||
import { GeneralSettings } from '@/components/settings/GeneralSettings'
|
||||
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
|
||||
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
|
||||
|
||||
export function Settings() {
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-background via-background to-background">
|
||||
<Header>
|
||||
<Header.BackButton to="/" />
|
||||
<Header.Title>Settings</Header.Title>
|
||||
<Header.Settings />
|
||||
</Header>
|
||||
|
||||
<div className="max-w-4xl mx-auto p-6">
|
||||
<Tabs defaultValue="general" className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-3 mb-8">
|
||||
<TabsTrigger value="general">General</TabsTrigger>
|
||||
<TabsTrigger value="shortcuts">Shortcuts</TabsTrigger>
|
||||
<TabsTrigger value="opencode">OpenCode</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="general">
|
||||
<GeneralSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="shortcuts">
|
||||
<KeyboardShortcuts />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="opencode">
|
||||
<OpenCodeConfigManager />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="commands">
|
||||
<div className="border border-border rounded-lg p-8 text-center">
|
||||
<p className="text-muted-foreground">Commands manager coming soon</p>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="agents">
|
||||
<div className="border border-border rounded-lg p-8 text-center">
|
||||
<p className="text-muted-foreground">Agents manager coming soon</p>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useTheme } from '@/hooks/useTheme'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Loader2, UserPlus, AlertCircle } from 'lucide-react'
|
||||
|
||||
const setupSchema = z.object({
|
||||
name: z.string().min(2, 'Name must be at least 2 characters'),
|
||||
email: z.string().email('Invalid email address'),
|
||||
password: z.string().min(8, 'Password must be at least 8 characters'),
|
||||
})
|
||||
|
||||
type SetupFormData = z.infer<typeof setupSchema>
|
||||
|
||||
export function Setup() {
|
||||
const { signUpWithEmail } = useAuth()
|
||||
const theme = useTheme()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<SetupFormData>({
|
||||
resolver: zodResolver(setupSchema),
|
||||
})
|
||||
|
||||
const onSubmit = async (data: SetupFormData) => {
|
||||
setError(null)
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const result = await signUpWithEmail(data.email, data.password, data.name)
|
||||
if (result.error) {
|
||||
setError(result.error)
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-dvh flex flex-col items-center justify-center bg-gradient-to-br from-background via-background to-background p-4">
|
||||
<div className="w-full max-w-sm space-y-6">
|
||||
<div className="flex flex-col items-center space-y-2">
|
||||
<img
|
||||
src={theme === 'light' ? "/opencode-wordmark-light.svg" : "/opencode-wordmark-dark.svg"}
|
||||
alt="OpenCode"
|
||||
className="h-8 w-auto"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">Create Admin Account</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-border bg-card p-6 space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name" className="text-sm text-muted-foreground">Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
type="text"
|
||||
placeholder="Your name"
|
||||
className="bg-input border-border focus:border-primary"
|
||||
{...register('name')}
|
||||
aria-invalid={!!errors.name}
|
||||
/>
|
||||
{errors.name && (
|
||||
<p className="text-sm text-destructive">{errors.name.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email" className="text-sm text-muted-foreground">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="admin@example.com"
|
||||
className="bg-input border-border focus:border-primary"
|
||||
{...register('email')}
|
||||
aria-invalid={!!errors.email}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p className="text-sm text-destructive">{errors.email.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password" className="text-sm text-muted-foreground">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="At least 8 characters"
|
||||
className="bg-input border-border focus:border-primary"
|
||||
{...register('password')}
|
||||
aria-invalid={!!errors.password}
|
||||
/>
|
||||
{errors.password && (
|
||||
<p className="text-sm text-destructive">{errors.password.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={isSubmitting}>
|
||||
{isSubmitting ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<UserPlus className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Create Admin Account
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user