Skip to content

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

TypeScript fluxerfluxerapp

feat(app): add code sign-in, remember known devices, age block

Hampus1b4945747a65
diff --git a/fluxer_app/src/features/auth/commands/AccountEntryCommands.ts b/fluxer_app/src/features/auth/commands/AccountEntryCommands.ts
new file mode 100644
index 000000000..a4d485fe0
--- /dev/null
+++ b/fluxer_app/src/features/auth/commands/AccountEntryCommands.ts
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {Endpoints} from '@app/features/app/constants/Endpoints';
+import type {RuntimeConfigSnapshot} from '@app/features/app/state/InstanceSnapshotStore';
+import {
+ type AuthTokenResponse,
+ isRegistrationPendingApprovalResponse,
+ type MfaLoginResponse,
+ type RegistrationPendingApprovalResponse,
+} from '@app/features/auth/commands/AuthenticationCommands';
+import {readDeviceProof, storeDeviceProof} from '@app/features/auth/state/AccountEntryStorage';
+import {switcherAccounts} from '@app/features/auth/state/AccountSwitcherAccounts';
+import {type LoginSuccessPayload, type MfaChallenge, toLoginSuccessPayload} from '@app/features/auth/state/AuthFlow';
+import {instanceRequest, instanceTargetFromSnapshot} from '@app/features/platform/transport/InstanceHTTP';
+import {getCurrentOrDetectedLocale} from '@app/features/user/utils/LocaleUtils';
+import type {EmailCodeSendResponse, IdentifyResponse} from '@fluxer/schema/src/domains/auth/AuthSchemas';
+import type {GuildEntryResult} from '@fluxer/schema/src/domains/user/AccountSchemas';
+
+type EntryTokenResponse = AuthTokenResponse & {device_proof?: string; entry?: GuildEntryResult | null};
+
+export type AccountEntryResult =
+ | {type: 'success'; payload: LoginSuccessPayload; entry: GuildEntryResult | null}
+ | {type: 'mfa'; challenge: MfaChallenge}
+ | {type: 'pending_approval'};
+
+function localeHeaders(): Record<string, string> {
+ return {'Accept-Language': getCurrentOrDetectedLocale()};
+}
+
+function deviceProofForEmail(email: string): string | undefined {
+ const normalized = email.trim().toLowerCase();
+ for (const account of switcherAccounts()) {
+ if (account.userData?.email?.toLowerCase() === normalized) {
+ return readDeviceProof(account.userId) ?? undefined;
+ }
+ }
+ return undefined;
+}
+
+function toEntryResult(
+ response: EntryTokenResponse | MfaLoginResponse | RegistrationPendingApprovalResponse,
+): AccountEntryResult {
+ if ('mfa' in response && response.mfa === true) {
+ return {
+ type: 'mfa',
+ challenge: {
+ ticket: response.ticket,
+ totp: response.totp,
+ webauthn: response.webauthn,
+ backupCodes: response.backup_codes ?? false,
+ },
+ };
+ }
+ if (isRegistrationPendingApprovalResponse(response as RegistrationPendingApprovalResponse)) {
+ return {type: 'pending_approval'};
+ }
+ const tokenResponse = response as EntryTokenResponse;
+ storeDeviceProof(tokenResponse.user_id, tokenResponse.device_proof);
+ return {type: 'success', payload: toLoginSuccessPayload(tokenResponse), entry: tokenResponse.entry ?? null};
+}
+
+export async function identify(email: string, snapshot: RuntimeConfigSnapshot): Promise<IdentifyResponse> {
+ const deviceProof = deviceProofForEmail(email);
+ const response = await instanceRequest<IdentifyResponse>({
+ method: 'POST',
+ path: Endpoints.AUTH_IDENTIFY,
+ target: instanceTargetFromSnapshot(snapshot),
+ body: deviceProof === undefined ? {email} : {email, device_proof: deviceProof},
+ headers: localeHeaders(),
+ });
+ return response.body;
+}
+
+export async function sendEmailCode(
+ ticket: string,
+ registrationUrlCode: string | null,
+ snapshot: RuntimeConfigSnapshot,
+): Promise<EmailCodeSendResponse> {
+ const response = await instanceRequest<EmailCodeSendResponse>({
+ method: 'POST',
+ path: Endpoints.AUTH_EMAIL_CODE_SEND,
+ target: instanceTargetFromSnapshot(snapshot),
+ body: registrationUrlCode === null ? {ticket} : {ticket, registration_url_code: registrationUrlCode},
+ headers: localeHeaders(),
+ });
+ return response.body;
+}
+
+interface VerifyEmailCodeRequest {
+ readonly ticket: string;
+ readonly code: string;
+ readonly consent: boolean;
+ readonly inviteCode: string | null;
+ readonly registrationUrlCode: string | null;
+ readonly snapshot: RuntimeConfigSnapshot;
+}
+
+export async function verifyEmailCode({
+ ticket,
+ code,
+ consent,
+ inviteCode,
+ registrationUrlCode,
+ snapshot,
+}: VerifyEmailCodeRequest): Promise<AccountEntryResult> {
+ const response = await instanceRequest<EntryTokenResponse | MfaLoginResponse | RegistrationPendingApprovalResponse>({
+ method: 'POST',
+ path: Endpoints.AUTH_EMAIL_CODE_VERIFY,
+ target: instanceTargetFromSnapshot(snapshot),
+ body: {
+ ticket,
+ code,
+ consent,
+ ...(inviteCode === null ? {} : {invite_code: inviteCode}),
+ ...(registrationUrlCode === null ? {} : {registration_url_code: registrationUrlCode}),
+ },
+ headers: localeHeaders(),
+ });
+ return toEntryResult(response.body);
+}
+
+interface InstantAccountRequest {
+ readonly globalName: string;
+ readonly consent: boolean;
+ readonly inviteCode: string | null;
+ readonly registrationUrlCode: string | null;
+ readonly snapshot: RuntimeConfigSnapshot;
+}
+
+export async function createInstantAccount({
+ globalName,
+ consent,
+ inviteCode,
+ registrationUrlCode,
+ snapshot,
+}: InstantAccountRequest): Promise<AccountEntryResult> {
+ const response = await instanceRequest<EntryTokenResponse | RegistrationPendingApprovalResponse>({
+ method: 'POST',
+ path: Endpoints.AUTH_REGISTER,
+ target: instanceTargetFromSnapshot(snapshot),
+ body: {
+ ...(globalName === '' ? {} : {global_name: globalName}),
+ consent,
+ ...(inviteCode === null ? {} : {invite_code: inviteCode}),
+ ...(registrationUrlCode === null ? {} : {registration_url_code: registrationUrlCode}),
+ },
+ headers: localeHeaders(),
+ });
+ return toEntryResult(response.body);
+}
+
+interface RedeemAccountHandoffRequest {
+ readonly handoffCode: string;
+ readonly nonce: string;
+ readonly consent: boolean;
+ readonly globalName: string;
+ readonly snapshot: RuntimeConfigSnapshot;
+}
+
+export async function redeemAccountHandoff({
+ handoffCode,
+ nonce,
+ consent,
+ globalName,
+ snapshot,
+}: RedeemAccountHandoffRequest): Promise<{payload: LoginSuccessPayload; entry: GuildEntryResult | null}> {
+ const response = await instanceRequest<EntryTokenResponse>({
+ method: 'POST',
+ path: Endpoints.AUTH_ACCOUNT_HANDOFF_REDEEM,
+ target: instanceTargetFromSnapshot(snapshot),
+ body: {
+ handoff_code: handoffCode,
+ nonce,
+ consent,
+ global_name: globalName,
+ },
+ headers: localeHeaders(),
+ auth: 'none',
+ });
+ storeDeviceProof(response.body.user_id, response.body.device_proof);
+ return {payload: toLoginSuccessPayload(response.body), entry: response.body.entry ?? null};
+}
diff --git a/fluxer_app/src/features/auth/state/AccountEntryStorage.ts b/fluxer_app/src/features/auth/state/AccountEntryStorage.ts
new file mode 100644
index 000000000..73d4a6c5e
--- /dev/null
+++ b/fluxer_app/src/features/auth/state/AccountEntryStorage.ts
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {getProtectedLocalStorage} from '@app/features/platform/state/ProtectedWebStorage';
+import {Logger} from '@app/features/platform/utils/AppLogger';
+import {MS_PER_DAY} from '@fluxer/date_utils/src/DateConstants';
+
+const logger = new Logger('AccountEntryStorage');
+
+const DEVICE_PROOF_KEY_PREFIX = 'fluxer.device_proof.';
+const AGE_BLOCK_KEY = 'fluxer.age_block_until';
+
+function readItem(key: string): string | null {
+ try {
+ return getProtectedLocalStorage()?.getItem(key) ?? null;
+ } catch (error) {
+ logger.warn('Failed to read account entry storage', error);
+ return null;
+ }
+}
+
+function writeItem(key: string, value: string): void {
+ try {
+ getProtectedLocalStorage()?.setItem(key, value);
+ } catch (error) {
+ logger.warn('Failed to write account entry storage', error);
+ }
+}
+
+export function readDeviceProof(userId: string): string | null {
+ return readItem(`${DEVICE_PROOF_KEY_PREFIX}${userId}`);
+}
+
+export function storeDeviceProof(userId: string, deviceProof: string | undefined): void {
+ if (deviceProof === undefined || deviceProof === '') {
+ return;
+ }
+ writeItem(`${DEVICE_PROOF_KEY_PREFIX}${userId}`, deviceProof);
+}
+
+export function isAgeBlocked(): boolean {
+ const now = Date.now();
+ const until = Number(readItem(AGE_BLOCK_KEY));
+ return Number.isFinite(until) && until > now;
+}
+
+let ageBlockedAccountRemoved = false;
+
+export function markAgeBlocked(options: {accountRemoved?: boolean} = {}): void {
+ const now = Date.now();
+ writeItem(AGE_BLOCK_KEY, String(now + MS_PER_DAY));
+ ageBlockedAccountRemoved = options.accountRemoved === true;
+}
+
+export function takeAgeBlockedAccountRemoved(): boolean {
+ const removed = ageBlockedAccountRemoved;
+ ageBlockedAccountRemoved = false;
+ return removed;
+}