Colota - Android GPS Location tracker
refactor(backup): verify the archive before offering restore (#857)
Max Dietrich993ab305db2b
diff --git a/apps/docs/docs/guides/backup-restore.md b/apps/docs/docs/guides/backup-restore.mdindex 525fc3cf..1848a165 100644--- a/apps/docs/docs/guides/backup-restore.md+++ b/apps/docs/docs/guides/backup-restore.md@@ -2,7 +2,7 @@sidebar_position: 3----# Backup & Restore+# Backup & restoreBundle your locations, settings and credentials into a single password-encrypted file you can store anywhere - cloud drive, USB stick, another device.@@ -12,20 +12,22 @@ Use this when you want a full archive of your data, when you're moving to a new| Included | Excluded || --- | --- |-| Location history (the full SQLite database) | mTLS client certificate (private key in OS keystore - re-import the `.p12` after restore) |+| Location history (the full SQLite database) | mTLS client certificate (the private key is generated inside the OS keystore and cannot be exported) || Settings (sync, GPS, server, appearance) | Offline map tiles (re-download after restore) || Geofences and tracking profiles | Cached map tiles || Manual trip merges and splits (see [Editing Trips](editing-trips.md)) | || Auth credentials (Basic, Bearer, custom headers) | || mTLS Trusted Server CA (public cert bytes) | |+The client certificate belongs to the device, not to the archive. A backup cannot carry it and a restore does not remove it, so the certificate on the device you restore onto is the one that stays in use. A device that has none will need one imported before an mTLS endpoint from the archive will connect.+The auth credentials Colota uses to reach your tracking endpoint (Basic Auth, Bearer token, custom headers) are stored as plaintext inside the encrypted container - they are protected by the backup password, not by the device's hardware-backed key. The leaked credentials let an attacker do whatever your server lets those credentials do. If you configured Colota with a credential limited to writing location data, that's all an attacker gets. If you used a credential tied to a user with broader privileges, or any token with more scope than posting locations requires, the attacker inherits that scope. Configure Colota with the minimum permission its endpoint actually needs. On restore the credentials are rewrapped under the destination device's key.## Creating a Backup-1. Go to **Settings → Backup & Restore**+1. Go to **Settings → Backup & restore**2. Enter a password (12 characters minimum) and confirm it-3. Wait for the strength meter to reach at least **OK**+3. Wait for the line under the field to read at least **OK**4. Tap **Create backup**5. Acknowledge the no-recovery warning6. Choose where to save the `.colota` file@@ -34,8 +36,10 @@ The app encrypts the file as it writes. You can leave the screen and the backup### Password Requirements-- **12 characters minimum** (hard limit)-- **~50 bits of entropy minimum** (soft strength meter)+Both are hard limits. The line under the password field is the same verdict the app checks against, so a password it calls **OK** or better is one **Create backup** will accept.++- **12 characters minimum**+- **50 bits of entropy minimum**- Sequences like `abcd` and `1234` cap the score, as do passwords with fewer than 4 distinct charactersA random 16-character password from a password manager, or a 4-5 word passphrase, both clear the bar comfortably. Common words and short tweaks of dictionary words do not.@@ -54,12 +58,15 @@ Replaces all current data Restoring overwrites every location, setting, geofence:::-1. Go to **Settings → Backup & Restore**-2. Tap **Choose backup file** and pick the `.colota` file-3. Enter the backup password when prompted-4. Confirm the replace warning-5. The app pauses tracking, swaps the database and restarts itself-6. Re-enable tracking from the Home screen when you're ready+1. Go to **Settings → Backup & restore**+2. Tap **Choose a backup file** and pick the `.colota` file+3. Type the backup password and tap **Open this file**+4. Check the date and app version the screen now reports+5. Tap **Replace all data** and confirm+6. The app pauses tracking, swaps the database and restarts itself+7. Re-enable tracking from the Home screen when you're ready++Opening the file is a read, not a commitment. It checks the password and reads what the archive holds without extracting anything, pausing recording or touching your data, so a wrong password costs you a retry. **Replace all data** does not appear until the file has been opened, so you never aim a destructive button at an archive nobody has verified.### What Gets Paused@@ -88,17 +95,25 @@ Each file is authenticated end-to-end with a key derived from your password. Wro## Failure Modes-| Error message | Cause |-| ------------------------------------------- | --------------------------------------------------------- |-| Incorrect password, or corrupted near start | Wrong password, or the first chunk has been tampered with |-| This file is not a Colota backup | Magic bytes don't match - file is something else |-| Made with a newer version of Colota | Schema is ahead of the installed app |-| Backup file is corrupted / incomplete | Mid-file tamper or truncation |-| Backup file is missing required data | Container is missing the database or manifest entry |-| Credentials could not be applied | Database restored, but credential write failed |+Every failure that happens before the swap ends with the same sentence, **Nothing on this device was changed**, because on every one of them it is true.++| Error message | Cause |+| --- | --- |+| That password did not open this file | Wrong password, or the first chunk has been tampered with |+| This is not a Colota backup | Magic bytes don't match, the file is something else |+| This backup was made by a newer version of Colota | Schema is ahead of the installed app |+| This file is damaged and cannot be trusted | Mid-file tamper, or the integrity check failed |+| This file is incomplete | Truncation, so the file was probably never finished being written |+| The file is intact but this version of Colota could not read its database | A migration of the archive's database failed. Not the same as a damaged file |+| This file is missing part of a backup | Container is missing the database or manifest entry |+| There is not enough free space to unpack this backup | The device ran out of room before the swap |+| Your server credentials could not be applied | Database restored, but the credential write failed. Enter them again on Connection |+| Something failed after the swap | The database is the backup's, but a later step did not finish. Check Connection and Tracking |++The last two are the only entries where your data **was** replaced. Both leave recording off, like a clean restore does.If a backup fails mid-encrypt, the app deletes the partial `.colota` file at the destination. If that cleanup fails (some cloud providers reject delete on freshly-created files), the error message tells you to delete it manually.## Storage Reference-A backup is roughly the size of your SQLite database after deflate compression (typically 30-60% of the raw DB size). Use the [Data Management](data-management.md) screen to see the current database size before backing up.+A backup is roughly the size of your SQLite database after deflate compression (typically 30-60% of the raw DB size). Use the [Data management](data-management.md) screen to see the current database size before backing up.diff --git a/apps/mobile/src/screens/BackupRestoreScreen.tsx b/apps/mobile/src/screens/BackupRestoreScreen.tsxindex 73d3721d..8da97124 100644--- a/apps/mobile/src/screens/BackupRestoreScreen.tsx+++ b/apps/mobile/src/screens/BackupRestoreScreen.tsx@@ -3,356 +3,388 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useEffect, useState } from "react"-import { Modal, ScrollView, View, Text, TextInput, Pressable, StyleSheet } from "react-native"-import { Eye, EyeOff } from "lucide-react-native"-import type { RootScreenProps } from "../types/navigation"+import React, { useCallback, useRef, useState } from "react"+import { ScrollView, StyleSheet, Text, View } from "react-native"+import { useFocusEffect } from "@react-navigation/native"+import { Archive, ArchiveX, Download, FileLock, Upload } from "lucide-react-native"+import {+ Button,+ Card,+ Container,+ Divider,+ FieldMessage,+ LoadingOverlay,+ SectionTitle,+ StateLine,+ TextField+} from "../components"import { useTheme } from "../hooks/useTheme"-import { Button, Card, Container, SectionTitle } from "../components"-import BackupService, {- MIN_BACKUP_PASSWORD_LENGTH,- MIN_BACKUP_PASSWORD_BITS,- type PasswordStrengthResult-} from "../services/BackupService"-import { showAlert, showConfirm, showChoice } from "../services/modalService"+import BackupService, { type BackupManifest, type PasswordStrengthResult } from "../services/BackupService"+import NativeLocationService from "../services/NativeLocationService"+import { showChoice, showConfirm } from "../services/modalService"import { logger } from "../utils/logger"-import { fonts } from "../styles/typography"-import { fontSizes } from "@colota/shared"-import type { ThemeColors } from "../types/global"+import {+ archiveLine,+ backupErrorMessage,+ backupExcludesLine,+ backupScopeLine,+ backupState,+ BACKUP_WRITTEN_LINE,+ NO_RECOVERY_LINE,+ OPEN_FILE_LINE,+ passwordLine,+ PASSWORD_HINT_LINE,+ PICKED_NOT_OPENED_CAPTION,+ restoreCaveat,+ restoreConfirm,+ restoreErrorMessage,+ RESTORE_IDLE_LINE,+ restoreOutcome,+ submitBlockedReason+} from "../utils/backupState"+import { fonts, fontSizes, lineHeights } from "../styles/typography"+import { space } from "../constants"+import type { ScreenProps } from "../types/global"-type Props = RootScreenProps<"Backup & Restore">+type Busy = "backup" | "open" | "restore" | null+type Picked = { uri: string; displayName: string }+type Message = { text: string; tone?: "warning" | "error" }-const SEGMENT_COUNT = 4+const EMPTY_STRENGTH: PasswordStrengthResult = { score: 0, label: "", bits: 0 }+const EMPTY_STATS = { total: 0, databaseSizeMB: 0 }-function strengthColor(score: number, colors: ThemeColors): string {- if (score <= 1) return colors.error- if (score === 2) return colors.warning- return colors.success-}+export function BackupRestoreScreen({}: ScreenProps) {+ const { colors } = useTheme()-function restoreErrorMessage(e: unknown): string {- const code = (e as { code?: string }).code- switch (code) {- case "E_BACKUP_WRONG_PASSWORD":- return "Incorrect password, or the backup file is corrupted near the start."- case "E_BACKUP_BAD_MAGIC":- return "This file is not a Colota backup."- case "E_BACKUP_UNSUPPORTED_SCHEMA":- return "This backup was made with a newer version of Colota. Update the app first."- case "E_BACKUP_UNSUPPORTED_VERSION":- case "E_BACKUP_UNSUPPORTED_KDF":- return "This backup was made with a different version of Colota."- case "E_BACKUP_INTEGRITY_FAIL":- return "The backup file is corrupted."- case "E_BACKUP_TRUNCATED":- return "The backup file is incomplete."- case "E_BACKUP_TAMPERED":- return "The backup file has been modified or is corrupted."- case "E_BACKUP_MISSING_ENTRY":- return "The backup file is missing required data."- case "E_BACKUP_SECRETS_PARTIAL":- return "Your data was restored, but stored credentials could not be applied. Re-enter them in Connection settings."- case "E_BUSY":- return "Another backup or restore is already in progress."- default:- return e instanceof Error ? e.message : "Unknown error"- }-}+ const [stats, setStats] = useState(EMPTY_STATS)+ const [lastBackupAt, setLastBackupAt] = useState<number | null>(null)+ const [hasClientCert, setHasClientCert] = useState(false)+ const [loaded, setLoaded] = useState(false)-type PasswordFieldProps = {- value: string- onChangeText: (v: string) => void- placeholder: string- editable: boolean- autoComplete: "password" | "new-password"- colors: ThemeColors-}+ const [password, setPassword] = useState("")+ const [confirm, setConfirm] = useState("")+ const [strength, setStrength] = useState<PasswordStrengthResult>(EMPTY_STRENGTH)+ const [strengthFailed, setStrengthFailed] = useState(false)+ const [backupMessage, setBackupMessage] = useState<Message | null>(null)-function PasswordField({ value, onChangeText, placeholder, editable, autoComplete, colors }: PasswordFieldProps) {- const [revealed, setRevealed] = useState(false)- const Icon = revealed ? EyeOff : Eye- return (- <View style={[styles.inputRow, { borderColor: colors.border, backgroundColor: colors.background }]}>- <TextInput- style={[styles.inputField, { color: colors.text }]}- value={value}- onChangeText={onChangeText}- placeholder={placeholder}- placeholderTextColor={colors.placeholder}- autoCapitalize="none"- autoCorrect={false}- secureTextEntry={!revealed}- autoComplete={autoComplete}- editable={editable}- />- <Pressable- onPressIn={() => setRevealed(true)}- onPressOut={() => setRevealed(false)}- hitSlop={8}- style={styles.eyeButton}- accessibilityLabel="Hold to show password"- >- <Icon size={20} color={colors.textSecondary} />- </Pressable>- </View>- )-}+ const [picked, setPicked] = useState<Picked | null>(null)+ const [restorePassword, setRestorePassword] = useState("")+ const [manifest, setManifest] = useState<BackupManifest | null>(null)+ const [restoreMessage, setRestoreMessage] = useState<Message | null>(null)+ const [busy, setBusy] = useState<Busy>(null)-function PasswordPromptModal({- visible,- filename,- busy,- onSubmit,- onCancel,- colors-}: {- visible: boolean- filename: string- busy: boolean- onSubmit: (password: string) => void- onCancel: () => void- colors: ThemeColors-}) {- const [pw, setPw] = useState("")+ // A ref, not the state, because two presses inside one render both read the same state value.+ const busyRef = useRef(false)- useEffect(() => {- if (!visible) {- setPw("")+ const read = useCallback(async () => {+ const [statsResult, lastResult, certResult] = await Promise.allSettled([+ NativeLocationService.getStats(),+ NativeLocationService.getSetting("last_backup_at"),+ NativeLocationService.getClientCertInfo()+ ])+ if (statsResult.status === "fulfilled") {+ setStats({ total: statsResult.value.total, databaseSizeMB: statsResult.value.databaseSizeMB })+ setLoaded(true)}- }, [visible])+ if (lastResult.status === "fulfilled") setLastBackupAt(Number(lastResult.value ?? 0) || null)+ if (certResult.status === "fulfilled") setHasClientCert(certResult.value !== null)+ }, [])- return (- <Modal- transparent- visible={visible}- animationType="fade"- statusBarTranslucent- onRequestClose={busy ? undefined : onCancel}- >- <View style={[styles.modalOverlay, { backgroundColor: colors.overlay }]}>- <View style={[styles.modalCard, { backgroundColor: colors.card, borderColor: colors.border }]}>- <Text style={[styles.modalTitle, { color: colors.text }]}>Enter password</Text>- <Text style={[styles.modalSubtitle, { color: colors.textSecondary }]} numberOfLines={1}>- For {filename}- </Text>- <PasswordField- value={pw}- onChangeText={setPw}- placeholder="Backup password"- editable={!busy}- autoComplete="password"- colors={colors}- />- <View style={styles.modalButtonsRow}>- <View style={styles.modalButton}>- <Button title="Cancel" onPress={onCancel} disabled={busy} variant="secondary" />- </View>- <View style={styles.modalButton}>- <Button- title={busy ? "Restoring..." : "Restore"}- onPress={() => pw && onSubmit(pw)}- disabled={!pw || busy}- loading={busy}- variant="danger"- />- </View>- </View>- </View>- </View>- </Modal>+ useFocusEffect(+ useCallback(() => {+ read()+ }, [read]))-}-export function BackupRestoreScreen({}: Props) {- const { colors } = useTheme()-- const [backupPassword, setBackupPassword] = useState("")- const [confirmPassword, setConfirmPassword] = useState("")- const [busy, setBusy] = useState<"backup" | "restore" | null>(null)- const [pendingRestore, setPendingRestore] = useState<{ uri: string; filename: string } | null>(null)-- const [strength, setStrength] = useState<PasswordStrengthResult>({ score: 0, label: "", bits: 0 })- useEffect(() => {- let cancelled = false- BackupService.passwordStrength(backupPassword)- .then((result) => {- if (!cancelled) setStrength(result)- })- .catch((err) => {- if (!cancelled) logger.warn("[BackupRestoreScreen] passwordStrength failed", err)- })- return () => {- cancelled = true+ const scoreDraft = useCallback(async (next: string) => {+ setPassword(next)+ try {+ setStrength(await BackupService.passwordStrength(next))+ setStrengthFailed(false)+ } catch (err) {+ logger.warn("[BackupRestoreScreen] passwordStrength failed", err)+ setStrengthFailed(true)}- }, [backupPassword])- const passwordAcceptable = strength.bits >= MIN_BACKUP_PASSWORD_BITS- const passwordsMatch = backupPassword === confirmPassword- const showMismatch = confirmPassword.length > 0 && !passwordsMatch- const canSubmitBackup = passwordAcceptable && passwordsMatch && backupPassword.length > 0+ }, [])++ const blocked = submitBlockedReason(password, confirm, strength)- const onCreateBackup = async () => {- if (!canSubmitBackup) {- showAlert("Password not ready", "Both passwords must match. Use a longer or more random password.", "warning")+ const onCreateBackup = useCallback(async () => {+ if (busyRef.current || blocked) return+ if (+ !(await showConfirm({+ title: "You cannot reset this password",+ message: `${NO_RECOVERY_LINE} Store it somewhere you can reach without this phone.`,+ confirmText: "I have stored it",+ destructive: false+ }))+ ) {return}- const acknowledged = await showConfirm({- title: "No password recovery",- message: "If you forget this password, the backup cannot be opened. Store it somewhere safe before continuing.",- confirmText: "I understand",- cancelText: "Cancel",- destructive: true- })- if (!acknowledged) return-const uri = await BackupService.pickBackupDestination()if (!uri) return+ busyRef.current = truesetBusy("backup")+ setBackupMessage(null)try {- await BackupService.createBackup(uri, backupPassword)- setBackupPassword("")- setConfirmPassword("")- showAlert("Backup created", "Your encrypted backup has been written.", "success")- } catch (e: unknown) {+ await BackupService.createBackup(uri, password)+ const now = Date.now()+ await NativeLocationService.saveSetting("last_backup_at", String(now)).catch(() => {})+ setLastBackupAt(now)+ setPassword("")+ setConfirm("")+ setStrength(EMPTY_STRENGTH)+ setBackupMessage({ text: BACKUP_WRITTEN_LINE })+ } catch (e) {logger.error("[BackupRestoreScreen] backup failed", e)- const message = e instanceof Error ? e.message : "Unknown error"- showAlert("Backup failed", message, "error")+ const err = e as { code?: string; message?: string }+ setBackupMessage({ text: backupErrorMessage(err.code, err.message), tone: "error" })} finally {+ busyRef.current = falsesetBusy(null)}- }+ }, [blocked, password])- const onChooseBackupFile = async () => {+ const onChooseFile = useCallback(async () => {+ if (busyRef.current) returnconst source = await BackupService.pickBackupSource()if (!source) return- setPendingRestore({- uri: source.uri,- filename: source.displayName ?? "the selected backup"- })- }-- const onRestorePasswordCancel = () => {- if (busy === "restore") return- setPendingRestore(null)- }+ setPicked({ uri: source.uri, displayName: source.displayName ?? "the file you chose" })+ setManifest(null)+ setRestorePassword("")+ setRestoreMessage(null)+ }, [])- const onRestorePasswordSubmit = async (password: string) => {- if (!pendingRestore) return- const { uri } = pendingRestore-- const acknowledged = await showConfirm({- title: "Replace all data?",- message: "Restoring will overwrite your current locations, settings and credentials. This cannot be undone.",- confirmText: "Replace",- cancelText: "Cancel",- destructive: true- })- if (!acknowledged) return+ const onOpenFile = useCallback(async () => {+ if (busyRef.current || !picked) return+ busyRef.current = true+ setBusy("open")+ setRestoreMessage(null)+ try {+ setManifest(await BackupService.describeBackup(picked.uri, restorePassword))+ } catch (e) {+ logger.error("[BackupRestoreScreen] describeBackup failed", e)+ const err = e as { code?: string; message?: string }+ setRestoreMessage({ text: restoreErrorMessage(err.code, err.message), tone: "error" })+ } finally {+ busyRef.current = false+ setBusy(null)+ }+ }, [picked, restorePassword])+ const onRestore = useCallback(async () => {+ if (busyRef.current || !picked || !manifest) return+ busyRef.current = truesetBusy("restore")+ let outcometry {- await BackupService.restoreBackup(uri, password)- setPendingRestore(null)- // Block on dismissal; applyRestore reloads the bridge and would wipe an unawaited alert.- await showChoice({- title: "Restore complete",- message: "Your data has been restored. Tracking has been paused; re-enable it from the home screen.",- variant: "success",- buttons: [{ text: "Restart app", style: "primary" }]- })- await BackupService.applyRestore()- } catch (e: unknown) {+ const fresh = await NativeLocationService.getStats()+ if (!(await showConfirm({ ...restoreConfirm(fresh.total, manifest), destructive: true }))) return+ await BackupService.restoreBackup(picked.uri, restorePassword)+ outcome = restoreOutcome(undefined)+ } catch (e) {logger.error("[BackupRestoreScreen] restore failed", e)- showAlert("Restore failed", restoreErrorMessage(e), "error")- setPendingRestore(null)+ const err = e as { code?: string; message?: string }+ outcome = restoreOutcome(err.code, err.message)} finally {+ busyRef.current = falsesetBusy(null)}- }- const meterColor = strengthColor(strength.score, colors)+ if (!outcome) return+ if (outcome.kind === "failed") {+ setRestoreMessage({ text: outcome.message, tone: "error" })+ return+ }+ // Blocking: applyRestore reloads the bridge and would tear down an unawaited dialog.+ await showChoice({+ title: outcome.title,+ message: outcome.message,+ variant: outcome.variant === "warning" ? "warning" : "success",+ buttons: [{ text: "Restart app", style: "primary" }]+ })+ // The row lives in the settings table, so it arrived from inside the archive and is one backup stale.+ const madeAt = Date.parse(manifest.createdAt)+ if (Number.isFinite(madeAt)) {+ await NativeLocationService.saveSetting("last_backup_at", String(madeAt)).catch(() => {})+ }+ await BackupService.applyRestore()+ }, [picked, manifest, restorePassword])++ const opening = backupState(lastBackupAt, stats)+ const caveat = manifest ? restoreCaveat(hasClientCert) : null+ const excludes = backupExcludesLine(hasClientCert)+ const pwLine = passwordLine(strength, strengthFailed)return (<Container>- <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>- <View style={styles.section}>- <SectionTitle>Encrypted Backup</SectionTitle>- <Card>- <Text style={[styles.intro, { color: colors.textSecondary }]}>- Bundle your locations, settings and credentials into a single encrypted file you can store anywhere.- </Text>+ <ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">+ <Text style={[styles.intro, { color: colors.textSecondary }]}>+ One encrypted file holding everything this device has recorded and everything it is set up to do.+ </Text>- <Text style={[styles.fieldLabel, { color: colors.text }]}>Password</Text>- <PasswordField- value={backupPassword}- onChangeText={setBackupPassword}- placeholder={`At least ${MIN_BACKUP_PASSWORD_LENGTH} characters`}- editable={busy === null}- autoComplete="new-password"- colors={colors}- />- {backupPassword.length > 0 && (- <View style={styles.strengthRow}>- <View style={styles.strengthBar}>- {Array.from({ length: SEGMENT_COUNT }).map((_, i) => (- <View- key={i}- style={[- styles.strengthSegment,- {- backgroundColor: i < strength.score ? meterColor : colors.borderLight- }- ]}- />- ))}- </View>- <Text style={[styles.strengthLabel, { color: meterColor }]}>{strength.label}</Text>- </View>- )}-- <Text style={[styles.fieldLabel, { color: colors.text }]}>Confirm password</Text>- <PasswordField- value={confirmPassword}- onChangeText={setConfirmPassword}- placeholder="Re-enter the same password"- editable={busy === null}- autoComplete="new-password"- colors={colors}- />- {showMismatch && <Text style={[styles.errorText, { color: colors.error }]}>Passwords do not match.</Text>}-- <Text style={[styles.hint, { color: colors.textSecondary }]}>- A random password from a password manager or a long passphrase is safest. Common words and phrases are- easy to crack. There is no recovery if forgotten.- </Text>- <Button- title={busy === "backup" ? "Creating backup..." : "Create backup"}- onPress={onCreateBackup}- disabled={busy !== null || !canSubmitBackup}- loading={busy === "backup"}+ {loaded && (+ <Card rows style={styles.section}>+ <StateLine+ icon={opening.tone === "ok" ? Archive : ArchiveX}+ iconColor={+ opening.tone === "ok" ? colors.primary : opening.tone === "none" ? colors.warning : colors.textSecondary+ }+ label={opening.label}+ caption={opening.caption}+ testID="backup-state"/></Card>- </View>+ )}<View style={styles.section}>- <SectionTitle>Restore from Backup</SectionTitle>+ <SectionTitle>Make a backup</SectionTitle><Card>- <Text style={[styles.intro, { color: colors.textSecondary }]}>- Replace all current data with a previous .colota backup file. You'll be asked for the backup password- after choosing the file.- </Text>- <Button title="Choose backup file" onPress={onChooseBackupFile} disabled={busy !== null} variant="danger" />+ <View style={styles.fields}>+ <View>+ <TextField+ label="Password"+ secure+ testID="backup-password"+ value={password}+ onChangeText={scoreDraft}+ autoCapitalize="none"+ autoCorrect={false}+ disabled={busy !== null}+ />+ <FieldMessage variant={password.length > 0 ? pwLine.variant : "info"}>+ {password.length > 0 ? pwLine.text : PASSWORD_HINT_LINE}+ </FieldMessage>+ </View>+ <View>+ <TextField+ label="Confirm password"+ secure+ testID="backup-password-confirm"+ value={confirm}+ onChangeText={setConfirm}+ autoCapitalize="none"+ autoCorrect={false}+ error={confirm.length > 0 && confirm !== password ? "The two passwords do not match." : undefined}+ disabled={busy !== null}+ />+ {!(confirm.length > 0 && confirm !== password) && <FieldMessage>{NO_RECOVERY_LINE}</FieldMessage>}+ </View>+ </View></Card>+ <Button+ variant="primary"+ icon={Upload}+ title="Create backup"+ testID="create-backup-btn"+ loading={busy === "backup"}+ disabled={busy !== null || blocked !== null}+ onPress={onCreateBackup}+ />+ <FieldMessage variant={backupMessage?.tone === "error" ? "error" : "info"}>+ {backupMessage?.text ?? blocked ?? backupScopeLine(stats.total)}+ </FieldMessage>+ {!backupMessage && !blocked && excludes ? <FieldMessage>{excludes}</FieldMessage> : null}+ </View>++ <View style={styles.section}>+ <SectionTitle>Restore from a backup</SectionTitle>++ {!picked && (+ <View>+ <Button+ variant="secondary"+ icon={Download}+ title="Choose a backup file"+ testID="choose-backup-btn"+ disabled={busy !== null}+ onPress={onChooseFile}+ />+ <FieldMessage>{RESTORE_IDLE_LINE}</FieldMessage>+ </View>+ )}++ {picked && !manifest && (+ <>+ <Card>+ <StateLine+ icon={FileLock}+ iconColor={colors.textSecondary}+ label={picked.displayName}+ caption={PICKED_NOT_OPENED_CAPTION}+ testID="picked-file"+ />+ <Divider tight />+ <View style={styles.pickedField}>+ <TextField+ label="Backup password"+ secure+ testID="restore-password"+ value={restorePassword}+ onChangeText={setRestorePassword}+ autoCapitalize="none"+ autoCorrect={false}+ error={restoreMessage?.tone === "error" ? restoreMessage.text : undefined}+ disabled={busy !== null}+ />+ </View>+ </Card>+ <Button+ variant="secondary"+ title="Open this file"+ testID="open-backup-btn"+ loading={busy === "open"}+ disabled={busy !== null || restorePassword.length === 0}+ onPress={onOpenFile}+ />+ <Button+ variant="ghost"+ title="Choose a different file"+ testID="repick-backup-btn"+ onPress={onChooseFile}+ />+ <FieldMessage>{OPEN_FILE_LINE}</FieldMessage>+ </>+ )}++ {picked && manifest && (+ <>+ <Card rows>+ <StateLine+ icon={Archive}+ iconColor={colors.primary}+ label={archiveLine(manifest).label}+ caption={archiveLine(manifest).caption}+ testID="archive-state"+ />+ </Card>+ {caveat && <FieldMessage variant="warning">{caveat}</FieldMessage>}+ <Button+ variant="danger"+ title="Replace all data"+ testID="restore-btn"+ loading={busy === "restore"}+ disabled={busy !== null}+ onPress={onRestore}+ />+ <Button+ variant="ghost"+ title="Choose a different file"+ testID="repick-backup-btn"+ onPress={onChooseFile}+ />+ {restoreMessage?.tone === "error" && <FieldMessage variant="error">{restoreMessage.text}</FieldMessage>}+ </>+ )}</View></ScrollView>- <PasswordPromptModal- visible={pendingRestore !== null}- filename={pendingRestore?.filename ?? ""}- busy={busy === "restore"}- onSubmit={onRestorePasswordSubmit}- onCancel={onRestorePasswordCancel}- colors={colors}++ <LoadingOverlay+ visible={busy === "backup" || busy === "open" || busy === "restore"}+ title={busy === "backup" ? "Writing the backup" : busy === "open" ? "Opening the backup" : "Restoring"}+ message={busy === "restore" ? "Keep Colota open until this finishes." : ""}/></Container>)@@ -360,98 +392,23 @@ export function BackupRestoreScreen({}: Props) {const styles = StyleSheet.create({scrollContent: {- paddingHorizontal: 16,- paddingBottom: 40- },- section: {- marginTop: 24+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl},intro: {- marginBottom: 12,- fontSize: 14,- lineHeight: 20- },- fieldLabel: {- fontSize: 14,- fontWeight: "500",- marginBottom: 8- },- inputRow: {- flexDirection: "row",- alignItems: "center",- borderWidth: 1,- borderRadius: 8,- marginBottom: 8- },- inputField: {- flex: 1,- paddingHorizontal: 12,- paddingVertical: 12,- fontSize: 16- },- eyeButton: {- paddingHorizontal: 12,- paddingVertical: 12- },- strengthRow: {- flexDirection: "row",- alignItems: "center",- marginBottom: 12,- gap: 8- },- strengthBar: {- flex: 1,- flexDirection: "row",- gap: 4- },- strengthSegment: {- flex: 1,- height: 4,- borderRadius: 2- },- strengthLabel: {- fontSize: 12,- fontWeight: "600",- minWidth: 60,- textAlign: "right"- },- errorText: {- fontSize: 12,- marginTop: -4,- marginBottom: 8- },- hint: {- fontSize: 12,- lineHeight: 18,- marginTop: 8,- marginBottom: 16- },- modalOverlay: {- flex: 1,- justifyContent: "center",- paddingHorizontal: 16- },- modalCard: {- padding: 16,- borderRadius: 12,- borderWidth: 1- },- modalTitle: {- fontSize: fontSizes.label,- ...fonts.semiBold,- marginBottom: 4- },- modalSubtitle: {- fontSize: fontSizes.description,+ fontSize: fontSizes.body,...fonts.regular,- marginBottom: 16+ lineHeight: lineHeights.body,+ marginBottom: space.lg+ },+ section: {+ marginBottom: space.xl},- modalButtonsRow: {- flexDirection: "row",- gap: 12,- marginTop: 4+ fields: {+ gap: space.lg},- modalButton: {- flex: 1+ pickedField: {+ paddingTop: space.lg}})diff --git a/apps/mobile/src/screens/__tests__/BackupRestoreScreen.test.tsx b/apps/mobile/src/screens/__tests__/BackupRestoreScreen.test.tsxnew file mode 100644index 00000000..f5d8da3c--- /dev/null+++ b/apps/mobile/src/screens/__tests__/BackupRestoreScreen.test.tsx@@ -0,0 +1,380 @@+import React from "react"+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"++jest.mock("@react-navigation/native", () => ({+ useFocusEffect: (cb: () => (() => void) | void) => {+ const R = require("react")+ R.useEffect(() => {+ const cleanup = cb()+ return typeof cleanup === "function" ? cleanup : undefined+ }, [cb])+ }+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++const mockGetStats = jest.fn()+const mockGetSetting = jest.fn()+const mockSaveSetting = jest.fn()+const mockGetClientCertInfo = jest.fn()++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getStats: (...a: unknown[]) => mockGetStats(...a),+ getSetting: (...a: unknown[]) => mockGetSetting(...a),+ saveSetting: (...a: unknown[]) => mockSaveSetting(...a),+ getClientCertInfo: (...a: unknown[]) => mockGetClientCertInfo(...a)+ }+}))++const mockPasswordStrength = jest.fn()+const mockPickDestination = jest.fn()+const mockPickSource = jest.fn()+const mockCreateBackup = jest.fn()+const mockDescribeBackup = jest.fn()+const mockRestoreBackup = jest.fn()+const mockApplyRestore = jest.fn()++// Every real method is a static opening with ensureModule(), so a bare reference throws.+jest.mock("../../services/BackupService", () => {+ const service: Record<string, unknown> = {}+ const onReceiver = (impl: (...a: unknown[]) => unknown) =>+ function (this: unknown, ...a: unknown[]) {+ if (this !== service) throw new TypeError("undefined is not a function")+ return impl(...a)+ }+ Object.assign(service, {+ passwordStrength: onReceiver((...a) => mockPasswordStrength(...a)),+ pickBackupDestination: onReceiver((...a) => mockPickDestination(...a)),+ pickBackupSource: onReceiver((...a) => mockPickSource(...a)),+ createBackup: onReceiver((...a) => mockCreateBackup(...a)),+ describeBackup: onReceiver((...a) => mockDescribeBackup(...a)),+ restoreBackup: onReceiver((...a) => mockRestoreBackup(...a)),+ applyRestore: onReceiver((...a) => mockApplyRestore(...a))+ })+ return { __esModule: true, default: service }+})++const mockShowConfirm = jest.fn()+const mockShowChoice = jest.fn()+jest.mock("../../services/modalService", () => ({+ showConfirm: (...a: unknown[]) => mockShowConfirm(...a),+ showChoice: (...a: unknown[]) => mockShowChoice(...a)+}))++jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn() } }))++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text, Pressable, TextInput } = require("react-native")+ return {+ Container: ({ children }: any) => R.createElement(View, null, children),+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),+ Card: ({ children }: any) => R.createElement(View, null, children),+ Divider: () => R.createElement(View, null),+ StateLine: ({ label, caption, testID }: any) =>+ R.createElement(View, { testID }, R.createElement(Text, null, label), R.createElement(Text, null, caption)),+ FieldMessage: ({ children, variant }: any) =>+ R.createElement(Text, { accessibilityValue: { text: variant ?? "info" } }, children),+ TextField: ({ label, value, onChangeText, testID, error, disabled }: any) =>+ R.createElement(+ View,+ null,+ R.createElement(Text, null, label),+ R.createElement(TextInput, { testID, value, onChangeText, editable: !disabled }),+ error ? R.createElement(Text, null, error) : null+ ),+ Button: ({ title, onPress, disabled, testID, loading, variant }: any) =>+ R.createElement(+ Pressable,+ {+ testID,+ onPress,+ disabled,+ accessibilityState: { disabled: !!disabled, busy: !!loading },+ accessibilityValue: { text: variant ?? "primary" }+ },+ R.createElement(Text, null, title)+ ),+ LoadingOverlay: ({ visible, title }: any) => (visible ? R.createElement(Text, null, title) : null)+ }+})++import { BackupRestoreScreen } from "../BackupRestoreScreen"++const MADE_AT = "2026-09-03T09:15:00Z"+const manifest = { createdAt: MADE_AT, appVersion: "1.16.0", appBuild: 48, schemaDb: 7 }+const strong = { score: 3, label: "Strong", bits: 62 }++const mockNavigation = { navigate: jest.fn(), setOptions: jest.fn(), goBack: jest.fn() }+const renderScreen = () => render(<BackupRestoreScreen navigation={mockNavigation as any} />)++const typeGoodPassword = (api: ReturnType<typeof renderScreen>) => {+ fireEvent.changeText(api.getByTestId("backup-password"), "correct horse battery staple")+ fireEvent.changeText(api.getByTestId("backup-password-confirm"), "correct horse battery staple")+}++const openArchive = async (api: ReturnType<typeof renderScreen>) => {+ fireEvent.press(api.getByTestId("choose-backup-btn"))+ await waitFor(() => expect(api.getByTestId("picked-file")).toBeTruthy())+ fireEvent.changeText(api.getByTestId("restore-password"), "the password")+ fireEvent.press(api.getByTestId("open-backup-btn"))+ await waitFor(() => expect(api.getByTestId("archive-state")).toBeTruthy())+}++beforeEach(() => {+ jest.clearAllMocks()+ mockGetStats.mockResolvedValue({ total: 12481, databaseSizeMB: 8.42 })+ mockGetSetting.mockResolvedValue(String(Date.parse(MADE_AT)))+ mockSaveSetting.mockResolvedValue(undefined)+ mockGetClientCertInfo.mockResolvedValue(null)+ mockPasswordStrength.mockResolvedValue(strong)+ mockPickDestination.mockResolvedValue("content://dest")+ mockPickSource.mockResolvedValue({ uri: "content://src", displayName: "colota_backup.colota" })+ mockCreateBackup.mockResolvedValue(undefined)+ mockDescribeBackup.mockResolvedValue(manifest)+ mockRestoreBackup.mockResolvedValue(undefined)+ mockApplyRestore.mockResolvedValue(undefined)+ mockShowConfirm.mockResolvedValue(true)+ mockShowChoice.mockResolvedValue(0)+})++describe("BackupRestoreScreen", () => {+ describe("what it says before anything is touched", () => {+ it("opens with whether a backup exists and what one would hold", async () => {+ const api = renderScreen()++ expect(await api.findByText(/^You last backed up /)).toBeTruthy()+ expect(api.getByText("Database: 12,481 locations, 8.42 MB")).toBeTruthy()+ })++ it("says so when there has never been a backup", async () => {+ mockGetSetting.mockResolvedValue(null)+ const api = renderScreen()++ expect(await api.findByText("You have never backed up")).toBeTruthy()+ })++ // The restore half must not open on a red button.+ it("starts restore on a secondary button, not a destructive one", async () => {+ const api = renderScreen()+ await api.findByText(/^You last backed up /)++ expect(api.getByTestId("choose-backup-btn").props.accessibilityValue.text).toBe("secondary")+ expect(api.queryByTestId("restore-btn")).toBeNull()+ })+ })++ describe("making a backup", () => {+ it("says why Create backup is disabled instead of leaving it dead", async () => {+ const api = renderScreen()+ await api.findByText(/^You last backed up /)++ expect(api.getByText("Choose a password first.")).toBeTruthy()+ expect(api.getByTestId("create-backup-btn").props.accessibilityState.disabled).toBe(true)++ fireEvent.changeText(api.getByTestId("backup-password"), "correct horse battery staple")+ await waitFor(() => expect(api.getByText("Type the password a second time.")).toBeTruthy())+ })++ it("blocks a weak password on the score native returned", async () => {+ mockPasswordStrength.mockResolvedValue({ score: 1, label: "Weak", bits: 28 })+ const api = renderScreen()+ await api.findByText(/^You last backed up /)++ typeGoodPassword(api)++ await waitFor(() => expect(api.getByText("This password is too easy to guess.")).toBeTruthy())+ expect(api.getByTestId("create-backup-btn").props.accessibilityState.disabled).toBe(true)+ })++ // A failed strength read used to leave the button dead for the session with no explanation.+ it("says the check failed rather than calling the password weak", async () => {+ mockPasswordStrength.mockRejectedValue(new Error("bridge"))+ const api = renderScreen()+ await api.findByText(/^You last backed up /)++ fireEvent.changeText(api.getByTestId("backup-password"), "correct horse battery staple")++ expect(await api.findByText("Could not check this password. Try again.")).toBeTruthy()+ })++ it("acknowledges the missing recovery path, then writes and records when", async () => {+ const api = renderScreen()+ await api.findByText(/^You last backed up /)+ typeGoodPassword(api)+ await waitFor(() => expect(api.getByTestId("create-backup-btn").props.accessibilityState.disabled).toBe(false))++ fireEvent.press(api.getByTestId("create-backup-btn"))++ await waitFor(() =>+ expect(mockCreateBackup).toHaveBeenCalledWith("content://dest", "correct horse battery staple")+ )+ expect(mockShowConfirm).toHaveBeenCalledWith(expect.objectContaining({ title: "You cannot reset this password" }))+ expect(mockSaveSetting).toHaveBeenCalledWith("last_backup_at", expect.any(String))+ expect(await api.findByText(/^Backup written\./)).toBeTruthy()+ })++ it("writes nothing when the acknowledgement is dismissed", async () => {+ mockShowConfirm.mockResolvedValue(false)+ const api = renderScreen()+ await api.findByText(/^You last backed up /)+ typeGoodPassword(api)+ await waitFor(() => expect(api.getByTestId("create-backup-btn").props.accessibilityState.disabled).toBe(false))++ fireEvent.press(api.getByTestId("create-backup-btn"))++ await waitFor(() => expect(mockShowConfirm).toHaveBeenCalled())+ expect(mockPickDestination).not.toHaveBeenCalled()+ expect(mockCreateBackup).not.toHaveBeenCalled()+ })+ })++ describe("opening an archive before replacing anything", () => {+ /**+ * The whole point of the redesign. A wrong password used to be discovered inside restoreBackup,+ * after tracking was stopped and the auto-export alarm cancelled.+ */+ it("costs a retry and nothing else when the password is wrong", async () => {+ mockDescribeBackup.mockRejectedValue({ code: "E_BACKUP_WRONG_PASSWORD" })+ const api = renderScreen()+ await api.findByText(/^You last backed up /)++ fireEvent.press(api.getByTestId("choose-backup-btn"))+ await waitFor(() => expect(api.getByTestId("picked-file")).toBeTruthy())+ fireEvent.changeText(api.getByTestId("restore-password"), "wrong")+ fireEvent.press(api.getByTestId("open-backup-btn"))++ expect(await api.findByText(/That password did not open this file/)).toBeTruthy()+ expect(mockRestoreBackup).not.toHaveBeenCalled()+ // The file stays picked, so retrying is one press.+ expect(api.getByTestId("picked-file")).toBeTruthy()+ })++ it("offers no destructive button until the archive has been read", async () => {+ const api = renderScreen()+ await api.findByText(/^You last backed up /)++ fireEvent.press(api.getByTestId("choose-backup-btn"))+ await waitFor(() => expect(api.getByTestId("picked-file")).toBeTruthy())++ expect(api.queryByTestId("restore-btn")).toBeNull()+ expect(api.getByText("Not opened yet.")).toBeTruthy()+ })++ it("names the archive's date once it is open, and offers the replace", async () => {+ const api = renderScreen()+ await api.findByText(/^You last backed up /)++ await openArchive(api)++ expect(api.getByText(/^Backup from /)).toBeTruthy()+ expect(api.getByText("Colota 1.16.0 · opened with your password")).toBeTruthy()+ expect(api.getByTestId("restore-btn").props.accessibilityValue.text).toBe("danger")+ })++ // The restore never touches the keystore, so the caveat says the certificate stays, not that it goes.+ it("says once that the certificate is untouched by a restore", async () => {+ mockGetClientCertInfo.mockResolvedValue({ subject: "phone" })+ const api = renderScreen()+ await api.findByText(/^You last backed up /)++ await openArchive(api)++ expect(api.getByText(/client certificate stays as it is/)).toBeTruthy()+ })+ })++ describe("replacing everything", () => {+ it("names the count and the archive date, from a read taken at the press", async () => {+ const api = renderScreen()+ await api.findByText(/^You last backed up /)+ await openArchive(api)+ mockGetStats.mockResolvedValue({ total: 12500, databaseSizeMB: 8.5 })++ fireEvent.press(api.getByTestId("restore-btn"))++ await waitFor(() =>+ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({ title: "Replace all 12,500 locations?", destructive: true })+ )+ )+ expect(mockRestoreBackup).toHaveBeenCalledWith("content://src", "the password")+ })++ it("replaces nothing when the confirmation is dismissed", async () => {+ const api = renderScreen()+ await api.findByText(/^You last backed up /)+ await openArchive(api)+ mockShowConfirm.mockResolvedValue(false)++ fireEvent.press(api.getByTestId("restore-btn"))++ await waitFor(() => expect(mockShowConfirm).toHaveBeenCalled())+ expect(mockRestoreBackup).not.toHaveBeenCalled()+ expect(mockApplyRestore).not.toHaveBeenCalled()+ })++ /**+ * The decision that matters most. A post-swap failure reported as failed would skip the reload+ * and leave every screen reading a database that no longer exists.+ */+ it.each([+ ["succeeded", undefined],+ ["could not apply the credentials", "E_BACKUP_SECRETS_PARTIAL"],+ ["failed after the swap", "E_BACKUP_RESTORED_INCOMPLETE"]+ ])("reloads the app when the restore %s", async (_label, code) => {+ if (code) mockRestoreBackup.mockRejectedValue({ code })+ const api = renderScreen()+ await api.findByText(/^You last backed up /)+ await openArchive(api)++ fireEvent.press(api.getByTestId("restore-btn"))++ await waitFor(() => expect(mockApplyRestore).toHaveBeenCalled())+ expect(mockShowChoice).toHaveBeenCalledWith(expect.objectContaining({ title: "Your data is restored" }))+ })++ it("does not reload on a failure that never reached the swap", async () => {+ mockRestoreBackup.mockRejectedValue({ code: "E_BACKUP_NO_SPACE" })+ const api = renderScreen()+ await api.findByText(/^You last backed up /)+ await openArchive(api)++ fireEvent.press(api.getByTestId("restore-btn"))++ expect(await api.findByText(/not enough free space/i)).toBeTruthy()+ expect(mockApplyRestore).not.toHaveBeenCalled()+ expect(mockShowChoice).not.toHaveBeenCalled()+ })++ // The row travels inside the archive, so without this it rewinds to the backup before this one.+ it("rewrites the last-backup date from the archive it just restored", async () => {+ const api = renderScreen()+ await api.findByText(/^You last backed up /)+ await openArchive(api)++ fireEvent.press(api.getByTestId("restore-btn"))++ await waitFor(() => expect(mockSaveSetting).toHaveBeenCalledWith("last_backup_at", String(Date.parse(MADE_AT))))+ })++ it("cannot arm two confirmations from two presses inside one render", async () => {+ mockShowConfirm.mockReturnValue(new Promise(() => {}))+ const api = renderScreen()+ await api.findByText(/^You last backed up /)+ await openArchive(api)++ act(() => {+ fireEvent.press(api.getByTestId("restore-btn"))+ fireEvent.press(api.getByTestId("restore-btn"))+ })++ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())+ expect(mockShowConfirm).toHaveBeenCalledTimes(1)+ })+ })+})diff --git a/apps/mobile/src/utils/__tests__/backupState.test.ts b/apps/mobile/src/utils/__tests__/backupState.test.tsnew file mode 100644index 00000000..1d42ba99--- /dev/null+++ b/apps/mobile/src/utils/__tests__/backupState.test.ts@@ -0,0 +1,237 @@+import type { BackupManifest, PasswordStrengthResult } from "../../services/BackupService"+import { formatDateWithYear } from "../geo"+import {+ archiveLine,+ backupErrorMessage,+ backupExcludesLine,+ backupRowSub,+ backupScopeLine,+ backupState,+ passwordLine,+ restoreCaveat,+ restoreConfirm,+ restoreErrorMessage,+ restoreOutcome,+ submitBlockedReason+} from "../backupState"++const MADE_AT = "2026-09-03T09:15:00Z"+const MADE_SECONDS = Math.floor(Date.parse(MADE_AT) / 1000)++const manifest = (over: Partial<BackupManifest> = {}): BackupManifest => ({+ createdAt: MADE_AT,+ appVersion: "1.16.0",+ appBuild: 48,+ schemaDb: 7,+ ...over+})++const strength = (score: number, bits: number, label = "Strong"): PasswordStrengthResult =>+ ({ score, bits, label }) as PasswordStrengthResult++describe("backupState", () => {+ it("says when the last backup was, and what a new one would hold", () => {+ const line = backupState(Date.parse(MADE_AT), { total: 12481, databaseSizeMB: 8.42 })+ expect(line.label).toBe(`You last backed up ${formatDateWithYear(MADE_SECONDS)}`)+ expect(line.caption).toBe("Database: 12,481 locations, 8.42 MB")+ expect(line.tone).toBe("ok")+ })++ // The tone separates a device with data and no backup from a device with nothing to lose.+ it("warns only when there is something to lose", () => {+ expect(backupState(null, { total: 12481, databaseSizeMB: 8.42 }).tone).toBe("none")+ expect(backupState(null, { total: 0, databaseSizeMB: 0.02 }).tone).toBe("empty")+ })++ it("treats a zero timestamp as never, since that is what an unset row reads as", () => {+ expect(backupState(0, { total: 5, databaseSizeMB: 1 }).label).toBe("You have never backed up")+ expect(backupRowSub(0)).toBe("Never backed up")+ expect(backupRowSub(Date.parse(MADE_AT))).toBe(`Last backed up ${formatDateWithYear(MADE_SECONDS)}`)+ })++ /**+ * The app holds no grant on the destination, so it cannot see whether the file is still there.+ * Every line states what the user did, never that a backup exists, or deleting the file makes it+ * a lie.+ */+ it("states the act of backing up, never that a file exists", () => {+ const line = backupState(Date.parse(MADE_AT), { total: 12481, databaseSizeMB: 8.42 })+ for (const text of [line.label, backupRowSub(Date.parse(MADE_AT)), backupRowSub(0)]) {+ expect(text).toMatch(/backed up/)+ }+ })+})++describe("submitBlockedReason", () => {+ // The old placeholder stated a length while the gate was entropy, so the button died silently.+ it("names the rule that is actually blocking, in order", () => {+ expect(submitBlockedReason("", "", strength(0, 0))).toBe("Choose a password first.")+ expect(submitBlockedReason("short", "", strength(1, 20))).toBe("This password is too easy to guess.")+ expect(submitBlockedReason("correct horse battery", "", strength(3, 62))).toBe("Type the password a second time.")+ expect(submitBlockedReason("correct horse battery", "typo", strength(3, 62))).toBe(+ "The two passwords do not match."+ )+ })++ it("returns nothing once the password can be submitted", () => {+ expect(submitBlockedReason("correct horse battery", "correct horse battery", strength(3, 62))).toBeNull()+ })++ // The gate is the native score, so the line and the button cannot disagree.+ it("gates on the same score the line reports", () => {+ expect(submitBlockedReason("x", "x", strength(2, 50))).toBeNull()+ expect(passwordLine(strength(2, 50), false).variant).toBe("info")+ expect(submitBlockedReason("x", "x", strength(1, 49))).not.toBeNull()+ expect(passwordLine(strength(1, 49), false).variant).toBe("warning")+ })+})++describe("passwordLine", () => {+ it("says so when the check itself failed, rather than calling the password weak", () => {+ expect(passwordLine(strength(0, 0), true).text).toBe("Could not check this password. Try again.")+ })++ /**+ * Native scores the password and JS prints its label, so the twelve-character minimum lives in+ * one place. A number copied into JS would go stale the day the native rule moves.+ */+ it("prints the verdict native computed, and the advice that fits it", () => {+ expect(passwordLine(strength(0, 0, "Too short"), false).text).toBe("Too short. Make it longer.")+ expect(passwordLine(strength(1, 38, "Weak"), false).text).toBe("Weak. Make it longer or less predictable.")+ expect(passwordLine(strength(2, 55, "OK"), false).text).toBe("OK. 55 bits.")+ })+})++describe("backupScopeLine and backupExcludesLine", () => {+ /**+ * BACKED_UP_KEYS carries the auth config and the mTLS server CA. The client certificate's private+ * key is generated in the Android keystore and cannot be read back, so no archive holds it and the+ * scope line must never claim one does.+ */+ it("never claims the client certificate is written", () => {+ expect(backupScopeLine(12481)).not.toContain("certificate")+ expect(backupScopeLine(12481)).toContain("stored server credentials")+ })++ it("says the certificate is excluded, and only to someone who has one", () => {+ expect(backupExcludesLine(true)).toContain("not included")+ expect(backupExcludesLine(false)).toBeNull()+ })+})++describe("archiveLine and restoreConfirm", () => {+ it("names the date the archive was made and the count it would replace", () => {+ expect(archiveLine(manifest()).label).toBe(`Backup from ${formatDateWithYear(MADE_SECONDS)}`)+ expect(archiveLine(manifest()).caption).toBe("Colota 1.16.0 · opened with your password")++ const copy = restoreConfirm(12481, manifest())+ expect(copy.title).toBe("Replace all 12,481 locations?")+ expect(copy.message).toContain(formatDateWithYear(MADE_SECONDS))+ expect(copy.confirmText).toBe("Replace")+ })++ // The shipped dialog named three of six tables and no count at all.+ it("names every table the swap takes", () => {+ const { message } = restoreConfirm(1, manifest())+ for (const noun of ["locations", "geofences", "tracking profiles", "trip splits", "settings", "upload queue"]) {+ expect(message).toContain(noun)+ }+ expect(message).toContain("cannot be undone")+ })++ it("survives an unreadable date instead of printing NaN", () => {+ expect(archiveLine(manifest({ createdAt: "not a date" })).label).toBe("Backup from an unknown date")+ })+})++describe("restoreCaveat", () => {+ // One string or none, so restraint is a signature rather than a discipline.+ it("returns at most one caveat", () => {+ expect(restoreCaveat(true)).toContain("client certificate")+ expect(restoreCaveat(false)).toBeNull()+ })++ /**+ * deleteAndroidKeyStoreClientCert has one caller, the Remove button in MtlsSection. Nothing in the+ * restore path touches the keystore, so a caveat promising removal would be false.+ */+ it("does not claim a restore removes the certificate", () => {+ expect(restoreCaveat(true)).not.toMatch(/remov|delet/i)+ expect(restoreCaveat(true)).toContain("stays as it is")+ })+})++describe("restoreOutcome", () => {+ /**+ * This is the decision that matters most: the caller reloads the bundle on "restored" and does+ * not on "failed". A post-swap failure reported as failed leaves every screen reading a database+ * that no longer exists.+ */+ it("calls every post-swap code restored, however it ended", () => {+ expect(restoreOutcome(undefined).kind).toBe("restored")+ expect(restoreOutcome("E_BACKUP_SECRETS_PARTIAL").kind).toBe("restored")+ expect(restoreOutcome("E_BACKUP_RESTORED_INCOMPLETE").kind).toBe("restored")+ })++ it("calls every pre-swap code failed", () => {+ for (const code of [+ "E_BACKUP_WRONG_PASSWORD",+ "E_BACKUP_BAD_MAGIC",+ "E_BACKUP_TRUNCATED",+ "E_BACKUP_MIGRATION_FAILED",+ "E_BACKUP_NO_SPACE",+ "E_BUSY"+ ]) {+ expect(restoreOutcome(code).kind).toBe("failed")+ }+ })++ it("opens every restored outcome the same way and says recording is off", () => {+ for (const code of [undefined, "E_BACKUP_SECRETS_PARTIAL", "E_BACKUP_RESTORED_INCOMPLETE"]) {+ const outcome = restoreOutcome(code)+ expect(outcome.title).toBe("Your data is restored")+ expect(outcome.message.toLowerCase()).toContain("recording is off")+ }+ })+})++describe("restoreErrorMessage", () => {+ // Every pre-swap failure is provably one where nothing was replaced, so every one says so.+ it("ends every pre-swap failure with the same promise", () => {+ for (const code of [+ "E_BACKUP_WRONG_PASSWORD",+ "E_BACKUP_BAD_MAGIC",+ "E_BACKUP_TRUNCATED",+ "E_BACKUP_TAMPERED",+ "E_BACKUP_MIGRATION_FAILED",+ "E_BACKUP_UNSUPPORTED_SCHEMA",+ "E_BACKUP_MISSING_ENTRY",+ "E_BACKUP_NO_SPACE",+ undefined+ ]) {+ expect(restoreErrorMessage(code)).toContain("Nothing on this device was changed.")+ }+ })++ // The file is intact and this app's migration failed, which is not the same as corruption.+ it("tells a migration failure apart from a damaged file", () => {+ expect(restoreErrorMessage("E_BACKUP_MIGRATION_FAILED")).not.toContain("damaged")+ expect(restoreErrorMessage("E_BACKUP_INTEGRITY_FAIL")).toContain("damaged")+ })++ it("has a sentence for a truncated archive, which is what a half-written file reads as", () => {+ expect(restoreErrorMessage("E_BACKUP_TRUNCATED")).toContain("never finished being written")+ })+})++describe("backupErrorMessage", () => {+ it("claims only the scope the lock has", () => {+ expect(backupErrorMessage("E_BUSY")).toBe("Another backup or restore is already running.")+ })++ it("falls back to what native said, since the backup path's messages are user-safe", () => {+ expect(backupErrorMessage(undefined, "Could not write to the file you chose.")).toBe(+ "Could not write to the file you chose."+ )+ })+})diff --git a/apps/mobile/src/utils/backupState.ts b/apps/mobile/src/utils/backupState.tsnew file mode 100644index 00000000..0296042b--- /dev/null+++ b/apps/mobile/src/utils/backupState.ts@@ -0,0 +1,225 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import type { BackupManifest, PasswordStrengthResult } from "../services/BackupService"+import { formatDateWithYear } from "./geo"++/**+ * What a backup holds and what restoring one replaces, in the words the screen prints.+ *+ * Restore swaps the database file rather than deleting rows, so every sentence here names what goes+ * and whether it has gone yet. `restoreOutcome` is the one place that decides whether the swap+ * happened, because that answer decides whether the caller reloads the bundle.+ *+ * The app never sees a backup file after it writes one: it holds no persisted grant on the+ * destination, so `last_backup_at` records that a backup was made and nothing more. Every line here+ * is worded as an event for that reason, because a file the user has since moved or deleted would+ * make any claim that one exists a lie.+ */++const plural = (n: number, noun: string) => `${n.toLocaleString()} ${noun}${n === 1 ? "" : "s"}`++const whenBackedUp = (ms: number | null): string | null =>+ ms && ms > 0 ? formatDateWithYear(Math.floor(ms / 1000)) : null++export interface BackupStateLine {+ label: string+ caption: string+ tone: "ok" | "none" | "empty"+}++/** The opening line: whether a backup was ever made, and what a new one would hold. */+export function backupState(+ lastBackupAtMs: number | null,+ stats: { total: number; databaseSizeMB: number }+): BackupStateLine {+ const caption = `Database: ${plural(stats.total, "location")}, ${stats.databaseSizeMB.toFixed(2)} MB`+ const when = whenBackedUp(lastBackupAtMs)+ if (when) return { label: `You last backed up ${when}`, caption, tone: "ok" }+ if (stats.total === 0) return { label: "You have never backed up", caption, tone: "empty" }+ return { label: "You have never backed up", caption, tone: "none" }+}++/** The Settings hub row. */+export function backupRowSub(lastBackupAtMs: number | null): string {+ const when = whenBackedUp(lastBackupAtMs)+ return when ? `Last backed up ${when}` : "Never backed up"+}++/** The line under the password field, from the score native computed rather than a second guess. */+export function passwordLine(+ strength: PasswordStrengthResult,+ failed: boolean+): { text: string; variant: "info" | "warning" } {+ if (failed) return { text: "Could not check this password. Try again.", variant: "warning" }+ if (strength.score >= 2) return { text: `${strength.label}. ${Math.round(strength.bits)} bits.`, variant: "info" }+ // Native's own label, so the reason can never disagree with the gate and no length lives in JS.+ const advice = strength.score === 0 ? "Make it longer." : "Make it longer or less predictable."+ return { text: strength.label ? `${strength.label}. ${advice}` : advice, variant: "warning" }+}++/** Why Create backup is disabled, in the words of the rule that blocks it. */+export function submitBlockedReason(+ password: string,+ confirm: string,+ strength: PasswordStrengthResult+): string | null {+ if (password.length === 0) return "Choose a password first."+ if (strength.score < 2) return "This password is too easy to guess."+ if (confirm.length === 0) return "Type the password a second time."+ if (password !== confirm) return "The two passwords do not match."+ return null+}++/** What a new archive would contain. Stated once, where the button that writes it lives. */+export function backupScopeLine(total: number): string {+ return `Writes ${plural(total, "location")}, your geofences, profiles, settings and your stored server credentials to a file you pick.`+}++/**+ * The client certificate's private key is generated in the Android keystore and cannot be read back+ * out, so no backup can carry it. Only said to someone who has one, since it is otherwise noise.+ */+export function backupExcludesLine(hasClientCert: boolean): string | null {+ if (!hasClientCert) return null+ return "Your client certificate is not included. Its private key cannot leave this device's keystore."+}++/** The archive is encrypted and there is no reset, which is the one thing worth saying twice. */+export const NO_RECOVERY_LINE = "Nobody can open this file without the password, and there is no way to reset it."++export const BACKUP_WRITTEN_LINE = "Backup written. Keep it somewhere you can reach without this phone."++export const RESTORE_IDLE_LINE = "Replaces everything on this device. Nothing is merged."++export const PICKED_NOT_OPENED_CAPTION = "Not opened yet."++export const OPEN_FILE_LINE = "Checks the password and reads what the file holds. Nothing on this device changes."++export const PASSWORD_HINT_LINE = "Several unrelated words work better than one short, clever one."++/** The opened archive, as a state line. */+export function archiveLine(manifest: BackupManifest): { label: string; caption: string } {+ const seconds = Date.parse(manifest.createdAt) / 1000+ const made = Number.isFinite(seconds) ? formatDateWithYear(Math.floor(seconds)) : "an unknown date"+ return {+ label: `Backup from ${made}`,+ caption: `Colota ${manifest.appVersion} · opened with your password`+ }+}++/** At most one caveat, so restraint is a signature rather than a discipline. */+export function restoreCaveat(certConfigured: boolean): string | null {+ if (!certConfigured) return null+ return "Your client certificate stays as it is. A backup carries none, and a restore does not replace it."+}++export interface ConfirmCopy {+ title: string+ message: string+ confirmText: string+}++/** Names the count it replaces and the date it replaces them with. */+export function restoreConfirm(total: number, manifest: BackupManifest): ConfirmCopy {+ const seconds = Date.parse(manifest.createdAt) / 1000+ const made = Number.isFinite(seconds) ? formatDateWithYear(Math.floor(seconds)) : "an unknown date"+ return {+ title: `Replace all ${plural(total, "location")}?`,+ message: `Replaces everything on this device with the backup from ${made}: locations, geofences, tracking profiles, trip splits, settings, the upload queue and your stored server credentials. Nothing is merged and nothing is kept. Recording stops and stays off until you turn it back on. The file and the password have already been checked, so your data is replaced in one step at the end, and that step cannot be undone.`,+ confirmText: "Replace"+ }+}++export type AlertTone = "success" | "warning" | "error"++export interface Outcome {+ kind: "restored" | "failed"+ title: string+ message: string+ variant: AlertTone+}++/**+ * The one place that decides whether the database was replaced, and therefore whether the caller+ * reloads the bundle. Every post-swap code answers "restored", however it ended.+ */+export function restoreOutcome(code: string | undefined, nativeMessage?: string): Outcome {+ switch (code) {+ case undefined:+ return {+ kind: "restored",+ title: "Your data is restored",+ message: "Recording is off. Turn it back on when you are ready.",+ variant: "success"+ }+ case "E_BACKUP_SECRETS_PARTIAL":+ return {+ kind: "restored",+ title: "Your data is restored",+ message:+ "Your server credentials could not be applied. Enter them again on Connection. Recording is off until you turn it back on.",+ variant: "warning"+ }+ case "E_BACKUP_RESTORED_INCOMPLETE":+ return {+ kind: "restored",+ title: "Your data is restored",+ message:+ "Something failed after the swap, so some settings may not have been applied. Check Connection and Tracking. Recording is off until you turn it back on.",+ variant: "warning"+ }+ default:+ return {+ kind: "failed",+ title: "Restore failed",+ message: restoreErrorMessage(code, nativeMessage),+ variant: "error"+ }+ }+}++/** Every pre-swap failure ends the same way, because on every one of them it is true. */+const UNCHANGED = "Nothing on this device was changed."++export function restoreErrorMessage(code: string | undefined, nativeMessage?: string): string {+ switch (code) {+ case "E_BACKUP_WRONG_PASSWORD":+ return `That password did not open this file. ${UNCHANGED}`+ case "E_BACKUP_BAD_MAGIC":+ case "E_BACKUP_UNSUPPORTED_VERSION":+ return `This is not a Colota backup. ${UNCHANGED}`+ case "E_BACKUP_TRUNCATED":+ return `This file is incomplete, so it was probably never finished being written. ${UNCHANGED}`+ case "E_BACKUP_TAMPERED":+ case "E_BACKUP_INTEGRITY_FAIL":+ return `This file is damaged and cannot be trusted. ${UNCHANGED}`+ case "E_BACKUP_MIGRATION_FAILED":+ return `The file is intact but this version of Colota could not read its database. ${UNCHANGED}`+ case "E_BACKUP_UNSUPPORTED_SCHEMA":+ return `This backup was made by a newer version of Colota. Update the app first. ${UNCHANGED}`+ case "E_BACKUP_MISSING_ENTRY":+ return `This file is missing part of a backup. ${UNCHANGED}`+ case "E_BACKUP_NO_SPACE":+ return `There is not enough free space to unpack this backup. ${UNCHANGED}`+ case "E_BUSY":+ return "Another backup or restore is already running."+ case "E_PASSWORD_EMPTY":+ return "Type the backup's password first."+ default:+ return nativeMessage ? `${nativeMessage} ${UNCHANGED}` : `The backup could not be restored. ${UNCHANGED}`+ }+}++export function backupErrorMessage(code: string | undefined, nativeMessage?: string): string {+ switch (code) {+ case "E_BUSY":+ return "Another backup or restore is already running."+ case "E_PASSWORD_EMPTY":+ return "Choose a password first."+ default:+ return nativeMessage ?? "The backup could not be written. Try a different location."+ }+}