Skip to content

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

TypeScript fluxerfluxerapp

feat(api): add configurable deletion of abandoned accounts

Hampusbf093c472fde
diff --git a/fluxer_api/src/api/user/AccountCleanup.ts b/fluxer_api/src/api/user/AccountCleanup.ts
new file mode 100644
index 000000000..7d7619f5c
--- /dev/null
+++ b/fluxer_api/src/api/user/AccountCleanup.ts
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {ApiContext} from '@app/api/ApiContext';
+import {revokeAllAuthSessions} from '@app/api/auth/AuthSessionRevocation';
+import {SYSTEM_USER_ID} from '@app/api/constants/Core';
+import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
+import type {KVAccountDeletionQueueService} from '@app/api/infrastructure/KVAccountDeletionQueueService';
+import {getCachedAccountsConfig} from '@app/api/instance/AccountsConfigCache';
+import {getKVAccountDeletionQueue} from '@app/api/middleware/ServiceSingletons';
+import type {User} from '@app/api/models/User';
+import {followOperatorPassWallStanding} from '@app/api/operator_pass/OperatorPassWallStanding';
+import {hasWayBackIn} from '@app/api/user/AccountTier';
+import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {reschedulePendingDeletion} from '@app/api/user/services/PendingDeletionCoordinator';
+import {AccountCleanupDefaults, LastSessionCleanupModes} from '@fluxer/constants/src/AccountConfigConstants';
+import {DeletionReasons} from '@fluxer/constants/src/Core';
+import {UserFlags} from '@fluxer/constants/src/UserConstants';
+
+export interface SystemDeletionDeps {
+ users: UserRepository;
+ gateway: IGatewayService;
+ deletionQueue: Pick<KVAccountDeletionQueueService, 'scheduleDeletion' | 'removeFromQueue'>;
+}
+
+export async function scheduleSystemDeletion(
+ deps: SystemDeletionDeps,
+ user: User,
+ params: {reasonCode: number; delayMs: number; cancelledBySignIn: boolean; endSessions: boolean},
+): Promise<User> {
+ const pendingDeletionAt = new Date(Date.now() + params.delayMs);
+ const updated = await deps.users.updateDeletionSchedule(user, {
+ flags: params.cancelledBySignIn ? user.flags | UserFlags.SELF_DELETED : user.flags | UserFlags.DELETED,
+ pending_deletion_at: pendingDeletionAt,
+ deletion_reason_code: params.reasonCode,
+ deletion_scheduled_by: SYSTEM_USER_ID,
+ deletion_scheduled_at: new Date(),
+ });
+ await reschedulePendingDeletion({
+ userId: user.id,
+ currentPendingDeletionAt: user.pendingDeletionAt,
+ nextPendingDeletionAt: pendingDeletionAt,
+ deletionReasonCode: params.reasonCode,
+ deletionQueue: deps.deletionQueue,
+ });
+ if (params.endSessions) {
+ await revokeAllAuthSessions({users: deps.users, gateway: deps.gateway}, user.id);
+ }
+ await followOperatorPassWallStanding(user, updated);
+ return updated;
+}
+
+export async function scheduleAbandonedOnLastLogout(ctx: ApiContext, user: User): Promise<void> {
+ const cleanup = getCachedAccountsConfig().unclaimed_account_cleanup;
+ if (cleanup.on_last_session_end !== LastSessionCleanupModes.AFTER_GRACE) return;
+ if (user.isBot || user.pendingDeletionAt !== null) return;
+ if (await hasWayBackIn(ctx.services, user)) return;
+ if ((await ctx.services.users.listAuthSessions(user.id)).length > 0) return;
+ await scheduleSystemDeletion(
+ {users: ctx.services.users, gateway: ctx.services.gateway, deletionQueue: getKVAccountDeletionQueue()},
+ user,
+ {
+ reasonCode: DeletionReasons.UNCLAIMED_ACCOUNT_ABANDONED,
+ delayMs: AccountCleanupDefaults.SCHEDULED_DELETION_GRACE_MS,
+ cancelledBySignIn: true,
+ endSessions: false,
+ },
+ );
+}
diff --git a/fluxer_api/src/api/user/UserHelpers.ts b/fluxer_api/src/api/user/UserHelpers.ts
index 008f69d4c..c211c8953 100644
--- a/fluxer_api/src/api/user/UserHelpers.ts
+++ b/fluxer_api/src/api/user/UserHelpers.ts
@@ -4,6 +4,7 @@ import {Config} from '@app/api/Config';
import type {UserRow} from '@app/api/database/types/UserTypes';
import {getCachedInstancePremiumMode} from '@app/api/limits/InstancePremiumModeCache';
import type {User} from '@app/api/models/User';
+import {isEnforcementReasonCode} from '@fluxer/constants/src/EnforcementReasons';
import {
PREMIUM_GRACE_PERIOD_DAYS,
PREMIUM_PAYMENT_RECOVERY_GRACE_DAYS,
@@ -19,6 +20,14 @@ export function isSsoUserWithoutPassword(user: Pick<User, 'traits' | 'passwordHa
return user.passwordHash === null && user.traits.has('sso');
}
+export function isSsoLinkedUser(user: Pick<User, 'traits'>): boolean {
+ return user.traits.has('sso');
+}
+
+export function isEnforcementDeletion(user: Pick<User, 'enforcementDecisionId' | 'deletionReasonCode'>): boolean {
+ return user.enforcementDecisionId !== null || isEnforcementReasonCode(user.deletionReasonCode);
+}
+
export function isAccountClosed(user: Pick<User, 'flags' | 'deletionStartedAt'>): boolean {
return (user.flags & UserFlags.DELETED) !== 0n || user.deletionStartedAt != null;
}
diff --git a/fluxer_api/src/api/user/tests/AbandonedAccountCleanup.test.ts b/fluxer_api/src/api/user/tests/AbandonedAccountCleanup.test.ts
new file mode 100644
index 000000000..df8c5b75e
--- /dev/null
+++ b/fluxer_api/src/api/user/tests/AbandonedAccountCleanup.test.ts
@@ -0,0 +1,179 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createUserID} from '@app/api/BrandedTypes';
+import {getKVClient} from '@app/api/middleware/ServiceRegistry';
+import {getInstanceConfigRepository, getUserRepository} from '@app/api/middleware/ServiceSingletons';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
+import {CleanupModes, LastSessionCleanupModes} from '@fluxer/constants/src/AccountConfigConstants';
+import {DeletionReasons} from '@fluxer/constants/src/Core';
+import {UserFlags, UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+describe('Abandoned account cleanup', () => {
+ let harness: ApiTestHarness;
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+ beforeEach(async () => {
+ await harness.reset();
+ });
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+
+ async function registerWithToken(body: Record<string, unknown>): Promise<{user_id: string; token: string}> {
+ return await createBuilderWithoutAuth<{user_id: string; token: string}>(harness)
+ .post('/auth/register')
+ .body({username: 'wanderer', consent: true, ...body})
+ .execute();
+ }
+
+ async function register(body: Record<string, unknown>): Promise<string> {
+ return (await registerWithToken(body)).user_id;
+ }
+
+ async function signOut(token: string): Promise<void> {
+ await createBuilder(harness, token).post('/auth/logout').body(null).expect(204).execute();
+ }
+
+ async function idleFor(userId: string, days: number): Promise<void> {
+ await createBuilderWithoutAuth(harness)
+ .post(`/test/users/${userId}/set-last-active-at`)
+ .body({timestamp: new Date(Date.now() - days * DAY_MS).toISOString()})
+ .execute();
+ }
+
+ async function sweep(): Promise<void> {
+ await createBuilderWithoutAuth(harness).post('/test/worker/process-inactivity-deletions').body({}).execute();
+ }
+
+ async function deletionReason(userId: string): Promise<number | null> {
+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(userId)));
+ return user.pendingDeletionAt ? user.deletionReasonCode : null;
+ }
+
+ it('leaves idle unclaimed accounts alone while the sweep is off', async () => {
+ const userId = await register({date_of_birth: '1995-05-05'});
+ await idleFor(userId, 120);
+ await sweep();
+ expect(await deletionReason(userId)).toBeNull();
+ });
+
+ it('schedules idle accounts with no way back in once the sweep is on', async () => {
+ await getInstanceConfigRepository().updateAccountsConfig({abandoned_account_cleanup: true});
+ const unclaimed = await register({date_of_birth: '1995-05-05'});
+ const owner = await createTestAccount(harness);
+ await idleFor(unclaimed, 120);
+ await idleFor(owner.userId, 120);
+ await sweep();
+ expect(await deletionReason(unclaimed)).toBe(DeletionReasons.UNCLAIMED_ACCOUNT_ABANDONED);
+ expect(await deletionReason(owner.userId)).toBeNull();
+ });
+
+ it('reads a missing activity entry as the last recorded activity, never as endless inactivity', async () => {
+ await getInstanceConfigRepository().updateAccountsConfig({abandoned_account_cleanup: true});
+ const fresh = await register({});
+ const freshWithDate = await register({date_of_birth: '1995-05-05'});
+ const stale = await register({date_of_birth: '1995-05-05'});
+ await idleFor(stale, 120);
+ await getKVClient().del(`user_activity:${fresh}`, `user_activity:${freshWithDate}`, `user_activity:${stale}`);
+ await sweep();
+ expect(await deletionReason(fresh)).toBeNull();
+ expect(await deletionReason(freshWithDate)).toBeNull();
+ expect(await deletionReason(stale)).toBe(DeletionReasons.UNCLAIMED_ACCOUNT_ABANDONED);
+ });
+
+ it('keeps an account with no way back in after its last session ends while the cleanup is off', async () => {
+ const created = await registerWithToken({date_of_birth: '1995-05-05'});
+ await signOut(created.token);
+ expect(await deletionReason(created.user_id)).toBeNull();
+ });
+
+ it('schedules an account with no way back in a day after its last session ends once the cleanup is on', async () => {
+ await getInstanceConfigRepository().updateAccountsConfig({abandoned_account_cleanup: true});
+ const created = await registerWithToken({date_of_birth: '1995-05-05'});
+ await signOut(created.token);
+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(created.user_id)));
+ expect(user.deletionReasonCode).toBe(DeletionReasons.UNCLAIMED_ACCOUNT_ABANDONED);
+ expect(user.pendingDeletionAt!.getTime() - Date.now()).toBeGreaterThan(23 * 3600 * 1000);
+ });
+
+ it('leaves an account with a confirmed email alone when it signs out with the cleanup on', async () => {
+ await getInstanceConfigRepository().updateAccountsConfig({abandoned_account_cleanup: true});
+ const account = await createTestAccount(harness);
+ await signOut(account.token);
+ expect(await deletionReason(account.userId)).toBeNull();
+ });
+
+ it('schedules accounts that never entered a date of birth after a week', async () => {
+ await getInstanceConfigRepository().updateAccountsConfig({abandoned_account_cleanup: true});
+ const fresh = await register({});
+ const stale = await register({});
+ await idleFor(fresh, 2);
+ await idleFor(stale, 8);
+ await sweep();
+ expect(await deletionReason(fresh)).toBeNull();
+ expect(await deletionReason(stale)).toBe(DeletionReasons.INACTIVITY);
+ });
+
+ it('honours the configured idle days of each cleanup policy', async () => {
+ await getInstanceConfigRepository().updateAccountsConfig({
+ unclaimed_account_cleanup: {mode: CleanupModes.AFTER_INACTIVITY, inactive_days: 30},
+ dob_missing_cleanup: {mode: CleanupModes.AFTER_INACTIVITY, inactive_days: 3},
+ });
+ const unclaimed = await register({date_of_birth: '1995-05-05'});
+ const recent = await register({date_of_birth: '1995-05-05'});
+ const noBirthday = await register({});
+ await idleFor(unclaimed, 40);
+ await idleFor(recent, 20);
+ await idleFor(noBirthday, 4);
+ await sweep();
+ expect(await deletionReason(unclaimed)).toBe(DeletionReasons.UNCLAIMED_ACCOUNT_ABANDONED);
+ expect(await deletionReason(noBirthday)).toBe(DeletionReasons.INACTIVITY);
+ expect(await deletionReason(recent)).toBeNull();
+ });
+
+ it('runs each cleanup policy on its own', async () => {
+ await getInstanceConfigRepository().updateAccountsConfig({
+ unclaimed_account_cleanup: {mode: CleanupModes.OFF, on_last_session_end: LastSessionCleanupModes.OFF},
+ dob_missing_cleanup: {mode: CleanupModes.AFTER_INACTIVITY},
+ });
+ const unclaimed = await register({date_of_birth: '1995-05-05'});
+ const noBirthday = await register({});
+ await idleFor(unclaimed, 120);
+ await idleFor(noBirthday, 8);
+ await sweep();
+ expect(await deletionReason(unclaimed)).toBeNull();
+ expect(await deletionReason(noBirthday)).toBe(DeletionReasons.INACTIVITY);
+ const created = await registerWithToken({date_of_birth: '1995-05-05'});
+ await signOut(created.token);
+ expect(await deletionReason(created.user_id)).toBeNull();
+ });
+
+ it('leaves pass holders, lifetime members and suspended accounts alone', async () => {
+ await getInstanceConfigRepository().updateAccountsConfig({abandoned_account_cleanup: true});
+ const lifetime = await register({});
+ const suspended = await register({});
+ await createBuilderWithoutAuth(harness)
+ .post(`/test/users/${lifetime}/premium`)
+ .body({premium_type: UserPremiumTypes.LIFETIME})
+ .execute();
+ const users = getUserRepository();
+ const banned = await users.findUniqueAssert(createUserID(BigInt(suspended)));
+ await users.patchUpsert(
+ banned.id,
+ {flags: banned.flags | UserFlags.DISABLED, temp_banned_until: new Date(Date.now() + 30 * DAY_MS)},
+ banned.toRow(),
+ );
+ for (const userId of [holder, lifetime, suspended]) {
+ await idleFor(userId, 120);
+ }
+ await sweep();
+ expect(await deletionReason(lifetime)).toBeNull();
+ expect(await deletionReason(suspended)).toBeNull();
+ });
+});
diff --git a/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts b/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts
index b075ad94a..0c336ee36 100644
--- a/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts
+++ b/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts
@@ -11,6 +11,10 @@ import type {KVAccountDeletionQueueService} from '@app/api/infrastructure/KVAcco
import type {KVActivityTracker} from '@app/api/infrastructure/KVActivityTracker';
import {Logger} from '@app/api/Logger';
import type {User} from '@app/api/models/User';
+import {followOperatorPassWallStanding} from '@app/api/operator_pass/OperatorPassWallStanding';
+import {scheduleSystemDeletion} from '@app/api/user/AccountCleanup';
+import {hasWayBackIn} from '@app/api/user/AccountTier';
+import {isDateOfBirthMissing} from '@app/api/user/DateOfBirth';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {
type PartialUserChangePropagationDeps,
@@ -18,10 +22,17 @@ 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 {DOB_DEFERRED_TRAIT} from '@app/api/user/UserTraits';
import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
+import {
+ AccountCleanupDefaults,
+ CleanupModes,
+ LastSessionCleanupModes,
+} from '@fluxer/constants/src/AccountConfigConstants';
import {DeletionReasons} from '@fluxer/constants/src/Core';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
+import type {AccountsConfig} from '@fluxer/schema/src/domains/admin/AccountsConfigSchemas';
import {snowflakeToDate} from '@fluxer/snowflake/src/Snowflake';
import type {IEmailService} from '@pkgs/email/src/IEmailService';
import {TestEmailService} from '@pkgs/email/src/TestEmailService';
@@ -48,7 +59,7 @@ async function scheduleDeletion(
): Promise<void> {
const gracePeriodMs = Config.deletionGracePeriodHours * ms('1 hour');
const pendingDeletionAt = new Date(Date.now() + gracePeriodMs);
- await userRepository.updateDeletionSchedule(user, {
+ const updated = await userRepository.updateDeletionSchedule(user, {
flags: user.flags | UserFlags.SELF_DELETED,
pending_deletion_at: pendingDeletionAt,
deletion_reason_code: DeletionReasons.INACTIVITY,
@@ -63,10 +74,29 @@ async function scheduleDeletion(
deletionQueue: deletionQueueService,
});
await revokeAllAuthSessions({users: userRepository, gateway: gatewayService}, userId);
+ await followOperatorPassWallStanding(user, updated);
Logger.debug({userId, pendingDeletionAt, reason: 'INACTIVITY'}, 'Scheduled inactive user for deletion');
}
+type AccountCleanupConfig = Pick<
+ AccountsConfig,
+ 'unclaimed_account_cleanup' | 'dob_missing_cleanup' | 'inactivity_deletion'
+>;
+
+function daysMs(days: number): number {
+ return days * ms('1 day');
+}
+
+function sweepsAbandonedAccounts(cleanup: AccountCleanupConfig): boolean {
+ return (
+ cleanup.dob_missing_cleanup.mode !== CleanupModes.OFF ||
+ cleanup.unclaimed_account_cleanup.mode !== CleanupModes.OFF ||
+ cleanup.unclaimed_account_cleanup.on_last_session_end !== LastSessionCleanupModes.OFF
+ );
+}
+
interface ProcessUserDeps {
+ cleanup: AccountCleanupConfig;
userRepository: UserRepository;
deletionQueueService: KVAccountDeletionQueueService;
gatewayService: IGatewayService;
@@ -137,7 +167,34 @@ async function processUser(
prefetchedActivity !== undefined ? prefetchedActivity : await activityTracker.getActivity(userId);
const now = new Date();
const userInactiveMs = lastActivity ? now.getTime() - lastActivity.getTime() : Infinity;
- if (userInactiveMs < ms('2 years')) {
+ if (sweepsAbandonedAccounts(deps.cleanup)) {
+ const lastKnownActivity = lastActivity ?? user.lastActiveAt ?? snowflakeToDate(BigInt(userId));
+ const abandonedInactiveMs = now.getTime() - lastKnownActivity.getTime();
+ const reasonCode = await abandonedAccountReason(user, abandonedInactiveMs, userRepository, deps.cleanup);
+ const current = reasonCode === null ? null : await userRepository.findUnique(userId);
+ const currentReason =
+ current === null ||
+ current.pendingDeletionAt ||
+ (await deletionEligibilityService.isProtectedFromSystemDeletion(current))
+ ? null
+ : await abandonedAccountReason(current, abandonedInactiveMs, userRepository, deps.cleanup);
+ if (current !== null && currentReason !== null) {
+ await scheduleSystemDeletion(
+ {users: userRepository, gateway: gatewayService, deletionQueue: deletionQueueService},
+ current,
+ {
+ reasonCode: currentReason,
+ delayMs: AccountCleanupDefaults.SCHEDULED_DELETION_GRACE_MS,
+ cancelledBySignIn: true,
+ endSessions: true,
+ },
+ );
+ result.deletionsScheduled++;
+ return;
+ }
+ }
+ const inactivity = deps.cleanup.inactivity_deletion;
+ if (inactivity.mode === CleanupModes.OFF || userInactiveMs < daysMs(inactivity.inactive_days)) {
return;
}
const isEligible = await deletionEligibilityService.isEligibleForInactivityDeletion(user);
@@ -164,12 +221,11 @@ async function processUser(
return;
}
try {
- const deletionDate = new Date(now.getTime() + ms('30 days'));
- const sent = await emailService.sendInactivityWarningEmail(
+ const deletionDate = new Date(now.getTime() + daysMs(inactivity.warning_lead_days));
+ const sent = await emailService.send(
+ 'inactivity_warning',
user.email,
- user.username,
- deletionDate,
- lastActivity ?? snowflakeToDate(BigInt(userId)),
+ {deletionDate, lastActiveDate: lastActivity ?? snowflakeToDate(BigInt(userId))},
user.locale,
);
if (sent) {
@@ -183,7 +239,38 @@ async function processUser(
}
}
+async function abandonedAccountReason(
+ user: User,
+ inactiveMs: number,
+ userRepository: UserRepository,
+ cleanup: AccountCleanupConfig,
+): Promise<number | null> {
+ const dobMissing = cleanup.dob_missing_cleanup;
+ if (
+ dobMissing.mode === CleanupModes.AFTER_INACTIVITY &&
+ user.traits.has(DOB_DEFERRED_TRAIT) &&
+ isDateOfBirthMissing(user) &&
+ inactiveMs >= daysMs(dobMissing.inactive_days)
+ ) {
+ return DeletionReasons.INACTIVITY;
+ }
+ const unclaimed = cleanup.unclaimed_account_cleanup;
+ const afterInactivity = unclaimed.mode === CleanupModes.AFTER_INACTIVITY;
+ const afterLastSession = unclaimed.on_last_session_end === LastSessionCleanupModes.AFTER_GRACE;
+ if (!afterInactivity && !afterLastSession) return null;
+ if (await hasWayBackIn({users: userRepository}, user)) return null;
+ if (afterInactivity && inactiveMs >= daysMs(unclaimed.inactive_days)) {
+ return DeletionReasons.UNCLAIMED_ACCOUNT_ABANDONED;
+ }
+ if (!afterLastSession) return null;
+ const createdAt = snowflakeToDate(BigInt(user.id)).getTime();
+ if (Date.now() - createdAt < AccountCleanupDefaults.MIN_ACCOUNT_AGE_MS) return null;
+ const sessions = await userRepository.listAuthSessions(user.id);
+ return sessions.length === 0 ? DeletionReasons.UNCLAIMED_ACCOUNT_ABANDONED : null;
+}
+
interface ProcessInactivityDeletionsDeps {
+ cleanup: AccountCleanupConfig;
kvClient: IKVProvider;
userRepository: UserRepository;
deletionQueueService: KVAccountDeletionQueueService;
@@ -199,6 +286,7 @@ export async function processInactivityDeletionsCore(
deps: ProcessInactivityDeletionsDeps,
): Promise<InactivityCheckResult> {
const {
+ cleanup,
userRepository,
deletionQueueService,
gatewayService,
@@ -221,6 +309,7 @@ export async function processInactivityDeletionsCore(
await activityTracker.rebuildActivities();
}
const userDeps: ProcessUserDeps = {
+ cleanup,
userRepository,
deletionQueueService,
gatewayService,
@@ -283,6 +372,7 @@ const processInactivityDeletions: WorkerTaskHandler = async (_payload, helpers)
guildRepository,
} = getWorkerDependencies();
await processInactivityDeletionsCore({
+ cleanup: await instanceConfigRepository.getAccountsConfig(),
kvClient,
userRepository,
deletionQueueService,