diff --git a/client/.storybook/stories/AuthStatusPage.stories.tsx b/client/.storybook/stories/AuthStatusPage.stories.tsx new file mode 100644 index 0000000..429e772 --- /dev/null +++ b/client/.storybook/stories/AuthStatusPage.stories.tsx @@ -0,0 +1,28 @@ +import '../../src/i18n'; +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, fn, userEvent, within } from 'storybook/test'; +import { AuthStatusPage } from '../../src/pages/auth/AuthStatusPage'; + +const meta: Meta = { + title: 'Authentication/Session status', + component: AuthStatusPage, + parameters: { layout: 'fullscreen' }, + tags: ['autodocs'], + args: { onRetry: fn() }, +}; +export default meta; +type Story = StoryObj; + +export const Checking: Story = {}; + +export const SessionCheckFailure: Story = { + args: { failed: true }, + play: async ({ canvasElement, args }) => { + const canvas = within(canvasElement); + await expect(canvas.getByRole('alert')).toHaveTextContent( + "Couldn't check your session. Try again.", + ); + await userEvent.click(canvas.getByRole('button', { name: 'Retry' })); + await expect(args.onRetry).toHaveBeenCalledTimes(1); + }, +}; diff --git a/client/.storybook/stories/AuthTransport.stories.tsx b/client/.storybook/stories/AuthTransport.stories.tsx new file mode 100644 index 0000000..b1953f9 --- /dev/null +++ b/client/.storybook/stories/AuthTransport.stories.tsx @@ -0,0 +1,71 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect } from 'storybook/test'; +import { auth } from '../../src/api/client'; +import { createRunEventSource } from '../../src/hooks/useRunNotifications'; + +function TransportExample() { + return

Browser auth uses HttpOnly cookies for API and run-event requests.

; +} + +const meta: Meta = { + title: 'Authentication/Cookie transport', + component: TransportExample, + tags: ['autodocs'], +}; +export default meta; +type Story = StoryObj; + +export const CookieCredentials: Story = { + play: async () => { + const originalFetch = globalThis.fetch; + const localStorageLength = localStorage.length; + let requestInit: RequestInit | undefined; + globalThis.fetch = async (_input, init) => { + requestInit = init; + return new Response( + JSON.stringify({ + user: { + id: 'synthetic-user-id', + username: 'synthetic-operator', + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-01T00:00:00.000Z', + }, + }), + { status: 200, headers: { 'Content-Type': 'application/json' } }, + ); + }; + try { + const user = await auth.login('synthetic-operator', 'synthetic-password'); + await expect(requestInit?.credentials).toBe('include'); + await expect(user.username).toBe('synthetic-operator'); + await expect(new Headers(requestInit?.headers).has('Authorization')).toBe(false); + await expect(localStorage.length).toBe(localStorageLength); + } finally { + globalThis.fetch = originalFetch; + } + }, +}; + +export const EventStreamIncludesCookieCredentials: Story = { + play: async () => { + const previous = Object.getOwnPropertyDescriptor(globalThis, 'EventSource'); + let options: EventSourceInit | undefined; + class StubEventSource { + constructor(_url: string | URL, init?: EventSourceInit) { + options = init; + } + close() {} + } + Object.defineProperty(globalThis, 'EventSource', { + configurable: true, + value: StubEventSource, + }); + try { + createRunEventSource().close(); + await expect(options?.withCredentials).toBe(true); + } finally { + if (previous) Object.defineProperty(globalThis, 'EventSource', previous); + else Reflect.deleteProperty(globalThis, 'EventSource'); + } + }, +}; diff --git a/client/.storybook/stories/LoginForm.stories.tsx b/client/.storybook/stories/LoginForm.stories.tsx new file mode 100644 index 0000000..22684de --- /dev/null +++ b/client/.storybook/stories/LoginForm.stories.tsx @@ -0,0 +1,132 @@ +import '../../src/i18n'; +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, userEvent, within } from 'storybook/test'; +import { ApiError } from '../../src/api/client'; +import { LoginForm } from '../../src/pages/auth/LoginForm'; + +const meta: Meta = { + title: 'Authentication/Login form', + component: LoginForm, + parameters: { layout: 'centered' }, + tags: ['autodocs'], + args: { onSubmit: async () => undefined }, + decorators: [ + (Story) => ( +
+ +
+ ), + ], +}; +export default meta; +type Story = StoryObj; + +async function expectLoginSurfaces(canvasElement: HTMLElement) { + const canvas = within(canvasElement); + const card = canvasElement.querySelector('section'); + const notice = canvas.getByText('Your session has expired. Sign in again to continue.'); + const username = canvas.getByRole('textbox', { name: 'Username' }); + if (!card) throw new Error('Login card was not rendered.'); + + await expect(window.getComputedStyle(notice).marginBottom).not.toBe('0px'); + await expect(window.getComputedStyle(username).backgroundColor).not.toBe( + window.getComputedStyle(card).backgroundColor, + ); +} + +export const Initial: Story = {}; + +export const ExpiredSession: Story = { + args: { expired: true }, + play: async ({ canvasElement }) => expectLoginSurfaces(canvasElement), +}; + +export const SignedOut: Story = { args: { signedOut: true } }; + +export const DarkTheme: Story = { + args: { expired: true }, + decorators: [ + (Story) => ( +
+ +
+ ), + ], + play: async ({ canvasElement }) => expectLoginSurfaces(canvasElement), +}; + +export const NarrowViewport: Story = { + decorators: [ + (Story) => ( +
+ +
+ ), + ], +}; + +export const EmptyFieldValidation: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole('button', { name: 'Sign in' })); + await expect(canvas.getByText('Enter your username.')).toBeVisible(); + await expect(canvas.getByRole('textbox', { name: 'Username' })).toHaveFocus(); + await expect(canvas.getByLabelText('Password')).toHaveAttribute('aria-invalid', 'true'); + }, +}; + +export const InvalidCredentials: Story = { + args: { + onSubmit: async () => { + throw new ApiError(401, 'Unauthorized'); + }, + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator'); + await userEvent.type(canvas.getByLabelText('Password'), 'wrong-password'); + await userEvent.click(canvas.getByRole('button', { name: 'Sign in' })); + await expect(await canvas.findByRole('alert')).toHaveTextContent( + 'Username or password is incorrect.', + ); + await expect(canvas.getByRole('textbox', { name: 'Username' })).toHaveValue('operator'); + await expect(canvas.getByLabelText('Password')).toHaveValue(''); + await expect(canvas.getByLabelText('Password')).toHaveFocus(); + }, +}; + +export const RequestFailureAndRetry: Story = { + args: { + onSubmit: (() => { + let attempts = 0; + return async () => { + attempts += 1; + if (attempts === 1) throw new ApiError(503, 'Unavailable'); + }; + })(), + }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator'); + await userEvent.type(canvas.getByLabelText('Password'), 'temporary'); + await userEvent.click(canvas.getByRole('button', { name: 'Sign in' })); + await expect(await canvas.findByRole('alert')).toHaveTextContent( + "Couldn't sign in. Check your connection and try again.", + ); + await expect(canvas.getByLabelText('Password')).toHaveValue('temporary'); + await userEvent.click(canvas.getByRole('button', { name: 'Sign in' })); + await expect(canvas.queryByRole('alert')).not.toBeInTheDocument(); + }, +}; + +export const Submitting: Story = { + args: { onSubmit: () => new Promise(() => undefined) }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator'); + await userEvent.type(canvas.getByLabelText('Password'), 'secret'); + await userEvent.click(canvas.getByRole('button', { name: 'Sign in' })); + await expect(canvas.getByRole('status')).toHaveTextContent('Signing in…'); + await expect(canvas.getByRole('button', { name: 'Signing in…' })).toBeDisabled(); + }, +}; diff --git a/client/.storybook/stories/ReturnToSafety.stories.tsx b/client/.storybook/stories/ReturnToSafety.stories.tsx new file mode 100644 index 0000000..9f1fc6b --- /dev/null +++ b/client/.storybook/stories/ReturnToSafety.stories.tsx @@ -0,0 +1,31 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect } from 'storybook/test'; +import { safeReturnTo } from '../../src/auth/returnTo'; + +function ReturnToSafetyExample() { + return

Local return destinations are checked before use.

; +} + +const meta: Meta = { + title: 'Authentication/Return destination safety', + component: ReturnToSafetyExample, + tags: ['autodocs'], +}; +export default meta; +type Story = StoryObj; + +export const Validation: Story = { + play: async () => { + await expect(safeReturnTo('/scenarios/123/runs/456?example=1#details')).toBe( + '/scenarios/123/runs/456?example=1#details', + ); + await expect(safeReturnTo('/scenarios')).toBe('/scenarios'); + await expect(safeReturnTo('//external.example/path')).toBeNull(); + await expect(safeReturnTo('https://external.example/path')).toBeNull(); + await expect(safeReturnTo('/%2f%2fexternal.example')).toBeNull(); + await expect(safeReturnTo('/%5c%5cexternal.example')).toBeNull(); + await expect(safeReturnTo('/login?returnTo=/scenarios')).toBeNull(); + await expect(safeReturnTo('/auth/me')).toBeNull(); + await expect(safeReturnTo('/%')).toBeNull(); + }, +}; diff --git a/client/.storybook/stories/SignOutControl.stories.tsx b/client/.storybook/stories/SignOutControl.stories.tsx new file mode 100644 index 0000000..dc871b3 --- /dev/null +++ b/client/.storybook/stories/SignOutControl.stories.tsx @@ -0,0 +1,34 @@ +import '../../src/i18n'; +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, fn, userEvent, within } from 'storybook/test'; +import { SignOutControl } from '../../src/pages/auth/SignOutControl'; + +const meta: Meta = { + title: 'Authentication/Sign out', + component: SignOutControl, + parameters: { layout: 'centered' }, + tags: ['autodocs'], + args: { onSignOut: fn() }, +}; +export default meta; +type Story = StoryObj; + +export const Ready: Story = {}; + +export const Pending: Story = { + args: { pending: true }, + play: async ({ canvasElement }) => { + const button = within(canvasElement).getByRole('button', { name: 'Signing out…' }); + await expect(button).toBeDisabled(); + }, +}; + +export const FailureAndRetry: Story = { + args: { failed: true }, + play: async ({ canvasElement, args }) => { + const canvas = within(canvasElement); + await expect(canvas.getByRole('alert')).toHaveTextContent("Couldn't sign out. Try again."); + await userEvent.click(canvas.getByRole('button', { name: 'Retry' })); + await expect(args.onSignOut).toHaveBeenCalledTimes(1); + }, +}; diff --git a/client/src/App.module.css b/client/src/App.module.css index 0d41f0b..8dff647 100644 --- a/client/src/App.module.css +++ b/client/src/App.module.css @@ -38,6 +38,7 @@ .footerButtons { display: flex; + flex-wrap: wrap; align-items: center; gap: var(--space-1); } @@ -47,6 +48,7 @@ padding: var(--space-3) var(--space-2) var(--space-2); border-top: var(--border-width) solid var(--color-border); display: flex; + flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--space-2); @@ -68,6 +70,68 @@ text-decoration: underline; } +.signOut, +.expandForSignOut { + display: inline-flex; + align-items: center; + justify-content: center; + width: 44px; + height: 44px; + padding: 0; + color: var(--color-text-muted); + background: transparent; + border: var(--border-width) solid var(--color-border); + border-radius: var(--radius-md); + cursor: pointer; +} + +.signOut:hover, +.expandForSignOut:hover { + color: var(--color-text); + background: var(--color-secondary); +} + +.signOut:focus-visible, +.expandForSignOut:focus-visible, +.logoutFailure button:focus-visible { + outline: 2px solid var(--color-primary-text); + outline-offset: 2px; +} + +.signOut:disabled { + opacity: 0.55; + cursor: wait; +} + +.logoutFailure { + display: flex; + align-items: center; + gap: var(--space-2); + padding: var(--space-2); + color: var(--color-error-fg); + background: var(--color-error-bg); + border-radius: var(--radius-sm); + font-size: var(--font-size-xs); +} + +.logoutFailure button { + min-height: 32px; + color: inherit; + background: transparent; + border: var(--border-width) solid currentColor; + border-radius: var(--radius-sm); + cursor: pointer; +} + +.expandForSignOut { + position: fixed; + left: 8px; + bottom: 12px; + z-index: 20; + background: var(--color-bg-subtle); + box-shadow: var(--shadow-sm); +} + .navItem { display: flex; align-items: center; diff --git a/client/src/App.tsx b/client/src/App.tsx index 8edb6f9..4a3b1ba 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,5 +1,6 @@ -import { lazy, Suspense } from 'react'; -import { NavLink, Navigate, Route, Routes } from 'react-router-dom'; +import { lazy, Suspense, useEffect, useRef, useState } from 'react'; +import { LogOut } from 'lucide-react'; +import { NavLink, Navigate, Route, Routes, useLocation, useSearchParams } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces, Upload } from 'lucide-react'; import type { LucideIcon } from 'lucide-react'; @@ -8,6 +9,11 @@ import { NotificationToggle, SidePanel, ThemeSwitcher } from './ui'; import liqaLogo from './assets/liqa.svg'; import { useManifest } from './hooks/useManifest'; import { useRunNotifications } from './hooks/useRunNotifications'; +import { useAuth } from './auth/useAuth'; +import { safeReturnTo } from './auth/returnTo'; +import { AuthStatusPage } from './pages/auth/AuthStatusPage'; +import { LoginPage } from './pages/auth/LoginPage'; +import { SignOutControl } from './pages/auth/SignOutControl'; const EnvironmentsPage = lazy(() => import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })), @@ -109,12 +115,59 @@ const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator: export default function App() { const { t } = useTranslation(); + const auth = useAuth(); + const location = useLocation(); + const [search] = useSearchParams(); + const [collapsed, setCollapsed] = useState(false); + const [loggingOut, setLoggingOut] = useState(false); + const [logoutFailed, setLogoutFailed] = useState(false); + const focusSignOut = useRef(false); const { version } = useManifest(); const notifications = useRunNotifications(); + useEffect(() => { + if (!collapsed && focusSignOut.current) { + focusSignOut.current = false; + document.querySelector('[data-sign-out="true"]')?.focus(); + } + }, [collapsed]); + + async function signOut() { + if (loggingOut) return; + setLoggingOut(true); + setLogoutFailed(false); + try { + await auth.logout(); + } catch { + setLogoutFailed(true); + } finally { + setLoggingOut(false); + } + } + + const onLogin = location.pathname === '/login'; + if (auth.enabled && (auth.status === 'checking' || auth.status === 'disabled')) { + return ; + } + if (auth.enabled && auth.status === 'error') { + return void auth.checkSession()} />; + } + if (!auth.enabled && onLogin) return ; + if (auth.enabled && auth.status === 'authenticated' && onLogin) { + return ; + } + if (auth.enabled && auth.status === 'unauthenticated' && !onLogin) { + const returnTo = + safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios'; + return ; + } + if (onLogin) return ; + return (
Liqa @@ -148,6 +201,13 @@ export default function App() { {notifications && ( )} + {auth.enabled && auth.status === 'authenticated' && ( + void signOut()} + /> + )}
+ {collapsed && auth.enabled && auth.status === 'authenticated' && ( + + )} +
Loading…

}> diff --git a/client/src/api/client.ts b/client/src/api/client.ts index a5459a7..2296094 100644 --- a/client/src/api/client.ts +++ b/client/src/api/client.ts @@ -31,7 +31,25 @@ const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/ /** URL of the server-sent events stream of run lifecycle events. */ export const RUN_EVENTS_URL = `${BASE_URL}/scenarios/runs/events`; -async function request(path: string, init?: RequestInit): Promise { +export class ApiError extends Error { + constructor( + public readonly status: number, + message: string, + ) { + super(message); + this.name = 'ApiError'; + } +} + +interface RequestOptions { + quietErrors?: boolean; +} + +async function request( + path: string, + init?: RequestInit, + options: RequestOptions = {}, +): Promise { let res: Response; try { const headers = new Headers(init?.headers); @@ -41,18 +59,26 @@ async function request(path: string, init?: RequestInit): Promise { res = await fetch(`${BASE_URL}${path}`, { ...init, + credentials: init?.credentials ?? 'include', headers, }); } catch (err) { const message = (err as Error).message || 'Network request failed'; - emitApiErrorToast(message); + if (!options.quietErrors) emitApiErrorToast(message); throw new Error(message); } if (!res.ok) { const text = await res.text().catch(() => res.statusText); const message = `${res.status} ${text}`; - emitApiErrorToast(message); - throw new Error(message); + const error = new ApiError(res.status, message); + if (res.status === 401 && !path.startsWith('/auth/')) { + const event = new CustomEvent('liqa:unauthorized', { cancelable: true }); + const handled = !window.dispatchEvent(event); + if (!handled && !options.quietErrors) emitApiErrorToast(message); + } else if (!options.quietErrors && !path.startsWith('/auth/')) { + emitApiErrorToast(message); + } + throw error; } const contentLength = res.headers.get('content-length'); if (res.status === 204 || contentLength === '0') return undefined as T; @@ -65,6 +91,30 @@ async function request(path: string, init?: RequestInit): Promise { return text as T; } +export interface AuthUser { + id: string; + username: string; + createdAt: string; + updatedAt: string; +} + +export const auth = { + async login(username: string, password: string): Promise { + const response = await request<{ user: AuthUser }>( + '/auth/login', + { method: 'POST', body: JSON.stringify({ username, password }) }, + { quietErrors: true }, + ); + return response.user; + }, + me(): Promise { + return request('/auth/me', undefined, { quietErrors: true }); + }, + logout(): Promise { + return request('/auth/logout', { method: 'POST' }, { quietErrors: true }); + }, +}; + // ── Credentials ─────────────────────────────────────────────────────────────── export const credentials = { diff --git a/client/src/auth/AuthContext.tsx b/client/src/auth/AuthContext.tsx new file mode 100644 index 0000000..a93fd51 --- /dev/null +++ b/client/src/auth/AuthContext.tsx @@ -0,0 +1,133 @@ +import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'; +import { useLocation, useNavigate } from 'react-router-dom'; +import { useQueryClient } from '@tanstack/react-query'; +import { ApiError, auth as authApi, type AuthUser } from '../api/client'; +import { refreshManifest } from '../lib/manifest'; +import { useManifest } from '../hooks/useManifest'; +import { loginPath, safeReturnTo } from './returnTo'; +import { AuthContext } from './context'; +import type { AuthStatus } from './context'; + +export function AuthProvider({ children }: { children: ReactNode }) { + const { auth: manifestAuth } = useManifest(); + const enabled = manifestAuth.enabled; + const location = useLocation(); + const navigate = useNavigate(); + const queryClient = useQueryClient(); + const [status, setStatus] = useState('checking'); + const [user, setUser] = useState(null); + const statusRef = useRef(status); + const enabledRef = useRef(enabled); + const handledUnauthorized = useRef(false); + const checkInFlight = useRef | null>(null); + + useEffect(() => { + enabledRef.current = enabled; + statusRef.current = status; + }, [enabled, status]); + + const updateStatus = useCallback((next: AuthStatus) => { + statusRef.current = next; + setStatus(next); + }, []); + + const checkSession = useCallback(async () => { + if (!enabledRef.current) { + setUser(null); + updateStatus('disabled'); + return; + } + if (checkInFlight.current) return checkInFlight.current; + updateStatus('checking'); + const check = authApi + .me() + .then((account) => { + setUser(account); + handledUnauthorized.current = false; + updateStatus('authenticated'); + }) + .catch((error: unknown) => { + setUser(null); + updateStatus( + error instanceof ApiError && error.status === 401 ? 'unauthenticated' : 'error', + ); + }) + .finally(() => { + checkInFlight.current = null; + }); + checkInFlight.current = check; + return check; + }, [updateStatus]); + + useEffect(() => { + if (!enabled) { + // This synchronizes the session state with the server's feature flag. + // eslint-disable-next-line react-hooks/set-state-in-effect + setUser(null); + updateStatus('disabled'); + queryClient.clear(); + return; + } + void checkSession(); + }, [enabled, checkSession, queryClient, updateStatus]); + + useEffect(() => { + const onUnauthorized = (event: Event) => { + if (!enabledRef.current) return; + if (handledUnauthorized.current) { + event.preventDefault(); + return; + } + if (statusRef.current !== 'authenticated') return; + event.preventDefault(); + handledUnauthorized.current = true; + queryClient.clear(); + setUser(null); + updateStatus('unauthenticated'); + const target = + safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios'; + navigate(loginPath(target, true), { replace: true }); + }; + window.addEventListener('liqa:unauthorized', onUnauthorized); + return () => window.removeEventListener('liqa:unauthorized', onUnauthorized); + }, [location.hash, location.pathname, location.search, navigate, queryClient, updateStatus]); + + const login = useCallback( + async (username: string, password: string) => { + let account: AuthUser; + try { + account = await authApi.login(username, password); + } catch (error) { + if (error instanceof ApiError && error.status === 404) await refreshManifest(); + throw error; + } + queryClient.clear(); + handledUnauthorized.current = false; + setUser(account); + updateStatus('authenticated'); + }, + [queryClient, updateStatus], + ); + + const logout = useCallback(async () => { + try { + await authApi.logout(); + } catch (error) { + if (!(error instanceof ApiError && error.status === 401)) { + await checkSession(); + throw error; + } + } + queryClient.clear(); + setUser(null); + updateStatus('unauthenticated'); + handledUnauthorized.current = false; + navigate('/login?notice=signedOut', { replace: true }); + }, [checkSession, navigate, queryClient, updateStatus]); + + return ( + + {children} + + ); +} diff --git a/client/src/auth/context.ts b/client/src/auth/context.ts new file mode 100644 index 0000000..087ec41 --- /dev/null +++ b/client/src/auth/context.ts @@ -0,0 +1,15 @@ +import { createContext } from 'react'; +import type { AuthUser } from '../api/client'; + +export type AuthStatus = 'disabled' | 'checking' | 'authenticated' | 'unauthenticated' | 'error'; + +export interface AuthContextValue { + enabled: boolean; + status: AuthStatus; + user: AuthUser | null; + login: (username: string, password: string) => Promise; + logout: () => Promise; + checkSession: () => Promise; +} + +export const AuthContext = createContext(null); diff --git a/client/src/auth/returnTo.ts b/client/src/auth/returnTo.ts new file mode 100644 index 0000000..0660fa6 --- /dev/null +++ b/client/src/auth/returnTo.ts @@ -0,0 +1,45 @@ +/** Return only a well-formed route on this app's origin. */ +export function safeReturnTo(value: string | null | undefined): string | null { + if ( + !value || + !value.startsWith('/') || + value.startsWith('//') || + value.includes('\\') || + /%(?:2f|5c)/i.test(value) + ) + return null; + + let decoded = value; + try { + for (let pass = 0; pass < 3; pass += 1) { + const next = decodeURIComponent(decoded); + if (next === decoded) break; + decoded = next; + } + } catch { + return null; + } + const containsControl = [...decoded].some((character) => { + const code = character.charCodeAt(0); + return code < 32 || code === 127; + }); + if (decoded.startsWith('//') || decoded.includes('\\') || containsControl) { + return null; + } + + try { + const target = new URL(value, window.location.origin); + if (target.origin !== window.location.origin) return null; + if (/^\/(?:login|auth)(?:\/|$)/i.test(target.pathname)) return null; + return `${target.pathname}${target.search}${target.hash}`; + } catch { + return null; + } +} + +export function loginPath(returnTo: string, expired = false): string { + const query = new URLSearchParams(); + query.set('returnTo', safeReturnTo(returnTo) ?? '/scenarios'); + if (expired) query.set('expired', '1'); + return `/login?${query.toString()}`; +} diff --git a/client/src/auth/useAuth.ts b/client/src/auth/useAuth.ts new file mode 100644 index 0000000..47e6105 --- /dev/null +++ b/client/src/auth/useAuth.ts @@ -0,0 +1,8 @@ +import { useContext } from 'react'; +import { AuthContext } from './context'; + +export function useAuth() { + const value = useContext(AuthContext); + if (!value) throw new Error('useAuth must be used inside AuthProvider'); + return value; +} diff --git a/client/src/hooks/useRunNotifications.ts b/client/src/hooks/useRunNotifications.ts index 5ed7ea4..a54f2ca 100644 --- a/client/src/hooks/useRunNotifications.ts +++ b/client/src/hooks/useRunNotifications.ts @@ -5,11 +5,16 @@ import { useTranslation } from 'react-i18next'; import { RUN_EVENTS_URL } from '../api/client'; import type { RunEvent } from '../api/types'; import type { NotificationToggleState } from '../ui'; +import { useAuth } from '../auth/useAuth'; const STORAGE_KEY = 'liqa-run-notifications'; const RETRY_MIN_MS = 1_000; const RETRY_MAX_MS = 30_000; +export function createRunEventSource(): EventSource { + return new EventSource(RUN_EVENTS_URL, { withCredentials: true }); +} + function supported(): boolean { return typeof window !== 'undefined' && 'Notification' in window && 'EventSource' in window; } @@ -41,6 +46,7 @@ export function useRunNotifications(): { state: NotificationToggleState; toggle: () => void; } | null { + const auth = useAuth(); const isSupported = supported(); const { t } = useTranslation(); const navigate = useNavigate(); @@ -81,7 +87,11 @@ export function useRunNotifications(): { handlers.current = { t, navigate }; }); - const active = isSupported && enabled && permission === 'granted'; + const active = + isSupported && + enabled && + permission === 'granted' && + (!auth.enabled || auth.status === 'authenticated'); useEffect(() => { if (!active) return; @@ -122,7 +132,7 @@ export function useRunNotifications(): { }; const connect = () => { - source = new EventSource(RUN_EVENTS_URL); + source = createRunEventSource(); source.addEventListener('open', () => { retryDelay = RETRY_MIN_MS; }); diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.json index a0e9bab..869d036 100644 --- a/client/src/i18n/locales/en.json +++ b/client/src/i18n/locales/en.json @@ -1,4 +1,24 @@ { + "auth": { + "page_title": "Sign in", + "sign_in": "Sign in", + "signing_in": "Signing in…", + "username": "Username", + "password": "Password", + "username_required": "Enter your username.", + "password_required": "Enter your password.", + "invalid_credentials": "Username or password is incorrect.", + "sign_in_failed": "Couldn't sign in. Check your connection and try again.", + "checking_session": "Checking your session…", + "session_check_failed": "Couldn't check your session. Try again.", + "retry": "Retry", + "session_expired": "Your session has expired. Sign in again to continue.", + "sign_out": "Sign out", + "signing_out": "Signing out…", + "signed_out": "You have signed out.", + "sign_out_failed": "Couldn't sign out. Try again.", + "show_sign_out": "Expand the menu to sign out" + }, "common": { "button_cancel": "Cancel", "button_confirm": "Confirm", diff --git a/client/src/lib/manifest.ts b/client/src/lib/manifest.ts index 2302037..9a144e4 100644 --- a/client/src/lib/manifest.ts +++ b/client/src/lib/manifest.ts @@ -8,12 +8,16 @@ export interface Manifest { runLogs: { dataLimits: LogDataLimits; }; + auth: { + enabled: boolean; + }; } export const DEFAULT_MANIFEST: Manifest = { name: 'liqa', version: __APP_VERSION__, runLogs: { dataLimits: DEFAULT_LOG_DATA_LIMITS }, + auth: { enabled: false }, }; const STORAGE_KEY = 'liqa-manifest'; @@ -39,6 +43,7 @@ function normalize(raw: unknown): Manifest | null { return { name: typeof m.name === 'string' ? m.name : DEFAULT_MANIFEST.name, version: typeof m.version === 'string' ? m.version : DEFAULT_MANIFEST.version, + auth: { enabled: m.auth?.enabled === true }, runLogs: { dataLimits: { bytes: num(limits.bytes, DEFAULT_LOG_DATA_LIMITS.bytes), @@ -77,7 +82,10 @@ const listeners = new Set<() => void>(); * silent: the cached (or default) manifest stays in use. */ export function refreshManifest(): Promise { - inFlight ??= fetch(MANIFEST_URL, { headers: { Accept: 'application/json' } }) + inFlight ??= fetch(MANIFEST_URL, { + headers: { Accept: 'application/json' }, + credentials: 'include', + }) .then((res) => (res.ok ? res.json() : null)) .then((raw: unknown) => { const next = normalize(raw); diff --git a/client/src/main.tsx b/client/src/main.tsx index dc784c2..f45933c 100644 --- a/client/src/main.tsx +++ b/client/src/main.tsx @@ -6,15 +6,26 @@ import './i18n'; import './ui/tokens.css'; import App from './App'; import { ToastProvider } from './ui'; +import { AuthProvider } from './auth/AuthContext'; +import { ApiError } from './api/client'; -const queryClient = new QueryClient(); +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: (failureCount, error) => + error instanceof ApiError && error.status === 401 ? false : failureCount < 3, + }, + }, +}); createRoot(document.getElementById('root')!).render( - + + + diff --git a/client/src/pages/auth/AuthStatusPage.module.css b/client/src/pages/auth/AuthStatusPage.module.css new file mode 100644 index 0000000..7f34e04 --- /dev/null +++ b/client/src/pages/auth/AuthStatusPage.module.css @@ -0,0 +1,57 @@ +.page { + min-height: 100vh; + padding: 24px; + display: flex; + flex-direction: column; + color: var(--color-text); + background: var(--color-bg); + font-family: var(--font-family); +} + +.header { + display: flex; + align-items: center; + justify-content: space-between; +} + +.logo { + display: block; + width: auto; + height: 32px; + padding: 3px 6px; + background: #e6edea; + border-radius: var(--radius-md); +} + +.main { + flex: 1; + display: grid; + place-items: center; + padding: var(--space-6) 0; +} + +.message { + width: min(100%, 440px); + display: flex; + flex-direction: column; + align-items: stretch; + gap: var(--space-4); + margin: 0; + padding: var(--space-6); + text-align: center; + background: var(--color-bg); + border: var(--border-width) solid var(--color-border); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-sm); +} + +.message p { + margin: 0; + color: var(--color-error-fg); +} + +@media (max-width: 480px) { + .page { + padding: 16px; + } +} diff --git a/client/src/pages/auth/AuthStatusPage.tsx b/client/src/pages/auth/AuthStatusPage.tsx new file mode 100644 index 0000000..ce0a669 --- /dev/null +++ b/client/src/pages/auth/AuthStatusPage.tsx @@ -0,0 +1,38 @@ +import { useTranslation } from 'react-i18next'; +import { Button, ThemeSwitcher } from '../../ui'; +import { usePageTitle } from '../../hooks/usePageTitle'; +import liqaLogo from '../../assets/liqa.svg'; +import styles from './AuthStatusPage.module.css'; + +export function AuthStatusPage({ + failed = false, + onRetry, +}: { + failed?: boolean; + onRetry?: () => void; +}) { + const { t } = useTranslation(); + usePageTitle(t('auth.page_title')); + return ( +
+
+ Liqa + +
+
+ {failed ? ( +
+

{t('auth.session_check_failed')}

+ +
+ ) : ( +

+ {t('auth.checking_session')} +

+ )} +
+
+ ); +} diff --git a/client/src/pages/auth/LoginForm.module.css b/client/src/pages/auth/LoginForm.module.css new file mode 100644 index 0000000..d8664d2 --- /dev/null +++ b/client/src/pages/auth/LoginForm.module.css @@ -0,0 +1,65 @@ +.card { + width: min(100%, 400px); + padding: 24px; + color: var(--color-text); + background: var(--color-bg); + border: var(--border-width) solid var(--color-border); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-sm); +} + +.title { + margin: 0 0 var(--space-5); + font-size: var(--font-size-lg); + line-height: 1.3; + text-align: center; +} + +.title:focus { + outline: 2px solid var(--color-primary-text); + outline-offset: 4px; + border-radius: var(--radius-sm); +} + +.notice, +.formError { + margin: 0; + padding: var(--space-3) var(--space-4); + color: var(--color-error-fg); + background: var(--color-error-bg); + border-radius: var(--radius-md); + font-size: var(--font-size-sm); +} + +.notice { + margin-bottom: var(--space-4); +} + +.form .loginInput { + background: var(--color-bg-subtle); +} + +.form { + display: flex; + flex-direction: column; + gap: var(--space-4); +} + +.submit { + width: 100%; +} + +.status { + margin: 0; + color: var(--color-text-muted); + font-size: var(--font-size-sm); +} + +@media (max-width: 480px) { + .card { + padding: var(--space-4); + border: 0; + border-radius: 0; + box-shadow: none; + } +} diff --git a/client/src/pages/auth/LoginForm.tsx b/client/src/pages/auth/LoginForm.tsx new file mode 100644 index 0000000..38ed75f --- /dev/null +++ b/client/src/pages/auth/LoginForm.tsx @@ -0,0 +1,133 @@ +import { useEffect, useRef, useState, type FormEvent } from 'react'; +import { useTranslation } from 'react-i18next'; +import { ApiError } from '../../api/client'; +import { Button, Input } from '../../ui'; +import styles from './LoginForm.module.css'; + +export interface LoginFormProps { + expired?: boolean; + signedOut?: boolean; + onSubmit: (username: string, password: string) => Promise; +} + +export function LoginForm({ expired = false, signedOut = false, onSubmit }: LoginFormProps) { + const { t } = useTranslation(); + const titleRef = useRef(null); + const formRef = useRef(null); + const focusPasswordAfterInvalidCredentialsRef = useRef(false); + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [usernameError, setUsernameError] = useState(''); + const [passwordError, setPasswordError] = useState(''); + const [formError, setFormError] = useState(''); + const [submitting, setSubmitting] = useState(false); + + useEffect(() => { + titleRef.current?.focus(); + }, []); + + useEffect(() => { + if (!submitting && focusPasswordAfterInvalidCredentialsRef.current) { + focusPasswordAfterInvalidCredentialsRef.current = false; + formRef.current?.querySelector('input[name="password"]')?.focus(); + } + }, [submitting]); + + function focusInput(name: string) { + formRef.current?.querySelector(`input[name="${name}"]`)?.focus(); + } + + async function handleSubmit(event: FormEvent) { + event.preventDefault(); + if (submitting) return; + setFormError(''); + const missingUsername = username.trim().length === 0; + const missingPassword = password.length === 0; + setUsernameError(missingUsername ? t('auth.username_required') : ''); + setPasswordError(missingPassword ? t('auth.password_required') : ''); + if (missingUsername || missingPassword) { + focusInput(missingUsername ? 'username' : 'password'); + return; + } + + setSubmitting(true); + try { + await onSubmit(username, password); + } catch (error) { + if (error instanceof ApiError && error.status === 401) { + setFormError(t('auth.invalid_credentials')); + setPassword(''); + focusPasswordAfterInvalidCredentialsRef.current = true; + } else { + setFormError(t('auth.sign_in_failed')); + } + } finally { + setSubmitting(false); + } + } + + return ( +
+

+ {t('auth.sign_in')} +

+ {expired &&

{t('auth.session_expired')}

} + {signedOut &&

{t('auth.signed_out')}

} +
void handleSubmit(event)} + noValidate + > + { + setUsername(event.target.value); + if (usernameError) setUsernameError(''); + }} + error={usernameError || undefined} + disabled={submitting} + /> + { + setPassword(event.target.value); + if (passwordError) setPasswordError(''); + }} + error={passwordError || undefined} + disabled={submitting} + /> + {formError && ( +

+ {formError} +

+ )} + {submitting && ( +

+ {t('auth.signing_in')} +

+ )} + +
+
+ ); +} diff --git a/client/src/pages/auth/LoginPage.module.css b/client/src/pages/auth/LoginPage.module.css new file mode 100644 index 0000000..d226e13 --- /dev/null +++ b/client/src/pages/auth/LoginPage.module.css @@ -0,0 +1,44 @@ +.page { + min-height: 100vh; + padding: 24px; + display: flex; + flex-direction: column; + color: var(--color-text); + background: var(--color-bg); + font-family: var(--font-family); +} + +.header { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-4); +} + +.logo { + display: block; + width: auto; + height: 32px; + padding: 3px 6px; + background: #e6edea; + border-radius: var(--radius-md); +} + +.main { + flex: 1; + min-height: 0; + display: grid; + place-items: center; + padding: var(--space-6) 0; +} + +@media (max-width: 480px) { + .page { + padding: 16px; + } + + .main { + align-items: start; + padding-top: clamp(40px, 12vh, 96px); + } +} diff --git a/client/src/pages/auth/LoginPage.tsx b/client/src/pages/auth/LoginPage.tsx new file mode 100644 index 0000000..0042e35 --- /dev/null +++ b/client/src/pages/auth/LoginPage.tsx @@ -0,0 +1,41 @@ +import { useCallback } from 'react'; +import { useNavigate, useSearchParams } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { useAuth } from '../../auth/useAuth'; +import { safeReturnTo } from '../../auth/returnTo'; +import { usePageTitle } from '../../hooks/usePageTitle'; +import { ThemeSwitcher } from '../../ui'; +import liqaLogo from '../../assets/liqa.svg'; +import { LoginForm } from './LoginForm'; +import styles from './LoginPage.module.css'; + +export function LoginPage() { + const auth = useAuth(); + const navigate = useNavigate(); + const [search] = useSearchParams(); + const { t } = useTranslation(); + const returnTo = safeReturnTo(search.get('returnTo')) ?? '/scenarios'; + const expired = search.get('expired') === '1'; + const signedOut = search.get('notice') === 'signedOut'; + usePageTitle(t('auth.page_title')); + + const handleSubmit = useCallback( + async (username: string, password: string) => { + await auth.login(username, password); + navigate(returnTo, { replace: true }); + }, + [auth, navigate, returnTo], + ); + + return ( +
+
+ Liqa + +
+
+ +
+
+ ); +} diff --git a/client/src/pages/auth/SignOutControl.module.css b/client/src/pages/auth/SignOutControl.module.css new file mode 100644 index 0000000..dab6b96 --- /dev/null +++ b/client/src/pages/auth/SignOutControl.module.css @@ -0,0 +1,57 @@ +.root { + display: flex; + flex-direction: column; + gap: var(--space-2); + min-width: 0; +} + +.button { + min-height: 44px; + display: inline-flex; + align-items: center; + justify-content: center; + gap: var(--space-2); + padding: var(--space-2) var(--space-3); + color: var(--color-text); + background: transparent; + border: var(--border-width) solid var(--color-border); + border-radius: var(--radius-md); + font: inherit; + font-size: var(--font-size-xs); + cursor: pointer; +} + +.button:hover:not(:disabled) { + background: var(--color-secondary); +} + +.button:focus-visible, +.failure button:focus-visible { + outline: 2px solid var(--color-primary-text); + outline-offset: 2px; +} + +.button:disabled { + opacity: 0.55; + cursor: wait; +} + +.failure { + display: flex; + align-items: center; + gap: var(--space-2); + padding: var(--space-2); + color: var(--color-error-fg); + background: var(--color-error-bg); + border-radius: var(--radius-sm); + font-size: var(--font-size-xs); +} + +.failure button { + min-height: 32px; + color: inherit; + background: transparent; + border: var(--border-width) solid currentColor; + border-radius: var(--radius-sm); + cursor: pointer; +} diff --git a/client/src/pages/auth/SignOutControl.tsx b/client/src/pages/auth/SignOutControl.tsx new file mode 100644 index 0000000..835954b --- /dev/null +++ b/client/src/pages/auth/SignOutControl.tsx @@ -0,0 +1,39 @@ +import { LogOut } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import styles from './SignOutControl.module.css'; + +export function SignOutControl({ + pending = false, + failed = false, + onSignOut, +}: { + pending?: boolean; + failed?: boolean; + onSignOut: () => void; +}) { + const { t } = useTranslation(); + return ( +
+ + {failed && ( +
+ {t('auth.sign_out_failed')} + +
+ )} +
+ ); +} diff --git a/client/src/ui/Button/Button.module.css b/client/src/ui/Button/Button.module.css index 02c0912..1445736 100644 --- a/client/src/ui/Button/Button.module.css +++ b/client/src/ui/Button/Button.module.css @@ -88,3 +88,9 @@ @keyframes spin { to { transform: rotate(360deg); } } + +@media (prefers-reduced-motion: reduce) { + .spinner { + animation: none; + } +} diff --git a/client/src/ui/SidePanel/SidePanel.tsx b/client/src/ui/SidePanel/SidePanel.tsx index 1c13fa5..fe39f8e 100644 --- a/client/src/ui/SidePanel/SidePanel.tsx +++ b/client/src/ui/SidePanel/SidePanel.tsx @@ -38,7 +38,7 @@ export function SidePanel({ style={{ '--side-panel-width': `${width}px` } as React.CSSProperties} aria-expanded={!collapsed} > -
+
{header &&
{header}
}
{children}