dorfteich/apps/web/src/pages/SettingsPage.tsx
Claude Fable 5 0c85293830
Some checks failed
CI / Lint, typecheck, test (push) Failing after 1m39s
CI / Auth e2e pack (push) Has been skipped
CI / Import/export fidelity gate (push) Has been skipped
CI / Build container images (push) Has been skipped
CD / Build and push images (push) Successful in 3m51s
CD / Deploy to Test (push) Successful in 9s
CD / Smoke tests against Test (push) Successful in 1m10s
CD / Promote to Int (push) Successful in 11s
Public REST API v1: personal access tokens, instance switch + per-pond opt-in (#104)
Token-authenticated machine access at /api/public/v1 — the foundation for
the built-in MCP endpoint (#105).

Personal access tokens:
- api_tokens table (SHA-256 hash, scope read|write, optional pond
  restriction, expiry, revocation, throttled last-used) + migration;
  secrets are dt_pat_<random>, shown exactly once
- lifecycle endpoints under /users/me/api-tokens (session-only — a leaked
  token can never mint more tokens) with audit entries
  api.token_created/api.token_revoked
- settings UI section (create with scope/expiry/pond restriction,
  one-time reveal with copy, list with status + revoke), de+en

Activation (404 semantics per #60 on both levels):
- instance setting api.enabled (default off, admin settings switch)
- pond setting apiEnabled (default off, pond settings toggle; the
  PondsService settings-merge learned the key — the #92 lesson)

Surface (/api/public/v1, excluded from the SPA's global prefix):
- me, ponds, pages (list/read as Markdown+HTML, create from Markdown via
  the shared pipeline, PATCH title/content, DELETE to trash), search
  (permission-filtered + narrowed to exposed ponds, highlights as **…**),
  markdown ZIP export, labels (tree, create/rename/recolour/move/delete,
  assign/unassign), comments (threads, create, resolve/reopen)
- content replacement travels the collab-owned document path: the new
  state lands as a MANUAL version "API update", then the established
  restore NOTIFY applies it — open editors converge, history stays
  append-only, no second lineage (VersionsService.replaceContent)
- hand-maintained OpenAPI 3.1 document at /openapi.json, pinned to the
  controller by a route-coverage test in both directions

Enforcement:
- PublicApiGuard: instance switch → bearer PAT auth (request.user is the
  token's user) → per-token rate limit (429 + Retry-After) → scope
  (403 scope_required) → pond opt-in + token restriction
- the shared PermissionGuard then applies the unchanged permission model;
  PageParamSource gained pondSlugParam for the slug+slug routes
- no cookies anywhere → no CSRF surface (pinned by a hostile-Origin test)
- every write audit-logged as api.write with the token attributed

Tests/verification:
- 12-test e2e pack: lifecycle, switches, permission matrix
  (reader/editor/outsider × scopes), restriction, page roundtrip incl.
  restore-NOTIFY assertion, labels, comments incl. policy, search
  narrowing, ZIP export, rate limit; full api suite 60/60 green
  (quota fixture via per-user override — never the instance default)
- new collab-pack test proves an open editor converges onto an API
  content replacement (green against a local seeded stack)
- UI smoke against the built SPA: token create/reveal/revoke, pond
  opt-in persists, admin switch persists (10/10)
- docs/self-hosting/public-api.md + README link

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EwZ4jR4KFAPvpjWevfUGX1
2026-07-12 11:17:03 +02:00

288 lines
9.5 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod';
import { changePasswordInputSchema, updateProfileInputSchema } from '@dorfteich/shared';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../auth/auth-context';
import { Field, FormError, FormSuccess, applyFieldErrors } from '../components/forms';
import { useDataExport } from '../export/use-data-export';
import { apiDelete, apiGet, apiPatch, apiPost } from '../lib/api';
import { ApiTokensSection } from '../api-tokens/ApiTokensSection';
import { WatchesSection } from '../watches/WatchesSection';
interface SessionView {
id: string;
createdAt: string;
lastSeenAt: string;
userAgent: string | null;
current: boolean;
}
export function SettingsPage(): React.JSX.Element {
const { t } = useTranslation();
return (
<>
<h1>{t('settings:title')}</h1>
<ProfileSection />
<PasswordSection />
<SessionsSection />
<WatchesSection />
<ApiTokensSection />
<DataExportSection />
</>
);
}
function DataExportSection(): React.JSX.Element {
const { t, i18n } = useTranslation();
const { status, expiresAt, request, download } = useDataExport();
const formatTime = (iso: string): string =>
new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium', timeStyle: 'short' }).format(
new Date(iso),
);
return (
<section className="settings-section">
<h2>{t('settings:dataExport.title')}</h2>
<p className="sidebar__hint">{t('settings:dataExport.description')}</p>
{status === 'error' && (
<p className="form-banner form-banner--error" role="alert">
{t('settings:dataExport.failed')}
</p>
)}
{status === 'rateLimited' && (
<p className="form-banner form-banner--error" role="alert">
{t('settings:dataExport.rateLimited')}
</p>
)}
{status === 'ready' ? (
<>
<FormSuccess message={t('settings:dataExport.ready')} />
<button type="button" className="button" onClick={download}>
{t('settings:dataExport.download')}
</button>
{expiresAt && (
<p className="sidebar__hint">
{t('settings:dataExport.expiresHint', { when: formatTime(expiresAt) })}
</p>
)}
</>
) : (
<button type="button" className="button" onClick={request} disabled={status === 'busy'}>
{status === 'busy'
? t('settings:dataExport.preparing')
: t('settings:dataExport.request')}
</button>
)}
</section>
);
}
function ProfileSection(): React.JSX.Element {
const { t, i18n } = useTranslation();
const { user, refresh } = useAuth();
const [error, setError] = useState<unknown>(null);
const [saved, setSaved] = useState(false);
const form = useForm<{
displayName?: string;
locale?: 'de' | 'en';
autoWatchOwnPages?: boolean;
autoWatchOnComment?: boolean;
digestFrequency?: 'hourly' | 'daily' | 'off';
}>({
resolver: zodResolver(updateProfileInputSchema),
values: {
displayName: user?.displayName,
locale: user?.locale,
autoWatchOwnPages: user?.autoWatchOwnPages,
autoWatchOnComment: user?.autoWatchOnComment,
digestFrequency: user?.digestFrequency,
},
});
const onSubmit = form.handleSubmit(async (input) => {
setError(null);
setSaved(false);
try {
await apiPatch('/users/me', input);
// The new language applies immediately, before the refetch lands.
if (input.locale) await i18n.changeLanguage(input.locale);
await refresh();
setSaved(true);
} catch (err) {
setError(err);
applyFieldErrors(err, (name, fieldError) =>
form.setError(name as 'displayName' | 'locale', fieldError),
);
}
});
return (
<section className="settings-section">
<h2>{t('settings:profile.title')}</h2>
<form onSubmit={onSubmit} noValidate>
<FormError error={error} />
<FormSuccess message={saved ? t('settings:profile.saved') : null} />
<Field
label={t('settings:profile.displayName')}
error={form.formState.errors.displayName?.message}
>
<input type="text" autoComplete="name" {...form.register('displayName')} />
</Field>
<Field label={t('settings:profile.locale')}>
<select {...form.register('locale')}>
<option value="de">{t('settings:profile.locales.de')}</option>
<option value="en">{t('settings:profile.locales.en')}</option>
</select>
</Field>
<label className="settings-checkbox">
<input type="checkbox" {...form.register('autoWatchOwnPages')} />
{t('watches:prefs.autoWatchOwnPages')}
</label>
<label className="settings-checkbox">
<input type="checkbox" {...form.register('autoWatchOnComment')} />
{t('watches:prefs.autoWatchOnComment')}
</label>
<Field label={t('notifications:digest.label')}>
<select {...form.register('digestFrequency')}>
<option value="hourly">{t('notifications:digest.hourly')}</option>
<option value="daily">{t('notifications:digest.daily')}</option>
<option value="off">{t('notifications:digest.off')}</option>
</select>
</Field>
<button type="submit" className="button" disabled={form.formState.isSubmitting}>
{t('settings:profile.save')}
</button>
</form>
</section>
);
}
function PasswordSection(): React.JSX.Element {
const { t } = useTranslation();
const [error, setError] = useState<unknown>(null);
const [changed, setChanged] = useState(false);
const form = useForm<{ currentPassword: string; newPassword: string }>({
resolver: zodResolver(changePasswordInputSchema),
});
const onSubmit = form.handleSubmit(async (input) => {
setError(null);
setChanged(false);
try {
await apiPost('/users/me/change-password', input);
form.reset();
setChanged(true);
} catch (err) {
setError(err);
}
});
return (
<section className="settings-section">
<h2>{t('settings:password.title')}</h2>
<form onSubmit={onSubmit} noValidate>
<FormError error={error} />
<FormSuccess message={changed ? t('settings:password.changed') : null} />
<Field
label={t('settings:password.current')}
error={form.formState.errors.currentPassword?.message}
>
<input
type="password"
autoComplete="current-password"
{...form.register('currentPassword')}
/>
</Field>
<Field
label={t('settings:password.new')}
hint={t('auth:signup.passwordHint')}
error={form.formState.errors.newPassword?.message}
>
<input type="password" autoComplete="new-password" {...form.register('newPassword')} />
</Field>
<button type="submit" className="button" disabled={form.formState.isSubmitting}>
{t('settings:password.submit')}
</button>
</form>
</section>
);
}
function SessionsSection(): React.JSX.Element {
const { t, i18n } = useTranslation();
const queryClient = useQueryClient();
const sessions = useQuery({
queryKey: ['sessions'],
queryFn: () => apiGet<SessionView[]>('/users/me/sessions'),
});
const invalidate = () => queryClient.invalidateQueries({ queryKey: ['sessions'] });
const revoke = useMutation({
mutationFn: (id: string) => apiDelete(`/users/me/sessions/${id}`),
onSuccess: invalidate,
});
const revokeOthers = useMutation({
mutationFn: () => apiDelete('/users/me/sessions'),
onSuccess: invalidate,
});
const formatTime = (iso: string) =>
new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium', timeStyle: 'short' }).format(
new Date(iso),
);
const others = (sessions.data ?? []).filter((s) => !s.current);
return (
<section className="settings-section">
<h2>{t('settings:sessions.title')}</h2>
<table className="table">
<thead>
<tr>
<th>{t('settings:sessions.device')}</th>
<th>{t('settings:sessions.created')}</th>
<th>{t('settings:sessions.lastSeen')}</th>
<th></th>
</tr>
</thead>
<tbody>
{(sessions.data ?? []).map((session) => (
<tr key={session.id}>
<td>
{session.userAgent ?? '—'}
{session.current && <span className="badge">{t('settings:sessions.current')}</span>}
</td>
<td>{formatTime(session.createdAt)}</td>
<td>{formatTime(session.lastSeenAt)}</td>
<td>
{!session.current && (
<button
type="button"
className="linklike"
onClick={() => revoke.mutate(session.id)}
>
{t('settings:sessions.revoke')}
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
{others.length > 0 ? (
<button type="button" className="button" onClick={() => revokeOthers.mutate()}>
{t('settings:sessions.revokeAll')}
</button>
) : (
<p className="sidebar__hint">{t('settings:sessions.empty')}</p>
)}
</section>
);
}