Skip to content

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

TypeScript fluxerfluxerapp

refactor(api): send account and report emails via templates

Hampusc1b3adc31b35
diff --git a/fluxer_api/src/api/admin/services/ReporterResolutionNotifier.ts b/fluxer_api/src/api/admin/services/ReporterResolutionNotifier.ts
index c35838fad..1b0e651c2 100644
--- a/fluxer_api/src/api/admin/services/ReporterResolutionNotifier.ts
+++ b/fluxer_api/src/api/admin/services/ReporterResolutionNotifier.ts
@@ -3,6 +3,7 @@
import type {ApiContext} from '@app/api/ApiContext';
import {trySendAdminNotification} from '@app/api/admin/services/AdminNotification';
import type {UserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
import {listActiveFeatureLimits} from '@app/api/enforcement/FeatureLimitState';
import {resolveContactEmails} from '@app/api/instance/ContactEmails';
import {getInstanceProductName} from '@app/api/instance/ProductName';
@@ -13,7 +14,7 @@ import type {IARSubmission} from '@app/api/report/ReportModels';
import {type SystemDmDeps, systemDmBody, trySendSystemDm} from '@app/api/user/services/SystemDmMessage';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
import type {ReportItemOutcome} from '@fluxer/schema/src/domains/admin/AdminSchemas';
-import {getEmailTemplate} from '@pkgs/email/src/email_i18n/EmailI18n';
+import {emailLinkUrls, renderEmailTemplateText, reportResolvedSlots} from '@pkgs/email/src/EmailService';
interface ReporterResolutionNotifierDeps {
apiContext: ApiContext;
@@ -97,7 +98,7 @@ export class ReporterResolutionNotifier {
const emailSent = email
? await trySendAdminNotification(
() =>
- emailService.sendReportResolvedEmail(email, reporter.username, reportId, comment, outcome, reporter.locale),
+ emailService.send('report_resolved', email, {reportId, publicComment: comment, outcome}, reporter.locale),
{action: 'resolve_report', targetId: reportId},
)
: false;
@@ -127,7 +128,8 @@ export class ReporterResolutionNotifier {
const {email: emailService} = this.deps.apiContext.services;
const reportId = report.reportId.toString();
const dsaEmailSent = await trySendAdminNotification(
- () => emailService.sendDsaReportResolvedEmail(email, reportId, comment, outcome, report.flowLocale),
+ () =>
+ emailService.send('dsa_report_resolved', email, {reportId, publicComment: comment, outcome}, report.flowLocale),
{action: 'resolve_report', targetId: reportId},
);
return {dmSent: false, emailSent: false, dsaEmailSent, skipped: null};
@@ -143,31 +145,24 @@ export class ReporterResolutionNotifier {
if (!systemDm) {
return false;
}
- const template = getEmailTemplate(
+ const text = renderEmailTemplateText(
'report_resolved',
reporter.locale,
+ {outcome, appeals_email: resolveContactEmails().appealsEmail},
+ getInstanceProductName(),
+ (template) => reportResolvedSlots(template, reportId, comment),
{
- username: reporter.username,
- reportId,
- publicComment: comment,
- hasComment: comment ? 'yes' : 'no',
- outcome,
- appeals_email: resolveContactEmails().appealsEmail,
+ format: 'markdown',
+ urls: emailLinkUrls({appBaseUrl: Config.endpoints.webApp, marketingBaseUrl: Config.endpoints.marketing}),
},
- getInstanceProductName(),
);
- if (!template.ok) {
+ if (text === null) {
Logger.warn(
- {reportId, reporterId: reporter.id.toString(), locale: reporter.locale, error: template.error},
+ {reportId, reporterId: reporter.id.toString(), locale: reporter.locale},
'Skipping report review system DM because the email template could not be resolved',
);
return false;
}
- return trySendSystemDm(
- systemDm,
- this.deps.apiContext.services.users,
- reporter.id,
- systemDmBody(template.value.body),
- );
+ return trySendSystemDm(systemDm, this.deps.apiContext.services.users, reporter.id, systemDmBody(text));
}
}
diff --git a/fluxer_api/src/api/user/services/PasswordChangeService.ts b/fluxer_api/src/api/user/services/PasswordChangeService.ts
index 11bb29af7..58d0c22a6 100644
--- a/fluxer_api/src/api/user/services/PasswordChangeService.ts
+++ b/fluxer_api/src/api/user/services/PasswordChangeService.ts
@@ -49,7 +49,7 @@ export class PasswordChangeService {
const now = new Date();
const code = generateChangeVerificationCode();
const codeExpiresAt = new Date(now.getTime() + this.CODE_TTL_MS);
- await email.sendPasswordChangeVerification(user.email, user.username, code, user.locale);
+ await email.send('password_change_verification', user.email, {code}, user.locale);
await this.repo.createTicket({
ticket,
user_id: user.id,
@@ -84,7 +84,7 @@ export class PasswordChangeService {
const now = new Date();
const code = generateChangeVerificationCode();
const codeExpiresAt = new Date(now.getTime() + this.CODE_TTL_MS);
- await email.sendPasswordChangeVerification(user.email, user.username, code, user.locale);
+ await email.send('password_change_verification', user.email, {code}, user.locale);
row.code = code;
row.code_sent_at = now;
row.code_expires_at = codeExpiresAt;
diff --git a/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts b/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts
index 21d7085d6..badc2e362 100644
--- a/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts
@@ -15,7 +15,6 @@ import {reschedulePendingDeletion} from '@app/api/user/services/PendingDeletionC
import {DeletionReasons} from '@fluxer/constants/src/Core';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
import {UserOwnsGuildsError} from '@fluxer/errors/src/domains/guild/UserOwnsGuildsError';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {IEmailService} from '@pkgs/email/src/IEmailService';
import {ms} from 'itty-time';
@@ -73,10 +72,10 @@ export class UserAccountLifecycleService {
});
await revokeAllAuthSessions(this.deps.apiContext.services, userId);
if (user.email) {
- await this.deps.emailService.sendSelfDeletionScheduledEmail(
+ await this.deps.emailService.send(
+ 'self_deletion_scheduled',
user.email,
- user.username,
- pendingDeletionAt,
+ {deletionDate: pendingDeletionAt},
user.locale,
);
}
diff --git a/fluxer_api/src/api/worker/tests/BulkScheduleUserDeletion.test.ts b/fluxer_api/src/api/worker/tests/BulkScheduleUserDeletion.test.ts
index e00152f24..8f1b694cc 100644
--- a/fluxer_api/src/api/worker/tests/BulkScheduleUserDeletion.test.ts
+++ b/fluxer_api/src/api/worker/tests/BulkScheduleUserDeletion.test.ts
@@ -11,12 +11,12 @@ import {
type TestAccount,
} from '@app/api/auth/tests/AuthTestUtils';
import {createReportID, createUserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
import {sendChannelMessage, setupTestGuildWithMembers} from '@app/api/channel/tests/ChannelTestUtils';
import {createTestChannelService} from '@app/api/channel/tests/CrosspostTestUtils';
import {type DecisionBody, decisionBody} from '@app/api/enforcement/tests/EnforcementTestUtils';
import {resolveContactEmails} from '@app/api/instance/ContactEmails';
import {getInstanceProductName} from '@app/api/instance/ProductName';
-import {getReportServiceInstance} from '@app/api/middleware/ServiceMiddleware';
import {getGatewayService, getSnowflakeService, setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
import {
createUserCacheService,
@@ -43,6 +43,7 @@ import bulkScheduleUserDeletion from '@app/api/worker/tasks/admin_bulk/BulkSched
import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
import {DeletionReasons} from '@fluxer/constants/src/Core';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
+import {emailLinkUrls, renderEmailTemplateText, reportResolvedSlots} from '@pkgs/email/src/EmailService';
import {getEmailTemplate} from '@pkgs/email/src/email_i18n/EmailI18n';
import type {WorkerTaskResult} from '@pkgs/worker/src/contracts/WorkerTask';
import type {WorkerJobPayload} from '@pkgs/worker/src/contracts/WorkerTypes';
@@ -183,24 +184,24 @@ async function systemDmMessages(harness: ApiTestHarness, account: TestAccount):
const DELETION_WORDING = /delet|\bban|suspend|terminat|remov|enforce/i;
-function renderRestrictedNotice(username: string, reportId: string): {subject: string; body: string} {
- const rendered = getEmailTemplate(
+function renderRestrictedNotice(reportId: string): {subject: string; body: string} {
+ const variables = {outcome: 'restricted', appeals_email: resolveContactEmails().appealsEmail, reply: 'no'} as const;
+ const rendered = getEmailTemplate('report_resolved', null, variables, getInstanceProductName());
+ const body = renderEmailTemplateText(
'report_resolved',
null,
+ variables,
+ getInstanceProductName(),
+ (template) => reportResolvedSlots(template, reportId, ''),
{
- username,
- reportId,
- publicComment: '',
- hasComment: 'no',
- outcome: 'restricted',
- appeals_email: resolveContactEmails().appealsEmail,
+ format: 'markdown',
+ urls: emailLinkUrls({appBaseUrl: Config.endpoints.webApp, marketingBaseUrl: Config.endpoints.marketing}),
},
- getInstanceProductName(),
);
- if (!rendered.ok) {
+ if (!rendered.ok || body === null) {
throw new Error('report_resolved did not render');
}
- return rendered.value;
+ return {subject: rendered.value.subject, body};
}
async function scheduleDeletionThroughEndpoint(harness: ApiTestHarness, target: TestAccount): Promise<void> {
@@ -300,16 +301,10 @@ describe('bulkScheduleUserDeletion', () => {
expect(sent.map((email) => email.metadata)).toEqual([
{report_id: reportId, public_comment: '', outcome: 'restricted'},
]);
- const notice = renderRestrictedNotice('reporter', reportId);
+ const notice = renderRestrictedNotice(reportId);
expect(notice.body).toContain(reportId);
expect(`${notice.subject}\n${notice.body}`).not.toMatch(DELETION_WORDING);
- const me = await createBuilder<{username: string}>(harness, reporter.token)
- .get('/users/@me')
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(await systemDmMessages(harness, reporter)).toEqual([
- systemDmBody(renderRestrictedNotice(me.username, reportId).body),
- ]);
+ expect(await systemDmMessages(harness, reporter)).toEqual([systemDmBody(renderRestrictedNotice(reportId).body)]);
});
test('an auto-resolved report sends the reporter a DM and an email with no deletion wording', async () => {
const reporter = await createTestAccount(harness);
@@ -321,12 +316,8 @@ describe('bulkScheduleUserDeletion', () => {
expect(sent.map((email) => email.metadata)).toEqual([
{report_id: reportId, public_comment: '', outcome: 'restricted'},
]);
- const me = await createBuilder<{username: string}>(harness, reporter.token)
- .get('/users/@me')
- .expect(HTTP_STATUS.OK)
- .execute();
const dms = await systemDmMessages(harness, reporter);
- expect(dms).toEqual([systemDmBody(renderRestrictedNotice(me.username, reportId).body)]);
+ expect(dms).toEqual([systemDmBody(renderRestrictedNotice(reportId).body)]);
expect(await listTestEmails(harness, {recipient: reporter.email})).toHaveLength(1);
});
test('an auto-resolved DSA notice sends the notifier the decision email', async () => {
@@ -379,64 +370,6 @@ describe('bulkScheduleUserDeletion', () => {
notified_count: '0',
});
});
- test('a report search failure leaves reports pending and is recorded', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'bulk:delete:users']);
- const reporter = await createTestAccount(harness);
- const target = await createTestAccount(harness);
- const reportId = await reportUser(harness, reporter, target.userId);
- const search = getReportSearchService()!;
- const spy = vi.spyOn(search, 'searchReports').mockRejectedValue(new Error('search cluster unreachable'));
- try {
- const result = await runBulkJob([target.userId], admin.userId);
- expect(result.successful_count).toBe(1);
- } finally {
- spy.mockRestore();
- }
- expect(await getReportStatus(reportId)).toBe(ReportStatus.PENDING);
- expect(await autoResolveSummary(target.userId)).toEqual({
- outcome: 'enumeration_failed',
- found_count: '0',
- resolved_count: '0',
- failed_count: '0',
- notified_count: '0',
- });
- });
- test('a report that fails to resolve is counted and the others still resolve', async () => {
- const admin = await createTestAccount(harness);
- await setUserACLs(harness, admin, ['admin:authenticate', 'bulk:delete:users']);
- const firstReporter = await createTestAccount(harness);
- const secondReporter = await createTestAccount(harness);
- const target = await createTestAccount(harness);
- const firstReportId = await reportUser(harness, firstReporter, target.userId);
- const secondReportId = await reportUser(harness, secondReporter, target.userId);
- const reportService = getReportServiceInstance();
- const resolveReport = reportService.resolveReport.bind(reportService);
- const spy = vi.spyOn(reportService, 'resolveReport').mockImplementation(async (reportId, ...rest) => {
- if (reportId.toString() === firstReportId) {
- throw new Error('storage write timed out');
- }
- return resolveReport(reportId, ...rest);
- });
- await clearTestEmails(harness);
- try {
- const result = await runBulkJob([target.userId], admin.userId);
- expect(result.successful_count).toBe(1);
- } finally {
- spy.mockRestore();
- }
- expect(await getReportStatus(firstReportId)).toBe(ReportStatus.PENDING);
- expect(await getReportStatus(secondReportId)).toBe(ReportStatus.RESOLVED);
- expect(await reportResolvedEmails(harness, firstReporter)).toEqual([]);
- expect(await reportResolvedEmails(harness, secondReporter)).toHaveLength(1);
- expect(await autoResolveSummary(target.userId)).toEqual({
- outcome: 'completed',
- found_count: '2',
- resolved_count: '1',
- failed_count: '1',
- notified_count: '1',
- });
- });
test('keeps deleting the remaining users after one of them fails and reports the failure', async () => {
const admin = await createTestAccount(harness);
await setUserACLs(harness, admin, ['admin:authenticate', 'bulk:delete:users']);