Skip to content

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

TypeScript fluxerfluxerapp

feat(api): close and email-ban accounts after lost chargebacks

Hampusff399f2bd0da
diff --git a/fluxer_api/src/api/admin/AdminService.ts b/fluxer_api/src/api/admin/AdminService.ts
index 3b3a8cd0b..ba0862043 100644
--- a/fluxer_api/src/api/admin/AdminService.ts
+++ b/fluxer_api/src/api/admin/AdminService.ts
@@ -38,13 +38,21 @@ import {
getEnforcementDecisionRepository,
getGuildDiscoveryRepository,
getKVAccountDeletionQueue,
+ getOAuth2TokenRepository,
+ getPaymentDisputeRepository,
getReportRepository,
} from '@app/api/middleware/ServiceSingletons';
import type {ApplicationRepository} from '@app/api/oauth/repositories/ApplicationRepository';
+import {
+ PaymentDisputeEnforcementService,
+ queuePaymentDisputeClosures,
+} from '@app/api/payment_disputes/PaymentDisputeEnforcement';
import type {ReportService} from '@app/api/report/ReportService';
import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';
+import {systemDmsHidden} from '@app/api/user/services/SystemDmMessage';
import type {UserService} from '@app/api/user/services/UserService';
import type {VoiceRepository} from '@app/api/voice/VoiceRepository';
+import {DirectMessagesDisabledError} from '@fluxer/errors/src/domains/channel/DirectMessagesDisabledError';
import type {SendSystemDmResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
import type Stripe from 'stripe';
@@ -66,6 +74,7 @@ export class AdminService {
readonly applicationService: AdminApplicationService;
readonly jobAdminService: JobAdminService;
readonly relationshipService: AdminUserRelationshipService;
+ readonly paymentDisputeEnforcement: PaymentDisputeEnforcementService;
constructor(
private readonly apiContext: ApiContext,
@@ -152,6 +161,7 @@ export class AdminService {
guildRepository: this.guildRepository,
reportService: this.reportService,
adminReportService: this.reportServiceAggregate,
+ onClosureEnded: queuePaymentDisputeClosures,
});
this.guildServiceAggregate = new AdminGuildService({
guildRepository: this.guildRepository,
@@ -176,6 +186,19 @@ export class AdminService {
auditService: this.auditService,
enforcement: this.enforcementService,
});
+ this.paymentDisputeEnforcement = new PaymentDisputeEnforcementService({
+ repository: getPaymentDisputeRepository(),
+ userRepository: users,
+ userCacheService: this.userCacheService,
+ emailService: this.apiContext.services.email,
+ cacheService: this.apiContext.services.cache,
+ gatewayService: gateway,
+ auditService: this.auditService,
+ kvDeletionQueue: getKVAccountDeletionQueue(),
+ oauth2Tokens: getOAuth2TokenRepository(),
+ systemDm,
+ enforcement: this.enforcementService,
+ });
this.userService = new AdminUserService({
apiContext: this.apiContext,
guildRepository: this.guildRepository,
@@ -223,6 +246,7 @@ export class AdminService {
this.relationshipService = new AdminUserRelationshipService({
apiContext: this.apiContext,
auditService: this.auditService,
+ userRelationshipService: this.runtimeUserService.relationshipService,
});
}
@@ -231,6 +255,9 @@ export class AdminService {
adminUserId: UserID,
auditLogReason: string | null,
): Promise<SendSystemDmResponse> {
+ if (await systemDmsHidden()) {
+ throw new DirectMessagesDisabledError();
+ }
const recipientCount = data.recipients.kind === 'all' ? null : data.recipients.userIds.length;
await this.apiContext.services.worker.addJob(
'sendSystemDm',
diff --git a/fluxer_api/src/api/admin/controllers/PaymentDisputeAdminController.ts b/fluxer_api/src/api/admin/controllers/PaymentDisputeAdminController.ts
new file mode 100644
index 000000000..721d28369
--- /dev/null
+++ b/fluxer_api/src/api/admin/controllers/PaymentDisputeAdminController.ts
@@ -0,0 +1,193 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {AdminAuditReadActions} from '@app/api/admin/AdminAuditActions';
+import {recordAdminRead, recordAdminWrite} from '@app/api/admin/AdminAuditRecorder';
+import type {PaymentDisputeReviewRow} from '@app/api/database/types/PaymentDisputeTypes';
+import {enforcementActor} from '@app/api/enforcement/EnforcementActor';
+import {requireAdminACL} from '@app/api/middleware/AdminMiddleware';
+import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
+import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
+import {getPaymentDisputeRepository, getUserRepository} from '@app/api/middleware/ServiceSingletons';
+import {
+ getClosuresAwaited,
+ getPaymentDisputeWarningDeadline,
+} from '@app/api/payment_disputes/PaymentDisputeEnforcement';
+import {
+ getPaymentDisputeReviewBlockers,
+ isPaymentDisputeOpen,
+ listPaymentDisputeReviews,
+} from '@app/api/payment_disputes/PaymentDisputeReviews';
+import {RateLimitConfigs} from '@app/api/RateLimitConfig';
+import type {HonoApp} from '@app/api/types/HonoEnv';
+import {Validator} from '@app/api/Validator';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {
+ AdminPaymentDisputeDecisionRequest,
+ AdminPaymentDisputeIdParam,
+ AdminPaymentDisputeReversalRequest,
+ AdminPaymentDisputeReviewListResponse,
+ AdminPaymentDisputeReviewResponse,
+} from '@fluxer/schema/src/domains/admin/AdminPaymentDisputeSchemas';
+
+const TAG = 'Admin';
+
+function mapReview(
+ review: PaymentDisputeReviewRow,
+ now: Date,
+ awaitedDecisionId: bigint | null,
+): AdminPaymentDisputeReviewResponse {
+ const blockers = getPaymentDisputeReviewBlockers(review);
+ const unreviewed = review.status === 'open' && isPaymentDisputeOpen(review);
+ const warningDeadline =
+ review.warning_deadline ?? (unreviewed ? getPaymentDisputeWarningDeadline(review.evidence_due_by, now) : null);
+ return {
+ dispute_id: review.dispute_id,
+ product: review.product,
+ order_id: review.order_id,
+ invoice_number: review.invoice_number ?? null,
+ purchaser_id: review.purchaser_id.toString(),
+ is_gift: review.is_gift,
+ reason: review.reason,
+ amount_minor: review.amount_minor,
+ currency: review.currency,
+ evidence_submitted: review.evidence_submitted,
+ evidence_due_by: review.evidence_due_by?.toISOString() ?? null,
+ disputed_at: review.disputed_at?.toISOString() ?? null,
+ closed_at: review.closed_at?.toISOString() ?? null,
+ outcome: review.outcome ?? null,
+ purchased_at: review.purchased_at?.toISOString() ?? null,
+ perks_started_at: review.perks_started_at?.toISOString() ?? null,
+ withdrawal_ends_at: review.withdrawal_ends_at?.toISOString() ?? null,
+ withdrawn_at: review.withdrawn_at?.toISOString() ?? null,
+ refunded_at: review.refunded_at?.toISOString() ?? null,
+ perks_removed_at: review.perks_removed_at?.toISOString() ?? null,
+ status: review.status,
+ blockers,
+ warnable: unreviewed && blockers.length === 0 && warningDeadline !== null,
+ warning_deadline: warningDeadline?.toISOString() ?? null,
+ warning_email_sent_at: review.warning_email_sent_at?.toISOString() ?? null,
+ warning_dm_sent_at: review.warning_dm_sent_at?.toISOString() ?? null,
+ warned_at: review.warned_at?.toISOString() ?? null,
+ enforcement_decision_id: review.enforcement_decision_id?.toString() ?? null,
+ awaited_decision_id: awaitedDecisionId?.toString() ?? null,
+ decided_at: review.decided_at?.toISOString() ?? null,
+ decided_by: review.decided_by?.toString() ?? null,
+ decision_note: review.decision_note ?? null,
+ reversed_at: review.reversed_at?.toISOString() ?? null,
+ reversed_by: review.reversed_by?.toString() ?? null,
+ reversal_note: review.reversal_note ?? null,
+ dispute_purchase_at: review.dispute_purchase_at?.toISOString() ?? null,
+ };
+}
+
+export function PaymentDisputeAdminController(app: HonoApp) {
+ app.get(
+ '/admin/payment-dispute-reviews',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_LOOKUP),
+ requireAdminACL(AdminACLs.USER_LOOKUP),
+ OpenAPI({
+ operationId: 'list_admin_payment_dispute_reviews',
+ summary: 'List payment dispute reviews',
+ responseSchema: AdminPaymentDisputeReviewListResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: TAG,
+ description:
+ 'Lists the Operator Pass and Plutonium payment disputes, newest first. A review opens when the dispute opens, and the account that made the payment cannot buy anything while any of its disputes is open. Each review shows the grounds that rule out finding it unjustified, the date a warning would name, and the other closure decision a pending closure waits for. Requires USER_LOOKUP permission.',
+ }),
+ async (ctx) => {
+ const reviews = await listPaymentDisputeReviews(getPaymentDisputeRepository());
+ await recordAdminRead(ctx, {
+ targetType: 'payment_dispute_review',
+ targetId: 0n,
+ action: AdminAuditReadActions.LIST_PAYMENT_DISPUTE_REVIEWS,
+ metadata: {result_count: reviews.length},
+ });
+ const now = new Date();
+ const awaited = await getClosuresAwaited(getUserRepository(), reviews);
+ return ctx.json({
+ reviews: reviews.map((review) => mapReview(review, now, awaited.get(review.dispute_id) ?? null)),
+ });
+ },
+ );
+ app.post(
+ '/admin/payment-dispute-reviews/:dispute_id/decision',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
+ requireAdminACL(AdminACLs.USER_DELETE),
+ Validator('param', AdminPaymentDisputeIdParam),
+ Validator('json', AdminPaymentDisputeDecisionRequest),
+ OpenAPI({
+ operationId: 'decide_admin_payment_dispute_review',
+ summary: 'Decide payment dispute review',
+ responseSchema: AdminPaymentDisputeReviewResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: TAG,
+ description:
+ 'Records whether an open payment dispute is justified. Unjustified is refused when the terms rule it out, after the dispute closed, or when the warning date, 3 days before the evidence deadline, is less than 2 days away. Unjustified emails the account and sends it a system message naming that date: if the dispute is not withdrawn by then and ends with the money returned, an enforcement decision closes the account and sends the enforcement notice. The warning counts only once both went out. When the instance has direct messages turned off, no system message is sent and the email alone counts. Deciding unjustified again on a review whose warning is incomplete sends only what is missing, with the same date. A justified dispute never leads to action against the account. A decision is final, only an appeal reverses an unjustified one. Creates audit log entry. Requires USER_DELETE permission.',
+ }),
+ async (ctx) => {
+ const {dispute_id: disputeId} = ctx.req.valid('param');
+ const body = ctx.req.valid('json');
+ const {review, emailSent, dmSent} = await ctx.get('adminService').paymentDisputeEnforcement.decide({
+ disputeId,
+ decision: body.decision,
+ note: body.note,
+ adminUserId: ctx.get('adminUserId'),
+ });
+ await recordAdminWrite(ctx, {
+ targetType: 'user',
+ targetId: review.purchaser_id,
+ action: 'decide_payment_dispute_review',
+ metadata: {
+ dispute_id: disputeId,
+ product: review.product,
+ decision: body.decision,
+ status: review.status,
+ warning_deadline: review.warning_deadline?.toISOString() ?? undefined,
+ warning_email_sent: emailSent,
+ warning_dm_sent: dmSent,
+ },
+ });
+ return ctx.json(mapReview(review, new Date(), null));
+ },
+ );
+ app.post(
+ '/admin/payment-dispute-reviews/:dispute_id/reversal',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
+ requireAdminACL(AdminACLs.USER_DELETE),
+ Validator('param', AdminPaymentDisputeIdParam),
+ Validator('json', AdminPaymentDisputeReversalRequest),
+ OpenAPI({
+ operationId: 'reverse_admin_payment_dispute_review',
+ summary: 'Reverse payment dispute decision',
+ responseSchema: AdminPaymentDisputeReviewResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: TAG,
+ description:
+ 'Reverses an unjustified finding when an appeal under section 6.2 of the terms shows the dispute was justified. The review becomes justified, and the enforcement decision that closed the account is reversed, which restores the account and sends the enforcement ended notice, unless the deletion already started or another unreversed unjustified dispute is linked to the same decision. Creates audit log entry. Requires USER_DELETE permission, and BAN_IP_REMOVE when the decision blocked networks.',
+ }),
+ async (ctx) => {
+ const {dispute_id: disputeId} = ctx.req.valid('param');
+ const {note} = ctx.req.valid('json');
+ const {review, decisionEnded} = await ctx.get('adminService').paymentDisputeEnforcement.reverse({
+ disputeId,
+ note,
+ actor: enforcementActor(ctx),
+ });
+ await recordAdminWrite(ctx, {
+ targetType: 'user',
+ targetId: review.purchaser_id,
+ action: 'reverse_payment_dispute_review',
+ metadata: {
+ dispute_id: disputeId,
+ product: review.product,
+ enforcement_decision_id: review.enforcement_decision_id?.toString() ?? undefined,
+ decision_ended: decisionEnded,
+ },
+ });
+ return ctx.json(mapReview(review, new Date(), null));
+ },
+ );
+}
diff --git a/fluxer_api/src/api/admin/controllers/index.ts b/fluxer_api/src/api/admin/controllers/index.ts
index 8d8663d1c..7d4846574 100644
--- a/fluxer_api/src/api/admin/controllers/index.ts
+++ b/fluxer_api/src/api/admin/controllers/index.ts
@@ -16,8 +16,11 @@ import {InstanceConfigAdminController} from '@app/api/admin/controllers/Instance
import {JobsAdminController} from '@app/api/admin/controllers/JobsAdminController';
import {LimitConfigAdminController} from '@app/api/admin/controllers/LimitConfigAdminController';
import {MessageAdminController} from '@app/api/admin/controllers/MessageAdminController';
+import {OperatorPassAdminController} from '@app/api/admin/controllers/OperatorPassAdminController';
+import {PaymentDisputeAdminController} from '@app/api/admin/controllers/PaymentDisputeAdminController';
import {ReportAdminController} from '@app/api/admin/controllers/ReportAdminController';
import {SearchAdminController} from '@app/api/admin/controllers/SearchAdminController';
+import {SsoIdentityAdminController} from '@app/api/admin/controllers/SsoIdentityAdminController';
import {StoreBillingAdminController} from '@app/api/admin/controllers/StoreBillingAdminController';
import {SystemDmAdminController} from '@app/api/admin/controllers/SystemDmAdminController';
import {ThreadAdminController} from '@app/api/admin/controllers/ThreadAdminController';
@@ -31,6 +34,8 @@ export function registerAdminControllers(app: HonoApp) {
UserAdminController(app);
EnforcementAdminController(app);
StoreBillingAdminController(app);
+ OperatorPassAdminController(app);
+ PaymentDisputeAdminController(app);
CodesAdminController(app);
GuildAdminController(app);
ThreadAdminController(app);
@@ -46,6 +51,7 @@ export function registerAdminControllers(app: HonoApp) {
VoiceAdminController(app);
GatewayAdminController(app);
SearchAdminController(app);
+ SsoIdentityAdminController(app);
DiscoveryAdminController(app);
SystemDmAdminController(app);
JobsAdminController(app);
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/PaymentDisputeAdminAuditCases.ts b/fluxer_api/src/api/admin/tests/audit_coverage/PaymentDisputeAdminAuditCases.ts
new file mode 100644
index 000000000..ed6ae6ae5
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/PaymentDisputeAdminAuditCases.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {AdminAuditCoverageCase} from '@app/api/admin/tests/audit_coverage/AdminAuditCoverage';
+import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createUserID, type UserID} from '@app/api/BrandedTypes';
+import type {PaymentDisputeReviewRow} from '@app/api/database/types/PaymentDisputeTypes';
+import {getPaymentDisputeRepository} from '@app/api/middleware/ServiceSingletons';
+
+function auditReview(disputeId: string, purchaserId: UserID, status: PaymentDisputeReviewRow['status']) {
+ const now = new Date();
+ return {
+ dispute_id: disputeId,
+ product: 'plutonium',
+ order_id: `cs_${disputeId}`,
+ invoice_number: null,
+ purchaser_id: purchaserId,
+ is_gift: false,
+ reason: 'general',
+ payment_intent_id: `pi_${disputeId}`,
+ charge_id: `ch_${disputeId}`,
+ amount_minor: 2499,
+ currency: 'USD',
+ evidence_submitted: false,
+ evidence_due_by: new Date(now.getTime() + 14 * 24 * 60 * 60 * 1000),
+ disputed_at: now,
+ closed_at: null,
+ outcome: null,
+ purchased_at: now,
+ perks_started_at: now,
+ withdrawal_ends_at: now,
+ withdrawn_at: null,
+ refunded_at: null,
+ perks_removed_at: null,
+ status,
+ created_at: now,
+ decided_at: status === 'open' ? null : now,
+ decided_by: null,
+ decision_note: null,
+ warning_deadline: null,
+ warning_email_sent_at: null,
+ warning_dm_sent_at: null,
+ warned_at: null,
+ enforcement_decision_id: null,
+ reversed_at: null,
+ reversed_by: null,
+ reversal_note: null,
+ dispute_purchase_at: null,
+ version: 1,
+ } satisfies PaymentDisputeReviewRow;
+}
+
+export const PaymentDisputeAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [
+ {
+ method: 'GET',
+ route: '/admin/payment-dispute-reviews',
+ async prepare() {
+ return {
+ request: {path: '/admin/payment-dispute-reviews'},
+ expected: {
+ action: 'list_payment_dispute_reviews',
+ targetType: 'payment_dispute_review',
+ targetId: '0',
+ metadata: {result_count: '0'},
+ },
+ };
+ },
+ },
+ {
+ method: 'POST',
+ route: '/admin/payment-dispute-reviews/:dispute_id/decision',
+ async prepare({harness}) {
+ const target = await createTestAccount(harness);
+ await getPaymentDisputeRepository().createReview(
+ auditReview('dp_audit_decision', createUserID(BigInt(target.userId)), 'open'),
+ );
+ return {
+ request: {
+ path: '/admin/payment-dispute-reviews/dp_audit_decision/decision',
+ body: {decision: 'justified', note: null},
+ },
+ expected: {
+ action: 'decide_payment_dispute_review',
+ targetType: 'user',
+ targetId: target.userId,
+ metadata: {
+ dispute_id: 'dp_audit_decision',
+ product: 'plutonium',
+ decision: 'justified',
+ status: 'justified',
+ warning_email_sent: 'false',
+ warning_dm_sent: 'false',
+ },
+ },
+ };
+ },
+ },
+ {
+ method: 'POST',
+ route: '/admin/payment-dispute-reviews/:dispute_id/reversal',
+ async prepare({harness}) {
+ const target = await createTestAccount(harness);
+ await getPaymentDisputeRepository().createReview(
+ auditReview('dp_audit_reversal', createUserID(BigInt(target.userId)), 'unjustified'),
+ );
+ return {
+ request: {
+ path: '/admin/payment-dispute-reviews/dp_audit_reversal/reversal',
+ body: {note: 'The bank statement shows a duplicate charge.'},
+ },
+ expected: {
+ action: 'reverse_payment_dispute_review',
+ targetType: 'user',
+ targetId: target.userId,
+ metadata: {
+ dispute_id: 'dp_audit_reversal',
+ product: 'plutonium',
+ decision_ended: 'false',
+ },
+ },
+ };
+ },
+ },
+];
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/PaymentDisputeAdminAuditCoverage.test.ts b/fluxer_api/src/api/admin/tests/audit_coverage/PaymentDisputeAdminAuditCoverage.test.ts
new file mode 100644
index 000000000..944584359
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/PaymentDisputeAdminAuditCoverage.test.ts
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {describeAdminAuditCoverage} from '@app/api/admin/tests/audit_coverage/AdminAuditCoverage';
+import {PaymentDisputeAdminAuditCases} from '@app/api/admin/tests/audit_coverage/PaymentDisputeAdminAuditCases';
+
+describeAdminAuditCoverage('PaymentDisputeAdminController', PaymentDisputeAdminAuditCases);
diff --git a/fluxer_api/src/api/enforcement/EnforcementDecisionService.ts b/fluxer_api/src/api/enforcement/EnforcementDecisionService.ts
index 5d817ed8c..407dbcdbc 100644
--- a/fluxer_api/src/api/enforcement/EnforcementDecisionService.ts
+++ b/fluxer_api/src/api/enforcement/EnforcementDecisionService.ts
@@ -1,14 +1,17 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import assert from 'node:assert/strict';
import type {BannedIpEntry} from '@app/api/admin/AdminRepository';
import type {AdminAuditService} from '@app/api/admin/services/AdminAuditService';
import type {AdminBanManagementService} from '@app/api/admin/services/AdminBanManagementService';
import {queueMessageShredJob} from '@app/api/admin/services/AdminMessageShredService';
import type {AdminReportService} from '@app/api/admin/services/AdminReportService';
import {createChannelID, createMessageID, createReportID, createUserID, type UserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
import type {ChannelRepository} from '@app/api/channel/ChannelRepository';
import {SYSTEM_USER_ID} from '@app/api/constants/Core';
import type {
+ EnforcementDecisionEvidenceRow,
EnforcementDecisionNoteRow,
EnforcementDecisionRow,
EvidenceChannelKind,
@@ -54,6 +57,7 @@ import type {User} from '@app/api/models/User';
import {type IARSubmission, ReportStatus} from '@app/api/report/ReportModels';
import type {ReportService} from '@app/api/report/ReportService';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import type {DeletionReasons} from '@fluxer/constants/src/Core';
import {
ENFORCEMENT_REASONS,
ENFORCEMENT_RULES,
@@ -120,6 +124,20 @@ interface AutomatedPurchaseLimitParams {
internalNote: string;
}
+export type PaymentDisputeClosureReason =
+ | typeof DeletionReasons.BILLING_DISPUTE_OR_ABUSE
+ | typeof DeletionReasons.OPERATOR_PASS_PAYMENT_DISPUTE;
+
+interface PaymentDisputeClosureParams {
+ subject: User;
+ reasonCode: PaymentDisputeClosureReason;
+ decidedBy: UserID;
+ paymentAt: Date;
+ deletionAt: Date;
+ statement: string | null;
+ internalNote: string;
+}
+
interface EnforcementDecisionServiceDeps extends ClosureStateDeps {
repository: EnforcementDecisionRepository;
delivery: EnforcementNoticeDelivery;
@@ -129,6 +147,7 @@ interface EnforcementDecisionServiceDeps extends ClosureStateDeps {
guildRepository: GuildRepository;
reportService: ReportService;
adminReportService: AdminReportService;
+ onClosureEnded?: (subjectId: UserID) => Promise<void>;
}
const EVIDENCE_LIMIT = 50;
@@ -183,7 +202,9 @@ export function decisionAuditMetadata(decision: EnforcementDecisionRow): Array<[
export function networkBlockAuditMetadata({blockedNetworks}: RecordedDecision): Array<[string, string]> {
const until = latestNetworkBlockExpiry(blockedNetworks);
- if (!until) return [];
+ if (!until) {
+ return [];
+ }
return [
['blocked_ips', blockedNetworks.map((entry) => entry.ip).join(',')],
['network_blocks_until', until.toISOString()],
@@ -215,7 +236,9 @@ type DecisionFields = Pick<
>;
function evidenceSubject(subject: EnforcementSubject): EvidenceSubject {
- if (subject.type === 'guild') return {type: 'guild', id: subject.guild.id};
+ if (subject.type === 'guild') {
+ return {type: 'guild', id: subject.guild.id};
+ }
const {id, username, discriminator} = subject.user;
return {type: 'user', id, username, discriminator};
}
@@ -229,17 +252,25 @@ function reportOutcome(
{kind, removal, removeEvidence}: RecordDecisionParams,
evidence: ReadonlyArray<IARMessageContextRow>,
): ReportItemOutcome | null {
- if (kind === 'community_removal') return 'removed';
- if (kind === 'profile_reset' && report.reportedMessageId === null) return 'removed';
+ if (kind === 'community_removal') {
+ return 'removed';
+ }
+ if (kind === 'profile_reset' && report.reportedMessageId === null) {
+ return 'removed';
+ }
const messageId = report.reportedMessageId;
if (messageId !== null) {
const removed =
removal?.type === 'all_messages' ||
(removal?.type === 'messages' && removal.entries.some((entry) => entry.message_id === messageId)) ||
(removeEvidence && evidence.some((message) => message.message_id === messageId));
- if (removed) return 'removed';
+ if (removed) {
+ return 'removed';
+ }
+ }
+ if (kind === 'warning') {
+ return 'warned';
}
- if (kind === 'warning') return 'warned';
return RESTRICTING_KINDS.has(kind) ? 'restricted' : null;
}
@@ -293,7 +324,7 @@ export class EnforcementDecisionService {
await this.queueEvidenceRemoval(decision, evidence, actor.adminUserId);
}
const carried = replacedDecisionId
- ? await this.takeOverNetworkBlocks(replacedDecisionId, decision, canBlockNetworks(kind, params.endsAt))
+ ? await this.takeOverNetworkBlocks(replacedDecisionId, decision, {keep: canBlockNetworks(kind, params.endsAt)})
: [];
const networks = networkPlan
? await this.blockNetworks(decision, networkPlan)
@@ -348,6 +379,74 @@ export class EnforcementDecisionService {
return this.deliverNotice(decision, [], new Map(), null);
}
+ async recordPaymentDisputeClosure(
+ {subject, reasonCode, decidedBy, paymentAt, deletionAt, statement, internalNote}: PaymentDisputeClosureParams,
+ applyState: (decisionId: bigint) => Promise<void>,
+ ): Promise<EnforcementDecisionRow> {
+ const replacedDecisionId = subject.enforcementDecisionId;
+ const decision = await this.persist(
+ await this.subjectFields({type: 'user', user: subject}),
+ {
+ kind: 'closure',
+ reason_code: reasonCode,
+ source: 'own_review',
+ automation: 'none',
+ statement,
+ rights_holder: null,
+ ends_at: null,
+ deletion_at: deletionAt,
+ feature_limit: null,
+ profile_fields: null,
+ removed_message_count: null,
+ removed_all_messages: null,
+ payment_at: paymentAt,
+ report_ids: null,
+ decided_by: decidedBy,
+ },
+ {messages: [], channelKinds: new Map(), profileValues: null},
+ internalNote,
+ applyState,
+ );
+ const carried = replacedDecisionId
+ ? await this.takeOverNetworkBlocks(replacedDecisionId, decision, {keep: true})
+ : [];
+ await this.banClosedAccountEmail(subject, decidedBy, internalNote);
+ return this.deliverNotice(decision, [], new Map(), latestNetworkBlockExpiry(carried));
+ }
+
+ async resumePaymentDisputeClosure(
+ subject: User,
+ decisionId: bigint,
+ reasonCode: PaymentDisputeClosureReason,
+ ): Promise<EnforcementDecisionRow | null> {
+ const decision = await this.deps.repository.get(decisionId);
+ if (
+ decision?.status !== 'active' ||
+ decision.kind !== 'closure' ||
+ decision.reason_code !== reasonCode ||
+ decision.payment_at === null
+ ) {
+ return null;
+ }
+ if (decision.notice_status !== 'pending') {
+ return decision;
+ }
+ await this.banClosedAccountEmail(subject, createUserID(decision.decided_by), `Enforcement decision ${decisionId}`);
+ const networkBlocks = await this.deps.banManagementService.listDecisionNetworkBlocks(decisionId);
+ return this.deliverNotice(decision, [], new Map(), latestNetworkBlockExpiry(networkBlocks));
+ }
+
+ private async banClosedAccountEmail(subject: User, bannedBy: UserID, reason: string): Promise<void> {
+ if (!subject.email) {
+ return;
+ }
+ try {
+ await this.deps.banManagementService.banEmail({email: subject.email}, bannedBy, reason);
+ } catch (error) {
+ Logger.warn({error, userId: subject.id.toString()}, 'Failed to ban the email of a closed account');
+ }
+ }
+
async end(
decisionId: bigint,
request: EnforcementDecisionEndRequest,
@@ -499,18 +598,16 @@ export class EnforcementDecisionService {
created_at: now,
};
const hasEvidence = evidence.messages.length > 0 || (evidence.profileValues?.size ?? 0) > 0;
- await repository.create({
- decision,
- evidence: hasEvidence
- ? {
- decision_id: decisionId,
- messages: evidence.messages.length > 0 ? [...evidence.messages] : null,
- message_locations: evidence.channelKinds.size > 0 ? new Map(evidence.channelKinds) : null,
- profile_values: evidence.profileValues?.size ? new Map(evidence.profileValues) : null,
- }
- : null,
- firstNote: note,
- });
+ let evidenceRow: EnforcementDecisionEvidenceRow | null = null;
+ if (hasEvidence) {
+ evidenceRow = {
+ decision_id: decisionId,
+ messages: evidence.messages.length > 0 ? [...evidence.messages] : null,
+ message_locations: evidence.channelKinds.size > 0 ? new Map(evidence.channelKinds) : null,
+ profile_values: evidence.profileValues?.size ? new Map(evidence.profileValues) : null,
+ };
+ }
+ await repository.create({decision, evidence: evidenceRow, firstNote: note});
try {
await applyState(decisionId);
} catch (error) {
@@ -545,7 +642,7 @@ export class EnforcementDecisionService {
throw InputValidationError.fromCode('outcome', ValidationErrorCodes.ENFORCEMENT_OUTCOME_NOT_ALLOWED);
}
const inForce = await this.undo(decision, request, endedBy, internalNote);
- const ended: EnforcementDecisionRow = {
+ const ended: EnforcementDecisionRow & {ended_at: Date} = {
...decision,
status: 'ended',
end_outcome: request.outcome,
@@ -555,7 +652,7 @@ export class EnforcementDecisionService {
};
await this.deps.repository.end(decision.decision_id, {
outcome: request.outcome,
- endedAt: ended.ended_at!,
+ endedAt: ended.ended_at,
endedBy,
statement: ended.end_statement,
});
@@ -576,6 +673,24 @@ export class EnforcementDecisionService {
['subject_id', decision.subject_id.toString()],
]),
});
+ if (decision.kind === 'closure' && inForce) {
+ await this.notifyClosureEnded(decision);
+ }
+ }
+
+ private async notifyClosureEnded(decision: EnforcementDecisionRow): Promise<void> {
+ const {onClosureEnded} = this.deps;
+ if (!onClosureEnded) {
+ return;
+ }
+ try {
+ await onClosureEnded(createUserID(decision.subject_id));
+ } catch (error) {
+ Logger.error(
+ {decisionId: decision.decision_id.toString(), error},
+ 'Failed to act on the end of a closure decision',
+ );
+ }
}
private async undo(
@@ -618,7 +733,8 @@ export class EnforcementDecisionService {
return true;
}
case 'feature_limit': {
- const limit = decision.feature_limit!;
+ const limit = decision.feature_limit;
+ assert(limit !== null);
const user = await this.requireUserSubject(decision);
const holding = await findHoldingFeatureLimit(this.deps.repository, subjectId, limit, decision.decision_id);
if (!holding) {
@@ -632,11 +748,17 @@ export class EnforcementDecisionService {
}
private async subjectNamesDecision(decision: EnforcementDecisionRow): Promise<boolean> {
- if (decision.subject_type !== 'user' || !isAccountKind(decision.kind)) return false;
+ if (decision.subject_type !== 'user' || !isAccountKind(decision.kind)) {
+ return false;
+ }
try {
const user = await this.findUserSubject(decision);
return user?.enforcementDecisionId === decision.decision_id;
- } catch {
+ } catch (error) {
+ Logger.warn(
+ {error, decisionId: decision.decision_id.toString(), subjectId: decision.subject_id.toString()},
+ 'Keeping enforcement decision because its account state could not be checked',
+ );
return true;
}
}
@@ -644,11 +766,11 @@ export class EnforcementDecisionService {
private async takeOverNetworkBlocks(
replacedDecisionId: bigint,
decision: EnforcementDecisionRow,
- keep: boolean,
+ options: {keep: boolean},
): Promise<Array<BannedIpEntry>> {
const {banManagementService} = this.deps;
try {
- if (keep) {
+ if (options.keep) {
return await banManagementService.relinkDecisionNetworkBlocks(replacedDecisionId, decision.decision_id);
}
await banManagementService.removeDecisionNetworkBlocks([replacedDecisionId]);
@@ -681,7 +803,9 @@ export class EnforcementDecisionService {
}
private async findUserSubject(decision: EnforcementDecisionRow): Promise<User | null> {
- if (decision.subject_type !== 'user') return null;
+ if (decision.subject_type !== 'user') {
+ return null;
+ }
return this.deps.apiContext.services.users.findUnique(createUserID(decision.subject_id));
}
@@ -730,6 +854,7 @@ export class EnforcementDecisionService {
const reason = ENFORCEMENT_REASONS[input.reason_code];
if (
!isEnforcementKindAllowed(input.reason_code, kind) ||
+ (Config.instance.selfHosted && ENFORCEMENT_RULES[reason.rule].policy === 'operator_pass_terms') ||
(subject.type === 'user' && subject.user.isBot && !isAccountKind(kind)) ||
(removal?.type === 'all_messages' && reason.handling === 'restricted')
) {
@@ -778,12 +903,12 @@ export class EnforcementDecisionService {
blockNetworks && subject.type === 'user'
? await planNetworkBlocks(this.deps.apiContext.services.users, subject.user, blockNetworks)
: null;
- const removedMessageCount =
- removal?.type === 'messages'
- ? evidence.length + (await this.countOwnMessages(subject, removed.slice(snapshotted)))
- : removeEvidence
- ? evidence.length
- : null;
+ let removedMessageCount: number | null = null;
+ if (removal?.type === 'messages') {
+ removedMessageCount = evidence.length + (await this.countOwnMessages(subject, removed.slice(snapshotted)));
+ } else if (removeEvidence) {
+ removedMessageCount = evidence.length;
+ }
return {reports, evidence, removedMessageCount, internalNote: actor.internalNote, networkPlan};
}
@@ -791,14 +916,18 @@ export class EnforcementDecisionService {
subject: EnforcementSubject,
entries: ReadonlyArray<MessageReference>,
): Promise<number> {
- if (subject.type !== 'user') return 0;
+ if (subject.type !== 'user') {
+ return 0;
+ }
let count = 0;
for (const entry of entries) {
const message = await this.deps.channelRepository.messages.getMessage(
createChannelID(entry.channel_id),
createMessageID(entry.message_id),
);
- if (message?.authorId === subject.user.id) count += 1;
+ if (message?.authorId === subject.user.id) {
+ count += 1;
+ }
}
return count;
}
@@ -807,7 +936,9 @@ export class EnforcementDecisionService {
decision: EnforcementDecisionRow,
plan: NetworkBlockPlan,
): Promise<{blocked: Array<BannedIpEntry>; skipped: Array<SkippedNetwork>}> {
- if (plan.ips.length === 0) return {blocked: [], skipped: plan.skipped};
+ if (plan.ips.length === 0) {
+ return {blocked: [], skipped: plan.skipped};
+ }
try {
const {blocked, alreadyBlocked} = await this.deps.banManagementService.blockNetworksForDecision(
plan.ips,
@@ -855,7 +986,9 @@ export class EnforcementDecisionService {
const reports: Array<IARSubmission> = [];
for (const [index, reportId] of [...new Set(reportIds)].entries()) {
const report = await this.deps.reportService.getReport(createReportID(reportId)).catch((error: unknown) => {
- if (error instanceof UnknownReportError) return null;
+ if (error instanceof UnknownReportError) {
+ return null;
+ }
throw error;
});
const reported = subject.type === 'user' ? report?.reportedUserId : report?.reportedGuildId;
@@ -894,7 +1027,9 @@ export class EnforcementDecisionService {
internalNote: string,
): Promise<void> {
for (const {report, outcome} of outcomes) {
- if (report.status !== ReportStatus.PENDING || outcome === null) continue;
+ if (report.status !== ReportStatus.PENDING || outcome === null) {
+ continue;
+ }
try {
await this.deps.adminReportService.resolveReport(report.reportId, {
adminUserId: actor.adminUserId,
@@ -920,7 +1055,9 @@ export class EnforcementDecisionService {
try {
const locations = await resolveEvidenceLocations(evidence, channelKinds, channelRepository, guildRepository);
const notice = await delivery.deliver(decision, locations, networksBlockedUntil);
- if (!notice) return decision;
+ if (!notice) {
+ return decision;
+ }
await repository.setNotice(decision.decision_id, notice);
return {
...decision,
diff --git a/fluxer_api/src/api/enforcement/EnforcementNotice.ts b/fluxer_api/src/api/enforcement/EnforcementNotice.ts
index 97bc6599e..bbaeb337f 100644
--- a/fluxer_api/src/api/enforcement/EnforcementNotice.ts
+++ b/fluxer_api/src/api/enforcement/EnforcementNotice.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import assert from 'node:assert/strict';
import {Config} from '@app/api/Config';
import {type ContentI18nMessageArgs, getContentMessage} from '@app/api/content_i18n/ContentI18n';
import type {ContentI18nKey} from '@app/api/content_i18n/ContentI18nMessages';
@@ -24,8 +25,10 @@ import {
enforcementReasonOf,
isAccountKind,
} from '@fluxer/constants/src/EnforcementReasons';
+import {toIsoOrNull} from '@fluxer/date_utils/src/DateSerialization';
import type {UserProfileField} from '@fluxer/schema/src/domains/admin/AdminUserSchemas';
import type {EnforcementNotice} from '@fluxer/schema/src/domains/auth/EnforcementNoticeSchemas';
+import {getOperatorPassTermsUrl} from '@pkgs/email/src/operator_pass_terms/OperatorPassTerms';
import {ms} from 'itty-time';
type EnforcementContentKey = Extract<ContentI18nKey, `enforcement.${string}`>;
@@ -86,9 +89,14 @@ function text<K extends EnforcementContentKey>(ctx: NoticeContext, key: K, ...ar
function ruleUrl(ctx: NoticeContext, rule: EnforcementRuleKey): string | null {
const {policy, anchor} = ENFORCEMENT_RULES[rule];
+ if (policy === 'operator_pass_terms') {
+ return ctx.hosted ? `${getOperatorPassTermsUrl(Config.endpoints.marketing)}#${anchor}` : null;
+ }
const legal = getLegalUrls();
const base = policy === 'terms' ? legal.termsUrl : legal.guidelinesUrl;
- if (!base) return null;
+ if (!base) {
+ return null;
+ }
return ctx.hosted ? `${base}#${anchor}` : base;
}
@@ -99,7 +107,9 @@ function ruleOf(ctx: NoticeContext, rule: EnforcementRuleKey): RuleReference {
}
function redressLines(ctx: NoticeContext): Array<string> {
- if (!ctx.hosted) return [];
+ if (!ctx.hosted) {
+ return [];
+ }
return [
text(ctx, 'enforcement.redress.out_of_court', {url: OUT_OF_COURT_URL}),
text(ctx, 'enforcement.redress.regulator_and_court'),
@@ -107,7 +117,9 @@ function redressLines(ctx: NoticeContext): Array<string> {
}
function appealOf(ctx: NoticeContext, from: Date | null, accountHasEmail: boolean): EnforcementNotice['appeal'] {
- if (!ctx.appealsEmail) return null;
+ if (!ctx.appealsEmail) {
+ return null;
+ }
return {
email: ctx.appealsEmail,
deadline: from
@@ -138,13 +150,13 @@ function isPrivateLocation(location: EvidenceLocation): boolean {
function groupLocations(
ctx: NoticeContext,
evidence: ReadonlyArray<EvidenceMessageLocation>,
- byMonth: boolean,
+ options: {byMonth: boolean},
): Array<LocationGroup> {
const groups = new Map<string, LocationGroup>();
const sorted = [...evidence].sort((left, right) => left.timestamp.getTime() - right.timestamp.getTime());
for (const message of sorted) {
const key =
- byMonth && isPrivateLocation(message.location)
+ options.byMonth && isPrivateLocation(message.location)
? `${message.locationKey}:${formatNoticeMonth(message.timestamp, ctx.locale)}`
: message.locationKey;
const group = groups.get(key);
@@ -158,14 +170,18 @@ function groupLocations(
return [...groups.values()];
}
-function locationLine(ctx: NoticeContext, group: LocationGroup, community: boolean, byMonth: boolean): string {
+function locationLine(
+ ctx: NoticeContext,
+ group: LocationGroup,
+ options: {community: boolean; byMonth: boolean},
+): string {
const start = formatNoticeTimeUtc(group.first, ctx.locale);
const end = formatNoticeTimeUtc(group.last, ctx.locale);
const range = {count: group.count, range: start === end ? 'single' : 'other', start, end};
const month = {count: group.count, month: formatNoticeMonth(group.first, ctx.locale)};
switch (group.location.type) {
case 'channel':
- return community
+ return options.community
? text(ctx, 'enforcement.facts.community_channel', {...range, channel: group.location.channelName})
: text(ctx, 'enforcement.facts.channel', {
...range,
@@ -173,11 +189,11 @@ function locationLine(ctx: NoticeContext, group: LocationGroup, community: boole
community: group.location.communityName,
});
case 'direct_message':
- return byMonth
+ return options.byMonth
? text(ctx, 'enforcement.facts.direct_message_month', month)
: text(ctx, 'enforcement.facts.direct_message', range);
case 'group_message':
- return byMonth
+ return options.byMonth
? text(ctx, 'enforcement.facts.group_message_month', month)
: text(ctx, 'enforcement.facts.group_message', range);
case 'unknown':
@@ -285,8 +301,12 @@ function decisionEffects(
}
function leadKey(decision: EnforcementDecisionRow, rule: EnforcementRuleKey): EnforcementContentKey {
- if (decision.kind === 'community_removal') return 'enforcement.lead.community';
- if (isBotDecision(decision)) return 'enforcement.lead.bot';
+ if (decision.kind === 'community_removal') {
+ return 'enforcement.lead.community';
+ }
+ if (isBotDecision(decision)) {
+ return 'enforcement.lead.bot';
+ }
return `enforcement.lead.${rule}`;
}
@@ -299,9 +319,9 @@ function decisionFacts(
const community = decision.kind === 'community_removal';
const facts = [text(ctx, leadKey(decision, reason.rule))];
if (reason.handling !== 'restricted') {
- const byMonth = reason.handling === 'protected';
- for (const group of groupLocations(ctx, evidence, byMonth)) {
- facts.push(locationLine(ctx, group, community, byMonth));
+ const options = {community, byMonth: reason.handling === 'protected'};
+ for (const group of groupLocations(ctx, evidence, options)) {
+ facts.push(locationLine(ctx, group, options));
}
}
if (decision.kind === 'profile_reset') {
@@ -321,10 +341,7 @@ function decisionFacts(
}
function howWeDecided(ctx: NoticeContext, decision: EnforcementDecisionRow): Array<string> {
- return [
- text(ctx, `enforcement.source.${decision.source}`),
- text(ctx, `enforcement.automation.${decision.automation}`),
- ];
+ return [text(ctx, 'enforcement.how_we_decided', {source: decision.source, automation: decision.automation})];
}
function buildDecisionNotice(
@@ -341,8 +358,8 @@ function buildDecisionNotice(
kind: decision.kind,
permanent: decision.kind === 'suspension' && decision.ends_at === null,
issued_at: decision.created_at.toISOString(),
- ends_at: decision.ends_at?.toISOString() ?? null,
- deletion_at: decision.deletion_at?.toISOString() ?? null,
+ ends_at: toIsoOrNull(decision.ends_at),
+ deletion_at: toIsoOrNull(decision.deletion_at),
summary: decisionSummary(ctx, decision, target),
effects: decisionEffects(ctx, decision, target, networksBlockedUntil),
rule: ruleOf(ctx, reason.rule),
@@ -361,27 +378,35 @@ function buildLegacyNotice(ctx: NoticeContext, user: User, now: Date): Enforceme
const reason = closed ? enforcementReasonOf(user.deletionReasonCode) : null;
const rule = reason ? ruleOf(ctx, reason.rule) : null;
const statement = closed && reason?.handling === 'standard' ? user.deletionPublicReason : null;
- const summary = closed
- ? text(ctx, 'enforcement.summary.closure', target)
- : permanent
- ? text(ctx, 'enforcement.summary.suspension_permanent', target)
- : text(ctx, 'enforcement.summary.suspension', {
- ...target,
- ends_at: formatNoticeTimeUtc(user.tempBannedUntil!, ctx.locale),
- });
- const effect = closed
- ? text(ctx, 'enforcement.effect.closure', {
- ...target,
- deletion_at: user.pendingDeletionAt ? formatNoticeDate(user.pendingDeletionAt, ctx.locale) : '',
- })
- : text(ctx, permanent ? 'enforcement.effect.suspension_permanent' : 'enforcement.effect.suspension', target);
+ let summary: string;
+ if (closed) {
+ summary = text(ctx, 'enforcement.summary.closure', target);
+ } else if (permanent) {
+ summary = text(ctx, 'enforcement.summary.suspension_permanent', target);
+ } else {
+ const endsAt = user.tempBannedUntil;
+ assert(endsAt !== null);
+ summary = text(ctx, 'enforcement.summary.suspension', {
+ ...target,
+ ends_at: formatNoticeTimeUtc(endsAt, ctx.locale),
+ });
+ }
+ let effect: string;
+ if (closed) {
+ effect = text(ctx, 'enforcement.effect.closure', {
+ ...target,
+ deletion_at: user.pendingDeletionAt ? formatNoticeDate(user.pendingDeletionAt, ctx.locale) : '',
+ });
+ } else {
+ effect = text(ctx, permanent ? 'enforcement.effect.suspension_permanent' : 'enforcement.effect.suspension', target);
+ }
return {
decision_id: null,
kind: closed ? 'closure' : 'suspension',
permanent,
issued_at: null,
- ends_at: closed || permanent ? null : (user.tempBannedUntil?.toISOString() ?? null),
- deletion_at: closed ? (user.pendingDeletionAt?.toISOString() ?? null) : null,
+ ends_at: closed || permanent ? null : toIsoOrNull(user.tempBannedUntil),
+ deletion_at: closed ? toIsoOrNull(user.pendingDeletionAt) : null,
summary,
effects: [effect],
rule,
diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementPaymentFraud.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementPaymentFraud.test.ts
index fe78b570c..4f55a9bb9 100644
--- a/fluxer_api/src/api/enforcement/tests/EnforcementPaymentFraud.test.ts
+++ b/fluxer_api/src/api/enforcement/tests/EnforcementPaymentFraud.test.ts
@@ -16,6 +16,7 @@ import {
warn,
} from '@app/api/enforcement/tests/EnforcementTestUtils';
import {getUserRepository} from '@app/api/middleware/ServiceSingletons';
+import {PaymentDisputeRepository} from '@app/api/payment_disputes/PaymentDisputeRepository';
import {
createTestPayment,
mockStripeWebhookSecret,
@@ -74,6 +75,26 @@ describe('Enforcement for payment fraud signals', () => {
});
}
+ async function fraudWarning(paymentIntentId: string) {
+ const chargeId = `ch_${paymentIntentId}`;
+ server.use(...createStripeApiHandlers({charges: {[chargeId]: {payment_intent: paymentIntentId}}}).handlers);
+ await sendStripeWebhook(harness, {
+ type: 'radar.early_fraud_warning.created',
+ data: {
+ object: {
+ actionable: true,
+ charge: chargeId,
+ created: Math.floor(Date.now() / 1000),
+ fraud_type: 'made_with_stolen_card',
+ id: `issfr_${paymentIntentId}`,
+ livemode: false,
+ object: 'radar.early_fraud_warning',
+ payment_intent: paymentIntentId,
+ },
+ },
+ });
+ }
+
async function reviewQueue(): Promise<Array<EnforcementDecisionResponse>> {
const {decisions} = await createBuilder<{decisions: Array<EnforcementDecisionResponse>}>(harness, staff.token)
.get('/admin/enforcement-decisions?review_queue=true')
@@ -88,12 +109,32 @@ describe('Enforcement for payment fraud signals', () => {
return getDecision(harness, staff, decisions[0]!.decision_id);
}
- test('a chargeback records an automated purchase limit and never suspends, closes or bans', async () => {
+ test('a chargeback opens a dispute review and records no decision', async () => {
const target = await createTestAccount(harness);
- const paidAt = await purchase(target, 'pi_enforcement_chargeback');
+ await purchase(target, 'pi_enforcement_chargeback');
await clearTestEmails(harness);
await chargeback('pi_enforcement_chargeback');
const user = await loadUser(target);
+ expect(user.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);
+ expect(user.flags & (UserFlags.DISABLED | UserFlags.DELETED)).toBe(0n);
+ expect(user.tempBannedUntil).toBeNull();
+ expect(user.pendingDeletionAt).toBeNull();
+ expect(user.enforcementDecisionId).toBeNull();
+ expect(await new AdminRepository().isEmailBanned(target.email)).toBe(false);
+ expect(await listDecisions(harness, staff, target.userId)).toEqual([]);
+ expect(await reviewQueue()).toEqual([]);
+ expect(await emailsTo(harness, target, 'enforcement_notice')).toEqual([]);
+ expect(await new PaymentDisputeRepository().findReview('dp_pi_enforcement_chargeback')).toMatchObject({
+ status: 'open',
+ });
+ });
+
+ test('an early fraud warning records an automated purchase limit and never suspends, closes or bans', async () => {
+ const target = await createTestAccount(harness);
+ const paidAt = await purchase(target, 'pi_enforcement_efw');
+ await clearTestEmails(harness);
+ await fraudWarning('pi_enforcement_efw');
+ const user = await loadUser(target);
expect(user.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(PremiumFlags.PURCHASE_DISABLED);
expect(user.flags & (UserFlags.DISABLED | UserFlags.DELETED)).toBe(0n);
expect(user.tempBannedUntil).toBeNull();
@@ -111,9 +152,9 @@ describe('Enforcement for payment fraud signals', () => {
payment_at: paidAt.toISOString(),
notice_status: 'sent',
});
- expect(decision.notes[0]?.body).toContain('Stripe chargeback');
+ expect(decision.notes[0]?.body).toContain('Stripe early fraud warning');
expect(decision.notice_text).toContain(
- 'This is a temporary limit applied automatically while a person on our team reviews it.',
+ 'Our automated tools applied this temporary limit, and a person on our team is reviewing it.',
);
expect(decision.notice_text).toContain('A payment on your account on ');
expect(decision.notice_text).not.toContain('fraud');
@@ -121,31 +162,6 @@ describe('Enforcement for payment fraud signals', () => {
expect(await emailsTo(harness, target, 'enforcement_notice')).toHaveLength(1);
});
- test('an early fraud warning records the same automated limit', async () => {
- const chargeId = 'ch_enforcement_efw';
- server.use(...createStripeApiHandlers({charges: {[chargeId]: {payment_intent: 'pi_enforcement_efw'}}}).handlers);
- const target = await createTestAccount(harness);
- const paidAt = await purchase(target, 'pi_enforcement_efw');
- await sendStripeWebhook(harness, {
- type: 'radar.early_fraud_warning.created',
- data: {
- object: {
- actionable: true,
- charge: chargeId,
- created: Math.floor(Date.now() / 1000),
- fraud_type: 'made_with_stolen_card',
- id: 'issfr_enforcement',
- livemode: false,
- object: 'radar.early_fraud_warning',
- payment_intent: 'pi_enforcement_efw',
- },
- },
- });
- const decision = await onlyDecision(target);
- expect(decision).toMatchObject({automation: 'automated', limit: 'purchases', payment_at: paidAt.toISOString()});
- expect((await loadUser(target)).pendingDeletionAt).toBeNull();
- });
-
test.each([
['warning', (target: TestAccount) => warn(harness, staff, target.userId, decisionBody())],
['suspension', (target: TestAccount) => suspend(harness, staff, target.userId)],
@@ -153,7 +169,7 @@ describe('Enforcement for payment fraud signals', () => {
])('a %s by a person takes the account out of the review queue', async (_label, decide) => {
const target = await createTestAccount(harness);
await purchase(target, `pi_queue_${_label}`);
- await chargeback(`pi_queue_${_label}`);
+ await fraudWarning(`pi_queue_${_label}`);
expect(await reviewQueue()).toHaveLength(1);
await decide(target);
expect(await reviewQueue()).toEqual([]);
@@ -166,7 +182,7 @@ describe('Enforcement for payment fraud signals', () => {
test('a person ending the limit clears the flag and the review queue', async () => {
const target = await createTestAccount(harness);
await purchase(target, 'pi_queue_end');
- await chargeback('pi_queue_end');
+ await fraudWarning('pi_queue_end');
const decision = await onlyDecision(target);
await endDecision(harness, staff, decision.decision_id, 'lifted').expect(HTTP_STATUS.OK).execute();
expect(await reviewQueue()).toEqual([]);
@@ -176,6 +192,7 @@ describe('Enforcement for payment fraud signals', () => {
test('a won dispute reverses the limit as the system', async () => {
const target = await createTestAccount(harness);
await purchase(target, 'pi_dispute_won');
+ await fraudWarning('pi_dispute_won');
await chargeback('pi_dispute_won');
await clearTestEmails(harness);
await chargeback('pi_dispute_won', 'won');
@@ -190,6 +207,7 @@ describe('Enforcement for payment fraud signals', () => {
test('a lost dispute leaves the limit in place', async () => {
const target = await createTestAccount(harness);
await purchase(target, 'pi_dispute_lost');
+ await fraudWarning('pi_dispute_lost');
await chargeback('pi_dispute_lost');
await chargeback('pi_dispute_lost', 'lost');
expect((await onlyDecision(target)).status).toBe('active');
diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementValidation.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementValidation.test.ts
index d2e18395a..7a4708e51 100644
--- a/fluxer_api/src/api/enforcement/tests/EnforcementValidation.test.ts
+++ b/fluxer_api/src/api/enforcement/tests/EnforcementValidation.test.ts
@@ -222,7 +222,9 @@ describe('Enforcement decision validation', () => {
decisionBody({source: 'report', report_ids: [reportId], evidence}),
);
const decision = await getDecision(harness, staff, decisionId);
- expect(decision.notice.how_we_decided[0]).toBe('We reviewed this after a report.');
+ expect(decision.notice.how_we_decided[0]).toBe(
+ 'We reviewed this after a report, and a person on our team made the decision.',
+ );
});
test('a decision needs evidence or a note to the user', async () => {
diff --git a/fluxer_api/src/api/worker/tasks/ClosePaymentDisputeAccounts.ts b/fluxer_api/src/api/worker/tasks/ClosePaymentDisputeAccounts.ts
new file mode 100644
index 000000000..2e170ac52
--- /dev/null
+++ b/fluxer_api/src/api/worker/tasks/ClosePaymentDisputeAccounts.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createUserID} from '@app/api/BrandedTypes';
+import {OAuth2TokenRepository} from '@app/api/oauth/repositories/OAuth2TokenRepository';
+import {PaymentDisputeEnforcementService} from '@app/api/payment_disputes/PaymentDisputeEnforcement';
+import {PaymentDisputeRepository} from '@app/api/payment_disputes/PaymentDisputeRepository';
+import {createWorkerEnforcementServices} from '@app/api/worker/tasks/admin_bulk/AdminBulkServices';
+import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
+import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
+import {ms} from 'itty-time';
+
+const SWEEP_MIN_CLOSED_AGE_MS = ms('10 minutes');
+
+const closePaymentDisputeAccounts: WorkerTaskHandler = async (payload, helpers) => {
+ const deps = getWorkerDependencies();
+ const repository = new PaymentDisputeRepository();
+ const purchaserId = typeof payload.purchaser_id === 'string' ? createUserID(BigInt(payload.purchaser_id)) : null;
+ const sweepBefore = Date.now() - SWEEP_MIN_CLOSED_AGE_MS;
+ const reviews = purchaserId
+ ? await repository.listReviewsByPurchaser(purchaserId)
+ : (await repository.listReviews()).filter((review) => (review.closed_at?.getTime() ?? Infinity) <= sweepBefore);
+ const {auditService, enforcementService} = createWorkerEnforcementServices(deps);
+ const service = new PaymentDisputeEnforcementService({
+ repository,
+ userRepository: deps.userRepository,
+ userCacheService: deps.userCacheService,
+ emailService: deps.emailService,
+ cacheService: deps.cacheService,
+ gatewayService: deps.gatewayService,
+ auditService,
+ kvDeletionQueue: deps.deletionQueueService,
+ oauth2Tokens: new OAuth2TokenRepository(),
+ systemDm: null,
+ enforcement: enforcementService,
+ });
+ const failed = await service.closeWaitingAccounts(reviews);
+ if (failed > 0 && purchaserId) {
+ throw new Error(`Failed to close the account after ${failed} payment disputes, retrying`);
+ }
+ if (failed > 0) {
+ helpers.logger.warn({failed}, 'Some lost unjustified payment disputes could not close their account yet');
+ }
+};
+
+export default closePaymentDisputeAccounts;
diff --git a/fluxer_api/src/api/worker/tasks/admin_bulk/AdminBulkServices.ts b/fluxer_api/src/api/worker/tasks/admin_bulk/AdminBulkServices.ts
index fc3b7efb8..3131081e8 100644
--- a/fluxer_api/src/api/worker/tasks/admin_bulk/AdminBulkServices.ts
+++ b/fluxer_api/src/api/worker/tasks/admin_bulk/AdminBulkServices.ts
@@ -18,6 +18,7 @@ import {
getGuildDiscoveryRepository,
getInviteRepository,
} from '@app/api/middleware/ServiceSingletons';
+import {queuePaymentDisputeClosures} from '@app/api/payment_disputes/PaymentDisputeEnforcement';
import type {SystemDmDeps} from '@app/api/user/services/SystemDmMessage';
import {UserChannelService} from '@app/api/user/services/UserChannelService';
import type {WorkerDependencies} from '@app/api/worker/WorkerDependencies';
@@ -97,6 +98,7 @@ export function createWorkerEnforcementServices(deps: WorkerDependencies): Worke
userCacheService: deps.userCacheService,
reporterResolutionNotifier,
}),
+ onClosureEnded: queuePaymentDisputeClosures,
});
return {apiContext, auditService, banManagementService, reporterResolutionNotifier, delivery, enforcementService};
}