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): add accounts config and email delivery state

Hampus7d1dca8b9aa6
diff --git a/fluxer_api/src/api/admin/tests/InstanceConfigAccounts.test.ts b/fluxer_api/src/api/admin/tests/InstanceConfigAccounts.test.ts
new file mode 100644
index 000000000..8888b70da
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/InstanceConfigAccounts.test.ts
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createTestAccount, createUniqueEmail, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
+import {getConfig} from '@app/api/Config';
+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {HTTP_STATUS} from '@app/api/test/TestConstants';
+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
+import {EmailDeliveryModes, VerificationBases} from '@fluxer/constants/src/AccountConfigConstants';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+interface ValidationErrorBody {
+ errors: Array<{path: string; code: string}>;
+}
+
+describe('instance account settings', () => {
+ let harness: ApiTestHarness;
+ let admin: TestAccount;
+ const config = getConfig();
+ let originalSelfHosted: boolean;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+ beforeEach(async () => {
+ await harness.reset();
+ originalSelfHosted = config.instance.selfHosted;
+ admin = await setUserACLs(harness, await createTestAccount(harness), [
+ AdminACLs.AUTHENTICATE,
+ AdminACLs.INSTANCE_CONFIG_VIEW,
+ AdminACLs.INSTANCE_CONFIG_UPDATE,
+ ]);
+ });
+ afterEach(() => {
+ config.instance.selfHosted = originalSelfHosted;
+ getInstanceConfigRepository().clearCacheForTesting();
+ });
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+
+ function patch(body: Record<string, unknown>) {
+ return createBuilder<InstanceConfigResponse>(harness, admin.token).patch('/admin/instance/config').body(body);
+ }
+
+ async function expectRejected(body: Record<string, unknown>, path: string, code: string): Promise<void> {
+ const {json} = await createBuilder<ValidationErrorBody>(harness, admin.token)
+ .patch('/admin/instance/config')
+ .body(body)
+ .expect(HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY')
+ .executeWithResponse();
+ expect(json.errors).toEqual([expect.objectContaining({path, code})]);
+ }
+
+ it('refuses to turn the captcha off while instant accounts are on', async () => {
+ expect((await getInstanceConfigRepository().getAuthConfig()).instant_accounts.enabled).toBe(true);
+ await expectRejected(
+ {captcha: {provider: 'none'}},
+ 'captcha.provider',
+ ValidationErrorCodes.CAPTCHA_REQUIRED_BY_INSTANT_ACCOUNTS,
+ );
+ await expectRejected(
+ {captcha: {enabled: false}},
+ 'captcha.enabled',
+ ValidationErrorCodes.CAPTCHA_REQUIRED_BY_INSTANT_ACCOUNTS,
+ );
+ expect((await getInstanceConfigRepository().getCaptchaConfig()).provider).toBe('altcha');
+ });
+
+ it('refuses to turn instant accounts on while the captcha is off', async () => {
+ await patch({auth: {instant_accounts: {enabled: false}}, captcha: {provider: 'none'}}).execute();
+ await expectRejected(
+ {auth: {instant_accounts: {enabled: true}}},
+ 'auth.instant_accounts.enabled',
+ ValidationErrorCodes.INSTANT_ACCOUNTS_REQUIRE_CAPTCHA,
+ );
+ });
+
+ it('refuses a confirmed email as the verification basis while no email can be sent', async () => {
+ await patch({integrations: {email: {delivery: EmailDeliveryModes.OFF}}}).execute();
+ await expectRejected(
+ {accounts: {verification_basis: VerificationBases.CONFIRMED_EMAIL}},
+ 'accounts.verification_basis',
+ ValidationErrorCodes.VERIFICATION_BASIS_REQUIRES_EMAIL_DELIVERY,
+ );
+ });
+
+ it('refuses to turn email delivery off while accounts need a confirmed email', async () => {
+ const repository = getInstanceConfigRepository();
+ if ((await repository.getEmailDeliveryState()) !== 'on') {
+ await repository.setInstanceIntegrationsConfig({
+ email: {
+ delivery: EmailDeliveryModes.SMTP,
+ from_email: '[email protected]',
+ smtp: {host: 'smtp.example.com', port: 587, username: 'user', password: 'secret'},
+ },
+ });
+ }
+ await patch({accounts: {verification_basis: VerificationBases.CONFIRMED_EMAIL}}).execute();
+ await expectRejected(
+ {integrations: {email: {delivery: EmailDeliveryModes.OFF}}},
+ 'integrations.email.delivery',
+ ValidationErrorCodes.VERIFICATION_BASIS_REQUIRES_EMAIL_DELIVERY,
+ );
+ });
+
+ it('refuses an email-only sign-up that could never sign in again while email delivery is off', async () => {
+ await getInstanceConfigRepository().setInstanceIntegrationsConfig({email: {delivery: EmailDeliveryModes.OFF}});
+ await createBuilderWithoutAuth(harness)
+ .post('/auth/register')
+ .body({email: createUniqueEmail('nodelivery'), global_name: 'Nobody', consent: true})
+ .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.REGISTRATION_CREDENTIAL_REQUIRED)
+ .execute();
+ await createBuilderWithoutAuth(harness)
+ .post('/auth/register')
+ .body({
+ email: createUniqueEmail('nodelivery'),
+ global_name: 'Somebody',
+ password: 'a-strong-password-123',
+ consent: true,
+ })
+ .execute();
+ });
+});
diff --git a/fluxer_api/src/api/instance/AccountIdentityModeCache.ts b/fluxer_api/src/api/instance/AccountIdentityModeCache.ts
index 7fce2039d..e2a24e444 100644
--- a/fluxer_api/src/api/instance/AccountIdentityModeCache.ts
+++ b/fluxer_api/src/api/instance/AccountIdentityModeCache.ts
@@ -2,36 +2,25 @@
import {Config} from '@app/api/Config';
import {
+ type AccountIdentity,
type AccountIdentityMode,
AccountIdentityModes,
DEFAULT_ACCOUNT_IDENTITY_MODE,
+ normalizeAccountIdentity,
type TagStyle,
TagStyles,
} from '@fluxer/constants/src/AccountIdentityConstants';
-export interface StoredAccountIdentity {
- mode: AccountIdentityMode;
- tagStyle: TagStyle;
-}
-
-export interface AccountIdentity {
- mode: AccountIdentityMode;
- tagStyle: TagStyle;
-}
-
-let cachedStored: StoredAccountIdentity | null = null;
+let cachedStored: AccountIdentity | null = null;
-export function resolveAccountIdentity(stored: StoredAccountIdentity | null): AccountIdentity {
+export function resolveAccountIdentity(stored: AccountIdentity | null): AccountIdentity {
if (!Config.instance.selfHosted || !stored) {
return {mode: DEFAULT_ACCOUNT_IDENTITY_MODE, tagStyle: TagStyles.RANDOM};
}
- return {
- mode: stored.mode,
- tagStyle: stored.mode === AccountIdentityModes.USERNAME ? TagStyles.NONE : stored.tagStyle,
- };
+ return normalizeAccountIdentity(stored.mode, stored.tagStyle);
}
-export function getCachedAccountIdentity(): AccountIdentity {
+function getCachedAccountIdentity(): AccountIdentity {
return resolveAccountIdentity(cachedStored);
}
@@ -51,6 +40,6 @@ export function usesUniqueUsernames(): boolean {
return getCachedTagStyle() === TagStyles.NONE;
}
-export function setCachedAccountIdentity(stored: StoredAccountIdentity | null): void {
+export function setCachedAccountIdentity(stored: AccountIdentity | null): void {
cachedStored = stored;
}
diff --git a/fluxer_api/src/api/instance/AccountsConfigCache.ts b/fluxer_api/src/api/instance/AccountsConfigCache.ts
new file mode 100644
index 000000000..bcd5c06b1
--- /dev/null
+++ b/fluxer_api/src/api/instance/AccountsConfigCache.ts
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {UserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
+import {userGuildVisitsActive} from '@app/api/experiment/GuildVisitsGate';
+import {getCachedAccountIdentityMode} from '@app/api/instance/AccountIdentityModeCache';
+import {envEmailDeliveryState} from '@app/api/instance/EmailDelivery';
+import {
+ AccountCleanupDefaults,
+ CleanupModes,
+ DateOfBirthPolicies,
+ type DateOfBirthPolicy,
+ type EffectiveVerificationBasis,
+ type EmailDeliveryState,
+ type GuildJoinGate,
+ GuildJoinGates,
+ IdentifierFirstModes,
+ InstantAccountLimits,
+ type InteractionTierMode,
+ InteractionTierModes,
+ LastSessionCleanupModes,
+ VerificationBases,
+} from '@fluxer/constants/src/AccountConfigConstants';
+import {resolveEffectiveVerificationBasis} from '@fluxer/constants/src/AccountTierRules';
+import type {AccountsConfig, AuthConfig} from '@fluxer/schema/src/domains/admin/AccountsConfigSchemas';
+
+export interface AccountsConfigDefaults {
+ auth: AuthConfig;
+ accounts: AccountsConfig;
+}
+
+export function seededInactivityDays(): number {
+ return Math.max(AccountCleanupDefaults.INACTIVITY_DAYS, Config.inactivityDeletionThresholdDays ?? 0);
+}
+
+function inactivityDeletionDefaults(): AccountsConfig['inactivity_deletion'] {
+ return {
+ mode: CleanupModes.AFTER_INACTIVITY,
+ inactive_days: Math.min(seededInactivityDays(), AccountCleanupDefaults.MAX_INACTIVE_DAYS),
+ warning_lead_days: AccountCleanupDefaults.INACTIVITY_WARNING_LEAD_DAYS,
+ };
+}
+
+export function abandonedAccountCleanupDefaults(
+ on: boolean,
+): Pick<AccountsConfig, 'unclaimed_account_cleanup' | 'dob_missing_cleanup'> {
+ return {
+ unclaimed_account_cleanup: {
+ mode: on ? CleanupModes.AFTER_INACTIVITY : CleanupModes.OFF,
+ inactive_days: AccountCleanupDefaults.UNCLAIMED_INACTIVE_DAYS,
+ on_last_session_end: on ? LastSessionCleanupModes.AFTER_GRACE : LastSessionCleanupModes.OFF,
+ },
+ dob_missing_cleanup: {
+ mode: on ? CleanupModes.AFTER_INACTIVITY : CleanupModes.OFF,
+ inactive_days: AccountCleanupDefaults.DOB_MISSING_INACTIVE_DAYS,
+ },
+ };
+}
+
+export function hostedAccountsDefaults(): AccountsConfigDefaults {
+ return {
+ auth: {
+ identifier_first: IdentifierFirstModes.OFF,
+ instant_accounts: {enabled: true, pow_escalation_per_hour: InstantAccountLimits.DEFAULT_POW_ESCALATION_PER_HOUR},
+ },
+ accounts: {
+ date_of_birth: DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS,
+ interaction_tier: InteractionTierModes.LEGACY,
+ verification_basis: VerificationBases.AUTO,
+ guild_join_gate: GuildJoinGates.ALWAYS,
+ ...abandonedAccountCleanupDefaults(false),
+ inactivity_deletion: inactivityDeletionDefaults(),
+ },
+ };
+}
+
+export function selfHostedAccountsDefaults(params: {
+ freshInstall: boolean;
+ dateOfBirth?: DateOfBirthPolicy;
+}): AccountsConfigDefaults {
+ return {
+ auth: {
+ identifier_first: IdentifierFirstModes.AUTO,
+ instant_accounts: {enabled: false, pow_escalation_per_hour: InstantAccountLimits.DEFAULT_POW_ESCALATION_PER_HOUR},
+ },
+ accounts: {
+ date_of_birth: params.dateOfBirth ?? DateOfBirthPolicies.OFF,
+ interaction_tier: params.freshInstall ? InteractionTierModes.ENFORCED : InteractionTierModes.LEGACY,
+ verification_basis: VerificationBases.AUTO,
+ guild_join_gate: GuildJoinGates.ALWAYS,
+ ...abandonedAccountCleanupDefaults(params.freshInstall),
+ inactivity_deletion: inactivityDeletionDefaults(),
+ },
+ };
+}
+
+export function fallbackAccountsDefaults(): AccountsConfigDefaults {
+ if (!Config.instance.selfHosted) return hostedAccountsDefaults();
+ return selfHostedAccountsDefaults({freshInstall: false});
+}
+
+let cachedAccounts: AccountsConfig | null = null;
+let cachedEmailDeliveryState: EmailDeliveryState | null = null;
+
+export function getCachedAccountsConfig(): AccountsConfig {
+ return cachedAccounts ?? fallbackAccountsDefaults().accounts;
+}
+
+export function setCachedAccountsConfig(config: AccountsConfig | null): void {
+ cachedAccounts = config;
+}
+
+export function getEmailDeliveryState(): EmailDeliveryState {
+ return cachedEmailDeliveryState ?? envEmailDeliveryState(getCachedAccountIdentityMode());
+}
+
+export function setCachedEmailDeliveryState(state: EmailDeliveryState | null): void {
+ cachedEmailDeliveryState = state;
+}
+
+export function getInteractionTierMode(): InteractionTierMode {
+ return getCachedAccountsConfig().interaction_tier;
+}
+
+function getGuildJoinGate(): GuildJoinGate {
+ return getCachedAccountsConfig().guild_join_gate;
+}
+
+export function guildJoinGateApplies(params: {userId: UserID; visitsCapable: boolean}): boolean {
+ const gate = getGuildJoinGate();
+ if (gate === GuildJoinGates.OFF) return false;
+ if (!userGuildVisitsActive(params.userId)) return false;
+ return gate === GuildJoinGates.ALWAYS || params.visitsCapable;
+}
+
+export function getEffectiveVerificationBasis(): EffectiveVerificationBasis {
+ return resolveEffectiveVerificationBasis({
+ identityMode: getCachedAccountIdentityMode(),
+ basis: getCachedAccountsConfig().verification_basis,
+ deliveryState: getEmailDeliveryState(),
+ });
+}
+
+export function getDateOfBirthPolicy(): DateOfBirthPolicy {
+ return getCachedAccountsConfig().date_of_birth;
+}
diff --git a/fluxer_api/src/api/instance/EmailDelivery.ts b/fluxer_api/src/api/instance/EmailDelivery.ts
new file mode 100644
index 000000000..3d07da5ea
--- /dev/null
+++ b/fluxer_api/src/api/instance/EmailDelivery.ts
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {Config} from '@app/api/Config';
+import type {APIConfig} from '@app/api/config/APIConfig';
+import {
+ type EmailDeliveryMode,
+ EmailDeliveryModes,
+ type EmailDeliveryState,
+ emailDeliveryFromLegacy,
+} from '@fluxer/constants/src/AccountConfigConstants';
+import type {AccountIdentityMode} from '@fluxer/constants/src/AccountIdentityConstants';
+import {resolveEmailDeliveryState} from '@fluxer/constants/src/AccountTierRules';
+import {type SmtpTlsMode, smtpTlsModeFromSecure} from '@fluxer/constants/src/SmtpConstants';
+
+export type EffectiveSmtpConfig = NonNullable<APIConfig['email']['smtp']>;
+
+export interface StoredEmailSmtpConfig {
+ host: string | null;
+ port: number | null;
+ username: string | null;
+ password: string | null;
+ tls_mode: SmtpTlsMode | null;
+ secure: boolean | null;
+}
+
+interface StoredEmailDeliveryConfig {
+ delivery: EmailDeliveryMode | null;
+ from_email: string | null;
+ smtp: StoredEmailSmtpConfig;
+}
+
+const NO_STORED_EMAIL_DELIVERY: StoredEmailDeliveryConfig = {
+ delivery: null,
+ from_email: null,
+ smtp: {host: null, port: null, username: null, password: null, tls_mode: null, secure: null},
+};
+
+function envEmailDelivery(): EmailDeliveryMode {
+ return emailDeliveryFromLegacy({enabled: Config.email.enabled, provider: Config.email.provider});
+}
+
+export function legacyStoredEmailDelivery(
+ enabled: boolean | null,
+ provider: APIConfig['email']['provider'] | null,
+): EmailDeliveryMode | null {
+ if (enabled === null && provider === null) return null;
+ return emailDeliveryFromLegacy({
+ enabled: enabled ?? Config.email.enabled,
+ provider: provider ?? Config.email.provider,
+ });
+}
+
+export function resolveEmailDelivery(stored: Pick<StoredEmailDeliveryConfig, 'delivery'>): EmailDeliveryMode {
+ return stored.delivery ?? envEmailDelivery();
+}
+
+export function storedSmtpTlsMode(smtp: StoredEmailSmtpConfig): SmtpTlsMode | null {
+ return smtp.tls_mode ?? smtpTlsModeFromSecure(smtp.secure, smtp.port ?? Config.email.smtp?.port);
+}
+
+export function resolveEffectiveSmtpConfig(smtp: StoredEmailSmtpConfig): EffectiveSmtpConfig {
+ return {
+ host: smtp.host ?? Config.email.smtp?.host ?? '',
+ port: smtp.port ?? Config.email.smtp?.port ?? 587,
+ username: smtp.username ?? Config.email.smtp?.username ?? '',
+ password: smtp.password ?? Config.email.smtp?.password ?? '',
+ tlsMode: storedSmtpTlsMode(smtp) ?? Config.email.smtp?.tlsMode ?? null,
+ };
+}
+
+export function describeIncompleteSmtpConfig(smtp: EffectiveSmtpConfig): string | null {
+ if (!smtp.host.trim()) return 'No SMTP host is configured';
+ if (!smtp.port) return 'No SMTP port is configured';
+ if (!smtp.username.trim() !== !smtp.password.trim()) {
+ return 'Set both the SMTP username and password, or leave both empty for a server that needs no sign-in';
+ }
+ return null;
+}
+
+export function resolveStoredEmailDeliveryState(
+ identityMode: AccountIdentityMode,
+ stored: StoredEmailDeliveryConfig,
+): EmailDeliveryState {
+ return resolveEmailDeliveryState({
+ identityMode,
+ delivery: resolveEmailDelivery(stored),
+ smtpComplete: describeIncompleteSmtpConfig(resolveEffectiveSmtpConfig(stored.smtp)) === null,
+ fromAddress: stored.from_email ?? Config.email.fromEmail,
+ });
+}
+
+export function envEmailDeliveryState(identityMode: AccountIdentityMode): EmailDeliveryState {
+ return resolveStoredEmailDeliveryState(identityMode, NO_STORED_EMAIL_DELIVERY);
+}
+
+export function emailProviderFor(delivery: EmailDeliveryMode): APIConfig['email']['provider'] {
+ return delivery === EmailDeliveryModes.SMTP ? 'smtp' : 'none';
+}
diff --git a/fluxer_api/src/api/instance/tests/AccountsConfigMigration.test.ts b/fluxer_api/src/api/instance/tests/AccountsConfigMigration.test.ts
new file mode 100644
index 000000000..8a733aca9
--- /dev/null
+++ b/fluxer_api/src/api/instance/tests/AccountsConfigMigration.test.ts
@@ -0,0 +1,334 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {getConfig} from '@app/api/Config';
+import {setCassandraQueryExecutorForTesting, upsertOne} from '@app/api/database/CassandraQueryExecution';
+import {setCachedAccountIdentity} from '@app/api/instance/AccountIdentityModeCache';
+import {getEmailDeliveryState, setCachedEmailDeliveryState} from '@app/api/instance/AccountsConfigCache';
+import {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
+import {AdminAuditLogs} from '@app/api/Tables';
+import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
+import {
+ CleanupModes,
+ DateOfBirthPolicies,
+ EmailDeliveryModes,
+ EmailDeliveryStates,
+ GuildJoinGates,
+ IdentifierFirstModes,
+ LastSessionCleanupModes,
+} from '@fluxer/constants/src/AccountConfigConstants';
+import {AccountIdentityModes, TagStyles} from '@fluxer/constants/src/AccountIdentityConstants';
+import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+
+const AUTH_CONFIG_KEY = 'auth_config';
+const ACCOUNTS_CONFIG_KEY = 'accounts_config';
+const APP_PUBLIC_CONFIG_KEY = 'app_public_config';
+const INTEGRATIONS_CONFIG_KEY = 'instance_integrations_config';
+
+const LEGACY_HOSTED_ACCOUNTS = {
+ date_of_birth_enforcement: 'new_accounts',
+ interaction_tier: 'legacy',
+ guild_join_gate: 'always',
+ abandoned_account_cleanup: false,
+};
+
+describe('account config migrations', () => {
+ const config = getConfig();
+ const repositories: Array<InstanceConfigRepository> = [];
+ let original: {
+ selfHosted: boolean;
+ threshold: number | undefined;
+ email: typeof config.email;
+ };
+
+ beforeEach(() => {
+ setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
+ original = {
+ selfHosted: config.instance.selfHosted,
+ threshold: config.inactivityDeletionThresholdDays,
+ email: {...config.email},
+ };
+ });
+
+ afterEach(() => {
+ for (const repository of repositories) {
+ repository.clearCacheForTesting();
+ repository.shutdown();
+ }
+ repositories.length = 0;
+ config.instance.selfHosted = original.selfHosted;
+ config.inactivityDeletionThresholdDays = original.threshold;
+ Object.assign(config.email, original.email);
+ setCachedAccountIdentity(null);
+ setCachedEmailDeliveryState(null);
+ });
+
+ function createRepository(): InstanceConfigRepository {
+ const repository = new InstanceConfigRepository(new MockKVProvider());
+ repositories.push(repository);
+ return repository;
+ }
+
+ async function storedJson(repository: InstanceConfigRepository, key: string): Promise<unknown> {
+ const raw = await repository.getConfig(key);
+ return raw === null ? null : JSON.parse(raw);
+ }
+
+ describe('identifier_first', () => {
+ it('reads a stored true as on and a stored false as off', async () => {
+ const repository = createRepository();
+ await repository.setConfig(AUTH_CONFIG_KEY, JSON.stringify({identifier_first: true}));
+ expect((await repository.getAuthConfig()).identifier_first).toBe(IdentifierFirstModes.ON);
+ await repository.setConfig(AUTH_CONFIG_KEY, JSON.stringify({identifier_first: false}));
+ expect((await repository.getAuthConfig()).identifier_first).toBe(IdentifierFirstModes.OFF);
+ });
+
+ it('leaves the hosted false alone at boot', async () => {
+ config.instance.selfHosted = false;
+ const repository = createRepository();
+ await repository.setConfig(AUTH_CONFIG_KEY, JSON.stringify({identifier_first: false}));
+ await repository.setConfig(ACCOUNTS_CONFIG_KEY, JSON.stringify(LEGACY_HOSTED_ACCOUNTS));
+ await repository.ensureAccountsDefaults();
+ expect(await storedJson(repository, AUTH_CONFIG_KEY)).toEqual({identifier_first: false});
+ expect((await repository.getAuthConfig()).identifier_first).toBe(IdentifierFirstModes.OFF);
+ });
+
+ it('moves a self-hosted false that no admin chose to auto at boot', async () => {
+ config.instance.selfHosted = true;
+ const repository = createRepository();
+ await repository.setConfig(AUTH_CONFIG_KEY, JSON.stringify({identifier_first: false}));
+ await repository.setConfig(ACCOUNTS_CONFIG_KEY, JSON.stringify({}));
+ await repository.ensureAccountsDefaults();
+ expect((await repository.getAuthConfig()).identifier_first).toBe(IdentifierFirstModes.AUTO);
+ expect(await storedJson(repository, AUTH_CONFIG_KEY)).toMatchObject({
+ identifier_first: IdentifierFirstModes.AUTO,
+ });
+ });
+
+ it('keeps a self-hosted false that an admin saved as off', async () => {
+ config.instance.selfHosted = true;
+ const repository = createRepository();
+ await upsertOne(
+ AdminAuditLogs.insert({
+ log_id: 1n,
+ admin_user_id: 2n,
+ target_type: 'instance_config',
+ target_id: 0n,
+ action: 'update_instance_config',
+ audit_log_reason: null,
+ metadata: new Map([['sections', 'auth,captcha']]),
+ created_at: new Date(),
+ }),
+ );
+ await repository.setConfig(AUTH_CONFIG_KEY, JSON.stringify({identifier_first: false}));
+ await repository.setConfig(ACCOUNTS_CONFIG_KEY, JSON.stringify({}));
+ await repository.ensureAccountsDefaults();
+ expect((await repository.getAuthConfig()).identifier_first).toBe(IdentifierFirstModes.OFF);
+ expect(await storedJson(repository, AUTH_CONFIG_KEY)).toMatchObject({identifier_first: IdentifierFirstModes.OFF});
+ });
+
+ it('turns on for a fresh install once email is configured after boot', async () => {
+ config.instance.selfHosted = true;
+ config.email.enabled = false;
+ const repository = createRepository();
+ await repository.ensureAccountsDefaults();
+ expect(await repository.getSignInFeatures()).toEqual({identifierFirst: false, emailCodes: false});
+ await repository.setInstanceIntegrationsConfig({
+ email: {
+ delivery: EmailDeliveryModes.SMTP,
+ from_email: '[email protected]',
+ smtp: {host: 'smtp.example.com', port: 587, username: 'user', password: 'secret'},
+ },
+ });
+ expect(await repository.getSignInFeatures()).toEqual({identifierFirst: true, emailCodes: true});
+ });
+ });
+
+ describe('date_of_birth', () => {
+ const cases: Array<[boolean | undefined, string | undefined, boolean, string]> = [
+ [false, 'all', true, DateOfBirthPolicies.OFF],
+ [true, 'off', true, DateOfBirthPolicies.ASK],
+ [true, 'new_accounts', true, DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS],
+ [true, 'all', true, DateOfBirthPolicies.REQUIRE_ALL],
+ [undefined, 'new_accounts', true, DateOfBirthPolicies.OFF],
+ [undefined, 'new_accounts', false, DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS],
+ [undefined, undefined, false, DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS],
+ ];
+ for (const [collect, enforcement, selfHosted, expected] of cases) {
+ it(`reads collect=${collect} with enforcement=${enforcement} ${selfHosted ? 'self-hosted' : 'hosted'} as ${expected}`, async () => {
+ config.instance.selfHosted = selfHosted;
+ const repository = createRepository();
+ if (collect !== undefined) {
+ await repository.setConfig(
+ APP_PUBLIC_CONFIG_KEY,
+ JSON.stringify({registration: {collect_date_of_birth: collect}}),
+ );
+ }
+ await repository.setConfig(
+ ACCOUNTS_CONFIG_KEY,
+ JSON.stringify(enforcement === undefined ? {} : {date_of_birth_enforcement: enforcement}),
+ );
+ expect((await repository.getAccountsConfig()).date_of_birth).toBe(expected);
+ expect((await repository.getAppPublicConfig()).registration.collect_date_of_birth).toBe(
+ expected !== DateOfBirthPolicies.OFF,
+ );
+ });
+ }
+
+ it('translates the deprecated collection switch and enforcement on write', async () => {
+ const repository = createRepository();
+ await repository.updateAccountsConfig({date_of_birth: DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS});
+ await repository.updateAccountsConfig({date_of_birth_enforcement: 'all'});
+ expect((await repository.getAccountsConfig()).date_of_birth).toBe(DateOfBirthPolicies.REQUIRE_ALL);
+ await repository.setDateOfBirthCollection(false);
+ expect((await repository.getAccountsConfig()).date_of_birth).toBe(DateOfBirthPolicies.OFF);
+ await repository.updateAccountsConfig({date_of_birth_enforcement: 'all'});
+ expect((await repository.getAccountsConfig()).date_of_birth).toBe(DateOfBirthPolicies.OFF);
+ await repository.setDateOfBirthCollection(true);
+ expect((await repository.getAccountsConfig()).date_of_birth).toBe(DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS);
+ });
+ });
+
+ describe('cleanup', () => {
+ it('turns both cleanup policies on with the defaults from a stored true', async () => {
+ const repository = createRepository();
+ await repository.setConfig(ACCOUNTS_CONFIG_KEY, JSON.stringify({abandoned_account_cleanup: true}));
+ const accounts = await repository.getAccountsConfig();
+ expect(accounts.unclaimed_account_cleanup).toEqual({
+ mode: CleanupModes.AFTER_INACTIVITY,
+ inactive_days: 90,
+ on_last_session_end: LastSessionCleanupModes.AFTER_GRACE,
+ });
+ expect(accounts.dob_missing_cleanup).toEqual({mode: CleanupModes.AFTER_INACTIVITY, inactive_days: 7});
+ });
+
+ it('turns both cleanup policies off from a stored false', async () => {
+ config.instance.selfHosted = true;
+ const repository = createRepository();
+ await repository.setConfig(ACCOUNTS_CONFIG_KEY, JSON.stringify({abandoned_account_cleanup: false}));
+ const accounts = await repository.getAccountsConfig();
+ expect(accounts.unclaimed_account_cleanup.mode).toBe(CleanupModes.OFF);
+ expect(accounts.unclaimed_account_cleanup.on_last_session_end).toBe(LastSessionCleanupModes.OFF);
+ expect(accounts.dob_missing_cleanup.mode).toBe(CleanupModes.OFF);
+ });
+
+ it('seeds a missing inactivity policy from the deprecated threshold, never below two years', async () => {
+ const repository = createRepository();
+ await repository.setConfig(ACCOUNTS_CONFIG_KEY, JSON.stringify(LEGACY_HOSTED_ACCOUNTS));
+ config.inactivityDeletionThresholdDays = 365;
+ expect((await repository.getAccountsConfig()).inactivity_deletion).toEqual({
+ mode: CleanupModes.AFTER_INACTIVITY,
+ inactive_days: 730,
+ warning_lead_days: 30,
+ });
+ config.inactivityDeletionThresholdDays = 900;
+ expect((await repository.getAccountsConfig()).inactivity_deletion.inactive_days).toBe(900);
+ });
+
+ it('keeps a stored inactivity threshold below two years', async () => {
+ const repository = createRepository();
+ await repository.updateAccountsConfig({inactivity_deletion: {inactive_days: 200}});
+ expect((await repository.getAccountsConfig()).inactivity_deletion.inactive_days).toBe(200);
+ });
+ });
+
+ it('reads an unknown guild join gate as always', async () => {
+ const repository = createRepository();
+ await repository.setConfig(ACCOUNTS_CONFIG_KEY, JSON.stringify({guild_join_gate: 'sometimes'}));
+ const accounts = await repository.getAccountsConfig();
+ expect(accounts.guild_join_gate).toBe(GuildJoinGates.ALWAYS);
+ expect(accounts.interaction_tier).toBeDefined();
+ });
+
+ it('keeps the hosted accounts row exactly as it behaves today', async () => {
+ config.instance.selfHosted = false;
+ const repository = createRepository();
+ await repository.setConfig(ACCOUNTS_CONFIG_KEY, JSON.stringify(LEGACY_HOSTED_ACCOUNTS));
+ expect(await repository.getAccountsConfig()).toEqual({
+ date_of_birth: DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS,
+ interaction_tier: 'legacy',
+ verification_basis: 'auto',
+ guild_join_gate: GuildJoinGates.ALWAYS,
+ unclaimed_account_cleanup: {
+ mode: CleanupModes.OFF,
+ inactive_days: 90,
+ on_last_session_end: LastSessionCleanupModes.OFF,
+ },
+ dob_missing_cleanup: {mode: CleanupModes.OFF, inactive_days: 7},
+ inactivity_deletion: {
+ mode: CleanupModes.AFTER_INACTIVITY,
+ inactive_days: Math.max(730, config.inactivityDeletionThresholdDays ?? 0),
+ warning_lead_days: 30,
+ },
+ });
+ });
+
+ describe('email delivery', () => {
+ const smtp = {host: 'smtp.example.com', port: 587, username: 'user', password: 'secret'};
+ const cases: Array<[boolean | null, 'smtp' | 'none' | null, string | null]> = [
+ [false, 'smtp', EmailDeliveryModes.OFF],
+ [true, 'none', EmailDeliveryModes.OFF],
+ [true, 'smtp', EmailDeliveryModes.SMTP],
+ [null, null, null],
+ ];
+ for (const [enabled, provider, expected] of cases) {
+ it(`reads enabled=${enabled} with provider=${provider} as ${expected}`, async () => {
+ const repository = createRepository();
+ await repository.setConfig(
+ INTEGRATIONS_CONFIG_KEY,
+ JSON.stringify({email: {enabled, provider, from_email: '[email protected]', smtp}}),
+ );
+ expect((await repository.getInstanceIntegrationsConfig()).email.delivery).toBe(expected);
+ });
+ }
+
+ it('translates the deprecated switches on write and stores only delivery', async () => {
+ const repository = createRepository();
+ await repository.setInstanceIntegrationsConfig({
+ email: {enabled: true, provider: 'smtp', from_email: '[email protected]', smtp},
+ });
+ expect((await repository.getInstanceIntegrationsConfig()).email.delivery).toBe(EmailDeliveryModes.SMTP);
+ expect(await repository.getEmailDeliveryState()).toBe(EmailDeliveryStates.ON);
+ await repository.setInstanceIntegrationsConfig({email: {enabled: false}});
+ const stored = (await storedJson(repository, INTEGRATIONS_CONFIG_KEY)) as {email: Record<string, unknown>};
+ expect(stored.email.delivery).toBe(EmailDeliveryModes.OFF);
+ expect(stored.email).not.toHaveProperty('enabled');
+ expect(stored.email).not.toHaveProperty('provider');
+ expect(await repository.getEmailDeliveryState()).toBe(EmailDeliveryStates.OFF_DISABLED);
+ });
+
+ it('reports incomplete settings separately from delivery being off', async () => {
+ const repository = createRepository();
+ await repository.setInstanceIntegrationsConfig({email: {delivery: EmailDeliveryModes.SMTP, from_email: null}});
+ config.email.fromEmail = '';
+ expect(await repository.getEmailDeliveryState()).toBe(EmailDeliveryStates.OFF_INCOMPLETE);
+ });
+
+ it('falls back to the env settings and the cached identity mode before the first sync', () => {
+ Object.assign(config.email, {
+ enabled: true,
+ provider: 'smtp',
+ fromEmail: '[email protected]',
+ smtp: {...smtp, tlsMode: null},
+ });
+ setCachedEmailDeliveryState(null);
+ setCachedAccountIdentity(null);
+ expect(getEmailDeliveryState()).toBe(EmailDeliveryStates.ON);
+ config.instance.selfHosted = true;
+ setCachedAccountIdentity({mode: AccountIdentityModes.USERNAME, tagStyle: TagStyles.NONE});
+ expect(getEmailDeliveryState()).toBe(EmailDeliveryStates.OFF_USERNAME_MODE);
+ });
+
+ it('turns delivery and identifier-first off when an instance switches to usernames', async () => {
+ config.instance.selfHosted = true;
+ const repository = createRepository();
+ await repository.updateAuthConfig({identifier_first: IdentifierFirstModes.ON});
+ await repository.setInstanceIntegrationsConfig({email: {delivery: EmailDeliveryModes.SMTP}});
+ await repository.setAccountIdentityMode(AccountIdentityModes.USERNAME, 'setup', TagStyles.RANDOM);
+ expect((await repository.getAccountIdentity()).tagStyle).toBe(TagStyles.NONE);
+ expect((await repository.getInstanceIntegrationsConfig()).email.delivery).toBe(EmailDeliveryModes.OFF);
+ expect((await repository.getAuthConfig()).identifier_first).toBe(IdentifierFirstModes.OFF);
+ expect(await repository.getEmailDeliveryState()).toBe(EmailDeliveryStates.OFF_USERNAME_MODE);
+ });
+ });
+});
diff --git a/fluxer_api/src/api/stripe/StripeCustomer.ts b/fluxer_api/src/api/stripe/StripeCustomer.ts
index 1e0845c18..c5826032e 100644
--- a/fluxer_api/src/api/stripe/StripeCustomer.ts
+++ b/fluxer_api/src/api/stripe/StripeCustomer.ts
@@ -57,7 +57,7 @@ export async function ensureStripeCustomer({
return freshUser;
}
const customer = await stripe.customers.create({
- email: user.email ?? undefined,
+ email: user.emailVerified ? (user.email ?? undefined) : undefined,
metadata: {
userId: user.id.toString(),
},
@@ -81,7 +81,7 @@ export async function ensureStripeCustomer({
export async function syncStripeCustomerEmail(stripe: Stripe, user: User): Promise<void> {
const customerId = user.stripeCustomerId;
const email = user.email;
- if (!customerId || !email) {
+ if (!customerId || !email || !user.emailVerified) {
return;
}
const mirrored = await getBillingRepository().customers.findById(customerId);
@@ -98,7 +98,10 @@ export async function enqueueStripeCustomerEmailSync(
oldUser: User,
newUser: User,
): Promise<void> {
- if (!newUser.stripeCustomerId || !newUser.email || oldUser.email === newUser.email) {
+ if (!newUser.stripeCustomerId || !newUser.email || !newUser.emailVerified) {
+ return;
+ }
+ if (oldUser.email === newUser.email && oldUser.emailVerified) {
return;
}
try {