feature/oidc-login #12

Merged
hzhang merged 5 commits from feature/oidc-login into main 2026-05-17 21:27:55 +00:00
13 changed files with 612 additions and 43 deletions

View File

@@ -12,5 +12,15 @@ RUN npm install -g serve@14
WORKDIR /app
COPY --from=build /app ./
ENV FRONTEND_DEV_MODE=0
# OIDC-only mode flag. Injected into the SPA at container start as
# /runtime-config.js so the setup wizard knows it before the backend
# exists; /auth/config remains authoritative once the backend is up.
ARG HARBORFORGE_OIDC_ONLY=false
ENV HARBORFORGE_OIDC_ONLY=${HARBORFORGE_OIDC_ONLY}
EXPOSE 3000
CMD ["sh", "-c", "if [ \"$FRONTEND_DEV_MODE\" = \"1\" ]; then npm run dev -- --host 0.0.0.0 --port 3000 --strictPort; else serve -s dist -l 3000; fi"]
CMD ["sh", "-c", "\
if [ \"$HARBORFORGE_OIDC_ONLY\" = \"true\" ]; then OO=true; else OO=false; fi; \
CFG=\"window.__HF_RUNTIME__={\\\"oidc_only\\\":$OO};\"; \
mkdir -p public; printf '%s' \"$CFG\" > public/runtime-config.js; \
[ -d dist ] && printf '%s' \"$CFG\" > dist/runtime-config.js; \
if [ \"$FRONTEND_DEV_MODE\" = \"1\" ]; then npm run dev -- --host 0.0.0.0 --port 3000 --strictPort; else serve -s dist -l 3000; fi"]

View File

@@ -8,6 +8,9 @@
</head>
<body>
<div id="root"></div>
<!-- Runtime config injected by the container entrypoint (deploy-time
HARBORFORGE_OIDC_ONLY). Absent in dev → app falls back to /auth/config. -->
<script src="/runtime-config.js"></script>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -20,6 +20,8 @@ import UsersPage from '@/pages/UsersPage'
import CalendarPage from '@/pages/CalendarPage'
import SupportDetailPage from '@/pages/SupportDetailPage'
import MeetingDetailPage from '@/pages/MeetingDetailPage'
import OidcCallbackPage from '@/pages/OidcCallbackPage'
import OidcSettingsPage from '@/pages/OidcSettingsPage'
import axios from 'axios'
const getStoredWizardPort = (): number | null => {
@@ -35,7 +37,7 @@ type AppState = 'checking' | 'setup' | 'ready'
export default function App() {
const [appState, setAppState] = useState<AppState>('checking')
const { user, loading, login, logout } = useAuth()
const { user, loading, login, loginWithToken, logout } = useAuth()
useEffect(() => {
checkInitialized()
@@ -100,6 +102,7 @@ export default function App() {
<Route path="/users" element={<UsersPage />} />
<Route path="/monitor" element={<MonitorPage />} />
<Route path="/login" element={<LoginPage onLogin={login} />} />
<Route path="/oidc/callback" element={<OidcCallbackPage onToken={loginWithToken} />} />
<Route path="*" element={<Navigate to="/monitor" />} />
</Routes>
</main>
@@ -133,6 +136,8 @@ export default function App() {
<Route path="/roles" element={<RoleEditorPage />} />
<Route path="/users" element={<UsersPage />} />
<Route path="/monitor" element={<MonitorPage />} />
{user?.is_admin && <Route path="/settings/oidc" element={<OidcSettingsPage />} />}
<Route path="/oidc/callback" element={<OidcCallbackPage onToken={loginWithToken} />} />
<Route path="*" element={<Navigate to="/" />} />
</Routes>
</main>

View File

@@ -1,6 +1,7 @@
import { useState, useEffect } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import api from '@/services/api'
import { useAuthConfig, oidcLinkHref } from '@/hooks/useAuthConfig'
import type { User } from '@/types'
interface Props {
@@ -11,6 +12,7 @@ interface Props {
export default function Sidebar({ user, onLogout }: Props) {
const { pathname } = useLocation()
const navigate = useNavigate()
const { config: authCfg } = useAuthConfig()
const [unreadCount, setUnreadCount] = useState(0)
useEffect(() => {
@@ -39,6 +41,7 @@ export default function Sidebar({ user, onLogout }: Props) {
...(user.is_admin ? [
{ to: '/users', icon: '👥', label: 'Users' },
{ to: '/roles', icon: '🔐', label: 'Roles' },
{ to: '/settings/oidc', icon: '🪪', label: 'OIDC' },
] : []),
] : [
{ to: '/monitor', icon: '📡', label: 'Monitor' },
@@ -64,6 +67,11 @@ export default function Sidebar({ user, onLogout }: Props) {
<button onClick={() => navigate('/login')}>Log in</button>
)}
</div>
{user && authCfg.oidcEnabled && !authCfg.oidcOnly && (
<div className="sidebar-footer" style={{ borderTop: 'none', paddingTop: 0 }}>
<a href={oidcLinkHref()} title="Link your account to an OIDC identity">🔗 Link OIDC account</a>
</div>
)}
</nav>
)
}

View File

@@ -44,10 +44,16 @@ export function useAuth() {
await fetchUser()
}
const loginWithToken = async (token: string) => {
localStorage.setItem('token', token)
setState((s) => ({ ...s, token }))
await fetchUser()
}
const logout = () => {
localStorage.removeItem('token')
setState({ user: null, token: null, loading: false })
}
return { ...state, login, logout }
return { ...state, login, loginWithToken, logout }
}

View File

@@ -0,0 +1,76 @@
import { useState, useEffect } from 'react'
import api from '@/services/api'
export interface AuthConfig {
oidcEnabled: boolean
oidcOnly: boolean
passwordLogin: boolean
oidcLoginUrl: string
}
const DEFAULT: AuthConfig = {
oidcEnabled: false,
oidcOnly: false,
passwordLogin: true,
oidcLoginUrl: '/auth/oidc/login',
}
let cache: AuthConfig | null = null
let inflight: Promise<AuthConfig> | null = null
async function load(): Promise<AuthConfig> {
if (cache) return cache
if (inflight) return inflight
inflight = api
.get('/auth/config')
.then(({ data }) => {
cache = {
oidcEnabled: !!data.oidc_enabled,
oidcOnly: !!data.oidc_only,
passwordLogin: data.password_login !== false,
oidcLoginUrl: data.oidc_login_url || '/auth/oidc/login',
}
return cache
})
.catch(() => {
// Backend unreachable / old backend without /auth/config:
// fall back to password-only so login is never fully blocked.
cache = { ...DEFAULT }
return cache
})
.finally(() => {
inflight = null
})
return inflight
}
/** Absolute backend URL for full-page OIDC redirects. */
export function oidcLoginHref(cfg: AuthConfig): string {
const base = localStorage.getItem('HF_BACKEND_BASE_URL') ?? ''
return `${base}${cfg.oidcLoginUrl}`
}
export function oidcLinkHref(): string {
const base = localStorage.getItem('HF_BACKEND_BASE_URL') ?? ''
return `${base}/auth/oidc/link`
}
export function useAuthConfig() {
const [config, setConfig] = useState<AuthConfig | null>(cache)
const [loading, setLoading] = useState(!cache)
useEffect(() => {
let alive = true
load().then((c) => {
if (alive) {
setConfig(c)
setLoading(false)
}
})
return () => {
alive = false
}
}, [])
return { config: config ?? DEFAULT, loading }
}

View File

@@ -1,15 +1,30 @@
import React, { useState } from 'react'
import { useAuthConfig, oidcLoginHref } from '@/hooks/useAuthConfig'
interface Props {
onLogin: (username: string, password: string) => Promise<void>
}
const OIDC_ERRORS: Record<string, string> = {
not_linked: 'This OIDC account is not linked to any HarborForge user. Ask an administrator to bind it first.',
exchange_failed: 'OIDC sign-in failed during token exchange. Please try again.',
no_subject: 'The identity provider did not return a subject. Sign-in aborted.',
token_rejected: 'The issued session token was rejected. Please try again.',
missing_token: 'No session token was returned. Please try again.',
link_not_allowed: 'Account linking is not allowed in this mode.',
already_bound: 'That OIDC identity is already bound to another user.',
}
export default function LoginPage({ onLogin }: Props) {
const { config, loading: cfgLoading } = useAuthConfig()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const urlError = new URLSearchParams(window.location.search).get('oidc_error')
const oidcError = urlError ? (OIDC_ERRORS[urlError] || `OIDC error: ${urlError}`) : ''
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
@@ -23,31 +38,58 @@ export default function LoginPage({ onLogin }: Props) {
}
}
const showPassword = !cfgLoading && config.passwordLogin && !config.oidcOnly
const showOidc = !cfgLoading && config.oidcEnabled
return (
<div className="login-page">
<div className="login-card">
<h1> HarborForge</h1>
<p className="subtitle">Agent/Human collaborative task management platform</p>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
{error && <p className="error">{error}</p>}
<button type="submit" disabled={loading}>
{loading ? 'Signing in...' : 'Sign in'}
</button>
</form>
{oidcError && <p className="error" style={{ marginBottom: 14 }}>{oidcError}</p>}
{showPassword && (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
{error && <p className="error">{error}</p>}
<button type="submit" disabled={loading}>
{loading ? 'Signing in...' : 'Sign in'}
</button>
</form>
)}
{showPassword && showOidc && (
<p className="text-dim" style={{ textAlign: 'center', margin: '14px 0' }}> or </p>
)}
{showOidc && (
<a
className="btn-primary"
style={{ display: 'block', textAlign: 'center', textDecoration: 'none' }}
href={oidcLoginHref(config)}
>
Sign in with SSO
</a>
)}
{cfgLoading && <p className="subtitle">Loading sign-in options</p>}
{!cfgLoading && !showPassword && !showOidc && (
<p className="error">No sign-in method is available. Check server configuration.</p>
)}
</div>
</div>
)

View File

@@ -0,0 +1,55 @@
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
interface Props {
onToken: (token: string) => Promise<void>
}
/**
* Lands here after the backend OIDC callback redirect.
* - sign-in: URL fragment `#token=<jwt>` → apply token, go to dashboard
* - self-link: query `?oidc_linked=1` → success notice, go to /users
* - failure: query `?oidc_error=<code>` → back to /login with the code
*/
export default function OidcCallbackPage({ onToken }: Props) {
const navigate = useNavigate()
const [msg, setMsg] = useState('Completing sign-in…')
const ran = useRef(false)
useEffect(() => {
if (ran.current) return
ran.current = true
const hash = new URLSearchParams(window.location.hash.replace(/^#/, ''))
const query = new URLSearchParams(window.location.search)
const token = hash.get('token')
const oidcError = query.get('oidc_error')
const linked = query.get('oidc_linked')
if (oidcError) {
navigate(`/login?oidc_error=${encodeURIComponent(oidcError)}`, { replace: true })
return
}
if (linked) {
setMsg('OIDC account linked. Redirecting…')
const t = setTimeout(() => navigate('/users', { replace: true }), 1200)
return () => clearTimeout(t)
}
if (token) {
onToken(token)
.then(() => navigate('/', { replace: true }))
.catch(() => navigate('/login?oidc_error=token_rejected', { replace: true }))
return
}
navigate('/login?oidc_error=missing_token', { replace: true })
}, [navigate, onToken])
return (
<div className="login-page">
<div className="login-card">
<h1> HarborForge</h1>
<p className="subtitle">{msg}</p>
</div>
</div>
)
}

View File

@@ -0,0 +1,171 @@
import { useEffect, useState } from 'react'
import api from '@/services/api'
import { useAuth } from '@/hooks/useAuth'
interface Settings {
enabled: boolean
issuer: string | null
client_id: string | null
has_client_secret: boolean
redirect_uri: string | null
scopes: string | null
post_login_redirect: string | null
admin_role: string
oidc_only: boolean
effective_enabled: boolean
source: string
}
export default function OidcSettingsPage() {
const { user } = useAuth()
const isAdmin = user?.is_admin === true
const [loaded, setLoaded] = useState<Settings | null>(null)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [message, setMessage] = useState('')
const [form, setForm] = useState({
enabled: false,
issuer: '',
client_id: '',
client_secret: '',
redirect_uri: '',
scopes: 'openid email profile',
post_login_redirect: '',
admin_role: 'admin',
})
useEffect(() => {
if (!isAdmin) { setLoading(false); return }
api.get<Settings>('/auth/oidc/settings')
.then(({ data }) => {
setLoaded(data)
setForm({
enabled: data.enabled,
issuer: data.issuer || '',
client_id: data.client_id || '',
client_secret: '',
redirect_uri: data.redirect_uri || '',
scopes: data.scopes || 'openid email profile',
post_login_redirect: data.post_login_redirect || '',
admin_role: data.admin_role || 'admin',
})
})
.catch((e) => setMessage(e.response?.data?.detail || 'Failed to load OIDC settings'))
.finally(() => setLoading(false))
}, [isAdmin])
const save = async () => {
setSaving(true)
setMessage('')
try {
const payload: Record<string, any> = {
enabled: form.enabled,
issuer: form.issuer.trim(),
client_id: form.client_id.trim(),
redirect_uri: form.redirect_uri.trim(),
scopes: form.scopes.trim(),
post_login_redirect: form.post_login_redirect.trim(),
admin_role: form.admin_role.trim() || 'admin',
}
if (form.client_secret) payload.client_secret = form.client_secret
const { data } = await api.put<Settings>('/auth/oidc/settings', payload)
setLoaded(data)
setForm((f) => ({ ...f, client_secret: '' }))
setMessage('OIDC settings saved successfully')
} catch (e: any) {
setMessage(e.response?.data?.detail || 'Failed to save OIDC settings')
} finally {
setSaving(false)
}
}
if (loading) return <div className="loading">Loading OIDC settings...</div>
if (!isAdmin) {
return (
<div className="section">
<h2>🔐 OIDC Settings</h2>
<p className="empty">Admin access required.</p>
</div>
)
}
const callbackHint = form.redirect_uri.trim() || loaded?.redirect_uri || '(set the Redirect / Callback URL below)'
return (
<div className="section">
<div className="page-header">
<div>
<h2>🔐 OIDC Settings</h2>
<div className="text-dim">Configure the OpenID Connect provider. Saved values override environment defaults.</div>
</div>
</div>
{message && (
<div style={{
padding: '10px 12px', marginBottom: 16, borderRadius: 8,
background: message.includes('success') ? 'rgba(70,180,135,.14)' : 'rgba(226,85,60,.14)',
border: `1px solid ${message.includes('success') ? 'rgba(70,180,135,.4)' : 'rgba(226,85,60,.4)'}`,
}}>{message}</div>
)}
<div className="monitor-card" style={{ marginBottom: 16 }}>
<div className="monitor-card-header">
<div style={{ fontWeight: 600 }}>Status</div>
<span className={'badge ' + (loaded?.effective_enabled ? 'status-online' : 'status-offline')}>
{loaded?.effective_enabled ? 'OIDC active' : 'OIDC inactive'}
</span>
</div>
<div className="monitor-metrics">
config source: <b>{loaded?.source}</b> · OIDC-only mode (deploy env): <b>{loaded?.oidc_only ? 'on' : 'off'}</b>
</div>
<div style={{ marginTop: 8 }}>
<div className="text-dim">Register this Redirect / Callback URL at your identity provider:</div>
<code style={{ display: 'block', marginTop: 6, wordBreak: 'break-all' }}>{callbackHint}</code>
</div>
</div>
<div className="task-create-form" style={{ maxWidth: 640 }}>
<label className="filter-check">
<input type="checkbox" checked={form.enabled} onChange={(e) => setForm({ ...form, enabled: e.target.checked })} />
Enable OIDC sign-in
</label>
<label>
Issuer (OIDC source)
<input placeholder="https://idp.example.com" value={form.issuer} onChange={(e) => setForm({ ...form, issuer: e.target.value })} />
</label>
<label>
Client ID
<input value={form.client_id} onChange={(e) => setForm({ ...form, client_id: e.target.value })} />
</label>
<label>
Client Secret
<input type="password" placeholder={loaded?.has_client_secret ? '•••••• (leave blank to keep current)' : 'client secret'} value={form.client_secret} onChange={(e) => setForm({ ...form, client_secret: e.target.value })} />
</label>
<label>
Redirect / Callback URL
<input placeholder="https://hf-api.example.com/auth/oidc/callback" value={form.redirect_uri} onChange={(e) => setForm({ ...form, redirect_uri: e.target.value })} />
</label>
<label>
Scopes
<input value={form.scopes} onChange={(e) => setForm({ ...form, scopes: e.target.value })} />
</label>
<label>
Post-login redirect (frontend)
<input placeholder="https://hf.example.com/oidc/callback" value={form.post_login_redirect} onChange={(e) => setForm({ ...form, post_login_redirect: e.target.value })} />
</label>
<label>
Admin role (bootstrap)
<input placeholder="admin" value={form.admin_role} onChange={(e) => setForm({ ...form, admin_role: e.target.value })} />
</label>
<p className="text-dim">
OIDC-only bootstrap: before any admin is linked, an IdP user whose token carries this role
auto-connects to the HarborForge admin account on first sign-in. Disables itself once an admin is bound.
</p>
<button className="btn-primary" disabled={saving} onClick={save}>
{saving ? 'Saving...' : 'Save OIDC Settings'}
</button>
</div>
</div>
)
}

View File

@@ -1,5 +1,6 @@
import { useState } from 'react'
import axios from 'axios'
import { getRuntimeOidcOnly } from '@/runtime'
interface Props {
initialWizardPort: number | null
@@ -14,9 +15,18 @@ interface SetupForm {
backend_base_url: string
project_name: string
project_description: string
oidc_enabled: boolean
oidc_issuer: string
oidc_client_id: string
oidc_client_secret: string
oidc_redirect_uri: string
oidc_scopes: string
oidc_post_login_redirect: string
oidc_admin_role: string
}
const STEPS = ['Wizard', 'Admin', 'Backend', 'Finish']
const oidcOnly = getRuntimeOidcOnly() === true
const STEPS = ['Wizard', 'Admin', 'OIDC', 'Backend', 'Finish']
export default function SetupWizardPage({ initialWizardPort, onComplete }: Props) {
const [step, setStep] = useState(0)
@@ -35,9 +45,17 @@ export default function SetupWizardPage({ initialWizardPort, onComplete }: Props
backend_base_url: '',
project_name: '',
project_description: '',
oidc_enabled: oidcOnly,
oidc_issuer: '',
oidc_client_id: '',
oidc_client_secret: '',
oidc_redirect_uri: '',
oidc_scopes: 'openid email profile',
oidc_post_login_redirect: '',
oidc_admin_role: 'admin',
})
const set = (key: keyof SetupForm, value: string | number) =>
const set = (key: keyof SetupForm, value: string | number | boolean) =>
setForm((f) => ({ ...f, [key]: value }))
const checkWizard = async () => {
@@ -61,11 +79,24 @@ export default function SetupWizardPage({ initialWizardPort, onComplete }: Props
}
}
const validateOidc = (): string => {
if (!oidcOnly && !form.oidc_enabled) return ''
if (!form.oidc_issuer.trim()) return 'OIDC issuer is required'
if (!form.oidc_client_id.trim()) return 'OIDC client ID is required'
if (!form.oidc_client_secret.trim()) return 'OIDC client secret is required'
if (!form.oidc_redirect_uri.trim()) return 'OIDC redirect/callback URL is required'
if (oidcOnly && !form.oidc_admin_role.trim()) {
return 'In OIDC-only mode the admin role is required so the admin can bootstrap'
}
return ''
}
const saveConfig = async () => {
setError('')
setSaving(true)
try {
const config = {
const includeOidc = oidcOnly || form.oidc_enabled
const config: Record<string, any> = {
initialized: true,
admin: {
username: form.admin_username,
@@ -75,6 +106,18 @@ export default function SetupWizardPage({ initialWizardPort, onComplete }: Props
},
backend_url: form.backend_base_url || undefined,
}
if (includeOidc) {
config.oidc = {
enabled: true,
issuer: form.oidc_issuer.trim(),
client_id: form.oidc_client_id.trim(),
client_secret: form.oidc_client_secret,
redirect_uri: form.oidc_redirect_uri.trim(),
scopes: form.oidc_scopes.trim() || 'openid email profile',
post_login_redirect: form.oidc_post_login_redirect.trim() || undefined,
admin_role: form.oidc_admin_role.trim() || 'admin',
}
}
await axios.put(`${wizardBase}/api/v1/config/harborforge.json`, config, {
headers: { 'Content-Type': 'application/json' },
@@ -85,7 +128,7 @@ export default function SetupWizardPage({ initialWizardPort, onComplete }: Props
localStorage.setItem('HF_BACKEND_BASE_URL', form.backend_base_url)
}
setStep(3)
setStep(4)
} catch (err: any) {
setError(`Failed to save configuration: ${err.message}`)
} finally {
@@ -150,6 +193,9 @@ export default function SetupWizardPage({ initialWizardPort, onComplete }: Props
<label>Email <input type="email" value={form.admin_email} onChange={(e) => set('admin_email', e.target.value)} placeholder="admin@example.com" /></label>
<label>Full name <input value={form.admin_full_name} onChange={(e) => set('admin_full_name', e.target.value)} /></label>
</div>
{oidcOnly && (
<p className="setup-hint">OIDC-only deployment: this admin will sign in via OIDC; the password is kept only as a fallback identity record.</p>
)}
<div className="setup-nav">
<button className="btn-back" onClick={() => setStep(0)}>Back</button>
<button className="btn-primary" onClick={() => {
@@ -161,8 +207,55 @@ export default function SetupWizardPage({ initialWizardPort, onComplete }: Props
</div>
)}
{/* Step 2: Backend */}
{/* Step 2: OIDC */}
{step === 2 && (
<div className="setup-step-content">
<h2>OIDC {oidcOnly ? '(required)' : '(optional)'}</h2>
<p className="text-dim">
{oidcOnly
? 'This deployment runs in OIDC-only mode — configure the identity provider now (the admin cannot reach this page again without it).'
: 'Optionally configure single sign-on. You can also do this later from the admin OIDC settings page.'}
</p>
{!oidcOnly && (
<label className="filter-check" style={{ marginBottom: 12 }}>
<input type="checkbox" checked={form.oidc_enabled} onChange={(e) => set('oidc_enabled', e.target.checked)} />
Enable OIDC sign-in
</label>
)}
{(oidcOnly || form.oidc_enabled) && (
<div className="setup-form">
<label>Issuer (OIDC source) <input value={form.oidc_issuer} onChange={(e) => set('oidc_issuer', e.target.value)} placeholder="https://idp.example.com/realms/hf" /></label>
<label>Client ID <input value={form.oidc_client_id} onChange={(e) => set('oidc_client_id', e.target.value)} /></label>
<label>Client Secret <input type="password" value={form.oidc_client_secret} onChange={(e) => set('oidc_client_secret', e.target.value)} /></label>
<label>Redirect / Callback URL <input value={form.oidc_redirect_uri} onChange={(e) => set('oidc_redirect_uri', e.target.value)} placeholder="https://hf-api.example.com/auth/oidc/callback" /></label>
<label>Scopes <input value={form.oidc_scopes} onChange={(e) => set('oidc_scopes', e.target.value)} /></label>
<label>Post-login redirect (frontend) <input value={form.oidc_post_login_redirect} onChange={(e) => set('oidc_post_login_redirect', e.target.value)} placeholder="https://hf.example.com/oidc/callback" /></label>
<label>Admin role (bootstrap)
<input value={form.oidc_admin_role} onChange={(e) => set('oidc_admin_role', e.target.value)} placeholder="admin" />
</label>
<p className="setup-hint">Register the Redirect / Callback URL above at your identity provider.</p>
{oidcOnly && (
<p className="setup-hint">
OIDC-only: before any admin is linked, the first IdP user whose token carries the
role above auto-connects to the HarborForge admin account. It then disables itself.
</p>
)}
</div>
)}
<div className="setup-nav">
<button className="btn-back" onClick={() => setStep(1)}>Back</button>
<button className="btn-primary" onClick={() => {
const e = validateOidc()
if (e) { setError(e); return }
setError('')
setStep(3)
}}>Next</button>
</div>
</div>
)}
{/* Step 3: Backend */}
{step === 3 && (
<div className="setup-step-content">
<h2>Backend URL</h2>
<p className="text-dim">Configure the HarborForge backend API URL (leave blank to use the frontend default).</p>
@@ -170,7 +263,7 @@ export default function SetupWizardPage({ initialWizardPort, onComplete }: Props
<label>Backend Base URL <input value={form.backend_base_url} onChange={(e) => set('backend_base_url', e.target.value)} placeholder="http://backend:8000" /></label>
</div>
<div className="setup-nav">
<button className="btn-back" onClick={() => setStep(1)}>Back</button>
<button className="btn-back" onClick={() => setStep(2)}>Back</button>
<button className="btn-primary" onClick={saveConfig} disabled={saving}>
{saving ? 'Saving...' : 'Finish setup'}
</button>
@@ -178,8 +271,8 @@ export default function SetupWizardPage({ initialWizardPort, onComplete }: Props
</div>
)}
{/* Step 3: Done */}
{step === 3 && (
{/* Step 4: Done */}
{step === 4 && (
<div className="setup-step-content">
<div className="setup-done">
<h2> Setup complete!</h2>

View File

@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from 'react'
import api from '@/services/api'
import { useAuth } from '@/hooks/useAuth'
import { useAuthConfig } from '@/hooks/useAuthConfig'
import type { User } from '@/types'
interface RoleOption {
@@ -16,8 +17,13 @@ interface ApiKeyPerms {
export default function UsersPage() {
const { user } = useAuth()
const { config: authCfg } = useAuthConfig()
const oidcOnly = authCfg.oidcOnly
const oidcEnabled = authCfg.oidcEnabled
const isAdmin = user?.is_admin === true
const [bindForm, setBindForm] = useState({ issuer: '', subject: '' })
const [users, setUsers] = useState<User[]>([])
const [roles, setRoles] = useState<RoleOption[]>([])
const [loading, setLoading] = useState(true)
@@ -105,17 +111,20 @@ export default function UsersPage() {
}
const handleCreateUser = async () => {
if (!createForm.username.trim() || !createForm.email.trim() || !createForm.password.trim()) return
if (!createForm.username.trim() || !createForm.email.trim()) return
if (!oidcOnly && !createForm.password.trim()) return
setSaving(true)
setMessage('')
try {
const payload = {
const payload: Record<string, any> = {
username: createForm.username.trim(),
email: createForm.email.trim(),
full_name: createForm.full_name.trim() || null,
password: createForm.password,
role_id: createForm.role_id ? Number(createForm.role_id) : undefined,
}
if (!oidcOnly) {
payload.password = createForm.password
}
const { data } = await api.post<User>('/users', payload)
const guestRole = roles.find((r) => r.name === 'guest') ?? roles[0]
setCreateForm({
@@ -201,6 +210,42 @@ export default function UsersPage() {
}
}
const handleBindOidc = async () => {
if (!selectedUser) return
if (!bindForm.issuer.trim() || !bindForm.subject.trim()) return
setSaving(true)
setMessage('')
try {
await api.put(`/users/${selectedUser.id}/oidc-binding`, {
issuer: bindForm.issuer.trim(),
subject: bindForm.subject.trim(),
})
setBindForm({ issuer: '', subject: '' })
setMessage('OIDC identity bound successfully')
await fetchData()
} catch (err: any) {
setMessage(err.response?.data?.detail || 'Failed to bind OIDC identity')
} finally {
setSaving(false)
}
}
const handleUnbindOidc = async () => {
if (!selectedUser) return
if (!confirm(`Remove the OIDC binding for ${selectedUser.username}?`)) return
setSaving(true)
setMessage('')
try {
await api.delete(`/users/${selectedUser.id}/oidc-binding`)
setMessage('OIDC binding removed')
await fetchData()
} catch (err: any) {
setMessage(err.response?.data?.detail || 'Failed to remove OIDC binding')
} finally {
setSaving(false)
}
}
if (loading) return <div className="loading">Loading users...</div>
if (!isAdmin) {
@@ -251,10 +296,15 @@ export default function UsersPage() {
Full Name
<input value={createForm.full_name} onChange={(e) => setCreateForm({ ...createForm, full_name: e.target.value })} />
</label>
<label>
Password
<input type="password" value={createForm.password} onChange={(e) => setCreateForm({ ...createForm, password: e.target.value })} />
</label>
{!oidcOnly && (
<label>
Password
<input type="password" value={createForm.password} onChange={(e) => setCreateForm({ ...createForm, password: e.target.value })} />
</label>
)}
{oidcOnly && (
<p className="text-dim">OIDC-only mode: users are created without a password and sign in via a bound OIDC identity.</p>
)}
<label>
Role
<select value={createForm.role_id} onChange={(e) => setCreateForm({ ...createForm, role_id: e.target.value })}>
@@ -264,7 +314,7 @@ export default function UsersPage() {
))}
</select>
</label>
<button className="btn-primary" disabled={saving || !createForm.username.trim() || !createForm.email.trim() || !createForm.password.trim() || !createForm.role_id} onClick={handleCreateUser}>
<button className="btn-primary" disabled={saving || !createForm.username.trim() || !createForm.email.trim() || (!oidcOnly && !createForm.password.trim()) || !createForm.role_id} onClick={handleCreateUser}>
{saving ? 'Saving...' : 'Create User'}
</button>
</div>
@@ -326,10 +376,12 @@ export default function UsersPage() {
Full Name
<input value={editForm.full_name} onChange={(e) => setEditForm({ ...editForm, full_name: e.target.value })} />
</label>
<label>
Reset Password
<input type="password" placeholder="Leave blank to keep current password" value={editForm.password} onChange={(e) => setEditForm({ ...editForm, password: e.target.value })} />
</label>
{!oidcOnly && (
<label>
Reset Password
<input type="password" placeholder="Leave blank to keep current password" value={editForm.password} onChange={(e) => setEditForm({ ...editForm, password: e.target.value })} />
</label>
)}
<div style={{ marginTop: '8px', padding: '12px', border: '1px solid var(--border)', borderRadius: '8px' }}>
<div style={{ fontWeight: 600, marginBottom: '10px' }}>Role</div>
@@ -381,6 +433,36 @@ export default function UsersPage() {
)}
</div>
)}
{oidcEnabled && (
<div style={{ marginTop: '8px', padding: '12px', border: '1px solid var(--border)', borderRadius: '8px' }}>
<div style={{ fontWeight: 600, marginBottom: '10px' }}>OIDC Binding</div>
{selectedUser.oidc_subject ? (
<div style={{ marginBottom: 10 }}>
<div className="text-dim" style={{ fontFamily: 'monospace', wordBreak: 'break-all' }}>
issuer: {selectedUser.oidc_issuer || '—'}<br />
subject: {selectedUser.oidc_subject}
</div>
<button className="btn-danger" style={{ marginTop: 10 }} disabled={saving} onClick={handleUnbindOidc}>
Unbind OIDC identity
</button>
</div>
) : (
<div className="text-dim" style={{ marginBottom: 10 }}>No OIDC identity bound.</div>
)}
<label>
Issuer
<input value={bindForm.issuer} placeholder="https://idp.example.com" onChange={(e) => setBindForm({ ...bindForm, issuer: e.target.value })} />
</label>
<label>
Subject (sub)
<input value={bindForm.subject} placeholder="OIDC subject claim" onChange={(e) => setBindForm({ ...bindForm, subject: e.target.value })} />
</label>
<button className="btn-secondary" style={{ marginTop: 10 }} disabled={saving || !bindForm.issuer.trim() || !bindForm.subject.trim()} onClick={handleBindOidc}>
{selectedUser.oidc_subject ? 'Rebind OIDC identity' : 'Bind OIDC identity'}
</button>
</div>
)}
</div>
</>
) : (

16
src/runtime.ts Normal file
View File

@@ -0,0 +1,16 @@
// Runtime config injected by the container entrypoint into
// /runtime-config.js (from the deploy-time HARBORFORGE_OIDC_ONLY env).
// Available before the backend exists — used by the setup wizard.
declare global {
interface Window {
__HF_RUNTIME__?: { oidc_only?: boolean }
}
}
/** true/false from the injected runtime config, or null when unknown. */
export function getRuntimeOidcOnly(): boolean | null {
const v = typeof window !== 'undefined' ? window.__HF_RUNTIME__?.oidc_only : undefined
return typeof v === 'boolean' ? v : null
}
export {}

View File

@@ -7,6 +7,8 @@ export interface User {
is_active: boolean
role_id: number | null
role_name: string | null
oidc_issuer?: string | null
oidc_subject?: string | null
created_at: string
}