From 81a66d2ddb5fbf6c9ebbb386010700140293f503 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 24 Jan 2026 17:45:44 -0500 Subject: [PATCH] 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 --- .env.example | 29 ++ CHANGELOG.md | 14 + README.md | 102 +++- backend/package.json | 2 + backend/src/auth/index.ts | 102 ++++ backend/src/auth/middleware.ts | 77 +++ backend/src/db/schema.ts | 74 ++- backend/src/index.ts | 43 +- backend/src/routes/auth.ts | 112 +++++ frontend/package.json | 2 + frontend/src/App.tsx | 115 +++-- .../components/settings/AccountSettings.tsx | 348 ++++++++++++++ .../components/settings/ProviderSettings.tsx | 53 +-- .../components/settings/SettingsDialog.tsx | 15 +- frontend/src/contexts/AuthContext.tsx | 145 ++++++ frontend/src/hooks/useAuth.ts | 10 + frontend/src/hooks/useOpenCode.ts | 9 + frontend/src/hooks/useRemoveMessage.ts | 8 +- frontend/src/index.css | 24 + frontend/src/lib/auth-client.ts | 28 ++ frontend/src/lib/auth-loaders.ts | 87 ++++ frontend/src/pages/Login.tsx | 253 ++++++++++ frontend/src/pages/Register.tsx | 156 ++++++ frontend/src/pages/Settings.tsx | 51 -- frontend/src/pages/Setup.tsx | 124 +++++ package.json | 4 +- pnpm-lock.yaml | 443 +++++++++++++++++- scripts/docker-entrypoint.sh | 17 + shared/src/config/env.ts | 26 + 29 files changed, 2324 insertions(+), 149 deletions(-) create mode 100644 backend/src/auth/index.ts create mode 100644 backend/src/auth/middleware.ts create mode 100644 backend/src/routes/auth.ts create mode 100644 frontend/src/components/settings/AccountSettings.tsx create mode 100644 frontend/src/contexts/AuthContext.tsx create mode 100644 frontend/src/hooks/useAuth.ts create mode 100644 frontend/src/lib/auth-client.ts create mode 100644 frontend/src/lib/auth-loaders.ts create mode 100644 frontend/src/pages/Login.tsx create mode 100644 frontend/src/pages/Register.tsx delete mode 100644 frontend/src/pages/Settings.tsx create mode 100644 frontend/src/pages/Setup.tsx diff --git a/.env.example b/.env.example index 2ea5ed9e..141e77a4 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 53021981..2a3037ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index c9b279cb..59d94881 100644 --- a/README.md +++ b/README.md @@ -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 -## 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. diff --git a/backend/package.json b/backend/package.json index bc190bdb..aacc088b 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/src/auth/index.ts b/backend/src/auth/index.ts new file mode 100644 index 00000000..d6e3e18f --- /dev/null +++ b/backend/src/auth/index.ts @@ -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 + +export function createAuth(db: Database) { + const socialProviders: Record = {} + + 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 + } +} diff --git a/backend/src/auth/middleware.ts b/backend/src/auth/middleware.ts new file mode 100644 index 00000000..70171ee5 --- /dev/null +++ b/backend/src/auth/middleware.ts @@ -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() + }) +} diff --git a/backend/src/db/schema.ts b/backend/src/db/schema.ts index e84e0c26..cc04b2fd 100644 --- a/backend/src/db/schema.ts +++ b/backend/src/db/schema.ts @@ -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()) diff --git a/backend/src/index.ts b/backend/src/index.ts index cf3a1584..83134c9e 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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 { } 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) }) diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts new file mode 100644 index 00000000..9e8421d3 --- /dev/null +++ b/backend/src/routes/auth.ts @@ -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 { + 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 +} diff --git a/frontend/package.json b/frontend/package.json index 868f0e8b..649652ba 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 6cd23eda..df5f0de4 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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 ( - <> - - } /> - } /> - } /> - - - - - ) -} - 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 ( + + + + + + + + + ) +} + +const router = createBrowserRouter([ + { + element: , + children: [ + { + path: '/login', + element: , + loader: loginLoader, + }, + { + path: '/register', + element: , + loader: registerLoader, + }, + { + path: '/setup', + element: , + loader: setupLoader, + }, + { + path: '/', + element: , + loader: protectedLoader, + }, + { + path: '/repos/:id', + element: , + loader: protectedLoader, + }, + { + path: '/repos/:id/sessions/:sessionId', + element: , + loader: protectedLoader, + }, + ], + }, +]) + function App() { return ( - - - - - - + ) diff --git a/frontend/src/components/settings/AccountSettings.tsx b/frontend/src/components/settings/AccountSettings.tsx new file mode 100644 index 00000000..967f560a --- /dev/null +++ b/frontend/src/components/settings/AccountSettings.tsx @@ -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(null) + const [success, setSuccess] = useState(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 + }, + 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 ( +
+ +
+ ) + } + + return ( +
+ {error && ( + + + {error} + + )} + + {success && ( + + + {success} + + )} + +
+ + +
+
+ + Profile +
+ {!editingProfile && ( + + )} +
+
+ + {editingProfile ? ( +
+
+ + +
+
+ + +
+ +
+ ) : ( +
+
+ Name + {user.name} +
+
+ Email + {user.email} +
+
+ )} +
+
+ + + + + + Change Password + + Update your account password + + + {!showChangePassword ? ( + + ) : ( +
+
+ + setCurrentPassword(e.target.value)} + placeholder="Enter current password" + className="h-9 sm:h-10 text-sm" + /> +
+
+ + setNewPassword(e.target.value)} + placeholder="At least 8 characters" + className="h-9 sm:h-10 text-sm" + /> +
+
+ + +
+
+ )} +
+
+
+ + + + + + Passkeys + + Manage passkeys for passwordless sign-in + + +
+ setPasskeyName(e.target.value)} + className="h-9 sm:h-10 text-sm" + /> + +
+ + {passkeysLoading ? ( +
+ +
+ ) : passkeys && passkeys.length > 0 ? ( +
+ {passkeys.map((pk) => ( +
+
+

{pk.name || 'Unnamed Passkey'}

+

+ {pk.deviceType} - {new Date(pk.createdAt).toLocaleDateString()} +

+
+ +
+ ))} +
+ ) : ( +

+ No passkeys registered. Add one for passwordless sign-in. +

+ )} +
+
+ + + + + + Sign Out + + Sign out of your account + + + + + +
+ ) +} diff --git a/frontend/src/components/settings/ProviderSettings.tsx b/frontend/src/components/settings/ProviderSettings.tsx index 114c18d5..c2d40d04 100644 --- a/frontend/src/components/settings/ProviderSettings.tsx +++ b/frontend/src/components/settings/ProviderSettings.tsx @@ -17,7 +17,7 @@ export function ProviderSettings() { const [oauthDialogOpen, setOauthDialogOpen] = useState(false) const [oauthCallbackDialogOpen, setOauthCallbackDialogOpen] = useState(false) const [oauthResponse, setOauthResponse] = useState(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 ( - +
@@ -357,39 +357,36 @@ export function ProviderSettings() { />
-
+
{filteredAvailableProviders.length === 0 ? (

{availableSearch ? 'No providers match your search.' : 'No available providers.'}

) : ( - filteredAvailableProviders.map((provider) => { + filteredAvailableProviders.map((provider, index) => { const modelCount = Object.keys(provider.models || {}).length return ( - - -
-
- - {provider.name || provider.id} - - {modelCount > 0 && ( - - {modelCount} model{modelCount !== 1 ? 's' : ''} - - )} -
- -
-
-
+
+
+ + {provider.name || provider.id} + + {modelCount > 0 && ( + + {modelCount} model{modelCount !== 1 ? 's' : ''} + + )} +
+ +
) }) )} diff --git a/frontend/src/components/settings/SettingsDialog.tsx b/frontend/src/components/settings/SettingsDialog.tsx index 26e7706b..feabfa0f 100644 --- a/frontend/src/components/settings/SettingsDialog.tsx +++ b/frontend/src/components/settings/SettingsDialog.tsx @@ -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('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
- +
- + + + Account + General @@ -88,6 +93,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
+ @@ -148,6 +154,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
)} + {mobileView === 'account' && } {mobileView === 'general' && } {mobileView === 'git' && } {mobileView === 'shortcuts' && } diff --git a/frontend/src/contexts/AuthContext.tsx b/frontend/src/contexts/AuthContext.tsx new file mode 100644 index 00000000..0daea826 --- /dev/null +++ b/frontend/src/contexts/AuthContext.tsx @@ -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 + refreshSession: () => Promise +} + +export const AuthContext = createContext(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(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 ( + + {children} + + ) +} diff --git a/frontend/src/hooks/useAuth.ts b/frontend/src/hooks/useAuth.ts new file mode 100644 index 00000000..cbf63ca1 --- /dev/null +++ b/frontend/src/hooks/useAuth.ts @@ -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 +} diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index fa39aeaf..86938907 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -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(); 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>(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( ["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( ["opencode", "messages", opcodeUrl, sessionID, directory], (old) => old?.filter((msg) => !msg.info.id.startsWith("optimistic_")), diff --git a/frontend/src/hooks/useRemoveMessage.ts b/frontend/src/hooks/useRemoveMessage.ts index 74f96bc8..55d510d6 100644 --- a/frontend/src/hooks/useRemoveMessage.ts +++ b/frontend/src/hooks/useRemoveMessage.ts @@ -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( ['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') } }) diff --git a/frontend/src/index.css b/frontend/src/index.css index bdadf9ea..23ac0ee2 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -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); +} diff --git a/frontend/src/lib/auth-client.ts b/frontend/src/lib/auth-client.ts new file mode 100644 index 00000000..f40a89b1 --- /dev/null +++ b/frontend/src/lib/auth-client.ts @@ -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'] diff --git a/frontend/src/lib/auth-loaders.ts b/frontend/src/lib/auth-loaders.ts new file mode 100644 index 00000000..45d99547 --- /dev/null +++ b/frontend/src/lib/auth-loaders.ts @@ -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 { + 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 +} diff --git a/frontend/src/pages/Login.tsx b/frontend/src/pages/Login.tsx new file mode 100644 index 00000000..2937b7ad --- /dev/null +++ b/frontend/src/pages/Login.tsx @@ -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 + +export function Login() { + const { signInWithEmail, signInWithProvider, signInWithPasskey } = useAuth() + const { config } = useLoaderData() as { config: AuthConfig } + const theme = useTheme() + const [error, setError] = useState(null) + const [isSubmitting, setIsSubmitting] = useState(false) + const [oauthLoading, setOauthLoading] = useState(null) + + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + 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 ( +
+
+
+ OpenCode +

Sign in to continue

+
+ +
+ {error && ( + + + {error} + + )} + + {hasPasskey && ( + + )} + + {hasOAuth && ( +
+ {config.enabledProviders.includes('github') && ( + + )} + {config.enabledProviders.includes('google') && ( + + )} + {config.enabledProviders.includes('discord') && ( + + )} +
+ )} + + {hasCredentials && (hasOAuth || hasPasskey) && ( +
+
+ +
+
+ Or continue with email +
+
+ )} + + {hasCredentials && ( +
+
+ + + {errors.email && ( +

{errors.email.message}

+ )} +
+
+ + + {errors.password && ( +

{errors.password.message}

+ )} +
+ +
+ )} +
+ + {config.registrationEnabled && ( +

+ Don't have an account?{' '} + + Sign up + +

+ )} +
+
+ ) +} diff --git a/frontend/src/pages/Register.tsx b/frontend/src/pages/Register.tsx new file mode 100644 index 00000000..1d0edea7 --- /dev/null +++ b/frontend/src/pages/Register.tsx @@ -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 + +export function Register() { + const { signUpWithEmail } = useAuth() + const { config } = useLoaderData() as { config: AuthConfig } + const theme = useTheme() + const [error, setError] = useState(null) + const [isSubmitting, setIsSubmitting] = useState(false) + + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + 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 ( +
+
+
+ OpenCode +

+ {config.isFirstUser + ? 'Create the first admin account' + : 'Create your account'} +

+
+ +
+ {error && ( + + + {error} + + )} + +
+
+ + + {errors.name && ( +

{errors.name.message}

+ )} +
+
+ + + {errors.email && ( +

{errors.email.message}

+ )} +
+
+ + + {errors.password && ( +

{errors.password.message}

+ )} +
+
+ + + {errors.confirmPassword && ( +

{errors.confirmPassword.message}

+ )} +
+ +
+
+ +

+ Already have an account?{' '} + + Sign in + +

+
+
+ ) +} diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsx deleted file mode 100644 index d2b6fb5a..00000000 --- a/frontend/src/pages/Settings.tsx +++ /dev/null @@ -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 ( -
-
- - Settings - -
- -
- - - General - Shortcuts - OpenCode - - - - - - - - - - - - - - - -
-

Commands manager coming soon

-
-
- - -
-

Agents manager coming soon

-
-
-
-
-
- ) -} diff --git a/frontend/src/pages/Setup.tsx b/frontend/src/pages/Setup.tsx new file mode 100644 index 00000000..08e87686 --- /dev/null +++ b/frontend/src/pages/Setup.tsx @@ -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 + +export function Setup() { + const { signUpWithEmail } = useAuth() + const theme = useTheme() + const [error, setError] = useState(null) + const [isSubmitting, setIsSubmitting] = useState(false) + + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + 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 ( +
+
+
+ OpenCode +

Create Admin Account

+
+ +
+ {error && ( + + + {error} + + )} + +
+
+ + + {errors.name && ( +

{errors.name.message}

+ )} +
+
+ + + {errors.email && ( +

{errors.email.message}

+ )} +
+
+ + + {errors.password && ( +

{errors.password.message}

+ )} +
+ +
+
+
+
+ ) +} diff --git a/package.json b/package.json index a74f1f5e..82717593 100644 --- a/package.json +++ b/package.json @@ -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\"", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 62e28585..064dc4d6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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 diff --git a/scripts/docker-entrypoint.sh b/scripts/docker-entrypoint.sh index 2da0ef59..4446c209 100644 --- a/scripts/docker-entrypoint.sh +++ b/scripts/docker-entrypoint.sh @@ -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 "$@" + diff --git a/shared/src/config/env.ts b/shared/src/config/env.ts index 6af06b01..075bdb9d 100644 --- a/shared/src/config/env.ts +++ b/shared/src/config/env.ts @@ -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