release: v1.4.1 — 上传策略设置、保留原图与上传 tagNames
管理员可在设置页配置上传大小、格式、限流与保留原图;上传 API 支持按标签名称打标。
This commit is contained in:
1 parent
d0eb364645
commit
99650717b3
25 files changed
+1354
-172
No files matched your search
@@ -30,6 +30,16 @@
|
||||
# 服务端 WebP 压缩质量 1-100(默认 80;也可在设置页配置)
|
||||
# WEBP_QUALITY=80
|
||||
|
||||
# 上传限制(也可在设置 → 访问控制配置;环境变量优先级更高)
|
||||
# UPLOAD_MAX_FILE_SIZE_MB=10
|
||||
# ALLOWED_MIME_TYPES=image/jpeg,image/png,image/webp,image/gif,image/svg+xml,image/x-icon
|
||||
# UPLOAD_RATE_IP_MAX=60
|
||||
# UPLOAD_RATE_TOKEN_MAX=120
|
||||
# UPLOAD_RATE_WINDOW_MINUTES=15
|
||||
# LOGIN_RATE_MAX=10
|
||||
# LOGIN_RATE_WINDOW_MINUTES=15
|
||||
# PRESERVE_ORIGINAL_UPLOAD=false
|
||||
|
||||
# 自动删除超过 N 天的图片(0 表示关闭;也可在设置页配置)
|
||||
# AUTO_DELETE_DAYS=0
|
||||
|
||||
|
||||
@@ -4,6 +4,19 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.4.1] - 2026-09-16
|
||||
|
||||
### 新增
|
||||
|
||||
- **上传策略(设置 → 基础)**:单文件大小、允许格式、上传/登录限流、保留原图(关闭服务端 WebP 转换);支持 `.env` 覆盖
|
||||
- **上传 API**:可选 `tagNames`(名称不存在则创建,存在则复用);与 `tagIds` 可并用
|
||||
|
||||
### 改进
|
||||
|
||||
- 登录接口接入可配置的登录限流
|
||||
- 设置页将全站上传策略并入「上传偏好 / 图片处理」;访问控制保留登录限流
|
||||
- API 文档补充 `tagIds` / `tagNames` 参数说明
|
||||
|
||||
## [1.4.0] - 2026-09-09
|
||||
|
||||
### 新增
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
<script setup lang="ts">
|
||||
type PolicySource = 'env' | 'db' | 'default'
|
||||
type MimeType = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/gif' | 'image/svg+xml' | 'image/x-icon'
|
||||
|
||||
defineProps<{
|
||||
part: 'upload-preference' | 'image-processing' | 'login-rate'
|
||||
uploadMaxFileSizeMbSource?: PolicySource
|
||||
allowedMimeTypesSource?: PolicySource
|
||||
uploadRateIpMaxSource?: PolicySource
|
||||
uploadRateTokenMaxSource?: PolicySource
|
||||
uploadRateWindowMinutesSource?: PolicySource
|
||||
loginRateMaxSource?: PolicySource
|
||||
loginRateWindowMinutesSource?: PolicySource
|
||||
preserveOriginalUploadSource?: PolicySource
|
||||
mimeTypeOptions?: ReadonlyArray<{ mime: MimeType, label: string }>
|
||||
}>()
|
||||
|
||||
const uploadMaxFileSizeMbDraft = defineModel<number>('uploadMaxFileSizeMb')
|
||||
const allowedMimeTypesDraft = defineModel<MimeType[]>('allowedMimeTypes')
|
||||
const uploadRateIpMaxDraft = defineModel<number>('uploadRateIpMax')
|
||||
const uploadRateTokenMaxDraft = defineModel<number>('uploadRateTokenMax')
|
||||
const uploadRateWindowMinutesDraft = defineModel<number>('uploadRateWindowMinutes')
|
||||
const loginRateMaxDraft = defineModel<number>('loginRateMax')
|
||||
const loginRateWindowMinutesDraft = defineModel<number>('loginRateWindowMinutes')
|
||||
const preserveOriginalUploadDraft = defineModel<boolean>('preserveOriginalUpload')
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
function sourceBadge(source: PolicySource) {
|
||||
switch (source) {
|
||||
case 'env':
|
||||
return { label: t('settings.badgeEnv'), color: 'warning' as const }
|
||||
case 'db':
|
||||
return { label: t('settings.badgeSaved'), color: 'success' as const }
|
||||
default:
|
||||
return { label: t('settings.badgeDefault'), color: 'neutral' as const }
|
||||
}
|
||||
}
|
||||
|
||||
function toggleMime(mime: MimeType, checked: boolean) {
|
||||
if (!allowedMimeTypesDraft.value) return
|
||||
if (checked) {
|
||||
if (!allowedMimeTypesDraft.value.includes(mime)) {
|
||||
allowedMimeTypesDraft.value = [...allowedMimeTypesDraft.value, mime]
|
||||
}
|
||||
return
|
||||
}
|
||||
if (allowedMimeTypesDraft.value.length <= 1) return
|
||||
allowedMimeTypesDraft.value = allowedMimeTypesDraft.value.filter(item => item !== mime)
|
||||
}
|
||||
|
||||
function isMimeChecked(mime: MimeType): boolean {
|
||||
return allowedMimeTypesDraft.value?.includes(mime) ?? false
|
||||
}
|
||||
|
||||
function clampUploadMaxFileSizeMb(value: unknown): number {
|
||||
const num = Number(value)
|
||||
if (!Number.isFinite(num)) return uploadMaxFileSizeMbDraft.value ?? 10
|
||||
return Math.min(100, Math.max(1, Math.round(num)))
|
||||
}
|
||||
|
||||
function onUploadMaxFileSizeInput(event: Event) {
|
||||
uploadMaxFileSizeMbDraft.value = clampUploadMaxFileSizeMb(
|
||||
(event.target as HTMLInputElement).value
|
||||
)
|
||||
}
|
||||
|
||||
function onUploadMaxFileSizeNumberInput(value: string | number) {
|
||||
uploadMaxFileSizeMbDraft.value = clampUploadMaxFileSizeMb(value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-if="part === 'upload-preference'">
|
||||
<div class="py-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.uploadMaxFileSize') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="uploadMaxFileSizeMbSource"
|
||||
:color="sourceBadge(uploadMaxFileSizeMbSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(uploadMaxFileSizeMbSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.uploadMaxFileSizeHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="mt-3 flex items-center gap-3"
|
||||
:class="uploadMaxFileSizeMbSource === 'env' ? 'pointer-events-none opacity-60' : ''"
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
min="1"
|
||||
max="100"
|
||||
:value="uploadMaxFileSizeMbDraft"
|
||||
class="h-1.5 min-w-0 flex-1 cursor-pointer appearance-none rounded-full bg-muted accent-primary"
|
||||
:disabled="uploadMaxFileSizeMbSource === 'env'"
|
||||
@input="onUploadMaxFileSizeInput"
|
||||
>
|
||||
<div class="flex shrink-0 items-center gap-1.5">
|
||||
<UInput
|
||||
:model-value="uploadMaxFileSizeMbDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="100"
|
||||
size="xs"
|
||||
class="w-14 tabular-nums"
|
||||
:disabled="uploadMaxFileSizeMbSource === 'env'"
|
||||
@update:model-value="onUploadMaxFileSizeNumberInput"
|
||||
/>
|
||||
<span class="text-xs text-muted">MB</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="py-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.allowedMimeTypes') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="allowedMimeTypesSource"
|
||||
:color="sourceBadge(allowedMimeTypesSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(allowedMimeTypesSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.allowedMimeTypesHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="mt-3 flex flex-wrap gap-2"
|
||||
:class="allowedMimeTypesSource === 'env' ? 'pointer-events-none opacity-60' : ''"
|
||||
>
|
||||
<label
|
||||
v-for="option in mimeTypeOptions ?? []"
|
||||
:key="option.mime"
|
||||
class="inline-flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors"
|
||||
:class="isMimeChecked(option.mime)
|
||||
? 'border-primary/40 bg-primary/5'
|
||||
: 'border-default bg-muted/20 hover:bg-muted/40'"
|
||||
:title="option.mime"
|
||||
>
|
||||
<UCheckbox
|
||||
:model-value="isMimeChecked(option.mime)"
|
||||
@update:model-value="(v) => toggleMime(option.mime, v === true)"
|
||||
@click.stop
|
||||
/>
|
||||
<span class="font-medium text-highlighted">{{ option.label }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="py-4">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.uploadRateGroup') }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.uploadRateFootnote') }}
|
||||
</p>
|
||||
<div class="mt-3 grid gap-4 sm:grid-cols-3">
|
||||
<div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-xs font-medium text-muted">
|
||||
{{ t('settings.uploadRateIpMax') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="uploadRateIpMaxSource"
|
||||
:color="sourceBadge(uploadRateIpMaxSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(uploadRateIpMaxSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<UInput
|
||||
v-model.number="uploadRateIpMaxDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="1000"
|
||||
size="sm"
|
||||
class="mt-2 w-full tabular-nums"
|
||||
:disabled="uploadRateIpMaxSource === 'env'"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-xs font-medium text-muted">
|
||||
{{ t('settings.uploadRateTokenMax') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="uploadRateTokenMaxSource"
|
||||
:color="sourceBadge(uploadRateTokenMaxSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(uploadRateTokenMaxSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<UInput
|
||||
v-model.number="uploadRateTokenMaxDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="5000"
|
||||
size="sm"
|
||||
class="mt-2 w-full tabular-nums"
|
||||
:disabled="uploadRateTokenMaxSource === 'env'"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-xs font-medium text-muted">
|
||||
{{ t('settings.uploadRateWindowMinutes') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="uploadRateWindowMinutesSource"
|
||||
:color="sourceBadge(uploadRateWindowMinutesSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(uploadRateWindowMinutesSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<div class="mt-2 flex items-center gap-2">
|
||||
<UInput
|
||||
v-model.number="uploadRateWindowMinutesDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="1440"
|
||||
size="sm"
|
||||
class="w-full tabular-nums"
|
||||
:disabled="uploadRateWindowMinutesSource === 'env'"
|
||||
/>
|
||||
<span class="shrink-0 text-xs text-muted">{{ t('settings.minutesUnit') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<SettingsToggleRow
|
||||
v-else-if="part === 'image-processing'"
|
||||
v-model="preserveOriginalUploadDraft!"
|
||||
:disabled="preserveOriginalUploadSource === 'env'"
|
||||
>
|
||||
<template #title>
|
||||
<span class="inline-flex flex-wrap items-center gap-2">
|
||||
{{ t('settings.preserveOriginalUpload') }}
|
||||
<UBadge
|
||||
v-if="preserveOriginalUploadSource"
|
||||
:color="sourceBadge(preserveOriginalUploadSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(preserveOriginalUploadSource).label }}
|
||||
</UBadge>
|
||||
</span>
|
||||
</template>
|
||||
<template #hint>
|
||||
{{ t('settings.preserveOriginalUploadHint') }}
|
||||
</template>
|
||||
</SettingsToggleRow>
|
||||
|
||||
<template v-else-if="part === 'login-rate'">
|
||||
<div class="grid gap-4 py-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.loginRateMax') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="loginRateMaxSource"
|
||||
:color="sourceBadge(loginRateMaxSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(loginRateMaxSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<UInput
|
||||
v-model.number="loginRateMaxDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="100"
|
||||
size="sm"
|
||||
class="mt-2 w-full tabular-nums"
|
||||
:disabled="loginRateMaxSource === 'env'"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.loginRateWindowMinutes') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="loginRateWindowMinutesSource"
|
||||
:color="sourceBadge(loginRateWindowMinutesSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(loginRateWindowMinutesSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<div class="mt-2 flex items-center gap-2">
|
||||
<UInput
|
||||
v-model.number="loginRateWindowMinutesDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="1440"
|
||||
size="sm"
|
||||
class="w-full tabular-nums"
|
||||
:disabled="loginRateWindowMinutesSource === 'env'"
|
||||
/>
|
||||
<span class="shrink-0 text-xs text-muted">{{ t('settings.minutesUnit') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="pb-4 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.loginRateFootnote') }}
|
||||
</p>
|
||||
</template>
|
||||
</template>
|
||||
@@ -1,4 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
part: 'upload-preference' | 'image-processing'
|
||||
}>()
|
||||
|
||||
const {
|
||||
compressEnabled,
|
||||
autoCopyMarkdown,
|
||||
@@ -44,111 +48,107 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SettingsSection :title="t('preferences.processing')">
|
||||
<SettingsGroup>
|
||||
<SettingsToggleRow
|
||||
v-model="compressEnabled"
|
||||
:title="t('preferences.clientCompress')"
|
||||
:hint="t('preferences.clientCompressHint')"
|
||||
/>
|
||||
<div
|
||||
v-if="userSettings"
|
||||
class="flex items-start justify-between gap-4 py-4"
|
||||
>
|
||||
<div class="min-w-0 flex-1 pr-2">
|
||||
<p class="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-sm font-medium text-highlighted">
|
||||
<span>{{ t('preferences.autoDeletePrefix') }}</span>
|
||||
<UInput
|
||||
v-model.number="userAutoDeleteDaysDraft"
|
||||
type="number"
|
||||
min="1"
|
||||
max="3650"
|
||||
size="xs"
|
||||
class="w-14 tabular-nums"
|
||||
:class="userAutoDeleteEnabled ? '' : 'pointer-events-none opacity-40'"
|
||||
/>
|
||||
<span>{{ t('preferences.autoDeleteSuffix') }}</span>
|
||||
</p>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('preferences.autoDeleteHint') }}
|
||||
</p>
|
||||
</div>
|
||||
<USwitch
|
||||
v-model="userAutoDeleteEnabled"
|
||||
class="mt-0.5 shrink-0"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="flex justify-center py-4"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-loader-circle"
|
||||
class="size-5 animate-spin text-muted"
|
||||
/>
|
||||
</div>
|
||||
<div class="py-4">
|
||||
<div class="min-w-0">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('preferences.webpQuality') }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('preferences.webpQualityHint') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-3 flex items-center gap-3">
|
||||
<input
|
||||
type="range"
|
||||
min="1"
|
||||
max="100"
|
||||
:value="clientWebpQuality"
|
||||
class="h-1.5 min-w-0 flex-1 cursor-pointer appearance-none rounded-full bg-muted accent-primary"
|
||||
@input="onClientQualityInput"
|
||||
>
|
||||
<template v-if="part === 'image-processing'">
|
||||
<SettingsToggleRow
|
||||
v-model="compressEnabled"
|
||||
:title="t('preferences.clientCompress')"
|
||||
:hint="t('preferences.clientCompressHint')"
|
||||
/>
|
||||
<div
|
||||
v-if="userSettings"
|
||||
class="flex items-start justify-between gap-4 py-4"
|
||||
>
|
||||
<div class="min-w-0 flex-1 pr-2">
|
||||
<p class="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-sm font-medium text-highlighted">
|
||||
<span>{{ t('preferences.autoDeletePrefix') }}</span>
|
||||
<UInput
|
||||
:model-value="clientWebpQuality"
|
||||
v-model.number="userAutoDeleteDaysDraft"
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
max="3650"
|
||||
size="xs"
|
||||
class="w-14 shrink-0 tabular-nums"
|
||||
@update:model-value="onClientQualityNumberInput"
|
||||
class="w-14 tabular-nums"
|
||||
:class="userAutoDeleteEnabled ? '' : 'pointer-events-none opacity-40'"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection :title="t('preferences.title')">
|
||||
<SettingsGroup>
|
||||
<SettingsToggleRow
|
||||
v-model="autoCopyMarkdown"
|
||||
:title="t('preferences.autoCopy')"
|
||||
:hint="t('preferences.autoCopyHint')"
|
||||
/>
|
||||
<div class="py-4">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.defaultCopyFormat') }}
|
||||
<span>{{ t('preferences.autoDeleteSuffix') }}</span>
|
||||
</p>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.defaultCopyFormatHint') }}
|
||||
{{ t('preferences.autoDeleteHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="mt-3 flex w-full max-w-md gap-1 rounded-lg border border-default p-0.5"
|
||||
:class="autoCopyMarkdown ? '' : 'pointer-events-none opacity-40'"
|
||||
>
|
||||
<UButton
|
||||
v-for="item in copyFormatItems"
|
||||
:key="item.value"
|
||||
size="xs"
|
||||
class="flex-1 justify-center"
|
||||
:variant="copyFormat === item.value ? 'solid' : 'ghost'"
|
||||
:color="copyFormat === item.value ? 'primary' : 'neutral'"
|
||||
:label="item.label"
|
||||
@click="setCopyFormat(item.value)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
</SettingsSection>
|
||||
<USwitch
|
||||
v-model="userAutoDeleteEnabled"
|
||||
class="mt-0.5 shrink-0"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="flex justify-center py-4"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-loader-circle"
|
||||
class="size-5 animate-spin text-muted"
|
||||
/>
|
||||
</div>
|
||||
<div class="py-4">
|
||||
<div class="min-w-0">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('preferences.webpQuality') }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('preferences.webpQualityHint') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-3 flex items-center gap-3">
|
||||
<input
|
||||
type="range"
|
||||
min="1"
|
||||
max="100"
|
||||
:value="clientWebpQuality"
|
||||
class="h-1.5 min-w-0 flex-1 cursor-pointer appearance-none rounded-full bg-muted accent-primary"
|
||||
@input="onClientQualityInput"
|
||||
>
|
||||
<UInput
|
||||
:model-value="clientWebpQuality"
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
size="xs"
|
||||
class="w-14 shrink-0 tabular-nums"
|
||||
@update:model-value="onClientQualityNumberInput"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<SettingsToggleRow
|
||||
v-model="autoCopyMarkdown"
|
||||
:title="t('preferences.autoCopy')"
|
||||
:hint="t('preferences.autoCopyHint')"
|
||||
/>
|
||||
<div class="py-4">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.defaultCopyFormat') }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.defaultCopyFormatHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="mt-3 flex w-full max-w-md gap-1 rounded-lg border border-default p-0.5"
|
||||
:class="autoCopyMarkdown ? '' : 'pointer-events-none opacity-40'"
|
||||
>
|
||||
<UButton
|
||||
v-for="item in copyFormatItems"
|
||||
:key="item.value"
|
||||
size="xs"
|
||||
class="flex-1 justify-center"
|
||||
:variant="copyFormat === item.value ? 'solid' : 'ghost'"
|
||||
:color="copyFormat === item.value ? 'primary' : 'neutral'"
|
||||
:label="item.label"
|
||||
@click="setCopyFormat(item.value)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
@@ -73,11 +73,26 @@ export function buildApiDocs(ctx: ApiDocsContext): ApiDocEndpoint[] {
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.upload.token'
|
||||
},
|
||||
{
|
||||
name: 'tagIds',
|
||||
type: 'string',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.upload.tagIds'
|
||||
},
|
||||
{
|
||||
name: 'tagNames',
|
||||
type: 'string',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.upload.tagNames'
|
||||
}
|
||||
],
|
||||
curl: `curl -X POST "${baseUrl}/api/images/upload" \\
|
||||
${auth} \\
|
||||
-F "image=@./demo.png"`,
|
||||
-F "image=@./demo.png" \\
|
||||
-F 'tagNames=["博客","截图"]'`,
|
||||
responseExample: `{
|
||||
"success": true,
|
||||
"items": [
|
||||
|
||||
@@ -3,10 +3,13 @@ import type { SettingsTab } from '~/types/settings'
|
||||
import { ADMIN_SETTINGS_TABS, USER_SETTINGS_TABS } from '~/types/settings'
|
||||
import { willActivateDomainSeparation } from '~/utils/domain-separation'
|
||||
import SettingsUserPreferencesFields from '~/components/settings/SettingsUserPreferencesFields.vue'
|
||||
import SettingsUploadPolicyFields from '~/components/settings/SettingsUploadPolicyFields.vue'
|
||||
|
||||
type SettingSource = 'env' | 'db' | 'none'
|
||||
type WebpQualitySource = 'env' | 'db' | 'default'
|
||||
type PolicySource = 'env' | 'db' | 'default'
|
||||
type LoginVerificationMethod = 'slider' | 'turnstile' | 'cap'
|
||||
type MimeType = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/gif' | 'image/svg+xml' | 'image/x-icon'
|
||||
|
||||
interface SettingsResponse {
|
||||
apiUploadToken: string
|
||||
@@ -42,6 +45,23 @@ interface SettingsResponse {
|
||||
capApiEndpoint: string
|
||||
capSecret: string
|
||||
appVersion: string
|
||||
uploadMaxFileSizeMb: number
|
||||
uploadMaxFileSizeMbSource: PolicySource
|
||||
allowedMimeTypes: MimeType[]
|
||||
allowedMimeTypesSource: PolicySource
|
||||
uploadRateIpMax: number
|
||||
uploadRateIpMaxSource: PolicySource
|
||||
uploadRateTokenMax: number
|
||||
uploadRateTokenMaxSource: PolicySource
|
||||
uploadRateWindowMinutes: number
|
||||
uploadRateWindowMinutesSource: PolicySource
|
||||
loginRateMax: number
|
||||
loginRateMaxSource: PolicySource
|
||||
loginRateWindowMinutes: number
|
||||
loginRateWindowMinutesSource: PolicySource
|
||||
preserveOriginalUpload: boolean
|
||||
preserveOriginalUploadSource: PolicySource
|
||||
mimeTypeOptions: ReadonlyArray<{ mime: MimeType, label: string }>
|
||||
}
|
||||
|
||||
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin } = useAuth()
|
||||
@@ -143,6 +163,15 @@ const disableDomainSeparationOpen = ref(false)
|
||||
const pendingDomainSeparationDisable = ref(false)
|
||||
const domainSeparationSaveConfirmOpen = ref(false)
|
||||
|
||||
const uploadMaxFileSizeMbDraft = ref(10)
|
||||
const allowedMimeTypesDraft = ref<MimeType[]>([])
|
||||
const uploadRateIpMaxDraft = ref(60)
|
||||
const uploadRateTokenMaxDraft = ref(120)
|
||||
const uploadRateWindowMinutesDraft = ref(15)
|
||||
const loginRateMaxDraft = ref(10)
|
||||
const loginRateWindowMinutesDraft = ref(15)
|
||||
const preserveOriginalUploadDraft = ref(false)
|
||||
|
||||
interface ReleaseCheckResponse {
|
||||
currentVersion: string
|
||||
latestVersion: string | null
|
||||
@@ -152,6 +181,10 @@ interface ReleaseCheckResponse {
|
||||
|
||||
const releaseCheck = ref<ReleaseCheckResponse | null>(null)
|
||||
|
||||
function mimeListsEqual(left: readonly string[], right: readonly string[]): boolean {
|
||||
return left.slice().sort().join(',') === right.slice().sort().join(',')
|
||||
}
|
||||
|
||||
const hasServerChanges = computed(() => {
|
||||
if (!settings.value) return false
|
||||
return refererDraft.value !== settings.value.allowedRefererHosts
|
||||
@@ -166,6 +199,14 @@ const hasServerChanges = computed(() => {
|
||||
|| turnstileSecretKeyDraft.value !== settings.value.turnstileSecretKey
|
||||
|| capApiEndpointDraft.value !== settings.value.capApiEndpoint
|
||||
|| capSecretDraft.value !== settings.value.capSecret
|
||||
|| uploadMaxFileSizeMbDraft.value !== settings.value.uploadMaxFileSizeMb
|
||||
|| !mimeListsEqual(allowedMimeTypesDraft.value, settings.value.allowedMimeTypes)
|
||||
|| uploadRateIpMaxDraft.value !== settings.value.uploadRateIpMax
|
||||
|| uploadRateTokenMaxDraft.value !== settings.value.uploadRateTokenMax
|
||||
|| uploadRateWindowMinutesDraft.value !== settings.value.uploadRateWindowMinutes
|
||||
|| loginRateMaxDraft.value !== settings.value.loginRateMax
|
||||
|| loginRateWindowMinutesDraft.value !== settings.value.loginRateWindowMinutes
|
||||
|| preserveOriginalUploadDraft.value !== settings.value.preserveOriginalUpload
|
||||
})
|
||||
|
||||
const domainSeparationWouldActivate = computed(() =>
|
||||
@@ -221,6 +262,14 @@ function applySettings(data: SettingsResponse) {
|
||||
capApiEndpointDraft.value = data.capApiEndpoint
|
||||
capSecretDraft.value = data.capSecret
|
||||
domainSeparationDraft.value = data.domainSeparation
|
||||
uploadMaxFileSizeMbDraft.value = data.uploadMaxFileSizeMb
|
||||
allowedMimeTypesDraft.value = [...data.allowedMimeTypes]
|
||||
uploadRateIpMaxDraft.value = data.uploadRateIpMax
|
||||
uploadRateTokenMaxDraft.value = data.uploadRateTokenMax
|
||||
uploadRateWindowMinutesDraft.value = data.uploadRateWindowMinutes
|
||||
loginRateMaxDraft.value = data.loginRateMax
|
||||
loginRateWindowMinutesDraft.value = data.loginRateWindowMinutes
|
||||
preserveOriginalUploadDraft.value = data.preserveOriginalUpload
|
||||
}
|
||||
|
||||
async function patchSettings(body: Record<string, unknown>) {
|
||||
@@ -296,6 +345,11 @@ async function performSaveServerSettings() {
|
||||
|
||||
savingServer.value = true
|
||||
try {
|
||||
if (allowedMimeTypesDraft.value.length === 0) {
|
||||
toast.add({ title: t('settings.allowedMimeTypesHint'), color: 'error' })
|
||||
return
|
||||
}
|
||||
|
||||
await patchSettings({
|
||||
allowedRefererHosts: refererDraft.value,
|
||||
domainSeparation: domainSeparationDraft.value,
|
||||
@@ -308,7 +362,15 @@ async function performSaveServerSettings() {
|
||||
turnstileSiteKey: turnstileSiteKeyDraft.value,
|
||||
turnstileSecretKey: turnstileSecretKeyDraft.value,
|
||||
capApiEndpoint: capApiEndpointDraft.value,
|
||||
capSecret: capSecretDraft.value
|
||||
capSecret: capSecretDraft.value,
|
||||
uploadMaxFileSizeMb: uploadMaxFileSizeMbDraft.value,
|
||||
allowedMimeTypes: allowedMimeTypesDraft.value,
|
||||
uploadRateIpMax: uploadRateIpMaxDraft.value,
|
||||
uploadRateTokenMax: uploadRateTokenMaxDraft.value,
|
||||
uploadRateWindowMinutes: uploadRateWindowMinutesDraft.value,
|
||||
loginRateMax: loginRateMaxDraft.value,
|
||||
loginRateWindowMinutes: loginRateWindowMinutesDraft.value,
|
||||
preserveOriginalUpload: preserveOriginalUploadDraft.value
|
||||
})
|
||||
toast.add({ title: t('settings.saved'), color: 'success' })
|
||||
} catch (error: unknown) {
|
||||
@@ -492,7 +554,42 @@ watch(isAdmin, () => {
|
||||
</SettingsGroup>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsUserPreferencesFields />
|
||||
<SettingsSection
|
||||
:title="t('preferences.title')"
|
||||
:hint="t('settings.uploadLimitsHint')"
|
||||
>
|
||||
<SettingsGroup>
|
||||
<SettingsUploadPolicyFields
|
||||
v-model:upload-max-file-size-mb="uploadMaxFileSizeMbDraft"
|
||||
v-model:allowed-mime-types="allowedMimeTypesDraft"
|
||||
v-model:upload-rate-ip-max="uploadRateIpMaxDraft"
|
||||
v-model:upload-rate-token-max="uploadRateTokenMaxDraft"
|
||||
v-model:upload-rate-window-minutes="uploadRateWindowMinutesDraft"
|
||||
part="upload-preference"
|
||||
:upload-max-file-size-mb-source="settings.uploadMaxFileSizeMbSource"
|
||||
:allowed-mime-types-source="settings.allowedMimeTypesSource"
|
||||
:upload-rate-ip-max-source="settings.uploadRateIpMaxSource"
|
||||
:upload-rate-token-max-source="settings.uploadRateTokenMaxSource"
|
||||
:upload-rate-window-minutes-source="settings.uploadRateWindowMinutesSource"
|
||||
:mime-type-options="settings.mimeTypeOptions"
|
||||
/>
|
||||
<SettingsUserPreferencesFields part="upload-preference" />
|
||||
</SettingsGroup>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
:title="t('preferences.processing')"
|
||||
:hint="t('settings.imageProcessingHint')"
|
||||
>
|
||||
<SettingsGroup>
|
||||
<SettingsUploadPolicyFields
|
||||
v-model:preserve-original-upload="preserveOriginalUploadDraft"
|
||||
part="image-processing"
|
||||
:preserve-original-upload-source="settings.preserveOriginalUploadSource"
|
||||
/>
|
||||
<SettingsUserPreferencesFields part="image-processing" />
|
||||
</SettingsGroup>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection :title="t('settings.systemInfo')">
|
||||
<SettingsGroup>
|
||||
@@ -897,6 +994,21 @@ watch(isAdmin, () => {
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
:title="t('settings.rateLimits')"
|
||||
:hint="t('settings.loginRateLimitsHint')"
|
||||
>
|
||||
<SettingsGroup>
|
||||
<SettingsUploadPolicyFields
|
||||
v-model:login-rate-max="loginRateMaxDraft"
|
||||
v-model:login-rate-window-minutes="loginRateWindowMinutesDraft"
|
||||
part="login-rate"
|
||||
:login-rate-max-source="settings.loginRateMaxSource"
|
||||
:login-rate-window-minutes-source="settings.loginRateWindowMinutesSource"
|
||||
/>
|
||||
</SettingsGroup>
|
||||
</SettingsSection>
|
||||
</SettingsPanel>
|
||||
<div
|
||||
v-else
|
||||
|
||||
@@ -4,6 +4,17 @@ Version history and notable changes. The full log is also in the repo root [CHAN
|
||||
|
||||
---
|
||||
|
||||
## [1.4.1] — 2026-09-16
|
||||
|
||||
### Added
|
||||
|
||||
- **Upload policy (Settings → Basic)**: max size, allowed formats, rate limits, preserve originals; env override
|
||||
- **Upload API**: optional `tagNames` for tagging by name (create or reuse)
|
||||
|
||||
### Improved
|
||||
|
||||
- Configurable login rate limits; settings layout updates
|
||||
|
||||
## [1.4.0] — 2026-09-09
|
||||
|
||||
### Added
|
||||
|
||||
@@ -4,6 +4,17 @@ PicHost 版本历史与重要变更说明。完整记录亦见仓库根目录 [C
|
||||
|
||||
---
|
||||
|
||||
## [1.4.1] — 2026-09-16
|
||||
|
||||
### 新增
|
||||
|
||||
- **上传策略(设置 → 基础)**:大小、格式、限流、保留原图;环境变量可覆盖
|
||||
- **上传 API**:可选 `tagNames` 按名称打标(自动创建或复用)
|
||||
|
||||
### 改进
|
||||
|
||||
- 登录限流可配置;设置页布局调整
|
||||
|
||||
## [1.4.0] — 2026-09-09
|
||||
|
||||
### 新增
|
||||
|
||||
+30
-4
@@ -286,12 +286,12 @@
|
||||
"back": "Back to upload",
|
||||
"processing": "Image processing",
|
||||
"clientCompress": "Client-side compression",
|
||||
"clientCompressHint": "Compress in the browser before upload (server still converts to WebP)",
|
||||
"clientCompressHint": "Compress in the browser before upload. The server may still convert to WebP unless “Preserve originals” is enabled above.",
|
||||
"autoDeletePrefix": "Auto-delete after",
|
||||
"autoDeleteSuffix": "days",
|
||||
"autoDeleteHint": "Only affects images uploaded after enabling; existing images are kept",
|
||||
"webpQuality": "WebP quality",
|
||||
"webpQualityHint": "Client compression quality (1–100); requires client-side compression",
|
||||
"webpQualityHint": "Quality for client-side WebP pre-compression; higher values mean better quality and larger files.",
|
||||
"current": "Current: {n}",
|
||||
"qualityHigh": "High quality",
|
||||
"qualityMedium": "Medium quality",
|
||||
@@ -414,7 +414,31 @@
|
||||
"envOverride": "Overridden by environment variable; cannot edit in UI",
|
||||
"saved": "Settings saved",
|
||||
"saveFailed": "Failed to save settings",
|
||||
"loadFailed": "Failed to load settings"
|
||||
"loadFailed": "Failed to load settings",
|
||||
"uploadLimits": "Upload limits",
|
||||
"uploadLimitsHint": "Site-wide upload policy and your personal convenience options. Applies after save.",
|
||||
"imageProcessingHint": "Site-wide format conversion and personal compression/cleanup.",
|
||||
"serverPolicy": "Site-wide",
|
||||
"personalPreference": "Personal",
|
||||
"uploadRateGroup": "Upload rate limits",
|
||||
"minutesUnit": "min",
|
||||
"uploadMaxFileSize": "Max file size",
|
||||
"uploadMaxFileSizeHint": "Uploads larger than this are rejected (1–100 MB).",
|
||||
"allowedMimeTypes": "Allowed image formats",
|
||||
"allowedMimeTypesHint": "Keep at least one format enabled. The server validates file signatures, not just extensions.",
|
||||
"preserveOriginalUpload": "Preserve originals (disable WebP conversion)",
|
||||
"preserveOriginalUploadHint": "When enabled, JPEG/PNG/GIF uploads are stored as-is instead of converting to WebP.",
|
||||
"rateLimits": "Rate limits",
|
||||
"rateLimitsHint": "Protect against upload abuse and login brute force.",
|
||||
"loginRateLimitsHint": "Protect the login endpoint from brute-force attempts.",
|
||||
"uploadRateFootnote": "Returns 429 when exceeded within the window. Token uploads are counted separately.",
|
||||
"loginRateFootnote": "Returns 429 when exceeded within the window.",
|
||||
"uploadRateIpMax": "Upload limit (per IP)",
|
||||
"uploadRateTokenMax": "Upload limit (per token)",
|
||||
"uploadRateWindowMinutes": "Upload window (minutes)",
|
||||
"loginRateMax": "Login limit (per IP)",
|
||||
"loginRateWindowMinutes": "Login window (minutes)",
|
||||
"rateLimitsFootnote": "Exceeding the limit within the window returns HTTP 429. Token uploads are counted separately."
|
||||
},
|
||||
"storage": {
|
||||
"title": "Storage",
|
||||
@@ -854,7 +878,9 @@
|
||||
"image": "Primary upload field",
|
||||
"file": "Compatibility field, single file",
|
||||
"files": "Compatibility field, multiple files",
|
||||
"token": "Twikoo protocol form token"
|
||||
"token": "Twikoo protocol form token",
|
||||
"tagIds": "Optional JSON array or repeated fields; tag images by ID after upload",
|
||||
"tagNames": "Optional JSON array or comma-separated names; creates missing tags, reuses existing"
|
||||
},
|
||||
"list": {
|
||||
"limit": "Page size, default 20, max 100",
|
||||
|
||||
+29
-4
@@ -286,12 +286,12 @@
|
||||
"back": "返回上传",
|
||||
"processing": "图片处理",
|
||||
"clientCompress": "客户端预压缩",
|
||||
"clientCompressHint": "在上传前于浏览器端压缩图片,减少上传体积(服务端仍会转 WebP)。",
|
||||
"clientCompressHint": "上传前在浏览器端压缩以减小体积;若未开启上方「保留原图」,服务端仍可能转为 WebP。",
|
||||
"autoDeletePrefix": "自动删除超过",
|
||||
"autoDeleteSuffix": "天的图片",
|
||||
"autoDeleteHint": "自动清理指定天数前上传的图片,仅对开启后新上传的图片生效。",
|
||||
"webpQuality": "WebP 压缩质量",
|
||||
"webpQualityHint": "转换为 WebP 格式时的图片质量,数值越高画质越好、体积越大。",
|
||||
"webpQualityHint": "客户端预压缩为 WebP 时的质量;数值越高画质越好、体积越大。",
|
||||
"current": "当前:{n}",
|
||||
"qualityHigh": "高质量",
|
||||
"qualityMedium": "中等质量",
|
||||
@@ -414,7 +414,31 @@
|
||||
"envOverride": "该项已由环境变量覆盖,无法在后台修改",
|
||||
"saved": "服务器配置已保存",
|
||||
"saveFailed": "保存服务器配置失败",
|
||||
"loadFailed": "加载设置失败"
|
||||
"loadFailed": "加载设置失败",
|
||||
"uploadLimits": "上传限制",
|
||||
"uploadLimitsHint": "全站上传策略与个人上传便捷选项,保存后立即生效。",
|
||||
"imageProcessingHint": "全站格式转换与个人端压缩、清理策略。",
|
||||
"serverPolicy": "全站策略",
|
||||
"personalPreference": "个人偏好",
|
||||
"uploadRateGroup": "上传限流",
|
||||
"minutesUnit": "分钟",
|
||||
"uploadMaxFileSize": "单文件大小上限",
|
||||
"uploadMaxFileSizeHint": "超过此大小的图片将被拒绝上传(1–100 MB)。",
|
||||
"allowedMimeTypes": "允许的图片格式",
|
||||
"allowedMimeTypesHint": "至少保留一种格式;服务端会校验文件签名,不仅看扩展名。",
|
||||
"preserveOriginalUpload": "保留原图(关闭 WebP 转换)",
|
||||
"preserveOriginalUploadHint": "开启后上传的 JPEG/PNG/GIF 不再转为 WebP,按原格式存储;关闭时可节省空间。",
|
||||
"rateLimits": "限流",
|
||||
"rateLimitsHint": "防止恶意刷上传或暴力登录。",
|
||||
"loginRateLimitsHint": "防止登录接口被暴力尝试。",
|
||||
"uploadRateFootnote": "窗口期内超过次数将返回 429;带 Token 的上传单独计数。",
|
||||
"loginRateFootnote": "窗口期内超过次数将返回 429。",
|
||||
"uploadRateIpMax": "上传限流(每 IP)",
|
||||
"uploadRateTokenMax": "上传限流(每 Token)",
|
||||
"uploadRateWindowMinutes": "上传限流窗口(分钟)",
|
||||
"loginRateMax": "登录限流(每 IP)",
|
||||
"loginRateWindowMinutes": "登录限流窗口(分钟)",
|
||||
"rateLimitsFootnote": "窗口期内超过次数将返回 429。带 Token 的上传单独计数。"
|
||||
},
|
||||
"storage": {
|
||||
"title": "存储设置",
|
||||
@@ -855,7 +879,8 @@
|
||||
"file": "兼容字段,单图上传",
|
||||
"files": "兼容字段,多图上传",
|
||||
"token": "Twikoo 协议兼容,表单 token",
|
||||
"tagIds": "可选,JSON 数组或重复字段,上传后自动打标"
|
||||
"tagIds": "可选,JSON 数组或重复字段,上传后按 ID 打标",
|
||||
"tagNames": "可选,JSON 数组或逗号分隔;名称不存在则自动创建,存在则复用"
|
||||
},
|
||||
"list": {
|
||||
"limit": "每页条数,默认 20,最大 100",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "pichost",
|
||||
"version": "1.4.0",
|
||||
"version": "1.4.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "pichost",
|
||||
"version": "1.4.0",
|
||||
"version": "1.4.1",
|
||||
"hasInstallScript": true,
|
||||
"license": "GPL-3.0-only",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pichost",
|
||||
"version": "1.4.0",
|
||||
"version": "1.4.1",
|
||||
"description": "Self-hosted image hosting for your NAS / home server — Nuxt admin UI, local disk or S3-compatible storage, server-side WebP compression, referer protection, Twikoo/EasyImage compatible.",
|
||||
"homepage": "https://github.com/O96u/PicHost#readme",
|
||||
"repository": {
|
||||
|
||||
@@ -14,6 +14,7 @@ import { getAdminSecret } from '../../utils/env'
|
||||
import { verifyLoginVerification, type VerificationBody } from '../../utils/login-verification'
|
||||
import { logActivity } from '../../utils/activity-log'
|
||||
import { clientIp, logInfo, logWarn } from '../../utils/logger'
|
||||
import { checkLoginRateLimit } from '../../utils/rate-limit'
|
||||
|
||||
interface LoginBody extends VerificationBody {
|
||||
username?: string
|
||||
@@ -21,29 +22,9 @@ interface LoginBody extends VerificationBody {
|
||||
secret?: string
|
||||
}
|
||||
|
||||
const loginAttempts = new Map<string, { count: number, resetAt: number }>()
|
||||
const MAX_ATTEMPTS = 10
|
||||
const WINDOW_MS = 15 * 60 * 1000
|
||||
|
||||
function checkRateLimit(ip: string): void {
|
||||
const now = Date.now()
|
||||
const entry = loginAttempts.get(ip)
|
||||
if (!entry || now > entry.resetAt) {
|
||||
loginAttempts.set(ip, { count: 1, resetAt: now + WINDOW_MS })
|
||||
return
|
||||
}
|
||||
entry.count += 1
|
||||
if (entry.count > MAX_ATTEMPTS) {
|
||||
throw createError({
|
||||
statusCode: 429,
|
||||
statusMessage: '登录尝试过于频繁,请稍后再试'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const ip = clientIp(event)
|
||||
checkRateLimit(ip)
|
||||
checkLoginRateLimit(ip)
|
||||
|
||||
const body = await readBody<LoginBody>(event)
|
||||
await verifyLoginVerification(event, body ?? {})
|
||||
|
||||
@@ -12,7 +12,12 @@ import {
|
||||
} from '../../utils/process-image-upload'
|
||||
import { createApiError } from '../../utils/api-error'
|
||||
import { checkUploadRateLimit } from '../../utils/rate-limit'
|
||||
import { parseTagIdsParam } from '../../utils/tags'
|
||||
import { readMultipartFormFieldValues } from '../../utils/multipart-form'
|
||||
import {
|
||||
parseTagIdsParam,
|
||||
parseTagNamesParam,
|
||||
resolveUploadTagIds
|
||||
} from '../../utils/tags'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await requireUploadAuth(event)
|
||||
@@ -31,24 +36,15 @@ export default defineEventHandler(async (event) => {
|
||||
const source = verifyApiUploadToken(event) ? 'api' : 'web'
|
||||
const uploadUserId = await getUploadUserId(event)
|
||||
|
||||
const tagIdsField = formData.find(part => part.name === 'tagIds')
|
||||
let uploadTagIds: number[] = []
|
||||
if (tagIdsField?.data?.length) {
|
||||
const raw = new TextDecoder().decode(tagIdsField.data).trim()
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown
|
||||
uploadTagIds = parseTagIdsParam(parsed)
|
||||
} catch {
|
||||
uploadTagIds = parseTagIdsParam(raw)
|
||||
}
|
||||
} else {
|
||||
const repeatFields = formData.filter(part => part.name === 'tagIds' && part.data?.length)
|
||||
if (repeatFields.length) {
|
||||
uploadTagIds = parseTagIdsParam(
|
||||
repeatFields.map(part => new TextDecoder().decode(part.data!).trim())
|
||||
)
|
||||
}
|
||||
const tagIdsRaw = readMultipartFormFieldValues(formData, 'tagIds')
|
||||
const tagNamesRaw = readMultipartFormFieldValues(formData, 'tagNames')
|
||||
const uploadTagIdsInput = parseTagIdsParam(tagIdsRaw.length === 1 ? tagIdsRaw[0] : tagIdsRaw)
|
||||
const uploadTagNames = parseTagNamesParam(tagNamesRaw.length === 1 ? tagNamesRaw[0] : tagNamesRaw)
|
||||
const resolvedTags = resolveUploadTagIds(uploadUserId, uploadTagIdsInput, uploadTagNames)
|
||||
if ('message' in resolvedTags) {
|
||||
createApiError(event, 'INVALID_REQUEST', resolvedTags.message, 400)
|
||||
}
|
||||
const uploadTagIds = resolvedTags.tagIds
|
||||
|
||||
// 兼容 image / file / files 字段名(图床脚本 / 通用客户端 / 网页多图)
|
||||
const fileParts = formData.filter(
|
||||
|
||||
@@ -34,6 +34,16 @@ import {
|
||||
validateLoginVerificationSettings,
|
||||
validateSettingsDomainPatch
|
||||
} from '../../utils/env'
|
||||
import {
|
||||
normalizeAllowedMimeTypes,
|
||||
parseLoginRateMax,
|
||||
parseLoginRateWindowMinutes,
|
||||
parseUploadMaxFileSizeMb,
|
||||
parseUploadRateIpMax,
|
||||
parseUploadRateTokenMax,
|
||||
parseUploadRateWindowMinutes,
|
||||
setUploadPolicySettings
|
||||
} from '../../utils/upload-policy'
|
||||
|
||||
interface SettingsPatchBody {
|
||||
webpQuality?: unknown
|
||||
@@ -50,6 +60,14 @@ interface SettingsPatchBody {
|
||||
turnstileSecretKey?: unknown
|
||||
capApiEndpoint?: unknown
|
||||
capSecret?: unknown
|
||||
uploadMaxFileSizeMb?: unknown
|
||||
allowedMimeTypes?: unknown
|
||||
uploadRateIpMax?: unknown
|
||||
uploadRateTokenMax?: unknown
|
||||
uploadRateWindowMinutes?: unknown
|
||||
loginRateMax?: unknown
|
||||
loginRateWindowMinutes?: unknown
|
||||
preserveOriginalUpload?: unknown
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
@@ -249,6 +267,72 @@ export default defineEventHandler(async (event) => {
|
||||
setSetting(SETTINGS_CAP_SECRET, nextCapSecret)
|
||||
}
|
||||
|
||||
if (body.uploadMaxFileSizeMb !== undefined) {
|
||||
const mb = parseUploadMaxFileSizeMb(String(body.uploadMaxFileSizeMb))
|
||||
if (mb === null) {
|
||||
createApiError(event, 'INVALID_REQUEST', '单文件大小需为 1–100 MB 的整数', 400)
|
||||
}
|
||||
setUploadPolicySettings({ uploadMaxFileSizeMb: mb })
|
||||
}
|
||||
|
||||
if (body.allowedMimeTypes !== undefined) {
|
||||
const raw = Array.isArray(body.allowedMimeTypes)
|
||||
? body.allowedMimeTypes.map(item => String(item))
|
||||
: String(body.allowedMimeTypes).split(',')
|
||||
const normalized = normalizeAllowedMimeTypes(raw.join(','))
|
||||
if (normalized.length === 0) {
|
||||
createApiError(event, 'INVALID_REQUEST', '至少选择一种允许上传的图片格式', 400)
|
||||
}
|
||||
setUploadPolicySettings({ allowedMimeTypes: normalized })
|
||||
}
|
||||
|
||||
if (body.uploadRateIpMax !== undefined) {
|
||||
const value = parseUploadRateIpMax(String(body.uploadRateIpMax))
|
||||
if (value === null) {
|
||||
createApiError(event, 'INVALID_REQUEST', '上传 IP 限流次数无效', 400)
|
||||
}
|
||||
setUploadPolicySettings({ uploadRateIpMax: value })
|
||||
}
|
||||
|
||||
if (body.uploadRateTokenMax !== undefined) {
|
||||
const value = parseUploadRateTokenMax(String(body.uploadRateTokenMax))
|
||||
if (value === null) {
|
||||
createApiError(event, 'INVALID_REQUEST', '上传 Token 限流次数无效', 400)
|
||||
}
|
||||
setUploadPolicySettings({ uploadRateTokenMax: value })
|
||||
}
|
||||
|
||||
if (body.uploadRateWindowMinutes !== undefined) {
|
||||
const value = parseUploadRateWindowMinutes(String(body.uploadRateWindowMinutes))
|
||||
if (value === null) {
|
||||
createApiError(event, 'INVALID_REQUEST', '上传限流窗口无效', 400)
|
||||
}
|
||||
setUploadPolicySettings({ uploadRateWindowMinutes: value })
|
||||
}
|
||||
|
||||
if (body.loginRateMax !== undefined) {
|
||||
const value = parseLoginRateMax(String(body.loginRateMax))
|
||||
if (value === null) {
|
||||
createApiError(event, 'INVALID_REQUEST', '登录限流次数无效', 400)
|
||||
}
|
||||
setUploadPolicySettings({ loginRateMax: value })
|
||||
}
|
||||
|
||||
if (body.loginRateWindowMinutes !== undefined) {
|
||||
const value = parseLoginRateWindowMinutes(String(body.loginRateWindowMinutes))
|
||||
if (value === null) {
|
||||
createApiError(event, 'INVALID_REQUEST', '登录限流窗口无效', 400)
|
||||
}
|
||||
setUploadPolicySettings({ loginRateWindowMinutes: value })
|
||||
}
|
||||
|
||||
if (body.preserveOriginalUpload !== undefined) {
|
||||
if (typeof body.preserveOriginalUpload !== 'boolean') {
|
||||
createApiError(event, 'INVALID_REQUEST', '保留原图设置无效', 400)
|
||||
}
|
||||
setUploadPolicySettings({ preserveOriginalUpload: body.preserveOriginalUpload })
|
||||
}
|
||||
|
||||
logActivity(event, {
|
||||
action: 'settings',
|
||||
key: 'settings/system',
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
SETTINGS_CAP_SECRET,
|
||||
isAllowRegistration
|
||||
} from './db'
|
||||
import { getUploadPolicySettingsPayload } from './upload-policy'
|
||||
|
||||
export function getRuntimeEnv(
|
||||
event: H3Event,
|
||||
@@ -694,6 +695,7 @@ export function getSettingsPayload(event: H3Event) {
|
||||
capApiEndpoint: getCapApiEndpointConfigured(event),
|
||||
capSecret: getCapSecret(event),
|
||||
appVersion,
|
||||
...getUploadPolicySettingsPayload(),
|
||||
env: {
|
||||
webpQuality,
|
||||
refererConfigured: allowedRefererHosts.length > 0,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { getStorageBackendRow } from './storage-backends'
|
||||
import { ALLOWED_MIME_TYPES } from './constants'
|
||||
import { getAllowedMimeTypesList } from './upload-policy'
|
||||
import { parseTagIdsParam, type TagFilterInput } from './tags'
|
||||
|
||||
export function readBackendIdQuery(
|
||||
@@ -15,7 +15,7 @@ export function readContentTypeQuery(
|
||||
): string | undefined | null {
|
||||
const raw = typeof query.contentType === 'string' ? query.contentType.trim() : ''
|
||||
if (!raw || raw === 'all') return undefined
|
||||
if (!(ALLOWED_MIME_TYPES as readonly string[]).includes(raw)) return null
|
||||
if (!(getAllowedMimeTypesList() as readonly string[]).includes(raw)) return null
|
||||
return raw
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { MultiPartData } from 'h3'
|
||||
|
||||
export function readMultipartFormFieldValues(
|
||||
formData: MultiPartData[],
|
||||
fieldName: string
|
||||
): string[] {
|
||||
const field = formData.find(part => part.name === fieldName)
|
||||
if (field?.data?.length) {
|
||||
const raw = new TextDecoder().decode(field.data).trim()
|
||||
if (!raw) return []
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed.map(item => String(item).trim()).filter(Boolean)
|
||||
}
|
||||
} catch {
|
||||
// fall through to comma-separated parsing
|
||||
}
|
||||
return raw.split(',').map(item => item.trim()).filter(Boolean)
|
||||
}
|
||||
|
||||
const repeatFields = formData.filter(
|
||||
part => part.name === fieldName && part.data?.length
|
||||
)
|
||||
if (!repeatFields.length) return []
|
||||
|
||||
return repeatFields
|
||||
.map(part => new TextDecoder().decode(part.data!).trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
@@ -2,10 +2,6 @@ import sharp from 'sharp'
|
||||
import type { H3Event } from 'h3'
|
||||
import type { ImageItem, UploadErrorItem } from '~/types/image'
|
||||
import type { AllowedMimeType } from './constants'
|
||||
import {
|
||||
ALLOWED_MIME_TYPES,
|
||||
MAX_FILE_SIZE
|
||||
} from './constants'
|
||||
import {
|
||||
detectMimeFromSignature,
|
||||
isAllowedMimeType,
|
||||
@@ -15,6 +11,12 @@ import type { LogSource } from './db'
|
||||
import { generateImageKey } from './image-key'
|
||||
import { buildImageItem, sanitizeOriginalName } from './image-response'
|
||||
import { getStorageLayout, getWebpQuality } from './env'
|
||||
import {
|
||||
formatMaxFileSizeMessage,
|
||||
getMaxFileSizeBytes,
|
||||
isMimeTypeAllowed,
|
||||
isPreserveOriginalUpload
|
||||
} from './upload-policy'
|
||||
import { logActivity } from './activity-log'
|
||||
import { attachTagsAfterUpload, getTagsForImageKeys } from './tags'
|
||||
import { putImage } from './storage'
|
||||
@@ -71,13 +73,13 @@ export async function processSingleImageUpload(
|
||||
const originalName = sanitizeOriginalName(input.filename ?? 'image')
|
||||
const bytes = input.bytes
|
||||
|
||||
if (bytes.byteLength > MAX_FILE_SIZE) {
|
||||
if (bytes.byteLength > getMaxFileSizeBytes()) {
|
||||
return {
|
||||
error: {
|
||||
name: originalName,
|
||||
error: {
|
||||
code: 'FILE_TOO_LARGE',
|
||||
message: '图片大小不能超过 10 MB'
|
||||
message: formatMaxFileSizeMessage()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,7 +98,7 @@ export async function processSingleImageUpload(
|
||||
}
|
||||
}
|
||||
|
||||
if (!ALLOWED_MIME_TYPES.includes(detectedMime)) {
|
||||
if (!isMimeTypeAllowed(detectedMime)) {
|
||||
return {
|
||||
error: {
|
||||
name: originalName,
|
||||
@@ -120,7 +122,9 @@ export async function processSingleImageUpload(
|
||||
}
|
||||
}
|
||||
|
||||
const compressed = await compressToWebp(bytes, detectedMime, getWebpQuality(event))
|
||||
const compressed = isPreserveOriginalUpload()
|
||||
? { bytes, mime: detectedMime }
|
||||
: await compressToWebp(bytes, detectedMime, getWebpQuality(event))
|
||||
|
||||
const uploadedAt = new Date().toISOString()
|
||||
const layout = getStorageLayout(event)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { checkUploadRateLimit } from './rate-limit'
|
||||
import { getUploadRateLimitSettings } from './upload-policy'
|
||||
|
||||
vi.mock('./logger', () => ({
|
||||
clientIp: (event: { __ip?: string }) => event.__ip ?? '127.0.0.1'
|
||||
@@ -27,7 +28,8 @@ describe('checkUploadRateLimit', () => {
|
||||
|
||||
it('limits repeated uploads by IP', () => {
|
||||
const event = mockEvent('10.0.0.3')
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const { ipMax } = getUploadRateLimitSettings()
|
||||
for (let i = 0; i < ipMax; i++) {
|
||||
checkUploadRateLimit(event)
|
||||
}
|
||||
expect(() => checkUploadRateLimit(event)).toThrow()
|
||||
@@ -35,7 +37,8 @@ describe('checkUploadRateLimit', () => {
|
||||
|
||||
it('limits repeated API token uploads', () => {
|
||||
const token = 'token-a'
|
||||
for (let i = 0; i < 120; i++) {
|
||||
const { tokenMax } = getUploadRateLimitSettings()
|
||||
for (let i = 0; i < tokenMax; i++) {
|
||||
checkUploadRateLimit(mockEvent(`10.0.${i % 200}`), token)
|
||||
}
|
||||
expect(() => checkUploadRateLimit(mockEvent('10.0.250'), token)).toThrow()
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { createError, getHeader, type H3Event } from 'h3'
|
||||
import { clientIp } from './logger'
|
||||
|
||||
const UPLOAD_IP_MAX = 60
|
||||
const UPLOAD_TOKEN_MAX = 120
|
||||
const UPLOAD_WINDOW_MS = 15 * 60 * 1000
|
||||
import { getUploadRateLimitSettings, getLoginRateLimitSettings } from './upload-policy'
|
||||
|
||||
const stores = new Map<string, Map<string, { count: number, resetAt: number }>>()
|
||||
|
||||
@@ -43,12 +40,13 @@ function assertRateLimit(
|
||||
}
|
||||
|
||||
export function checkUploadRateLimit(event: H3Event, apiToken?: string): void {
|
||||
const { ipMax, tokenMax, windowMs } = getUploadRateLimitSettings()
|
||||
const ip = clientIp(event)
|
||||
assertRateLimit(
|
||||
'upload-ip',
|
||||
ip,
|
||||
UPLOAD_IP_MAX,
|
||||
UPLOAD_WINDOW_MS,
|
||||
ipMax,
|
||||
windowMs,
|
||||
'上传过于频繁,请稍后再试'
|
||||
)
|
||||
|
||||
@@ -60,8 +58,27 @@ export function checkUploadRateLimit(event: H3Event, apiToken?: string): void {
|
||||
assertRateLimit(
|
||||
'upload-token',
|
||||
hash,
|
||||
UPLOAD_TOKEN_MAX,
|
||||
UPLOAD_WINDOW_MS,
|
||||
tokenMax,
|
||||
windowMs,
|
||||
'上传过于频繁,请稍后再试'
|
||||
)
|
||||
}
|
||||
|
||||
const loginAttempts = new Map<string, { count: number, resetAt: number }>()
|
||||
|
||||
export function checkLoginRateLimit(ip: string): void {
|
||||
const { max, windowMs } = getLoginRateLimitSettings()
|
||||
const now = Date.now()
|
||||
const entry = loginAttempts.get(ip)
|
||||
if (!entry || now > entry.resetAt) {
|
||||
loginAttempts.set(ip, { count: 1, resetAt: now + windowMs })
|
||||
return
|
||||
}
|
||||
entry.count += 1
|
||||
if (entry.count > max) {
|
||||
throw createError({
|
||||
statusCode: 429,
|
||||
statusMessage: '登录尝试过于频繁,请稍后再试'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import {
|
||||
isValidTagColor,
|
||||
isValidTagName,
|
||||
normalizeTagName,
|
||||
parseTagIdsParam
|
||||
parseTagIdsParam,
|
||||
parseTagNamesParam,
|
||||
resolveUploadTagIds
|
||||
} from './tags'
|
||||
|
||||
describe('normalizeTagName', () => {
|
||||
@@ -51,6 +53,33 @@ describe('parseTagIdsParam', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseTagNamesParam', () => {
|
||||
it('parses comma-separated and json array values', () => {
|
||||
expect(parseTagNamesParam('博客, 截图')).toEqual(['博客', '截图'])
|
||||
expect(parseTagNamesParam('["工作","截图"]')).toEqual(['工作', '截图'])
|
||||
expect(parseTagNamesParam(['A', 'B'])).toEqual(['A', 'B'])
|
||||
})
|
||||
|
||||
it('deduplicates normalized names', () => {
|
||||
expect(parseTagNamesParam('博客, 博客 ,截图')).toEqual(['博客', '截图'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveUploadTagIds', () => {
|
||||
it('returns empty when no tags requested', () => {
|
||||
expect(resolveUploadTagIds(1, [], [])).toEqual({ tagIds: [] })
|
||||
})
|
||||
|
||||
it('requires user when tags are requested', () => {
|
||||
expect(resolveUploadTagIds(null, [1], [])).toMatchObject({
|
||||
message: expect.stringContaining('API Token')
|
||||
})
|
||||
expect(resolveUploadTagIds(null, [], ['博客'])).toMatchObject({
|
||||
message: expect.stringContaining('API Token')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildTagFilterSql', () => {
|
||||
it('returns empty sql without filter', () => {
|
||||
const params: Array<string | number> = []
|
||||
|
||||
@@ -471,3 +471,91 @@ export function parseTagIdsParam(raw: unknown): number[] {
|
||||
}
|
||||
return [...new Set(ids)]
|
||||
}
|
||||
|
||||
export function parseTagNamesParam(raw: unknown): string[] {
|
||||
if (raw == null || raw === '') return []
|
||||
|
||||
let parts: string[]
|
||||
if (Array.isArray(raw)) {
|
||||
parts = raw.flatMap(item => String(item).split(','))
|
||||
} else {
|
||||
const str = String(raw).trim()
|
||||
if (str.startsWith('[')) {
|
||||
try {
|
||||
const parsed = JSON.parse(str) as unknown
|
||||
parts = Array.isArray(parsed)
|
||||
? parsed.map(item => String(item))
|
||||
: str.split(',')
|
||||
} catch {
|
||||
parts = str.split(',')
|
||||
}
|
||||
} else {
|
||||
parts = str.split(',')
|
||||
}
|
||||
}
|
||||
|
||||
const names: string[] = []
|
||||
for (const part of parts) {
|
||||
const normalized = normalizeTagName(part)
|
||||
if (normalized) names.push(normalized)
|
||||
}
|
||||
return [...new Set(names)]
|
||||
}
|
||||
|
||||
export function findOrCreateTagByName(userId: number, name: string): TagRow {
|
||||
const normalized = normalizeTagName(name)
|
||||
if (!isValidTagName(normalized)) {
|
||||
throw new Error('INVALID_TAG_NAME')
|
||||
}
|
||||
|
||||
const existing = findTagByName(userId, normalized)
|
||||
if (existing) return existing
|
||||
|
||||
const created = createTag(userId, normalized)
|
||||
const row = getTagById(created.id)
|
||||
if (!row) {
|
||||
throw new Error('TAG_CREATE_FAILED')
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
export function resolveTagIdsFromNames(userId: number, names: readonly string[]): number[] {
|
||||
const ids: number[] = []
|
||||
for (const name of names) {
|
||||
ids.push(findOrCreateTagByName(userId, name).id)
|
||||
}
|
||||
return [...new Set(ids)]
|
||||
}
|
||||
|
||||
export function resolveUploadTagIds(
|
||||
userId: number | null,
|
||||
tagIds: number[],
|
||||
tagNames: string[]
|
||||
): { tagIds: number[] } | { message: string } {
|
||||
if (!tagIds.length && !tagNames.length) {
|
||||
return { tagIds: [] }
|
||||
}
|
||||
|
||||
if (userId == null) {
|
||||
return {
|
||||
message: '打标签需要登录或使用绑定用户的 API Token'
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const fromNames = tagNames.length ? resolveTagIdsFromNames(userId, tagNames) : []
|
||||
return { tagIds: [...new Set([...tagIds, ...fromNames])] }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
switch (error.message) {
|
||||
case 'INVALID_TAG_NAME':
|
||||
return { message: '标签名称无效' }
|
||||
case 'TAG_LIMIT_REACHED':
|
||||
return { message: '标签数量已达上限' }
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
DEFAULT_UPLOAD_MAX_FILE_SIZE_MB,
|
||||
normalizeAllowedMimeTypes,
|
||||
parseLoginRateMax,
|
||||
parsePreserveOriginalUpload,
|
||||
parseUploadMaxFileSizeMb,
|
||||
parseUploadRateIpMax,
|
||||
serializeAllowedMimeTypes,
|
||||
serializePreserveOriginalUpload
|
||||
} from './upload-policy'
|
||||
|
||||
describe('upload-policy parsers', () => {
|
||||
it('parses upload max file size mb', () => {
|
||||
expect(parseUploadMaxFileSizeMb('10')).toBe(10)
|
||||
expect(parseUploadMaxFileSizeMb('0')).toBeNull()
|
||||
expect(parseUploadMaxFileSizeMb('101')).toBeNull()
|
||||
})
|
||||
|
||||
it('normalizes allowed mime types', () => {
|
||||
expect(normalizeAllowedMimeTypes('image/png, image/jpeg, image/png')).toEqual([
|
||||
'image/png',
|
||||
'image/jpeg'
|
||||
])
|
||||
expect(normalizeAllowedMimeTypes('image/bmp')).toEqual([])
|
||||
})
|
||||
|
||||
it('serializes allowed mime types in canonical order', () => {
|
||||
expect(serializeAllowedMimeTypes(['image/webp', 'image/jpeg'])).toBe('image/jpeg,image/webp')
|
||||
})
|
||||
|
||||
it('parses rate limit values', () => {
|
||||
expect(parseUploadRateIpMax('60')).toBe(60)
|
||||
expect(parseLoginRateMax('10')).toBe(10)
|
||||
expect(parseUploadRateIpMax('0')).toBeNull()
|
||||
})
|
||||
|
||||
it('defaults max file size mb constant matches legacy 10MB', () => {
|
||||
expect(DEFAULT_UPLOAD_MAX_FILE_SIZE_MB).toBe(10)
|
||||
})
|
||||
|
||||
it('parses preserve original upload flag', () => {
|
||||
expect(parsePreserveOriginalUpload('true')).toBe(true)
|
||||
expect(parsePreserveOriginalUpload('0')).toBe(false)
|
||||
expect(parsePreserveOriginalUpload('')).toBeNull()
|
||||
expect(serializePreserveOriginalUpload(true)).toBe('true')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,347 @@
|
||||
import {
|
||||
ALLOWED_MIME_TYPES,
|
||||
type AllowedMimeType
|
||||
} from './constants'
|
||||
import { getSetting, setSetting } from './db'
|
||||
|
||||
export const SETTINGS_UPLOAD_MAX_FILE_SIZE_MB = 'upload_max_file_size_mb'
|
||||
export const SETTINGS_ALLOWED_MIME_TYPES = 'allowed_mime_types'
|
||||
export const SETTINGS_UPLOAD_RATE_IP_MAX = 'upload_rate_ip_max'
|
||||
export const SETTINGS_UPLOAD_RATE_TOKEN_MAX = 'upload_rate_token_max'
|
||||
export const SETTINGS_UPLOAD_RATE_WINDOW_MINUTES = 'upload_rate_window_minutes'
|
||||
export const SETTINGS_LOGIN_RATE_MAX = 'login_rate_max'
|
||||
export const SETTINGS_LOGIN_RATE_WINDOW_MINUTES = 'login_rate_window_minutes'
|
||||
export const SETTINGS_PRESERVE_ORIGINAL_UPLOAD = 'preserve_original_upload'
|
||||
|
||||
export const DEFAULT_UPLOAD_MAX_FILE_SIZE_MB = 10
|
||||
export const MIN_UPLOAD_MAX_FILE_SIZE_MB = 1
|
||||
export const MAX_UPLOAD_MAX_FILE_SIZE_MB = 100
|
||||
|
||||
export const DEFAULT_UPLOAD_RATE_IP_MAX = 60
|
||||
export const DEFAULT_UPLOAD_RATE_TOKEN_MAX = 120
|
||||
export const DEFAULT_UPLOAD_RATE_WINDOW_MINUTES = 15
|
||||
export const MIN_UPLOAD_RATE_MAX = 1
|
||||
export const MAX_UPLOAD_RATE_IP_MAX = 1000
|
||||
export const MAX_UPLOAD_RATE_TOKEN_MAX = 5000
|
||||
export const MIN_RATE_WINDOW_MINUTES = 1
|
||||
export const MAX_RATE_WINDOW_MINUTES = 1440
|
||||
|
||||
export const DEFAULT_LOGIN_RATE_MAX = 10
|
||||
export const DEFAULT_LOGIN_RATE_WINDOW_MINUTES = 15
|
||||
export const MAX_LOGIN_RATE_MAX = 100
|
||||
|
||||
export const ALL_MIME_TYPE_OPTIONS = [
|
||||
{ mime: 'image/jpeg', label: 'JPEG' },
|
||||
{ mime: 'image/png', label: 'PNG' },
|
||||
{ mime: 'image/webp', label: 'WebP' },
|
||||
{ mime: 'image/gif', label: 'GIF' },
|
||||
{ mime: 'image/svg+xml', label: 'SVG' },
|
||||
{ mime: 'image/x-icon', label: 'ICO' }
|
||||
] as const satisfies ReadonlyArray<{ mime: AllowedMimeType, label: string }>
|
||||
|
||||
export type PolicySource = 'env' | 'db' | 'default'
|
||||
|
||||
function readEnv(name: string): string {
|
||||
try {
|
||||
return process.env[name]?.trim() ?? ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function parsePositiveInt(raw: string, min: number, max: number): number | null {
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed) return null
|
||||
const value = Number(trimmed)
|
||||
if (!Number.isFinite(value) || !Number.isInteger(value)) return null
|
||||
if (value < min || value > max) return null
|
||||
return value
|
||||
}
|
||||
|
||||
export function parseUploadMaxFileSizeMb(raw: string): number | null {
|
||||
return parsePositiveInt(raw, MIN_UPLOAD_MAX_FILE_SIZE_MB, MAX_UPLOAD_MAX_FILE_SIZE_MB)
|
||||
}
|
||||
|
||||
export function parseUploadRateIpMax(raw: string): number | null {
|
||||
return parsePositiveInt(raw, MIN_UPLOAD_RATE_MAX, MAX_UPLOAD_RATE_IP_MAX)
|
||||
}
|
||||
|
||||
export function parseUploadRateTokenMax(raw: string): number | null {
|
||||
return parsePositiveInt(raw, MIN_UPLOAD_RATE_MAX, MAX_UPLOAD_RATE_TOKEN_MAX)
|
||||
}
|
||||
|
||||
export function parseUploadRateWindowMinutes(raw: string): number | null {
|
||||
return parsePositiveInt(raw, MIN_RATE_WINDOW_MINUTES, MAX_RATE_WINDOW_MINUTES)
|
||||
}
|
||||
|
||||
export function parseLoginRateMax(raw: string): number | null {
|
||||
return parsePositiveInt(raw, MIN_UPLOAD_RATE_MAX, MAX_LOGIN_RATE_MAX)
|
||||
}
|
||||
|
||||
export function parseLoginRateWindowMinutes(raw: string): number | null {
|
||||
return parsePositiveInt(raw, MIN_RATE_WINDOW_MINUTES, MAX_RATE_WINDOW_MINUTES)
|
||||
}
|
||||
|
||||
export function parsePreserveOriginalUpload(raw: string): boolean | null {
|
||||
const trimmed = raw.trim().toLowerCase()
|
||||
if (!trimmed) return null
|
||||
if (trimmed === 'true' || trimmed === '1' || trimmed === 'yes') return true
|
||||
if (trimmed === 'false' || trimmed === '0' || trimmed === 'no') return false
|
||||
return null
|
||||
}
|
||||
|
||||
export function serializePreserveOriginalUpload(value: boolean): string {
|
||||
return value ? 'true' : 'false'
|
||||
}
|
||||
|
||||
export function normalizeAllowedMimeTypes(raw: string): AllowedMimeType[] {
|
||||
const allowedSet = new Set<string>(ALLOWED_MIME_TYPES)
|
||||
const seen = new Set<string>()
|
||||
const result: AllowedMimeType[] = []
|
||||
|
||||
for (const part of raw.split(',')) {
|
||||
const mime = part.trim().toLowerCase()
|
||||
if (!mime || seen.has(mime) || !allowedSet.has(mime)) continue
|
||||
seen.add(mime)
|
||||
result.push(mime as AllowedMimeType)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
export function serializeAllowedMimeTypes(mimes: readonly string[]): string {
|
||||
const normalized = new Set(normalizeAllowedMimeTypes(mimes.join(',')))
|
||||
return ALL_MIME_TYPE_OPTIONS
|
||||
.map(option => option.mime)
|
||||
.filter(mime => normalized.has(mime))
|
||||
.join(',')
|
||||
}
|
||||
|
||||
function getUploadMaxFileSizeMbSource(): PolicySource {
|
||||
if (getSetting(SETTINGS_UPLOAD_MAX_FILE_SIZE_MB) !== null) return 'db'
|
||||
if (parseUploadMaxFileSizeMb(readEnv('UPLOAD_MAX_FILE_SIZE_MB')) !== null) return 'env'
|
||||
return 'default'
|
||||
}
|
||||
|
||||
function getAllowedMimeTypesSource(): PolicySource {
|
||||
if (getSetting(SETTINGS_ALLOWED_MIME_TYPES) !== null) return 'db'
|
||||
if (normalizeAllowedMimeTypes(readEnv('ALLOWED_MIME_TYPES')).length > 0) return 'env'
|
||||
return 'default'
|
||||
}
|
||||
|
||||
function getUploadRateIpMaxSource(): PolicySource {
|
||||
if (getSetting(SETTINGS_UPLOAD_RATE_IP_MAX) !== null) return 'db'
|
||||
if (parseUploadRateIpMax(readEnv('UPLOAD_RATE_IP_MAX')) !== null) return 'env'
|
||||
return 'default'
|
||||
}
|
||||
|
||||
function getUploadRateTokenMaxSource(): PolicySource {
|
||||
if (getSetting(SETTINGS_UPLOAD_RATE_TOKEN_MAX) !== null) return 'db'
|
||||
if (parseUploadRateTokenMax(readEnv('UPLOAD_RATE_TOKEN_MAX')) !== null) return 'env'
|
||||
return 'default'
|
||||
}
|
||||
|
||||
function getUploadRateWindowMinutesSource(): PolicySource {
|
||||
if (getSetting(SETTINGS_UPLOAD_RATE_WINDOW_MINUTES) !== null) return 'db'
|
||||
if (parseUploadRateWindowMinutes(readEnv('UPLOAD_RATE_WINDOW_MINUTES')) !== null) return 'env'
|
||||
return 'default'
|
||||
}
|
||||
|
||||
function getLoginRateMaxSource(): PolicySource {
|
||||
if (getSetting(SETTINGS_LOGIN_RATE_MAX) !== null) return 'db'
|
||||
if (parseLoginRateMax(readEnv('LOGIN_RATE_MAX')) !== null) return 'env'
|
||||
return 'default'
|
||||
}
|
||||
|
||||
function getLoginRateWindowMinutesSource(): PolicySource {
|
||||
if (getSetting(SETTINGS_LOGIN_RATE_WINDOW_MINUTES) !== null) return 'db'
|
||||
if (parseLoginRateWindowMinutes(readEnv('LOGIN_RATE_WINDOW_MINUTES')) !== null) return 'env'
|
||||
return 'default'
|
||||
}
|
||||
|
||||
function getPreserveOriginalUploadSource(): PolicySource {
|
||||
if (getSetting(SETTINGS_PRESERVE_ORIGINAL_UPLOAD) !== null) return 'db'
|
||||
if (parsePreserveOriginalUpload(readEnv('PRESERVE_ORIGINAL_UPLOAD')) !== null) return 'env'
|
||||
return 'default'
|
||||
}
|
||||
|
||||
export function getUploadMaxFileSizeMb(): number {
|
||||
const dbRaw = getSetting(SETTINGS_UPLOAD_MAX_FILE_SIZE_MB)
|
||||
if (dbRaw !== null) {
|
||||
const parsed = parseUploadMaxFileSizeMb(dbRaw)
|
||||
if (parsed !== null) return parsed
|
||||
}
|
||||
const fromEnv = parseUploadMaxFileSizeMb(readEnv('UPLOAD_MAX_FILE_SIZE_MB'))
|
||||
if (fromEnv !== null) return fromEnv
|
||||
return DEFAULT_UPLOAD_MAX_FILE_SIZE_MB
|
||||
}
|
||||
|
||||
export function getMaxFileSizeBytes(): number {
|
||||
return getUploadMaxFileSizeMb() * 1024 * 1024
|
||||
}
|
||||
|
||||
export function getAllowedMimeTypesList(): AllowedMimeType[] {
|
||||
const dbRaw = getSetting(SETTINGS_ALLOWED_MIME_TYPES)
|
||||
if (dbRaw !== null) {
|
||||
const parsed = normalizeAllowedMimeTypes(dbRaw)
|
||||
if (parsed.length > 0) return parsed
|
||||
}
|
||||
const fromEnv = normalizeAllowedMimeTypes(readEnv('ALLOWED_MIME_TYPES'))
|
||||
if (fromEnv.length > 0) return fromEnv
|
||||
return [...ALLOWED_MIME_TYPES]
|
||||
}
|
||||
|
||||
export function isMimeTypeAllowed(mime: string): mime is AllowedMimeType {
|
||||
return getAllowedMimeTypesList().includes(mime as AllowedMimeType)
|
||||
}
|
||||
|
||||
export function isPreserveOriginalUpload(): boolean {
|
||||
const dbRaw = getSetting(SETTINGS_PRESERVE_ORIGINAL_UPLOAD)
|
||||
if (dbRaw !== null) {
|
||||
const parsed = parsePreserveOriginalUpload(dbRaw)
|
||||
if (parsed !== null) return parsed
|
||||
}
|
||||
const fromEnv = parsePreserveOriginalUpload(readEnv('PRESERVE_ORIGINAL_UPLOAD'))
|
||||
if (fromEnv !== null) return fromEnv
|
||||
return false
|
||||
}
|
||||
|
||||
export function getUploadRateLimitSettings(): {
|
||||
ipMax: number
|
||||
tokenMax: number
|
||||
windowMs: number
|
||||
} {
|
||||
const ipMax = (() => {
|
||||
const dbRaw = getSetting(SETTINGS_UPLOAD_RATE_IP_MAX)
|
||||
if (dbRaw !== null) {
|
||||
const parsed = parseUploadRateIpMax(dbRaw)
|
||||
if (parsed !== null) return parsed
|
||||
}
|
||||
return parseUploadRateIpMax(readEnv('UPLOAD_RATE_IP_MAX')) ?? DEFAULT_UPLOAD_RATE_IP_MAX
|
||||
})()
|
||||
|
||||
const tokenMax = (() => {
|
||||
const dbRaw = getSetting(SETTINGS_UPLOAD_RATE_TOKEN_MAX)
|
||||
if (dbRaw !== null) {
|
||||
const parsed = parseUploadRateTokenMax(dbRaw)
|
||||
if (parsed !== null) return parsed
|
||||
}
|
||||
return parseUploadRateTokenMax(readEnv('UPLOAD_RATE_TOKEN_MAX')) ?? DEFAULT_UPLOAD_RATE_TOKEN_MAX
|
||||
})()
|
||||
|
||||
const windowMinutes = (() => {
|
||||
const dbRaw = getSetting(SETTINGS_UPLOAD_RATE_WINDOW_MINUTES)
|
||||
if (dbRaw !== null) {
|
||||
const parsed = parseUploadRateWindowMinutes(dbRaw)
|
||||
if (parsed !== null) return parsed
|
||||
}
|
||||
return parseUploadRateWindowMinutes(readEnv('UPLOAD_RATE_WINDOW_MINUTES'))
|
||||
?? DEFAULT_UPLOAD_RATE_WINDOW_MINUTES
|
||||
})()
|
||||
|
||||
return {
|
||||
ipMax,
|
||||
tokenMax,
|
||||
windowMs: windowMinutes * 60 * 1000
|
||||
}
|
||||
}
|
||||
|
||||
export function getLoginRateLimitSettings(): {
|
||||
max: number
|
||||
windowMs: number
|
||||
} {
|
||||
const max = (() => {
|
||||
const dbRaw = getSetting(SETTINGS_LOGIN_RATE_MAX)
|
||||
if (dbRaw !== null) {
|
||||
const parsed = parseLoginRateMax(dbRaw)
|
||||
if (parsed !== null) return parsed
|
||||
}
|
||||
return parseLoginRateMax(readEnv('LOGIN_RATE_MAX')) ?? DEFAULT_LOGIN_RATE_MAX
|
||||
})()
|
||||
|
||||
const windowMinutes = (() => {
|
||||
const dbRaw = getSetting(SETTINGS_LOGIN_RATE_WINDOW_MINUTES)
|
||||
if (dbRaw !== null) {
|
||||
const parsed = parseLoginRateWindowMinutes(dbRaw)
|
||||
if (parsed !== null) return parsed
|
||||
}
|
||||
return parseLoginRateWindowMinutes(readEnv('LOGIN_RATE_WINDOW_MINUTES'))
|
||||
?? DEFAULT_LOGIN_RATE_WINDOW_MINUTES
|
||||
})()
|
||||
|
||||
return {
|
||||
max,
|
||||
windowMs: windowMinutes * 60 * 1000
|
||||
}
|
||||
}
|
||||
|
||||
export function formatMaxFileSizeMessage(): string {
|
||||
return `图片大小不能超过 ${getUploadMaxFileSizeMb()} MB`
|
||||
}
|
||||
|
||||
export function getUploadPolicySettingsPayload() {
|
||||
return {
|
||||
uploadMaxFileSizeMb: getUploadMaxFileSizeMb(),
|
||||
uploadMaxFileSizeMbSource: getUploadMaxFileSizeMbSource(),
|
||||
uploadMaxFileSizeMbEnvFallback: parseUploadMaxFileSizeMb(readEnv('UPLOAD_MAX_FILE_SIZE_MB'))
|
||||
?? DEFAULT_UPLOAD_MAX_FILE_SIZE_MB,
|
||||
allowedMimeTypes: getAllowedMimeTypesList(),
|
||||
allowedMimeTypesSource: getAllowedMimeTypesSource(),
|
||||
allowedMimeTypesEnvFallback: normalizeAllowedMimeTypes(readEnv('ALLOWED_MIME_TYPES')),
|
||||
uploadRateIpMax: getUploadRateLimitSettings().ipMax,
|
||||
uploadRateIpMaxSource: getUploadRateIpMaxSource(),
|
||||
uploadRateTokenMax: getUploadRateLimitSettings().tokenMax,
|
||||
uploadRateTokenMaxSource: getUploadRateTokenMaxSource(),
|
||||
uploadRateWindowMinutes: getUploadRateLimitSettings().windowMs / (60 * 1000),
|
||||
uploadRateWindowMinutesSource: getUploadRateWindowMinutesSource(),
|
||||
loginRateMax: getLoginRateLimitSettings().max,
|
||||
loginRateMaxSource: getLoginRateMaxSource(),
|
||||
loginRateWindowMinutes: getLoginRateLimitSettings().windowMs / (60 * 1000),
|
||||
loginRateWindowMinutesSource: getLoginRateWindowMinutesSource(),
|
||||
preserveOriginalUpload: isPreserveOriginalUpload(),
|
||||
preserveOriginalUploadSource: getPreserveOriginalUploadSource(),
|
||||
mimeTypeOptions: ALL_MIME_TYPE_OPTIONS.map(option => ({
|
||||
mime: option.mime,
|
||||
label: option.label
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
export function setUploadPolicySettings(input: {
|
||||
uploadMaxFileSizeMb?: number
|
||||
allowedMimeTypes?: readonly string[]
|
||||
uploadRateIpMax?: number
|
||||
uploadRateTokenMax?: number
|
||||
uploadRateWindowMinutes?: number
|
||||
loginRateMax?: number
|
||||
loginRateWindowMinutes?: number
|
||||
preserveOriginalUpload?: boolean
|
||||
}): void {
|
||||
if (input.uploadMaxFileSizeMb !== undefined) {
|
||||
setSetting(SETTINGS_UPLOAD_MAX_FILE_SIZE_MB, String(input.uploadMaxFileSizeMb))
|
||||
}
|
||||
if (input.allowedMimeTypes !== undefined) {
|
||||
setSetting(SETTINGS_ALLOWED_MIME_TYPES, serializeAllowedMimeTypes(input.allowedMimeTypes))
|
||||
}
|
||||
if (input.uploadRateIpMax !== undefined) {
|
||||
setSetting(SETTINGS_UPLOAD_RATE_IP_MAX, String(input.uploadRateIpMax))
|
||||
}
|
||||
if (input.uploadRateTokenMax !== undefined) {
|
||||
setSetting(SETTINGS_UPLOAD_RATE_TOKEN_MAX, String(input.uploadRateTokenMax))
|
||||
}
|
||||
if (input.uploadRateWindowMinutes !== undefined) {
|
||||
setSetting(SETTINGS_UPLOAD_RATE_WINDOW_MINUTES, String(input.uploadRateWindowMinutes))
|
||||
}
|
||||
if (input.loginRateMax !== undefined) {
|
||||
setSetting(SETTINGS_LOGIN_RATE_MAX, String(input.loginRateMax))
|
||||
}
|
||||
if (input.loginRateWindowMinutes !== undefined) {
|
||||
setSetting(SETTINGS_LOGIN_RATE_WINDOW_MINUTES, String(input.loginRateWindowMinutes))
|
||||
}
|
||||
if (input.preserveOriginalUpload !== undefined) {
|
||||
setSetting(
|
||||
SETTINGS_PRESERVE_ORIGINAL_UPLOAD,
|
||||
serializePreserveOriginalUpload(input.preserveOriginalUpload)
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user