freezmo/components/SyncSection.tsx
Martin Dvorak bb1f4e2018 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.
2026-10-10 13:43:42 +00:00

303 lines
11 KiB
TypeScript

"use client";
import { useEffect, useState, useSyncExternalStore } from "react";
import { Button } from "@/components/ui";
import { copyText } from "@/lib/clipboard";
import { haptic } from "@/lib/haptics";
import { useI18n } from "@/lib/i18n";
import { deleteSyncedData, enableSync, forgetDeviceKey, hasDeviceKey, joinSync, syncNow, unlockSync, type SyncOutcome } from "@/lib/sync";
import { syncStore } from "@/lib/sync-state";
/**
* Settings → Sync (off by default). Enabling derives a key from the user's
* passphrase, stores it as a non-extractable CryptoKey and uploads the first
* encrypted blob. Joining needs the sync ID plus the passphrase. Conflicts
* are surfaced with an explicit choice — never resolved silently.
*/
export function SyncSection() {
const { t, locale } = useI18n();
const record = useSyncExternalStore(syncStore.subscribe, syncStore.getSnapshot, syncStore.getServerSnapshot);
const [mode, setMode] = useState<"idle" | "enable" | "join">("idle");
const [pass, setPass] = useState("");
const [pass2, setPass2] = useState("");
const [joinId, setJoinId] = useState("");
const [busy, setBusy] = useState(false);
const [notice, setNotice] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [locked, setLocked] = useState<boolean | null>(null);
const [confirmDelete, setConfirmDelete] = useState(false);
useEffect(() => {
if (!record.enabled) {
setLocked(null);
return;
}
void hasDeviceKey().then(setLocked);
}, [record.enabled, record.id]);
const statusFor = (outcome: SyncOutcome): string | null => {
switch (outcome.status) {
case "pushed":
return t("settings.syncPushed");
case "pulled":
return t("settings.syncPulled");
case "up-to-date":
return t("settings.syncDone");
case "conflict":
return t("settings.syncConflict");
case "locked":
return t("settings.syncLocked");
case "error":
return outcome.message ?? t("settings.syncError");
default:
return null;
}
};
const reset = () => {
setMode("idle");
setPass("");
setPass2("");
setJoinId("");
setError(null);
};
const run = async (action: () => Promise<SyncOutcome>) => {
setBusy(true);
setError(null);
setNotice(null);
try {
const outcome = await action();
const text = statusFor(outcome);
if (outcome.status === "error" || outcome.status === "locked") setError(text);
else setNotice(text);
if (outcome.status !== "error" && outcome.status !== "locked") reset();
} finally {
setBusy(false);
}
};
const startEnable = () => {
if (pass.length < 8) return setError(t("settings.syncPassphraseShort"));
if (pass !== pass2) return setError(t("settings.syncPassphraseMismatch"));
void run(() => enableSync(pass));
};
const startJoin = () => {
if (!joinId.trim()) return setError(t("server.syncInvalidId"));
if (pass.length < 8) return setError(t("settings.syncPassphraseShort"));
void run(() => joinSync(joinId, pass));
};
const startUnlock = () => {
if (!pass) return setError(t("settings.syncPassphraseShort"));
void run(async () => {
const outcome = await unlockSync(pass);
if (outcome.status !== "error") setLocked(true);
return outcome;
});
};
const lastSynced = record.lastSyncedAt
? t("settings.syncLast", { when: new Date(record.lastSyncedAt).toLocaleString(locale) })
: t("settings.syncNever");
const fieldClass =
"w-full rounded-xl border border-[var(--hairline)] bg-[var(--surface-strong)] px-3 py-2.5 text-sm text-frost-950 outline-none transition focus:border-accent-500 dark:text-frost-50";
/* Revoking the server copy must work even on a device that can't unlock
(e.g. after the browser dropped the stored key). */
const deleteBlock = (
<div className="flex flex-wrap gap-2 border-t border-[var(--hairline-soft)] pt-2">
{confirmDelete ? (
<span className="flex flex-wrap items-center gap-2">
<span className="text-[11.5px] text-[var(--text-muted)]">{t("settings.syncDeleteConfirm")}</span>
<Button
size="sm"
variant="danger"
loading={busy}
onClick={() =>
void run(async () => {
setConfirmDelete(false);
return deleteSyncedData();
})
}
>
{t("settings.syncDeleteYes")}
</Button>
<Button size="sm" variant="ghost" onClick={() => setConfirmDelete(false)}>
{t("settings.syncCancel")}
</Button>
</span>
) : (
<Button size="sm" variant="ghost" onClick={() => setConfirmDelete(true)}>
{t("settings.syncDelete")}
</Button>
)}
</div>
);
return (
<section className="mb-4 space-y-2 rounded-2xl border border-[var(--hairline)] bg-[var(--surface-sunken)] p-3">
<h3 className="text-sm font-semibold text-frost-950 dark:text-frost-50">{t("settings.sync")}</h3>
<p className="text-[11.5px] leading-relaxed text-[var(--text-subtle)]">{t("settings.syncNote")}</p>
<p className="text-[11px] font-medium leading-relaxed text-[var(--text-muted)]">{t("settings.syncNoteKey")}</p>
{!record.enabled ? (
mode === "enable" ? (
<div className="space-y-2">
<input
type="password"
value={pass}
onChange={(event) => setPass(event.target.value)}
placeholder={t("settings.syncPassphrase")}
autoComplete="new-password"
spellCheck={false}
className={fieldClass}
/>
<input
type="password"
value={pass2}
onChange={(event) => setPass2(event.target.value)}
placeholder={t("settings.syncPassphraseConfirm")}
autoComplete="new-password"
spellCheck={false}
className={fieldClass}
/>
{error ? <p className="text-[11.5px] font-medium text-rose-600 dark:text-rose-300">{error}</p> : null}
<div className="flex flex-wrap gap-2">
<Button size="sm" loading={busy} onClick={startEnable}>
{t("settings.syncStart")}
</Button>
<Button size="sm" variant="ghost" onClick={reset}>
{t("settings.syncCancel")}
</Button>
</div>
</div>
) : mode === "join" ? (
<div className="space-y-2">
<input
type="text"
value={joinId}
onChange={(event) => setJoinId(event.target.value)}
placeholder={t("settings.syncJoinId")}
autoComplete="off"
spellCheck={false}
className={fieldClass}
/>
<input
type="password"
value={pass}
onChange={(event) => setPass(event.target.value)}
placeholder={t("settings.syncPassphrase")}
autoComplete="off"
spellCheck={false}
className={fieldClass}
/>
<p className="text-[11px] leading-relaxed text-[var(--text-subtle)]">{t("settings.syncJoinNote")}</p>
{error ? <p className="text-[11.5px] font-medium text-rose-600 dark:text-rose-300">{error}</p> : null}
<div className="flex flex-wrap gap-2">
<Button size="sm" loading={busy} onClick={startJoin}>
{t("settings.syncJoinAction")}
</Button>
<Button size="sm" variant="ghost" onClick={reset}>
{t("settings.syncCancel")}
</Button>
</div>
</div>
) : (
<div className="flex flex-wrap gap-2">
<Button size="sm" variant="secondary" onClick={() => setMode("enable")}>
{t("settings.syncEnable")}
</Button>
<Button size="sm" variant="ghost" onClick={() => setMode("join")}>
{t("settings.syncJoin")}
</Button>
</div>
)
) : locked === false ? (
<div className="space-y-2">
<p className="text-[11.5px] leading-relaxed text-[var(--text-muted)]">{t("settings.syncLocked")}</p>
<input
type="password"
value={pass}
onChange={(event) => setPass(event.target.value)}
placeholder={t("settings.syncPassphrase")}
autoComplete="off"
spellCheck={false}
className={fieldClass}
/>
{error ? <p className="text-[11.5px] font-medium text-rose-600 dark:text-rose-300">{error}</p> : null}
<Button size="sm" loading={busy} onClick={startUnlock}>
{t("settings.syncUnlock")}
</Button>
{deleteBlock}
</div>
) : (
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<span className="min-w-0">
<span className="block text-[11px] font-semibold uppercase tracking-wide text-[var(--text-subtle)]">
{t("settings.syncId")}
</span>
<span className="block truncate font-mono text-[12px] text-[var(--text)]">{record.id}</span>
</span>
<Button
size="sm"
variant="secondary"
className="shrink-0"
onClick={() => {
void copyText(record.id).then((ok) => {
haptic("tap");
setNotice(ok ? t("settings.syncCopied") : t("settings.syncError"));
});
}}
>
{t("settings.syncCopy")}
</Button>
</div>
<p className="text-[11.5px] font-medium text-[var(--text-muted)]">{lastSynced}</p>
{record.conflict ? (
<div className="space-y-2 rounded-xl border border-amber-300 bg-amber-50 p-2.5 text-[12px] text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/10 dark:text-amber-100">
<p className="font-semibold">{t("settings.syncConflict")}</p>
<div className="flex flex-wrap gap-2">
<Button size="sm" loading={busy} onClick={() => void run(() => syncNow("push"))}>
{t("settings.syncKeepLocal")}
</Button>
<Button size="sm" variant="secondary" loading={busy} onClick={() => void run(() => syncNow("pull"))}>
{t("settings.syncKeepRemote")}
</Button>
</div>
</div>
) : (
<Button size="sm" loading={busy} onClick={() => void run(() => syncNow("auto"))}>
{t("settings.syncNow")}
</Button>
)}
{notice ? <p className="text-[12px] font-medium text-[var(--text-muted)]">{notice}</p> : null}
{error ? <p className="text-[11.5px] font-medium text-rose-600 dark:text-rose-300">{error}</p> : null}
<div className="flex flex-wrap gap-2 border-t border-[var(--hairline-soft)] pt-2">
<Button
size="sm"
variant="ghost"
onClick={() => {
void forgetDeviceKey().then(() => {
setLocked(false);
setNotice(null);
});
}}
>
{t("settings.syncForget")}
</Button>
{deleteBlock}
</div>
</div>
)}
</section>
);
}