Phase 1: backup, encrypted sync and monthly-usage handling

Safety net and errors, mobile-first, desktop unchanged in behaviour.

Backup and persistence
- Settings -> Data & backup: 'Export all data' writes one zod-validated
  JSON (decks, folders, homework, progress, safe settings; the API key
  is not part of the shape and never appears in the file).
- 'Import backup' validates, shows a preview with added/replaced
  counts and offers merge or replace; invalid files get a friendly
  error. Storage persistence (navigator.storage.persist) is shown and
  requestable, with the result reported.
- A dismissible nudge appears after 5 new decks or 14 days without a
  backup and stays snoozed for 14 days.

Opt-in encrypted sync (off by default)
- New lib/sync.ts: PBKDF2-SHA256 (310k) -> AES-GCM-256, derived key
  kept as a non-extractable CryptoKey in IndexedDB (lib/sync-key.ts);
  the passphrase and key never leave the browser.
- New POST/GET/DELETE /api/sync following the route pattern (locale,
  cross-origin guard, body cap, rate limit RATE_LIMIT_SYNC, auth
  before body parsing, zod validation). One atomic JSON file per
  random 128-bit sync ID under SYNC_DIR; server-stamped updatedAt is
  the conflict clock; SYNC_MAX_BYTES and SYNC_TOTAL_BYTES enforced
  (413 / 507). The server only ever sees an opaque envelope.
- Settings -> Sync: enable with a passphrase, copy the sync ID, sync
  now, last-synced time, explicit keep-this-device / use-synced-copy
  conflict choice, join from another device (ID + passphrase, wrong
  passphrase rejected), unlock after the key is gone, delete the
  synced copy (works even on a locked device). Every data store marks
  sync dirty on write; pulled payloads are applied without marking
  dirty again.

Monthly usage vs short-term throttling
- lib/ollama.ts classifies the real 429 body (monthly/quota/upgrade
  vs burst) into new 'usage_limit' and 'throttled' kinds, mapped in
  every route and in the health probe.
- The client renders the same localized message in the deck flow,
  homework, grading and the Settings banner: the required
  upgrade/new-key copy with 'Open Settings' (jumps to and focuses the
  key field) and 'Open Ollama'. Input and wizard drafts are kept so
  Retry works right after swapping the key. No model fallback.

Verified: new phase-1 suite 38/38 (backup content + no key, import
preview/merge/replace, junk file, persistence row, nudge + snooze,
sync enable/upload/opaque blob/push/join/wrong passphrase/delete,
server validation 400/401, usage-limit copy and key focus, and the
real route mapping against a stub Ollama for both 429 variants) plus
regression 74/74, mobile 52/52, wizard 80/80, declutter 116/116,
animation 8/8, native 35/35, i18n 25/25. Key parity 638/638. Lint +
build clean. SW freezmo-v25.
This commit is contained in:
Martin Dvořák 2026-10-10 13:43:42 +00:00
commit bb1f4e2018
31 changed files with 1933 additions and 36 deletions

251
lib/backup.ts Normal file
View file

@ -0,0 +1,251 @@
"use client";
/**
* Full-data backup: one JSON file with decks, folders, homework, progress and
* safe settings — **never the API key**. Import validates with zod, shows a
* preview of what will be added or replaced, and offers merge or replace.
*
* The same payload shape is what encrypted sync uploads (minus settings), so
* the two features share this file's validation.
*/
import { z } from "zod";
import { applyTheme } from "@/components/ThemeToggle";
import { replaceFolders, folderStore } from "./folders";
import { homeworkStore, replaceHomework } from "./homework";
import { setLocale, t } from "./i18n";
import { folderSchema, deckSchema, homeworkRecordSchema } from "./schemas";
import { saveSettings, settingsStore } from "./settings";
import { deckStore, replaceDecks } from "./storage";
export const BACKUP_VERSION = 1;
const settingsSchema = z.object({
haptics: z.boolean().optional(),
locale: z.enum(["en", "cs"]).optional(),
theme: z.enum(["light", "dark"]).optional(),
});
export const backupDataSchema = z.object({
decks: z.array(deckSchema).max(2000),
folders: z.array(folderSchema).max(500),
homework: z.array(homeworkRecordSchema).max(2000),
});
export const backupSchema = z.object({
app: z.literal("freezmo"),
kind: z.literal("backup"),
version: z.literal(1),
exportedAt: z.string(),
data: backupDataSchema.extend({ settings: settingsSchema.optional() }),
});
export type BackupFile = z.infer<typeof backupSchema>;
/* ------------------------------------------------------------------ */
/* Building and downloading */
/* ------------------------------------------------------------------ */
export function buildBackup(): BackupFile {
return {
app: "freezmo",
kind: "backup",
version: BACKUP_VERSION,
exportedAt: new Date().toISOString(),
data: {
decks: deckStore.getSnapshot(),
folders: folderStore.getSnapshot(),
homework: homeworkStore.getSnapshot(),
settings: {
haptics: settingsStore.getSnapshot().haptics,
locale: (window.localStorage.getItem("freezmo.locale.v1") as "en" | "cs" | null) ?? undefined,
theme: (window.localStorage.getItem("freezmo.theme") as "light" | "dark" | null) ?? undefined,
},
},
};
}
export function downloadBackup(): BackupFile {
const backup = buildBackup();
const blob = new Blob([JSON.stringify(backup, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = `freezmo-backup-${new Date().toISOString().slice(0, 10)}.json`;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
URL.revokeObjectURL(url);
markBackedUp(backup.data.decks.length);
return backup;
}
/* ------------------------------------------------------------------ */
/* Parsing, previewing, applying */
/* ------------------------------------------------------------------ */
export function parseBackup(raw: string): { backup: BackupFile } | { error: string } {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return { error: t("import.notJson") };
}
const result = backupSchema.safeParse(parsed);
if (!result.success) return { error: t("import.notBackup") };
return { backup: result.data };
}
export type ImportCounts = { added: number; replaced: number };
function countMerge<T extends { id: string }>(current: T[], incoming: T[]): ImportCounts {
const ids = new Set(current.map((item) => item.id));
let added = 0;
let replaced = 0;
for (const item of incoming) {
if (ids.has(item.id)) replaced += 1;
else added += 1;
}
return { added, replaced };
}
function mergeById<T extends { id: string }>(current: T[], incoming: T[]): T[] {
const positions = new Map(current.map((item, index) => [item.id, index]));
const merged = [...current];
for (const item of incoming) {
const at = positions.get(item.id);
if (at === undefined) {
positions.set(item.id, merged.length);
merged.push(item);
} else {
merged[at] = item;
}
}
return merged;
}
export type ImportPreview = {
decks: ImportCounts;
folders: ImportCounts;
homework: ImportCounts;
};
export function previewImport(backup: BackupFile): ImportPreview {
return {
decks: countMerge(deckStore.getSnapshot(), backup.data.decks),
folders: countMerge(folderStore.getSnapshot(), backup.data.folders),
homework: countMerge(homeworkStore.getSnapshot(), backup.data.homework),
};
}
/** Applies a backup; the API key is never touched (it is not in the file). */
export function applyImport(backup: BackupFile, mode: "merge" | "replace"): { decks: number; homework: number } {
const data = backup.data;
const decks =
mode === "replace" ? data.decks : mergeById(deckStore.getSnapshot(), data.decks);
const folders =
mode === "replace" ? data.folders : mergeById(folderStore.getSnapshot(), data.folders);
const homework =
mode === "replace" ? data.homework : mergeById(homeworkStore.getSnapshot(), data.homework);
// Folders first so imported decks can point at them. Importing is a real
// local change, so it also marks sync dirty (via the stores' write()).
replaceFolders(folders);
replaceDecks(decks);
replaceHomework(homework);
const settings = data.settings;
if (settings) {
if (typeof settings.haptics === "boolean") saveSettings({ haptics: settings.haptics });
if (settings.locale) setLocale(settings.locale);
if (settings.theme) applyTheme(settings.theme);
}
return { decks: decks.length, homework: homework.length };
}
/* ------------------------------------------------------------------ */
/* Backup nudge */
/* ------------------------------------------------------------------ */
const BACKUP_STATE_KEY = "freezmo.backup.v1";
const NUDGE_DAYS = 14;
const NUDGE_DECKS = 5;
type BackupState = {
lastBackupAt: number | null;
decksAtLastBackup: number;
snoozedUntil: number | null;
};
const EMPTY_STATE: BackupState = { lastBackupAt: null, decksAtLastBackup: 0, snoozedUntil: null };
function readBackupState(): BackupState {
try {
const raw = window.localStorage.getItem(BACKUP_STATE_KEY);
if (!raw) return EMPTY_STATE;
const parsed = JSON.parse(raw) as Partial<BackupState>;
return {
lastBackupAt: typeof parsed.lastBackupAt === "number" ? parsed.lastBackupAt : null,
decksAtLastBackup: typeof parsed.decksAtLastBackup === "number" ? parsed.decksAtLastBackup : 0,
snoozedUntil: typeof parsed.snoozedUntil === "number" ? parsed.snoozedUntil : null,
};
} catch {
return EMPTY_STATE;
}
}
function writeBackupState(next: BackupState): void {
try {
window.localStorage.setItem(BACKUP_STATE_KEY, JSON.stringify(next));
} catch {
/* private mode */
}
}
export function markBackedUp(deckCount: number): void {
writeBackupState({ lastBackupAt: Date.now(), decksAtLastBackup: deckCount, snoozedUntil: null });
}
export function snoozeBackupNudge(): void {
const state = readBackupState();
writeBackupState({ ...state, snoozedUntil: Date.now() + NUDGE_DAYS * 86_400_000 });
}
export function backupNudgeDue(deckCount: number): boolean {
if (deckCount < 2) return false;
const state = readBackupState();
if (state.snoozedUntil && state.snoozedUntil > Date.now()) return false;
if (state.lastBackupAt === null) return deckCount >= NUDGE_DECKS;
if (Date.now() - state.lastBackupAt > NUDGE_DAYS * 86_400_000) return true;
return deckCount >= state.decksAtLastBackup + NUDGE_DECKS;
}
export function lastBackupAt(): number | null {
return readBackupState().lastBackupAt;
}
/* ------------------------------------------------------------------ */
/* Storage persistence */
/* ------------------------------------------------------------------ */
export type PersistenceState = "persistent" | "best-effort" | "unsupported";
export async function getStoragePersistence(): Promise<PersistenceState> {
try {
if (!navigator.storage?.persisted) return "unsupported";
return (await navigator.storage.persisted()) ? "persistent" : "best-effort";
} catch {
return "unsupported";
}
}
export async function requestStoragePersistence(): Promise<boolean> {
try {
if (!navigator.storage?.persist) return false;
return await navigator.storage.persist();
} catch {
return false;
}
}