8000 feat: @jimp/server, an image transform handler for edge runtimes by hipstersmoothie · Pull Request #1560 · jimp-dev/jimp · GitHub
[go: up one dir, main page]

Skip to content

feat: @jimp/server, an image transform handler for edge runtimes - #1560

Merged
hipstersmoothie merged 7 commits into
mainfrom
feat/jimp-server
Nov 25, 2026
Merged

hipstersmoothie merged 7 commits into
mainfrom
feat/jimp-server

Conversation

@hipstersmoothie
Copy link
Copy Markdown
Collaborator

Adds @jimp/server, an on-the-fly image transform handler in the style of imgix, Thumbor and Next's /_next/image. It takes a web Request and returns a Response, so the same handler runs on Cloudflare Workers, Vercel Edge, Deno, Bun and Node. It runs on pure-JS Jimp (plus the optional wasm codecs), so it doesn't hit sharp's native-binary walls.

import { Jimp } from "jimp";
import { createImageHandler, fetchSource } from "@jimp/server";

const handler = createImageHandler({
  Jimp, // or a createJimp class with @jimp/wasm-webp / @jimp/wasm-avif
  source: fetchSource({ baseUrl: "https://assets.example.com/" }),
  basePath: "/images",
  secret: env.IMAGE_SECRET, // optional
});

export default { fetch: handler }; // /images/cats/tom.jpg?w=400&h=300&fm=auto

The base is #1558 (apply), so this diff only shows the server work. GitHub retargets it to main when #1558 merges.

What's in it

  • @jimp/server (packages/server). The handler turns URL params into a JimpEdit[] and calls image.apply. It exports createImageHandler, signUrl, encodeEdits, fetchSource, remoteSource, ImageHandlerError and defaultAllowedEdits.
  • @jimp/server/node (Node-only subpath). It has directorySource(root) and toNodeHandler(handler) for node:http and Express.
  • Plugin changes. These follow "extend the plugin rather than the server":
    • maxResolutionInMP decode option for @jimp/js-png, @jimp/wasm-png, @jimp/wasm-webp, @jimp/wasm-avif and @jimp/js-ico. Each reads the size from the file's header before the codec runs, the same way wasm-jxl already does.
      • It's off by default, so existing reads don't change in a minor release. With a limit set, WebP/AVIF files whose size can't be read are refused rather than decoded unchecked.
      • You may want a 100 MP default like the other formats in the next major.
    • quality (0–100) encode option for @jimp/wasm-avif, so q maps to the same option name for AVIF, JPEG, JPEG XL and WebP. It takes precedence over cqLevel.
  • apply is unchanged. The handler pre-checks edit names against the allowlist and the class, using an instance, since plugin methods are attached per instance. It maps Edit N (name) failed errors to 400.
  • Docs.
    • A new Image Server guide: deploying to Workers (R2 and wasm codecs), Vercel/Next, Deno, Bun, Node and Express, the param reference, sources, security, limits, caching, errors and options.
    • Updated Reading Large Images (the new limits) and the AVIF quality option in the WASM guide.

Design decisions

Params (imgix/Next-style short names):

Param Notes
w, h One side alone keeps the aspect ratio.
dpr 1–4. Multiplies w and h.
fit cover, contain, scale-to-fit or fill. Defaults to cover, like sharp.
pos A keyword like top-left, or x,y fractions as a focal point.
q 1–100, default 75. Ignored for PNG/GIF/BMP/TIFF.
fm auto/avif/webp/jpeg/jpg/png/gif/jxl/bmp/tiff. Defaults to the source's format.
bg Hex without #, or a CSS color. Used for the letterbox and for JPEG flattening. Without bg, transparency becomes white for JPEG.
blur 1–100.
sharpen 0–10.
greyscale No value needed.
rot 90/180/270, clockwise like Cloudflare. Jimp's rotate is counter-clockwise, so it's negated.
flip h, v or hv.
edits base64url JSON of a JimpEdit[], accepted on signed URLs only.
s The signature.
  • Unknown or duplicate params are a 400. This catches typos like width= and stops junk params from creating extra cache keys.
  • Edit order: edits, rot, flip, resize, blur, sharpen, greyscale. Effects run after shrinking, and crops in edits use the source's pixel coordinates.

fm=auto:

  • It picks AVIF, then WebP, then the source format if it's JPEG/PNG/GIF, otherwise PNG for images with transparency and JPEG for the rest.
  • It only picks formats the given Jimp class can encode, and only counts explicit Accept entries with q>0 (image/* and */* don't count). It sends Vary: Accept.
  • defaultFormat: "auto" negotiates even without fm.

Signing:

  • HMAC-SHA256 over the path plus params, using crypto.subtle and constant-time verify. Several secrets are accepted, for rotation.
  • signUrl sorts the params, and verification requires that exact query string with a single s. Each signed transform therefore has one URL, and can't be varied into new CDN cache keys.
  • The host isn't signed. requireSignature: false allows unsigned URLs but still requires a signature for edits.

Limits (defaults):

Option Default Notes
maxSize 4096 Applies to w, h, the derived side of a one-side resize (checked before resizing), and the edited image's longest side. That side may be the source's size if the source is larger.
maxEdits 10 Counts param-derived edits too.
maxSourceBytes 20 MB
maxSourceResolutionInMP 25 Passed as maxResolutionInMP to every format that has it. Over the limit is a 413, before any pixels are allocated.
allowedEdits defaultAllowedEdits Resize, crop, rotate, color and blur methods. Excludes methods that need images or fonts, and convolute.

Caching:

  • Cache-Control: public, max-age=86400, stale-while-revalidate=604800, configurable.
  • A strong ETag computed from SHA-256 of the source bytes, the canonical query, the formats fm=auto could pick, and the output-affecting config.
  • If-None-Match gets a 304 without decoding. * isn't matched, because the ETag is computed before the edits run.

Statuses:

Status When
400 Bad param (with the validation message), disallowed or failing edit, invalid path
403 Bad or missing signature, or a host that isn't allowed
404 Missing source, or a path outside basePath
405 Method other than GET/HEAD
413 Source over the byte or resolution limits
415 The class can't decode the source or encode fm
422 Output limits, too many edits, or an undecodable source
500 Generic body, details go to onError
502/504 Origin errors and timeouts

SSRF and traversal:

  • ./../empty segments, backslashes, NUL and encoded / are rejected before the source runs.
  • fetchSource URL-encodes each segment and only follows redirects that stay under baseUrl.
  • remoteSource is opt-in with an allowedHosts allowlist (with *. wildcards), is https-only, and re-checks every redirect.
  • directorySource uses realpath containment, so symlinks out of the root are a 404.

Testing

  • Handler tests (141, vitest, driven by Request objects):
    • param mapping, checked by pixel colors for cover/pos/contain/rot/flip/greyscale/blur
    • negotiation, including AVIF/WebP through the real wasm codecs
    • signing, including forged and varied URLs and key rotation
    • limits, ETag/304, error statuses, and traversal attempts
  • Sources: fetchSource and remoteSource against a mocked fetch (redirects, size, timeout, host matching).
  • Node: directorySource with symlinks, and toNodeHandler through a real node:http server, including the Express originalUrl case.
  • Plugins: tests for each new decode limit, the WebP VP8/VP8L/VP8X header reader, AVIF ispe, and AVIF quality.
  • Runtimes:
    • Smoke-tested the built package on Node 24, Bun and Deno.
    • Bundled a worker entry with esbuild using wrangler's workerd,worker,browser conditions. It has no node: imports, and I ran that bundle in Deno. I didn't run it in real workerd.
  • Checks:
    • pnpm install --frozen-lockfile, pnpm build, pnpm lint, pnpm test (87/87 tasks) and the docs build all pass.
  • Review: an independent review pass found a one-side-resize memory blowup, a WebP header-check bypass, ICO skipping the limit, and signed-URL cache-key variance. All are fixed with regression tests.

Left out

  • Animated output: GIF/APNG sources are read as their first frame.
  • Enlargement: there's no withoutEnlargement/scale-down fit. Images can be scaled up to maxSize.
  • Built-in caching: there's no result cache or concurrency limit. The guide recommends a CDN or the Workers Cache API in front.
  • Accept wildcards: image/* and */* don't count for negotiation, as described above.
  • @jimp/wasm-jpeg: it still has no resolution limit; only maxSourceBytes protects it. Adding one would mean parsing SOF markers.
  • AVIF limits: they rely on ispe, so with a limit set, AVIFs without one are refused.
  • remoteSource and DNS: there's no private-IP or DNS-rebinding check. It trusts the DNS of the allowlisted hosts.
  • ETags across upgrades: the ETag doesn't include package versions, so an upgrade that changes the encoded bytes keeps the old ETags until the source or the config changes.
  • Workers runtime: not run in real workerd, as noted above.
  • Publishing: not published to npm.

🤖 Generated with Claude Code

hipstersmoothie and others added 6 commits November 24, 2026 15:44
image.apply([["resize", { w: 100 }], ["greyscale"]]) runs plugin methods
from a list of [name, ...args] tuples, so edits can be stored as JSON, sent
to a server or worker, and applied later. Names are checked before any edit
runs; only plugin methods that return the image are allowed. JimpEdit types
each edit from the image type, so the declaration stays one line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
js-png, wasm-png, wasm-webp and wasm-avif take a maxResolutionInMP decode
option, read from the file's header so oversized images are rejected before
the codec allocates pixels. It's off by default, so existing reads don't
change. wasm-avif's encode takes quality (0-100) like the JPEG and WebP
formats, which takes precedence over cqLevel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
createImageHandler({ Jimp, source }) returns a (Request) => Response
handler that turns URL params (w, h, fit, pos, q, fm, blur, rot, ...) into
edits for image.apply. fm=auto negotiates AVIF/WebP from Accept, URLs can be
HMAC-signed with Web Crypto, and it sends strong ETags and 304s. Sources:
fetchSource for one origin, remoteSource for allowlisted hosts, and
directorySource plus a node:http/Express adapter in @jimp/server/node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
js-ico checks the chosen image's own header against maxResolutionInMP, so
an oversized PNG or BMP inside an ICO is rejected before decoding. With a
limit set, WebP and AVIF files whose size can't be read from the header
(a bare VP8L bitstream, an AVIF without ispe) are refused instead of
decoded unchecked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- With only w or h, check the side that follows the aspect ratio before
  resizing, so a tall source can't use far more memory than maxSize allows
- signUrl sorts the params and verification needs that exact query with one
  s, so a signed transform can't be varied into new CDN cache keys
- Limit ICO decoding, don't 304 on If-None-Match: *, include the formats
  in the ETag's config key, reject __proto__ as an unknown param
- toNodeHandler skips HTTP/2 pseudo-headers and answers TRACE etc. with 405;
  directorySource works with a filesystem root

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds an Image Server guide for @jimp/server (deploying to Workers, Vercel,
Deno, Bun and Node, the URL params, sources, signing, limits, caching and
errors), and documents maxResolutionInMP for PNG, ICO, WebP and AVIF and
AVIF's quality option.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@hipstersmoothie hipstersmoothie added the minor Increment the minor version when merged label Nov 25, 2026
…ce test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Base automatically changed from feat/apply-edits to main November 25, 2026 01:02
@hipstersmoothie
hipstersmoothie merged commit 2e173f7 into main Nov 25, 2026
7 checks passed
@hipstersmoothie
hipstersmoothie deleted the feat/jimp-server branch November 25, 2026 01:40
@hipstersmoothie
Copy link
Copy Markdown
Collaborator Author

🚀 PR was released in v2.2.0 🚀

@hipstersmoothie hipstersmoothie added the released This issue/pull request has been released. label Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor Increment the minor version when merged released This issue/pull request has been released.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

0