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:
parent
1dc2992fb5
commit
bb1f4e2018
31 changed files with 1933 additions and 36 deletions
251
lib/backup.ts
Normal file
251
lib/backup.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@
|
|||
|
||||
import { sanitiseApiKey } from "./http-guard";
|
||||
import { translate, type Locale } from "./i18n-dict";
|
||||
import path from "node:path";
|
||||
|
||||
export type AuthMode = "user-key" | "server" | "local";
|
||||
|
||||
|
|
@ -29,6 +30,15 @@ export type ServerConfig = {
|
|||
grade: number;
|
||||
homework: number;
|
||||
health: number;
|
||||
sync: number;
|
||||
};
|
||||
sync: {
|
||||
/** Where opaque encrypted sync blobs live (SYNC_DIR). */
|
||||
dir: string;
|
||||
/** Per-blob cap in bytes (SYNC_MAX_BYTES). */
|
||||
maxBytes: number;
|
||||
/** Total cap for the whole directory in bytes (SYNC_TOTAL_BYTES). */
|
||||
totalBytes: number;
|
||||
};
|
||||
};
|
||||
|
||||
|
|
@ -99,6 +109,13 @@ export function getServerConfig(): ServerConfig {
|
|||
// Homework is one to two model calls, like a deck.
|
||||
homework: positiveInt(process.env.RATE_LIMIT_HOMEWORK, 12),
|
||||
health: positiveInt(process.env.RATE_LIMIT_HEALTH, 90),
|
||||
// Sync is cheap (no model calls) but shouldn't be hammered.
|
||||
sync: positiveInt(process.env.RATE_LIMIT_SYNC, 60),
|
||||
},
|
||||
sync: {
|
||||
dir: process.env.SYNC_DIR?.trim() || path.join(process.cwd(), ".freezmo", "sync"),
|
||||
maxBytes: positiveInt(process.env.SYNC_MAX_BYTES, 12 * 1024 * 1024),
|
||||
totalBytes: positiveInt(process.env.SYNC_TOTAL_BYTES, 1024 * 1024 * 1024),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
|
||||
import { t } from "./i18n";
|
||||
import { folderSchema, UNORGANIZED_ID, type Folder } from "./schemas";
|
||||
import { markSyncDirty } from "./sync-state";
|
||||
import { uid } from "./utils";
|
||||
|
||||
const STORAGE_KEY = "freezmo.folders.v1";
|
||||
|
|
@ -55,9 +56,21 @@ function write(next: Folder[]): void {
|
|||
} catch (error) {
|
||||
console.warn("[freezmo] could not save folders", error);
|
||||
}
|
||||
markSyncDirty();
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
/** Used by backup import and sync: wholesale replacement of the folders. */
|
||||
export function replaceFolders(next: Folder[]): void {
|
||||
const valid: Folder[] = [];
|
||||
for (const entry of next) {
|
||||
const result = folderSchema.safeParse(entry);
|
||||
if (result.success) valid.push(result.data);
|
||||
else console.warn("[freezmo] skipping invalid folder in import", result.error.issues);
|
||||
}
|
||||
write(valid);
|
||||
}
|
||||
|
||||
export const folderStore = {
|
||||
subscribe(listener: Listener): () => void {
|
||||
ensureLoaded();
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import {
|
|||
type HomeworkRecord,
|
||||
type HomeworkStep,
|
||||
} from "./schemas";
|
||||
import { markSyncDirty } from "./sync-state";
|
||||
import { uid } from "./utils";
|
||||
|
||||
const STORAGE_KEY = "freezmo.homework.v1";
|
||||
|
|
@ -63,9 +64,21 @@ function write(next: HomeworkRecord[]): void {
|
|||
} catch (error) {
|
||||
console.warn("[freezmo] could not save the homework history (storage full?)", error);
|
||||
}
|
||||
markSyncDirty();
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
/** Used by backup import and sync: wholesale replacement of the history. */
|
||||
export function replaceHomework(next: HomeworkRecord[]): void {
|
||||
const valid: HomeworkRecord[] = [];
|
||||
for (const entry of next) {
|
||||
const result = homeworkRecordSchema.safeParse(entry);
|
||||
if (result.success) valid.push(result.data as HomeworkRecord);
|
||||
else console.warn("[freezmo] skipping invalid homework record in import", result.error.issues);
|
||||
}
|
||||
write(valid);
|
||||
}
|
||||
|
||||
export const homeworkStore = {
|
||||
subscribe(listener: Listener): () => void {
|
||||
ensureLoaded();
|
||||
|
|
|
|||
156
lib/i18n-dict.ts
156
lib/i18n-dict.ts
|
|
@ -151,6 +151,70 @@ const en: Record<string, string> = {
|
|||
"settings.haptics": "Haptics",
|
||||
"settings.hapticsNote": "Vibration feedback on supported phones.",
|
||||
|
||||
/* data, backup & sync --------------------------------------------- */
|
||||
"settings.data": "Data & backup",
|
||||
"settings.dataNote": "Everything lives in this browser. Export a backup regularly.",
|
||||
"settings.exportAll": "Export all data",
|
||||
"settings.exportNote": "Decks, homework, progress and settings — never your API key.",
|
||||
"settings.importBackup": "Import backup",
|
||||
"settings.importPreview": "This backup has {decks} decks, {homework} homework results and {folders} folders.",
|
||||
"settings.importMergeNote": "Merge keeps what's here and adds the backup; matching IDs are replaced.",
|
||||
"settings.importReplaceNote": "Replace wipes this browser's data and uses the backup instead.",
|
||||
"settings.importMerge": "Merge",
|
||||
"settings.importReplace": "Replace",
|
||||
"settings.importCancel": "Cancel",
|
||||
"settings.importDone": "Imported {decks} decks and {homework} homework results.",
|
||||
"settings.importFailed": "That backup could not be imported.",
|
||||
"settings.storage": "Storage",
|
||||
"settings.storagePersistent": "Persistent — the browser won't evict your data.",
|
||||
"settings.storageBestEffort": "Best-effort — the browser may clear data under pressure.",
|
||||
"settings.storageRequest": "Ask for persistence",
|
||||
"settings.storageGranted": "Granted — your data is now persistent.",
|
||||
"settings.storageDenied": "The browser declined. Installing the app usually helps.",
|
||||
"settings.backupNudgeTitle": "Back up your decks?",
|
||||
"settings.backupNudgeBody": "You've added decks since your last backup. A backup keeps them safe.",
|
||||
"settings.backupNow": "Back up now",
|
||||
"settings.backupLater": "Not now",
|
||||
"settings.sync": "Sync",
|
||||
"settings.syncNote":
|
||||
"Off by default. Data is encrypted in this browser before upload — the server stores an opaque blob and never sees your data or key.",
|
||||
"settings.syncEnable": "Turn on sync",
|
||||
"settings.syncPassphrase": "Sync passphrase",
|
||||
"settings.syncPassphraseConfirm": "Repeat the passphrase",
|
||||
"settings.syncPassphraseMismatch": "The passphrases don't match.",
|
||||
"settings.syncPassphraseShort": "Use at least 8 characters.",
|
||||
"settings.syncStart": "Start syncing",
|
||||
"settings.syncCancel": "Cancel",
|
||||
"settings.syncId": "Sync ID",
|
||||
"settings.syncCopy": "Copy",
|
||||
"settings.syncCopied": "Copied.",
|
||||
"settings.syncLast": "Last synced {when}",
|
||||
"settings.syncNever": "Not synced yet.",
|
||||
"settings.syncNow": "Sync now",
|
||||
"settings.syncWorking": "Syncing…",
|
||||
"settings.syncDone": "Up to date.",
|
||||
"settings.syncPushed": "Uploaded from this device.",
|
||||
"settings.syncPulled": "Downloaded from the synced copy.",
|
||||
"settings.syncConflict": "This device and the synced copy both changed. Choose which one to keep.",
|
||||
"settings.syncKeepLocal": "Keep this device",
|
||||
"settings.syncKeepRemote": "Use synced copy",
|
||||
"settings.syncJoin": "Join another sync",
|
||||
"settings.syncJoinNote":
|
||||
"Enter the sync ID and passphrase from your other device. Data in this browser is replaced by the synced copy.",
|
||||
"settings.syncJoinId": "Sync ID",
|
||||
"settings.syncJoinAction": "Join",
|
||||
"settings.syncLocked": "Enter your sync passphrase to unlock syncing on this device.",
|
||||
"settings.syncUnlock": "Unlock",
|
||||
"settings.syncForget": "Forget passphrase on this device",
|
||||
"settings.syncDelete": "Delete synced data",
|
||||
"settings.syncDeleteConfirm": "Delete the synced copy from the server? This device keeps its data.",
|
||||
"settings.syncDeleteYes": "Delete",
|
||||
"settings.syncWrongPass": "That passphrase can't unlock the synced copy.",
|
||||
"settings.syncError": "Sync failed. Check your connection and try again.",
|
||||
"settings.syncOff": "Sync is off.",
|
||||
"settings.syncOn": "Sync is on.",
|
||||
"settings.syncNoteKey": "Your API key is never synced.",
|
||||
|
||||
/* offline / share / toasts ---------------------------------------- */
|
||||
"offline.banner": "You're offline — saved decks still work.",
|
||||
"offline.generate": "You're offline — connect to generate.",
|
||||
|
|
@ -693,6 +757,13 @@ const en: Record<string, string> = {
|
|||
"server.healthModelNoteLocal": "Not in the daemon's model list. Run `ollama pull {model}` or check your sign-in.",
|
||||
"server.healthModelNoteCloud": "Not returned by {url}/api/tags. Check the model name and your key's plan.",
|
||||
"server.healthModelsMissing": "Ollama is reachable, but at least one configured model is not available.",
|
||||
"server.usageLimit":
|
||||
"Your free monthly Ollama usage has run out. Upgrade your Ollama account, or create a new one and use the new API key.",
|
||||
"server.ollamaThrottled": "Ollama is temporarily rate limiting requests. Try again in a moment.",
|
||||
"server.syncInvalidId": "That sync ID doesn't look right.",
|
||||
"server.syncTooLarge": "This sync upload is too large.",
|
||||
"server.syncStorageFull": "The sync storage is full. Delete some synced data and try again.",
|
||||
"server.syncNotFound": "No synced data found for that ID.",
|
||||
|
||||
/* folders / files -------------------------------------------------- */
|
||||
"folder.nameRequired": "Give the folder a name.",
|
||||
|
|
@ -704,6 +775,13 @@ const en: Record<string, string> = {
|
|||
"file.documentTooLarge": "“{name}” is larger than 40 MB.",
|
||||
"import.notJson": "That file is not valid JSON.",
|
||||
"import.notDeck": "That file doesn't look like a Freezmo deck.",
|
||||
"import.notBackup": "That file doesn't look like a Freezmo backup.",
|
||||
"error.usageTitle": "Free monthly usage used up",
|
||||
"error.usageBody":
|
||||
"You've run out of your free monthly Ollama usage. Upgrade your Ollama account, or create a new one and use the new API key.",
|
||||
"error.openOllama": "Open Ollama",
|
||||
"error.throttledTitle": "Ollama is busy",
|
||||
"error.throttledBody": "Ollama is temporarily rate limiting requests. Try again in a moment.",
|
||||
"doc.readingPage": "Reading page {n} of {total}…",
|
||||
"doc.readingWord": "Reading the Word document…",
|
||||
"doc.readingSlides": "Reading the slides…",
|
||||
|
|
@ -801,6 +879,70 @@ const cs: Record<string, string> = {
|
|||
"settings.haptics": "Haptika",
|
||||
"settings.hapticsNote": "Vibrace na podporovaných telefonech.",
|
||||
|
||||
/* data, backup & sync --------------------------------------------- */
|
||||
"settings.data": "Data a záloha",
|
||||
"settings.dataNote": "Všechno je v tomto prohlížeči. Zálohuj pravidelně.",
|
||||
"settings.exportAll": "Exportovat všechna data",
|
||||
"settings.exportNote": "Sady, úkoly, pokrok a nastavení — nikdy tvůj API klíč.",
|
||||
"settings.importBackup": "Importovat zálohu",
|
||||
"settings.importPreview": "Záloha obsahuje {decks} sad, {homework} výsledků úkolů a {folders} složek.",
|
||||
"settings.importMergeNote": "Sloučení ponechá stávající data a přidá zálohu; stejná ID se nahradí.",
|
||||
"settings.importReplaceNote": "Nahrazení smaže data v tomto prohlížeči a použije zálohu.",
|
||||
"settings.importMerge": "Sloučit",
|
||||
"settings.importReplace": "Nahradit",
|
||||
"settings.importCancel": "Zrušit",
|
||||
"settings.importDone": "Importováno {decks} sad a {homework} výsledků úkolů.",
|
||||
"settings.importFailed": "Zálohu se nepodařilo importovat.",
|
||||
"settings.storage": "Úložiště",
|
||||
"settings.storagePersistent": "Trvalé — prohlížeč tvá data nesmaže.",
|
||||
"settings.storageBestEffort": "Dočasné — prohlížeč může data při nedostatku místa smazat.",
|
||||
"settings.storageRequest": "Požádat o trvalé úložiště",
|
||||
"settings.storageGranted": "Povoleno — data jsou teď trvalá.",
|
||||
"settings.storageDenied": "Prohlížeč odmítl. Pomůže nainstalovat aplikaci.",
|
||||
"settings.backupNudgeTitle": "Zálohovat sady?",
|
||||
"settings.backupNudgeBody": "Od poslední zálohy jsi přidal sady. Záloha je udrží v bezpečí.",
|
||||
"settings.backupNow": "Zálohovat teď",
|
||||
"settings.backupLater": "Teď ne",
|
||||
"settings.sync": "Synchronizace",
|
||||
"settings.syncNote":
|
||||
"Ve výchozím stavu vypnuto. Data se šifrují v tomto prohlížeči před odesláním — server ukládá jen neprůhledný blob a nikdy nevidí tvá data ani klíč.",
|
||||
"settings.syncEnable": "Zapnout synchronizaci",
|
||||
"settings.syncPassphrase": "Přístupová fráze",
|
||||
"settings.syncPassphraseConfirm": "Zopakuj přístupovou frázi",
|
||||
"settings.syncPassphraseMismatch": "Fráze se neshodují.",
|
||||
"settings.syncPassphraseShort": "Použij aspoň 8 znaků.",
|
||||
"settings.syncStart": "Začít synchronizovat",
|
||||
"settings.syncCancel": "Zrušit",
|
||||
"settings.syncId": "Sync ID",
|
||||
"settings.syncCopy": "Kopírovat",
|
||||
"settings.syncCopied": "Zkopírováno.",
|
||||
"settings.syncLast": "Naposledy synchronizováno {when}",
|
||||
"settings.syncNever": "Zatím nesynchronizováno.",
|
||||
"settings.syncNow": "Synchronizovat teď",
|
||||
"settings.syncWorking": "Synchronizuji…",
|
||||
"settings.syncDone": "Vše je aktuální.",
|
||||
"settings.syncPushed": "Nahráno z tohoto zařízení.",
|
||||
"settings.syncPulled": "Staženo ze synchronizované kopie.",
|
||||
"settings.syncConflict": "Toto zařízení i synchronizovaná kopie se změnily. Vyber, kterou ponechat.",
|
||||
"settings.syncKeepLocal": "Ponechat toto zařízení",
|
||||
"settings.syncKeepRemote": "Použít synchronizovanou kopii",
|
||||
"settings.syncJoin": "Připojit k jiné synchronizaci",
|
||||
"settings.syncJoinNote":
|
||||
"Zadej sync ID a přístupovou frázi z druhého zařízení. Data v tomto prohlížeči nahradí synchronizovaná kopie.",
|
||||
"settings.syncJoinId": "Sync ID",
|
||||
"settings.syncJoinAction": "Připojit",
|
||||
"settings.syncLocked": "Zadej přístupovou frázi a odemkni synchronizaci na tomto zařízení.",
|
||||
"settings.syncUnlock": "Odemknout",
|
||||
"settings.syncForget": "Zapomenout frázi na tomto zařízení",
|
||||
"settings.syncDelete": "Smazat synchronizovaná data",
|
||||
"settings.syncDeleteConfirm": "Smazat synchronizovanou kopii ze serveru? Data v tomto zařízení zůstanou.",
|
||||
"settings.syncDeleteYes": "Smazat",
|
||||
"settings.syncWrongPass": "Touhle frází se synchronizovaná kopie odemknout nedá.",
|
||||
"settings.syncError": "Synchronizace selhala. Zkontroluj připojení a zkus to znovu.",
|
||||
"settings.syncOff": "Synchronizace je vypnutá.",
|
||||
"settings.syncOn": "Synchronizace je zapnutá.",
|
||||
"settings.syncNoteKey": "Tvůj API klíč se nikdy nesynchronizuje.",
|
||||
|
||||
/* offline / share / toasts ---------------------------------------- */
|
||||
"offline.banner": "Jsi offline — uložené sady fungují dál.",
|
||||
"offline.generate": "Jsi offline — pro vytvoření se připoj.",
|
||||
|
|
@ -1343,6 +1485,13 @@ const cs: Record<string, string> = {
|
|||
"server.healthModelNoteLocal": "Není v seznamu modelů daemonu. Spusť `ollama pull {model}` nebo zkontroluj přihlášení.",
|
||||
"server.healthModelNoteCloud": "Není v odpovědi {url}/api/tags. Zkontroluj název modelu a tarif klíče.",
|
||||
"server.healthModelsMissing": "Ollama je dostupná, ale aspoň jeden nakonfigurovaný model není k dispozici.",
|
||||
"server.usageLimit":
|
||||
"Vyčerpal se tvůj měsíční limit Ollama zdarma. Upgraduj svůj účet Ollama, nebo si vytvoř nový a použij jeho nový API klíč.",
|
||||
"server.ollamaThrottled": "Ollama dočasně omezuje požadavky. Zkus to za chvíli znovu.",
|
||||
"server.syncInvalidId": "Tenhle sync ID nevypadá správně.",
|
||||
"server.syncTooLarge": "Tahle synchronizace je příliš velká.",
|
||||
"server.syncStorageFull": "Úložiště synchronizace je plné. Smaž nějaká synchronizovaná data a zkus to znovu.",
|
||||
"server.syncNotFound": "Pro tenhle ID nejsou žádná synchronizovaná data.",
|
||||
|
||||
/* folders / files -------------------------------------------------- */
|
||||
"folder.nameRequired": "Dej složce název.",
|
||||
|
|
@ -1354,6 +1503,13 @@ const cs: Record<string, string> = {
|
|||
"file.documentTooLarge": "„{name}“ je větší než 40 MB.",
|
||||
"import.notJson": "Tento soubor není platný JSON.",
|
||||
"import.notDeck": "Tento soubor nevypadá jako sada Freezmo.",
|
||||
"import.notBackup": "Tento soubor nevypadá jako záloha Freezmo.",
|
||||
"error.usageTitle": "Měsíční limit zdarma vyčerpán",
|
||||
"error.usageBody":
|
||||
"Vyčerpal se tvůj měsíční limit Ollama zdarma. Upgraduj svůj účet Ollama, nebo si vytvoř nový a použij jeho nový API klíč.",
|
||||
"error.openOllama": "Otevřít Ollamu",
|
||||
"error.throttledTitle": "Ollama je zaneprázdněná",
|
||||
"error.throttledBody": "Ollama dočasně omezuje požadavky. Zkus to za chvíli znovu.",
|
||||
"doc.readingPage": "Čtu stranu {n} z {total}…",
|
||||
"doc.readingWord": "Čtu dokument Word…",
|
||||
"doc.readingSlides": "Čtu snímky…",
|
||||
|
|
|
|||
24
lib/model-errors.ts
Normal file
24
lib/model-errors.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
"use client";
|
||||
|
||||
/**
|
||||
* Copy for the two Ollama failure modes the user can actually do something
|
||||
* about: the free monthly usage being used up (upgrade / new key) and
|
||||
* short-term throttling (just retry). Every flow that calls the model uses
|
||||
* this so the message is identical everywhere.
|
||||
*/
|
||||
|
||||
import { t } from "./i18n";
|
||||
|
||||
export const OLLAMA_SETTINGS_URL = "https://ollama.com/settings";
|
||||
|
||||
export type ModelErrorCopy = { title: string; body: string };
|
||||
|
||||
export function modelErrorCopy(kind: string | undefined): ModelErrorCopy | null {
|
||||
if (kind === "usage_limit") {
|
||||
return { title: t("error.usageTitle"), body: t("error.usageBody") };
|
||||
}
|
||||
if (kind === "throttled") {
|
||||
return { title: t("error.throttledTitle"), body: t("error.throttledBody") };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -24,10 +24,28 @@ export type OllamaErrorKind =
|
|||
| "timeout"
|
||||
| "auth"
|
||||
| "no_credits"
|
||||
/** The free monthly Ollama usage is used up — only the user can fix this. */
|
||||
| "usage_limit"
|
||||
/** Ollama is throttling short-term requests; retrying soon usually works. */
|
||||
| "throttled"
|
||||
| "model_missing"
|
||||
| "http"
|
||||
| "bad_response";
|
||||
|
||||
/**
|
||||
* Ollama reports two very different things with HTTP 429:
|
||||
* - the free monthly usage is exhausted ("upgrade", "quota", "monthly …")
|
||||
* - a short-term rate limit ("too many requests", "try again …")
|
||||
* The body is the only signal, so classify it (kept pure for testing).
|
||||
*/
|
||||
const USAGE_LIMIT_PATTERN =
|
||||
/(monthly|per month|this month|quota|usage limit|limit reached|free (plan|tier|usage)|upgrade|billing|subscribe|exceeded your)/i;
|
||||
|
||||
export function classifyOllamaFailure(status: number, body: string): "usage_limit" | "throttled" | null {
|
||||
if (status !== 429) return null;
|
||||
return USAGE_LIMIT_PATTERN.test(body) ? "usage_limit" : "throttled";
|
||||
}
|
||||
|
||||
export class OllamaError extends Error {
|
||||
kind: OllamaErrorKind;
|
||||
status?: number;
|
||||
|
|
@ -57,6 +75,10 @@ export function friendlyErrorMessage(
|
|||
return translate(locale, "server.ollamaTimeout");
|
||||
case "auth":
|
||||
return translate(locale, "server.ollamaAuth");
|
||||
case "usage_limit":
|
||||
return translate(locale, "server.usageLimit");
|
||||
case "throttled":
|
||||
return translate(locale, "server.ollamaThrottled");
|
||||
case "no_credits":
|
||||
return error.message;
|
||||
case "model_missing":
|
||||
|
|
@ -166,6 +188,20 @@ export async function ollamaChat(options: ChatOptions): Promise<ChatResult> {
|
|||
{ status: response.status, detail: text.slice(0, 500) },
|
||||
);
|
||||
}
|
||||
if (response.status === 429) {
|
||||
if (classifyOllamaFailure(response.status, text) === "usage_limit") {
|
||||
throw new OllamaError(
|
||||
"usage_limit",
|
||||
"Your free monthly Ollama usage has run out. Upgrade your Ollama account, or create a new one and use the new API key.",
|
||||
{ status: response.status, detail: text.slice(0, 500) },
|
||||
);
|
||||
}
|
||||
throw new OllamaError(
|
||||
"throttled",
|
||||
"Ollama is temporarily rate limiting requests. Try again in a moment.",
|
||||
{ status: response.status, detail: text.slice(0, 500) },
|
||||
);
|
||||
}
|
||||
throw new OllamaError(
|
||||
"http",
|
||||
`Ollama responded with HTTP ${response.status}.`,
|
||||
|
|
@ -256,7 +292,7 @@ export async function ollamaListModels(auth: OllamaAuth, timeoutMs?: number): Pr
|
|||
export type KeyProbe = {
|
||||
/** true = accepted, false = rejected, null = could not tell. */
|
||||
valid: boolean | null;
|
||||
reason?: "invalid" | "no_credits" | "model_missing" | "unreachable";
|
||||
reason?: "invalid" | "no_credits" | "usage_limit" | "throttled" | "model_missing" | "unreachable";
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
|
|
@ -316,7 +352,14 @@ export async function ollamaVerifyKey(auth: OllamaAuth, model: string, timeoutMs
|
|||
else if (response.status === 401 || response.status === 403) probe = { valid: false, reason: "invalid", detail };
|
||||
else if (response.status === 402) probe = { valid: true, reason: "no_credits", detail };
|
||||
else if (response.status === 404) probe = { valid: null, reason: "model_missing", detail };
|
||||
else probe = { valid: null, detail: `HTTP ${response.status}` };
|
||||
else if (response.status === 429) {
|
||||
// The key itself is fine; the account is either out of monthly usage or
|
||||
// being throttled for a moment.
|
||||
probe =
|
||||
classifyOllamaFailure(response.status, detail) === "usage_limit"
|
||||
? { valid: true, reason: "usage_limit", detail }
|
||||
: { valid: null, reason: "throttled", detail };
|
||||
} else probe = { valid: null, detail: `HTTP ${response.status}` };
|
||||
|
||||
probeCache.set(cacheKey, { ...probe, at: Date.now() });
|
||||
return probe;
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
import { t } from "./i18n";
|
||||
import { deckSchema, UNORGANIZED_ID, type Activity, type Deck } from "./schemas";
|
||||
import { createFolder, findFolderByName, getFolder, removeFolder } from "./folders";
|
||||
import { markSyncDirty } from "./sync-state";
|
||||
import { uid } from "./utils";
|
||||
|
||||
const STORAGE_KEY = "freezmo.decks.v1";
|
||||
|
|
@ -53,9 +54,21 @@ function write(next: Deck[]): void {
|
|||
} catch (error) {
|
||||
console.warn("[freezmo] could not save the deck library (storage full?)", error);
|
||||
}
|
||||
markSyncDirty();
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
/** Used by backup import and sync: wholesale replacement of the library. */
|
||||
export function replaceDecks(next: Deck[]): void {
|
||||
const valid: Deck[] = [];
|
||||
for (const entry of next) {
|
||||
const result = deckSchema.safeParse(entry);
|
||||
if (result.success) valid.push(result.data);
|
||||
else console.warn("[freezmo] skipping invalid deck in import", result.error.issues);
|
||||
}
|
||||
write(valid);
|
||||
}
|
||||
|
||||
export const deckStore = {
|
||||
subscribe(listener: Listener): () => void {
|
||||
ensureLoaded();
|
||||
|
|
|
|||
63
lib/sync-key.ts
Normal file
63
lib/sync-key.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
"use client";
|
||||
|
||||
/**
|
||||
* The derived sync key is kept in IndexedDB as a **non-extractable**
|
||||
* CryptoKey: it can encrypt/decrypt for this origin but its raw bytes can
|
||||
* never be read out (not even by a script that got in). If the browser
|
||||
* doesn't allow that, syncing asks for the passphrase again instead.
|
||||
*/
|
||||
|
||||
const DB_NAME = "freezmo-sync";
|
||||
const STORE = "keys";
|
||||
const KEY_ID = "device-key";
|
||||
|
||||
function openDb(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DB_NAME, 1);
|
||||
request.onupgradeneeded = () => {
|
||||
request.result.createObjectStore(STORE);
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
async function withStore<T>(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
|
||||
const db = await openDb();
|
||||
try {
|
||||
return await new Promise<T>((resolve, reject) => {
|
||||
const transaction = db.transaction(STORE, mode);
|
||||
const request = run(transaction.objectStore(STORE));
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveDeviceKey(key: CryptoKey): Promise<boolean> {
|
||||
try {
|
||||
await withStore("readwrite", (store) => store.put(key, KEY_ID));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadDeviceKey(): Promise<CryptoKey | null> {
|
||||
try {
|
||||
const key = await withStore<CryptoKey | undefined>("readonly", (store) => store.get(KEY_ID));
|
||||
return key ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function clearDeviceKey(): Promise<void> {
|
||||
try {
|
||||
await withStore("readwrite", (store) => store.delete(KEY_ID));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
136
lib/sync-state.ts
Normal file
136
lib/sync-state.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
"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("");
|
||||
}
|
||||
329
lib/sync.ts
Normal file
329
lib/sync.ts
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
"use client";
|
||||
|
||||
/**
|
||||
* Opt-in encrypted sync. The payload (decks, folders, homework — never the
|
||||
* API key) is encrypted in this browser with AES-GCM using a key derived from
|
||||
* the user's passphrase (PBKDF2-SHA256, 310k iterations). The server only
|
||||
* ever stores the opaque envelope under a random sync ID.
|
||||
*
|
||||
* Conflict policy: server-stamped `updatedAt` is the clock; when both sides
|
||||
* changed since the last sync the UI asks the user which one to keep.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { backupDataSchema } from "./backup";
|
||||
import { ApiError } from "./client-api";
|
||||
import { replaceFolders } from "./folders";
|
||||
import { replaceHomework } from "./homework";
|
||||
import { localeHeader, t } from "./i18n";
|
||||
import { authHeaders } from "./settings";
|
||||
import { deckStore, replaceDecks } from "./storage";
|
||||
import { homeworkStore } from "./homework";
|
||||
import { folderStore } from "./folders";
|
||||
import { clearDeviceKey, loadDeviceKey, saveDeviceKey } from "./sync-key";
|
||||
import { newSyncId, setSyncRecord, syncStore, withoutDirtyTracking } from "./sync-state";
|
||||
|
||||
const KDF = "PBKDF2-SHA256";
|
||||
const ITERATIONS = 310_000;
|
||||
|
||||
export type SyncEnvelope = {
|
||||
v: 1;
|
||||
kdf: "PBKDF2-SHA256";
|
||||
iterations: number;
|
||||
salt: string;
|
||||
iv: string;
|
||||
ciphertext: string;
|
||||
};
|
||||
|
||||
export type SyncStatus = "pushed" | "pulled" | "up-to-date" | "conflict" | "locked" | "error" | "off";
|
||||
export type SyncOutcome = { status: SyncStatus; message?: string };
|
||||
|
||||
const syncPayloadSchema = z.object({
|
||||
app: z.literal("freezmo"),
|
||||
kind: z.literal("sync"),
|
||||
version: z.literal(1),
|
||||
clientUpdatedAt: z.number(),
|
||||
data: backupDataSchema,
|
||||
});
|
||||
|
||||
type SyncPayload = z.infer<typeof syncPayloadSchema>;
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Encoding helpers (chunked: payloads can be megabytes) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function toBase64(bytes: Uint8Array): string {
|
||||
let binary = "";
|
||||
const chunk = 0x8000;
|
||||
for (let index = 0; index < bytes.length; index += chunk) {
|
||||
binary += String.fromCharCode(...bytes.subarray(index, index + chunk));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
function fromBase64(value: string): Uint8Array {
|
||||
const binary = atob(value);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Crypto */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export async function deriveSyncKey(passphrase: string, saltBase64: string): Promise<CryptoKey> {
|
||||
const material = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
new TextEncoder().encode(passphrase),
|
||||
"PBKDF2",
|
||||
false,
|
||||
["deriveKey"],
|
||||
);
|
||||
return crypto.subtle.deriveKey(
|
||||
{ name: "PBKDF2", salt: fromBase64(saltBase64) as unknown as BufferSource, iterations: ITERATIONS, hash: "SHA-256" },
|
||||
material,
|
||||
{ name: "AES-GCM", length: 256 },
|
||||
false,
|
||||
["encrypt", "decrypt"],
|
||||
);
|
||||
}
|
||||
|
||||
async function encryptWithKey(key: CryptoKey, payload: unknown): Promise<{ iv: string; ciphertext: string }> {
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const encoded = new TextEncoder().encode(JSON.stringify(payload));
|
||||
const cipher = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, encoded);
|
||||
return { iv: toBase64(iv), ciphertext: toBase64(new Uint8Array(cipher)) };
|
||||
}
|
||||
|
||||
async function decryptWithKey(key: CryptoKey, ivBase64: string, ciphertextBase64: string): Promise<unknown> {
|
||||
const plain = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: fromBase64(ivBase64) as unknown as BufferSource },
|
||||
key,
|
||||
fromBase64(ciphertextBase64) as unknown as BufferSource,
|
||||
);
|
||||
return JSON.parse(new TextDecoder().decode(plain));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Server API */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function apiGet(id: string): Promise<{ updatedAt: number; envelope: SyncEnvelope } | null> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`/api/sync?id=${encodeURIComponent(id)}`, {
|
||||
cache: "no-store",
|
||||
headers: { ...authHeaders(), ...localeHeader() },
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(t("settings.syncError"), "network");
|
||||
}
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) {
|
||||
const body = (await response.json().catch(() => null)) as { error?: string } | null;
|
||||
throw new ApiError(body?.error ?? t("settings.syncError"), "sync");
|
||||
}
|
||||
return (await response.json()) as { updatedAt: number; envelope: SyncEnvelope };
|
||||
}
|
||||
|
||||
async function apiPut(id: string, envelope: SyncEnvelope): Promise<number> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch("/api/sync", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...authHeaders(), ...localeHeader() },
|
||||
body: JSON.stringify({ id, envelope }),
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(t("settings.syncError"), "network");
|
||||
}
|
||||
if (!response.ok) {
|
||||
const body = (await response.json().catch(() => null)) as { error?: string } | null;
|
||||
throw new ApiError(body?.error ?? t("settings.syncError"), "sync");
|
||||
}
|
||||
const body = (await response.json()) as { updatedAt: number };
|
||||
return body.updatedAt;
|
||||
}
|
||||
|
||||
async function apiDelete(id: string): Promise<void> {
|
||||
const response = await fetch(`/api/sync?id=${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
headers: { ...authHeaders(), ...localeHeader() },
|
||||
});
|
||||
if (!response.ok) throw new ApiError(t("settings.syncError"), "sync");
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Payload */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function buildPayload(): SyncPayload {
|
||||
return {
|
||||
app: "freezmo",
|
||||
kind: "sync",
|
||||
version: 1,
|
||||
clientUpdatedAt: Date.now(),
|
||||
data: {
|
||||
decks: deckStore.getSnapshot(),
|
||||
folders: folderStore.getSnapshot(),
|
||||
homework: homeworkStore.getSnapshot(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function applyRemote(key: CryptoKey, remote: { updatedAt: number; envelope: SyncEnvelope }): Promise<void> {
|
||||
const parsed = syncPayloadSchema.parse(
|
||||
await decryptWithKey(key, remote.envelope.iv, remote.envelope.ciphertext),
|
||||
);
|
||||
withoutDirtyTracking(() => {
|
||||
replaceFolders(parsed.data.folders);
|
||||
replaceDecks(parsed.data.decks);
|
||||
replaceHomework(parsed.data.homework);
|
||||
});
|
||||
setSyncRecord({ lastSyncedAt: remote.updatedAt, dirtyAt: null, conflict: false });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Public API */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export async function syncNow(strategy: "auto" | "push" | "pull" = "auto"): Promise<SyncOutcome> {
|
||||
const record = syncStore.getSnapshot();
|
||||
if (!record.enabled || !record.id) return { status: "off" };
|
||||
const key = await loadDeviceKey();
|
||||
if (!key) return { status: "locked" };
|
||||
|
||||
try {
|
||||
const remote = await apiGet(record.id);
|
||||
const remoteIsNewer = Boolean(remote && remote.updatedAt > (record.lastSyncedAt ?? 0));
|
||||
|
||||
if (strategy === "pull") {
|
||||
if (!remote) return { status: "error", message: t("server.syncNotFound") };
|
||||
await applyRemote(key, remote);
|
||||
return { status: "pulled" };
|
||||
}
|
||||
|
||||
if (strategy === "auto" && remoteIsNewer) {
|
||||
if (record.dirtyAt) {
|
||||
setSyncRecord({ conflict: true });
|
||||
return { status: "conflict" };
|
||||
}
|
||||
await applyRemote(key, remote!);
|
||||
return { status: "pulled" };
|
||||
}
|
||||
|
||||
if (strategy === "auto" && !remoteIsNewer && !record.dirtyAt) {
|
||||
return { status: "up-to-date" };
|
||||
}
|
||||
|
||||
const { iv, ciphertext } = await encryptWithKey(key, buildPayload());
|
||||
const envelope: SyncEnvelope = {
|
||||
v: 1,
|
||||
kdf: KDF,
|
||||
iterations: ITERATIONS,
|
||||
salt: record.salt,
|
||||
iv,
|
||||
ciphertext,
|
||||
};
|
||||
const updatedAt = await apiPut(record.id, envelope);
|
||||
setSyncRecord({ lastSyncedAt: updatedAt, dirtyAt: null, conflict: false });
|
||||
return { status: "pushed" };
|
||||
} catch (error) {
|
||||
return {
|
||||
status: "error",
|
||||
message: error instanceof ApiError ? error.message : t("settings.syncError"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** First device: brand-new id and salt, uploads straight away. */
|
||||
export async function enableSync(passphrase: string): Promise<SyncOutcome> {
|
||||
const id = newSyncId();
|
||||
const salt = toBase64(crypto.getRandomValues(new Uint8Array(16)));
|
||||
const key = await deriveSyncKey(passphrase, salt);
|
||||
await saveDeviceKey(key);
|
||||
setSyncRecord({ enabled: true, id, salt, lastSyncedAt: null, dirtyAt: Date.now(), conflict: false });
|
||||
return syncNow("push");
|
||||
}
|
||||
|
||||
/** Same device after the browser dropped the stored key. */
|
||||
export async function unlockSync(passphrase: string): Promise<SyncOutcome> {
|
||||
const record = syncStore.getSnapshot();
|
||||
if (!record.enabled || !record.id) return { status: "off" };
|
||||
try {
|
||||
const remote = await apiGet(record.id);
|
||||
const salt = remote?.envelope.salt || record.salt;
|
||||
if (!salt) return { status: "error", message: t("settings.syncError") };
|
||||
const key = await deriveSyncKey(passphrase, salt);
|
||||
if (remote) {
|
||||
try {
|
||||
syncPayloadSchema.parse(await decryptWithKey(key, remote.envelope.iv, remote.envelope.ciphertext));
|
||||
} catch {
|
||||
return { status: "error", message: t("settings.syncWrongPass") };
|
||||
}
|
||||
}
|
||||
await saveDeviceKey(key);
|
||||
setSyncRecord({ salt });
|
||||
return syncNow("auto");
|
||||
} catch (error) {
|
||||
return {
|
||||
status: "error",
|
||||
message: error instanceof ApiError ? error.message : t("settings.syncError"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** New device: the sync ID plus the passphrase from the other device. */
|
||||
export async function joinSync(id: string, passphrase: string): Promise<SyncOutcome> {
|
||||
try {
|
||||
const remote = await apiGet(id.trim());
|
||||
if (!remote) return { status: "error", message: t("server.syncNotFound") };
|
||||
const key = await deriveSyncKey(passphrase, remote.envelope.salt);
|
||||
try {
|
||||
syncPayloadSchema.parse(await decryptWithKey(key, remote.envelope.iv, remote.envelope.ciphertext));
|
||||
} catch {
|
||||
return { status: "error", message: t("settings.syncWrongPass") };
|
||||
}
|
||||
await saveDeviceKey(key);
|
||||
setSyncRecord({
|
||||
enabled: true,
|
||||
id: id.trim(),
|
||||
salt: remote.envelope.salt,
|
||||
lastSyncedAt: null,
|
||||
dirtyAt: null,
|
||||
conflict: false,
|
||||
});
|
||||
await applyRemote(key, remote);
|
||||
return { status: "pulled" };
|
||||
} catch (error) {
|
||||
return {
|
||||
status: "error",
|
||||
message: error instanceof ApiError ? error.message : t("settings.syncError"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteSyncedData(): Promise<SyncOutcome> {
|
||||
const record = syncStore.getSnapshot();
|
||||
try {
|
||||
if (record.id) await apiDelete(record.id);
|
||||
} catch (error) {
|
||||
return {
|
||||
status: "error",
|
||||
message: error instanceof ApiError ? error.message : t("settings.syncError"),
|
||||
};
|
||||
}
|
||||
await clearDeviceKey();
|
||||
setSyncRecord({ enabled: false, id: "", salt: "", lastSyncedAt: null, dirtyAt: null, conflict: false });
|
||||
return { status: "up-to-date" };
|
||||
}
|
||||
|
||||
export async function forgetDeviceKey(): Promise<void> {
|
||||
await clearDeviceKey();
|
||||
}
|
||||
|
||||
export async function hasDeviceKey(): Promise<boolean> {
|
||||
return Boolean(await loadDeviceKey());
|
||||
}
|
||||
|
|
@ -7,7 +7,10 @@
|
|||
|
||||
export const OPEN_SETTINGS_EVENT = "freezmo:open-settings";
|
||||
|
||||
export function openSettings(): void {
|
||||
export type SettingsFocus = "key";
|
||||
|
||||
/** `focus` scrolls the settings dialog to that field once it opens. */
|
||||
export function openSettings(focus?: SettingsFocus): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.dispatchEvent(new CustomEvent(OPEN_SETTINGS_EVENT));
|
||||
window.dispatchEvent(new CustomEvent(OPEN_SETTINGS_EVENT, { detail: { focus } }));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue