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:
Chris Scott authored and GitHub committed 2026-01-24 17:45:44 -05:00
1 parent af292758c3
commit 81a66d2ddb
29 files changed
+2324 -149

No files matched your search

+29
View File
@@ -46,6 +46,35 @@ MAX_UPLOAD_SIZE_MB=50
# ============================================
DEBUG=false
# ============================================
# Authentication (Better Auth)
# ============================================
# AUTH_SECRET is required for production deployments
# Generate with: openssl rand -base64 32
# AUTH_SECRET=your-secure-random-secret-here
# Admin Account (optional - for pre-configured single-user mode)
# When set, admin user is created on first startup and self-registration is disabled
# ADMIN_EMAIL=admin@example.com
# ADMIN_PASSWORD=your-secure-password
# Password Reset (set to true to force password update from ADMIN_PASSWORD)
# Remove after resetting password
# ADMIN_PASSWORD_RESET=false
# OAuth Providers (optional - enable by providing client ID and secret)
# GITHUB_CLIENT_ID=
# GITHUB_CLIENT_SECRET=
# GOOGLE_CLIENT_ID=
# GOOGLE_CLIENT_SECRET=
# DISCORD_CLIENT_ID=
# DISCORD_CLIENT_SECRET=
# Passkey/WebAuthn Configuration
PASSKEY_RP_ID=localhost
PASSKEY_RP_NAME=OpenCode Manager
PASSKEY_ORIGIN=http://localhost:5173
# ============================================
# Frontend Configuration (Vite)
# These are optional - frontend uses defaults if not set
+14
View File
@@ -5,6 +5,20 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Features
- Add single-user authentication system with first-run admin setup
- Add dedicated Setup page for initial admin account creation
- Add environment variable support for pre-configured admin (`ADMIN_EMAIL`, `ADMIN_PASSWORD`)
- Add password reset via `ADMIN_PASSWORD_RESET=true` environment flag
- Add `adminConfigured` flag to auth config API for frontend routing
- Login page now redirects to Setup when no users exist and admin is not pre-configured
- Registration is automatically disabled when admin credentials are configured via environment
### Changed
- Auth config endpoint now returns `adminConfigured` boolean indicating env-based admin setup
## [0.7.4] - 2026-01-24
### Features
+98 -4
View File
@@ -48,6 +48,14 @@ Mobile-first web interface for OpenCode AI agents. Manage, control, and code wit
- **Server Templates** - Pre-built templates for common MCP servers
- **Enable/Disable Servers** - Toggle servers on/off with auto-restart
### Authentication
- **Single-User Mode** - Designed for personal/single-user deployments
- **First-Run Setup** - Guided admin account creation on first launch
- **Passkey Support** - WebAuthn/passkey authentication for passwordless login
- **OAuth Providers** - Optional GitHub, Google, Discord login (requires configuration)
- **Environment-Based Admin** - Pre-configure admin credentials via environment variables
- **Password Reset** - Reset password via environment variable flag
### Settings & Customization
- **Theme Selection** - Dark, Light, or System theme
- **Keyboard Shortcuts** - Customizable keyboard shortcuts
@@ -101,10 +109,6 @@ Mobile-first web interface for OpenCode AI agents. Manage, control, and code wit
</tr>
</table>
## Coming Soon
- **Authentication** - User authentication and session management
See the [Roadmap](ROADMAP.md) for planned features and future development.
## Installation
@@ -192,6 +196,96 @@ OpenCode Manager creates a default `AGENTS.md` file in the workspace config dire
This file is merged with any repository-specific `AGENTS.md` files, with repository instructions taking precedence for their respective codebases.
### Authentication Setup
OpenCode Manager uses a single-user authentication system. On first launch, you'll be prompted to create an admin account.
#### AUTH_SECRET (Required for Production)
The `AUTH_SECRET` environment variable is required for production deployments for session encryption and security. Generate a secure random secret:
```bash
# Generate a secure random secret
openssl rand -base64 32
```
Then add it to your environment configuration:
```bash
# In docker-compose.yml or .env
AUTH_SECRET=your-secure-random-secret-here
```
**Important:** Never commit the AUTH_SECRET to version control. Use different secrets for development and production environments.
#### First-Run Setup (Interactive)
1. Start the application
2. Navigate to the web interface
3. You'll be redirected to the Setup page
4. Create your admin account with name, email, and password
5. Optionally add a passkey for passwordless login in Settings
#### Pre-Configured Admin (Environment Variables)
For automated deployments, you can pre-configure the admin account:
```bash
# In docker-compose.yml or .env
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=your-secure-password
```
When these are set:
- The admin user is created automatically on first startup
- Self-registration is disabled (single-user mode)
- Users must log in with the configured credentials
#### Password Reset
If you forget your password, reset it via environment variables:
```bash
# Set the new password and enable reset
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=new-secure-password
ADMIN_PASSWORD_RESET=true
```
1. Set `ADMIN_PASSWORD_RESET=true` along with the new password
2. Restart the application
3. Log in with the new password
4. **Important:** Remove `ADMIN_PASSWORD_RESET=true` from your environment after resetting
#### OAuth Providers (Optional)
To enable social login, configure OAuth credentials:
```bash
# GitHub OAuth
GITHUB_CLIENT_ID=your-client-id
GITHUB_CLIENT_SECRET=your-client-secret
# Google OAuth
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
# Discord OAuth
DISCORD_CLIENT_ID=your-client-id
DISCORD_CLIENT_SECRET=your-client-secret
```
#### Passkey Configuration
For passkey/WebAuthn support, configure your domain:
```bash
# Production example
PASSKEY_RP_ID=yourdomain.com
PASSKEY_RP_NAME=OpenCode Manager
PASSKEY_ORIGIN=https://yourdomain.com
```
### Option 2: Local Development (Contributors)
For contributors who want to develop locally instead of using Docker.
+2
View File
@@ -15,9 +15,11 @@
"lint:fix": "eslint . --ext .ts --fix"
},
"dependencies": {
"@better-auth/passkey": "^1.4.17",
"@hono/node-server": "^1.19.5",
"@opencode-manager/shared": "workspace:*",
"archiver": "^7.0.1",
"better-auth": "^1.4.17",
"dotenv": "^17.2.3",
"eventsource": "^4.1.0",
"hono": "^4.10.1",
+102
View File
@@ -0,0 +1,102 @@
import { betterAuth } from 'better-auth'
import { passkey } from '@better-auth/passkey'
import { Database } from 'bun:sqlite'
import { ENV } from '@opencode-manager/shared/config/env'
export type AuthInstance = ReturnType<typeof createAuth>
export function createAuth(db: Database) {
const socialProviders: Record<string, { clientId: string; clientSecret: string }> = {}
if (ENV.AUTH.GITHUB_CLIENT_ID && ENV.AUTH.GITHUB_CLIENT_SECRET) {
socialProviders.github = {
clientId: ENV.AUTH.GITHUB_CLIENT_ID,
clientSecret: ENV.AUTH.GITHUB_CLIENT_SECRET,
}
}
if (ENV.AUTH.GOOGLE_CLIENT_ID && ENV.AUTH.GOOGLE_CLIENT_SECRET) {
socialProviders.google = {
clientId: ENV.AUTH.GOOGLE_CLIENT_ID,
clientSecret: ENV.AUTH.GOOGLE_CLIENT_SECRET,
}
}
if (ENV.AUTH.DISCORD_CLIENT_ID && ENV.AUTH.DISCORD_CLIENT_SECRET) {
socialProviders.discord = {
clientId: ENV.AUTH.DISCORD_CLIENT_ID,
clientSecret: ENV.AUTH.DISCORD_CLIENT_SECRET,
}
}
const auth = betterAuth({
database: db,
secret: ENV.AUTH.SECRET,
trustedOrigins: ENV.AUTH.TRUSTED_ORIGINS.split(',').map(o => o.trim()),
emailAndPassword: {
enabled: true,
minPasswordLength: 8,
maxPasswordLength: 128,
autoSignIn: true,
},
socialProviders: Object.keys(socialProviders).length > 0 ? socialProviders : undefined,
plugins: [
passkey({
rpID: ENV.AUTH.PASSKEY_RP_ID,
rpName: ENV.AUTH.PASSKEY_RP_NAME,
origin: ENV.AUTH.PASSKEY_ORIGIN,
authenticatorSelection: {
residentKey: 'required',
userVerification: 'preferred',
},
}),
],
session: {
expiresIn: 60 * 60 * 24 * 7,
updateAge: 60 * 60 * 24,
cookieCache: {
enabled: true,
maxAge: 60 * 5,
},
},
user: {
additionalFields: {
role: {
type: 'string',
required: false,
defaultValue: 'user',
input: false,
},
},
},
advanced: {
cookiePrefix: 'opencode',
useSecureCookies: ENV.SERVER.NODE_ENV === 'production',
},
})
return auth
}
export type Session = {
session: {
id: string
userId: string
token: string
expiresAt: Date
createdAt: Date
updatedAt: Date
ipAddress?: string | null
userAgent?: string | null
}
user: {
id: string
name: string
email: string
emailVerified: boolean
image?: string | null
createdAt: Date
updatedAt: Date
role?: string
}
}
+77
View File
@@ -0,0 +1,77 @@
import { createMiddleware } from 'hono/factory'
import type { AuthInstance, Session } from './index'
export function createAuthMiddleware(auth: AuthInstance) {
return createMiddleware<{
Variables: {
session: Session['session']
user: Session['user']
}
}>(async (c, next) => {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (!session) {
return c.json({ error: 'Unauthorized' }, 401)
}
c.set('session', session.session as Session['session'])
c.set('user', session.user as Session['user'])
await next()
})
}
export function createOptionalAuthMiddleware(auth: AuthInstance) {
return createMiddleware<{
Variables: {
session: Session['session'] | null
user: Session['user'] | null
}
}>(async (c, next) => {
try {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (session) {
c.set('session', session.session as Session['session'])
c.set('user', session.user as Session['user'])
} else {
c.set('session', null)
c.set('user', null)
}
} catch {
c.set('session', null)
c.set('user', null)
}
await next()
})
}
export function createAdminMiddleware(auth: AuthInstance) {
return createMiddleware<{
Variables: {
session: Session['session']
user: Session['user']
}
}>(async (c, next) => {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (!session) {
return c.json({ error: 'Unauthorized' }, 401)
}
const user = session.user as Session['user']
if (user.role !== 'admin') {
return c.json({ error: 'Forbidden: Admin access required' }, 403)
}
c.set('session', session.session as Session['session'])
c.set('user', user)
await next()
})
}
+73 -1
View File
@@ -48,11 +48,83 @@ export function initializeDatabase(dbPath: string = './data/opencode.db'): Datab
CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id);
CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default);
-- Better Auth tables
CREATE TABLE IF NOT EXISTS "user" (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
emailVerified INTEGER NOT NULL DEFAULT 0,
image TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
role TEXT DEFAULT 'user'
);
CREATE TABLE IF NOT EXISTS "session" (
id TEXT PRIMARY KEY NOT NULL,
expiresAt INTEGER NOT NULL,
token TEXT NOT NULL UNIQUE,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
ipAddress TEXT,
userAgent TEXT,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_session_userId ON "session"(userId);
CREATE INDEX IF NOT EXISTS idx_session_token ON "session"(token);
CREATE TABLE IF NOT EXISTS "account" (
id TEXT PRIMARY KEY NOT NULL,
accountId TEXT NOT NULL,
providerId TEXT NOT NULL,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
accessToken TEXT,
refreshToken TEXT,
idToken TEXT,
accessTokenExpiresAt INTEGER,
refreshTokenExpiresAt INTEGER,
scope TEXT,
password TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_account_userId ON "account"(userId);
CREATE UNIQUE INDEX IF NOT EXISTS idx_account_provider ON "account"(providerId, accountId);
CREATE TABLE IF NOT EXISTS "verification" (
id TEXT PRIMARY KEY NOT NULL,
identifier TEXT NOT NULL,
value TEXT NOT NULL,
expiresAt INTEGER NOT NULL,
createdAt INTEGER,
updatedAt INTEGER
);
CREATE INDEX IF NOT EXISTS idx_verification_identifier ON "verification"(identifier);
CREATE TABLE IF NOT EXISTS "passkey" (
id TEXT PRIMARY KEY NOT NULL,
name TEXT,
publicKey TEXT NOT NULL,
userId TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
credentialID TEXT NOT NULL,
counter INTEGER NOT NULL,
deviceType TEXT NOT NULL,
backedUp INTEGER NOT NULL DEFAULT 0,
transports TEXT,
createdAt INTEGER,
aaguid TEXT
);
CREATE INDEX IF NOT EXISTS idx_passkey_userId ON "passkey"(userId);
CREATE INDEX IF NOT EXISTS idx_passkey_credentialID ON "passkey"(credentialID);
`)
runMigrations(db)
// Force database file creation by performing a write
db.prepare('INSERT OR IGNORE INTO user_preferences (user_id, preferences, updated_at) VALUES (?, ?, ?)')
.run('default', '{}', Date.now())
+33 -10
View File
@@ -16,6 +16,9 @@ import { createProvidersRoutes } from './routes/providers'
import { createOAuthRoutes } from './routes/oauth'
import { createTitleRoutes } from './routes/title'
import { createSSERoutes } from './routes/sse'
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
import { createAuth } from './auth'
import { createAuthMiddleware } from './auth/middleware'
import { sseAggregator } from './services/sse-aggregator'
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
import { SettingsService } from './services/settings'
@@ -47,6 +50,8 @@ app.use('/*', cors({
}))
const db = initializeDatabase(DB_PATH)
const auth = createAuth(db)
const requireAuth = createAuthMiddleware(auth)
let ipcServer: IPCServer | undefined
const gitAuthService = new GitAuthService()
@@ -208,6 +213,13 @@ async function ensureDefaultAgentsMdExists(): Promise<void> {
}
try {
if (ENV.SERVER.NODE_ENV === 'production' && !ENV.AUTH.SECRET) {
logger.error('AUTH_SECRET is required in production mode')
logger.error('Generate one with: openssl rand -base64 32')
logger.error('Set it as environment variable: AUTH_SECRET=your-secret')
process.exit(1)
}
await ensureDirectoryExists(getWorkspacePath())
await ensureDirectoryExists(getReposPath())
await ensureDirectoryExists(getConfigPath())
@@ -231,21 +243,32 @@ try {
opencodeServerManager.setDatabase(db)
await opencodeServerManager.start()
logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`)
await syncAdminFromEnv(auth, db)
} catch (error) {
logger.error('Failed to initialize workspace:', error)
}
app.route('/api/repos', createRepoRoutes(db, gitAuthService))
app.route('/api/settings', createSettingsRoutes(db))
app.route('/api/health', createHealthRoutes(db))
app.route('/api/files', createFileRoutes())
app.route('/api/providers', createProvidersRoutes())
app.route('/api/oauth', createOAuthRoutes())
app.route('/api/tts', createTTSRoutes(db))
app.route('/api/generate-title', createTitleRoutes())
app.route('/api/sse', createSSERoutes())
app.route('/api/auth', createAuthRoutes(auth, db))
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
app.all('/api/opencode/*', async (c) => {
app.route('/api/health', createHealthRoutes(db))
const protectedApi = new Hono()
protectedApi.use('/*', requireAuth)
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService))
protectedApi.route('/settings', createSettingsRoutes(db))
protectedApi.route('/files', createFileRoutes())
protectedApi.route('/providers', createProvidersRoutes())
protectedApi.route('/oauth', createOAuthRoutes())
protectedApi.route('/tts', createTTSRoutes(db))
protectedApi.route('/generate-title', createTitleRoutes())
protectedApi.route('/sse', createSSERoutes())
app.route('/api', protectedApi)
app.all('/api/opencode/*', requireAuth, async (c) => {
const request = c.req.raw
return proxyRequest(request)
})
+112
View File
@@ -0,0 +1,112 @@
import { Hono } from 'hono'
import type { AuthInstance } from '../auth'
import { Database } from 'bun:sqlite'
import { ENV } from '@opencode-manager/shared/config/env'
import { logger } from '../utils/logger'
export function createAuthRoutes(auth: AuthInstance, _db: Database) {
const app = new Hono()
app.all('/*', async (c) => {
return auth.handler(c.req.raw)
})
return app
}
const isAdminConfigured = (): boolean => {
return !!(ENV.AUTH.ADMIN_EMAIL && ENV.AUTH.ADMIN_PASSWORD)
}
export async function syncAdminFromEnv(auth: AuthInstance, db: Database): Promise<void> {
if (!isAdminConfigured()) return
const adminEmail = ENV.AUTH.ADMIN_EMAIL!
const adminPassword = ENV.AUTH.ADMIN_PASSWORD!
const existingUser = db.prepare('SELECT id, email FROM "user" WHERE email = ?').get(adminEmail) as { id: string; email: string } | undefined
if (existingUser) {
if (ENV.AUTH.ADMIN_PASSWORD_RESET) {
const hashedPassword = await Bun.password.hash(adminPassword, {
algorithm: 'bcrypt',
cost: 10,
})
db.prepare('UPDATE "account" SET password = ? WHERE "userId" = ? AND "providerId" = ?').run(
hashedPassword,
existingUser.id,
'credential'
)
logger.info(`Admin password reset from environment for ${adminEmail}`)
logger.warn('Remove ADMIN_PASSWORD_RESET=true from environment after password reset')
}
return
}
try {
await auth.api.signUpEmail({
body: {
email: adminEmail,
password: adminPassword,
name: 'Admin',
},
})
logger.info(`Admin user created from environment: ${adminEmail}`)
} catch (error) {
logger.error('Failed to create admin user from environment:', error)
}
}
export function createAuthInfoRoutes(auth: AuthInstance, db: Database) {
const app = new Hono()
app.get('/config', async (c) => {
const enabledProviders: string[] = ['credentials']
if (ENV.AUTH.GITHUB_CLIENT_ID && ENV.AUTH.GITHUB_CLIENT_SECRET) {
enabledProviders.push('github')
}
if (ENV.AUTH.GOOGLE_CLIENT_ID && ENV.AUTH.GOOGLE_CLIENT_SECRET) {
enabledProviders.push('google')
}
if (ENV.AUTH.DISCORD_CLIENT_ID && ENV.AUTH.DISCORD_CLIENT_SECRET) {
enabledProviders.push('discord')
}
enabledProviders.push('passkey')
const hasUsers = db.prepare('SELECT COUNT(*) as count FROM "user"').get() as { count: number }
const adminConfigured = isAdminConfigured()
return c.json({
enabledProviders,
registrationEnabled: !adminConfigured,
isFirstUser: hasUsers.count === 0,
adminConfigured,
})
})
app.get('/me', async (c) => {
try {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (!session) {
return c.json({ user: null, session: null })
}
return c.json({
user: session.user,
session: {
id: session.session.id,
expiresAt: session.session.expiresAt,
},
})
} catch {
return c.json({ user: null, session: null })
}
})
return app
}
+2
View File
@@ -11,6 +11,7 @@
"test": "vitest"
},
"dependencies": {
"@better-auth/passkey": "^1.4.17",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
@@ -29,6 +30,7 @@
"@tailwindcss/vite": "^4.1.14",
"@tanstack/react-query": "^5.90.5",
"axios": "^1.12.2",
"better-auth": "^1.4.17",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
+76 -39
View File
@@ -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 />}
+145
View File
@@ -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>
)
}
+10
View File
@@ -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
}
+9
View File
@@ -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_")),
+6 -2
View File
@@ -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')
}
})
+24
View File
@@ -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);
}
+28
View File
@@ -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']
+87
View File
@@ -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
}
+253
View File
@@ -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>
)
}
+156
View File
@@ -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>
)
}
-51
View File
@@ -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>
)
}
+124
View File
@@ -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>
)
}
+2 -2
View File
@@ -1,9 +1,9 @@
{
"name": "opencode-manager",
"version": "0.7.4",
"version": "0.7.5",
"private": false,
"type": "module",
"packageManager": "pnpm@9.15.0",
"packageManager": "pnpm@10.28.1",
"scripts": {
"predev": "bash scripts/setup-dev.sh",
"dev": "concurrently \"pnpm:dev:backend\" \"pnpm:dev:frontend\"",
+435 -8
View File
@@ -21,6 +21,9 @@ importers:
backend:
dependencies:
'@better-auth/passkey':
specifier: ^1.4.17
version: 1.4.17(@better-auth/core@1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0))(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-auth@1.4.17(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vitest@3.2.4))(better-call@1.1.8(zod@4.3.2))(nanostores@1.1.0)
'@hono/node-server':
specifier: ^1.19.5
version: 1.19.7(hono@4.11.3)
@@ -30,6 +33,9 @@ importers:
archiver:
specifier: ^7.0.1
version: 7.0.1
better-auth:
specifier: ^1.4.17
version: 1.4.17(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vitest@3.2.4)
dotenv:
specifier: ^17.2.3
version: 17.2.3
@@ -60,7 +66,7 @@ importers:
version: 7.6.13
'@types/bun':
specifier: latest
version: 1.3.5
version: 1.3.6
'@types/eventsource':
specifier: ^3.0.0
version: 3.0.0
@@ -79,6 +85,9 @@ importers:
frontend:
dependencies:
'@better-auth/passkey':
specifier: ^1.4.17
version: 1.4.17(@better-auth/core@1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0))(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-auth@1.4.17(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vitest@3.2.4))(better-call@1.1.8(zod@4.3.2))(nanostores@1.1.0)
'@dnd-kit/core':
specifier: ^6.3.1
version: 6.3.1(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
@@ -133,6 +142,9 @@ importers:
axios:
specifier: ^1.12.2
version: 1.13.2
better-auth:
specifier: ^1.4.17
version: 1.4.17(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vitest@3.2.4)
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -382,6 +394,37 @@ packages:
resolution: {integrity: sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==}
engines: {node: '>=6.9.0'}
'@better-auth/core@1.4.17':
resolution: {integrity: sha512-WSaEQDdUO6B1CzAmissN6j0lx9fM9lcslEYzlApB5UzFaBeAOHNUONTdglSyUs6/idiZBoRvt0t/qMXCgIU8ug==}
peerDependencies:
'@better-auth/utils': 0.3.0
'@better-fetch/fetch': 1.1.21
better-call: 1.1.8
jose: ^6.1.0
kysely: ^0.28.5
nanostores: ^1.0.1
'@better-auth/passkey@1.4.17':
resolution: {integrity: sha512-SmS7a3UYi9A0muo4fWx1wEn59vtjoOLBFD5PnRo330BcXro6mHWxG/IXtnOnyeQKNGnEp4X7/QXcRrW/nDH0Iw==}
peerDependencies:
'@better-auth/core': 1.4.17
'@better-auth/utils': 0.3.0
'@better-fetch/fetch': 1.1.21
better-auth: 1.4.17
better-call: 1.1.8
nanostores: ^1.0.1
'@better-auth/telemetry@1.4.17':
resolution: {integrity: sha512-R1BC4e/bNjQbXu7lG6ubpgmsPj7IMqky5DvMlzAtnAJWJhh99pMh/n6w5gOHa0cqDZgEAuj75IPTxv+q3YiInA==}
peerDependencies:
'@better-auth/core': 1.4.17
'@better-auth/utils@0.3.0':
resolution: {integrity: sha512-W+Adw6ZA6mgvnSnhOki270rwJ42t4XzSK6YWGF//BbVXL6SwCLWfyzBc1lN2m/4RM28KubdBKQ4X5VMoLRNPQw==}
'@better-fetch/fetch@1.1.21':
resolution: {integrity: sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A==}
'@braintree/sanitize-url@7.1.1':
resolution: {integrity: sha512-i1L7noDNxtFyL5DmZafWy1wRVhGehQmzZaz1HiN5e7iylJMSZR7ekOV7NsIqa5qBldlLrsKv4HbgFUVlQrz8Mw==}
@@ -672,6 +715,9 @@ packages:
'@floating-ui/utils@0.2.10':
resolution: {integrity: sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==}
'@hexagon/base64@1.1.28':
resolution: {integrity: sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==}
'@hono/node-server@1.19.7':
resolution: {integrity: sha512-vUcD0uauS7EU2caukW8z5lJKtoGMokxNbJtBiwHgpqxEXokaHCBkQUmCHhjFB1VUTWdqj25QoMkMKzgjq+uhrw==}
engines: {node: '>=18.14.1'}
@@ -725,6 +771,9 @@ packages:
'@jridgewell/trace-mapping@0.3.31':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@levischuck/tiny-cbor@0.2.11':
resolution: {integrity: sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==}
'@mermaid-js/parser@0.6.3':
resolution: {integrity: sha512-lnjOhe7zyHjc+If7yT4zoedx2vo4sHaTmtkl1+or8BRTnCtDmcTpAjpzDSfCZrshM5bCoz0GyidzadJAH1xobA==}
@@ -738,6 +787,51 @@ packages:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
'@noble/ciphers@2.1.1':
resolution: {integrity: sha512-bysYuiVfhxNJuldNXlFEitTVdNnYUc+XNJZd7Qm2a5j1vZHgY+fazadNFWFaMK/2vye0JVlxV3gHmC0WDfAOQw==}
engines: {node: '>= 20.19.0'}
'@noble/hashes@2.0.1':
resolution: {integrity: sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==}
engines: {node: '>= 20.19.0'}
'@peculiar/asn1-android@2.6.0':
resolution: {integrity: sha512-cBRCKtYPF7vJGN76/yG8VbxRcHLPF3HnkoHhKOZeHpoVtbMYfY9ROKtH3DtYUY9m8uI1Mh47PRhHf2hSK3xcSQ==}
'@peculiar/asn1-cms@2.6.0':
resolution: {integrity: sha512-2uZqP+ggSncESeUF/9Su8rWqGclEfEiz1SyU02WX5fUONFfkjzS2Z/F1Li0ofSmf4JqYXIOdCAZqIXAIBAT1OA==}
'@peculiar/asn1-csr@2.6.0':
resolution: {integrity: sha512-BeWIu5VpTIhfRysfEp73SGbwjjoLL/JWXhJ/9mo4vXnz3tRGm+NGm3KNcRzQ9VMVqwYS2RHlolz21svzRXIHPQ==}
'@peculiar/asn1-ecc@2.6.0':
resolution: {integrity: sha512-FF3LMGq6SfAOwUG2sKpPXblibn6XnEIKa+SryvUl5Pik+WR9rmRA3OCiwz8R3lVXnYnyRkSZsSLdml8H3UiOcw==}
'@peculiar/asn1-pfx@2.6.0':
resolution: {integrity: sha512-rtUvtf+tyKGgokHHmZzeUojRZJYPxoD/jaN1+VAB4kKR7tXrnDCA/RAWXAIhMJJC+7W27IIRGe9djvxKgsldCQ==}
'@peculiar/asn1-pkcs8@2.6.0':
resolution: {integrity: sha512-KyQ4D8G/NrS7Fw3XCJrngxmjwO/3htnA0lL9gDICvEQ+GJ+EPFqldcJQTwPIdvx98Tua+WjkdKHSC0/Km7T+lA==}
'@peculiar/asn1-pkcs9@2.6.0':
resolution: {integrity: sha512-b78OQ6OciW0aqZxdzliXGYHASeCvvw5caqidbpQRYW2mBtXIX2WhofNXTEe7NyxTb0P6J62kAAWLwn0HuMF1Fw==}
'@peculiar/asn1-rsa@2.6.0':
resolution: {integrity: sha512-Nu4C19tsrTsCp9fDrH+sdcOKoVfdfoQQ7S3VqjJU6vedR7tY3RLkQ5oguOIB3zFW33USDUuYZnPEQYySlgha4w==}
'@peculiar/asn1-schema@2.6.0':
resolution: {integrity: sha512-xNLYLBFTBKkCzEZIw842BxytQQATQv+lDTCEMZ8C196iJcJJMBUZxrhSTxLaohMyKK8QlzRNTRkUmanucnDSqg==}
'@peculiar/asn1-x509-attr@2.6.0':
resolution: {integrity: sha512-MuIAXFX3/dc8gmoZBkwJWxUWOSvG4MMDntXhrOZpJVMkYX+MYc/rUAU2uJOved9iJEoiUx7//3D8oG83a78UJA==}
'@peculiar/asn1-x509@2.6.0':
resolution: {integrity: sha512-uzYbPEpoQiBoTq0/+jZtpM6Gq6zADBx+JNFP3yqRgziWBxQ/Dt/HcuvRfm9zJTPdRcBqPNdaRHTVwpyiq6iNMA==}
'@peculiar/x509@1.14.3':
resolution: {integrity: sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==}
engines: {node: '>=20.0.0'}
'@pkgjs/parseargs@0.11.0':
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
@@ -1272,6 +1366,16 @@ packages:
cpu: [x64]
os: [win32]
'@simplewebauthn/browser@13.2.2':
resolution: {integrity: sha512-FNW1oLQpTJyqG5kkDg5ZsotvWgmBaC6jCHR7Ej0qUNep36Wl9tj2eZu7J5rP+uhXgHaLk+QQ3lqcw2vS5MX1IA==}
'@simplewebauthn/server@13.2.2':
resolution: {integrity: sha512-HcWLW28yTMGXpwE9VLx9J+N2KEUaELadLrkPEEI9tpI5la70xNEVEsu/C+m3u7uoq4FulLqZQhgBCzR9IZhFpA==}
engines: {node: '>=20.0.0'}
'@standard-schema/spec@1.1.0':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
'@standard-schema/utils@0.3.0':
resolution: {integrity: sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==}
@@ -1423,8 +1527,8 @@ packages:
'@types/better-sqlite3@7.6.13':
resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==}
'@types/bun@1.3.5':
resolution: {integrity: sha512-RnygCqNrd3srIPEWBd5LFeUYG7plCoH2Yw9WaZGyNmdTEei+gWaHqydbaIRkIkcbXwhBT94q78QljxN0Sk838w==}
'@types/bun@1.3.6':
resolution: {integrity: sha512-uWCv6FO/8LcpREhenN1d1b6fcspAB+cefwD7uti8C8VffIv0Um08TKMn98FynpTiU38+y2dUO55T11NgDt8VAA==}
'@types/chai@5.2.3':
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
@@ -1745,6 +1849,10 @@ packages:
resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}
engines: {node: '>= 0.4'}
asn1js@3.0.7:
resolution: {integrity: sha512-uLvq6KJu04qoQM6gvBfKFjlh6Gl0vOKQuR5cJMDHQkmwfMOQeN3F3SHCv9SNYSL+CRoHvOGFfllDlVz03GQjvQ==}
engines: {node: '>=12.0.0'}
assertion-error@2.0.1:
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
engines: {node: '>=12'}
@@ -1794,6 +1902,76 @@ packages:
resolution: {integrity: sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==}
hasBin: true
better-auth@1.4.17:
resolution: {integrity: sha512-VmHGQyKsEahkEs37qguROKg/6ypYpNF13D7v/lkbO7w7Aivz0Bv2h+VyUkH4NzrGY0QBKXi1577mGhDCVwp0ew==}
peerDependencies:
'@lynx-js/react': '*'
'@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0
'@sveltejs/kit': ^2.0.0
'@tanstack/react-start': ^1.0.0
'@tanstack/solid-start': ^1.0.0
better-sqlite3: ^12.0.0
drizzle-kit: '>=0.31.4'
drizzle-orm: '>=0.41.0'
mongodb: ^6.0.0 || ^7.0.0
mysql2: ^3.0.0
next: ^14.0.0 || ^15.0.0 || ^16.0.0
pg: ^8.0.0
prisma: ^5.0.0 || ^6.0.0 || ^7.0.0
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
solid-js: ^1.0.0
svelte: ^4.0.0 || ^5.0.0
vitest: ^2.0.0 || ^3.0.0 || ^4.0.0
vue: ^3.0.0
peerDependenciesMeta:
'@lynx-js/react':
optional: true
'@prisma/client':
optional: true
'@sveltejs/kit':
optional: true
'@tanstack/react-start':
optional: true
'@tanstack/solid-start':
optional: true
better-sqlite3:
optional: true
drizzle-kit:
optional: true
drizzle-orm:
optional: true
mongodb:
optional: true
mysql2:
optional: true
next:
optional: true
pg:
optional: true
prisma:
optional: true
react:
optional: true
react-dom:
optional: true
solid-js:
optional: true
svelte:
optional: true
vitest:
optional: true
vue:
optional: true
better-call@1.1.8:
resolution: {integrity: sha512-XMQ2rs6FNXasGNfMjzbyroSwKwYbZ/T3IxruSS6U2MJRsSYh3wYtG3o6H00ZlKZ/C/UPOAD97tqgQJNsxyeTXw==}
peerDependencies:
zod: ^4.0.0
peerDependenciesMeta:
zod:
optional: true
bidi-js@1.0.3:
resolution: {integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==}
@@ -1815,8 +1993,8 @@ packages:
buffer@6.0.3:
resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==}
bun-types@1.3.5:
resolution: {integrity: sha512-inmAYe2PFLs0SUbFOWSVD24sg1jFlMPxOjOSSCYqUgn4Hsc3rDc7dFvfVYjFPNHtov6kgUeulV4SxbuIV/stPw==}
bun-types@1.3.6:
resolution: {integrity: sha512-OlFwHcnNV99r//9v5IIOgQ9Uk37gZqrNMCcqEaExdkVq3Avwqok1bJFmvGMCkCE0FqzdY8VMOZpfpR3lwI+CsQ==}
cac@6.7.14:
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
@@ -2159,6 +2337,9 @@ packages:
deep-is@0.1.4:
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
defu@6.1.4:
resolution: {integrity: sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==}
delaunator@5.0.1:
resolution: {integrity: sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==}
@@ -2622,6 +2803,9 @@ packages:
resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==}
hasBin: true
jose@6.1.3:
resolution: {integrity: sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==}
js-levenshtein@1.1.6:
resolution: {integrity: sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==}
engines: {node: '>=0.10.0'}
@@ -2677,6 +2861,10 @@ packages:
khroma@2.1.0:
resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}
kysely@0.28.10:
resolution: {integrity: sha512-ksNxfzIW77OcZ+QWSAPC7yDqUSaIVwkTWnTPNiIy//vifNbwsSgQ57OkkncHxxpcBHM3LRfLAZVEh7kjq5twVA==}
engines: {node: '>=20.0.0'}
langium@3.3.1:
resolution: {integrity: sha512-QJv/h939gDpvT+9SiLVlY7tZC3xB2qK57v0J04Sh9wpMb6MP1q8gB21L3WIo8T5P1MSMg3Ep14L7KkDCFG3y4w==}
engines: {node: '>=16.0.0'}
@@ -3009,6 +3197,10 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
nanostores@1.1.0:
resolution: {integrity: sha512-yJBmDJr18xy47dbNVlHcgdPrulSn1nhSE6Ns9vTG+Nx9VPT6iV1MD6aQFp/t52zpf82FhLLTXAXr30NuCnxvwA==}
engines: {node: ^20.0.0 || >=22.0.0}
natural-compare@1.4.0:
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
@@ -3134,6 +3326,13 @@ packages:
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
pvtsutils@1.3.6:
resolution: {integrity: sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==}
pvutils@1.1.5:
resolution: {integrity: sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA==}
engines: {node: '>=16.0.0'}
react-dom@19.2.3:
resolution: {integrity: sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==}
peerDependencies:
@@ -3223,6 +3422,9 @@ packages:
resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}
engines: {node: '>=8'}
reflect-metadata@0.2.2:
resolution: {integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==}
rehype-highlight@7.0.2:
resolution: {integrity: sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA==}
@@ -3261,6 +3463,9 @@ packages:
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
hasBin: true
rou3@0.7.12:
resolution: {integrity: sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg==}
roughjs@4.6.6:
resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==}
@@ -3491,9 +3696,16 @@ packages:
resolution: {integrity: sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==}
engines: {node: '>=6.10'}
tslib@1.14.1:
resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==}
tslib@2.8.1:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
tsyringe@4.10.0:
resolution: {integrity: sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==}
engines: {node: '>= 6.0.0'}
type-check@0.4.0:
resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==}
engines: {node: '>= 0.8.0'}
@@ -3768,6 +3980,9 @@ packages:
zod@4.3.2:
resolution: {integrity: sha512-b8L8yn4rIVfiXyHAmnr52/ZEpDumlT0bmxiq3Ws1ybrinhflGpt12Hvv54kYnEsGPRs6o/Ka3/ppA2OWY21IVg==}
zod@4.3.5:
resolution: {integrity: sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==}
zustand@5.0.9:
resolution: {integrity: sha512-ALBtUj0AfjJt3uNRQoL1tL2tMvj6Gp/6e39dnfT6uzpelGru8v1tPOGBzayOWbPJvujM8JojDk3E1LxeFisBNg==}
engines: {node: '>=12.20.0'}
@@ -3932,6 +4147,39 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
'@better-auth/core@1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0)':
dependencies:
'@better-auth/utils': 0.3.0
'@better-fetch/fetch': 1.1.21
'@standard-schema/spec': 1.1.0
better-call: 1.1.8(zod@4.3.2)
jose: 6.1.3
kysely: 0.28.10
nanostores: 1.1.0
zod: 4.3.5
'@better-auth/passkey@1.4.17(@better-auth/core@1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0))(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-auth@1.4.17(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vitest@3.2.4))(better-call@1.1.8(zod@4.3.2))(nanostores@1.1.0)':
dependencies:
'@better-auth/core': 1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0)
'@better-auth/utils': 0.3.0
'@better-fetch/fetch': 1.1.21
'@simplewebauthn/browser': 13.2.2
'@simplewebauthn/server': 13.2.2
better-auth: 1.4.17(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vitest@3.2.4)
better-call: 1.1.8(zod@4.3.2)
nanostores: 1.1.0
zod: 4.3.5
'@better-auth/telemetry@1.4.17(@better-auth/core@1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0))':
dependencies:
'@better-auth/core': 1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0)
'@better-auth/utils': 0.3.0
'@better-fetch/fetch': 1.1.21
'@better-auth/utils@0.3.0': {}
'@better-fetch/fetch@1.1.21': {}
'@braintree/sanitize-url@7.1.1': {}
'@chevrotain/cst-dts-gen@11.0.3':
@@ -4141,6 +4389,8 @@ snapshots:
'@floating-ui/utils@0.2.10': {}
'@hexagon/base64@1.1.28': {}
'@hono/node-server@1.19.7(hono@4.11.3)':
dependencies:
hono: 4.11.3
@@ -4197,6 +4447,8 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5
'@levischuck/tiny-cbor@0.2.11': {}
'@mermaid-js/parser@0.6.3':
dependencies:
langium: 3.3.1
@@ -4212,6 +4464,106 @@ snapshots:
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
'@noble/ciphers@2.1.1': {}
'@noble/hashes@2.0.1': {}
'@peculiar/asn1-android@2.6.0':
dependencies:
'@peculiar/asn1-schema': 2.6.0
asn1js: 3.0.7
tslib: 2.8.1
'@peculiar/asn1-cms@2.6.0':
dependencies:
'@peculiar/asn1-schema': 2.6.0
'@peculiar/asn1-x509': 2.6.0
'@peculiar/asn1-x509-attr': 2.6.0
asn1js: 3.0.7
tslib: 2.8.1
'@peculiar/asn1-csr@2.6.0':
dependencies:
'@peculiar/asn1-schema': 2.6.0
'@peculiar/asn1-x509': 2.6.0
asn1js: 3.0.7
tslib: 2.8.1
'@peculiar/asn1-ecc@2.6.0':
dependencies:
'@peculiar/asn1-schema': 2.6.0
'@peculiar/asn1-x509': 2.6.0
asn1js: 3.0.7
tslib: 2.8.1
'@peculiar/asn1-pfx@2.6.0':
dependencies:
'@peculiar/asn1-cms': 2.6.0
'@peculiar/asn1-pkcs8': 2.6.0
'@peculiar/asn1-rsa': 2.6.0
'@peculiar/asn1-schema': 2.6.0
asn1js: 3.0.7
tslib: 2.8.1
'@peculiar/asn1-pkcs8@2.6.0':
dependencies:
'@peculiar/asn1-schema': 2.6.0
'@peculiar/asn1-x509': 2.6.0
asn1js: 3.0.7
tslib: 2.8.1
'@peculiar/asn1-pkcs9@2.6.0':
dependencies:
'@peculiar/asn1-cms': 2.6.0
'@peculiar/asn1-pfx': 2.6.0
'@peculiar/asn1-pkcs8': 2.6.0
'@peculiar/asn1-schema': 2.6.0
'@peculiar/asn1-x509': 2.6.0
'@peculiar/asn1-x509-attr': 2.6.0
asn1js: 3.0.7
tslib: 2.8.1
'@peculiar/asn1-rsa@2.6.0':
dependencies:
'@peculiar/asn1-schema': 2.6.0
'@peculiar/asn1-x509': 2.6.0
asn1js: 3.0.7
tslib: 2.8.1
'@peculiar/asn1-schema@2.6.0':
dependencies:
asn1js: 3.0.7
pvtsutils: 1.3.6
tslib: 2.8.1
'@peculiar/asn1-x509-attr@2.6.0':
dependencies:
'@peculiar/asn1-schema': 2.6.0
'@peculiar/asn1-x509': 2.6.0
asn1js: 3.0.7
tslib: 2.8.1
'@peculiar/asn1-x509@2.6.0':
dependencies:
'@peculiar/asn1-schema': 2.6.0
asn1js: 3.0.7
pvtsutils: 1.3.6
tslib: 2.8.1
'@peculiar/x509@1.14.3':
dependencies:
'@peculiar/asn1-cms': 2.6.0
'@peculiar/asn1-csr': 2.6.0
'@peculiar/asn1-ecc': 2.6.0
'@peculiar/asn1-pkcs9': 2.6.0
'@peculiar/asn1-rsa': 2.6.0
'@peculiar/asn1-schema': 2.6.0
'@peculiar/asn1-x509': 2.6.0
pvtsutils: 1.3.6
reflect-metadata: 0.2.2
tslib: 2.8.1
tsyringe: 4.10.0
'@pkgjs/parseargs@0.11.0':
optional: true
@@ -4707,6 +5059,21 @@ snapshots:
'@rollup/rollup-win32-x64-msvc@4.54.0':
optional: true
'@simplewebauthn/browser@13.2.2': {}
'@simplewebauthn/server@13.2.2':
dependencies:
'@hexagon/base64': 1.1.28
'@levischuck/tiny-cbor': 0.2.11
'@peculiar/asn1-android': 2.6.0
'@peculiar/asn1-ecc': 2.6.0
'@peculiar/asn1-rsa': 2.6.0
'@peculiar/asn1-schema': 2.6.0
'@peculiar/asn1-x509': 2.6.0
'@peculiar/x509': 1.14.3
'@standard-schema/spec@1.1.0': {}
'@standard-schema/utils@0.3.0': {}
'@tailwindcss/node@4.1.18':
@@ -4849,9 +5216,9 @@ snapshots:
dependencies:
'@types/node': 24.10.4
'@types/bun@1.3.5':
'@types/bun@1.3.6':
dependencies:
bun-types: 1.3.5
bun-types: 1.3.6
'@types/chai@5.2.3':
dependencies:
@@ -5254,6 +5621,12 @@ snapshots:
aria-query@5.3.2: {}
asn1js@3.0.7:
dependencies:
pvtsutils: 1.3.6
pvutils: 1.1.5
tslib: 2.8.1
assertion-error@2.0.1: {}
async@3.2.6: {}
@@ -5289,6 +5662,34 @@ snapshots:
baseline-browser-mapping@2.9.11: {}
better-auth@1.4.17(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vitest@3.2.4):
dependencies:
'@better-auth/core': 1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0)
'@better-auth/telemetry': 1.4.17(@better-auth/core@1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0))
'@better-auth/utils': 0.3.0
'@better-fetch/fetch': 1.1.21
'@noble/ciphers': 2.1.1
'@noble/hashes': 2.0.1
better-call: 1.1.8(zod@4.3.2)
defu: 6.1.4
jose: 6.1.3
kysely: 0.28.10
nanostores: 1.1.0
zod: 4.3.5
optionalDependencies:
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
vitest: 3.2.4(@types/debug@4.1.12)(@types/node@24.10.4)(@vitest/ui@3.2.4)(jiti@2.6.1)(jsdom@27.4.0)(lightningcss@1.30.2)
better-call@1.1.8(zod@4.3.2):
dependencies:
'@better-auth/utils': 0.3.0
'@better-fetch/fetch': 1.1.21
rou3: 0.7.12
set-cookie-parser: 2.7.2
optionalDependencies:
zod: 4.3.2
bidi-js@1.0.3:
dependencies:
require-from-string: 2.0.2
@@ -5317,7 +5718,7 @@ snapshots:
base64-js: 1.5.1
ieee754: 1.2.1
bun-types@1.3.5:
bun-types@1.3.6:
dependencies:
'@types/node': 24.10.4
@@ -5688,6 +6089,8 @@ snapshots:
deep-is@0.1.4: {}
defu@6.1.4: {}
delaunator@5.0.1:
dependencies:
robust-predicates: 3.0.2
@@ -6186,6 +6589,8 @@ snapshots:
jiti@2.6.1: {}
jose@6.1.3: {}
js-levenshtein@1.1.6: {}
js-tokens@4.0.0: {}
@@ -6246,6 +6651,8 @@ snapshots:
khroma@2.1.0: {}
kysely@0.28.10: {}
langium@3.3.1:
dependencies:
chevrotain: 11.0.3
@@ -6773,6 +7180,8 @@ snapshots:
nanoid@3.3.11: {}
nanostores@1.1.0: {}
natural-compare@1.4.0: {}
node-releases@2.0.27: {}
@@ -6898,6 +7307,12 @@ snapshots:
punycode@2.3.1: {}
pvtsutils@1.3.6:
dependencies:
tslib: 2.8.1
pvutils@1.1.5: {}
react-dom@19.2.3(react@19.2.3):
dependencies:
react: 19.2.3
@@ -6999,6 +7414,8 @@ snapshots:
indent-string: 4.0.0
strip-indent: 3.0.0
reflect-metadata@0.2.2: {}
rehype-highlight@7.0.2:
dependencies:
'@types/hast': 3.0.4
@@ -7083,6 +7500,8 @@ snapshots:
'@rollup/rollup-win32-x64-msvc': 4.54.0
fsevents: 2.3.3
rou3@0.7.12: {}
roughjs@4.6.6:
dependencies:
hachure-fill: 0.5.2
@@ -7289,8 +7708,14 @@ snapshots:
ts-dedent@2.2.0: {}
tslib@1.14.1: {}
tslib@2.8.1: {}
tsyringe@4.10.0:
dependencies:
tslib: 1.14.1
type-check@0.4.0:
dependencies:
prelude-ls: 1.2.1
@@ -7564,6 +7989,8 @@ snapshots:
zod@4.3.2: {}
zod@4.3.5: {}
zustand@5.0.9(@types/react@19.2.7)(react@19.2.3):
optionalDependencies:
'@types/react': 19.2.7
+17
View File
@@ -59,4 +59,21 @@ fi
echo "🚀 Starting OpenCode Manager Backend..."
if [ -z "$AUTH_SECRET" ]; then
echo "❌ AUTH_SECRET is required but not set"
echo ""
echo "Please set AUTH_SECRET environment variable with a secure random string."
echo "Generate one with: openssl rand -base64 32"
echo ""
echo "Example in docker-compose.yml:"
echo " environment:"
echo " - AUTH_SECRET=your-secure-random-secret-here"
echo ""
echo "Example with Docker run:"
echo " docker run -e AUTH_SECRET=\$(openssl rand -base64 32) ..."
echo ""
exit 1
fi
exec "$@"
+26
View File
@@ -37,6 +37,15 @@ const resolveWorkspacePath = (): string => {
const workspaceBasePath = resolveWorkspacePath()
const generateDefaultSecret = (): string => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
let result = ''
for (let i = 0; i < 32; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}
export const ENV = {
SERVER: {
PORT: getEnvNumber('PORT', DEFAULTS.SERVER.PORT),
@@ -77,6 +86,23 @@ export const ENV = {
DEBUG: getEnvBoolean('DEBUG', DEFAULTS.LOGGING.DEBUG),
LOG_LEVEL: getEnvString('LOG_LEVEL', DEFAULTS.LOGGING.LOG_LEVEL),
},
AUTH: {
SECRET: getEnvString('AUTH_SECRET', process.env.NODE_ENV === 'production' ? '' : generateDefaultSecret()),
TRUSTED_ORIGINS: getEnvString('AUTH_TRUSTED_ORIGINS', 'http://localhost:5173,http://localhost:5001'),
ADMIN_EMAIL: process.env.ADMIN_EMAIL,
ADMIN_PASSWORD: process.env.ADMIN_PASSWORD,
ADMIN_PASSWORD_RESET: getEnvBoolean('ADMIN_PASSWORD_RESET', false),
GITHUB_CLIENT_ID: process.env.GITHUB_CLIENT_ID,
GITHUB_CLIENT_SECRET: process.env.GITHUB_CLIENT_SECRET,
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
DISCORD_CLIENT_ID: process.env.DISCORD_CLIENT_ID,
DISCORD_CLIENT_SECRET: process.env.DISCORD_CLIENT_SECRET,
PASSKEY_RP_ID: getEnvString('PASSKEY_RP_ID', 'localhost'),
PASSKEY_RP_NAME: getEnvString('PASSKEY_RP_NAME', 'OpenCode Manager'),
PASSKEY_ORIGIN: getEnvString('PASSKEY_ORIGIN', 'http://localhost:5173'),
},
} as const
export const getWorkspacePath = () => ENV.WORKSPACE.BASE_PATH