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
+24
View File
@@ -99,6 +99,12 @@ export function runMigrations(db: Database.Database): void {
columns: [
{ name: 'avatar_color', type: 'TEXT' },
]
},
{
name: 'users',
columns: [
{ name: 'is_deleted', type: 'INTEGER DEFAULT 0' },
]
}
];
@@ -192,6 +198,9 @@ export function runMigrations(db: Database.Database): void {
// ─── Clean up corrupted read_states (temp_ IDs leaked from optimistic messages) ─
migrateCorruptedReadStates(db);
// ─── Free usernames from already-tombstoned users ───────────────────────────
migrateDeletedUsernames(db);
console.log('Migrations complete.');
}
@@ -418,6 +427,21 @@ function migrateCorruptedReadStates(db: Database.Database): void {
}
}
/** Rename already-tombstoned users so their original username can be reused */
function migrateDeletedUsernames(db: Database.Database): void {
const rows = db.prepare(
"SELECT id, username FROM users WHERE is_deleted = 1 AND username NOT LIKE '!deleted:%'"
).all() as { id: string; username: string }[];
if (rows.length === 0) return;
const update = db.prepare('UPDATE users SET username = ? WHERE id = ?');
for (const row of rows) {
update.run(`!deleted:${row.id}`, row.id);
console.log(`Migrating: Freed username "${row.username}" from deleted user ${row.id}`);
}
}
/**
* Rename non-namespaced replicated users: e.g. "test" → "test@nova.ddns.net"
* Frees plain usernames for native user creation and makes all federated users
+1
View File
@@ -16,6 +16,7 @@ export const users = sqliteTable('users', {
accentColor: text('accent_color'),
avatarColor: text('avatar_color'),
bio: text('bio'),
isDeleted: integer('is_deleted').default(0),
createdAt: integer('created_at').notNull(),
});
+6
View File
@@ -43,6 +43,12 @@ async function main(): Promise<void> {
max: 200,
timeWindow: '1 minute',
keyGenerator: (request) => (request as any).userId || request.ip,
errorResponseBuilder: (_request, context) => ({
statusCode: 429,
error: 'Too Many Requests',
message: 'Rate limit exceeded',
retryAfter: Math.ceil(context.ttl / 1000),
}),
});
await app.register(websocket);
+45 -3
View File
@@ -13,7 +13,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
config: {
rateLimit: {
max: 10,
timeWindow: '15 minutes',
timeWindow: '2 minutes',
keyGenerator: (request: any) => request.ip,
},
},
@@ -128,11 +128,49 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
return reply.code(201).send(response);
});
app.get<{ Querystring: { username?: string } }>('/api/auth/check-username', {
config: {
rateLimit: {
max: 30,
timeWindow: '1 minute',
keyGenerator: (request: any) => request.ip,
},
},
}, async (request, reply) => {
const raw = request.query.username;
if (!raw || typeof raw !== 'string') {
return reply.code(400).send({ available: false, reason: 'Username is required' });
}
const trimmed = raw.trim();
// Format validation (same rules as registration)
if (trimmed.length < 3 || trimmed.length > 32) {
return reply.code(200).send({ available: false, reason: 'Username must be between 3 and 32 characters' });
}
if (!/^[a-zA-Z0-9_]+$/.test(trimmed)) {
return reply.code(200).send({ available: false, reason: 'Username can only contain letters, numbers, and underscores' });
}
// Check registration is open
const db = getDb();
const instanceRow = db.select().from(schema.instanceSettings).where(eq(schema.instanceSettings.id, 1)).get();
const registrationOpen = instanceRow?.registrationOpen !== null && instanceRow?.registrationOpen !== undefined
? instanceRow.registrationOpen === 1
: config.registrationOpen;
if (!registrationOpen) {
return reply.code(403).send({ available: false, reason: 'Registration is currently closed' });
}
const existing = db.select().from(schema.users).where(eq(schema.users.username, trimmed)).get();
return reply.code(200).send({ available: !existing });
});
app.post<{ Body: LoginRequest }>('/api/auth/login', {
config: {
rateLimit: {
max: 10,
timeWindow: '15 minutes',
max: 15,
timeWindow: '2 minutes',
keyGenerator: (request: any) => request.ip,
},
},
@@ -154,6 +192,10 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
return reply.code(401).send({ error: 'Invalid username or password', statusCode: 401 });
}
if (user.isDeleted) {
return reply.code(401).send({ error: 'This account has been deleted', statusCode: 401 });
}
const validPassword = await verifyPassword(password, user.passwordHash);
if (!validPassword) {
return reply.code(401).send({ error: 'Invalid username or password', statusCode: 401 });
+48
View File
@@ -953,6 +953,54 @@ export async function spaceRoutes(app: FastifyInstance): Promise<void> {
return reply.code(200).send({ success: true });
});
// PATCH /api/spaces/:id/transfer-ownership — Transfer space ownership
app.patch<{ Params: { id: string }; Body: { newOwnerId: string } }>('/api/spaces/:id/transfer-ownership', {
preHandler: authenticate,
}, async (request, reply) => {
const { id } = request.params;
const { newOwnerId } = request.body;
const db = getDb();
if (!newOwnerId || typeof newOwnerId !== 'string') {
return reply.code(400).send({ error: 'newOwnerId is required', statusCode: 400 });
}
const server = db.select().from(schema.spaces).where(eq(schema.spaces.id, id)).get();
if (!server) {
return reply.code(404).send({ error: 'Space not found', statusCode: 404 });
}
if (!isSpaceOwner(id, request.userId)) {
return reply.code(403).send({ error: 'Only the space owner can transfer ownership', statusCode: 403 });
}
if (newOwnerId === request.userId) {
return reply.code(400).send({ error: 'You are already the owner', statusCode: 400 });
}
// Verify new owner is a member
if (!isMember(id, newOwnerId)) {
return reply.code(400).send({ error: 'New owner must be a member of the space', statusCode: 400 });
}
db.update(schema.spaces).set({ ownerId: newOwnerId }).where(eq(schema.spaces.id, id)).run();
const updated = db.select().from(schema.spaces).where(eq(schema.spaces.id, id)).get();
if (!updated) {
return reply.code(500).send({ error: 'Failed to transfer ownership', statusCode: 500 });
}
const spaceData = rowToSpace(updated);
// Broadcast space_updated so all clients see the new owner
connectionManager.sendToSpace(id, {
type: 'space_updated',
space: spaceData,
});
return reply.code(200).send(spaceData);
});
// ─── Ban Management ───────────────────────────────────────────────────────
// GET /api/spaces/:id/bans - List bans
+139 -5
View File
@@ -1,9 +1,10 @@
import type { FastifyInstance } from 'fastify';
import { eq, or, inArray } from 'drizzle-orm';
import { eq, or, and, inArray } from 'drizzle-orm';
import crypto from 'crypto';
import { getDb, schema } from '../db/index.js';
import { authenticate, verifyPassword } from '../utils/auth.js';
import { authenticate, verifyPassword, hashPassword, signJwt } from '../utils/auth.js';
import { connectionManager } from '../ws/handler.js';
import type { UpdateUserRequest, VerifyPasswordRequest, VerifyPasswordResponse, ReplicatedInstance } from '@backspace/shared';
import type { UpdateUserRequest, VerifyPasswordRequest, VerifyPasswordResponse, ChangePasswordRequest, ChangePasswordResponse, DeleteAccountRequest, ReplicatedInstance } from '@backspace/shared';
import { AVATAR_COLORS } from '@backspace/shared';
import { sanitizeUser } from '../utils/sanitize.js';
@@ -12,8 +13,8 @@ export async function userRoutes(app: FastifyInstance): Promise<void> {
const db = getDb();
const user = db.select().from(schema.users).where(eq(schema.users.id, request.userId)).get();
if (!user) {
return reply.code(404).send({ error: 'User not found', statusCode: 404 });
if (!user || user.isDeleted) {
return reply.code(401).send({ error: 'This account has been deleted', statusCode: 401 });
}
return reply.code(200).send(sanitizeUser(user));
@@ -38,6 +39,139 @@ export async function userRoutes(app: FastifyInstance): Promise<void> {
return reply.code(200).send(response);
});
// POST /api/users/@me/change-password — change account password
app.post<{ Body: ChangePasswordRequest }>('/api/users/@me/change-password', {
preHandler: authenticate,
config: { rateLimit: { max: 5, timeWindow: '15 minutes' } },
}, async (request, reply) => {
const { currentPassword, newPassword } = request.body;
if (!newPassword || typeof newPassword !== 'string' || newPassword.length < 6) {
return reply.code(400).send({ error: 'New password must be at least 6 characters', statusCode: 400 });
}
const db = getDb();
const user = db.select().from(schema.users).where(eq(schema.users.id, request.userId)).get();
if (!user) {
return reply.code(404).send({ error: 'User not found', statusCode: 404 });
}
// Native users (no homeInstance) must provide current password
if (!user.homeInstance) {
if (!currentPassword || typeof currentPassword !== 'string') {
return reply.code(400).send({ error: 'Current password is required', statusCode: 400 });
}
const valid = await verifyPassword(currentPassword, user.passwordHash);
if (!valid) {
return reply.code(403).send({ error: 'Incorrect password', statusCode: 403 });
}
}
// Federated users: JWT auth is sufficient — skip old password verification
const newHash = await hashPassword(newPassword);
db.update(schema.users).set({ passwordHash: newHash }).where(eq(schema.users.id, request.userId)).run();
// Issue fresh JWT
const token = signJwt({ userId: user.id, username: user.username });
const response: ChangePasswordResponse = { token };
return reply.code(200).send(response);
});
// DELETE /api/users/@me — delete (tombstone) account
app.delete<{ Body: DeleteAccountRequest }>('/api/users/@me', {
preHandler: authenticate,
config: { rateLimit: { max: 3, timeWindow: '15 minutes' } },
}, async (request, reply) => {
const { password, username } = request.body;
if (!username || typeof username !== 'string') {
return reply.code(400).send({ error: 'Username confirmation is required', statusCode: 400 });
}
const db = getDb();
const user = db.select().from(schema.users).where(eq(schema.users.id, request.userId)).get();
if (!user) {
return reply.code(404).send({ error: 'User not found', statusCode: 404 });
}
// Verify username matches (confirmation safeguard)
if (user.username !== username) {
return reply.code(400).send({ error: 'Username does not match', statusCode: 400 });
}
// Native users must verify password; federated users rely on JWT auth
if (!user.homeInstance) {
if (!password || typeof password !== 'string') {
return reply.code(400).send({ error: 'Password is required', statusCode: 400 });
}
const valid = await verifyPassword(password, user.passwordHash);
if (!valid) {
return reply.code(403).send({ error: 'Incorrect password', statusCode: 403 });
}
}
// Check if user owns any spaces
const ownedSpaces = db.select({ id: schema.spaces.id, name: schema.spaces.name })
.from(schema.spaces)
.where(eq(schema.spaces.ownerId, request.userId))
.all();
if (ownedSpaces.length > 0) {
return reply.code(400).send({
error: 'You must transfer ownership or delete all spaces you own before deleting your account',
statusCode: 400,
ownedSpaces,
});
}
// Run all cleanup in a single transaction
db.transaction((tx) => {
const uid = request.userId;
// Remove from spaces, roles, friends, DMs, read states, reactions, folders, bans, join requests, voice restrictions, channel overrides
tx.delete(schema.spaceMembers).where(eq(schema.spaceMembers.userId, uid)).run();
tx.delete(schema.memberRoles).where(eq(schema.memberRoles.userId, uid)).run();
tx.delete(schema.friends).where(or(eq(schema.friends.userId, uid), eq(schema.friends.friendId, uid))).run();
tx.delete(schema.friendRequests).where(or(eq(schema.friendRequests.fromId, uid), eq(schema.friendRequests.toId, uid))).run();
tx.delete(schema.dmMembers).where(eq(schema.dmMembers.userId, uid)).run();
tx.delete(schema.readStates).where(eq(schema.readStates.userId, uid)).run();
tx.delete(schema.reactions).where(eq(schema.reactions.userId, uid)).run();
tx.delete(schema.dmReactions).where(eq(schema.dmReactions.userId, uid)).run();
tx.delete(schema.spaceFolders).where(eq(schema.spaceFolders.userId, uid)).run();
// Conditional deletes for tables that may reference userId
try { tx.delete(schema.bans).where(eq(schema.bans.userId, uid)).run(); } catch { /* table may not exist */ }
try { tx.delete(schema.joinRequests).where(eq(schema.joinRequests.userId, uid)).run(); } catch { /* table may not exist */ }
try { tx.delete(schema.voiceRestrictions).where(eq(schema.voiceRestrictions.userId, uid)).run(); } catch { /* table may not exist */ }
// Remove member-type channel overrides for this user
tx.delete(schema.channelOverrides).where(
and(eq(schema.channelOverrides.targetType, 'member'), eq(schema.channelOverrides.targetId, uid))
).run();
// Tombstone user row — rename username to free it for reuse
tx.update(schema.users).set({
username: `!deleted:${uid}`,
passwordHash: crypto.randomBytes(32).toString('hex'), // unusable random string
displayName: null,
avatar: null,
banner: null,
bio: null,
customStatus: null,
accentColor: null,
avatarColor: null,
replicatedInstances: '[]',
isDeleted: 1,
status: 'offline',
isAdmin: 0,
}).where(eq(schema.users.id, uid)).run();
});
// Force-close all WebSocket connections
connectionManager.forceDisconnectUser(request.userId);
return reply.code(200).send({ success: true });
});
app.patch<{ Body: UpdateUserRequest }>('/api/users/@me', { preHandler: authenticate }, async (request, reply) => {
const { displayName, avatar, banner, accentColor, avatarColor, bio, customStatus, status, replicatedInstances, homeUserId } = request.body;
const db = getDb();
+22
View File
@@ -2,6 +2,28 @@ import type { User, ReplicatedInstance } from '@backspace/shared';
import { schema } from '../db/index.js';
export function sanitizeUser(row: typeof schema.users.$inferSelect): User {
// Tombstoned (deleted) users — return anonymized profile
if (row.isDeleted === 1) {
return {
id: row.id,
username: 'Deleted User',
displayName: null,
avatar: null,
banner: null,
accentColor: null,
avatarColor: null,
bio: null,
status: 'offline',
customStatus: null,
isAdmin: false,
isDeleted: true,
createdAt: row.createdAt,
homeInstance: null,
homeUserId: null,
replicatedInstances: [],
};
}
let replicatedInstances: ReplicatedInstance[] = [];
if (row.replicatedInstances) {
try {
+69 -1
View File
@@ -532,6 +532,65 @@ class ConnectionManager {
}
}
/** Force-disconnect all WebSocket connections for a user (e.g. account deletion). */
forceDisconnectUser(userId: string): void {
// Cancel any pending offline timeout
const timeout = this.pendingOfflineTimeouts.get(userId);
if (timeout) {
clearTimeout(timeout);
this.pendingOfflineTimeouts.delete(userId);
}
// Leave voice room if in one
const left = this.leaveCurrentRoom(userId);
this.clearVoiceUserStatus(userId);
if (left) {
if (left.room.roomType === 'space') {
const meta = left.room.metadata as SpaceRoomMeta;
this.sendToSpace(meta.spaceId, {
type: 'voice_state_update',
channelId: left.roomId,
userId,
action: 'leave',
});
} else {
this.sendToDmMembers(left.roomId, {
type: 'voice_state_update',
channelId: left.roomId,
userId,
action: 'leave',
});
}
}
// Destroy any ringing DM rooms where this user is the caller
for (const [roomId, room] of this.voiceRooms) {
if (room.roomType === 'dm') {
const meta = room.metadata as DmRoomMeta;
if (meta.state === 'ringing' && meta.callerId === userId) {
this.destroyRoom(roomId);
this.sendToDmMembers(roomId, {
type: 'dm_call_ended',
dmChannelId: roomId,
});
}
}
}
// Close all WebSocket connections
const connections = this.connections.get(userId);
if (connections) {
for (const ws of connections) {
this.wsToUser.delete(ws);
try { ws.close(4001, 'Account deleted'); } catch { /* ignore */ }
}
this.connections.delete(userId);
}
// Clean up user spaces
this.userSpaces.delete(userId);
}
getAllOnlineUserIds(): string[] {
return Array.from(this.connections.keys());
}
@@ -991,11 +1050,20 @@ export async function registerWebSocket(app: FastifyInstance): Promise<void> {
const payload = verifyJwt(parsed.token);
userId = payload.userId;
username = payload.username;
// Reject deleted users
const db = getDb();
const userRow = db.select().from(schema.users).where(eq(schema.users.id, userId)).get();
if (!userRow || userRow.isDeleted) {
ws.send(JSON.stringify({ type: 'error', message: 'This account has been deleted' }));
ws.close();
return;
}
authenticated = true;
clearTimeout(authTimeout);
// Update user status to online
const db = getDb();
db.update(schema.users).set({ status: 'online' }).where(eq(schema.users.id, userId)).run();
// Add connection