mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-06 23:56:37 +08:00
feat(frontend): add origin error page settings under websites
This commit is contained in:
@@ -0,0 +1,411 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import {
|
||||||
|
ExternalLink,
|
||||||
|
FileWarning,
|
||||||
|
Loader2,
|
||||||
|
RotateCcw,
|
||||||
|
Save,
|
||||||
|
Sparkles,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
import { useAuth } from '@/components/providers/auth-provider';
|
||||||
|
import { EmptyStateWithBorder } from '@/components/layout/empty';
|
||||||
|
import { ErrorInline } from '@/components/layout/error';
|
||||||
|
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from '@/components/ui/alert-dialog';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from '@/components/ui/card';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import { TagsInput } from '@/components/ui/tags-input';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import {
|
||||||
|
DEFAULT_ORIGIN_ERROR_PAGE_HTML,
|
||||||
|
ORIGIN_ERROR_PAGE_HTML_MAX_BYTES,
|
||||||
|
previewOriginErrorPageHTML,
|
||||||
|
} from '@/lib/openflare/default-origin-error-page-html';
|
||||||
|
import {
|
||||||
|
DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS,
|
||||||
|
parseStatusCodeTagsJSON,
|
||||||
|
validateStatusCodeTagMessage,
|
||||||
|
validateStatusCodeTags,
|
||||||
|
} from '@/lib/openflare/status-code-tags';
|
||||||
|
import { OptionService } from '@/lib/services/openflare';
|
||||||
|
|
||||||
|
const optionsQueryKey = ['openflare', 'options'] as const;
|
||||||
|
|
||||||
|
const KEY_ENABLED = 'origin_error_page_enabled';
|
||||||
|
const KEY_STATUS_CODES = 'origin_error_page_status_codes';
|
||||||
|
const KEY_HTML = 'origin_error_page_html';
|
||||||
|
|
||||||
|
type ErrorPageFields = {
|
||||||
|
enabled: boolean;
|
||||||
|
statusCodes: string[];
|
||||||
|
html: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultFields: ErrorPageFields = {
|
||||||
|
enabled: true,
|
||||||
|
statusCodes: [...DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS],
|
||||||
|
html: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
function optionsToMap(options: Array<{ key: string; value: string }>) {
|
||||||
|
return options.reduce<Record<string, string>>((acc, option) => {
|
||||||
|
acc[option.key] = option.value;
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapOptionsToFields(
|
||||||
|
optionMap: Record<string, string>,
|
||||||
|
): ErrorPageFields {
|
||||||
|
const enabledRaw = optionMap[KEY_ENABLED];
|
||||||
|
return {
|
||||||
|
enabled: enabledRaw === undefined ? true : enabledRaw === 'true',
|
||||||
|
statusCodes: parseStatusCodeTagsJSON(optionMap[KEY_STATUS_CODES]),
|
||||||
|
html: optionMap[KEY_HTML] ?? '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateFields(fields: ErrorPageFields) {
|
||||||
|
validateStatusCodeTags(fields.statusCodes);
|
||||||
|
|
||||||
|
const htmlBytes = new TextEncoder().encode(fields.html).length;
|
||||||
|
if (htmlBytes > ORIGIN_ERROR_PAGE_HTML_MAX_BYTES) {
|
||||||
|
throw new Error(
|
||||||
|
`HTML 超过最大长度限制(${ORIGIN_ERROR_PAGE_HTML_MAX_BYTES} 字节)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ErrorPagesPage() {
|
||||||
|
const { user, loading: authLoading } = useAuth();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [fields, setFields] = useState<ErrorPageFields>(defaultFields);
|
||||||
|
const [restoreOpen, setRestoreOpen] = useState(false);
|
||||||
|
const [tagError, setTagError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const optionsQuery = useQuery({
|
||||||
|
queryKey: optionsQueryKey,
|
||||||
|
queryFn: () => OptionService.list(),
|
||||||
|
enabled: !!user?.is_admin,
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!optionsQuery.data) return;
|
||||||
|
setFields(mapOptionsToFields(optionsToMap(optionsQuery.data)));
|
||||||
|
setTagError(null);
|
||||||
|
}, [optionsQuery.data]);
|
||||||
|
|
||||||
|
const previewSrcDoc = useMemo(
|
||||||
|
() => previewOriginErrorPageHTML(fields.html),
|
||||||
|
[fields.html],
|
||||||
|
);
|
||||||
|
|
||||||
|
const saveMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
validateFields(fields);
|
||||||
|
await OptionService.updateBatch([
|
||||||
|
{ key: KEY_ENABLED, value: String(fields.enabled) },
|
||||||
|
{
|
||||||
|
key: KEY_STATUS_CODES,
|
||||||
|
value: JSON.stringify(fields.statusCodes),
|
||||||
|
},
|
||||||
|
{ key: KEY_HTML, value: fields.html },
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
onSuccess: async () => {
|
||||||
|
toast.success('源站错误页已保存,请前往版本发布使配置生效');
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({ queryKey: optionsQueryKey }),
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ['openflare', 'config-preview'],
|
||||||
|
}),
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ['openflare', 'config-versions'],
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
toast.error(error instanceof Error ? error.message : '保存失败');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleStatusCodesChange = (statusCodes: string[]) => {
|
||||||
|
setFields((prev) => ({ ...prev, statusCodes }));
|
||||||
|
setTagError(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleValidateTag = (tag: string) => {
|
||||||
|
const message = validateStatusCodeTagMessage(tag);
|
||||||
|
if (message) {
|
||||||
|
setTagError(message);
|
||||||
|
toast.error(message);
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
setTagError(null);
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadDefaultTemplate = () => {
|
||||||
|
setFields((prev) => ({
|
||||||
|
...prev,
|
||||||
|
html: DEFAULT_ORIGIN_ERROR_PAGE_HTML,
|
||||||
|
}));
|
||||||
|
toast.success('已加载默认 HTML 模板到编辑器');
|
||||||
|
};
|
||||||
|
|
||||||
|
const restoreDefault = () => {
|
||||||
|
setFields((prev) => ({
|
||||||
|
...prev,
|
||||||
|
html: '',
|
||||||
|
statusCodes: [...DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS],
|
||||||
|
}));
|
||||||
|
setRestoreOpen(false);
|
||||||
|
setTagError(null);
|
||||||
|
toast.success('已恢复默认:状态码 500-599,HTML 使用服务端内置模板');
|
||||||
|
};
|
||||||
|
|
||||||
|
if (authLoading) {
|
||||||
|
return (
|
||||||
|
<div className='py-6 px-1'>
|
||||||
|
<LoadingStateWithBorder
|
||||||
|
icon={FileWarning}
|
||||||
|
description='加载权限信息...'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user?.is_admin) {
|
||||||
|
return (
|
||||||
|
<div className='py-6 px-1'>
|
||||||
|
<EmptyStateWithBorder
|
||||||
|
icon={FileWarning}
|
||||||
|
title='权限不足'
|
||||||
|
description='只有管理员可以访问源站错误页设置。'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (optionsQuery.isLoading) {
|
||||||
|
return (
|
||||||
|
<div className='py-6 px-1'>
|
||||||
|
<LoadingStateWithBorder
|
||||||
|
icon={FileWarning}
|
||||||
|
description='加载错误页配置...'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (optionsQuery.isError) {
|
||||||
|
return (
|
||||||
|
<div className='py-6 px-1'>
|
||||||
|
<ErrorInline
|
||||||
|
message={
|
||||||
|
optionsQuery.error instanceof Error
|
||||||
|
? optionsQuery.error.message
|
||||||
|
: '加载失败'
|
||||||
|
}
|
||||||
|
onRetry={() => void optionsQuery.refetch()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='flex flex-col gap-6 py-6 px-1'>
|
||||||
|
<div className='flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<FileWarning className='size-5 text-primary' />
|
||||||
|
<div>
|
||||||
|
<h1 className='text-2xl font-semibold tracking-tight'>错误页</h1>
|
||||||
|
<p className='text-sm text-muted-foreground'>
|
||||||
|
配置源站/网关错误响应时的统一 HTML
|
||||||
|
页面。保存后需发布配置版本后生效。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-wrap gap-2'>
|
||||||
|
<Button variant='outline' size='sm' asChild>
|
||||||
|
<Link href='/config-versions'>
|
||||||
|
<ExternalLink className='size-3.5' />
|
||||||
|
查看配置预览
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size='sm'
|
||||||
|
disabled={saveMutation.isPending}
|
||||||
|
onClick={() => saveMutation.mutate()}
|
||||||
|
>
|
||||||
|
{saveMutation.isPending ? (
|
||||||
|
<Loader2 className='size-3.5 animate-spin' />
|
||||||
|
) : (
|
||||||
|
<Save className='size-3.5' />
|
||||||
|
)}
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card className='border-dashed shadow-none'>
|
||||||
|
<CardHeader className='flex flex-row items-center justify-between gap-4'>
|
||||||
|
<div>
|
||||||
|
<CardTitle className='text-base'>启用源站错误页</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
关闭后透传源站或 Nginx 默认错误响应,不注入 error_page 指令。
|
||||||
|
</CardDescription>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={fields.enabled}
|
||||||
|
onCheckedChange={(enabled) =>
|
||||||
|
setFields((prev) => ({ ...prev, enabled }))
|
||||||
|
}
|
||||||
|
aria-label='启用源站错误页'
|
||||||
|
/>
|
||||||
|
</CardHeader>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card className='border-dashed shadow-none'>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className='text-base'>触发状态码</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
支持单码(如 502)或闭区间(如 500-599),范围 400–599。默认
|
||||||
|
500-599。
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className='flex flex-col gap-2'>
|
||||||
|
<Label htmlFor='origin-error-status-codes' className='sr-only'>
|
||||||
|
状态码标签
|
||||||
|
</Label>
|
||||||
|
<TagsInput
|
||||||
|
id='origin-error-status-codes'
|
||||||
|
value={fields.statusCodes}
|
||||||
|
onChange={handleStatusCodesChange}
|
||||||
|
validateTag={handleValidateTag}
|
||||||
|
placeholder='例如 502 或 500-599,回车添加'
|
||||||
|
aria-invalid={!!tagError}
|
||||||
|
/>
|
||||||
|
{tagError ? (
|
||||||
|
<p className='text-xs text-destructive'>{tagError}</p>
|
||||||
|
) : (
|
||||||
|
<p className='text-xs text-muted-foreground'>
|
||||||
|
输入后按 Enter 或逗号添加;Backspace 可删除最后一个标签。
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<div className='grid gap-6 xl:grid-cols-2'>
|
||||||
|
<Card className='border-dashed shadow-none'>
|
||||||
|
<CardHeader className='flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between'>
|
||||||
|
<div>
|
||||||
|
<CardTitle className='text-base'>HTML 模板</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
支持占位符 {'{{status}}'} 与 {'{{host}}'}
|
||||||
|
。留空则使用服务端内置默认页。
|
||||||
|
</CardDescription>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-wrap gap-2'>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='outline'
|
||||||
|
size='sm'
|
||||||
|
onClick={loadDefaultTemplate}
|
||||||
|
>
|
||||||
|
<Sparkles className='size-3.5' />
|
||||||
|
加载默认模板
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='outline'
|
||||||
|
size='sm'
|
||||||
|
onClick={() => setRestoreOpen(true)}
|
||||||
|
>
|
||||||
|
<RotateCcw className='size-3.5' />
|
||||||
|
恢复默认
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Textarea
|
||||||
|
id='origin-error-html'
|
||||||
|
value={fields.html}
|
||||||
|
onChange={(event) =>
|
||||||
|
setFields((prev) => ({ ...prev, html: event.target.value }))
|
||||||
|
}
|
||||||
|
placeholder='留空使用内置默认模板…'
|
||||||
|
className='min-h-[28rem] font-mono text-xs leading-relaxed'
|
||||||
|
spellCheck={false}
|
||||||
|
/>
|
||||||
|
<p className='mt-2 text-xs text-muted-foreground'>
|
||||||
|
当前 {new TextEncoder().encode(fields.html).length} /{' '}
|
||||||
|
{ORIGIN_ERROR_PAGE_HTML_MAX_BYTES} 字节
|
||||||
|
{fields.html.trim() === '' ? '(使用内置默认)' : ''}
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card className='border-dashed shadow-none'>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className='text-base'>预览</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
客户端预览:{'{{status}}'}→502,{'{{host}}'}→example.com
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className='overflow-hidden rounded-md border bg-muted/30'>
|
||||||
|
<iframe
|
||||||
|
title='源站错误页预览'
|
||||||
|
sandbox=''
|
||||||
|
srcDoc={previewSrcDoc}
|
||||||
|
className='h-[32rem] w-full bg-background'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AlertDialog open={restoreOpen} onOpenChange={setRestoreOpen}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>恢复默认配置?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
将状态码重置为 500-599,并将 HTML
|
||||||
|
清空为「使用服务端内置默认模板」。此操作不会自动保存,仍需点击保存并发布配置版本。
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||||
|
<AlertDialogAction onClick={restoreDefault}>
|
||||||
|
确认恢复
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import * as React from 'react';
|
||||||
|
import { X } from 'lucide-react';
|
||||||
|
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
export type TagsInputProps = {
|
||||||
|
value: string[];
|
||||||
|
onChange: (value: string[]) => void;
|
||||||
|
placeholder?: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
className?: string;
|
||||||
|
id?: string;
|
||||||
|
/** Called when a tag fails a custom validator; return true if accepted. */
|
||||||
|
validateTag?: (tag: string) => string | null;
|
||||||
|
'aria-invalid'?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
function normalizeTag(raw: string) {
|
||||||
|
return raw.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function TagsInput({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
placeholder = '输入后按 Enter 添加',
|
||||||
|
disabled = false,
|
||||||
|
className,
|
||||||
|
id,
|
||||||
|
validateTag,
|
||||||
|
'aria-invalid': ariaInvalid,
|
||||||
|
}: TagsInputProps) {
|
||||||
|
const [draft, setDraft] = React.useState('');
|
||||||
|
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const commit = (raw: string) => {
|
||||||
|
const tag = normalizeTag(raw);
|
||||||
|
if (!tag) {
|
||||||
|
setDraft('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (validateTag) {
|
||||||
|
const error = validateTag(tag);
|
||||||
|
if (error) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.includes(tag)) {
|
||||||
|
setDraft('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
onChange([...value, tag]);
|
||||||
|
setDraft('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeAt = (index: number) => {
|
||||||
|
onChange(value.filter((_, i) => i !== index));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (disabled) return;
|
||||||
|
|
||||||
|
if (event.key === 'Enter' || event.key === ',' || event.key === 'Tab') {
|
||||||
|
if (draft.trim()) {
|
||||||
|
event.preventDefault();
|
||||||
|
commit(draft);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event.key === 'Backspace' && !draft && value.length > 0) {
|
||||||
|
event.preventDefault();
|
||||||
|
removeAt(value.length - 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePaste = (event: React.ClipboardEvent<HTMLInputElement>) => {
|
||||||
|
const text = event.clipboardData.getData('text');
|
||||||
|
if (!text || (!text.includes(',') && !text.includes('\n'))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
const parts = text
|
||||||
|
.split(/[,\n]+/)
|
||||||
|
.map(normalizeTag)
|
||||||
|
.filter(Boolean);
|
||||||
|
if (parts.length === 0) return;
|
||||||
|
|
||||||
|
const next = [...value];
|
||||||
|
for (const part of parts) {
|
||||||
|
if (validateTag) {
|
||||||
|
const error = validateTag(part);
|
||||||
|
if (error) continue;
|
||||||
|
}
|
||||||
|
if (!next.includes(part)) {
|
||||||
|
next.push(part);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onChange(next);
|
||||||
|
setDraft('');
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot='tags-input'
|
||||||
|
className={cn(
|
||||||
|
'border-input dark:bg-input/30 flex min-h-8 w-full flex-wrap items-center gap-1.5 rounded-md border bg-transparent px-2 py-1 text-xs transition-[color,box-shadow] outline-none',
|
||||||
|
'focus-within:border-ring focus-within:ring-ring/30 focus-within:ring-[2px]',
|
||||||
|
ariaInvalid &&
|
||||||
|
'ring-destructive/20 dark:ring-destructive/40 border-destructive',
|
||||||
|
disabled && 'pointer-events-none cursor-not-allowed opacity-50',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
onClick={() => inputRef.current?.focus()}
|
||||||
|
>
|
||||||
|
{value.map((tag, index) => (
|
||||||
|
<Badge
|
||||||
|
key={`${tag}-${index}`}
|
||||||
|
variant='secondary'
|
||||||
|
className='gap-1 pr-1 font-normal'
|
||||||
|
>
|
||||||
|
<span className='max-w-[12rem] truncate'>{tag}</span>
|
||||||
|
<button
|
||||||
|
type='button'
|
||||||
|
className='hover:bg-muted rounded-sm p-0.5 outline-none focus-visible:ring-1 focus-visible:ring-ring'
|
||||||
|
aria-label={`移除 ${tag}`}
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
removeAt(index);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<X className='size-3' />
|
||||||
|
</button>
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
id={id}
|
||||||
|
value={draft}
|
||||||
|
disabled={disabled}
|
||||||
|
aria-invalid={ariaInvalid}
|
||||||
|
placeholder={value.length === 0 ? placeholder : undefined}
|
||||||
|
className='placeholder:text-muted-foreground min-w-[8rem] flex-1 bg-transparent py-0.5 text-xs outline-none'
|
||||||
|
onChange={(event) => setDraft(event.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
onPaste={handlePaste}
|
||||||
|
onBlur={() => {
|
||||||
|
if (draft.trim()) {
|
||||||
|
commit(draft);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { TagsInput };
|
||||||
@@ -60,6 +60,7 @@ export const openflareWebsiteNavGroup: OpenFlareNavGroup = {
|
|||||||
childUrls: ['/cloudflare/settings'],
|
childUrls: ['/cloudflare/settings'],
|
||||||
},
|
},
|
||||||
{ title: '源站地址', url: '/origins', childUrls: ['/origins/detail'] },
|
{ title: '源站地址', url: '/origins', childUrls: ['/origins/detail'] },
|
||||||
|
{ title: '错误页', url: '/error-pages' },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -115,6 +116,7 @@ export const openflareWebsiteSubNav = [
|
|||||||
{ title: '证书', url: '/certificates' },
|
{ title: '证书', url: '/certificates' },
|
||||||
{ title: 'DNS 账号', url: '/dns-accounts' },
|
{ title: 'DNS 账号', url: '/dns-accounts' },
|
||||||
{ title: 'Cloudflare', url: '/cloudflare' },
|
{ title: 'Cloudflare', url: '/cloudflare' },
|
||||||
|
{ title: '错误页', url: '/error-pages' },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
const nonConsoleRoutePrefixes = [
|
const nonConsoleRoutePrefixes = [
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
/**
|
||||||
|
* Built-in Cloudflare-style origin error page.
|
||||||
|
* Keep in sync with Go DefaultOriginErrorPageHTML in
|
||||||
|
* pkg/render/openresty/origin_error_page.go
|
||||||
|
*/
|
||||||
|
export const DEFAULT_ORIGIN_ERROR_PAGE_HTML = `<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>{{status}} | 源站暂时无法提供服务</title>
|
||||||
|
<style>
|
||||||
|
:root { color-scheme: light dark; }
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
|
||||||
|
background: #f6f7f9;
|
||||||
|
color: #1f2937;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
body { background: #0f1419; color: #e5e7eb; }
|
||||||
|
.card { background: #1a2332; border-color: #2d3a4d; box-shadow: none; }
|
||||||
|
.status { color: #f3f4f6; }
|
||||||
|
.muted { color: #9ca3af; }
|
||||||
|
.host { background: #243044; color: #d1d5db; }
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
width: min(32rem, calc(100% - 2rem));
|
||||||
|
padding: 2.5rem 2rem;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.06);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.status {
|
||||||
|
margin: 0;
|
||||||
|
font-size: clamp(3.5rem, 12vw, 5.5rem);
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: -0.04em;
|
||||||
|
line-height: 1;
|
||||||
|
color: #111827;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
margin: 1rem 0 0.5rem;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
p { margin: 0.4rem 0; line-height: 1.6; }
|
||||||
|
.muted { color: #6b7280; font-size: 0.95rem; }
|
||||||
|
.host {
|
||||||
|
display: inline-block;
|
||||||
|
margin-top: 1.25rem;
|
||||||
|
padding: 0.35rem 0.75rem;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #f3f4f6;
|
||||||
|
color: #374151;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="card" role="main">
|
||||||
|
<p class="status" aria-label="HTTP status">{{status}}</p>
|
||||||
|
<h1>源站暂时无法提供服务</h1>
|
||||||
|
<p class="muted">网关已拦截源站错误响应。请稍后重试;若问题持续,请联系站点管理员。</p>
|
||||||
|
<p class="host">{{host}}</p>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`;
|
||||||
|
|
||||||
|
/** Max HTML size in bytes (aligned with backend 256 KiB). */
|
||||||
|
export const ORIGIN_ERROR_PAGE_HTML_MAX_BYTES = 256 * 1024;
|
||||||
|
|
||||||
|
export function effectiveOriginErrorPageHTML(html: string): string {
|
||||||
|
return html.trim() === '' ? DEFAULT_ORIGIN_ERROR_PAGE_HTML : html;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function previewOriginErrorPageHTML(
|
||||||
|
html: string,
|
||||||
|
status = '502',
|
||||||
|
host = 'example.com',
|
||||||
|
): string {
|
||||||
|
return effectiveOriginErrorPageHTML(html)
|
||||||
|
.replaceAll('{{status}}', status)
|
||||||
|
.replaceAll('{{host}}', host);
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
/** Matches pkg/render/openresty StatusCodeMin / StatusCodeMax. */
|
||||||
|
export const STATUS_CODE_MIN = 400;
|
||||||
|
export const STATUS_CODE_MAX = 599;
|
||||||
|
|
||||||
|
export const DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS = ['500-599'] as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a single tag such as "502" or "500-599".
|
||||||
|
* Bounds must fall within 400–599 inclusive (aligned with Go ParseStatusCodeTag).
|
||||||
|
*/
|
||||||
|
export function parseStatusCodeTag(tag: string): {
|
||||||
|
lo: number;
|
||||||
|
hi: number;
|
||||||
|
} {
|
||||||
|
const trimmed = tag.trim();
|
||||||
|
if (!trimmed) {
|
||||||
|
throw new Error('状态码标签不能为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
let lo: number;
|
||||||
|
let hi: number;
|
||||||
|
|
||||||
|
const dash = trimmed.indexOf('-');
|
||||||
|
if (dash >= 0) {
|
||||||
|
lo = Number.parseInt(trimmed.slice(0, dash), 10);
|
||||||
|
hi = Number.parseInt(trimmed.slice(dash + 1), 10);
|
||||||
|
if (Number.isNaN(lo) || Number.isNaN(hi)) {
|
||||||
|
throw new Error(`无效状态码区间: ${trimmed}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
lo = Number.parseInt(trimmed, 10);
|
||||||
|
if (Number.isNaN(lo)) {
|
||||||
|
throw new Error(`无效状态码: ${trimmed}`);
|
||||||
|
}
|
||||||
|
hi = lo;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lo > hi) {
|
||||||
|
throw new Error(`状态码区间左右端点反序: ${trimmed}`);
|
||||||
|
}
|
||||||
|
if (lo < STATUS_CODE_MIN || hi > STATUS_CODE_MAX) {
|
||||||
|
throw new Error(
|
||||||
|
`状态码须在 ${STATUS_CODE_MIN}–${STATUS_CODE_MAX}: ${trimmed}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { lo, hi };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Expand tags into a sorted unique list of integers. */
|
||||||
|
export function expandStatusCodeTags(tags: string[]): number[] {
|
||||||
|
const set = new Set<number>();
|
||||||
|
for (const tag of tags) {
|
||||||
|
const { lo, hi } = parseStatusCodeTag(tag);
|
||||||
|
for (let code = lo; code <= hi; code += 1) {
|
||||||
|
set.add(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Array.from(set).sort((a, b) => a - b);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Soft validator for TagsInput: returns error message or null if ok. */
|
||||||
|
export function validateStatusCodeTagMessage(tag: string): string | null {
|
||||||
|
try {
|
||||||
|
parseStatusCodeTag(tag);
|
||||||
|
return null;
|
||||||
|
} catch (error) {
|
||||||
|
return error instanceof Error ? error.message : '无效状态码标签';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Validate a full tag list before save (must be non-empty and expand cleanly). */
|
||||||
|
export function validateStatusCodeTags(tags: string[]): void {
|
||||||
|
if (tags.length === 0) {
|
||||||
|
throw new Error('请至少添加一个状态码标签');
|
||||||
|
}
|
||||||
|
const codes = expandStatusCodeTags(tags);
|
||||||
|
if (codes.length === 0) {
|
||||||
|
throw new Error('状态码展开结果为空');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseStatusCodeTagsJSON(raw: string | undefined): string[] {
|
||||||
|
if (!raw || !raw.trim()) {
|
||||||
|
return [...DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS];
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw) as unknown;
|
||||||
|
if (!Array.isArray(parsed)) {
|
||||||
|
return [...DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS];
|
||||||
|
}
|
||||||
|
const tags = parsed
|
||||||
|
.filter((item): item is string => typeof item === 'string')
|
||||||
|
.map((item) => item.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
return tags.length > 0 ? tags : [...DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS];
|
||||||
|
} catch {
|
||||||
|
return [...DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -130,6 +130,23 @@ export const searchData: SearchItem[] = [
|
|||||||
category: 'page',
|
category: 'page',
|
||||||
keywords: ['origin', '源站', '后端', 'backend', '服务器', '负载均衡'],
|
keywords: ['origin', '源站', '后端', 'backend', '服务器', '负载均衡'],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'console-error-pages',
|
||||||
|
title: '错误页',
|
||||||
|
description: '配置源站错误状态码触发的统一 HTML 错误页',
|
||||||
|
url: '/error-pages',
|
||||||
|
category: 'page',
|
||||||
|
keywords: [
|
||||||
|
'错误页',
|
||||||
|
'源站',
|
||||||
|
'502',
|
||||||
|
'503',
|
||||||
|
'5xx',
|
||||||
|
'error page',
|
||||||
|
'origin error',
|
||||||
|
'error_page',
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: 'console-waf',
|
id: 'console-waf',
|
||||||
title: 'WAF 防火墙',
|
title: 'WAF 防火墙',
|
||||||
|
|||||||
Reference in New Issue
Block a user