Skip to content

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

TypeScript fluxerfluxerapp

feat(api): show pass badges, check verification on profile edits

Hampus0d2259759c56
diff --git a/fluxer_api/src/api/user/services/PartialUserChangePropagation.ts b/fluxer_api/src/api/user/services/PartialUserChangePropagation.ts
index ae70be8e6..dfeeb5a0d 100644
--- a/fluxer_api/src/api/user/services/PartialUserChangePropagation.ts
+++ b/fluxer_api/src/api/user/services/PartialUserChangePropagation.ts
@@ -7,6 +7,7 @@ import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
import {createRequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import type {User} from '@app/api/models/User';
+import {followOperatorPassWallStanding} from '@app/api/operator_pass/OperatorPassWallStanding';
import {dispatchUserUpdate, hasPartialUserFieldsChanged} from '@app/api/user/UserMappers';
import {runAllInOrder} from '@app/api/utils/ConcurrencyUtils';
@@ -54,10 +55,12 @@ export async function propagateUserUpdate(
const partial = async () => {
if (hasPartialUserFieldsChanged(oldUser, updatedUser)) await propagatePartialUserChange(deps, updatedUser);
};
+ const wall = () => followOperatorPassWallStanding(oldUser, updatedUser);
if (options.continueAfterDispatchFailure) {
- await runAllInOrder([dispatch, partial], 'Failed to propagate user update');
+ await runAllInOrder([dispatch, partial, wall], 'Failed to propagate user update');
} else {
await dispatch();
await partial();
+ await wall();
}
}
diff --git a/fluxer_api/src/api/user/services/UserAccountRequestService.ts b/fluxer_api/src/api/user/services/UserAccountRequestService.ts
index 4f931b762..4193c70a0 100644
--- a/fluxer_api/src/api/user/services/UserAccountRequestService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountRequestService.ts
@@ -1,21 +1,39 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import * as AuthEmailRevert from '@app/api/auth/AuthEmailRevert';
-import {requireEmailVerified} from '@app/api/auth/EmailVerificationUtils';
import {requireSudoMode, type SudoVerificationResult} from '@app/api/auth/services/SudoVerificationService';
import {createChannelID, createGuildID, type UserID} from '@app/api/BrandedTypes';
import type {UserConnectionRow} from '@app/api/database/types/ConnectionTypes';
import type {ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';
import {emitActivity} from '@app/api/infrastructure/activity/ActivityEvents';
import {isBlockedEmailDomain} from '@app/api/infrastructure/activity/SharedLists';
+import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
+import {usesUsernameSignIn} from '@app/api/instance/AccountIdentityModeCache';
import {Logger} from '@app/api/Logger';
import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import type {AuthSession} from '@app/api/models/AuthSession';
import type {User} from '@app/api/models/User';
-import type {HonoEnv} from '@app/api/types/HonoEnv';
+import {
+ dispatchOperatorPassUserUpdate,
+ type OperatorPassEntitlementService,
+ operatorPassPrivateFields,
+ profileOperatorPassSince,
+ resolveOperatorPassHolder,
+} from '@app/api/operator_pass/OperatorPassEntitlementService';
+import type {AuthTokenType, HonoEnv} from '@app/api/types/HonoEnv';
import {assertAccountNotLimited} from '@app/api/user/AccountLimit';
+import {
+ evaluateTierGateFor,
+ getAccountTier,
+ isInteractionTierEnforced,
+ NO_TIER_CONTEXT,
+ tierDenialError,
+} from '@app/api/user/AccountTier';
import {isProfileHidden} from '@app/api/user/ProfileVisibility';
+import {applyProfileBadgeSettings} from '@app/api/user/profile_badges/PremiumBadgeMasking';
+import {buildProfileBadges} from '@app/api/user/profile_badges/ProfileBadgeBuilder';
+import {loadProfileBadgeEnvironment} from '@app/api/user/profile_badges/ProfileBadgeEnvironment';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import type {EmailChangeService} from '@app/api/user/services/EmailChangeService';
import type {UserAccountService} from '@app/api/user/services/UserAccountService';
@@ -28,12 +46,17 @@ import {
mapUserToProfileResponse,
} from '@app/api/user/UserMappers';
import {extractEmailDomain} from '@app/api/utils/EmailDomainUtils';
-import {AccountIdentityModes} from '@fluxer/constants/src/AccountIdentityConstants';
+import {AccountTiers, TierGatedActions} from '@fluxer/constants/src/AccountTierConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {getCurrentTimeZoneOffsetMinutes} from '@fluxer/date_utils/src/TimeZoneUtils';
+import {UseClaimRouteError} from '@fluxer/errors/src/domains/auth/UseClaimRouteError';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {UnauthorizedError} from '@fluxer/errors/src/domains/core/UnauthorizedError';
import type {ConnectionResponse} from '@fluxer/schema/src/domains/connection/ConnectionSchemas';
+import type {
+ ProfileBadgePreviewRequest,
+ ProfileBadgePreviewResponse,
+} from '@fluxer/schema/src/domains/user/ProfileBadgeSchemas';
import type {
EmailChangeApplyRequest,
UserUpdateWithVerificationRequest,
@@ -50,7 +73,7 @@ type UserUpdatePayload = Omit<
'mfa_method' | 'mfa_code' | 'webauthn_response' | 'webauthn_challenge' | 'email_token'
>;
-const EMAIL_VERIFICATION_REQUIRED_PROFILE_UPDATE_FIELDS: ReadonlyArray<keyof UserUpdatePayload> = [
+const PROFILE_CUSTOMIZATION_FIELDS: ReadonlyArray<keyof UserUpdatePayload> = [
'username',
'discriminator',
'global_name',
@@ -65,10 +88,13 @@ const EMAIL_VERIFICATION_REQUIRED_PROFILE_UPDATE_FIELDS: ReadonlyArray<keyof Use
'premium_badge_masked',
'premium_badge_timestamp_hidden',
'premium_badge_sequence_hidden',
+ 'operator_pass_badge_hidden',
+ 'operator_pass_badge_timestamp_hidden',
+ 'operator_pass_badge_count_hidden',
];
function hasProfileCustomizationUpdate(data: UserUpdatePayload): boolean {
- return EMAIL_VERIFICATION_REQUIRED_PROFILE_UPDATE_FIELDS.some((field) => data[field] !== undefined);
+ return PROFILE_CUSTOMIZATION_FIELDS.some((field) => data[field] !== undefined);
}
function hasDefinedUserUpdatePayload(data: UserUpdatePayload): boolean {
@@ -92,6 +118,7 @@ interface UserProfileParams {
withMutualFriends?: boolean;
withMutualGuilds?: boolean;
requestCache: RequestCache;
+ requestLocale: string;
}
export class UserAccountRequestService {
@@ -101,13 +128,15 @@ export class UserAccountRequestService {
private readonly userChannelService: UserChannelService,
private readonly userRepository: UserRepository,
private readonly userCacheService: UserCacheService,
+ private readonly gatewayService: IGatewayService,
+ private readonly operatorPassEntitlementService: OperatorPassEntitlementService | null = null,
) {}
- getCurrentUserResponse(params: {
- authTokenType?: 'session' | 'bearer' | 'bot' | 'admin_api_key';
+ async getCurrentUserResponse(params: {
+ authTokenType?: AuthTokenType;
oauthBearerScopes?: Set<string> | null;
user?: User;
- }): UserPrivateResponse {
+ }): Promise<UserPrivateResponse> {
const tokenType = params.authTokenType;
if (tokenType === 'bearer') {
const bearerUser = params.user;
@@ -124,11 +153,19 @@ export class UserAccountRequestService {
}
const user = params.user;
if (user) {
- return mapUserToPrivateResponse(user);
+ return this.withOperatorPassFields(user, mapUserToPrivateResponse(user));
}
throw new UnauthorizedError();
}
+ private async withOperatorPassFields<T extends UserPrivateResponse>(user: User, response: T): Promise<T> {
+ if (!this.operatorPassEntitlementService || user.isBot) {
+ return response;
+ }
+ const holder = await this.operatorPassEntitlementService.getHolder(user);
+ return {...response, ...operatorPassPrivateFields(user, holder)};
+ }
+
async updateCurrentUser(params: {
ctx: Context<HonoEnv>;
user: User;
@@ -149,21 +186,26 @@ export class UserAccountRequestService {
let userUpdateData: UserUpdatePayload = userUpdateDataRest;
const emailTokenProvided = emailToken !== undefined;
if (!emailTokenProvided && !hasDefinedUserUpdatePayload(userUpdateData)) {
- return mapUserToPrivateResponse(user);
+ return this.withOperatorPassFields(user, mapUserToPrivateResponse(user));
}
if (userUpdateData.email !== undefined) {
throw InputValidationError.fromCode('email', ValidationErrorCodes.EMAIL_MUST_BE_CHANGED_VIA_TOKEN);
}
- const isUnclaimed = user.isUnclaimedAccount();
- if (!isUnclaimed && userUpdateData.new_password !== undefined && !userUpdateData.password) {
+ const isUnclaimed = getAccountTier(user) === AccountTiers.UNCLAIMED;
+ const usernameSignIn = usesUsernameSignIn();
+ if (
+ !isUnclaimed &&
+ userUpdateData.new_password !== undefined &&
+ !userUpdateData.password &&
+ user.passwordHash !== null
+ ) {
throw InputValidationError.fromCode('password', ValidationErrorCodes.PASSWORD_NOT_SET);
}
- if (isUnclaimed) {
+ const profileCustomization = hasProfileCustomizationUpdate(userUpdateData);
+ const profileGate = evaluateTierGateFor(user, TierGatedActions.PROFILE_CUSTOMIZE, NO_TIER_CONTEXT);
+ if (isUnclaimed && !profileGate.allowed) {
const allowed = new Set(['new_password', 'has_dismissed_premium_onboarding', 'has_unread_gift_inventory']);
- if (
- userUpdateData.new_password !== undefined &&
- (await ctx.get('instanceConfigRepository').getAccountIdentityMode()) === AccountIdentityModes.USERNAME
- ) {
+ if (userUpdateData.new_password !== undefined && usernameSignIn) {
allowed.add('username');
}
const disallowedField = Object.keys(userUpdateData).find((key) => !allowed.has(key));
@@ -171,13 +213,16 @@ export class UserAccountRequestService {
throw InputValidationError.fromCode(
disallowedField,
ValidationErrorCodes.UNCLAIMED_ACCOUNTS_CAN_ONLY_SET_EMAIL_VIA_TOKEN,
+ {need: profileGate.need},
);
}
+ } else {
+ if (isUnclaimed && userUpdateData.new_password !== undefined && !usernameSignIn && !emailTokenProvided) {
+ throw new UseClaimRouteError();
+ }
+ if (profileCustomization && !profileGate.allowed) throw tierDenialError(profileGate);
}
- if (!isUnclaimed && hasProfileCustomizationUpdate(userUpdateData)) {
- requireEmailVerified(user, 'profile');
- assertAccountNotLimited(user);
- }
+ if (profileCustomization) assertAccountNotLimited(user);
let emailFromToken: string | null = null;
let emailVerifiedViaToken = false;
const needsVerification = this.requiresSensitiveUserVerification(user, userUpdateData, emailTokenProvided);
@@ -214,6 +259,7 @@ export class UserAccountRequestService {
new_email: updatedUser.email,
was_unclaimed: isUnclaimed,
has_ever_purchased: updatedUser.hasEverPurchased,
+ origin: 'user',
});
}
if (profileFieldsChanged(user, updatedUser)) {
@@ -237,7 +283,22 @@ export class UserAccountRequestService {
Logger.warn({error, userId: updatedUser.id}, 'Failed to issue email revert token');
}
}
- const response = mapUserToPrivateResponse(updatedUser);
+ if (
+ (userUpdateData.operator_pass_badge_hidden !== undefined ||
+ userUpdateData.operator_pass_badge_timestamp_hidden !== undefined ||
+ userUpdateData.operator_pass_badge_count_hidden !== undefined) &&
+ this.operatorPassEntitlementService
+ ) {
+ await dispatchOperatorPassUserUpdate(
+ {
+ repository: this.operatorPassEntitlementService.repository,
+ userRepository: this.userRepository,
+ gatewayService: this.gatewayService,
+ },
+ updatedUser.id,
+ );
+ }
+ const response = await this.withOperatorPassFields(updatedUser, mapUserToPrivateResponse(updatedUser));
if (!authSessionReplacement) {
return response;
}
@@ -278,14 +339,18 @@ export class UserAccountRequestService {
async getUserProfile(params: UserProfileParams): Promise<UserProfileFullResponse> {
const guildId = params.guildId ? createGuildID(params.guildId) : undefined;
- const profile = await this.userAccountService.lookupService.getUserProfile({
- userId: params.currentUserId,
- targetId: params.targetUserId,
- guildId,
- withMutualFriends: params.withMutualFriends,
- withMutualGuilds: params.withMutualGuilds,
- requestCache: params.requestCache,
- });
+ const [profile, operatorPassState, badgeEnvironment] = await Promise.all([
+ this.userAccountService.lookupService.getUserProfile({
+ userId: params.currentUserId,
+ targetId: params.targetUserId,
+ guildId,
+ withMutualFriends: params.withMutualFriends,
+ withMutualGuilds: params.withMutualGuilds,
+ requestCache: params.requestCache,
+ }),
+ this.operatorPassEntitlementService?.loadState(params.targetUserId) ?? null,
+ loadProfileBadgeEnvironment(),
+ ]);
let profileUser = profile.user;
let premiumType = profile.premiumType;
let premiumSince = profile.premiumSince;
@@ -313,7 +378,10 @@ export class UserAccountRequestService {
}
const restrictProfile = profile.restrictProfile;
const hidden = isProfileHidden(profileUser);
- const userProfile = mapUserToProfileResponse(profileUser, {restrictProfile});
+ const userProfile = mapUserToProfileResponse(profileUser, {
+ restrictProfile,
+ viewerIsSelf: params.currentUserId === profileUser.id,
+ });
const guildMemberProfile = mapGuildMemberToProfileResponse(profile.guildMemberDomain ?? null, {
restrictProfile,
hidden,
@@ -328,6 +396,23 @@ export class UserAccountRequestService {
: undefined;
const connectedAccounts =
profile.connections && !hidden ? this.mapConnectionsToResponse(profile.connections) : undefined;
+ const operatorPassSince = operatorPassState
+ ? profileOperatorPassSince({
+ user: profileUser,
+ state: operatorPassState,
+ viewerId: params.currentUserId,
+ restrictProfile,
+ })
+ : null;
+ const profileBadges = buildProfileBadges({
+ user: profileUser,
+ operatorPass: profileUser.isBot || !operatorPassState ? null : resolveOperatorPassHolder(operatorPassState),
+ locale: params.requestLocale,
+ environment: badgeEnvironment,
+ restricted: restrictProfile,
+ hidden,
+ viewerIsSelf: params.currentUserId === profileUser.id,
+ });
return {
user:
params.requestCache.userPartials.get(profileUser.id) ??
@@ -338,6 +423,8 @@ export class UserAccountRequestService {
premium_type: premiumType,
premium_since: premiumSince?.toISOString(),
premium_lifetime_sequence: premiumLifetimeSequence,
+ profile_badges: profileBadges,
+ operator_pass_since: operatorPassSince?.toISOString() ?? null,
mutual_friends: mutualFriends,
mutual_guilds: profile.mutualGuilds,
connected_accounts: connectedAccounts,
@@ -346,6 +433,35 @@ export class UserAccountRequestService {
};
}
+ async previewProfileBadges(params: {
+ user: User;
+ settings: ProfileBadgePreviewRequest;
+ requestLocale: string;
+ }): Promise<ProfileBadgePreviewResponse> {
+ const {user} = params;
+ const [operatorPassState, environment] = await Promise.all([
+ user.isBot ? null : (this.operatorPassEntitlementService?.loadState(user.id) ?? null),
+ loadProfileBadgeEnvironment(),
+ ]);
+ const expired = shouldStripExpiredPremium(user);
+ return {
+ profile_badges: buildProfileBadges({
+ user: {
+ flags: user.flags,
+ premiumFlags: user.premiumFlags,
+ premiumType: expired ? null : user.premiumType,
+ premiumSince: expired ? null : user.premiumSince,
+ premiumLifetimeSequence: expired ? null : user.premiumLifetimeSequence,
+ },
+ operatorPass: operatorPassState ? resolveOperatorPassHolder(operatorPassState) : null,
+ locale: params.requestLocale,
+ environment,
+ hidden: isProfileHidden(user),
+ previewPremiumFlags: applyProfileBadgeSettings(user.premiumFlags, params.settings),
+ }),
+ };
+ }
+
checkTagAvailability(params: {currentUser: User; username: string; discriminator: number}): boolean {
const currentUser = params.currentUser;
const discriminator = params.discriminator;
@@ -378,6 +494,7 @@ export class UserAccountRequestService {
response.premium_purchase_disabled = false;
response.premium_enabled_override = false;
response.premium_perks_disabled = false;
+ response.operator_pass_since = null;
response.has_dismissed_premium_onboarding = false;
response.has_ever_purchased = false;
response.has_unread_gift_inventory = false;
@@ -386,13 +503,13 @@ export class UserAccountRequestService {
}
private requiresSensitiveUserVerification(user: User, data: UserUpdatePayload, emailTokenProvided: boolean): boolean {
- const isUnclaimed = user.isUnclaimedAccount();
+ const isUnclaimed = getAccountTier(user) === AccountTiers.UNCLAIMED;
const usernameChanged = data.username !== undefined && data.username !== user.username;
const discriminatorChanged = data.discriminator !== undefined && data.discriminator !== user.discriminator;
const emailChanged = data.email !== undefined && data.email !== user.email;
const newPasswordProvided = data.new_password !== undefined;
if (isUnclaimed) {
- return usernameChanged || discriminatorChanged;
+ return !isInteractionTierEnforced() && (usernameChanged || discriminatorChanged);
}
return usernameChanged || discriminatorChanged || emailTokenProvided || emailChanged || newPasswordProvided;
}
diff --git a/fluxer_api/src/api/user/services/UserAccountService.ts b/fluxer_api/src/api/user/services/UserAccountService.ts
index 5d79a41ea..d2b097ff7 100644
--- a/fluxer_api/src/api/user/services/UserAccountService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountService.ts
@@ -2,6 +2,7 @@
import type {ApiContext} from '@app/api/ApiContext';
import type {SudoVerificationResult} from '@app/api/auth/services/SudoVerificationService';
+import {Config} from '@app/api/Config';
import type {ConnectionRepository} from '@app/api/connection/ConnectionRepository';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import type {GuildService} from '@app/api/guild/services/GuildService';
@@ -12,9 +13,11 @@ import type {KVAccountDeletionQueueService} from '@app/api/infrastructure/KVAcco
import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
import {Logger} from '@app/api/Logger';
import type {LimitConfigService} from '@app/api/limits/LimitConfigService';
+import {getOperatorPassWallService} from '@app/api/middleware/ServiceSingletons';
import type {AuthSession} from '@app/api/models/AuthSession';
import type {User} from '@app/api/models/User';
import {enqueueStripeCustomerEmailSync} from '@app/api/stripe/StripeCustomer';
+import {isOperatorPassCountHidden} from '@app/api/user/profile_badges/PremiumBadgeMasking';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {
type PartialUserChangePropagationDeps,
@@ -178,6 +181,37 @@ export class UserAccountService {
}
},
() => propagateUserUpdate(this.userUpdateDeps, user, updatedUser, {continueAfterDispatchFailure: true}),
+ async () => {
+ const changed =
+ user.username !== updatedUser.username ||
+ user.globalName !== updatedUser.globalName ||
+ user.avatarHash !== updatedUser.avatarHash;
+ if (!changed || Config.instance.selfHosted) {
+ return;
+ }
+ try {
+ await getOperatorPassWallService().onProfileChanged(updatedUser, {
+ username: user.username,
+ globalName: user.globalName,
+ avatarHash: user.avatarHash,
+ });
+ } catch (error) {
+ Logger.error({error, userId: user.id}, "Failed to follow a profile change on the Operators' wall");
+ }
+ },
+ async () => {
+ if (
+ Config.instance.selfHosted ||
+ isOperatorPassCountHidden(user.premiumFlags) === isOperatorPassCountHidden(updatedUser.premiumFlags)
+ ) {
+ return;
+ }
+ try {
+ await getOperatorPassWallService().publication.publishChanges([updatedUser.id], 'preserve');
+ } catch (error) {
+ Logger.error({error, userId: user.id}, "Failed to publish an Operators' wall count visibility change");
+ }
+ },
async () => {
const nameChanged =
user.username !== updatedUser.username ||