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.
136 lines
3.6 KiB
TypeScript
136 lines
3.6 KiB
TypeScript
"use client";
|
|
|
|
/**
|
|
* Local bookkeeping for opt-in encrypted sync: whether it is on, the random
|
|
* sync ID, when this device last synced and whether local data changed since.
|
|
* The passphrase itself is never stored here — the derived key lives in
|
|
* IndexedDB as a non-extractable CryptoKey (lib/sync-key.ts) and nowhere else.
|
|
*/
|
|
|
|
const STORAGE_KEY = "freezmo.sync.v1";
|
|
|
|
export type SyncRecord = {
|
|
v: 1;
|
|
enabled: boolean;
|
|
/** Random 128-bit id — the only handle the server ever sees. */
|
|
id: string;
|
|
/** KDF salt (not secret; travels in the envelope too). */
|
|
salt: string;
|
|
lastSyncedAt: number | null;
|
|
/** Set whenever local data changes; cleared after a successful sync. */
|
|
dirtyAt: number | null;
|
|
/** True when a sync found both sides changed (the UI asks what to keep). */
|
|
conflict: boolean;
|
|
};
|
|
|
|
const EMPTY: SyncRecord = {
|
|
v: 1,
|
|
enabled: false,
|
|
id: "",
|
|
salt: "",
|
|
lastSyncedAt: null,
|
|
dirtyAt: null,
|
|
conflict: false,
|
|
};
|
|
|
|
type Listener = () => void;
|
|
|
|
let record: SyncRecord | null = null;
|
|
let cached: SyncRecord = EMPTY;
|
|
const listeners = new Set<Listener>();
|
|
let suppressDirty = false;
|
|
|
|
function read(): SyncRecord {
|
|
if (typeof window === "undefined") return EMPTY;
|
|
try {
|
|
const raw = window.localStorage.getItem(STORAGE_KEY);
|
|
if (!raw) return EMPTY;
|
|
const parsed = JSON.parse(raw) as Partial<SyncRecord>;
|
|
if (parsed.v !== 1) return EMPTY;
|
|
return {
|
|
v: 1,
|
|
enabled: parsed.enabled === true,
|
|
id: typeof parsed.id === "string" ? parsed.id : "",
|
|
salt: typeof parsed.salt === "string" ? parsed.salt : "",
|
|
lastSyncedAt: typeof parsed.lastSyncedAt === "number" ? parsed.lastSyncedAt : null,
|
|
dirtyAt: typeof parsed.dirtyAt === "number" ? parsed.dirtyAt : null,
|
|
conflict: parsed.conflict === true,
|
|
};
|
|
} catch {
|
|
return EMPTY;
|
|
}
|
|
}
|
|
|
|
function ensureLoaded(): void {
|
|
if (record !== null) return;
|
|
record = read();
|
|
cached = record;
|
|
}
|
|
|
|
function write(next: SyncRecord): void {
|
|
record = next;
|
|
cached = next;
|
|
try {
|
|
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
|
} catch {
|
|
/* private mode */
|
|
}
|
|
listeners.forEach((listener) => listener());
|
|
}
|
|
|
|
export const syncStore = {
|
|
subscribe(listener: Listener): () => void {
|
|
ensureLoaded();
|
|
listeners.add(listener);
|
|
const onStorage = (event: StorageEvent) => {
|
|
if (event.key === STORAGE_KEY) {
|
|
record = null;
|
|
ensureLoaded();
|
|
listeners.forEach((l) => l());
|
|
}
|
|
};
|
|
window.addEventListener("storage", onStorage);
|
|
return () => {
|
|
listeners.delete(listener);
|
|
window.removeEventListener("storage", onStorage);
|
|
};
|
|
},
|
|
getSnapshot(): SyncRecord {
|
|
ensureLoaded();
|
|
return cached;
|
|
},
|
|
getServerSnapshot(): SyncRecord {
|
|
return EMPTY;
|
|
},
|
|
};
|
|
|
|
export function setSyncRecord(next: Partial<SyncRecord>): void {
|
|
ensureLoaded();
|
|
write({ ...syncStore.getSnapshot(), ...next });
|
|
}
|
|
|
|
/** Called by every data store's write(); no-op when sync is off. */
|
|
export function markSyncDirty(): void {
|
|
if (suppressDirty) return;
|
|
ensureLoaded();
|
|
const current = syncStore.getSnapshot();
|
|
if (!current.enabled || current.dirtyAt !== null) return;
|
|
write({ ...current, dirtyAt: Date.now() });
|
|
}
|
|
|
|
/** Applying a pulled payload must not mark the local data dirty again. */
|
|
export function withoutDirtyTracking<T>(fn: () => T): T {
|
|
suppressDirty = true;
|
|
try {
|
|
return fn();
|
|
} finally {
|
|
suppressDirty = false;
|
|
}
|
|
}
|
|
|
|
/** 16 random bytes as hex = 128 bits, unguessable. */
|
|
export function newSyncId(): string {
|
|
const bytes = new Uint8Array(16);
|
|
crypto.getRandomValues(bytes);
|
|
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
}
|