The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Uploads: owner switches for the browser's fitting step
Adarsh62e1b3011a3a
diff --git a/docs/admin-api.md b/docs/admin-api.mdindex 4ca9ef9c..04a76cf3 100644--- a/docs/admin-api.md+++ b/docs/admin-api.md@@ -48,6 +48,8 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz| `workers:tokens` | `POST /api/admin/workers`, and `PATCH /api/admin/workers/{id}` with `rotate`: both answer with a worker token. A worker receives accounts' queued jobs with their input files and sends back the results, so give this scope only to a tool you'd trust with those || `queue:read` | `GET /api/admin/queue`, `GET /api/admin/queue/settings` || `queue:write` | `PATCH /api/admin/queue/settings`: the run ceiling, the owner's wait limit, fair share, the pick allowance and the paused budget (`pausedBudgetS`: how long a run that has started may spend back in line) |+| `site:read` | `GET /api/admin/site/uploads` |+| `site:write` | `PATCH /api/admin/site/uploads`: the upload switches || `audit:read` | `GET /api/admin/audit` |The read-only preset in Settings ticks `runs:read`, `reports:read`, `workers:read`, `queue:read` and `audit:read`:@@ -113,6 +115,8 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control| `GET /api/admin/queue` | | `{ lanes }` || `GET /api/admin/queue/settings` | | `{ settings: { runCeilingS: { default, lanes }, ownerWaitLimitS, fairShare, pickAllowanceMs, pausedBudgetS } }` ([gpu-workers.md](gpu-workers.md#the-queue)) || `PATCH /api/admin/queue/settings` | any of `runCeilingS: { default, lanes? }` (seconds, 60 to 86400; a given `runCeilingS` replaces the default and every lane's value), `ownerWaitLimitS` (seconds, 60 to 604800, or `null` for no limit), `fairShare` (boolean), `pickAllowanceMs` (0 to 3600000), `pausedBudgetS` (seconds, 0 to 604800) | `{ settings }`; 400 with the reason for a value out of bounds, an unknown setting or an unknown lane |+| `GET /api/admin/site/uploads` | | `{ switches: { soundConvert, soundTrim, videoTrim, photoConvert, photoCrop } }`: what a browser may do to a file that doesn't fit a tool before it is uploaded (convert a sound to MP3, offer a part of a sound or clip, convert or shrink a photo, offer a crop). All `true` by default. Every visitor reads the same values at `GET /api/site/uploads` |+| `PATCH /api/admin/site/uploads` | any of the five, each `true` or `false` | `{ switches }`; 400 with the reason for an unknown switch or a value that isn't a boolean. A switch that is off leaves that kind of file as it is: the tool says why it can't take it, and the server's checks apply. Browsers pick it up when they next load a page || `GET /api/admin/workers` | | `{ workers, lanes }` || `POST /api/admin/workers` | `{ name, pool? }` | 201 `{ id, token }`: the worker's token, once || `PATCH /api/admin/workers/{id}` | any of `paused`, `pauseNow`, `drain`, `autoResume`, `hours`, `allow`, `claimAfterMs`, `switchAfterMs`, `rotate` (needs `workers:tokens`), `revoke` | `{ worker, token? }`: a new worker token after `rotate`, once |@@ -124,7 +128,7 @@ A log row is `{ id, at, actor: "owner" | "token" | "system", token: { id, name }`token.name` is the name the token had at the time. Actions: `account.disable`, `account.enable`, `account.signout`,`account.delete`, `run.delete`, `outputs.hide`, `outputs.unhide`, `outputs.remove`, `worker.add`, `worker.change`,`worker.rotate`, `worker.revoke`, `worker.revoke_all` (Sign everyone out with every API token), `queue.settings` (with-the values before and after), `token.create`, `token.revoke`,+the values before and after), `site.uploads` (the upload switches, with the values before and after), `token.create`, `token.revoke`,`token.revoke_all`, `settings.comfy_where` (where ComfyUI runs, with the values before and after); a token's reads`accounts.list`, `accounts.csv`, `account.read`, `runs.list`, `reports.list`, `audit.read` (one row per token and actionevery 10 minutes); reads of accounts' content by a token or the owner: `runs.content` (one row per reader and accountdiff --git a/src/app/api/admin/site/uploads/route.ts b/src/app/api/admin/site/uploads/route.tsnew file mode 100644index 00000000..78e4aa63--- /dev/null+++ b/src/app/api/admin/site/uploads/route.ts@@ -0,0 +1,37 @@+import { connection } from "next/server";+import { adminAccess, audit } from "@/server/admin-tokens";+import { checkUploadSwitches } from "@/lib/av/upload-switches";+import { saveUploadSwitches, uploadSwitches } from "@/server/upload-switches";++const NO_STORE = { "Cache-Control": "no-store" };++/**+ * The upload switches (owner only, or an admin token with site:read): what a browser may do to a file that doesn't fit a+ * tool before it is uploaded (src/lib/av/upload-switches.ts).+ */+export async function GET(request: Request) {+ await connection();+ const access = adminAccess(request, "site:read", "Only the studio's owner sees the site's switches");+ if (access instanceof Response) return access;+ return Response.json({ switches: uploadSwitches() }, { headers: NO_STORE });+}++/**+ * Change them (owner only, or an admin token with site:write): any of `{ soundConvert, soundTrim, videoTrim, photoConvert,+ * photoCrop }`, each true or false. Each change is written to the admin log with the values before and after. Browsers+ * pick it up when they next load the switches.+ */+export async function PATCH(request: Request) {+ const access = adminAccess(request, "site:write", "Only the studio's owner changes the site's switches");+ if (access instanceof Response) return access;+ const body = (await request.json().catch(() => null)) as unknown;+ const before = uploadSwitches();+ const r = checkUploadSwitches(body, before);+ if ("error" in r) {+ audit(access.actor, "site.uploads", null, { keys: body && typeof body === "object" ? Object.keys(body).slice(0, 8) : [] }, 400);+ return Response.json({ error: r.error }, { status: 400, headers: NO_STORE });+ }+ const switches = saveUploadSwitches(r.switches);+ audit(access.actor, "site.uploads", null, { before, after: switches }, 200);+ return Response.json({ switches }, { headers: NO_STORE });+}diff --git a/src/app/api/site/uploads/route.ts b/src/app/api/site/uploads/route.tsnew file mode 100644index 00000000..205c9622--- /dev/null+++ b/src/app/api/site/uploads/route.ts@@ -0,0 +1,11 @@+import { connection } from "next/server";+import { uploadSwitches } from "@/server/upload-switches";++/**+ * The upload switches, for every browser (guests and accounts too): what it may do to a file that doesn't fit a tool before+ * it is uploaded (src/lib/av/upload-switches.ts). Holds nothing else.+ */+export async function GET() {+ await connection();+ return Response.json({ switches: uploadSwitches() }, { headers: { "Cache-Control": "no-store" } });+}diff --git a/src/components/av/fit-upload.tsx b/src/components/av/fit-upload.tsxindex c0a92e99..33ce3094 100644--- a/src/components/av/fit-upload.tsx+++ b/src/components/av/fit-upload.tsx@@ -2,7 +2,7 @@import { Loader2, Scissors, X } from "lucide-react";import { nanoid } from "nanoid";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import type { SlotValue } from "@/components/studio/media-slot";import { useAskBeforeUpload, useIsGuest } from "@/lib/api";import { clock, convertedLine, fitSourceKind, FIT_SOURCE_MAX_BYTES, mp3Kbps, planAudioFit, type AudioFitRule, type FitPlan } from "@/lib/av/fit-upload";@@ -10,6 +10,7 @@ import { songFormat } from "@/lib/lyrics";import { postFile } from "@/lib/upload";import { cn } from "@/lib/utils";import { readSeconds, toMp3 } from "./fit-audio";+import { useUploadSwitches } from "./use-upload-switches";/*** The fitting step on a sound slot (src/lib/av/fit-upload.ts): a file the tool can't take as it is becomes one it takes, in@@ -28,7 +29,7 @@ type Offer = { source: Blob | string; name?: string; seconds: number; max: numbeconst MARGIN = 0.5;export function useFitUpload({- rule,+ rule: given,value,skip = false,seconds,@@ -45,6 +46,14 @@ export function useFitUpload({/** The slot's own upload (it places the tile and swaps in the stored file, or keeps it for a guest). */upload: (f: File) => void;}) {+ // The owner's switches: a step switched off leaves the file to the tool's own check; both off, the step is off.+ const sw = useUploadSwitches();+ const rule = useMemo(() => {+ if (!given) return null;+ const convert = sw.soundConvert && given.convert !== false;+ const trim = sw.soundTrim && given.trim !== false;+ return convert || trim ? { ...given, convert, trim } : null;+ }, [given, sw.soundConvert, sw.soundTrim]);const guest = useIsGuest();const askFirst = useAskBeforeUpload();const [busy, setBusy] = useState(false);@@ -176,8 +185,11 @@ export function useFitUpload({[convertFile, convertStored],);- /** True when this step takes the file (any sound or video file while a rule is on). */- const wants = useCallback((f: File) => !!rule && !!fitSourceKind(f), [rule]);+ /** True when this step takes the file: any sound file while a rule is on, and a video file (its sound) while converting is. */+ const wants = useCallback((f: File) => {+ const kind = fitSourceKind(f);+ return !!rule && (kind === "audio" || (kind === "video" && rule.convert !== false));+ }, [rule]);/** A file picked, dropped or pasted: its length read from its header first (nothing else is read), then fitted. */const take = useCallback(@@ -253,6 +265,8 @@ export function useFitUpload({return {on: !!rule,wants,+ /** The slot's file picker while the step is on: sound, and video while converting is on. */+ accept: rule ? (rule.convert !== false ? "audio/*,video/*" : "audio/*") : undefined,take,busy,line,diff --git a/src/components/av/use-upload-switches.ts b/src/components/av/use-upload-switches.tsnew file mode 100644index 00000000..eb8b9151--- /dev/null+++ b/src/components/av/use-upload-switches.ts@@ -0,0 +1,25 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { readUploadSwitches, UPLOAD_SWITCH_DEFAULTS, type UploadSwitches } from "@/lib/av/upload-switches";++/** The query that holds the upload switches (Settings changes them and refreshes it). */+export const UPLOAD_SWITCHES_KEY = ["upload-switches"] as const;++/**+ * The owner's upload switches (src/lib/av/upload-switches.ts), read once a page loads and again when it comes back into+ * view, so a change applies without a deploy. All on while they load or when they can't be read.+ */+export function useUploadSwitches(): UploadSwitches {+ const q = useQuery({+ queryKey: UPLOAD_SWITCHES_KEY,+ queryFn: async () => {+ const res = await fetch("/api/site/uploads", { cache: "no-store" });+ if (!res.ok) throw new Error(String(res.status));+ return readUploadSwitches(((await res.json()) as { switches?: unknown }).switches);+ },+ staleTime: 60_000,+ retry: 1,+ });+ return q.data ?? UPLOAD_SWITCH_DEFAULTS;+}diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex ce93c1f8..3a3b4129 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -31,6 +31,7 @@ import { NotificationSettings } from "@/components/notification-settings";import { SecuritySettings } from "@/components/security-settings";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { AutoPatternsSetting } from "@/components/auto-patterns-setting";+import { UploadSwitchesSettings } from "@/components/upload-switches-settings";function Section({id,@@ -741,6 +742,14 @@ export function SettingsForm({ prices }: { prices?: string }) {<SecuritySettings /></Section>+ <Section+ id="uploads"+ title="Uploads · fit in the browser"+ description="When a file doesn't fit a tool, the visitor's browser can fix it before it is uploaded. Switch a step off if it causes trouble: that kind of file is then refused with the reason, as before, and the server's own checks still apply."+ >+ <UploadSwitchesSettings />+ </Section>+<Sectionid="demo"title="Placeholder results"diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 821d9579..c7ae7c26 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -15,8 +15,7 @@ import { useToday } from "@/hooks/use-today";import { estimateCost, imageLimit, layoutCanvas, planGeneration, routesFor, type Plan } from "@/lib/catalog/plan";import type { Engine, InputSlot, MediaKind, ModelDef, Operation, Preset, PresetRoute, VideoFormat } from "@/lib/catalog/types";import { LYRICS_PARAM, SONG_ID_PARAM, songFormat, songToolProblem, withSongId } from "@/lib/lyrics";-import { murekaSongRule, SONG_ACCEPT, SONG_FIT_OPS } from "@/lib/av/song-fit";-import { fitSourceKind } from "@/lib/av/fit-upload";+import { murekaSongRule, SONG_FIT_OPS } from "@/lib/av/song-fit";import { FitUploadNote, useFitUpload } from "@/components/av/fit-upload";import { dualEngine, onEngine } from "@/lib/catalog/engines";import { locksByDefault } from "@/lib/catalog/palettes";@@ -1690,7 +1689,7 @@ export function Composer({ docked }: { docked: boolean }) {value={draft.slots[s.key] ?? null}onChange={(v) => attach.setSlotValue(s.key, v)}onFile={(f) => (s.key === "audio" && songFit.wants(f) ? songFit.take(f) : attach.uploadToSlot(s.key, f, s.accept))}- {...(s.key === "audio" && songFit.on && { accept: SONG_ACCEPT, takes: (f: File) => !!fitSourceKind(f) })}+ {...(s.key === "audio" && songFit.on && { accept: songFit.accept, takes: songFit.wants })}/>),)}diff --git a/src/components/upload-switches-settings.tsx b/src/components/upload-switches-settings.tsxnew file mode 100644index 00000000..6cbca0ad--- /dev/null+++ b/src/components/upload-switches-settings.tsx@@ -0,0 +1,78 @@+"use client";++import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { Skeleton } from "@/components/ui/skeleton";+import { Switch } from "@/components/ui/switch";+import { UPLOAD_SWITCHES_KEY } from "@/components/av/use-upload-switches";+import { readUploadSwitches, UPLOAD_SWITCH_KEYS, UPLOAD_SWITCH_LABELS, type UploadSwitches } from "@/lib/av/upload-switches";++const ADMIN_KEY = ["admin", "upload-switches"] as const;+const GROUPS = ["Sound", "Video", "Photos"] as const;++/**+ * Settings → Uploads (the owner's): the fitting step's switches, grouped by kind of file. Each one saves at once+ * (PATCH /api/admin/site/uploads) and browsers pick it up when they next load the switches.+ */+export function UploadSwitchesSettings() {+ const qc = useQueryClient();+ const q = useQuery({+ queryKey: ADMIN_KEY,+ queryFn: async () => {+ const res = await fetch("/api/admin/site/uploads", { cache: "no-store" });+ const body = (await res.json().catch(() => ({}))) as { switches?: unknown; error?: string };+ if (!res.ok) throw new Error(body.error || "We couldn't load the switches. Reload the page");+ return readUploadSwitches(body.switches);+ },+ });+ const save = useMutation({+ mutationFn: async (patch: Partial<UploadSwitches>) => {+ const res = await fetch("/api/admin/site/uploads", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(patch) });+ const body = (await res.json().catch(() => ({}))) as { switches?: unknown; error?: string };+ if (!res.ok) throw new Error(body.error || "We couldn't save that. Try again");+ return readUploadSwitches(body.switches);+ },+ onMutate: (patch) => {+ const before = qc.getQueryData<UploadSwitches>(ADMIN_KEY);+ if (before) qc.setQueryData(ADMIN_KEY, { ...before, ...patch });+ return { before };+ },+ onError: (e, _patch, ctx) => {+ if (ctx?.before) qc.setQueryData(ADMIN_KEY, ctx.before);+ toast.error((e as Error).message);+ },+ onSuccess: (switches) => {+ qc.setQueryData(ADMIN_KEY, switches);+ qc.setQueryData(UPLOAD_SWITCHES_KEY, switches);+ toast.success("Saved");+ },+ });++ if (q.isLoading) return <Skeleton className="h-48 w-full rounded-xl" />;+ if (q.isError || !q.data) return <p className="text-[13px] text-destructive">{(q.error as Error | null)?.message ?? "We couldn't load the switches. Reload the page"}</p>;+ const s = q.data;+ return (+ <div className="space-y-4">+ {GROUPS.map((group) => (+ <div key={group} role="group" aria-labelledby={`uploads-${group}`} className="overflow-hidden rounded-xl border bg-background">+ <p id={`uploads-${group}`} className="border-b bg-muted/40 px-4 py-2 text-[12px] font-medium tracking-wide text-muted-foreground uppercase">+ {group}+ </p>+ {UPLOAD_SWITCH_KEYS.filter((k) => UPLOAD_SWITCH_LABELS[k].group === group).map((k) => {+ const l = UPLOAD_SWITCH_LABELS[k];+ const id = `upload-switch-${k}`;+ return (+ <label key={k} htmlFor={id} className="flex cursor-pointer items-start justify-between gap-4 border-b px-4 py-3.5 last:border-b-0">+ <span className="min-w-0 space-y-0.5">+ <span className="block text-[14px] font-medium">{l.label}</span>+ <span className="block text-[13px] leading-relaxed text-muted-foreground">{l.hint}</span>+ </span>+ <Switch id={id} className="mt-0.5" checked={s[k]} disabled={save.isPending} onCheckedChange={(on) => save.mutate({ [k]: on })} />+ </label>+ );+ })}+ </div>+ ))}+ </div>+ );+}diff --git a/src/lib/av/fit-upload.ts b/src/lib/av/fit-upload.tsindex 564595e6..fc630751 100644--- a/src/lib/av/fit-upload.ts+++ b/src/lib/av/fit-upload.ts@@ -30,6 +30,12 @@ export interface AudioFitRule {maxSeconds?: number;/** The largest file a conversion may make. */outMaxBytes: number;+ /**+ * The owner's switches (src/lib/av/upload-switches.ts): false leaves a file that would be converted, or offered a part,+ * as it is, so the tool's own check says why it can't take it, as before the step existed. On unless said.+ */+ convert?: boolean;+ trim?: boolean;}/** The largest file read in the browser to fit it: the app's own upload limit (MAX_MB in media-slot.tsx, /api/uploads). */@@ -99,6 +105,13 @@ export function fitMaxSeconds(rule: AudioFitRule): number {* length can't be read is refused in words.*/export function planAudioFit(rule: AudioFitRule, file: { format?: string; bytes?: number; seconds?: number; video?: boolean }): FitPlan {+ if (rule.convert === false && rule.trim === false) return { kind: "keep" };+ const plan = planAll(rule, file);+ if ((plan.kind === "convert" && rule.convert === false) || (plan.kind === "trim" && rule.trim === false)) return { kind: "keep" };+ return plan;+}++function planAll(rule: AudioFitRule, file: { format?: string; bytes?: number; seconds?: number; video?: boolean }): FitPlan {const tooLong = !!rule.maxSeconds && !!file.seconds && file.seconds > rule.maxSeconds;const needs = !!file.video || (!!file.format && !rule.formats.includes(file.format)) || (!!rule.maxBytes && !!file.bytes && file.bytes > rule.maxBytes);if (!needs && !tooLong) return { kind: "keep" };diff --git a/src/lib/av/song-fit.ts b/src/lib/av/song-fit.tsindex 3ed6c958..2319a57a 100644--- a/src/lib/av/song-fit.ts+++ b/src/lib/av/song-fit.ts@@ -14,9 +14,6 @@ export const SONG_FIT_OPS = new Set(["song-extend", "song-remix", "song-stems"])/** What a converted song may weigh: Extend's and Stems' 10 MB. */export const SONG_FIT_MAX_BYTES = Math.min(EXTEND_UPLOAD_MAX_BYTES, STEMS_MAX_BYTES);-/** The song slot's file picker: any sound or video file (a phone offers its videos too). */-export const SONG_ACCEPT = "audio/*,video/*";-/** The rule for a song tool's song, or null for any other op. */export function murekaSongRule(op: string | undefined): AudioFitRule | null {if (op === "song-extend") return { for: "Mureka", tool: "Extend", formats: UPLOAD_FORMATS, maxBytes: EXTEND_UPLOAD_MAX_BYTES, outMaxBytes: SONG_FIT_MAX_BYTES };diff --git a/src/lib/av/upload-switches.ts b/src/lib/av/upload-switches.tsnew file mode 100644index 00000000..d5f9ff68--- /dev/null+++ b/src/lib/av/upload-switches.ts@@ -0,0 +1,60 @@+/**+ * The owner's switches for the fitting step (src/lib/av/fit-upload.ts): what a browser may do to a file that doesn't fit a+ * tool before it is uploaded. All on by default. A switch that is off leaves that kind of file as it was before the step+ * existed: the slot says why the tool can't take it, and the server's own checks stand.+ *+ * Stored by the server (src/server/upload-switches.ts), changed by the owner (Settings, or PATCH /api/admin/site/uploads),+ * and read by every browser on load (GET /api/site/uploads), so a change applies without a deploy.+ */++export interface UploadSwitches {+ /** A sound converted to an MP3 (another format, too big, a video's sound). */+ soundConvert: boolean;+ /** A part of a sound offered when it is longer than the tool takes. */+ soundTrim: boolean;+ /** A part of a clip offered when it is longer than the tool takes. */+ videoTrim: boolean;+ /** A photo converted or made smaller (HEIC, AVIF, too big, too many pixels). */+ photoConvert: boolean;+ /** A crop of a photo offered when its shape is outside what the tool takes. */+ photoCrop: boolean;+}++export const UPLOAD_SWITCH_KEYS = ["soundConvert", "soundTrim", "videoTrim", "photoConvert", "photoCrop"] as const satisfies readonly (keyof UploadSwitches)[];++export const UPLOAD_SWITCH_DEFAULTS: UploadSwitches = { soundConvert: true, soundTrim: true, videoTrim: true, photoConvert: true, photoCrop: true };++/** Each switch in the owner's words, grouped by kind of file (Settings and the docs use these). */+export const UPLOAD_SWITCH_LABELS: Record<keyof UploadSwitches, { group: "Sound" | "Video" | "Photos"; label: string; hint: string }> = {+ soundConvert: { group: "Sound", label: "Convert to MP3", hint: "Another format, a file that's too big, or a video's sound becomes an MP3 the tool takes." },+ soundTrim: { group: "Sound", label: "Offer a part", hint: "A sound longer than the tool takes: pick the part to use." },+ videoTrim: { group: "Video", label: "Offer a part", hint: "A clip longer than the tool takes: pick the part to use (MP4 and MOV)." },+ photoConvert: { group: "Photos", label: "Convert or make smaller", hint: "HEIC, AVIF or a photo that's too big becomes a JPEG the tool takes." },+ photoCrop: { group: "Photos", label: "Offer a crop", hint: "A photo whose shape the tool can't take: pick the crop to use." },+};++/** A change checked against `base`: any of the switches, each true or false. The error says what is wrong, in words. */+export function checkUploadSwitches(body: unknown, base: UploadSwitches = UPLOAD_SWITCH_DEFAULTS): { switches: UploadSwitches } | { error: string } {+ if (!body || typeof body !== "object" || Array.isArray(body)) return { error: "Send the switches as an object" };+ const b = body as Record<string, unknown>;+ const unknown = Object.keys(b).filter((k) => !(UPLOAD_SWITCH_KEYS as readonly string[]).includes(k));+ if (unknown.length) return { error: `Unknown switch: ${unknown[0].slice(0, 40)}` };+ const out = { ...base };+ for (const k of UPLOAD_SWITCH_KEYS) {+ if (b[k] === undefined) continue;+ if (typeof b[k] !== "boolean") return { error: `${k} is true or false` };+ out[k] = b[k];+ }+ return { switches: out };+}++/** A stored or fetched value read leniently: anything missing or not valid is on (the default). */+export function readUploadSwitches(v: unknown): UploadSwitches {+ const out = { ...UPLOAD_SWITCH_DEFAULTS };+ if (!v || typeof v !== "object") return out;+ for (const k of UPLOAD_SWITCH_KEYS) {+ const x = (v as Record<string, unknown>)[k];+ if (typeof x === "boolean") out[k] = x;+ }+ return out;+}diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 36dd8ffe..49fb20ac 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -23,7 +23,7 @@ export const GUEST_LIBRARY_MESSAGE = "Sign up to see this.";export const GUEST_RUN_MESSAGE = "Create a free account to run this.";/** Catalog and status reads that hold nothing of the owner's library: a guest gets the real answer. */-const GUEST_READS = new Set(["/api/status", "/api/examples", "/api/models", "/api/search-index", "/api/comfyui", "/api/settings/models", "/api/gpu/requirements", "/api/live/nodes"]);+const GUEST_READS = new Set(["/api/status", "/api/site/uploads", "/api/examples", "/api/models", "/api/search-index", "/api/comfyui", "/api/settings/models", "/api/gpu/requirements", "/api/live/nodes"]);/** Catalogs mixed with the owner's own items: the route leaves the owner's part out for a guest (GUEST_HEADER). */const GUEST_FILTERED = new Set(["/api/moodboards", "/api/palettes", "/api/assist", "/api/assist/skills"]);diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.tsindex 4abe74a3..d4e9f0d8 100644--- a/src/server/admin-tokens.ts+++ b/src/server/admin-tokens.ts@@ -33,6 +33,8 @@ export const SCOPES = ["workers:tokens","queue:read","queue:write",+ "site:read",+ "site:write","audit:read",] as const;@@ -54,6 +56,8 @@ export const SCOPE_LABELS: Record<Scope, string> = {"workers:tokens": "Add workers and give them new tokens (a worker runs accounts' queued jobs, with their files)","queue:read": "See the queue and its settings","queue:write": "Change the queue's settings: the run ceiling, the owner's wait limit, fair share, the pick allowance and the paused budget",+ "site:read": "See the site's switches: the upload fitting steps",+ "site:write": "Switch the upload fitting steps off and on: convert, offer a part, offer a crop","audit:read": "See the admin log",};diff --git a/src/server/upload-switches.ts b/src/server/upload-switches.tsnew file mode 100644index 00000000..0185291b--- /dev/null+++ b/src/server/upload-switches.ts@@ -0,0 +1,43 @@+import "server-only";+import { readUploadSwitches, type UploadSwitches } from "@/lib/av/upload-switches";+import { db } from "./db";++/**+ * The owner's switches for the fitting step (src/lib/av/upload-switches.ts), kept in the settings table under one key as+ * JSON. Nothing set: all on. Read again at most every 2 s, so both of a deploy's processes see a change within that.+ */++const KEY = "uploads.switches";++declare global {+ var __fuobeUploadSwitches: { at: number; raw: string | null; value: UploadSwitches } | undefined;+}++function fromStored(raw: string | null): UploadSwitches {+ if (!raw) return readUploadSwitches(null);+ try {+ return readUploadSwitches(JSON.parse(raw));+ } catch {+ return readUploadSwitches(null);+ }+}++/** The switches in effect. */+export function uploadSwitches(now = Date.now()): UploadSwitches {+ const c = globalThis.__fuobeUploadSwitches;+ if (c && now - c.at < 2000) return { ...c.value };+ const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(KEY) as { value: string } | undefined;+ const raw = row?.value ?? null;+ const value = c && c.raw === raw ? c.value : fromStored(raw);+ globalThis.__fuobeUploadSwitches = { at: now, raw, value };+ return { ...value };+}++/** Save the switches (checked first with checkUploadSwitches). */+export function saveUploadSwitches(s: UploadSwitches): UploadSwitches {+ db()+ .prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value")+ .run(KEY, JSON.stringify(s));+ globalThis.__fuobeUploadSwitches = undefined;+ return uploadSwitches();+}diff --git a/tests/upload-switches.test.ts b/tests/upload-switches.test.tsnew file mode 100644index 00000000..c9b7e90f--- /dev/null+++ b/tests/upload-switches.test.ts@@ -0,0 +1,146 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";+import { checkUploadSwitches, readUploadSwitches, UPLOAD_SWITCH_DEFAULTS } from "@/lib/av/upload-switches";+import { planAudioFit, type AudioFitRule } from "@/lib/av/fit-upload";++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = tempDir("fuobe-upload-switches-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_TRUST_PROXY;+const auth = await import("@/server/auth");+const admin = await import("@/server/admin-tokens");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { proxy } = await import("@/proxy");+const route = await import("@/app/api/admin/site/uploads/route");+const pub = await import("@/app/api/site/uploads/route");+afterAll(() => {+ delete process.env.FUOBE_PUBLIC_SIGNUP;+});++const req = (url: string, o: { method?: string; token?: string; cookie?: string; body?: unknown } = {}) =>+ new NextRequest(`http://localhost:3000${url}`, {+ method: o.method ?? "GET",+ headers: {+ ...(o.token && { authorization: `Bearer ${o.token}` }),+ ...(o.cookie && { cookie: `${auth.SESSION_COOKIE}=${o.cookie}` }),+ ...(o.body !== undefined && { "content-type": "application/json" }),+ },+ ...(o.body !== undefined && { body: JSON.stringify(o.body) }),+ });++const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";+let n = 0;+const make = (scopes: (typeof admin.SCOPES)[number][]) => admin.createAdminToken({ name: `switches ${++n}`, scopes, expiresInDays: null });+const audits = () => db().prepare("SELECT * FROM admin_audit WHERE action = 'site.uploads' ORDER BY id").all() as { actor: string; detail_json: string | null; status: number }[];++let owner = "";+let account = "";+beforeAll(() => {+ auth.setPassword("install password");+ owner = auth.createSession().value;+ account = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;+});+beforeEach(() => {+ resetRates();+ admin.revokeAllAdminTokens();+ db().prepare("DELETE FROM settings WHERE key = 'uploads.switches'").run();+ globalThis.__fuobeUploadSwitches = undefined;+});++describe("upload switches: the checks", () => {+ it("takes any of the five as true or false, and nothing else", () => {+ expect(checkUploadSwitches({ soundTrim: false })).toEqual({ switches: { ...UPLOAD_SWITCH_DEFAULTS, soundTrim: false } });+ expect(checkUploadSwitches({})).toEqual({ switches: UPLOAD_SWITCH_DEFAULTS });+ expect(checkUploadSwitches({ soundTrim: "no" })).toEqual({ error: "soundTrim is true or false" });+ expect(checkUploadSwitches({ everything: false })).toEqual({ error: "Unknown switch: everything" });+ expect(checkUploadSwitches([])).toHaveProperty("error");+ expect(checkUploadSwitches(null)).toHaveProperty("error");+ });++ it("reads a stored or fetched value leniently: what is missing or wrong is on", () => {+ expect(readUploadSwitches(undefined)).toEqual(UPLOAD_SWITCH_DEFAULTS);+ expect(readUploadSwitches({ photoCrop: false, videoTrim: "off" })).toEqual({ ...UPLOAD_SWITCH_DEFAULTS, photoCrop: false });+ });++ it("leaves a file as it is when its step is off, so the tool's own check says why", () => {+ const remix: AudioFitRule = { for: "Mureka", tool: "Remix", formats: ["mp3"], maxSeconds: 350, outMaxBytes: 10e6 };+ expect(planAudioFit(remix, { format: "wav", bytes: 5e6, seconds: 60 })).toMatchObject({ kind: "convert" });+ expect(planAudioFit({ ...remix, convert: false }, { format: "wav", bytes: 5e6, seconds: 60 })).toEqual({ kind: "keep" });+ expect(planAudioFit(remix, { format: "mp3", bytes: 5e6, seconds: 400 })).toMatchObject({ kind: "trim" });+ expect(planAudioFit({ ...remix, trim: false }, { format: "mp3", bytes: 5e6, seconds: 400 })).toEqual({ kind: "keep" });+ // Converting stays on while trimming is off, and the other way round.+ expect(planAudioFit({ ...remix, trim: false }, { format: "wav", bytes: 5e6, seconds: 60 })).toMatchObject({ kind: "convert" });+ expect(planAudioFit({ ...remix, convert: false }, { format: "mp3", bytes: 5e6, seconds: 400 })).toMatchObject({ kind: "trim" });+ });+});++describe("upload switches: who may read and change them", () => {+ it("answers a guest 401 and an account 403 at the proxy, and lets the owner through", () => {+ for (const method of ["GET", "PATCH"]) {+ expect(proxy(req("/api/admin/site/uploads", { method })).status, method).toBe(401);+ expect(proxy(req("/api/admin/site/uploads", { method, cookie: account })).status, method).toBe(403);+ expect(passed(proxy(req("/api/admin/site/uploads", { method, cookie: owner }))), method).toBe(true);+ }+ });++ it("gives every visitor the switches to read, and nothing to change", () => {+ for (const cookie of [undefined, account, owner]) expect(passed(proxy(req("/api/site/uploads", { cookie }))), String(cookie)).toBe(true);+ expect(passed(proxy(req("/api/site/uploads", { method: "PATCH" })))).toBe(false);+ expect(pub).not.toHaveProperty("PATCH");+ });++ it("refuses the route itself to anyone but the owner or a token with the scope", async () => {+ expect((await route.GET(req("/api/admin/site/uploads"))).status).toBe(403);+ expect((await route.PATCH(req("/api/admin/site/uploads", { method: "PATCH", body: { soundTrim: false } }))).status).toBe(403);+ expect((await route.GET(req("/api/admin/site/uploads", { token: `fuobe_adm_${"q".repeat(43)}` }))).status).toBe(401);+ // A token with every other scope.+ const other = make(admin.SCOPES.filter((s) => s !== "site:read" && s !== "site:write"));+ const r = await route.GET(req("/api/admin/site/uploads", { token: other.token }));+ expect(r.status).toBe(403);+ expect(await r.json()).toMatchObject({ code: "scope", scope: "site:read" });+ expect((await route.PATCH(req("/api/admin/site/uploads", { token: other.token, method: "PATCH", body: { soundTrim: false } }))).status).toBe(403);+ // Reading doesn't let it change them.+ const reader = make(["site:read"]);+ expect((await route.GET(req("/api/admin/site/uploads", { token: reader.token }))).status).toBe(200);+ const no = await route.PATCH(req("/api/admin/site/uploads", { token: reader.token, method: "PATCH", body: { soundTrim: false } }));+ expect(no.status).toBe(403);+ expect(await no.json()).toMatchObject({ code: "scope", scope: "site:write" });+ });++ it("lets the owner and a site:write token change them, logs before and after, and every browser reads them", async () => {+ const first = await route.GET(req("/api/admin/site/uploads", { cookie: owner }));+ expect(first.headers.get("cache-control")).toBe("no-store");+ expect(await first.json()).toEqual({ switches: UPLOAD_SWITCH_DEFAULTS });+ const off = await route.PATCH(req("/api/admin/site/uploads", { cookie: owner, method: "PATCH", body: { soundTrim: false, photoCrop: false } }));+ expect(off.status).toBe(200);+ expect(off.headers.get("cache-control")).toBe("no-store");+ const after = { ...UPLOAD_SWITCH_DEFAULTS, soundTrim: false, photoCrop: false };+ expect(await off.json()).toEqual({ switches: after });+ expect(await (await pub.GET()).json()).toEqual({ switches: after });+ const log = audits().at(-1)!;+ expect(log).toMatchObject({ actor: "owner", status: 200 });+ expect(JSON.parse(log.detail_json!)).toEqual({ before: UPLOAD_SWITCH_DEFAULTS, after });++ const writer = make(["site:write"]);+ const on = await route.PATCH(req("/api/admin/site/uploads", { token: writer.token, method: "PATCH", body: { soundTrim: true } }));+ expect(await on.json()).toEqual({ switches: { ...after, soundTrim: true } });+ expect(audits().at(-1)).toMatchObject({ actor: "token", status: 200 });++ const bad = await route.PATCH(req("/api/admin/site/uploads", { cookie: owner, method: "PATCH", body: { soundTrim: 1 } }));+ expect(bad.status).toBe(400);+ expect(await bad.json()).toEqual({ error: "soundTrim is true or false" });+ expect(audits().at(-1)).toMatchObject({ status: 400 });+ expect(await (await pub.GET()).json()).toEqual({ switches: { ...after, soundTrim: true } });+ });++ it("doesn't give the new scopes to a token made before them", () => {+ const old = make(["queue:read", "queue:write", "audit:read"]);+ expect(old.info.scopes).not.toContain("site:write");+ expect(admin.listAdminTokens().find((t) => t.id === old.info.id)?.scopes).toEqual(["audit:read", "queue:read", "queue:write"]);+ });+});