Repository navigation
feat: @jimp/server, an image transform handler for edge runtimes - #1560
Merged
Merged
Conversation
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>
…ce test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Collaborator
Author
|
🚀 PR was released in |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adds
@jimp/server, an on-the-fly image transform handler in the style of imgix, Thumbor and Next's/_next/image. It takes a webRequestand returns aResponse, 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.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 aJimpEdit[]and callsimage.apply. It exportscreateImageHandler,signUrl,encodeEdits,fetchSource,remoteSource,ImageHandlerErroranddefaultAllowedEdits.@jimp/server/node(Node-only subpath). It hasdirectorySource(root)andtoNodeHandler(handler)fornode:httpand Express.maxResolutionInMPdecode option for@jimp/js-png,@jimp/wasm-png,@jimp/wasm-webp,@jimp/wasm-avifand@jimp/js-ico. Each reads the size from the file's header before the codec runs, the same waywasm-jxlalready does.quality(0–100) encode option for@jimp/wasm-avif, soqmaps to the same option name for AVIF, JPEG, JPEG XL and WebP. It takes precedence overcqLevel.applyis unchanged. The handler pre-checks edit names against the allowlist and the class, using an instance, since plugin methods are attached per instance. It mapsEdit N (name) failederrors to 400.qualityoption in the WASM guide.Design decisions
Params (imgix/Next-style short names):
w,hdprwandh.fitcover,contain,scale-to-fitorfill. Defaults tocover, like sharp.postop-left, orx,yfractions as a focal point.qfmauto/avif/webp/jpeg/jpg/png/gif/jxl/bmp/tiff. Defaults to the source's format.bg#, or a CSS color. Used for the letterbox and for JPEG flattening. Withoutbg, transparency becomes white for JPEG.blursharpengreyscalerotrotateis counter-clockwise, so it's negated.fliph,vorhv.editsJimpEdit[], accepted on signed URLs only.swidth=and stops junk params from creating extra cache keys.edits,rot,flip, resize,blur,sharpen,greyscale. Effects run after shrinking, and crops ineditsuse the source's pixel coordinates.fm=auto:Acceptentries with q>0 (image/*and*/*don't count). It sendsVary: Accept.defaultFormat: "auto"negotiates even withoutfm.Signing:
crypto.subtleand constant-timeverify. Several secrets are accepted, for rotation.signUrlsorts the params, and verification requires that exact query string with a singles. Each signed transform therefore has one URL, and can't be varied into new CDN cache keys.requireSignature: falseallows unsigned URLs but still requires a signature foredits.Limits (defaults):
maxSizew,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.maxEditsmaxSourceBytesmaxSourceResolutionInMPmaxResolutionInMPto every format that has it. Over the limit is a 413, before any pixels are allocated.allowedEditsdefaultAllowedEditsconvolute.Caching:
Cache-Control: public, max-age=86400, stale-while-revalidate=604800, configurable.fm=autocould pick, and the output-affecting config.If-None-Matchgets a 304 without decoding.*isn't matched, because the ETag is computed before the edits run.Statuses:
basePathfmonErrorSSRF and traversal:
./../empty segments, backslashes, NUL and encoded/are rejected before the source runs.fetchSourceURL-encodes each segment and only follows redirects that stay underbaseUrl.remoteSourceis opt-in with anallowedHostsallowlist (with*.wildcards), is https-only, and re-checks every redirect.directorySourceusesrealpathcontainment, so symlinks out of the root are a 404.Testing
Requestobjects):fetchSourceandremoteSourceagainst a mockedfetch(redirects, size, timeout, host matching).directorySourcewith symlinks, andtoNodeHandlerthrough a realnode:httpserver, including the ExpressoriginalUrlcase.ispe, and AVIFquality.workerd,worker,browserconditions. It has nonode:imports, and I ran that bundle in Deno. I didn't run it in real workerd.pnpm install --frozen-lockfile,pnpm build,pnpm lint,pnpm test(87/87 tasks) and the docs build all pass.Left out
withoutEnlargement/scale-downfit. Images can be scaled up tomaxSize.image/*and*/*don't count for negotiation, as described above.@jimp/wasm-jpeg: it still has no resolution limit; onlymaxSourceBytesprotects it. Adding one would mean parsing SOF markers.ispe, so with a limit set, AVIFs without one are refused.remoteSourceand DNS: there's no private-IP or DNS-rebinding check. It trusts the DNS of the allowlisted hosts.🤖 Generated with Claude Code