freezmo/app/api/sync/route.ts
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

196 lines
6.4 KiB
TypeScript

import { promises as fs } from "node:fs";
import path from "node:path";
import { z } from "zod";
import { authErrorKind, authErrorMessage, getServerConfig, resolveAuth } from "@/lib/config";
import { rejectCrossOrigin, rejectOversizedBody, requestLocale } from "@/lib/http-guard";
import { translate } from "@/lib/i18n-dict";
import { clientKey, rateLimit, rateLimitResponse } from "@/lib/rate-limit";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* Opt-in encrypted sync storage. The server only ever sees:
* - a random sync ID (the capability)
* - an opaque AES-GCM envelope (salt, iv, ciphertext) and a server timestamp
* It cannot read the data and never receives the passphrase or API key.
*/
const idSchema = z.string().regex(/^[A-Za-z0-9_-]{16,64}$/);
const envelopeSchema = z.object({
v: z.literal(1),
kdf: z.literal("PBKDF2-SHA256"),
iterations: z.number().int().min(50_000).max(2_000_000),
salt: z.string().min(8).max(128),
iv: z.string().min(8).max(64),
ciphertext: z.string().min(1).max(24_000_000),
});
const postSchema = z.object({ id: idSchema, envelope: envelopeSchema });
function fileFor(dir: string, id: string): string {
return path.join(dir, `${id}.json`);
}
async function writeAtomic(file: string, data: string): Promise<void> {
await fs.mkdir(path.dirname(file), { recursive: true });
const temporary = `${file}.${crypto.randomUUID()}.tmp`;
await fs.writeFile(temporary, data, "utf8");
await fs.rename(temporary, file);
}
/** Size of all stored blobs except `exclude` (the one being replaced). */
async function directoryBytes(dir: string, exclude: string): Promise<number> {
let total = 0;
try {
for (const entry of await fs.readdir(dir)) {
if (!entry.endsWith(".json")) continue;
const full = path.join(dir, entry);
if (full === exclude) continue;
try {
total += (await fs.stat(full)).size;
} catch {
/* deleted meanwhile */
}
}
} catch {
/* directory doesn't exist yet */
}
return total;
}
export async function GET(request: Request) {
const locale = requestLocale(request);
const crossOrigin = rejectCrossOrigin(request);
if (crossOrigin) return crossOrigin;
const config = getServerConfig();
const limit = rateLimit(`sync:${clientKey(request)}`, config.rateLimits.sync, config.rateLimits.windowMs);
if (!limit.allowed) return rateLimitResponse(limit, locale);
const auth = resolveAuth(config, request);
if ("error" in auth) {
return Response.json(
{ error: authErrorMessage(locale, auth.error), kind: authErrorKind(auth.error) },
{ status: 401 },
);
}
const id = new URL(request.url).searchParams.get("id") ?? "";
if (!idSchema.safeParse(id).success) {
return Response.json(
{ error: translate(locale, "server.syncInvalidId") },
{ status: 400, headers: { "Cache-Control": "no-store" } },
);
}
try {
const raw = await fs.readFile(fileFor(config.sync.dir, id), "utf8");
return new Response(raw, {
status: 200,
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
});
} catch {
return Response.json(
{ error: translate(locale, "server.syncNotFound") },
{ status: 404, headers: { "Cache-Control": "no-store" } },
);
}
}
export async function POST(request: Request) {
const locale = requestLocale(request);
const crossOrigin = rejectCrossOrigin(request);
if (crossOrigin) return crossOrigin;
const config = getServerConfig();
const oversized = rejectOversizedBody(request, config.sync.maxBytes);
if (oversized) return oversized;
const limit = rateLimit(`sync:${clientKey(request)}`, config.rateLimits.sync, config.rateLimits.windowMs);
if (!limit.allowed) return rateLimitResponse(limit, locale);
// Auth before parsing the body, like every other route.
const auth = resolveAuth(config, request);
if ("error" in auth) {
return Response.json(
{ error: authErrorMessage(locale, auth.error), kind: authErrorKind(auth.error) },
{ status: 401 },
);
}
let payload: unknown;
try {
payload = await request.json();
} catch {
return Response.json({ error: translate(locale, "server.bodyNotJson") }, { status: 400 });
}
const parsed = postSchema.safeParse(payload);
if (!parsed.success) {
return Response.json(
{
error: translate(locale, "server.invalidRequest", {
detail: parsed.error.issues
.slice(0, 3)
.map((issue) => `${issue.path.join(".") || "body"} ${issue.message}`)
.join("; "),
}),
},
{ status: 400 },
);
}
const file = fileFor(config.sync.dir, parsed.data.id);
const serialised = JSON.stringify({ updatedAt: Date.now(), envelope: parsed.data.envelope });
// Total storage cap, checked only when a new blob is created.
const exists = await fs
.stat(file)
.then(() => true)
.catch(() => false);
if (!exists) {
const used = await directoryBytes(config.sync.dir, file);
if (used + serialised.length > config.sync.totalBytes) {
return Response.json(
{ error: translate(locale, "server.syncStorageFull"), kind: "storage_full" },
{ status: 507 },
);
}
}
await writeAtomic(file, serialised);
const updatedAt = (JSON.parse(serialised) as { updatedAt: number }).updatedAt;
return Response.json({ updatedAt }, { headers: { "Cache-Control": "no-store" } });
}
export async function DELETE(request: Request) {
const locale = requestLocale(request);
const crossOrigin = rejectCrossOrigin(request);
if (crossOrigin) return crossOrigin;
const config = getServerConfig();
const limit = rateLimit(`sync:${clientKey(request)}`, config.rateLimits.sync, config.rateLimits.windowMs);
if (!limit.allowed) return rateLimitResponse(limit, locale);
const auth = resolveAuth(config, request);
if ("error" in auth) {
return Response.json(
{ error: authErrorMessage(locale, auth.error), kind: authErrorKind(auth.error) },
{ status: 401 },
);
}
const id = new URL(request.url).searchParams.get("id") ?? "";
if (!idSchema.safeParse(id).success) {
return Response.json(
{ error: translate(locale, "server.syncInvalidId") },
{ status: 400, headers: { "Cache-Control": "no-store" } },
);
}
await fs.unlink(fileFor(config.sync.dir, id)).catch(() => {});
return Response.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });
}