The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Sharing: read-only share links with a public page, a share-scoped files route and a guarded proxy
Claude90abab348055
diff --git a/src/app/api/files/[...path]/route.ts b/src/app/api/files/[...path]/route.tsindex ee5dda27..f6a7e920 100644--- a/src/app/api/files/[...path]/route.ts+++ b/src/app/api/files/[...path]/route.ts@@ -1,40 +1,12 @@-import fs from "node:fs";-import { absolutePath, contentTypeFor } from "@/server/storage";+import { fileResponse } from "@/server/file-response";export async function GET(request: Request, ctx: RouteContext<"/api/files/[...path]">) {const { path: parts } = await ctx.params;- let abs: string;+ let rel: string;try {- abs = absolutePath(parts.map(decodeURIComponent).join("/"));+ rel = parts.map(decodeURIComponent).join("/");} catch {return new Response("Bad path", { status: 400 });}- if (!fs.existsSync(abs)) return new Response("Not found", { status: 404 });- const size = fs.statSync(abs).size;- const type = contentTypeFor(abs);- const headers: Record<string, string> = {- // Transcripts, subtitles and scripts are UTF-8 text.- "Content-Type": /^text\/|^application\/(json|x-subrip)$/.test(type) ? `${type}; charset=utf-8` : type,- "Accept-Ranges": "bytes",- "Cache-Control": "private, max-age=31536000, immutable",- "X-Content-Type-Options": "nosniff",- };- if (type === "image/svg+xml") headers["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'";- const download = new URL(request.url).searchParams.get("download");- if (download) headers["Content-Disposition"] = `attachment; filename="${download.replace(/[^\w.-]/g, "_")}"`;- const range = request.headers.get("range");- const m = range && /bytes=(\d*)-(\d*)/.exec(range);- if (m) {- const start = m[1] ? Number(m[1]) : Math.max(0, size - Number(m[2]));- const end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : size - 1;- if (start >= size || start > end) return new Response(null, { status: 416, headers: { "Content-Range": `bytes */${size}` } });- const stream = fs.createReadStream(abs, { start, end });- return new Response(stream as unknown as ReadableStream, {- status: 206,- headers: { ...headers, "Content-Range": `bytes ${start}-${end}/${size}`, "Content-Length": String(end - start + 1) },- });- }- return new Response(fs.createReadStream(abs) as unknown as ReadableStream, {- headers: { ...headers, "Content-Length": String(size) },- });+ return fileResponse(request, rel);}diff --git a/src/app/api/shares/[id]/route.ts b/src/app/api/shares/[id]/route.tsnew file mode 100644index 00000000..9b34879e--- /dev/null+++ b/src/app/api/shares/[id]/route.ts@@ -0,0 +1,43 @@+import { connection } from "next/server";+import { z } from "zod";+import { MAX_EXPIRY_DAYS } from "@/lib/share";+import { getShare, revokeShare, ShareError, updateShare } from "@/server/shares";++const Patch = z.object({+ title: z.string().max(300).optional(),+ description: z.string().max(3000).optional(),+ tags: z.union([z.string().max(500), z.array(z.string().max(60)).max(20)]).optional(),+ layout: z.enum(["feature", "series", "carousel"]).optional(),+ showPrompts: z.boolean().optional(),+ /** Days from now, or null: never expires. */+ expiresInDays: z.number().int().min(1).max(MAX_EXPIRY_DAYS).nullable().optional(),+ /** A new token; the old link stops working. The answer carries the new one once. */+ newLink: z.literal(true).optional(),+});++export async function GET(_req: Request, ctx: RouteContext<"/api/shares/[id]">) {+ await connection();+ const { id } = await ctx.params;+ const s = getShare(id);+ return s ? Response.json(s) : Response.json({ error: "Not found" }, { status: 404 });+}++/** Change a link: its words, prompts on or off, a new expiry from now, or a new token. */+export async function PATCH(request: Request, ctx: RouteContext<"/api/shares/[id]">) {+ const { id } = await ctx.params;+ const parsed = Patch.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });+ try {+ const out = updateShare(id, parsed.data);+ return out ? Response.json(out) : Response.json({ error: "That link doesn't exist anymore" }, { status: 404 });+ } catch (e) {+ if (e instanceof ShareError) return Response.json({ error: e.message }, { status: e.status });+ throw e;+ }+}++/** Revoke: the link stops working at once. */+export async function DELETE(_req: Request, ctx: RouteContext<"/api/shares/[id]">) {+ const { id } = await ctx.params;+ return revokeShare(id) ? new Response(null, { status: 204 }) : Response.json({ error: "That link doesn't exist anymore" }, { status: 404 });+}diff --git a/src/app/api/shares/route.ts b/src/app/api/shares/route.tsnew file mode 100644index 00000000..89ddc55e--- /dev/null+++ b/src/app/api/shares/route.ts@@ -0,0 +1,40 @@+import { connection } from "next/server";+import { z } from "zod";+import { MAX_EXPIRY_DAYS, SHARE_KINDS } from "@/lib/share";+import { authEnabled } from "@/server/auth";+import { createShare, listShares, MAX_PUBLISH_ITEMS, ShareError } from "@/server/shares";++const Body = z.object({+ kind: z.enum(SHARE_KINDS as [string, ...string[]]),+ targetId: z.string().min(1).max(64).nullable().optional(),+ items: z.array(z.string().min(1).max(64)).max(MAX_PUBLISH_ITEMS).optional(),+ title: z.string().max(300).optional(),+ description: z.string().max(3000).optional(),+ tags: z.union([z.string().max(500), z.array(z.string().max(60)).max(20)]).optional(),+ layout: z.enum(["grid", "feature", "series", "carousel"]).optional(),+ cover: z.object({ generationId: z.string().min(1).max(64), index: z.number().int().min(0).max(500) }).nullable().optional(),+ showPrompts: z.boolean().optional(),+ expiresInDays: z.number().int().min(1).max(MAX_EXPIRY_DAYS).nullable().optional(),+});++/** Every share link (Library → Shared), and whether sign-in is on (the share dialog warns when it isn't). */+export async function GET() {+ await connection();+ return Response.json({ items: listShares(), signIn: authEnabled() });+}++/**+ * A new read-only link to a result, a folder, a Cinema project, or (kind "publish") a page of picked+ * results. The answer carries the token once; only its hash is stored.+ */+export async function POST(request: Request) {+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: parsed.error.issues.some((i) => i.path[0] === "items") ? `Pick up to ${MAX_PUBLISH_ITEMS} results` : "That isn't something Fuobe can share" }, { status: 400 });+ try {+ const d = parsed.data;+ return Response.json(createShare({ ...d, kind: d.kind as (typeof SHARE_KINDS)[number] }), { status: 201 });+ } catch (e) {+ if (e instanceof ShareError) return Response.json({ error: e.message }, { status: e.status });+ throw e;+ }+}diff --git a/src/app/s/[token]/f/[...path]/route.ts b/src/app/s/[token]/f/[...path]/route.tsnew file mode 100644index 00000000..3b0c0902--- /dev/null+++ b/src/app/s/[token]/f/[...path]/route.ts@@ -0,0 +1,20 @@+import { shareRoute } from "@/lib/share";+import { fileResponse } from "@/server/file-response";+import { findShare } from "@/server/share-access";+import { shareServesFile } from "@/server/shares";++const NOINDEX = { "X-Robots-Tag": "noindex, nofollow, noarchive", "Referrer-Policy": "no-referrer" };++/**+ * A file a share's page shows, without a session (the proxy lets exactly this path shape through).+ * Served only while the link is live and only when that page shows the file: a token never opens+ * another share's files or anything else in the files folder.+ */+export async function GET(request: Request, ctx: RouteContext<"/s/[token]/f/[...path]">) {+ const { token, path: parts } = await ctx.params;+ const rel = shareRoute(`/s/${token}/f/${parts.join("/")}`)?.file;+ const row = rel ? findShare(token) : null;+ if (!rel || !row || !shareServesFile(row, token, rel)) return new Response("Not found", { status: 404, headers: NOINDEX });+ // Revoking stops new requests at once; a browser may keep what it already has for a few minutes.+ return fileResponse(request, rel, { cache: "private, max-age=300", headers: NOINDEX });+}diff --git a/src/app/s/[token]/not-found.tsx b/src/app/s/[token]/not-found.tsxnew file mode 100644index 00000000..a88aa61f--- /dev/null+++ b/src/app/s/[token]/not-found.tsx@@ -0,0 +1,5 @@+import { ShareGone } from "@/components/share/share-page";++export default function NotFound() {+ return <ShareGone />;+}diff --git a/src/app/s/[token]/page.tsx b/src/app/s/[token]/page.tsxnew file mode 100644index 00000000..e21d791d--- /dev/null+++ b/src/app/s/[token]/page.tsx@@ -0,0 +1,56 @@+import type { Metadata } from "next";+import { cookies } from "next/headers";+import { notFound } from "next/navigation";+import { cache, Suspense } from "react";+import { SharePage, ShareSkeleton } from "@/components/share/share-page";+import { authEnabled, SESSION_COOKIE, validSession } from "@/server/auth";+import { findShare } from "@/server/share-access";+import { buildPublicShare, recordView } from "@/server/shares";++/** The share and its page, once per request (metadata and the page both read it). */+const load = cache((token: string) => {+ const row = findShare(token);+ const built = row ? buildPublicShare(row, token) : null;+ return row && built ? { id: row.id, page: built.page } : null;+});++/** Never indexed, never cached by a search engine, and no Referer (it would carry the token) to links. */+const PRIVATE: Metadata = {+ robots: { index: false, follow: false, nocache: true, googleBot: { index: false, follow: false, noimageindex: true } },+ referrer: "no-referrer",+};++export async function generateMetadata({ params }: PageProps<"/s/[token]">): Promise<Metadata> {+ const { token } = await params;+ const s = load(token);+ if (!s) return { ...PRIVATE, title: { absolute: "Link unavailable · Fuobe" } };+ return {+ ...PRIVATE,+ title: { absolute: `${s.page.title} · Fuobe` },+ description: s.page.description || `${s.page.items.length === 1 ? "A piece" : `${s.page.items.length} pieces`} shared with a read-only link.`,+ openGraph: { title: s.page.title, ...(s.page.description && { description: s.page.description }), type: "website" },+ };+}++async function Content({ params }: { params: PageProps<"/s/[token]">["params"] }) {+ const { token } = await params;+ const s = load(token);+ if (!s) notFound();+ // Views count visitors, not the owner checking their own link.+ const jar = await cookies();+ if (!(authEnabled() && validSession(jar.get(SESSION_COOKIE)?.value))) recordView(s.id);+ return <SharePage share={s.page} />;+}++/**+ * A share link's public page. The sign-in proxy lets exactly this path (and the share's files)+ * through without a session, after checking the token; an unknown, revoked or expired one gets a+ * real 404 there (src/app/s/gone), before this page streams.+ */+export default function Page({ params }: PageProps<"/s/[token]">) {+ return (+ <Suspense fallback={<ShareSkeleton />}>+ <Content params={params} />+ </Suspense>+ );+}diff --git a/src/app/s/gone/page.tsx b/src/app/s/gone/page.tsxnew file mode 100644index 00000000..5102c5b2--- /dev/null+++ b/src/app/s/gone/page.tsx@@ -0,0 +1,9 @@+import type { Metadata } from "next";+import { ShareGone } from "@/components/share/share-page";++export const metadata: Metadata = { title: { absolute: "Link unavailable · Fuobe" }, robots: { index: false, follow: false }, referrer: "no-referrer" };++/** Where the proxy sends a share link that doesn't work (with a 404): no studio chrome, no way in. */+export default function Page() {+ return <ShareGone />;+}diff --git a/src/components/share/share-client.tsx b/src/components/share/share-client.tsxnew file mode 100644index 00000000..6f54c1c9--- /dev/null+++ b/src/components/share/share-client.tsx@@ -0,0 +1,75 @@+"use client";++import { ChevronLeft, ChevronRight, Copy } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { Button } from "@/components/ui/button";+import { copyWithToast } from "@/lib/clipboard";+import { cn } from "@/lib/utils";++/** "Recreate in your Fuobe": copies the prompt, to paste into a studio with the same model. */+export function RecreateButton({ prompt, model, className }: { prompt: string; model: string; className?: string }) {+ return (+ <Button+ size="sm"+ className={cn("rounded-full", className)}+ onClick={() => void copyWithToast(prompt, `Prompt copied: paste it into a Fuobe studio with ${model}`)}+ aria-label={`Recreate in your Fuobe: copy the prompt (made with ${model})`}+ >+ <Copy /> Recreate in your Fuobe+ </Button>+ );+}++/** Slides in a scroll-snap track: swipe, scroll, the arrow buttons or the arrow keys; "3 / 8" says where you are. */+export function Carousel({ count, labels, children }: { count: number; labels: string[]; children: React.ReactNode }) {+ const track = useRef<HTMLDivElement>(null);+ const [at, setAt] = useState(0);+ useEffect(() => {+ const el = track.current;+ if (!el) return;+ const onScroll = () => setAt(Math.round(el.scrollLeft / Math.max(1, el.clientWidth)));+ el.addEventListener("scroll", onScroll, { passive: true });+ return () => el.removeEventListener("scroll", onScroll);+ }, []);+ const go = useCallback(+ (i: number) => {+ const el = track.current;+ if (!el) return;+ const next = Math.max(0, Math.min(count - 1, i));+ el.scrollTo({ left: next * el.clientWidth, behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });+ setAt(next);+ },+ [count],+ );+ return (+ <section aria-roledescription="carousel" aria-label="Pieces" className="min-w-0">+ <div+ ref={track}+ tabIndex={0}+ aria-live="polite"+ onKeyDown={(e) => {+ if (e.key === "ArrowRight" || e.key === "ArrowLeft") {+ e.preventDefault();+ go(at + (e.key === "ArrowRight" ? 1 : -1));+ }+ }}+ className="scrollbar-none flex snap-x snap-mandatory overflow-x-auto overscroll-x-contain rounded-2xl outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {children}+ </div>+ {count > 1 && (+ <div className="mt-3 flex items-center justify-center gap-3">+ <Button variant="outline" size="icon" className="rounded-full" onClick={() => go(at - 1)} disabled={at <= 0} aria-label="Previous">+ <ChevronLeft />+ </Button>+ <p className="min-w-16 text-center font-mono text-[12px] text-muted-foreground tabular-nums" aria-label={`${labels[at] ?? ""}, ${at + 1} of ${count}`}>+ {at + 1} / {count}+ </p>+ <Button variant="outline" size="icon" className="rounded-full" onClick={() => go(at + 1)} disabled={at >= count - 1} aria-label="Next">+ <ChevronRight />+ </Button>+ </div>+ )}+ </section>+ );+}diff --git a/src/components/share/share-page.tsx b/src/components/share/share-page.tsxnew file mode 100644index 00000000..09d09f97--- /dev/null+++ b/src/components/share/share-page.tsx@@ -0,0 +1,249 @@+import { Box, Download, EyeOff, FileText, Link2Off } from "lucide-react";+import { orderForLayout, pieces, type PublicItem, type PublicMedia, type PublicShare } from "@/lib/share";+import { cn } from "@/lib/utils";+import { Carousel, RecreateButton } from "./share-client";++/**+ * The public page of a share link (/s/<token>): what was shared, its title, model and — when the+ * owner shares prompts — each prompt with "Recreate in your Fuobe". Server-rendered from+ * PublicShare (src/server/shares.ts); every file URL is share-scoped. No app chrome, no links into+ * the studio: a visitor has nothing else to open.+ */+export function SharePage({ share }: { share: PublicShare }) {+ const items = orderForLayout(share.items, share.layout, share.coverKey);+ const single = items.length === 1;+ return (+ <div className="flex min-h-svh flex-col bg-background">+ <header className="mx-auto flex w-full max-w-[1200px] items-center justify-between gap-3 px-4 pt-5 sm:px-8">+ <p className="font-heading text-[22px] leading-none">Fuobe</p>+ <p className="text-[12px] text-muted-foreground">Shared with a read-only link</p>+ </header>+ <main className="mx-auto w-full max-w-[1200px] min-w-0 flex-1 px-4 pt-8 pb-16 sm:px-8 sm:pt-12">+ <div className="max-w-3xl">+ {share.tags.length > 0 && (+ <ul className="mb-3 flex flex-wrap gap-1.5" aria-label="Tags">+ {share.tags.map((t) => (+ <li key={t} className="rounded-full bg-brand-faint px-2.5 py-0.5 text-[12px] font-medium text-brand-text">+ #{t}+ </li>+ ))}+ </ul>+ )}+ <h1 className="font-heading text-[38px] leading-[1.08] text-balance break-words sm:text-[52px]">{share.title}</h1>+ {share.description && <p className="mt-3 text-[16px] leading-relaxed whitespace-pre-line text-pretty text-muted-foreground">{share.description}</p>}+ <p className="mt-4 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-muted-foreground">+ <span>{pieces(items.length)}</span>+ {!share.showPrompts && (+ <span className="inline-flex items-center gap-1">+ <EyeOff className="size-3.5" /> Prompts hidden by the owner+ </span>+ )}+ </p>+ </div>++ <div className="mt-8 sm:mt-10">+ {!items.length ? (+ <Nothing />+ ) : single ? (+ <Hero item={items[0]} showPrompts={share.showPrompts} />+ ) : share.layout === "feature" ? (+ <div className="space-y-10">+ <Hero item={items[0]} showPrompts={share.showPrompts} />+ <Grid items={items.slice(1)} showPrompts={share.showPrompts} />+ </div>+ ) : share.layout === "series" ? (+ <ol className="mx-auto max-w-3xl space-y-12">+ {items.map((it, i) => (+ <li key={it.key}>+ <p className="mb-2 font-mono text-[12px] tracking-wide text-muted-foreground uppercase">Episode {i + 1}</p>+ <Piece item={it} showPrompts={share.showPrompts} wide />+ </li>+ ))}+ </ol>+ ) : share.layout === "carousel" ? (+ <Carousel count={items.length} labels={items.map((it) => it.title)}>+ {items.map((it, i) => (+ <div key={it.key} role="group" aria-roledescription="slide" aria-label={`${i + 1} of ${items.length}`} className="w-full shrink-0 snap-center px-px">+ <Piece item={it} showPrompts={share.showPrompts} wide fit />+ </div>+ ))}+ </Carousel>+ ) : (+ <Grid items={items} showPrompts={share.showPrompts} />+ )}+ {share.truncated && <p className="mt-6 text-center text-[13px] text-muted-foreground">Showing the newest {items.length}.</p>}+ </div>+ </main>+ <footer className="mx-auto w-full max-w-[1200px] px-4 pb-8 text-[12px] text-muted-foreground sm:px-8">+ Made with Fuobe, an open-source studio for images and video. This page is read-only.+ </footer>+ </div>+ );+}++function Grid({ items, showPrompts }: { items: PublicItem[]; showPrompts: boolean }) {+ return (+ <div className="columns-1 gap-4 sm:columns-2 lg:columns-3">+ {items.map((it) => (+ <div key={it.key} className="mb-4 break-inside-avoid">+ <Piece item={it} showPrompts={showPrompts} />+ </div>+ ))}+ </div>+ );+}++/** One piece large, its words beside it on wide screens and under it on phones. */+function Hero({ item, showPrompts }: { item: PublicItem; showPrompts: boolean }) {+ return (+ <figure className="grid min-w-0 gap-5 lg:grid-cols-[minmax(0,1fr)_340px] lg:items-start">+ <div className="min-w-0 overflow-hidden rounded-2xl border bg-muted/40">+ <MediaSet item={item} fit />+ </div>+ <figcaption className="min-w-0 lg:sticky lg:top-6">+ <Caption item={item} showPrompts={showPrompts} />+ </figcaption>+ </figure>+ );+}++function Piece({ item, showPrompts, wide, fit }: { item: PublicItem; showPrompts: boolean; wide?: boolean; fit?: boolean }) {+ return (+ <figure className="min-w-0 overflow-hidden rounded-2xl border bg-card">+ <div className={cn("bg-muted/40", wide && "border-b")}>+ <MediaSet item={item} fit={fit} />+ </div>+ <figcaption className="p-4">+ <Caption item={item} showPrompts={showPrompts} compact={!wide} />+ </figcaption>+ </figure>+ );+}++function Caption({ item, showPrompts, compact }: { item: PublicItem; showPrompts: boolean; compact?: boolean }) {+ const first = item.media[0];+ return (+ <div className="min-w-0 space-y-2.5">+ <div className="min-w-0">+ <p className={cn("font-medium break-words", compact ? "text-[14px] leading-snug" : "text-[16px]")}>{item.title}</p>+ <p className="mt-0.5 text-[12px] text-muted-foreground">Made with {item.model}</p>+ </div>+ {showPrompts && item.prompt && (+ <blockquote className={cn("rounded-xl bg-muted/60 px-3 py-2 text-[13px] leading-relaxed break-words whitespace-pre-line", compact && "line-clamp-6")}>{item.prompt}</blockquote>+ )}+ <div className="flex flex-wrap gap-1.5">+ {showPrompts && item.prompt && <RecreateButton prompt={item.prompt} model={item.model} />}+ {first && (+ <a+ href={`${first.url}?download=${encodeURIComponent(first.download)}`}+ download={first.download}+ className="inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-[0.8rem] font-medium hover:bg-muted"+ aria-label={`Download ${first.download}`}+ >+ <Download className="size-3.5" /> Download+ </a>+ )}+ </div>+ </div>+ );+}++/** An item's files: one large, or a small grid when a run made several pictures. */+function MediaSet({ item, fit }: { item: PublicItem; fit?: boolean }) {+ const shown = item.kind === "model3d" ? [...item.media].sort((a, b) => Number(a.kind === "model3d") - Number(b.kind === "model3d")) : item.media;+ if (shown.length > 1 && shown.every((m) => m.kind === "image")) {+ return (+ <div className="grid grid-cols-2 gap-px">+ {shown.slice(0, 8).map((m, i) => (+ <Media key={m.url} media={m} alt={`${item.title}, ${i + 1} of ${shown.length}`} />+ ))}+ </div>+ );+ }+ return (+ <div className="divide-y">+ {shown.slice(0, 4).map((m, i) => (+ <Media key={m.url} media={m} alt={shown.length > 1 ? `${item.title}, ${i + 1} of ${shown.length}` : item.title} fit={fit} />+ ))}+ </div>+ );+}++function Media({ media: m, alt, fit }: { media: PublicMedia; alt: string; fit?: boolean }) {+ const box = fit ? "mx-auto max-h-[78svh] w-auto max-w-full" : "w-full";+ switch (m.kind) {+ case "image":+ return (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={m.url} alt={alt} width={m.width} height={m.height} loading="lazy" decoding="async" className={cn("block h-auto object-contain", box)} />+ );+ case "video":+ return <video src={m.url} poster={m.poster} controls playsInline preload="metadata" aria-label={alt} className={cn("block h-auto bg-black", box)} />;+ case "audio":+ return (+ <div className="p-4">+ <audio src={m.url} controls preload="metadata" aria-label={alt} className="w-full" />+ </div>+ );+ case "text":+ return (+ <div className="max-h-[60svh] overflow-auto p-4">+ {m.text ? (+ <p className="text-[14px] leading-relaxed break-words whitespace-pre-wrap">{m.text}</p>+ ) : (+ <p className="flex items-center gap-2 text-[14px] text-muted-foreground">+ <FileText className="size-4" /> A text file: use Download to read it.+ </p>+ )}+ </div>+ );+ default:+ return (+ <div className="flex items-center gap-3 p-4">+ <span className="grid size-10 shrink-0 place-items-center rounded-xl bg-brand-faint text-brand-text">+ <Box className="size-5" />+ </span>+ <div className="min-w-0 text-[13px]">+ <p className="font-medium break-all">{m.download}</p>+ <a href={`${m.url}?download=${encodeURIComponent(m.download)}`} download={m.download} className="text-brand-text underline underline-offset-2">+ Download the 3D file+ </a>+ </div>+ </div>+ );+ }+}++function Nothing() {+ return (+ <div className="rounded-2xl border border-primary/10 bg-brand-faint px-6 py-14 text-center">+ <p className="font-heading text-[24px]">Nothing to show here yet</p>+ <p className="mt-1 text-[14px] text-muted-foreground">The owner hasn't added anything finished to what they shared.</p>+ </div>+ );+}++/** A revoked, expired, wrong or emptied link: one calm screen, no way into the studio. */+export function ShareGone() {+ return (+ <main className="grid min-h-svh place-items-center bg-background px-6 pb-[10vh] text-center">+ <div className="max-w-[460px]">+ <span className="mx-auto grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <Link2Off className="size-5" />+ </span>+ <h1 className="mt-5 font-heading text-[34px] leading-tight text-balance">This link isn't available</h1>+ <p className="mt-2 text-[15px] text-pretty text-muted-foreground">It may have expired or been turned off, or what it shared was removed. Ask the person who sent it for a new link.</p>+ </div>+ </main>+ );+}++export function ShareSkeleton() {+ return (+ <div className="mx-auto w-full max-w-[1200px] px-4 pt-16 sm:px-8" aria-busy="true" aria-label="Loading">+ <div className="h-12 w-2/3 max-w-lg animate-pulse rounded-xl bg-muted" />+ <div className="mt-4 h-4 w-1/2 max-w-sm animate-pulse rounded bg-muted" />+ <div className="mt-10 aspect-video w-full animate-pulse rounded-2xl bg-muted" />+ </div>+ );+}diff --git a/src/lib/share.ts b/src/lib/share.tsnew file mode 100644index 00000000..089899f0--- /dev/null+++ b/src/lib/share.ts@@ -0,0 +1,235 @@+/**+ * Read-only share links and published pages (R4-28). Fuobe has one owner and no accounts, so+ * sharing is a link: an unguessable token that opens one public page (/s/<token>) and the files+ * that page shows (/s/<token>/f/<path>), nothing else. Pure: the proxy, the server+ * (src/server/share-access.ts, src/server/shares.ts) and the UI share these rules.+ */+import type { MediaKind } from "./catalog/types";++/** What a link shares: one result, a Library folder (with its subfolders), a Cinema project, or a published selection. */+export type ShareKind = "result" | "folder" | "cinema" | "publish";++/** How the page lays the pieces out: a plain grid, or one of the Publish wizard's layouts. */+export type ShareLayout = "grid" | "feature" | "series" | "carousel";++export const SHARE_KINDS: readonly ShareKind[] = ["result", "folder", "cinema", "publish"];++export const KIND_LABELS: Record<ShareKind, string> = {+ result: "Result",+ folder: "Folder",+ cinema: "Cinema project",+ publish: "Published page",+};++/** The Publish wizard's Assets step (Higgsfield's Feature / Series / Carousel). */+export const PUBLISH_LAYOUTS: { id: Exclude<ShareLayout, "grid">; label: string; hint: string }[] = [+ { id: "feature", label: "Feature", hint: "The first piece large on top, the rest under it." },+ { id: "series", label: "Series", hint: "Numbered episodes, one after another, in your order." },+ { id: "carousel", label: "Carousel", hint: "One piece at a time; viewers swipe or click through." },+];++export const SHARE_LAYOUTS: readonly ShareLayout[] = ["grid", "feature", "series", "carousel"];++/** A link as the owner sees it (Library → Shared). The token itself is never stored, only its hash. */+export interface ShareInfo {+ /** The token's first characters: names the link in the owner's API, opens nothing on its own. */+ id: string;+ kind: ShareKind;+ /** The result, folder or Cinema project shared; null for a published selection. */+ targetId: string | null;+ title: string;+ description: string;+ tags: string[];+ layout: ShareLayout;+ /** A published selection's generation ids, in page order. */+ items: string[];+ /** The cover the Publish wizard picked (an item's output); null: the first piece. */+ cover: { generationId: string; index: number } | null;+ /** Prompts on the page ("With prompts"), with the Recreate button; off: results and model names only. */+ showPrompts: boolean;+ /** Stops working at (null: until revoked). */+ expiresAt: number | null;+ createdAt: number;+ updatedAt: number;+ /** Page views by people other than the signed-in owner. */+ views: number;+ lastViewedAt: number | null;+}++/** The list's extras: how many pieces the page shows now, a thumbnail for the owner, and whether what it shares still exists. */+export interface ShareListItem extends ShareInfo {+ count: number;+ /** The cover as the owner's own file URL (/api/files/…), for the list. */+ thumb: { url: string; kind: MediaKind } | null;+ /** The result, folder or project was deleted: the link answers 404. */+ gone: boolean;+}++// ---------------------------------------------------------------------------+// Tokens and the public routes++/** A token is a 12-character id (looked up) and a 32-character secret (only its hash is kept), base64url. */+export const SHARE_ID_LENGTH = 12;+export const SHARE_TOKEN_LENGTH = 44;+const TOKEN = /^[A-Za-z0-9_-]{44}$/;++export const isShareToken = (s: string): boolean => TOKEN.test(s);++/** A stored file's path under the files folder ("outputs/2026-10-26/abc.png"): no dot segments, no encoding. */+const FILE_PATH = /^[A-Za-z0-9_-][A-Za-z0-9._-]*(?:\/[A-Za-z0-9_-][A-Za-z0-9._-]*)*$/;+const ROUTE = /^\/s\/([A-Za-z0-9_-]{44})(?:\/f\/(.+))?$/;++/**+ * The public routes a share opens, which the sign-in proxy lets through without a session: exactly+ * its page (/s/<token>) and a stored file under it (/s/<token>/f/<path>). Anything else is null.+ */+export function shareRoute(pathname: string): { token: string; file?: string } | null {+ const m = ROUTE.exec(pathname);+ if (!m) return null;+ if (m[2] === undefined) return { token: m[1] };+ return FILE_PATH.test(m[2]) && m[2].length <= 300 ? { token: m[1], file: m[2] } : null;+}++export const sharePath = (token: string) => `/s/${token}`;++/** A stored file's path from its URL (/api/files/<path>), or null for anything else (data: URIs, provider links). */+export function storedPath(url: string | undefined | null): string | null {+ if (!url || !url.startsWith("/api/files/")) return null;+ const rel = url.slice("/api/files/".length).split(/[?#]/)[0];+ return FILE_PATH.test(rel) ? rel : null;+}++/** The share-scoped URL of a stored file (/s/<token>/f/<path>), or null when it isn't one of Fuobe's files. */+export function shareFileUrl(token: string, url: string | undefined | null): string | null {+ const rel = storedPath(url);+ return rel ? `/s/${token}/f/${rel}` : null;+}++/** The files a result's output brings with it on a share page: the file, and its poster, thumbnail or preview. */+export function outputFiles(o: { url: string; meta?: Record<string, unknown> }): string[] {+ const out = [storedPath(o.url)];+ for (const k of ["poster", "thumbnail", "preview"]) {+ const v = o.meta?.[k];+ if (typeof v === "string") out.push(storedPath(v));+ }+ return out.filter((p): p is string => !!p);+}++// ---------------------------------------------------------------------------+// Expiry, tags, words++export const EXPIRY_CHOICES: { id: string; label: string; days: number | null }[] = [+ { id: "never", label: "Never", days: null },+ { id: "1d", label: "1 day", days: 1 },+ { id: "7d", label: "7 days", days: 7 },+ { id: "30d", label: "30 days", days: 30 },+];++const DAY = 86_400_000;++export const MAX_EXPIRY_DAYS = 365;++export function expiryFrom(days: number | null | undefined, now = Date.now()): number | null {+ return days ? now + Math.min(days, MAX_EXPIRY_DAYS) * DAY : null;+}++export const isExpired = (s: Pick<ShareInfo, "expiresAt">, now = Date.now()) => s.expiresAt !== null && s.expiresAt <= now;++/** "Never expires", "Expires in 3 days", "Expires in 5 hours", "Expired 2 days ago". */+export function expiryLabel(expiresAt: number | null, now = Date.now()): string {+ if (expiresAt === null) return "Never expires";+ const left = expiresAt - now;+ const span = (ms: number) => {+ const days = Math.round(ms / DAY);+ if (days >= 1) return `${days} day${days === 1 ? "" : "s"}`;+ const hours = Math.max(1, Math.round(ms / 3_600_000));+ return `${hours} hour${hours === 1 ? "" : "s"}`;+ };+ return left > 0 ? `Expires in ${span(left)}` : `Expired ${span(-left)} ago`;+}++export const MAX_TAGS = 8;+export const MAX_TAG_LENGTH = 24;++/** "#cinematic, Noir ,noir, portrait" → ["cinematic", "Noir", "portrait"]: trimmed, no #, unique (any case), at most 8. */+export function parseTags(input: string | string[]): string[] {+ const parts = Array.isArray(input) ? input : input.split(/[,\n]/);+ const out: string[] = [];+ for (const raw of parts) {+ const t = raw.trim().replace(/^#+/, "").replace(/\s+/g, " ").slice(0, MAX_TAG_LENGTH).trim();+ if (t && !out.some((x) => x.toLowerCase() === t.toLowerCase())) out.push(t);+ if (out.length >= MAX_TAGS) break;+ }+ return out;+}++/** Items in the order a layout shows them (Feature puts the cover's piece first). */+export function orderForLayout<T extends { key: string }>(items: T[], layout: ShareLayout, coverKey?: string | null): T[] {+ if (layout !== "feature" || !coverKey) return items;+ const at = items.findIndex((i) => i.key === coverKey);+ return at > 0 ? [items[at], ...items.slice(0, at), ...items.slice(at + 1)] : items;+}++/** Move item `from` to `to` (the wizard's reorder buttons). */+export function moveItem<T>(list: T[], from: number, to: number): T[] {+ if (from === to || from < 0 || to < 0 || from >= list.length || to >= list.length) return list;+ const next = [...list];+ const [it] = next.splice(from, 1);+ next.splice(to, 0, it);+ return next;+}++// ---------------------------------------------------------------------------+// The public page's data (built on the server, rendered by src/app/s/[token])++export interface PublicMedia {+ /** Share-scoped (/s/<token>/f/…). */+ url: string;+ kind: MediaKind;+ contentType?: string;+ width?: number;+ height?: number;+ poster?: string;+ /** A text output's words, inline. */+ text?: string;+ /** A file name for Download. */+ download: string;+}++export interface PublicItem {+ /** Position-based key (generation ids stay private). */+ key: string;+ title: string;+ model: string;+ kind: MediaKind;+ /** Only when the owner shares prompts. */+ prompt?: string;+ aspectRatio?: string | null;+ media: PublicMedia[];+ createdAt: number;+}++export interface PublicShare {+ kind: ShareKind;+ title: string;+ description: string;+ tags: string[];+ layout: ShareLayout;+ showPrompts: boolean;+ cover: PublicMedia | null;+ /** Key of the cover's item (Feature shows it first). */+ coverKey: string | null;+ items: PublicItem[];+ /** More pieces exist than the page shows (a folder or project over the limit). */+ truncated: boolean;+ updatedAt: number;+}++/** "a-neon-alley-at-night-2.png": a download name from a title, never empty. */+export function fileName(title: string, index: number, ext: string): string {+ const base = title.slice(0, 40).replace(/[^\w]+/g, "-").replace(/^-|-$/g, "") || "fuobe";+ return `${base}${index ? `-${index + 1}` : ""}.${ext || "bin"}`;+}++/** "12 pieces", "1 piece". */+export const pieces = (n: number) => `${n} piece${n === 1 ? "" : "s"}`;diff --git a/src/proxy.ts b/src/proxy.tsindex fd8877fb..3a084bd4 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -1,10 +1,12 @@import { NextResponse, type NextRequest } from "next/server";import { APPS } from "@/lib/catalog/apps";import { recordForPath, unknownHubMode } from "@/lib/record-pages";-import { authEnabled, crossSite, hostAllowed, SESSION_COOKIE, validSession, validToken } from "@/server/auth";+import { shareRoute } from "@/lib/share";+import { authEnabled, crossSite, hostAllowed, LoginGuard, SESSION_COOKIE, validSession, validToken } from "@/server/auth";import { recordExists } from "@/server/records";+import { findShare, shareGuard, shareTargetExists } from "@/server/share-access";-/** Paths that work signed out: the login page and its API. */+/** Paths that work signed out: the login page and its API (and share links: openShare). */const OPEN = new Set(["/login", "/api/auth/login"]);const APP_IDS = new Set(APPS.map((a) => a.id));@@ -27,6 +29,33 @@ function pass(request: NextRequest): NextResponse {const notFound = (request: NextRequest) => NextResponse.rewrite(new URL("/_fuobe-not-found", request.url), { status: 404 });+/** Share pages and their files: never indexed, and the token never leaks to another site in a Referer. */+const SHARE_HEADERS = { "X-Robots-Tag": "noindex, nofollow, noarchive", "Referrer-Policy": "no-referrer" };++const signedIn = (request: NextRequest) => validSession(request.cookies.get(SESSION_COOKIE)?.value) || validToken(request.headers.get("authorization"));++/**+ * A share link (/s/<token>, /s/<token>/f/<file>): open without a session when the token is a live+ * share whose result, folder or project still exists, else a 404 (a "link unavailable" page). Wrong+ * tokens count against ShareGuard; past its budget a visitor gets 429 before any lookup (the+ * signed-in owner never does). The page and the files route check the token again, and the files+ * route serves only files that page shows.+ */+function openShare(request: NextRequest, token: string): NextResponse {+ const owner = authEnabled() && signedIn(request);+ const guard = shareGuard();+ const key = LoginGuard.clientKey(request.headers);+ if (!owner) {+ const wait = guard.blockedFor(key);+ if (wait > 0) return new NextResponse("Too many wrong links. Try again in a minute.", { status: 429, headers: { ...SHARE_HEADERS, "Retry-After": String(Math.ceil(wait / 1000)) } });+ }+ const row = findShare(token);+ if (!row && !owner) guard.miss(key, key === LoginGuard.DIRECT);+ const res = row && shareTargetExists(row) ? NextResponse.next() : NextResponse.rewrite(new URL("/s/gone", request.url), { status: 404 });+ for (const [k, v] of Object.entries(SHARE_HEADERS)) res.headers.set(k, v);+ return res;+}+function safeDecode(s: string): string {try {return decodeURIComponent(s);@@ -49,10 +78,13 @@ export function proxy(request: NextRequest) {if (crossSite(request, request.nextUrl.host)) {return NextResponse.json({ error: "Blocked a request from another website. Use Fuobe from its own address (or add it to FUOBE_ALLOWED_ORIGINS)." }, { status: 403 });}- if (!authEnabled()) return pass(request);const { pathname, search } = request.nextUrl;+ // Share links are read-only and public, password or not: exactly a share's page and its files.+ const share = (request.method === "GET" || request.method === "HEAD") && shareRoute(pathname);+ if (share) return openShare(request, share.token);+ if (!authEnabled()) return pass(request);if (OPEN.has(pathname)) return NextResponse.next();- if (validSession(request.cookies.get(SESSION_COOKIE)?.value) || validToken(request.headers.get("authorization"))) return pass(request);+ if (signedIn(request)) return pass(request);if (pathname.startsWith("/api/")) {return NextResponse.json({ error: "Sign in, or send an API token as Authorization: Bearer fuobe_…" }, { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="fuobe"' } });}diff --git a/src/server/db.ts b/src/server/db.tsindex cd50b504..e0a6bb5d 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -469,6 +469,29 @@ const MIGRATIONS: string[] = [updated_at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS content_series_updated ON content_series(updated_at DESC);`,+ // round 4 (r4/share-links): read-only share links and published pages. `id` is the token's first 12 characters+ // (the lookup key); only the SHA-256 of the whole token is kept. A share names generations, folders or projects,+ // never files: its page shows what still exists.+ `CREATE TABLE IF NOT EXISTS shares (+ id TEXT PRIMARY KEY,+ token_hash TEXT NOT NULL,+ kind TEXT NOT NULL,+ target_id TEXT,+ title TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ tags_json TEXT NOT NULL DEFAULT '[]',+ layout TEXT NOT NULL DEFAULT 'grid',+ items_json TEXT NOT NULL DEFAULT '[]',+ cover_id TEXT,+ cover_index INTEGER NOT NULL DEFAULT 0,+ show_prompts INTEGER NOT NULL DEFAULT 0,+ expires_at INTEGER,+ views INTEGER NOT NULL DEFAULT 0,+ last_viewed_at INTEGER,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS shares_target ON shares(kind, target_id);`,];declare global {diff --git a/src/server/file-response.ts b/src/server/file-response.tsnew file mode 100644index 00000000..5460bb8a--- /dev/null+++ b/src/server/file-response.ts@@ -0,0 +1,46 @@+import "server-only";+import fs from "node:fs";+import { absolutePath, contentTypeFor } from "./storage";++/**+ * A stored file as an HTTP response, with byte ranges (video seeking), a UTF-8 charset for text,+ * `nosniff`, and a script-free CSP for SVG. `relPath` is under the files folder; traversal is+ * refused. Used by /api/files (signed in) and the share routes (/s/<token>/f/…).+ */+export function fileResponse(request: Request, relPath: string, opts: { cache?: string; headers?: Record<string, string> } = {}): Response {+ let abs: string;+ try {+ abs = absolutePath(relPath);+ } catch {+ return new Response("Bad path", { status: 400 });+ }+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) return new Response("Not found", { status: 404 });+ const size = fs.statSync(abs).size;+ const type = contentTypeFor(abs);+ const headers: Record<string, string> = {+ // Transcripts, subtitles and scripts are UTF-8 text.+ "Content-Type": /^text\/|^application\/(json|x-subrip)$/.test(type) ? `${type}; charset=utf-8` : type,+ "Accept-Ranges": "bytes",+ "Cache-Control": opts.cache ?? "private, max-age=31536000, immutable",+ "X-Content-Type-Options": "nosniff",+ ...opts.headers,+ };+ if (type === "image/svg+xml") headers["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'";+ const download = new URL(request.url).searchParams.get("download");+ if (download) headers["Content-Disposition"] = `attachment; filename="${download.replace(/[^\w.-]/g, "_")}"`;+ const range = request.headers.get("range");+ const m = range && /bytes=(\d*)-(\d*)/.exec(range);+ if (m) {+ const start = m[1] ? Number(m[1]) : Math.max(0, size - Number(m[2]));+ const end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : size - 1;+ if (start >= size || start > end) return new Response(null, { status: 416, headers: { "Content-Range": `bytes */${size}` } });+ const stream = fs.createReadStream(abs, { start, end });+ return new Response(stream as unknown as ReadableStream, {+ status: 206,+ headers: { ...headers, "Content-Range": `bytes ${start}-${end}/${size}`, "Content-Length": String(end - start + 1) },+ });+ }+ return new Response(fs.createReadStream(abs) as unknown as ReadableStream, {+ headers: { ...headers, "Content-Length": String(size) },+ });+}diff --git a/src/server/generations.ts b/src/server/generations.tsindex ae4c29a0..593fcef3 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -315,6 +315,8 @@ export const ASSET_FREE: Record<string, string> = {"skills.files_json": "a skill's own text files, stored inline","lora_mirrors.source_url": "where a LoRA file downloads from (civitai, Hugging Face), without the key","lora_mirrors.hosted_url": "the provider's copy of a LoRA file (fal or Replicate storage), never ours",+ "shares.tags_json": "words",+ "shares.items_json": "generation ids: a share link shows what still exists and keeps no file alive","lora_mirrors.licence_json": "the licence and civitai permissions a LoRA copy was made under",};diff --git a/src/server/share-access.ts b/src/server/share-access.tsnew file mode 100644index 00000000..c5970c0b--- /dev/null+++ b/src/server/share-access.ts@@ -0,0 +1,168 @@+import "server-only";+/**+ * Who may open a share link: token creation and lookup, and the guess limiter. Kept apart from+ * src/server/shares.ts (which builds the pages) because the sign-in proxy imports it: SQLite and+ * `crypto` only, no catalog or providers.+ *+ * A token is 44 base64url characters: a 12-character id (9 random bytes, the row's primary key)+ * and a 32-character secret (24 random bytes). Only the SHA-256 of the whole token is stored. A+ * lookup finds the row by its id, then compares the hashes with timingSafeEqual — also when no row+ * matched, against a dummy, so a miss takes as long as a wrong secret.+ */+import crypto from "node:crypto";+import { isShareToken, SHARE_ID_LENGTH, type ShareInfo, type ShareKind, type ShareLayout } from "@/lib/share";+import { db } from "./db";++export interface ShareRow {+ id: string;+ token_hash: string;+ kind: ShareKind;+ target_id: string | null;+ title: string;+ description: string;+ tags_json: string;+ layout: ShareLayout;+ items_json: string;+ cover_id: string | null;+ cover_index: number;+ show_prompts: number;+ expires_at: number | null;+ views: number;+ last_viewed_at: number | null;+ created_at: number;+ updated_at: number;+}++const parse = <T,>(s: string | null, fallback: T): T => {+ try {+ return s ? (JSON.parse(s) as T) : fallback;+ } catch {+ return fallback;+ }+};++export function toShareInfo(r: ShareRow): ShareInfo {+ return {+ id: r.id,+ kind: r.kind,+ targetId: r.target_id,+ title: r.title,+ description: r.description,+ tags: parse<string[]>(r.tags_json, []),+ layout: r.layout,+ items: parse<string[]>(r.items_json, []),+ cover: r.cover_id ? { generationId: r.cover_id, index: r.cover_index } : null,+ showPrompts: !!r.show_prompts,+ expiresAt: r.expires_at,+ createdAt: r.created_at,+ updatedAt: r.updated_at,+ views: r.views,+ lastViewedAt: r.last_viewed_at,+ };+}++const sha256 = (token: string) => crypto.createHash("sha256").update(token).digest();++/** A fresh token: shown to the owner once; the row keeps `id` and `hash`. */+export function newToken(): { id: string; token: string; hash: string } {+ const id = crypto.randomBytes(9).toString("base64url");+ const token = id + crypto.randomBytes(24).toString("base64url");+ return { id, token, hash: sha256(token).toString("hex") };+}++const DUMMY = Buffer.alloc(32);++/**+ * The share a token opens, or null: an unknown token, a wrong secret, an expired link (a revoked+ * one is deleted). The hash comparison is constant-time and runs for every well-formed token.+ */+export function findShare(token: string, now = Date.now()): ShareRow | null {+ if (!isShareToken(token)) return null;+ let row: ShareRow | undefined;+ try {+ row = db().prepare("SELECT * FROM shares WHERE id = ?").get(token.slice(0, SHARE_ID_LENGTH)) as ShareRow | undefined;+ } catch {+ row = undefined; // no shares table yet (an install the migration hasn't reached): nothing is shared+ }+ const stored = row && /^[0-9a-f]{64}$/.test(row.token_hash) ? Buffer.from(row.token_hash, "hex") : DUMMY;+ const same = crypto.timingSafeEqual(sha256(token), stored);+ if (!row || !same) return null;+ if (row.expires_at !== null && row.expires_at <= now) return null;+ return row;+}++/** The SQL test for "in the Trash" (generation_trash) on `g`. */+export const NOT_TRASHED = "NOT EXISTS (SELECT 1 FROM generation_trash t WHERE t.generation_id = g.id)";++const TARGET: Record<ShareKind, string | null> = {+ result: `SELECT 1 FROM generations g WHERE g.id = ? AND g.status = 'succeeded' AND ${NOT_TRASHED}`,+ folder: "SELECT 1 FROM folders WHERE id = ?",+ cinema: "SELECT 1 FROM cinema_projects WHERE id = ?",+ publish: null,+};++/**+ * Whether what a link shares still exists (one primary-key lookup): the result (not in the Trash),+ * the folder or the project. A published selection always does (its page shows what is left).+ * The proxy answers 404 when it doesn't.+ */+export function shareTargetExists(row: Pick<ShareRow, "kind" | "target_id">): boolean {+ const sql: string | null | undefined = TARGET[row.kind];+ if (sql === undefined) return false;+ if (sql === null) return true;+ return !!row.target_id && !!db().prepare(sql).get(row.target_id);+}++// ---------------------------------------------------------------------------+// Guesses++/**+ * Limits wrong share tokens. Each miss (an unknown, wrong or expired token) counts for the client+ * and for everyone; past either budget the client (or, past the global one, every visitor) gets+ * 429 for a minute before any lookup. The client is the last X-Forwarded-For hop only behind a+ * trusted reverse proxy (FUOBE_TRUST_PROXY=1, see LoginGuard.clientKey); otherwise every visitor+ * shares one key and only the global budget applies. A signed-in owner is never limited. Tokens+ * carry 192 random bits, so this is about load and noise more than about odds.+ */+export class ShareGuard {+ private misses = new Map<string, { n: number; first: number; until: number }>();+ private recent: number[] = [];+ private globalUntil = 0;++ constructor(private readonly o = { perClient: 20, global: 100, windowMs: 60_000, lockMs: 60_000, maxClients: 5000 }) {}++ /** Milliseconds until this client's share requests are looked up again (0 = now). */+ blockedFor(key: string, now = Date.now()): number {+ const own = this.misses.get(key);+ return Math.max(0, own && own.until > now ? own.until - now : 0, this.globalUntil > now ? this.globalUntil - now : 0);+ }++ miss(key: string, shared: boolean, now = Date.now()): void {+ this.recent = this.recent.filter((t) => now - t < this.o.windowMs);+ this.recent.push(now);+ if (this.recent.length >= this.o.global) {+ this.globalUntil = now + this.o.lockMs;+ this.recent = [];+ }+ if (shared) return; // one key for everyone: the global budget is its budget+ const m = this.misses.get(key);+ const fresh = !m || now - m.first > this.o.windowMs;+ const n = fresh ? 1 : m.n + 1;+ this.misses.delete(key);+ this.misses.set(key, { n, first: fresh ? now : m.first, until: n >= this.o.perClient ? now + this.o.lockMs : (m?.until ?? 0) });+ for (const [k, v] of this.misses) {+ if (this.misses.size <= this.o.maxClients && now - v.first < this.o.windowMs * 10) break;+ if (v.until < now || this.misses.size > this.o.maxClients) this.misses.delete(k);+ }+ }+}++declare global {+ var __fuobeShareGuard: ShareGuard | undefined;+}++/** The process's guard (kept across hot reloads). */+export function shareGuard(): ShareGuard {+ globalThis.__fuobeShareGuard ??= new ShareGuard();+ return globalThis.__fuobeShareGuard;+}diff --git a/src/server/shares.ts b/src/server/shares.tsnew file mode 100644index 00000000..a46c4469--- /dev/null+++ b/src/server/shares.ts@@ -0,0 +1,357 @@+import "server-only";+/**+ * Share links and published pages (R4-28): create, list, change, revoke, and build the public+ * page. A share names what it shows (a result, a folder with its subfolders, a Cinema project, or+ * a published selection of results), never files, so its page always shows what still exists:+ * finished results that aren't in the Trash, without helper steps. The files route serves exactly+ * the files that page shows (`files` of buildPublicShare), nothing else.+ */+import { getModel } from "@/lib/catalog";+import { OPERATION_LABELS, type Generation, type OutputFile } from "@/lib/catalog/types";+import { HELPER_FEATURES, HELPER_SUFFIX, extensionOf, userTitle } from "@/lib/library";+import { shownOutputs } from "@/lib/output-actions";+import {+ expiryFrom,+ fileName,+ MAX_EXPIRY_DAYS,+ outputFiles,+ parseTags,+ SHARE_KINDS,+ shareFileUrl,+ sharePath,+ storedPath,+ type PublicItem,+ type PublicMedia,+ type PublicShare,+ type ShareInfo,+ type ShareKind,+ type ShareLayout,+ type ShareListItem,+} from "@/lib/share";+import { db } from "./db";+import { toGeneration } from "./generations";+import { NOT_TRASHED, newToken, shareTargetExists, toShareInfo, type ShareRow } from "./share-access";++export class ShareError extends Error {+ constructor(+ message: string,+ readonly status = 400,+ ) {+ super(message);+ }+}++/** A folder or project page shows its newest 200 results; a published page up to 100 picked ones. */+export const SCOPE_LIMIT = 200;+export const MAX_PUBLISH_ITEMS = 100;+const MAX_TITLE = 120;+const MAX_DESCRIPTION = 1000;++const HELPER_SQL = `(g.feature LIKE '%${HELPER_SUFFIX}' OR g.feature IN (${HELPER_FEATURES.map((f) => `'${f}'`).join(", ")}))`;+const SHOWN = `g.status = 'succeeded' AND g.outputs_json != '[]' AND ${NOT_TRASHED}`;+const COLUMNS = "g.*, NULL AS deleted_at, NULL AS folder_id";++type GenRow = Parameters<typeof toGeneration>[0];++const marks = (n: number) => Array.from({ length: n }, () => "?").join(", ");++/** The results a share shows, in page order (null: what it shares is gone), and whether there are more. */+function scope(s: Pick<ShareRow, "kind" | "target_id" | "items_json">): { list: Generation[]; truncated: boolean } | null {+ if (!shareTargetExists(s)) return null;+ const all = (sql: string, ...args: unknown[]) => (db().prepare(sql).all(...args) as GenRow[]).map(toGeneration);+ const capped = (list: Generation[]) => ({ list: list.slice(0, SCOPE_LIMIT), truncated: list.length > SCOPE_LIMIT });+ switch (s.kind) {+ case "result":+ return { list: all(`SELECT ${COLUMNS} FROM generations g WHERE g.id = ? AND ${SHOWN}`, s.target_id), truncated: false };+ case "folder":+ return capped(+ all(+ `WITH RECURSIVE sub(id) AS (SELECT ? UNION SELECT f.id FROM folders f JOIN sub ON f.parent_id = sub.id)+ SELECT ${COLUMNS} FROM generations g JOIN folder_items fi ON fi.generation_id = g.id+ WHERE fi.folder_id IN (SELECT id FROM sub) AND ${SHOWN} AND NOT ${HELPER_SQL}+ ORDER BY g.created_at DESC, g.id DESC LIMIT ?`,+ s.target_id,+ SCOPE_LIMIT + 1,+ ),+ );+ case "cinema":+ return capped(+ all(+ `SELECT ${COLUMNS} FROM generations g JOIN cinema_items i ON i.generation_id = g.id+ WHERE i.project_id = ? AND json_extract(i.meta_json, '$.removed') IS NULL AND ${SHOWN} AND NOT ${HELPER_SQL}+ ORDER BY g.created_at DESC, g.id DESC LIMIT ?`,+ s.target_id,+ SCOPE_LIMIT + 1,+ ),+ );+ case "publish": {+ const ids = parseIds(s.items_json);+ if (!ids.length) return { list: [], truncated: false };+ const found = new Map(all(`SELECT ${COLUMNS} FROM generations g WHERE g.id IN (${marks(ids.length)}) AND ${SHOWN}`, ...ids).map((g) => [g.id, g]));+ return { list: ids.map((id) => found.get(id)).filter((g): g is Generation => !!g), truncated: false };+ }+ }+}++function parseIds(json: string): string[] {+ try {+ const v = JSON.parse(json) as unknown;+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string").slice(0, MAX_PUBLISH_ITEMS) : [];+ } catch {+ return [];+ }+}++/** A user's own words, unless a chained step's prompt is data (a cue list). */+function promptOf(g: Generation): string | undefined {+ const p = (g.request.prompt?.trim() || g.prompt?.trim() || "").slice(0, 4000);+ return p && !/^[[{]/.test(p) ? p : undefined;+}++/** What an item is called on the page: its title or prompt when prompts are shared, else what was made and with what. */+function itemTitle(g: Generation, showPrompts: boolean): string {+ if (showPrompts) return userTitle(g).slice(0, 140);+ return OPERATION_LABELS[g.op] ?? (g.kind === "video" ? "Video" : g.kind === "audio" ? "Audio" : g.kind === "model3d" ? "3D model" : g.kind === "text" ? "Text" : "Image");+}++/**+ * The public page for a share, and every stored file it may serve (relative paths under the files+ * folder). Null when what it shares is gone. Prompts (and titles made from them) are left out+ * unless the share shows prompts; file names are made from the page's own titles.+ */+export function buildPublicShare(row: ShareRow, token: string): { page: PublicShare; files: Set<string> } | null {+ const sc = scope(row);+ if (!sc) return null;+ const share = toShareInfo(row);+ const files = new Set<string>();+ const media = (o: OutputFile, index: number, title: string): PublicMedia | null => {+ const url = shareFileUrl(token, o.url);+ if (!url) return null;+ for (const f of outputFiles(o)) files.add(f);+ const posterSrc = ["poster", "thumbnail", "preview"].map((k) => o.meta?.[k]).find((v): v is string => typeof v === "string" && !!storedPath(v));+ return {+ url,+ kind: o.kind,+ ...(o.contentType && { contentType: o.contentType }),+ ...(o.width && { width: o.width }),+ ...(o.height && { height: o.height }),+ ...(o.kind === "video" && posterSrc && { poster: shareFileUrl(token, posterSrc)! }),+ ...(o.kind === "text" && typeof o.text === "string" && { text: o.text.slice(0, 20_000) }),+ download: fileName(title, index, extensionOf(o)),+ };+ };+ let cover: PublicMedia | null = null;+ let coverKey: string | null = null;+ const items: PublicItem[] = [];+ for (const [n, g] of sc.list.entries()) {+ const key = String(n + 1);+ const title = itemTitle(g, share.showPrompts);+ // A 3D result shows its turntable (a video output) with the model as a download.+ const shown = g.kind === "model3d" ? g.outputs.map((_, i) => i) : shownOutputs(g);+ const list = shown.map((i) => ({ i, m: media(g.outputs[i], i, title) })).filter((x): x is { i: number; m: PublicMedia } => !!x.m);+ if (!list.length) continue;+ if (share.cover?.generationId === g.id) {+ cover = (list.find((x) => x.i === share.cover!.index) ?? list[0]).m;+ coverKey = key;+ }+ const prompt = share.showPrompts ? promptOf(g) : undefined;+ items.push({+ key,+ title,+ model: getModel(g.modelId)?.name ?? g.modelName ?? g.modelId,+ kind: g.kind,+ ...(prompt && { prompt }),+ aspectRatio: g.aspectRatio ?? null,+ media: list.map((x) => x.m),+ createdAt: g.createdAt,+ });+ }+ if (!cover) {+ for (const it of items) {+ const m = it.media.find((x) => x.kind === "image" || x.poster);+ if (m) {+ cover = m;+ coverKey = it.key;+ break;+ }+ }+ }+ return {+ page: {+ kind: share.kind,+ title: share.title,+ description: share.description,+ tags: share.tags,+ layout: share.layout,+ showPrompts: share.showPrompts,+ cover,+ coverKey,+ items,+ truncated: sc.truncated,+ updatedAt: share.updatedAt,+ },+ files,+ };+}++/** Whether a share may serve this stored file: only one its page shows. */+export function shareServesFile(row: ShareRow, token: string, rel: string): boolean {+ return buildPublicShare(row, token)?.files.has(rel) ?? false;+}++/** A page view by someone other than the signed-in owner. */+export function recordView(id: string, now = Date.now()): void {+ db().prepare("UPDATE shares SET views = views + 1, last_viewed_at = ? WHERE id = ?").run(now, id);+}++// ---------------------------------------------------------------------------+// The owner's side++export interface CreateShareInput {+ kind: ShareKind;+ /** The result, folder or Cinema project (not for a published selection). */+ targetId?: string | null;+ /** A published selection's results, in page order. */+ items?: string[];+ title?: string;+ description?: string;+ tags?: string[] | string;+ layout?: ShareLayout;+ cover?: { generationId: string; index: number } | null;+ showPrompts?: boolean;+ /** Days until the link stops working; null or left out: until revoked. */+ expiresInDays?: number | null;+}++const clean = (s: string | undefined, max: number) => (s ?? "").replace(/\s+/g, (w) => (w.includes("\n") ? "\n" : " ")).trim().slice(0, max);++/** What a link is called when the owner leaves the title empty: the result, folder or project's own name. */+function defaultTitle(kind: ShareKind, targetId: string | null): string {+ const get = (sql: string) => (targetId ? (db().prepare(sql).get(targetId) as { name?: string } | undefined)?.name : undefined);+ if (kind === "folder") return get("SELECT name FROM folders WHERE id = ?") ?? "Shared folder";+ if (kind === "cinema") return get("SELECT name FROM cinema_projects WHERE id = ?") ?? "Shared project";+ if (kind === "result") {+ const g = targetId ? scope({ kind, target_id: targetId, items_json: "[]" })?.list[0] : undefined;+ return g ? itemTitle(g, false) : "Shared result";+ }+ return "Untitled";+}++function validCover(cover: CreateShareInput["cover"], items: Generation[]): { generationId: string; index: number } | null {+ if (!cover) return null;+ const g = items.find((x) => x.id === cover.generationId);+ if (!g) throw new ShareError("Pick the cover from the results you're publishing");+ const index = Number.isInteger(cover.index) && cover.index >= 0 && cover.index < g.outputs.length ? cover.index : 0;+ return { generationId: g.id, index };+}++/** A new link. The token is in the answer only: it can't be read back later (only its hash is kept). */+export function createShare(input: CreateShareInput, now = Date.now()): { share: ShareInfo; token: string; path: string } {+ if (!SHARE_KINDS.includes(input.kind)) throw new ShareError("Share a result, a folder, a Cinema project or a selection");+ const publish = input.kind === "publish";+ const targetId = publish ? null : (input.targetId ?? "").trim();+ let items: string[] = [];+ let cover: ShareInfo["cover"] = null;+ if (publish) {+ items = [...new Set((input.items ?? []).filter((x) => typeof x === "string" && x))];+ if (!items.length) throw new ShareError("Pick at least one result to publish");+ if (items.length > MAX_PUBLISH_ITEMS) throw new ShareError(`A page holds up to ${MAX_PUBLISH_ITEMS} results; pick fewer`);+ const found = scope({ kind: "publish", target_id: null, items_json: JSON.stringify(items) })!.list;+ if (found.length < items.length) {+ const n = items.length - found.length;+ throw new ShareError(`${n === 1 ? "One result isn't" : `${n} results aren't`} finished or ${n === 1 ? "is" : "are"} in the Trash: take ${n === 1 ? "it" : "them"} out of the selection`);+ }+ cover = validCover(input.cover, found);+ } else if (!targetId || !shareTargetExists({ kind: input.kind, target_id: targetId })) {+ throw new ShareError(input.kind === "result" ? "Only a finished result that isn't in the Trash can be shared" : `That ${input.kind === "folder" ? "folder" : "project"} doesn't exist anymore`, 404);+ }+ const layout: ShareLayout = publish ? (input.layout && input.layout !== "grid" ? input.layout : "feature") : "grid";+ const title = clean(input.title, MAX_TITLE) || defaultTitle(input.kind, targetId);+ const { id, token, hash } = newToken();+ db()+ .prepare(+ `INSERT INTO shares (id, token_hash, kind, target_id, title, description, tags_json, layout, items_json, cover_id, cover_index, show_prompts, expires_at, created_at, updated_at)+ VALUES (@id, @hash, @kind, @target, @title, @description, @tags, @layout, @items, @coverId, @coverIndex, @prompts, @expires, @now, @now)`,+ )+ .run({+ id,+ hash,+ kind: input.kind,+ target: targetId,+ title,+ description: clean(input.description, MAX_DESCRIPTION),+ tags: JSON.stringify(parseTags(input.tags ?? [])),+ layout,+ items: JSON.stringify(items),+ coverId: cover?.generationId ?? null,+ coverIndex: cover?.index ?? 0,+ prompts: input.showPrompts ? 1 : 0,+ expires: expiryFrom(input.expiresInDays, now),+ now,+ });+ return { share: getShare(id)!, token, path: sharePath(token) };+}++function rowOf(id: string): ShareRow | undefined {+ return db().prepare("SELECT * FROM shares WHERE id = ?").get(id) as ShareRow | undefined;+}++export function getShare(id: string): ShareInfo | null {+ const r = rowOf(id);+ return r ? toShareInfo(r) : null;+}++/** Every link, newest first, with what its page shows now (Library → Shared). */+export function listShares(): ShareListItem[] {+ const rows = db().prepare("SELECT * FROM shares ORDER BY created_at DESC, id DESC").all() as ShareRow[];+ return rows.map((r) => {+ const sc = scope(r);+ const info = toShareInfo(r);+ const coverGen = (info.cover && sc?.list.find((g) => g.id === info.cover!.generationId)) || sc?.list.find((g) => g.outputs.some((o) => (o.kind === "image" || o.kind === "video") && storedPath(o.url)));+ const out = coverGen?.outputs[coverGen.id === info.cover?.generationId ? info.cover.index : coverGen.outputs.findIndex((o) => (o.kind === "image" || o.kind === "video") && storedPath(o.url))];+ return { ...info, count: sc?.list.length ?? 0, thumb: out && storedPath(out.url) ? { url: out.url, kind: out.kind } : null, gone: !sc };+ });+}++export interface SharePatch {+ title?: string;+ description?: string;+ tags?: string[] | string;+ layout?: ShareLayout;+ showPrompts?: boolean;+ /** Days from now; null: never expires. */+ expiresInDays?: number | null;+ /** A new token: the old link stops working. */+ newLink?: boolean;+}++/** Change a link (its words, prompts on or off, a new expiry from now), or give it a new token. */+export function updateShare(id: string, patch: SharePatch, now = Date.now()): { share: ShareInfo; token?: string; path?: string } | null {+ const r = rowOf(id);+ if (!r) return null;+ const sets: Record<string, unknown> = {};+ if (patch.title !== undefined) sets.title = clean(patch.title, MAX_TITLE) || r.title;+ if (patch.description !== undefined) sets.description = clean(patch.description, MAX_DESCRIPTION);+ if (patch.tags !== undefined) sets.tags_json = JSON.stringify(parseTags(patch.tags));+ if (patch.layout !== undefined && r.kind === "publish" && patch.layout !== "grid") sets.layout = patch.layout;+ if (patch.showPrompts !== undefined) sets.show_prompts = patch.showPrompts ? 1 : 0;+ if (patch.expiresInDays !== undefined) {+ if (patch.expiresInDays !== null && !(patch.expiresInDays > 0 && patch.expiresInDays <= MAX_EXPIRY_DAYS)) throw new ShareError(`Pick 1 to ${MAX_EXPIRY_DAYS} days, or never`);+ sets.expires_at = expiryFrom(patch.expiresInDays, now);+ }+ let fresh: ReturnType<typeof newToken> | undefined;+ // A new token keeps the row (and its views); its id is the token's start, so the row's key changes too.+ if (patch.newLink) fresh = newToken();+ const keys = Object.keys(sets);+ db().transaction(() => {+ if (keys.length) db().prepare(`UPDATE shares SET ${keys.map((k) => `${k} = @${k}`).join(", ")}, updated_at = @__now WHERE id = @__id`).run({ ...sets, __now: now, __id: id });+ if (fresh) db().prepare("UPDATE shares SET id = ?, token_hash = ?, updated_at = ? WHERE id = ?").run(fresh.id, fresh.hash, now, id);+ })();+ const share = getShare(fresh?.id ?? id)!;+ return fresh ? { share, token: fresh.token, path: sharePath(fresh.token) } : { share };+}++/** Revoke: the link stops working at once (its row is deleted). */+export function revokeShare(id: string): boolean {+ return db().prepare("DELETE FROM shares WHERE id = ?").run(id).changes > 0;+}diff --git a/tests/record-pages.test.ts b/tests/record-pages.test.tsindex a1b90e55..73c2a184 100644--- a/tests/record-pages.test.ts+++ b/tests/record-pages.test.ts@@ -54,8 +54,8 @@ describe("record pages (real 404s)", () => {};walk(app, []);expect(routes.length).toBeGreaterThan(40);- // Ids the catalog answers for (apps, hub modes), not stored records: the proxy checks those itself.- const catalog = /^\/(apps|audio|video-tools|upscale)\/\[/;+ // Ids the catalog answers for (apps, hub modes), not stored records, and share tokens: the proxy checks those itself.+ const catalog = /^\/(apps|audio|video-tools|upscale|s)\/\[/;for (const route of routes) {if (!route.includes("[")) {expect(recordForPath(route), route).toBeNull();diff --git a/tests/share-links.test.ts b/tests/share-links.test.tsnew file mode 100644index 00000000..40d12cc4--- /dev/null+++ b/tests/share-links.test.ts@@ -0,0 +1,432 @@+import crypto from "node:crypto";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";++// Route handlers call connection() (no request scope in a test).+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-share-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_TRUST_PROXY;++const share = await import("@/lib/share");+const gens = await import("@/server/generations");+const lib = await import("@/server/library");+const cinema = await import("@/server/cinema");+const access = await import("@/server/share-access");+const shares = await import("@/server/shares");+const auth = await import("@/server/auth");+const { saveFile } = await import("@/server/storage");+const { db } = await import("@/server/db");+const { proxy } = await import("@/proxy");+const fileRoute = await import("@/app/s/[token]/f/[...path]/route");+const listRoute = await import("@/app/api/shares/route");+const idRoute = await import("@/app/api/shares/[id]/route");+const { SharePage } = await import("@/components/share/share-page");++afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));+afterEach(() => {+ vi.restoreAllMocks();+ globalThis.__fuobeShareGuard = undefined;+});++const PNG = Buffer.from("89504e470d0a1a0a0000000d4948445200000001000000010806000000", "hex");++/** A finished generation with a real output file; its input is an upload of its own. */+function made(prompt: string, feature = "grade") {+ const input = saveFile({ data: Buffer.concat([PNG, Buffer.from(`in ${prompt}`)]), contentType: "image/png", source: "upload" });+ const asset = saveFile({ data: Buffer.concat([PNG, Buffer.from(prompt)]), contentType: "image/png", source: "generation" });+ const g = gens.recordLocalGeneration({+ feature,+ modelId: "local-color-grade",+ op: "grade",+ prompt,+ inputs: { images: [input.url] },+ output: { url: asset.url, kind: "image", contentType: "image/png" },+ });+ db().prepare("UPDATE assets SET generation_id = ? WHERE id = ?").run(g.id, asset.id);+ return { g, rel: share.storedPath(asset.url)!, input: share.storedPath(input.url)! };+}++/** The files route's answer, read to the end (a file stream left open outlives the test's folder). */+async function serve(token: string, rel: string) {+ const res = await fileRoute.GET(new Request(`http://localhost/s/${token}/f/${rel}`), { params: Promise.resolve({ token, path: rel.split("/") }) });+ const body = Buffer.from(await res.arrayBuffer()).toString();+ return { status: res.status, headers: res.headers, body };+}++const req = (url: string, init: { method?: string; headers?: Record<string, string> } = {}) =>+ new NextRequest(url, { method: init.method ?? "GET", headers: init.headers, ...(init.method === "POST" && { body: "{}" }) });+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";+const gone = (r: Response) => r.status === 404 && (r.headers.get("x-middleware-rewrite") ?? "").endsWith("/s/gone");++describe("share routes (pure)", () => {+ const token = "AbCdEfGhIjKl" + "m".repeat(32);++ it("opens exactly a share's page and a stored file under it", () => {+ expect(token).toHaveLength(share.SHARE_TOKEN_LENGTH);+ expect(share.shareRoute(`/s/${token}`)).toEqual({ token });+ expect(share.shareRoute(`/s/${token}/f/outputs/2026-10-26/abc_-1.png`)).toEqual({ token, file: "outputs/2026-10-26/abc_-1.png" });+ for (const p of [+ "/s",+ "/s/",+ `/s/${token}/`,+ `/s/${token}x`,+ `/s/${token.slice(1)}`,+ `/s/${token}/f`,+ `/s/${token}/f/`,+ `/s/${token}/other`,+ `/s/${token}/f/../db.sqlite`,+ `/s/${token}/f/outputs/../../fuobe.db`,+ `/s/${token}/f/.hidden`,+ `/s/${token}/f/outputs//x.png`,+ `/s/${token}/f/outputs/a%2F..%2Fb.png`,+ `/s/${token}/f/outputs/x.png/`,+ `/x/s/${token}`,+ "/s/gone",+ "/api/files/outputs/x.png",+ ]) {+ expect(share.shareRoute(p), p).toBeNull();+ }+ });++ it("maps stored files to share-scoped URLs and leaves other links out", () => {+ expect(share.storedPath("/api/files/outputs/d/a.png")).toBe("outputs/d/a.png");+ expect(share.storedPath("/api/files/outputs/d/a.png?download=x")).toBe("outputs/d/a.png");+ expect(share.storedPath("/api/files/../auth.json")).toBeNull();+ expect(share.storedPath("data:image/png;base64,AA")).toBeNull();+ expect(share.storedPath("https://fal.media/x.png")).toBeNull();+ expect(share.shareFileUrl(token, "/api/files/outputs/d/a.mp4")).toBe(`/s/${token}/f/outputs/d/a.mp4`);+ expect(share.outputFiles({ url: "/api/files/outputs/d/a.mp4", meta: { poster: "/api/files/outputs/d/p.png", preview: "https://x.example/p.png" } })).toEqual(["outputs/d/a.mp4", "outputs/d/p.png"]);+ });++ it("cleans tags, words expiry, and orders a Feature page by its cover", () => {+ expect(share.parseTags("#cinematic, Noir ,noir,, portrait")).toEqual(["cinematic", "Noir", "portrait"]);+ expect(share.parseTags(Array.from({ length: 12 }, (_, i) => `t${i}`))).toHaveLength(share.MAX_TAGS);+ const now = 1_000_000_000;+ expect(share.expiryLabel(null, now)).toBe("Never expires");+ expect(share.expiryLabel(now + 3 * 86_400_000, now)).toBe("Expires in 3 days");+ expect(share.expiryLabel(now + 5 * 3_600_000, now)).toBe("Expires in 5 hours");+ expect(share.expiryLabel(now - 2 * 86_400_000, now)).toBe("Expired 2 days ago");+ expect(share.expiryFrom(7, now)).toBe(now + 7 * 86_400_000);+ expect(share.expiryFrom(null, now)).toBeNull();+ const items = [{ key: "1" }, { key: "2" }, { key: "3" }];+ expect(share.orderForLayout(items, "feature", "3").map((i) => i.key)).toEqual(["3", "1", "2"]);+ expect(share.orderForLayout(items, "series", "3").map((i) => i.key)).toEqual(["1", "2", "3"]);+ expect(share.moveItem(["a", "b", "c"], 2, 0)).toEqual(["c", "a", "b"]);+ expect(share.moveItem(["a", "b"], 0, 5)).toEqual(["a", "b"]);+ });+});++describe("tokens", () => {+ it("stores only the token's hash and looks it up in constant time on the hash, hits and misses alike", () => {+ const { g } = made("a hashed lighthouse");+ const { share: s, token, path: p } = shares.createShare({ kind: "result", targetId: g.id });+ expect(p).toBe(`/s/${token}`);+ expect(share.isShareToken(token)).toBe(true);+ expect(s.id).toBe(token.slice(0, share.SHARE_ID_LENGTH));+ const row = db().prepare("SELECT * FROM shares WHERE id = ?").get(s.id) as access.ShareRow;+ expect(row.token_hash).toBe(crypto.createHash("sha256").update(token).digest("hex"));+ expect(JSON.stringify(db().prepare("SELECT * FROM shares").all())).not.toContain(token.slice(share.SHARE_ID_LENGTH));++ const spy = vi.spyOn(crypto, "timingSafeEqual");+ expect(access.findShare(token)?.id).toBe(s.id);+ const wrongSecret = token.slice(0, share.SHARE_ID_LENGTH) + (token.at(-1) === "A" ? "B" : "A").repeat(32);+ expect(access.findShare(wrongSecret)).toBeNull();+ expect(access.findShare("Z".repeat(44))).toBeNull(); // no row with that id: compared against a dummy+ expect(spy).toHaveBeenCalledTimes(3);+ for (const [given, stored] of spy.mock.calls) {+ expect((given as Buffer).length).toBe(32);+ expect((stored as Buffer).length).toBe(32);+ }+ expect(spy.mock.calls[0][0]).toEqual(crypto.createHash("sha256").update(token).digest());+ // Malformed tokens never reach the database.+ expect(access.findShare("short")).toBeNull();+ expect(spy).toHaveBeenCalledTimes(3);+ });++ it("stops at its expiry", () => {+ const { g } = made("an expiring dune");+ const now = Date.now();+ const { token } = shares.createShare({ kind: "result", targetId: g.id, expiresInDays: 1 }, now);+ expect(access.findShare(token, now + 3_600_000)).not.toBeNull();+ expect(access.findShare(token, now + 2 * 86_400_000)).toBeNull();+ });+});++describe("what a token serves", () => {+ it("serves its own files only: never another share's, a request's input, or anything unshared", async () => {+ const a = made("share A canyon");+ const b = made("share B glacier");+ const loose = made("never shared harbour");+ const A = shares.createShare({ kind: "result", targetId: a.g.id });+ const B = shares.createShare({ kind: "result", targetId: b.g.id });++ const own = await serve(A.token, a.rel);+ expect(own.status).toBe(200);+ expect(own.body).toContain("share A canyon");+ expect(own.headers.get("x-robots-tag")).toMatch(/noindex/);+ expect(own.headers.get("x-content-type-options")).toBe("nosniff");+ expect((await serve(B.token, b.rel)).status).toBe(200);++ expect((await serve(A.token, b.rel)).status).toBe(404);+ expect((await serve(B.token, a.rel)).status).toBe(404);+ expect((await serve(A.token, loose.rel)).status).toBe(404);+ expect((await serve(A.token, a.input)).status).toBe(404); // the run's input stays private+ expect((await serve(A.token, "outputs/../fuobe.db")).status).toBe(404);+ expect((await serve(A.token, "fuobe.db")).status).toBe(404);+ // A forged token with A's id but another secret opens nothing.+ expect((await serve(A.share.id + "x".repeat(32), a.rel)).status).toBe(404);+ });++ it("answers 404 once revoked, expired, or when the result went to the Trash", async () => {+ const r1 = made("revoked reef");+ const S1 = shares.createShare({ kind: "result", targetId: r1.g.id });+ expect(shares.revokeShare(S1.share.id)).toBe(true);+ expect((await serve(S1.token, r1.rel)).status).toBe(404);+ expect(access.findShare(S1.token)).toBeNull();++ const r2 = made("expired estuary");+ const S2 = shares.createShare({ kind: "result", targetId: r2.g.id, expiresInDays: 1 });+ db().prepare("UPDATE shares SET expires_at = ? WHERE id = ?").run(Date.now() - 1, S2.share.id);+ expect((await serve(S2.token, r2.rel)).status).toBe(404);++ const r3 = made("trashed tundra");+ const S3 = shares.createShare({ kind: "result", targetId: r3.g.id });+ lib.trashGenerations([r3.g.id]);+ expect((await serve(S3.token, r3.rel)).status).toBe(404);+ expect(access.shareTargetExists(access.findShare(S3.token)!)).toBe(false);+ lib.restoreGenerations([r3.g.id]);+ expect((await serve(S3.token, r3.rel)).status).toBe(200);+ });++ it("shares a folder with its subfolders, without the Trash or helper steps", async () => {+ const top = lib.createFolder({ name: "Shared top" });+ const sub = lib.createFolder({ name: "Shared sub", parentId: top.id });+ const other = lib.createFolder({ name: "Not shared" });+ const inTop = made("folder top fjord");+ const inSub = made("folder sub fjord");+ const helper = made("helper step fjord", "image-step");+ const trashed = made("trashed fjord");+ const elsewhere = made("other folder fjord");+ lib.moveToFolder([inTop.g.id, helper.g.id, trashed.g.id], top.id);+ lib.moveToFolder([inSub.g.id], sub.id);+ lib.moveToFolder([elsewhere.g.id], other.id);+ lib.trashGenerations([trashed.g.id]);++ const S = shares.createShare({ kind: "folder", targetId: top.id });+ expect(S.share.title).toBe("Shared top");+ const built = shares.buildPublicShare(access.findShare(S.token)!, S.token)!;+ expect(built.page.items).toHaveLength(2);+ expect([...built.files].sort()).toEqual([inTop.rel, inSub.rel].sort());+ expect((await serve(S.token, inSub.rel)).status).toBe(200);+ for (const x of [helper, trashed, elsewhere]) expect((await serve(S.token, x.rel)).status).toBe(404);+ // Moved out of the folder: no longer served.+ lib.moveToFolder([inSub.g.id], other.id);+ expect((await serve(S.token, inSub.rel)).status).toBe(404);+ // The folder deleted: the link is gone.+ lib.deleteFolder(top.id);+ expect(access.shareTargetExists(access.findShare(S.token)!)).toBe(false);+ });++ it("shares a Cinema project's takes", async () => {+ const p = cinema.createProject({ name: "Night shoot" });+ const take = made("cinema take alley");+ const outside = made("cinema outside alley");+ cinema.addItems(p.id, [take.g.id]);+ const S = shares.createShare({ kind: "cinema", targetId: p.id });+ expect(S.share.title).toBe("Night shoot");+ expect((await serve(S.token, take.rel)).status).toBe(200);+ expect((await serve(S.token, outside.rel)).status).toBe(404);+ });+});++describe("prompts", () => {+ it("leaves prompts (and titles made from them) out of a page whose Access says Prompts hidden", () => {+ const { g } = made("a secret prompt about violet tigers");+ const hidden = shares.createShare({ kind: "result", targetId: g.id, showPrompts: false });+ const page = shares.buildPublicShare(access.findShare(hidden.token)!, hidden.token)!.page;+ expect(JSON.stringify(page)).not.toMatch(/violet tigers/);+ expect(page.items[0].prompt).toBeUndefined();+ expect(page.items[0].model).toBe("Color Grading");+ const html = renderToStaticMarkup(createElement(SharePage, { share: page }));+ expect(html).not.toMatch(/violet tigers/);+ expect(html).not.toMatch(/Recreate in your Fuobe/);+ expect(html).toMatch(/Prompts hidden by the owner/);+ expect(html).not.toMatch(/\/api\/files\//); // every file through the share++ const shown = shares.createShare({ kind: "result", targetId: g.id, showPrompts: true });+ const page2 = shares.buildPublicShare(access.findShare(shown.token)!, shown.token)!.page;+ expect(page2.items[0].prompt).toBe("a secret prompt about violet tigers");+ const html2 = renderToStaticMarkup(createElement(SharePage, { share: page2 }));+ expect(html2).toMatch(/violet tigers/);+ expect(html2).toMatch(/Recreate in your Fuobe/);+ });++ it("turns prompts off for an existing link", async () => {+ const { g } = made("prompt that gets hidden later: amber koi");+ const S = shares.createShare({ kind: "result", targetId: g.id, showPrompts: true });+ const res = await idRoute.PATCH(new Request("http://localhost", { method: "PATCH", body: JSON.stringify({ showPrompts: false }) }), { params: Promise.resolve({ id: S.share.id }) });+ expect(res.status).toBe(200);+ expect(JSON.stringify(shares.buildPublicShare(access.findShare(S.token)!, S.token)!.page)).not.toMatch(/amber koi/);+ });+});++describe("publish", () => {+ it("keeps the picked order, layout, cover, details, and refuses unfinished or unknown results", () => {+ const a = made("publish one");+ const b = made("publish two");+ const c = made("publish three");+ const P = shares.createShare({+ kind: "publish",+ items: [c.g.id, a.g.id, b.g.id],+ title: " My series ",+ description: "Three looks",+ tags: "#grade, Look, look",+ layout: "series",+ cover: { generationId: b.g.id, index: 0 },+ showPrompts: true,+ });+ expect(P.share).toMatchObject({ kind: "publish", title: "My series", tags: ["grade", "Look"], layout: "series", cover: { generationId: b.g.id, index: 0 }, showPrompts: true });+ const page = shares.buildPublicShare(access.findShare(P.token)!, P.token)!.page;+ expect(page.items.map((i) => i.prompt)).toEqual(["publish three", "publish one", "publish two"]);+ expect(page.coverKey).toBe("3");+ expect(page.cover?.url).toBe(`/s/${P.token}/f/${b.rel}`);+ expect(() => shares.createShare({ kind: "publish", items: [] })).toThrow(/at least one/);+ expect(() => shares.createShare({ kind: "publish", items: [a.g.id, "nope"] })).toThrow(/One result isn't finished/);+ expect(() => shares.createShare({ kind: "publish", items: [a.g.id], cover: { generationId: b.g.id, index: 0 } })).toThrow(/cover/);+ // A result taken to the Trash drops off the page; the rest stay.+ lib.trashGenerations([a.g.id]);+ expect(shares.buildPublicShare(access.findShare(P.token)!, P.token)!.page.items).toHaveLength(2);+ });+});++describe("the owner's API", () => {+ it("creates, lists, renews and revokes links", async () => {+ const { g } = made("api lagoon");+ const created = await listRoute.POST(new Request("http://localhost/api/shares", { method: "POST", body: JSON.stringify({ kind: "result", targetId: g.id, expiresInDays: 7 }) }));+ expect(created.status).toBe(201);+ const { share: s, token } = (await created.json()) as { share: { id: string; expiresAt: number }; token: string };+ expect(s.expiresAt).toBeGreaterThan(Date.now());+ const list = (await (await listRoute.GET()).json()) as { items: (share.ShareListItem & { token?: string })[]; signIn: boolean };+ const row = list.items.find((x) => x.id === s.id)!;+ expect(row).toMatchObject({ count: 1, gone: false, thumb: { kind: "image" } });+ expect(JSON.stringify(list)).not.toContain(token);+ expect(list.signIn).toBe(false);++ const bad = await listRoute.POST(new Request("http://localhost/api/shares", { method: "POST", body: JSON.stringify({ kind: "result", targetId: "missing" }) }));+ expect(bad.status).toBe(404);++ // A new link: the old token stops working, the new one works.+ const renewed = await idRoute.PATCH(new Request("http://localhost", { method: "PATCH", body: JSON.stringify({ newLink: true }) }), { params: Promise.resolve({ id: s.id }) });+ const r = (await renewed.json()) as { share: { id: string }; token: string };+ expect(access.findShare(token)).toBeNull();+ expect(access.findShare(r.token)?.id).toBe(r.share.id);++ const del = await idRoute.DELETE(new Request("http://localhost", { method: "DELETE" }), { params: Promise.resolve({ id: r.share.id }) });+ expect(del.status).toBe(204);+ expect(access.findShare(r.token)).toBeNull();+ expect((await idRoute.DELETE(new Request("http://localhost", { method: "DELETE" }), { params: Promise.resolve({ id: r.share.id }) })).status).toBe(404);+ });+});++describe("the sign-in proxy", () => {+ it("lets exactly a live share's page and files through without a session, and nothing else", () => {+ const { g, rel, input } = made("proxy pier");+ const S = shares.createShare({ kind: "result", targetId: g.id });+ auth.setPassword("correct horse battery");+ try {+ const page = proxy(req(`http://localhost:3000/s/${S.token}`));+ expect(passed(page)).toBe(true);+ expect(page.headers.get("x-robots-tag")).toMatch(/noindex/);+ expect(page.headers.get("referrer-policy")).toBe("no-referrer");+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}/f/${rel}`)))).toBe(true);+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`, { method: "HEAD" })))).toBe(true);+ // The files route itself decides which files (the proxy passes the shape; see "what a token serves").+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}/f/${input}`)))).toBe(true);++ // Everything else still needs a session.+ expect(proxy(req(`http://localhost:3000/api/files/${rel}`)).status).toBe(401);+ expect(proxy(req("http://localhost:3000/api/shares")).status).toBe(401);+ expect(proxy(req(`http://localhost:3000/api/shares/${S.share.id}`, { method: "POST", headers: { origin: "http://localhost:3000" } })).status).toBe(401);+ for (const p of [`/s/${S.token}/other`, `/s/${S.token}/f/../../library`, "/s/gone", "/library", `/s/${S.token}x`]) {+ const r = proxy(req(`http://localhost:3000${p}`));+ expect(r.status, p).toBe(307);+ expect(r.headers.get("location"), p).toMatch(/\/login/);+ }+ // A share path written to (a server action, a form post) is not opened.+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`, { method: "POST", headers: { origin: "http://localhost:3000" } })))).toBe(false);++ // Revoked or unknown: a real 404 (the "link unavailable" page), not a sign-in redirect.+ expect(gone(proxy(req(`http://localhost:3000/s/${"Q".repeat(44)}`)))).toBe(true);+ shares.revokeShare(S.share.id);+ expect(gone(proxy(req(`http://localhost:3000/s/${S.token}`)))).toBe(true);+ expect(gone(proxy(req(`http://localhost:3000/s/${S.token}/f/${rel}`)))).toBe(true);+ } finally {+ auth.setPassword(null);+ }+ });++ it("keeps the host allowlist and the cross-site check when no password is set", () => {+ const { g } = made("rebound pier");+ const S = shares.createShare({ kind: "result", targetId: g.id });+ expect(auth.authEnabled()).toBe(false);+ const rebound = proxy(new NextRequest(`http://rebind.attacker.example/s/${S.token}`, { headers: { host: "rebind.attacker.example" } }));+ expect(rebound.status).toBe(403);+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`)))).toBe(true);+ expect(proxy(req(`http://localhost:3000/s/${S.token}`, { method: "POST", headers: { origin: "http://evil.example" } })).status).toBe(403);+ });++ it("rate-limits wrong tokens, but never the signed-in owner", () => {+ const { g } = made("guessed pier");+ const S = shares.createShare({ kind: "result", targetId: g.id });+ globalThis.__fuobeShareGuard = new access.ShareGuard({ perClient: 3, global: 5, windowMs: 60_000, lockMs: 60_000, maxClients: 100 });+ auth.setPassword("correct horse battery");+ try {+ for (let i = 0; i < 5; i++) expect(gone(proxy(req(`http://localhost:3000/s/${String(i).repeat(44)}`)))).toBe(true);+ const blocked = proxy(req(`http://localhost:3000/s/${S.token}`));+ expect(blocked.status).toBe(429);+ expect(Number(blocked.headers.get("retry-after"))).toBeGreaterThan(0);+ expect(proxy(req(`http://localhost:3000/s/${"7".repeat(44)}`)).status).toBe(429);+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`, { headers: { cookie } })))).toBe(true);+ } finally {+ auth.setPassword(null);+ }+ });+});++describe("ShareGuard", () => {+ const o = { perClient: 3, global: 10, windowMs: 60_000, lockMs: 60_000, maxClients: 100 };++ it("locks a trusted client after its misses, and everyone past the global budget", () => {+ const g = new access.ShareGuard(o);+ const t = 5_000_000;+ for (let i = 0; i < 2; i++) g.miss("1.2.3.4", false, t + i);+ expect(g.blockedFor("1.2.3.4", t + 5)).toBe(0);+ g.miss("1.2.3.4", false, t + 6);+ expect(g.blockedFor("1.2.3.4", t + 7)).toBeGreaterThan(50_000);+ expect(g.blockedFor("5.6.7.8", t + 7)).toBe(0);+ expect(g.blockedFor("1.2.3.4", t + 6 + 60_001)).toBe(0);+ // Rotating keys: the global budget still runs out, and then it's everyone.+ for (let i = 0; i < 10; i++) g.miss(`spoof-${i}`, false, t + 100 + i);+ expect(g.blockedFor("fresh", t + 200)).toBeGreaterThan(0);+ expect(g.blockedFor("fresh", t + 200 + 60_000)).toBe(0);+ });++ it("gives the shared key (no trusted proxy) only the global budget", () => {+ const g = new access.ShareGuard(o);+ const t = 9_000_000;+ for (let i = 0; i < 9; i++) g.miss("direct", true, t + i);+ expect(g.blockedFor("direct", t + 10)).toBe(0);+ g.miss("direct", true, t + 11);+ expect(g.blockedFor("direct", t + 12)).toBeGreaterThan(0);+ });+});