mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Add single-user authentication system with Better Auth integration (#76)
* Add Better Auth integration with session management - Implement user authentication using Better Auth library - Add login, register, and sign out functionality - Support passkey/WebAuthn authentication - Create database schema for users, sessions, accounts, passkeys - Add AuthProvider context and ProtectedRoute components - Add account settings page in settings dialog - Protect all API routes with authentication middleware - Update environment configuration for auth providers * Add single-user authentication system with admin setup - Add first-run Setup page for initial admin account creation - Add environment-based admin configuration (ADMIN_EMAIL, ADMIN_PASSWORD) - Add password reset capability via ADMIN_PASSWORD_RESET environment flag - Migrate to data routers with auth loaders, remove ProtectedRoute - Add change password functionality to account settings - Enforce AUTH_SECRET requirement in production - Auto-disable registration when admin is pre-configured via environment * Track busy/idle session status across hooks * Bump version to 0.7.5 * Update pnpm to 10.28.1
This commit is contained in:
1 parent
af292758c3
commit
81a66d2ddb
29 files changed
+2324
-149
No files matched your search
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user