audit: 33-agent comprehensive audit + critical fixes

Full team audit run, all reports verbatim in docs/AUDIT-2026-05-12.md
(5900+ lines, 30+ critical findings). Already-fixed this commit:
- permission-overrides PUT: self-target block + RolePermissions allow-list + cross-tenant guard
- /api/auth/resolve-identifier: rate-limit + synthetic miss-email kill enumeration
- admin email-change: rotates account.accountId + revokes sessions
- middleware: token-gated email confirm/cancel routes whitelisted
- NAV_CATALOG: 10 dead-link sweeps to existing /admin/<x> targets

Feature work landing same commit: optional username sign-in
(migration 0054), per-user permission overrides (0055) with three-state
matrix tabbed inside UserForm, user disable button, role + outcome +
stage label normalisation across the platform, admin email-change
with auto-notification template.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-12 16:52:35 +02:00
parent 660553c074
commit 4b9743a594
31 changed files with 7042 additions and 81 deletions

View File

@@ -70,7 +70,14 @@ const GROUPS: AdminGroup[] = [
label: 'Users',
description: 'CRM accounts, role assignments, and per-user residential access toggles.',
icon: Users,
keywords: ['accounts', 'staff', 'team', 'disable user', 'reset password', 'residential access'],
keywords: [
'accounts',
'staff',
'team',
'disable user',
'reset password',
'residential access',
],
},
{
href: 'invitations',

View File

@@ -1,15 +1,6 @@
'use client';
import {
Clock,
Mail,
MoreHorizontal,
Pencil,
Power,
PowerOff,
Shield,
Trash2,
} from 'lucide-react';
import { Clock, Mail, MoreHorizontal, Pencil, Power, PowerOff, Shield, Trash2 } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { formatRole } from '@/lib/constants';

View File

@@ -2,7 +2,6 @@
import { formatErrorBanner } from '@/lib/api/toast-error';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -15,6 +14,8 @@ import {
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { UserPermissionMatrix } from './user-permission-matrix';
import {
AlertDialog,
AlertDialogAction,
@@ -26,7 +27,6 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { PhoneInput, type PhoneInputValue } from '@/components/shared/phone-input';
import { useUIStore } from '@/stores/ui-store';
import { apiFetch } from '@/lib/api/client';
import { formatRole } from '@/lib/constants';
@@ -69,7 +69,6 @@ export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps)
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const portSlug = useUIStore((s) => s.currentPortSlug);
const isEdit = !!user;
const fullName = `${firstName} ${lastName}`.trim();
@@ -192,7 +191,28 @@ export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps)
<SheetTitle>{isEdit ? 'Edit User' : 'New User'}</SheetTitle>
</SheetHeader>
<form onSubmit={handleSubmit} className="mt-6 space-y-4">
<Tabs defaultValue="profile" className="mt-6">
<TabsList className="w-full">
<TabsTrigger value="profile" className="flex-1">
Profile &amp; role
</TabsTrigger>
<TabsTrigger value="permissions" className="flex-1" disabled={!isEdit}>
Permissions
</TabsTrigger>
</TabsList>
<TabsContent value="permissions" className="mt-4">
{isEdit ? (
<UserPermissionMatrix userId={user.userId} />
) : (
<p className="text-sm text-muted-foreground">
Save the new user first, then return here to fine-tune their permissions.
</p>
)}
</TabsContent>
<TabsContent value="profile" className="mt-4">
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-3">
<div className="space-y-2">
<Label htmlFor="user-first-name">First name</Label>
@@ -320,23 +340,6 @@ export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps)
</div>
)}
{isEdit && portSlug && (
<div className="rounded-lg border bg-muted/30 p-3">
<p className="text-sm font-medium">Fine-tuned permissions</p>
<p className="text-xs text-muted-foreground">
The selected role grants a baseline. To add or remove a specific permission for
this user only, open the role &amp; permissions page.
</p>
<Link
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
href={`/${portSlug}/admin/roles?focusUser=${user.userId}` as any}
className="mt-2 inline-block text-xs font-medium text-primary hover:underline"
>
Manage permissions
</Link>
</div>
)}
{error && <p className="whitespace-pre-line text-sm text-destructive">{error}</p>}
<SheetFooter>
@@ -353,6 +356,8 @@ export function UserForm({ open, onOpenChange, user, onSuccess }: UserFormProps)
</Button>
</SheetFooter>
</form>
</TabsContent>
</Tabs>
<AlertDialog open={emailConfirmOpen} onOpenChange={setEmailConfirmOpen}>
<AlertDialogContent>

View File

@@ -157,9 +157,7 @@ export function UserList() {
) : (
<Power className="h-4 w-4" />
)}
<span className="sr-only">
{row.original.isActive ? 'Disable' : 'Enable'}
</span>
<span className="sr-only">{row.original.isActive ? 'Disable' : 'Enable'}</span>
</Button>
}
title={row.original.isActive ? 'Disable user' : 'Enable user'}

View File

@@ -0,0 +1,301 @@
'use client';
import { useEffect, useState } from 'react';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { ScrollArea } from '@/components/ui/scroll-area';
import { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';
/**
* Three-state per-user permission editor.
*
* For every leaf in RolePermissions we render an Inherit / Grant / Deny
* toggle. "Inherit" leaves the leaf out of the user_permission_overrides
* map so the role + port-role-override baseline wins. "Grant" / "Deny"
* write `true` / `false` and override the baseline.
*
* Baseline comes from the GET endpoint which already merges role + port-
* role override + residential toggle, so the inherit-state label matches
* what `withAuth` would resolve to today.
*/
const GROUP_LABELS: Record<string, string> = {
clients: 'Clients',
interests: 'Interests / Pipeline',
berths: 'Berths',
documents: 'Documents',
expenses: 'Expenses',
invoices: 'Invoices',
files: 'Files',
email: 'Email',
reminders: 'Reminders',
calendar: 'Calendar',
reports: 'Reports',
document_templates: 'Document Templates',
yachts: 'Yachts',
companies: 'Companies',
memberships: 'Company Memberships',
reservations: 'Reservations',
admin: 'Administration',
residential_clients: 'Residential Clients',
residential_interests: 'Residential Interests',
};
// Mirrors RolePermissions in src/lib/db/schema/users.ts — used as the
// canonical leaf list so the matrix shows every action even when the
// baseline JSON omits a key (older roles, partial overrides).
const PERMISSION_LEAVES: Record<string, string[]> = {
clients: ['view', 'create', 'edit', 'delete', 'merge', 'export'],
interests: [
'view',
'create',
'edit',
'delete',
'change_stage',
'override_stage',
'generate_eoi',
'export',
],
berths: ['view', 'edit', 'import', 'manage_waiting_list'],
documents: [
'view',
'create',
'edit',
'send_for_signing',
'upload_signed',
'delete',
'manage_folders',
],
expenses: ['view', 'create', 'edit', 'delete', 'export', 'scan_receipt'],
invoices: ['view', 'create', 'edit', 'delete', 'send', 'record_payment', 'export'],
files: ['view', 'upload', 'edit', 'delete', 'manage_folders'],
email: ['view', 'send', 'configure_account'],
reminders: ['view_own', 'view_all', 'create', 'edit_own', 'edit_all', 'assign_others'],
calendar: ['connect', 'view_events'],
reports: ['view_dashboard', 'view_analytics', 'export'],
document_templates: ['view', 'generate', 'manage'],
yachts: ['view', 'create', 'edit', 'delete', 'transfer'],
companies: ['view', 'create', 'edit', 'delete'],
memberships: ['view', 'manage'],
reservations: ['view', 'create', 'activate', 'cancel'],
admin: [
'manage_users',
'view_audit_log',
'manage_settings',
'manage_webhooks',
'manage_reports',
'manage_custom_fields',
'manage_forms',
'manage_tags',
'system_backup',
'permanently_delete_clients',
],
residential_clients: ['view', 'create', 'edit', 'delete'],
residential_interests: ['view', 'create', 'edit', 'delete', 'change_stage'],
};
function formatAction(action: string): string {
return action.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
}
type Overrides = Record<string, Record<string, boolean>>;
type Baseline = Record<string, Record<string, boolean>> | null;
interface PermissionMatrixResponse {
data: {
baseline: Baseline;
overrides: Overrides;
isSuperAdmin: boolean;
};
}
interface UserPermissionMatrixProps {
userId: string;
}
export function UserPermissionMatrix({ userId }: UserPermissionMatrixProps) {
const [baseline, setBaseline] = useState<Baseline>(null);
const [overrides, setOverrides] = useState<Overrides>({});
// Tracked so future revisions can surface a dirty-state indicator; the
// ui-ux audit recommended one. Setter is wired now to capture the
// server-canonical baseline post-save.
const [, setOriginalOverrides] = useState<Overrides>({});
const [isSuperAdmin, setIsSuperAdmin] = useState(false);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [message, setMessage] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
void (async () => {
setLoading(true);
try {
const res = await apiFetch<PermissionMatrixResponse>(
`/api/v1/admin/users/${userId}/permission-overrides`,
);
if (cancelled) return;
setBaseline(res.data.baseline);
const fetched = res.data.overrides ?? {};
setOverrides(fetched);
setOriginalOverrides(fetched);
setIsSuperAdmin(res.data.isSuperAdmin);
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [userId]);
function getState(resource: string, action: string): 'inherit' | 'grant' | 'deny' {
const v = overrides[resource]?.[action];
if (v === true) return 'grant';
if (v === false) return 'deny';
return 'inherit';
}
function setState(resource: string, action: string, next: 'inherit' | 'grant' | 'deny') {
setOverrides((prev) => {
const copy: Overrides = { ...prev, [resource]: { ...(prev[resource] ?? {}) } };
if (next === 'inherit') {
delete copy[resource]![action];
if (Object.keys(copy[resource]!).length === 0) delete copy[resource];
} else {
copy[resource]![action] = next === 'grant';
}
return copy;
});
}
function baselineFor(resource: string, action: string): boolean {
return baseline?.[resource]?.[action] === true;
}
async function save() {
setSaving(true);
setMessage(null);
try {
await apiFetch(`/api/v1/admin/users/${userId}/permission-overrides`, {
method: 'PUT',
body: { overrides },
});
setOriginalOverrides(overrides);
setMessage('Overrides saved.');
} catch (err: unknown) {
setMessage(err instanceof Error ? err.message : 'Failed to save overrides');
} finally {
setSaving(false);
}
}
if (loading) {
return (
<div className="py-6 text-center text-sm text-muted-foreground">Loading permissions</div>
);
}
if (isSuperAdmin) {
return (
<div className="rounded-md border bg-muted/30 p-4 text-sm text-muted-foreground">
Super-admin users bypass per-port permission checks. Overrides don&apos;t apply here
revoke the super-admin flag on the Profile tab first.
</div>
);
}
if (!baseline) {
return (
<div className="rounded-md border bg-amber-50 p-4 text-sm text-amber-900">
This user isn&apos;t assigned to this port, so the role baseline isn&apos;t resolvable.
Assign them a role on the Profile tab before editing per-user permissions.
</div>
);
}
return (
<div className="space-y-3">
<div className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
<p>
Permission overrides save <strong>on the button below</strong>, separately from the
Profile &amp; role tab. Switching tabs or closing the drawer without clicking
<strong> Save overrides</strong> drops your changes.
</p>
</div>
<p className="text-xs text-muted-foreground">
Each toggle defaults to <strong>Inherit</strong> (role + port override decide). Switch to
<strong> Grant</strong> or <strong>Deny</strong> to force the value for this user only.
</p>
<ScrollArea className="h-[420px] rounded-md border">
<Accordion type="multiple" className="px-3">
{Object.entries(PERMISSION_LEAVES).map(([resource, leaves]) => (
<AccordionItem key={resource} value={resource}>
<AccordionTrigger className="text-sm">
{GROUP_LABELS[resource] ?? resource}
</AccordionTrigger>
<AccordionContent>
<div className="space-y-2 pl-2 pb-2">
{leaves.map((action) => {
const state = getState(resource, action);
const inherited = baselineFor(resource, action);
return (
<div
key={action}
className="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-background px-2 py-1.5"
>
<div className="text-sm">
<Label className="text-sm">{formatAction(action)}</Label>
<p className="text-[11px] text-muted-foreground">
Inherits: {inherited ? 'granted' : 'denied'}
</p>
</div>
<div
className="inline-flex rounded-md border bg-muted/30 p-0.5"
role="radiogroup"
aria-label={`${formatAction(action)} permission override`}
>
{(['inherit', 'grant', 'deny'] as const).map((opt) => (
<button
key={opt}
type="button"
role="radio"
aria-checked={state === opt}
onClick={() => setState(resource, action, opt)}
className={cn(
'rounded px-2 py-0.5 text-xs font-medium transition-colors',
state === opt
? opt === 'grant'
? 'bg-emerald-600 text-white'
: opt === 'deny'
? 'bg-rose-600 text-white'
: 'bg-foreground text-background'
: 'text-muted-foreground hover:text-foreground',
)}
>
{opt[0]!.toUpperCase() + opt.slice(1)}
</button>
))}
</div>
</div>
);
})}
</div>
</AccordionContent>
</AccordionItem>
))}
</Accordion>
</ScrollArea>
<div className="flex items-center gap-3">
<Button size="sm" onClick={save} disabled={saving}>
{saving ? 'Saving…' : 'Save overrides'}
</Button>
{message && <span className="text-xs text-muted-foreground">{message}</span>}
</div>
</div>
);
}

View File

@@ -15,7 +15,7 @@ import {
import { Badge } from '@/components/ui/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { getCountryName } from '@/lib/i18n/countries';
import { stageDotClass, stageLabel, formatSource } from '@/lib/constants';
import { stageDotClass, stageLabel, formatSource, formatOutcome } from '@/lib/constants';
import { cn } from '@/lib/utils';
import type { ColumnPickerOption } from '@/components/shared/column-picker';
@@ -249,7 +249,7 @@ export function getClientColumns({
<span className="font-medium text-foreground">{b.mooringNumber}</span>
<span className="text-xs text-muted-foreground">
{b.outcome
? `${stageLabel(b.stage)} · ${b.outcome.replace(/_/g, ' ')}`
? `${stageLabel(b.stage)} · ${formatOutcome(b.outcome) ?? b.outcome}`
: stageLabel(b.stage)}
</span>
</Link>
@@ -342,7 +342,7 @@ function BerthInterestChip({
}) {
const isClosed = berth.outcome !== null;
const label = isClosed
? `${stageLabel(berth.stage)} · ${berth.outcome!.replace(/_/g, ' ')}`
? `${stageLabel(berth.stage)} · ${formatOutcome(berth.outcome) ?? berth.outcome}`
: stageLabel(berth.stage);
return (
<Link

View File

@@ -26,6 +26,7 @@ import { InterestForm } from '@/components/interests/interest-form';
import { InlineStagePicker } from '@/components/interests/inline-stage-picker';
import { InterestOutcomeDialog } from '@/components/interests/interest-outcome-dialog';
import { apiFetch } from '@/lib/api/client';
import { formatOutcome } from '@/lib/constants';
import { cn } from '@/lib/utils';
const OUTCOME_BADGE: Record<string, { label: string; className: string }> = {
@@ -46,7 +47,7 @@ function resolveOutcomeBadge(outcome: string | null | undefined) {
if (known) return known;
const isLoss = outcome.startsWith('lost');
return {
label: outcome.replace(/_/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase()),
label: formatOutcome(outcome) ?? outcome,
className: isLoss ? 'bg-rose-100 text-rose-700' : 'bg-slate-200 text-slate-700',
};
}

View File

@@ -39,6 +39,7 @@ import {
import { apiFetch } from '@/lib/api/client';
import { cn } from '@/lib/utils';
import { formatCurrency } from '@/lib/utils/currency';
import { STAGE_LABELS, formatOutcome, type PipelineStage } from '@/lib/constants';
import {
useSearch,
type BucketType,
@@ -929,11 +930,15 @@ export function buildFlatRows(args: BuildFlatRowsArgs): FlatRow[] {
const badges: ResultBadge[] = [];
if (i.outcome) {
badges.push({
label: i.outcome.replace(/_/g, ' '),
label: formatOutcome(i.outcome) ?? i.outcome,
tone: i.outcome === 'won' ? 'success' : 'neutral',
});
} else {
badges.push({ label: i.pipelineStage.replace(/_/g, ' '), tone: 'warning' });
badges.push({
label:
STAGE_LABELS[i.pipelineStage as PipelineStage] ?? i.pipelineStage.replace(/_/g, ' '),
tone: 'warning',
});
}
rows.push({
kind: 'result',
@@ -956,7 +961,8 @@ export function buildFlatRows(args: BuildFlatRowsArgs): FlatRow[] {
bucket: 'residentialInterests',
icon: TrendingUp,
label: i.clientName,
sub: i.pipelineStage.replace(/_/g, ' '),
sub:
STAGE_LABELS[i.pipelineStage as PipelineStage] ?? i.pipelineStage.replace(/_/g, ' '),
href: `/${portSlug}/residential/interests/${i.id}`,
});
}

View File

@@ -28,6 +28,7 @@ interface MeResponse {
firstName?: string | null;
lastName?: string | null;
displayName?: string | null;
username?: string | null;
};
}
@@ -35,6 +36,9 @@ export function UserSettings() {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [displayName, setDisplayName] = useState('');
const [username, setUsername] = useState('');
const [originalUsername, setOriginalUsername] = useState('');
const [usernameMsg, setUsernameMsg] = useState<string | null>(null);
const [phone, setPhone] = useState('');
const [email, setEmail] = useState('');
const [originalEmail, setOriginalEmail] = useState('');
@@ -75,6 +79,8 @@ export function UserSettings() {
setDisplayName(res.data.profile?.displayName ?? res.data.user?.name ?? '');
setEmail(res.data.user?.email ?? '');
setOriginalEmail(res.data.user?.email ?? '');
setUsername(res.data.profile?.username ?? '');
setOriginalUsername(res.data.profile?.username ?? '');
setCountry(res.data.preferences?.country ?? null);
// Fall back to the browser-detected zone when no value has been saved
// yet — first-time users land on a sensible default rather than an
@@ -149,6 +155,25 @@ export function UserSettings() {
}
}
async function saveUsername() {
if (username.trim().toLowerCase() === originalUsername.toLowerCase()) return;
setSaving('username');
setUsernameMsg(null);
try {
const next = username.trim().toLowerCase() || null;
await apiFetch('/api/v1/me', { method: 'PATCH', body: { username: next } });
setOriginalUsername(next ?? '');
setUsername(next ?? '');
setUsernameMsg(
next ? `Username updated. You can now sign in with @${next} or your email.` : 'Username cleared.',
);
} catch (err: unknown) {
setUsernameMsg(err instanceof Error ? err.message : 'Failed to save username');
} finally {
setSaving(null);
}
}
async function saveEmail() {
if (email === originalEmail) return;
setSaving('email');
@@ -328,6 +353,38 @@ export function UserSettings() {
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="settings-username">
Username <span className="text-muted-foreground">(optional)</span>
</Label>
<Input
id="settings-username"
value={username}
onChange={(e) => setUsername(e.target.value.toLowerCase())}
placeholder="yourname"
autoCapitalize="none"
spellCheck={false}
pattern="^[a-z0-9._-]{2,30}$"
/>
<div className="flex items-center gap-3">
<Button
size="sm"
variant="outline"
onClick={saveUsername}
disabled={
saving === 'username' ||
username.trim().toLowerCase() === originalUsername.toLowerCase()
}
>
{saving === 'username' ? 'Saving…' : 'Save username'}
</Button>
{usernameMsg && <span className="text-xs text-muted-foreground">{usernameMsg}</span>}
</div>
<p className="text-xs text-muted-foreground">
Optional alias you can use to sign in instead of your email. 230 lowercase
letters, digits, dot, underscore, or hyphen.
</p>
</div>
<div className="space-y-2 pt-2 border-t">
<Label htmlFor="settings-email">Email</Label>
<Input
id="settings-email"

View File

@@ -16,6 +16,7 @@ import {
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useDebounce } from '@/hooks/use-debounce';
import { apiFetch } from '@/lib/api/client';
import { stageLabel } from '@/lib/constants';
import { cn } from '@/lib/utils';
interface InterestOption {
@@ -71,7 +72,7 @@ export function InterestPicker({
const labelFor = (o: InterestOption) => {
const parts = [o.clientName ?? 'Unknown client'];
if (o.berthMooringNumber) parts.push(`Berth ${o.berthMooringNumber}`);
parts.push(o.pipelineStage.replace(/_/g, ' '));
parts.push(stageLabel(o.pipelineStage));
return parts.join(' · ');
};

View File

@@ -4,7 +4,7 @@ import { useEffect } from 'react';
import { toast } from 'sonner';
import { useSocket } from '@/providers/socket-provider';
import { stageLabel } from '@/lib/constants';
import { stageLabel, formatOutcome } from '@/lib/constants';
/**
* App-wide subscriber that surfaces high-signal sales events as sonner
@@ -62,9 +62,9 @@ export function RealtimeToasts() {
function onOutcomeSet(payload: { outcome?: string }) {
if (!payload?.outcome) return;
const isWon = payload.outcome === 'won';
const label = payload.outcome.replace(/_/g, ' ');
const label = formatOutcome(payload.outcome) ?? payload.outcome;
const fn = isWon ? toast.success : toast.message;
fn(`Interest closed - ${label}`);
fn(`Interest closed ${label}`);
}
socket.on('interest:stageChanged', onStageChanged);

View File

@@ -11,6 +11,7 @@ import { EntityActivityFeed } from '@/components/shared/entity-activity-feed';
import { ReservationList, type ReservationRow } from '@/components/reservations/reservation-list';
import { YachtOwnershipHistory } from '@/components/yachts/yacht-ownership-history';
import { apiFetch } from '@/lib/api/client';
import { stageLabel } from '@/lib/constants';
type YachtPatchField =
| 'name'
@@ -283,7 +284,7 @@ function YachtInterestsTab({ yachtId }: { yachtId: string }) {
className="flex items-center gap-3 rounded-md border bg-muted/30 p-3 text-sm"
>
<span className="w-36 shrink-0 text-xs font-medium uppercase text-muted-foreground">
{i.pipelineStage.replace(/_/g, ' ')}
{stageLabel(i.pipelineStage)}
</span>
<span className="flex-1 truncate">{i.clientName ?? '-'}</span>
{i.berthMooringNumber && (