Skip to content

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

TypeScript fluxerfluxerapp

feat(api): email system notices when the instance turns DMs off

Hampus8e6d79199923
diff --git a/fluxer_api/src/api/admin/controllers/ReportAdminController.ts b/fluxer_api/src/api/admin/controllers/ReportAdminController.ts
index a84d6f71c..3a7b84726 100644
--- a/fluxer_api/src/api/admin/controllers/ReportAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/ReportAdminController.ts
@@ -214,7 +214,7 @@ export function ReportAdminController(app: HonoApp) {
operationId: 'update_admin_report',
summary: 'Update report',
description:
- 'Moves a report to the resolved status. resolution is required. actioned also needs the outcome for the reported item, and no_violation sets the outcome no_violation. duplicate needs duplicate_of and takes the outcome stored on that report. The reporter is told the outcome: an account reporter by system DM and email, a Digital Services Act notifier by email. A duplicate of a report with no outcome yet is resolved without telling the reporter. notify_reporter false leaves the public comment out of that notice. Nothing is sent when the reporter account is deleted, or barred from reporting when the report was filed. Creates an audit log entry. Requires REPORT_RESOLVE permission.',
+ 'Moves a report to the resolved status. resolution is required. actioned also needs the outcome for the reported item, and no_violation sets the outcome no_violation. duplicate needs duplicate_of and takes the outcome stored on that report. The reporter is told the outcome: an account reporter by system DM and email, a Digital Services Act notifier by email. The system DM is left out when the instance has direct messages turned off. A duplicate of a report with no outcome yet is resolved without telling the reporter. notify_reporter false leaves the public comment out of that notice. Nothing is sent when the reporter account is deleted, or barred from reporting when the report was filed. Creates an audit log entry. Requires REPORT_RESOLVE permission.',
responseSchema: ResolveReportResponse,
statusCode: 200,
security: 'adminApiKey',
diff --git a/fluxer_api/src/api/admin/controllers/SystemDmAdminController.ts b/fluxer_api/src/api/admin/controllers/SystemDmAdminController.ts
index 28ac4b936..9a9b078d7 100644
--- a/fluxer_api/src/api/admin/controllers/SystemDmAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/SystemDmAdminController.ts
@@ -23,7 +23,7 @@ export function SystemDmAdminController(app: HonoApp) {
security: 'adminApiKey',
tags: 'Admin',
description:
- 'Queue a worker job that delivers the same content to every listed user, or to every user when all_users is set, as a direct message from the system account. Progress is observable through the Jobs admin resource (task_type=sendSystemDm), and an in-flight broadcast is stopped by cancelling that job. Requires SYSTEM_DM_SEND permission.',
+ 'Queue a worker job that delivers the same content to every listed user, or to every user when all_users is set, as a direct message from the system account. Progress is observable through the Jobs admin resource (task_type=sendSystemDm), and an in-flight broadcast is stopped by cancelling that job. Returns 400 DIRECT_MESSAGES_DISABLED when the instance has direct messages turned off, because nobody would see the message. Requires SYSTEM_DM_SEND permission.',
}),
async (ctx) => {
const adminService = ctx.get('adminService');
diff --git a/fluxer_api/src/api/admin/tests/AdminStaffNotifications.test.ts b/fluxer_api/src/api/admin/tests/AdminStaffNotifications.test.ts
index 8e1c6684d..e90128adf 100644
--- a/fluxer_api/src/api/admin/tests/AdminStaffNotifications.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminStaffNotifications.test.ts
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
import {
clearTestEmails,
createTestAccount,
@@ -10,8 +12,12 @@ import {
import {createReportID, createUserID} from '@app/api/BrandedTypes';
import {setupTestGuildWithMembers} from '@app/api/channel/tests/ChannelTestUtils';
import {decisionBody, warn} from '@app/api/enforcement/tests/EnforcementTestUtils';
-import {getAdminRepository, getUserRepository} from '@app/api/middleware/ServiceSingletons';
-import {getReportFlowVariant} from '@app/api/report/flows/ReportFlowRegistry';
+import {
+ getAdminRepository,
+ getInstanceConfigRepository,
+ getUserRepository,
+} from '@app/api/middleware/ServiceSingletons';
+import {getReportFlowResponse} from '@app/api/report/flows/ReportFlowRegistry';
import {ReportRepository} from '@app/api/report/ReportRepository';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
@@ -211,7 +217,7 @@ describe('Admin staff notifications', () => {
ticket,
report_type: 'guild',
guild_id: guild.id,
- revision_hash: getReportFlowVariant('guild', 'dsa').revisionHash,
+ revision_hash: getReportFlowResponse('guild', 'dsa', 'en-US').revision_hash,
steps: [
{screen_id: 'community_parts', item_ids: ['activity']},
{screen_id: 'root_guild', option_id: 'abuse'},
@@ -296,6 +302,19 @@ describe('Admin staff notifications', () => {
expect(sent.map((email) => email.metadata.public_comment)).toEqual(['']);
});
+ test('with DMs off on the instance the reporter hears back by email only', async () => {
+ const {reporter, reportId} = await fileReport();
+ await getInstanceConfigRepository().setInstancePolicyConfig({direct_messages_disabled: true});
+ await clearTestEmails(harness);
+ await resolve(reportId, {public_comment: 'Handled'});
+ const sent = (await emailsTo(reporter)).filter((email) => email.type === 'report_resolved');
+ expect(sent).toHaveLength(1);
+ expect(await systemDmMessages(reporter)).toEqual([]);
+ const metadata = await auditMetadata('resolve_report', reportId);
+ expect(metadata?.get('reporter_dm_sent')).toBe('false');
+ expect(metadata?.get('reporter_email_sent')).toBe('true');
+ });
+
test('a DSA notice emails the verified address and sends no DM', async () => {
const {email, reportId} = await fileDsaGuildNotice();
await clearTestEmails(harness);
@@ -330,7 +349,7 @@ describe('Admin staff notifications', () => {
{report_id: reportId, public_comment: '', outcome: 'action_taken'},
]);
const [dm] = await systemDmMessages(reporter);
- expect(dm?.content).toContain('We found that what you reported broke our rules, and we took action.');
+ expect(dm?.content).toContain('What you reported broke our rules, and we took action.');
expect(dm?.content).not.toMatch(/warn|restricted|suspend/i);
const metadata = await auditMetadata('resolve_report', reportId);
expect(metadata?.get('outcome')).toBe('warned');
diff --git a/fluxer_api/src/api/user/services/SystemDmMessage.ts b/fluxer_api/src/api/user/services/SystemDmMessage.ts
index e7a1397e6..e6f50fbc8 100644
--- a/fluxer_api/src/api/user/services/SystemDmMessage.ts
+++ b/fluxer_api/src/api/user/services/SystemDmMessage.ts
@@ -5,8 +5,10 @@ import type {ChannelService} from '@app/api/channel/services/ChannelService';
import {SYSTEM_USER_ID} from '@app/api/constants/Core';
import {SYSTEM_THREAD_VIEWER} from '@app/api/experiment/ChannelThreadsGate';
import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
+import type {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
import {Logger} from '@app/api/Logger';
import {createRequestCache, type RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import type {User} from '@app/api/models/User';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import type {UserChannelService} from '@app/api/user/services/UserChannelService';
@@ -17,9 +19,21 @@ export interface SystemDmDeps {
userCacheService: UserCacheService;
}
+export async function systemDmsHidden(
+ config: Pick<InstanceConfigRepository, 'getInstancePolicyConfig'> = getInstanceConfigRepository(),
+): Promise<boolean> {
+ return (await config.getInstancePolicyConfig()).direct_messages_disabled;
+}
+
+export async function noticeEmailAddress(
+ user: Pick<User, 'email'>,
+ config: Pick<InstanceConfigRepository, 'isEmailEnabled'> = getInstanceConfigRepository(),
+): Promise<string | null> {
+ return user.email && (await config.isEmailEnabled()) ? user.email : null;
+}
+
export function systemDmBody(emailBody: string): string {
- const body = emailBody.split('\n\n').slice(1, -1).join('\n\n');
- return body.charAt(0).toLocaleUpperCase() + body.slice(1);
+ return emailBody.split('\n\n').slice(0, -1).join('\n\n');
}
export async function sendSystemDmMessage(params: {
@@ -53,6 +67,9 @@ export async function trySendSystemDm(
recipientId: UserID,
content: string,
): Promise<boolean> {
+ if (await systemDmsHidden()) {
+ return false;
+ }
const requestCache = createRequestCache();
try {
await sendSystemDmMessage({
diff --git a/fluxer_api/src/api/worker/tasks/BulkDeleteSelfMessagesImmediate.ts b/fluxer_api/src/api/worker/tasks/BulkDeleteSelfMessagesImmediate.ts
index 8e5579abd..ffcb4a7d6 100644
--- a/fluxer_api/src/api/worker/tasks/BulkDeleteSelfMessagesImmediate.ts
+++ b/fluxer_api/src/api/worker/tasks/BulkDeleteSelfMessagesImmediate.ts
@@ -4,6 +4,7 @@ import {createUserID} from '@app/api/BrandedTypes';
import {loadSelfMessageEligibilityContext} from '@app/api/channel/services/message/SelfMessageFilter';
import {getContentMessage} from '@app/api/content_i18n/ContentI18n';
import {Logger} from '@app/api/Logger';
+import {noticeEmailAddress, systemDmsHidden} from '@app/api/user/services/SystemDmMessage';
import {deserializeSelfMessageFilter, SelfMessageFilterPayload} from '@app/api/worker/utils/SelfMessageFilterPayload';
import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
@@ -17,7 +18,8 @@ const bulkDeleteSelfMessagesImmediate: WorkerTaskHandler = async (payload, helpe
const validated = PayloadSchema.parse(payload);
helpers.logger.debug({payload: validated}, 'Processing bulkDeleteSelfMessagesImmediate task');
const userId = createUserID(BigInt(validated.userId));
- const {channelService, userRepository, guildRepository, workerService} = getWorkerDependencies();
+ const {channelService, userRepository, guildRepository, workerService, instanceConfigRepository, emailService} =
+ getWorkerDependencies();
const user = await userRepository.findUnique(userId);
if (!user) {
helpers.logger.info({userId: validated.userId}, 'User no longer exists, skipping deletion');
@@ -35,10 +37,15 @@ const bulkDeleteSelfMessagesImmediate: WorkerTaskHandler = async (payload, helpe
{userId: userId.toString(), totalDeleted: result.totalDeleted, channelCount: result.channelCount},
'Filtered bulk self message deletion completed',
);
- const content = getContentMessage('bulk_message_deletion.complete', user.locale, {
- message_count: result.totalDeleted,
- channel_count: result.channelCount,
- });
+ const totals = {message_count: result.totalDeleted, channel_count: result.channelCount};
+ if (await systemDmsHidden(instanceConfigRepository)) {
+ const email = await noticeEmailAddress(user, instanceConfigRepository);
+ if (email) {
+ await emailService.send('bulk_message_deletion_completed', email, totals, user.locale);
+ }
+ return;
+ }
+ const content = getContentMessage('bulk_message_deletion.complete', user.locale, totals);
if (content && content.length > 0) {
await workerService.addJob(
'sendSystemDm',