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

feat(image-clean): composable opt-in pipeline + raw-byte upload (#1763)

[._.]/ Adam Eivyd83e4cebc6df
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b931e00c73..75bcc61d93 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,10 @@
- **[issue-1760] Groundwork: offline beat/tempo/section analysis of an audio track (Phase 0 spike).** The first slice of the planned Music Video production mode proves the riskiest unknown — that a music track's BPM, beat grid, 4/4 downbeats, and a coarse section map can be extracted **fully offline with no new dependency**, using only ffmpeg (already required) plus a pure-JS DSP core (onset-strength envelope → tempo-weighted autocorrelation → beat-phase fit → energy-novelty sections). No Python, no ML model download, no network — so it runs the same in CI and on every install. There's no user-facing surface yet; this is the analyzer the upcoming director scene board and beat-snapped render build on. (`server/services/musicVideo/audioAnalysis.js`)
+## Devtools
+
+- **[issue-1763] Image Cleaner is now a composable, opt-in pipeline with no upload-size cap (Phase 1).** The cleaner ran one fixed pipeline — it *always* stripped the C2PA chunk *and* applied a median+sharpen denoise, with a hard 40MB base64-in-JSON upload cap. It's now a step selector: **Strip metadata & C2PA** (default ON, lossless) and **Median + sharpen** (default OFF, lossy) run independently, with a per-step report card showing exactly what each pass did. The lossless metadata strip was widened from C2PA-only to also drop EXIF/XMP/IPTC and PNG text chunks (`tEXt`/`zTXt`/`iTXt`/`eXIf`) — pixels and color chunks left byte-identical. The upload switched from base64-in-JSON to **raw image bytes** (`express.raw`, 256MB transport ceiling), killing the ~33% base64 inflation and removing the 40MB cap entirely; the decompression-bomb pixel guard stays. The page now also shows the source resolution (W×H + megapixels) before cleaning. The honest "this does NOT defeat SynthID" messaging is preserved. The local diffusion SynthID-disruption pass, the ignore-zone mask, and resolution-aware diffusion options remain tracked in #1763 as the next phase. (`server/lib/imageClean.js`, `server/routes/imageClean.js`, `client/src/pages/ImageClean.jsx`, `client/src/services/apiMedia.js`)
+
## Performance
- **Tabbed pages now lazy-load their tab bodies, and `/apps` + `/ambient` moved out of the eager entry bundle.** Digital Twin (17 tabs), MeatSpace (11 tabs), and Brain (10 tabs) previously imported *every* tab component up front, so opening any one tab downloaded a single 240–450 kB chunk's worth of all of them. Each tab body is now a `React.lazy` chunk behind a `<Suspense>` boundary, so a user who views 1–2 tabs no longer pays for the other 15. `Apps` and `Ambient` were the only two non-index pages still imported statically into the entry chunk — they're now `lazyWithReload` like every other route, shrinking the initial bundle (~109 → ~95 kB gzip). The Vite vendor split also gained named `vendor-three` / `vendor-charts` / `vendor-term` groups so the big 3D/charting/terminal libs land in stable, single shared chunks instead of an opaque `OrbitControls-*.js`. (`client/src/App.jsx`, `client/src/pages/DigitalTwin.jsx`, `client/src/pages/MeatSpace.jsx`, `client/src/pages/Brain.jsx`, `client/vite.config.js`)
diff --git a/client/src/pages/ImageClean.jsx b/client/src/pages/ImageClean.jsx
index dc734c7a29..65d7b69ce9 100644
--- a/client/src/pages/ImageClean.jsx
+++ b/client/src/pages/ImageClean.jsx
@@ -1,22 +1,35 @@
import { useState, useRef, useCallback, useEffect } from 'react';
-import { Eraser, Upload, Download, ShieldCheck } from 'lucide-react';
+import { Eraser, Upload, Download, ShieldCheck, Sparkles } 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 ALLOWED_EXT = /\.(png|jpe?g|webp)$/i;
const ALLOWED_MIME = /^image\/(png|jpe?g|webp)$/i;
+// Detect pixel dimensions from a File without uploading — load it into an
+// <img> and read naturalWidth/Height. Resolves to null on decode failure so the
+// caller just omits the pre-clean dimensions instead of blocking the upload.
+function detectDimensions(objectUrl) {
+ return new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => resolve({ width: img.naturalWidth, height: img.naturalHeight });
+ img.onerror = () => resolve(null);
+ img.src = objectUrl;
+ });
+}
+
+const megapixels = (w, h) => (w && h ? (w * h) / 1_000_000 : 0);
+
export default function ImageClean() {
- const [original, setOriginal] = useState(null); // { previewUrl, base64, size, name }
+ // { previewUrl, file, size, name, width, height }
+ const [original, setOriginal] = useState(null);
const [result, setResult] = useState(null);
const [busy, setBusy] = useState(false);
const [dragActive, setDragActive] = useState(false);
+ // Opt-in pipeline steps. metadata defaults ON (lossless), denoise OFF (lossy).
+ const [steps, setSteps] = useState({ metadata: true, denoise: false });
const fileInputRef = useRef(null);
const requestIdRef = useRef(0);
const previewUrlRef = useRef(null);
@@ -28,17 +41,8 @@ export default function ImageClean() {
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) => {
+ const runClean = useCallback(async (file, selectedSteps) => {
+ if (!file) return;
const myRequestId = ++requestIdRef.current;
setBusy(true);
if (resultUrlRef.current) {
@@ -46,46 +50,31 @@ export default function ImageClean() {
resultUrlRef.current = null;
}
setResult(null);
- const cleaned = await api.cleanImage(base64).catch((err) => {
+ const cleaned = await api.cleanImage(file, selectedSteps).catch((err) => {
toast.error(err.message || 'Failed to clean image');
return null;
});
- // Drop responses from a stale click — newer reclean is in flight.
+ // Drop responses from a stale click — a 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;
+ const objectUrl = URL.createObjectURL(cleaned.blob);
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 chunk removed' : 'Image cleaned (no C2PA chunk found)');
+ const report = cleaned.report || {};
+ setResult({ ...report, mimeType: cleaned.mimeType, objectUrl });
+ toast.success(report.c2paStripped ? 'C2PA chunk removed' : '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.
+ // to the server. No byte cap: the server streams raw bytes (256MB transport
+ // limit) and guards against decompression bombs by pixel count.
const hasMime = !!file.type;
const hasExt = /\./.test(file.name || '');
const mimeOk = hasMime ? ALLOWED_MIME.test(file.type) : null;
@@ -95,25 +84,30 @@ export default function ImageClean() {
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.
+ // Use a blob URL for the Before preview and dimension detection.
if (previewUrlRef.current) URL.revokeObjectURL(previewUrlRef.current);
const previewUrl = URL.createObjectURL(file);
previewUrlRef.current = previewUrl;
+ const dims = await detectDimensions(previewUrl);
setOriginal({
previewUrl,
- base64,
+ file,
size: file.size,
name: file.name,
+ width: dims?.width || null,
+ height: dims?.height || null,
});
- runClean(base64);
+ runClean(file, steps);
+ };
+
+ const toggleStep = (key) => {
+ // Compute next outside setState so the updater stays pure (no side effects).
+ const next = { ...steps, [key]: !steps[key] };
+ setSteps(next);
+ // Re-run immediately against the new selection so the After preview always
+ // reflects the current steps.
+ if (original?.file) runClean(original.file, next);
};
const handleDrag = (e) => {
@@ -162,6 +156,19 @@ export default function ImageClean() {
? ((sizeDelta / result.sizeBefore) * 100).toFixed(1)
: '0.0';
+ const STEP_DEFS = [
+ {
+ key: 'metadata',
+ label: 'Strip metadata & C2PA',
+ hint: 'Lossless — removes the C2PA provenance chunk plus EXIF/XMP/IPTC and PNG text chunks. Pixels untouched.',
+ },
+ {
+ key: 'denoise',
+ label: 'Median + sharpen',
+ hint: 'Lossy — reduces visible AI-generation artifacts but blurs fine text. Re-encodes the image.',
+ },
+ ];
+
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 sm:gap-4">
@@ -171,16 +178,17 @@ export default function ImageClean() {
Image Cleaner
</h2>
<p className="text-gray-500 text-sm">
- Removes the C2PA metadata chunk (when present) and reduces visible AI-generation artifacts via a median pass + sharpen.
+ Composable, opt-in pipeline: strip provenance/identifying metadata and/or reduce AI-generation artifacts.
</p>
<p className="text-gray-500 text-xs mt-1">
<span className="text-port-warning">Note:</span>{' '}
- does NOT defeat SynthID. gpt-image / Imagen / Gemini renders stay detectable by their vendor watermark checkers
+ these passes do NOT defeat SynthID. gpt-image / Imagen / Gemini renders stay detectable by their vendor watermark checkers
(e.g.{' '}
<a href="https://openai.com/synthid" target="_blank" rel="noopener noreferrer" className="text-port-accent hover:underline">
openai.com/synthid
</a>
- ) after a clean — SynthID is embedded in pixel values and was designed to survive median + sharpen + re-encode.
+ ) — SynthID is embedded in pixel values and was designed to survive median + sharpen + re-encode. A local diffusion pass that
+ actually disrupts SynthID is tracked as a follow-up (issue #1763).
</p>
</div>
</div>
@@ -214,7 +222,7 @@ export default function ImageClean() {
<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>
+ <p className="text-gray-500 text-sm mb-4">PNG, JPEG, or WebP</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"
@@ -226,11 +234,47 @@ export default function ImageClean() {
{original && (
<div className="space-y-6">
+ {/* Step selector */}
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex items-center gap-2 mb-3">
+ <Sparkles size={16} className="text-port-accent" />
+ <span className="text-sm font-medium text-white">Pipeline steps</span>
+ <span className="text-xs text-gray-500">run in order: metadata → median/sharpen</span>
+ </div>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {STEP_DEFS.map(({ key, label, hint }) => (
+ <label
+ key={key}
+ htmlFor={`step-${key}`}
+ className="flex items-start gap-3 p-3 rounded-lg border border-port-border hover:border-port-accent/50 cursor-pointer transition-colors"
+ >
+ <input
+ id={`step-${key}`}
+ type="checkbox"
+ checked={steps[key]}
+ onChange={() => toggleStep(key)}
+ disabled={busy}
+ className="mt-1 accent-port-accent"
+ />
+ <span>
+ <span className="block text-sm text-white">{label}</span>
+ <span className="block text-xs text-gray-500">{hint}</span>
+ </span>
+ </label>
+ ))}
+ </div>
+ </div>
+
<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>
+ <span className="text-xs text-gray-500">
+ {formatBytes(original.size)}
+ {original.width && original.height && (
+ <> · {original.width}×{original.height} · {megapixels(original.width, original.height).toFixed(1)}MP</>
+ )}
+ </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" />
@@ -251,6 +295,9 @@ export default function ImageClean() {
className="max-w-full max-h-[480px] object-contain"
/>
)}
+ {!busy && !result && (
+ <span className="text-gray-600 text-sm">Select steps to clean</span>
+ )}
</div>
</div>
</div>
@@ -284,6 +331,21 @@ export default function ImageClean() {
</div>
)}
+ {result?.steps?.length > 0 && (
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Per-step report</div>
+ <ul className="space-y-1 text-sm">
+ {result.steps.map((s) => (
+ <li key={s.step} className="flex items-center gap-2">
+ <span className={`w-2 h-2 rounded-full ${s.status === 'applied' ? 'bg-port-success' : 'bg-gray-600'}`} />
+ <span className="text-white capitalize">{s.step}</span>
+ <span className="text-gray-500">— {s.status}{s.detail ? ` (${s.detail})` : ''}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
<div className="flex flex-wrap gap-2">
{result && (
<a
diff --git a/client/src/services/apiMedia.js b/client/src/services/apiMedia.js
index e12fb63211..4b5b16a650 100644
--- a/client/src/services/apiMedia.js
+++ b/client/src/services/apiMedia.js
@@ -1,4 +1,4 @@
-import { request } from './apiCore.js';
+import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';
// Screenshots
export const uploadScreenshot = (base64Data, filename, mimeType) => request('/screenshots', {
@@ -25,11 +25,42 @@ export const getUploadUrl = (filename) => `/api/uploads/${encodeURIComponent(fil
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) => request('/image-clean', {
- method: 'POST',
- silent: true,
- body: JSON.stringify({ data: base64Data })
-});
+// Image Cleaner — composable opt-in pipeline (metadata strip and/or denoise).
+// Uploads the RAW image bytes (no base64 inflation) with the step selection in
+// the query string; the cleaned bytes come back as the response body and the
+// per-step report rides in the `X-Clean-Report` header. Bypasses request()
+// because that helper assumes a JSON response and can't surface a Blob body +
+// custom header. Returns `{ blob, mimeType, report }`. Throws on failure so the
+// page's own catch can toast (no silent flag needed — this never double-toasts).
+//
+// `steps` is `{ metadata?: boolean, denoise?: boolean }`; both default on the
+// server (metadata ON, denoise OFF) when omitted.
+export const cleanImage = async (file, steps = {}) => {
+ const params = new URLSearchParams();
+ if (typeof steps.metadata === 'boolean') params.set('metadata', steps.metadata ? '1' : '0');
+ if (typeof steps.denoise === 'boolean') params.set('denoise', steps.denoise ? '1' : '0');
+ const qs = params.toString();
+
+ const response = await fetch(`${API_BASE}/image-clean${qs ? `?${qs}` : ''}`, {
+ method: 'POST',
+ headers: { 'Content-Type': file.type || 'application/octet-stream' },
+ body: file,
+ }).catch(() => null);
+
+ if (!response) throw new Error('Server unreachable — check your connection and try again');
+
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({ error: 'Failed to clean image' }));
+ maybeRedirectToLogin(response, error);
+ const err = new Error(error.error || `HTTP ${response.status}`);
+ err.code = error?.code;
+ err.status = response.status;
+ throw err;
+ }
+
+ const reportHeader = response.headers.get('X-Clean-Report');
+ let report = null;
+ if (reportHeader) { try { report = JSON.parse(reportHeader); } catch { report = null; } }
+ const blob = await response.blob();
+ return { blob, mimeType: blob.type || report?.format || 'application/octet-stream', report };
+};
diff --git a/server/lib/README.md b/server/lib/README.md
index 1c16d031ef..955836a6f1 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -109,7 +109,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
-| `imageClean.js` | `cleanImageBuffer` (sharp-based denoise + C2PA strip) + `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |
+| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
| `multipart.js` | Streaming multipart/form-data parser. |
diff --git a/server/lib/imageClean.js b/server/lib/imageClean.js
index bfd17a9bd9..8a1d2ae19b 100644
--- a/server/lib/imageClean.js
+++ b/server/lib/imageClean.js
@@ -41,13 +41,13 @@ export function resolveCleanersFromConfig(modeCfg, mode) {
};
}
-// 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.
-export const MAX_INPUT_BYTES = 40 * 1024 * 1024;
-// Reject oversized payloads before allocating the decoded Buffer.
-export const MAX_BASE64_CHARS = Math.ceil((MAX_INPUT_BYTES * 4) / 3) + 4;
+// There is intentionally no decoded-byte cap. The HTTP route streams raw bytes
+// through `express.raw({ limit })`, so the transport itself is the (generous)
+// byte ceiling — the old base64-in-JSON cap (40 MiB sized to fit a 55 MiB JSON
+// body parser) only existed to bound the ~33% base64 inflation, which the raw
+// transport removes. The decompression-bomb guard below stays: it protects the
+// process regardless of how the buffer arrived.
+//
// 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.
@@ -79,9 +79,19 @@ function isPngChunkType(buf, offset) {
// 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.
+// force millions of iterations on a large input.
const MAX_PNG_CHUNKS = 10000;
+// Chunk types the metadata-strip pass removes. `caBX` is the gpt-image C2PA
+// provenance chunk; the text chunks (`tEXt`/`zTXt`/`iTXt`) carry XMP, IPTC and
+// arbitrary author/comment key-values (PNG stores XMP as an `iTXt` keyed
+// `XML:com.adobe.xmp`), and `eXIf` is the PNG-native EXIF block. All four are
+// ancillary — none affect rendering — so dropping them is lossless. Critical and
+// color/gamma chunks (IHDR/PLTE/IDAT/IEND, gAMA/cHRM/sRGB/iCCP/tRNS/…) are left
+// untouched so pixels and color reproduction are byte-identical.
+const C2PA_CHUNK_TYPES = new Set(['caBX']);
+const METADATA_CHUNK_TYPES = new Set(['caBX', 'tEXt', 'zTXt', 'iTXt', 'eXIf']);
+
// Walks PNG chunks once for the `caBX` provenance chunk emitted by gpt-image.
// 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
@@ -105,29 +115,35 @@ function pngHasC2PA(buf) {
}
/**
- * Lossless C2PA strip — walks PNG chunks and emits a NEW buffer containing
- * every chunk except `caBX`. Pixels untouched, no decode, no re-encode.
- * Output is byte-identical to input modulo the removed chunk(s).
+ * Lossless PNG-chunk strip — walks PNG chunks and emits a NEW buffer containing
+ * every chunk except those whose type is in `dropTypes`. Pixels untouched, no
+ * decode, no re-encode. Output is byte-identical to input modulo the removed
+ * chunk(s).
*
- * Returns `{ data, stripped, sizeBefore, sizeAfter }`:
+ * Returns `{ data, stripped, droppedTypes, sizeBefore, sizeAfter }`:
* - `data` is the new buffer (or the input buffer when no strip happened).
- * - `stripped` is true only when a `caBX` chunk was actually found and removed.
+ * - `stripped` is true only when at least one matching chunk was removed.
+ * - `droppedTypes` lists the distinct chunk types actually removed.
* - sizes reflect input vs output buffer lengths.
*
* Returns the input untouched (`stripped: false`) on non-PNG / malformed PNG /
* chunk-count overrun. Never throws — caller decides whether to write the
* result back or skip.
*/
-export function stripPngC2PAChunk(buffer) {
- const passThrough = { data: buffer, stripped: false, sizeBefore: buffer?.length || 0, sizeAfter: buffer?.length || 0 };
+function stripPngChunks(buffer, dropTypes) {
+ const passThrough = {
+ data: buffer, stripped: false, droppedTypes: [],
+ sizeBefore: buffer?.length || 0, sizeAfter: buffer?.length || 0,
+ };
if (!Buffer.isBuffer(buffer) || buffer.length < 8 || detectFormat(buffer) !== 'png') {
return passThrough;
}
- // First pass: locate every `caBX` chunk's start/end so we can splice them
- // out into a single new buffer allocation. Real PNGs only carry one but the
- // PNG spec doesn't forbid duplicates — handle it anyway so a defective
+ // First pass: locate every droppable chunk's start/end so we can splice them
+ // out into a single new buffer allocation. Real PNGs only carry one of each
+ // but the PNG spec doesn't forbid duplicates — handle it anyway so a defective
// producer can't leave provenance fragments behind.
const ranges = []; // [{ start, end }] of chunk bytes (length+type+data+crc) to drop
+ const dropped = new Set();
let offset = 8;
let count = 0;
let sawIEND = false;
@@ -138,7 +154,7 @@ export function stripPngC2PAChunk(buffer) {
const chunkEnd = offset + 8 + length + 4;
if (chunkEnd > buffer.length) return passThrough;
const type = buffer.toString('ascii', offset + 4, offset + 8);
- if (type === 'caBX') ranges.push({ start: offset, end: chunkEnd });
+ if (dropTypes.has(type)) { ranges.push({ start: offset, end: chunkEnd }); dropped.add(type); }
if (type === 'IEND') { sawIEND = true; break; }
offset = chunkEnd;
}
@@ -159,7 +175,29 @@ export function stripPngC2PAChunk(buffer) {
}
// Copy the tail after the last dropped chunk.
buffer.copy(out, writeOffset, readOffset);
- return { data: out, stripped: true, sizeBefore: buffer.length, sizeAfter: out.length };
+ return { data: out, stripped: true, droppedTypes: [...dropped], sizeBefore: buffer.length, sizeAfter: out.length };
+}
+
+/**
+ * Lossless C2PA strip — removes only the gpt-image `caBX` provenance chunk.
+ * Kept as a focused wrapper so the post-generation auto-clean hook (which only
+ * wants the provenance gone, not author metadata) and its tests stay stable.
+ * Returns `{ data, stripped, sizeBefore, sizeAfter }`.
+ */
+export function stripPngC2PAChunk(buffer) {
+ const { data, stripped, sizeBefore, sizeAfter } = stripPngChunks(buffer, C2PA_CHUNK_TYPES);
+ return { data, stripped, sizeBefore, sizeAfter };
+}
+
+/**
+ * Lossless metadata strip — removes C2PA (`caBX`) plus the ancillary metadata
+ * chunks (`tEXt`/`zTXt`/`iTXt`/`eXIf`, which carry EXIF/XMP/IPTC/comments).
+ * Pixels and color chunks are untouched. Returns the full
+ * `{ data, stripped, droppedTypes, sizeBefore, sizeAfter }` shape so callers can
+ * report exactly what was removed.
+ */
+export function stripPngMetadataChunks(buffer) {
+ return stripPngChunks(buffer, METADATA_CHUNK_TYPES);
}
const MIME_TYPES = {
@@ -178,18 +216,25 @@ function applyEncoder(pipeline, format) {
return pipeline.webp({ quality: 92 });
}
-// Throws ServerError (400) on invalid input so callers get a consistent
-// status instead of a sharp stack trace surfacing as a 500.
-export async function cleanImageBuffer(buffer) {
+/**
+ * Composable clean — runs an opt-in subset of the cleaning steps, in order:
+ * 1. metadata (default ON, lossless) — strip C2PA + EXIF/XMP/IPTC/text
+ * 2. denoise (default OFF, lossy) — median(3) + sharpen
+ *
+ * `denoise` re-encodes through sharp, which drops ALL ancillary metadata as a
+ * side effect — so when denoise runs it implicitly satisfies the metadata step
+ * regardless of the `metadata` flag (both off is the only way to keep metadata).
+ *
+ * Returns the cleaned bytes plus a per-step `steps[]` report so the route/UI can
+ * tell the user exactly what ran. Throws ServerError (400) on invalid input so
+ * callers get a consistent status instead of a sharp stack trace surfacing as a
+ * 500. No byte cap — see the MAX_PIXELS note above; the transport bounds size.
+ */
+export async function cleanImageBuffer(buffer, options = {}) {
+ const { metadata = true, denoise = false } = options;
if (!Buffer.isBuffer(buffer) || 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) {
@@ -199,27 +244,62 @@ export async function cleanImageBuffer(buffer) {
});
}
- const c2paStripped = format === 'png' && pngHasC2PA(buffer);
+ const sizeBefore = buffer.length;
+ const hadC2PA = format === 'png' && pngHasC2PA(buffer);
+ const steps = [];
+ let outData = buffer;
+ let width = null;
+ let height = null;
+ let c2paStripped = false;
- // 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.
- const base = sharp(buffer, { limitInputPixels: MAX_PIXELS }).rotate();
try {
- const { data, info } = await applyEncoder(applyDenoise(base), format)
- .toBuffer({ resolveWithObject: true });
- return {
- data,
- format,
- mimeType: MIME_TYPES[format],
- sizeBefore: buffer.length,
- sizeAfter: data.length,
- width: info.width || null,
- height: info.height || null,
- c2paStripped,
- };
+ if (denoise) {
+ // Single decode for EXIF auto-orient + denoise + encode. .rotate() with no
+ // args bakes the EXIF Orientation tag into pixels so the cleaned image
+ // matches what the browser showed (browsers honor EXIF orientation, sharp
+ // does not by default). The re-encode drops every ancillary chunk, so the
+ // metadata step is implicitly satisfied here too.
+ const base = sharp(buffer, { limitInputPixels: MAX_PIXELS }).rotate();
+ const { data, info } = await applyEncoder(applyDenoise(base), format)
+ .toBuffer({ resolveWithObject: true });
+ outData = data;
+ width = info.width || null;
+ height = info.height || null;
+ c2paStripped = hadC2PA;
+ if (metadata) steps.push({ step: 'metadata', status: 'applied', detail: 'dropped via re-encode' });
+ steps.push({ step: 'denoise', status: 'applied', detail: 'median(3) + sharpen' });
+ } else if (metadata && format === 'png') {
+ // Lossless PNG path: walk chunks and emit a new buffer minus the metadata
+ // chunks. Pixels byte-identical, no decode/re-encode.
+ const stripped = stripPngMetadataChunks(buffer);
+ outData = stripped.data;
+ c2paStripped = stripped.droppedTypes.includes('caBX');
+ const meta = await sharp(buffer, { limitInputPixels: MAX_PIXELS }).metadata();
+ width = meta.width || null;
+ height = meta.height || null;
+ steps.push({
+ step: 'metadata',
+ status: stripped.stripped ? 'applied' : 'noop',
+ detail: stripped.stripped ? `dropped ${stripped.droppedTypes.join(', ')}` : 'no metadata chunks found',
+ });
+ } else if (metadata) {
+ // JPEG/WebP have no cheap lossless chunk-walk; re-encode through sharp,
+ // which drops metadata by default. .rotate() bakes EXIF orientation into
+ // pixels first so the image still displays right-side-up after the tag is
+ // dropped. This is a re-encode (not strictly lossless) — the format
+ // carries no separate lossless metadata path here.
+ const base = sharp(buffer, { limitInputPixels: MAX_PIXELS }).rotate();
+ const { data, info } = await applyEncoder(base, format).toBuffer({ resolveWithObject: true });
+ outData = data;
+ width = info.width || null;
+ height = info.height || null;
+ steps.push({ step: 'metadata', status: 'applied', detail: 'dropped via re-encode' });
+ } else {
+ // No steps selected — return the input untouched, but still report dims.
+ const meta = await sharp(buffer, { limitInputPixels: MAX_PIXELS }).metadata();
+ width = meta.width || null;
+ height = meta.height || null;
+ }
} catch (err) {
// Wrap sharp errors (truncated/corrupt buffer that still passed the
// magic-byte sniff) into a 400 so bad input doesn't surface as a 500.
@@ -229,6 +309,18 @@ export async function cleanImageBuffer(buffer) {
context: { details: { format, reason: err.message } },
});
}
+
+ return {
+ data: outData,
+ format,
+ mimeType: MIME_TYPES[format],
+ sizeBefore,
+ sizeAfter: outData.length,
+ width,
+ height,
+ c2paStripped,
+ steps,
+ };
}
// Post-generation cleaners. Reads the just-written PNG, applies the requested
@@ -276,7 +368,7 @@ export async function autoCleanGeneratedImage({ cleanC2PA = false, denoise = fal
// Denoise re-encodes through sharp, which incidentally drops every
// ancillary chunk (including caBX). So a denoise pass implicitly
// satisfies the cleanC2PA flag too — no separate strip needed.
- const result = await cleanImageBuffer(buffer).catch((err) => {
+ const result = await cleanImageBuffer(buffer, { metadata: true, denoise: true }).catch((err) => {
console.warn(`⚠️ Auto-clean denoise failed for ${basename(pngPath)}: ${err?.message || err}`);
return null;
});
diff --git a/server/lib/imageClean.test.js b/server/lib/imageClean.test.js
index b4f63aa56d..6170fb0f60 100644
--- a/server/lib/imageClean.test.js
+++ b/server/lib/imageClean.test.js
@@ -4,7 +4,9 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import sharp from 'sharp';
-import { autoCleanGeneratedImage, stripPngC2PAChunk } from './imageClean.js';
+import {
+ autoCleanGeneratedImage, stripPngC2PAChunk, stripPngMetadataChunks, cleanImageBuffer,
+} from './imageClean.js';
let sandbox;
let pngFixture;
@@ -274,4 +276,82 @@ describe('stripPngC2PAChunk', () => {
expect(stripPngC2PAChunk(undefined).stripped).toBe(false);
expect(stripPngC2PAChunk('a string').stripped).toBe(false);
});
+
+ it('leaves text/exif chunks in place (caBX-only scope)', () => {
+ const textChunk = makePngChunk('tEXt', Buffer.from('Comment\0note', 'latin1'));
+ const polluted = injectChunkBeforeIEND(pngFixture, textChunk);
+ const result = stripPngC2PAChunk(polluted);
+ // stripPngC2PAChunk only targets caBX — a text chunk is untouched.
+ expect(result.stripped).toBe(false);
+ expect(result.data).toBe(polluted);
+ });
+});
+
+describe('stripPngMetadataChunks', () => {
+ it('strips caBX + text + exif chunks and reports which types it dropped', () => {
+ const caBX = makePngChunk('caBX', Buffer.alloc(20, 0xCA));
+ const text = makePngChunk('tEXt', Buffer.from('Author\0secret', 'latin1'));
+ const exif = makePngChunk('eXIf', Buffer.alloc(16, 0x07));
+ const polluted = injectChunkBeforeIEND(
+ injectChunkBeforeIEND(injectChunkBeforeIEND(pngFixture, caBX), text), exif,
+ );
+ const result = stripPngMetadataChunks(polluted);
+ expect(result.stripped).toBe(true);
+ expect(result.droppedTypes.sort()).toEqual(['caBX', 'eXIf', 'tEXt']);
+ // All three ancillary chunks gone → output equals the clean fixture.
+ expect(result.data.equals(pngFixture)).toBe(true);
+ });
+
+ it('is a no-op when only critical chunks are present', () => {
+ const result = stripPngMetadataChunks(pngFixture);
+ expect(result.stripped).toBe(false);
+ expect(result.droppedTypes).toEqual([]);
+ expect(result.data).toBe(pngFixture);
+ });
+});
+
+describe('cleanImageBuffer (composable steps)', () => {
+ it('throws VALIDATION_ERROR on an empty buffer', async () => {
+ await expect(cleanImageBuffer(Buffer.alloc(0))).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });
+ });
+
+ it('throws UNSUPPORTED_FORMAT on non-image input', async () => {
+ await expect(cleanImageBuffer(Buffer.from('nope'))).rejects.toMatchObject({ code: 'UNSUPPORTED_FORMAT' });
+ });
+
+ it('default (metadata only) losslessly strips a caBX chunk without re-encoding pixels', async () => {
+ const caBX = makePngChunk('caBX', Buffer.alloc(32, 0xCA));
+ const polluted = injectChunkBeforeIEND(pngFixture, caBX);
+ const result = await cleanImageBuffer(polluted);
+ expect(result.c2paStripped).toBe(true);
+ expect(result.steps.map((s) => s.step)).toEqual(['metadata']);
+ expect(result.steps[0].status).toBe('applied');
+ // Lossless: byte-identical to the clean fixture (no decode/re-encode).
+ expect(result.data.equals(pngFixture)).toBe(true);
+ expect(result.width).toBe(32);
+ expect(result.height).toBe(32);
+ });
+
+ it('metadata-only on a clean PNG reports a noop and returns the input', async () => {
+ const result = await cleanImageBuffer(pngFixture, { metadata: true, denoise: false });
+ expect(result.steps[0].status).toBe('noop');
+ expect(result.data).toBe(pngFixture);
+ });
+
+ it('denoise re-encodes (output differs) and reports both steps when metadata is also on', async () => {
+ const result = await cleanImageBuffer(pngFixture, { metadata: true, denoise: true });
+ expect(result.steps.map((s) => s.step)).toEqual(['metadata', 'denoise']);
+ // A re-encode produces a different buffer object than the input.
+ expect(result.data).not.toBe(pngFixture);
+ expect(result.width).toBe(32);
+ expect(result.height).toBe(32);
+ });
+
+ it('no steps selected returns the input untouched with an empty report', async () => {
+ const result = await cleanImageBuffer(pngFixture, { metadata: false, denoise: false });
+ expect(result.steps).toEqual([]);
+ expect(result.data).toBe(pngFixture);
+ expect(result.sizeAfter).toBe(result.sizeBefore);
+ expect(result.width).toBe(32);
+ });
});
diff --git a/server/routes/imageClean.js b/server/routes/imageClean.js
index 3c2c443986..db81d2f4f5 100644
--- a/server/routes/imageClean.js
+++ b/server/routes/imageClean.js
@@ -1,14 +1,18 @@
// HTTP wrapper around the core cleaning primitives in server/lib/imageClean.js.
// All sharp/PNG-walker logic lives in the lib so services can call it directly
// (services importing from routes would be a layering violation).
+//
+// Transport: raw image bytes in the request body (no base64-in-JSON inflation),
+// pipeline options in the query string, cleaned bytes back as the response body
+// with the small report in the `X-Clean-Report` header. The global
+// express.json() parser in server/index.js is a no-op here because the request
+// content-type is image/*, so this route's express.raw() owns the body.
-import { Router } from 'express';
+import { Router, raw } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import {
- cleanImageBuffer, CLEAN_LEVELS, MAX_INPUT_BYTES, MAX_BASE64_CHARS,
-} from '../lib/imageClean.js';
+import { cleanImageBuffer, CLEAN_LEVELS } from '../lib/imageClean.js';
const router = Router();
@@ -16,37 +20,65 @@ const router = Router();
// consumers in the routes layer keep working.
export { cleanImageBuffer, CLEAN_LEVELS };
-const cleanBodySchema = z.object({
- data: z.string().min(1, 'data is required (base64)'),
+// Query-string flag → boolean. Accepts the common truthy/falsey string forms a
+// browser fetch sends ("1"/"0"/"true"/"false"); anything else falls back to the
+// schema default. Mirrors the history.js success-filter pattern.
+const queryFlag = (def) => z.preprocess(
+ (v) => {
+ if (v === undefined) return def;
+ if (v === 'true' || v === '1') return true;
+ if (v === 'false' || v === '0') return false;
+ return v;
+ },
+ z.boolean(),
+);
+
+// Pipeline steps ride in the query string, not the body (the body is the image).
+const cleanQuerySchema = z.object({
+ metadata: queryFlag(true),
+ denoise: queryFlag(false),
});
-router.post('/', asyncHandler(async (req, res) => {
- const { data } = 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');
- const result = await cleanImageBuffer(buffer);
-
- console.log(`🧼 Image cleaned: ${result.format} ${result.sizeBefore}B → ${result.sizeAfter}B (c2pa=${result.c2paStripped})`);
-
- res.json({
- data: result.data.toString('base64'),
- mimeType: result.mimeType,
- format: result.format,
- sizeBefore: result.sizeBefore,
- sizeAfter: result.sizeAfter,
- width: result.width,
- height: result.height,
- c2paStripped: result.c2paStripped,
- });
-}));
+// 256 MiB raw-byte ceiling — the transport is the only (generous) size bound now
+// that base64 inflation is gone. The decompression-bomb guard (MAX_PIXELS) in
+// the lib still protects the process regardless of byte size.
+const RAW_LIMIT = '256mb';
+const RAW_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'application/octet-stream'];
+
+router.post(
+ '/',
+ raw({ type: RAW_TYPES, limit: RAW_LIMIT }),
+ asyncHandler(async (req, res) => {
+ const { metadata, denoise } = validateRequest(cleanQuerySchema, req.query);
+
+ const buffer = Buffer.isBuffer(req.body) ? req.body : null;
+ if (!buffer || buffer.length === 0) {
+ throw new ServerError('Request body must be raw image bytes', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+
+ const result = await cleanImageBuffer(buffer, { metadata, denoise });
+
+ const report = {
+ format: result.format,
+ sizeBefore: result.sizeBefore,
+ sizeAfter: result.sizeAfter,
+ width: result.width,
+ height: result.height,
+ c2paStripped: result.c2paStripped,
+ steps: result.steps,
+ };
+
+ console.log(`🧼 Image cleaned: ${result.format} ${result.sizeBefore}B → ${result.sizeAfter}B (c2pa=${result.c2paStripped}, steps=${result.steps.map((s) => s.step).join('+') || 'none'})`);
+
+ // Expose the report header so a cross-origin / dev-proxied fetch can read it.
+ res.setHeader('Access-Control-Expose-Headers', 'X-Clean-Report');
+ res.setHeader('X-Clean-Report', JSON.stringify(report));
+ res.setHeader('Content-Type', result.mimeType);
+ res.send(result.data);
+ }),
+);
export default router;
diff --git a/server/routes/imageClean.test.js b/server/routes/imageClean.test.js
index 090f8fc350..c56d63ce01 100644
--- a/server/routes/imageClean.test.js
+++ b/server/routes/imageClean.test.js
@@ -1,10 +1,13 @@
import { describe, it, expect, beforeAll } from 'vitest';
+import { randomBytes } from 'node:crypto';
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';
+// Mirror server/index.js: the global express.json() runs first but is a no-op
+// for image/* content-types, so the route's own express.raw() owns the body.
const buildApp = () => {
const app = express();
app.use(express.json({ limit: '55mb' }));
@@ -13,10 +16,15 @@ const buildApp = () => {
return app;
};
+// Read the JSON report the route stows in the X-Clean-Report response header.
+const reportOf = (res) => JSON.parse(res.headers['x-clean-report']);
+
let pngFixture;
let jpegFixture;
let webpFixture;
let pngWithC2PA;
+let pngWithText;
+let largePng;
beforeAll(async () => {
// 4×4 fixtures sized just large enough to round-trip through sharp.
@@ -27,162 +35,152 @@ beforeAll(async () => {
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),
- ]);
+ // Build extra chunks structurally so the metadata-strip pass has something to
+ // remove regardless of sharp's metadata-writing behavior across versions.
+ const ihdrEnd = 8 + 25; // signature + IHDR (4+4+13+4)
+ const buildChunk = (type, data) => {
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(data.length, 0);
+ return Buffer.concat([len, Buffer.from(type, 'ascii'), data, Buffer.alloc(4) /* CRC unchecked */]);
+ };
+ const cabxChunk = buildChunk('caBX', Buffer.from([0x01, 0x02, 0x03, 0x04]));
+ pngWithC2PA = Buffer.concat([pngFixture.slice(0, ihdrEnd), cabxChunk, pngFixture.slice(ihdrEnd)]);
+
+ const textChunk = buildChunk('tEXt', Buffer.from('Comment\0secret author note', 'latin1'));
+ pngWithText = Buffer.concat([pngFixture.slice(0, ihdrEnd), textChunk, pngFixture.slice(ihdrEnd)]);
+
+ // A multi-MB valid PNG to prove raw-byte transport handles payloads far above
+ // the old 40MB *base64* envelope without a 413/FILE_TOO_LARGE. Truly random
+ // bytes so PNG can't compress it down to a trivial size.
+ const w = 1200;
+ const h = 1200;
+ const raw = randomBytes(w * h * 3);
+ largePng = await sharp(raw, { raw: { width: w, height: h, channels: 3 } }).png().toBuffer();
});
-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') });
+const postImage = (query, buffer, contentType = 'image/png') =>
+ request(buildApp())
+ .post(`/api/image-clean${query}`)
+ .set('Content-Type', contentType)
+ .send(buffer);
+describe('POST /api/image-clean (raw transport)', () => {
+ it('cleans a PNG and returns the bytes + report header', async () => {
+ const res = await postImage('', pngFixture);
expect(res.status).toBe(200);
- expect(res.body.format).toBe('png');
- expect(res.body.mimeType).toBe('image/png');
- 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);
+ expect(res.headers['content-type']).toBe('image/png');
+ const report = reportOf(res);
+ expect(report.format).toBe('png');
+ expect(report.width).toBe(4);
+ expect(report.height).toBe(4);
+ expect(report.c2paStripped).toBe(false);
+ expect(report.steps.some((s) => s.step === 'metadata')).toBe(true);
});
it('cleans a JPEG and emits a JPEG response', async () => {
- const res = await request(buildApp())
- .post('/api/image-clean')
- .send({ data: jpegFixture.toString('base64') });
-
+ const res = await postImage('', jpegFixture, 'image/jpeg');
expect(res.status).toBe(200);
- expect(res.body.format).toBe('jpeg');
- expect(res.body.mimeType).toBe('image/jpeg');
+ expect(res.headers['content-type']).toBe('image/jpeg');
+ expect(reportOf(res).format).toBe('jpeg');
});
it('cleans a WebP', async () => {
- const res = await request(buildApp())
- .post('/api/image-clean')
- .send({ data: webpFixture.toString('base64') });
-
+ const res = await postImage('', webpFixture, 'image/webp');
expect(res.status).toBe(200);
- expect(res.body.format).toBe('webp');
- expect(res.body.mimeType).toBe('image/webp');
+ expect(res.headers['content-type']).toBe('image/webp');
+ expect(reportOf(res).format).toBe('webp');
});
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') });
+ const res = await postImage('', pngWithC2PA);
+ expect(res.status).toBe(200);
+ expect(reportOf(res).c2paStripped).toBe(true);
+ });
+
+ it('metadata step (default) losslessly strips text chunks', async () => {
+ const res = await postImage('', pngWithText);
+ expect(res.status).toBe(200);
+ const report = reportOf(res);
+ const meta = report.steps.find((s) => s.step === 'metadata');
+ expect(meta.status).toBe('applied');
+ expect(meta.detail).toContain('tEXt');
+ // Lossless strip only removes the chunk → output is smaller than input.
+ expect(report.sizeAfter).toBeLessThan(report.sizeBefore);
+ });
+
+ it('runs the denoise step when ?denoise=1', async () => {
+ const res = await postImage('?denoise=1', pngFixture);
+ expect(res.status).toBe(200);
+ const report = reportOf(res);
+ expect(report.steps.some((s) => s.step === 'denoise' && s.status === 'applied')).toBe(true);
+ });
+ it('runs no steps and passes bytes through when ?metadata=0&denoise=0', async () => {
+ const res = await postImage('?metadata=0&denoise=0', pngWithC2PA);
expect(res.status).toBe(200);
- expect(res.body.c2paStripped).toBe(true);
+ const report = reportOf(res);
+ expect(report.steps).toEqual([]);
+ // Untouched passthrough — the caBX chunk is left in place.
+ expect(report.sizeAfter).toBe(report.sizeBefore);
+ expect(report.c2paStripped).toBe(false);
+ });
+
+ it('accepts a multi-MB raw payload without a 413/FILE_TOO_LARGE (40MB cap removed)', async () => {
+ expect(largePng.length).toBeGreaterThan(1_000_000);
+ const res = await postImage('', largePng);
+ expect(res.status).toBe(200);
+ expect(reportOf(res).format).toBe('png');
});
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 fake = Buffer.concat([pngSig, Buffer.alloc(1024)]);
const start = Date.now();
- const res = await request(buildApp())
- .post('/api/image-clean')
- .send({ data: fake.toString('base64') });
- const elapsed = Date.now() - start;
-
+ const res = await postImage('', fake);
+ expect(Date.now() - start).toBeLessThan(1000);
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.
+ it('caps the chunk walk so a PNG-sig buffer of zero-length ASCII chunks bails fast', async () => {
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)
+ Buffer.from([0x00, 0x00, 0x00, 0x00]),
+ Buffer.from('ABCD', 'ascii'),
+ Buffer.from([0x00, 0x00, 0x00, 0x00]),
]);
- // 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;
-
+ const res = await postImage('', fake);
+ expect(Date.now() - start).toBeLessThan(1500);
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 });
-
+ const res = await postImage('', Buffer.from('not an image at all'), 'application/octet-stream');
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: '' });
-
+ it('rejects an empty body with VALIDATION_ERROR', async () => {
+ const res = await postImage('', Buffer.alloc(0));
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('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.
+ // 4×8 JPEG re-emitted with EXIF Orientation=6 (rotate 90° CW). The metadata
+ // re-encode path bakes in the rotation → output is 8×4 (dims 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') });
+ const oriented = await sharp(raw).withMetadata({ orientation: 6 }).jpeg().toBuffer();
+ const res = await postImage('', oriented, 'image/jpeg');
expect(res.status).toBe(200);
- expect(res.body.width).toBe(8);
- expect(res.body.height).toBe(4);
+ const report = reportOf(res);
+ expect(report.width).toBe(8);
+ expect(report.height).toBe(4);
});
});
diff --git a/server/services/imageGen/variants.js b/server/services/imageGen/variants.js
index 1f0e9416ed..e7283a4d0a 100644
--- a/server/services/imageGen/variants.js
+++ b/server/services/imageGen/variants.js
@@ -134,7 +134,8 @@ export async function applyImageClean({ filename, sourceMeta }) {
throw err;
});
- const result = await cleanImageBuffer(buffer);
+ // Gallery "clean" is the aggressive variant: metadata strip + denoise.
+ const result = await cleanImageBuffer(buffer, { metadata: true, denoise: true });
if (result.format !== 'png') {
throw new ServerError('Gallery images must be PNG', { status: 400, code: 'UNSUPPORTED_FORMAT' });
}