mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(backend,frontend): add Web UI for configuring OpenCode server Basic Auth password
Allow administrators to set and clear the managed OpenCode server password from the Settings UI without requiring container or environment variable changes. Passwords are encrypted before database persistence and never returned to the frontend. The server manager resolves the password dynamically at restart time, falling back to the env var if no stored password exists. - Add system_settings table migration (v12) - Add SettingsService methods for encrypted password storage - Add GET/PATCH /api/settings/opencode-server-auth routes - Make OpenCodeServerManager resolve password dynamically from DB - Add frontend API methods, React Query hook, and auth settings component
This commit is contained in:
1 parent
efae3b86c1
commit
954bc60ddb
13 files changed
+731
-20
No files matched your search
@@ -0,0 +1,22 @@
|
|||||||
|
import type { Migration } from '../migration-runner'
|
||||||
|
|
||||||
|
const migration: Migration = {
|
||||||
|
version: 12,
|
||||||
|
name: 'system_settings',
|
||||||
|
|
||||||
|
up(db) {
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE IF NOT EXISTS system_settings (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
},
|
||||||
|
|
||||||
|
down(db) {
|
||||||
|
db.run('DROP TABLE IF EXISTS system_settings')
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export default migration
|
||||||
@@ -10,6 +10,7 @@ import migration008 from './008-schedule-cron-support'
|
|||||||
import migration009 from './009-repo-source-path'
|
import migration009 from './009-repo-source-path'
|
||||||
import migration010 from './009-prompt-templates'
|
import migration010 from './009-prompt-templates'
|
||||||
import migration011 from './011-repo-last-accessed'
|
import migration011 from './011-repo-last-accessed'
|
||||||
|
import migration012 from './012-system-settings'
|
||||||
|
|
||||||
export const allMigrations: Migration[] = [
|
export const allMigrations: Migration[] = [
|
||||||
migration001,
|
migration001,
|
||||||
@@ -23,4 +24,5 @@ export const allMigrations: Migration[] = [
|
|||||||
migration009,
|
migration009,
|
||||||
migration010,
|
migration010,
|
||||||
migration011,
|
migration011,
|
||||||
|
migration012,
|
||||||
]
|
]
|
||||||
@@ -7,7 +7,7 @@ import type { Database } from 'bun:sqlite'
|
|||||||
import { SettingsService } from '../services/settings'
|
import { SettingsService } from '../services/settings'
|
||||||
import { writeFileContent, readFileContent, fileExists } from '../services/file-operations'
|
import { writeFileContent, readFileContent, fileExists } from '../services/file-operations'
|
||||||
import { patchOpenCodeConfig, proxyToOpenCodeWithDirectory } from '../services/proxy'
|
import { patchOpenCodeConfig, proxyToOpenCodeWithDirectory } from '../services/proxy'
|
||||||
import { getOpenCodeConfigFilePath, getAgentsMdPath } from '@opencode-manager/shared/config/env'
|
import { getOpenCodeConfigFilePath, getAgentsMdPath, ENV } from '@opencode-manager/shared/config/env'
|
||||||
import {
|
import {
|
||||||
UserPreferencesSchema,
|
UserPreferencesSchema,
|
||||||
OpenCodeConfigSchema,
|
OpenCodeConfigSchema,
|
||||||
@@ -17,10 +17,11 @@ import {
|
|||||||
CreateSkillRequestSchema,
|
CreateSkillRequestSchema,
|
||||||
UpdateSkillRequestSchema,
|
UpdateSkillRequestSchema,
|
||||||
SkillScopeSchema,
|
SkillScopeSchema,
|
||||||
|
UpdateOpenCodeServerAuthSettingsSchema,
|
||||||
} from '@opencode-manager/shared'
|
} from '@opencode-manager/shared'
|
||||||
import { logger } from '../utils/logger'
|
import { logger } from '../utils/logger'
|
||||||
import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server'
|
import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server'
|
||||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
import type { OpenCodeLifecycleStatus, OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||||
import type { GitAuthService } from '../services/git-auth'
|
import type { GitAuthService } from '../services/git-auth'
|
||||||
import { DEFAULT_AGENTS_MD } from '../constants'
|
import { DEFAULT_AGENTS_MD } from '../constants'
|
||||||
import { validateSSHPrivateKey } from '../utils/ssh-validation'
|
import { validateSSHPrivateKey } from '../utils/ssh-validation'
|
||||||
@@ -78,16 +79,23 @@ async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Pr
|
|||||||
await opencodeServerManager.reloadConfig()
|
await opencodeServerManager.reloadConfig()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise<void> {
|
async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise<OpenCodeLifecycleStatus | void> {
|
||||||
if (openCodeSupervisor) {
|
if (openCodeSupervisor) {
|
||||||
await openCodeSupervisor.restart('settings_restart')
|
return openCodeSupervisor.restart('settings_restart')
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
opencodeServerManager.clearStartupError()
|
opencodeServerManager.clearStartupError()
|
||||||
await opencodeServerManager.restart()
|
await opencodeServerManager.restart()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getRestartFailureMessage(status: OpenCodeLifecycleStatus | void): string | undefined {
|
||||||
|
if (!status || status.healthy) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
return status.lastError || `OpenCode server restart finished in ${status.state} state`
|
||||||
|
}
|
||||||
|
|
||||||
function didConfigFieldChange(
|
function didConfigFieldChange(
|
||||||
previous: Record<string, unknown> | undefined,
|
previous: Record<string, unknown> | undefined,
|
||||||
next: Record<string, unknown> | undefined,
|
next: Record<string, unknown> | undefined,
|
||||||
@@ -1508,5 +1516,95 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
app.get('/opencode-server-auth', async (c) => {
|
||||||
|
try {
|
||||||
|
const hasConfiguredPassword = settingsService.hasConfiguredOpenCodeServerPassword()
|
||||||
|
const envPasswordExists = !!ENV.OPENCODE.SERVER_PASSWORD
|
||||||
|
|
||||||
|
let source: 'configured' | 'env' | 'none'
|
||||||
|
if (hasConfiguredPassword) {
|
||||||
|
source = 'configured'
|
||||||
|
} else if (envPasswordExists) {
|
||||||
|
source = 'env'
|
||||||
|
} else {
|
||||||
|
source = 'none'
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
username: ENV.OPENCODE.SERVER_USERNAME,
|
||||||
|
hasPassword: hasConfiguredPassword || envPasswordExists,
|
||||||
|
source,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to get OpenCode server auth settings:', error)
|
||||||
|
return c.json({ error: 'Failed to get OpenCode server auth settings' }, 500)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.patch('/opencode-server-auth', async (c) => {
|
||||||
|
try {
|
||||||
|
const body = await c.req.json()
|
||||||
|
const validated = UpdateOpenCodeServerAuthSettingsSchema.parse(body)
|
||||||
|
|
||||||
|
if (validated.password && validated.clearPassword) {
|
||||||
|
return c.json({ error: 'Cannot set and clear password simultaneously' }, 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
let serverRestarted = false
|
||||||
|
let restartError: string | undefined
|
||||||
|
|
||||||
|
if (validated.clearPassword) {
|
||||||
|
settingsService.clearOpenCodeServerPassword()
|
||||||
|
logger.info('Cleared stored OpenCode server password')
|
||||||
|
} else if (validated.password) {
|
||||||
|
settingsService.setOpenCodeServerPassword(validated.password)
|
||||||
|
logger.info('Stored new OpenCode server password')
|
||||||
|
} else {
|
||||||
|
const hasConfiguredPassword = settingsService.hasConfiguredOpenCodeServerPassword()
|
||||||
|
const envPasswordExists = !!ENV.OPENCODE.SERVER_PASSWORD
|
||||||
|
const source = hasConfiguredPassword ? 'configured' : envPasswordExists ? 'env' : 'none'
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
username: ENV.OPENCODE.SERVER_USERNAME,
|
||||||
|
hasPassword: hasConfiguredPassword || envPasswordExists,
|
||||||
|
source,
|
||||||
|
serverRestarted: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const restartStatus = await restartOpenCode(openCodeSupervisor)
|
||||||
|
restartError = getRestartFailureMessage(restartStatus)
|
||||||
|
serverRestarted = !restartError
|
||||||
|
if (restartError) {
|
||||||
|
logger.warn('OpenCode server restart after password change finished unhealthy:', restartError)
|
||||||
|
} else {
|
||||||
|
logger.info('OpenCode server restarted after password change')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('Failed to restart OpenCode server after password change:', error)
|
||||||
|
restartError = error instanceof Error ? error.message : 'Unknown error'
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasConfiguredPassword = settingsService.hasConfiguredOpenCodeServerPassword()
|
||||||
|
const envPasswordExists = !!ENV.OPENCODE.SERVER_PASSWORD
|
||||||
|
const source = hasConfiguredPassword ? 'configured' : envPasswordExists ? 'env' : 'none'
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
username: ENV.OPENCODE.SERVER_USERNAME,
|
||||||
|
hasPassword: hasConfiguredPassword || envPasswordExists,
|
||||||
|
source,
|
||||||
|
serverRestarted,
|
||||||
|
restartError,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to update OpenCode server auth settings:', error)
|
||||||
|
if (error instanceof z.ZodError) {
|
||||||
|
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
|
||||||
|
}
|
||||||
|
return c.json({ error: 'Failed to update OpenCode server auth settings' }, 500)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
return app
|
return app
|
||||||
}
|
}
|
||||||
@@ -26,11 +26,7 @@ const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
|
|||||||
const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST
|
const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST
|
||||||
const OPENCODE_SERVER_CONNECT_HOST = OPENCODE_SERVER_HOST === '0.0.0.0' ? '127.0.0.1' : OPENCODE_SERVER_HOST
|
const OPENCODE_SERVER_CONNECT_HOST = OPENCODE_SERVER_HOST === '0.0.0.0' ? '127.0.0.1' : OPENCODE_SERVER_HOST
|
||||||
const OPENCODE_SERVER_PUBLIC_URL = ENV.OPENCODE.PUBLIC_URL
|
const OPENCODE_SERVER_PUBLIC_URL = ENV.OPENCODE.PUBLIC_URL
|
||||||
const OPENCODE_SERVER_PASSWORD = ENV.OPENCODE.SERVER_PASSWORD
|
|
||||||
const OPENCODE_SERVER_USERNAME = ENV.OPENCODE.SERVER_USERNAME
|
const OPENCODE_SERVER_USERNAME = ENV.OPENCODE.SERVER_USERNAME
|
||||||
const OPENCODE_BASIC_AUTH = OPENCODE_SERVER_PASSWORD
|
|
||||||
? `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${OPENCODE_SERVER_PASSWORD}`).toString('base64')}`
|
|
||||||
: ''
|
|
||||||
const MIN_OPENCODE_VERSION = '1.0.137'
|
const MIN_OPENCODE_VERSION = '1.0.137'
|
||||||
const MAX_STDERR_SIZE = 10240
|
const MAX_STDERR_SIZE = 10240
|
||||||
|
|
||||||
@@ -105,6 +101,29 @@ class OpenCodeServerManager {
|
|||||||
|
|
||||||
private constructor() {}
|
private constructor() {}
|
||||||
|
|
||||||
|
private getSettingsService(): SettingsService | undefined {
|
||||||
|
if (!this.db) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
return new SettingsService(this.db)
|
||||||
|
}
|
||||||
|
|
||||||
|
private getOpenCodeServerPassword(): string {
|
||||||
|
const settingsService = this.getSettingsService()
|
||||||
|
if (settingsService) {
|
||||||
|
return settingsService.getOpenCodeServerPassword()
|
||||||
|
}
|
||||||
|
return ENV.OPENCODE.SERVER_PASSWORD
|
||||||
|
}
|
||||||
|
|
||||||
|
private getOpenCodeBasicAuth(): string {
|
||||||
|
const password = this.getOpenCodeServerPassword()
|
||||||
|
if (!password) {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
return `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${password}`).toString('base64')}`
|
||||||
|
}
|
||||||
|
|
||||||
setDatabase(db: Database) {
|
setDatabase(db: Database) {
|
||||||
this.db = db
|
this.db = db
|
||||||
}
|
}
|
||||||
@@ -268,6 +287,8 @@ class OpenCodeServerManager {
|
|||||||
|
|
||||||
let stderrOutput = ''
|
let stderrOutput = ''
|
||||||
|
|
||||||
|
const opencodeServerPassword = this.getOpenCodeServerPassword()
|
||||||
|
|
||||||
const cleanEnv = { ...process.env }
|
const cleanEnv = { ...process.env }
|
||||||
delete cleanEnv.OPENCODE_SERVER_PASSWORD
|
delete cleanEnv.OPENCODE_SERVER_PASSWORD
|
||||||
delete cleanEnv.OPENCODE_RUN_ID
|
delete cleanEnv.OPENCODE_RUN_ID
|
||||||
@@ -291,12 +312,10 @@ class OpenCodeServerManager {
|
|||||||
XDG_STATE_HOME: path.join(openCodeServerDirectory, '.opencode/state'),
|
XDG_STATE_HOME: path.join(openCodeServerDirectory, '.opencode/state'),
|
||||||
XDG_CONFIG_HOME: path.join(openCodeServerDirectory, '.config'),
|
XDG_CONFIG_HOME: path.join(openCodeServerDirectory, '.config'),
|
||||||
...(OPENCODE_SERVER_PUBLIC_URL ? { OPENCODE_PUBLIC_URL: OPENCODE_SERVER_PUBLIC_URL } : {}),
|
...(OPENCODE_SERVER_PUBLIC_URL ? { OPENCODE_PUBLIC_URL: OPENCODE_SERVER_PUBLIC_URL } : {}),
|
||||||
...(OPENCODE_SERVER_PASSWORD
|
...(opencodeServerPassword ? {
|
||||||
? {
|
OPENCODE_SERVER_PASSWORD: opencodeServerPassword,
|
||||||
OPENCODE_SERVER_PASSWORD,
|
OPENCODE_SERVER_USERNAME,
|
||||||
OPENCODE_SERVER_USERNAME,
|
} : {}),
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
OPENCODE_CONFIG: openCodeConfigPath,
|
OPENCODE_CONFIG: openCodeConfigPath,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -547,8 +566,9 @@ class OpenCodeServerManager {
|
|||||||
async checkHealth(): Promise<boolean> {
|
async checkHealth(): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
const headers: Record<string, string> = {}
|
const headers: Record<string, string> = {}
|
||||||
if (OPENCODE_BASIC_AUTH) {
|
const basicAuth = this.getOpenCodeBasicAuth()
|
||||||
headers.Authorization = OPENCODE_BASIC_AUTH
|
if (basicAuth) {
|
||||||
|
headers.Authorization = basicAuth
|
||||||
}
|
}
|
||||||
const response = await fetch(`http://${OPENCODE_SERVER_CONNECT_HOST}:${OPENCODE_SERVER_PORT}/doc`, {
|
const response = await fetch(`http://${OPENCODE_SERVER_CONNECT_HOST}:${OPENCODE_SERVER_PORT}/doc`, {
|
||||||
signal: AbortSignal.timeout(3000),
|
signal: AbortSignal.timeout(3000),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Database } from 'bun:sqlite'
|
import { Database } from 'bun:sqlite'
|
||||||
import { unlinkSync, existsSync } from 'fs'
|
import { unlinkSync, existsSync } from 'fs'
|
||||||
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
|
import { getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env'
|
||||||
import { logger } from '../utils/logger'
|
import { logger } from '../utils/logger'
|
||||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
OpenCodeConfigSchema,
|
OpenCodeConfigSchema,
|
||||||
DEFAULT_USER_PREFERENCES,
|
DEFAULT_USER_PREFERENCES,
|
||||||
} from '../types/settings'
|
} from '../types/settings'
|
||||||
|
import { encryptSecret, decryptSecret } from '../utils/crypto'
|
||||||
|
|
||||||
interface OpenCodeConfigValidationIssue {
|
interface OpenCodeConfigValidationIssue {
|
||||||
path: string
|
path: string
|
||||||
@@ -597,4 +598,66 @@ export class SettingsService {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getSystemSetting(key: string): string | undefined {
|
||||||
|
const row = this.db
|
||||||
|
.query('SELECT value FROM system_settings WHERE key = ?')
|
||||||
|
.get(key) as { value: string } | undefined
|
||||||
|
|
||||||
|
return row?.value
|
||||||
|
}
|
||||||
|
|
||||||
|
setSystemSetting(key: string, value: string): void {
|
||||||
|
const updatedAt = Date.now()
|
||||||
|
this.db
|
||||||
|
.query(
|
||||||
|
`INSERT INTO system_settings (key, value, updated_at)
|
||||||
|
VALUES (?, ?, ?)
|
||||||
|
ON CONFLICT(key) DO UPDATE SET
|
||||||
|
value = excluded.value,
|
||||||
|
updated_at = excluded.updated_at`
|
||||||
|
)
|
||||||
|
.run(key, value, updatedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteSystemSetting(key: string): void {
|
||||||
|
this.db.query('DELETE FROM system_settings WHERE key = ?').run(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
getOpenCodeServerPassword(): string {
|
||||||
|
const encrypted = this.getSystemSetting('opencode.serverPassword')
|
||||||
|
if (!encrypted) {
|
||||||
|
return ENV.OPENCODE.SERVER_PASSWORD
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return decryptSecret(encrypted)
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('Failed to decrypt stored OpenCode server password, falling back to env:', error)
|
||||||
|
return ENV.OPENCODE.SERVER_PASSWORD
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hasConfiguredOpenCodeServerPassword(): boolean {
|
||||||
|
const encrypted = this.getSystemSetting('opencode.serverPassword')
|
||||||
|
if (!encrypted) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
decryptSecret(encrypted)
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setOpenCodeServerPassword(password: string): void {
|
||||||
|
const encrypted = encryptSecret(password)
|
||||||
|
this.setSystemSetting('opencode.serverPassword', encrypted)
|
||||||
|
}
|
||||||
|
|
||||||
|
clearOpenCodeServerPassword(): void {
|
||||||
|
this.deleteSystemSetting('opencode.serverPassword')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -43,6 +43,11 @@ vi.mock('../../src/constants', () => ({
|
|||||||
DEFAULT_AGENTS_MD: '# Test Agents MD',
|
DEFAULT_AGENTS_MD: '# Test Agents MD',
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
const mockHasConfiguredOpenCodeServerPassword = vi.fn()
|
||||||
|
const mockSetOpenCodeServerPassword = vi.fn()
|
||||||
|
const mockClearOpenCodeServerPassword = vi.fn()
|
||||||
|
const mockGetOpenCodeServerPassword = vi.fn()
|
||||||
|
|
||||||
vi.mock('../../src/services/settings', () => ({
|
vi.mock('../../src/services/settings', () => ({
|
||||||
SettingsService: vi.fn().mockImplementation(() => ({
|
SettingsService: vi.fn().mockImplementation(() => ({
|
||||||
getSettings: mockGetSettings,
|
getSettings: mockGetSettings,
|
||||||
@@ -53,6 +58,10 @@ vi.mock('../../src/services/settings', () => ({
|
|||||||
deleteOpenCodeConfig: mockDeleteOpenCodeConfig,
|
deleteOpenCodeConfig: mockDeleteOpenCodeConfig,
|
||||||
getOpenCodeConfigByName: mockGetOpenCodeConfigByName,
|
getOpenCodeConfigByName: mockGetOpenCodeConfigByName,
|
||||||
setDefaultOpenCodeConfig: mockSetDefaultOpenCodeConfig,
|
setDefaultOpenCodeConfig: mockSetDefaultOpenCodeConfig,
|
||||||
|
hasConfiguredOpenCodeServerPassword: mockHasConfiguredOpenCodeServerPassword,
|
||||||
|
setOpenCodeServerPassword: mockSetOpenCodeServerPassword,
|
||||||
|
clearOpenCodeServerPassword: mockClearOpenCodeServerPassword,
|
||||||
|
getOpenCodeServerPassword: mockGetOpenCodeServerPassword,
|
||||||
})),
|
})),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
@@ -1017,4 +1026,123 @@ describe('Settings Routes - OpenCode Upgrade', () => {
|
|||||||
expect(json.removedFields).toEqual([])
|
expect(json.removedFields).toEqual([])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('GET /opencode-server-auth', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
mockHasConfiguredOpenCodeServerPassword.mockReset()
|
||||||
|
mockGetOpenCodeServerPassword.mockReset()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return configured source when DB password exists', async () => {
|
||||||
|
mockHasConfiguredOpenCodeServerPassword.mockReturnValue(true)
|
||||||
|
|
||||||
|
const req = new Request('http://localhost/opencode-server-auth')
|
||||||
|
const res = await settingsApp.fetch(req)
|
||||||
|
const json = await res.json() as Record<string, unknown>
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(json.hasPassword).toBe(true)
|
||||||
|
expect(json.source).toBe('configured')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return none source when no password exists', async () => {
|
||||||
|
mockHasConfiguredOpenCodeServerPassword.mockReturnValue(false)
|
||||||
|
|
||||||
|
const req = new Request('http://localhost/opencode-server-auth')
|
||||||
|
const res = await settingsApp.fetch(req)
|
||||||
|
const json = await res.json() as Record<string, unknown>
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(json.hasPassword).toBe(false)
|
||||||
|
expect(json.source).toBe('none')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('PATCH /opencode-server-auth', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
mockHasConfiguredOpenCodeServerPassword.mockReset()
|
||||||
|
mockSetOpenCodeServerPassword.mockReset()
|
||||||
|
mockClearOpenCodeServerPassword.mockReset()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should store encrypted password and restart server', async () => {
|
||||||
|
mockHasConfiguredOpenCodeServerPassword.mockReturnValue(true)
|
||||||
|
|
||||||
|
const req = new Request('http://localhost/opencode-server-auth', {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify({ password: 'new_password' }),
|
||||||
|
})
|
||||||
|
const res = await settingsApp.fetch(req)
|
||||||
|
const json = await res.json() as Record<string, unknown>
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(mockSetOpenCodeServerPassword).toHaveBeenCalledWith('new_password')
|
||||||
|
expect(json.hasPassword).toBe(true)
|
||||||
|
expect(json.source).toBe('configured')
|
||||||
|
expect(json.serverRestarted).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should clear password when clearPassword is true', async () => {
|
||||||
|
mockHasConfiguredOpenCodeServerPassword.mockReturnValue(false)
|
||||||
|
|
||||||
|
const req = new Request('http://localhost/opencode-server-auth', {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify({ clearPassword: true }),
|
||||||
|
})
|
||||||
|
const res = await settingsApp.fetch(req)
|
||||||
|
const json = await res.json() as Record<string, unknown>
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(mockClearOpenCodeServerPassword).toHaveBeenCalled()
|
||||||
|
expect(json.hasPassword).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should report restart error when supervisor restart returns unhealthy status', async () => {
|
||||||
|
mockHasConfiguredOpenCodeServerPassword.mockReturnValue(true)
|
||||||
|
const restart = vi.fn().mockResolvedValue({
|
||||||
|
state: 'failed',
|
||||||
|
healthy: false,
|
||||||
|
port: 5551,
|
||||||
|
version: null,
|
||||||
|
minVersion: '1.0.137',
|
||||||
|
versionSupported: false,
|
||||||
|
lastError: 'OpenCode failed to restart',
|
||||||
|
activeRecoveryAction: null,
|
||||||
|
attemptedRecoveryActions: [],
|
||||||
|
nextRecoveryAction: null,
|
||||||
|
failureCount: 1,
|
||||||
|
watching: false,
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
const supervisorApp = createSettingsRoutes(
|
||||||
|
testDb,
|
||||||
|
{ getGitEnvironment: vi.fn().mockReturnValue({}) } as any,
|
||||||
|
{ restart } as any,
|
||||||
|
)
|
||||||
|
|
||||||
|
const req = new Request('http://localhost/opencode-server-auth', {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify({ password: 'new_password' }),
|
||||||
|
})
|
||||||
|
const res = await supervisorApp.fetch(req)
|
||||||
|
const json = await res.json() as Record<string, unknown>
|
||||||
|
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(json.serverRestarted).toBe(false)
|
||||||
|
expect(json.restartError).toBe('OpenCode failed to restart')
|
||||||
|
expect(restart).toHaveBeenCalledWith('settings_restart')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should reject request when both password and clearPassword are provided', async () => {
|
||||||
|
const req = new Request('http://localhost/opencode-server-auth', {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify({ password: 'test', clearPassword: true }),
|
||||||
|
})
|
||||||
|
const res = await settingsApp.fetch(req)
|
||||||
|
|
||||||
|
expect(res.status).toBe(400)
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import type { Database } from 'bun:sqlite'
|
||||||
|
|
||||||
|
vi.mock('bun:sqlite', () => ({
|
||||||
|
Database: vi.fn().mockImplementation(() => ({
|
||||||
|
query: vi.fn(),
|
||||||
|
})),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/utils/crypto', () => ({
|
||||||
|
encryptSecret: vi.fn((plaintext) => `encrypted:${plaintext}`),
|
||||||
|
decryptSecret: vi.fn((encrypted) => {
|
||||||
|
if (encrypted.startsWith('encrypted:')) {
|
||||||
|
return encrypted.slice(10)
|
||||||
|
}
|
||||||
|
throw new Error('Invalid encrypted data format')
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||||
|
ENV: {
|
||||||
|
OPENCODE: {
|
||||||
|
SERVER_PASSWORD: 'env_password',
|
||||||
|
SERVER_USERNAME: 'opencode',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
import { SettingsService } from '../../src/services/settings'
|
||||||
|
|
||||||
|
describe('SettingsService - system settings', () => {
|
||||||
|
let settingsService: SettingsService
|
||||||
|
let mockGet: ReturnType<typeof vi.fn>
|
||||||
|
let mockRun: ReturnType<typeof vi.fn>
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
mockGet = vi.fn()
|
||||||
|
mockRun = vi.fn()
|
||||||
|
const mockDb = {
|
||||||
|
query: vi.fn((sql: string) => {
|
||||||
|
if (sql.includes('SELECT')) {
|
||||||
|
return { get: mockGet }
|
||||||
|
}
|
||||||
|
return { run: mockRun }
|
||||||
|
}),
|
||||||
|
} as unknown as Database
|
||||||
|
settingsService = new SettingsService(mockDb)
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('getSystemSetting', () => {
|
||||||
|
it('returns the value when key exists', () => {
|
||||||
|
mockGet.mockReturnValue({ value: 'test-value' })
|
||||||
|
|
||||||
|
const result = settingsService.getSystemSetting('test.key')
|
||||||
|
|
||||||
|
expect(result).toBe('test-value')
|
||||||
|
expect(mockGet).toHaveBeenCalledWith('test.key')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns undefined when key does not exist', () => {
|
||||||
|
mockGet.mockReturnValue(undefined)
|
||||||
|
|
||||||
|
const result = settingsService.getSystemSetting('nonexistent')
|
||||||
|
|
||||||
|
expect(result).toBeUndefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('setSystemSetting', () => {
|
||||||
|
it('inserts or updates the setting', () => {
|
||||||
|
settingsService.setSystemSetting('test.key', 'test-value')
|
||||||
|
|
||||||
|
expect(mockRun).toHaveBeenCalledWith(
|
||||||
|
'test.key',
|
||||||
|
'test-value',
|
||||||
|
expect.any(Number),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('deleteSystemSetting', () => {
|
||||||
|
it('deletes the setting by key', () => {
|
||||||
|
settingsService.deleteSystemSetting('test.key')
|
||||||
|
|
||||||
|
expect(mockRun).toHaveBeenCalledWith('test.key')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('getOpenCodeServerPassword', () => {
|
||||||
|
it('returns decrypted stored password when present', () => {
|
||||||
|
mockGet.mockReturnValue({ value: 'encrypted:stored_password' })
|
||||||
|
|
||||||
|
const result = settingsService.getOpenCodeServerPassword()
|
||||||
|
|
||||||
|
expect(result).toBe('stored_password')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to env password when no stored password', () => {
|
||||||
|
mockGet.mockReturnValue(undefined)
|
||||||
|
|
||||||
|
const result = settingsService.getOpenCodeServerPassword()
|
||||||
|
|
||||||
|
expect(result).toBe('env_password')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to env password when decrypt fails', () => {
|
||||||
|
mockGet.mockReturnValue({ value: 'invalid_encrypted' })
|
||||||
|
|
||||||
|
const result = settingsService.getOpenCodeServerPassword()
|
||||||
|
|
||||||
|
expect(result).toBe('env_password')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('hasConfiguredOpenCodeServerPassword', () => {
|
||||||
|
it('returns true when stored password exists and is valid', () => {
|
||||||
|
mockGet.mockReturnValue({ value: 'encrypted:stored_password' })
|
||||||
|
|
||||||
|
const result = settingsService.hasConfiguredOpenCodeServerPassword()
|
||||||
|
|
||||||
|
expect(result).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns false when no stored password', () => {
|
||||||
|
mockGet.mockReturnValue(undefined)
|
||||||
|
|
||||||
|
const result = settingsService.hasConfiguredOpenCodeServerPassword()
|
||||||
|
|
||||||
|
expect(result).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns false when decrypt fails', () => {
|
||||||
|
mockGet.mockReturnValue({ value: 'invalid' })
|
||||||
|
|
||||||
|
const result = settingsService.hasConfiguredOpenCodeServerPassword()
|
||||||
|
|
||||||
|
expect(result).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('setOpenCodeServerPassword', () => {
|
||||||
|
it('encrypts and stores the password', () => {
|
||||||
|
settingsService.setOpenCodeServerPassword('new_password')
|
||||||
|
|
||||||
|
expect(mockRun).toHaveBeenCalledWith(
|
||||||
|
'opencode.serverPassword',
|
||||||
|
'encrypted:new_password',
|
||||||
|
expect.any(Number),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('clearOpenCodeServerPassword', () => {
|
||||||
|
it('deletes the stored password', () => {
|
||||||
|
settingsService.clearOpenCodeServerPassword()
|
||||||
|
|
||||||
|
expect(mockRun).toHaveBeenCalledWith('opencode.serverPassword')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -11,6 +11,9 @@ import type {
|
|||||||
CreateSkillRequest,
|
CreateSkillRequest,
|
||||||
UpdateSkillRequest,
|
UpdateSkillRequest,
|
||||||
SkillScope,
|
SkillScope,
|
||||||
|
OpenCodeServerAuthSettings,
|
||||||
|
UpdateOpenCodeServerAuthSettings,
|
||||||
|
OpenCodeServerAuthSettingsResponse,
|
||||||
} from './types/settings'
|
} from './types/settings'
|
||||||
import { API_BASE_URL } from '@/config'
|
import { API_BASE_URL } from '@/config'
|
||||||
import { fetchWrapper, FetchError } from './fetchWrapper'
|
import { fetchWrapper, FetchError } from './fetchWrapper'
|
||||||
@@ -269,6 +272,18 @@ export const settingsApi = {
|
|||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getOpenCodeServerAuthSettings: async (): Promise<OpenCodeServerAuthSettings> => {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-server-auth`)
|
||||||
|
},
|
||||||
|
|
||||||
|
updateOpenCodeServerAuthSettings: async (request: UpdateOpenCodeServerAuthSettings): Promise<OpenCodeServerAuthSettingsResponse> => {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-server-auth`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(request),
|
||||||
|
})
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface VersionInfo {
|
export interface VersionInfo {
|
||||||
|
|||||||
@@ -132,3 +132,19 @@ export interface SyncOpenCodeImportResponse extends OpenCodeImportStatus {
|
|||||||
errors: Array<{ path: string; error: string }>
|
errors: Array<{ path: string; error: string }>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface OpenCodeServerAuthSettings {
|
||||||
|
username: string
|
||||||
|
hasPassword: boolean
|
||||||
|
source: 'configured' | 'env' | 'none'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateOpenCodeServerAuthSettings {
|
||||||
|
password?: string
|
||||||
|
clearPassword?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OpenCodeServerAuthSettingsResponse extends OpenCodeServerAuthSettings {
|
||||||
|
serverRestarted: boolean
|
||||||
|
restartError?: string
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useOpenCodeServerAuthSettings } from '@/hooks/useOpenCodeServerAuthSettings'
|
||||||
|
import { showToast } from '@/lib/toast'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Loader2, Key } from 'lucide-react'
|
||||||
|
|
||||||
|
export function OpenCodeServerAuthSettings() {
|
||||||
|
const { settings, isLoading, updateAuthSettingsAsync, isUpdating } = useOpenCodeServerAuthSettings()
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!password.trim()) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await updateAuthSettingsAsync({ password: password.trim() })
|
||||||
|
setPassword('')
|
||||||
|
|
||||||
|
if (result.serverRestarted) {
|
||||||
|
showToast.success('Password updated and OpenCode server restarted')
|
||||||
|
} else if (result.restartError) {
|
||||||
|
showToast.success('Password updated (restart failed: ' + result.restartError + ')')
|
||||||
|
} else {
|
||||||
|
showToast.success('Password updated')
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
showToast.error('Failed to update password')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleClear = async () => {
|
||||||
|
try {
|
||||||
|
const result = await updateAuthSettingsAsync({ clearPassword: true })
|
||||||
|
|
||||||
|
if (result.serverRestarted) {
|
||||||
|
showToast.success('Password cleared and OpenCode server restarted')
|
||||||
|
} else if (result.restartError) {
|
||||||
|
showToast.success('Password cleared (restart failed: ' + result.restartError + ')')
|
||||||
|
} else {
|
||||||
|
showToast.success('Password cleared')
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
showToast.error('Failed to clear password')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getPasswordStatusText = () => {
|
||||||
|
if (!settings) return 'Loading...'
|
||||||
|
|
||||||
|
switch (settings.source) {
|
||||||
|
case 'configured':
|
||||||
|
return 'Password configured in Web UI'
|
||||||
|
case 'env':
|
||||||
|
return 'Using environment password'
|
||||||
|
case 'none':
|
||||||
|
return 'No password configured'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const showClearButton = settings?.source === 'configured'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-card border border-border rounded-lg p-6">
|
||||||
|
<h2 className="text-lg font-semibold text-foreground mb-6 flex items-center gap-2">
|
||||||
|
<Key className="h-5 w-5" />
|
||||||
|
OpenCode Server Authentication
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Username</Label>
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
{settings?.username || 'Loading...'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Password Status</Label>
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
{getPasswordStatusText()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">New Password</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
placeholder="Leave blank to keep current password"
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Set a new password for the OpenCode server Basic Auth
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={!password.trim() || isUpdating}
|
||||||
|
>
|
||||||
|
{isUpdating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
Save Password
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{showClearButton && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleClear}
|
||||||
|
disabled={isUpdating}
|
||||||
|
>
|
||||||
|
{isUpdating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
|
Clear Web UI Password
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { GeneralSettings } from '@/components/settings/GeneralSettings'
|
|||||||
import { GitSettings } from '@/components/settings/GitSettings'
|
import { GitSettings } from '@/components/settings/GitSettings'
|
||||||
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
|
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
|
||||||
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
|
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
|
||||||
|
import { OpenCodeServerAuthSettings } from '@/components/settings/OpenCodeServerAuthSettings'
|
||||||
import { ProviderSettings } from '@/components/settings/ProviderSettings'
|
import { ProviderSettings } from '@/components/settings/ProviderSettings'
|
||||||
import { AccountSettings } from '@/components/settings/AccountSettings'
|
import { AccountSettings } from '@/components/settings/AccountSettings'
|
||||||
import { VoiceSettings } from '@/components/settings/VoiceSettings'
|
import { VoiceSettings } from '@/components/settings/VoiceSettings'
|
||||||
@@ -118,7 +119,12 @@ export function SettingsDialog() {
|
|||||||
<TabsContent key="voice" value="voice" className="mt-0"><VoiceSettings /></TabsContent>
|
<TabsContent key="voice" value="voice" className="mt-0"><VoiceSettings /></TabsContent>
|
||||||
<TabsContent key="git" value="git" className="mt-0"><GitSettings /></TabsContent>
|
<TabsContent key="git" value="git" className="mt-0"><GitSettings /></TabsContent>
|
||||||
<TabsContent key="shortcuts" value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
|
<TabsContent key="shortcuts" value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
|
||||||
<TabsContent key="opencode" value="opencode" className="mt-0"><OpenCodeConfigManager /></TabsContent>
|
<TabsContent key="opencode" value="opencode" className="mt-0">
|
||||||
|
<div className="space-y-6">
|
||||||
|
<OpenCodeServerAuthSettings />
|
||||||
|
<OpenCodeConfigManager />
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
<TabsContent key="providers" value="providers" className="mt-0"><ProviderSettings /></TabsContent>
|
<TabsContent key="providers" value="providers" className="mt-0"><ProviderSettings /></TabsContent>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -184,7 +190,12 @@ export function SettingsDialog() {
|
|||||||
{mobileView === 'voice' && <div key="voice"><VoiceSettings /></div>}
|
{mobileView === 'voice' && <div key="voice"><VoiceSettings /></div>}
|
||||||
{mobileView === 'git' && <div key="git"><GitSettings /></div>}
|
{mobileView === 'git' && <div key="git"><GitSettings /></div>}
|
||||||
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
|
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
|
||||||
{mobileView === 'opencode' && <div key="opencode"><OpenCodeConfigManager /></div>}
|
{mobileView === 'opencode' && (
|
||||||
|
<div key="opencode" className="space-y-6">
|
||||||
|
<OpenCodeServerAuthSettings />
|
||||||
|
<OpenCodeConfigManager />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}
|
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { settingsApi } from '@/api/settings'
|
||||||
|
import type { OpenCodeServerAuthSettings, UpdateOpenCodeServerAuthSettings } from '@/api/types/settings'
|
||||||
|
|
||||||
|
export function useOpenCodeServerAuthSettings() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const { data: settings, isLoading, error } = useQuery<OpenCodeServerAuthSettings>({
|
||||||
|
queryKey: ['settings', 'opencode-server-auth'],
|
||||||
|
queryFn: () => settingsApi.getOpenCodeServerAuthSettings(),
|
||||||
|
})
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: (request: UpdateOpenCodeServerAuthSettings) =>
|
||||||
|
settingsApi.updateOpenCodeServerAuthSettings(request),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['settings', 'opencode-server-auth'] })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
settings,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
updateAuthSettingsAsync: mutation.mutateAsync,
|
||||||
|
isUpdating: mutation.isPending,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -328,3 +328,17 @@ export const OpenCodeConfigResponseSchema = z.object({
|
|||||||
configs: z.array(OpenCodeConfigMetadataSchema),
|
configs: z.array(OpenCodeConfigMetadataSchema),
|
||||||
defaultConfig: OpenCodeConfigMetadataSchema.nullable(),
|
defaultConfig: OpenCodeConfigMetadataSchema.nullable(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const OpenCodeServerAuthSettingsSchema = z.object({
|
||||||
|
username: z.string().min(1),
|
||||||
|
hasPassword: z.boolean(),
|
||||||
|
source: z.enum(['configured', 'env', 'none']),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const UpdateOpenCodeServerAuthSettingsSchema = z.object({
|
||||||
|
password: z.string().min(1).optional(),
|
||||||
|
clearPassword: z.boolean().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type OpenCodeServerAuthSettings = z.infer<typeof OpenCodeServerAuthSettingsSchema>;
|
||||||
|
export type UpdateOpenCodeServerAuthSettings = z.infer<typeof UpdateOpenCodeServerAuthSettingsSchema>;
|
||||||
Reference in new issue
Block a user