Skip to content

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

TypeScript fluxerfluxerapp

feat(api/admin): show badges and account status in user lookups

Hampus904e3fc1e0a3
diff --git a/fluxer_api/src/api/admin/models/UserTypes.ts b/fluxer_api/src/api/admin/models/UserTypes.ts
index 82f7b45ad..bb0e3b210 100644
--- a/fluxer_api/src/api/admin/models/UserTypes.ts
+++ b/fluxer_api/src/api/admin/models/UserTypes.ts
@@ -1,14 +1,27 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type {UserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
import {hasAdminACL} from '@app/api/middleware/AdminMiddleware';
+import {getOperatorPassRepository} from '@app/api/middleware/ServiceSingletons';
import type {User} from '@app/api/models/User';
+import {
+ loadOperatorPassEntitlementState,
+ resolveOperatorPassHolder,
+} from '@app/api/operator_pass/OperatorPassEntitlementService';
+import {getAccountTier} from '@app/api/user/AccountTier';
+import {isDateOfBirthMissing} from '@app/api/user/DateOfBirth';
+import {isProfileHidden} from '@app/api/user/ProfileVisibility';
+import {buildOperatorProfileBadges} 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 {getIpAddressReverse, lookupGeoip} from '@app/api/utils/IpUtils';
+import {AccountTiers} from '@fluxer/constants/src/AccountTierConstants';
import {AdminACLs, filterKnownAdminACLs} from '@fluxer/constants/src/AdminACLs';
import {DeletionReasons} from '@fluxer/constants/src/Core';
import type {ValueOf} from '@fluxer/constants/src/ValueOf';
import type {AdminResolvedUser, UserAdminResponse} from '@fluxer/schema/src/domains/admin/AdminUserSchemas';
+import type {AdminProfileBadgeResponse} from '@fluxer/schema/src/domains/user/ProfileBadgeSchemas';
import type {ICacheService} from '@pkgs/cache/src/ICacheService';
import {formatGeoipLocation} from '@pkgs/geoip/src/GeoipLookup';
@@ -18,17 +31,39 @@ function deletionReasonCode(code: number | null): ValueOf<typeof DeletionReasons
return code !== null && DELETION_REASON_CODES.has(code) ? (code as ValueOf<typeof DeletionReasons>) : null;
}
+async function buildAdminProfileBadges(
+ user: User,
+ locale: string | undefined,
+): Promise<Array<AdminProfileBadgeResponse>> {
+ const [operatorPassState, environment] = await Promise.all([
+ Config.instance.selfHosted || user.isBot
+ ? null
+ : loadOperatorPassEntitlementState(getOperatorPassRepository(), user.id),
+ loadProfileBadgeEnvironment(),
+ ]);
+ return buildOperatorProfileBadges({
+ user,
+ operatorPass: operatorPassState ? resolveOperatorPassHolder(operatorPassState) : null,
+ locale,
+ environment,
+ hidden: isProfileHidden(user),
+ });
+}
+
export async function mapUserToAdminResponse(
user: User,
cacheService?: ICacheService,
acls?: ReadonlySet<string>,
+ locale?: string,
): Promise<UserAdminResponse> {
const canViewEmail = !acls || hasAdminACL(acls, AdminACLs.USER_VIEW_EMAIL);
const canViewDob = !acls || hasAdminACL(acls, AdminACLs.USER_VIEW_DOB);
const canViewIp = !acls || hasAdminACL(acls, AdminACLs.USER_VIEW_IP);
const canViewAuditLog = !acls || hasAdminACL(acls, AdminACLs.AUDIT_LOG_VIEW);
- const lastActiveIpReverse =
- canViewIp && user.lastActiveIp ? await getIpAddressReverse(user.lastActiveIp, cacheService) : null;
+ const [lastActiveIpReverse, profileBadges] = await Promise.all([
+ canViewIp && user.lastActiveIp ? getIpAddressReverse(user.lastActiveIp, cacheService) : null,
+ buildAdminProfileBadges(user, locale),
+ ]);
let lastActiveLocation: string | null = null;
if (canViewIp && user.lastActiveIp) {
try {
@@ -39,6 +74,7 @@ export async function mapUserToAdminResponse(
lastActiveLocation = null;
}
}
+ const accountTier = getAccountTier(user);
return {
id: user.id.toString(),
username: user.username,
@@ -63,6 +99,7 @@ export async function mapUserToAdminResponse(
premium_until: user.premiumUntil?.toISOString() ?? null,
premium_grace_ends_at: user.premiumGraceEndsAt?.toISOString() ?? null,
premium_lifetime_sequence: user.premiumLifetimeSequence ?? null,
+ profile_badges: profileBadges,
temp_banned_until:
user.tempBannedUntil && user.tempBannedUntil.getTime() > Date.now() ? user.tempBannedUntil.toISOString() : null,
pending_deletion_at: user.pendingDeletionAt?.toISOString() ?? null,
@@ -76,6 +113,10 @@ export async function mapUserToAdminResponse(
acls: user.acls ? filterKnownAdminACLs(user.acls) : [],
traits: Array.from(user.traits).sort(),
has_totp: user.totpSecret !== null,
+ has_password: user.passwordHash !== null,
+ claimed: accountTier !== AccountTiers.UNCLAIMED,
+ account_tier: accountTier,
+ date_of_birth_required: isDateOfBirthMissing(user),
authenticator_types: user.authenticatorTypes ? Array.from(user.authenticatorTypes) : [],
last_active_at: user.lastActiveAt?.toISOString() ?? null,
last_active_ip: canViewIp ? (user.lastActiveIp ?? null) : null,
diff --git a/fluxer_api/src/api/admin/services/AdminUserLookupService.ts b/fluxer_api/src/api/admin/services/AdminUserLookupService.ts
index d562510e5..cb908b6aa 100644
--- a/fluxer_api/src/api/admin/services/AdminUserLookupService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserLookupService.ts
@@ -17,13 +17,13 @@ interface AdminUserLookupServiceDeps {
export class AdminUserLookupService {
constructor(private readonly deps: AdminUserLookupServiceDeps) {}
- async lookupUser(data: LookupUserRequest, acls: ReadonlySet<string>) {
+ async lookupUser(data: LookupUserRequest, acls: ReadonlySet<string>, locale?: string) {
const {users: userRepository, cache: cacheService} = this.deps.apiContext.services;
if ('user_ids' in data) {
const userIds = data.user_ids.map((id) => createUserID(id));
const users = await userRepository.listUsers(userIds);
return {
- users: await Promise.all(users.map((user) => mapUserToAdminResponse(user, cacheService, acls))),
+ users: await Promise.all(users.map((user) => mapUserToAdminResponse(user, cacheService, acls, locale))),
};
}
let user = null;
@@ -47,7 +47,7 @@ export class AdminUserLookupService {
user = (await this.findPersonByBareUsername(query)) ?? (await userRepository.findByStripeSubscriptionId(query));
}
return {
- users: user ? [await mapUserToAdminResponse(user, cacheService, acls)] : [],
+ users: user ? [await mapUserToAdminResponse(user, cacheService, acls, locale)] : [],
};
}
diff --git a/fluxer_api/src/api/user/tests/ProfileBadges.test.ts b/fluxer_api/src/api/user/tests/ProfileBadges.test.ts
new file mode 100644
index 000000000..3b850365d
--- /dev/null
+++ b/fluxer_api/src/api/user/tests/ProfileBadges.test.ts
@@ -0,0 +1,228 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {acceptInvite, createChannelInvite, createGuild, getGuildChannels} from '@app/api/guild/tests/GuildTestUtils';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {HTTP_STATUS} from '@app/api/test/TestConstants';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+import {PROFILE_BADGE_ASSETS} from '@app/api/user/profile_badges/ProfileBadgeAssets';
+import {VISIONARY_NUMBER_TAGS} from '@app/api/user/profile_badges/VisionaryNumberTags';
+import {PremiumFlags, ProfilePrivacyLevels, UserFlags, UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
+import type {UserAdminResponse} from '@fluxer/schema/src/domains/admin/AdminUserSchemas';
+import type {
+ ProfileBadgePreviewResponse,
+ ProfileBadgeResponse,
+} from '@fluxer/schema/src/domains/user/ProfileBadgeSchemas';
+import type {UserProfileFullResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
+
+type ProfileWithBadges = UserProfileFullResponse & {profile_badges: Array<ProfileBadgeResponse>};
+
+const PREMIUM_SINCE = '2026-10-15T12:00:00.000Z';
+
+describe('profile badges', () => {
+ let harness: ApiTestHarness;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+ afterAll(async () => {
+ await harness.shutdown();
+ });
+ beforeEach(async () => {
+ await harness.resetData();
+ });
+
+ async function shareGuild(owner: TestAccount, member: TestAccount): Promise<void> {
+ const guild = await createGuild(harness, owner.token, 'Shared');
+ const channels = await getGuildChannels(harness, owner.token, guild.id);
+ const invite = await createChannelInvite(harness, owner.token, channels[0]!.id);
+ await acceptInvite(harness, member.token, invite.code);
+ }
+
+ async function setFlags(account: TestAccount, flags: bigint): Promise<void> {
+ await createBuilder(harness, '')
+ .patch(`/test/users/${account.userId}/flags`)
+ .body({flags: flags.toString()})
+ .execute();
+ }
+
+ async function setPremium(account: TestAccount, body: Record<string, unknown>): Promise<void> {
+ await createBuilder(harness, '').post(`/test/users/${account.userId}/premium`).body(body).execute();
+ }
+
+ async function makeVisionary(account: TestAccount): Promise<void> {
+ await setPremium(account, {
+ premium_type: UserPremiumTypes.LIFETIME,
+ premium_since: PREMIUM_SINCE,
+ premium_lifetime_sequence: 42,
+ });
+ }
+
+ async function profile(
+ viewer: TestAccount,
+ target: TestAccount,
+ acceptLanguage?: string,
+ ): Promise<ProfileWithBadges> {
+ const builder = createBuilder<ProfileWithBadges>(harness, viewer.token).get(`/users/${target.userId}/profile`);
+ if (acceptLanguage) builder.header('Accept-Language', acceptLanguage);
+ return builder.expect(HTTP_STATUS.OK).execute();
+ }
+
+ async function preview(account: TestAccount, body: Record<string, boolean>): Promise<ProfileBadgePreviewResponse> {
+ return createBuilder<ProfileBadgePreviewResponse>(harness, account.token)
+ .post('/users/@me/profile-badges/preview')
+ .body(body)
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ }
+
+ const kinds = (response: {profile_badges: Array<{kind: string}>}) => response.profile_badges.map((b) => b.kind);
+
+ test('profiles list the badges with assets and labels in the viewer locale', async () => {
+ const target = await createTestAccount(harness);
+ const viewer = await createTestAccount(harness);
+ await shareGuild(target, viewer);
+ await setFlags(target, UserFlags.STAFF | UserFlags.BUG_HUNTER);
+ await makeVisionary(target);
+ const english = await profile(viewer, target);
+ expect(english.profile_badges).toEqual([
+ {
+ kind: 'staff',
+ label: 'Fluxer Staff',
+ asset: PROFILE_BADGE_ASSETS.staff,
+ aspect_ratio: null,
+ caption: null,
+ href: expect.any(String),
+ },
+ {
+ kind: 'bug_hunter',
+ label: 'Fluxer Bug Hunter',
+ asset: PROFILE_BADGE_ASSETS.bug_hunter,
+ aspect_ratio: null,
+ caption: null,
+ href: expect.any(String),
+ },
+ {
+ kind: 'visionary',
+ label: 'Fluxer Visionary since October 2026',
+ asset: PROFILE_BADGE_ASSETS.visionary,
+ aspect_ratio: null,
+ caption: null,
+ href: expect.stringMatching(/\/help\/visionary$/),
+ },
+ {
+ kind: 'visionary_number',
+ label: 'Visionary ID #42',
+ asset: VISIONARY_NUMBER_TAGS['42']!.asset,
+ aspect_ratio: 226 / 128,
+ caption: '#42',
+ href: expect.stringMatching(/\/help\/visionary$/),
+ },
+ ]);
+ });
+
+ test('a stored sequence of 0 shows #0 and an unset one shows no number', async () => {
+ const account = await createTestAccount(harness);
+ await makeVisionary(account);
+ await setPremium(account, {premium_lifetime_sequence: 0});
+ const [, number] = (await profile(account, account)).profile_badges;
+ expect(number).toMatchObject({kind: 'visionary_number', caption: '#0', asset: VISIONARY_NUMBER_TAGS['0']!.asset});
+ await setPremium(account, {premium_lifetime_sequence: null});
+ expect(kinds(await profile(account, account))).toEqual(['visionary']);
+ });
+
+ test('the stored viewer locale beats the Accept-Language header', async () => {
+ const target = await createTestAccount(harness);
+ const viewer = await createTestAccount(harness);
+ await shareGuild(target, viewer);
+ await makeVisionary(target);
+ const visionaryLabel = async (acceptLanguage: string) =>
+ (await profile(viewer, target, acceptLanguage)).profile_badges.find((badge) => badge.kind === 'visionary')?.label;
+ await createBuilder(harness, viewer.token).patch('/users/@me/settings').body({locale: 'de'}).execute();
+ expect(await visionaryLabel('ja')).toContain('Oktober 2026');
+ await createBuilder(harness, viewer.token).patch('/users/@me/settings').body({locale: 'ja'}).execute();
+ expect(await visionaryLabel('de')).toContain('2026年10月');
+ });
+
+ test('legacy premium fields keep their current shape', async () => {
+ const target = await createTestAccount(harness);
+ const viewer = await createTestAccount(harness);
+ await shareGuild(target, viewer);
+ await makeVisionary(target);
+ const response = await profile(viewer, target);
+ expect(response).toMatchObject({
+ premium_type: UserPremiumTypes.LIFETIME,
+ premium_since: PREMIUM_SINCE,
+ premium_lifetime_sequence: 42,
+ });
+ await createBuilder(harness, '')
+ .patch(`/test/users/${target.userId}/premium-flags`)
+ .body({premium_flags: PremiumFlags.BADGE_MASKED})
+ .execute();
+ const masked = await profile(viewer, target);
+ expect(masked.premium_type).toBe(UserPremiumTypes.SUBSCRIPTION);
+ expect(kinds(masked)).toEqual(['plutonium']);
+ });
+
+ test('a restricted viewer only sees the flag badges', async () => {
+ const target = await createTestAccount(harness);
+ const viewer = await createTestAccount(harness);
+ await shareGuild(target, viewer);
+ await setFlags(target, UserFlags.PARTNER);
+ await makeVisionary(target);
+ await createBuilder(harness, target.token)
+ .patch('/users/@me/settings')
+ .body({profile_privacy: ProfilePrivacyLevels.FRIENDS_ONLY})
+ .execute();
+ const response = await profile(viewer, target);
+ expect(response.profile_limited).toBe(true);
+ expect(kinds(response)).toEqual(['partner']);
+ expect(kinds(await profile(target, target))).toEqual(['partner', 'visionary', 'visionary_number']);
+ });
+
+ test('hidden accounts show no badges', async () => {
+ const target = await createTestAccount(harness);
+ const viewer = await createTestAccount(harness);
+ await shareGuild(target, viewer);
+ await setFlags(target, UserFlags.STAFF | UserFlags.PROFILE_HIDDEN);
+ await makeVisionary(target);
+ expect((await profile(viewer, target)).profile_badges).toEqual([]);
+ });
+
+ test('the preview reflects each setting without saving it', async () => {
+ const account = await createTestAccount(harness);
+ await makeVisionary(account);
+ expect(kinds(await preview(account, {}))).toEqual(['visionary', 'visionary_number']);
+ expect(kinds(await preview(account, {premium_badge_hidden: true}))).toEqual([]);
+ expect(kinds(await preview(account, {premium_badge_masked: true}))).toEqual(['plutonium']);
+ expect(kinds(await preview(account, {premium_badge_sequence_hidden: true}))).toEqual(['visionary']);
+ const dateless = await preview(account, {premium_badge_timestamp_hidden: true});
+ expect(dateless.profile_badges[0]?.label).toBe('Fluxer Visionary');
+ const saved = await createBuilder<{premium_badge_hidden: boolean}>(harness, account.token)
+ .get('/users/@me')
+ .execute();
+ expect(saved.premium_badge_hidden).toBe(false);
+ expect(kinds(await profile(account, account))).toEqual(['visionary', 'visionary_number']);
+ });
+
+ test('staff see every badge with the hidden ones marked', async () => {
+ const admin = await setUserACLs(harness, await createTestAccount(harness), ['admin:authenticate', 'user:lookup']);
+ const target = await createTestAccount(harness);
+ await setFlags(target, UserFlags.STAFF | UserFlags.STAFF_HIDDEN);
+ await makeVisionary(target);
+ await createBuilder(harness, '')
+ .patch(`/test/users/${target.userId}/premium-flags`)
+ .body({premium_flags: PremiumFlags.BADGE_HIDDEN})
+ .execute();
+ const {users} = await createBuilder<{users: Array<UserAdminResponse>}>(harness, admin.token)
+ .get(`/admin/users/${target.userId}`)
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ expect(users[0]!.profile_badges.map(({kind, suppressed}) => [kind, suppressed])).toEqual([
+ ['staff', true],
+ ['visionary', true],
+ ['visionary_number', true],
+ ]);
+ });
+});