@@ -23,12 +23,15 @@ import type { ReadonlyRecord } from "../../Record.ts"
2323import { TracerEnabled } from "../../References.ts"
2424import { ParentSpan } from "../../Tracer.ts"
2525import * as Headers from "./Headers.ts"
26+ import type { CompressionAlgorithm } from "./HttpPlatform.ts"
27+ import { HttpPlatform } from "./HttpPlatform.ts"
2628import { causeResponseStripped } from "./HttpServerError.ts"
2729import { HttpServerRequest } from "./HttpServerRequest.ts"
2830import * as Request from "./HttpServerRequest.ts"
2931import * as Response from "./HttpServerResponse.ts"
3032import type { HttpServerResponse } from "./HttpServerResponse.ts"
3133import * as TraceContext from "./HttpTraceContext.ts"
34+ import * as compressionInternal from "./internal/compression.ts"
3235import { appendPreResponseHandlerUnsafe } from "./internal/preResponseHandler.ts"
3336
3437/**
@@ -403,3 +406,161 @@ export const cors = (options?: {
403406 return httpApp
404407 } )
405408}
409+
410+ /**
411+ * Middleware that compresses HTTP response bodies based on the request's
412+ * `Accept-Encoding` header.
413+ *
414+ * **Details**
415+ *
416+ * Content negotiation follows RFC 9110: the first algorithm in server
417+ * preference order that the client accepts with a positive q-value and the
418+ * platform supports is used. When no algorithm is acceptable the response is
419+ * sent uncompressed.
420+ *
421+ * The body transform is performed by the `HttpPlatform` service.
422+ *
423+ * Responses are skipped when the status is 1xx, 204, 206, or 304, when a
424+ * `Content-Encoding` is already present, when `Cache-Control: no-transform`
425+ * is set, when the content type is absent or not compressible, when a known
426+ * body length is below `minSize`, or when the body is empty or `FormData`. A
427+ * response carrying `Content-Encoding: identity` opts out of compression and
428+ * has the header stripped before sending.
429+ *
430+ * `Vary: Accept-Encoding` is set on every response that was eligible by
431+ * status and content type, including ones skipped by negotiation or
432+ * `minSize`.
433+ *
434+ * Do not combine this middleware with Deno's automatic response compression.
435+ * On edge runtimes that already apply automatic compression, the middleware
436+ * is unnecessary. Platforms backed by Web `CompressionStream` also cannot
437+ * explicitly flush each input chunk, so incremental delivery depends on the
438+ * runtime's implementation.
439+ *
440+ * **Security**
441+ *
442+ * Compression can expose secrets through BREACH-style attacks when one
443+ * response contains both secret data and attacker-controlled input and an
444+ * attacker can observe the compressed response length. For affected routes,
445+ * disable compression with `Content-Encoding: identity` or
446+ * `Cache-Control: no-transform`, or use `compressible` to restrict which
447+ * response content types can be compressed.
448+ *
449+ * @category compression
450+ * @since 4.0.0
451+ */
452+ export const compression = (
453+ options ?: {
454+ /**
455+ * Server preference order. Negotiation picks the first accepted algorithm
456+ * supported by the platform. Defaults to `["br", "gzip", "deflate"]`;
457+ * `zstd` must be explicitly opted into.
458+ */
459+ readonly algorithms ?: ReadonlyArray < CompressionAlgorithm > | undefined
460+ /**
461+ * Minimum body size in bytes when the length is known. Unknown-length bodies
462+ * are always compressed. Defaults to `1024`.
463+ */
464+ readonly minSize ?: number | undefined
465+ /** Replaces the default content-type predicate. */
466+ readonly compressible ?: ( ( contentType : string ) => boolean ) | undefined
467+ /** Per-algorithm levels. Platforms without a level knob ignore them. */
468+ readonly levels ?: {
469+ readonly gzip ?: number | undefined
470+ readonly deflate ?: number | undefined
471+ readonly br ?: number | undefined
472+ readonly zstd ?: number | undefined
473+ } | undefined
474+ } | undefined
475+ ) : < E , R > (
476+ httpApp : Effect . Effect < HttpServerResponse , E , R >
477+ ) => Effect . Effect < HttpServerResponse , E , R | HttpServerRequest | HttpPlatform > => {
478+ const preferred = options ?. algorithms ?? defaultAlgorithms
479+ const minSize = options ?. minSize ?? 1024
480+ const compressible = options ?. compressible ?? compressionInternal . defaultCompressible
481+ const levels = { ...defaultLevels , ...options ?. levels }
482+ const levelOptions : Record < CompressionAlgorithm , { readonly level : number | undefined } > = {
483+ gzip : { level : levels . gzip } ,
484+ deflate : { level : levels . deflate } ,
485+ br : { level : levels . br } ,
486+ zstd : { level : levels . zstd }
487+ }
488+ const transform = (
489+ compression : HttpPlatform [ "Service" ] [ "compression" ] ,
490+ acceptEncoding : string | undefined ,
491+ response : HttpServerResponse
492+ ) : Effect . Effect < HttpServerResponse > => {
493+ if (
494+ response . status < 200 ||
495+ response . status === 204 ||
496+ response . status === 206 ||
497+ response . status === 304
498+ ) {
499+ return Effect . succeed ( response )
500+ }
501+ const currentEncoding = response . headers [ "content-encoding" ]
502+ if ( currentEncoding !== undefined ) {
503+ return Effect . succeed (
504+ currentEncoding . trim ( ) . toLowerCase ( ) === "identity"
505+ ? Response . removeHeader ( response , "content-encoding" )
506+ : response
507+ )
508+ }
509+ const body = response . body
510+ if ( body . _tag === "Empty" || body . _tag === "FormData" ) {
511+ return Effect . succeed ( response )
512+ }
513+ const cacheControl = response . headers [ "cache-control" ]
514+ if ( cacheControl !== undefined && noTransformRegex . test ( cacheControl ) ) {
515+ return Effect . succeed ( response )
516+ }
517+ const contentType = response . headers [ "content-type" ] ?? body . contentType
518+ if ( contentType === undefined || ! compressible ( contentType ) ) {
519+ return Effect . succeed ( response )
520+ }
521+ const algorithm = compressionInternal . negotiate ( acceptEncoding , preferred , compression . algorithms )
522+ if ( algorithm === undefined ) {
523+ return Effect . succeed ( withVary ( response ) )
524+ }
525+ const contentLength = body . contentLength ?? contentLengthHeader ( response . headers )
526+ if ( contentLength !== undefined && contentLength < minSize ) {
527+ return Effect . succeed ( withVary ( response ) )
528+ }
529+ return compression . compressResponse ( response , algorithm , levelOptions [ algorithm ] )
530+ }
531+ return < E , R > (
532+ httpApp : Effect . Effect < HttpServerResponse , E , R >
533+ ) : Effect . Effect < HttpServerResponse , E , R | HttpServerRequest | HttpPlatform > =>
534+ Effect . withFiber ( ( fiber ) => {
535+ const request = Context . getUnsafe ( fiber . context , HttpServerRequest )
536+ const compression = Context . getUnsafe ( fiber . context , HttpPlatform ) . compression
537+ appendPreResponseHandlerUnsafe ( request , ( request , response ) =>
538+ transform ( compression , request . headers [ "accept-encoding" ] , response ) )
539+ return httpApp
540+ } )
541+ }
542+
543+ const withVary = ( response : HttpServerResponse ) : HttpServerResponse => {
544+ const vary = compressionInternal . varyAcceptEncoding ( response . headers )
545+ return vary === undefined ? response : Response . setHeader ( response , "vary" , vary )
546+ }
547+
548+ const defaultAlgorithms : ReadonlyArray < CompressionAlgorithm > = [ "br" , "gzip" , "deflate" ]
549+
550+ const defaultLevels = {
551+ gzip : 6 ,
552+ deflate : 6 ,
553+ br : 4 ,
554+ zstd : 3
555+ } as const
556+
557+ const noTransformRegex = / (?: ^ | [ \s , ] ) n o - t r a n s f o r m (?: $ | [ \s , ; ] ) / i
558+
559+ const contentLengthHeader = ( headers : Headers . Headers ) : number | undefined => {
560+ const value = headers [ "content-length" ]
561+ if ( value === undefined ) {
562+ return undefined
563+ }
564+ const parsed = Number ( value )
565+ return Number . isFinite ( parsed ) && parsed >= 0 ? parsed : undefined
566+ }
0 commit comments