import { CheckboxField } from '@components/common/form/CheckboxField.js';
import { InputField } from '@components/common/form/InputField.js';
import { RadioGroupField } from '@components/common/form/RadioGroupField.js';
import { TextareaField } from '@components/common/form/TextareaField.js';
import { ToggleField } from '@components/common/form/ToggleField.js';
import {
Alert,
AlertDescription,
AlertTitle
} from '@components/common/ui/Alert.js';
import { Button } from '@components/common/ui/Button.js';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle
} from '@components/common/ui/Card.js';
import { _ } from '@evershop/evershop/lib/locale/translate/_';
import { Plus, Trash2, TriangleAlert } from 'lucide-react';
import React from 'react';
import { useFieldArray, useFormContext, useWatch } from 'react-hook-form';
interface OverrideRow {
type: string;
maxSize: number | string;
}
interface MimeTypeOption {
value: string;
label: string;
}
interface FileStorageSettingProps {
setting: {
fileStorage: string;
s3Region?: string;
s3Bucket?: string;
s3AccessKeyId?: string;
s3SecretAccessKey?: string;
s3Endpoint?: string;
s3ForcePathStyle: boolean;
s3BaseUrl?: string;
azureStorageConnectionString?: string;
azureStorageContainerName: string;
azureContainerAccess: string;
azureBaseUrl?: string;
gcsBucket?: string;
gcsServiceAccountKey?: string;
gcsBaseUrl?: string;
fileStorageConfigOverrides: string[];
uploadMaxFileSize?: number | null;
uploadMaxFileSizePinned: boolean;
uploadMaxFileSizePerType: OverrideRow[];
uploadMaxFileSizePerTypePinned: boolean;
uploadAllowedMimeTypes: string[];
uploadMimeTypeOptions: MimeTypeOption[];
uploadAllowedMimeTypesConfigExtras: string[];
};
}
/** The built-in defaults, pre-checked when the admin has not saved a selection */
const DEFAULT_TYPE_SELECTION = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/avif',
'image/apng'
];
/** `type/subtype` or a family wildcard `type/*` */
const MIME_PATTERN = /^[a-z0-9.+-]+\/(\*|[a-z0-9.+-]+)$/i;
function PerTypeOverrides({ initial }: { initial: OverrideRow[] }) {
const { control } = useFormContext();
const { fields, append, remove } = useFieldArray({
control,
name: 'uploadMaxFileSizePerType'
});
// Seed once from the saved rows. useFieldArray starts empty because the
// page-level form has no defaultValues for this key.
const seeded = React.useRef(false);
React.useEffect(() => {
if (!seeded.current && fields.length === 0 && initial.length > 0) {
initial.forEach((row) => append(row, { shouldFocus: false }));
}
seeded.current = true;
}, []);
return (
{fields.length === 0 && (
// The page form unregisters unmounted fields, so an empty list would
// vanish from the save payload and the previously saved overrides
// would silently survive. This marker posts an explicit "no
// overrides" value instead; it unmounts as soon as a row exists.
)}
{fields.map((field, index) => (
MIME_PATTERN.test(String(value).trim()) ||
_('Use type/subtype (video/mp4) or a family (video/*)')
}}
/>
Number(value) > 0 || _('Enter a size greater than zero')
}}
/>
))}
);
}
/** Loose client-side shape check for a pasted service-account key file */
const looksLikeServiceAccountKey = (value: string): boolean => {
try {
const parsed = JSON.parse(value);
return Boolean(parsed?.client_email && parsed?.private_key);
} catch {
return false;
}
};
/**
* Visible hint below a control. The Field components' `helperText` prop
* renders as a tooltip on the field LABEL — these rows carry their label in
* the left column instead, so a tooltip would never show.
*/
export function FieldHint({ children }: { children: React.ReactNode }) {
return
{children}
;
}
export function SettingRow({
label,
children
}: {
label: string;
children: React.ReactNode;
}) {
return (
{label}
{children}
);
}
/**
* Values pinned by config file / environment variable are shown read-only and
* OUTSIDE the form — a disabled-but-registered input would still post its
* (possibly masked) value to saveSetting and overwrite the DB row with
* garbage.
*/
export function PinnedValue({ value }: { value?: string | null }) {
return (
{value || '—'}
{_('Managed by configuration (config file or environment variable)')}
);
}
export default function FileStorageSetting({
setting
}: FileStorageSettingProps) {
const provider = useWatch({
name: 'fileStorage',
defaultValue: setting.fileStorage
});
const pinned = (name: string) =>
setting.fileStorageConfigOverrides.includes(name);
return (
{_('File Storage & Uploads')}
{_(
'Where uploaded files (product images, banners, media) are stored, which types are allowed, and how big they can be'
)}
{_('Provider')}
{provider === 's3' && (
<>
{pinned('s3Bucket') ? (
) : (
)}
{pinned('s3Region') ? (
) : (
<>
{_(
'For S3-compatible services use the provider value (e.g. fsn1 for Hetzner)'
)}
>
)}
{pinned('s3AccessKeyId') ? (
) : (
<>
{_(
'Create an access key in your storage provider console. For AWS: sign in to the AWS Console, open IAM → Users → your user → Security credentials → Create access key.'
)}
>
)}
{pinned('s3SecretAccessKey') ? (
) : (
<>
{_(
'The secret is shown only once, when the access key is created — copy it from there.'
)}
>
)}
{!pinned('s3AccessKeyId') && !pinned('s3SecretAccessKey') && (
{_(
"Don't have keys? If EverShop runs on a server that already has access to the bucket — for example an AWS IAM role, or AWS keys set up as environment variables on the server — leave both fields empty and the server's own credentials are used automatically. The connection is tested when you save, so a wrong or missing setup cannot be saved."
)}
)}
{pinned('s3Endpoint') ? (
) : (
<>
{_(
'S3-compatible services only (Hetzner, Cloudflare R2, MinIO, DigitalOcean Spaces). Leave empty for AWS.'
)}
>
)}
{pinned('s3ForcePathStyle') ? (
) : (
<>
{_('Required by MinIO. Leave off for AWS, Hetzner and R2.')}
>
)}
{pinned('s3BaseUrl') ? (
) : (
<>
{_(
'Optional CDN (e.g. CloudFront) serving the bucket — lets the bucket stay private. Without it, objects must be publicly readable via a bucket policy. Example: https://cdn.mystore.com or https://d111abcdef8.cloudfront.net, a CloudFront distribution with this bucket as its origin. Files are served as /, so the domain must point at the bucket root.'
)}
>
)}
>
)}
{provider === 'azure' && (
<>
{pinned('azureStorageConnectionString') ? (
) : (
<>
{_(
'Copy it from the Azure portal: sign in, open your storage account, then Security + networking → Access keys → Connection string.'
)}
>
)}
{pinned('azureStorageContainerName') ? (
) : (
)}
{pinned('azureContainerAccess') ? (
) : (
<>
{_(
'Public read requires "Allow blob anonymous access" on the storage account — disallowed by default on new accounts. Prefer a private container with a public base URL (CDN).'
)}
>
)}
{pinned('azureBaseUrl') ? (
) : (
<>
{_(
'Optional CDN (e.g. Azure CDN / Front Door) serving the container — lets the container stay private. Files are served as / with no container segment added, so either set the CDN origin path to / (example: https://mystore.azureedge.net) or include the container here (example: https://mystore.azureedge.net/media).'
)}
>
)}
>
)}
{provider === 'gcs' && (
<>
{pinned('gcsBucket') ? (
) : (
)}
{pinned('gcsServiceAccountKey') ? (
) : (
<>
!value ||
looksLikeServiceAccountKey(value) ||
_(
'Paste the entire content of the downloaded JSON key file'
)
}}
/>
{_(
'Create a key in the Google Cloud Console: IAM & Admin → Service Accounts → create or pick an account with the Storage Object Admin role on the bucket → Keys → Add key → JSON. Paste the whole downloaded file here.'
)}
>
)}
{!pinned('gcsServiceAccountKey') && (
{_(
"Don't have a key? If EverShop runs on Google Cloud (Compute Engine, GKE, Cloud Run) with a service account attached, or the GOOGLE_APPLICATION_CREDENTIALS environment variable is set on the server, leave this field empty and the server's own credentials are used automatically. The connection is tested when you save, so a wrong or missing setup cannot be saved."
)}
)}
{pinned('gcsBaseUrl') ? (
) : (
<>
{_(
'Optional CDN (e.g. Cloud CDN) serving the bucket — lets the bucket stay private. Without it, objects must be publicly readable: grant "allUsers" the Storage Object Viewer role on the bucket (blocked when Public Access Prevention is enforced on your organization). Example: https://cdn.mystore.com, a load balancer domain with this bucket as its backend bucket.'
)}
>
)}
>
)}
{provider === 'local' && (
{_('Local storage is not recommended for production')}
{_(
'Files stored on this server can be lost when it is updated, moved, or fails. For a live store, use S3 or Azure Blob Storage instead.'
)}
)}
{_('Upload rules')}
{_(
'What can be uploaded and how big it can be — applies on every storage provider.'
)}
0
? setting.uploadAllowedMimeTypes
: DEFAULT_TYPE_SELECTION
}
validation={{
validate: (value: string[]) =>
(Array.isArray(value) && value.length > 0) ||
_('Select at least one file type')
}}
/>
{_(
'Files with other types are rejected at upload. SVG is not offered on purpose — SVG files can contain scripts and are a security risk when served.'
)}
{setting.uploadAllowedMimeTypesConfigExtras.length > 0 && (
{_('Also allowed via server configuration: ${types}', {
types: setting.uploadAllowedMimeTypesConfigExtras.join(', ')
})}
)}
{setting.uploadMaxFileSizePinned ? (
) : (
<>
!value ||
Number(value) > 0 ||
_('Enter a size greater than zero')
}}
/>
{_(
'Per file, in megabytes (MB). Leave empty for the default of 10 MB. Applies to every upload in the admin panel — product images, banners, media.'
)}
>
)}
{setting.uploadMaxFileSizePerTypePinned ? (
`${row.type}: ${row.maxSize} MB`)
.join(', ')
: null
}
/>
) : (
<>
{_(
'Overrides the maximum size for matching file types — for example a smaller limit for images and a bigger one for videos. An exact type (video/mp4) wins over a family (video/*); anything without a match uses the maximum file size above. Overrides do not allow new types: the file type itself must be enabled in "Allowed file types".'
)}
>
)}
);
}
export const layout = {
areaId: 'systemSetting',
sortOrder: 10
};
export const query = `
query Query {
setting {
fileStorage
s3Region
s3Bucket
s3AccessKeyId
s3SecretAccessKey
s3Endpoint
s3ForcePathStyle
s3BaseUrl
azureStorageConnectionString
azureStorageContainerName
azureContainerAccess
azureBaseUrl
gcsBucket
gcsServiceAccountKey
gcsBaseUrl
fileStorageConfigOverrides
uploadMaxFileSize
uploadMaxFileSizePinned
uploadMaxFileSizePerType
uploadMaxFileSizePerTypePinned
uploadAllowedMimeTypes
uploadMimeTypeOptions
uploadAllowedMimeTypesConfigExtras
}
}
`;