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

View file

@ -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;