Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Sharing: review fixes: prompts stay hidden in titles and files, links can't be switched off, covers show

Claude91d9de4b0b77
diff --git a/src/app/s/[token]/f/[...path]/route.ts b/src/app/s/[token]/f/[...path]/route.ts
index 3b0c0902..4ac2b0f0 100644
--- a/src/app/s/[token]/f/[...path]/route.ts
+++ b/src/app/s/[token]/f/[...path]/route.ts
@@ -8,13 +8,14 @@ const NOINDEX = { "X-Robots-Tag": "noindex, nofollow, noarchive", "Referrer-Poli
/**
* 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.
+ * another share's files or anything else in the files folder. Files go out without the generation
+ * data saved inside them (ComfyUI's prompt and workflow, EXIF, XMP, tags): see media-clean.ts.
*/
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 });
+ if (!rel || !row || !shareServesFile(row, 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 });
+ return fileResponse(request, rel, { cache: "private, max-age=300", headers: NOINDEX, clean: true });
}
diff --git a/src/app/s/[token]/page.tsx b/src/app/s/[token]/page.tsx
index 53a081b1..96c6daaf 100644
--- a/src/app/s/[token]/page.tsx
+++ b/src/app/s/[token]/page.tsx
@@ -1,10 +1,10 @@
import type { Metadata } from "next";
-import { cookies } from "next/headers";
+import { headers } from "next/headers";
import { notFound } from "next/navigation";
import { connection } from "next/server";
import { cache, Suspense } from "react";
import { SharePage, ShareSkeleton } from "../share-page";
-import { authEnabled, SESSION_COOKIE, validSession } from "@/server/auth";
+import { previewImage, SHARE_VIEW_HEADER } from "@/lib/share";
import { findShare } from "@/server/share-access";
import { buildPublicShare, recordView } from "@/server/shares";
@@ -21,17 +21,31 @@ const PRIVATE: Metadata = {
referrer: "no-referrer",
};
+/** The address this page was opened at (a link preview needs a full URL for its picture). */
+async function requestBase(): Promise<URL | null> {
+ const h = await headers();
+ const host = h.get("x-forwarded-host")?.split(",")[0].trim() || h.get("host");
+ const proto = h.get("x-forwarded-proto")?.split(",")[0].trim() === "https" ? "https" : "http";
+ return host && /^[\w.-]+(:\d+)?$|^\[[\da-f:.]+\](:\d+)?$/i.test(host) ? new URL(`${proto}://${host}`) : null;
+}
+
export async function generateMetadata({ params }: PageProps<"/s/[token]">): Promise<Metadata> {
const { token } = await params;
// A link opens per request (it may expire or be revoked any minute): never prerendered.
await connection();
const s = load(token);
if (!s) return { ...PRIVATE, title: { absolute: "Link unavailable · Fuobe" } };
+ // The cover as the link preview's picture (Slack, iMessage…), at this address (share-scoped, like every file).
+ const image = previewImage(s.page.cover);
+ const base = await requestBase();
+ const preview = image && base;
return {
...PRIVATE,
+ ...(base && { metadataBase: base }),
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" },
+ openGraph: { title: s.page.title, ...(s.page.description && { description: s.page.description }), type: "website", ...(preview && { images: [image] }) },
+ twitter: { card: preview ? "summary_large_image" : "summary", title: s.page.title },
};
}
@@ -40,9 +54,9 @@ async function Content({ params }: { params: PageProps<"/s/[token]">["params"] }
await connection();
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);
+ // Views count visitors opening the page, as the sign-in proxy tells them apart: not the owner
+ // checking their own link, a HEAD, a prefetch or a link-preview bot (lib/share countsAsView).
+ if ((await headers()).get(SHARE_VIEW_HEADER) === "1") recordView(s.id);
return <SharePage share={s.page} />;
}
diff --git a/src/app/s/share-page.tsx b/src/app/s/share-page.tsx
index 3ee73334..fa0fe8c1 100644
--- a/src/app/s/share-page.tsx
+++ b/src/app/s/share-page.tsx
@@ -1,5 +1,5 @@
import { Box, Download, EyeOff, FileText, Link2Off } from "lucide-react";
-import { orderForLayout, pieces, type PublicItem, type PublicMedia, type PublicShare } from "@/lib/share";
+import { coverSlide, orderForLayout, pieces, type PublicItem, type PublicMedia, type PublicShare } from "@/lib/share";
import { cn } from "@/lib/utils";
import { Carousel, RecreateButton } from "@/components/share/share-client";
@@ -13,6 +13,7 @@ import { Carousel, RecreateButton } from "@/components/share/share-client";
export function SharePage({ share }: { share: PublicShare }) {
const items = orderForLayout(share.items, share.layout, share.coverKey);
const single = items.length === 1;
+ const keyArt = share.layout === "series" && !single ? share.cover : null;
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">
@@ -20,26 +21,35 @@ export function SharePage({ share }: { share: PublicShare }) {
<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>
+ {/* A Series shows its cover as key art beside the title (under it on phones). */}
+ <div className={cn(keyArt ? "grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,380px)] lg:items-end lg:gap-10" : "max-w-3xl")}>
+ <div className="min-w-0 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>
)}
- </p>
+ <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>
+ {keyArt && (
+ <figure className="min-w-0 overflow-hidden rounded-2xl border bg-muted/40" data-cover>
+ {/* A clip's poster as the still; the clip itself plays in its episode. */}
+ <Media media={keyArt.kind === "video" && keyArt.poster ? { ...keyArt, kind: "image", url: keyArt.poster } : keyArt} alt={`Cover of ${share.title}`} fit short />
+ </figure>
+ )}
</div>
<div className="mt-8 sm:mt-10">
@@ -62,7 +72,7 @@ export function SharePage({ share }: { share: PublicShare }) {
))}
</ol>
) : share.layout === "carousel" ? (
- <Carousel count={items.length} labels={items.map((it) => it.title)}>
+ <Carousel count={items.length} labels={items.map((it) => it.title)} start={coverSlide(items, share.coverKey)}>
{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 />
@@ -170,8 +180,8 @@ function MediaSet({ item, fit }: { item: PublicItem; fit?: boolean }) {
);
}
-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";
+function Media({ media: m, alt, fit, short }: { media: PublicMedia; alt: string; fit?: boolean; short?: boolean }) {
+ const box = fit ? cn("mx-auto w-auto max-w-full", short ? "max-h-[56svh]" : "max-h-[78svh]") : "w-full";
switch (m.kind) {
case "image":
return (
diff --git a/src/components/library-view.tsx b/src/components/library-view.tsx
index 443f2955..9b30eccb 100644
--- a/src/components/library-view.tsx
+++ b/src/components/library-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { ArchiveRestore, CheckCheck, CheckSquare, ChevronUp, CircleDot, Download, FolderInput, Globe, Heart, Loader2, Pin, PinOff, Search, Trash2, X } from "lucide-react";
+import { ArchiveRestore, CheckCheck, CheckSquare, ChevronUp, CircleDot, Download, FolderInput, Globe, Heart, Loader2, MoreHorizontal, Pin, PinOff, Search, Trash2, X } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -27,11 +27,19 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
-import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
import { Kbd } from "@/components/ui/kbd";
import { Skeleton } from "@/components/ui/skeleton";
import { BULK_MAX, useCreateGeneration, useFolders, useGenerationActions, useLibrary, useLibraryFacets, useShares, useUploads, type Asset, type FeedFilter } from "@/lib/api";
-import type { Generation, MediaKind } from "@/lib/catalog/types";
+import type { Generation, MediaKind, ReviewStatus } from "@/lib/catalog/types";
import { keyCombo, useModKey } from "@/lib/keys";
import { buildEntries, folderAndDescendants, reviewInfo, splitByDate, toggleAll, TRASH_DAYS, type LibraryEntry } from "@/lib/library";
import { isLayered, shownOutputs } from "@/lib/output-actions";
@@ -434,6 +442,10 @@ function Inner() {
const allPinned = selectedGens.length > 0 && selectedGens.every((g) => g.pinnedAt);
// The bulk bar's review menu checks a status only when every selected result has it.
const sameReview = selectedGens.length && selectedGens.every((g) => (g.review ?? null) === (selectedGens[0].review ?? null)) ? (selectedGens[0].review ?? null) : undefined;
+ // The bar's Like, Pin and Review (as buttons, or in ⋯ on phones).
+ const like = () => void actions.favoriteMany(selectedGens, !allFav);
+ const pinAll = () => void actions.pin(selectedGens, !allPinned).then((n) => n && toast(allPinned ? `Unpinned ${n}` : `Pinned ${n} to the top`));
+ const review = (r: ReviewStatus | null) => void actions.review(selectedGens, r).then((n) => n && toast(r ? `Marked ${n} as ${reviewInfo(r)?.label}` : `Cleared the review status of ${n}`));
const empty = () => {
if (dq) {
@@ -759,21 +771,40 @@ function Inner() {
if (done.length > BULK_MAX) toast(`The zip has the first ${BULK_MAX} of ${done.length}`, { description: "Select the rest and download them as a second zip." });
}}
/>
- <BarButton icon={Heart} label={allFav ? "Unlike" : "Like"} disabled={!selectedGens.length} onClick={() => void actions.favoriteMany(selectedGens, !allFav)} />
- <BarButton
- icon={allPinned ? PinOff : Pin}
- label={allPinned ? "Unpin" : "Pin"}
- disabled={!selectedGens.length}
- onClick={() => void actions.pin(selectedGens, !allPinned).then((n) => n && toast(allPinned ? `Unpinned ${n}` : `Pinned ${n} to the top`))}
- />
+ {/* Like, Pin and Review fold into ⋯ on phones, so the bar fits 390 px with Publish. */}
+ <BarButton icon={Heart} label={allFav ? "Unlike" : "Like"} disabled={!selectedGens.length} onClick={like} className="max-sm:hidden" />
+ <BarButton icon={allPinned ? PinOff : Pin} label={allPinned ? "Unpin" : "Pin"} disabled={!selectedGens.length} onClick={pinAll} className="max-sm:hidden" />
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild disabled={!selectedGens.length}>
- <button className={BAR} disabled={!selectedGens.length} aria-label="Review status" title="Review status">
+ <button className={cn(BAR, "max-sm:hidden")} disabled={!selectedGens.length} aria-label="Review status" title="Review status">
<CircleDot className="size-4" /> <span className="hidden sm:inline">Review</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="center" collisionPadding={12} className="min-w-44">
- <ReviewMenuItems value={sameReview} onPick={(r) => void actions.review(selectedGens, r).then((n) => n && toast(r ? `Marked ${n} as ${reviewInfo(r)?.label}` : `Cleared the review status of ${n}`))} />
+ <ReviewMenuItems value={sameReview} onPick={review} />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild disabled={!selectedGens.length}>
+ <button className={cn(BAR, "sm:hidden")} disabled={!selectedGens.length} aria-label="Like, pin or review" title="Like, pin or review">
+ <MoreHorizontal className="size-4" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="top" align="center" collisionPadding={12} className="min-w-44">
+ <DropdownMenuItem onSelect={like}>
+ <Heart /> {allFav ? "Unlike" : "Like"}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={pinAll}>
+ {allPinned ? <PinOff /> : <Pin />} {allPinned ? "Unpin" : "Pin to the top"}
+ </DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <CircleDot /> Review status
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="min-w-44">
+ <ReviewMenuItems value={sameReview} onPick={review} />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
</DropdownMenuContent>
</DropdownMenu>
{share && (
@@ -881,9 +912,9 @@ function SectionSelect({ label, ids, selected, quiet, onToggle }: { label: strin
// Phones: a little narrower, so the bar keeps every action (and Select all) at 390 px.
const BAR = "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-[13px] font-medium whitespace-nowrap transition-colors hover:bg-accent disabled:pointer-events-none disabled:opacity-40 max-sm:px-2";
-function BarButton({ icon: Icon, label, onClick, disabled, destructive }: { icon: typeof Download; label: string; onClick: () => void; disabled?: boolean; destructive?: boolean }) {
+function BarButton({ icon: Icon, label, onClick, disabled, destructive, className }: { icon: typeof Download; label: string; onClick: () => void; disabled?: boolean; destructive?: boolean; className?: string }) {
return (
- <button onClick={onClick} disabled={disabled} aria-label={label} title={label} className={cn(BAR, destructive && "text-destructive")}>
+ <button onClick={onClick} disabled={disabled} aria-label={label} title={label} className={cn(BAR, destructive && "text-destructive", className)}>
<Icon className="size-4" /> <span className="hidden sm:inline">{label}</span>
</button>
);
diff --git a/src/components/share/publish-wizard.tsx b/src/components/share/publish-wizard.tsx
index a3d98b59..7e105df0 100644
--- a/src/components/share/publish-wizard.tsx
+++ b/src/components/share/publish-wizard.tsx
@@ -14,7 +14,7 @@ import { useShareActions } from "@/lib/api";
import type { Generation } from "@/lib/catalog/types";
import { userTitle } from "@/lib/library";
import { shownOutputs } from "@/lib/output-actions";
-import { MAX_TAGS, moveItem, parseTags, pieces, PUBLISH_LAYOUTS, type ShareCreated, type ShareLayout } from "@/lib/share";
+import { MAX_PUBLISH_ITEMS, MAX_TAGS, moveItem, parseTags, pieces, PUBLISH_LAYOUTS, type ShareCreated, type ShareLayout } from "@/lib/share";
import { cn } from "@/lib/utils";
import { ExpiryPicker } from "./share-dialog";
@@ -33,8 +33,10 @@ const firstShown = (g: Generation) => shownOutputs(g)[0] ?? 0;
* Cover → Access (with prompts or prompts hidden, and when the link stops working).
*/
export function PublishWizard({ items, onClose, onPublished }: { items: Generation[]; onClose: () => void; onPublished: (c: ShareCreated) => void }) {
- const ready = useMemo(() => items.filter(publishable).slice(0, 100), [items]);
- const skipped = items.length - ready.length;
+ const finished = useMemo(() => items.filter(publishable), [items]);
+ const ready = useMemo(() => finished.slice(0, MAX_PUBLISH_ITEMS), [finished]);
+ const unfinished = items.length - finished.length;
+ const over = finished.length - ready.length;
const [step, setStep] = useState<Step>("Details");
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
@@ -76,7 +78,8 @@ export function PublishWizard({ items, onClose, onPublished }: { items: Generati
<DialogTitle>Publish {pieces(order.length)}</DialogTitle>
<DialogDescription>
A read-only page anyone with the link can open.
- {skipped > 0 && ` ${skipped} of your selection ${skipped === 1 ? "isn't" : "aren't"} finished, so ${skipped === 1 ? "it stays" : "they stay"} out.`}
+ {unfinished > 0 && ` ${unfinished} of your selection ${unfinished === 1 ? "isn't" : "aren't"} finished, so ${unfinished === 1 ? "it stays" : "they stay"} out.`}
+ {over > 0 && ` A page holds up to ${MAX_PUBLISH_ITEMS}, so the last ${over === 1 ? "one stays" : `${over} stay`} out.`}
</DialogDescription>
<ol className="mt-1 grid grid-cols-4 gap-1" aria-label="Steps">
{STEPS.map((s, i) => (
@@ -191,7 +194,9 @@ export function PublishWizard({ items, onClose, onPublished }: { items: Generati
{step === "Cover" && (
<div className="grid gap-2">
- <p className="text-[12px] text-muted-foreground">The picture people see first{layout === "feature" ? ", and the piece on top" : ""}. Without one, it&apos;s the first piece.</p>
+ <p className="text-[12px] text-muted-foreground">
+ The picture link previews show. {PUBLISH_LAYOUTS.find((l) => l.id === layout)?.cover}. Without a pick, it&apos;s the first piece.
+ </p>
<div role="radiogroup" aria-label="Cover" onKeyDown={radioKeys} className="grid grid-cols-3 gap-2 sm:grid-cols-4">
{order.map((g, i) => {
const index = firstShown(g);
diff --git a/src/components/share/share-client.tsx b/src/components/share/share-client.tsx
index 6f54c1c9..75b73538 100644
--- a/src/components/share/share-client.tsx
+++ b/src/components/share/share-client.tsx
@@ -20,17 +20,21 @@ export function RecreateButton({ prompt, model, className }: { prompt: string; m
);
}
-/** 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 }) {
+/**
+ * Slides in a scroll-snap track: swipe, scroll, the arrow buttons or the arrow keys; "3 / 8" says
+ * where you are (and is read out when it changes). Opens on `start` (the cover's slide).
+ */
+export function Carousel({ count, labels, start = 0, children }: { count: number; labels: string[]; start?: number; children: React.ReactNode }) {
const track = useRef<HTMLDivElement>(null);
- const [at, setAt] = useState(0);
+ const [at, setAt] = useState(start);
useEffect(() => {
const el = track.current;
if (!el) return;
+ if (start > 0) el.scrollLeft = start * el.clientWidth;
const onScroll = () => setAt(Math.round(el.scrollLeft / Math.max(1, el.clientWidth)));
el.addEventListener("scroll", onScroll, { passive: true });
return () => el.removeEventListener("scroll", onScroll);
- }, []);
+ }, [start]);
const go = useCallback(
(i: number) => {
const el = track.current;
@@ -46,7 +50,7 @@ export function Carousel({ count, labels, children }: { count: number; labels: s
<div
ref={track}
tabIndex={0}
- aria-live="polite"
+ aria-label="Slides: use the arrow keys"
onKeyDown={(e) => {
if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
e.preventDefault();
@@ -62,8 +66,14 @@ export function Carousel({ count, labels, children }: { count: number; labels: s
<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 className="min-w-16 text-center font-mono text-[12px] text-muted-foreground tabular-nums" aria-live="polite" aria-atomic="true">
+ <span aria-hidden>
+ {at + 1} / {count}
+ </span>
+ <span className="sr-only">
+ {labels[at] ? `${labels[at]}, ` : ""}
+ {at + 1} of {count}
+ </span>
</p>
<Button variant="outline" size="icon" className="rounded-full" onClick={() => go(at + 1)} disabled={at >= count - 1} aria-label="Next">
<ChevronRight />
diff --git a/src/components/share/shared-links.tsx b/src/components/share/shared-links.tsx
index cb012ecb..4afe2ed7 100644
--- a/src/components/share/shared-links.tsx
+++ b/src/components/share/shared-links.tsx
@@ -30,7 +30,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { useShareActions, useShares } from "@/lib/api";
import { copyWithToast } from "@/lib/clipboard";
import { timeAgo } from "@/lib/format";
-import { EXPIRY_CHOICES, expiryLabel, isExpired, KIND_LABELS, pieces, PUBLISH_LAYOUTS, type ShareListItem } from "@/lib/share";
+import { EXPIRY_CHOICES, expiryLabel, isExpired, KIND_LABELS, pieces, PUBLISH_LAYOUTS, type ShareListItem, type SharePatch } from "@/lib/share";
import { cn } from "@/lib/utils";
import { forgetLink, rememberLink, shareUrl, useRememberedLinks, useShare } from "./share-provider";
@@ -113,15 +113,19 @@ function Row({ s, token, now }: { s: ShareListItem; token?: string; now: number
const dead = s.gone || expired;
const fail = (e: Error) => toast.error(e.message);
const kind = s.kind === "publish" ? `${PUBLISH_LAYOUTS.find((l) => l.id === s.layout)?.label ?? "Published"} page` : KIND_LABELS[s.kind];
- const renew = () =>
+ // A new token (and, for an expired link, a new expiry with it): the dialog shows the link to copy.
+ const renew = (patch: SharePatch = {}) =>
void actions
- .update(s.id, { newLink: true })
+ .update(s.id, { ...patch, newLink: true })
.then((r) => {
if (!r.token || !r.path) return;
rememberLink(r.share.id, r.token, s.id);
share?.showLink({ share: r.share, token: r.token, path: r.path });
})
.catch(fail);
+ // Turning an expired link back on: this browser has its token, so the old link works again; else a new one to copy.
+ const reopen = (days: number | null) =>
+ token ? void actions.update(s.id, { expiresInDays: days }).then((r) => toast(expiryLabel(r.share.expiresAt))).catch(fail) : renew({ expiresInDays: days });
return (
<li className={cn("flex min-w-0 items-center gap-3 rounded-xl border bg-card p-2.5", dead && "opacity-75")}>
<div className="grid size-14 shrink-0 place-items-center overflow-hidden rounded-lg bg-muted">
@@ -170,13 +174,22 @@ function Row({ s, token, now }: { s: ShareListItem; token?: string; now: number
<Copy /> Copy link
</DropdownMenuItem>
)}
- {!s.gone && (
- <DropdownMenuItem onSelect={renew}>
+ {/* An expired link comes back through "Turn back on for" (with a new expiry), not a dead new link. */}
+ {!dead && (
+ <DropdownMenuItem onSelect={() => renew()}>
<RefreshCw /> {token ? "New link (the old one stops)" : "New link to copy"}
</DropdownMenuItem>
)}
{!s.gone && (
- <DropdownMenuItem onSelect={() => void actions.update(s.id, { showPrompts: !s.showPrompts }).then(() => toast(s.showPrompts ? "Prompts hidden on the page" : "Prompts shown on the page")).catch(fail)}>
+ <DropdownMenuItem
+ onSelect={() =>
+ void actions
+ .update(s.id, { showPrompts: !s.showPrompts })
+ // Hiding prompts also swaps a title made from the prompt (src/server/shares.ts updateShare).
+ .then((r) => toast(s.showPrompts ? "Prompts hidden on the page" : "Prompts shown on the page", r.share.title !== s.title ? { description: `Its title was the prompt, so it's now “${r.share.title}”.` } : undefined))
+ .catch(fail)
+ }
+ >
{s.showPrompts ? <EyeOff /> : <Eye />} {s.showPrompts ? "Hide prompts" : "Show prompts"}
</DropdownMenuItem>
)}
@@ -187,8 +200,11 @@ function Row({ s, token, now }: { s: ShareListItem; token?: string; now: number
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
{EXPIRY_CHOICES.map((c) => (
- <DropdownMenuItem key={c.id} onSelect={() => void actions.update(s.id, { expiresInDays: c.days }).then((r) => toast(expiryLabel(r.share.expiresAt))).catch(fail)}>
- {c.days === null ? "Never" : `In ${c.label}`}
+ <DropdownMenuItem
+ key={c.id}
+ onSelect={() => (expired ? reopen(c.days) : void actions.update(s.id, { expiresInDays: c.days }).then((r) => toast(expiryLabel(r.share.expiresAt))).catch(fail))}
+ >
+ {expired ? (c.days === null ? "Always" : c.label) : c.days === null ? "Never" : `In ${c.label}`}
</DropdownMenuItem>
))}
</DropdownMenuSubContent>
diff --git a/src/lib/share.ts b/src/lib/share.ts
index f66fd79c..231779b4 100644
--- a/src/lib/share.ts
+++ b/src/lib/share.ts
@@ -22,14 +22,17 @@ export const KIND_LABELS: Record<ShareKind, string> = {
};
/** 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 PUBLISH_LAYOUTS: { id: Exclude<ShareLayout, "grid">; label: string; hint: string; cover: string }[] = [
+ { id: "feature", label: "Feature", hint: "The first piece large on top, the rest under it.", cover: "Its piece goes large on top" },
+ { id: "series", label: "Series", hint: "Numbered episodes, one after another, in your order.", cover: "It sits beside the title, above the episodes" },
+ { id: "carousel", label: "Carousel", hint: "One piece at a time; viewers swipe or click through.", cover: "The carousel opens on it" },
];
export const SHARE_LAYOUTS: readonly ShareLayout[] = ["grid", "feature", "series", "carousel"];
+/** A published page holds up to 100 picked results (a folder or project page shows its newest 200). */
+export const MAX_PUBLISH_ITEMS = 100;
+
/** 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. */
@@ -129,6 +132,29 @@ export function shareRoute(pathname: string): { token: string; file?: string } |
export const sharePath = (token: string) => `/s/${token}`;
+/** Set by the sign-in proxy on a share page request that counts as a view (the page records it). */
+export const SHARE_VIEW_HEADER = "x-fuobe-share-view";
+
+/** Link checkers, unfurlers (Slack, iMessage, WhatsApp, Discord…), crawlers and scripts. */
+const NOT_A_VISITOR =
+ /bot\b|bot\/|crawl|spider|slurp|facebookexternalhit|facebot|embedly|iframely|whatsapp|telegram|skypeuripreview|slack|discord|linkedin|pinterest|vkshare|mastodon|bluesky|headless|curl\/|wget\/|python-|go-http|okhttp|axios|node-fetch|undici|httpclient|java\//i;
+
+/**
+ * Whether a request for a share page is someone looking at it: a GET from a browser opening the
+ * page. Not a HEAD, a prefetch or prerender, a fetch from a script, or a link-preview bot (pasting
+ * a link into a chat fetches it before anyone opens it).
+ */
+export function countsAsView(method: string, headers: { get(name: string): string | null }): boolean {
+ if (method !== "GET") return false;
+ const purpose = [headers.get("sec-purpose"), headers.get("purpose"), headers.get("x-purpose"), headers.get("x-moz")].join(" ");
+ if (/prefetch|prerender|preview/i.test(purpose)) return false;
+ if (headers.get("rsc") || headers.get("next-router-prefetch")) return false;
+ const dest = headers.get("sec-fetch-dest");
+ if (dest && dest !== "document") return false;
+ const ua = headers.get("user-agent") ?? "";
+ return !!ua && !NOT_A_VISITOR.test(ua);
+}
+
/** 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;
@@ -200,6 +226,18 @@ export function parseTags(input: string | string[]): string[] {
return out;
}
+/** Where a Carousel opens: on the cover's slide (the first when there's none). */
+export function coverSlide(items: { key: string }[], coverKey?: string | null): number {
+ return Math.max(0, items.findIndex((i) => i.key === coverKey));
+}
+
+/** The picture a link preview (og:image) shows: the cover if it's a picture, else a clip's poster. */
+export function previewImage(cover: PublicMedia | null): { url: string; width?: number; height?: number } | null {
+ if (!cover) return null;
+ if (cover.kind === "image") return { url: cover.url, ...(cover.width && { width: cover.width }), ...(cover.height && { height: cover.height }) };
+ return cover.poster ? { url: cover.poster } : null;
+}
+
/** 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;
diff --git a/src/proxy.ts b/src/proxy.ts
index 3a084bd4..570a4570 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -1,7 +1,7 @@
import { NextResponse, type NextRequest } from "next/server";
import { APPS } from "@/lib/catalog/apps";
import { recordForPath, unknownHubMode } from "@/lib/record-pages";
-import { shareRoute } from "@/lib/share";
+import { countsAsView, SHARE_VIEW_HEADER, 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";
@@ -34,24 +34,42 @@ const SHARE_HEADERS = { "X-Robots-Tag": "noindex, nofollow, noarchive", "Referre
const signedIn = (request: NextRequest) => validSession(request.cookies.get(SESSION_COOKIE)?.value) || validToken(request.headers.get("authorization"));
+const tooMany = (seconds: number) =>
+ new NextResponse("Too many wrong links. Try again in a minute.", { status: 429, headers: { ...SHARE_HEADERS, "Retry-After": String(seconds) } });
+
/**
* 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.
+ * share whose result, folder or project still exists, else a 404 (a "link unavailable" page). A
+ * live link always opens: wrong tokens count against ShareGuard, which answers them 429 past its
+ * budget and locks out only a client it can tell apart (never everyone, never the signed-in owner).
+ * The page and the files route check the token again, and the files route serves only files that
+ * page shows. A page view by a visitor (a browser's GET, not a prefetch, a HEAD or a link-preview
+ * bot) is passed on to the page as SHARE_VIEW_HEADER, which the page counts.
*/
-function openShare(request: NextRequest, token: string): NextResponse {
+function openShare(request: NextRequest, token: string, file: boolean): 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)) } });
+ if (wait > 0) return tooMany(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 });
+ let res: NextResponse;
+ if (!row || !shareTargetExists(row)) {
+ if (!row && !owner) {
+ const spent = guard.saturated();
+ guard.miss(key, token, key === LoginGuard.DIRECT);
+ if (spent) return tooMany(60);
+ }
+ res = NextResponse.rewrite(new URL("/s/gone", request.url), { status: 404 });
+ } else {
+ // Only the proxy says what counts as a view: a visitor can't send the header themselves.
+ const headers = new Headers(request.headers);
+ headers.delete(SHARE_VIEW_HEADER);
+ if (!file && !owner && countsAsView(request.method, request.headers)) headers.set(SHARE_VIEW_HEADER, "1");
+ res = NextResponse.next({ request: { headers } });
+ }
for (const [k, v] of Object.entries(SHARE_HEADERS)) res.headers.set(k, v);
return res;
}
@@ -81,7 +99,7 @@ export function proxy(request: NextRequest) {
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 (share) return openShare(request, share.token, !!share.file);
if (!authEnabled()) return pass(request);
if (OPEN.has(pathname)) return NextResponse.next();
if (signedIn(request)) return pass(request);
diff --git a/src/server/file-response.ts b/src/server/file-response.ts
index 5460bb8a..bde932be 100644
--- a/src/server/file-response.ts
+++ b/src/server/file-response.ts
@@ -1,22 +1,36 @@
import "server-only";
import fs from "node:fs";
+import { pipeline, type Readable } from "node:stream";
+import { cachedPatches, patchStream } from "./media-clean";
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/…).
+ * refused. Used by /api/files (signed in) and the share routes (/s/<token>/f/…). `clean` serves the
+ * file without the generation data embedded in it (src/server/media-clean.ts): same size and byte
+ * ranges, metadata blanked as it streams; a file whose metadata can't be read isn't served.
*/
-export function fileResponse(request: Request, relPath: string, opts: { cache?: string; headers?: Record<string, string> } = {}): Response {
+export function fileResponse(request: Request, relPath: string, opts: { cache?: string; headers?: Record<string, string>; clean?: boolean } = {}): 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 stat = fs.existsSync(abs) ? fs.statSync(abs) : null;
+ if (!stat?.isFile()) return new Response("Not found", { status: 404, headers: opts.headers });
+ const size = stat.size;
const type = contentTypeFor(abs);
+ const patches = opts.clean ? cachedPatches(abs, stat, type) : [];
+ if (!patches) return new Response("Not found", { status: 404, headers: opts.headers });
+ const read = (range?: { start: number; end: number }): Readable => {
+ const stream = fs.createReadStream(abs, range);
+ if (!patches.length) return stream;
+ const patched = patchStream(patches, range?.start ?? 0);
+ pipeline(stream, patched, () => {}); // a read error ends the response (pipeline destroys both)
+ return patched;
+ };
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,
@@ -34,13 +48,12 @@ export function fileResponse(request: Request, relPath: string, opts: { cache?:
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, {
+ return new Response(read({ start, end }) 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, {
+ return new Response(read() as unknown as ReadableStream, {
headers: { ...headers, "Content-Length": String(size) },
});
}
diff --git a/src/server/media-clean.ts b/src/server/media-clean.ts
new file mode 100644
index 00000000..e46bf1ed
--- /dev/null
+++ b/src/server/media-clean.ts
@@ -0,0 +1,516 @@
+import "server-only";
+/**
+ * Files on a share page go out without the generation data saved inside them. ComfyUI writes its
+ * whole API prompt (every node's inputs: the prompt, the negative prompt, seeds, LoRAs, input file
+ * names) and the workflow into what it saves: PNG text chunks, MP4/MOV and WebM/MKV tags, FLAC, MP3
+ * and Ogg tags, GLB asset.extras, an SVG <metadata> block. Other tools write EXIF/XMP. A page whose
+ * owner hid the prompts must not hand them out in its files, so the share files route serves every
+ * file through these patches (src/server/file-response.ts, `clean`).
+ *
+ * Each patch blanks bytes in place without changing the file's size or any offset: a metadata
+ * chunk or box is renamed to one every reader skips (a private PNG chunk, MP4 `free`, Matroska
+ * `Void`, FLAC PADDING, RIFF `JUNK`, a JPEG comment) and its contents are zeroed (an Ogg comment is
+ * overwritten with blanks and its page's checksum worked out again). So byte ranges
+ * (video seeking) work on the cleaned file exactly as on the stored one, and nothing is copied: the
+ * patches overlay the stream as it is read. A file whose structure can't be read where metadata
+ * lives gives null (the route then refuses it); formats that carry none (text, GIF, PLY, …) pass.
+ */
+import fs from "node:fs";
+import { Transform } from "node:stream";
+
+/** Bytes to write at `at`, or `length` bytes of `fill` there. */
+export type Patch = { at: number; bytes: Buffer } | { at: number; length: number; fill: number };
+
+const span = (p: Patch) => ("bytes" in p ? p.bytes.length : p.length);
+const zeros = (at: number, length: number): Patch => ({ at, length, fill: 0 });
+
+/** A chunk of the file read from `pos`, with the patches that touch it applied (a copy when any does). */
+export function overlay(chunk: Buffer, pos: number, patches: Patch[]): Buffer {
+ let out = chunk;
+ const end = pos + chunk.length;
+ for (const p of patches) {
+ const s = p.at;
+ const e = s + span(p);
+ if (e <= pos || s >= end) continue;
+ if (out === chunk) out = Buffer.from(chunk);
+ const from = Math.max(s, pos);
+ const to = Math.min(e, end);
+ if ("bytes" in p) p.bytes.copy(out, from - pos, from - s, to - s);
+ else out.fill(p.fill, from - pos, to - pos);
+ }
+ return out;
+}
+
+/** A stream transform that applies the patches to a file read from `start`. */
+export function patchStream(patches: Patch[], start: number): Transform {
+ let pos = start;
+ return new Transform({
+ transform(chunk: Buffer, _enc, done) {
+ const out = overlay(chunk, pos, patches);
+ pos += chunk.length;
+ done(null, out);
+ },
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Reading
+
+class Reader {
+ constructor(
+ private readonly fd: number,
+ readonly size: number,
+ ) {}
+ read(at: number, n: number): Buffer {
+ const len = Math.max(0, Math.min(n, this.size - at));
+ const buf = Buffer.alloc(len);
+ let got = 0;
+ while (got < len) {
+ const r = fs.readSync(this.fd, buf, got, len - got, at + got);
+ if (!r) break;
+ got += r;
+ }
+ return got === len ? buf : buf.subarray(0, got);
+ }
+}
+
+class Unreadable extends Error {}
+const need = (ok: boolean) => {
+ if (!ok) throw new Unreadable();
+};
+
+// CRC-32 (PNG chunks).
+const CRC_TABLE = (() => {
+ const t = new Uint32Array(256);
+ for (let n = 0; n < 256; n++) {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ t[n] = c >>> 0;
+ }
+ return t;
+})();
+
+function crc32(parts: (Buffer | number)[]): number {
+ let c = 0xffffffff;
+ for (const p of parts) {
+ if (typeof p === "number") for (let i = 0; i < p; i++) c = CRC_TABLE[c & 0xff] ^ (c >>> 8);
+ else for (const b of p) c = CRC_TABLE[(c ^ b) & 0xff] ^ (c >>> 8);
+ }
+ return (c ^ 0xffffffff) >>> 0;
+}
+
+const u32be = (n: number) => {
+ const b = Buffer.alloc(4);
+ b.writeUInt32BE(n >>> 0);
+ return b;
+};
+
+// ---------------------------------------------------------------------------
+// Formats
+
+/** PNG: tEXt / zTXt / iTXt / eXIf become a private chunk every decoder skips ("fuPd"), zeroed, with a fresh CRC. */
+function png(r: Reader): Patch[] {
+ const out: Patch[] = [];
+ const NAME = Buffer.from("fuPd");
+ let at = 8;
+ for (;;) {
+ const h = r.read(at, 8);
+ need(h.length === 8);
+ const len = h.readUInt32BE(0);
+ const type = h.toString("latin1", 4, 8);
+ need(at + 12 + len <= r.size);
+ if (type === "tEXt" || type === "zTXt" || type === "iTXt" || type === "eXIf") {
+ out.push({ at: at + 4, bytes: NAME }, zeros(at + 8, len), { at: at + 8 + len, bytes: u32be(crc32([NAME, len])) });
+ }
+ at += 12 + len;
+ if (type === "IEND" || at >= r.size) return out;
+ }
+}
+
+/** JPEG: EXIF/XMP (APP1), APP3–APP13, APP15 and comments become zeroed comments. JFIF, ICC (APP2) and Adobe (APP14) stay. */
+function jpeg(r: Reader): Patch[] {
+ const out: Patch[] = [];
+ let at = 2;
+ for (;;) {
+ const h = r.read(at, 4);
+ need(h.length >= 2 && h[0] === 0xff);
+ const m = h[1];
+ if (m === 0xff) {
+ at += 1; // fill byte
+ continue;
+ }
+ if (m === 0xd9 || m === 0xda) return out; // end, or the image data (no metadata after it)
+ if (m === 0x01 || (m >= 0xd0 && m <= 0xd7)) {
+ at += 2;
+ continue;
+ }
+ need(h.length === 4);
+ const len = h.readUInt16BE(2);
+ need(len >= 2 && at + 2 + len <= r.size);
+ const app = m >= 0xe0 && m <= 0xef;
+ if ((app && m !== 0xe0 && m !== 0xe2 && m !== 0xee) || m === 0xfe) out.push({ at: at + 1, bytes: Buffer.from([0xfe]) }, zeros(at + 4, len - 2));
+ at += 2 + len;
+ }
+}
+
+/**
+ * RIFF (WebP, WAV, RF64): metadata chunks become JUNK, zeroed; WebP's VP8X flags stop announcing
+ * EXIF/XMP. A file written to a pipe can't go back to fill in its sizes (0 or 0xFFFFFFFF, and RF64
+ * keeps the real ones elsewhere), so a size past the end of the file means "to the end".
+ */
+function riff(r: Reader, webp: boolean): Patch[] {
+ const out: Patch[] = [];
+ const META = webp ? new Set(["EXIF", "XMP "]) : new Set(["LIST", "id3 ", "ID3 ", "bext", "iXML", "_PMX", "XMP ", "EXIF"]);
+ const declared = r.read(4, 4).readUInt32LE(0);
+ const end = declared === 0 ? r.size : Math.min(r.size, 8 + declared);
+ let at = 12;
+ while (at + 8 <= end) {
+ const h = r.read(at, 9);
+ const id = h.toString("latin1", 0, 4);
+ const len = h.readUInt32LE(4);
+ // A chunk running past the end (a streamed `data` chunk, a cut-off file) is the last one.
+ const last = at + 8 + len > r.size;
+ if (META.has(id)) out.push({ at, bytes: Buffer.from("JUNK") }, zeros(at + 8, last ? r.size - at - 8 : len));
+ if (webp && id === "VP8X" && h.length === 9 && h[8] & 0x0c) out.push({ at: at + 8, bytes: Buffer.from([h[8] & ~0x0c]) });
+ if (last) break;
+ at += 8 + len + (len & 1);
+ }
+ return out;
+}
+
+const IMAGE_BRANDS = new Set(["avif", "avis", "heic", "heix", "hevc", "hevx", "heim", "heis", "mif1", "msf1"]);
+const XMP_UUID = "be7acfcb97a942e89c71999491e3afac";
+
+/** MP4 / MOV: user data and metadata boxes in the movie and its tracks (and an XMP uuid box) become `free`, zeroed. */
+function isoBmff(r: Reader): Patch[] {
+ const out: Patch[] = [];
+ const blank = (start: number, header: number, end: number) => out.push({ at: start + 4, bytes: Buffer.from("free") }, zeros(start + header, end - start - header));
+ // `cut`: the file's own top level, where the last box may run past the end (a cut-off download,
+ // a recording that stopped): it then ends with the file. Inside a box sizes must add up.
+ const boxes = (from: number, to: number, cut = false) => {
+ const list: { type: string; start: number; header: number; end: number }[] = [];
+ let at = from;
+ while (at + 8 <= to) {
+ const h = r.read(at, 16);
+ let size = h.readUInt32BE(0);
+ let header = 8;
+ if (size === 1) {
+ need(h.length === 16);
+ size = Number(h.readBigUInt64BE(8));
+ header = 16;
+ } else if (size === 0) size = to - at;
+ need(size >= header);
+ const type = h.toString("latin1", 4, 8);
+ if (at + size > to) {
+ need(cut && type !== "moov");
+ list.push({ type, start: at, header, end: to });
+ return list;
+ }
+ list.push({ type, start: at, header, end: at + size });
+ at += size;
+ }
+ need(at === to || to - at < 8);
+ return list;
+ };
+ const top = boxes(0, r.size, true);
+ const ftyp = top.find((b) => b.type === "ftyp");
+ const brand = ftyp ? r.read(ftyp.start + 8, 4).toString("latin1") : "";
+ // A HEIF/AVIF image keeps its top-level meta: that's where its picture is described.
+ const movie = top.some((b) => b.type === "moov") && !IMAGE_BRANDS.has(brand);
+ // The movie's and each track's user data and metadata; the track list is inside moov.
+ const walk = (list: typeof top, parent: "" | "moov" | "trak") => {
+ for (const b of list) {
+ if ((parent === "" && b.type === "moov") || (parent === "moov" && b.type === "trak")) walk(boxes(b.start + b.header, b.end), b.type as "moov" | "trak");
+ else if ((b.type === "udta" || b.type === "meta") && (parent !== "" || movie)) blank(b.start, b.header, b.end);
+ else if (b.type === "uuid" && parent === "" && r.read(b.start + b.header, 16).toString("hex") === XMP_UUID) blank(b.start, b.header, b.end);
+ }
+ };
+ walk(top, "");
+ return out;
+}
+
+const EBML = 0x1a45dfa3;
+const SEGMENT = 0x18538067;
+const CLUSTER = 0x1f43b675;
+const TAGS = 0x1254c367;
+const INFO = 0x1549a966;
+const TITLE = 0x7ba9;
+/** Segment-level elements: one of these ends a cluster of unknown size. */
+const CLUSTER_ENDS = new Set([0x114d9b74, INFO, 0x1654ae6b, CLUSTER, 0x1c53bb6b, 0x1941a469, 0x1043a770, TAGS]);
+
+/** WebM / MKV: the Tags element (where every tag lives) and the segment's Title become Void elements of the same length. */
+function matroska(r: Reader): Patch[] {
+ const out: Patch[] = [];
+ const vint = (at: number, keepMarker: boolean) => {
+ const b = r.read(at, 8);
+ need(b.length > 0 && b[0] !== 0);
+ const len = Math.clz32(b[0]) - 23;
+ need(len <= 8 && b.length >= len);
+ let value = keepMarker ? b[0] : b[0] & (0xff >> len);
+ let ones = value === 0xff >> len;
+ for (let i = 1; i < len; i++) {
+ value = value * 256 + b[i];
+ ones &&= b[i] === 0xff;
+ }
+ return { len, value, unknown: !keepMarker && ones };
+ };
+ const element = (at: number) => {
+ const id = vint(at, true);
+ const size = vint(at + id.len, false);
+ return { id: id.value, start: at, data: at + id.len + size.len, end: size.unknown ? null : at + id.len + size.len + size.value };
+ };
+ const voidOf = (start: number, end: number) => {
+ const total = end - start;
+ const k = Math.min(8, total - 1);
+ const v = total - 1 - k;
+ const head = Buffer.alloc(1 + k);
+ head[0] = 0xec;
+ let rest = v;
+ for (let i = k; i >= 1; i--) {
+ head[i] = rest % 256;
+ rest = Math.floor(rest / 256);
+ }
+ head[1] |= 1 << (8 - k);
+ out.push({ at: start, bytes: head }, zeros(start + 1 + k, v));
+ };
+ let at = 0;
+ while (at < r.size) {
+ const e = element(at);
+ if (e.id === EBML) {
+ need(e.end !== null && e.end <= r.size);
+ at = e.end!;
+ continue;
+ }
+ need(e.id === SEGMENT);
+ const segEnd = Math.min(e.end ?? r.size, r.size);
+ let c = e.data;
+ while (c < segEnd) {
+ const child = element(c);
+ if (child.end !== null) {
+ // A cut-off file: its last cluster (or cues) ends with the file; cut metadata isn't readable.
+ if (child.end > segEnd) {
+ need(child.id !== TAGS && child.id !== INFO);
+ break;
+ }
+ if (child.id === TAGS) voidOf(child.start, child.end);
+ // The segment's title (ffmpeg writes a "title" tag there).
+ if (child.id === INFO) {
+ for (let i = child.data; i < child.end; ) {
+ const field = element(i);
+ need(field.end !== null && field.end <= child.end);
+ if (field.id === TITLE) voidOf(field.start, field.end!);
+ i = field.end!;
+ }
+ }
+ c = child.end;
+ continue;
+ }
+ // A cluster of unknown size (a live writer) ends where the next segment-level element starts.
+ need(child.id === CLUSTER);
+ c = child.data;
+ while (c < segEnd) {
+ const inner = element(c);
+ if (CLUSTER_ENDS.has(inner.id)) break;
+ need(inner.end !== null && inner.end <= segEnd);
+ c = inner.end!;
+ }
+ }
+ at = segEnd;
+ }
+ return out;
+}
+
+/** An ID3v2 tag at `at`: its frames become padding (zeros). Returns where the audio starts. */
+function id3v2(r: Reader, at: number, out: Patch[]): number {
+ const h = r.read(at, 10);
+ need(h.length === 10);
+ const size = (h[6] & 0x7f) * 2 ** 21 + (h[7] & 0x7f) * 2 ** 14 + (h[8] & 0x7f) * 2 ** 7 + (h[9] & 0x7f);
+ need(at + 10 + size <= r.size);
+ out.push({ at: at + 5, bytes: Buffer.from([0]) }, zeros(at + 10, size));
+ return at + 10 + size + (h[5] & 0x10 ? 10 : 0);
+}
+
+/** MP3: the ID3v2 tag's frames become padding; an ID3v1 tag at the end is emptied. */
+function mp3(r: Reader): Patch[] {
+ const out: Patch[] = [];
+ if (r.read(0, 3).toString("latin1") === "ID3") id3v2(r, 0, out);
+ // An empty ID3v1 tag (no genre) rather than 128 zero bytes a decoder would take for audio.
+ if (r.size >= 128 && r.read(r.size - 128, 3).toString("latin1") === "TAG") out.push(zeros(r.size - 125, 124), { at: r.size - 1, bytes: Buffer.from([0xff]) });
+ return out;
+}
+
+/** FLAC: VORBIS_COMMENT blocks become PADDING, zeroed (and a leading ID3 tag is blanked). */
+function flac(r: Reader): Patch[] {
+ const out: Patch[] = [];
+ let at = r.read(0, 3).toString("latin1") === "ID3" ? id3v2(r, 0, out) : 0;
+ need(r.read(at, 4).toString("latin1") === "fLaC");
+ at += 4;
+ for (;;) {
+ const h = r.read(at, 4);
+ need(h.length === 4);
+ const last = h[0] & 0x80;
+ const type = h[0] & 0x7f;
+ const len = h.readUIntBE(1, 3);
+ need(at + 4 + len <= r.size);
+ if (type === 4) out.push({ at, bytes: Buffer.from([last | 1]) }, zeros(at + 4, len));
+ at += 4 + len;
+ if (last) return out;
+ }
+}
+
+const OGG_TABLE = (() => {
+ const t = new Uint32Array(256);
+ for (let n = 0; n < 256; n++) {
+ let c = n << 24;
+ for (let k = 0; k < 8; k++) c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : c << 1;
+ t[n] = c >>> 0;
+ }
+ return t;
+})();
+
+/** Ogg (Opus, Vorbis, Theora): each comment in the comment header becomes "_=" and spaces; its pages get fresh CRCs. */
+function ogg(r: Reader): Patch[] {
+ // The first stream's second packet, as pieces of page bodies.
+ const pieces: { page: number; from: number; len: number }[] = [];
+ const pages = new Map<number, number>(); // page start → page end
+ let serial: number | null = null;
+ let packet = 0;
+ let at = 0;
+ while (packet < 2) {
+ const h = r.read(at, 27);
+ need(h.length === 27 && h.toString("latin1", 0, 4) === "OggS");
+ const table = r.read(at + 27, h[26]);
+ need(table.length === h[26]);
+ let off = at + 27 + table.length;
+ const end = off + table.reduce((a, b) => a + b, 0);
+ need(end <= r.size);
+ serial ??= h.readUInt32LE(14);
+ if (h.readUInt32LE(14) === serial) {
+ for (const seg of table) {
+ if (packet === 1) {
+ pieces.push({ page: at, from: off, len: seg });
+ pages.set(at, end);
+ }
+ off += seg;
+ if (seg < 255 && ++packet === 2) break;
+ }
+ }
+ at = end;
+ }
+ const body = Buffer.concat(pieces.map((p) => r.read(p.from, p.len)));
+ const head = body.toString("latin1", 0, 8);
+ const start = head === "OpusTags" ? 8 : /^[\x03\x81](vorbis|theora)$/.test(body.toString("latin1", 0, 7)) ? 7 : -1;
+ if (start < 0) return []; // another codec's header: no comments in this layout
+ const edited = Buffer.from(body);
+ let p = start;
+ need(p + 4 <= body.length);
+ p += 4 + body.readUInt32LE(p);
+ need(p + 4 <= body.length);
+ const count = body.readUInt32LE(p);
+ p += 4;
+ for (let i = 0; i < count; i++) {
+ need(p + 4 <= body.length);
+ const len = body.readUInt32LE(p);
+ p += 4;
+ need(p + len <= body.length);
+ edited.fill(0x20, p, p + len);
+ edited.write("_=".slice(0, len), p, "latin1");
+ p += len;
+ }
+ // Rewrite each page that carries the packet, with its CRC worked out again.
+ const out: Patch[] = [];
+ let k = 0;
+ for (const [page, end] of pages) {
+ const bytes = r.read(page, end - page);
+ for (const piece of pieces) {
+ if (piece.page === page) edited.copy(bytes, piece.from - page, k, k + piece.len);
+ if (piece.page === page) k += piece.len;
+ }
+ bytes.writeUInt32LE(0, 22);
+ let c = 0;
+ for (const b of bytes) c = ((c << 8) ^ OGG_TABLE[((c >>> 24) ^ b) & 0xff]) >>> 0;
+ bytes.writeUInt32LE(c, 22);
+ out.push({ at: page, bytes });
+ }
+ return out;
+}
+
+/** GLB: the JSON chunk without `extras` on the asset or the root, padded with spaces to its old length. */
+function glb(r: Reader): Patch[] {
+ const h = r.read(12, 8);
+ need(h.length === 8 && h.toString("latin1", 4, 8) === "JSON");
+ const len = h.readUInt32LE(0);
+ need(20 + len <= r.size && len < 64 * 1024 * 1024);
+ const text = r.read(20, len).toString("utf8");
+ let doc: { asset?: { extras?: unknown }; extras?: unknown };
+ try {
+ doc = JSON.parse(text) as typeof doc;
+ } catch {
+ throw new Unreadable();
+ }
+ if (doc.asset?.extras === undefined && doc.extras === undefined) return [];
+ delete doc.asset?.extras;
+ delete doc.extras;
+ const next = Buffer.from(JSON.stringify(doc), "utf8");
+ need(next.length <= len);
+ return [{ at: 20, bytes: Buffer.concat([next, Buffer.alloc(len - next.length, 0x20)]) }];
+}
+
+/** SVG: what's inside each <metadata> element becomes spaces. */
+function svg(r: Reader): Patch[] {
+ need(r.size < 32 * 1024 * 1024);
+ const text = r.read(0, r.size).toString("latin1");
+ const lower = text.toLowerCase();
+ const out: Patch[] = [];
+ const open = /<metadata\b[^>]*>/gi;
+ for (let m = open.exec(text); m; m = open.exec(text)) {
+ const from = m.index + m[0].length;
+ const close = lower.indexOf("</metadata", from);
+ need(close >= 0);
+ if (close > from) out.push({ at: from, length: close - from, fill: 0x20 });
+ open.lastIndex = close;
+ }
+ return out;
+}
+
+/** The patches that clear a file's embedded metadata ([] when it has none), or null when it can't be read. */
+export function metadataPatches(abs: string, contentType = ""): Patch[] | null {
+ let fd: number | undefined;
+ try {
+ fd = fs.openSync(abs, "r");
+ const r = new Reader(fd, fs.fstatSync(fd).size);
+ const head = r.read(0, 16);
+ const at = (s: string, i = 0) => head.toString("latin1", i, i + s.length) === s;
+ if (head.length >= 8 && head.readUInt32BE(0) === 0x89504e47) return png(r);
+ if (head[0] === 0xff && head[1] === 0xd8) return jpeg(r);
+ if (at("RIFF") && at("WEBP", 8)) return riff(r, true);
+ if ((at("RIFF") || at("RF64")) && at("WAVE", 8)) return riff(r, false);
+ if (head.length >= 4 && head.readUInt32BE(0) === EBML) return matroska(r);
+ if (at("glTF")) return glb(r);
+ if (at("OggS")) return ogg(r);
+ if (at("fLaC")) return flac(r);
+ // An ID3 tag starts MP3s and, now and then, a FLAC file: what follows it tells them apart.
+ if (at("ID3")) return r.read(id3v2(r, 0, []), 4).toString("latin1") === "fLaC" ? flac(r) : mp3(r);
+ if (/audio\/(mpeg|mp3)/.test(contentType)) return mp3(r);
+ if (head.length >= 8 && /^(ftyp|moov|mdat|free|skip|wide|pnot|uuid)$/.test(head.toString("latin1", 4, 8))) return isoBmff(r);
+ if (contentType === "image/svg+xml") return svg(r);
+ return [];
+ } catch (e) {
+ if (e instanceof Unreadable || e instanceof RangeError) return null;
+ throw e;
+ } finally {
+ if (fd !== undefined) fs.closeSync(fd);
+ }
+}
+
+const cache = new Map<string, Patch[] | null>();
+
+/** metadataPatches, remembered per file version (path, size, modified time). Stored files don't change. */
+export function cachedPatches(abs: string, stat: { size: number; mtimeMs: number }, contentType: string): Patch[] | null {
+ const key = `${abs}\0${stat.size}\0${stat.mtimeMs}`;
+ if (cache.has(key)) return cache.get(key)!;
+ const patches = metadataPatches(abs, contentType);
+ if (cache.size >= 500) cache.delete(cache.keys().next().value!);
+ cache.set(key, patches);
+ return patches;
+}
diff --git a/src/server/share-access.ts b/src/server/share-access.ts
index c5970c0b..fdf36c35 100644
--- a/src/server/share-access.ts
+++ b/src/server/share-access.ts
@@ -117,34 +117,48 @@ export function shareTargetExists(row: Pick<ShareRow, "kind" | "target_id">): bo
// 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.
+ * Limits wrong share tokens without letting anyone switch working links off. A live link is looked
+ * up first and always opens: other people's misses never block it. A miss (an unknown, wrong or
+ * expired token) counts once per token per window, so a page left open after its link was revoked
+ * (one miss per lazy-loaded file) counts as one. Past the global budget, misses answer 429 instead
+ * of 404. A client the server can tell apart (the last X-Forwarded-For hop behind a trusted reverse
+ * proxy, FUOBE_TRUST_PROXY=1, see LoginGuard.clientKey) that misses too often is locked out of
+ * share links for a minute, its own working ones included, so it can't tell a hit from a miss
+ * meanwhile. Without a trusted proxy every visitor shares one key, which is never locked (a lock
+ * would let anyone take every link down). Tokens carry 192 random bits, so this is about load and
+ * noise more than about odds. A signed-in owner is never limited.
*/
export class ShareGuard {
private misses = new Map<string, { n: number; first: number; until: number }>();
- private recent: number[] = [];
- private globalUntil = 0;
+ private recent = new Map<string, number>(); // missed token → when it first missed in this window
+ private globalMisses: number[] = []; // the times of the last `global` misses, oldest first (a flood can't grow it)
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). */
+ /** Milliseconds until this client's share requests are looked up again (0 = now). Only a told-apart client is ever locked. */
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);
+ return own && own.until > now ? own.until - 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 = [];
+ /** Whether misses are over the global budget (they then answer 429; working links still open). */
+ saturated(now = Date.now()): boolean {
+ return this.globalMisses.length >= this.o.global && now - this.globalMisses[0] < this.o.windowMs;
+ }
+
+ /** A wrong token. `shared`: the key is everyone's (no trusted proxy), so only the global budget counts. */
+ miss(key: string, token: string, shared: boolean, now = Date.now()): void {
+ for (const [t, at] of this.recent) {
+ if (now - at < this.o.windowMs && this.recent.size <= this.o.maxClients * 4) break;
+ this.recent.delete(t);
}
- if (shared) return; // one key for everyone: the global budget is its budget
+ // The same dead token again (a page's files, a reload) is one miss.
+ const seen = `${key}\0${token}`;
+ if (this.recent.has(seen)) return;
+ this.recent.set(seen, now);
+ this.globalMisses.push(now);
+ if (this.globalMisses.length > this.o.global) this.globalMisses.shift();
+ if (shared) return;
const m = this.misses.get(key);
const fresh = !m || now - m.first > this.o.windowMs;
const n = fresh ? 1 : m.n + 1;
diff --git a/src/server/shares.ts b/src/server/shares.ts
index 06a152af..521d438b 100644
--- a/src/server/shares.ts
+++ b/src/server/shares.ts
@@ -9,11 +9,13 @@ import "server-only";
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 { unwrapScene } from "@/lib/storyboard-board";
import { shownOutputs } from "@/lib/output-actions";
import {
expiryFrom,
fileName,
MAX_EXPIRY_DAYS,
+ MAX_PUBLISH_ITEMS,
outputFiles,
parseTags,
SHARE_KINDS,
@@ -45,7 +47,7 @@ export class ShareError extends Error {
/** 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;
+export { MAX_PUBLISH_ITEMS };
const MAX_TITLE = 120;
const MAX_DESCRIPTION = 1000;
@@ -57,44 +59,50 @@ 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 });
+/**
+ * The query for what a share shows, in page order: a folder or project its newest SCOPE_LIMIT + 1
+ * (one more tells the page there are more), a published page its picked results.
+ */
+function scopeQuery(s: Pick<ShareRow, "kind" | "target_id" | "items_json">): { sql: string; args: unknown[]; ids?: string[] } {
switch (s.kind) {
case "result":
- return { list: all(`SELECT ${COLUMNS} FROM generations g WHERE g.id = ? AND ${SHOWN}`, s.target_id), truncated: false };
+ return { sql: `SELECT ${COLUMNS} FROM generations g WHERE g.id = ? AND ${SHOWN}`, args: [s.target_id] };
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,
- ),
- );
+ return {
+ sql: `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 ?`,
+ args: [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,
- ),
- );
+ return {
+ sql: `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 ?`,
+ args: [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 };
+ return { sql: `SELECT ${COLUMNS} FROM generations g WHERE g.id IN (${marks(ids.length) || "NULL"}) AND ${SHOWN}`, args: ids, ids };
}
}
}
+const rowsOf = (q: { sql: string; args: unknown[] }) => (db().prepare(q.sql).all(...q.args) as GenRow[]).map(toGeneration);
+
+/** 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 q = scopeQuery(s);
+ const list = rowsOf(q);
+ if (q.ids) {
+ const found = new Map(list.map((g) => [g.id, g]));
+ return { list: q.ids.map((id) => found.get(id)).filter((g): g is Generation => !!g), truncated: false };
+ }
+ return { list: list.slice(0, SCOPE_LIMIT), truncated: list.length > SCOPE_LIMIT };
+}
+
function parseIds(json: string): string[] {
try {
const v = JSON.parse(json) as unknown;
@@ -104,12 +112,39 @@ function parseIds(json: string): string[] {
}
}
+/** The outputs a piece shows: a 3D result its turntable (a video output) with the model as a download, else what feeds show. */
+const shownIndices = (g: Generation) => (g.kind === "model3d" ? g.outputs.map((_, i) => i) : shownOutputs(g));
+
+/** The stored files a piece puts on a page: each shown output's file and its poster, thumbnail or preview. */
+function itemFiles(g: Generation): string[] {
+ return shownIndices(g).flatMap((i) => (g.outputs[i] && storedPath(g.outputs[i].url) ? outputFiles(g.outputs[i]) : []));
+}
+
/** 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;
}
+const norm = (t: string) => t.toLowerCase().replace(/\s+/g, " ").trim();
+
+/** Everything a piece was asked with in words: its prompt and, for a storyboard frame, the scene. */
+function promptTexts(g: Generation): string[] {
+ const scene = g.request.frame?.scene;
+ return [g.request.prompt, g.prompt, scene, scene && unwrapScene(scene)].filter((t): t is string => !!t?.trim()).map(norm);
+}
+
+/**
+ * Whether a result's link title is (the start of) its prompt, or holds the whole prompt: what the
+ * Share dialog offers while Show prompts is on. A page that hides prompts doesn't show one. (A
+ * folder, project or published page is titled by its name or by the owner in the wizard.)
+ */
+function madeFromPrompt(title: string, list: Generation[]): boolean {
+ const t = norm(title);
+ if (t.length < 4) return false;
+ return list.some((g) => promptTexts(g).some((p) => p === t || (t.length >= 12 && p.startsWith(t)) || (p.length >= 12 && t.includes(p))));
+}
+
/** 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);
@@ -151,12 +186,15 @@ export function buildPublicShare(row: ShareRow, token: string): { page: PublicSh
const named = itemTitle(g, share.showPrompts);
// The prompt shows under the title, so a title that is only the prompt again says what was made instead.
const title = prompt && prompt.startsWith(named) ? itemTitle(g, false) : named;
- // 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, named) })).filter((x): x is { i: number; m: PublicMedia } => !!x.m);
+ const list = shownIndices(g)
+ .map((i) => ({ i, m: media(g.outputs[i], i, named) }))
+ .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;
+ // The picked output leads its piece (Feature's hero, Download).
+ const at = Math.max(0, list.findIndex((x) => x.i === share.cover!.index));
+ list.unshift(...list.splice(at, 1));
+ cover = list[0].m;
coverKey = key;
}
items.push({
@@ -180,10 +218,13 @@ export function buildPublicShare(row: ShareRow, token: string): { page: PublicSh
}
}
}
+ // A result's title made from its prompt (kept from when the page showed prompts, or sent through
+ // the API) isn't shown on a page that hides them: what was made, and with what, is.
+ const title = !share.showPrompts && share.kind === "result" && madeFromPrompt(share.title, sc.list) ? defaultTitle(share.kind, share.targetId, sc.list) : share.title;
return {
page: {
kind: share.kind,
- title: share.title,
+ title,
description: share.description,
tags: share.tags,
layout: share.layout,
@@ -198,12 +239,35 @@ export function buildPublicShare(row: ShareRow, token: string): { page: PublicSh
};
}
+/** The stored files a share's page shows now (its pieces' shown outputs, posters and thumbnails). */
+function pageFiles(row: ShareRow): Set<string> {
+ return new Set((scope(row)?.list ?? []).flatMap(itemFiles));
+}
+
+/** Changes whenever anything is written to the database (by this process or another one). */
+function dbStamp(): string {
+ const d = db();
+ return `${d.prepare("SELECT total_changes()").pluck().get()}:${d.pragma("data_version", { simple: true })}`;
+}
+
+const served = new Map<string, { stamp: string; files: Set<string> }>();
+
/**
- * Whether a share may serve this stored file: only one its page shows now. Worked out per request
- * (no cache), so a result taken to the Trash or out of a folder stops opening at once.
+ * Whether a share may serve this stored file: only one its page shows now. The page's file list is
+ * worked out again after any write to the database, so a result taken to the Trash or out of a
+ * folder stops opening at once; between writes (a visitor scrolling a 200-piece page, or someone
+ * looping wrong file names) each file is one lookup, not a rebuild of the page.
*/
-export function shareServesFile(row: ShareRow, token: string, rel: string): boolean {
- return buildPublicShare(row, token)?.files.has(rel) ?? false;
+export function shareServesFile(row: ShareRow, rel: string): boolean {
+ const stamp = dbStamp();
+ let hit = served.get(row.id);
+ if (hit?.stamp !== stamp) {
+ hit = { stamp, files: pageFiles(row) };
+ served.delete(row.id);
+ if (served.size >= 200) served.delete(served.keys().next().value!);
+ served.set(row.id, hit);
+ }
+ return hit.files.has(rel);
}
/** A page view by someone other than the signed-in owner. */
@@ -218,14 +282,17 @@ export type CreateShareInput = ShareRequest;
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 {
+/**
+ * What a link is called when the owner leaves the title empty, or when prompts are hidden and its
+ * title was made from one: the result's kind and model, the folder's or project's own name.
+ */
+function defaultTitle(kind: ShareKind, targetId: string | null, list?: Generation[]): 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";
+ const g = list?.[0] ?? (targetId ? scope({ kind, target_id: targetId, items_json: "[]" })?.list[0] : undefined);
+ return g ? `${itemTitle(g, false)} · ${getModel(g.modelId)?.name ?? g.modelName ?? g.modelId}` : "Shared result";
}
return "Untitled";
}
@@ -317,7 +384,11 @@ function thumbOf(list: Generation[], cover: ShareInfo["cover"]): ShareListItem["
return { url: out.url, kind: out.kind, ...(poster && { poster }) };
}
-/** Change a link (its words, prompts on or off, a new expiry from now), or give it a new token. */
+/**
+ * Change a link (its words, prompts on or off, a new expiry from now), or give it a new token. A new
+ * token for a link that has expired needs a new expiry too (else the new link is dead on arrival).
+ * Turning prompts off swaps a title made from a prompt for the hide-safe one.
+ */
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;
@@ -327,9 +398,15 @@ export function updateShare(id: string, patch: SharePatch, now = Date.now()): {
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.showPrompts === false && patch.title === undefined && r.show_prompts && r.kind === "result") {
+ const list = scope(r)?.list ?? [];
+ if (madeFromPrompt(r.title, list)) sets.title = defaultTitle(r.kind, r.target_id, list);
+ }
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);
+ } else if (patch.newLink && r.expires_at !== null && r.expires_at <= now) {
+ throw new ShareError("This link has expired: pick how long the new one works");
}
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.
diff --git a/tests/media-clean.test.ts b/tests/media-clean.test.ts
new file mode 100644
index 00000000..1864a9a1
--- /dev/null
+++ b/tests/media-clean.test.ts
@@ -0,0 +1,335 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { Readable } from "node:stream";
+import zlib from "node:zlib";
+import { afterAll, describe, expect, it } from "vitest";
+import { metadataPatches, overlay, patchStream, type Patch } from "@/server/media-clean";
+
+/**
+ * Files on share pages lose the generation data saved inside them (ComfyUI writes its prompt and
+ * workflow into PNG text chunks, MP4/WebM/FLAC/MP3/Ogg tags, GLB extras and SVG metadata). Each
+ * fixture here is a small, well-formed file of that format carrying SECRET where that tool puts it.
+ */
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-clean-"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const SECRET = "SECRET violet tiger prompt";
+let n = 0;
+function file(data: Buffer, ext: string): string {
+ const p = path.join(dir, `f${n++}.${ext}`);
+ fs.writeFileSync(p, data);
+ return p;
+}
+
+/** The file as the share route sends it. */
+function cleaned(p: string, type = ""): Buffer {
+ const patches = metadataPatches(p, type);
+ expect(patches, p).not.toBeNull();
+ const data = fs.readFileSync(p);
+ const out = overlay(data, 0, patches!);
+ expect(out.length).toBe(data.length); // same size: byte ranges and offsets stay valid
+ return out;
+}
+
+const u32be = (v: number) => {
+ const b = Buffer.alloc(4);
+ b.writeUInt32BE(v);
+ return b;
+};
+const u32le = (v: number) => {
+ const b = Buffer.alloc(4);
+ b.writeUInt32LE(v);
+ return b;
+};
+const u16be = (v: number) => {
+ const b = Buffer.alloc(2);
+ b.writeUInt16BE(v);
+ return b;
+};
+
+const CRC = Array.from({ length: 256 }, (_, k) => {
+ let c = k;
+ for (let i = 0; i < 8; i++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+});
+const crc32 = (b: Buffer) => {
+ let c = 0xffffffff;
+ for (const x of b) c = CRC[(c ^ x) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+};
+const pngChunk = (type: string, data: Buffer) => Buffer.concat([u32be(data.length), Buffer.from(type, "latin1"), data, u32be(crc32(Buffer.concat([Buffer.from(type, "latin1"), data])))]);
+
+function pngChunks(b: Buffer): { type: string; data: Buffer; crcOk: boolean }[] {
+ const out = [];
+ for (let at = 8; at < b.length; ) {
+ const len = b.readUInt32BE(at);
+ const type = b.toString("latin1", at + 4, at + 8);
+ const data = b.subarray(at + 8, at + 8 + len);
+ out.push({ type, data, crcOk: crc32(b.subarray(at + 4, at + 8 + len)) === b.readUInt32BE(at + 8 + len) });
+ at += 12 + len;
+ }
+ return out;
+}
+
+const box = (type: string, ...children: Buffer[]) => {
+ const body = Buffer.concat(children);
+ return Buffer.concat([u32be(8 + body.length), Buffer.from(type, "latin1"), body]);
+};
+
+describe("media metadata", () => {
+ it("PNG: text and EXIF chunks become a private chunk decoders skip, zeroed, with valid CRCs; pixels untouched", () => {
+ const idat = zlib.deflateSync(Buffer.from([0, 10, 20, 30, 255]));
+ const src = Buffer.concat([
+ Buffer.from("89504e470d0a1a0a", "hex"),
+ pngChunk("IHDR", Buffer.from("00000001000000010806000000", "hex")),
+ pngChunk("tEXt", Buffer.from(`prompt\0{"6": {"inputs": {"text": "${SECRET}"}}}`, "latin1")),
+ pngChunk("zTXt", Buffer.concat([Buffer.from("workflow\0\0", "latin1"), zlib.deflateSync(Buffer.from(SECRET))])),
+ pngChunk("iTXt", Buffer.from(`parameters\0\0\0\0\0${SECRET}`, "utf8")),
+ pngChunk("IDAT", idat),
+ pngChunk("eXIf", Buffer.from(`MM\0*${SECRET}`, "latin1")),
+ pngChunk("IEND", Buffer.alloc(0)),
+ ]);
+ const out = cleaned(file(src, "png"));
+ const chunks = pngChunks(out);
+ expect(chunks.map((c) => c.type)).toEqual(["IHDR", "fuPd", "fuPd", "fuPd", "IDAT", "fuPd", "IEND"]);
+ expect(chunks.every((c) => c.crcOk)).toBe(true);
+ expect(chunks.filter((c) => c.type === "fuPd").every((c) => c.data.every((x) => x === 0))).toBe(true);
+ expect(zlib.inflateSync(chunks[4].data)).toEqual(Buffer.from([0, 10, 20, 30, 255]));
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ });
+
+ it("JPEG: EXIF/XMP and comments become empty comments; JFIF, ICC and Adobe segments and the image stay", () => {
+ const seg = (m: number, data: Buffer) => Buffer.concat([Buffer.from([0xff, m]), u16be(data.length + 2), data]);
+ const scan = Buffer.from([0x12, 0x34, 0xff, 0x00, 0x56]);
+ const src = Buffer.concat([
+ Buffer.from([0xff, 0xd8]),
+ seg(0xe0, Buffer.from("JFIF\0\x01\x01\0\0\x01\0\x01\0\0", "latin1")),
+ seg(0xe1, Buffer.from(`Exif\0\0MM\0*${SECRET}`, "latin1")),
+ seg(0xe2, Buffer.from("ICC_PROFILE\0\x01\x01profile", "latin1")),
+ seg(0xed, Buffer.from(`Photoshop 3.0\0${SECRET}`, "latin1")),
+ seg(0xfe, Buffer.from(SECRET, "latin1")),
+ seg(0xee, Buffer.from("Adobe\0\x64\0\0\0\0\x01", "latin1")),
+ seg(0xdb, Buffer.alloc(65, 1)),
+ seg(0xda, Buffer.from([1, 1, 0, 0, 0x3f, 0])),
+ scan,
+ Buffer.from([0xff, 0xd9]),
+ ]);
+ const out = cleaned(file(src, "jpg"));
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ expect(out.toString("latin1")).toContain("JFIF");
+ expect(out.toString("latin1")).toContain("ICC_PROFILE");
+ expect(out.toString("latin1")).toContain("Adobe");
+ const markers: number[] = [];
+ for (let at = 2; out[at] === 0xff && out[at + 1] !== 0xda; at += 2 + out.readUInt16BE(at + 2)) markers.push(out[at + 1]);
+ expect(markers).toEqual([0xe0, 0xfe, 0xe2, 0xfe, 0xfe, 0xee, 0xdb]);
+ expect(out.subarray(out.length - 2 - scan.length)).toEqual(src.subarray(src.length - 2 - scan.length));
+ });
+
+ it("WebP: EXIF and XMP chunks become JUNK and VP8X stops announcing them", () => {
+ const chunk = (id: string, data: Buffer) => Buffer.concat([Buffer.from(id, "latin1"), u32le(data.length), data, data.length & 1 ? Buffer.alloc(1) : Buffer.alloc(0)]);
+ const body = Buffer.concat([
+ Buffer.from("WEBP"),
+ chunk("VP8X", Buffer.from([0x0c | 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0])),
+ chunk("VP8L", Buffer.from("not-really-pixels")),
+ chunk("EXIF", Buffer.from(`MM\0*${SECRET}`, "latin1")),
+ chunk("XMP ", Buffer.from(`<x:xmpmeta>${SECRET}</x:xmpmeta>`)),
+ ]);
+ const out = cleaned(file(Buffer.concat([Buffer.from("RIFF"), u32le(body.length), body]), "webp"));
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ expect(out.toString("latin1")).not.toMatch(/EXIF|XMP /);
+ expect(out[20] & 0x0c).toBe(0); // VP8X flags: no EXIF, no XMP
+ expect(out[20] & 0x10).toBe(0x10); // the alpha flag stays
+ expect(out.toString("latin1")).toContain("not-really-pixels");
+ });
+
+ it("WAV: INFO and ID3 chunks become JUNK; the samples stay", () => {
+ const chunk = (id: string, data: Buffer) => Buffer.concat([Buffer.from(id, "latin1"), u32le(data.length), data]);
+ const body = Buffer.concat([Buffer.from("WAVE"), chunk("fmt ", Buffer.alloc(16, 1)), chunk("LIST", Buffer.from(`INFOICMT${SECRET}`)), chunk("data", Buffer.from("samples!"))]);
+ const out = cleaned(file(Buffer.concat([Buffer.from("RIFF"), u32le(body.length), body]), "wav"));
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ expect(out.toString("latin1")).toContain("JUNK");
+ expect(out.toString("latin1")).toContain("samples!");
+ });
+
+ it("WAV written to a pipe (sizes left at 0xFFFFFFFF) or as RF64: still cleaned, not refused", () => {
+ const chunk = (id: string, data: Buffer, size = data.length) => Buffer.concat([Buffer.from(id, "latin1"), u32le(size), data]);
+ const body = (riff: string) =>
+ Buffer.concat([Buffer.from(riff), u32le(0xffffffff), Buffer.from("WAVE"), chunk("fmt ", Buffer.alloc(16, 1)), chunk("LIST", Buffer.from(`INFOINAM${SECRET}`)), chunk("data", Buffer.from("samples!"), 0xffffffff)]);
+ for (const riff of ["RIFF", "RF64"]) {
+ const out = cleaned(file(body(riff), "wav"));
+ expect(out.toString("latin1"), riff).not.toContain("SECRET");
+ expect(out.toString("latin1")).toContain("JUNK");
+ expect(out.subarray(out.length - 8).toString()).toBe("samples!");
+ }
+ // A metadata chunk cut off by the end of the file is blanked to the end.
+ const cut = Buffer.concat([Buffer.from("RIFF"), u32le(0), Buffer.from("WAVE"), chunk("fmt ", Buffer.alloc(16, 1)), chunk("LIST", Buffer.from(`INFOINAM${SECRET}`), 4000)]);
+ expect(cleaned(file(cut, "wav")).toString("latin1")).not.toContain("SECRET");
+ });
+
+ it("MP4 / WebM cut off in their media data (a stopped recording, a partial download) are cleaned, not refused", () => {
+ const meta = box("udta", box("meta", Buffer.alloc(4), box("ilst", box("©cmt", box("data", Buffer.alloc(8), Buffer.from(SECRET))))));
+ const mp4 = Buffer.concat([box("ftyp", Buffer.from("isom\0\0\x02\0isom", "latin1")), box("moov", box("mvhd", Buffer.alloc(100)), meta), u32be(5000), Buffer.from("mdatframes")]);
+ expect(cleaned(file(mp4, "mp4")).toString("latin1")).not.toContain("SECRET");
+ // …but not when the cut is in the movie box (where metadata lives).
+ expect(metadataPatches(file(Buffer.concat([box("ftyp", Buffer.from("isom")), u32be(5000), Buffer.from("moov"), meta]), "mp4"))).toBeNull();
+
+ const el = (id: number[], data: Buffer, size = data.length) => Buffer.concat([Buffer.from(id), Buffer.from([0x40 | (size >> 8), size & 0xff]), data]);
+ const webm = Buffer.concat([
+ el([0x1a, 0x45, 0xdf, 0xa3], el([0x42, 0x82], Buffer.from("webm"))),
+ el([0x18, 0x53, 0x80, 0x67], Buffer.concat([el([0x12, 0x54, 0xc3, 0x67], el([0x73, 0x73], Buffer.from(SECRET))), el([0x1f, 0x43, 0xb6, 0x75], Buffer.from("cut-frames"), 3000)]), 4000),
+ ]);
+ const out = cleaned(file(webm, "webm"));
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ expect(out.toString("latin1")).toContain("cut-frames");
+ });
+
+ it("MP4 / MOV: the movie's and tracks' user data and metadata become free boxes; media data and offsets stay", () => {
+ const ilst = box("meta", Buffer.alloc(4), box("hdlr", Buffer.alloc(20)), box("ilst", box("©cmt", box("data", Buffer.alloc(8), Buffer.from(SECRET)))));
+ const src = Buffer.concat([
+ box("ftyp", Buffer.from("isom\0\0\x02\0isomavc1", "latin1")),
+ box("moov", box("mvhd", Buffer.alloc(100)), box("trak", box("tkhd", Buffer.alloc(84)), box("udta", box("name", Buffer.from(SECRET)))), box("udta", ilst)),
+ // A 64-bit-size mdat (largesize) holding the frames.
+ Buffer.concat([u32be(1), Buffer.from("mdat"), Buffer.from([0, 0, 0, 0, 0, 0, 0, 16 + 6]), Buffer.from("frames")]),
+ ]);
+ const out = cleaned(file(src, "mp4"));
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ expect(out.toString("latin1")).not.toContain("udta");
+ expect(out.toString("latin1")).toContain("mvhd");
+ expect(out.toString("latin1")).toContain("tkhd");
+ expect(out.subarray(out.length - 6).toString()).toBe("frames");
+ });
+
+ it("MP4: keeps an AVIF/HEIF image's top-level meta (its picture is described there)", () => {
+ const src = Buffer.concat([box("ftyp", Buffer.from("avif\0\0\0\0mif1", "latin1")), box("meta", Buffer.alloc(4), box("pitm", Buffer.alloc(6))), box("mdat", Buffer.from("pixels"))]);
+ expect(metadataPatches(file(src, "avif"))).toEqual([]);
+ });
+
+ it("WebM / MKV: Tags and the segment title become Void elements; clusters (even of unknown size) stay", () => {
+ const vint = (v: number) => Buffer.from([0x80 | v]); // sizes < 127
+ const el = (id: number[], data: Buffer) => Buffer.concat([Buffer.from(id), vint(data.length), data]);
+ const unknown = Buffer.from([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
+ const src = Buffer.concat([
+ el([0x1a, 0x45, 0xdf, 0xa3], el([0x42, 0x82], Buffer.from("webm"))),
+ Buffer.from([0x18, 0x53, 0x80, 0x67]),
+ unknown, // a Segment of unknown size (a live writer)
+ el([0x15, 0x49, 0xa9, 0x66], Buffer.concat([el([0x2a, 0xd7, 0xb1], Buffer.from([0x0f, 0x42, 0x40])), el([0x7b, 0xa9], Buffer.from(SECRET))])),
+ Buffer.from([0x1f, 0x43, 0xb6, 0x75]),
+ unknown, // a Cluster of unknown size
+ el([0xe7], Buffer.from([0])),
+ el([0xa3], Buffer.from("a-frame")),
+ el([0x12, 0x54, 0xc3, 0x67], el([0x73, 0x73], el([0x67, 0xc8], Buffer.concat([el([0x45, 0xa3], Buffer.from("PROMPT")), el([0x44, 0x87], Buffer.from(SECRET))])))),
+ ]);
+ const out = cleaned(file(src, "webm"));
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ expect(out.toString("latin1")).not.toContain("PROMPT");
+ expect(out.toString("latin1")).toContain("a-frame");
+ expect(out.includes(Buffer.from([0x12, 0x54, 0xc3, 0x67]))).toBe(false);
+ expect(out.includes(Buffer.from([0x2a, 0xd7, 0xb1]))).toBe(true); // TimecodeScale stays
+ });
+
+ it("FLAC: Vorbis comments become padding (a leading ID3 tag too); the stream info stays", () => {
+ const block = (type: number, last: boolean, data: Buffer) => Buffer.concat([Buffer.from([(last ? 0x80 : 0) | type, data.length >> 16, (data.length >> 8) & 0xff, data.length & 0xff]), data]);
+ const id3 = Buffer.concat([Buffer.from("ID3\x04\0\0\0\0\0", "latin1"), Buffer.from([SECRET.length]), Buffer.from(SECRET)]);
+ const src = Buffer.concat([id3, Buffer.from("fLaC"), block(0, false, Buffer.alloc(34, 7)), block(4, true, Buffer.from(`\x05\0\0\0Lavf3\x01\0\0\0${SECRET}`, "latin1")), Buffer.from("audio-frames")]);
+ const out = cleaned(file(src, "flac"));
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ const at = out.indexOf("fLaC") + 4 + 4 + 34;
+ expect(out[at]).toBe(0x81); // the last block, now PADDING
+ expect(out.toString("latin1")).toContain("audio-frames");
+ });
+
+ it("MP3: the ID3v2 frames become padding and an ID3v1 tag is emptied; the audio stays", () => {
+ const frames = Buffer.concat([Buffer.from("TXXX", "latin1"), u32be(SECRET.length + 8), Buffer.from([0, 0, 3]), Buffer.from(`prompt\0${SECRET}`, "latin1")]);
+ const size = frames.length;
+ const id3 = Buffer.concat([Buffer.from("ID3\x04\0\x40", "latin1"), Buffer.from([0, 0, size >> 7, size & 0x7f]), frames]);
+ const v1 = Buffer.concat([Buffer.from("TAG"), Buffer.from(SECRET.padEnd(124, "\0")), Buffer.from([12])]);
+ const audio = Buffer.from([0xff, 0xfb, 0x90, 0x64, 1, 2, 3, 4]);
+ const out = cleaned(file(Buffer.concat([id3, audio, v1]), "mp3"), "audio/mpeg");
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ expect(out.subarray(0, 3).toString()).toBe("ID3");
+ expect(out[5]).toBe(0); // no extended header any more
+ expect(out.subarray(10, 10 + size).every((x) => x === 0)).toBe(true);
+ expect(out.subarray(10 + size, 10 + size + audio.length)).toEqual(audio);
+ expect(out.subarray(out.length - 128, out.length - 125).toString()).toBe("TAG");
+ expect(out[out.length - 1]).toBe(0xff); // no genre
+ });
+
+ it("Ogg: comments are blanked in place and the page checksum is worked out again", () => {
+ const OGG = Array.from({ length: 256 }, (_, k) => {
+ let c = k << 24;
+ for (let i = 0; i < 8; i++) c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : c << 1;
+ return c >>> 0;
+ });
+ const oggCrc = (b: Buffer) => {
+ let c = 0;
+ for (const x of b) c = ((c << 8) ^ OGG[((c >>> 24) ^ x) & 0xff]) >>> 0;
+ return c;
+ };
+ const page = (seq: number, packet: Buffer) => {
+ const head = Buffer.alloc(27);
+ head.write("OggS", 0, "latin1");
+ head.writeUInt32LE(77, 14);
+ head.writeUInt32LE(seq, 18);
+ head[26] = 1;
+ const p = Buffer.concat([head, Buffer.from([packet.length]), packet]);
+ p.writeUInt32LE(oggCrc(p), 22);
+ return p;
+ };
+ const comment = `PROMPT=${SECRET}`;
+ const tags = Buffer.concat([Buffer.from("OpusTags"), u32le(4), Buffer.from("Lavf"), u32le(1), u32le(comment.length), Buffer.from(comment)]);
+ const src = Buffer.concat([page(0, Buffer.from("OpusHead\x01\x02\0\0\x80\xbb\0\0\0\0\0", "latin1")), page(1, tags), page(2, Buffer.from("audio"))]);
+ const out = cleaned(file(src, "ogg"));
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ expect(out.toString("latin1")).toContain("Lavf");
+ const second = out.subarray(src.indexOf("OggS", 1), src.lastIndexOf("OggS"));
+ const zeroed = Buffer.from(second);
+ zeroed.writeUInt32LE(0, 22);
+ expect(second.readUInt32LE(22)).toBe(oggCrc(zeroed));
+ expect(out.subarray(out.length - 5).toString()).toBe("audio");
+ });
+
+ it("GLB: asset.extras goes, the JSON chunk keeps its length (spaces), the binary chunk stays", () => {
+ const json = Buffer.from(JSON.stringify({ asset: { version: "2.0", generator: "ComfyUI", extras: { prompt: SECRET } }, scenes: [{ nodes: [] }] }));
+ const pad = (4 - (json.length % 4)) % 4;
+ const jsonChunk = Buffer.concat([u32le(json.length + pad), Buffer.from("JSON"), json, Buffer.alloc(pad, 0x20)]);
+ const bin = Buffer.concat([u32le(4), Buffer.from("BIN\0", "latin1"), Buffer.from("mesh")]);
+ const total = 12 + jsonChunk.length + bin.length;
+ const out = cleaned(file(Buffer.concat([Buffer.from("glTF"), u32le(2), u32le(total), jsonChunk, bin]), "glb"));
+ const len = out.readUInt32LE(12);
+ const doc = JSON.parse(out.subarray(20, 20 + len).toString()) as { asset: Record<string, unknown> };
+ expect(doc.asset).toEqual({ version: "2.0", generator: "ComfyUI" });
+ expect(out.subarray(out.length - 4).toString()).toBe("mesh");
+ expect(out.toString("latin1")).not.toContain("SECRET");
+ });
+
+ it("SVG: the <metadata> element is emptied", () => {
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg">\n <metadata>\n<![CDATA[\n{"prompt": "${SECRET} ünïcode"}\n]]>\n</metadata><rect width="1" height="1"/></svg>`;
+ const out = cleaned(file(Buffer.from(svg), "svg"), "image/svg+xml").toString();
+ expect(out).not.toContain("SECRET");
+ expect(out).toMatch(/<metadata>\s+<\/metadata><rect/);
+ });
+
+ it("passes files without embedded metadata, and refuses a file it can't read where metadata lives", () => {
+ expect(metadataPatches(file(Buffer.from(`a transcript mentioning ${SECRET}`), "txt"), "text/plain")).toEqual([]);
+ expect(metadataPatches(file(Buffer.from("GIF89a\x01\0\x01\0\0\0\0;", "latin1"), "gif"))).toEqual([]);
+ const truncated = Buffer.concat([Buffer.from("89504e470d0a1a0a", "hex"), u32be(5000), Buffer.from("tEXtprompt")]);
+ expect(metadataPatches(file(truncated, "png"))).toBeNull();
+ expect(metadataPatches(file(Buffer.concat([box("ftyp", Buffer.from("isom")), u32be(9999), Buffer.from("moov")]), "mp4"))).toBeNull();
+ });
+
+ it("applies patches across chunk boundaries and from a range's start", async () => {
+ const data = Buffer.from("0123456789abcdefghij");
+ const patches: Patch[] = [
+ { at: 3, bytes: Buffer.from("XYZ") },
+ { at: 8, length: 6, fill: 0x2e },
+ ];
+ expect(overlay(data, 0, patches).toString()).toBe("012XYZ67......efghij");
+ // A range starting at 5, arriving in three pieces.
+ const parts = [data.subarray(5, 9), data.subarray(9, 12), data.subarray(12, 16)];
+ const chunks: Buffer[] = [];
+ for await (const c of Readable.from(parts).pipe(patchStream(patches, 5))) chunks.push(c as Buffer);
+ expect(Buffer.concat(chunks).toString()).toBe("Z67......ef");
+ expect(data.toString()).toBe("0123456789abcdefghij"); // the stored bytes aren't touched
+ });
+});
diff --git a/tests/share-links.test.ts b/tests/share-links.test.ts
index 2d2fb3be..99743a55 100644
--- a/tests/share-links.test.ts
+++ b/tests/share-links.test.ts
@@ -2,15 +2,21 @@ import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import zlib from "node:zlib";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
+import { userTitle } from "@/lib/library";
import type { ShareListItem } from "@/lib/share";
import type { ShareRow } from "@/server/share-access";
-// Route handlers call connection() (no request scope in a test).
+// Route handlers call connection() and the page reads its address from headers() (no request scope in a test).
vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.mock("next/headers", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("next/headers")>()),
+ headers: async () => new Headers({ host: "studio.example:3000", "x-forwarded-proto": "https" }),
+}));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-share-"));
process.env.FUOBE_DATA_DIR = dir;
@@ -32,6 +38,8 @@ 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("@/app/s/share-page");
+const sharePage = await import("@/app/s/[token]/page");
+const filesRoute = await import("@/app/api/files/[...path]/route");
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
afterEach(() => {
@@ -39,12 +47,48 @@ afterEach(() => {
globalThis.__fuobeShareGuard = undefined;
});
-const PNG = Buffer.from("89504e470d0a1a0a0000000d4948445200000001000000010806000000", "hex");
+const CRC = (() => {
+ const t = Array.from({ length: 256 }, (_, n) => {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+ });
+ return (b: Buffer) => {
+ let c = 0xffffffff;
+ for (const x of b) c = t[(c ^ x) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+ };
+})();
+
+function chunk(type: string, data: Buffer): Buffer {
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(data.length);
+ const body = Buffer.concat([Buffer.from(type, "latin1"), data]);
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(CRC(body));
+ return Buffer.concat([len, body, crc]);
+}
+
+/**
+ * A real 1×1 PNG that carries `marker` in a chunk of its own (so a test can tell files apart) and,
+ * like ComfyUI's, the run's prompt in a tEXt chunk when `embedded` is given.
+ */
+function png(marker: string, embedded?: string): Buffer {
+ const ihdr = Buffer.from("0000000100000001080600000000", "hex").subarray(0, 13);
+ return Buffer.concat([
+ Buffer.from("89504e470d0a1a0a", "hex"),
+ chunk("IHDR", ihdr),
+ chunk("tEST", Buffer.from(marker)),
+ ...(embedded ? [chunk("tEXt", Buffer.from(`prompt\0{"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "${embedded}"}}}`, "latin1"))] : []),
+ chunk("IDAT", zlib.deflateSync(Buffer.from([0, 255, 0, 0, 255]))),
+ chunk("IEND", Buffer.alloc(0)),
+ ]);
+}
-/** A finished generation with a real output file; its input is an upload of its own. */
+/** A finished generation with a real output file (its prompt saved inside it, as ComfyUI does); 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 input = saveFile({ data: png(`in ${prompt}`), contentType: "image/png", source: "upload" });
+ const asset = saveFile({ data: png(prompt, prompt), contentType: "image/png", source: "generation" });
const g = gens.recordLocalGeneration({
feature,
modelId: "local-color-grade",
@@ -188,6 +232,47 @@ describe("what a token serves", () => {
expect((await serve(A.share.id + "x".repeat(32), a.rel)).status).toBe(404);
});
+ it("serves files without the generation data saved inside them (ComfyUI's prompt and workflow), byte ranges included", async () => {
+ const { g } = made("metadata host");
+ const stored = saveFile({ data: png("pixels-of-the-piece", "a secret violet tiger prompt"), contentType: "image/png", source: "generation" });
+ const rel = share.storedPath(stored.url)!;
+ db().prepare("UPDATE generations SET outputs_json = ? WHERE id = ?").run(JSON.stringify([{ url: stored.url, kind: "image", contentType: "image/png" }]), g.id);
+ const S = shares.createShare({ kind: "result", targetId: g.id });
+ const original = fs.readFileSync(path.join(dir, "files", rel));
+ expect(original.toString("latin1")).toContain("violet tiger");
+
+ const res = await fileRoute.GET(new Request(`http://localhost/s/${S.token}/f/${rel}`), { params: Promise.resolve({ token: S.token, path: rel.split("/") }) });
+ const body = Buffer.from(await res.arrayBuffer());
+ expect(res.status).toBe(200);
+ expect(body.length).toBe(original.length);
+ expect(body.toString("latin1")).toContain("pixels-of-the-piece");
+ expect(body.toString("latin1")).not.toMatch(/violet tiger|class_type|tEXt/);
+ // A range from the middle of the file is the same bytes as the cleaned whole.
+ const ranged = await fileRoute.GET(new Request(`http://localhost/s/${S.token}/f/${rel}`, { headers: { range: "bytes=20-90" } }), { params: Promise.resolve({ token: S.token, path: rel.split("/") }) });
+ expect(ranged.status).toBe(206);
+ expect(Buffer.from(await ranged.arrayBuffer()).equals(body.subarray(20, 91))).toBe(true);
+ // The owner's own copy keeps everything.
+ const own = await filesRoute.GET(new Request(`http://localhost/api/files/${rel}`), { params: Promise.resolve({ path: rel.split("/") }) });
+ expect(Buffer.from(await own.arrayBuffer()).equals(original)).toBe(true);
+ });
+
+ it("serves only what a folder page shows: its newest 200", async () => {
+ const big = lib.createFolder({ name: "Big folder" });
+ const list = Array.from({ length: shares.SCOPE_LIMIT + 1 }, (_, i) => made(`crowded ${i}`));
+ lib.moveToFolder(
+ list.map((x) => x.g.id),
+ big.id,
+ );
+ list.forEach((x, i) => db().prepare("UPDATE generations SET created_at = ? WHERE id = ?").run(1_000_000 + i, x.g.id));
+ const S = shares.createShare({ kind: "folder", targetId: big.id });
+ const page = shares.buildPublicShare(access.findShare(S.token)!, S.token)!.page;
+ expect(page.items).toHaveLength(shares.SCOPE_LIMIT);
+ expect(page.truncated).toBe(true);
+ expect((await serve(S.token, list.at(-1)!.rel)).status).toBe(200);
+ expect((await serve(S.token, list[1].rel)).status).toBe(200);
+ expect((await serve(S.token, list[0].rel)).status).toBe(404); // the oldest isn't on the page
+ });
+
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 });
@@ -202,6 +287,8 @@ describe("what a token serves", () => {
const r3 = made("trashed tundra");
const S3 = shares.createShare({ kind: "result", targetId: r3.g.id });
+ // Served once (the share's file list is remembered between writes), then trashed: 404 at once.
+ expect((await serve(S3.token, r3.rel)).status).toBe(200);
lib.trashGenerations([r3.g.id]);
expect((await serve(S3.token, r3.rel)).status).toBe(404);
expect(access.shareTargetExists(access.findShare(S3.token)!)).toBe(false);
@@ -275,12 +362,31 @@ describe("prompts", () => {
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 });
+ it("turns prompts off for an existing link, title made from the prompt included", async () => {
+ const { g } = made("prompt that gets hidden later: amber koi in a moonlit pond");
+ // What the Share dialog sends while Show prompts is on and the title is left as it is.
+ const S = shares.createShare({ kind: "result", targetId: g.id, title: userTitle(g), showPrompts: true });
+ expect(S.share.title).toMatch(/amber koi/);
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/);
+ expect(((await res.json()) as { share: { title: string } }).share.title).toBe("Color grade · Color Grading");
+ const page = shares.buildPublicShare(access.findShare(S.token)!, S.token)!.page;
+ expect(JSON.stringify(page)).not.toMatch(/amber koi/);
+ expect(renderToStaticMarkup(createElement(SharePage, { share: page }))).not.toMatch(/amber koi/);
+ const meta = await sharePage.generateMetadata({ params: Promise.resolve({ token: S.token }) } as never);
+ expect(JSON.stringify(meta)).not.toMatch(/amber koi/);
+ });
+
+ it("never titles a prompts-hidden result page with its prompt, however the title got there", () => {
+ const { g } = made("a lantern festival over a frozen river at dusk");
+ const viaApi = shares.createShare({ kind: "result", targetId: g.id, title: "A lantern festival over a frozen river", showPrompts: false });
+ const page = shares.buildPublicShare(access.findShare(viaApi.token)!, viaApi.token)!.page;
+ expect(page.title).not.toMatch(/lantern/i);
+ // An owner's own title stays, and so does a published page's (typed in the wizard).
+ const own = shares.createShare({ kind: "result", targetId: g.id, title: "Winter festival", showPrompts: false });
+ expect(shares.buildPublicShare(access.findShare(own.token)!, own.token)!.page.title).toBe("Winter festival");
+ const pub = shares.createShare({ kind: "publish", items: [g.id], title: "A lantern festival", showPrompts: false });
+ expect(shares.buildPublicShare(access.findShare(pub.token)!, pub.token)!.page.title).toBe("A lantern festival");
});
});
@@ -307,6 +413,14 @@ describe("publish", () => {
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/);
+ // The cover: Series shows it beside the title, Carousel opens on it, link previews show it.
+ const coverUrl = `/s/${P.token}/f/${b.rel}`;
+ const series = renderToStaticMarkup(createElement(SharePage, { share: page }));
+ expect(series).toMatch(new RegExp(`<figure[^>]*data-cover[^>]*>.*?${coverUrl.replace(/[/.]/g, "\\$&")}`));
+ const carousel = renderToStaticMarkup(createElement(SharePage, { share: { ...page, layout: "carousel" } }));
+ expect(carousel).toMatch(/, 3 of 3</);
+ expect(share.coverSlide(page.items, page.coverKey)).toBe(2);
+ expect(share.previewImage(page.cover)).toEqual({ url: coverUrl });
// 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);
@@ -342,6 +456,34 @@ describe("the owner's API", () => {
});
});
+describe("link previews", () => {
+ it("show the cover at the address the page was opened on, and nothing for a dead link", async () => {
+ const a = made("preview one");
+ const P = shares.createShare({ kind: "publish", items: [a.g.id], title: "Preview page", layout: "feature" });
+ const meta = await sharePage.generateMetadata({ params: Promise.resolve({ token: P.token }) } as never);
+ expect(String(meta.metadataBase)).toBe("https://studio.example:3000/");
+ expect(meta.openGraph?.images).toEqual([{ url: `/s/${P.token}/f/${a.rel}` }]);
+ expect(meta.robots).toMatchObject({ index: false, follow: false });
+ const dead = await sharePage.generateMetadata({ params: Promise.resolve({ token: "Q".repeat(44) }) } as never);
+ expect(dead.openGraph).toBeUndefined();
+ });
+});
+
+describe("renewing", () => {
+ it("won't hand out a new link that is already expired; with a new expiry it works", async () => {
+ const { g } = made("expired renew reef");
+ const S = shares.createShare({ kind: "result", targetId: g.id, expiresInDays: 1 });
+ db().prepare("UPDATE shares SET expires_at = ? WHERE id = ?").run(Date.now() - 86_400_000, S.share.id);
+ expect(() => shares.updateShare(S.share.id, { newLink: true })).toThrow(/expired/);
+ const refused = await idRoute.PATCH(new Request("http://localhost", { method: "PATCH", body: JSON.stringify({ newLink: true }) }), { params: Promise.resolve({ id: S.share.id }) });
+ expect(refused.status).toBe(400);
+ const r = shares.updateShare(S.share.id, { newLink: true, expiresInDays: 7 })!;
+ expect(r.share.expiresAt).toBeGreaterThan(Date.now());
+ expect(access.findShare(r.token!)?.id).toBe(r.share.id);
+ expect(access.findShare(S.token)).toBeNull();
+ });
+});
+
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");
@@ -389,49 +531,152 @@ describe("the sign-in proxy", () => {
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", () => {
+ it("rate-limits wrong tokens without ever blocking a live link, and 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}`));
+ // Past the global budget a wrong token answers 429…
+ const blocked = proxy(req(`http://localhost:3000/s/${"7".repeat(44)}`));
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);
+ // …but anyone else's misses never take a working link down.
+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`)))).toBe(true);
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);
}
});
+
+ it("counts one miss per dead token, so a revoked page full of files doesn't trip the limit", () => {
+ const { g, rel } = made("revoked gallery pier");
+ const S = shares.createShare({ kind: "result", targetId: g.id });
+ const other = shares.createShare({ kind: "result", targetId: made("other live pier").g.id });
+ globalThis.__fuobeShareGuard = new access.ShareGuard({ perClient: 3, global: 5, windowMs: 60_000, lockMs: 60_000, maxClients: 100 });
+ shares.revokeShare(S.share.id);
+ // A page left open after its link was revoked: the page and 120 lazy-loaded files.
+ for (let i = 0; i < 120; i++) expect(gone(proxy(req(`http://localhost:3000/s/${S.token}${i ? `/f/${rel}` : ""}`)))).toBe(true);
+ expect(globalThis.__fuobeShareGuard.saturated()).toBe(false);
+ expect(passed(proxy(req(`http://localhost:3000/s/${other.token}`)))).toBe(true);
+ });
+
+ it("locks out a client it can tell apart (behind a trusted proxy), working links included, and nobody else", () => {
+ const { g } = made("trusted proxy pier");
+ const S = shares.createShare({ kind: "result", targetId: g.id });
+ globalThis.__fuobeShareGuard = new access.ShareGuard({ perClient: 3, global: 50, windowMs: 60_000, lockMs: 60_000, maxClients: 100 });
+ vi.stubEnv("FUOBE_TRUST_PROXY", "1");
+ try {
+ const from = (ip: string) => ({ headers: { "x-forwarded-for": ip } });
+ for (let i = 0; i < 3; i++) expect(gone(proxy(req(`http://localhost:3000/s/${String(i).repeat(44)}`, from("203.0.113.9"))))).toBe(true);
+ // That client can't tell a hit from a miss for a minute…
+ expect(proxy(req(`http://localhost:3000/s/${S.token}`, from("203.0.113.9"))).status).toBe(429);
+ // …while everyone else opens the link.
+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`, from("198.51.100.4"))))).toBe(true);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+});
+
+describe("views", () => {
+ const CHROME = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
+ const viewHeader = (r: Response) => r.headers.get(`x-middleware-request-${share.SHARE_VIEW_HEADER}`);
+
+ it("counts a browser opening the page, not a HEAD, a prefetch, a script or a link-preview bot", () => {
+ const h = (o: Record<string, string>) => new Headers(o);
+ expect(share.countsAsView("GET", h({ "user-agent": CHROME, "sec-fetch-dest": "document" }))).toBe(true);
+ expect(share.countsAsView("GET", h({ "user-agent": CHROME }))).toBe(true); // older browsers send no Sec-Fetch-*
+ expect(share.countsAsView("HEAD", h({ "user-agent": CHROME }))).toBe(false);
+ expect(share.countsAsView("GET", h({ "user-agent": CHROME, "sec-purpose": "prefetch;prerender" }))).toBe(false);
+ expect(share.countsAsView("GET", h({ "user-agent": CHROME, purpose: "prefetch" }))).toBe(false);
+ expect(share.countsAsView("GET", h({ "user-agent": CHROME, "sec-fetch-dest": "image" }))).toBe(false);
+ expect(share.countsAsView("GET", h({}))).toBe(false);
+ for (const bot of [
+ "Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)",
+ "facebookexternalhit/1.1 Facebot Twitterbot/1.0", // iMessage previews
+ "WhatsApp/2.23.20.0",
+ "Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)",
+ "TelegramBot (like TwitterBot)",
+ "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
+ "curl/8.5.0",
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/141.0.0.0 Safari/537.36",
+ ]) {
+ expect(share.countsAsView("GET", h({ "user-agent": bot })), bot).toBe(false);
+ }
+ });
+
+ it("is told to the page by the proxy only, for a visitor's page request", () => {
+ const { g, rel } = made("viewed pier");
+ const S = shares.createShare({ kind: "result", targetId: g.id });
+ const page = `http://localhost:3000/s/${S.token}`;
+ expect(viewHeader(proxy(req(page, { headers: { "user-agent": CHROME } })))).toBe("1");
+ expect(viewHeader(proxy(req(page, { method: "HEAD", headers: { "user-agent": CHROME } })))).toBeNull();
+ expect(viewHeader(proxy(req(`${page}/f/${rel}`, { headers: { "user-agent": CHROME } })))).toBeNull();
+ // A visitor can't count views by sending the header themselves.
+ const forged = proxy(req(page, { headers: { "user-agent": "Slackbot 1.0", [share.SHARE_VIEW_HEADER]: "1" } }));
+ expect(viewHeader(forged)).toBeNull();
+ expect(forged.headers.get("x-middleware-override-headers") ?? "").not.toContain(share.SHARE_VIEW_HEADER);
+ // The signed-in owner checking their own link isn't a view.
+ auth.setPassword("correct horse battery");
+ try {
+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ expect(viewHeader(proxy(req(page, { headers: { "user-agent": CHROME, cookie } })))).toBeNull();
+ expect(viewHeader(proxy(req(page, { headers: { "user-agent": CHROME } })))).toBe("1");
+ } 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", () => {
+ it("locks a client it can tell apart after its misses; past the global budget misses are only refused", () => {
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);
+ for (let i = 0; i < 2; i++) g.miss("1.2.3.4", `guess-${i}`, false, t + i);
expect(g.blockedFor("1.2.3.4", t + 5)).toBe(0);
- g.miss("1.2.3.4", false, t + 6);
+ g.miss("1.2.3.4", "guess-2", 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);
+ // Rotating keys: the global budget runs out, misses answer 429, and still nobody is locked out.
+ for (let i = 0; i < 10; i++) g.miss(`spoof-${i}`, `rot-${i}`, false, t + 100 + i);
+ expect(g.saturated(t + 200)).toBe(true);
+ expect(g.blockedFor("fresh", t + 200)).toBe(0);
+ expect(g.saturated(t + 200 + 60_000)).toBe(false);
});
- it("gives the shared key (no trusted proxy) only the global budget", () => {
+ it("never locks the shared key (no trusted proxy): it only spends 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);
+ for (let i = 0; i < 9; i++) g.miss("direct", `guess-${i}`, true, t + i);
+ expect(g.saturated(t + 10)).toBe(false);
+ g.miss("direct", "guess-9", true, t + 11);
+ expect(g.saturated(t + 12)).toBe(true);
+ expect(g.blockedFor("direct", t + 12)).toBe(0);
+ });
+
+ it("counts the same wrong token once per window", () => {
+ const g = new access.ShareGuard(o);
+ const t = 12_000_000;
+ for (let i = 0; i < 50; i++) g.miss("direct", "same-dead-token", true, t + i);
+ expect(g.saturated(t + 60)).toBe(false);
+ for (let i = 0; i < 5; i++) g.miss("1.2.3.4", "one-dead-token", false, t + i);
+ expect(g.blockedFor("1.2.3.4", t + 10)).toBe(0);
+ });
+
+ it("keeps a flood of misses in bounded memory, and lets the budget recover after the window", () => {
+ const g = new access.ShareGuard(o);
+ const t = 15_000_000;
+ for (let i = 0; i < 20_000; i++) g.miss("direct", `flood-${i}`, true, t + Math.floor(i / 1000));
+ expect(g.saturated(t + 30)).toBe(true);
+ const inner = g as unknown as { globalMisses: number[]; recent: Map<string, number> };
+ expect(inner.globalMisses.length).toBeLessThanOrEqual(o.global);
+ expect(inner.recent.size).toBeLessThanOrEqual(o.maxClients * 4 + 1);
+ expect(g.saturated(t + 20 + 60_000)).toBe(false);
});
});