Skip to content

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

TypeScript fluxerfluxerapp

feat(api/auth): add passkey and birth date user traits

Hampus7f828cbb9435
diff --git a/fluxer_api/src/api/auth/AuthEmailRevert.ts b/fluxer_api/src/api/auth/AuthEmailRevert.ts
index 82a08078e..da9d522fa 100644
--- a/fluxer_api/src/api/auth/AuthEmailRevert.ts
+++ b/fluxer_api/src/api/auth/AuthEmailRevert.ts
@@ -13,6 +13,7 @@ import type {User} from '@app/api/models/User';
import {enqueueStripeCustomerEmailSync} from '@app/api/stripe/StripeCustomer';
import {EMAIL_REVERT_TOKEN_TTL_SECONDS} from '@app/api/user/repositories/auth/TokenRepository';
import {dispatchUserUpdate} from '@app/api/user/UserMappers';
+import {UserTraits} from '@app/api/user/UserTraits';
import {hashPassword} from '@app/api/utils/PasswordUtils';
import * as RandomUtils from '@app/api/utils/RandomUtils';
import {requireConfiguredClientIp} from '@app/api/utils/RequestClientIp';
@@ -42,7 +43,7 @@ export async function issueEmailRevertToken(ctx: ApiContext, params: IssueEmailR
user_id: user.id,
email: trimmed,
});
- await email.sendEmailChangeRevert(trimmed, user.username, newEmail, token, user.locale);
+ await email.send('email_change_revert', trimmed, {newEmail, token}, user.locale);
}
const EMAIL_REVERT_CLAIM_KEY_PREFIX = 'auth:email-revert:claimed:';
@@ -91,6 +92,8 @@ export async function revertEmailChange(
let updatedUser: User;
try {
const passwordHash = await hashPassword(password);
+ const traits = user.traits;
+ traits.delete(UserTraits.PASSKEY);
updatedUser = await users.patchUpsert(
user.id,
{
@@ -100,6 +103,7 @@ export async function revertEmailChange(
authenticator_types: null,
password_hash: passwordHash,
password_last_changed_at: new Date(),
+ traits: traits.size > 0 ? traits : null,
},
user.toRow(),
);
diff --git a/fluxer_api/src/api/auth/services/PasskeyMigrationService.ts b/fluxer_api/src/api/auth/services/PasskeyMigrationService.ts
index f3244a773..72b781a4b 100644
--- a/fluxer_api/src/api/auth/services/PasskeyMigrationService.ts
+++ b/fluxer_api/src/api/auth/services/PasskeyMigrationService.ts
@@ -162,5 +162,6 @@ export async function completePasskeyMigration(
AuthMfa.storedRpId(ctx, verified.rpId),
);
await users.setWebAuthnCredentialSupersededBy(userId, legacy.credentialId, verified.credentialId);
+ await AuthMfa.syncPasskeyTrait(ctx, userId, true);
await AuthMfa.dispatchWebAuthnCredentialsUpdate(ctx, userId);
}
diff --git a/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts b/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
index 290417cdd..88fc5357c 100644
--- a/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
+++ b/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
@@ -9,9 +9,12 @@ import {
loginUser,
type TestAccount,
} from '@app/api/auth/tests/AuthTestUtils';
+import {createUserID} from '@app/api/BrandedTypes';
+import {getUserRepository} from '@app/api/middleware/ServiceSingletons';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
+import {UserTraits} from '@app/api/user/UserTraits';
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
interface EmailChangeStartResponse {
@@ -48,6 +51,7 @@ interface UserPrivateResponse {
mfa_enabled: boolean;
authenticator_types: Array<number>;
password_last_changed_at?: string;
+ traits?: Array<string>;
}
interface EmailRevertResponse {
@@ -170,9 +174,6 @@ describe('Email revert flow', () => {
await harness.reset();
await clearTestEmails(harness);
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
afterAll(async () => {
await harness?.shutdown();
});
@@ -233,4 +234,22 @@ describe('Email revert flow', () => {
.expect(400)
.execute();
});
+ it('drops the passkey trait when a claimed revert clears the passkeys', async () => {
+ const account = await createTestAccount(harness);
+ const userId = createUserID(BigInt(account.userId));
+ const stored = await getUserRepository().findUniqueAssert(userId);
+ await getUserRepository().patchUpsert(userId, {traits: new Set([UserTraits.PASSKEY])}, stored.toRow());
+ const revertToken = await changeEmailAndGetRevertToken(harness, account);
+ const revertResp = await createBuilderWithoutAuth<EmailRevertResponse>(harness)
+ .post('/auth/email-revert')
+ .body({token: revertToken, password: uniquePassword()})
+ .execute();
+ const user = await createBuilder<UserPrivateResponse>(harness, revertResp.token).get('/users/@me').execute();
+ expect(user.traits ?? []).not.toContain(UserTraits.PASSKEY);
+ await createBuilderWithoutAuth(harness)
+ .post('/auth/email-revert')
+ .body({token: revertToken, password: uniquePassword()})
+ .expect(400)
+ .execute();
+ });
});
diff --git a/fluxer_api/src/api/auth/tests/PasskeyTrait.test.ts b/fluxer_api/src/api/auth/tests/PasskeyTrait.test.ts
new file mode 100644
index 000000000..d305ccdfb
--- /dev/null
+++ b/fluxer_api/src/api/auth/tests/PasskeyTrait.test.ts
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {randomBytes} from 'node:crypto';
+import {createAuthHarness, createTestAccount, createUniqueEmail} from '@app/api/auth/tests/AuthTestUtils';
+import {
+ createSudoWebAuthnBody,
+ createWebAuthnDevice,
+ registerWebAuthnCredential,
+} from '@app/api/auth/tests/WebAuthnTestUtils';
+import {createUserID, type UserID} from '@app/api/BrandedTypes';
+import {getConfig} from '@app/api/Config';
+import {createApiContext} from '@app/api/CreateApiContext';
+import {getInstanceConfigRepository, getUserRepository} from '@app/api/middleware/ServiceSingletons';
+import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {HTTP_STATUS} from '@app/api/test/TestConstants';
+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
+import {hasWayBackIn} from '@app/api/user/AccountTier';
+import {UserTraits} from '@app/api/user/UserTraits';
+import {backfillPasskeyTraits} from '@app/api/worker/tasks/BackfillPasskeyTrait';
+import {ClaimAccountNextSteps} from '@fluxer/constants/src/AccountConfigConstants';
+import {AccountIdentityModes} from '@fluxer/constants/src/AccountIdentityConstants';
+import {AccountTiers} from '@fluxer/constants/src/AccountTierConstants';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+interface Me {
+ account_tier: string;
+ verification_need: string | null;
+ traits: Array<string>;
+}
+
+interface Registered {
+ token: string;
+ user_id: string;
+}
+
+interface Credential {
+ id: string;
+}
+
+describe('Passkey trait', () => {
+ let harness: ApiTestHarness;
+ let originalSelfHosted: boolean;
+ beforeAll(async () => {
+ harness = await createAuthHarness();
+ });
+ beforeEach(async () => {
+ await harness.reset();
+ originalSelfHosted = getConfig().instance.selfHosted;
+ });
+ afterEach(() => {
+ getConfig().instance.selfHosted = originalSelfHosted;
+ getInstanceConfigRepository().clearCacheForTesting();
+ });
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+
+ function me(token: string): Promise<Me> {
+ return createBuilder<Me>(harness, token).get('/users/@me').execute();
+ }
+
+ async function loadUser(userId: string) {
+ return await getUserRepository().findUniqueAssert(createUserID(BigInt(userId)));
+ }
+
+ async function storeCredentialWithoutTrait(userId: UserID): Promise<string> {
+ const credentialId = randomBytes(16).toString('base64url');
+ await getUserRepository().createWebAuthnCredential(
+ userId,
+ credentialId,
+ randomBytes(65),
+ 0n,
+ null,
+ 'Older passkey',
+ null,
+ );
+ return credentialId;
+ }
+
+ async function createUsernameModeUnclaimed(): Promise<Registered> {
+ getConfig().instance.selfHosted = true;
+ await getInstanceConfigRepository().setAccountIdentityMode(AccountIdentityModes.USERNAME, 'setup');
+ await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});
+ await getInstanceConfigRepository().updateAuthConfig({instant_accounts: {enabled: true}});
+ return await createBuilderWithoutAuth<Registered>(harness)
+ .post('/auth/register')
+ .body({global_name: 'Guest', date_of_birth: '1995-05-05'})
+ .execute();
+ }
+
+ it('makes an unclaimed username account verified once it registers a passkey, whatever its two-factor setting', async () => {
+ const account = await createUsernameModeUnclaimed();
+ expect((await me(account.token)).account_tier).toBe(AccountTiers.UNCLAIMED);
+ const device = createWebAuthnDevice();
+ await registerWebAuthnCredential(harness, account.token, device, () => ({}));
+ const registered = await me(account.token);
+ expect(registered).toMatchObject({account_tier: AccountTiers.VERIFIED, verification_need: null});
+ expect(registered.traits).toContain(UserTraits.PASSKEY);
+ const enable = await createSudoWebAuthnBody(harness, account.token, device);
+ await createBuilder(harness, account.token)
+ .put('/users/@me/mfa/webauthn/two-factor')
+ .body({enabled: true, ...enable})
+ .execute();
+ expect((await me(account.token)).account_tier).toBe(AccountTiers.VERIFIED);
+ const disable = await createSudoWebAuthnBody(harness, account.token, device);
+ await createBuilder(harness, account.token)
+ .put('/users/@me/mfa/webauthn/two-factor')
+ .body({enabled: false, ...disable})
+ .execute();
+ expect((await me(account.token)).account_tier).toBe(AccountTiers.VERIFIED);
+ const user = await loadUser(account.user_id);
+ expect(await hasWayBackIn({users: getUserRepository()}, user)).toBe(true);
+ });
+
+ it('removes the trait when the last passkey is deleted', async () => {
+ const account = await createTestAccount(harness);
+ const device = createWebAuthnDevice();
+ await registerWebAuthnCredential(harness, account.token, device, () => ({password: account.password}));
+ expect((await me(account.token)).traits).toContain(UserTraits.PASSKEY);
+ const [credential] = await createBuilder<Array<Credential>>(harness, account.token)
+ .get('/users/@me/mfa/webauthn/credentials')
+ .execute();
+ await createBuilder(harness, account.token)
+ .delete(`/users/@me/mfa/webauthn/credentials/${credential!.id}`)
+ .body({password: account.password})
+ .expect(HTTP_STATUS.NO_CONTENT)
+ .execute();
+ expect((await me(account.token)).traits).not.toContain(UserTraits.PASSKEY);
+ });
+
+ it('backfills the trait for stored passkeys and clears it where none is left', async () => {
+ const holder = await createTestAccount(harness);
+ const holderId = createUserID(BigInt(holder.userId));
+ await storeCredentialWithoutTrait(holderId);
+ const stale = await createTestAccount(harness);
+ const staleId = createUserID(BigInt(stale.userId));
+ const staleCredential = await storeCredentialWithoutTrait(staleId);
+ await getUserRepository().setWebAuthnCredentialSupersededBy(staleId, staleCredential, 'replacement');
+ const staleUser = await loadUser(stale.userId);
+ await getUserRepository().patchUpsert(staleId, {traits: new Set([UserTraits.PASSKEY])}, staleUser.toRow());
+ const summary = await backfillPasskeyTraits(createApiContext(), 1);
+ expect(summary).toMatchObject({users: 2, set: 1, cleared: 1, failed: 0});
+ expect((await loadUser(holder.userId)).traits.has(UserTraits.PASSKEY)).toBe(true);
+ expect((await loadUser(stale.userId)).traits.has(UserTraits.PASSKEY)).toBe(false);
+ expect(await backfillPasskeyTraits(createApiContext())).toMatchObject({set: 0, cleared: 0, failed: 0});
+ });
+
+ it('lets an email instance without delivery claim with an existing passkey and no password', async () => {
+ await getInstanceConfigRepository().setInstanceIntegrationsConfig({email: {enabled: false}});
+ await getInstanceConfigRepository().isEmailEnabled();
+ const account = await createBuilderWithoutAuth<Registered>(harness)
+ .post('/auth/register')
+ .body({username: 'keyholder', consent: true, date_of_birth: '1995-05-05'})
+ .execute();
+ await storeCredentialWithoutTrait(createUserID(BigInt(account.user_id)));
+ await backfillPasskeyTraits(createApiContext());
+ expect((await me(account.token)).account_tier).toBe(AccountTiers.UNCLAIMED);
+ const claimed = await createBuilder<{next_step: string; user: Me}>(harness, account.token)
+ .post('/users/@me/claim')
+ .body({email: createUniqueEmail('keyholder')})
+ .execute();
+ expect(claimed.next_step).toBe(ClaimAccountNextSteps.NONE);
+ expect(claimed.user.account_tier).toBe(AccountTiers.VERIFIED);
+ });
+});
diff --git a/fluxer_api/src/api/user/UserTraits.test.ts b/fluxer_api/src/api/user/UserTraits.test.ts
index 86742eb89..e0ff6064e 100644
--- a/fluxer_api/src/api/user/UserTraits.test.ts
+++ b/fluxer_api/src/api/user/UserTraits.test.ts
@@ -1,10 +1,24 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {getConfig} from '@app/api/Config';
import {isDerivedTrait, isServerManagedTrait, resolveAssignedTraits} from '@app/api/user/UserTraits';
-import {describe, expect, it} from 'vitest';
+import {afterEach, describe, expect, it} from 'vitest';
describe('UserTraits', () => {
+ const selfHosted = getConfig().instance.selfHosted;
+
+ afterEach(() => {
+ getConfig().instance.selfHosted = selfHosted;
+ });
+
+ it('lets a self-hosted admin assign premium', () => {
+ getConfig().instance.selfHosted = true;
+ expect(isDerivedTrait('premium')).toBe(false);
+ expect([...resolveAssignedTraits([], ['beta-tester', 'premium'])]).toEqual(['beta-tester', 'premium']);
+ });
+
it('treats premium as derived rather than assignable', () => {
+ getConfig().instance.selfHosted = false;
expect(isDerivedTrait('premium')).toBe(true);
expect(isDerivedTrait('beta-tester')).toBe(false);
});
@@ -23,7 +37,8 @@ describe('UserTraits', () => {
expect([...resolveAssignedTraits([], ['beta-tester', 'experimental'])]).toEqual(['beta-tester', 'experimental']);
});
- it('drops premium because nothing reads the stored value', () => {
+ it('drops premium on the hosted instance because nothing reads the stored value', () => {
+ getConfig().instance.selfHosted = false;
expect([...resolveAssignedTraits([], ['premium'])]).toEqual([]);
expect([...resolveAssignedTraits([], ['beta-tester', 'premium'])]).toEqual(['beta-tester']);
});
diff --git a/fluxer_api/src/api/user/UserTraits.ts b/fluxer_api/src/api/user/UserTraits.ts
index 6ec22e28c..af4ca0aa4 100644
--- a/fluxer_api/src/api/user/UserTraits.ts
+++ b/fluxer_api/src/api/user/UserTraits.ts
@@ -1,13 +1,28 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {Config} from '@app/api/Config';
+import {UserTraits} from '@fluxer/constants/src/UserTraitConstants';
+
+export {UserTraits};
+
+export const DOB_DEFERRED_TRAIT = UserTraits.DOB_DEFERRED;
+export const BELOW_MINIMUM_AGE_TRAIT = UserTraits.BELOW_MINIMUM_AGE;
+
const DERIVED_TRAITS = new Set(['premium']);
-const SERVER_MANAGED_TRAITS = new Set(['sso', 'registration_pending_approval', 'registration_rejected']);
+const SERVER_MANAGED_TRAITS = new Set<string>([
+ UserTraits.SSO,
+ UserTraits.PASSKEY,
+ 'registration_pending_approval',
+ 'registration_rejected',
+ UserTraits.DOB_DEFERRED,
+ UserTraits.BELOW_MINIMUM_AGE,
+]);
const SERVER_MANAGED_TRAIT_PREFIXES = ['sso:', 'sso_provider:', 'sso_identity:'];
export function isDerivedTrait(trait: string): boolean {
- return DERIVED_TRAITS.has(trait);
+ return !Config.instance.selfHosted && DERIVED_TRAITS.has(trait);
}
export function isServerManagedTrait(trait: string): boolean {
diff --git a/fluxer_api/src/api/worker/tasks/BackfillPasskeyTrait.ts b/fluxer_api/src/api/worker/tasks/BackfillPasskeyTrait.ts
new file mode 100644
index 000000000..d6809658e
--- /dev/null
+++ b/fluxer_api/src/api/worker/tasks/BackfillPasskeyTrait.ts
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {ApiContext} from '@app/api/ApiContext';
+import {syncPasskeyTrait} from '@app/api/auth/AuthMfa';
+import {visibleWebAuthnCredentials} from '@app/api/auth/services/PasskeyRelyingParty';
+import type {UserID} from '@app/api/BrandedTypes';
+import {createApiContext} from '@app/api/CreateApiContext';
+import {fetchMany} from '@app/api/database/CassandraQueryExecution';
+import {Logger} from '@app/api/Logger';
+import {WebAuthnCredentialLookup} from '@app/api/Tables';
+import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
+import {WorkerQueueOverflowError} from '@app/api/worker/WorkerQueueOverflowError';
+import type {WorkerService} from '@app/api/worker/WorkerService';
+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
+import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
+import {ms} from 'itty-time';
+
+const PASSKEY_TRAIT_BACKFILL_DONE_KEY = 'backfill:passkey_trait:done';
+const CLAIM_KEY = 'backfill:passkey_trait:queued';
+const CLAIM_TTL_SECONDS = ms('6 hours') / 1000;
+const DEFAULT_PAGE_SIZE = 500;
+
+interface CredentialOwnerRow {
+ credential_id: string;
+ user_id: UserID;
+}
+
+export interface PasskeyTraitBackfillSummary {
+ users: number;
+ set: number;
+ cleared: number;
+ failed: number;
+}
+
+const firstPageQuery = (limit: number) => WebAuthnCredentialLookup.select({limit});
+const nextPageQuery = (limit: number) =>
+ WebAuthnCredentialLookup.select({
+ where: WebAuthnCredentialLookup.where.tokenGt('credential_id', 'last_credential_id'),
+ limit,
+ });
+
+async function fetchCredentialOwners(limit: number, after: string | undefined): Promise<Array<CredentialOwnerRow>> {
+ if (after === undefined) return fetchMany<CredentialOwnerRow>(firstPageQuery(limit).bind({}));
+ return fetchMany<CredentialOwnerRow>(nextPageQuery(limit).bind({last_credential_id: after}));
+}
+
+export async function backfillPasskeyTraits(
+ ctx: ApiContext,
+ pageSize = DEFAULT_PAGE_SIZE,
+): Promise<PasskeyTraitBackfillSummary> {
+ const summary: PasskeyTraitBackfillSummary = {users: 0, set: 0, cleared: 0, failed: 0};
+ const seen = new Set<UserID>();
+ let cursor: string | undefined;
+ while (true) {
+ const page = await fetchCredentialOwners(pageSize, cursor);
+ for (const row of page) {
+ if (seen.has(row.user_id)) continue;
+ seen.add(row.user_id);
+ summary.users++;
+ try {
+ const credentials = await ctx.services.users.listWebAuthnCredentials(row.user_id);
+ const present = visibleWebAuthnCredentials(credentials).length > 0;
+ if (await syncPasskeyTrait(ctx, row.user_id, present)) {
+ if (present) summary.set++;
+ else summary.cleared++;
+ }
+ } catch (error) {
+ summary.failed++;
+ Logger.error({error, userId: row.user_id.toString()}, 'Failed to backfill the passkey trait');
+ }
+ }
+ if (page.length < pageSize) break;
+ cursor = page[page.length - 1]!.credential_id;
+ }
+ Logger.info(summary, 'Backfilled the passkey trait');
+ return summary;
+}
+
+export async function queuePasskeyTraitBackfill(
+ kvClient: Pick<IKVProvider, 'get' | 'setnx' | 'del'>,
+ workerService: Pick<WorkerService, 'addJob'>,
+): Promise<void> {
+ if ((await kvClient.get(PASSKEY_TRAIT_BACKFILL_DONE_KEY)) !== null) return;
+ if (!(await kvClient.setnx(CLAIM_KEY, '1', CLAIM_TTL_SECONDS))) return;
+ try {
+ await workerService.addJob('backfillPasskeyTrait', {});
+ } catch (error) {
+ await kvClient.del(CLAIM_KEY);
+ if (!(error instanceof WorkerQueueOverflowError)) throw error;
+ Logger.warn('Dropped the passkey trait backfill job, jobs stream is at its limit');
+ }
+}
+
+const backfillPasskeyTraitTask: WorkerTaskHandler = async () => {
+ const summary = await backfillPasskeyTraits(createApiContext());
+ if (summary.failed > 0) throw new Error(`Passkey trait backfill failed for ${summary.failed} users`);
+ await getWorkerDependencies().kvClient.set(PASSKEY_TRAIT_BACKFILL_DONE_KEY, new Date().toISOString());
+};
+
+export default backfillPasskeyTraitTask;