A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(api): derive usernames from display names
Hampus36f2b9680617
diff --git a/fluxer_api/src/api/auth/tests/RegistrationUsernameDerivation.test.ts b/fluxer_api/src/api/auth/tests/RegistrationUsernameDerivation.test.tsnew file mode 100644index 000000000..617619764--- /dev/null+++ b/fluxer_api/src/api/auth/tests/RegistrationUsernameDerivation.test.ts@@ -0,0 +1,119 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createAuthHarness, registerUser} from '@app/api/auth/tests/AuthTestUtils';+import {getKvMeta} from '@app/api/database/CassandraMetaRegistry';+import {+ type CassandraQueryExecutorForTesting,+ setCassandraQueryExecutorForTesting,+} from '@app/api/database/CassandraQueryExecution';+import type {CassandraParams, PreparedQuery} from '@app/api/database/CassandraTypes';+import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';+import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';+import {createBuilder} from '@app/api/test/TestRequestBuilder';+import type {UserPrivateResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';++const DISCRIMINATOR_CAPACITY = 9999;+const AVAILABLE_DISCRIMINATOR = 42;+const ALL_CLAIMS = Array.from({length: DISCRIMINATOR_CAPACITY}, (_, index) => String(index + 1));+const CLAIMS_WITH_ONE_AVAILABLE = ALL_CLAIMS.filter((value) => value !== String(AVAILABLE_DISCRIMINATOR));++describe('registration username derivation through the public API', () => {+ let harness: ApiTestHarness;+ const storage = new InMemoryCassandraQueryExecutor();+ const seededKeys = new Set<string>();+ const requests = new Set<Promise<UserPrivateResponse>>();+ let exhaustedNames: RegExp | null = null;+ let armed = false;++ beforeAll(async () => {+ harness = await createAuthHarness();+ });++ beforeEach(async () => {+ seededKeys.clear();+ exhaustedNames = null;+ armed = false;+ const executor: CassandraQueryExecutorForTesting = {+ async executeQuery<T, P extends CassandraParams>(query: PreparedQuery<P>): Promise<Array<T>> {+ const metadata = query.kvMeta ?? getKvMeta(query.cql);+ const username = query.params.username;+ if (+ armed &&+ metadata?.table.name === 'users_by_username' &&+ metadata.action === 'select' &&+ typeof username === 'string' &&+ query.params.discriminator === undefined+ ) {+ const key = `discrim-claimed:${username}`;+ if (!seededKeys.has(key)) {+ seededKeys.add(key);+ const claims = exhaustedNames?.test(username) ? ALL_CLAIMS : CLAIMS_WITH_ONE_AVAILABLE;+ await harness.kvProvider.sadd(key, ...claims);+ }+ }+ return storage.executeQuery<T>(query);+ },+ executeBatch: (queries, atomic) => storage.executeBatch(queries, atomic),+ reset: () => storage.reset(),+ };+ setCassandraQueryExecutorForTesting(executor);+ await harness.reset();+ });++ afterEach(async () => {+ armed = false;+ try {+ await Promise.allSettled(requests);+ } finally {+ setCassandraQueryExecutorForTesting(storage);+ try {+ if (seededKeys.size > 0) {+ await harness.kvProvider.del(...seededKeys);+ }+ } finally {+ requests.clear();+ seededKeys.clear();+ exhaustedNames = null;+ }+ }+ });++ afterAll(async () => {+ await harness.shutdown();+ });++ function registerDerivedName(exhausted: RegExp | null): Promise<UserPrivateResponse> {+ exhaustedNames = exhausted;+ armed = true;+ const request = registerUser(harness, {+ email: '[email protected]',+ password: 'a-strong-password',+ global_name: 'Åsa',+ date_of_birth: '2000-01-01',+ consent: true,+ }).then(({token}) => createBuilder<UserPrivateResponse>(harness, token).get('/users/@me').execute());+ requests.add(request);+ return request;+ }++ it('gives the derived name a tag', async () => {+ const user = await registerDerivedName(null);+ expect(user).toMatchObject({username: 'Asa', discriminator: '0042', global_name: 'Åsa'});+ expect(seededKeys.has('discrim-claimed:asa')).toBe(true);+ });++ it('moves to a close variant when every tag for the name is in use', async () => {+ const user = await registerDerivedName(/^asa$/u);+ expect(user.username).toMatch(/^Asa[1-9]\d{0,3}$/u);+ expect(user.discriminator).toBe('0042');+ expect(await harness.kvProvider.smembers('discrim-claimed:asa')).toHaveLength(9999);+ });++ it('falls back to a generated name when the variants are full too', async () => {+ const user = await registerDerivedName(/^asa(?:[1-9]\d{0,3})?$/u);+ expect(user.username.toLowerCase().startsWith('asa')).toBe(false);+ expect(user.discriminator).toBe('0042');+ expect(await harness.kvProvider.smembers('discrim-claimed:asa')).toHaveLength(9999);+ });+});diff --git a/fluxer_api/src/api/user/UniqueUsernames.ts b/fluxer_api/src/api/user/UniqueUsernames.tsindex 3096a91ac..9bed6bc88 100644--- a/fluxer_api/src/api/user/UniqueUsernames.ts+++ b/fluxer_api/src/api/user/UniqueUsernames.ts@@ -1,10 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {randomInt} from 'node:crypto';import type {UserID} from '@app/api/BrandedTypes';import type {User} from '@app/api/models/User';import type {UserRepository} from '@app/api/user/repositories/UserRepository';import {USERNAME_MODE_DISCRIMINATOR} from '@app/api/user/UserTag';+import {randomUsernameVariant} from '@app/api/utils/UsernameSuggestionUtils';import {DELETED_USER_USERNAME, UserFlags} from '@fluxer/constants/src/UserConstants';import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';@@ -28,7 +28,6 @@ export interface ParsedLoginHandle {discriminator: number | null;}-const USERNAME_MAX_LENGTH = 32;const RESERVATION_TTL_SECONDS = 15;const RESERVATION_WAIT_MS = ms('5 seconds');const RESERVATION_RETRY_MS = 50;@@ -119,14 +118,9 @@ export async function reserveUsername(return {username, release};}-function withNumericSuffix(base: string, suffix: number): string {- const suffixText = String(suffix);- return `${base.slice(0, USERNAME_MAX_LENGTH - suffixText.length)}${suffixText}`;-}-export async function deriveAvailableUsername(users: UsernameLookup, base: string): Promise<string> {for (let attempt = 0; attempt < DERIVE_ATTEMPTS; attempt++) {- const candidate = attempt === 0 ? base : withNumericSuffix(base, randomInt(1, 10000));+ const candidate = attempt === 0 ? base : randomUsernameVariant(base);if (!(await isUsernameTaken(users, candidate))) return candidate;}throw usernameTakenError();diff --git a/fluxer_api/src/api/utils/UsernameSuggestionUtils.ts b/fluxer_api/src/api/utils/UsernameSuggestionUtils.tsindex 9ab2100a0..d6cc5dfd2 100644--- a/fluxer_api/src/api/utils/UsernameSuggestionUtils.ts+++ b/fluxer_api/src/api/utils/UsernameSuggestionUtils.ts@@ -1,9 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {randomInt} from 'node:crypto';+import {generateRandomUsername} from '@app/api/utils/UsernameGenerator';import {UsernameType} from '@fluxer/schema/src/primitives/UserValidators';import {transliterate as tr} from 'transliteration';const MAX_USERNAME_LENGTH = 32;+const RESERVED_TERMS = /fluxer|system_?message/giu;export function normaliseUsernameCandidate(value: string): string {const trimmed = value.trim();@@ -17,18 +20,41 @@ export function normaliseUsernameCandidate(value: string): string {return sanitized;}-function sanitizeDisplayName(globalName: string): string | null {- const sanitized = normaliseUsernameCandidate(globalName);- if (!sanitized) return null;- const validation = UsernameType.safeParse(sanitized);- if (!validation.success) {- return null;- }- return sanitized;+function tidyUnderscores(value: string): string {+ return value.replace(/_+/g, '_').replace(/^_+|_+$/g, '');+}++function displayNameCandidate(globalName: string): string {+ const transliterated = tidyUnderscores(normaliseUsernameCandidate(globalName.normalize('NFKC')));+ return tidyUnderscores(transliterated.replace(RESERVED_TERMS, '_'));+}++function isValidUsername(value: string): boolean {+ return UsernameType.safeParse(value).success;}export function deriveUsernameFromDisplayName(globalName: string): string | null {- return sanitizeDisplayName(globalName);+ const candidate = displayNameCandidate(globalName);+ return candidate && isValidUsername(candidate) ? candidate : null;+}++function withNumericSuffix(base: string, suffix: number): string {+ const suffixText = String(suffix);+ return `${base.slice(0, MAX_USERNAME_LENGTH - suffixText.length)}${suffixText}`;+}++export function randomUsernameVariant(base: string): string {+ return withNumericSuffix(base, randomInt(1, 10000));+}++export function usernameBaseFromDisplayName(globalName: string, isBlocked: (username: string) => boolean): string {+ const candidate = displayNameCandidate(globalName);+ if (candidate) {+ for (const option of [candidate, randomUsernameVariant(candidate)]) {+ if (isValidUsername(option) && !isBlocked(option)) return option;+ }+ }+ return generateRandomUsername();}export function generateUsernameSuggestions(globalName: string): Array<string> {diff --git a/fluxer_api/src/api/utils/tests/UsernameSuggestionUtils.test.ts b/fluxer_api/src/api/utils/tests/UsernameSuggestionUtils.test.tsnew file mode 100644index 000000000..a9dc957e3--- /dev/null+++ b/fluxer_api/src/api/utils/tests/UsernameSuggestionUtils.test.ts@@ -0,0 +1,61 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {usernameBaseFromDisplayName} from '@app/api/utils/UsernameSuggestionUtils';+import {UsernameType} from '@fluxer/schema/src/primitives/UserValidators';+import {describe, expect, it} from 'vitest';++const notBlocked = () => false;++describe('usernameBaseFromDisplayName', () => {+ it.each([+ {name: 'José Ñúñez', expected: 'Jose_Nunez'},+ {name: 'Åsa Öberg-Ärlig', expected: 'Asa_Oberg_Arlig'},+ {name: 'Дмитрий', expected: 'Dmitriy'},+ {name: 'Γιώργος', expected: 'Giorgos'},+ {name: 'さくら', expected: 'sakura'},+ {name: '李小龍', expected: 'Li_Xiao_Long'},+ {name: '김민준', expected: 'gimminjun'},+ {name: 'محمد', expected: 'mHmd'},+ {name: 'דוד', expected: 'dvd'},+ {name: 'Zoë 🦊', expected: 'Zoe'},+ {name: '𝓕𝓪𝓷𝓬𝔂', expected: 'Fancy'},+ {name: ' __Kai__ ', expected: 'Kai'},+ ])('derives $expected from $name', ({name, expected}) => {+ expect(usernameBaseFromDisplayName(name, notBlocked)).toBe(expected);+ });++ it('romanises Japanese kanji into a valid name', () => {+ const derived = usernameBaseFromDisplayName('山田太郎', notBlocked);+ expect(derived).toMatch(/^[A-Za-z_]+$/);+ expect(UsernameType.safeParse(derived).success).toBe(true);+ });++ it.each(['🦊✨', '!!!', '・・・', '❤️🔥'])('falls back to a generated name for %s', (name) => {+ const derived = usernameBaseFromDisplayName(name, notBlocked);+ expect(derived).toMatch(/^[A-Z][a-z]+[A-Z][a-z]+$/);+ expect(UsernameType.safeParse(derived).success).toBe(true);+ });++ it('keeps long names within the username limit', () => {+ const derived = usernameBaseFromDisplayName('長い名前のテストユーザーです長い名前のテストユーザーです', notBlocked);+ expect(derived.length).toBeLessThanOrEqual(32);+ expect(derived.endsWith('_')).toBe(false);+ expect(UsernameType.safeParse(derived).success).toBe(true);+ });++ it('drops reserved terms and keeps the rest of the name', () => {+ expect(usernameBaseFromDisplayName('Fluxer Fan', notBlocked)).toBe('Fan');+ expect(usernameBaseFromDisplayName('my system message', notBlocked)).toBe('my');+ });++ it('adds digits to a name that is reserved on its own', () => {+ expect(usernameBaseFromDisplayName('everyone 🎉', notBlocked)).toMatch(/^everyone\d{1,4}$/);+ expect(usernameBaseFromDisplayName('Here', notBlocked)).toMatch(/^Here\d{1,4}$/);+ });++ it('picks a generated name when the derived one is blocked', () => {+ const derived = usernameBaseFromDisplayName('Rude Word', (username) => username.toLowerCase().includes('rude'));+ expect(derived.toLowerCase()).not.toContain('rude');+ expect(UsernameType.safeParse(derived).success).toBe(true);+ });+});