Skip to content

Latest commit

 

History

History
181 lines (147 loc) · 34.6 KB

CLAUDE.md

File metadata and controls

181 lines (147 loc) · 34.6 KB

CLAUDE.md

This file provides context for Claude when working on this codebase.


Project overview

ImaGUIck is a self-hosted Flask web application for single/batch image resizing, format conversion, and GIF/WEBP animation creation & editing, powered by ImageMagick. It is deployed via Docker (multi-arch: amd64 + arm64) and published on Docker Hub as tiritibambix/imaguick.


Repository structure

app.py                  # All Flask routes and image processing logic
cleanup.py              # Scheduled file cleanup (48 h retention)
cleanup.sh              # Manual cleanup helper script
Dockerfile              # Multi-arch Docker build (ImageMagick compiled from source on both arches)
docker-compose.yml      # Reference deployment
start.sh                # Container entrypoint: starts cron + Gunicorn
requirements.txt        # Python deps (Flask, Pillow, requests)
templates/
  base.html                    # Design system: CSS variables, shared header/nav, SVG icon sprite, DM Sans + DM Mono fonts
  index.html                   # Upload page — Resize / Create GIF·WEBP tabs, drag-and-drop, XHR upload, URL import
  resize.html                  # Single-image resize options
  resize_batch.html            # Batch resize options
  gif_create.html               # Create an animated GIF/WEBP from a sequence of uploaded images
  gif_edit.html                 # Edit an existing animated GIF/WEBP (resize/optimize/speed/reverse/rotate/loop/extract)
  progress.html                 # Real-time SSE progress page for batch jobs and GIF creation
  result.html                   # Success / error result page
  _resize_options_styles.html   # Shared <style> partial for the resize/GIF options-page layout
  _resize_form_fields.html      # Shared Jinja macros for repeated form field groups
static/media/           # Logo, banner, favicon
.github/workflows/
  docker-build.yml      # CI/CD: build + push multi-arch image to Docker Hub (every branch)
  export-alerts.yml     # Manual export of code-scanning alerts as an artifact

Architecture decisions

Backend

  • Flask + Gunicorn (gthread worker, exactly 1 worker process × 16 threads — see start.sh comment: jobs/upload_sessions/the ImageMagick semaphore are plain in-process Python state with no external store, so they are only consistent within a single worker process; more than one worker causes spurious "No files selected"/"Job not found" errors when a request lands on a worker that never saw an earlier request's state)
  • No database — job state held in-memory in the jobs dict (protected by jobs_lock), purged after JOBS_TTL_HOURS via purge_old_jobs()
  • Async batch processing via ThreadPoolExecutor (16 workers) + BoundedSemaphore(4) for ImageMagick concurrency
  • SSE streaming — /job/<id>/status polls the in-memory job dict and streams JSON events; the payload's kind field ('batch' or 'gif_create') and output/zip fields tell progress.html which single-file vs. ZIP download link to show
  • Upload sessions — batch/GIF-creation filenames stored server-side in upload_sessions dict (keyed by UUID) to avoid the URL length limit set by Gunicorn's --limit-request-line 8190 (see start.sh)
  • GIF/WEBP creation (process_gif_create_job()) runs in two stages, which is what makes its progress measurable: prepare_gif_frame() normalises each frame in its own ImageMagick process (orientation + canvas), submitted to the shared executor under the same semaphore batch resize uses, then build_gif_assemble_command() assembles the already-normalised frames in one final pass. Frames land in output/gifframes_<job_id>/, removed in a finally regardless of outcome. Beyond progress, this keeps peak memory to one frame instead of the whole coalesced sequence, and leaves the assembly working on already-resized images
  • The GIF progress bar is a count, never an estimate. The frame stage owns GIF_FRAME_PHASE_PERCENT of the bar and its value is round(80 * frames_done / total) — finished subprocesses, counted in Python, with nothing parsed. The assembly that follows is one indivisible invocation, so the bar goes indeterminate (indeterminate on the job and in the SSE payload) rather than inventing a figure. An earlier version assigned each ImageMagick operation a hand-picked slice of the bar; that is what produced a meaningless "14 of 14" frozen at the end of reading, and stage names scrolling past while the bar sat still. Do not reintroduce weighted bands.
    • run_with_progress() still runs the assembly under -monitor via Popen, but only to name the current operation (make_gif_assembly_reporter() → phase_detail) and to refresh liveness. Tags are mapped through _MONITOR_STAGE_NAMES, which matches what ImageMagick actually emits — -colors reports as Classify/Image then Assign/Image (see MagickCore/quantize.c), never "quantize" — and an unrecognised tag falls back to its own operation name instead of being dropped.
    • Some steps report nothing at all. OptimizeLayerFrames(), which is what -layers optimize runs, has no progress monitor, so silence there is expected. The job carries stage_started_at / last_event_at, streamed as stage_seconds / idle_seconds; the page shows a per-stage timer plus a note past MONITOR_IDLE_HINT_SECONDS. That timer is what distinguishes working from hung.
    • run_with_progress() raises exactly what subprocess.run(check=True) would, keeping timeout and error handling unchanged, and strips progress lines out of the stderr used for user-facing messages
    • The assembly timeout is scaled to the frames, not the flat SUBPROCESS_TIMEOUT_LONG. -layers optimize plus -colors over many full-resolution frames runs well past 300 s (23 frames at 2304×1536 did not finish in it, and full resolution is kept by choice — frames are only downscaled when a canvas size is requested). gif_assembly_timeout() reads each normalised frame's size from its header and budgets GIF_ASSEMBLE_SECONDS_PER_MEGAPIXEL per frame-megapixel, floored at SUBPROCESS_TIMEOUT_LONG so small jobs are unchanged and capped at GIF_ASSEMBLE_TIMEOUT_CEILING so a runaway pass is still killed. The per-megapixel figure is an estimate; tune it against real container timings. The per-stage liveness timer on progress.html is what makes a multi-minute assembly legible rather than looking hung
  • GIF/WEBP editing (/gif_edit/<filename>) is synchronous, mirroring /resize/<filename>'s pattern, since edits operate on one already-uploaded file and are bounded

Image processing

  • ImageMagick 7.1.2-31, built from source on both architectures. The version lives in a single ARG IMAGEMAGICK_VERSION in the Dockerfile and is asserted at build time (magick -version | grep -q), so a wrong tarball fails the build instead of shipping
  • JXL support via libjxl-tools (cjxl / djxl)
  • RAW support via ExifTool (dimension extraction) + dcraw (decode to TIFF via prepare_input_file())
  • WebP support via libwebp-dev + pkg-config (needed for animated WEBP muxing, not just single-frame WEBP — ImageMagick's ./configure detects delegate libraries like libwebp via pkg-config, so both packages are required on the amd64 source-build path) — webp_animation_supported() reads the WEBP row of magick -list format once at startup (logged) and is re-checked before any GIF/WEBP route accepts WEBP as an output format
  • Vector output (SVG, EPS, PDF, AI) requires potrace — checked at runtime before building the ImageMagick command
  • SVG input is rasterized by librsvg (librsvg2-dev + --with-rsvg), not by Ghostscript. Without it ImageMagick silently falls back to its built-in MSVG renderer, which draws basic shapes but ignores gradients, filters, clip paths, CSS and font-rendered text — so a Figma/Illustrator export comes out mangled or blank. Like libwebp, this is a ./configure detection rather than a guarantee, so the Dockerfile asserts magick -version | grep -q rsvg at build time: a detection miss fails the build instead of shipping a broken SVG path. .svg is carried by its own SVG_EXTENSIONS set rather than DOCUMENT_INPUT_EXTENSIONS, because an SVG is not multi-page and must not get the [0] suffix
  • PDF/EPS input is rasterized by Ghostscript (apt package ghostscript). Two consequences are wired into build_imagemagick_command(): the input gets a [0] suffix for DOCUMENT_INPUT_EXTENSIONS, because a multi-page PDF would otherwise make ImageMagick write out-0.png, out-1.png … and never create the single output_path the caller expects; and the -density guard scales the 72 dpi probe by the requested dpi before comparing against MAX_DIMENSION, since a check against the probe alone cannot see a large page blowing past it once rasterized
  • Photo retouching — -clahe (adaptive local contrast, levels mapped through CLAHE_PARAMS), -modulate (brightness/saturation/hue, clamped by MODULATE_RANGES and omitted entirely when all three are neutral), and noise reduction (-despeckle, -enhance, -kuwahara). -kuwahara is superlinear in radius, so it is refused above KUWAHARA_MAX_PIXELS up front rather than being left to hit the subprocess timeout
  • GIF/WEBP animation — creation is split across build_gif_frame_command() (one frame: -auto-orient, plus -resize/-extent when a canvas was requested) and build_gif_assemble_command() (-delay/-loop over the normalised frames, then palette and optimisation). There is deliberately no -coalesce on the creation path: these are still images with no frame-disposal history, and coalescing them forces a full RGBA materialisation of the sequence. build_gif_edit_command() handles resize/optimize/speed/reverse/rotate/loop on an existing animated file; build_gif_extract_command() pulls one frame, a range, or all frames via ImageMagick's file[N]/file[N-M] subimage syntax. RAW/JXL files are not supported as GIF-creation frames (they'd need the same dcraw/djxl pre-decode prepare_input_file() does for the resize pipeline, which the GIF path doesn't call) — rejected explicitly rather than failing silently.
  • All subprocess calls use list form, never shell=True
  • Argument order in build_imagemagick_command() is load-bearing: -density and -define jpeg:size= are read-time settings and must precede the input path; -auto-orient must precede -strip, which would otherwise discard the EXIF orientation before it is applied; cropping precedes -resize so the resize geometry frames the cropped image. Noise reduction runs before the tonal block because both -clahe and -unsharp amplify whatever noise they are handed, and -modulate runs last of the tonal operations so the one manual setting is not re-equalised by an automatic one. Rotation and mirroring precede the crop, so a crop box is expressed against the image as it will be framed; effects and blur sit after the tonal block but before -unsharp, since sharpening a deliberate blur undoes it; and the watermark is applied after the resize, so its point size is relative to the delivered image, and after flattening, so it is never composited onto an alpha channel that is about to be removed. The full order is: [-density] [-define jpeg:size=] <input> -auto-orient [-strip] [-rotate/-flop/-flip] [crop] [denoise] [-auto-gamma] [-auto-level] [-clahe] [-modulate] [effect] [-blur] [-unsharp] [-resize | upscale] [flatten] [watermark] [-quality] <output>. jpeg:size makes libjpeg decode at a reduced scale, so it is emitted only for absolute bounding-box geometries — never alongside a percentage resize, a pixel crop box, or an enlargement, all of which are measured against the decoded image and would silently operate on the wrong size (jpeg_decode_hint() encodes the rule, and build_imagemagick_command() resolves cropping and upscale_value before the hint so both can suppress it)
  • Enlarging (UPSCALE_FACTORS) is a -resize N% followed by -unsharp UPSCALE_UNSHARP. It is its own resize mode and wins over the presets and width/height rather than compounding with them, so the requested factor is the one that applies. Its -unsharp follows the resize, which is the opposite of the sharpen option and deliberate: enlarging softens, so the sharpen has to come after. This is what tools advertising "AI upscaling" on a CPU generally do; naming it plainly promises nothing it cannot deliver
  • Cropping has two forms. ALLOWED_CROP_RATIOS gives a centred box via centered_crop_box() and emits -gravity center; an explicit crop_w/h/x/y goes through explicit_crop_box(), which bounds-checks the region against the source and emits no -gravity, because -gravity center would measure its offsets from the middle. An explicit box wins over a ratio
  • Reading magick -list format — the columns are Format / Module / Mode / Description. Locate the mode by its shape via parse_format_row(), never by index: reading position 1 returns Module. webp_animation_supported() relies on the + in the WEBP row's mode, which is what marks multi-image support; it does not use -list delegate, which reports external delegate programs rather than built-in coders like libwebp

Frontend

  • All templates extend base.html via Jinja2 {% extends %}; resize.html/resize_batch.html/gif_create.html/gif_edit.html also share _resize_options_styles.html (CSS) and _resize_form_fields.html (Jinja macros) to avoid re-duplicating the options-page layout
  • The options pages have one control vocabulary, and a control's shape states what kind of answer it wants. Four primitives in _resize_form_fields.html cover everything: segmented() for one of 2–5 exclusive choices, switch() for an independent on/off, number() for a magnitude with its unit attached, and a plain <select> for one of many. Everything sits on a single --control-h, so pills, inputs and selects line up. Before this there were eight idioms, 26 .intensity-radio and 10 .check-pill doing overlapping jobs, and three inline grid-template-columns overrides. Do not add a fifth shape; if a decision does not fit one of the four, the decision is probably mis-framed
  • Options are grouped in the order build_imagemagick_command() runs them, across three stages: Source (read-time settings), Actions (Size, Frame, Repair, Tone, Look, Watermark), Output (Encoding). The ordering is not a style choice — it is the pipeline, which is why "why is sharpening before the resize?" answers itself from the UI. Groups are <details>, so disclosure costs no JS and keeps keyboard behaviour native
  • A shut group states its own state, and only what deviates from the default. options_script() builds each summary from the group's own controls with no per-group configuration to drift, and compares against the browser's own defaultChecked/defaultValue/defaultSelected, so "Keep", "None" and a quality of 100 stay silent. This is what makes collapsing safe in a form with one submit button: nothing is ever both set and invisible. Controls inside a hidden reveal are skipped, so a field belonging to an unselected mode never counts. When reading a value's unit, scope the lookup to the input's own .num wrapper — searching the parent picks up a sibling field's unit, which is how the watermark caption once rendered as "hellopt"
  • data-when="field=value" and data-when-filled="field" drive conditional reveals generically; there is no per-field JavaScript. A new conditional block needs only the attribute
  • _resize_options_styles.html still carries a small block of legacy layout classes (.form-grid, .section-block, .options-row, .submit-area, …) used only by gif_create.html and gif_edit.html, which have not been migrated to the stage/group vocabulary. It is marked as such; delete it when they move over. The resize pages reference none of them
  • Design system: dark theme, violet accent (#8b5cf6), DM Sans + DM Mono (Google Fonts)
  • CSS variables defined in base.html :root — do not redefine in child templates
  • Sticky header/nav (base.html) with an inline SVG <symbol> icon sprite — add new icons there, reference via <svg class="icon"><use href="#icon-name"></use></svg>
  • No JS frameworks, no build step — vanilla JS only
  • XHR upload with progress bar in index.html; batch/GIF-creation progress via EventSource (SSE) in progress.html
  • GIF creation preview (gif_create.html) preloads every frame as a decoded Image and then plays them on a <canvas> from a requestAnimationFrame accumulator. Both halves matter: frames are fetched from /preview_frame/<filename>?w=<px> as PIL-generated thumbnails (build_preview_thumbnail(), JPEG draft mode + an in-memory cache bounded by PREVIEW_CACHE_MAX_ENTRIES) rather than full-resolution originals, and playback is driven by elapsed time rather than setInterval + <img src> swapping, which used to make frame duration depend on network and decode latency. Thumbnail width scales down as frame count grows, since every frame stays decoded in memory for the session
  • index.html has a Resize / Create GIF·WEBP tab switcher; the GIF tab enables drag-to-reorder on the selected-files list (order becomes frame order) and sets a hidden intent field read by /upload
  • The GIF tab covers both creation and editing, decided by what was uploaded: several images go to gif_create_options, a single animated file (is_animated_file(), extension-gated on ANIMATED_EXTENSIONS then confirmed with PIL) goes to gif_edit_options. Before this, the editor was only reachable from an inline link on the resize options page, so users looking for it on the GIF tab hit "at least 2 images" and never found it. That resize-page link is kept as a second way in.

Security constraints

These are non-negotiable — do not remove or weaken them:

  • Serving a file the request named goes through resolve_stored_file(name, folder), never through joining the request value onto a folder. It matches the basename against a os.scandir() listing and returns the matching entry's own absolute path, so nothing a client sends ever forms a filesystem path — traversal, absolute paths and symlink tricks simply fail to match. It returns an absolute path deliberately: send_file() resolves a relative path against the Flask app root rather than the working directory.
  • secure_path() is for paths the application builds (output files, temp frames), not for request-named ones. It resolves both sides and tests containment against base + os.sep — a bare prefix test would also accept a sibling directory whose name merely starts with the folder's (uploads_elsewhere next to uploads).
  • safe_display_filename() applied to any filename from the URL or form before it is displayed, stored or logged. It preserves spaces, & and accents, and strips a leading -, which would otherwise be read as an option by a tool the name is handed to as an argv element.
  • Directories that get created, listed and rmtreed are named from a UUID alone (the GIF frame-extraction scratch dir), with nothing derived from the request. A readable name is used for the resulting download instead.
  • Every path the app writes to is passed through secure_path() first, including the two upload paths. The sanitiser already removes separators so the check cannot currently fail — that is the point: a regression in the sanitiser surfaces as a refused upload rather than a write outside uploads/.
  • Mutually exclusive options are enforced where form input enters, not hoped for downstream. The four resize modes (pixels, percentage, the fit presets, enlarging) and the two crop modes are exclusive branches in the builder, but the form used to offer them as independent controls. The result was measurable: ticking both presets emitted -resize 1920x1920> -resize 1080x1080>, a preset plus explicit dimensions resized twice, and a typed percentage was silently discarded when a preset was also set. resolve_size_mode() now reads a single size_mode (and crop_mode alongside it) and extract_processing_params() lets only that mode's fields through; the builder's resize section is a single if/elif chain, so more than one -resize cannot be expressed. Both resolvers fall back to inferring the mode from whichever fields carry a value, in the builder's own precedence order, so a page left open across a deploy still resizes instead of silently doing nothing. Sharpening went the same way: the level is the switch, and use_sharpen is derived, so there is no "enabled but no level" state left to resolve
  • An allowlisted string that goes on to form a command argument or a filename is passed through canonical_value(), which returns the allowlist's own literal rather than the caller's string (output_format, density, extract_format, background colour). Checking membership with in and then forwarding the request's copy leaves that copy in play; this is the COMMANDS[action] idiom CodeQL's own guidance recommends. A hex colour is rebuilt from its parsed components by canonical_hex_color() for the same reason. Values that only ever serve as a dict key (sharpen_level, clahe_level, kuwahara_level, crop_ratio) or as the subject of an == test (denoise_mode) need no such treatment — what reaches the command is already one of our constants.
  • Output filenames derive from the resolved file's own name, never from the route parameter. os.path.basename(filepath) after resolve_stored_file() and the request string are equal by construction, but only the former is known to name a file we store, so it is the one that gets stripped of its UUID prefix to build the output name.
  • A numeric value that ends up in a command argument is parsed into a name of its own, never converted in place. width = int(width) sitting inside if width: leaves two definitions of width reaching the geometry string below it, and on the branch that skipped the conversion the unconverted request string is one of them — the guards make that branch unreachable, but nothing in the code says so. resize_dimension() and jpeg_decode_hint() both return fresh values for this reason; -quality and -modulate build their arguments from int() results the same way. This was the last py/command-line-injection alert and the only one whose flow ran through arithmetic rather than through a path or an allowlist.
  • Free-form text is contained, not escaped. The watermark caption cannot be allowlisted, so safe_watermark_text() keeps it safe structurally: it travels as exactly one argv element, verbatim, and no shell is involved — which is why spaces, quotes, ;, & and accents must survive untouched. Escaping them is what breaks the moment the transport changes. Two things are still removed, because they are ImageMagick problems rather than shell ones: a leading @, which makes ImageMagick read the annotation from a file (-annotate @/etc/passwd would render that file into the image — the same class of defect as the leading - that safe_display_filename() strips), and unprintable characters. Surrounding whitespace is trimmed before the @ strip, or " @file" survives it and the later trim puts the @ back in front. The property worth pinning if a test suite ever lands: for every -annotate, argv[i + 2] is the caption exactly
  • ALLOWED_OUTPUT_FORMATS — explicit set; any format value not in it is rejected to ''
  • ALLOWED_SHARPEN_LEVELS — {'low', 'standard', 'high'}; unknown values fall back to 'standard'
  • POTRACE_FORMATS — vector formats checked for potrace availability before building the command
  • is_safe_url() — full DNS resolution + rejection of private/loopback/link-local/multicast IPs (SSRF prevention)
  • MAX_DIMENSION is enforced on both input (get_image_dimensions()) and output (build_imagemagick_command() rejects any requested width/height/percentage that would exceed it); GIF_MAX_OUTPUT_DIMENSION/GIF_MAX_FRAMES/GIF_MAX_TOTAL_PIXELS do the equivalent for GIF/WEBP creation and editing, checked before any decode/processing work
  • SUBPROCESS_TIMEOUT_SHORT/MEDIUM/LONG — every subprocess.run() call has an explicit timeout
  • All subprocess calls use list arguments — never build shell strings with user data

GitHub Actions

Workflows live in .github/workflows/. Key conventions:

  • Secrets: DOCKER_USERNAME and DOCKER_PASSWORD (not DOCKERHUB_*)
  • Actions are SHA-pinned where possible, with version comment (e.g. # v7.0.1)
  • Each job has permissions: contents: read; a global permissions: contents: read block sits above jobs:
  • Standard action versions in use:
    • actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
    • docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
    • actions/cache/restore@v5 / actions/cache/save@v5 (SHA pin pending)
    • docker/setup-qemu-action@v4 (SHA pin pending)
    • docker/setup-buildx-action@v4 (SHA pin pending)
    • docker/build-push-action@v7 (SHA pin pending)
    • peter-evans/dockerhub-description@v5 (SHA pin pending)

One workflow covers every branch. docker-build.yml triggers on push to '**' plus workflow_dispatch; there is deliberately no pull_request trigger, because a fork PR cannot read the Docker Hub secrets and would only ever fail at the push step. There is no paths-ignore either: the point is a published image for every commit.

  • The check job caches last_commit.txt per branch (actions/cache) and sets skip=true when the current SHA was already built, so re-running a workflow does not rebuild and re-push the same commit. A workflow_dispatch always overrides the skip.
  • It also composes the whole tag list, as a multi-line step output consumed by build-and-push as needs.check.outputs.tags. Keeping tag composition in one shell step rather than in the tags: block is what makes the main-only latest a two-line conditional instead of a YAML expression per tag.
  • update-dockerhub-description is gated on github.ref_name == 'main'. Without that gate, pushing any branch would rewrite the public Docker Hub description from that branch's README.
  • audit (pip-audit) gates the build, so a known CVE in Flask/Pillow/requests stops the image from being published on any branch.
  • Both architectures build ImageMagick from source and arm64 runs under QEMU, so this workflow is slow by nature. cache-from/to: type=gha is what keeps a second push to the same branch from paying the full compile again; expect the first build on a new branch to be long.

Docker Hub

  • Account: tiritibambix
  • Image: tiritibambix/imaguick
  • Tags: every branch publishes <branch>-latest, <branch>-<short-sha> and <branch>-<YYYYMMDD>; main additionally keeps the bare latest, because docker-compose.yml and the README both pull it by name. Branch names are sanitised to the Docker tag charset (feat/café#2 → feat-caf-2), and a name starting with a separator is prefixed, since a tag may not

Known constraints and gotchas

  • Accepting PDF/EPS uploads hands arbitrary files to Ghostscript, which has a long history of vulnerabilities allowing code execution via crafted PostScript. Two things blunt it: Ghostscript ≥ 9.50 enables -dSAFER by default and ImageMagick invokes it that way. The residual risk is accepted deliberately, consistent with the local/trusted-network model the README already documents. Note that an ImageMagick built from source ships a permissive policy.xml, unlike Debian's package which disables the PS/PDF coders for exactly this reason — so nothing blocks these formats at the policy layer here. DOCUMENT_INPUT_EXTENSIONS is kept separate from IMAGE_EXTENSIONS to keep that distinction visible: those files are interpreted, not merely decoded.
  • Accepting SVG uploads hands arbitrary XML to a renderer, which is a smaller version of the same bargain as PDF/EPS above: an SVG can carry external entity declarations and can reference remote or local resources (<image href="file:///…"> or an http:// URL), so a crafted file is a potential XXE and server-side request vector. librsvg does not resolve external entities and does not fetch remote resources by default, which is most of the defence; the residual risk is accepted on the same local/trusted-network basis, and it is a reason not to drop back to the MSVG fallback, whose hardening is far less clear. .svg is deliberately absent from IMAGE_EXTENSIONS for the same reason DOCUMENT_INPUT_EXTENSIONS is: those files are interpreted, not merely decoded.
  • AVIF and HEIC are not supported by this build — libheif/libaom are not installed, so the delegates are not compiled in. They stay out of the hardcoded fallback list in get_available_formats(), which is the only path by which an unsupported format could reach the UI (the normal path filters against magick -list format). They remain in ALLOWED_OUTPUT_FORMATS harmlessly, since that set only rejects, never offers.
  • The text watermark needs a font package. The Dockerfile installs fonts-dejavu-core, and build_watermark_args() always emits -font from the WATERMARK_FONTS allowlist. Relying on ImageMagick's compiled-in default instead fails at runtime with "unable to read font" on an image that ships no fonts, which is the trap to avoid: the failure only appears when a caption is actually requested, long after the build passed. Adding a family to WATERMARK_FONTS without installing it reintroduces exactly that.
  • potrace must be installed for SVG/EPS/PDF/AI output. The Dockerfile installs it via apt-get install potrace. Without it, ImageMagick raises a delegate error.
  • Never pin the base image to $BUILDPLATFORM, and never pass TARGETARCH as an explicit build-args from CI. Both mistakes shipped together: the workflows passed TARGETARCH=${{ matrix.arch }} while defining no matrix, so the value was empty and the Dockerfile's arm64 branch never ran, while FROM --platform=$BUILDPLATFORM baked the runner's architecture into every image — meaning the published arm64 manifest entry carried amd64 binaries. Both architectures now build ImageMagick from source; Debian's imagemagick package is ImageMagick 6 and ships no magick binary, so an apt path was never viable for this app anyway.
  • Animated WEBP support depends on libwebpmux/libwebpdemux being linked into ImageMagick at build time — the Dockerfile installs libwebp-dev for this, but it's a build-time detection (via ./configure), not guaranteed. Always check via webp_animation_supported() / docker logs rather than assuming; the UI hides/disables the WEBP option server-side when unsupported.
  • Gunicorn MUST run with exactly one worker process (--workers 1 in start.sh) — jobs, upload_sessions, _processing_semaphore, executor, and _webp_anim_supported_cache are all plain in-process Python objects with no shared/external store. Multiple worker processes each get their own independent copy, so a request that lands on a different worker than an earlier one in the same flow (upload → options page → submit) won't see that earlier worker's state — this previously caused real, reproducible "No files selected" (upload_sessions) and would equally cause "Job not found" (jobs) failures under the --workers 4 config that shipped before this was diagnosed. Scale via --threads (in-process, shares memory) instead of --workers.
  • In-memory job state is lost on container restart — any in-flight batch jobs or GIF creation jobs are abandoned. This is acceptable for the current use case (local/trusted network).
  • upload_sessions dict grows indefinitely — sessions are never explicitly purged. Not a problem at typical self-hosted scale. (Unlike jobs, which is purged — see purge_old_jobs() / JOBS_TTL_HOURS.)
  • cleanup.py removes files from uploads/ and output/ older than 48 h. Batch output subdirectories (e.g. output/batch_20240101_120000/) and GIF frame-extraction temp directories are also cleaned (the latter are additionally removed immediately after zipping in /gif_edit, so cleanup.py is only a backstop for interrupted requests).
  • Gunicorn's --limit-request-line 8190 URL limit — batch and GIF-creation filenames must go through the server-side upload_sessions mechanism, not the query string.
  • GIF creation doesn't call prepare_input_file() — RAW/JXL frames are explicitly rejected (gif_create_options/gif_create) rather than silently mishandled, since ImageMagick would receive the raw/undecoded file directly.
  • The flask_error / flash_error function logs and renders result.html with success=False. Use it consistently for error returns instead of ad-hoc render_template calls.
  • A builder that refuses must say why, through refuse(). The command builders have ~27 refusal paths and their callers only ever see None, so every one of them used to surface as "Could not build ImageMagick command" while the real reason sat in the log. refuse(message) logs it, records it on a threading.local (batch runs 16 workers against these builders at once, so a module-level variable would let one worker read a sibling's reason) and returns None; callers then raise CommandRefused(last_refusal_reason()) or flash it. classify_processing_error() returns a CommandRefused message verbatim, which is safe precisely because we author these strings — never pass tool output through it, and never interpolate a path into a refusal message. When adding a refusal path, use refuse(); a bare return None is only correct as a pass-through of an inner builder that already recorded a reason.
  • Enlarging is bounded by MAX_DIMENSION, which rules it out for most modern photos (a 5142px source cannot be doubled under a 10000px cap). That is the feature working as intended, not a defect: enlarging is for small images. The failure must not be discovered after submitting, so upscale_field() receives the source dimensions on the single-image page, shows the size each factor would produce, and disables the ones that would be refused. The batch page cannot do this (sizes differ per image), so it says so and relies on the per-image refusal message instead.

Development notes

  • Python 3.11+ required. The floor is set by Pillow>=13.0.0 in requirements.txt, not by any language feature the app uses: every Pillow below 13 carries unpatched decoder CVEs, and Pillow 13 requires Python >= 3.11. The Dockerfile's base image and the audit job's container must move together — pip resolves a requirement to the newest version supporting the running Python, so a mismatched audit checks versions the image never installs
  • No test suite currently exists
  • Commit messages in English
  • Commit titles follow conventional commits format: type(scope): description
  • When modifying templates: always extend base.html, never duplicate :root or body styles
  • When modifying app.py: run through the security checklist above before committing