Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Image Cleaner: strip C2PA + denoise gpt-image-1 output (#204)

[._.]/ Adam Eivy1a46f810b64d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 002c00d5be..2d036a602c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,6 +3,10 @@
## Added
+### Image Cleaner (Dev Tools)
+
+New `/devtools/image-clean` page strips C2PA provenance metadata and median-filters pixel-level noise from `gpt-image-1` / Codex output. Drag-and-drop or browse-to-upload PNG/JPEG/WebP images (up to 40MB), pick a cleaning level (`light` = median(1), `aggressive` = median(3) + sharpen), and download the re-encoded result. Side-by-side before/after preview with size delta, dimensions, format, and a "C2PA stripped" badge when the source PNG carried a `caBX` chunk. Backed by a new `POST /api/image-clean` route powered by `sharp`, with magic-byte format sniffing so client-supplied MIME types aren't trusted. Reachable via `⌘K` and voice (`ui_navigate`) through new `nav.devtools.image-clean` manifest entry.
+
### Writers Room — Read view + cross-linked storyboard
A new `?view=read` mode for the Writers Room editor renders prose with scene anchors, inline character/setting/object highlighting, and hover tooltips that show extracted profile details. Hovering a token in the prose rings the matching chip on its scene card and the matching row in the bible; clicking jumps the sidebar to the right tab. Hovering a scene card flashes the matching scene marker in the prose.
diff --git a/.gitignore b/.gitignore
index 2ad72435b0..fb47e14288 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,7 +51,11 @@ BTW.md
# Browser service node_modules (code is committed)
browser/node_modules/
-# Workspace sub-package lock files (root package-lock.json is canonical)
+# Sub-package lock files. Root package.json does NOT declare these as
+# workspaces; `npm run setup` runs `npm install --prefix <pkg>` for each,
+# generating their own lockfiles locally. The root package-lock.json only
+# tracks root devDependencies (pm2) — the `client`/`server` entries you may
+# see there are stale `extraneous: true` leftovers and are not authoritative.
browser/package-lock.json
client/package-lock.json
server/package-lock.json
diff --git a/.npmrc b/.npmrc
index 8656875294..f1444d0846 100644
--- a/.npmrc
+++ b/.npmrc
@@ -4,4 +4,5 @@
# Trusted packages requiring install scripts:
# esbuild (client + server) — downloads platform-specific binary
# node-pty (server) — builds native PTY addon
+# sharp (server) — fetches/builds libvips native binding
ignore-scripts=true
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 885cf08cda..c0e401eef4 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -40,6 +40,7 @@ const Messages = lazyWithReload(() => import('./pages/Messages'));
const Goals = lazyWithReload(() => import('./pages/Goals'));
const OpenClawPage = lazyWithReload(() => import('./pages/OpenClaw'));
const Submodules = lazyWithReload(() => import('./pages/Submodules'));
+const ImageClean = lazyWithReload(() => import('./pages/ImageClean'));
const ChiefOfStaff = lazyWithReload(() => import('./pages/ChiefOfStaff'));
const Ask = lazyWithReload(() => import('./pages/Ask'));
const MediaGen = lazyWithReload(() => import('./pages/MediaGen'));
@@ -130,6 +131,7 @@ export default function App() {
<Route path="devtools/datadog" element={<DataDog />} />
<Route path="devtools/github" element={<GitHub />} />
<Route path="devtools/history" element={<HistoryPage />} />
+ <Route path="devtools/image-clean" element={<ImageClean />} />
<Route path="devtools/runs" element={<RunsHistoryPage />} />
<Route path="devtools/runner" element={<RunnerPage />} />
<Route path="devtools/submodules" element={<Submodules />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 728abc2673..3ac3e06a68 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -76,6 +76,7 @@ import {
Mic,
Rss,
Archive,
+ Eraser,
Sun,
Moon
} from 'lucide-react';
@@ -206,6 +207,7 @@ const navItems = [
{ to: '/feature-agents', label: 'Feature Agents', icon: Wand2 },
{ to: '/devtools/github', label: 'GitHub', icon: Github },
{ to: '/devtools/history', label: 'History', icon: History },
+ { to: '/devtools/image-clean', label: 'Image Cleaner', icon: Eraser },
{ to: '/devtools/jira', label: 'JIRA', icon: Ticket },
{ to: '/devtools/jira/reports', label: 'JIRA Reports', icon: FileText },
{ to: '/shell', label: 'Shell', icon: SquareTerminal },
diff --git a/client/src/pages/ImageClean.jsx b/client/src/pages/ImageClean.jsx
new file mode 100644
index 0000000000..ac5309d656
--- /dev/null
+++ b/client/src/pages/ImageClean.jsx
@@ -0,0 +1,335 @@
+import { useState, useRef, useCallback, useEffect } from 'react';
+import { Eraser, Upload, Download, ShieldCheck } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import BrailleSpinner from '../components/BrailleSpinner';
+import * as api from '../services/api';
+import { formatBytes } from '../utils/formatters';
+import { readFileAsBase64 } from '../utils/fileUpload';
+
+// Keep aligned with MAX_INPUT_BYTES in server/routes/imageClean.js — both are
+// sized so the base64+JSON envelope fits under the 55mb body parser cap.
+const MAX_BYTES = 40 * 1024 * 1024;
+const CLEAN_LEVELS = ['light', 'aggressive'];
+const ALLOWED_EXT = /\.(png|jpe?g|webp)$/i;
+const ALLOWED_MIME = /^image\/(png|jpe?g|webp)$/i;
+
+export default function ImageClean() {
+ const [level, setLevel] = useState('light');
+ const [original, setOriginal] = useState(null); // { previewUrl, base64, size, name }
+ const [result, setResult] = useState(null);
+ const [busy, setBusy] = useState(false);
+ const [dragActive, setDragActive] = useState(false);
+ const fileInputRef = useRef(null);
+ const requestIdRef = useRef(0);
+ const previewUrlRef = useRef(null);
+ const resultUrlRef = useRef(null);
+ // Mirror `level` so handleFile can read the user's CURRENT choice after the
+ // readFileAsBase64 await — otherwise the closure captures the level at the
+ // moment the upload started and a mid-read level switch would be ignored.
+ const levelRef = useRef(level);
+ useEffect(() => { levelRef.current = level; }, [level]);
+
+ // Revoke any outstanding blob URL on unmount so we don't leak.
+ useEffect(() => () => {
+ if (previewUrlRef.current) URL.revokeObjectURL(previewUrlRef.current);
+ if (resultUrlRef.current) URL.revokeObjectURL(resultUrlRef.current);
+ }, []);
+
+ // Decode the cleaned-image base64 once into a blob URL so the After preview
+ // and the download link don't each carry a multi-MB data: string. Use
+ // fetch().blob() so the base64 → bytes conversion happens in native browser
+ // code instead of a JS atob loop that would block the main thread for large
+ // images.
+ const buildResultUrl = async (cleaned) => {
+ const blob = await fetch(`data:${cleaned.mimeType};base64,${cleaned.data}`).then((r) => r.blob());
+ return URL.createObjectURL(blob);
+ };
+
+ const runClean = useCallback(async (base64, lvl) => {
+ const myRequestId = ++requestIdRef.current;
+ setBusy(true);
+ if (resultUrlRef.current) {
+ URL.revokeObjectURL(resultUrlRef.current);
+ resultUrlRef.current = null;
+ }
+ setResult(null);
+ const cleaned = await api.cleanImage(base64, lvl).catch((err) => {
+ toast.error(err.message || 'Failed to clean image');
+ return null;
+ });
+ // Drop responses from a stale click — newer reclean is in flight.
+ if (myRequestId !== requestIdRef.current) return;
+ if (!cleaned) {
+ setBusy(false);
+ return;
+ }
+ // Keep busy=true through the decode — for large images the base64→Blob
+ // conversion is non-trivial and the spinner should stay visible.
+ const objectUrl = await buildResultUrl(cleaned).catch((err) => {
+ toast.error(err.message || 'Failed to decode cleaned image');
+ return null;
+ });
+ if (myRequestId !== requestIdRef.current) {
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
+ return;
+ }
+ setBusy(false);
+ if (!objectUrl) return;
+ resultUrlRef.current = objectUrl;
+ // Drop `cleaned.data` (the full base64 payload) before storing — keeping it
+ // alongside the blob URL would double the in-memory image footprint.
+ const { data: _omit, ...meta } = cleaned;
+ setResult({ ...meta, objectUrl });
+ toast.success(cleaned.c2paStripped ? 'C2PA provenance stripped' : 'Image cleaned');
+ }, []);
+
+ const handleFile = async (file) => {
+ if (!file) return;
+ if (file.size > MAX_BYTES) {
+ toast.error(`File exceeds ${MAX_BYTES / 1024 / 1024}MB limit`);
+ return;
+ }
+ // Server-side magic-byte sniff is the source of truth. Only fail-fast in the
+ // client when BOTH MIME and extension are present and clearly not supported
+ // — missing/empty values (common on drag from the file system) fall through
+ // to the server.
+ const hasMime = !!file.type;
+ const hasExt = /\./.test(file.name || '');
+ const mimeOk = hasMime ? ALLOWED_MIME.test(file.type) : null;
+ const extOk = hasExt ? ALLOWED_EXT.test(file.name) : null;
+ if (mimeOk === false && extOk === false) {
+ toast.error('Only PNG, JPEG, and WebP images are supported');
+ return;
+ }
+
+ const base64 = await readFileAsBase64(file).catch(() => null);
+ if (!base64) {
+ toast.error('Failed to read file');
+ return;
+ }
+
+ // Use a blob URL for the Before preview so we don't double the in-memory
+ // image (base64 string + data URI string). Revoke any previous URL first.
+ if (previewUrlRef.current) URL.revokeObjectURL(previewUrlRef.current);
+ const previewUrl = URL.createObjectURL(file);
+ previewUrlRef.current = previewUrl;
+
+ setOriginal({
+ previewUrl,
+ base64,
+ size: file.size,
+ name: file.name,
+ });
+ runClean(base64, levelRef.current);
+ };
+
+ const handleLevelChange = (newLevel) => {
+ setLevel(newLevel);
+ if (original?.base64) runClean(original.base64, newLevel);
+ };
+
+ const handleDrag = (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (e.type === 'dragenter' || e.type === 'dragover') setDragActive(true);
+ else if (e.type === 'dragleave') setDragActive(false);
+ };
+
+ const handleDrop = (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragActive(false);
+ const file = e.dataTransfer.files?.[0];
+ if (file) handleFile(file);
+ };
+
+ const handleReset = () => {
+ requestIdRef.current++;
+ if (previewUrlRef.current) {
+ URL.revokeObjectURL(previewUrlRef.current);
+ previewUrlRef.current = null;
+ }
+ if (resultUrlRef.current) {
+ URL.revokeObjectURL(resultUrlRef.current);
+ resultUrlRef.current = null;
+ }
+ // Clear the input so picking the same file again still fires onChange
+ // (browsers suppress onChange when the value is unchanged).
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ setOriginal(null);
+ setResult(null);
+ setBusy(false);
+ };
+
+ const downloadName = (() => {
+ if (!original?.name) return 'cleaned';
+ const dot = original.name.lastIndexOf('.');
+ const stem = dot > 0 ? original.name.slice(0, dot) : original.name;
+ const ext = result?.format === 'jpeg' ? 'jpg' : result?.format || 'png';
+ return `${stem}.cleaned.${ext}`;
+ })();
+
+ const sizeDelta = result ? result.sizeAfter - result.sizeBefore : 0;
+ const sizeDeltaPct = result && result.sizeBefore > 0
+ ? ((sizeDelta / result.sizeBefore) * 100).toFixed(1)
+ : '0.0';
+
+ return (
+ <div className="space-y-6">
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 sm:gap-4">
+ <div>
+ <h2 className="text-2xl font-bold text-white flex items-center gap-2">
+ <Eraser size={24} className="text-port-accent" />
+ Image Cleaner
+ </h2>
+ <p className="text-gray-500 text-sm">
+ Strip C2PA provenance + median-filter pixel noise from gpt-image-1 / Codex output.
+ </p>
+ </div>
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col sm:flex-row sm:items-center gap-3">
+ <span className="text-sm text-gray-400">Cleaning level</span>
+ <div className="flex gap-2">
+ {CLEAN_LEVELS.map((opt) => (
+ <button
+ key={opt}
+ type="button"
+ onClick={() => handleLevelChange(opt)}
+ className={`px-3 py-1.5 rounded-lg text-sm transition-colors capitalize ${
+ level === opt
+ ? 'bg-port-accent text-white'
+ : 'bg-port-bg border border-port-border text-gray-400 hover:text-white'
+ }`}
+ >
+ {opt}
+ </button>
+ ))}
+ </div>
+ <span className="text-xs text-gray-600 sm:ml-auto">
+ {level === 'light' ? 'median(1)' : 'median(3) + sharpen'}
+ </span>
+ </div>
+
+ {!original && (
+ <div
+ className={`relative p-12 border-2 border-dashed rounded-lg text-center transition-colors ${
+ dragActive
+ ? 'border-port-accent bg-port-accent/10'
+ : 'border-port-border hover:border-port-accent/50 bg-port-card'
+ }`}
+ onDragEnter={handleDrag}
+ onDragLeave={handleDrag}
+ onDragOver={handleDrag}
+ onDrop={handleDrop}
+ >
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ onChange={(e) => {
+ const file = e.target.files?.[0];
+ e.target.value = '';
+ handleFile(file);
+ }}
+ className="sr-only"
+ tabIndex={-1}
+ aria-hidden="true"
+ />
+ <Upload size={40} className={`mx-auto mb-4 ${dragActive ? 'text-port-accent' : 'text-gray-500'}`} />
+ <p className="text-white mb-2">
+ {dragActive ? 'Drop image here' : 'Drag and drop an image here'}
+ </p>
+ <p className="text-gray-500 text-sm mb-4">PNG, JPEG, or WebP (max 40MB)</p>
+ <button
+ onClick={() => fileInputRef.current?.click()}
+ className="px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg transition-colors"
+ >
+ Browse File
+ </button>
+ </div>
+ )}
+
+ {original && (
+ <div className="space-y-6">
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
+ <div className="px-4 py-2 border-b border-port-border flex items-center justify-between">
+ <span className="text-sm font-medium text-white">Before</span>
+ <span className="text-xs text-gray-500">{formatBytes(original.size)}</span>
+ </div>
+ <div className="p-4 flex items-center justify-center bg-port-bg/50 min-h-[200px]">
+ <img src={original.previewUrl} alt="Original" className="max-w-full max-h-[480px] object-contain" />
+ </div>
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
+ <div className="px-4 py-2 border-b border-port-border flex items-center justify-between">
+ <span className="text-sm font-medium text-white">After</span>
+ {result && <span className="text-xs text-gray-500">{formatBytes(result.sizeAfter)}</span>}
+ </div>
+ <div className="p-4 flex items-center justify-center bg-port-bg/50 min-h-[200px]">
+ {busy && <BrailleSpinner text="Cleaning" />}
+ {!busy && result && (
+ <img
+ src={result.objectUrl}
+ alt="Cleaned"
+ className="max-w-full max-h-[480px] object-contain"
+ />
+ )}
+ </div>
+ </div>
+ </div>
+
+ {result && (
+ <div className="bg-port-card border border-port-border rounded-lg p-4 grid grid-cols-2 sm:grid-cols-4 gap-4">
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide">Format</div>
+ <div className="text-white font-medium">{result.format}</div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide">Dimensions</div>
+ <div className="text-white font-medium">
+ {result.width && result.height ? `${result.width}×${result.height}` : '—'}
+ </div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide">Size delta</div>
+ <div className="text-white font-medium">
+ {sizeDelta >= 0 ? '+' : '−'}{formatBytes(Math.abs(sizeDelta))}{' '}
+ <span className="text-xs text-gray-500">({sizeDeltaPct}%)</span>
+ </div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide">C2PA</div>
+ <div className={`font-medium flex items-center gap-1 ${result.c2paStripped ? 'text-port-success' : 'text-gray-400'}`}>
+ {result.c2paStripped && <ShieldCheck size={14} />}
+ {result.c2paStripped ? 'Stripped' : 'None found'}
+ </div>
+ </div>
+ </div>
+ )}
+
+ <div className="flex flex-wrap gap-2">
+ {result && (
+ <a
+ href={result.objectUrl}
+ download={downloadName}
+ className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors flex items-center gap-2"
+ >
+ <Download size={16} />
+ Download
+ </a>
+ )}
+ <button
+ onClick={handleReset}
+ className="px-4 py-2 bg-port-card border border-port-border hover:border-port-accent/50 text-gray-300 rounded-lg transition-colors"
+ >
+ Choose another image
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/services/apiMedia.js b/client/src/services/apiMedia.js
index 51e7319d49..a7624d587f 100644
--- a/client/src/services/apiMedia.js
+++ b/client/src/services/apiMedia.js
@@ -24,3 +24,12 @@ export const listUploads = () => request('/uploads');
export const getUploadUrl = (filename) => `/api/uploads/${encodeURIComponent(filename)}`;
export const deleteUpload = (filename) => request(`/uploads/${encodeURIComponent(filename)}`, { method: 'DELETE' });
export const deleteAllUploads = () => request('/uploads?confirm=true', { method: 'DELETE' });
+
+// Image Cleaner — strips C2PA provenance + median-filters AI-generated noise.
+// silent: true so the page can render its own error toast without duplicating
+// the one apiCore.request() fires by default.
+export const cleanImage = (base64Data, level = 'light') => request('/image-clean', {
+ method: 'POST',
+ silent: true,
+ body: JSON.stringify({ data: base64Data, level })
+});
diff --git a/package.json b/package.json
index 2c093494c5..1a0e11ce81 100644
--- a/package.json
+++ b/package.json
@@ -20,7 +20,7 @@
"pm2:startup": "node ./node_modules/pm2/bin/pm2 startup",
"install:all": "npm run setup",
"migrations": "node scripts/run-migrations.js",
- "setup": "git submodule update --init --recursive && npm install && npm install --prefix client && npm install --prefix server && npm install --prefix autofixer && node client/node_modules/esbuild/install.js && node server/node_modules/esbuild/install.js && npm rebuild node-pty --prefix server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-browser.js",
+ "setup": "git submodule update --init --recursive && npm install && npm install --prefix client && npm install --prefix server && npm install --prefix autofixer && node client/node_modules/esbuild/install.js && node server/node_modules/esbuild/install.js && npm rebuild node-pty sharp --prefix server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-browser.js",
"setup:data": "node scripts/setup-data.js",
"setup:db": "node scripts/setup-db.js",
"setup:browser": "node scripts/setup-browser.js",
diff --git a/server/index.js b/server/index.js
index b83a29c2ee..6a202fecfb 100644
--- a/server/index.js
+++ b/server/index.js
@@ -26,6 +26,7 @@ import usageRoutes from './routes/usage.js';
import screenshotsRoutes from './routes/screenshots.js';
import attachmentsRoutes from './routes/attachments.js';
import uploadsRoutes from './routes/uploads.js';
+import imageCleanRoutes from './routes/imageClean.js';
import agentsRoutes from './routes/agents.js';
import agentPersonalitiesRoutes from './routes/agentPersonalities.js';
import platformAccountsRoutes from './routes/platformAccounts.js';
@@ -271,6 +272,7 @@ app.use('/api/attachments', attachmentsRoutes);
app.use('/api/backup', backupRoutes);
app.use('/api/database', databaseRoutes);
app.use('/api/uploads', uploadsRoutes);
+app.use('/api/image-clean', imageCleanRoutes);
// Agent Personalities feature routes (must be before /api/agents to avoid route conflicts)
app.use('/api/agents/personalities', agentPersonalitiesRoutes);
app.use('/api/agents/accounts', platformAccountsRoutes);
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 78c5a8c4fd..d7d1f70bee 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -73,6 +73,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.feature-agents', path: '/feature-agents', label: 'Feature Agents', section: 'Dev Tools', aliases: ['feature-agents'] },
{ id: 'nav.devtools.github', path: '/devtools/github', label: 'GitHub', section: 'Dev Tools', aliases: ['github', 'devtools-github'] },
{ id: 'nav.devtools.history', path: '/devtools/history', label: 'History', section: 'Dev Tools', aliases: ['devtools-history'] },
+ { id: 'nav.devtools.image-clean', path: '/devtools/image-clean', label: 'Image Cleaner', section: 'Dev Tools', aliases: ['image-clean', 'image-cleaner'], keywords: ['watermark', 'metadata', 'c2pa', 'sharp', 'denoise'] },
{ id: 'nav.devtools.jira', path: '/devtools/jira', label: 'JIRA', section: 'Dev Tools', aliases: ['jira', 'devtools-jira'] },
{ id: 'nav.devtools.jira-reports', path: '/devtools/jira/reports', label: 'JIRA Reports', section: 'Dev Tools', aliases: ['jira-reports'] },
{ id: 'nav.shell', path: '/shell', label: 'Shell', section: 'Dev Tools', aliases: ['shell', 'terminal'] },
diff --git a/server/package.json b/server/package.json
index 924b97630e..2fec5db454 100644
--- a/server/package.json
+++ b/server/package.json
@@ -19,6 +19,7 @@
"pm2": "5.4.3",
"portos-ai-toolkit": "0.8.3",
"sax": "1.4.4",
+ "sharp": "0.34.5",
"socket.io": "4.8.3",
"socket.io-client": "4.8.3",
"ws": "8.18.0",
diff --git a/server/routes/imageClean.js b/server/routes/imageClean.js
new file mode 100644
index 0000000000..d4ab651441
--- /dev/null
+++ b/server/routes/imageClean.js
@@ -0,0 +1,178 @@
+// Mirrors void-private's CodexImagegenService.cleanImage — strips C2PA
+// provenance + median-filters pixel-level noise from gpt-image-1 output.
+
+import { Router } from 'express';
+import { z } from 'zod';
+import sharp from 'sharp';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+
+const router = Router();
+
+// All sizes here are MiB (1024*1024). 40 MiB decoded → ~53.3 MiB base64 (4*ceil(n/3))
+// + small JSON envelope, which fits under the 55mb (= 55 MiB) body parser limit
+// in server/index.js. Keep these aligned — raising the decoded cap requires
+// raising the body parser limit too.
+const MAX_INPUT_BYTES = 40 * 1024 * 1024;
+// Reject oversized payloads before allocating the decoded Buffer.
+const MAX_BASE64_CHARS = Math.ceil((MAX_INPUT_BYTES * 4) / 3) + 4;
+// Cap decoded pixel count to prevent decompression-bomb images: a small payload
+// can declare gigantic dimensions and OOM the process during sharp decode. ~96MP
+// covers reasonable photos (12000×8000) without allowing pathological inputs.
+const MAX_PIXELS = 96 * 1000 * 1000;
+
+export const CLEAN_LEVELS = ['light', 'aggressive'];
+
+const cleanBodySchema = z.object({
+ data: z.string().min(1, 'data is required (base64)'),
+ level: z.enum(CLEAN_LEVELS).optional().default('light'),
+});
+
+// Magic-byte sniff so we re-encode as the source format and emit the right
+// MIME type — extension/header is supplied by the client and not trustworthy.
+function detectFormat(buf) {
+ if (buf.length >= 8 &&
+ buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
+ buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) {
+ return 'png';
+ }
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
+ return 'jpeg';
+ }
+ if (buf.length >= 12 &&
+ buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
+ buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) {
+ return 'webp';
+ }
+ return null;
+}
+
+// PNG chunk type bytes must be ASCII letters per the PNG spec (RFC 2083 §3.2).
+// Validating this lets us bail out of the walker on garbage payloads that
+// happen to start with the PNG signature, instead of looping millions of times.
+function isPngChunkType(buf, offset) {
+ for (let i = 0; i < 4; i++) {
+ const b = buf[offset + i];
+ if (!((b >= 0x41 && b <= 0x5a) || (b >= 0x61 && b <= 0x7a))) return false;
+ }
+ return true;
+}
+
+// Real PNGs have well under 50 chunks. Cap the walk so a buffer crafted with
+// the PNG signature followed by many tiny ASCII-typed zero-length chunks can't
+// force millions of iterations at the 40MiB input limit.
+const MAX_PNG_CHUNKS = 10000;
+
+// Walks PNG chunks once for the `caBX` provenance chunk emitted by gpt-image-1.
+// Sharp's default re-encode drops it; we detect it explicitly so the response
+// can flag what was stripped. Bails on invalid chunk type, truncated chunk, or
+// chunk-count overrun — a buffer that only matches the PNG signature but is
+// otherwise garbage could otherwise trigger millions of loop iterations
+// (CPU/event-loop DoS).
+function pngHasC2PA(buf) {
+ let offset = 8;
+ let count = 0;
+ while (offset + 8 <= buf.length) {
+ if (++count > MAX_PNG_CHUNKS) return false;
+ if (!isPngChunkType(buf, offset + 4)) return false;
+ const length = buf.readUInt32BE(offset);
+ if (offset + 8 + length + 4 > buf.length) return false;
+ const type = buf.toString('ascii', offset + 4, offset + 8);
+ if (type === 'caBX') return true;
+ if (type === 'IEND') return false;
+ offset += 8 + length + 4;
+ }
+ return false;
+}
+
+const MIME_TYPES = {
+ png: 'image/png',
+ jpeg: 'image/jpeg',
+ webp: 'image/webp',
+};
+
+function applyDenoise(pipeline, level) {
+ if (level === 'light') return pipeline.median(1);
+ return pipeline.median(3).sharpen();
+}
+
+function applyEncoder(pipeline, format) {
+ if (format === 'png') return pipeline.png({ compressionLevel: 9 });
+ if (format === 'jpeg') return pipeline.jpeg({ quality: 92, mozjpeg: true });
+ return pipeline.webp({ quality: 92 });
+}
+
+router.post('/', asyncHandler(async (req, res) => {
+ const { data, level } = validateRequest(cleanBodySchema, req.body);
+
+ // Cap by base64 length BEFORE allocating the decoded Buffer so an oversized
+ // payload doesn't briefly balloon RSS.
+ if (data.length > MAX_BASE64_CHARS) {
+ throw new ServerError(`Image exceeds ${MAX_INPUT_BYTES / 1024 / 1024}MB limit`, {
+ status: 400,
+ code: 'FILE_TOO_LARGE',
+ });
+ }
+
+ const buffer = Buffer.from(data, 'base64');
+ if (buffer.length === 0) {
+ throw new ServerError('Decoded payload is empty', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (buffer.length > MAX_INPUT_BYTES) {
+ throw new ServerError(`Image exceeds ${MAX_INPUT_BYTES / 1024 / 1024}MB limit`, {
+ status: 400,
+ code: 'FILE_TOO_LARGE',
+ });
+ }
+
+ const format = detectFormat(buffer);
+ if (!format) {
+ throw new ServerError('Unsupported image format (expected PNG, JPEG, or WebP)', {
+ status: 400,
+ code: 'UNSUPPORTED_FORMAT',
+ });
+ }
+
+ const c2paStripped = format === 'png' && pngHasC2PA(buffer);
+
+ // Single decode for both EXIF auto-orient + denoise/encode. .rotate() with no
+ // args applies the EXIF Orientation tag so the cleaned pixels match what the
+ // browser showed in the Before preview (browsers honor EXIF orientation but
+ // sharp does not by default). resolveWithObject gives us output dimensions
+ // (post-rotation), avoiding a second decode for metadata.
+ // Wrap sharp errors (truncated/corrupt buffer that still passed the magic-byte
+ // sniff) into a 400 so bad client input doesn't surface as a 500. Pass the
+ // libvips reason through context.details so asyncHandler logs it once
+ // (instead of an extra console.error duplicating its own log line) — the
+ // sanitized client-facing message stays generic so libvips internals don't
+ // leak in the API response or socket broadcast.
+ const base = sharp(buffer, { limitInputPixels: MAX_PIXELS }).rotate();
+ let cleaned;
+ let info;
+ try {
+ ({ data: cleaned, info } = await applyEncoder(applyDenoise(base, level), format)
+ .toBuffer({ resolveWithObject: true }));
+ } catch (err) {
+ throw new ServerError('Invalid or corrupt image', {
+ status: 400,
+ code: 'INVALID_IMAGE',
+ context: { details: { format, reason: err.message } },
+ });
+ }
+
+ console.log(`🧼 Image cleaned: ${format} ${buffer.length}B → ${cleaned.length}B (level=${level}, c2pa=${c2paStripped})`);
+
+ res.json({
+ data: cleaned.toString('base64'),
+ mimeType: MIME_TYPES[format],
+ format,
+ level,
+ sizeBefore: buffer.length,
+ sizeAfter: cleaned.length,
+ width: info.width || null,
+ height: info.height || null,
+ c2paStripped,
+ });
+}));
+
+export default router;
diff --git a/server/routes/imageClean.test.js b/server/routes/imageClean.test.js
new file mode 100644
index 0000000000..5debf3d97d
--- /dev/null
+++ b/server/routes/imageClean.test.js
@@ -0,0 +1,200 @@
+import { describe, it, expect, beforeAll } from 'vitest';
+import express from 'express';
+import sharp from 'sharp';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import imageCleanRoutes from './imageClean.js';
+
+const buildApp = () => {
+ const app = express();
+ app.use(express.json({ limit: '55mb' }));
+ app.use('/api/image-clean', imageCleanRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+let pngFixture;
+let jpegFixture;
+let webpFixture;
+let pngWithC2PA;
+
+beforeAll(async () => {
+ // 4×4 fixtures sized just large enough to round-trip through sharp.
+ const baseInput = {
+ create: { width: 4, height: 4, channels: 3, background: { r: 200, g: 100, b: 50 } },
+ };
+ pngFixture = await sharp(baseInput).png().toBuffer();
+ jpegFixture = await sharp(baseInput).jpeg().toBuffer();
+ webpFixture = await sharp(baseInput).webp().toBuffer();
+
+ // Synthesize a PNG with a `caBX` chunk inserted AFTER the IHDR chunk so the
+ // file remains a structurally valid PNG that sharp can still decode, but
+ // pngHasC2PA's walker has something to find.
+ // PNG layout: 8-byte signature, then IHDR (length=13 ⇒ 4+4+13+4 = 25 bytes).
+ const ihdrEnd = 8 + 25;
+ const cabxType = Buffer.from('caBX', 'ascii');
+ const cabxData = Buffer.from([0x01, 0x02, 0x03, 0x04]);
+ const cabxLen = Buffer.alloc(4);
+ cabxLen.writeUInt32BE(cabxData.length, 0);
+ const cabxCrc = Buffer.alloc(4); // CRC value not validated by walker or sharp's strict mode here
+ const cabxChunk = Buffer.concat([cabxLen, cabxType, cabxData, cabxCrc]);
+ pngWithC2PA = Buffer.concat([
+ pngFixture.slice(0, ihdrEnd),
+ cabxChunk,
+ pngFixture.slice(ihdrEnd),
+ ]);
+});
+
+describe('POST /api/image-clean', () => {
+ it('cleans a PNG and returns base64 + metadata', async () => {
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: pngFixture.toString('base64'), level: 'light' });
+
+ expect(res.status).toBe(200);
+ expect(res.body.format).toBe('png');
+ expect(res.body.mimeType).toBe('image/png');
+ expect(res.body.level).toBe('light');
+ expect(res.body.width).toBe(4);
+ expect(res.body.height).toBe(4);
+ expect(res.body.c2paStripped).toBe(false);
+ expect(typeof res.body.data).toBe('string');
+ expect(res.body.data.length).toBeGreaterThan(0);
+ });
+
+ it('cleans a JPEG and emits a JPEG response', async () => {
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: jpegFixture.toString('base64') });
+
+ expect(res.status).toBe(200);
+ expect(res.body.format).toBe('jpeg');
+ expect(res.body.mimeType).toBe('image/jpeg');
+ expect(res.body.level).toBe('light'); // default
+ });
+
+ it('cleans a WebP', async () => {
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: webpFixture.toString('base64'), level: 'aggressive' });
+
+ expect(res.status).toBe(200);
+ expect(res.body.format).toBe('webp');
+ expect(res.body.mimeType).toBe('image/webp');
+ expect(res.body.level).toBe('aggressive');
+ });
+
+ it('flags c2paStripped=true when PNG contains a caBX chunk', async () => {
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: pngWithC2PA.toString('base64') });
+
+ expect(res.status).toBe(200);
+ expect(res.body.c2paStripped).toBe(true);
+ });
+
+ it('bails on PNG-signature buffers with garbage chunk data instead of looping', async () => {
+ // PNG magic bytes followed by zero-filled garbage. Without an early bailout,
+ // pngHasC2PA would walk in 12-byte steps through ~40MiB of zeros (~3.3M
+ // iterations) before sharp's decode failure surfaces. This test asserts the
+ // request resolves quickly with INVALID_IMAGE rather than timing out.
+ const pngSig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+ const garbage = Buffer.alloc(1024); // zeros — chunk type bytes will be 0x00
+ const fake = Buffer.concat([pngSig, garbage]);
+ const start = Date.now();
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: fake.toString('base64') });
+ const elapsed = Date.now() - start;
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('INVALID_IMAGE');
+ expect(elapsed).toBeLessThan(1000);
+ });
+
+ it('caps the chunk walk so a PNG-sig buffer of zero-length ASCII-typed chunks bails fast', async () => {
+ // Adversarial input: valid PNG signature + many tiny chunks with valid
+ // ASCII chunk types (so isPngChunkType passes) but length=0. Without a
+ // chunk-count cap, the walker would iterate ~3.5M times for a 40MiB
+ // payload. With MAX_PNG_CHUNKS=10000, it bails after 10000 iterations.
+ const pngSig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+ const oneChunk = Buffer.concat([
+ Buffer.from([0x00, 0x00, 0x00, 0x00]), // length=0
+ Buffer.from('ABCD', 'ascii'), // valid chunk type bytes
+ Buffer.from([0x00, 0x00, 0x00, 0x00]), // CRC (unchecked)
+ ]);
+ // 20000 chunks > MAX_PNG_CHUNKS=10000 — proves the cap fires.
+ const fake = Buffer.concat([pngSig, Buffer.concat(Array(20000).fill(oneChunk))]);
+ const start = Date.now();
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: fake.toString('base64') });
+ const elapsed = Date.now() - start;
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('INVALID_IMAGE');
+ expect(elapsed).toBeLessThan(1500);
+ });
+
+ it('rejects unsupported formats with UNSUPPORTED_FORMAT', async () => {
+ const garbage = Buffer.from('not an image at all').toString('base64');
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: garbage });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('UNSUPPORTED_FORMAT');
+ });
+
+ it('rejects empty payloads with VALIDATION_ERROR', async () => {
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: '' });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ });
+
+ it('rejects oversized base64 payloads with FILE_TOO_LARGE before decoding', async () => {
+ // Sized (in MiB) to exceed the pre-decode base64 cap (~53.3 MiB, derived
+ // from MAX_INPUT_BYTES = 40 MiB) but stay under the 55 MiB body parser
+ // ceiling so the route handler runs (not express's 413).
+ const tooBig = 'A'.repeat(54 * 1024 * 1024);
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: tooBig });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('FILE_TOO_LARGE');
+ });
+
+ it('rejects invalid level enum with VALIDATION_ERROR', async () => {
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: pngFixture.toString('base64'), level: 'nuclear' });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ });
+
+ it('auto-orients images via EXIF Orientation tag', async () => {
+ // Build a 4×8 JPEG, then re-emit with EXIF Orientation=6 (rotate 90° CW)
+ // embedded via withMetadata. After the route's auto-orient, the output
+ // should be 8×4 — i.e., width/height swapped.
+ const raw = await sharp({
+ create: { width: 4, height: 8, channels: 3, background: { r: 100, g: 150, b: 200 } },
+ }).jpeg().toBuffer();
+ const oriented = await sharp(raw)
+ .withMetadata({ orientation: 6 })
+ .jpeg()
+ .toBuffer();
+
+ const res = await request(buildApp())
+ .post('/api/image-clean')
+ .send({ data: oriented.toString('base64') });
+
+ expect(res.status).toBe(200);
+ expect(res.body.width).toBe(8);
+ expect(res.body.height).toBe(4);
+ });
+});
diff --git a/setup.ps1 b/setup.ps1
index a64b9616c5..c2d646ebeb 100644
--- a/setup.ps1
+++ b/setup.ps1
@@ -62,12 +62,12 @@ Pop-Location
# Rebuild native bindings
Write-Host ""
-Write-Host "Rebuilding esbuild & node-pty..." -ForegroundColor Yellow
+Write-Host "Rebuilding esbuild, node-pty & sharp..." -ForegroundColor Yellow
node client/node_modules/esbuild/install.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
node server/node_modules/esbuild/install.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
-npm rebuild node-pty --prefix server
+npm rebuild node-pty sharp --prefix server
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
# Run data setup scripts
diff --git a/update.ps1 b/update.ps1
index fa235b0647..f64423b9ed 100644
--- a/update.ps1
+++ b/update.ps1
@@ -172,12 +172,12 @@ Safe-Install -Dir "server" -Label "server"
Safe-Install -Dir "autofixer" -Label "autofixer"
# Run trusted install scripts skipped by ignore-scripts=true in .npmrc
-Write-SafeHost "🔧 Rebuilding esbuild & node-pty..." -ForegroundColor Yellow
+Write-SafeHost "🔧 Rebuilding esbuild, node-pty & sharp..." -ForegroundColor Yellow
Invoke-Logged node client/node_modules/esbuild/install.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Invoke-Logged node server/node_modules/esbuild/install.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
-Invoke-Logged npm rebuild node-pty --prefix server
+Invoke-Logged npm rebuild node-pty sharp --prefix server
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Write-SafeHost ""
diff --git a/update.sh b/update.sh
index 46866a409f..d16b0470fa 100755
--- a/update.sh
+++ b/update.sh
@@ -112,10 +112,10 @@ safe_install server
safe_install autofixer
# Run trusted install scripts skipped by ignore-scripts=true in .npmrc
-log "🔧 Rebuilding esbuild & node-pty..."
+log "🔧 Rebuilding esbuild, node-pty & sharp..."
run node client/node_modules/esbuild/install.js
run node server/node_modules/esbuild/install.js
-run npm rebuild node-pty --prefix server
+run npm rebuild node-pty sharp --prefix server
log ""
# Verify critical dependencies exist