/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState, useRef } from 'react';
import {
Button,
Form,
Row,
Col,
Typography,
Modal,
Banner,
TagInput,
Spin,
Card,
Radio,
Select,
} from '@douyinfe/semi-ui';
const { Text } = Typography;
import {
API,
removeTrailingSlash,
showError,
showSuccess,
toBoolean,
} from '../../helpers';
import axios from 'axios';
import { useTranslation } from 'react-i18next';
const SystemSetting = () => {
const { t } = useTranslation();
let [inputs, setInputs] = useState({
PasswordLoginEnabled: '',
PasswordRegisterEnabled: '',
EmailVerificationEnabled: '',
GitHubOAuthEnabled: '',
GitHubClientId: '',
GitHubClientSecret: '',
'discord.enabled': '',
'discord.client_id': '',
'discord.client_secret': '',
'oidc.enabled': '',
'oidc.client_id': '',
'oidc.client_secret': '',
'oidc.well_known': '',
'oidc.authorization_endpoint': '',
'oidc.token_endpoint': '',
'oidc.user_info_endpoint': '',
Notice: '',
SMTPServer: '',
SMTPPort: '',
SMTPAccount: '',
SMTPFrom: '',
SMTPToken: '',
WorkerUrl: '',
WorkerValidKey: '',
WorkerAllowHttpImageRequestEnabled: '',
Footer: '',
WeChatAuthEnabled: '',
WeChatServerAddress: '',
WeChatServerToken: '',
WeChatAccountQRCodeImageURL: '',
TurnstileCheckEnabled: '',
TurnstileSiteKey: '',
TurnstileSecretKey: '',
RegisterEnabled: '',
'passkey.enabled': '',
'passkey.rp_display_name': '',
'passkey.rp_id': '',
'passkey.origins': [],
'passkey.allow_insecure_origin': '',
'passkey.user_verification': 'preferred',
'passkey.attachment_preference': '',
EmailDomainRestrictionEnabled: '',
EmailAliasRestrictionEnabled: '',
SMTPSSLEnabled: '',
EmailDomainWhitelist: [],
TelegramOAuthEnabled: '',
TelegramBotToken: '',
TelegramBotName: '',
LinuxDOOAuthEnabled: '',
LinuxDOClientId: '',
LinuxDOClientSecret: '',
LinuxDOMinimumTrustLevel: '',
ServerAddress: '',
// SSRF防护配置
'fetch_setting.enable_ssrf_protection': true,
'fetch_setting.allow_private_ip': '',
'fetch_setting.domain_filter_mode': false, // true 白名单,false 黑名单
'fetch_setting.ip_filter_mode': false, // true 白名单,false 黑名单
'fetch_setting.domain_list': [],
'fetch_setting.ip_list': [],
'fetch_setting.allowed_ports': [],
'fetch_setting.apply_ip_filter_for_domain': false,
});
const [originInputs, setOriginInputs] = useState({});
const [loading, setLoading] = useState(false);
const [isLoaded, setIsLoaded] = useState(false);
const formApiRef = useRef(null);
const [emailDomainWhitelist, setEmailDomainWhitelist] = useState([]);
const [showPasswordLoginConfirmModal, setShowPasswordLoginConfirmModal] =
useState(false);
const [linuxDOOAuthEnabled, setLinuxDOOAuthEnabled] = useState(false);
const [emailToAdd, setEmailToAdd] = useState('');
const [domainFilterMode, setDomainFilterMode] = useState(true);
const [ipFilterMode, setIpFilterMode] = useState(true);
const [domainList, setDomainList] = useState([]);
const [ipList, setIpList] = useState([]);
const [allowedPorts, setAllowedPorts] = useState([]);
const getOptions = async () => {
setLoading(true);
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
switch (item.key) {
case 'TopupGroupRatio':
item.value = JSON.stringify(JSON.parse(item.value), null, 2);
break;
case 'EmailDomainWhitelist':
setEmailDomainWhitelist(item.value ? item.value.split(',') : []);
break;
case 'fetch_setting.allow_private_ip':
case 'fetch_setting.enable_ssrf_protection':
case 'fetch_setting.domain_filter_mode':
case 'fetch_setting.ip_filter_mode':
case 'fetch_setting.apply_ip_filter_for_domain':
item.value = toBoolean(item.value);
break;
case 'fetch_setting.domain_list':
try {
const domains = item.value ? JSON.parse(item.value) : [];
setDomainList(Array.isArray(domains) ? domains : []);
} catch (e) {
setDomainList([]);
}
break;
case 'fetch_setting.ip_list':
try {
const ips = item.value ? JSON.parse(item.value) : [];
setIpList(Array.isArray(ips) ? ips : []);
} catch (e) {
setIpList([]);
}
break;
case 'fetch_setting.allowed_ports':
try {
const ports = item.value ? JSON.parse(item.value) : [];
setAllowedPorts(Array.isArray(ports) ? ports : []);
} catch (e) {
setAllowedPorts(['80', '443', '8080', '8443']);
}
break;
case 'PasswordLoginEnabled':
case 'PasswordRegisterEnabled':
case 'EmailVerificationEnabled':
case 'GitHubOAuthEnabled':
case 'WeChatAuthEnabled':
case 'TelegramOAuthEnabled':
case 'RegisterEnabled':
case 'TurnstileCheckEnabled':
case 'EmailDomainRestrictionEnabled':
case 'EmailAliasRestrictionEnabled':
case 'SMTPSSLEnabled':
case 'LinuxDOOAuthEnabled':
case 'discord.enabled':
case 'oidc.enabled':
case 'passkey.enabled':
case 'passkey.allow_insecure_origin':
case 'WorkerAllowHttpImageRequestEnabled':
item.value = toBoolean(item.value);
break;
case 'passkey.origins':
// origins是逗号分隔的字符串,直接使用
item.value = item.value || '';
break;
case 'passkey.rp_display_name':
case 'passkey.rp_id':
case 'passkey.attachment_preference':
// 确保字符串字段不为null/undefined
item.value = item.value || '';
break;
case 'passkey.user_verification':
// 确保有默认值
item.value = item.value || 'preferred';
break;
case 'Price':
case 'MinTopUp':
item.value = parseFloat(item.value);
break;
default:
break;
}
newInputs[item.key] = item.value;
});
setInputs(newInputs);
setOriginInputs(newInputs);
// 同步模式布尔到本地状态
if (
typeof newInputs['fetch_setting.domain_filter_mode'] !== 'undefined'
) {
setDomainFilterMode(!!newInputs['fetch_setting.domain_filter_mode']);
}
if (typeof newInputs['fetch_setting.ip_filter_mode'] !== 'undefined') {
setIpFilterMode(!!newInputs['fetch_setting.ip_filter_mode']);
}
if (formApiRef.current) {
formApiRef.current.setValues(newInputs);
}
setIsLoaded(true);
} else {
showError(message);
}
setLoading(false);
};
useEffect(() => {
getOptions();
}, []);
const updateOptions = async (options) => {
setLoading(true);
try {
// 分离 checkbox 类型的选项和其他选项
const checkboxOptions = options.filter((opt) =>
opt.key.toLowerCase().endsWith('enabled'),
);
const otherOptions = options.filter(
(opt) => !opt.key.toLowerCase().endsWith('enabled'),
);
// 处理 checkbox 类型的选项
for (const opt of checkboxOptions) {
const res = await API.put('/api/option/', {
key: opt.key,
value: opt.value.toString(),
});
if (!res.data.success) {
showError(res.data.message);
return;
}
}
// 处理其他选项
if (otherOptions.length > 0) {
const requestQueue = otherOptions.map((opt) =>
API.put('/api/option/', {
key: opt.key,
value:
typeof opt.value === 'boolean' ? opt.value.toString() : opt.value,
}),
);
const results = await Promise.all(requestQueue);
// 检查所有请求是否成功
const errorResults = results.filter((res) => !res.data.success);
errorResults.forEach((res) => {
showError(res.data.message);
});
}
showSuccess(t('更新成功'));
// 更新本地状态
const newInputs = { ...inputs };
options.forEach((opt) => {
newInputs[opt.key] = opt.value;
});
setInputs(newInputs);
} catch (error) {
showError(t('更新失败'));
}
setLoading(false);
};
const handleFormChange = (values) => {
setInputs(values);
};
const submitWorker = async () => {
let WorkerUrl = removeTrailingSlash(inputs.WorkerUrl);
const options = [
{ key: 'WorkerUrl', value: WorkerUrl },
{
key: 'WorkerAllowHttpImageRequestEnabled',
value: inputs.WorkerAllowHttpImageRequestEnabled ? 'true' : 'false',
},
];
if (inputs.WorkerValidKey !== '' || WorkerUrl === '') {
options.push({ key: 'WorkerValidKey', value: inputs.WorkerValidKey });
}
await updateOptions(options);
};
const submitServerAddress = async () => {
let ServerAddress = removeTrailingSlash(inputs.ServerAddress);
await updateOptions([{ key: 'ServerAddress', value: ServerAddress }]);
};
const submitSMTP = async () => {
const options = [];
if (originInputs['SMTPServer'] !== inputs.SMTPServer) {
options.push({ key: 'SMTPServer', value: inputs.SMTPServer });
}
if (originInputs['SMTPAccount'] !== inputs.SMTPAccount) {
options.push({ key: 'SMTPAccount', value: inputs.SMTPAccount });
}
if (originInputs['SMTPFrom'] !== inputs.SMTPFrom) {
options.push({ key: 'SMTPFrom', value: inputs.SMTPFrom });
}
if (
originInputs['SMTPPort'] !== inputs.SMTPPort &&
inputs.SMTPPort !== ''
) {
options.push({ key: 'SMTPPort', value: inputs.SMTPPort });
}
if (
originInputs['SMTPToken'] !== inputs.SMTPToken &&
inputs.SMTPToken !== ''
) {
options.push({ key: 'SMTPToken', value: inputs.SMTPToken });
}
if (options.length > 0) {
await updateOptions(options);
}
};
const submitEmailDomainWhitelist = async () => {
if (Array.isArray(emailDomainWhitelist)) {
await updateOptions([
{
key: 'EmailDomainWhitelist',
value: emailDomainWhitelist.join(','),
},
]);
} else {
showError(t('邮箱域名白名单格式不正确'));
}
};
const submitSSRF = async () => {
const options = [];
// 处理域名过滤模式与列表
options.push({
key: 'fetch_setting.domain_filter_mode',
value: domainFilterMode,
});
if (Array.isArray(domainList)) {
options.push({
key: 'fetch_setting.domain_list',
value: JSON.stringify(domainList),
});
}
// 处理IP过滤模式与列表
options.push({
key: 'fetch_setting.ip_filter_mode',
value: ipFilterMode,
});
if (Array.isArray(ipList)) {
options.push({
key: 'fetch_setting.ip_list',
value: JSON.stringify(ipList),
});
}
// 处理端口配置
if (Array.isArray(allowedPorts)) {
options.push({
key: 'fetch_setting.allowed_ports',
value: JSON.stringify(allowedPorts),
});
}
if (options.length > 0) {
await updateOptions(options);
}
};
const handleAddEmail = () => {
if (emailToAdd && emailToAdd.trim() !== '') {
const domain = emailToAdd.trim();
// 验证域名格式
const domainRegex =
/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
if (!domainRegex.test(domain)) {
showError(t('邮箱域名格式不正确,请输入有效的域名,如 gmail.com'));
return;
}
// 检查是否已存在
if (emailDomainWhitelist.includes(domain)) {
showError(t('该域名已存在于白名单中'));
return;
}
setEmailDomainWhitelist([...emailDomainWhitelist, domain]);
setEmailToAdd('');
showSuccess(t('已添加到白名单'));
}
};
const submitWeChat = async () => {
const options = [];
if (originInputs['WeChatServerAddress'] !== inputs.WeChatServerAddress) {
options.push({
key: 'WeChatServerAddress',
value: removeTrailingSlash(inputs.WeChatServerAddress),
});
}
if (
originInputs['WeChatAccountQRCodeImageURL'] !==
inputs.WeChatAccountQRCodeImageURL
) {
options.push({
key: 'WeChatAccountQRCodeImageURL',
value: inputs.WeChatAccountQRCodeImageURL,
});
}
if (
originInputs['WeChatServerToken'] !== inputs.WeChatServerToken &&
inputs.WeChatServerToken !== ''
) {
options.push({
key: 'WeChatServerToken',
value: inputs.WeChatServerToken,
});
}
if (options.length > 0) {
await updateOptions(options);
}
};
const submitGitHubOAuth = async () => {
const options = [];
if (originInputs['GitHubClientId'] !== inputs.GitHubClientId) {
options.push({ key: 'GitHubClientId', value: inputs.GitHubClientId });
}
if (
originInputs['GitHubClientSecret'] !== inputs.GitHubClientSecret &&
inputs.GitHubClientSecret !== ''
) {
options.push({
key: 'GitHubClientSecret',
value: inputs.GitHubClientSecret,
});
}
if (options.length > 0) {
await updateOptions(options);
}
};
const submitDiscordOAuth = async () => {
const options = [];
if (originInputs['discord.client_id'] !== inputs['discord.client_id']) {
options.push({ key: 'discord.client_id', value: inputs['discord.client_id'] });
}
if (
originInputs['discord.client_secret'] !== inputs['discord.client_secret'] &&
inputs['discord.client_secret'] !== ''
) {
options.push({
key: 'discord.client_secret',
value: inputs['discord.client_secret'],
});
}
if (options.length > 0) {
await updateOptions(options);
}
};
const submitOIDCSettings = async () => {
if (inputs['oidc.well_known'] && inputs['oidc.well_known'] !== '') {
if (
!inputs['oidc.well_known'].startsWith('http://') &&
!inputs['oidc.well_known'].startsWith('https://')
) {
showError(t('Well-Known URL 必须以 http:// 或 https:// 开头'));
return;
}
try {
const res = await axios.create().get(inputs['oidc.well_known']);
inputs['oidc.authorization_endpoint'] =
res.data['authorization_endpoint'];
inputs['oidc.token_endpoint'] = res.data['token_endpoint'];
inputs['oidc.user_info_endpoint'] = res.data['userinfo_endpoint'];
showSuccess(t('获取 OIDC 配置成功!'));
} catch (err) {
console.error(err);
showError(
t('获取 OIDC 配置失败,请检查网络状况和 Well-Known URL 是否正确'),
);
return;
}
}
const options = [];
if (originInputs['oidc.well_known'] !== inputs['oidc.well_known']) {
options.push({
key: 'oidc.well_known',
value: inputs['oidc.well_known'],
});
}
if (originInputs['oidc.client_id'] !== inputs['oidc.client_id']) {
options.push({ key: 'oidc.client_id', value: inputs['oidc.client_id'] });
}
if (
originInputs['oidc.client_secret'] !== inputs['oidc.client_secret'] &&
inputs['oidc.client_secret'] !== ''
) {
options.push({
key: 'oidc.client_secret',
value: inputs['oidc.client_secret'],
});
}
if (
originInputs['oidc.authorization_endpoint'] !==
inputs['oidc.authorization_endpoint']
) {
options.push({
key: 'oidc.authorization_endpoint',
value: inputs['oidc.authorization_endpoint'],
});
}
if (originInputs['oidc.token_endpoint'] !== inputs['oidc.token_endpoint']) {
options.push({
key: 'oidc.token_endpoint',
value: inputs['oidc.token_endpoint'],
});
}
if (
originInputs['oidc.user_info_endpoint'] !==
inputs['oidc.user_info_endpoint']
) {
options.push({
key: 'oidc.user_info_endpoint',
value: inputs['oidc.user_info_endpoint'],
});
}
if (options.length > 0) {
await updateOptions(options);
}
};
const submitTelegramSettings = async () => {
const options = [
{ key: 'TelegramBotToken', value: inputs.TelegramBotToken },
{ key: 'TelegramBotName', value: inputs.TelegramBotName },
];
await updateOptions(options);
};
const submitTurnstile = async () => {
const options = [];
if (originInputs['TurnstileSiteKey'] !== inputs.TurnstileSiteKey) {
options.push({ key: 'TurnstileSiteKey', value: inputs.TurnstileSiteKey });
}
if (
originInputs['TurnstileSecretKey'] !== inputs.TurnstileSecretKey &&
inputs.TurnstileSecretKey !== ''
) {
options.push({
key: 'TurnstileSecretKey',
value: inputs.TurnstileSecretKey,
});
}
if (options.length > 0) {
await updateOptions(options);
}
};
const submitLinuxDOOAuth = async () => {
const options = [];
if (originInputs['LinuxDOClientId'] !== inputs.LinuxDOClientId) {
options.push({ key: 'LinuxDOClientId', value: inputs.LinuxDOClientId });
}
if (
originInputs['LinuxDOClientSecret'] !== inputs.LinuxDOClientSecret &&
inputs.LinuxDOClientSecret !== ''
) {
options.push({
key: 'LinuxDOClientSecret',
value: inputs.LinuxDOClientSecret,
});
}
if (
originInputs['LinuxDOMinimumTrustLevel'] !==
inputs.LinuxDOMinimumTrustLevel
) {
options.push({
key: 'LinuxDOMinimumTrustLevel',
value: inputs.LinuxDOMinimumTrustLevel,
});
}
if (options.length > 0) {
await updateOptions(options);
}
};
const submitPasskeySettings = async () => {
// 使用formApi直接获取当前表单值
const formValues = formApiRef.current?.getValues() || {};
const options = [];
options.push({
key: 'passkey.rp_display_name',
value:
formValues['passkey.rp_display_name'] ||
inputs['passkey.rp_display_name'] ||
'',
});
options.push({
key: 'passkey.rp_id',
value: formValues['passkey.rp_id'] || inputs['passkey.rp_id'] || '',
});
options.push({
key: 'passkey.user_verification',
value:
formValues['passkey.user_verification'] ||
inputs['passkey.user_verification'] ||
'preferred',
});
options.push({
key: 'passkey.attachment_preference',
value:
formValues['passkey.attachment_preference'] ||
inputs['passkey.attachment_preference'] ||
'',
});
options.push({
key: 'passkey.origins',
value: formValues['passkey.origins'] || inputs['passkey.origins'] || '',
});
await updateOptions(options);
};
const handleCheckboxChange = async (optionKey, event) => {
const value = event.target.checked;
if (optionKey === 'PasswordLoginEnabled' && !value) {
setShowPasswordLoginConfirmModal(true);
} else {
await updateOptions([{ key: optionKey, value }]);
}
if (optionKey === 'LinuxDOOAuthEnabled') {
setLinuxDOOAuthEnabled(value);
}
};
const handlePasswordLoginConfirm = async () => {
await updateOptions([{ key: 'PasswordLoginEnabled', value: false }]);
setShowPasswordLoginConfirmModal(false);
};
return (
);
};
export default SystemSetting;