Skip to content

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

TypeScript fluxerfluxerapp

feat(api/instance): publish sign-in, setup and contact details

Hampus25f2045c89d3
diff --git a/fluxer_api/src/api/instance/ContactEmails.ts b/fluxer_api/src/api/instance/ContactEmails.ts
index 11c5f2a06..6dcfd120b 100644
--- a/fluxer_api/src/api/instance/ContactEmails.ts
+++ b/fluxer_api/src/api/instance/ContactEmails.ts
@@ -4,22 +4,31 @@ import {Config} from '@app/api/Config';
export interface ContactEmails {
appealsEmail: string | null;
+ privacyEmail: string | null;
safetyEmail: string | null;
supportEmail: string | null;
}
const HOSTED_CONTACT_EMAILS: ContactEmails = {
appealsEmail: '[email protected]',
+ privacyEmail: '[email protected]',
safetyEmail: '[email protected]',
supportEmail: '[email protected]',
};
const SELF_HOSTED_CONTACT_EMAILS: ContactEmails = {
appealsEmail: null,
+ privacyEmail: null,
safetyEmail: null,
supportEmail: null,
};
+const HOSTED_LEGAL_ADDRESS = 'Fluxer Platform AB, c/o Embassy House, Östgötagatan 12, 116 25 Stockholm, Sweden';
+
+export function resolveLegalAddress(): string | null {
+ return Config.instance.selfHosted ? null : HOSTED_LEGAL_ADDRESS;
+}
+
export function resolveContactEmails(): ContactEmails {
return Config.instance.selfHosted ? SELF_HOSTED_CONTACT_EMAILS : HOSTED_CONTACT_EMAILS;
}
diff --git a/fluxer_api/src/api/instance/InstanceController.test.ts b/fluxer_api/src/api/instance/InstanceController.test.ts
index 4d392d074..b45d650c1 100644
--- a/fluxer_api/src/api/instance/InstanceController.test.ts
+++ b/fluxer_api/src/api/instance/InstanceController.test.ts
@@ -13,10 +13,6 @@ import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
import {Hono} from 'hono';
import {afterEach, describe, expect, it} from 'vitest';
-interface DiscoveryCaptcha {
- provider: string;
-}
-
describe('InstanceController discovery captcha', () => {
const repositories: Array<InstanceConfigRepository> = [];
@@ -46,6 +42,7 @@ describe('InstanceController discovery captcha', () => {
enabled: false,
enforced: false,
display_name: null,
+ button_label: null,
redirect_uri: '',
}),
} as unknown as SsoService);
@@ -66,7 +63,6 @@ describe('InstanceController discovery captcha', () => {
});
it('advertises no provider once an admin turns the captcha off', async () => {
- const repository = createRepository();
await repository.updateCaptchaConfig({enabled: false});
await expect(readCaptcha(repository)).resolves.toEqual({provider: 'none'});
diff --git a/fluxer_api/src/api/instance/InstanceController.ts b/fluxer_api/src/api/instance/InstanceController.ts
index 2326d572b..0160c3852 100644
--- a/fluxer_api/src/api/instance/InstanceController.ts
+++ b/fluxer_api/src/api/instance/InstanceController.ts
@@ -2,7 +2,6 @@
import {Config} from '@app/api/Config';
import type {NatsGifProvider} from '@app/api/gif/NatsGifProvider';
-import type {AccountIdentity} from '@app/api/instance/AccountIdentityModeCache';
import {withAccountIdentitySetupLock} from '@app/api/instance/AccountIdentitySetupLock';
import {
type DiscoveryValidators,
@@ -17,18 +16,31 @@ import {isBillingActive, isPremiumTieringActive, isStripeServiceable} from '@app
import type {HonoEnv} from '@app/api/types/HonoEnv';
import {requireConfiguredClientIp} from '@app/api/utils/RequestClientIp';
import {Validator} from '@app/api/Validator';
-import {AccountIdentityModes, TagStyles} from '@fluxer/constants/src/AccountIdentityConstants';
+import {
+ type EmailDeliveryState,
+ EmailDeliveryStates,
+ InstantAccountAvailability,
+} from '@fluxer/constants/src/AccountConfigConstants';
+import {
+ type AccountIdentity,
+ AccountIdentityDecisionSources,
+ AccountIdentityModes,
+ TagStyles,
+} from '@fluxer/constants/src/AccountIdentityConstants';
+import {resolveEffectiveVerificationBasis, resolveIdentifierFirst} from '@fluxer/constants/src/AccountTierRules';
import {API_CODE_VERSION} from '@fluxer/constants/src/AppConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {AccountIdentityLockedError} from '@fluxer/errors/src/domains/auth/AccountIdentityLockedError';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {buildDiscoveryResponse, type DiscoveryStaticInput} from '@fluxer/instance_bootstrap/src/BuildDiscovery';
import type {InstanceAppPublic} from '@fluxer/instance_bootstrap/src/Types';
+import type {AccountsConfig, AuthConfig} from '@fluxer/schema/src/domains/admin/AccountsConfigSchemas';
import type {CaptchaConfig} from '@fluxer/schema/src/domains/admin/CaptchaSchemas';
import {toDomainMigrationDiscovery} from '@fluxer/schema/src/domains/admin/DomainMigrationSchemas';
import {
InstanceAccountIdentityResponse,
InstanceAccountIdentityUpdateRequest,
+ InstanceSetupTokenCheckRequest,
WellKnownFluxerResponse,
} from '@fluxer/schema/src/domains/instance/InstanceSchemas';
import type {Hono} from 'hono';
@@ -40,10 +52,18 @@ function buildDiscoveryStaticInput(
appPublic: InstanceAppPublic,
runtime: {
captcha: CaptchaConfig;
- emailEnabled: boolean;
+ emailDeliveryState: EmailDeliveryState;
accountIdentity: AccountIdentity;
+ auth: AuthConfig;
+ accounts: AccountsConfig;
+ instantAccountAvailability: InstantAccountAvailability;
},
): DiscoveryStaticInput {
+ const signIn = resolveIdentifierFirst({
+ mode: runtime.auth.identifier_first,
+ identityMode: runtime.accountIdentity.mode,
+ deliveryState: runtime.emailDeliveryState,
+ });
const apiClientEndpoint = Config.endpoints.apiClient;
const apiPublicEndpoint = Config.endpoints.apiPublic;
let gifProvider: NatsGifProvider | undefined;
@@ -75,7 +95,7 @@ function buildDiscoveryStaticInput(
webapp: Config.endpoints.webApp,
},
captcha: {
- provider: runtime.captcha.enabled ? 'altcha' : 'none',
+ provider: runtime.captcha.provider,
},
features: {
voice_enabled: Config.voice.enabled,
@@ -84,11 +104,24 @@ function buildDiscoveryStaticInput(
stripe_serviceable: isStripeServiceable(),
self_hosted: Config.instance.selfHosted,
presigned_attachment_uploads: Config.presignedAttachmentUploadsEnabled,
- emails_enabled: runtime.emailEnabled,
- discovery_enabled: Config.discovery.enabled,
+ emails_enabled: runtime.emailDeliveryState === EmailDeliveryStates.ON,
phone_verification_enabled: false,
+ discovery_enabled: Config.discovery.enabled,
account_identity: runtime.accountIdentity.mode,
tag_style: runtime.accountIdentity.tagStyle,
+ identifier_first: signIn.identifierFirst,
+ instant_accounts: runtime.instantAccountAvailability === InstantAccountAvailability.AVAILABLE,
+ email_codes: signIn.emailCodes,
+ date_of_birth_step: true,
+ instant_account_availability: runtime.instantAccountAvailability,
+ interaction_tier: runtime.accounts.interaction_tier,
+ guild_join_gate: runtime.accounts.guild_join_gate,
+ email_delivery_state: runtime.emailDeliveryState,
+ verification_basis: resolveEffectiveVerificationBasis({
+ identityMode: runtime.accountIdentity.mode,
+ basis: runtime.accounts.verification_basis,
+ deliveryState: runtime.emailDeliveryState,
+ }),
},
gif: {
provider: gifProviderName,
@@ -122,24 +155,45 @@ export function InstanceController(app: Hono<HonoEnv>) {
const limits = ctx.get('limitConfigService').getConfigWireFormat();
const sso = await ctx.get('ssoService').getPublicStatus();
const instanceConfigRepository = ctx.get('instanceConfigRepository');
- const [registration, community, services, appPublicConfig, captcha, email, domainMigration, accountIdentity] =
- await Promise.all([
- instanceConfigRepository.getRegistrationPublicConfig(),
- instanceConfigRepository.getInstanceCommunityPublicConfig(),
- instanceConfigRepository.getResolvedServicesConfig(),
- instanceConfigRepository.getAppPublicConfig(),
- instanceConfigRepository.getCaptchaConfig(),
- instanceConfigRepository.getEffectiveEmailConfig(),
- instanceConfigRepository.getDomainMigrationConfig(),
- instanceConfigRepository.getAccountIdentity(),
- ]);
- const openSetup =
+ const [
+ registration,
+ community,
+ services,
+ appPublicConfig,
+ captcha,
+ emailDeliveryState,
+ domainMigration,
+ accountIdentity,
+ auth,
+ accounts,
+ instantAccountAvailability,
+ notice,
+ ] = await Promise.all([
+ instanceConfigRepository.getRegistrationPublicConfig(),
+ instanceConfigRepository.getInstanceCommunityPublicConfig(),
+ instanceConfigRepository.getResolvedServicesConfig(),
+ instanceConfigRepository.getAppPublicConfig(),
+ instanceConfigRepository.getCaptchaConfig(),
+ instanceConfigRepository.getEmailDeliveryState(),
+ instanceConfigRepository.getDomainMigrationConfig(),
+ instanceConfigRepository.getAccountIdentity(),
+ instanceConfigRepository.getAuthConfig(),
+ instanceConfigRepository.getAccountsConfig(),
+ instanceConfigRepository.getInstantAccountAvailability(),
+ instanceConfigRepository.getActiveInstanceNotice(),
+ ]);
+ const lockReason =
Config.instance.selfHosted && !appPublicConfig.setup.configured
- ? {
- account_identity_locked: await instanceConfigRepository.isAccountIdentityLocked(),
+ ? await instanceConfigRepository.getAccountIdentityLockReason()
+ : undefined;
+ const openSetup =
+ lockReason === undefined
+ ? {}
+ : {
+ account_identity_locked: lockReason !== null,
+ account_identity_lock_reason: lockReason,
setup_token_required: await instanceConfigRepository.isSetupTokenRequired(),
- }
- : {};
+ };
const discovery = buildDiscoveryResponse(
buildDiscoveryStaticInput(
gifService,
@@ -153,8 +207,11 @@ export function InstanceController(app: Hono<HonoEnv>) {
},
{
captcha,
- emailEnabled: email.enabled,
+ emailDeliveryState,
accountIdentity,
+ auth,
+ accounts,
+ instantAccountAvailability,
},
),
{
@@ -165,7 +222,7 @@ export function InstanceController(app: Hono<HonoEnv>) {
limits,
},
);
- const response = {...discovery, domain_migration: toDomainMigrationDiscovery(domainMigration)};
+ const response = {...discovery, notice, domain_migration: toDomainMigrationDiscovery(domainMigration)};
discoveryValidators = nextDiscoveryValidators(response, discoveryValidators);
ctx.header('ETag', discoveryValidators.etag);
ctx.header('Last-Modified', discoveryValidators.lastModified.toUTCString());
@@ -181,6 +238,33 @@ export function InstanceController(app: Hono<HonoEnv>) {
return ctx.json(response);
},
);
+ app.post(
+ '/instance/setup/token-checks',
+ RateLimitMiddleware(RateLimitConfigs.INSTANCE_SETUP_TOKEN_CHECK),
+ Validator('json', InstanceSetupTokenCheckRequest),
+ OpenAPI({
+ operationId: 'check_instance_setup_token',
+ summary: 'Check the setup token of a new instance',
+ responseSchema: null,
+ statusCode: 204,
+ security: [],
+ tags: ['Instance'],
+ description:
+ 'Checks a setup token before the setup wizard asks for anything else. It returns 204 when the token is correct, and also when the instance no longer needs one. A missing or wrong token fails with the same field codes as registration and counts toward the same allowance of wrong tokens. The check never uses up the token.',
+ }),
+ async (ctx) => {
+ const {setup_token} = ctx.req.valid('json');
+ const {config, rateLimit} = ctx.get('apiContext').services;
+ await assertSetupToken({
+ rateLimit,
+ config,
+ repository: ctx.get('instanceConfigRepository'),
+ presented: setup_token,
+ clientIp: requireConfiguredClientIp(ctx.req.raw, config.proxy),
+ });
+ return ctx.body(null, 204);
+ },
+ );
app.put(
'/instance/setup/account-identity',
RateLimitMiddleware(RateLimitConfigs.INSTANCE_SETUP_ACCOUNT_IDENTITY),
@@ -213,7 +297,11 @@ export function InstanceController(app: Hono<HonoEnv>) {
if (await instanceConfigRepository.isAccountIdentityLocked()) {
throw new AccountIdentityLockedError();
}
- await instanceConfigRepository.setAccountIdentityMode(mode, 'setup', tag_style ?? TagStyles.NONE);
+ await instanceConfigRepository.setAccountIdentityMode(
+ mode,
+ AccountIdentityDecisionSources.SETUP,
+ tag_style ?? TagStyles.NONE,
+ );
return await instanceConfigRepository.getAccountIdentity();
});
return ctx.json({mode: identity.mode, tag_style: identity.tagStyle});
diff --git a/fluxer_api/src/api/instance/tests/AccountIdentityMode.test.ts b/fluxer_api/src/api/instance/tests/AccountIdentityMode.test.ts
index 1a4bead53..80db0435e 100644
--- a/fluxer_api/src/api/instance/tests/AccountIdentityMode.test.ts
+++ b/fluxer_api/src/api/instance/tests/AccountIdentityMode.test.ts
@@ -3,7 +3,7 @@
import {createHash} from 'node:crypto';
import {createAuthHarness, createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
import {getConfig} from '@app/api/Config';
-import {getCachedAccountIdentity, getCachedAccountIdentityMode} from '@app/api/instance/AccountIdentityModeCache';
+import {getCachedAccountIdentityMode} from '@app/api/instance/AccountIdentityModeCache';
import type {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
import {getCacheService, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
@@ -20,7 +20,14 @@ const WRONG_SETUP_TOKEN = 'wrong-setup-token-0123456789-abcdefghijklmnopqrstuvwx
interface DiscoveryResponse {
features: {account_identity: string; emails_enabled: boolean; tag_style: string};
- app_public: {setup: {configured: boolean; account_identity_locked?: boolean; setup_token_required?: boolean}};
+ app_public: {
+ setup: {
+ configured: boolean;
+ account_identity_locked?: boolean;
+ account_identity_lock_reason?: string | null;
+ setup_token_required?: boolean;
+ };
+ };
}
interface AdminInstanceConfigResponse {
@@ -52,7 +59,6 @@ describe('Account identity mode', () => {
originalSetupToken = config.instance.setup.token;
});
afterEach(() => {
- vi.restoreAllMocks();
config.instance.selfHosted = originalSelfHosted;
config.email.enabled = originalEmailEnabled;
config.instance.setup.configured = originalSetupConfigured;
@@ -108,126 +114,6 @@ describe('Account identity mode', () => {
expect(discovery.features.tag_style).toBe('random');
});
- it('reports email on the hosted service even when a row exists', async () => {
- useFreshSelfHostedInstance();
- await repository.setAccountIdentityMode(AccountIdentityModes.USERNAME, 'setup');
- config.instance.selfHosted = false;
- expect(await repository.getAccountIdentityMode()).toBe(AccountIdentityModes.EMAIL);
- expect(getCachedAccountIdentityMode()).toBe(AccountIdentityModes.EMAIL);
- expect((await fetchDiscovery()).features.account_identity).toBe(AccountIdentityModes.EMAIL);
- });
-
- it('stamps username on a fresh self-hosted instance', async () => {
- useFreshSelfHostedInstance();
- await repository.ensureAccountIdentityMode();
- const row = await readStoredRow();
- expect(row).toMatchObject({mode: AccountIdentityModes.USERNAME, source: 'new_instance'});
- expect(Number.isNaN(Date.parse(row!.decided_at))).toBe(false);
- expect(await repository.getAccountIdentityMode()).toBe(AccountIdentityModes.USERNAME);
- expect(getCachedAccountIdentityMode()).toBe(AccountIdentityModes.USERNAME);
- const discovery = await fetchDiscovery();
- expect(discovery.features).toMatchObject({
- account_identity: AccountIdentityModes.USERNAME,
- emails_enabled: false,
- tag_style: 'none',
- });
- expect(row).toMatchObject({tag_style: 'none'});
- expect(getCachedAccountIdentity().tagStyle).toBe('none');
- });
-
- it('ignores a random tag style env on a fresh username instance', async () => {
- useFreshSelfHostedInstance();
- config.instance.tagStyle = 'random';
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toMatchObject({
- mode: AccountIdentityModes.USERNAME,
- tag_style: 'none',
- source: 'new_instance',
- });
- expect(await repository.getAccountIdentity()).toEqual({
- mode: AccountIdentityModes.USERNAME,
- tagStyle: 'none',
- });
- expect((await fetchDiscovery()).features.tag_style).toBe('none');
- });
-
- it('ignores the tag style env on an existing instance', async () => {
- useFreshSelfHostedInstance();
- config.instance.tagStyle = 'none';
- await createAccountWhileHosted();
- await repository.ensureAccountIdentityMode();
- const row = await readStoredRow();
- expect(row).toMatchObject({mode: AccountIdentityModes.EMAIL, tag_style: 'random', source: 'existing_instance'});
- expect((await fetchDiscovery()).features.tag_style).toBe('random');
- });
-
- it('reads a username row written before the field existed as no tags', async () => {
- useFreshSelfHostedInstance();
- await repository.setConfig(
- ACCOUNT_IDENTITY_CONFIG_KEY,
- JSON.stringify({mode: AccountIdentityModes.USERNAME, decided_at: new Date().toISOString(), source: 'setup'}),
- );
- repository.clearCacheForTesting();
- expect(await repository.getAccountIdentity()).toEqual({mode: AccountIdentityModes.USERNAME, tagStyle: 'none'});
- });
-
- it('reads an email row written before the field existed as tagged', async () => {
- useFreshSelfHostedInstance();
- await repository.setConfig(
- ACCOUNT_IDENTITY_CONFIG_KEY,
- JSON.stringify({
- mode: AccountIdentityModes.EMAIL,
- decided_at: new Date().toISOString(),
- source: 'existing_instance',
- }),
- );
- repository.clearCacheForTesting();
- expect(await repository.getAccountIdentity()).toEqual({mode: AccountIdentityModes.EMAIL, tagStyle: 'random'});
- });
-
- it('stamps no tags for a fresh email instance', async () => {
- useFreshSelfHostedInstance();
- config.instance.accountIdentity = AccountIdentityModes.EMAIL;
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toMatchObject({
- mode: AccountIdentityModes.EMAIL,
- tag_style: 'none',
- source: 'new_instance',
- });
- expect((await fetchDiscovery()).features).toMatchObject({
- account_identity: AccountIdentityModes.EMAIL,
- tag_style: 'none',
- });
- });
-
- it.each([
- [{mode: AccountIdentityModes.USERNAME, unique_usernames: true}, 'none'],
- [{mode: AccountIdentityModes.USERNAME, unique_usernames: false}, 'none'],
- [{mode: AccountIdentityModes.USERNAME, tag_style: 'random'}, 'none'],
- [{mode: AccountIdentityModes.USERNAME, tag_style: 'zero_first'}, 'none'],
- [{mode: AccountIdentityModes.EMAIL, unique_usernames: true}, 'none'],
- [{mode: AccountIdentityModes.EMAIL, unique_usernames: false}, 'random'],
- [{mode: AccountIdentityModes.EMAIL, tag_style: 'zero_first'}, 'none'],
- [{mode: AccountIdentityModes.EMAIL, tag_style: 'random'}, 'random'],
- ])('reads the stored row %j as %s', async (row, tagStyle) => {
- useFreshSelfHostedInstance();
- await repository.setConfig(
- ACCOUNT_IDENTITY_CONFIG_KEY,
- JSON.stringify({...row, decided_at: new Date().toISOString(), source: 'setup'}),
- );
- repository.clearCacheForTesting();
- expect((await repository.getAccountIdentity()).tagStyle).toBe(tagStyle);
- });
-
- it.each(['none', 'random'] as const)('stamps the %s tag style from the env on email', async (tagStyle) => {
- useFreshSelfHostedInstance();
- config.instance.accountIdentity = AccountIdentityModes.EMAIL;
- config.instance.tagStyle = tagStyle;
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toMatchObject({tag_style: tagStyle, source: 'new_instance'});
- expect((await fetchDiscovery()).features.tag_style).toBe(tagStyle);
- });
-
it('stamps email when a users row exists', async () => {
useFreshSelfHostedInstance();
await createAccountWhileHosted();
@@ -235,14 +121,6 @@ describe('Account identity mode', () => {
expect(await readStoredRow()).toMatchObject({mode: AccountIdentityModes.EMAIL, source: 'existing_instance'});
});
- it('stamps email when the env override says username but users already exist', async () => {
- useFreshSelfHostedInstance();
- config.instance.accountIdentity = AccountIdentityModes.USERNAME;
- await createAccountWhileHosted();
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toMatchObject({mode: AccountIdentityModes.EMAIL, source: 'existing_instance'});
- });
-
it('stamps email when the admin was bootstrapped', async () => {
useFreshSelfHostedInstance();
await repository.claimAdminBootstrap();
@@ -264,76 +142,6 @@ describe('Account identity mode', () => {
expect(await readStoredRow()).toMatchObject({mode: AccountIdentityModes.EMAIL, source: 'existing_instance'});
});
- it('starts a new instance with email delivery in env on email with no tags', async () => {
- useFreshSelfHostedInstance();
- config.email.enabled = true;
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toMatchObject({
- mode: AccountIdentityModes.EMAIL,
- tag_style: 'none',
- source: 'new_instance',
- });
- expect(await repository.isAccountIdentityLocked()).toBe(false);
- });
-
- it('starts a new instance with email delivery in storage on email', async () => {
- useFreshSelfHostedInstance();
- await repository.setInstanceIntegrationsConfig({email: {enabled: true}});
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toMatchObject({mode: AccountIdentityModes.EMAIL, source: 'new_instance'});
- });
-
- it('takes the tag style env on a new instance with email delivery', async () => {
- useFreshSelfHostedInstance();
- config.email.enabled = true;
- config.instance.tagStyle = 'random';
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toMatchObject({
- mode: AccountIdentityModes.EMAIL,
- tag_style: 'random',
- source: 'new_instance',
- });
- });
-
- it('lets the sign-in env win over email delivery on a new instance', async () => {
- useFreshSelfHostedInstance();
- config.email.enabled = true;
- config.instance.accountIdentity = AccountIdentityModes.USERNAME;
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toMatchObject({
- mode: AccountIdentityModes.USERNAME,
- tag_style: 'none',
- source: 'new_instance',
- });
- });
-
- it('keeps an existing row', async () => {
- useFreshSelfHostedInstance();
- await repository.setAccountIdentityMode(AccountIdentityModes.EMAIL, 'setup');
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toMatchObject({mode: AccountIdentityModes.EMAIL, source: 'setup'});
- });
-
- it('writes nothing and stays on email when a probe fails', async () => {
- useFreshSelfHostedInstance();
- vi.spyOn(repository as unknown as {hasAnyUser: () => Promise<boolean>}, 'hasAnyUser').mockRejectedValue(
- new Error('database not ready'),
- );
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toBeNull();
- expect(await repository.getAccountIdentityMode()).toBe(AccountIdentityModes.EMAIL);
- });
-
- it('skips the users probe when a cheaper signal already decides', async () => {
- useFreshSelfHostedInstance();
- const probe = vi.spyOn(repository as unknown as {hasAnyUser: () => Promise<boolean>}, 'hasAnyUser');
- await repository.claimAdminBootstrap();
- await repository.ensureAccountIdentityMode();
- expect(await readStoredRow()).toMatchObject({mode: AccountIdentityModes.EMAIL, source: 'existing_instance'});
- expect(await repository.isAccountIdentityLocked()).toBe(true);
- expect(probe).not.toHaveBeenCalled();
- });
-
it('forces the effective email config off in username mode', async () => {
useFreshSelfHostedInstance();
await repository.setInstanceIntegrationsConfig({
@@ -505,44 +313,29 @@ describe('Account identity mode', () => {
expect((await fetchDiscovery()).app_public.setup).not.toHaveProperty('account_identity_locked');
});
- it('waits for a registration holding the setup lock', async () => {
+ it('reports why the sign-in method is locked', async () => {
useFreshSelfHostedInstance();
await repository.ensureAccountIdentityMode();
- const cache = getCacheService();
- const token = await cache.acquireLock('account-identity-setup', 30);
- expect(token).not.toBeNull();
- let settled = false;
- const pending = putMode(AccountIdentityModes.EMAIL).then((result) => {
- settled = true;
- return result;
+ expect((await fetchDiscovery()).app_public.setup).toMatchObject({
+ account_identity_locked: false,
+ account_identity_lock_reason: null,
});
- await new Promise((resolve) => setTimeout(resolve, 250));
- expect(settled).toBe(false);
- expect(await readStoredRow()).toMatchObject({mode: AccountIdentityModes.USERNAME});
- await cache.releaseLock('account-identity-setup', token!);
- expect(await pending).toEqual({mode: AccountIdentityModes.EMAIL, tag_style: 'none'});
- });
-
- it('makes the first registration wait for a setup choice in progress', async () => {
- useFreshSelfHostedInstance();
- await repository.ensureAccountIdentityMode();
- const cache = getCacheService();
- const token = await cache.acquireLock('account-identity-setup', 30);
- expect(token).not.toBeNull();
- let settled = false;
- const pending = createBuilderWithoutAuth<{token: string}>(harness)
- .post('/auth/register')
- .body({username: 'waitingadmin', global_name: 'Waiting', password: 'a-strong-password-123'})
- .execute()
- .then((result) => {
- settled = true;
- return result;
- });
- await new Promise((resolve) => setTimeout(resolve, 250));
- expect(settled).toBe(false);
- await cache.releaseLock('account-identity-setup', token!);
- expect((await pending).token).toBeTruthy();
- expect(await repository.isAccountIdentityLocked()).toBe(true);
+ await createAccountWhileHosted();
+ expect((await fetchDiscovery()).app_public.setup).toMatchObject({
+ account_identity_locked: true,
+ account_identity_lock_reason: 'accounts_exist',
+ });
+ await repository.claimAdminBootstrap();
+ expect((await fetchDiscovery()).app_public.setup.account_identity_lock_reason).toBe('admin_exists');
+ await repository.setAccountIdentityMode(AccountIdentityModes.EMAIL, 'existing_instance', 'random');
+ expect((await fetchDiscovery()).app_public.setup.account_identity_lock_reason).toBe('existing_instance');
+ config.instance.setup.configured = true;
+ expect(await repository.getAccountIdentityLockReason()).toBe('setup_configured');
+ config.instance.setup.configured = false;
+ await repository.setAccountIdentityMode(AccountIdentityModes.EMAIL, 'setup');
+ await repository.setAppPublicConfig({setup: {configured: true}});
+ expect(await repository.getAccountIdentityLockReason()).toBe('setup_configured');
+ expect((await fetchDiscovery()).app_public.setup).not.toHaveProperty('account_identity_lock_reason');
});
});
@@ -617,6 +410,85 @@ describe('Account identity mode', () => {
});
});
+ describe('setup token check', () => {
+ async function checkToken(body: Record<string, unknown>, ipAddress?: string) {
+ const builder = createBuilderWithoutAuth<{code?: string; errors?: Array<{path: string; code: string}>}>(harness)
+ .post('/instance/setup/token-checks')
+ .body(body);
+ if (ipAddress) builder.header('x-forwarded-for', ipAddress);
+ return await builder.executeRaw();
+ }
+
+ function errorCodes(json: {errors?: Array<{path: string; code: string}>}) {
+ return (json.errors ?? []).map(({path, code}) => ({path, code}));
+ }
+
+ it('accepts the setup token without using it up', async () => {
+ useFreshSelfHostedInstance();
+ await repository.ensureAccountIdentityMode();
+ config.instance.setup.token = SETUP_TOKEN;
+ const accepted = await checkToken({setup_token: SETUP_TOKEN});
+ expect(accepted.response.status).toBe(204);
+ expect(accepted.text).toBe('');
+ expect(await repository.isAdminBootstrapped()).toBe(false);
+ expect(await repository.verifySetupToken(SETUP_TOKEN)).toBe(true);
+ expect((await fetchDiscovery()).app_public.setup.setup_token_required).toBe(true);
+ const again = await checkToken({setup_token: ` ${SETUP_TOKEN}\n`});
+ expect(again.response.status).toBe(204);
+ });
+
+ it('refuses a wrong or blank setup token', async () => {
+ useFreshSelfHostedInstance();
+ await repository.ensureAccountIdentityMode();
+ config.instance.setup.token = SETUP_TOKEN;
+ const wrong = await checkToken({setup_token: WRONG_SETUP_TOKEN});
+ expect(wrong.response.status).toBe(400);
+ expect(errorCodes(wrong.json)).toEqual([{path: 'setup_token', code: ValidationErrorCodes.SETUP_TOKEN_INVALID}]);
+ const blank = await checkToken({setup_token: ' '});
+ expect(blank.response.status).toBe(400);
+ expect(errorCodes(blank.json).map(({path}) => path)).toEqual(['setup_token']);
+ const missing = await checkToken({});
+ expect(missing.response.status).toBe(400);
+ expect(errorCodes(missing.json).map(({path}) => path)).toEqual(['setup_token']);
+ });
+
+ it('answers 204 when the instance needs no setup token', async () => {
+ useFreshSelfHostedInstance();
+ await repository.ensureAccountIdentityMode();
+ expect((await checkToken({setup_token: WRONG_SETUP_TOKEN})).response.status).toBe(204);
+ config.instance.setup.token = SETUP_TOKEN;
+ await repository.claimAdminBootstrap();
+ expect((await checkToken({setup_token: WRONG_SETUP_TOKEN})).response.status).toBe(204);
+ });
+
+ it('counts wrong setup tokens toward the same lockout as registration', async () => {
+ useFreshSelfHostedInstance();
+ await repository.ensureAccountIdentityMode();
+ config.instance.setup.token = SETUP_TOKEN;
+ const originalRelax = config.dev.relaxRegistrationRateLimits;
+ config.dev.relaxRegistrationRateLimits = false;
+ try {
+ const attacker = '203.0.113.40';
+ for (let attempt = 0; attempt < 5; attempt++) {
+ const wrong = await createBuilderWithoutAuth(harness)
+ .put('/instance/setup/account-identity')
+ .header('x-forwarded-for', attacker)
+ .body({mode: AccountIdentityModes.EMAIL, setup_token: WRONG_SETUP_TOKEN})
+ .executeRaw();
+ expect(wrong.response.status).toBe(400);
+ }
+ for (let attempt = 0; attempt < 5; attempt++) {
+ const wrong = await checkToken({setup_token: WRONG_SETUP_TOKEN}, attacker);
+ expect(wrong.response.status).toBe(400);
+ }
+ expect((await checkToken({setup_token: SETUP_TOKEN}, attacker)).response.status).toBe(429);
+ expect((await checkToken({setup_token: SETUP_TOKEN}, '203.0.113.41')).response.status).toBe(204);
+ } finally {
+ config.dev.relaxRegistrationRateLimits = originalRelax;
+ }
+ });
+ });
+
describe('admin instance config', () => {
async function fetchAdminConfig(token: string): Promise<AdminInstanceConfigResponse> {
return await createBuilder<AdminInstanceConfigResponse>(harness, token).get('/admin/instance/config').execute();
@@ -629,6 +501,7 @@ describe('Account identity mode', () => {
mode: AccountIdentityModes.EMAIL,
locked: true,
tag_style: 'random',
+ lock_reason: 'setup_configured',
});
});
@@ -643,6 +516,7 @@ describe('Account identity mode', () => {
mode: AccountIdentityModes.USERNAME,
locked: true,
tag_style: 'none',
+ lock_reason: 'admin_exists',
});
});
});
diff --git a/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts b/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts
new file mode 100644
index 000000000..994452975
--- /dev/null
+++ b/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {SsoService} from '@app/api/auth/services/SsoService';
+import {getConfig} from '@app/api/Config';
+import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
+import {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
+import {InstanceController} from '@app/api/instance/InstanceController';
+import type {LimitConfigService} from '@app/api/limits/LimitConfigService';
+import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
+import type {HonoEnv} from '@app/api/types/HonoEnv';
+import {parseInstanceDiscoveryDocument} from '@fluxer/instance_bootstrap/src/Discovery';
+import type {WellKnownFluxerResponse} from '@fluxer/schema/src/domains/instance/InstanceSchemas';
+import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
+import {Hono} from 'hono';
+import {afterEach, describe, expect, it} from 'vitest';
+
+describe('discovery fields for self-hosted clients', () => {
+ const repositories: Array<InstanceConfigRepository> = [];
+ const discoveryEnabled = getConfig().discovery.enabled;
+
+ afterEach(() => {
+ getConfig().discovery.enabled = discoveryEnabled;
+ for (const repository of repositories) {
+ repository.shutdown();
+ }
+ repositories.length = 0;
+ });
+
+ it('keeps friend requests off on an instance that turned direct messages off before the split', async () => {
+ const repository = createRepository();
+ await repository.setConfig('instance_policy_config', JSON.stringify({direct_messages_disabled: true}));
+ const discovery = await readDiscovery(repository);
+ expect(discovery.community).toMatchObject({direct_messages_disabled: true, friends_disabled: true});
+ });
+
+ it('fills friends_disabled from the direct message flag for an older server', () => {
+ const document = parseInstanceDiscoveryDocument({
+ api_code_version: 1,
+ endpoints: {api: 'https://chat.example.com/api', gateway: 'wss://chat.example.com/gateway'},
+ community: {single_community: false, single_community_guild_id: null, direct_messages_disabled: true},
+ });
+ expect(document.community?.friends_disabled).toBe(true);
+ expect(document.notice).toBeNull();
+ });
+});
diff --git a/fluxer_api/src/api/rate_limit_configs/MiscRateLimitConfig.ts b/fluxer_api/src/api/rate_limit_configs/MiscRateLimitConfig.ts
index dedbc3185..f18cdf9d3 100644
--- a/fluxer_api/src/api/rate_limit_configs/MiscRateLimitConfig.ts
+++ b/fluxer_api/src/api/rate_limit_configs/MiscRateLimitConfig.ts
@@ -12,6 +12,10 @@ export const MiscRateLimitConfigs = {
bucket: 'instance:setup:account_identity',
config: {limit: 10, windowMs: ms('1 minute')},
} as RouteRateLimitConfig,
+ INSTANCE_SETUP_TOKEN_CHECK: {
+ bucket: 'instance:setup:token_check',
+ config: {limit: 10, windowMs: ms('1 minute')},
+ } as RouteRateLimitConfig,
IP_GEO_LOOKUP: {
bucket: 'ip:geo_lookup',
config: {limit: 30, windowMs: ms('1 minute')},