Skip to content

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

TypeScript fluxerfluxerapp

feat(api): add verification levels gating actions and purchases

Hampusc1a31a149ae1
diff --git a/fluxer_api/src/api/user/AccountTier.ts b/fluxer_api/src/api/user/AccountTier.ts
new file mode 100644
index 000000000..1b0deab7a
--- /dev/null
+++ b/fluxer_api/src/api/user/AccountTier.ts
@@ -0,0 +1,273 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {RecoveryKitRepository} from '@app/api/auth/services/RecoveryKitRepository';
+import type {UserID} from '@app/api/BrandedTypes';
+import {getCachedAccountIdentityMode, usesUsernameSignIn} from '@app/api/instance/AccountIdentityModeCache';
+import {
+ getEffectiveVerificationBasis,
+ getEmailDeliveryState,
+ getInteractionTierMode,
+ guildJoinGateApplies,
+} from '@app/api/instance/AccountsConfigCache';
+import {instanceCollectsDateOfBirth} from '@app/api/instance/DateOfBirthCollectionCache';
+import type {User} from '@app/api/models/User';
+import type {HonoEnv} from '@app/api/types/HonoEnv';
+import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {UserTraits} from '@app/api/user/UserTraits';
+import {canUserAccessNsfwContent} from '@app/api/utils/AgeUtils';
+import {EmailDeliveryStates, InteractionTierModes} from '@fluxer/constants/src/AccountConfigConstants';
+import {
+ type AccountTier,
+ AccountTiers,
+ type AccountVerificationNeed,
+ AccountVerificationNeeds,
+ type LocalCredentialKind,
+ LocalCredentialKinds,
+ localCredentialKindOf,
+ type PurchaseBlockedReason,
+ type TierDenialError,
+ TierDenialErrors,
+ type TierExemption,
+ TierExemptions,
+ type TierGatedAction,
+ TierGatedActions,
+} from '@fluxer/constants/src/AccountTierConstants';
+import {
+ evaluateTierGate,
+ resolveAccountTier,
+ resolvePurchaseBlockedReason,
+ resolveVerificationNeed,
+ type TierGateDenial,
+ type TierGateResult,
+} from '@fluxer/constants/src/AccountTierRules';
+import {Headers} from '@fluxer/constants/src/Headers';
+import {UserAuthenticatorTypes} from '@fluxer/constants/src/UserConstants';
+import {AccountBelowMinimumAgeError} from '@fluxer/errors/src/domains/auth/AccountBelowMinimumAgeError';
+import {AccountVerificationRequiredError} from '@fluxer/errors/src/domains/auth/AccountVerificationRequiredError';
+import {DateOfBirthRequiredError} from '@fluxer/errors/src/domains/auth/DateOfBirthRequiredError';
+import {
+ DirectMessageEmailVerificationRequiredError,
+ EmailVerificationRequiredError,
+ FriendRequestEmailVerificationRequiredError,
+ GuildCreationEmailVerificationRequiredError,
+ GuildEmailVerificationRequiredError,
+ MfaEmailVerificationRequiredError,
+ ProfileEmailVerificationRequiredError,
+ ReactionEmailVerificationRequiredError,
+ ReportEmailVerificationRequiredError,
+} from '@fluxer/errors/src/domains/auth/EmailVerificationRequiredError';
+import {UnclaimedAccountCannotAddReactionsError} from '@fluxer/errors/src/domains/channel/UnclaimedAccountCannotAddReactionsError';
+import {UnclaimedAccountCannotJoinGroupDmsError} from '@fluxer/errors/src/domains/channel/UnclaimedAccountCannotJoinGroupDmsError';
+import {UnclaimedAccountCannotJoinOneOnOneVoiceCallsError} from '@fluxer/errors/src/domains/channel/UnclaimedAccountCannotJoinOneOnOneVoiceCallsError';
+import {UnclaimedAccountCannotJoinVoiceChannelsError} from '@fluxer/errors/src/domains/channel/UnclaimedAccountCannotJoinVoiceChannelsError';
+import {UnclaimedAccountCannotSendDirectMessagesError} from '@fluxer/errors/src/domains/channel/UnclaimedAccountCannotSendDirectMessagesError';
+import {UnclaimedAccountCannotSendMessagesError} from '@fluxer/errors/src/domains/channel/UnclaimedAccountCannotSendMessagesError';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
+import {GuildVerificationRequiredError} from '@fluxer/errors/src/domains/guild/GuildVerificationRequiredError';
+import {GuildVisitAgeRestrictedError} from '@fluxer/errors/src/domains/guild/GuildVisitAgeRestrictedError';
+import {UnclaimedAccountCannotCreateGuildsError} from '@fluxer/errors/src/domains/guild/UnclaimedAccountCannotCreateGuildsError';
+import {UnclaimedAccountCannotSubmitReportsError} from '@fluxer/errors/src/domains/moderation/UnclaimedAccountCannotSubmitReportsError';
+import {UnclaimedAccountCannotCreateApplicationsError} from '@fluxer/errors/src/domains/oauth/UnclaimedAccountCannotCreateApplicationsError';
+import {UnclaimedAccountCannotAcceptFriendRequestsError} from '@fluxer/errors/src/domains/user/UnclaimedAccountCannotAcceptFriendRequestsError';
+import {UnclaimedAccountCannotSendFriendRequestsError} from '@fluxer/errors/src/domains/user/UnclaimedAccountCannotSendFriendRequestsError';
+import type {FluxerError} from '@fluxer/errors/src/FluxerError';
+import type {Context} from 'hono';
+
+export type {AccountTier};
+
+export const GUILD_VISITS_CAPABILITY = 'guild_visits';
+export const PAYMENT_DISPUTE_REASON_CAPABILITY = 'payment_dispute_reason';
+
+const KNOWN_CAPABILITIES = [GUILD_VISITS_CAPABILITY, PAYMENT_DISPUTE_REASON_CAPABILITY] as const;
+
+export type TierCapability = (typeof KNOWN_CAPABILITIES)[number];
+
+export interface TierContext {
+ capabilities: ReadonlySet<TierCapability>;
+ isGuildOwner?: boolean;
+}
+
+export const NO_TIER_CONTEXT: TierContext = {capabilities: new Set()};
+
+type TierUser = Pick<User, 'isBot' | 'isSystem' | 'email' | 'emailVerified' | 'passwordHash' | 'authenticatorTypes'> & {
+ traits: ReadonlySet<string>;
+};
+
+type GatedUser = TierUser & {id: UserID};
+
+export function getLocalCredential(
+ user: Pick<TierUser, 'passwordHash' | 'authenticatorTypes' | 'traits'>,
+): LocalCredentialKind {
+ return localCredentialKindOf({
+ hasPassword: user.passwordHash !== null,
+ hasPasskey: user.traits.has(UserTraits.PASSKEY) || user.authenticatorTypes.has(UserAuthenticatorTypes.WEBAUTHN),
+ });
+}
+
+export function getAccountTier(user: TierUser): AccountTier {
+ return resolveAccountTier({
+ isBot: user.isBot,
+ isSystem: user.isSystem,
+ traits: user.traits,
+ identityMode: getCachedAccountIdentityMode(),
+ effectiveBasis: getEffectiveVerificationBasis(),
+ hasEmail: user.email !== null,
+ emailVerified: user.emailVerified,
+ localCredential: getLocalCredential(user),
+ });
+}
+
+export function getVerificationNeed(user: TierUser): AccountVerificationNeed | null {
+ return resolveVerificationNeed({
+ tier: getAccountTier(user),
+ identityMode: getCachedAccountIdentityMode(),
+ hasEmail: user.email !== null,
+ });
+}
+
+interface WayBackDeps {
+ users: Pick<UserRepository, 'listWebAuthnCredentials'>;
+}
+
+const recoveryKits = new RecoveryKitRepository();
+
+export async function hasWayBackIn(deps: WayBackDeps, user: GatedUser): Promise<boolean> {
+ if (user.isBot || user.isSystem || user.traits.has(UserTraits.SSO)) return true;
+ const localCredential = getLocalCredential(user);
+ if (
+ localCredential === LocalCredentialKinds.PASSKEY ||
+ localCredential === LocalCredentialKinds.PASSWORD_AND_PASSKEY
+ ) {
+ return true;
+ }
+ const usernameMode = usesUsernameSignIn();
+ if (user.passwordHash !== null && (usernameMode || user.email !== null)) return true;
+ if (user.email !== null && !usernameMode && getEmailDeliveryState() === EmailDeliveryStates.ON) return true;
+ if (usernameMode && (await recoveryKits.find(user.id)) !== null) return true;
+ return (await deps.users.listWebAuthnCredentials(user.id)).length > 0;
+}
+
+export function isInteractionTierEnforced(): boolean {
+ return getInteractionTierMode() === InteractionTierModes.ENFORCED;
+}
+
+export function canReachOthers(user: TierUser): boolean {
+ return getAccountTier(user) === AccountTiers.VERIFIED;
+}
+
+function tierExemptionsFor(ctx: TierContext): ReadonlyArray<TierExemption> {
+ return ctx.isGuildOwner ? [TierExemptions.GUILD_OWNER] : [];
+}
+
+export function evaluateTierGateFor(user: GatedUser, action: TierGatedAction, ctx: TierContext): TierGateResult {
+ const tier = getAccountTier(user);
+ if (tier === AccountTiers.VERIFIED) return {allowed: true};
+ return evaluateTierGate({
+ tier,
+ mode: getInteractionTierMode(),
+ action,
+ identityMode: getCachedAccountIdentityMode(),
+ hasEmail: user.email !== null,
+ guildJoinGateApplies:
+ action === TierGatedActions.GUILD_JOIN &&
+ guildJoinGateApplies({userId: user.id, visitsCapable: ctx.capabilities.has(GUILD_VISITS_CAPABILITY)}),
+ exemptions: tierExemptionsFor(ctx),
+ });
+}
+
+export function canTierPerform(user: GatedUser, action: TierGatedAction, ctx: TierContext): boolean {
+ return evaluateTierGateFor(user, action, ctx).allowed;
+}
+
+const TIER_DENIAL_ERRORS: Record<TierDenialError, (denial: TierGateDenial) => FluxerError> = {
+ [TierDenialErrors.ACCOUNT_VERIFICATION_REQUIRED]: (denial) =>
+ new AccountVerificationRequiredError(denial.action, denial.tier, denial.need),
+ [TierDenialErrors.EMAIL_VERIFICATION_REQUIRED]: () => new EmailVerificationRequiredError(),
+ [TierDenialErrors.DIRECT_MESSAGE_EMAIL_VERIFICATION_REQUIRED]: () =>
+ new DirectMessageEmailVerificationRequiredError(),
+ [TierDenialErrors.FRIEND_REQUEST_EMAIL_VERIFICATION_REQUIRED]: () =>
+ new FriendRequestEmailVerificationRequiredError(),
+ [TierDenialErrors.GUILD_CREATION_EMAIL_VERIFICATION_REQUIRED]: () =>
+ new GuildCreationEmailVerificationRequiredError(),
+ [TierDenialErrors.GUILD_EMAIL_VERIFICATION_REQUIRED]: () => new GuildEmailVerificationRequiredError(),
+ [TierDenialErrors.GUILD_VERIFICATION_REQUIRED]: () => new GuildVerificationRequiredError(),
+ [TierDenialErrors.MFA_EMAIL_VERIFICATION_REQUIRED]: () => new MfaEmailVerificationRequiredError(),
+ [TierDenialErrors.PROFILE_EMAIL_VERIFICATION_REQUIRED]: () => new ProfileEmailVerificationRequiredError(),
+ [TierDenialErrors.REACTION_EMAIL_VERIFICATION_REQUIRED]: () => new ReactionEmailVerificationRequiredError(),
+ [TierDenialErrors.REPORT_EMAIL_VERIFICATION_REQUIRED]: () => new ReportEmailVerificationRequiredError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_ACCEPT_FRIEND_REQUESTS]: () =>
+ new UnclaimedAccountCannotAcceptFriendRequestsError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_ADD_REACTIONS]: () => new UnclaimedAccountCannotAddReactionsError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_CREATE_APPLICATIONS]: () =>
+ new UnclaimedAccountCannotCreateApplicationsError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_CREATE_GUILDS]: () => new UnclaimedAccountCannotCreateGuildsError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_JOIN_GROUP_DMS]: () => new UnclaimedAccountCannotJoinGroupDmsError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_JOIN_ONE_ON_ONE_VOICE_CALLS]: () =>
+ new UnclaimedAccountCannotJoinOneOnOneVoiceCallsError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_JOIN_VOICE_CHANNELS]: () =>
+ new UnclaimedAccountCannotJoinVoiceChannelsError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_SEND_DIRECT_MESSAGES]: () =>
+ new UnclaimedAccountCannotSendDirectMessagesError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_SEND_FRIEND_REQUESTS]: () =>
+ new UnclaimedAccountCannotSendFriendRequestsError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_SEND_MESSAGES]: () => new UnclaimedAccountCannotSendMessagesError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNT_CANNOT_SUBMIT_REPORTS]: () => new UnclaimedAccountCannotSubmitReportsError(),
+ [TierDenialErrors.UNCLAIMED_ACCOUNTS_CAN_ONLY_SET_EMAIL_VIA_TOKEN]: (denial) =>
+ InputValidationError.fromCode('profile', TierDenialErrors.UNCLAIMED_ACCOUNTS_CAN_ONLY_SET_EMAIL_VIA_TOKEN, {
+ need: denial.need,
+ }),
+};
+
+export function tierDenialError(denial: TierGateDenial): FluxerError {
+ return TIER_DENIAL_ERRORS[denial.errorCode](denial);
+}
+
+export function assertTierAllows(user: GatedUser, action: TierGatedAction, ctx: TierContext): void {
+ const result = evaluateTierGateFor(user, action, ctx);
+ if (!result.allowed) throw tierDenialError(result);
+}
+
+export function assertCanRegisterPasskey(user: GatedUser): void {
+ const result = evaluateTierGateFor(user, TierGatedActions.MFA, NO_TIER_CONTEXT);
+ if (!result.allowed && result.need !== AccountVerificationNeeds.SET_PASSWORD) throw tierDenialError(result);
+}
+
+export type PurchaseEligibility = {allowed: true} | {allowed: false; blocked: PurchaseBlockedReason};
+
+export function resolvePurchaseEligibility(user: TierUser): PurchaseEligibility {
+ const blocked = resolvePurchaseBlockedReason({tier: getAccountTier(user), hasEmail: user.email !== null});
+ return blocked === null ? {allowed: true} : {allowed: false, blocked};
+}
+
+type VisitUser = Pick<User, 'isBot' | 'isSystem' | 'dateOfBirth'> & {traits: ReadonlySet<string>};
+
+export function assertCanVisit(user: VisitUser, guild: {nsfw: boolean}): {adult_content_allowed: boolean} {
+ if (user.traits.has(UserTraits.BELOW_MINIMUM_AGE)) throw new AccountBelowMinimumAgeError();
+ if (!user.isBot && !user.isSystem && instanceCollectsDateOfBirth() && user.dateOfBirth === null) {
+ throw new DateOfBirthRequiredError();
+ }
+ const adultContentAllowed = canUserAccessNsfwContent(user);
+ if (guild.nsfw && !adultContentAllowed) throw new GuildVisitAgeRestrictedError();
+ return {adult_content_allowed: adultContentAllowed};
+}
+
+const MAX_CAPABILITY_HEADER_LENGTH = 512;
+
+export function tierContextFrom(ctx: Context<HonoEnv>): TierContext {
+ return tierContextFromRequest(ctx.req.raw);
+}
+
+export function tierContextFromRequest(request: Request): TierContext {
+ return {capabilities: parseTierCapabilities(request.headers.get(Headers.X_FLUXER_CAPABILITIES))};
+}
+
+export function parseTierCapabilities(headerValue: string | null | undefined): ReadonlySet<TierCapability> {
+ if (!headerValue || headerValue.length > MAX_CAPABILITY_HEADER_LENGTH) return NO_TIER_CONTEXT.capabilities;
+ const capabilities = new Set<TierCapability>();
+ for (const raw of headerValue.split(',')) {
+ const name = raw.trim().toLowerCase();
+ const known = KNOWN_CAPABILITIES.find((capability) => capability === name);
+ if (known) capabilities.add(known);
+ }
+ return capabilities;
+}
diff --git a/fluxer_api/src/api/user/tests/AccountTier.test.ts b/fluxer_api/src/api/user/tests/AccountTier.test.ts
new file mode 100644
index 000000000..4c8a0588b
--- /dev/null
+++ b/fluxer_api/src/api/user/tests/AccountTier.test.ts
@@ -0,0 +1,265 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createUserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
+import {EMPTY_USER_ROW, type UserRow} from '@app/api/database/types/UserTypes';
+import {setCachedGuildVisitsConfig} from '@app/api/experiment/GuildVisitsGate';
+import {setCachedAccountIdentity} from '@app/api/instance/AccountIdentityModeCache';
+import {
+ getEffectiveVerificationBasis,
+ hostedAccountsDefaults,
+ setCachedAccountsConfig,
+ setCachedEmailDeliveryState,
+} from '@app/api/instance/AccountsConfigCache';
+import {User} from '@app/api/models/User';
+import {WebAuthnCredential} from '@app/api/models/WebAuthnCredential';
+import {
+ assertCanRegisterPasskey,
+ assertTierAllows,
+ GUILD_VISITS_CAPABILITY,
+ getAccountTier,
+ hasWayBackIn,
+ NO_TIER_CONTEXT,
+ PAYMENT_DISPUTE_REASON_CAPABILITY,
+ parseTierCapabilities,
+ type TierContext,
+} from '@app/api/user/AccountTier';
+import {EmailDeliveryStates, VerificationBases} from '@fluxer/constants/src/AccountConfigConstants';
+import {AccountIdentityModes, TagStyles} from '@fluxer/constants/src/AccountIdentityConstants';
+import type {TierGatedAction} from '@fluxer/constants/src/AccountTierConstants';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {UserAuthenticatorTypes} from '@fluxer/constants/src/UserConstants';
+import {FluxerError} from '@fluxer/errors/src/FluxerError';
+import {GuildVisitsConfigSchema} from '@fluxer/schema/src/domains/admin/GuildVisitsSchemas';
+import {afterEach, describe, expect, it} from 'vitest';
+
+function createUser(overrides: Partial<UserRow> = {}): User {
+ return new User({
+ ...EMPTY_USER_ROW,
+ user_id: createUserID(1n),
+ username: 'tier_user',
+ discriminator: 1,
+ bot: false,
+ email: '[email protected]',
+ email_verified: true,
+ password_hash: null,
+ traits: new Set<string>(),
+ ...overrides,
+ });
+}
+
+const UNCLAIMED = createUser({email: null, email_verified: false});
+const UNVERIFIED = createUser({email_verified: false});
+const VERIFIED = createUser();
+
+function useInteractionTier(mode: 'legacy' | 'enforced', guildJoinGate: 'visits_capable' | 'always' = 'always') {
+ setCachedAccountsConfig({
+ ...hostedAccountsDefaults().accounts,
+ interaction_tier: mode,
+ guild_join_gate: guildJoinGate,
+ });
+}
+
+function useGuildVisits(enabled: boolean): void {
+ setCachedGuildVisitsConfig(GuildVisitsConfigSchema.parse({enabled, included_user_ids: enabled ? ['1'] : []}));
+}
+
+function reachCode(user: User, action: TierGatedAction, ctx: TierContext = NO_TIER_CONTEXT): string | null {
+ try {
+ assertTierAllows(user, action, ctx);
+ return null;
+ } catch (error) {
+ if (error instanceof FluxerError) return error.code;
+ throw error;
+ }
+}
+
+const CAPABLE: TierContext = {capabilities: new Set([GUILD_VISITS_CAPABILITY])};
+
+afterEach(() => {
+ setCachedAccountsConfig(null);
+ setCachedGuildVisitsConfig(null);
+ setCachedEmailDeliveryState(null);
+});
+
+describe('getAccountTier', () => {
+ it('decides by email on instances that sign in with an email', () => {
+ expect(getAccountTier(UNCLAIMED)).toBe('unclaimed');
+ expect(getAccountTier(UNVERIFIED)).toBe('unverified');
+ expect(getAccountTier(VERIFIED)).toBe('verified');
+ expect(getAccountTier(createUser({email: null, password_hash: 'hash'}))).toBe('unclaimed');
+ });
+
+ it('treats bots, system accounts and SSO accounts as verified', () => {
+ expect(getAccountTier(createUser({email: null, bot: true}))).toBe('verified');
+ expect(getAccountTier(createUser({email: null, system: true}))).toBe('verified');
+ expect(getAccountTier(createUser({email: null, traits: new Set(['sso'])}))).toBe('verified');
+ });
+
+ it('needs a password or passkey next to the email when the instance cannot send email', () => {
+ setCachedEmailDeliveryState(EmailDeliveryStates.OFF_DISABLED);
+ expect(getAccountTier(createUser({email_verified: true}))).toBe('unclaimed');
+ expect(getAccountTier(createUser({password_hash: 'hash'}))).toBe('verified');
+ expect(getAccountTier(createUser({authenticator_types: new Set([UserAuthenticatorTypes.WEBAUTHN])}))).toBe(
+ 'verified',
+ );
+ });
+
+ it('reads a stored confirmed email basis as a local credential while email cannot be delivered', () => {
+ setCachedAccountsConfig({
+ ...hostedAccountsDefaults().accounts,
+ verification_basis: VerificationBases.CONFIRMED_EMAIL,
+ });
+ expect(getAccountTier(createUser({email_verified: false, password_hash: 'hash'}))).toBe('unverified');
+ setCachedEmailDeliveryState(EmailDeliveryStates.OFF_INCOMPLETE);
+ expect(getEffectiveVerificationBasis()).toBe(VerificationBases.LOCAL_CREDENTIAL);
+ expect(getAccountTier(createUser({email_verified: false, password_hash: 'hash'}))).toBe('verified');
+ expect(getAccountTier(createUser({email_verified: false}))).toBe('unclaimed');
+ });
+});
+
+describe('guild join gate', () => {
+ it('keeps joining open while the visit rollout does not cover the account', () => {
+ useInteractionTier('enforced');
+ useGuildVisits(false);
+ expect(reachCode(UNCLAIMED, 'guild_join', CAPABLE)).toBeNull();
+ });
+
+ it('keeps joining open for a client that cannot visit when the gate is limited to visit clients', () => {
+ useInteractionTier('enforced', 'visits_capable');
+ useGuildVisits(true);
+ expect(reachCode(UNCLAIMED, 'guild_join', NO_TIER_CONTEXT)).toBeNull();
+ });
+
+ it('refuses joining for a visit capable client in the rollout', () => {
+ useInteractionTier('enforced');
+ useGuildVisits(true);
+ expect(reachCode(UNCLAIMED, 'guild_join', CAPABLE)).toBe(APIErrorCodes.ACCOUNT_VERIFICATION_REQUIRED);
+ expect(reachCode(UNVERIFIED, 'guild_join', CAPABLE)).toBe(APIErrorCodes.ACCOUNT_VERIFICATION_REQUIRED);
+ expect(reachCode(VERIFIED, 'guild_join', CAPABLE)).toBeNull();
+ });
+
+ it('refuses joining for every client by default', () => {
+ useInteractionTier('enforced');
+ useGuildVisits(true);
+ expect(reachCode(UNCLAIMED, 'guild_join', NO_TIER_CONTEXT)).toBe(APIErrorCodes.ACCOUNT_VERIFICATION_REQUIRED);
+ });
+
+ it('stays open in legacy mode', () => {
+ useInteractionTier('legacy', 'always');
+ useGuildVisits(true);
+ expect(reachCode(UNCLAIMED, 'guild_join', CAPABLE)).toBeNull();
+ });
+
+ it('parses only known capabilities', () => {
+ expect(parseTierCapabilities('guild_visits, other')).toEqual(new Set([GUILD_VISITS_CAPABILITY]));
+ expect(parseTierCapabilities('Guild_Visits')).toEqual(new Set([GUILD_VISITS_CAPABILITY]));
+ expect(parseTierCapabilities('guild_visits,payment_dispute_reason')).toEqual(
+ new Set([GUILD_VISITS_CAPABILITY, PAYMENT_DISPUTE_REASON_CAPABILITY]),
+ );
+ expect(parseTierCapabilities(undefined).size).toBe(0);
+ expect(parseTierCapabilities('x'.repeat(600)).size).toBe(0);
+ });
+});
+
+describe('hasWayBackIn', () => {
+ function deps(credentials: Array<WebAuthnCredential> = []) {
+ return {
+ users: {
+ listWebAuthnCredentials: async () => credentials,
+ },
+ };
+ }
+
+ it('counts a confirmed email, a password, a passkey and SSO', async () => {
+ expect(await hasWayBackIn(deps(), VERIFIED)).toBe(true);
+ expect(await hasWayBackIn(deps(), createUser({email_verified: false, password_hash: 'hash'}))).toBe(true);
+ const credential = new WebAuthnCredential({
+ user_id: UNCLAIMED.id,
+ credential_id: 'stored-passkey',
+ public_key: Buffer.from([1, 2, 3]),
+ counter: 0n,
+ transports: new Set(['internal']),
+ name: 'Passkey',
+ created_at: new Date(0),
+ last_used_at: null,
+ version: 1,
+ rp_id: 'example.com',
+ superseded_by: null,
+ });
+ expect(await hasWayBackIn(deps([credential]), UNCLAIMED)).toBe(true);
+ expect(await hasWayBackIn(deps(), createUser({email: null, traits: new Set(['sso'])}))).toBe(true);
+ });
+
+ it('counts an unconfirmed address when the instance sends email', async () => {
+ expect(await hasWayBackIn(deps(), UNVERIFIED)).toBe(true);
+ });
+
+ it('counts a password without an email only where sign-in takes a username', async () => {
+ const passwordOnly = createUser({email: null, email_verified: false, password_hash: 'hash'});
+ expect(await hasWayBackIn(deps(), passwordOnly)).toBe(false);
+ const selfHosted = Config.instance.selfHosted;
+ Config.instance.selfHosted = true;
+ setCachedAccountIdentity({mode: AccountIdentityModes.USERNAME, tagStyle: TagStyles.NONE});
+ try {
+ expect(await hasWayBackIn(deps(), passwordOnly)).toBe(true);
+ } finally {
+ setCachedAccountIdentity(null);
+ Config.instance.selfHosted = selfHosted;
+ }
+ });
+
+ it('finds no way back for a username-only account', async () => {
+ expect(await hasWayBackIn(deps(), UNCLAIMED)).toBe(false);
+ });
+
+ it('counts no email at all when the instance cannot send email, whatever the stored flag says', async () => {
+ setCachedEmailDeliveryState(EmailDeliveryStates.OFF_DISABLED);
+ expect(await hasWayBackIn(deps(), VERIFIED)).toBe(false);
+ expect(await hasWayBackIn(deps(), UNVERIFIED)).toBe(false);
+ expect(await hasWayBackIn(deps(), createUser({password_hash: 'hash'}))).toBe(true);
+ });
+
+ it('counts the passkey trait without reading stored credentials', async () => {
+ const passkeyOnly = createUser({email: null, email_verified: false, traits: new Set(['passkey'])});
+ const users = {
+ listWebAuthnCredentials: async () => {
+ throw new Error('should not be read');
+ },
+ };
+ expect(await hasWayBackIn({users}, passkeyOnly)).toBe(true);
+ });
+});
+
+describe('assertCanRegisterPasskey', () => {
+ function registerCode(user: User): string | null {
+ try {
+ assertCanRegisterPasskey(user);
+ return null;
+ } catch (error) {
+ if (error instanceof FluxerError) return error.code;
+ throw error;
+ }
+ }
+
+ it('keeps the MFA gate where an email is what the account still needs', () => {
+ useInteractionTier('legacy');
+ expect(registerCode(UNCLAIMED)).toBe(APIErrorCodes.MFA_EMAIL_VERIFICATION_REQUIRED);
+ expect(registerCode(UNVERIFIED)).toBe(APIErrorCodes.MFA_EMAIL_VERIFICATION_REQUIRED);
+ expect(registerCode(VERIFIED)).toBeNull();
+ });
+
+ it('lets an account that needs a credential register a passkey', () => {
+ setCachedEmailDeliveryState(EmailDeliveryStates.OFF_DISABLED);
+ expect(registerCode(createUser({email_verified: false}))).toBeNull();
+ const selfHosted = Config.instance.selfHosted;
+ Config.instance.selfHosted = true;
+ setCachedAccountIdentity({mode: AccountIdentityModes.USERNAME, tagStyle: TagStyles.NONE});
+ try {
+ expect(registerCode(UNCLAIMED)).toBeNull();
+ } finally {
+ setCachedAccountIdentity(null);
+ Config.instance.selfHosted = selfHosted;
+ }
+ });
+});