Files
ChatApp/packages/shared/src/auth/profile.ts
T
byGalax eb8f9857ff feat: device backup/restore + quick wins + username casing
Backup / restore flow:
- deviceBackup.ts: v2 format wrapping userId + deviceId + privateKey in
  an encrypted JSON payload so restore can re-seed localStorage, vault,
  and reattach to the existing server-side device row without provisioning
  a new one (conv-key bundles stay valid, no "awaiting key" state)
- shared/auth: restoreDeviceFromServerRecord — verifies session.user.id
  matches the backup's userId, confirms the server device row still
  exists, then writes the private key into the local secret store
- BackupExportDialog — passphrase + confirm, generates portable string,
  copy + download .txt
- DeviceRestore — textarea + passphrase → seeds vault + writes
  deviceId cache, treats this install as the original device
- DevicePage now has tabs "Neu einrichten" / "Backup wiederherstellen"
- BackupPromptBanner — post-registration nudge, reads sessionStorage
  signal from fresh provisions and persists "never-ask-again" in
  localStorage so it stops nagging
- SettingsPage backup section: uses the new dialog; removes the
  dangerous in-place key import (restore now lives in the device flow)

Username casing:
- Migration 20260420000002 drops lower() from the handle_new_user trigger
  and widens the regex to [A-Za-z0-9_]. profiles.username is citext so
  uniqueness + lookups stay case-insensitive regardless of stored casing
- Shared auth: trim() only, no toLowerCase on signup/lookups/search.
  ilike handles CI anyway and citext makes client normalisation redundant
- AuthPage regex + input preserve case, FriendsPage search preserves case
- i18n (de+en): updated username_hint / username_invalid / ERR_USERNAME_INVALID
  to reflect the new rule

Quick wins:
- React Router v7 future flags (v7_startTransition + v7_relativeSplatPath)
  set on BrowserRouter — silences the upgrade warning
- appUpdates.checkForUpdate: swallow benign network/fetch/"could not
  fetch valid release JSON" cases silently instead of console spam
- osNotify: persist an "asked" marker in localStorage so the permission
  prompt only fires once per install (OS already persists the answer,
  but the plugin re-queries loudly otherwise)
2026-04-20 19:07:31 +02:00

134 lines
4.1 KiB
TypeScript

import type { SupportedLocale } from '../i18n/types.js';
import type { AppSupabaseClient } from '../supabase/client.js';
import type { Database, PresenceState } from '../supabase/types.js';
type ProfileUpdate = Database['public']['Tables']['profiles']['Update'];
export interface Profile {
userId: string;
username: string;
displayName: string;
avatarUrl: string | null;
statusMessage: string | null;
presenceState: PresenceState;
showReadReceipts: boolean;
allowDmsFromStrangers: boolean;
isAdmin: boolean;
locale: SupportedLocale;
}
type ProfileRow = {
user_id: string;
username: string;
display_name: string;
avatar_url: string | null;
status_message: string | null;
presence_state: PresenceState;
show_read_receipts: boolean;
allow_dms_from_strangers: boolean;
is_admin: boolean;
locale: string;
};
const PROFILE_COLS =
'user_id, username, display_name, avatar_url, status_message, presence_state, show_read_receipts, allow_dms_from_strangers, is_admin, locale';
function toSupportedLocale(raw: string): SupportedLocale {
return raw === 'de' ? 'de' : 'en';
}
function mapProfile(row: ProfileRow): Profile {
return {
userId: row.user_id,
username: row.username,
displayName: row.display_name,
avatarUrl: row.avatar_url,
statusMessage: row.status_message,
presenceState: row.presence_state,
showReadReceipts: row.show_read_receipts,
allowDmsFromStrangers: row.allow_dms_from_strangers,
isAdmin: row.is_admin,
locale: toSupportedLocale(row.locale),
};
}
export async function getOwnProfile(client: AppSupabaseClient): Promise<Profile | null> {
const { data: session } = await client.auth.getUser();
if (!session.user) return null;
const { data, error } = await client
.from('profiles')
.select(PROFILE_COLS)
.eq('user_id', session.user.id)
.maybeSingle();
if (error) throw error;
return data ? mapProfile(data as unknown as ProfileRow) : null;
}
export async function getProfileByUsername(
client: AppSupabaseClient,
username: string,
): Promise<Profile | null> {
const { data, error } = await client
.from('profiles')
.select(PROFILE_COLS)
// citext column compares CI server-side — send raw input, don't force case.
.eq('username', username.trim())
.maybeSingle();
if (error) throw error;
return data ? mapProfile(data as unknown as ProfileRow) : null;
}
export async function isUsernameAvailable(
client: AppSupabaseClient,
username: string,
): Promise<boolean> {
const { count, error } = await client
.from('profiles')
.select('user_id', { count: 'exact', head: true })
// citext compares CI — no manual normalization needed.
.eq('username', username.trim());
if (error) throw error;
return (count ?? 0) === 0;
}
export interface UpdateProfileParams {
displayName?: string;
avatarUrl?: string | null;
statusMessage?: string | null;
presenceState?: PresenceState;
showReadReceipts?: boolean;
allowDmsFromStrangers?: boolean;
locale?: SupportedLocale;
}
export async function updateOwnProfile(
client: AppSupabaseClient,
params: UpdateProfileParams,
): Promise<Profile> {
const { data: session } = await client.auth.getUser();
if (!session.user) throw new Error('not authenticated');
const patch: ProfileUpdate = {};
if (params.displayName !== undefined) patch.display_name = params.displayName;
if (params.avatarUrl !== undefined) patch.avatar_url = params.avatarUrl;
if (params.statusMessage !== undefined) patch.status_message = params.statusMessage;
if (params.presenceState !== undefined) patch.presence_state = params.presenceState;
if (params.showReadReceipts !== undefined) patch.show_read_receipts = params.showReadReceipts;
if (params.allowDmsFromStrangers !== undefined) {
patch.allow_dms_from_strangers = params.allowDmsFromStrangers;
}
if (params.locale !== undefined) {
(patch as ProfileUpdate & { locale?: string }).locale = params.locale;
}
const { data, error } = await client
.from('profiles')
.update(patch)
.eq('user_id', session.user.id)
.select(PROFILE_COLS)
.single();
if (error) throw error;
return mapProfile(data as unknown as ProfileRow);
}