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)
This commit is contained in:
2026-04-20 19:07:31 +02:00
parent de431386ea
commit eb8f9857ff
22 changed files with 895 additions and 157 deletions
+50
View File
@@ -152,6 +152,56 @@ export async function saveDevicePrivateKey(
await secretStore.setSecret(privateKeySecretName(userId, deviceId), privateKey);
}
// Restores a device record from a backup by re-seeding the local private key
// store for an EXISTING server-side device row. Does NOT insert a new row —
// the original row is kept intact so conversation-key bundles stay valid.
// Throws when the server-side device was removed (the backup is then unusable;
// user must provision a fresh device and get conv-keys shared from another
// live device).
export async function restoreDeviceFromServerRecord(params: {
client: AppSupabaseClient;
secretStore: SecretStore;
userId: string;
deviceId: string;
privateKey: Uint8Array;
}): Promise<DeviceRecord> {
const { data: session } = await params.client.auth.getUser();
if (!session.user) throw new Error('not authenticated');
if (session.user.id !== params.userId) {
throw new Error(
'Backup is for a different account — sign in as the owner before restoring.',
);
}
const { data: row, error } = await params.client
.from('devices')
.select('id, name, platform, public_key, last_seen_at')
.eq('id', params.deviceId)
.eq('user_id', params.userId)
.maybeSingle();
if (error) throw error;
if (!row) {
throw new Error(
'Device record not found on server — it was removed. Backup is no longer valid; register a new device instead.',
);
}
await saveDevicePrivateKey(
params.secretStore,
params.userId,
params.deviceId,
params.privateKey,
);
return {
id: row.id,
name: row.name,
platform: row.platform,
publicKey: pgHexToBytes(row.public_key),
lastSeenAt: row.last_seen_at,
};
}
// Lightweight helpers for platforms that want to cache their current device id
// in JSON storage (separate from the secret store, which only holds raw bytes).
export const DEVICE_ID_STORAGE_KEY_PREFIX = 'chatapp.device_id';
+5 -2
View File
@@ -3,7 +3,8 @@ import type { AppSupabaseClient } from '../supabase/client.js';
export interface SignupParams {
email: string;
// Login handle. Lowercased server-side; must match ^[a-z0-9_]{3,32}$ once lowercased.
// Login handle. Stored with original casing but uniqueness is case-insensitive
// (citext). Must match ^[A-Za-z0-9_]{3,32}$.
username: string;
// Optional human-readable name. Defaults to username server-side if omitted.
displayName?: string;
@@ -29,7 +30,9 @@ export async function signUpWithMagicLink(
shouldCreateUser: true,
data: {
invite_code: params.inviteCode,
username: params.username.toLowerCase(),
// Preserve case. `profiles.username` is citext so uniqueness + lookups
// stay case-insensitive regardless of stored casing.
username: params.username.trim(),
display_name: params.displayName ?? params.username,
...(params.locale ? { locale: params.locale } : {}),
},
+4 -2
View File
@@ -72,7 +72,8 @@ export async function getProfileByUsername(
const { data, error } = await client
.from('profiles')
.select(PROFILE_COLS)
.eq('username', username.toLowerCase())
// 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;
@@ -85,7 +86,8 @@ export async function isUsernameAvailable(
const { count, error } = await client
.from('profiles')
.select('user_id', { count: 'exact', head: true })
.eq('username', username.toLowerCase());
// citext compares CI — no manual normalization needed.
.eq('username', username.trim());
if (error) throw error;
return (count ?? 0) === 0;
}
+1 -1
View File
@@ -55,7 +55,7 @@ export async function searchProfiles(
query: string,
limit = 10,
): Promise<ProfileBrief[]> {
const trimmed = query.trim().toLowerCase();
const trimmed = query.trim();
if (trimmed.length < 2) return [];
const myId = await currentUserId(client);
@@ -30,8 +30,8 @@
"email_placeholder": "du@beispiel.de",
"username": "Benutzername",
"username_placeholder": "dennis",
"username_hint": "Damit meldest du dich an. Nur Kleinbuchstaben.",
"username_invalid": "Kleinbuchstaben az, Ziffern, Unterstrich · 332 Zeichen.",
"username_hint": "Damit meldest du dich an. Groß-/Kleinschreibung bleibt, ist aber nicht unterscheidbar (dennis = Dennis).",
"username_invalid": "Buchstaben, Ziffern oder Unterstrich · 332 Zeichen.",
"invite_code": "Einladungscode",
"invite_hint": "Pflichtfeld · Zugang nur auf Einladung."
},
@@ -3,7 +3,7 @@
"network": "Netzwerkfehler. Prüfe deine Verbindung.",
"ERR_NOT_AUTH": "Du bist nicht angemeldet.",
"ERR_INVITE_CODE_REQUIRED": "Einladungscode ist erforderlich.",
"ERR_USERNAME_INVALID": "Benutzername muss aus Kleinbuchstaben az, Ziffern oder Unterstrich bestehen (332 Zeichen).",
"ERR_USERNAME_INVALID": "Benutzername darf nur aus Buchstaben (AZ, az), Ziffern oder Unterstrich bestehen (332 Zeichen).",
"ERR_INVITES_DISABLED": "Registrierungen sind derzeit vom Admin deaktiviert.",
"ERR_INVITE_NOT_FOUND": "Einladungscode nicht gefunden.",
"ERR_INVITE_DISABLED": "Diese Einladung wurde deaktiviert.",
@@ -30,8 +30,8 @@
"email_placeholder": "you@example.com",
"username": "Username",
"username_placeholder": "dennis",
"username_hint": "You log in with this. Lowercase only.",
"username_invalid": "Lowercase az, digits, underscore · 332 chars.",
"username_hint": "You log in with this. Case is preserved but not unique (dennis = Dennis).",
"username_invalid": "Letters, digits, or underscore · 332 chars.",
"invite_code": "Invite code",
"invite_hint": "Required · invite-only access."
},
@@ -3,7 +3,7 @@
"network": "Network error. Check your connection.",
"ERR_NOT_AUTH": "You are not signed in.",
"ERR_INVITE_CODE_REQUIRED": "Invite code is required.",
"ERR_USERNAME_INVALID": "Username must be lowercase az, digits, underscore, 332 chars.",
"ERR_USERNAME_INVALID": "Username must be letters (AZ, az), digits, or underscore, 332 chars.",
"ERR_INVITES_DISABLED": "Signups are currently disabled by the admin.",
"ERR_INVITE_NOT_FOUND": "Invite code not found.",
"ERR_INVITE_DISABLED": "This invite has been disabled.",