317 lines
21 KiB
TypeScript
317 lines
21 KiB
TypeScript
import {useConfirmation} from './Confirmation';
|
||
import {ModalBackdrop} from './ModalBackdrop';
|
||
import {SiteRuntime} from './SiteRuntime';
|
||
import {StartupSettings} from './StartupSettings';
|
||
import {SiteTools} from './SiteTools';
|
||
import { Cloud, FileSearch2, Globe2, LockKeyhole, Play, Plus, RefreshCw, ShieldOff, Square, Trash2, X } from 'lucide-react';
|
||
import { useEffect, useState } from 'react';
|
||
import { api } from '../api';
|
||
import { normalizeRunPath } from '../runPath';
|
||
import type { DeploymentCheck, Project, Runtime, RuntimeCatalog, Site, SiteDraft } from '../types';
|
||
|
||
const runtimes: Runtime[] = ['PHP', 'Node.js', 'Python', 'Go', 'Java'];
|
||
|
||
interface HostSitesModalProps {
|
||
project: Project;
|
||
runtimeVersions: RuntimeCatalog;
|
||
live: boolean;
|
||
onClose: () => void;
|
||
}
|
||
|
||
export function HostSitesModal({ project, runtimeVersions, live, onClose }: HostSitesModalProps) {
|
||
const {confirm,confirmation}=useConfirmation();
|
||
const [runtimeSite,setRuntimeSite]=useState<Site>();
|
||
const [tools,setTools]=useState<Site>(),[startup,setStartup]=useState<Site>();
|
||
const initialRuntime = project.runtime;
|
||
const [sites, setSites] = useState<Site[]>([]);
|
||
const [creating, setCreating] = useState(false);
|
||
const [busy, setBusy] = useState(live);
|
||
const [busySiteID, setBusySiteID] = useState<number>();
|
||
const [error, setError] = useState('');
|
||
const [deploymentSite, setDeploymentSite] = useState<Site>();
|
||
const [deploymentEntry, setDeploymentEntry] = useState('');
|
||
const [deploymentCheck, setDeploymentCheck] = useState<DeploymentCheck>();
|
||
const [certificateSite, setCertificateSite] = useState<Site>();
|
||
const [certificatePEM, setCertificatePEM] = useState('');
|
||
const [privateKeyPEM, setPrivateKeyPEM] = useState('');
|
||
const [draft, setDraft] = useState<SiteDraft>({ name: 'site-two', runtime: initialRuntime, version: runtimeVersions[initialRuntime]?.[0] ?? '', runPath: '/site-two', customDomain: '', autoSSL: true });
|
||
const normalizedRunPath = normalizeRunPath(draft.runPath);
|
||
|
||
useEffect(() => {
|
||
setDraft(current => {
|
||
if (runtimeVersions[current.runtime]?.includes(current.version)) return current;
|
||
const runtime = runtimeVersions[current.runtime]?.length ? current.runtime : runtimes.find(item => runtimeVersions[item]?.length);
|
||
return runtime ? { ...current, runtime, version: runtimeVersions[runtime][0] } : current;
|
||
});
|
||
}, [runtimeVersions]);
|
||
|
||
useEffect(() => {
|
||
let active = true;
|
||
if (!live) {
|
||
setSites([{ id: project.id, projectId: project.id, name: project.name, domain: project.domain, runPath: project.runPath, runtime: project.runtime, version: project.version, status: project.status, sslStatus: project.ssl ? 'active' : 'off', autoSSL: project.ssl, processLimit: 10, primary: true, createdAt: project.createdAt }]);
|
||
setBusy(false);
|
||
return () => { active = false; };
|
||
}
|
||
api.projectSites(project.id)
|
||
.then((result) => { if (active) setSites(result.sites); })
|
||
.catch((reason) => { if (active) setError(message(reason, '无法读取网站')); })
|
||
.finally(() => { if (active) setBusy(false); });
|
||
return () => { active = false; };
|
||
}, [live, project.id, project.name, project.domain, project.runPath, project.runtime, project.version, project.status, project.ssl, project.createdAt]);
|
||
|
||
function selectRuntime(runtime: Runtime) {
|
||
setDraft((current) => ({ ...current, runtime, version: runtimeVersions[runtime]?.[0] ?? '' }));
|
||
}
|
||
|
||
async function submit() {
|
||
if (!normalizedRunPath || !draft.version) return;
|
||
setBusy(true);
|
||
setError('');
|
||
const input = { ...draft, name: draft.name.trim().toLowerCase(), runPath: normalizedRunPath };
|
||
try {
|
||
const site = live
|
||
? (await api.createSite(project.id, input)).site
|
||
: { id: Date.now(), projectId: project.id, domain: `${project.hostName}-demo.vhost.ser888.cn`, status: input.runtime === 'PHP' ? 'running' as const : 'awaiting_upload' as const, sslStatus: input.autoSSL ? 'pending' : 'off', processLimit: 10, primary: false, createdAt: new Date().toISOString(), ...input };
|
||
setSites((current) => [...current, site]);
|
||
setCreating(false);
|
||
setDraft((current) => ({ ...current, name: 'site-new', runPath: '/site-new', customDomain: '' }));
|
||
} catch (reason) {
|
||
setError(message(reason, '创建网站失败'));
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
async function toggleSite(site: Site) {
|
||
if (!['running', 'stopped'].includes(site.status)) return;
|
||
const enabled = site.status !== 'running';
|
||
setBusySiteID(site.id);
|
||
setError('');
|
||
try {
|
||
const updated = live ? (await api.setSiteState(project.id, site.id, enabled)).site : { ...site, status: enabled ? 'running' as const : 'stopped' as const };
|
||
setSites((current) => current.map((item) => item.id === updated.id ? updated : item));
|
||
} catch (reason) {
|
||
setError(message(reason, '更新网站状态失败'));
|
||
} finally {
|
||
setBusySiteID(undefined);
|
||
}
|
||
}
|
||
|
||
async function deleteSite(site: Site) {
|
||
if (site.primary || !await confirm(`确定删除网站“${site.name}”的宝塔配置?主机目录中的源码会保留。`)) return;
|
||
setBusySiteID(site.id);
|
||
setError('');
|
||
try {
|
||
if (live) await api.deleteSite(project.id, site.id);
|
||
setSites((current) => current.filter((item) => item.id !== site.id));
|
||
} catch (reason) {
|
||
setError(message(reason, '删除网站失败'));
|
||
} finally {
|
||
setBusySiteID(undefined);
|
||
}
|
||
}
|
||
|
||
function openDeploymentCheck(site: Site) {
|
||
setDeploymentSite(site);
|
||
setDeploymentEntry(defaultEntry(site.runtime));
|
||
setDeploymentCheck(undefined);
|
||
setError('');
|
||
}
|
||
|
||
async function checkDeployment() {
|
||
if (!deploymentSite || !deploymentEntry.trim()) return;
|
||
setBusySiteID(deploymentSite.id);
|
||
setError('');
|
||
setDeploymentCheck(undefined);
|
||
try {
|
||
const check = live
|
||
? (await api.checkSiteDeployment(project.id, deploymentSite.id, deploymentEntry.trim())).check
|
||
: { runtime: deploymentSite.runtime, entryFile: deploymentEntry.trim(), ready: true, adapterReady: true, size: 18_432, message: '入口文件检查通过,可以创建宝塔语言项目并验证运行状态' };
|
||
setDeploymentCheck(check);
|
||
} catch (reason) {
|
||
setError(message(reason, '部署检查失败'));
|
||
} finally {
|
||
setBusySiteID(undefined);
|
||
}
|
||
}
|
||
|
||
async function deploySite() {
|
||
if (!deploymentSite || !deploymentCheck?.ready || !deploymentCheck.adapterReady) return;
|
||
setBusySiteID(deploymentSite.id);
|
||
setError('');
|
||
try {
|
||
const updated = live
|
||
? (await api.deploySite(project.id, deploymentSite.id, deploymentCheck.entryFile)).site
|
||
: { ...deploymentSite, status: 'running' as const };
|
||
setSites((current) => current.map((item) => item.id === updated.id ? updated : item));
|
||
setDeploymentSite(undefined);
|
||
setDeploymentCheck(undefined);
|
||
} catch (reason) {
|
||
setError(message(reason, '部署网站失败'));
|
||
} finally {
|
||
setBusySiteID(undefined);
|
||
}
|
||
}
|
||
|
||
function openCertificate(site: Site) {
|
||
setCertificateSite(site);
|
||
setCertificatePEM('');
|
||
setPrivateKeyPEM('');
|
||
setError('');
|
||
}
|
||
|
||
function closeCertificate() {
|
||
setCertificateSite(undefined);
|
||
setCertificatePEM('');
|
||
setPrivateKeyPEM('');
|
||
}
|
||
|
||
async function installCertificate() {
|
||
if (!certificateSite || !certificatePEM.trim() || !privateKeyPEM.trim()) return;
|
||
setBusySiteID(certificateSite.id);
|
||
setError('');
|
||
try {
|
||
const updated = live
|
||
? (await api.installManualCertificate(project.id, certificateSite.id, certificatePEM.trim(), privateKeyPEM.trim())).site
|
||
: { ...certificateSite, sslStatus: 'active', autoSSL: false };
|
||
setSites((current) => current.map((item) => item.id === updated.id ? updated : item));
|
||
closeCertificate();
|
||
} catch (reason) {
|
||
// Keep the inputs only while the form remains open so the tenant can fix
|
||
// a validation error; closing the form always discards the private key.
|
||
setError(message(reason, '安装证书失败'));
|
||
} finally {
|
||
setBusySiteID(undefined);
|
||
}
|
||
}
|
||
|
||
async function requestAutoCertificate(site: Site) {
|
||
setBusySiteID(site.id);
|
||
setError('');
|
||
try {
|
||
const updated = live
|
||
? (await api.requestAutoCertificate(project.id, site.id)).site
|
||
: { ...site, sslStatus: 'active', autoSSL: true };
|
||
setSites((current) => current.map((item) => item.id === updated.id ? updated : item));
|
||
} catch (reason) {
|
||
setSites((current) => current.map((item) => item.id === site.id ? { ...item, sslStatus: 'failed', autoSSL: true } : item));
|
||
setError(message(reason, '自动证书申请失败'));
|
||
} finally {
|
||
setBusySiteID(undefined);
|
||
}
|
||
}
|
||
|
||
async function requestDNSCertificate(site: Site) {
|
||
setBusySiteID(site.id);
|
||
setError('');
|
||
try {
|
||
const updated = live
|
||
? (await api.requestDNSCertificate(project.id, site.id)).site
|
||
: { ...site, sslStatus: 'active', autoSSL: true };
|
||
setSites((current) => current.map((item) => item.id === updated.id ? updated : item));
|
||
} catch (reason) {
|
||
setSites((current) => current.map((item) => item.id === site.id ? { ...item, sslStatus: 'failed', autoSSL: true } : item));
|
||
setError(message(reason, 'DNS-01 证书申请失败'));
|
||
} finally {
|
||
setBusySiteID(undefined);
|
||
}
|
||
}
|
||
|
||
async function disableCertificate(site: Site) {
|
||
if (!await confirm(`确定关闭“${site.name}”的 SSL 和自动续签?关闭后网站将仅通过 HTTP 提供服务。`)) return;
|
||
setBusySiteID(site.id);
|
||
setError('');
|
||
try {
|
||
const updated = live
|
||
? (await api.disableCertificate(project.id, site.id)).site
|
||
: { ...site, sslStatus: 'off', autoSSL: false };
|
||
setSites((current) => current.map((item) => item.id === updated.id ? updated : item));
|
||
} catch (reason) {
|
||
setError(message(reason, '关闭 SSL 失败'));
|
||
} finally {
|
||
setBusySiteID(undefined);
|
||
}
|
||
}
|
||
|
||
if(startup)return <StartupSettings site={startup} projectId={project.id} live={live} onClose={()=>setStartup(undefined)}/>;
|
||
if(tools)return <SiteTools site={tools} projectId={project.id} live={live} onClose={()=>setTools(undefined)}/>;
|
||
return (
|
||
<ModalBackdrop className="modal-backdrop" role="presentation">
|
||
<section className="sites-modal" role="dialog" aria-modal="true" aria-labelledby="sites-title">
|
||
<button className="modal-close" onClick={onClose} aria-label="关闭"><X size={18} /></button>
|
||
<Globe2 size={26} className="modal-icon" />
|
||
{confirmation}<div className="sites-heading">
|
||
<div><h2 id="sites-title">主机网站</h2></div>
|
||
<button className="primary" onClick={() => setCreating((value) => !value)}><Plus size={15} />新增网站</button>
|
||
</div>
|
||
{error ? <p className="form-error" role="alert">{error}</p> : null}
|
||
{runtimeSite?<SiteRuntime site={sites.find(s=>s.id===runtimeSite.id)||runtimeSite} project={project} catalog={runtimeVersions} live={live} onClose={()=>setRuntimeSite(undefined)} onChanged={async()=>{if(live)setSites((await api.projectSites(project.id)).sites)}}/>:null}
|
||
{creating ? <form className="site-create-form" onSubmit={(event) => { event.preventDefault(); void submit(); }}>
|
||
<label><span>网站名称</span><input required minLength={3} maxLength={50} value={draft.name} onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))} /></label>
|
||
<label><span>运行目录</span><input required value={draft.runPath} onChange={(event) => setDraft((current) => ({ ...current, runPath: event.target.value }))} /><small>{normalizedRunPath ? `${project.path}${normalizedRunPath}` : '请输入主机根目录内的安全相对路径'}</small></label>
|
||
<label><span>运行环境</span><select value={draft.runtime} onChange={(event) => selectRuntime(event.target.value as Runtime)}>{runtimes.filter((runtime) => (project.allowRuntimeChange||runtime===project.runtime)&&runtimeVersions[runtime]?.length).map((runtime) => <option key={runtime}>{runtime}</option>)}</select></label>
|
||
<label><span>版本</span><select value={draft.version} onChange={(event) => setDraft((current) => ({ ...current, version: event.target.value }))}>{runtimeVersions[draft.runtime]?.map((version) => <option key={version}>{version}</option>)}</select></label>
|
||
<label><span>自定义域名</span><input placeholder="可选,例如 app.vhost.ser888.cn" value={draft.customDomain} onChange={(event) => setDraft((current) => ({ ...current, customDomain: event.target.value }))} /></label>
|
||
<label className="site-ssl"><input type="checkbox" checked={draft.autoSSL} onChange={(event) => setDraft((current) => ({ ...current, autoSSL: event.target.checked }))} />自动申请 SSL(HTTP-01)</label>
|
||
<div className="modal-actions"><button type="button" className="secondary" onClick={() => setCreating(false)}>取消</button><button className="primary" disabled={busy || !normalizedRunPath || !draft.version}>{busy ? '创建中…' : '创建网站'}</button></div>
|
||
</form> : null}
|
||
{deploymentSite ? <form className="deployment-check-form" onSubmit={(event) => { event.preventDefault(); void checkDeployment(); }}>
|
||
<div><FileSearch2 size={20} /><span><b>部署前检查</b><small>{deploymentSite.name} · {deploymentSite.runtime} {deploymentSite.version}</small></span></div>
|
||
<label><span>入口文件</span><input required aria-label="入口文件" value={deploymentEntry} onChange={(event) => { setDeploymentEntry(event.target.value); setDeploymentCheck(undefined); }} /><small>相对于运行目录 {deploymentSite.runPath},不可使用绝对路径或软链接。{deploymentSite.backendPort ? `系统会注入 PORT=${deploymentSite.backendPort},应用应监听 127.0.0.1。` : ''}</small></label>
|
||
<div className="deployment-check-actions"><button type="button" className="secondary" onClick={() => { setDeploymentSite(undefined); setDeploymentCheck(undefined); }}>关闭</button><button className="primary" disabled={busySiteID === deploymentSite.id || !deploymentEntry.trim()}>{busySiteID === deploymentSite.id ? '处理中…' : '检查文件'}</button>{deploymentCheck?.ready && deploymentCheck.adapterReady ? <button type="button" className="primary" disabled={busySiteID === deploymentSite.id} onClick={() => void deploySite()}>开始部署</button> : null}</div>
|
||
{deploymentCheck ? <p className={`deployment-check-result ${deploymentCheck.ready ? deploymentCheck.adapterReady ? 'ready' : 'warning' : 'missing'}`} role="status"><b>{deploymentCheck.ready ? deploymentCheck.adapterReady ? '可以继续' : '文件就绪,适配器待验证' : '尚未就绪'}</b><span>{deploymentCheck.message}{deploymentCheck.size ? ` · ${formatBytes(deploymentCheck.size)}` : ''}</span></p> : null}
|
||
</form> : null}
|
||
{certificateSite ? <form className="certificate-form" onSubmit={(event) => { event.preventDefault(); void installCertificate(); }}>
|
||
<div className="certificate-heading"><LockKeyhole size={20} /><span><b>安装自有证书</b><small>{certificateSite.domain}</small></span></div>
|
||
<p className="certificate-notice">证书必须覆盖该网站全部已启用域名。安装后将关闭此网站的自动续签;私钥仅用于本次请求,不会保存在 Sea vHost 数据库或日志中。</p>
|
||
<label>上传证书链<input type="file" accept=".pem,.crt,.cer" onChange={async e=>{const f=e.target.files?.[0];if(f){if(f.size>96*1024){setError('证书链不能超过 96 KB');return}setCertificatePEM(await f.text())}}}/></label><label>上传私钥<input type="file" accept=".pem,.key" onChange={async e=>{const f=e.target.files?.[0];if(f){if(f.size>32*1024){setError('私钥不能超过 32 KB');return}setPrivateKeyPEM(await f.text())}}}/></label><label><span>证书链(PEM)</span><textarea required rows={7} spellCheck={false} placeholder="-----BEGIN CERTIFICATE-----" value={certificatePEM} onChange={(event) => setCertificatePEM(event.target.value)} /></label>
|
||
<label><span>私钥(PEM,无口令)</span><textarea required rows={7} spellCheck={false} autoComplete="off" placeholder="-----BEGIN PRIVATE KEY-----" value={privateKeyPEM} onChange={(event) => setPrivateKeyPEM(event.target.value)} /></label>
|
||
<div className="modal-actions"><button type="button" className="secondary" onClick={closeCertificate}>取消并清空</button><button className="primary" disabled={busySiteID === certificateSite.id || !certificatePEM.trim() || !privateKeyPEM.trim()}>{busySiteID === certificateSite.id ? '校验并安装中…' : '校验并安装'}</button></div>
|
||
</form> : null}
|
||
<div className="sites-list">
|
||
<div className="sites-row sites-head"><span>网站</span><span>运行目录</span><span>环境</span><span>状态</span><span>操作</span></div>
|
||
{sites.map((site) => <div className="sites-row" key={site.id}>
|
||
<span className="site-identity"><b>{site.domain}</b><small><span>{site.name}</span>{site.primary ? ' · 主站' : ''} · SSL {sslStatusLabel(site.sslStatus)}</small></span>
|
||
<code className="site-run-path">{site.runPath}</code>
|
||
<span className="site-runtime">{site.runtime} {site.version}{site.runtime !== 'PHP' && site.backendPort ? <small>127.0.0.1:{site.backendPort}</small> : null}</span>
|
||
<em className={`status ${site.status}`}>{statusLabel(site.status)}</em>
|
||
<span className="site-actions"><button disabled={busySiteID===site.id||!['running','stopped','awaiting_upload'].includes(site.status)} aria-label={`运行环境 ${site.name}`} onClick={()=>setRuntimeSite(site)}>环境</button>
|
||
{site.status === 'awaiting_upload' ? <button onClick={() => openDeploymentCheck(site)} aria-label={`部署检查 ${site.name}`}><FileSearch2 size={14} /></button> : null}
|
||
<button disabled={busySiteID === site.id || site.status!=='running'} onClick={() => void requestAutoCertificate(site)} aria-label={`HTTP-01 申请证书 ${site.name}`} title={site.status!=='running'?'请先部署并启动网站后使用 HTTP-01;未运行时可使用 DNS-01 或上传证书':'HTTP-01 自动申请并续期'}><RefreshCw size={14} /></button>
|
||
<button disabled={busySiteID === site.id || ['provisioning', 'failed'].includes(site.status)} onClick={() => void requestDNSCertificate(site)} aria-label={`DNS 申请证书 ${site.name}`} title="使用平台与用户 DNS API 按域名签发并自动续期"><Cloud size={14} /></button>
|
||
<button disabled={busySiteID === site.id || ['provisioning', 'failed'].includes(site.status)} onClick={() => openCertificate(site)} aria-label={`安装证书 ${site.name}`}><LockKeyhole size={14} /></button>
|
||
<button onClick={()=>setStartup(site)} aria-label={'启动设置 '+site.name}>环境 / 启动</button>
|
||
<button onClick={()=>setTools(site)} aria-label={'网站设置与日志 '+site.name}>设置 / 日志</button>
|
||
{site.sslStatus !== 'off' ? <button disabled={busySiteID === site.id || ['provisioning', 'failed'].includes(site.status)} onClick={() => void disableCertificate(site)} aria-label={`关闭 SSL ${site.name}`} title="关闭 SSL 与自动续签"><ShieldOff size={14} /></button> : null}
|
||
<button disabled={busySiteID === site.id || !['running', 'stopped'].includes(site.status)} onClick={() => void toggleSite(site)} aria-label={`${site.status === 'running' ? '停止' : '启动'} ${site.name}`}>{site.status === 'running' ? <Square size={14} /> : <Play size={14} />}</button>
|
||
<button className="danger" title={site.primary?'主站随主机管理,不能单独删除':busySiteID===site.id?'网站正在处理操作':'删除附加网站配置,保留源码'} disabled={site.primary || busySiteID === site.id} onClick={() => void deleteSite(site)} aria-label={`删除 ${site.name}`}><Trash2 size={14} /></button>
|
||
</span>
|
||
</div>)}
|
||
{busy && sites.length === 0 ? <div className="sites-empty">正在读取网站…</div> : null}
|
||
</div>
|
||
<p className="sites-footnote">主站不能单独删除;附加网站删除只移除 Nginx/宝塔配置,保留主机目录中的文件。</p>
|
||
</section>
|
||
</ModalBackdrop>
|
||
);
|
||
}
|
||
|
||
function statusLabel(status: Site['status']) {
|
||
return ({ running: '运行中', stopped: '已停止', awaiting_upload: '待上传', provisioning: '创建中', failed: '失败', quota_suspended: '配额暂停' })[status];
|
||
}
|
||
|
||
function sslStatusLabel(status: string) {
|
||
return ({ active: '已启用', pending: '签发中', failed: '失败', off: '未启用' } as Record<string, string>)[status] ?? status;
|
||
}
|
||
|
||
function message(reason: unknown, fallback: string) {
|
||
return reason instanceof Error ? reason.message : fallback;
|
||
}
|
||
|
||
function defaultEntry(runtime: Runtime) {
|
||
return ({ PHP: 'index.php', 'Node.js': 'package.json', Python: 'app.py', Go: 'app', Java: 'app.jar' })[runtime];
|
||
}
|
||
|
||
function formatBytes(value: number) {
|
||
return value < 1024 ? `${value} B` : `${(value / 1024).toFixed(value < 10 * 1024 ? 1 : 0)} KB`;
|
||
}
|