feat(frontend): OIDC login + runtime env (FABRIC_OIDC_ONLY/FIX_TO_CENTER)

- Runtime container env injected by docker/entrypoint.sh -> runtime-env.js
  (loaded before the bundle); src/lib/runtime-env.ts reads it.
  FABRIC_OIDC_ONLY hides the password form; FIX_TO_CENTER pins the
  Center base and hides its input. Dockerfile ENTRYPOINT + ENV defaults.
- LoginPage: 'Sign in with SSO' when /auth/oidc/status enabled; password
  form gated by OIDC_ONLY; center input gated by FIX_TO_CENTER.
- /oidc route (OidcCallback) redeems the fragment ticket via
  /auth/oidc/exchange and adopts the session (AuthContext.adoptSession).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
h z
2026-05-18 09:44:49 +01:00
parent 4892af55e8
commit 92d3b4dc1b
11 changed files with 234 additions and 26 deletions

View File

@@ -9,7 +9,15 @@ RUN npm run build
FROM nginx:1.27-alpine AS runtime FROM nginx:1.27-alpine AS runtime
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
COPY docker/entrypoint.sh /docker-entrypoint-fabric.sh
COPY --from=build /app/dist /usr/share/nginx/html COPY --from=build /app/dist /usr/share/nginx/html
RUN chmod +x /docker-entrypoint-fabric.sh
# Runtime SPA config (see docker/entrypoint.sh). Override at `docker run`
# / compose: empty values keep prior behavior.
ENV FABRIC_OIDC_ONLY=""
ENV FIX_TO_CENTER=""
EXPOSE 80 EXPOSE 80
ENTRYPOINT ["/docker-entrypoint-fabric.sh"]
CMD ["nginx", "-g", "daemon off;"] CMD ["nginx", "-g", "daemon off;"]

20
docker/entrypoint.sh Normal file
View File

@@ -0,0 +1,20 @@
#!/bin/sh
set -e
# Inject container env into the static SPA at runtime. The app loads
# /runtime-env.js (see index.html) before its bundle.
# FABRIC_OIDC_ONLY - "true" hides the username/password login form
# FIX_TO_CENTER - non-empty pins the Center API base + hides its input
ONLY="false"
case "$(printf '%s' "${FABRIC_OIDC_ONLY:-}" | tr '[:upper:]' '[:lower:]')" in
1|true|yes|on) ONLY="true" ;;
esac
# JSON-escape FIX_TO_CENTER (backslash + double-quote)
FIX="$(printf '%s' "${FIX_TO_CENTER:-}" | sed 's/\\/\\\\/g; s/"/\\"/g')"
cat > /usr/share/nginx/html/runtime-env.js <<EOF
window.__FABRIC_ENV__ = { oidcOnly: ${ONLY}, fixToCenter: "${FIX}" };
EOF
exec "$@"

View File

@@ -19,6 +19,8 @@
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
<!-- runtime container env (generated by docker/entrypoint.sh); absent in dev -->
<script src="/runtime-env.js"></script>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
</body> </body>
</html> </html>

View File

@@ -3,6 +3,7 @@ import ProtectedRoute from './auth/ProtectedRoute'
import AppLayout from './layouts/AppLayout' import AppLayout from './layouts/AppLayout'
import ChatPage from './pages/ChatPage' import ChatPage from './pages/ChatPage'
import LoginPage from './pages/LoginPage' import LoginPage from './pages/LoginPage'
import OidcCallback from './pages/OidcCallback'
export default function App() { export default function App() {
return ( return (
@@ -26,6 +27,7 @@ export default function App() {
} }
/> />
<Route path="login" element={<LoginPage />} /> <Route path="login" element={<LoginPage />} />
<Route path="oidc" element={<OidcCallback />} />
</Route> </Route>
<Route path="*" element={<Navigate to="/workspace" replace />} /> <Route path="*" element={<Navigate to="/workspace" replace />} />
</Routes> </Routes>

View File

@@ -18,6 +18,11 @@ export function AuthProvider({ children }: PropsWithChildren) {
setAuthSession(next) setAuthSession(next)
setSession(next) setSession(next)
}, },
// Adopt a session obtained out-of-band (OIDC ticket exchange).
adoptSession: (next: AuthSession) => {
setAuthSession(next)
setSession(next)
},
logout: async () => { logout: async () => {
if (session?.refreshToken) { if (session?.refreshToken) {
try { try {

View File

@@ -5,6 +5,7 @@ export type AuthContextValue = {
session: AuthSession | null session: AuthSession | null
isAuthed: boolean isAuthed: boolean
login: (centerApiBase: string, email: string, password: string) => Promise<void> login: (centerApiBase: string, email: string, password: string) => Promise<void>
adoptSession: (session: AuthSession) => void
logout: () => Promise<void> logout: () => Promise<void>
ensureFreshToken: () => Promise<string | null> ensureFreshToken: () => Promise<string | null>
refreshGuilds: () => Promise<void> refreshGuilds: () => Promise<void>

View File

@@ -215,6 +215,14 @@ button {
width: auto; width: auto;
margin-bottom: 18px; margin-bottom: 18px;
} }
.login-or {
text-align: center;
color: var(--text-faint);
font-size: 11px;
letter-spacing: 0.18em;
text-transform: uppercase;
margin: 14px 0;
}
.login-card h1 { .login-card h1 {
font-size: 24px; font-size: 24px;
margin-bottom: 4px; margin-bottom: 4px;

View File

@@ -82,6 +82,20 @@ export async function guildMembersCenter(
return Array.isArray(res.data) ? res.data : [] return Array.isArray(res.data) ? res.data : []
} }
export async function oidcStatusCenter(centerApiBase: string): Promise<{ enabled: boolean }> {
try {
const res = await centerClient(centerApiBase).get<{ enabled: boolean }>('/auth/oidc/status')
return { enabled: !!res.data?.enabled }
} catch {
return { enabled: false }
}
}
export async function oidcExchangeCenter(centerApiBase: string, ticket: string): Promise<AuthSession> {
const res = await centerClient(centerApiBase).post<LoginResponse>('/auth/oidc/exchange', { ticket })
return { ...res.data, centerApiBase }
}
export async function updateMeNameCenter( export async function updateMeNameCenter(
centerApiBase: string, centerApiBase: string,
accessToken: string, accessToken: string,

37
src/lib/runtime-env.ts Normal file
View File

@@ -0,0 +1,37 @@
// Runtime (container) env, injected by the Docker entrypoint into
// /runtime-env.js as window.__FABRIC_ENV__ (NOT build-time). Empty/unset
// keeps the prior behavior.
type FabricEnv = { oidcOnly?: boolean; fixToCenter?: string }
const env: FabricEnv =
(typeof window !== 'undefined' && (window as unknown as { __FABRIC_ENV__?: FabricEnv }).__FABRIC_ENV__) || {}
// FABRIC_OIDC_ONLY: hide the username/password form (SSO is the only login).
export const OIDC_ONLY = env.oidcOnly === true
// FIX_TO_CENTER: when non-empty, the Center API base is pinned to this and
// the login page no longer shows the "Center API Base" input.
export const FIXED_CENTER = (env.fixToCenter ?? '').trim()
export const DEFAULT_CENTER = 'http://localhost:7001/api'
// Where OIDC exchange should call back to. FIX_TO_CENTER wins; otherwise
// the value the user used to start SSO (persisted before redirect).
const OIDC_CENTER_KEY = 'fabric.oidc.center.v1'
export function rememberOidcCenter(base: string): void {
try {
localStorage.setItem(OIDC_CENTER_KEY, base)
} catch {
// ignore
}
}
export function resolveCenterBase(): string {
if (FIXED_CENTER) return FIXED_CENTER
try {
const v = localStorage.getItem(OIDC_CENTER_KEY)
if (v) return v
} catch {
// ignore
}
return DEFAULT_CENTER
}

View File

@@ -1,16 +1,29 @@
import { useState } from 'react' import { useEffect, useState } from 'react'
import type { FormEvent } from 'react' import type { FormEvent } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { useAuth } from '../auth/auth-context' import { useAuth } from '../auth/auth-context'
import { APP_NAME, LOGO_URL } from '../lib/brand' import { APP_NAME, LOGO_URL } from '../lib/brand'
import { OIDC_ONLY, FIXED_CENTER, DEFAULT_CENTER, rememberOidcCenter } from '../lib/runtime-env'
import { oidcStatusCenter } from '../lib/center-auth-client'
export default function LoginPage() { export default function LoginPage() {
const navigate = useNavigate() const navigate = useNavigate()
const { login, isAuthed, session } = useAuth() const { login, isAuthed, session } = useAuth()
const [centerApiBase, setCenterApiBase] = useState('http://localhost:7001/api') const [centerApiBase, setCenterApiBase] = useState(FIXED_CENTER || DEFAULT_CENTER)
const [email, setEmail] = useState('') const [email, setEmail] = useState('')
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const [error, setError] = useState('') const [error, setError] = useState('')
const [oidcEnabled, setOidcEnabled] = useState(false)
useEffect(() => {
let alive = true
oidcStatusCenter(centerApiBase.trim()).then((s) => {
if (alive) setOidcEnabled(s.enabled)
})
return () => {
alive = false
}
}, [centerApiBase])
async function onSubmit(e: FormEvent) { async function onSubmit(e: FormEvent) {
e.preventDefault() e.preventDefault()
@@ -23,6 +36,15 @@ export default function LoginPage() {
} }
} }
function startOidc() {
const base = centerApiBase.trim().replace(/\/$/, '')
rememberOidcCenter(base)
window.location.href = `${base}/auth/oidc/start`
}
const showPasswordForm = !OIDC_ONLY
const showCenterInput = !FIXED_CENTER
return ( return (
<div className="login-screen"> <div className="login-screen">
<div className="login-card"> <div className="login-card">
@@ -35,7 +57,8 @@ export default function LoginPage() {
<p className="login-sub"> <p className="login-sub">
{isAuthed ? `Signed in as ${session?.user.email}` : `Sign in to continue to ${APP_NAME}`} {isAuthed ? `Signed in as ${session?.user.email}` : `Sign in to continue to ${APP_NAME}`}
</p> </p>
<form onSubmit={onSubmit}>
{showCenterInput ? (
<div className="field"> <div className="field">
<label>Center API Base</label> <label>Center API Base</label>
<input <input
@@ -45,29 +68,51 @@ export default function LoginPage() {
placeholder="http://localhost:7001/api" placeholder="http://localhost:7001/api"
/> />
</div> </div>
<div className="field"> ) : null}
<label>Email</label>
<input {oidcEnabled ? (
className="input" <button className="btn" type="button" onClick={startOidc} style={{ width: '100%' }}>
value={email} Sign in with SSO
onChange={(e) => setEmail(e.target.value)} </button>
placeholder="you@example.com" ) : null}
type="email"
/> {OIDC_ONLY && !oidcEnabled ? (
</div> <p className="error-text" style={{ marginTop: 12 }}>
<div className="field"> SSO is not configured on this Center yet.
<label>Password</label> </p>
<input ) : null}
className="input"
value={password} {showPasswordForm ? (
onChange={(e) => setPassword(e.target.value)} <>
placeholder="••••••••" {oidcEnabled ? <div className="login-or">or</div> : null}
type="password" <form onSubmit={onSubmit}>
/> <div className="field">
</div> <label>Email</label>
{error ? <p className="error-text" style={{ marginBottom: 12 }}>{error}</p> : null} <input
<button className="btn" type="submit">Sign in</button> className="input"
</form> value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@example.com"
type="email"
/>
</div>
<div className="field">
<label>Password</label>
<input
className="input"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••"
type="password"
/>
</div>
{error ? <p className="error-text" style={{ marginBottom: 12 }}>{error}</p> : null}
<button className="btn" type="submit">Sign in</button>
</form>
</>
) : error ? (
<p className="error-text" style={{ marginTop: 12 }}>{error}</p>
) : null}
</div> </div>
</div> </div>
) )

View File

@@ -0,0 +1,66 @@
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../auth/auth-context'
import { APP_NAME } from '../lib/brand'
import { resolveCenterBase } from '../lib/runtime-env'
import { oidcExchangeCenter } from '../lib/center-auth-client'
// Landing route for the OIDC redirect: Center bounces the browser here
// with #oidc_ticket=... (or #oidc_error=...). We redeem the one-time
// ticket for a full session and adopt it.
export default function OidcCallback() {
const navigate = useNavigate()
const { adoptSession } = useAuth()
const [error, setError] = useState('')
const ran = useRef(false)
useEffect(() => {
if (ran.current) return
ran.current = true
const hash = window.location.hash.replace(/^#/, '')
const params = new URLSearchParams(hash)
const ticket = params.get('oidc_ticket')
const errParam = params.get('oidc_error')
// scrub the fragment so the ticket isn't left in the URL/history
window.history.replaceState(null, '', window.location.pathname)
if (errParam) {
setError(decodeURIComponent(errParam))
return
}
if (!ticket) {
setError('Missing OIDC ticket.')
return
}
oidcExchangeCenter(resolveCenterBase(), ticket)
.then((next) => {
adoptSession(next)
navigate('/workspace', { replace: true })
})
.catch(() => setError('SSO sign-in failed. The ticket may have expired — please try again.'))
}, [adoptSession, navigate])
return (
<div className="login-screen">
<div className="login-card">
<div className="brand-wordmark">{APP_NAME}</div>
{error ? (
<>
<h1>Sign-in failed</h1>
<p className="error-text" style={{ marginBottom: 16 }}>{error}</p>
<button className="btn" type="button" onClick={() => navigate('/login', { replace: true })}>
Back to sign in
</button>
</>
) : (
<>
<h1>Signing you in</h1>
<p className="login-sub">Completing SSO authentication.</p>
</>
)}
</div>
</div>
)
}