feat: account deletion, username reuse, and real-time username availability

- Add account deletion with tombstone (isDeleted flag), password/username
  confirmation, owned-space guard, and full cleanup transaction
- Free deleted usernames by renaming to !deleted:<id> so they can be reused
- Add migration to retroactively free usernames from already-tombstoned users
- Add GET /api/auth/check-username endpoint with rate limiting for real-time
  availability checking during registration
- Add debounced username availability indicator on registration Step 1
- Add DeleteAccountModal with federation-aware remote account cleanup
- Add federation ops utility for remote instance management
- Update sanitizeUser to anonymize deleted user profiles
- Add instance store improvements and connected instances modal updates
This commit is contained in:
Jannis Braun
2026-03-11 16:29:25 +01:00
parent c8e2945c07
commit 8c8767ba2c
18 changed files with 1343 additions and 21 deletions
+38 -4
View File
@@ -1,15 +1,31 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuthStore } from '../../stores/authStore';
import { RateLimitError } from '../../api/client';
export function LoginPage() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [retryAfter, setRetryAfter] = useState(0);
const login = useAuthStore((s) => s.login);
const isLoading = useAuthStore((s) => s.isLoading);
const navigate = useNavigate();
useEffect(() => {
if (retryAfter <= 0) return;
const timer = setInterval(() => {
setRetryAfter((prev) => {
if (prev <= 1) {
clearInterval(timer);
return 0;
}
return prev - 1;
});
}, 1000);
return () => clearInterval(timer);
}, [retryAfter]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
@@ -27,10 +43,17 @@ export function LoginPage() {
await login(username.trim(), password);
navigate('/channels/@me');
} catch (err) {
setError(err instanceof Error ? err.message : 'Login failed');
if (err instanceof RateLimitError) {
setRetryAfter(err.retryAfter);
setError('');
} else {
setError(err instanceof Error ? err.message : 'Login failed');
}
}
};
const isDisabled = isLoading || retryAfter > 0;
return (
<div className="min-h-screen flex items-center justify-center bg-surface-base relative">
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(124,108,246,0.06)_0%,transparent_50%)]" />
@@ -41,6 +64,13 @@ export function LoginPage() {
</div>
<form onSubmit={handleSubmit}>
{retryAfter > 0 && (
<div className="mb-4 p-3 bg-accent-amber/10 border border-accent-amber/30 rounded text-sm">
<p className="font-medium text-accent-amber">Too many login attempts</p>
<p className="text-txt-secondary mt-0.5">Try again in {retryAfter}s</p>
</div>
)}
{error && (
<div className="mb-4 p-3 bg-accent-rose/10 border border-accent-rose/30 rounded text-txt-danger text-sm">
{error}
@@ -76,10 +106,14 @@ export function LoginPage() {
<button
type="submit"
disabled={isLoading}
disabled={isDisabled}
className="w-full py-2.5 bg-accent-primary hover:bg-accent-primary/80 text-white font-medium rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? 'Logging in...' : 'Log In'}
{retryAfter > 0
? `Try again in ${retryAfter}s`
: isLoading
? 'Logging in...'
: 'Log In'}
</button>
<p className="mt-3 text-sm text-txt-tertiary">
@@ -6,7 +6,9 @@ import { ImageCropModal } from '../ui/ImageCropModal';
import { AVATAR_GRADIENT_MAP } from '../../utils/gradients';
import { AVATAR_COLORS } from '@backspace/shared';
import type { AvatarColor } from '@backspace/shared';
import { api } from '../../api/client';
import { api, RateLimitError } from '../../api/client';
type UsernameStatus = 'idle' | 'checking' | 'available' | 'taken' | 'invalid';
export function RegisterPage() {
// Step state
@@ -18,6 +20,12 @@ export function RegisterPage() {
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
// Username availability check
const [usernameStatus, setUsernameStatus] = useState<UsernameStatus>('idle');
const [usernameStatusMessage, setUsernameStatusMessage] = useState('');
const usernameCheckTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const usernameCheckAbortRef = useRef<AbortController | null>(null);
// Step 2 fields
const [displayName, setDisplayName] = useState('');
const [avatarColor, setAvatarColor] = useState<AvatarColor>(
@@ -30,6 +38,7 @@ export function RegisterPage() {
const [error, setError] = useState('');
const [isRegistering, setIsRegistering] = useState(false);
const [retryAfter, setRetryAfter] = useState(0);
const register = useAuthStore((s) => s.register);
const updateProfile = useAuthStore((s) => s.updateProfile);
@@ -42,6 +51,82 @@ export function RegisterPage() {
};
}, [avatarPreview]);
// Debounced username availability check
useEffect(() => {
// Clear previous timer and abort
if (usernameCheckTimerRef.current) clearTimeout(usernameCheckTimerRef.current);
if (usernameCheckAbortRef.current) usernameCheckAbortRef.current.abort();
const trimmed = username.trim();
if (trimmed.length === 0) {
setUsernameStatus('idle');
setUsernameStatusMessage('');
return;
}
if (trimmed.length < 3 || trimmed.length > 32) {
setUsernameStatus(trimmed.length > 0 ? 'invalid' : 'idle');
setUsernameStatusMessage(trimmed.length > 0 ? 'Username must be between 3 and 32 characters' : '');
return;
}
if (!/^[a-zA-Z0-9_]+$/.test(trimmed)) {
setUsernameStatus('invalid');
setUsernameStatusMessage('Username can only contain letters, numbers, and underscores');
return;
}
setUsernameStatus('checking');
setUsernameStatusMessage('Checking availability...');
usernameCheckTimerRef.current = setTimeout(async () => {
const controller = new AbortController();
usernameCheckAbortRef.current = controller;
try {
const result = await api.auth.checkUsername(trimmed);
if (controller.signal.aborted) return;
if (result.reason) {
setUsernameStatus('invalid');
setUsernameStatusMessage(result.reason);
} else if (result.available) {
setUsernameStatus('available');
setUsernameStatusMessage('Username is available');
} else {
setUsernameStatus('taken');
setUsernameStatusMessage('Username is already taken');
}
} catch {
if (controller.signal.aborted) return;
// Network error or rate limit — fall back to idle silently
setUsernameStatus('idle');
setUsernameStatusMessage('');
}
}, 500);
return () => {
if (usernameCheckTimerRef.current) clearTimeout(usernameCheckTimerRef.current);
if (usernameCheckAbortRef.current) usernameCheckAbortRef.current.abort();
};
}, [username]);
// Countdown timer
useEffect(() => {
if (retryAfter <= 0) return;
const timer = setInterval(() => {
setRetryAfter((prev) => {
if (prev <= 1) {
clearInterval(timer);
return 0;
}
return prev - 1;
});
}, 1000);
return () => clearInterval(timer);
}, [retryAfter]);
// ── Step 1 validation ──
const handleContinue = (e: React.FormEvent) => {
e.preventDefault();
@@ -60,6 +145,9 @@ export function RegisterPage() {
setError('Username can only contain letters, numbers, and underscores');
return;
}
if (usernameStatus === 'taken' || usernameStatus === 'invalid') {
return;
}
if (!password) {
setError('Password is required');
return;
@@ -116,7 +204,12 @@ export function RegisterPage() {
navigate('/channels/@me');
} catch (err) {
setError(err instanceof Error ? err.message : 'Registration failed');
if (err instanceof RateLimitError) {
setRetryAfter(err.retryAfter);
setError('');
} else {
setError(err instanceof Error ? err.message : 'Registration failed');
}
setIsRegistering(false);
}
};
@@ -125,6 +218,8 @@ export function RegisterPage() {
const initial = effectiveDisplayName.charAt(0).toUpperCase();
const gradient = AVATAR_GRADIENT_MAP[avatarColor];
const isDisabled = isRegistering || retryAfter > 0;
return (
<div className="min-h-screen flex items-center justify-center bg-surface-base relative">
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(124,108,246,0.06)_0%,transparent_50%)]" />
@@ -160,6 +255,31 @@ export function RegisterPage() {
autoFocus
autoComplete="username"
/>
{usernameStatus !== 'idle' && (
<div className={`mt-1.5 flex items-center gap-1.5 text-xs ${
usernameStatus === 'available' ? 'text-status-online' :
usernameStatus === 'checking' ? 'text-txt-tertiary' :
'text-txt-danger'
}`}>
{usernameStatus === 'checking' && (
<svg className="w-3.5 h-3.5 animate-spin" viewBox="0 0 24 24" fill="none">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
)}
{usernameStatus === 'available' && (
<svg className="w-3.5 h-3.5" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
</svg>
)}
{(usernameStatus === 'taken' || usernameStatus === 'invalid') && (
<svg className="w-3.5 h-3.5" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
</svg>
)}
<span>{usernameStatusMessage}</span>
</div>
)}
</div>
<div className="mb-5">
@@ -190,7 +310,8 @@ export function RegisterPage() {
<button
type="submit"
className="w-full py-2.5 bg-accent-primary hover:bg-accent-primary/80 text-white font-medium rounded transition-colors"
disabled={usernameStatus === 'taken' || usernameStatus === 'invalid'}
className="w-full py-2.5 bg-accent-primary hover:bg-accent-primary/80 text-white font-medium rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
Continue
</button>
@@ -210,6 +331,13 @@ export function RegisterPage() {
<p className="text-txt-tertiary text-sm mt-1">Personalize your profile, or skip for now</p>
</div>
{retryAfter > 0 && (
<div className="mb-4 p-3 bg-accent-amber/10 border border-accent-amber/30 rounded text-sm">
<p className="font-medium text-accent-amber">Too many attempts</p>
<p className="text-txt-secondary mt-0.5">Try again in {retryAfter}s</p>
</div>
)}
{error && (
<div className="mb-4 p-3 bg-accent-rose/10 border border-accent-rose/30 rounded text-txt-danger text-sm">
{error}
@@ -297,16 +425,20 @@ export function RegisterPage() {
<button
type="button"
onClick={() => handleRegister(false)}
disabled={isRegistering}
disabled={isDisabled}
className="w-full py-2.5 bg-accent-primary hover:bg-accent-primary/80 text-white font-medium rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isRegistering ? 'Creating account...' : 'Get Started'}
{retryAfter > 0
? `Try again in ${retryAfter}s`
: isRegistering
? 'Creating account...'
: 'Get Started'}
</button>
<div className="flex items-center justify-between mt-3">
<button
type="button"
onClick={() => { setError(''); setDirection('back'); setStep(1); }}
onClick={() => { setError(''); setRetryAfter(0); setDirection('back'); setStep(1); }}
disabled={isRegistering}
className="text-sm text-txt-tertiary hover:text-txt-secondary transition-colors disabled:opacity-50"
>
@@ -315,7 +447,7 @@ export function RegisterPage() {
<button
type="button"
onClick={() => handleRegister(true)}
disabled={isRegistering}
disabled={isDisabled}
className="text-sm text-txt-tertiary hover:text-txt-secondary transition-colors disabled:opacity-50"
>
Skip for now
@@ -266,6 +266,7 @@ function InstanceRow({ inst }: { inst: import('../../stores/instanceStore').Conn
const removeInstance = useInstanceStore((s) => s.removeInstance);
const reconnectInstance = useInstanceStore((s) => s.reconnectInstance);
const reauthenticateInstance = useInstanceStore((s) => s.reauthenticateInstance);
const hasPendingSync = useInstanceStore((s) => s.hasPendingPasswordSync)(inst.origin);
const [showReauth, setShowReauth] = useState(false);
const [reauthPassword, setReauthPassword] = useState('');
@@ -307,6 +308,11 @@ function InstanceRow({ inst }: { inst: import('../../stores/instanceStore').Conn
{(inst.status === 'disconnected' || inst.status === 'error') && inst.error && (
<div className="text-xs text-accent-amber mt-0.5">{inst.error}</div>
)}
{hasPendingSync && inst.status === 'connected' && (
<div className="text-xs text-accent-amber mt-0.5" title="Password not synced — re-authenticate to sync">
Password not synced
</div>
)}
</div>
</div>
<div className="flex items-center gap-1 shrink-0 ml-2">
@@ -0,0 +1,398 @@
import { useState, useEffect } from 'react';
import { useAuthStore } from '../../stores/authStore';
import { useInstanceStore } from '../../stores/instanceStore';
import { useSpaceStore } from '../../stores/spaceStore';
import { api } from '../../api/client';
import { deleteAccountOnRemotes, type FederationOpResult } from '../../utils/federationOps';
interface DeleteAccountModalProps {
isOpen: boolean;
onClose: () => void;
}
type Step = 'warning' | 'confirm' | 'federation' | 'complete';
interface OwnedSpaceInfo {
id: string;
name: string;
members: { userId: string; username: string; displayName: string | null }[];
action: 'none' | 'transfer' | 'delete';
transferTo: string;
}
export function DeleteAccountModal({ isOpen, onClose }: DeleteAccountModalProps) {
const user = useAuthStore((s) => s.user);
const instances = useInstanceStore((s) => s.instances);
const spaces = useSpaceStore((s) => s.spaces);
const [step, setStep] = useState<Step>('warning');
const [ownedSpaces, setOwnedSpaces] = useState<OwnedSpaceInfo[]>([]);
const [confirmUsername, setConfirmUsername] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [federationResults, setFederationResults] = useState<FederationOpResult[]>([]);
const [deletionComplete, setDeletionComplete] = useState(false);
// Reset state when modal opens/closes
useEffect(() => {
if (isOpen) {
setStep('warning');
setConfirmUsername('');
setConfirmPassword('');
setError('');
setIsLoading(false);
setFederationResults([]);
setDeletionComplete(false);
// Build owned spaces list and fetch members for each
if (user) {
const owned = spaces.filter(s => s.ownerId === user.id);
if (owned.length > 0) {
Promise.all(
owned.map(async (s) => {
try {
const members = await api.spaces.members(s.id);
return {
id: s.id,
name: s.name,
members: members
.filter(m => m.userId !== user.id)
.map(m => ({
userId: m.userId,
username: m.user.username,
displayName: m.user.displayName,
})),
action: 'none' as const,
transferTo: '',
};
} catch {
return {
id: s.id,
name: s.name,
members: [] as OwnedSpaceInfo['members'],
action: 'none' as const,
transferTo: '',
};
}
})
).then(setOwnedSpaces);
}
}
}
}, [isOpen, user]);
// Auto-redirect after deletion — must be before early return to maintain hooks order
useEffect(() => {
if (deletionComplete && step === 'complete') {
const timer = setTimeout(() => {
localStorage.removeItem('backspace_token');
window.location.href = '/login';
}, 3000);
return () => clearTimeout(timer);
}
}, [deletionComplete, step]);
if (!isOpen || !user) return null;
const hasRemotes = instances.filter(i => i.status === 'connected').length > 0;
const allOwnedHandled = ownedSpaces.every(s => s.action !== 'none');
const handleSpaceAction = (spaceId: string, action: 'transfer' | 'delete') => {
setOwnedSpaces(prev => prev.map(s =>
s.id === spaceId ? { ...s, action, transferTo: action === 'transfer' ? s.transferTo : '' } : s
));
};
const handleTransferTo = (spaceId: string, userId: string) => {
setOwnedSpaces(prev => prev.map(s =>
s.id === spaceId ? { ...s, transferTo: userId } : s
));
};
const handleContinueFromWarning = async () => {
setError('');
setIsLoading(true);
try {
// Process owned spaces
for (const space of ownedSpaces) {
if (space.action === 'transfer' && space.transferTo) {
await api.spaces.transferOwnership(space.id, space.transferTo);
} else if (space.action === 'delete') {
await api.spaces.delete(space.id);
}
}
setStep('confirm');
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to process spaces');
} finally {
setIsLoading(false);
}
};
const handleConfirmDelete = async () => {
if (confirmUsername !== user.username) {
setError('Username does not match');
return;
}
setError('');
setIsLoading(true);
try {
if (hasRemotes) {
setStep('federation');
// Delete on remotes first
const results = await deleteAccountOnRemotes();
setFederationResults(results);
// Then delete home account
await api.users.deleteAccount({ password: confirmPassword, username: confirmUsername });
setDeletionComplete(true);
setStep('complete');
} else {
// No remotes — direct delete via API (don't clear auth state yet — let the modal show "complete")
await api.users.deleteAccount({ password: confirmPassword, username: confirmUsername });
setDeletionComplete(true);
setStep('complete');
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete account');
if (step === 'federation') {
// Stay on federation step so user can see results
} else {
setStep('confirm');
}
} finally {
setIsLoading(false);
}
};
const handleDeleteAnyway = async () => {
setError('');
setIsLoading(true);
try {
await api.users.deleteAccount({ password: confirmPassword, username: confirmUsername });
setDeletionComplete(true);
setStep('complete');
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete account');
} finally {
setIsLoading(false);
}
};
return (
<div className="fixed inset-0 z-[200] flex items-center justify-center animate-fade-in">
<div className="absolute inset-0 bg-surface-overlay" onClick={step !== 'complete' ? onClose : undefined} />
<div className="relative max-w-lg w-full mx-4 max-h-[calc(100vh-2rem)] flex flex-col bg-surface-elevated rounded-lg shadow-xl animate-slide-up overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between px-5 pt-5 flex-shrink-0">
<h2 className="text-lg font-bold text-txt-primary">Delete Account</h2>
{step !== 'complete' && (
<button onClick={onClose} className="text-txt-tertiary hover:text-txt-primary transition-colors p-1">
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
<div className="p-5 overflow-y-auto space-y-4">
{/* Step 1: Warning & Space Handling */}
{step === 'warning' && (
<>
<div className="bg-accent-rose/10 border border-accent-rose/20 rounded-lg p-3.5">
<p className="text-sm text-txt-primary font-medium mb-2">This will permanently delete your account.</p>
<ul className="text-xs text-txt-secondary space-y-1">
<li>- All space memberships will be removed</li>
<li>- All friend connections will be removed</li>
<li>- All DM memberships will be removed</li>
<li>- Your messages will remain but be attributed to "Deleted User"</li>
</ul>
</div>
{ownedSpaces.length > 0 && (
<div>
<p className="text-sm text-txt-primary font-medium mb-2">
You own {ownedSpaces.length} space{ownedSpaces.length > 1 ? 's' : ''}. Handle each before continuing:
</p>
<div className="space-y-3">
{ownedSpaces.map(space => (
<div key={space.id} className="rounded-lg bg-white/[0.03] border border-white/[0.04] p-3">
<div className="text-sm font-medium text-txt-primary mb-2">{space.name}</div>
<div className="flex gap-2 mb-2">
<button
onClick={() => handleSpaceAction(space.id, 'transfer')}
className={`px-2.5 py-1 text-xs rounded transition-colors ${
space.action === 'transfer'
? 'bg-accent-primary text-white'
: 'bg-white/[0.06] text-txt-secondary hover:text-txt-primary'
}`}
>
Transfer
</button>
<button
onClick={() => handleSpaceAction(space.id, 'delete')}
className={`px-2.5 py-1 text-xs rounded transition-colors ${
space.action === 'delete'
? 'bg-accent-rose text-white'
: 'bg-white/[0.06] text-txt-secondary hover:text-txt-primary'
}`}
>
Delete Space
</button>
</div>
{space.action === 'transfer' && (
<select
value={space.transferTo}
onChange={(e) => handleTransferTo(space.id, e.target.value)}
className="w-full px-2.5 py-1.5 bg-surface-input rounded text-xs text-txt-primary outline-none focus:ring-2 focus:ring-accent-primary"
>
<option value="">Select new owner...</option>
{space.members.map(m => (
<option key={m.userId} value={m.userId}>
{m.displayName || m.username}
</option>
))}
</select>
)}
</div>
))}
</div>
</div>
)}
{error && (
<div className="p-2 bg-accent-rose/10 border border-accent-rose/30 rounded text-txt-danger text-xs">{error}</div>
)}
<button
onClick={ownedSpaces.length > 0 ? handleContinueFromWarning : () => setStep('confirm')}
disabled={
isLoading ||
(ownedSpaces.length > 0 && (!allOwnedHandled || ownedSpaces.some(s => s.action === 'transfer' && !s.transferTo)))
}
className="w-full py-2 bg-accent-rose hover:bg-accent-rose/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? 'Processing...' : 'Continue'}
</button>
</>
)}
{/* Step 2: Confirmation */}
{step === 'confirm' && (
<>
<div className="bg-accent-rose/10 border border-accent-rose/20 rounded-lg p-3.5">
<p className="text-sm text-txt-danger font-medium">This action is permanent and cannot be undone.</p>
</div>
<div>
<label className="block text-xs text-txt-secondary mb-1.5">
Type your username <span className="font-mono text-txt-primary">{user.username}</span> to confirm
</label>
<input
type="text"
value={confirmUsername}
onChange={(e) => setConfirmUsername(e.target.value)}
className="w-full px-3 py-2 bg-surface-input rounded text-sm text-txt-primary outline-none focus:ring-2 focus:ring-accent-rose"
placeholder={user.username}
/>
</div>
<div>
<label className="block text-xs text-txt-secondary mb-1.5">Password</label>
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="w-full px-3 py-2 bg-surface-input rounded text-sm text-txt-primary outline-none focus:ring-2 focus:ring-accent-rose"
placeholder="Enter your password"
/>
</div>
{error && (
<div className="p-2 bg-accent-rose/10 border border-accent-rose/30 rounded text-txt-danger text-xs">{error}</div>
)}
<div className="flex gap-3">
<button
onClick={() => { setStep('warning'); setError(''); }}
className="flex-1 py-2 bg-white/[0.06] hover:bg-white/[0.1] text-txt-secondary text-sm font-medium rounded-lg transition-colors"
>
Back
</button>
<button
onClick={handleConfirmDelete}
disabled={isLoading || confirmUsername !== user.username || !confirmPassword}
className="flex-1 py-2 bg-accent-rose hover:bg-accent-rose/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? 'Deleting...' : 'Delete My Account'}
</button>
</div>
</>
)}
{/* Step 3: Federation Progress */}
{step === 'federation' && (
<>
<p className="text-sm text-txt-secondary">Removing your account from connected instances...</p>
<div className="space-y-2">
{instances.filter(i => i.status === 'connected').map(inst => {
const result = federationResults.find(r => r.origin === inst.origin);
return (
<div key={inst.origin} className="flex items-center justify-between px-3 py-2 rounded-lg bg-white/[0.03] border border-white/[0.04]">
<span className="text-sm text-txt-primary">{inst.label || new URL(inst.origin).host}</span>
{!result ? (
<svg className="animate-spin w-4 h-4 text-txt-tertiary" viewBox="0 0 24 24" fill="none">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : result.success ? (
<svg className="w-4 h-4 text-status-online" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
) : (
<div className="flex items-center gap-1.5">
<svg className="w-4 h-4 text-txt-danger" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
<span className="text-xs text-txt-danger">{result.error}</span>
</div>
)}
</div>
);
})}
</div>
{error && (
<div className="p-2 bg-accent-rose/10 border border-accent-rose/30 rounded text-txt-danger text-xs">{error}</div>
)}
{federationResults.length > 0 && !deletionComplete && (
<button
onClick={handleDeleteAnyway}
disabled={isLoading}
className="w-full py-2 bg-accent-rose hover:bg-accent-rose/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
>
{isLoading ? 'Deleting...' : 'Delete Account Now'}
</button>
)}
</>
)}
{/* Step 4: Complete */}
{step === 'complete' && (
<div className="text-center py-6">
<svg className="w-12 h-12 text-txt-tertiary mx-auto mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
<p className="text-lg font-medium text-txt-primary mb-1">Account deleted</p>
<p className="text-sm text-txt-tertiary">Redirecting to login...</p>
</div>
)}
</div>
</div>
</div>
);
}
@@ -1,11 +1,14 @@
import { useState, useEffect, useRef } from 'react';
import { useAuthStore } from '../../../stores/authStore';
import { useInstanceStore } from '../../../stores/instanceStore';
import { Avatar } from '../../ui/Avatar';
import { ImageCropModal } from '../../ui/ImageCropModal';
import { DeleteAccountModal } from '../DeleteAccountModal';
import { api } from '../../../api/client';
import { getAvatarGradient, adjustColor, mutedGradient, AVATAR_GRADIENT_MAP, BANNER_COLOR_PRESETS } from '../../../utils/gradients';
import { AVATAR_COLORS } from '@backspace/shared';
import type { User, UserStatus, AvatarColor } from '@backspace/shared';
import type { FederationOpResult } from '../../../utils/federationOps';
export function AccountPanel() {
@@ -57,6 +60,23 @@ export function AccountPanel() {
}
}, [user?.displayName, user?.customStatus, user?.status, user?.bio, user?.accentColor, user?.avatarColor, user?.avatar, user?.banner]);
// Password change state
const [currentPassword, setCurrentPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmNewPassword, setConfirmNewPassword] = useState('');
const [passwordError, setPasswordError] = useState('');
const [passwordSuccess, setPasswordSuccess] = useState('');
const [passwordLoading, setPasswordLoading] = useState(false);
const [passwordResults, setPasswordResults] = useState<FederationOpResult[] | null>(null);
const [showCurrentPassword, setShowCurrentPassword] = useState(false);
const [showNewPassword, setShowNewPassword] = useState(false);
// Delete account state
const [showDeleteModal, setShowDeleteModal] = useState(false);
const instances = useInstanceStore((s) => s.instances);
const changePassword = useAuthStore((s) => s.changePassword);
if (!user) return null;
const effectiveDisplayName = displayName.trim() || user.username;
@@ -189,6 +209,43 @@ export function AccountPanel() {
}
};
const handleChangePassword = async () => {
setPasswordError('');
setPasswordSuccess('');
setPasswordResults(null);
if (newPassword.length < 6) {
setPasswordError('New password must be at least 6 characters');
return;
}
if (newPassword !== confirmNewPassword) {
setPasswordError('Passwords do not match');
return;
}
setPasswordLoading(true);
try {
const results = await changePassword(currentPassword, newPassword);
setPasswordSuccess('Password changed successfully!');
setCurrentPassword('');
setNewPassword('');
setConfirmNewPassword('');
if (results.length > 0) {
setPasswordResults(results);
}
setTimeout(() => {
setPasswordSuccess('');
setPasswordResults(null);
}, 5000);
} catch (err) {
setPasswordError(err instanceof Error ? err.message : 'Failed to change password');
} finally {
setPasswordLoading(false);
}
};
const handleReset = () => {
setDisplayName(user.displayName ?? '');
setCustomStatus(user.customStatus ?? '');
@@ -524,6 +581,124 @@ export function AccountPanel() {
</div>
</div>
{/* ── Password ── */}
<div>
<div className="text-[11px] font-semibold text-txt-tertiary uppercase tracking-wider mb-1.5">Password</div>
<div className="rounded-lg bg-white/[0.03] border border-white/[0.04] p-3.5 space-y-3">
<div>
<label className="block text-xs text-txt-secondary mb-1.5">Current Password</label>
<div className="relative">
<input
type={showCurrentPassword ? 'text' : 'password'}
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
className="w-full px-3 py-2 pr-10 bg-surface-input rounded text-sm text-txt-primary outline-none focus:ring-2 focus:ring-accent-primary"
placeholder="Enter current password"
/>
<button
type="button"
onClick={() => setShowCurrentPassword(!showCurrentPassword)}
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-txt-tertiary hover:text-txt-secondary transition-colors"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
{showCurrentPassword ? (
<path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
) : (
<>
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</>
)}
</svg>
</button>
</div>
</div>
<div>
<label className="block text-xs text-txt-secondary mb-1.5">New Password</label>
<div className="relative">
<input
type={showNewPassword ? 'text' : 'password'}
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="w-full px-3 py-2 pr-10 bg-surface-input rounded text-sm text-txt-primary outline-none focus:ring-2 focus:ring-accent-primary"
placeholder="Minimum 6 characters"
/>
<button
type="button"
onClick={() => setShowNewPassword(!showNewPassword)}
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-txt-tertiary hover:text-txt-secondary transition-colors"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
{showNewPassword ? (
<path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
) : (
<>
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</>
)}
</svg>
</button>
</div>
</div>
<div>
<label className="block text-xs text-txt-secondary mb-1.5">Confirm New Password</label>
<input
type="password"
value={confirmNewPassword}
onChange={(e) => setConfirmNewPassword(e.target.value)}
className="w-full px-3 py-2 bg-surface-input rounded text-sm text-txt-primary outline-none focus:ring-2 focus:ring-accent-primary"
placeholder="Confirm new password"
/>
</div>
{passwordError && (
<div className="p-2 bg-accent-rose/10 border border-accent-rose/30 rounded text-txt-danger text-xs">{passwordError}</div>
)}
{passwordSuccess && (
<div className="p-2 bg-status-online/10 border border-status-online/30 rounded text-status-online text-xs">{passwordSuccess}</div>
)}
{passwordResults && passwordResults.length > 0 && (
<div className="space-y-1">
{passwordResults.map(r => (
<div key={r.origin} className="flex items-center justify-between text-xs px-2 py-1 rounded bg-white/[0.02]">
<span className="text-txt-secondary">{r.origin}</span>
{r.success ? (
<span className="text-status-online">Synced</span>
) : (
<span className="text-txt-danger" title={r.error}>Failed will sync on reconnect</span>
)}
</div>
))}
</div>
)}
<button
onClick={handleChangePassword}
disabled={passwordLoading || !currentPassword || !newPassword || !confirmNewPassword}
className="px-4 py-2 bg-accent-primary hover:bg-accent-primary/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{passwordLoading ? 'Changing...' : 'Change Password'}
</button>
</div>
</div>
{/* ── Danger Zone ── */}
<div>
<div className="text-[11px] font-semibold text-txt-tertiary uppercase tracking-wider mb-1.5">Danger Zone</div>
<div className="rounded-lg bg-accent-rose/5 border border-accent-rose/20 p-3.5">
<p className="text-sm text-txt-secondary mb-3">
Once you delete your account, there is no going back. Your messages will remain but be attributed to "Deleted User".
</p>
<button
onClick={() => setShowDeleteModal(true)}
className="px-4 py-2 bg-accent-rose hover:bg-accent-rose/80 text-white text-sm font-medium rounded-lg transition-colors"
>
Delete Account
</button>
</div>
</div>
{error && (
<div className="p-2 bg-accent-rose/10 border border-accent-rose/30 rounded text-txt-danger text-sm">{error}</div>
)}
@@ -572,6 +747,11 @@ export function AccountPanel() {
cropShape="rect"
aspectRatio={3}
/>
<DeleteAccountModal
isOpen={showDeleteModal}
onClose={() => setShowDeleteModal(false)}
/>
</div>
);
}