feat(persistence): bidirectional local/cloud story sync (Supabase)

Connect the previously-skeleton cloudStore to the client with a full
bidirectional reconcile engine. Commercial build (AUTH_ENABLED) only; the
open-source build is byte-for-byte unchanged — all cloud paths short-circuit
when AUTH_ENABLED is false.

- cloudSync.ts: reconcile engine — decideAction (pure, LWW rev->updatedAt with
  tombstone priority) + syncOnLogin/pushOnSave/pushDeletion (best-effort,
  serialized, isAuthed-gated)
- cloudSyncClient.ts: browser fetch bridge (short-circuit + fault-tolerant)
- /api/stories/{manifest,pull,push,delete}: RLS-guarded sync endpoints
- upsert_story_if_newer RPC: optimistic concurrency (SECURITY INVOKER,
  auth.uid() injection, rev->updated_at guard, revoked from public)
- cloudStore: +manifest/pullBlobs, save->RPC {stored,won}, softDelete w/ rev
- localStore: +listAllRecordsForSync/putSyncedRecord/markRecordSynced
  (concurrency-guarded sync writes); types: +StorySyncMeta/StorySyncEnvelope
- facade + UserChip: inject pushOnSave/pushDeletion + login-triggered reconcile

Sync model: full reconcile on login + background push on save (no Realtime;
eventual consistency). Conflict resolution: last-write-wins.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Kai ki
2026-06-28 11:20:47 +08:00
parent da74e3e763
commit ff12b2759f
12 changed files with 824 additions and 66 deletions
+32
View File
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server";
import { requireUser } from "@/lib/supabase/guard";
import { cloudSoftDeleteStory } from "@/lib/persistence/cloudStore";
import { coerceEpoch } from "@/lib/persistence/types";
export const runtime = "nodejs";
// POST /api/stories/delete — body { id, rev, deletedAt } → { ok }. Propagates a
// soft-delete (tombstone) under the same optimistic-concurrency guard as push.
// requireUser 401s an unauthenticated commercial caller; on the open-source
// build cloudSoftDeleteStory short-circuits to false.
export async function POST(req: Request) {
const auth = await requireUser();
if (auth instanceof NextResponse) return auth;
let body: { id?: unknown; rev?: unknown; deletedAt?: unknown };
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "invalid json" }, { status: 400 });
}
const id = typeof body.id === "string" ? body.id : "";
if (!id) {
return NextResponse.json({ error: "missing id" }, { status: 400 });
}
const rev = typeof body.rev === "number" ? body.rev : 1;
const deletedAt = coerceEpoch(body.deletedAt, Date.now());
const ok = await cloudSoftDeleteStory(id, rev, deletedAt);
return NextResponse.json({ ok });
}
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { requireUser } from "@/lib/supabase/guard";
import { cloudStoryManifest } from "@/lib/persistence/cloudStore";
export const runtime = "nodejs";
// GET /api/stories/manifest — the reconcile diff basis: every cloud row for the
// signed-in user (INCLUDING tombstones), projected to {id, rev, updatedAt,
// deletedAt} without the bulky session_jsonb. Pure passthrough to cloudStore;
// requireUser 401s an unauthenticated commercial-build caller, and on the
// open-source build (AUTH_ENABLED=false) cloudStoryManifest short-circuits to []
// without ever constructing a Supabase client.
export async function GET() {
const auth = await requireUser();
if (auth instanceof NextResponse) return auth;
const items = await cloudStoryManifest();
return NextResponse.json({ items });
}
+33
View File
@@ -0,0 +1,33 @@
import { NextResponse } from "next/server";
import { requireUser } from "@/lib/supabase/guard";
import { cloudPullBlobs } from "@/lib/persistence/cloudStore";
export const runtime = "nodejs";
// Cap per request — reconcile chunks its pull set, so one call never asks for an
// unbounded id list (a denial-of-wallet / oversized-response guard).
const MAX_PULL_IDS = 200;
// POST /api/stories/pull — body { ids: string[] } → { blobs: StorySyncEnvelope[] }
// (full payloads, INCLUDING tombstones, for write-back into the local store).
// Pure passthrough to cloudStore; same auth/short-circuit story as manifest.
export async function POST(req: Request) {
const auth = await requireUser();
if (auth instanceof NextResponse) return auth;
let body: { ids?: unknown };
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "invalid json" }, { status: 400 });
}
const ids = Array.isArray(body.ids)
? body.ids
.filter((x): x is string => typeof x === "string" && x.length > 0)
.slice(0, MAX_PULL_IDS)
: [];
const blobs = await cloudPullBlobs(ids);
return NextResponse.json({ blobs });
}
+51
View File
@@ -0,0 +1,51 @@
import { NextResponse } from "next/server";
import { coerceOrientation } from "@infiplot/types";
import { requireUser } from "@/lib/supabase/guard";
import { cloudSaveStory } from "@/lib/persistence/cloudStore";
import { coerceEpoch, type StorySyncEnvelope } from "@/lib/persistence/types";
export const runtime = "nodejs";
// Matches story-pack's 12 MB doc ceiling — a slim Session (voice +
// styleReferenceImage stripped) is far smaller, so this only rejects
// pathological payloads, never normal saves.
const MAX_PUSH_BYTES = 12_000_000;
// POST /api/stories/push — body StorySyncEnvelope → { stored, won }. Pure
// passthrough to the optimistic-concurrency RPC; won=false means a newer cloud
// row was preserved. requireUser 401s an unauthenticated commercial caller; on
// the open-source build cloudSaveStory short-circuits to { stored:null, won:false }.
export async function POST(req: Request) {
const auth = await requireUser();
if (auth instanceof NextResponse) return auth;
let raw: string;
try {
raw = await req.text();
} catch {
return NextResponse.json({ error: "invalid body" }, { status: 400 });
}
if (Buffer.byteLength(raw, "utf8") > MAX_PUSH_BYTES) {
return NextResponse.json({ error: "payload too large" }, { status: 413 });
}
let env: StorySyncEnvelope;
try {
env = JSON.parse(raw) as StorySyncEnvelope;
} catch {
return NextResponse.json({ error: "invalid json" }, { status: 400 });
}
if (!env?.id || typeof env.id !== "string") {
return NextResponse.json({ error: "missing id" }, { status: 400 });
}
// Defensive coercion at the trust boundary (the slim session itself is left to
// the client — it's reconstructible and never security-sensitive after slim).
const result = await cloudSaveStory({
...env,
orientation: coerceOrientation(env.orientation),
updatedAt: coerceEpoch(env.updatedAt, Date.now()),
deletedAt: env.deletedAt == null ? null : coerceEpoch(env.deletedAt, Date.now()),
});
return NextResponse.json(result);
}