lint
This commit is contained in:
977 files changed
+198426
-158324
No files matched your search
@@ -2,18 +2,21 @@ export const DEVELOPER_CRASH_MESSAGE = '开发者工具主动触发的 WebUI 崩
|
||||
|
||||
/** Throws the deliberate render-time exception used to exercise ErrorPage. */
|
||||
export function raiseDeveloperCrash(): never {
|
||||
throw new Error(DEVELOPER_CRASH_MESSAGE);
|
||||
throw new Error(DEVELOPER_CRASH_MESSAGE);
|
||||
}
|
||||
|
||||
export function developerCrashReducer(
|
||||
_requested: boolean,
|
||||
action: 'confirm',
|
||||
): boolean {
|
||||
if (action === 'confirm') return true;
|
||||
throw new Error(`Unknown developer crash action: ${String(action)}`);
|
||||
export function developerCrashReducer(_requested: boolean, action: 'confirm'): boolean {
|
||||
if (action === 'confirm') {
|
||||
return true;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown developer crash action: ${String(action)}`);
|
||||
}
|
||||
|
||||
export function DeveloperCrashProbe({ requested }: { requested: boolean }): null {
|
||||
if (requested) raiseDeveloperCrash();
|
||||
return null;
|
||||
if (requested) {
|
||||
raiseDeveloperCrash();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -20,223 +20,271 @@ import type { GlobalSettings } from '@/types';
|
||||
const MUSIC_SIGN_DEFAULT = 'https://ss.xingzhige.com/music_card/card';
|
||||
|
||||
function isHttpUrl(value: string): boolean {
|
||||
try {
|
||||
const u = new URL(value);
|
||||
return (u.protocol === 'http:' || u.protocol === 'https:') && u.host.length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const u = new URL(value);
|
||||
return (u.protocol === 'http:' || u.protocol === 'https:') && u.host.length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function GlobalConfigPanel() {
|
||||
const api = useApi();
|
||||
const { runAction } = useActionFeedback();
|
||||
const [config, setConfig] = useState<GlobalSettings | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadFailed, setLoadFailed] = useState(false);
|
||||
const { msg, flash } = useFlashMessage();
|
||||
const saveTimer = useRef<number | null>(null);
|
||||
const saveGen = useRef(0);
|
||||
const api = useApi();
|
||||
const { runAction } = useActionFeedback();
|
||||
const [config, setConfig] = useState<GlobalSettings | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadFailed, setLoadFailed] = useState(false);
|
||||
const { msg, flash } = useFlashMessage();
|
||||
const saveTimer = useRef<number | null>(null);
|
||||
const saveGen = useRef(0);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setLoadFailed(false);
|
||||
try {
|
||||
setConfig(await api.globalConfig.get());
|
||||
} catch (error) {
|
||||
console.error('load global config failed', error);
|
||||
setLoadFailed(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [api]);
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setLoadFailed(false);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
try {
|
||||
setConfig(await api.globalConfig.get());
|
||||
} catch (error) {
|
||||
console.error('load global config failed', error);
|
||||
setLoadFailed(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [api]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
/** Apply locally + debounced auto-save. Deliberately does NOT reconcile the
|
||||
* inputs from the server's normalized response (it would wipe a half-typed
|
||||
* URL); a generation guard just confirms the latest save. */
|
||||
const commit = (
|
||||
next: GlobalSettings,
|
||||
feedback: false | { title: string; successTitle: string } = {
|
||||
title: '正在更新全局配置',
|
||||
successTitle: '全局配置已更新',
|
||||
},
|
||||
) => {
|
||||
setConfig(next);
|
||||
const gen = ++saveGen.current;
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
saveTimer.current = window.setTimeout(() => {
|
||||
const dropped = next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim()))
|
||||
|| (next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim()));
|
||||
const save = feedback === false
|
||||
? api.globalConfig.save(next)
|
||||
: runAction(
|
||||
{
|
||||
title: feedback.title,
|
||||
detail: '正在同步 config/snowluma.json',
|
||||
successTitle: feedback.successTitle,
|
||||
successDetail: dropped ? '已保存,无效项已忽略' : '配置已同步',
|
||||
errorTitle: '全局配置更新失败',
|
||||
},
|
||||
() => api.globalConfig.save(next),
|
||||
);
|
||||
void save
|
||||
.then(() => {
|
||||
if (saveGen.current !== gen) return;
|
||||
// The server drops invalid (non-http) entries; say so rather than a
|
||||
// bare "已保存" next to a still-visible rejected value.
|
||||
flash('ok', dropped ? '已保存(无效项已忽略)' : '已保存');
|
||||
})
|
||||
.catch((error) => {
|
||||
if (saveGen.current !== gen) return;
|
||||
console.error('save global config failed', error);
|
||||
flash('err', '保存失败,请检查服务器日志');
|
||||
});
|
||||
}, 500);
|
||||
};
|
||||
|
||||
if (loading || !config) {
|
||||
return (
|
||||
<SkeletonSwap
|
||||
ready={!loading}
|
||||
lines={6}
|
||||
lineHeight={26}
|
||||
reserve={156}
|
||||
label="全局配置"
|
||||
className={!loading ? 'skeleton-swap-fluid min-h-[156px]' : ''}
|
||||
>
|
||||
{!loading && (loadFailed || !config) ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
|
||||
<AlertTriangle className="size-8 opacity-40" strokeWidth={1.5} />
|
||||
<p className="text-sm">加载全局配置失败</p>
|
||||
<Button variant="outline" size="sm" onClick={() => void load()}>
|
||||
<RefreshCw className="size-3.5" /> 重试
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</SkeletonSwap>
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (saveTimer.current) {
|
||||
clearTimeout(saveTimer.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
const servers = config.rkey.fallbackServers;
|
||||
const setServers = (next: string[]) =>
|
||||
commit({ ...config, rkey: { fallbackServers: next } }, false);
|
||||
/** Apply locally + debounced auto-save. Deliberately does NOT reconcile the
|
||||
* inputs from the server's normalized response (it would wipe a half-typed
|
||||
* URL); a generation guard just confirms the latest save. */
|
||||
const commit = (
|
||||
next: GlobalSettings,
|
||||
feedback: false | { title: string; successTitle: string } = {
|
||||
title: '正在更新全局配置',
|
||||
successTitle: '全局配置已更新',
|
||||
},
|
||||
) => {
|
||||
setConfig(next);
|
||||
const gen = ++saveGen.current;
|
||||
|
||||
return (
|
||||
<SkeletonSwap
|
||||
ready
|
||||
lines={6}
|
||||
lineHeight={26}
|
||||
reserve={156}
|
||||
label="全局配置"
|
||||
className="skeleton-swap-fluid min-h-[156px]"
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* rkey fallback servers */}
|
||||
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
|
||||
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
<KeyRound className="mt-0.5 size-3.5 shrink-0" />
|
||||
<p>
|
||||
图片 / 文件下载链接需要服务器签发的 <code className="font-mono">rkey</code>。SnowLuma 默认走内核获取;
|
||||
当内核在你的环境下持续取不到时,会按顺序向这里配置的 HTTP 端点回退。
|
||||
<strong className="font-medium text-foreground/80">默认留空=关闭</strong>,不配置就不会联系任何第三方。
|
||||
建议填你自建的端点。
|
||||
</p>
|
||||
</div>
|
||||
if (saveTimer.current) {
|
||||
clearTimeout(saveTimer.current);
|
||||
}
|
||||
|
||||
<div className="flex flex-col gap-2 border-t pt-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>rkey 回退服务器</Label>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setServers([...servers, ''])}
|
||||
>
|
||||
<Plus className="size-3.5" /> 添加
|
||||
</Button>
|
||||
</div>
|
||||
saveTimer.current = window.setTimeout(() => {
|
||||
const dropped =
|
||||
next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim())) ||
|
||||
(next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim()));
|
||||
const save =
|
||||
feedback === false
|
||||
? api.globalConfig.save(next)
|
||||
: runAction(
|
||||
{
|
||||
title: feedback.title,
|
||||
detail: '正在同步 config/snowluma.json',
|
||||
successTitle: feedback.successTitle,
|
||||
successDetail: dropped ? '已保存,无效项已忽略' : '配置已同步',
|
||||
errorTitle: '全局配置更新失败',
|
||||
},
|
||||
() => api.globalConfig.save(next),
|
||||
);
|
||||
void save
|
||||
.then(() => {
|
||||
if (saveGen.current !== gen) {
|
||||
return;
|
||||
}
|
||||
|
||||
{servers.length === 0 ? (
|
||||
<p className="rounded-lg border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
|
||||
未配置回退服务器(rkey 回退已关闭)
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{servers.map((url, i) => {
|
||||
const invalid = url.trim().length > 0 && !isHttpUrl(url.trim());
|
||||
return (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<Input
|
||||
type="url"
|
||||
inputMode="url"
|
||||
spellCheck={false}
|
||||
placeholder="https://your-rkey-server.example/rkeys"
|
||||
value={url}
|
||||
aria-invalid={invalid}
|
||||
className={cn('font-mono text-xs', invalid && 'border-destructive focus-visible:ring-destructive')}
|
||||
onChange={(e) => setServers(servers.map((s, idx) => (idx === i ? e.target.value : s)))}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="删除"
|
||||
className="shrink-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => setServers(servers.filter((_, idx) => idx !== i))}
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
// The server drops invalid (non-http) entries; say so rather than a
|
||||
// bare "已保存" next to a still-visible rejected value.
|
||||
flash('ok', dropped ? '已保存(无效项已忽略)' : '已保存');
|
||||
})
|
||||
.catch((error) => {
|
||||
if (saveGen.current !== gen) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('save global config failed', error);
|
||||
flash('err', '保存失败,请检查服务器日志');
|
||||
});
|
||||
}, 500);
|
||||
};
|
||||
|
||||
if (loading || !config) {
|
||||
return (
|
||||
<SkeletonSwap
|
||||
ready={!loading}
|
||||
lines={6}
|
||||
lineHeight={26}
|
||||
reserve={156}
|
||||
label="全局配置"
|
||||
className={!loading ? 'skeleton-swap-fluid min-h-[156px]' : ''}
|
||||
>
|
||||
{!loading && (loadFailed || !config) ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
|
||||
<AlertTriangle className="size-8 opacity-40" strokeWidth={1.5} />
|
||||
<p className="text-sm">加载全局配置失败</p>
|
||||
<Button variant="outline" size="sm" onClick={() => void load()}>
|
||||
<RefreshCw className="size-3.5" /> 重试
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
端点需返回 <code className="font-mono">{'{ group_rkey, private_rkey, expired_time }'}</code>
|
||||
(兼容 NapCat rkey 服务格式)。非 http(s) 链接会被忽略。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</SkeletonSwap>
|
||||
);
|
||||
}
|
||||
|
||||
{/* music sign URL */}
|
||||
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
|
||||
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
<Music className="mt-0.5 size-3.5 shrink-0" />
|
||||
<p>音乐分享卡片的签名服务,对所有账号统一生效。留空则使用内置默认服务。</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5 border-t pt-3">
|
||||
<Label>音乐签名服务 URL</Label>
|
||||
<Input
|
||||
type="url"
|
||||
inputMode="url"
|
||||
spellCheck={false}
|
||||
placeholder={MUSIC_SIGN_DEFAULT}
|
||||
value={config.musicSignUrl}
|
||||
aria-invalid={config.musicSignUrl.trim().length > 0 && !isHttpUrl(config.musicSignUrl.trim())}
|
||||
className={cn(
|
||||
'font-mono text-xs',
|
||||
config.musicSignUrl.trim().length > 0 && !isHttpUrl(config.musicSignUrl.trim())
|
||||
&& 'border-destructive focus-visible:ring-destructive',
|
||||
)}
|
||||
onChange={(e) => commit({ ...config, musicSignUrl: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
内置默认:<code className="font-mono">{MUSIC_SIGN_DEFAULT}</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
const servers = config.rkey.fallbackServers;
|
||||
const setServers = (next: string[]) =>
|
||||
commit({ ...config, rkey: { fallbackServers: next } }, false);
|
||||
|
||||
{msg && <p className={cn('text-xs', msg.kind === 'ok' ? 'text-success' : 'text-destructive')}>{msg.text}</p>}
|
||||
</div>
|
||||
</SkeletonSwap>
|
||||
);
|
||||
return (
|
||||
<SkeletonSwap
|
||||
ready
|
||||
lines={6}
|
||||
lineHeight={26}
|
||||
reserve={156}
|
||||
label="全局配置"
|
||||
className="skeleton-swap-fluid min-h-[156px]"
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* rkey fallback servers */}
|
||||
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
|
||||
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
<KeyRound className="mt-0.5 size-3.5 shrink-0" />
|
||||
<p>
|
||||
图片 / 文件下载链接需要服务器签发的{' '}
|
||||
<code className="font-mono">rkey</code>。SnowLuma 默认走内核获取;
|
||||
当内核在你的环境下持续取不到时,会按顺序向这里配置的 HTTP 端点回退。
|
||||
<strong className="font-medium text-foreground/80">
|
||||
默认留空=关闭
|
||||
</strong>
|
||||
,不配置就不会联系任何第三方。 建议填你自建的端点。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 border-t pt-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>rkey 回退服务器</Label>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setServers([...servers, ''])}
|
||||
>
|
||||
<Plus className="size-3.5" /> 添加
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{servers.length === 0 ? (
|
||||
<p className="rounded-lg border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
|
||||
未配置回退服务器(rkey 回退已关闭)
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{servers.map((url, i) => {
|
||||
const invalid = url.trim().length > 0 && !isHttpUrl(url.trim());
|
||||
return (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<Input
|
||||
type="url"
|
||||
inputMode="url"
|
||||
spellCheck={false}
|
||||
placeholder="https://your-rkey-server.example/rkeys"
|
||||
value={url}
|
||||
aria-invalid={invalid}
|
||||
className={cn(
|
||||
'font-mono text-xs',
|
||||
invalid &&
|
||||
'border-destructive focus-visible:ring-destructive',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
setServers(
|
||||
servers.map((s, idx) =>
|
||||
idx === i ? e.target.value : s,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="删除"
|
||||
className="shrink-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={() =>
|
||||
setServers(
|
||||
servers.filter((_, idx) => idx !== i),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
端点需返回{' '}
|
||||
<code className="font-mono">
|
||||
{'{ group_rkey, private_rkey, expired_time }'}
|
||||
</code>
|
||||
(兼容 NapCat rkey 服务格式)。非 http(s) 链接会被忽略。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* music sign URL */}
|
||||
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
|
||||
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
<Music className="mt-0.5 size-3.5 shrink-0" />
|
||||
<p>音乐分享卡片的签名服务,对所有账号统一生效。留空则使用内置默认服务。</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5 border-t pt-3">
|
||||
<Label>音乐签名服务 URL</Label>
|
||||
<Input
|
||||
type="url"
|
||||
inputMode="url"
|
||||
spellCheck={false}
|
||||
placeholder={MUSIC_SIGN_DEFAULT}
|
||||
value={config.musicSignUrl}
|
||||
aria-invalid={
|
||||
config.musicSignUrl.trim().length > 0 &&
|
||||
!isHttpUrl(config.musicSignUrl.trim())
|
||||
}
|
||||
className={cn(
|
||||
'font-mono text-xs',
|
||||
config.musicSignUrl.trim().length > 0 &&
|
||||
!isHttpUrl(config.musicSignUrl.trim()) &&
|
||||
'border-destructive focus-visible:ring-destructive',
|
||||
)}
|
||||
onChange={(e) => commit({ ...config, musicSignUrl: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
内置默认:<code className="font-mono">{MUSIC_SIGN_DEFAULT}</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{msg && (
|
||||
<p
|
||||
className={cn(
|
||||
'text-xs',
|
||||
msg.kind === 'ok' ? 'text-success' : 'text-destructive',
|
||||
)}
|
||||
>
|
||||
{msg.text}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</SkeletonSwap>
|
||||
);
|
||||
}
|
||||
@@ -14,49 +14,55 @@ import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import { useTheme } from '@/contexts/ThemeContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
notificationChannelType,
|
||||
type NotificationChannel,
|
||||
type NotificationChannelType,
|
||||
notificationChannelType,
|
||||
type NotificationChannel,
|
||||
type NotificationChannelType,
|
||||
} from '@/types';
|
||||
|
||||
interface HeaderRow {
|
||||
name: string;
|
||||
value: string;
|
||||
name: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
function headersToRows(headers?: Record<string, string>): HeaderRow[] {
|
||||
const rows = Object.entries(headers ?? {}).map(([name, value]) => ({ name, value }));
|
||||
return rows.length > 0 ? rows : [{ name: '', value: '' }];
|
||||
const rows = Object.entries(headers ?? {}).map(([name, value]) => ({ name, value }));
|
||||
return rows.length > 0 ? rows : [{ name: '', value: '' }];
|
||||
}
|
||||
|
||||
function rowsToHeaders(rows: HeaderRow[]): Record<string, string> | undefined {
|
||||
const out: Record<string, string> = {};
|
||||
for (const row of rows) {
|
||||
const name = row.name.trim();
|
||||
const value = row.value.trim();
|
||||
if (!name || !value) continue;
|
||||
out[name] = value;
|
||||
}
|
||||
return Object.keys(out).length > 0 ? out : undefined;
|
||||
const out: Record<string, string> = {};
|
||||
|
||||
for (const row of rows) {
|
||||
const name = row.name.trim();
|
||||
const value = row.value.trim();
|
||||
|
||||
if (!name || !value) {
|
||||
continue;
|
||||
}
|
||||
|
||||
out[name] = value;
|
||||
}
|
||||
|
||||
return Object.keys(out).length > 0 ? out : undefined;
|
||||
}
|
||||
|
||||
const CHANNEL_ID_RE = /^[\w.-]+$/;
|
||||
|
||||
function isHttpUrl(u: string): boolean {
|
||||
try {
|
||||
const x = new URL(u.trim());
|
||||
return x.protocol === 'http:' || x.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const x = new URL(u.trim());
|
||||
return x.protocol === 'http:' || x.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function looksLikeEmail(value: string): boolean {
|
||||
return /^[^\s<>@]+@[^\s<>@]+$/.test(value.trim())
|
||||
|| /<[^<>@\s]+@[^<>@\s]+>/.test(value);
|
||||
return /^[^\s<>@]+@[^\s<>@]+$/.test(value.trim()) || /<[^<>@\s]+@[^<>@\s]+>/.test(value);
|
||||
}
|
||||
|
||||
function hasRecipient(value: string): boolean {
|
||||
return value.split(/[,;\n]+/).some((part) => looksLikeEmail(part));
|
||||
return value.split(/[,;\n]+/).some((part) => looksLikeEmail(part));
|
||||
}
|
||||
|
||||
export const DEFAULT_WEBHOOK_BODY = `{
|
||||
@@ -73,420 +79,482 @@ QQ号:{uin}
|
||||
|
||||
export const DEFAULT_EMAIL_SUBJECT = '账号{event}:{nickname} ({uin})';
|
||||
|
||||
export function applyType(draft: NotificationChannel, type: NotificationChannelType): NotificationChannel {
|
||||
if (type === notificationChannelType(draft)) return { ...draft, type };
|
||||
if (type === 'email') {
|
||||
const keepBody = draft.bodyTemplate && draft.bodyTemplate !== DEFAULT_WEBHOOK_BODY;
|
||||
export function applyType(
|
||||
draft: NotificationChannel,
|
||||
type: NotificationChannelType,
|
||||
): NotificationChannel {
|
||||
if (type === notificationChannelType(draft)) {
|
||||
return { ...draft, type };
|
||||
}
|
||||
|
||||
if (type === 'email') {
|
||||
const keepBody = draft.bodyTemplate && draft.bodyTemplate !== DEFAULT_WEBHOOK_BODY;
|
||||
return {
|
||||
...draft,
|
||||
type,
|
||||
url: '',
|
||||
headers: undefined,
|
||||
smtpHost: draft.smtpHost ?? '',
|
||||
smtpPort: draft.smtpPort ?? 465,
|
||||
smtpSecure: draft.smtpSecure ?? true,
|
||||
smtpUser: draft.smtpUser ?? '',
|
||||
smtpPass: draft.smtpPass ?? '',
|
||||
from: draft.from ?? '',
|
||||
to: draft.to ?? '',
|
||||
subjectTemplate: draft.subjectTemplate || DEFAULT_EMAIL_SUBJECT,
|
||||
bodyTemplate: keepBody ? draft.bodyTemplate : DEFAULT_EMAIL_BODY,
|
||||
};
|
||||
}
|
||||
|
||||
const keepBody = draft.bodyTemplate && draft.bodyTemplate !== DEFAULT_EMAIL_BODY;
|
||||
return {
|
||||
...draft,
|
||||
type,
|
||||
url: '',
|
||||
headers: undefined,
|
||||
smtpHost: draft.smtpHost ?? '',
|
||||
smtpPort: draft.smtpPort ?? 465,
|
||||
smtpSecure: draft.smtpSecure ?? true,
|
||||
smtpUser: draft.smtpUser ?? '',
|
||||
smtpPass: draft.smtpPass ?? '',
|
||||
from: draft.from ?? '',
|
||||
to: draft.to ?? '',
|
||||
subjectTemplate: draft.subjectTemplate || DEFAULT_EMAIL_SUBJECT,
|
||||
bodyTemplate: keepBody ? draft.bodyTemplate : DEFAULT_EMAIL_BODY,
|
||||
id: draft.id,
|
||||
name: draft.name,
|
||||
type: 'webhook',
|
||||
url: draft.url,
|
||||
bodyTemplate: keepBody ? draft.bodyTemplate : DEFAULT_WEBHOOK_BODY,
|
||||
enabled: draft.enabled,
|
||||
};
|
||||
}
|
||||
const keepBody = draft.bodyTemplate && draft.bodyTemplate !== DEFAULT_EMAIL_BODY;
|
||||
return {
|
||||
id: draft.id,
|
||||
name: draft.name,
|
||||
type: 'webhook',
|
||||
url: draft.url,
|
||||
bodyTemplate: keepBody ? draft.bodyTemplate : DEFAULT_WEBHOOK_BODY,
|
||||
enabled: draft.enabled,
|
||||
};
|
||||
}
|
||||
|
||||
export function toChannel(draft: NotificationChannel, headerRows: HeaderRow[]): NotificationChannel {
|
||||
const id = draft.id.trim();
|
||||
const name = draft.name.trim();
|
||||
const enabled = draft.enabled;
|
||||
if (notificationChannelType(draft) === 'email') {
|
||||
export function toChannel(
|
||||
draft: NotificationChannel,
|
||||
headerRows: HeaderRow[],
|
||||
): NotificationChannel {
|
||||
const id = draft.id.trim();
|
||||
const name = draft.name.trim();
|
||||
const enabled = draft.enabled;
|
||||
|
||||
if (notificationChannelType(draft) === 'email') {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: 'email',
|
||||
url: '',
|
||||
bodyTemplate: draft.bodyTemplate,
|
||||
enabled,
|
||||
smtpHost: draft.smtpHost?.trim() ?? '',
|
||||
smtpPort: draft.smtpPort ?? 465,
|
||||
smtpSecure: draft.smtpSecure ?? true,
|
||||
smtpUser: draft.smtpUser?.trim() || undefined,
|
||||
smtpPass: draft.smtpPass || undefined,
|
||||
from: draft.from?.trim() ?? '',
|
||||
to: draft.to?.trim() ?? '',
|
||||
subjectTemplate: draft.subjectTemplate?.trim() || DEFAULT_EMAIL_SUBJECT,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: 'email',
|
||||
url: '',
|
||||
bodyTemplate: draft.bodyTemplate,
|
||||
enabled,
|
||||
smtpHost: draft.smtpHost?.trim() ?? '',
|
||||
smtpPort: draft.smtpPort ?? 465,
|
||||
smtpSecure: draft.smtpSecure ?? true,
|
||||
smtpUser: draft.smtpUser?.trim() || undefined,
|
||||
smtpPass: draft.smtpPass || undefined,
|
||||
from: draft.from?.trim() ?? '',
|
||||
to: draft.to?.trim() ?? '',
|
||||
subjectTemplate: draft.subjectTemplate?.trim() || DEFAULT_EMAIL_SUBJECT,
|
||||
id,
|
||||
name,
|
||||
type: 'webhook',
|
||||
url: draft.url.trim(),
|
||||
bodyTemplate: draft.bodyTemplate,
|
||||
enabled,
|
||||
headers: rowsToHeaders(headerRows),
|
||||
};
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: 'webhook',
|
||||
url: draft.url.trim(),
|
||||
bodyTemplate: draft.bodyTemplate,
|
||||
enabled,
|
||||
headers: rowsToHeaders(headerRows),
|
||||
};
|
||||
}
|
||||
|
||||
interface NotificationChannelDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
isEdit: boolean;
|
||||
/** Seed draft — a blank channel for create, the existing one for edit. */
|
||||
initial: NotificationChannel;
|
||||
/** Ids of every other channel, for the duplicate check. */
|
||||
otherIds: string[];
|
||||
onSubmit: (channel: NotificationChannel) => void;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
isEdit: boolean;
|
||||
/** Seed draft — a blank channel for create, the existing one for edit. */
|
||||
initial: NotificationChannel;
|
||||
/** Ids of every other channel, for the duplicate check. */
|
||||
otherIds: string[];
|
||||
onSubmit: (channel: NotificationChannel) => void;
|
||||
}
|
||||
|
||||
export function NotificationChannelDialog(props: NotificationChannelDialogProps) {
|
||||
const { open, onOpenChange, isEdit, initial, otherIds, onSubmit } = props;
|
||||
// Parent unmounts on close, so each open re-seeds via lazy init.
|
||||
const [draft, setDraft] = useState<NotificationChannel>(() => ({
|
||||
...initial,
|
||||
type: notificationChannelType(initial),
|
||||
}));
|
||||
const [headerRows, setHeaderRows] = useState<HeaderRow[]>(() => headersToRows(initial.headers));
|
||||
const [showPass, setShowPass] = useState(false);
|
||||
const reduce = useTheme().appearance.disableMotion;
|
||||
const patch = (p: Partial<NotificationChannel>) => setDraft({ ...draft, ...p });
|
||||
const patchHeader = (index: number, p: Partial<HeaderRow>) => {
|
||||
setHeaderRows(headerRows.map((row, i) => (i === index ? { ...row, ...p } : row)));
|
||||
};
|
||||
const { open, onOpenChange, isEdit, initial, otherIds, onSubmit } = props;
|
||||
// Parent unmounts on close, so each open re-seeds via lazy init.
|
||||
const [draft, setDraft] = useState<NotificationChannel>(() => ({
|
||||
...initial,
|
||||
type: notificationChannelType(initial),
|
||||
}));
|
||||
const [headerRows, setHeaderRows] = useState<HeaderRow[]>(() => headersToRows(initial.headers));
|
||||
const [showPass, setShowPass] = useState(false);
|
||||
const reduce = useTheme().appearance.disableMotion;
|
||||
const patch = (p: Partial<NotificationChannel>) => setDraft({ ...draft, ...p });
|
||||
|
||||
const type = notificationChannelType(draft);
|
||||
const id = draft.id.trim();
|
||||
const idBlank = id.length === 0;
|
||||
const idBad = !idBlank && (!CHANNEL_ID_RE.test(id) || id.length > 64);
|
||||
const idDup = !idBlank && otherIds.includes(id);
|
||||
const urlBlank = draft.url.trim().length === 0;
|
||||
const urlBad = !urlBlank && !isHttpUrl(draft.url);
|
||||
const hostBlank = !(draft.smtpHost ?? '').trim();
|
||||
const fromBlank = !(draft.from ?? '').trim();
|
||||
const fromBad = !fromBlank && !looksLikeEmail(draft.from ?? '');
|
||||
const toBlank = !(draft.to ?? '').trim();
|
||||
const toBad = !toBlank && !hasRecipient(draft.to ?? '');
|
||||
const port = draft.smtpPort ?? 465;
|
||||
const portBad = !Number.isInteger(port) || port < 1 || port > 65535;
|
||||
const canSave = type === 'email'
|
||||
? !idBlank && !idBad && !idDup && !hostBlank && !fromBlank && !fromBad && !toBlank && !toBad && !portBad
|
||||
: !idBlank && !idBad && !idDup && !urlBlank && !urlBad;
|
||||
const patchHeader = (index: number, p: Partial<HeaderRow>) => {
|
||||
setHeaderRows(headerRows.map((row, i) => (i === index ? { ...row, ...p } : row)));
|
||||
};
|
||||
|
||||
const idError = idBlank
|
||||
? '请填写渠道 ID'
|
||||
: idBad
|
||||
? '只能用字母 / 数字 / . _ - ,≤64 字符'
|
||||
: idDup
|
||||
? 'ID 与其它渠道重复'
|
||||
: undefined;
|
||||
const urlError = urlBlank ? '请填写 Webhook URL' : urlBad ? '必须是 http(s) 地址' : undefined;
|
||||
const hostError = hostBlank ? '请填写 SMTP 主机' : undefined;
|
||||
const fromError = fromBlank ? '请填写发件人' : fromBad ? '必须是邮箱地址' : undefined;
|
||||
const toError = toBlank ? '请填写收件人' : toBad ? '至少填写一个邮箱' : undefined;
|
||||
const portError = portBad ? '端口 1–65535' : undefined;
|
||||
const type = notificationChannelType(draft);
|
||||
const id = draft.id.trim();
|
||||
const idBlank = id.length === 0;
|
||||
const idBad = !idBlank && (!CHANNEL_ID_RE.test(id) || id.length > 64);
|
||||
const idDup = !idBlank && otherIds.includes(id);
|
||||
const urlBlank = draft.url.trim().length === 0;
|
||||
const urlBad = !urlBlank && !isHttpUrl(draft.url);
|
||||
const hostBlank = !(draft.smtpHost ?? '').trim();
|
||||
const fromBlank = !(draft.from ?? '').trim();
|
||||
const fromBad = !fromBlank && !looksLikeEmail(draft.from ?? '');
|
||||
const toBlank = !(draft.to ?? '').trim();
|
||||
const toBad = !toBlank && !hasRecipient(draft.to ?? '');
|
||||
const port = draft.smtpPort ?? 465;
|
||||
const portBad = !Number.isInteger(port) || port < 1 || port > 65535;
|
||||
const canSave =
|
||||
type === 'email'
|
||||
? !idBlank &&
|
||||
!idBad &&
|
||||
!idDup &&
|
||||
!hostBlank &&
|
||||
!fromBlank &&
|
||||
!fromBad &&
|
||||
!toBlank &&
|
||||
!toBad &&
|
||||
!portBad
|
||||
: !idBlank && !idBad && !idDup && !urlBlank && !urlBad;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => onOpenChange(false)}
|
||||
title={isEdit ? '编辑渠道' : '新建渠道'}
|
||||
description={type === 'email'
|
||||
? '账号上线 / 下线时向该邮箱发送一封渲染后的通知。'
|
||||
: '账号上线 / 下线时向该 Webhook POST 一条渲染后的通知。'}
|
||||
closeLabel="关闭渠道编辑弹窗"
|
||||
maxWidth={576}
|
||||
maxHeight="min(86dvh, 780px)"
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
disabled={!canSave}
|
||||
onClick={() => {
|
||||
onSubmit(toChannel(draft, headerRows));
|
||||
onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
{isEdit ? '保存修改' : '创建渠道'}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="grid grid-cols-2 gap-1 rounded-lg border bg-muted/40 p-1">
|
||||
{([
|
||||
['webhook', 'Webhook'],
|
||||
['email', '邮件'],
|
||||
] as const).map(([value, label]) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
aria-pressed={type === value}
|
||||
onClick={() => setDraft(applyType(draft, value))}
|
||||
className={cn(
|
||||
'rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
|
||||
type === value
|
||||
? 'bg-background text-foreground shadow-sm'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
const idError = idBlank
|
||||
? '请填写渠道 ID'
|
||||
: idBad
|
||||
? '只能用字母 / 数字 / . _ - ,≤64 字符'
|
||||
: idDup
|
||||
? 'ID 与其它渠道重复'
|
||||
: undefined;
|
||||
const urlError = urlBlank ? '请填写 Webhook URL' : urlBad ? '必须是 http(s) 地址' : undefined;
|
||||
const hostError = hostBlank ? '请填写 SMTP 主机' : undefined;
|
||||
const fromError = fromBlank ? '请填写发件人' : fromBad ? '必须是邮箱地址' : undefined;
|
||||
const toError = toBlank ? '请填写收件人' : toBad ? '至少填写一个邮箱' : undefined;
|
||||
const portError = portBad ? '端口 1–65535' : undefined;
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field
|
||||
label="渠道 ID"
|
||||
placeholder="dingtalk"
|
||||
value={draft.id}
|
||||
disabled={isEdit}
|
||||
hint={isEdit ? '创建后不可更改' : '账号据此勾选;字母/数字/. _ -'}
|
||||
error={idError}
|
||||
onChange={(v) => patch({ id: v })}
|
||||
/>
|
||||
<Field
|
||||
label="显示名"
|
||||
placeholder={type === 'email' ? '运维邮箱' : '钉钉群机器人'}
|
||||
value={draft.name}
|
||||
onChange={(v) => patch({ name: v })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{type === 'webhook' ? (
|
||||
<>
|
||||
<Field
|
||||
label="Webhook URL"
|
||||
type="url"
|
||||
placeholder="https://oapi.dingtalk.com/robot/send?access_token=…"
|
||||
value={draft.url}
|
||||
error={urlError}
|
||||
onChange={(v) => patch({ url: v })}
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Label>请求头</Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setHeaderRows([...headerRows, { name: '', value: '' }])}
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
添加
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
{headerRows.map((row, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<Input
|
||||
value={row.name}
|
||||
placeholder="Authorization"
|
||||
spellCheck={false}
|
||||
onChange={(e) => patchHeader(i, { name: e.target.value })}
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
<Input
|
||||
value={row.value}
|
||||
placeholder="Bearer …"
|
||||
spellCheck={false}
|
||||
onChange={(e) => patchHeader(i, { value: e.target.value })}
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="删除请求头"
|
||||
onClick={() => {
|
||||
const next = headerRows.filter((_, idx) => idx !== i);
|
||||
setHeaderRows(next.length > 0 ? next : [{ name: '', value: '' }]);
|
||||
}}
|
||||
className="shrink-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => onOpenChange(false)}
|
||||
title={isEdit ? '编辑渠道' : '新建渠道'}
|
||||
description={
|
||||
type === 'email'
|
||||
? '账号上线 / 下线时向该邮箱发送一封渲染后的通知。'
|
||||
: '账号上线 / 下线时向该 Webhook POST 一条渲染后的通知。'
|
||||
}
|
||||
closeLabel="关闭渠道编辑弹窗"
|
||||
maxWidth={576}
|
||||
maxHeight="min(86dvh, 780px)"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
可选。用于飞书等需要鉴权头的 Webhook;默认仍带 JSON Content-Type。
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_7rem]">
|
||||
<Field
|
||||
label="SMTP 主机"
|
||||
placeholder="smtp.qq.com"
|
||||
value={draft.smtpHost ?? ''}
|
||||
error={hostError}
|
||||
onChange={(v) => patch({ smtpHost: v })}
|
||||
/>
|
||||
<Field
|
||||
label="端口"
|
||||
type="number"
|
||||
placeholder="465"
|
||||
value={String(draft.smtpPort ?? 465)}
|
||||
error={portError}
|
||||
onChange={(v) => {
|
||||
const n = Math.trunc(Number(v));
|
||||
if (!Number.isFinite(n)) {
|
||||
patch({ smtpPort: 465 });
|
||||
return;
|
||||
}
|
||||
patch({
|
||||
smtpPort: n,
|
||||
smtpSecure: n === 465 ? true : n === 587 ? false : draft.smtpSecure,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field
|
||||
label="SMTP 用户名"
|
||||
placeholder="[email protected]"
|
||||
value={draft.smtpUser ?? ''}
|
||||
hint="部分内网中继可不填"
|
||||
onChange={(v) => patch({ smtpUser: v })}
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>SMTP 密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type={showPass ? 'text' : 'password'}
|
||||
value={draft.smtpPass ?? ''}
|
||||
autoComplete="new-password"
|
||||
spellCheck={false}
|
||||
placeholder="授权码 / 密码"
|
||||
onChange={(e) => patch({ smtpPass: e.target.value })}
|
||||
className="pr-11 font-mono text-xs"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPass((v) => !v)}
|
||||
className="absolute right-1.5 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
tabIndex={-1}
|
||||
aria-label={showPass ? '隐藏密码' : '显示密码'}
|
||||
>
|
||||
<PasswordVisibilityIcon visible={showPass} reduceMotion={reduce} />
|
||||
</button>
|
||||
<Button
|
||||
disabled={!canSave}
|
||||
onClick={() => {
|
||||
onSubmit(toChannel(draft, headerRows));
|
||||
onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
{isEdit ? '保存修改' : '创建渠道'}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="grid grid-cols-2 gap-1 rounded-lg border bg-muted/40 p-1">
|
||||
{(
|
||||
[
|
||||
['webhook', 'Webhook'],
|
||||
['email', '邮件'],
|
||||
] as const
|
||||
).map(([value, label]) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
aria-pressed={type === value}
|
||||
onClick={() => setDraft(applyType(draft, value))}
|
||||
className={cn(
|
||||
'rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
|
||||
type === value
|
||||
? 'bg-background text-foreground shadow-sm'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field
|
||||
label="渠道 ID"
|
||||
placeholder="dingtalk"
|
||||
value={draft.id}
|
||||
disabled={isEdit}
|
||||
hint={isEdit ? '创建后不可更改' : '账号据此勾选;字母/数字/. _ -'}
|
||||
error={idError}
|
||||
onChange={(v) => patch({ id: v })}
|
||||
/>
|
||||
<Field
|
||||
label="显示名"
|
||||
placeholder={type === 'email' ? '运维邮箱' : '钉钉群机器人'}
|
||||
value={draft.name}
|
||||
onChange={(v) => patch({ name: v })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{type === 'webhook' ? (
|
||||
<>
|
||||
<Field
|
||||
label="Webhook URL"
|
||||
type="url"
|
||||
placeholder="https://oapi.dingtalk.com/robot/send?access_token=…"
|
||||
value={draft.url}
|
||||
error={urlError}
|
||||
onChange={(v) => patch({ url: v })}
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Label>请求头</Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
setHeaderRows([...headerRows, { name: '', value: '' }])
|
||||
}
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
添加
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
{headerRows.map((row, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<Input
|
||||
value={row.name}
|
||||
placeholder="Authorization"
|
||||
spellCheck={false}
|
||||
onChange={(e) =>
|
||||
patchHeader(i, { name: e.target.value })
|
||||
}
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
<Input
|
||||
value={row.value}
|
||||
placeholder="Bearer …"
|
||||
spellCheck={false}
|
||||
onChange={(e) =>
|
||||
patchHeader(i, { value: e.target.value })
|
||||
}
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="删除请求头"
|
||||
onClick={() => {
|
||||
const next = headerRows.filter(
|
||||
(_, idx) => idx !== i,
|
||||
);
|
||||
setHeaderRows(
|
||||
next.length > 0
|
||||
? next
|
||||
: [{ name: '', value: '' }],
|
||||
);
|
||||
}}
|
||||
className="shrink-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
可选。用于飞书等需要鉴权头的 Webhook;默认仍带 JSON Content-Type。
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_7rem]">
|
||||
<Field
|
||||
label="SMTP 主机"
|
||||
placeholder="smtp.qq.com"
|
||||
value={draft.smtpHost ?? ''}
|
||||
error={hostError}
|
||||
onChange={(v) => patch({ smtpHost: v })}
|
||||
/>
|
||||
<Field
|
||||
label="端口"
|
||||
type="number"
|
||||
placeholder="465"
|
||||
value={String(draft.smtpPort ?? 465)}
|
||||
error={portError}
|
||||
onChange={(v) => {
|
||||
const n = Math.trunc(Number(v));
|
||||
|
||||
if (!Number.isFinite(n)) {
|
||||
patch({ smtpPort: 465 });
|
||||
return;
|
||||
}
|
||||
|
||||
patch({
|
||||
smtpPort: n,
|
||||
smtpSecure:
|
||||
n === 465 ? true : n === 587 ? false : draft.smtpSecure,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field
|
||||
label="SMTP 用户名"
|
||||
placeholder="[email protected]"
|
||||
value={draft.smtpUser ?? ''}
|
||||
hint="部分内网中继可不填"
|
||||
onChange={(v) => patch({ smtpUser: v })}
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>SMTP 密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type={showPass ? 'text' : 'password'}
|
||||
value={draft.smtpPass ?? ''}
|
||||
autoComplete="new-password"
|
||||
spellCheck={false}
|
||||
placeholder="授权码 / 密码"
|
||||
onChange={(e) => patch({ smtpPass: e.target.value })}
|
||||
className="pr-11 font-mono text-xs"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPass((v) => !v)}
|
||||
className="absolute right-1.5 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
tabIndex={-1}
|
||||
aria-label={showPass ? '隐藏密码' : '显示密码'}
|
||||
>
|
||||
<PasswordVisibilityIcon
|
||||
visible={showPass}
|
||||
reduceMotion={reduce}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border bg-card/40 p-3">
|
||||
<div className="min-w-0">
|
||||
<Label className="text-sm">隐式 TLS</Label>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
465 通常开启;587 先明文再 STARTTLS,请关掉此项。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={draft.smtpSecure ?? true}
|
||||
onChange={(v) => patch({ smtpSecure: v })}
|
||||
ariaLabel="隐式 TLS"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field
|
||||
label="发件人"
|
||||
placeholder="SnowLuma <[email protected]>"
|
||||
value={draft.from ?? ''}
|
||||
error={fromError}
|
||||
onChange={(v) => patch({ from: v })}
|
||||
/>
|
||||
<Field
|
||||
label="收件人"
|
||||
placeholder="[email protected], [email protected]"
|
||||
value={draft.to ?? ''}
|
||||
error={toError}
|
||||
hint="多个地址用逗号或分号分隔"
|
||||
onChange={(v) => patch({ to: v })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Field
|
||||
label="主题模板"
|
||||
placeholder={DEFAULT_EMAIL_SUBJECT}
|
||||
value={draft.subjectTemplate ?? DEFAULT_EMAIL_SUBJECT}
|
||||
onChange={(v) => patch({ subjectTemplate: v })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{type === 'email' ? '正文模板' : 'Body 模板'}</Label>
|
||||
<Textarea
|
||||
value={draft.bodyTemplate}
|
||||
rows={type === 'email' ? 6 : 3}
|
||||
spellCheck={false}
|
||||
onChange={(e) => patch({ bodyTemplate: e.target.value })}
|
||||
className="font-mono text-xs leading-relaxed"
|
||||
/>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
变量:<code className="font-mono">{'{uin}'}</code>{' '}
|
||||
<code className="font-mono">{'{nickname}'}</code>{' '}
|
||||
<code className="font-mono">{'{event}'}</code>(offline/online){' '}
|
||||
<code className="font-mono">{'{time}'}</code>
|
||||
{type === 'email' ? '。正文以 < 开头时按 HTML 发送。' : ''}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border bg-card/40 p-3">
|
||||
<div className="min-w-0">
|
||||
<Label className="text-sm">启用</Label>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
关闭后保留配置但不推送;账号侧对应开关会被锁定并关闭。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={draft.enabled}
|
||||
onChange={(v) => patch({ enabled: v })}
|
||||
ariaLabel="启用渠道"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border bg-card/40 p-3">
|
||||
<div className="min-w-0">
|
||||
<Label className="text-sm">隐式 TLS</Label>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
465 通常开启;587 先明文再 STARTTLS,请关掉此项。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={draft.smtpSecure ?? true}
|
||||
onChange={(v) => patch({ smtpSecure: v })}
|
||||
ariaLabel="隐式 TLS"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field
|
||||
label="发件人"
|
||||
placeholder="SnowLuma <[email protected]>"
|
||||
value={draft.from ?? ''}
|
||||
error={fromError}
|
||||
onChange={(v) => patch({ from: v })}
|
||||
/>
|
||||
<Field
|
||||
label="收件人"
|
||||
placeholder="[email protected], [email protected]"
|
||||
value={draft.to ?? ''}
|
||||
error={toError}
|
||||
hint="多个地址用逗号或分号分隔"
|
||||
onChange={(v) => patch({ to: v })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Field
|
||||
label="主题模板"
|
||||
placeholder={DEFAULT_EMAIL_SUBJECT}
|
||||
value={draft.subjectTemplate ?? DEFAULT_EMAIL_SUBJECT}
|
||||
onChange={(v) => patch({ subjectTemplate: v })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{type === 'email' ? '正文模板' : 'Body 模板'}</Label>
|
||||
<Textarea
|
||||
value={draft.bodyTemplate}
|
||||
rows={type === 'email' ? 6 : 3}
|
||||
spellCheck={false}
|
||||
onChange={(e) => patch({ bodyTemplate: e.target.value })}
|
||||
className="font-mono text-xs leading-relaxed"
|
||||
/>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
变量:<code className="font-mono">{'{uin}'}</code> <code className="font-mono">{'{nickname}'}</code>{' '}
|
||||
<code className="font-mono">{'{event}'}</code>(offline/online) <code className="font-mono">{'{time}'}</code>
|
||||
{type === 'email' ? '。正文以 < 开头时按 HTML 发送。' : ''}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border bg-card/40 p-3">
|
||||
<div className="min-w-0">
|
||||
<Label className="text-sm">启用</Label>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
关闭后保留配置但不推送;账号侧对应开关会被锁定并关闭。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch value={draft.enabled} onChange={(v) => patch({ enabled: v })} ariaLabel="启用渠道" />
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
interface FieldProps {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
placeholder?: string;
|
||||
type?: 'text' | 'url' | 'number';
|
||||
error?: string;
|
||||
hint?: string;
|
||||
disabled?: boolean;
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
placeholder?: string;
|
||||
type?: 'text' | 'url' | 'number';
|
||||
error?: string;
|
||||
hint?: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
function Field({ label, value, onChange, placeholder, type = 'text', error, hint, disabled }: FieldProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{label}</Label>
|
||||
<Input
|
||||
type={type}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className={cn(error && 'border-destructive focus-visible:ring-destructive/40', disabled && 'opacity-60')}
|
||||
/>
|
||||
{error ? (
|
||||
<p className="text-xs text-destructive">{error}</p>
|
||||
) : hint ? (
|
||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
function Field({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
type = 'text',
|
||||
error,
|
||||
hint,
|
||||
disabled,
|
||||
}: FieldProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{label}</Label>
|
||||
<Input
|
||||
type={type}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className={cn(
|
||||
error && 'border-destructive focus-visible:ring-destructive/40',
|
||||
disabled && 'opacity-60',
|
||||
)}
|
||||
/>
|
||||
{error ? (
|
||||
<p className="text-xs text-destructive">{error}</p>
|
||||
) : hint ? (
|
||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,340 +16,422 @@ import { useApi } from '@/lib/api';
|
||||
import { useFlashMessage } from '@/hooks/use-flash-message';
|
||||
import { useTheme } from '@/contexts/ThemeContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { notificationChannelType, type NotificationChannel, type NotificationsConfig } from '@/types';
|
||||
import {
|
||||
notificationChannelType,
|
||||
type NotificationChannel,
|
||||
type NotificationsConfig,
|
||||
} from '@/types';
|
||||
import { DEFAULT_WEBHOOK_BODY, NotificationChannelDialog } from './notification-channel-dialog';
|
||||
|
||||
/** A fresh channel with a non-colliding default id. */
|
||||
function blankChannel(existing: NotificationChannel[]): NotificationChannel {
|
||||
const used = new Set(existing.map((c) => c.id));
|
||||
let n = existing.length + 1;
|
||||
while (used.has(`channel-${n}`)) n += 1;
|
||||
return { id: `channel-${n}`, name: '', type: 'webhook', url: '', bodyTemplate: DEFAULT_WEBHOOK_BODY, enabled: true };
|
||||
const used = new Set(existing.map((c) => c.id));
|
||||
let n = existing.length + 1;
|
||||
|
||||
while (used.has(`channel-${n}`)) {
|
||||
n += 1;
|
||||
}
|
||||
|
||||
return {
|
||||
id: `channel-${n}`,
|
||||
name: '',
|
||||
type: 'webhook',
|
||||
url: '',
|
||||
bodyTemplate: DEFAULT_WEBHOOK_BODY,
|
||||
enabled: true,
|
||||
};
|
||||
}
|
||||
|
||||
interface DialogState {
|
||||
open: boolean;
|
||||
index: number | null; // null → create
|
||||
seed: NotificationChannel;
|
||||
open: boolean;
|
||||
index: number | null; // null → create
|
||||
seed: NotificationChannel;
|
||||
}
|
||||
|
||||
export function NotificationsPanel() {
|
||||
const api = useApi();
|
||||
const { runAction } = useActionFeedback();
|
||||
const [config, setConfig] = useState<NotificationsConfig | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dialog, setDialog] = useState<DialogState>({ open: false, index: null, seed: blankChannel([]) });
|
||||
const [testing, setTesting] = useState<string | null>(null);
|
||||
const { msg, flash, setMsg } = useFlashMessage();
|
||||
const saveTimer = useRef<number | null>(null);
|
||||
const saveGen = useRef(0);
|
||||
const api = useApi();
|
||||
const { runAction } = useActionFeedback();
|
||||
const [config, setConfig] = useState<NotificationsConfig | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dialog, setDialog] = useState<DialogState>({
|
||||
open: false,
|
||||
index: null,
|
||||
seed: blankChannel([]),
|
||||
});
|
||||
const [testing, setTesting] = useState<string | null>(null);
|
||||
const { msg, flash, setMsg } = useFlashMessage();
|
||||
const saveTimer = useRef<number | null>(null);
|
||||
const saveGen = useRef(0);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
setConfig(await api.notifications.getConfig());
|
||||
} catch (error) {
|
||||
console.error('load notifications config failed', error);
|
||||
setMsg({ kind: 'err', text: '加载通知配置失败' });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [api, setMsg]);
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
try {
|
||||
setConfig(await api.notifications.getConfig());
|
||||
} catch (error) {
|
||||
console.error('load notifications config failed', error);
|
||||
setMsg({ kind: 'err', text: '加载通知配置失败' });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [api, setMsg]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
/** Apply locally + debounced auto-save. A generation guard reconciles with
|
||||
* the server's normalized result only if no newer edit landed meanwhile. */
|
||||
const commit = (
|
||||
next: NotificationsConfig,
|
||||
copy: { title: string; successTitle: string } = {
|
||||
title: '正在更新通知配置',
|
||||
successTitle: '通知配置已更新',
|
||||
},
|
||||
) => {
|
||||
setConfig(next);
|
||||
const gen = ++saveGen.current;
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
saveTimer.current = window.setTimeout(() => {
|
||||
void runAction(
|
||||
{
|
||||
title: copy.title,
|
||||
detail: '正在同步通知渠道设置',
|
||||
successTitle: copy.successTitle,
|
||||
successDetail: '通知配置已同步',
|
||||
errorTitle: '通知配置更新失败',
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (saveTimer.current) {
|
||||
clearTimeout(saveTimer.current);
|
||||
}
|
||||
},
|
||||
() => api.notifications.saveConfig(next),
|
||||
)
|
||||
.then((result) => {
|
||||
// Only the latest save reconciles + confirms; a superseded in-flight
|
||||
// save stays silent (its successor will confirm).
|
||||
if (saveGen.current !== gen) return;
|
||||
setConfig(result);
|
||||
flash('ok', '已保存');
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('save notifications config failed', error);
|
||||
flash('err', '保存失败,请检查服务器日志');
|
||||
});
|
||||
}, 350);
|
||||
};
|
||||
|
||||
if (loading || !config) {
|
||||
return (
|
||||
<SkeletonSwap
|
||||
ready={!loading}
|
||||
lines={6}
|
||||
lineHeight={26}
|
||||
reserve={156}
|
||||
label="通知配置"
|
||||
className={!loading ? 'skeleton-swap-fluid min-h-[156px]' : ''}
|
||||
>
|
||||
{!loading && !config ? (
|
||||
<div role="alert" className="flex items-center justify-between gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive">
|
||||
<span>{msg?.text ?? '加载通知配置失败'}</span>
|
||||
<Button variant="outline" size="sm" onClick={() => void load()}>
|
||||
重试
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</SkeletonSwap>
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
const channels = config.channels;
|
||||
const setChannels = (
|
||||
next: NotificationChannel[],
|
||||
copy?: { title: string; successTitle: string },
|
||||
) => commit({ ...config, channels: next }, copy);
|
||||
const otherIds = (index: number | null) => channels.filter((_, i) => i !== index).map((c) => c.id);
|
||||
|
||||
const openCreate = () => setDialog({ open: true, index: null, seed: blankChannel(channels) });
|
||||
const openEdit = (i: number) => setDialog({ open: true, index: i, seed: channels[i] });
|
||||
const submitChannel = (ch: NotificationChannel) => {
|
||||
if (dialog.index == null) {
|
||||
setChannels(
|
||||
[...channels, ch],
|
||||
{ title: '正在新增通知渠道', successTitle: '通知渠道已新增' },
|
||||
);
|
||||
} else {
|
||||
setChannels(
|
||||
channels.map((c, idx) => (idx === dialog.index ? ch : c)),
|
||||
{ title: '正在更新通知渠道', successTitle: '通知渠道已更新' },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const test = async (id: string) => {
|
||||
setTesting(id);
|
||||
// Persist any pending edit first — the server tests the stored channel by id.
|
||||
if (saveTimer.current) {
|
||||
clearTimeout(saveTimer.current);
|
||||
saveTimer.current = null;
|
||||
}
|
||||
try {
|
||||
const res = await runAction(
|
||||
{
|
||||
title: '正在测试通知渠道',
|
||||
detail: id,
|
||||
successTitle: '测试通知已发送',
|
||||
successDetail: id,
|
||||
errorTitle: '通知渠道测试失败',
|
||||
resultError: (result) => result.success ? null : result.message || '测试发送失败',
|
||||
/** Apply locally + debounced auto-save. A generation guard reconciles with
|
||||
* the server's normalized result only if no newer edit landed meanwhile. */
|
||||
const commit = (
|
||||
next: NotificationsConfig,
|
||||
copy: { title: string; successTitle: string } = {
|
||||
title: '正在更新通知配置',
|
||||
successTitle: '通知配置已更新',
|
||||
},
|
||||
async () => {
|
||||
await api.notifications.saveConfig(config);
|
||||
return api.notifications.test(id);
|
||||
},
|
||||
);
|
||||
flash(res.success ? 'ok' : 'err', res.message ?? (res.success ? '测试发送成功' : '测试发送失败'));
|
||||
} catch (error) {
|
||||
console.error('test notification channel failed', error);
|
||||
flash('err', '测试请求失败');
|
||||
} finally {
|
||||
setTesting(null);
|
||||
) => {
|
||||
setConfig(next);
|
||||
const gen = ++saveGen.current;
|
||||
|
||||
if (saveTimer.current) {
|
||||
clearTimeout(saveTimer.current);
|
||||
}
|
||||
|
||||
saveTimer.current = window.setTimeout(() => {
|
||||
void runAction(
|
||||
{
|
||||
title: copy.title,
|
||||
detail: '正在同步通知渠道设置',
|
||||
successTitle: copy.successTitle,
|
||||
successDetail: '通知配置已同步',
|
||||
errorTitle: '通知配置更新失败',
|
||||
},
|
||||
() => api.notifications.saveConfig(next),
|
||||
)
|
||||
.then((result) => {
|
||||
// Only the latest save reconciles + confirms; a superseded in-flight
|
||||
// save stays silent (its successor will confirm).
|
||||
if (saveGen.current !== gen) {
|
||||
return;
|
||||
}
|
||||
|
||||
setConfig(result);
|
||||
flash('ok', '已保存');
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('save notifications config failed', error);
|
||||
flash('err', '保存失败,请检查服务器日志');
|
||||
});
|
||||
}, 350);
|
||||
};
|
||||
|
||||
if (loading || !config) {
|
||||
return (
|
||||
<SkeletonSwap
|
||||
ready={!loading}
|
||||
lines={6}
|
||||
lineHeight={26}
|
||||
reserve={156}
|
||||
label="通知配置"
|
||||
className={!loading ? 'skeleton-swap-fluid min-h-[156px]' : ''}
|
||||
>
|
||||
{!loading && !config ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-center justify-between gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive"
|
||||
>
|
||||
<span>{msg?.text ?? '加载通知配置失败'}</span>
|
||||
<Button variant="outline" size="sm" onClick={() => void load()}>
|
||||
重试
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</SkeletonSwap>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SkeletonSwap
|
||||
ready
|
||||
lines={6}
|
||||
lineHeight={26}
|
||||
reserve={156}
|
||||
label="通知配置"
|
||||
className="skeleton-swap-fluid min-h-[156px]"
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Global settings */}
|
||||
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
|
||||
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
<Bell className="mt-0.5 size-3.5 shrink-0" />
|
||||
<p>
|
||||
账号上线 / 下线时向启用的渠道发送通知(Webhook POST 或邮件,仅去抖防刷屏)。渠道在此全局定义,每个账号在其「配置」页勾选启用哪些。
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5 border-t pt-3">
|
||||
<Label>去抖窗口(秒)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={3600}
|
||||
className="w-32 tabular-nums"
|
||||
value={config.debounceSeconds}
|
||||
onChange={(e) => {
|
||||
const n = Math.trunc(Number(e.target.value));
|
||||
commit({ ...config, debounceSeconds: Number.isFinite(n) ? Math.min(3600, Math.max(0, n)) : 0 });
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
下线后在该秒数内自愈则不发;超时才发「下线」,恢复时再发「上线」。<code className="font-mono">0</code> = 立即发、不去抖。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
const channels = config.channels;
|
||||
const setChannels = (
|
||||
next: NotificationChannel[],
|
||||
copy?: { title: string; successTitle: string },
|
||||
) => commit({ ...config, channels: next }, copy);
|
||||
const otherIds = (index: number | null) =>
|
||||
channels.filter((_, i) => i !== index).map((c) => c.id);
|
||||
|
||||
{/* Channels */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold tracking-tight">通知渠道</h3>
|
||||
{channels.length > 0 && (
|
||||
<Button variant="outline" size="sm" onClick={openCreate}>
|
||||
<Plus className="size-3.5" /> 新增渠道
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
const openCreate = () => setDialog({ open: true, index: null, seed: blankChannel(channels) });
|
||||
const openEdit = (i: number) => setDialog({ open: true, index: i, seed: channels[i] });
|
||||
|
||||
{channels.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
|
||||
<Bell className="size-8 opacity-40" strokeWidth={1.5} />
|
||||
<p className="text-sm">还没有通知渠道</p>
|
||||
<Button variant="outline" size="sm" onClick={openCreate}>
|
||||
<Plus className="size-3.5" /> 创建第一个
|
||||
</Button>
|
||||
const submitChannel = (ch: NotificationChannel) => {
|
||||
if (dialog.index == null) {
|
||||
setChannels([...channels, ch], {
|
||||
title: '正在新增通知渠道',
|
||||
successTitle: '通知渠道已新增',
|
||||
});
|
||||
} else {
|
||||
setChannels(
|
||||
channels.map((c, idx) => (idx === dialog.index ? ch : c)),
|
||||
{ title: '正在更新通知渠道', successTitle: '通知渠道已更新' },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const test = async (id: string) => {
|
||||
setTesting(id);
|
||||
|
||||
// Persist any pending edit first — the server tests the stored channel by id.
|
||||
if (saveTimer.current) {
|
||||
clearTimeout(saveTimer.current);
|
||||
saveTimer.current = null;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await runAction(
|
||||
{
|
||||
title: '正在测试通知渠道',
|
||||
detail: id,
|
||||
successTitle: '测试通知已发送',
|
||||
successDetail: id,
|
||||
errorTitle: '通知渠道测试失败',
|
||||
resultError: (result) =>
|
||||
result.success ? null : result.message || '测试发送失败',
|
||||
},
|
||||
async () => {
|
||||
await api.notifications.saveConfig(config);
|
||||
return api.notifications.test(id);
|
||||
},
|
||||
);
|
||||
flash(
|
||||
res.success ? 'ok' : 'err',
|
||||
res.message ?? (res.success ? '测试发送成功' : '测试发送失败'),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('test notification channel failed', error);
|
||||
flash('err', '测试请求失败');
|
||||
} finally {
|
||||
setTesting(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SkeletonSwap
|
||||
ready
|
||||
lines={6}
|
||||
lineHeight={26}
|
||||
reserve={156}
|
||||
label="通知配置"
|
||||
className="skeleton-swap-fluid min-h-[156px]"
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Global settings */}
|
||||
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
|
||||
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
<Bell className="mt-0.5 size-3.5 shrink-0" />
|
||||
<p>
|
||||
账号上线 / 下线时向启用的渠道发送通知(Webhook POST
|
||||
或邮件,仅去抖防刷屏)。渠道在此全局定义,每个账号在其「配置」页勾选启用哪些。
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5 border-t pt-3">
|
||||
<Label>去抖窗口(秒)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={3600}
|
||||
className="w-32 tabular-nums"
|
||||
value={config.debounceSeconds}
|
||||
onChange={(e) => {
|
||||
const n = Math.trunc(Number(e.target.value));
|
||||
commit({
|
||||
...config,
|
||||
debounceSeconds: Number.isFinite(n)
|
||||
? Math.min(3600, Math.max(0, n))
|
||||
: 0,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
下线后在该秒数内自愈则不发;超时才发「下线」,恢复时再发「上线」。
|
||||
<code className="font-mono">0</code> = 立即发、不去抖。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Channels */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold tracking-tight">通知渠道</h3>
|
||||
{channels.length > 0 && (
|
||||
<Button variant="outline" size="sm" onClick={openCreate}>
|
||||
<Plus className="size-3.5" /> 新增渠道
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{channels.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
|
||||
<Bell className="size-8 opacity-40" strokeWidth={1.5} />
|
||||
<p className="text-sm">还没有通知渠道</p>
|
||||
<Button variant="outline" size="sm" onClick={openCreate}>
|
||||
<Plus className="size-3.5" /> 创建第一个
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{channels.map((ch, i) => (
|
||||
<ChannelCard
|
||||
key={ch.id}
|
||||
channel={ch}
|
||||
testing={testing === ch.id}
|
||||
onToggle={(v) =>
|
||||
setChannels(
|
||||
channels.map((c, idx) =>
|
||||
idx === i ? { ...c, enabled: v } : c,
|
||||
),
|
||||
{
|
||||
title: '正在更新通知渠道',
|
||||
successTitle: '通知渠道已更新',
|
||||
},
|
||||
)
|
||||
}
|
||||
onTest={() => void test(ch.id)}
|
||||
onEdit={() => openEdit(i)}
|
||||
onDelete={() =>
|
||||
setChannels(
|
||||
channels.filter((_, idx) => idx !== i),
|
||||
{
|
||||
title: '正在删除通知渠道',
|
||||
successTitle: '通知渠道已删除',
|
||||
},
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{msg && (
|
||||
<p
|
||||
className={cn(
|
||||
'text-xs',
|
||||
msg.kind === 'ok' ? 'text-success' : 'text-destructive',
|
||||
)}
|
||||
>
|
||||
{msg.text}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{dialog.open && (
|
||||
<NotificationChannelDialog
|
||||
open={dialog.open}
|
||||
onOpenChange={(open) => !open && setDialog((d) => ({ ...d, open: false }))}
|
||||
isEdit={dialog.index != null}
|
||||
initial={dialog.seed}
|
||||
otherIds={otherIds(dialog.index)}
|
||||
onSubmit={submitChannel}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{channels.map((ch, i) => (
|
||||
<ChannelCard
|
||||
key={ch.id}
|
||||
channel={ch}
|
||||
testing={testing === ch.id}
|
||||
onToggle={(v) => setChannels(
|
||||
channels.map((c, idx) => (idx === i ? { ...c, enabled: v } : c)),
|
||||
{ title: '正在更新通知渠道', successTitle: '通知渠道已更新' },
|
||||
)}
|
||||
onTest={() => void test(ch.id)}
|
||||
onEdit={() => openEdit(i)}
|
||||
onDelete={() => setChannels(
|
||||
channels.filter((_, idx) => idx !== i),
|
||||
{ title: '正在删除通知渠道', successTitle: '通知渠道已删除' },
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{msg && <p className={cn('text-xs', msg.kind === 'ok' ? 'text-success' : 'text-destructive')}>{msg.text}</p>}
|
||||
|
||||
{dialog.open && (
|
||||
<NotificationChannelDialog
|
||||
open={dialog.open}
|
||||
onOpenChange={(open) => !open && setDialog((d) => ({ ...d, open: false }))}
|
||||
isEdit={dialog.index != null}
|
||||
initial={dialog.seed}
|
||||
otherIds={otherIds(dialog.index)}
|
||||
onSubmit={submitChannel}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</SkeletonSwap>
|
||||
);
|
||||
</SkeletonSwap>
|
||||
);
|
||||
}
|
||||
|
||||
interface ChannelCardProps {
|
||||
channel: NotificationChannel;
|
||||
testing: boolean;
|
||||
onToggle: (v: boolean) => void;
|
||||
onTest: () => void;
|
||||
onEdit: () => void;
|
||||
onDelete: () => void;
|
||||
channel: NotificationChannel;
|
||||
testing: boolean;
|
||||
onToggle: (v: boolean) => void;
|
||||
onTest: () => void;
|
||||
onEdit: () => void;
|
||||
onDelete: () => void;
|
||||
}
|
||||
|
||||
/** Info-only row + inline actions. No live-typed fields — editing is the dialog. */
|
||||
function ChannelCard({ channel, testing, onToggle, onTest, onEdit, onDelete }: ChannelCardProps) {
|
||||
const off = useTheme().appearance.disableMotion;
|
||||
return (
|
||||
<motion.div
|
||||
initial={off ? false : { opacity: 0, y: 4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={off ? { duration: 0 } : { duration: 0.18 }}
|
||||
className={cn(
|
||||
'flex flex-col gap-2 rounded-xl border bg-card/40 p-3.5 transition-[background-color,opacity] duration-150 ease-out hover:bg-accent/20 sm:flex-row sm:items-center sm:gap-3',
|
||||
!channel.enabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium">{channel.name || channel.id}</span>
|
||||
<Badge variant="secondary" className="font-mono font-normal">{channel.id}</Badge>
|
||||
<Badge variant="outline" className="font-normal">
|
||||
{notificationChannelType(channel) === 'email' ? '邮件' : 'Webhook'}
|
||||
</Badge>
|
||||
{!channel.enabled && <Badge variant="secondary" className="font-normal">已停用</Badge>}
|
||||
</div>
|
||||
<div className="mt-0.5 truncate font-mono text-xs text-muted-foreground">
|
||||
{notificationChannelType(channel) === 'email'
|
||||
? [channel.to, channel.smtpHost].filter(Boolean).join(' · ')
|
||||
: channel.url}
|
||||
</div>
|
||||
<div className="mt-1 truncate font-mono text-meta text-muted-foreground/80">
|
||||
{notificationChannelType(channel) === 'email'
|
||||
? (channel.subjectTemplate || channel.bodyTemplate)
|
||||
: channel.bodyTemplate}
|
||||
</div>
|
||||
</div>
|
||||
const off = useTheme().appearance.disableMotion;
|
||||
return (
|
||||
<motion.div
|
||||
initial={off ? false : { opacity: 0, y: 4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={off ? { duration: 0 } : { duration: 0.18 }}
|
||||
className={cn(
|
||||
'flex flex-col gap-2 rounded-xl border bg-card/40 p-3.5 transition-[background-color,opacity] duration-150 ease-out hover:bg-accent/20 sm:flex-row sm:items-center sm:gap-3',
|
||||
!channel.enabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium">{channel.name || channel.id}</span>
|
||||
<Badge variant="secondary" className="font-mono font-normal">
|
||||
{channel.id}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="font-normal">
|
||||
{notificationChannelType(channel) === 'email' ? '邮件' : 'Webhook'}
|
||||
</Badge>
|
||||
{!channel.enabled && (
|
||||
<Badge variant="secondary" className="font-normal">
|
||||
已停用
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 truncate font-mono text-xs text-muted-foreground">
|
||||
{notificationChannelType(channel) === 'email'
|
||||
? [channel.to, channel.smtpHost].filter(Boolean).join(' · ')
|
||||
: channel.url}
|
||||
</div>
|
||||
<div className="mt-1 truncate font-mono text-meta text-muted-foreground/80">
|
||||
{notificationChannelType(channel) === 'email'
|
||||
? channel.subjectTemplate || channel.bodyTemplate
|
||||
: channel.bodyTemplate}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 sm:justify-end">
|
||||
<ToggleSwitch value={channel.enabled} onChange={onToggle} ariaLabel={`启用 ${channel.name || channel.id}`} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onTest}
|
||||
disabled={testing}
|
||||
aria-label="测试发送"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{testing ? <Loader2 className="size-4 animate-spin" /> : <Send className="optical-forward size-4" />}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onEdit}
|
||||
aria-label="编辑"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Pencil className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onDelete}
|
||||
aria-label="删除"
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
<div className="flex items-center gap-1.5 sm:justify-end">
|
||||
<ToggleSwitch
|
||||
value={channel.enabled}
|
||||
onChange={onToggle}
|
||||
ariaLabel={`启用 ${channel.name || channel.id}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onTest}
|
||||
disabled={testing}
|
||||
aria-label="测试发送"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{testing ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="optical-forward size-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onEdit}
|
||||
aria-label="编辑"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Pencil className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onDelete}
|
||||
aria-label="删除"
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -12,400 +12,480 @@ import { TotpRecoveryCodes } from '@/components/settings/totp-recovery-codes';
|
||||
import { copyText } from '@/lib/utils';
|
||||
|
||||
function SettingRow({
|
||||
label,
|
||||
hint,
|
||||
children,
|
||||
label,
|
||||
hint,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
hint?: string;
|
||||
children: React.ReactNode;
|
||||
label: string;
|
||||
hint?: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-3 px-5 py-4 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium">{label}</p>
|
||||
{hint && <p className="mt-0.5 text-[12px] leading-snug text-muted-foreground">{hint}</p>}
|
||||
</div>
|
||||
<div className="sm:shrink-0">{children}</div>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className="flex flex-col gap-3 px-5 py-4 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium">{label}</p>
|
||||
{hint && (
|
||||
<p className="mt-0.5 text-[12px] leading-snug text-muted-foreground">{hint}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="sm:shrink-0">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TotpPanel() {
|
||||
const api = useApi();
|
||||
const [status, setStatus] = useState<TotpStatus | 'hidden' | 'loading'>('loading');
|
||||
const [setupOpen, setSetupOpen] = useState(false);
|
||||
const [disableOpen, setDisableOpen] = useState(false);
|
||||
const [regenOpen, setRegenOpen] = useState(false);
|
||||
const api = useApi();
|
||||
const [status, setStatus] = useState<TotpStatus | 'hidden' | 'loading'>('loading');
|
||||
const [setupOpen, setSetupOpen] = useState(false);
|
||||
const [disableOpen, setDisableOpen] = useState(false);
|
||||
const [regenOpen, setRegenOpen] = useState(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
setStatus(await api.totp.status());
|
||||
} catch {
|
||||
setStatus('hidden');
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
setStatus(await api.totp.status());
|
||||
} catch {
|
||||
setStatus('hidden');
|
||||
}
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
if (status === 'hidden') {
|
||||
return null;
|
||||
}
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => { void refresh(); }, [refresh]);
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<CardHeader className="gap-1 pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-[15px]">
|
||||
<ShieldCheck className="size-4 text-primary" />
|
||||
双重验证
|
||||
</CardTitle>
|
||||
<CardDescription className="text-[12px] leading-relaxed">
|
||||
登录时在访问密码之外再验证 Authenticator 一次性密码。默认关闭。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<div className="divide-y divide-border/60 border-t border-border/60">
|
||||
{status === 'loading' ? (
|
||||
<SettingRow label="2FA" hint="正在读取…">
|
||||
<span className="text-sm text-muted-foreground">…</span>
|
||||
</SettingRow>
|
||||
) : status.enabled ? (
|
||||
<>
|
||||
<SettingRow
|
||||
label="状态"
|
||||
hint={`已绑定 ${status.label} · 剩余 ${status.remainingRecoveryCodes} 个恢复码`}
|
||||
>
|
||||
<span className="text-sm text-success">已开启</span>
|
||||
</SettingRow>
|
||||
<SettingRow label="恢复码" hint="重新生成后旧码立即作废。">
|
||||
<Button variant="outline" size="sm" onClick={() => setRegenOpen(true)}>
|
||||
重新生成
|
||||
</Button>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
label="关闭 2FA"
|
||||
hint="需要当前密码,以及验证码或恢复码。其他设备的会话将失效。"
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => setDisableOpen(true)}
|
||||
>
|
||||
关闭
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</>
|
||||
) : (
|
||||
<SettingRow
|
||||
label="Authenticator"
|
||||
hint="扫描二维码或手动输入密钥,再用 6 位验证码确认。"
|
||||
>
|
||||
<Button variant="outline" size="sm" onClick={() => setSetupOpen(true)}>
|
||||
<KeyRound className="size-4" /> 开启 2FA
|
||||
</Button>
|
||||
</SettingRow>
|
||||
)}
|
||||
</div>
|
||||
|
||||
if (status === 'hidden') return null;
|
||||
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<CardHeader className="gap-1 pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-[15px]">
|
||||
<ShieldCheck className="size-4 text-primary" />
|
||||
双重验证
|
||||
</CardTitle>
|
||||
<CardDescription className="text-[12px] leading-relaxed">
|
||||
登录时在访问密码之外再验证 Authenticator 一次性密码。默认关闭。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<div className="divide-y divide-border/60 border-t border-border/60">
|
||||
{status === 'loading' ? (
|
||||
<SettingRow label="2FA" hint="正在读取…">
|
||||
<span className="text-sm text-muted-foreground">…</span>
|
||||
</SettingRow>
|
||||
) : status.enabled ? (
|
||||
<>
|
||||
<SettingRow label="状态" hint={`已绑定 ${status.label} · 剩余 ${status.remainingRecoveryCodes} 个恢复码`}>
|
||||
<span className="text-sm text-success">已开启</span>
|
||||
</SettingRow>
|
||||
<SettingRow label="恢复码" hint="重新生成后旧码立即作废。">
|
||||
<Button variant="outline" size="sm" onClick={() => setRegenOpen(true)}>
|
||||
重新生成
|
||||
</Button>
|
||||
</SettingRow>
|
||||
<SettingRow label="关闭 2FA" hint="需要当前密码,以及验证码或恢复码。其他设备的会话将失效。">
|
||||
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" onClick={() => setDisableOpen(true)}>
|
||||
关闭
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</>
|
||||
) : (
|
||||
<SettingRow label="Authenticator" hint="扫描二维码或手动输入密钥,再用 6 位验证码确认。">
|
||||
<Button variant="outline" size="sm" onClick={() => setSetupOpen(true)}>
|
||||
<KeyRound className="size-4" /> 开启 2FA
|
||||
</Button>
|
||||
</SettingRow>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TotpSetupDialog
|
||||
open={setupOpen}
|
||||
onOpenChange={setSetupOpen}
|
||||
onEnabled={async () => { await refresh(); }}
|
||||
/>
|
||||
<TotpChallengeDialog
|
||||
open={disableOpen}
|
||||
onOpenChange={setDisableOpen}
|
||||
title="关闭双重验证"
|
||||
description="关闭后,只需访问密码即可登录。其他已登录会话会立即失效。"
|
||||
confirmText="关闭 2FA"
|
||||
destructive
|
||||
onSubmit={async (password, second) => api.totp.disable(password, second)}
|
||||
onDone={refresh}
|
||||
/>
|
||||
<TotpRegenDialog
|
||||
open={regenOpen}
|
||||
onOpenChange={setRegenOpen}
|
||||
onDone={refresh}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
<TotpSetupDialog
|
||||
open={setupOpen}
|
||||
onOpenChange={setSetupOpen}
|
||||
onEnabled={async () => {
|
||||
await refresh();
|
||||
}}
|
||||
/>
|
||||
<TotpChallengeDialog
|
||||
open={disableOpen}
|
||||
onOpenChange={setDisableOpen}
|
||||
title="关闭双重验证"
|
||||
description="关闭后,只需访问密码即可登录。其他已登录会话会立即失效。"
|
||||
confirmText="关闭 2FA"
|
||||
destructive
|
||||
onSubmit={async (password, second) => api.totp.disable(password, second)}
|
||||
onDone={refresh}
|
||||
/>
|
||||
<TotpRegenDialog open={regenOpen} onOpenChange={setRegenOpen} onDone={refresh} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function TotpSetupDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onEnabled,
|
||||
open,
|
||||
onOpenChange,
|
||||
onEnabled,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onEnabled: () => void | Promise<void>;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onEnabled: () => void | Promise<void>;
|
||||
}) {
|
||||
const api = useApi();
|
||||
const [enrollment, setEnrollment] = useState<TotpEnrollment | null>(null);
|
||||
const [issuer, setIssuer] = useState('');
|
||||
const [accountName, setAccountName] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);
|
||||
const api = useApi();
|
||||
const [enrollment, setEnrollment] = useState<TotpEnrollment | null>(null);
|
||||
const [issuer, setIssuer] = useState('');
|
||||
const [accountName, setAccountName] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);
|
||||
|
||||
const loadEnrollment = useCallback(async (nextIssuer?: string, nextAccount?: string) => {
|
||||
const result = await api.totp.begin({
|
||||
...(nextIssuer ? { issuer: nextIssuer } : {}),
|
||||
...(nextAccount ? { accountName: nextAccount } : {}),
|
||||
});
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
setEnrollment(result);
|
||||
setIssuer(result.issuer);
|
||||
setAccountName(result.accountName);
|
||||
setError('');
|
||||
}, [api]);
|
||||
const loadEnrollment = useCallback(
|
||||
async (nextIssuer?: string, nextAccount?: string) => {
|
||||
const result = await api.totp.begin({
|
||||
...(nextIssuer ? { issuer: nextIssuer } : {}),
|
||||
...(nextAccount ? { accountName: nextAccount } : {}),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setEnrollment(null);
|
||||
setPassword('');
|
||||
setCode('');
|
||||
setError('');
|
||||
setRecoveryCodes(null);
|
||||
return;
|
||||
}
|
||||
void loadEnrollment();
|
||||
}, [open, loadEnrollment]);
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
|
||||
const refreshLabels = async () => {
|
||||
if (!enrollment) return;
|
||||
await loadEnrollment(issuer, accountName);
|
||||
};
|
||||
setEnrollment(result);
|
||||
setIssuer(result.issuer);
|
||||
setAccountName(result.accountName);
|
||||
setError('');
|
||||
},
|
||||
[api],
|
||||
);
|
||||
|
||||
const confirm = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
await loadEnrollment(issuer, accountName);
|
||||
const result = await api.totp.confirm(password, code);
|
||||
setBusy(false);
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
setRecoveryCodes(result.recoveryCodes);
|
||||
await onEnabled();
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setEnrollment(null);
|
||||
setPassword('');
|
||||
setCode('');
|
||||
setError('');
|
||||
setRecoveryCodes(null);
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => { if (!recoveryCodes) onOpenChange(false); }}
|
||||
title={recoveryCodes ? '保存恢复码' : '开启双重验证'}
|
||||
description={recoveryCodes
|
||||
? '这些恢复码只显示一次。丢失 Authenticator 时用它们登录。'
|
||||
: '用 Authenticator 扫描二维码,或手动输入密钥,然后输入当前访问密码和 6 位验证码。'}
|
||||
closeLabel="关闭 2FA 绑定"
|
||||
maxWidth={440}
|
||||
>
|
||||
{recoveryCodes ? (
|
||||
<TotpRecoveryCodes codes={recoveryCodes} onConfirm={() => onOpenChange(false)} />
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
{enrollment && (
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<TotpQr value={enrollment.otpauthUrl} label="2FA 绑定二维码" />
|
||||
<p className="break-all text-center font-mono text-xs text-muted-foreground">{enrollment.secret}</p>
|
||||
<div className="flex flex-wrap justify-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => { void copyText(enrollment.secret); }}
|
||||
>
|
||||
复制密钥
|
||||
</Button>
|
||||
<a
|
||||
href={enrollment.otpauthUrl}
|
||||
className="inline-flex h-8 items-center rounded-md border border-border px-3 text-xs font-medium text-foreground"
|
||||
>
|
||||
在验证器中打开
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
||||
服务名
|
||||
<Input value={issuer} onChange={(e) => setIssuer(e.target.value)} onBlur={() => { void refreshLabels(); }} />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
||||
账号名
|
||||
<Input value={accountName} onChange={(e) => setAccountName(e.target.value)} onBlur={() => { void refreshLabels(); }} />
|
||||
</label>
|
||||
</div>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="当前访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<Input
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
pattern="[0-9]*"
|
||||
placeholder="6 位验证码"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
/>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
<Button type="button" disabled={busy || !password || !code} onClick={() => { void confirm(); }}>
|
||||
{busy ? '正在开启…' : '确认开启'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
void loadEnrollment();
|
||||
}, [open, loadEnrollment]);
|
||||
|
||||
const refreshLabels = async () => {
|
||||
if (!enrollment) {
|
||||
return;
|
||||
}
|
||||
|
||||
await loadEnrollment(issuer, accountName);
|
||||
};
|
||||
|
||||
const confirm = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
await loadEnrollment(issuer, accountName);
|
||||
const result = await api.totp.confirm(password, code);
|
||||
setBusy(false);
|
||||
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
|
||||
setRecoveryCodes(result.recoveryCodes);
|
||||
await onEnabled();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => {
|
||||
if (!recoveryCodes) {
|
||||
onOpenChange(false);
|
||||
}
|
||||
}}
|
||||
title={recoveryCodes ? '保存恢复码' : '开启双重验证'}
|
||||
description={
|
||||
recoveryCodes
|
||||
? '这些恢复码只显示一次。丢失 Authenticator 时用它们登录。'
|
||||
: '用 Authenticator 扫描二维码,或手动输入密钥,然后输入当前访问密码和 6 位验证码。'
|
||||
}
|
||||
closeLabel="关闭 2FA 绑定"
|
||||
maxWidth={440}
|
||||
>
|
||||
{recoveryCodes ? (
|
||||
<TotpRecoveryCodes codes={recoveryCodes} onConfirm={() => onOpenChange(false)} />
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
{enrollment && (
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<TotpQr value={enrollment.otpauthUrl} label="2FA 绑定二维码" />
|
||||
<p className="break-all text-center font-mono text-xs text-muted-foreground">
|
||||
{enrollment.secret}
|
||||
</p>
|
||||
<div className="flex flex-wrap justify-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
void copyText(enrollment.secret);
|
||||
}}
|
||||
>
|
||||
复制密钥
|
||||
</Button>
|
||||
<a
|
||||
href={enrollment.otpauthUrl}
|
||||
className="inline-flex h-8 items-center rounded-md border border-border px-3 text-xs font-medium text-foreground"
|
||||
>
|
||||
在验证器中打开
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
||||
服务名
|
||||
<Input
|
||||
value={issuer}
|
||||
onChange={(e) => setIssuer(e.target.value)}
|
||||
onBlur={() => {
|
||||
void refreshLabels();
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
|
||||
账号名
|
||||
<Input
|
||||
value={accountName}
|
||||
onChange={(e) => setAccountName(e.target.value)}
|
||||
onBlur={() => {
|
||||
void refreshLabels();
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="当前访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<Input
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
pattern="[0-9]*"
|
||||
placeholder="6 位验证码"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
/>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
<Button
|
||||
type="button"
|
||||
disabled={busy || !password || !code}
|
||||
onClick={() => {
|
||||
void confirm();
|
||||
}}
|
||||
>
|
||||
{busy ? '正在开启…' : '确认开启'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function TotpChallengeDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
confirmText,
|
||||
destructive,
|
||||
onSubmit,
|
||||
onDone,
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
confirmText,
|
||||
destructive,
|
||||
onSubmit,
|
||||
onDone,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
description: string;
|
||||
confirmText: string;
|
||||
destructive?: boolean;
|
||||
onSubmit: (password: string, second: { totp?: string; recoveryCode?: string }) => Promise<{ success: boolean; message?: string }>;
|
||||
onDone: () => void | Promise<void>;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
description: string;
|
||||
confirmText: string;
|
||||
destructive?: boolean;
|
||||
onSubmit: (
|
||||
password: string,
|
||||
second: { totp?: string; recoveryCode?: string },
|
||||
) => Promise<{ success: boolean; message?: string }>;
|
||||
onDone: () => void | Promise<void>;
|
||||
}) {
|
||||
const [password, setPassword] = useState('');
|
||||
const [second, setSecond] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [password, setPassword] = useState('');
|
||||
const [second, setSecond] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setPassword('');
|
||||
setSecond('');
|
||||
setError('');
|
||||
}
|
||||
}, [open]);
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setPassword('');
|
||||
setSecond('');
|
||||
setError('');
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const result = await onSubmit(password, parseSecondFactor(second));
|
||||
setBusy(false);
|
||||
if (!result.success) {
|
||||
setError(result.message ?? '操作失败');
|
||||
return;
|
||||
}
|
||||
await onDone();
|
||||
onOpenChange(false);
|
||||
};
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const result = await onSubmit(password, parseSecondFactor(second));
|
||||
setBusy(false);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => onOpenChange(false)}
|
||||
title={title}
|
||||
description={description}
|
||||
closeLabel={`关闭${title}`}
|
||||
maxWidth={400}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="当前访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<Input
|
||||
placeholder="6 位验证码或恢复码"
|
||||
value={second}
|
||||
onChange={(e) => setSecond(e.target.value)}
|
||||
autoComplete="one-time-code"
|
||||
/>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
<Button
|
||||
type="button"
|
||||
variant={destructive ? 'destructive' : 'default'}
|
||||
disabled={busy || !password || !second.trim()}
|
||||
onClick={() => { void submit(); }}
|
||||
if (!result.success) {
|
||||
setError(result.message ?? '操作失败');
|
||||
return;
|
||||
}
|
||||
|
||||
await onDone();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => onOpenChange(false)}
|
||||
title={title}
|
||||
description={description}
|
||||
closeLabel={`关闭${title}`}
|
||||
maxWidth={400}
|
||||
>
|
||||
{busy ? '处理中…' : confirmText}
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
<div className="flex flex-col gap-3">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="当前访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<Input
|
||||
placeholder="6 位验证码或恢复码"
|
||||
value={second}
|
||||
onChange={(e) => setSecond(e.target.value)}
|
||||
autoComplete="one-time-code"
|
||||
/>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
<Button
|
||||
type="button"
|
||||
variant={destructive ? 'destructive' : 'default'}
|
||||
disabled={busy || !password || !second.trim()}
|
||||
onClick={() => {
|
||||
void submit();
|
||||
}}
|
||||
>
|
||||
{busy ? '处理中…' : confirmText}
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function TotpRegenDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onDone,
|
||||
open,
|
||||
onOpenChange,
|
||||
onDone,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onDone: () => void | Promise<void>;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onDone: () => void | Promise<void>;
|
||||
}) {
|
||||
const api = useApi();
|
||||
const [password, setPassword] = useState('');
|
||||
const [totp, setTotp] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [codes, setCodes] = useState<string[] | null>(null);
|
||||
const api = useApi();
|
||||
const [password, setPassword] = useState('');
|
||||
const [totp, setTotp] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [codes, setCodes] = useState<string[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setPassword('');
|
||||
setTotp('');
|
||||
setError('');
|
||||
setCodes(null);
|
||||
}
|
||||
}, [open]);
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setPassword('');
|
||||
setTotp('');
|
||||
setError('');
|
||||
setCodes(null);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const result = await api.totp.regenerateRecoveryCodes(password, totp.trim());
|
||||
setBusy(false);
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
setCodes(result.recoveryCodes);
|
||||
await onDone();
|
||||
};
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const result = await api.totp.regenerateRecoveryCodes(password, totp.trim());
|
||||
setBusy(false);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => { if (!codes) onOpenChange(false); }}
|
||||
title={codes ? '新的恢复码' : '重新生成恢复码'}
|
||||
description={codes ? '旧恢复码已作废。请保存下面的新码。' : '需要当前密码和 Authenticator 验证码。旧恢复码会立即作废。'}
|
||||
closeLabel="关闭恢复码"
|
||||
maxWidth={440}
|
||||
>
|
||||
{codes ? (
|
||||
<TotpRecoveryCodes codes={codes} onConfirm={() => onOpenChange(false)} />
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="当前访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<Input
|
||||
inputMode="numeric"
|
||||
placeholder="6 位验证码"
|
||||
value={totp}
|
||||
onChange={(e) => setTotp(e.target.value)}
|
||||
autoComplete="one-time-code"
|
||||
/>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
<Button type="button" disabled={busy || !password || !totp.trim()} onClick={() => { void submit(); }}>
|
||||
{busy ? '正在生成…' : '生成新恢复码'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
|
||||
setCodes(result.recoveryCodes);
|
||||
await onDone();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => {
|
||||
if (!codes) {
|
||||
onOpenChange(false);
|
||||
}
|
||||
}}
|
||||
title={codes ? '新的恢复码' : '重新生成恢复码'}
|
||||
description={
|
||||
codes
|
||||
? '旧恢复码已作废。请保存下面的新码。'
|
||||
: '需要当前密码和 Authenticator 验证码。旧恢复码会立即作废。'
|
||||
}
|
||||
closeLabel="关闭恢复码"
|
||||
maxWidth={440}
|
||||
>
|
||||
{codes ? (
|
||||
<TotpRecoveryCodes codes={codes} onConfirm={() => onOpenChange(false)} />
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="当前访问密码"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<Input
|
||||
inputMode="numeric"
|
||||
placeholder="6 位验证码"
|
||||
value={totp}
|
||||
onChange={(e) => setTotp(e.target.value)}
|
||||
autoComplete="one-time-code"
|
||||
/>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
<Button
|
||||
type="button"
|
||||
disabled={busy || !password || !totp.trim()}
|
||||
onClick={() => {
|
||||
void submit();
|
||||
}}
|
||||
>
|
||||
{busy ? '正在生成…' : '生成新恢复码'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -2,33 +2,37 @@ import { useMemo } from 'react';
|
||||
import { encode } from 'uqr';
|
||||
|
||||
export function TotpQr({ value, label }: { value: string; label: string }) {
|
||||
const qr = useMemo(() => encode(value, { ecc: 'M', border: 4 }), [value]);
|
||||
const modulePx = 4;
|
||||
const px = qr.size * modulePx;
|
||||
const d = useMemo(() => {
|
||||
const parts: string[] = [];
|
||||
qr.data.forEach((row, y) => {
|
||||
row.forEach((on, x) => {
|
||||
if (on) parts.push(`M${x * modulePx},${y * modulePx}h${modulePx}v${modulePx}h-${modulePx}z`);
|
||||
});
|
||||
});
|
||||
return parts.join('');
|
||||
}, [qr]);
|
||||
const qr = useMemo(() => encode(value, { ecc: 'M', border: 4 }), [value]);
|
||||
const modulePx = 4;
|
||||
const px = qr.size * modulePx;
|
||||
const d = useMemo(() => {
|
||||
const parts: string[] = [];
|
||||
qr.data.forEach((row, y) => {
|
||||
row.forEach((on, x) => {
|
||||
if (on) {
|
||||
parts.push(
|
||||
`M${x * modulePx},${y * modulePx}h${modulePx}v${modulePx}h-${modulePx}z`,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
return parts.join('');
|
||||
}, [qr]);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg bg-white p-2">
|
||||
<svg
|
||||
role="img"
|
||||
aria-label={label}
|
||||
width={px}
|
||||
height={px}
|
||||
viewBox={`0 0 ${px} ${px}`}
|
||||
className="block text-black"
|
||||
shapeRendering="crispEdges"
|
||||
>
|
||||
<rect width={px} height={px} fill="white" />
|
||||
<path d={d} fill="black" />
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className="rounded-lg bg-white p-2">
|
||||
<svg
|
||||
role="img"
|
||||
aria-label={label}
|
||||
width={px}
|
||||
height={px}
|
||||
viewBox={`0 0 ${px} ${px}`}
|
||||
className="block text-black"
|
||||
shapeRendering="crispEdges"
|
||||
>
|
||||
<rect width={px} height={px} fill="white" />
|
||||
<path d={d} fill="black" />
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,63 +4,66 @@ import { Button } from '@/components/ui/button';
|
||||
import { copyText } from '@/lib/utils';
|
||||
|
||||
export function TotpRecoveryCodes({
|
||||
codes,
|
||||
onConfirm,
|
||||
codes,
|
||||
onConfirm,
|
||||
}: {
|
||||
codes: string[];
|
||||
onConfirm: () => void;
|
||||
codes: string[];
|
||||
onConfirm: () => void;
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [copyError, setCopyError] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [copyError, setCopyError] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
每个恢复码只能用一次。请立刻抄写或保存到离线位置,关闭后将无法再查看。
|
||||
</p>
|
||||
<ol className="grid grid-cols-2 gap-2 font-mono text-sm">
|
||||
{codes.map((code) => (
|
||||
<li key={code}>
|
||||
<input
|
||||
readOnly
|
||||
value={code}
|
||||
className="w-full rounded-md border bg-muted/40 px-3 py-2 text-center tracking-wide outline-none"
|
||||
onFocus={(e) => e.currentTarget.select()}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="self-start"
|
||||
onClick={async () => {
|
||||
const ok = await copyText(codes.join('\n'));
|
||||
setCopied(ok);
|
||||
setCopyError(!ok);
|
||||
if (ok) window.setTimeout(() => setCopied(false), 1600);
|
||||
}}
|
||||
>
|
||||
{copied ? <Check className="size-4" /> : <Copy className="size-4" />}
|
||||
{copied ? '已复制' : '复制全部'}
|
||||
</Button>
|
||||
{copyError && (
|
||||
<p className="text-xs text-destructive">复制失败,请长按上面的码手动拷贝。</p>
|
||||
)}
|
||||
<label className="flex items-start gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={saved}
|
||||
onChange={(e) => setSaved(e.target.checked)}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
我已把恢复码保存到安全的地方
|
||||
</label>
|
||||
<Button type="button" disabled={!saved} onClick={onConfirm}>
|
||||
完成
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
每个恢复码只能用一次。请立刻抄写或保存到离线位置,关闭后将无法再查看。
|
||||
</p>
|
||||
<ol className="grid grid-cols-2 gap-2 font-mono text-sm">
|
||||
{codes.map((code) => (
|
||||
<li key={code}>
|
||||
<input
|
||||
readOnly
|
||||
value={code}
|
||||
className="w-full rounded-md border bg-muted/40 px-3 py-2 text-center tracking-wide outline-none"
|
||||
onFocus={(e) => e.currentTarget.select()}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="self-start"
|
||||
onClick={async () => {
|
||||
const ok = await copyText(codes.join('\n'));
|
||||
setCopied(ok);
|
||||
setCopyError(!ok);
|
||||
|
||||
if (ok) {
|
||||
window.setTimeout(() => setCopied(false), 1600);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{copied ? <Check className="size-4" /> : <Copy className="size-4" />}
|
||||
{copied ? '已复制' : '复制全部'}
|
||||
</Button>
|
||||
{copyError && (
|
||||
<p className="text-xs text-destructive">复制失败,请长按上面的码手动拷贝。</p>
|
||||
)}
|
||||
<label className="flex items-start gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={saved}
|
||||
onChange={(e) => setSaved(e.target.checked)}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
我已把恢复码保存到安全的地方
|
||||
</label>
|
||||
<Button type="button" disabled={!saved} onClick={onConfirm}>
|
||||
完成
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user