Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

fix(api): clear personal data from deleted accounts (#3623)

Hampusb01ce726c9f1
diff --git a/fluxer_admin/src/templates/pages/user_detail_tabs/moderation.rs b/fluxer_admin/src/templates/pages/user_detail_tabs/moderation.rs
index 35727defe..51aa9bf2b 100644
--- a/fluxer_admin/src/templates/pages/user_detail_tabs/moderation.rs
+++ b/fluxer_admin/src/templates/pages/user_detail_tabs/moderation.rs
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-use crate::admin_flags::{ENFORCEMENT_LIMITS, deletion_reason_label};
+use crate::admin_flags::{ENFORCEMENT_LIMITS, deletion_reason_label, user_flag_bits};
use crate::utils::plural::{count_noun, noun_for};
use crate::{
acl,
@@ -119,7 +119,7 @@ pub fn moderation_tab(
@if acl::has_permission(admin_acls, acl::USER_TEMP_BAN) {
(suspend_card(base, user, csrf_token, context))
}
- @if acl::has_permission(admin_acls, acl::USER_DELETE) {
+ @if acl::has_permission(admin_acls, acl::USER_DELETE) && !deletion_complete(user) {
(close_card(base, config.self_hosted, user, csrf_token, context))
}
@if can_limit {
@@ -147,6 +147,10 @@ pub fn moderation_tab(
}
}
+fn deletion_complete(user: &AdminUser) -> bool {
+ user.flags & user_flag_bits::DELETED != 0 && user.pending_deletion_at.is_none()
+}
+
fn current_restriction_card(
base: &str,
user: &AdminUser,
@@ -164,6 +168,8 @@ fn current_restriction_card(
(legacy_suspension_restriction(base, user, csrf_token, admin_acls, until, context.legacy_suspension.as_ref()))
} @else if let Some(pending) = &user.pending_deletion_at {
(legacy_deletion_restriction(base, user, csrf_token, admin_acls, pending, context.deletion_scheduler))
+ } @else if deletion_complete(user) {
+ p class="text-sm text-neutral-900" { "This account was deleted." }
} @else {
p class="text-sm text-neutral-500" { "No current restriction." }
}
diff --git a/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts b/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts
index b362ec00f..1fbf92648 100644
--- a/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts
@@ -38,7 +38,7 @@ import {
propagateUserUpdate,
} from '@app/api/user/services/PartialUserChangePropagation';
import {reschedulePendingDeletion} from '@app/api/user/services/PendingDeletionCoordinator';
-import {isHeldByDecision} from '@app/api/user/UserHelpers';
+import {isDeletionComplete, isHeldByDecision} from '@app/api/user/UserHelpers';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {DeletionReasons} from '@fluxer/constants/src/Core';
import {
@@ -154,6 +154,12 @@ export class AdminUserDeletionService {
): Promise<{user: User; skippedNetworks: Array<SkippedNetwork>}> {
const {basis} = request;
const user = await this.deps.apiContext.services.users.findUniqueAssert(userId);
+ if (isDeletionComplete(user)) {
+ throw new ConflictError({
+ code: APIErrorCodes.CONFLICT,
+ message: 'This account has already been deleted',
+ });
+ }
if (
user.pendingDeletionAt &&
(!request.replace_pending_deletion_at ||
diff --git a/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts b/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts
index a98e855b2..9030af6a7 100644
--- a/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts
@@ -1,11 +1,25 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createTestAccount, listTestEmails, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {
+ createTestAccount,
+ createUniqueEmail,
+ listTestEmails,
+ setUserACLs,
+ type TestAccount,
+} from '@app/api/auth/tests/AuthTestUtils';
+import {createUserID} from '@app/api/BrandedTypes';
import {getConfig} from '@app/api/Config';
+import {createApiContext} from '@app/api/CreateApiContext';
+import {createChannel, createGuild} from '@app/api/guild/tests/GuildTestUtils';
+import {sendMessage} from '@app/api/message/tests/MessageTestUtils';
+import {getUserActivityBuffer} from '@app/api/middleware/ServiceSingletons';
+import {getUserSearchService} from '@app/api/SearchFactory';
+import {convertToSearchableUser} from '@app/api/search/user/UserSearchSerializer';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {triggerDeletionWorker, waitForDeletionCompletion} from '@app/api/user/tests/UserTestUtils';
+import {backfillDeletedUsers} from '@app/api/worker/tasks/BackfillDeletedUsers';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
@@ -16,7 +30,7 @@ describe('immediate account deletion from the admin panel', () => {
const selfHosted = getConfig().instance.selfHosted;
beforeAll(async () => {
- harness = await createApiTestHarness();
+ harness = await createApiTestHarness({search: 'enabled'});
});
beforeEach(async () => {
@@ -24,6 +38,8 @@ describe('immediate account deletion from the admin panel', () => {
admin = await setUserACLs(harness, await createTestAccount(harness), [
AdminACLs.AUTHENTICATE,
AdminACLs.USER_DELETE,
+ AdminACLs.USER_LOOKUP,
+ AdminACLs.USER_VIEW_IP,
AdminACLs.AUDIT_LOG_VIEW,
]);
});
@@ -55,6 +71,86 @@ describe('immediate account deletion from the admin panel', () => {
expect(emails.filter((email) => email.type === 'account_deletion_requested')).toEqual([]);
});
+ async function listedUsers() {
+ const result = await createBuilder<{users: Array<{id: string; username: string}>}>(harness, admin.token)
+ .get('/admin/users?limit=100')
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ return result.users;
+ }
+
+ async function deleteWithLeftovers(target: TestAccount) {
+ getConfig().instance.selfHosted = true;
+ const guild = await createGuild(harness, target.token, 'Deleted author');
+ const channel = await createChannel(harness, target.token, guild.id, 'general');
+ await sendMessage(harness, target.token, channel.id, 'kept after deletion');
+ await createBuilder(harness, target.token)
+ .get('/users/@me')
+ .header('x-forwarded-for', '203.0.113.44')
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ await getUserActivityBuffer().drainAndFlush();
+ await deleteNow(target).expect(HTTP_STATUS.OK).execute();
+ await triggerDeletionWorker(harness);
+ await waitForDeletionCompletion(harness, target.userId, 20000);
+ }
+
+ it('leaves no deleted account in the user list and no personal data on its row', async () => {
+ const target = await createTestAccount(harness);
+ await deleteWithLeftovers(target);
+ const listed = await listedUsers();
+ expect(listed.map((user) => user.id)).toContain(admin.userId);
+ expect(listed.filter((user) => user.id === target.userId || user.username === 'DeletedUser')).toEqual([]);
+ const row = await createApiContext().services.users.findUniqueAssert(createUserID(BigInt(target.userId)));
+ expect(row.toRow()).toMatchObject({
+ email: null,
+ last_active_ip: null,
+ last_active_at: null,
+ locale: null,
+ terms_agreed_at: null,
+ privacy_agreed_at: null,
+ });
+ await deleteNow(target).expect(HTTP_STATUS.CONFLICT, APIErrorCodes.CONFLICT).execute();
+ });
+
+ it('clears what older deletions left behind', async () => {
+ const target = await createTestAccount(harness);
+ await deleteWithLeftovers(target);
+ const users = createApiContext().services.users;
+ const targetId = createUserID(BigInt(target.userId));
+ const deleted = await users.findUniqueAssert(targetId);
+ const leftoverEmail = createUniqueEmail('leftover');
+ const leftover = await users.patchUpsert(
+ targetId,
+ {
+ email: leftoverEmail,
+ last_active_ip: '203.0.113.45',
+ last_active_at: new Date(),
+ locale: 'sv-SE',
+ terms_agreed_at: new Date(),
+ },
+ deleted.toRow(),
+ );
+ await getUserSearchService()!.indexDocument(convertToSearchableUser(leftover));
+ expect((await listedUsers()).map((user) => user.id)).toContain(target.userId);
+ expect(await backfillDeletedUsers(users, 2)).toMatchObject({scrubbed: 1});
+ expect((await users.findUniqueAssert(targetId)).toRow()).toMatchObject({
+ email: null,
+ last_active_ip: null,
+ last_active_at: null,
+ locale: null,
+ terms_agreed_at: null,
+ });
+ expect((await listedUsers()).map((user) => user.id)).not.toContain(target.userId);
+ const byIp = await createBuilder<{users: Array<{id: string}>}>(harness, admin.token)
+ .get(`/admin/users?last_active_ip=${encodeURIComponent('203.0.113.45')}`)
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ expect(byIp.users).toEqual([]);
+ expect(await backfillDeletedUsers(users)).toMatchObject({scrubbed: 0});
+ await createTestAccount(harness, {email: leftoverEmail});
+ });
+
it('keeps the waiting period on the hosted instance', async () => {
getConfig().instance.selfHosted = false;
const target = await createTestAccount(harness);
diff --git a/fluxer_api/src/api/search/SearchServices.ts b/fluxer_api/src/api/search/SearchServices.ts
index afd5594c4..4c95f3916 100644
--- a/fluxer_api/src/api/search/SearchServices.ts
+++ b/fluxer_api/src/api/search/SearchServices.ts
@@ -25,6 +25,7 @@ import {
import {convertToSearchableReport} from '@app/api/search/report/ReportSearchSerializer';
import {SearchAdapterServiceBase} from '@app/api/search/SearchAdapterServiceBase';
import {convertToSearchableUser} from '@app/api/search/user/UserSearchSerializer';
+import {isDeletionComplete} from '@app/api/user/UserHelpers';
import type {
ISearchAdapter,
SearchOptions as SchemaSearchOptions,
@@ -178,15 +179,24 @@ export class UserSearchService
implements IUserSearchService
{
async indexUser(user: User): Promise<void> {
+ if (isDeletionComplete(user)) {
+ await this.deleteDocument(user.id.toString());
+ return;
+ }
await this.indexDocument(convertToSearchableUser(user));
}
async indexUsers(users: Array<User>): Promise<void> {
- if (users.length === 0) return;
- await this.indexDocuments(users.map(convertToSearchableUser));
+ const listed = users.filter((user) => !isDeletionComplete(user));
+ if (listed.length === 0) return;
+ await this.indexDocuments(listed.map(convertToSearchableUser));
}
async updateUser(user: User): Promise<void> {
+ if (isDeletionComplete(user)) {
+ await this.deleteDocument(user.id.toString());
+ return;
+ }
await this.updateDocument(convertToSearchableUser(user));
}
diff --git a/fluxer_api/src/api/user/UserHelpers.ts b/fluxer_api/src/api/user/UserHelpers.ts
index c211c8953..98508054f 100644
--- a/fluxer_api/src/api/user/UserHelpers.ts
+++ b/fluxer_api/src/api/user/UserHelpers.ts
@@ -6,9 +6,13 @@ import {getCachedInstancePremiumMode} from '@app/api/limits/InstancePremiumModeC
import type {User} from '@app/api/models/User';
import {isEnforcementReasonCode} from '@fluxer/constants/src/EnforcementReasons';
import {
+ DELETED_USER_DISCRIMINATOR,
+ DELETED_USER_GLOBAL_NAME,
+ DELETED_USER_USERNAME,
PREMIUM_GRACE_PERIOD_DAYS,
PREMIUM_PAYMENT_RECOVERY_GRACE_DAYS,
PremiumFlags,
+ ProfileFieldPrivacyFlags,
UserFlags,
type UserPremiumType,
UserPremiumTypes,
@@ -32,6 +36,74 @@ export function isAccountClosed(user: Pick<User, 'flags' | 'deletionStartedAt'>)
return (user.flags & UserFlags.DELETED) !== 0n || user.deletionStartedAt != null;
}
+export function isDeletionComplete(user: Pick<User, 'flags' | 'pendingDeletionAt'>): boolean {
+ return (user.flags & UserFlags.DELETED) !== 0n && user.pendingDeletionAt === null;
+}
+
+const FIELDS_CLEARED_ON_DELETION = [
+ 'email',
+ 'email_bounced',
+ 'password_hash',
+ 'password_last_changed_at',
+ 'totp_secret',
+ 'authenticator_types',
+ 'avatar_hash',
+ 'avatar_color',
+ 'banner_hash',
+ 'banner_color',
+ 'bio',
+ 'pronouns',
+ 'accent_color',
+ 'timezone',
+ 'date_of_birth',
+ 'locale',
+ 'premium_flags',
+ 'premium_type',
+ 'premium_since',
+ 'premium_until',
+ 'premium_gift_extension_ends_at',
+ 'premium_will_cancel',
+ 'premium_billing_cycle',
+ 'premium_lifetime_sequence',
+ 'premium_grace_ends_at',
+ 'stripe_subscription_id',
+ 'stripe_customer_id',
+ 'has_ever_purchased',
+ 'terms_agreed_at',
+ 'privacy_agreed_at',
+ 'last_active_at',
+ 'last_active_ip',
+ 'acls',
+ 'traits',
+ 'first_refund_at',
+ 'gift_inventory_server_seq',
+ 'gift_inventory_client_seq',
+ 'premium_onboarding_dismissed_at',
+ 'mention_flags',
+ 'last_voice_activity_sharing_change_at',
+] as const satisfies ReadonlyArray<keyof UserRow>;
+
+export function deletedUserIdentity() {
+ return {
+ username: DELETED_USER_USERNAME,
+ discriminator: DELETED_USER_DISCRIMINATOR,
+ global_name: DELETED_USER_GLOBAL_NAME,
+ email_verified: false,
+ timezone_privacy_flags: ProfileFieldPrivacyFlags.EVERYONE,
+ flags: UserFlags.DELETED,
+ } satisfies Partial<UserRow>;
+}
+
+export function personalFieldsToClear(row: UserRow): Partial<UserRow> {
+ const patch: Partial<UserRow> = {};
+ for (const field of FIELDS_CLEARED_ON_DELETION) {
+ const value = row[field];
+ if (!value || (value instanceof Set && value.size === 0)) continue;
+ patch[field] = null;
+ }
+ return patch;
+}
+
export function isTemporarilyBanned(user: Pick<User, 'flags' | 'tempBannedUntil'>, now = Date.now()): boolean {
return (
(user.flags & UserFlags.DISABLED) !== 0n && user.tempBannedUntil != null && user.tempBannedUntil.getTime() > now
diff --git a/fluxer_api/src/api/user/repositories/UserRepository.ts b/fluxer_api/src/api/user/repositories/UserRepository.ts
index d4ec83364..d0c08d129 100644
--- a/fluxer_api/src/api/user/repositories/UserRepository.ts
+++ b/fluxer_api/src/api/user/repositories/UserRepository.ts
@@ -123,6 +123,10 @@ export class UserRepository {
return this.accountRepo.completeDeletion(user);
}
+ async scrubDeletedUser(user: User): Promise<boolean> {
+ return this.accountRepo.scrubDeletedUser(user);
+ }
+
async findUnique(userId: UserID): Promise<User | null> {
return this.accountRepo.findUnique(userId);
}
diff --git a/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts b/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts
index 334a8e019..6fde36663 100644
--- a/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts
+++ b/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts
@@ -15,6 +15,7 @@ import {
} from '@app/api/user/repositories/account/crud/UserEmailOwnershipRepository';
import {UserIndexRepository} from '@app/api/user/repositories/account/crud/UserIndexRepository';
import {UserSearchRepository} from '@app/api/user/repositories/account/crud/UserSearchRepository';
+import {personalFieldsToClear} from '@app/api/user/UserHelpers';
import {
extractPremiumFlagsFromLegacyUserFlags,
LEGACY_DEAD_USER_FLAGS_MASK,
@@ -161,7 +162,23 @@ export class UserAccountRepository {
}
async completeDeletion(user: User): Promise<void> {
- await this.dataRepo.patchDeletion(user, {pending_deletion_at: Db.clear()}, 'complete');
+ const {updatedData} = await this.dataRepo.patchDeletion(user, {pending_deletion_at: Db.clear()}, 'complete');
+ await this.searchRepo.updateUser(new User(updatedData));
+ }
+
+ async scrubDeletedUser(user: User): Promise<boolean> {
+ const cleared = Object.keys(personalFieldsToClear(user.toRow()));
+ if (cleared.length === 0) return false;
+ await this.deleteUserSecondaryIndices(user.id);
+ await this.dataRepo.patchUser(
+ user.id,
+ Object.fromEntries(cleared.map((field) => [field, Db.clear()])),
+ user.toRow(),
+ );
+ if (user.email) {
+ await this.emailOwnershipRepo.releaseEmail(user.email, user.id);
+ }
+ return true;
}
private async patchAccount(
diff --git a/fluxer_api/src/api/user/services/AccountStateApplier.ts b/fluxer_api/src/api/user/services/AccountStateApplier.ts
index 13a371f8a..34128d1d9 100644
--- a/fluxer_api/src/api/user/services/AccountStateApplier.ts
+++ b/fluxer_api/src/api/user/services/AccountStateApplier.ts
@@ -28,6 +28,7 @@ import {
type PartialUserChangePropagationDeps,
propagatePartialUserChange,
} from '@app/api/user/services/PartialUserChangePropagation';
+import {isDeletionComplete} from '@app/api/user/UserHelpers';
import {dispatchUserUpdate} from '@app/api/user/UserMappers';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
import {getSameIpDecisionKey, isPublicIpAddress, parseIpAddress} from '@fluxer/ip_utils/src/IpAddress';
@@ -144,10 +145,6 @@ function isIneligible(user: User): boolean {
return user.isBot || (user.flags & UserFlags.DELETED) !== 0n;
}
-function isDeletionComplete(user: User): boolean {
- return (user.flags & UserFlags.DELETED) !== 0n && user.pendingDeletionAt === null;
-}
-
export async function applySetAccountLimit(
deps: AccountStateDeps,
env: ActionOf<'set_account_limit'>,
diff --git a/fluxer_api/src/api/user/services/UserDeletionService.ts b/fluxer_api/src/api/user/services/UserDeletionService.ts
index 74642e2e8..dc7e60bfa 100644
--- a/fluxer_api/src/api/user/services/UserDeletionService.ts
+++ b/fluxer_api/src/api/user/services/UserDeletionService.ts
@@ -12,6 +12,7 @@ import type {ChannelRepository} from '@app/api/channel/ChannelRepository';
import {UserMessageDeletionService} from '@app/api/channel/services/message/UserMessageDeletionService';
import type {ConnectionRepository} from '@app/api/connection/ConnectionRepository';
import {IP_BAN_REFRESH_CHANNEL} from '@app/api/constants/IpBan';
+import {EMPTY_USER_ROW} from '@app/api/database/types/UserTypes';
import type {FavoriteMemeRepository} from '@app/api/favorite_meme/FavoriteMemeRepository';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import {guildVisitRepository} from '@app/api/guild/visits/GuildVisitorAccess';
@@ -34,16 +35,14 @@ import {endOperatorPassesForDeletion} from '@app/api/operator_pass/OperatorPassH
import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {isPendingDeletionBlocked} from '@app/api/user/services/PendingDeletionCoordinator';
-import {isEnforcementDeletion, isSsoLinkedUser} from '@app/api/user/UserHelpers';
+import {
+ deletedUserIdentity,
+ isEnforcementDeletion,
+ isSsoLinkedUser,
+ personalFieldsToClear,
+} from '@app/api/user/UserHelpers';
import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';
import {ChannelTypes, MessageTypes} from '@fluxer/constants/src/ChannelConstants';
-import {
- DELETED_USER_DISCRIMINATOR,
- DELETED_USER_GLOBAL_NAME,
- DELETED_USER_USERNAME,
- ProfileFieldPrivacyFlags,
- UserFlags,
-} from '@fluxer/constants/src/UserConstants';
import * as BucketUtils from '@fluxer/snowflake/src/SnowflakeBuckets';
import type {ICacheService} from '@pkgs/cache/src/ICacheService';
import type {IWorkerService} from '@pkgs/worker/src/contracts/IWorkerService';
@@ -98,6 +97,24 @@ async function removeNetworkBlocksOf(userId: UserID, deps: UserDeletionDependenc
}
}
+async function createDeletedUserPlaceholder(
+ userRepository: UserRepository,
+ snowflakeService: ISnowflakeService,
+ userId: UserID,
+): Promise<UserID> {
+ const deletedUserId = createUserID(await snowflakeService.generate());
+ Logger.debug({userId, deletedUserId}, 'Creating dedicated deleted user record');
+ await userRepository.create({
+ ...EMPTY_USER_ROW,
+ ...deletedUserIdentity(),
+ user_id: deletedUserId,
+ bot: false,
+ system: false,
+ });
+ await userRepository.deleteUserSecondaryIndices(deletedUserId);
+ return deletedUserId;
+}
+
export async function processUserDeletion(
userId: UserID,
pendingDeletionAt: Date,
@@ -202,68 +219,6 @@ export async function processUserDeletion(
await withdrawPendingRegistrationOf(user);
await storeEntitlementService.stopBillingForDeletedUser(userId);
await connectionRepository.sealAndDeleteForUser(userId);
- const deletedUserId = createUserID(await snowflakeService.generate());
- Logger.debug({userId, deletedUserId}, 'Creating dedicated deleted user record');
- await userRepository.create({
- user_id: deletedUserId,
- username: DELETED_USER_USERNAME,
- discriminator: DELETED_USER_DISCRIMINATOR,
- global_name: DELETED_USER_GLOBAL_NAME,
- bot: false,
- system: false,
- email: null,
- email_verified: null,
- email_bounced: null,
- password_hash: null,
- password_last_changed_at: null,
- totp_secret: null,
- authenticator_types: null,
- avatar_hash: null,
- avatar_color: null,
- banner_hash: null,
- banner_color: null,
- bio: null,
- pronouns: null,
- accent_color: null,
- timezone: null,
- timezone_privacy_flags: ProfileFieldPrivacyFlags.EVERYONE,
- date_of_birth: null,
- locale: null,
- flags: UserFlags.DELETED,
- premium_type: null,
- premium_since: null,
- premium_until: null,
- premium_gift_extension_ends_at: null,
- premium_will_cancel: null,
- premium_billing_cycle: null,
- premium_lifetime_sequence: null,
- premium_grace_ends_at: null,
- stripe_subscription_id: null,
- stripe_customer_id: null,
- has_ever_purchased: null,
- terms_agreed_at: null,
- privacy_agreed_at: null,
- last_active_at: null,
- last_active_ip: null,
- temp_banned_until: null,
- pending_deletion_at: null,
- pending_bulk_message_deletion_at: null,
- pending_bulk_message_deletion_channel_count: null,
- pending_bulk_message_deletion_message_count: null,
- deletion_reason_code: null,
- deletion_public_reason: null,
- deletion_audit_log_reason: null,
- acls: null,
- traits: null,
- first_refund_at: null,
- gift_inventory_server_seq: null,
- gift_inventory_client_seq: null,
- premium_onboarding_dismissed_at: null,
- mention_flags: null,
- last_voice_activity_sharing_change_at: null,
- version: 1,
- });
- await userRepository.deleteUserSecondaryIndices(deletedUserId);
Logger.debug({userId}, 'Leaving all guilds');
const guildIds = await userRepository.getUserGuildIds(userId);
for (const guildId of guildIds) {
@@ -434,6 +389,7 @@ export async function processUserDeletion(
Logger.debug({userId}, 'Anonymizing user messages');
let lastMessageId: MessageID | undefined;
let processedCount = 0;
+ let deletedUserId: UserID | null = null;
while (true) {
const messagesToAnonymize = await channelRepository.messages.listMessagesByAuthor(
userId,
@@ -443,6 +399,7 @@ export async function processUserDeletion(
if (messagesToAnonymize.length === 0) {
break;
}
+ deletedUserId ??= await createDeletedUserPlaceholder(userRepository, snowflakeService, userId);
for (const {channelId, messageId} of messagesToAnonymize) {
await channelRepository.messages.anonymizeMessage(channelId, messageId, deletedUserId);
}
@@ -528,29 +485,8 @@ export async function processUserDeletion(
const userForAnonymization = await userRepository.findUniqueAssert(userId);
Logger.debug({userId}, 'Anonymizing user record');
const anonymisedUser = await userRepository.anonymizeForDeletion(userForAnonymization, {
- username: DELETED_USER_USERNAME,
- discriminator: DELETED_USER_DISCRIMINATOR,
- global_name: DELETED_USER_GLOBAL_NAME,
- email: null,
- email_verified: false,
- password_hash: null,
- totp_secret: null,
- avatar_hash: null,
- banner_hash: null,
- bio: null,
- pronouns: null,
- accent_color: null,
- timezone: null,
- timezone_privacy_flags: ProfileFieldPrivacyFlags.EVERYONE,
- date_of_birth: null,
- flags: UserFlags.DELETED,
- premium_type: null,
- premium_since: null,
- premium_until: null,
- premium_gift_extension_ends_at: null,
- stripe_customer_id: null,
- stripe_subscription_id: null,
- authenticator_types: new Set(),
+ ...deletedUserIdentity(),
+ ...personalFieldsToClear(userForAnonymization.toRow()),
});
await userCacheService.setUserPartialResponseFromUser(anonymisedUser);
diff --git a/fluxer_api/src/api/user/tests/InactivityDeletion.test.ts b/fluxer_api/src/api/user/tests/InactivityDeletion.test.ts
index 7aaf4b663..8c6998f11 100644
--- a/fluxer_api/src/api/user/tests/InactivityDeletion.test.ts
+++ b/fluxer_api/src/api/user/tests/InactivityDeletion.test.ts
@@ -10,6 +10,7 @@ import {UserRepository} from '@app/api/user/repositories/UserRepository';
import {expectDataExists} from '@app/api/user/tests/UserTestUtils';
import {CleanupModes} from '@fluxer/constants/src/AccountConfigConstants';
import {DeletionReasons} from '@fluxer/constants/src/Core';
+import {UserFlags} from '@fluxer/constants/src/UserConstants';
import type {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
import {afterEach, beforeEach, describe, expect, test} from 'vitest';
@@ -143,6 +144,23 @@ describe('Inactivity Deletion', () => {
const dataStatus = await expectDataExists(harness, account.userId);
expect(dataStatus.userExists).toBe(true);
});
+ test('a finished deletion is never scheduled again', async () => {
+ const account = await createTestAccount(harness);
+ await setUserActivity(harness, account.userId, new Date(Date.now() - 3 * 365 * 24 * 60 * 60 * 1000));
+ await harness.kvProvider.setex(
+ `inactivity_warning_sent:${account.userId}`,
+ 35 * 24 * 60 * 60,
+ String(Date.now() - 31 * 24 * 60 * 60 * 1000),
+ );
+ const users = new UserRepository();
+ const userId = createUserID(BigInt(account.userId));
+ const user = await users.findUniqueAssert(userId);
+ await users.patchUpsert(userId, {flags: UserFlags.DELETED}, user.toRow());
+ const result = await processInactivityDeletions(harness);
+ expect(result.deletions_scheduled).toBe(0);
+ expect(result.warnings_sent).toBe(0);
+ expect((await users.findUniqueAssert(userId)).pendingDeletionAt).toBeNull();
+ });
test('a configured threshold below two years warns accounts idle that long', async () => {
await getInstanceConfigRepository().updateAccountsConfig({inactivity_deletion: {inactive_days: 200}});
const account = await createTestAccount(harness);
diff --git a/fluxer_api/src/api/worker/WorkerLaneConfig.ts b/fluxer_api/src/api/worker/WorkerLaneConfig.ts
index aac63b9c0..489708654 100644
--- a/fluxer_api/src/api/worker/WorkerLaneConfig.ts
+++ b/fluxer_api/src/api/worker/WorkerLaneConfig.ts
@@ -103,6 +103,7 @@ const LANE_CONFIG = {
'backfillThreadSearch',
'backfillPasskeyTrait',
'backfillUserAclIndex',
+ 'backfillDeletedUsers',
'syncDiscoveryIndex',
'syncUrlBlocklists',
'syncFileShaBlocklists',
diff --git a/fluxer_api/src/api/worker/WorkerMain.ts b/fluxer_api/src/api/worker/WorkerMain.ts
index 3b4e0c562..7df98eb6c 100644
--- a/fluxer_api/src/api/worker/WorkerMain.ts
+++ b/fluxer_api/src/api/worker/WorkerMain.ts
@@ -44,6 +44,7 @@ import {startAccountActionConsumer, stopAccountActionConsumer} from '@app/api/wo
import {queueBlocklistFeedStartupJobs} from '@app/api/worker/BlocklistFeedStartup';
import {CronScheduler} from '@app/api/worker/CronScheduler';
import {JetStreamWorkerQueue, JOBS_STREAM_MAX_AGE_MS} from '@app/api/worker/JetStreamWorkerQueue';
+import {queueDeletedUsersBackfill} from '@app/api/worker/tasks/BackfillDeletedUsers';
import {queuePasskeyTraitBackfill} from '@app/api/worker/tasks/BackfillPasskeyTrait';
import {queueUserAclIndexBackfill} from '@app/api/worker/tasks/BackfillUserAclIndex';
import {singleCommunityJoinPending} from '@app/api/worker/tasks/JoinSingleCommunityMembers';
@@ -230,6 +231,7 @@ export async function startWorkerRuntime(options: WorkerRuntimeOptions): Promise
await queueBlocklistFeedStartupJobs(dependencies.kvClient, workerService, Config.blocklistFeeds.enabled);
await queuePasskeyTraitBackfill(dependencies.kvClient, workerService);
await queueUserAclIndexBackfill(dependencies.kvClient, workerService);
+ await queueDeletedUsersBackfill(dependencies.kvClient, workerService);
try {
const normalized = await getInstanceConfigRepository().normalizeStoredBrandingAssets(dependencies.storageService);
if (normalized > 0) {
diff --git a/fluxer_api/src/api/worker/WorkerTaskRegistry.ts b/fluxer_api/src/api/worker/WorkerTaskRegistry.ts
index 4b7ba5a85..4f004c371 100644
--- a/fluxer_api/src/api/worker/WorkerTaskRegistry.ts
+++ b/fluxer_api/src/api/worker/WorkerTaskRegistry.ts
@@ -7,6 +7,7 @@ import bulkDeleteMessagesForUsers from '@app/api/worker/tasks/admin_bulk/BulkDel
import bulkScheduleUserDeletion from '@app/api/worker/tasks/admin_bulk/BulkScheduleUserDeletion';
import bulkUpdateGuildFeatures from '@app/api/worker/tasks/admin_bulk/BulkUpdateGuildFeatures';
import bulkUpdateUserFlags from '@app/api/worker/tasks/admin_bulk/BulkUpdateUserFlags';
+import backfillDeletedUsers from '@app/api/worker/tasks/BackfillDeletedUsers';
import backfillPasskeyTrait from '@app/api/worker/tasks/BackfillPasskeyTrait';
import backfillUserAclIndex from '@app/api/worker/tasks/BackfillUserAclIndex';
import batchGuildAuditLogMessageDeletes from '@app/api/worker/tasks/BatchGuildAuditLogMessageDeletes';
@@ -90,6 +91,7 @@ export const workerTasks: Record<WorkerTaskName, WorkerTaskHandler> = {
repairThreadIndexes,
syncThreadSearchDocument,
backfillThreadSearch,
+ backfillDeletedUsers,
backfillPasskeyTrait,
backfillUserAclIndex,
batchGuildAuditLogMessageDeletes,
diff --git a/fluxer_api/src/api/worker/tasks/BackfillDeletedUsers.ts b/fluxer_api/src/api/worker/tasks/BackfillDeletedUsers.ts
new file mode 100644
index 000000000..7088956b7
--- /dev/null
+++ b/fluxer_api/src/api/worker/tasks/BackfillDeletedUsers.ts
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {Logger} from '@app/api/Logger';
+import {getUserSearchService} from '@app/api/SearchFactory';
+import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {isDeletionComplete} from '@app/api/user/UserHelpers';
+import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
+import {WorkerQueueOverflowError} from '@app/api/worker/WorkerQueueOverflowError';
+import type {WorkerService} from '@app/api/worker/WorkerService';
+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
+import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
+import {ms} from 'itty-time';
+
+const DELETED_USERS_BACKFILL_DONE_KEY = 'backfill:deleted_users:done';
+const CLAIM_KEY = 'backfill:deleted_users:queued';
+const CLAIM_TTL_SECONDS = ms('6 hours') / 1000;
+const DEFAULT_PAGE_SIZE = 500;
+
+interface DeletedUsersBackfillSummary {
+ deleted: number;
+ scrubbed: number;
+}
+
+export async function backfillDeletedUsers(
+ userRepository: Pick<UserRepository, 'scanAllUsersPage' | 'scrubDeletedUser'>,
+ pageSize = DEFAULT_PAGE_SIZE,
+): Promise<DeletedUsersBackfillSummary> {
+ const summary: DeletedUsersBackfillSummary = {deleted: 0, scrubbed: 0};
+ const searchService = getUserSearchService();
+ let pageState: string | null = null;
+ do {
+ const page = await userRepository.scanAllUsersPage(pageSize, pageState);
+ pageState = page.pageState;
+ const deletedUsers = page.users.filter(isDeletionComplete);
+ for (const user of deletedUsers) {
+ if (await userRepository.scrubDeletedUser(user)) summary.scrubbed++;
+ }
+ if (searchService && deletedUsers.length > 0) {
+ await searchService.deleteDocuments(deletedUsers.map((user) => user.id.toString()));
+ }
+ summary.deleted += deletedUsers.length;
+ } while (pageState !== null);
+ Logger.info(summary, 'Backfilled deleted user rows');
+ return summary;
+}
+
+export async function queueDeletedUsersBackfill(
+ kvClient: Pick<IKVProvider, 'get' | 'setnx' | 'del'>,
+ workerService: Pick<WorkerService, 'addJob'>,
+): Promise<void> {
+ if ((await kvClient.get(DELETED_USERS_BACKFILL_DONE_KEY)) !== null) return;
+ if (!(await kvClient.setnx(CLAIM_KEY, '1', CLAIM_TTL_SECONDS))) return;
+ try {
+ await workerService.addJob('backfillDeletedUsers', {});
+ } catch (error) {
+ await kvClient.del(CLAIM_KEY);
+ if (!(error instanceof WorkerQueueOverflowError)) throw error;
+ Logger.warn('Dropped the deleted users backfill job, jobs stream is at its limit');
+ }
+}
+
+const backfillDeletedUsersTask: WorkerTaskHandler = async () => {
+ const {userRepository, kvClient} = getWorkerDependencies();
+ await backfillDeletedUsers(userRepository);
+ await kvClient.set(DELETED_USERS_BACKFILL_DONE_KEY, new Date().toISOString());
+};
+
+export default backfillDeletedUsersTask;
diff --git a/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts b/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts
index 0c336ee36..791628e4a 100644
--- a/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts
+++ b/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts
@@ -22,6 +22,7 @@ import {
} from '@app/api/user/services/PartialUserChangePropagation';
import {reschedulePendingDeletion} from '@app/api/user/services/PendingDeletionCoordinator';
import type {UserDeletionEligibilityService} from '@app/api/user/services/UserDeletionEligibilityService';
+import {isDeletionComplete} from '@app/api/user/UserHelpers';
import {DOB_DEFERRED_TRAIT} from '@app/api/user/UserTraits';
import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
@@ -148,6 +149,7 @@ async function processUser(
activityTracker,
deletionEligibilityService,
} = deps;
+ if (isDeletionComplete(listedUser)) return;
const user = await clearSuspensionIfExpired(listedUser, deps, result);
const userId = user.id;
if (user.pendingDeletionAt) {
diff --git a/fluxer_rexctl/cmd/users.go b/fluxer_rexctl/cmd/users.go
index 3e67fe0ec..d41183aec 100644
--- a/fluxer_rexctl/cmd/users.go
+++ b/fluxer_rexctl/cmd/users.go
@@ -337,6 +337,10 @@ func newUsersCmd(app *App) *cobra.Command {
if err != nil {
return err
}
+ if u.DeletionFinished() {
+ app.UI.OK("Account %s is already deleted.", u.ID)
+ return nil
+ }
if err := app.UI.ConfirmDestructive(fmt.Sprintf("This deletes %s and everything they posted.", u.Username), inst.Domain(), confirm); err != nil {
return err
}
@@ -345,6 +349,10 @@ func newUsersCmd(app *App) *cobra.Command {
app.UI.OK("%s is already being deleted.", u.Username)
return nil
}
+ if errors.Is(err, adminapi.ErrAlreadyDeleted) {
+ app.UI.OK("Account %s is already deleted.", u.ID)
+ return nil
+ }
return err
}
app.UI.OK("Deleted %s.", u.Username)
diff --git a/fluxer_rexctl/internal/adminapi/users.go b/fluxer_rexctl/internal/adminapi/users.go
index 00ce01f29..719354baa 100644
--- a/fluxer_rexctl/internal/adminapi/users.go
+++ b/fluxer_rexctl/internal/adminapi/users.go
@@ -28,8 +28,12 @@ type User struct {
Banned bool `json:"banned"`
MFA bool `json:"mfa"`
CreatedAt string `json:"created_at"`
+
+ deletionFinished bool
}
+func (u User) DeletionFinished() bool { return u.deletionFinished }
+
type UserDetail struct {
User
Disabled bool `json:"disabled"`
@@ -41,6 +45,8 @@ type UserDetail struct {
var ErrDeletionPending = errors.New("adminapi: the account is already being deleted")
+var ErrAlreadyDeleted = errors.New("adminapi: the account was already deleted")
+
type BanBlocksDeletionError struct{ Username string }
func (e *BanBlocksDeletionError) Error() string {
@@ -78,6 +84,8 @@ func toUser(u UserAdminResponseSchema) User {
Banned: bannedNow(u.TempBannedUntil),
MFA: u.HasTotp || len(u.AuthenticatorTypes) > 0,
CreatedAt: SnowflakeTime(u.Id),
+
+ deletionFinished: deletionFinished(u),
}
if u.Email != nil {
out.Email = *u.Email
@@ -123,6 +131,10 @@ func isDeleted(u UserAdminResponseSchema) bool {
return flags&userFlagDeleted != 0
}
+func deletionFinished(u UserAdminResponseSchema) bool {
+ return isDeleted(u) && u.PendingDeletionAt == nil
+}
+
func (c *Client) ListUsers(ctx context.Context, search string, admins bool) ([]User, error) {
out := []User{}
for offset := 0; ; offset += listPageSize {
@@ -410,6 +422,9 @@ func (c *Client) DeleteUser(ctx context.Context, id string) error {
if err != nil {
return err
}
+ if deletionFinished(*u) {
+ return ErrAlreadyDeleted
+ }
basis, err := c.deletionBasis(ctx, *u)
if err != nil {
return err