Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 2 additions & 8 deletions packages/asset-server-plugin/src/asset-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import fs from 'fs-extra';
import mime from 'mime-types';
import path from 'path';

import { getValidBackgroundColor, getValidFormat } from './common';
import { getValidFormat } from './common';
import { ImageTransformParameters, ImageTransformStrategy } from './config/image-transform-strategy';
import { S3AssetStorageStrategy } from './config/s3-asset-storage-strategy';
import { ASSET_SERVER_PLUGIN_INIT_OPTIONS, DEFAULT_CACHE_HEADER, loggerCtx } from './constants';
Expand Down Expand Up @@ -199,7 +199,6 @@ export class AssetServer {
const fpx = +queryParams.fpx || undefined;
const fpy = +queryParams.fpy || undefined;
const format = getValidFormat(queryParams.format);
const backgroundColor = getValidBackgroundColor(queryParams.bg);

return {
width,
Expand All @@ -210,16 +209,14 @@ export class AssetServer {
fpx,
fpy,
preset: queryParams.preset,
backgroundColor,
};
}

private getFileNameFromParameters(filePath: string, params: ImageTransformParameters): string {
const { width: w, height: h, mode, preset, fpx, fpy, format, quality: q, backgroundColor } = params;
const { width: w, height: h, mode, preset, fpx, fpy, format, quality: q } = params;
/* eslint-disable @typescript-eslint/restrict-template-expressions */
const focalPoint = fpx && fpy ? `_fpx${fpx}_fpy${fpy}` : '';
const quality = q ? `_q${q}` : '';
const bg = backgroundColor ? `_bg${backgroundColor.replace('#', '')}` : '';
const imageFormat = getValidFormat(format);
let imageParamsString = '';
if (w || h) {
Expand All @@ -241,9 +238,6 @@ export class AssetServer {
if (quality) {
imageParamsString += quality;
}
if (bg) {
imageParamsString += bg;
}

const decodedReqPath = this.sanitizeFilePath(filePath);
if (imageParamsString !== '') {
Expand Down
16 changes: 0 additions & 16 deletions packages/asset-server-plugin/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,3 @@ export function getValidFormat(format?: unknown): ImageTransformFormat | undefin
return undefined;
}
}

/**
* Validates and normalizes a background color hex string.
* Accepts 3, 4, 6, or 8 character hex strings (with or without `#` prefix).
* Returns the normalized hex string with `#` prefix, or `undefined` if invalid.
*/
export function getValidBackgroundColor(input?: unknown): string | undefined {
if (typeof input !== 'string' || input.length === 0) {
return undefined;
}
const hex = input.startsWith('#') ? input.slice(1) : input;
if (/^[0-9a-fA-F]{3,4}$|^[0-9a-fA-F]{6}$|^[0-9a-fA-F]{8}$/.test(hex)) {
return `#${hex.toLowerCase()}`;
}
return undefined;
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,6 @@ export interface ImageTransformParameters {
fpx: number | undefined;
fpy: number | undefined;
preset: string | undefined;
/**
* @description
* A hex color string (e.g. `'#ffffff'`) to be used as the background color
* for images with alpha transparency. The alpha channel will be merged with
* this color using Sharp's `flatten()` method.
*
* @since 3.8.0
*/
backgroundColor: string | undefined;
}

/**
Expand Down
36 changes: 1 addition & 35 deletions packages/asset-server-plugin/src/config/preset-only-strategy.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HexColorString, ImageTransformFormat } from '../types';
import { ImageTransformFormat } from '../types';

import {
GetImageTransformParametersArgs,
Expand Down Expand Up @@ -42,22 +42,6 @@ export interface PresetOnlyStrategyOptions {
* @default false
*/
allowFocalPoint?: boolean;
/**
* @description
* Whether to allow the background color to be specified in the URL.
* If omitted (default), the `bg` parameter is dropped.
* If set to an array of hex color strings (e.g. `['#ffffff', '#000000']`),
* only those colors are permitted — keeping the cache key space bounded.
* If set to `'any'`, any valid hex color is accepted (explicit opt-in to an
* unbounded cache surface).
*
* Comparison is case-insensitive, so `'#FFFFFF'` and `'#ffffff'` are
* treated as the same entry.
*
* @default undefined
* @since 3.8.0
*/
permittedBackgroundColors?: HexColorString[] | 'any';
}

/**
Expand Down Expand Up @@ -89,7 +73,6 @@ export interface PresetOnlyStrategyOptions {
* permittedQuality: [0, 50, 75, 85, 95],
* permittedFormats: ['jpg', 'webp', 'avif'],
* allowFocalPoint: true,
* permittedBackgroundColors: ['#ffffff', '#000000'],
* }),
* });
* ```
Expand Down Expand Up @@ -124,23 +107,6 @@ export class PresetOnlyStrategy implements ImageTransformStrategy {
fpx: this.options.allowFocalPoint ? input.fpx : undefined,
fpy: this.options.allowFocalPoint ? input.fpy : undefined,
preset: input.preset,
backgroundColor: this.getPermittedBackgroundColor(input.backgroundColor),
};
}

private getPermittedBackgroundColor(input: string | undefined): string | undefined {
if (!input) {
return undefined;
}
const permitted = this.options.permittedBackgroundColors;
if (!permitted) {
return undefined;
}
if (permitted === 'any') {
return input;
}
const normalise = (c: string) => c.toLowerCase();
const normalised = normalise(input);
return permitted.some(c => normalise(c) === normalised) ? input : undefined;
}
}
191 changes: 1 addition & 190 deletions packages/asset-server-plugin/src/transform-image.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import sharp from 'sharp';
import { describe, expect, it } from 'vitest';

import { getValidBackgroundColor } from './common';
import { PresetOnlyStrategy } from './config/preset-only-strategy';
import { Dimensions, Point, resizeToFocalPoint, transformImage } from './transform-image';
import { Dimensions, Point, resizeToFocalPoint } from './transform-image';

describe('resizeToFocalPoint', () => {
it('no resize, crop left', () => {
Expand Down Expand Up @@ -70,189 +67,3 @@ describe('resizeToFocalPoint', () => {
});
});
});

describe('getValidBackgroundColor', () => {
it('accepts 6-char hex without #', () => {
expect(getValidBackgroundColor('ffffff')).toBe('#ffffff');
});

it('accepts 6-char hex with #', () => {
expect(getValidBackgroundColor('#F0A703')).toBe('#f0a703');
});

it('accepts 3-char shorthand hex', () => {
expect(getValidBackgroundColor('fff')).toBe('#fff');
});

it('accepts 8-char hex with alpha', () => {
expect(getValidBackgroundColor('ffffff80')).toBe('#ffffff80');
});

it('accepts 4-char shorthand hex with alpha', () => {
expect(getValidBackgroundColor('fff8')).toBe('#fff8');
});

it('returns undefined for empty string', () => {
expect(getValidBackgroundColor('')).toBeUndefined();
});

it('returns undefined for non-string input', () => {
expect(getValidBackgroundColor(undefined)).toBeUndefined();
expect(getValidBackgroundColor(123)).toBeUndefined();
expect(getValidBackgroundColor(null)).toBeUndefined();
});

it('returns undefined for invalid hex characters', () => {
expect(getValidBackgroundColor('gggggg')).toBeUndefined();
expect(getValidBackgroundColor('xyz')).toBeUndefined();
});

it('returns undefined for wrong length hex', () => {
expect(getValidBackgroundColor('ff')).toBeUndefined();
expect(getValidBackgroundColor('fffff')).toBeUndefined();
expect(getValidBackgroundColor('fffffffff')).toBeUndefined();
});
});

describe('transformImage with backgroundColor', () => {
function createTestPngWithAlpha(width: number, height: number): Promise<Buffer> {
return sharp({
create: {
width,
height,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 0.5 },
},
})
.png()
.toBuffer();
}

it('flattens alpha channel with specified background color', async () => {
const input = await createTestPngWithAlpha(10, 10);
const result = await transformImage(input, {
width: 10,
height: 10,
mode: 'resize',
quality: undefined,
format: 'png',
fpx: undefined,
fpy: undefined,
preset: undefined,
backgroundColor: '#ffffff',
});
const buffer = await result.toBuffer();
const { channels, hasAlpha } = await sharp(buffer).metadata();
expect(channels).toBe(3);
expect(hasAlpha).toBe(false);
});

it('preserves alpha channel when no backgroundColor is set', async () => {
const input = await createTestPngWithAlpha(10, 10);
const result = await transformImage(input, {
width: 10,
height: 10,
mode: 'resize',
quality: undefined,
format: 'png',
fpx: undefined,
fpy: undefined,
preset: undefined,
backgroundColor: undefined,
});
const buffer = await result.toBuffer();
const { channels, hasAlpha } = await sharp(buffer).metadata();
expect(channels).toBe(4);
expect(hasAlpha).toBe(true);
});
});

describe('PresetOnlyStrategy permittedBackgroundColors', () => {
const presets = [{ name: 'thumb', width: 100, height: 100, mode: 'crop' as const }];
const baseInput = {
width: undefined,
height: undefined,
mode: undefined,
quality: undefined,
format: undefined,
fpx: undefined,
fpy: undefined,
preset: 'thumb',
backgroundColor: '#ffffff',
};

it('drops backgroundColor when permittedBackgroundColors is omitted', () => {
const strategy = new PresetOnlyStrategy({ defaultPreset: 'thumb' });
const result = strategy.getImageTransformParameters({
input: baseInput,
availablePresets: presets,
req: {} as any,
});
expect(result.backgroundColor).toBeUndefined();
});

it('allows any backgroundColor when set to "any"', () => {
const strategy = new PresetOnlyStrategy({
defaultPreset: 'thumb',
permittedBackgroundColors: 'any',
});
const result = strategy.getImageTransformParameters({
input: baseInput,
availablePresets: presets,
req: {} as any,
});
expect(result.backgroundColor).toBe('#ffffff');
});

it('allows a whitelisted backgroundColor', () => {
const strategy = new PresetOnlyStrategy({
defaultPreset: 'thumb',
permittedBackgroundColors: ['#ffffff', '#000000'],
});
const result = strategy.getImageTransformParameters({
input: baseInput,
availablePresets: presets,
req: {} as any,
});
expect(result.backgroundColor).toBe('#ffffff');
});

it('drops a non-whitelisted backgroundColor', () => {
const strategy = new PresetOnlyStrategy({
defaultPreset: 'thumb',
permittedBackgroundColors: ['#000000'],
});
const result = strategy.getImageTransformParameters({
input: baseInput,
availablePresets: presets,
req: {} as any,
});
expect(result.backgroundColor).toBeUndefined();
});

it('whitelist comparison is case-insensitive', () => {
const strategy = new PresetOnlyStrategy({
defaultPreset: 'thumb',
permittedBackgroundColors: ['#FFFFFF'],
});
const result = strategy.getImageTransformParameters({
input: { ...baseInput, backgroundColor: '#ffffff' },
availablePresets: presets,
req: {} as any,
});
expect(result.backgroundColor).toBe('#ffffff');
});

it('whitelist comparison is case-insensitive with # prefix', () => {
const strategy = new PresetOnlyStrategy({
defaultPreset: 'thumb',
permittedBackgroundColors: ['#ffffff'],
});
const result = strategy.getImageTransformParameters({
input: { ...baseInput, backgroundColor: '#ffffff' },
availablePresets: presets,
req: {} as any,
});
expect(result.backgroundColor).toBe('#ffffff');
});
});
6 changes: 0 additions & 6 deletions packages/asset-server-plugin/src/transform-image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,6 @@ export async function transformImage(
}

const image = sharp(originalImage).rotate();

// Merge alpha transparency channel with the specified background color
if (parameters.backgroundColor) {
image.flatten({ background: parameters.backgroundColor });
}

try {
await applyFormat(image, parameters.format, parameters.quality);
} catch (e: any) {
Expand Down
14 changes: 0 additions & 14 deletions packages/asset-server-plugin/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,6 @@ import { ImageTransformStrategy } from './config/image-transform-strategy';

export type ImageTransformFormat = 'jpg' | 'jpeg' | 'png' | 'webp' | 'avif';

/**
* @description
* A `#`-prefixed hex color string, e.g. `'#ffffff'` or `'#000'`.
* Full hex-char validation at the type level is not feasible because
* TypeScript's template literal unions exceed compiler limits for
* 6- and 8-char hex strings. The `#` prefix is enforced at compile time;
* hex-character and length validation is handled at runtime by
* `getValidBackgroundColor()`.
*
* @docsCategory core plugins/AssetServerPlugin
* @since 3.8.0
*/
export type HexColorString = `#${string}`;

/**
* @description
* Specifies the way in which an asset preview image will be resized to fit in the
Expand Down
Loading