Skip to content

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

TypeScript fluxerfluxerapp

feat(api/admin): allow immediate user deletion on self-hosted

Hampusa9257b566f62
diff --git a/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts b/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts
index adb6a9b03..f3dcbc965 100644
--- a/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts
@@ -54,7 +54,6 @@ import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidat
import {NoPendingDeletionError} from '@fluxer/errors/src/domains/core/NoPendingDeletionError';
import {EnforcementDecisionOwnsStateError} from '@fluxer/errors/src/domains/moderation/EnforcementDecisionOwnsStateError';
import {ReportAlreadyResolvedError} from '@fluxer/errors/src/domains/moderation/ReportAlreadyResolvedError';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {
AdminUserDeletionCancelRequest,
AdminUserDeletionScheduleRequest,
@@ -179,7 +178,11 @@ export class AdminUserDeletionService {
);
}
}
- const days = resolveDeletionDays(basis.type, request.days_until_deletion);
+ const immediate = request.immediate === true;
+ if (immediate && !Config.instance.selfHosted) {
+ throw InputValidationError.create('immediate', 'Immediate deletion is only available on self-hosted instances');
+ }
+ const days = immediate ? 0 : resolveDeletionDays(basis.type, request.days_until_deletion);
const scheduledAt = new Date();
const pendingDeletionAt = new Date(scheduledAt);
pendingDeletionAt.setDate(pendingDeletionAt.getDate() + days);
@@ -219,7 +222,10 @@ export class AdminUserDeletionService {
await this.cancelSubscription(user, actor.adminUserId);
await this.deps.storeEntitlementService.revokeForBannedUser(userId);
const notificationSent =
- basis.type === 'enforcement' ? null : await this.sendScheduledEmail(user, basis.type, pendingDeletionAt);
+ basis.type === 'enforcement' || immediate
+ ? null
+ : await this.sendScheduledEmail(user, basis.type, pendingDeletionAt);
+ const notificationSentValue = notificationSent ? 'true' : 'false';
await this.deps.auditService.createAuditLog({
adminUserId: actor.adminUserId,
targetType: 'user',
@@ -231,10 +237,11 @@ export class AdminUserDeletionService {
['days', days.toString()],
['reason_code', closed.deletionReasonCode?.toString() ?? ''],
['pending_deletion_at', pendingDeletionAt.toISOString()],
+ ...(immediate ? ([['immediate', 'true']] as Array<[string, string]>) : []),
...describePendingDeletion(user, 'replaced'),
...(recorded
? [...decisionAuditMetadata(recorded.decision), ...networkBlockAuditMetadata(recorded)]
- : ([['notification_sent', notificationSent ? 'true' : 'false']] as Array<[string, string]>)),
+ : ([['notification_sent', notificationSentValue]] as Array<[string, string]>)),
]),
});
const decision = recorded?.decision ?? null;
@@ -247,6 +254,13 @@ export class AdminUserDeletionService {
ips: knownIps,
});
await propagateUserUpdate(this.deps.userUpdateDeps, user, closed);
+ if (immediate) {
+ await this.deps.apiContext.services.worker.addJob('userProcessPendingDeletion', {
+ userId: userId.toString(),
+ deletionReasonCode: closed.deletionReasonCode ?? BASIS_DELETION_REASONS.housekeeping,
+ pendingDeletionAt: pendingDeletionAt.toISOString(),
+ });
+ }
return {user: closed, skippedNetworks: recorded?.skippedNetworks ?? []};
}
@@ -287,14 +301,6 @@ export class AdminUserDeletionService {
return {user: await mapUserToAdminResponse(cancelled, cache, actor.acls)};
}
- private async requireUser(userId: UserID): Promise<User> {
- const user = await this.deps.apiContext.services.users.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
- return user;
- }
-
private async writeClosure(
user: User,
params: {
@@ -340,8 +346,8 @@ export class AdminUserDeletionService {
return trySendAdminNotification(
() =>
basis === 'holder_request'
- ? emailService.sendAccountDeletionRequestedEmail(email, user.username, date, user.locale)
- : emailService.sendAccountDeletionInactivityEmail(email, user.username, date, user.locale),
+ ? emailService.send('account_deletion_scheduled_requested', email, {deletionDate: date}, user.locale)
+ : emailService.send('account_deletion_scheduled_inactivity', email, {deletionDate: date}, user.locale),
{action: 'schedule_deletion', targetId: user.id.toString()},
);
}
@@ -350,10 +356,10 @@ export class AdminUserDeletionService {
const {email: emailService} = this.deps.apiContext.services;
const email = user.email;
if (!email) return;
- await trySendAdminNotification(
- () => emailService.sendAccountDeletionCancelledEmail(email, user.username, user.locale),
- {action: 'cancel_deletion', targetId: user.id.toString()},
- );
+ await trySendAdminNotification(() => emailService.send('account_deletion_cancelled', email, {}, user.locale), {
+ action: 'cancel_deletion',
+ targetId: user.id.toString(),
+ });
}
private async banIdentifiers(
diff --git a/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts b/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts
new file mode 100644
index 000000000..c9892e584
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createTestAccount, listTestEmails, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {getConfig} from '@app/api/Config';
+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 {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+
+describe('immediate account deletion from the admin panel', () => {
+ let harness: ApiTestHarness;
+ let admin: TestAccount;
+ const selfHosted = getConfig().instance.selfHosted;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+
+ beforeEach(async () => {
+ await harness.reset();
+ admin = await setUserACLs(harness, await createTestAccount(harness), [
+ AdminACLs.AUTHENTICATE,
+ AdminACLs.USER_DELETE,
+ AdminACLs.AUDIT_LOG_VIEW,
+ ]);
+ });
+
+ afterEach(() => {
+ getConfig().instance.selfHosted = selfHosted;
+ });
+
+ afterAll(async () => {
+ await harness.shutdown();
+ });
+
+ function deleteNow(target: TestAccount) {
+ return createBuilder<{user: {pending_deletion_at: string | null}}>(harness, admin.token)
+ .put(`/admin/users/${target.userId}/deletion`)
+ .body({days_until_deletion: 14, basis: {type: 'holder_request'}, immediate: true});
+ }
+
+ it('deletes the account at once on a self-hosted instance', async () => {
+ getConfig().instance.selfHosted = true;
+ const target = await createTestAccount(harness);
+ const before = Date.now();
+ const response = await deleteNow(target).expect(HTTP_STATUS.OK).execute();
+ expect(Date.parse(response.user.pending_deletion_at!)).toBeLessThanOrEqual(Date.now());
+ expect(Date.parse(response.user.pending_deletion_at!)).toBeGreaterThanOrEqual(before - 1000);
+ await triggerDeletionWorker(harness);
+ await waitForDeletionCompletion(harness, target.userId, 20000);
+ const emails = await listTestEmails(harness, {recipient: target.email});
+ expect(emails.filter((email) => email.type === 'account_deletion_requested')).toEqual([]);
+ });
+
+ it('keeps the waiting period on the hosted instance', async () => {
+ getConfig().instance.selfHosted = false;
+ const target = await createTestAccount(harness);
+ await deleteNow(target).expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_FORM_BODY).execute();
+ });
+
+ it('keeps the 14 day floor when immediate is not asked for', async () => {
+ getConfig().instance.selfHosted = true;
+ const target = await createTestAccount(harness);
+ const response = await createBuilder<{user: {pending_deletion_at: string}}>(harness, admin.token)
+ .put(`/admin/users/${target.userId}/deletion`)
+ .body({days_until_deletion: 1, basis: {type: 'holder_request'}})
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ expect(Date.parse(response.user.pending_deletion_at) - Date.now()).toBeGreaterThan(13 * 24 * 3600 * 1000);
+ });
+});