Skip to content

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

TypeScript fluxerfluxerapp

feat(api/reports): let unverified accounts report, capped daily

Hampus7e6b4a5cbf0e
diff --git a/fluxer_api/src/api/report/LimitedReporterPolicy.ts b/fluxer_api/src/api/report/LimitedReporterPolicy.ts
new file mode 100644
index 000000000..a2107934b
--- /dev/null
+++ b/fluxer_api/src/api/report/LimitedReporterPolicy.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {type BudgetEnv, ipKey} from '@app/api/auth/AccountBudgets';
+import type {User} from '@app/api/models/User';
+import {getAccountTier, isInteractionTierEnforced} from '@app/api/user/AccountTier';
+import {createRateLimitError} from '@app/api/utils/RateLimitUtils';
+import {getSubnet} from '@fluxer/ip_utils/src/IpAddress';
+
+const DAY_SECONDS = 86400;
+const ACCOUNT_REPORTS_PER_DAY = 5;
+const IP_REPORTS_PER_DAY = 10;
+
+type LimitedReportTargetType = 'message' | 'user' | 'guild';
+
+export interface LimitedReportTarget {
+ type: LimitedReportTargetType;
+ id: bigint;
+}
+
+function dedupeKey(clientIp: string, target: LimitedReportTarget): string {
+ return `report:dedupe:${getSubnet(clientIp) ?? ipKey(clientIp)}:${target.type}:${target.id}`;
+}
+
+export function isLimitedReporter(user: User): boolean {
+ return isInteractionTierEnforced() && getAccountTier(user) !== 'verified';
+}
+
+export async function admitLimitedReport(
+ env: BudgetEnv,
+ params: {user: User; clientIp: string; target: LimitedReportTarget},
+): Promise<'store' | 'drop'> {
+ const {user, clientIp, target} = params;
+ for (const [identifier, maxAttempts] of [
+ [`report:limited:user:${user.id}`, ACCOUNT_REPORTS_PER_DAY],
+ [`report:limited:ip:${ipKey(clientIp)}`, IP_REPORTS_PER_DAY],
+ ] as const) {
+ const result = await env.rateLimit.checkLimit({identifier, maxAttempts, windowMs: DAY_SECONDS * 1000});
+ if (!result.allowed && env.enforce) throw createRateLimitError(result);
+ }
+ const stored = await env.kv.setnx(dedupeKey(clientIp, target), '1', DAY_SECONDS);
+ return stored ? 'store' : 'drop';
+}
diff --git a/fluxer_api/src/api/report/ReportController.ts b/fluxer_api/src/api/report/ReportController.ts
index c5031ef47..bdd408190 100644
--- a/fluxer_api/src/api/report/ReportController.ts
+++ b/fluxer_api/src/api/report/ReportController.ts
@@ -77,6 +77,7 @@ export function ReportController(app: HonoApp) {
return ctx.json(
await ctx.get('reportRequestService').submitMessageReportFlow({
user: ctx.get('user'),
+ request: ctx.req.raw,
viewer: viewerFromCtx(ctx),
data: ctx.req.valid('json'),
locale: ctx.get('requestLocale') ?? null,
@@ -103,6 +104,7 @@ export function ReportController(app: HonoApp) {
return ctx.json(
await ctx.get('reportRequestService').submitUserReportFlow({
user: ctx.get('user'),
+ request: ctx.req.raw,
data: ctx.req.valid('json'),
locale: ctx.get('requestLocale') ?? null,
}),
@@ -129,6 +131,7 @@ export function ReportController(app: HonoApp) {
return ctx.json(
await ctx.get('reportRequestService').reportMessage({
user: ctx.get('user'),
+ request: ctx.req.raw,
viewer: viewerFromCtx(ctx),
data: ctx.req.valid('json'),
}),
@@ -154,6 +157,7 @@ export function ReportController(app: HonoApp) {
return ctx.json(
await ctx.get('reportRequestService').reportUser({
user: ctx.get('user'),
+ request: ctx.req.raw,
data: ctx.req.valid('json'),
}),
);
@@ -178,6 +182,7 @@ export function ReportController(app: HonoApp) {
return ctx.json(
await ctx.get('reportRequestService').reportGuild({
user: ctx.get('user'),
+ request: ctx.req.raw,
data: ctx.req.valid('json'),
}),
);
diff --git a/fluxer_api/src/api/report/ReportRequestService.ts b/fluxer_api/src/api/report/ReportRequestService.ts
index ba4b372eb..e43b743b7 100644
--- a/fluxer_api/src/api/report/ReportRequestService.ts
+++ b/fluxer_api/src/api/report/ReportRequestService.ts
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {requireEmailVerified} from '@app/api/auth/EmailVerificationUtils';
+import {type BudgetEnv, budgetEnvFor} from '@app/api/auth/AccountBudgets';
import {createChannelID, createGuildID, createInviteCode, createMessageID, createUserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
import type {ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';
import {Logger} from '@app/api/Logger';
import type {User} from '@app/api/models/User';
@@ -10,9 +11,12 @@ import {
resolveReportFlowAnswers,
resolveReportFlowLocale,
} from '@app/api/report/flows/ReportFlowRegistry';
-import {type ReportStatus, reportStatusToString} from '@app/api/report/ReportModels';
+import {admitLimitedReport, isLimitedReporter, type LimitedReportTarget} from '@app/api/report/LimitedReporterPolicy';
+import {ReportStatus, reportStatusToString} from '@app/api/report/ReportModels';
import type {ReportFlowRecord, ReportService} from '@app/api/report/ReportService';
-import {UnclaimedAccountCannotSubmitReportsError} from '@fluxer/errors/src/domains/moderation/UnclaimedAccountCannotSubmitReportsError';
+import {assertTierAllows, getAccountTier, NO_TIER_CONTEXT} from '@app/api/user/AccountTier';
+import {TierGatedActions} from '@fluxer/constants/src/AccountTierConstants';
+import {requireClientIp} from '@fluxer/ip_utils/src/ClientIp';
import type {
ReportFlowMessageSubmissionRequest,
ReportFlowResponse,
@@ -31,10 +35,12 @@ import type {
ReportUserRequest,
TicketResponse,
} from '@fluxer/schema/src/domains/report/ReportSchemas';
+import {createSnowflakeFromTimestamp} from '@fluxer/snowflake/src/Snowflake';
interface ReportUserRequestContext<T> {
user: User;
data: T;
+ request: Request;
}
interface ReportDsaRequestContext<T> {
@@ -46,6 +52,7 @@ interface ReportFlowSubmissionContext<T> {
user: User;
data: T;
locale: string | null;
+ request: Request;
}
interface ReportFlowAnswersInput {
@@ -61,14 +68,19 @@ interface ReportRecord {
}
export class ReportRequestService {
- constructor(private reportService: ReportService) {}
+ constructor(
+ private reportService: ReportService,
+ private readonly budgetServices: Pick<BudgetEnv, 'kv' | 'rateLimit'>,
+ ) {}
async reportMessage({
user,
viewer,
data,
+ request,
}: ReportUserRequestContext<ReportMessageRequest> & {viewer: ThreadViewer}): Promise<ReportResponse> {
- this.requireVerifiedAccount(user);
+ const admission = await this.admitReporter(user, request, {type: 'message', id: BigInt(data.message_id)});
+ if (admission) return admission;
const report = await this.reportService.reportMessage(
this.createReporter(user),
viewer,
@@ -79,8 +91,9 @@ export class ReportRequestService {
return this.toReportResponse(report);
}
- async reportUser({user, data}: ReportUserRequestContext<ReportUserRequest>): Promise<ReportResponse> {
- this.requireVerifiedAccount(user);
+ async reportUser({user, data, request}: ReportUserRequestContext<ReportUserRequest>): Promise<ReportResponse> {
+ const admission = await this.admitReporter(user, request, {type: 'user', id: BigInt(data.user_id)});
+ if (admission) return admission;
const report = await this.reportService.reportUser(
this.createReporter(user),
createUserID(data.user_id),
@@ -90,8 +103,9 @@ export class ReportRequestService {
return this.toReportResponse(report);
}
- async reportGuild({user, data}: ReportUserRequestContext<ReportGuildRequest>): Promise<ReportResponse> {
- this.requireVerifiedAccount(user);
+ async reportGuild({user, data, request}: ReportUserRequestContext<ReportGuildRequest>): Promise<ReportResponse> {
+ const admission = await this.admitReporter(user, request, {type: 'guild', id: BigInt(data.guild_id)});
+ if (admission) return admission;
const report = await this.reportService.reportGuild(
this.createReporter(user),
createGuildID(data.guild_id),
@@ -114,10 +128,12 @@ export class ReportRequestService {
viewer,
data,
locale,
+ request,
}: ReportFlowSubmissionContext<ReportFlowMessageSubmissionRequest> & {
viewer: ThreadViewer;
}): Promise<ReportResponse> {
- this.requireVerifiedAccount(user);
+ const admission = await this.admitReporter(user, request, {type: 'message', id: BigInt(data.message_id)});
+ if (admission) return admission;
const flow = this.resolveInAppFlow('message', data, locale);
const report = await this.reportService.reportMessage(
this.createReporter(user),
@@ -134,8 +150,10 @@ export class ReportRequestService {
user,
data,
locale,
+ request,
}: ReportFlowSubmissionContext<ReportFlowUserSubmissionRequest>): Promise<ReportResponse> {
- this.requireVerifiedAccount(user);
+ const admission = await this.admitReporter(user, request, {type: 'user', id: BigInt(data.user_id)});
+ if (admission) return admission;
const flow = this.resolveInAppFlow('user', data, locale);
const report = await this.reportService.reportUser(
this.createReporter(user),
@@ -193,11 +211,27 @@ export class ReportRequestService {
};
}
- private requireVerifiedAccount(user: User): void {
- if (user.isUnclaimedAccount()) {
- throw new UnclaimedAccountCannotSubmitReportsError();
+ private async admitReporter(
+ user: User,
+ request: Request,
+ target: LimitedReportTarget,
+ ): Promise<ReportResponse | null> {
+ if (!isLimitedReporter(user)) {
+ assertTierAllows(user, TierGatedActions.REPORT, NO_TIER_CONTEXT);
+ return null;
}
- requireEmailVerified(user, 'report');
+ const clientIp = requireClientIp(request, {
+ trustClientIpHeader: Config.proxy.trust_client_ip_header,
+ clientIpHeaderName: Config.proxy.client_ip_header,
+ });
+ const env = budgetEnvFor(this.budgetServices, request);
+ if ((await admitLimitedReport(env, {user, clientIp, target})) === 'store') return null;
+ const now = Date.now();
+ return {
+ report_id: createSnowflakeFromTimestamp(now).toString(),
+ status: reportStatusToString(ReportStatus.PENDING),
+ reported_at: new Date(now).toISOString(),
+ };
}
private createReporter(user: User) {
@@ -206,6 +240,7 @@ export class ReportRequestService {
email: user.email,
fullLegalName: null,
countryOfResidence: null,
+ tier: getAccountTier(user),
};
}
diff --git a/fluxer_api/src/api/report/ReportService.ts b/fluxer_api/src/api/report/ReportService.ts
index d5afaf736..448d02866 100644
--- a/fluxer_api/src/api/report/ReportService.ts
+++ b/fluxer_api/src/api/report/ReportService.ts
@@ -37,8 +37,14 @@ import {isDecisionExpired} from '@app/api/enforcement/DecisionStatus';
import {listActiveFeatureLimits} from '@app/api/enforcement/FeatureLimitState';
import type {ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
+import {channelToVisitorInput} from '@app/api/guild/visits/GuildVisitorAccess';
import {emitActivity} from '@app/api/infrastructure/activity/ActivityEvents';
-import type {ReportOutcome, ReportTarget, ResolvedBy} from '@app/api/infrastructure/activity/Contract.generated';
+import type {
+ ReporterTier,
+ ReportOutcome,
+ ReportTarget,
+ ResolvedBy,
+} from '@app/api/infrastructure/activity/Contract.generated';
import {emitReportResolved} from '@app/api/infrastructure/activity/ModerationEvents';
import type {EmailDnsValidationService} from '@app/api/infrastructure/EmailDnsValidationService';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
@@ -75,6 +81,10 @@ import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ME} from '@fluxer/constants/src/AppConstants';
import {InviteTypes, MessageFlags, Permissions} from '@fluxer/constants/src/ChannelConstants';
import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
+import {
+ computeGuildVisitorChannelPermissions,
+ GUILD_VISITOR_PERMISSIONS_MASK,
+} from '@fluxer/constants/src/GuildVisitConstants';
import {DELETED_USER_USERNAME, UserFlags} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {CannotReportOwnMessageError} from '@fluxer/errors/src/domains/channel/CannotReportOwnMessageError';
@@ -117,6 +127,7 @@ interface ReporterMetadata {
email: string | null;
fullLegalName: string | null;
countryOfResidence: string | null;
+ tier?: ReporterTier;
}
export interface ReportFlowRecord {
@@ -247,9 +258,12 @@ const DSA_EMAIL_SEND_RECIPIENT_WINDOW = ms('1 hour');
const DSA_EMAIL_RESEND_COOLDOWN = ms('1 minute');
const DSA_EMAIL_VERIFY_ADDRESS_MAX = 5;
const DSA_EMAIL_VERIFY_ADDRESS_WINDOW = ms('10 minutes');
-const PUBLIC_CHANNEL_PERMISSIONS = Permissions.VIEW_CHANNEL | Permissions.READ_MESSAGE_HISTORY;
-async function emitReportFiled(row: IARSubmissionRow, target: ReportTarget): Promise<void> {
+async function emitReportFiled(
+ row: IARSubmissionRow,
+ target: ReportTarget,
+ reporterTier: ReporterTier = 'verified',
+): Promise<void> {
const key = row.reported_user_id ?? row.reporter_id ?? 0n;
await emitActivity(
'report_filed',
@@ -257,6 +271,7 @@ async function emitReportFiled(row: IARSubmissionRow, target: ReportTarget): Pro
{
report_id: row.report_id.toString(),
reporter_id: (row.reporter_id ?? 0n).toString(),
+ reporter_tier: reporterTier,
category: row.category,
target_type: target,
reported_user_id: row.reported_user_id?.toString() ?? null,
@@ -380,7 +395,7 @@ export class ReportService {
memberGuildId: channel.guildId,
});
const report = await this.reportRepository.createReport(reportData);
- await emitReportFiled(reportData, 'message');
+ await emitReportFiled(reportData, 'message', reporter.tier);
await this.reportSearchService?.indexReport(report).catch((error) => {
Logger.error({error, reportId: report.reportId}, 'Failed to index message report in search');
});
@@ -408,8 +423,10 @@ export class ReportService {
if (reporter.id && reportedUserId === reporter.id) {
throw new CannotReportYourselfError();
}
- const reportedUser = await this.userRepository.findUnique(reportedUserId);
- if (!reportedUser || isSyntheticUserId(reportedUserId)) {
+ const reportedUser = isSyntheticUserId(reportedUserId)
+ ? null
+ : await this.userRepository.findUnique(reportedUserId);
+ if (!reportedUser || reportedUser.isSystem) {
throw new UnknownUserError();
}
const reportId = createReportID(await this.snowflakeService.generate());
@@ -464,7 +481,7 @@ export class ReportService {
memberGuildId: guildId,
});
const report = await this.reportRepository.createReport(reportData);
- await emitReportFiled(reportData, 'user');
+ await emitReportFiled(reportData, 'user', reporter.tier);
await this.reportSearchService?.indexReport(report).catch((error) => {
Logger.error({error, reportId: report.reportId}, 'Failed to index user report in search');
});
@@ -545,7 +562,7 @@ export class ReportService {
await this.ensureReportRateLimit(rateLimitIdentifier, REPORT_RATE_LIMIT_MAX, true);
reportData.reported_profile_snapshot = await this.captureProfileSnapshot(reportId, {guild});
const report = await this.reportRepository.createReport(reportData);
- await emitReportFiled(reportData, 'guild');
+ await emitReportFiled(reportData, 'guild', reporter.tier);
await this.reportSearchService?.indexReport(report).catch((error) => {
Logger.error({error, reportId: report.reportId}, 'Failed to index guild report in search');
});
@@ -616,10 +633,10 @@ export class ReportService {
last_sent_at: new Date(),
});
await this.rateLimitService.resetLimit(this.createDsaVerifyAttemptIdentifier(normalizedEmail));
- const sent = await this.emailService.sendDsaReportVerificationCode(
+ const sent = await this.emailService.send(
+ 'dsa_report_verification',
normalizedEmail,
- verificationCode,
- expiresAt,
+ {code: verificationCode, expiresAt},
locale,
);
if (!sent) {
@@ -737,7 +754,12 @@ export class ReportService {
locale: string | null,
): Promise<void> {
try {
- const sent = await this.emailService.sendReportReceivedEmail(email, reportId.toString(), targetKind, locale);
+ const sent = await this.emailService.send(
+ 'report_received',
+ email,
+ {reportId: reportId.toString(), targetKind},
+ locale,
+ );
if (!sent) {
Logger.warn({template: 'report_received', reportId}, 'DSA report receipt was not sent');
}
@@ -999,6 +1021,7 @@ export class ReportService {
userId: reporterId,
channelId,
viewer,
+ access: 'visitor_read',
});
if (!(await this.canAccessMessage(authChannel, messageId))) {
throw new UnknownMessageError();
@@ -1179,14 +1202,14 @@ export class ReportService {
if (!everyoneRole) {
return false;
}
- if ((everyoneRole.permissions & Permissions.ADMINISTRATOR) !== 0n) {
- return true;
- }
- const overwrite = channel.permissionOverwrites.get(everyoneRole.id);
- const permissions = overwrite
- ? (everyoneRole.permissions & ~overwrite.deny) | overwrite.allow
- : everyoneRole.permissions;
- return (permissions & PUBLIC_CHANNEL_PERMISSIONS) === PUBLIC_CHANNEL_PERMISSIONS;
+ const permissions = computeGuildVisitorChannelPermissions({
+ guildId: channel.guildId.toString(),
+ everyonePermissions: everyoneRole.permissions,
+ guildNsfw: false,
+ channel: channelToVisitorInput(channel),
+ adultContentAllowed: true,
+ });
+ return (permissions & GUILD_VISITOR_PERMISSIONS_MASK) === GUILD_VISITOR_PERMISSIONS_MASK;
}
private async readDsaTicket(ticket: string): Promise<DSAReportTicketRow> {