feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,83 @@
|
||||
import {PageHeader} from './UI';
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Download,Layers,RefreshCw,Upload,X} from 'lucide-react';
|
||||
import {api,type AdminBatch,type AdminProject,type BatchOperation,type BatchPreviewRow,type BatchRow,type ControlNode,type Tenant} from '../api';
|
||||
import type {Plan,Runtime,RuntimeCatalog} from '../types';
|
||||
import {downloadBatchTemplate,parseBatchJSON} from '../batchJSON';
|
||||
|
||||
export const batchOperationNames:Record<BatchOperation,string>={create_users:'批量创建用户',create_hosts:'批量创建主机',assign_hosts:'批量绑定 / 解绑用户',host_subscription:'批量修改套餐与到期',host_start:'批量启动主机',host_stop:'批量停止主机',host_password_reset:'重置主机登录密码',user_enable:'批量启用用户',user_disable:'批量停用用户'};
|
||||
const states:Record<string,string>={queued:'排队中',running:'执行中',completed:'已完成',partial:'部分完成',pending:'待执行',succeeded:'成功',failed:'失败',uncertain:'待核验',cancelled:'已取消'};
|
||||
const emptyCatalog:RuntimeCatalog={PHP:[],'Node.js':[],Python:[],Go:[],Java:[]};
|
||||
const message=(reason:unknown)=>reason instanceof Error?reason.message:'操作失败,请稍后重试';
|
||||
function key(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),byte=>byte.toString(16).padStart(2,'0')).join('')}
|
||||
export interface BatchSelection {operation:BatchOperation;rows?:BatchRow[];}
|
||||
interface ComposerProps extends BatchSelection {users:Tenant[];projects:AdminProject[];plans:Plan[];onClose:()=>void;onChanged:()=>Promise<void>;}
|
||||
|
||||
export function BatchComposer({operation,rows:selection=[],users,projects,plans,onClose,onChanged}:ComposerProps){
|
||||
const creating=operation==='create_users'||operation==='create_hosts';
|
||||
const [mode,setMode]=useState<'quantity'|'json'|'selection'>(creating?'quantity':selection.length?'selection':'json');
|
||||
const [count,setCount]=useState(3),[start,setStart]=useState(1),[prefix,setPrefix]=useState(()=>`batch-${key().slice(0,6)}`),[displayPrefix,setDisplayPrefix]=useState('批量用户'),[emailDomain,setEmailDomain]=useState('vhost.ser888.cn');
|
||||
const pending=selection.length===1?projects.find(p=>p.id===selection[0].hostId)?.pendingOwnership:undefined;
|
||||
const [credentialMode,setCredentialMode]=useState(pending?.credentialMode||'preserve'),[stopServices,setStopServices]=useState(pending?.stopServices??true),[resumeOwnership,setResumeOwnership]=useState(false);
|
||||
const [owner,setOwner]=useState(pending?.targetOwnerId||0),[plan,setPlan]=useState(operation==='host_subscription'?0:plans[0]?.id||0),[node,setNode]=useState(0),[nodes,setNodes]=useState<ControlNode[]>([]);
|
||||
const [runtime,setRuntime]=useState<Runtime>('PHP'),[version,setVersion]=useState(''),[catalog,setCatalog]=useState<RuntimeCatalog>(emptyCatalog),[runPath,setRunPath]=useState('/'),[expiry,setExpiryValue]=useState(''),[changeExpiry,setChangeExpiry]=useState(false),[autoSSL,setAutoSSL]=useState(true);
|
||||
const [imported,setImported]=useState<BatchRow[]>([]),[fileName,setFileName]=useState(''),[preview,setPreview]=useState<BatchPreviewRow[]>([]),[prepared,setPrepared]=useState<BatchRow[]>([]),[requestKey,setRequestKey]=useState(''),[job,setJob]=useState<AdminBatch>();
|
||||
const [busy,setBusy]=useState(false),[catalogBusy,setCatalogBusy]=useState(false),[error,setError]=useState('');
|
||||
function invalidate(){setPreview([]);setPrepared([]);setRequestKey('');setError('')}
|
||||
useEffect(()=>{if(operation!=='create_hosts')return;let active=true;api.nodes().then(result=>{if(active){setNodes(result.nodes.filter(n=>n.enabled));setNode(result.nodes.find(n=>n.enabled)?.id||0)}}).catch(reason=>{if(active)setError(message(reason))});return()=>{active=false}},[operation]);
|
||||
useEffect(()=>{if(operation!=='create_hosts'||!node)return;let active=true;setCatalogBusy(true);setCatalog(emptyCatalog);api.panelSites(node).then(result=>{if(active)setCatalog(result.versions)}).catch(reason=>{if(active)setError(message(reason))}).finally(()=>{if(active)setCatalogBusy(false)});return()=>{active=false}},[node,operation]);
|
||||
useEffect(()=>{setVersion(current=>catalog[runtime]?.includes(current)?current:catalog[runtime]?.[0]||'')},[catalog,runtime]);
|
||||
function defaults():BatchRow{return {credentialMode,stopServices,resumeOwnership,tenantId:owner,nodeId:node,planId:plan,runtime,version:catalog[runtime]?.includes(version)?version:catalog[runtime]?.[0]||'',runPath,expiresAt:expiry?new Date(expiry).toISOString():null,setExpiry:operation==='host_subscription'?changeExpiry:!!expiry,autoSSL}}
|
||||
function buildRows():BatchRow[]{
|
||||
const shared=defaults();
|
||||
if(mode==='selection')return selection.map(row=>({...row,...shared}));
|
||||
if(mode==='json'){if(!imported.length)throw new Error('请先导入 JSON 文件');return imported.map(record=>({...shared,...record}))}
|
||||
const max=operation==='create_users'?100:50;if(!Number.isInteger(count)||count<1||count>max||!Number.isInteger(start)||start<1||start>999999)throw new Error(`数量应为 1–${max},起始编号应为正整数`);
|
||||
if(!/^[a-z0-9][a-z0-9-]{1,35}[a-z0-9]$/.test(prefix))throw new Error('名称前缀应为 3–37 位小写字母、数字或连字符');
|
||||
return Array.from({length:count},(_,index)=>{const serial=String(start+index).padStart(4,'0'),slug=`${prefix}-${serial}`;return operation==='create_users'?{slug,name:`${displayPrefix}${start+index}`,email:`${slug}@${emailDomain.trim()}`,displayName:`${displayPrefix}${start+index}`}:{...shared,name:slug}})
|
||||
}
|
||||
async function prepare(){setBusy(true);setError('');setPreview([]);try{const rows=buildRows();if(operation==='host_subscription'&&!plan&&!changeExpiry)throw new Error('请选择新套餐,或勾选修改到期时间');const result=await api.previewBatch(operation,rows);setPrepared(rows);setPreview(result.rows);setRequestKey(key())}catch(reason){setError(message(reason))}finally{setBusy(false)}}
|
||||
async function submit(){setBusy(true);setError('');try{const result=await api.createBatch(operation,prepared,requestKey);setJob(result.batch);setImported([]);setPrepared([])}catch(reason){setError(message(reason))}finally{setBusy(false)}}
|
||||
async function importFile(file?:File){invalidate();if(!file)return;setBusy(true);try{if(file.size>256*1024)throw new Error('JSON 文件不能超过 256 KiB');const data=parseBatchJSON(await file.text(),operation);setImported(data);setFileName(file.name)}catch(reason){setImported([]);setFileName('');setError(message(reason))}finally{setBusy(false)}}
|
||||
const validCount=preview.filter(row=>row.valid).length;
|
||||
return <ModalBackdrop className="modal-backdrop"><section className="batch-modal" role="dialog" aria-modal="true" aria-labelledby="batch-title"><header className="batch-heading"><div><Layers size={22}/><h2 id="batch-title">{batchOperationNames[operation]}</h2></div><button type="button" aria-label="关闭批量操作" onClick={onClose}><X size={19}/></button></header>
|
||||
{job?<BatchProgress id={job.id} onChanged={onChanged}/>:<>
|
||||
<p className="batch-description">先验证预览,再提交后台执行。每条独立记录结果;部分失败不会撤销成功项。离开页面后可在“批量任务”继续查看。</p>
|
||||
<fieldset className="batch-composer-fields" disabled={busy}><div className="batch-controls">
|
||||
<label>输入方式<select value={mode} onChange={event=>{invalidate();setMode(event.target.value as typeof mode)}}>{creating?<option value="quantity">数量与名称前缀</option>:null}{selection.length?<option value="selection">已勾选的 {selection.length} 项</option>:null}<option value="json">JSON 模板导入</option></select></label>
|
||||
{mode==='quantity'?<><label>创建数量<input type="number" min="1" max={operation==='create_users'?100:50} value={count} onChange={e=>{invalidate();setCount(Number(e.target.value))}}/></label><label>名称前缀<input value={prefix} maxLength={37} onChange={e=>{invalidate();setPrefix(e.target.value)}}/></label><label>起始编号<input type="number" min="1" max="999999" value={start} onChange={e=>{invalidate();setStart(Number(e.target.value))}}/></label></>:null}
|
||||
{operation==='create_users'&&mode==='quantity'?<><label>用户名称前缀<input value={displayPrefix} onChange={e=>{invalidate();setDisplayPrefix(e.target.value)}}/></label><label>登录邮箱后缀<input placeholder="vhost.ser888.cn" value={emailDomain} onChange={e=>{invalidate();setEmailDomain(e.target.value)}}/></label></>:null}
|
||||
{operation==='create_hosts'||operation==='assign_hosts'?<label>{operation==='assign_hosts'?'目标用户':'绑定用户(可选)'}<select value={owner} onChange={e=>{invalidate();setOwner(Number(e.target.value))}}><option value="0">{operation==='assign_hosts'?'解绑用户,仅保留独立主机登录':'不绑定用户,独立主机账号登录'}</option>{users.filter(user=>user.status==='active').map(user=><option key={user.id} value={user.id}>{user.name} · {user.slug}</option>)}</select></label>:null}
|
||||
{operation==='assign_hosts'?<><label>凭据处理<select value={credentialMode} onChange={e=>{invalidate();setCredentialMode(e.target.value as 'preserve'|'reset')}}><option value="preserve">保留主机、FTP、数据库密码</option><option value="reset">随机重置三类密码</option></select></label><label className="batch-check"><input type="checkbox" checked={stopServices} onChange={e=>{invalidate();setStopServices(e.target.checked)}}/>变更前停止全部网站(默认)</label><label className="batch-check"><input type="checkbox" checked={resumeOwnership} onChange={e=>{invalidate();setResumeOwnership(e.target.checked)}}/>按原策略恢复未完成的归属变更</label></>:null}
|
||||
{operation==='create_hosts'?<><label>所属节点<select value={node} onChange={e=>{invalidate();setNode(Number(e.target.value))}}><option value="0" disabled>请选择节点</option>{nodes.map(item=><option value={item.id} key={item.id}>{item.name} · {item.rootDomain}</option>)}</select></label><label>运行环境<select value={runtime} onChange={e=>{invalidate();setRuntime(e.target.value as Runtime)}}>{Object.keys(catalog).map(name=><option key={name}>{name}</option>)}</select></label><label>运行版本<select aria-label="批量运行版本" value={version} onChange={e=>{invalidate();setVersion(e.target.value)}}>{(catalog[runtime]||[]).map(value=><option key={value}>{value}</option>)}</select></label><label>运行目录<input value={runPath} onChange={e=>{invalidate();setRunPath(e.target.value)}}/></label></>:null}
|
||||
{operation==='create_hosts'||operation==='host_subscription'?<><label>主机套餐<select value={plan} onChange={e=>{invalidate();setPlan(Number(e.target.value))}}>{operation==='host_subscription'?<option value="0">保持每台主机原套餐</option>:null}{plans.map(item=><option value={item.id} key={item.id}>{item.name}</option>)}</select></label>{operation==='host_subscription'?<label className="batch-check"><input type="checkbox" checked={changeExpiry} onChange={e=>{invalidate();setChangeExpiry(e.target.checked)}}/>修改到期时间(留空为长期)</label>:null}<label>到期时间<input type="datetime-local" disabled={operation==='host_subscription'&&!changeExpiry} value={expiry} onChange={e=>{invalidate();setExpiryValue(e.target.value)}}/><small>{operation==='create_hosts'?'留空为长期使用':'不勾选修改时保留各主机原到期时间'}</small></label></>:null}
|
||||
{operation==='create_hosts'?<label className="batch-check"><input type="checkbox" checked={autoSSL} onChange={e=>{invalidate();setAutoSSL(e.target.checked)}}/>自动申请并续期 SSL</label>:null}
|
||||
</div>
|
||||
{mode==='json'?<div className="batch-import"><button className="secondary" onClick={()=>downloadBatchTemplate(operation)}><Download size={15}/>下载 JSON 模板</button><label className="batch-upload"><Upload size={15}/>选择 JSON 文件<input aria-label="导入批量 JSON" type="file" accept=".json,application/json" onChange={e=>void importFile(e.target.files?.[0])}/></label><span>{fileName?`${fileName} · ${imported.length} 条`:'支持 UTF-8 JSON 模板;空密码独立随机生成'}</span></div>:null}
|
||||
{operation==='assign_hosts'?<p className="batch-note">一台主机最多绑定一个用户;用户可管理多台主机。归属变更不改变目录、Linux 身份和资源限额。JSON 中 owner 留空表示解绑。保留密码时,旧持有者仍可使用原主机密码重新登录,也可继续访问 FTP 或数据库;重置后需更新程序的数据库密码。变更会注销旧主机会话,并关闭自动证书续期,现有证书继续使用,可由新管理者重新配置。</p>:null}
|
||||
{operation==='user_disable'?<p className="batch-note">停用用户会注销用户登录和代入会话;独立主机账号及运行中的网站不因此停止。</p>:null}
|
||||
{operation==='host_stop'?<p className="batch-note">将停止所选主机的网站;文件和数据库保留。</p>:null}
|
||||
{operation==='host_password_reset'?<p className="batch-note">将随机重置主机登录密码,并注销该主机的旧登录及代入会话;FTP 和数据库密码保持不变。新登录密码通过结果 JSON 下载。</p>:null}
|
||||
</fieldset>{error?<p className="form-error" role="alert">{error}</p>:null}
|
||||
{preview.length?<section className="batch-preview"><h3>执行预览 · {validCount} 项可执行 / {preview.length-validCount} 项需修正</h3><div className="table-scroll"><table><thead><tr><th>行号</th><th>账号 / 主机</th><th>操作</th><th>说明</th></tr></thead><tbody>{preview.map(row=><tr key={row.row}><td>{row.row}</td><td>{row.label}</td><td>{batchOperationNames[operation]}</td><td className={row.valid?'log-ok':'log-fail'}>{row.detail}{operation==='create_users'&&row.valid?' · 密码不在预览中显示':''}</td></tr>)}</tbody></table></div></section>:null}
|
||||
<footer className="batch-actions"><button className="secondary" disabled={busy||catalogBusy} onClick={()=>void prepare()}>{busy?'正在处理…':'验证并预览'}</button><button className="primary" disabled={busy||!validCount||!requestKey} onClick={()=>void submit()}>提交 {validCount||''} 项任务</button><button className="secondary" onClick={onClose}>关闭</button></footer>
|
||||
</>}
|
||||
</section></ModalBackdrop>
|
||||
}
|
||||
|
||||
function BatchProgress({id,onChanged}:{id:number;onChanged:()=>Promise<void>}){
|
||||
const {confirm,confirmation}=useConfirmation();
|
||||
const [job,setJob]=useState<AdminBatch>(),[error,setError]=useState(''),[busy,setBusy]=useState(false);const changed=useRef(false);const mayContainCredentials=!!job&&['create_users','create_hosts','assign_hosts','host_password_reset'].includes(job.operation);
|
||||
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>|undefined;async function load(){try{const result=await api.batch(id);if(!active)return;setJob(result.batch);setError('');if(result.batch.pending>0||['queued','running'].includes(result.batch.state))timer=setTimeout(()=>void load(),1500);else if(!changed.current){changed.current=true;await onChanged()}}catch(reason){if(active){setError(message(reason));timer=setTimeout(()=>void load(),3000)}}}void load();return()=>{active=false;if(timer)clearTimeout(timer)}},[id,onChanged]);
|
||||
async function cancel(){if(!await confirm('只取消尚未执行的条目,执行中条目继续完成,是否取消?',{title:'取消剩余任务'}))return;setBusy(true);try{await api.cancelBatch(id);const result=await api.batch(id);setJob(result.batch)}catch(reason){setError(message(reason))}finally{setBusy(false)}}
|
||||
return <section className="batch-progress">{confirmation}{error?<p className="form-error" role="alert">{error}</p>:null}{!job?<p>正在读取批次…</p>:<><div className="batch-summary"><strong>批次 #{id} · {states[job.state]||job.state}</strong><span>成功 {job.succeeded} · 失败/取消 {job.failed} · 待核验 {job.uncertain} · 待完成 {job.pending}</span></div><progress aria-label="批量任务完成进度" max={Math.max(1,job.total)} value={job.total-job.pending}/><p className="batch-note">{mayContainCredentials?'结果可能包含登录、FTP 和数据库密码,加密保留 24 小时,需主动下载 JSON。不要把凭据文件发给无关人员;过期后可在主机中查看 FTP/数据库凭据并重置登录密码。':'下载结果 JSON 可查看每一项的执行状态与说明,本次操作不会生成新密码。'}</p><div className="batch-actions">{job.pending===0&&['queued','running'].includes(job.state)?<span>正在保存任务结果…</span>:job.pending>0?<button className="secondary" disabled={busy} onClick={()=>void cancel()}>取消未执行项</button>:job.secretsExpireAt&&new Date(job.secretsExpireAt)>new Date()?<a className="primary" href={api.batchDownloadURL(id)}><Download size={15}/>{mayContainCredentials?'下载结果与凭据 JSON':'下载结果 JSON'}</a>:<span>{mayContainCredentials?'批次凭据已过期':'结果下载已过期'}</span>}</div><div className="table-scroll"><table><thead><tr><th>行号</th><th>账号 / 主机</th><th>资源 ID</th><th>状态</th><th>说明</th></tr></thead><tbody>{job.items?.map(item=><tr key={item.id}><td>{item.row}</td><td>{item.label}</td><td>{item.resourceId||'—'}</td><td>{states[item.state]||item.state}</td><td>{item.detail}</td></tr>)}</tbody></table></div></> }</section>
|
||||
}
|
||||
|
||||
export function BatchJobs({create,onChanged}:{create:(selection:BatchSelection)=>void;onChanged:()=>Promise<void>}){
|
||||
const [jobs,setJobs]=useState<AdminBatch[]>([]),[selected,setSelected]=useState<number>(),[error,setError]=useState(''),[version,setVersion]=useState(0);
|
||||
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>|undefined;async function load(){try{const result=await api.batches();if(!active)return;setJobs(result.batches);setError('');if(result.batches.some(job=>job.pending>0||['queued','running'].includes(job.state)))timer=setTimeout(()=>void load(),2500)}catch(reason){if(active)setError(message(reason))}}void load();return()=>{active=false;if(timer)clearTimeout(timer)}},[version]);
|
||||
return <section className="admin-page"><PageHeader title="批量任务" actions={<div className="batch-create-actions"><button className="primary" onClick={()=>create({operation:'create_users'})}>批量创建用户</button><button className="secondary" onClick={()=>create({operation:'create_hosts'})}>批量创建主机</button><button className="secondary" onClick={()=>create({operation:'assign_hosts'})}>JSON 批量绑定</button></div>}/><div className="admin-toolbar batch-list-toolbar"><button className="secondary" onClick={()=>setVersion(value=>value+1)}><RefreshCw size={16}/>刷新任务</button></div>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="admin-table-v2"><table><thead><tr><th>批次</th><th>操作</th><th>状态</th><th>成功 / 总数</th><th>创建时间</th><th>操作</th></tr></thead><tbody>{jobs.map(job=><tr key={job.id}><td>#{job.id}</td><td>{batchOperationNames[job.operation]}</td><td>{states[job.state]||job.state}</td><td>{job.succeeded} / {job.total}</td><td>{new Date(job.createdAt).toLocaleString('zh-CN')}</td><td><button className="table-link" onClick={()=>setSelected(job.id)}>查看结果 #{job.id}</button></td></tr>)}</tbody></table>{!jobs.length?<p className="admin-empty">暂无批量任务</p>:null}</div>{selected?<ModalBackdrop className="modal-backdrop"><section className="batch-modal" role="dialog" aria-modal="true" aria-label="批量任务详情"><header className="batch-heading"><h2>批量任务 #{selected}</h2><button aria-label="关闭批次详情" onClick={()=>{setSelected(undefined);setVersion(value=>value+1)}}><X size={18}/></button></header><BatchProgress id={selected} onChanged={onChanged}/></section></ModalBackdrop>:null}</section>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import {SystemSettingsForm as SettingsPage} from './SystemSettingsForm';
|
||||
import {AdminLogs} from './AdminLogs';
|
||||
import {AdminDomains as Domains} from './AdminDomains';
|
||||
import {AccountEditor} from './ResourceEditors';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {AdminHosts as Hosts} from './AdminHosts';
|
||||
import {PageHeader} from './UI';
|
||||
import {useNavigationOverlay} from './overlay';
|
||||
import {HostProvisioning} from './HostProvisioning';
|
||||
import {IntegrationAPI} from './IntegrationAPI';
|
||||
import {SystemScheduler} from './SystemScheduler';
|
||||
import { Activity, Boxes, ChevronDown, CloudCog, Cpu, Database, Globe2, KeyRound, LayoutGrid, LogOut, Menu, Mail, Network, Plus, Search, Server, Settings, ShieldCheck, UserRoundCog, UsersRound } from 'lucide-react';
|
||||
import { useCallback, useEffect, useState, type ReactNode } from 'react';
|
||||
import { api, type AdminOverview, type AdminProject, type AdminSettings, type Credentials, type DomainResource, type PanelSite, type PlanInput, type Tenant, type User } from '../api';
|
||||
import { formatBytes } from '../format';
|
||||
import type { Plan } from '../types';
|
||||
import { Brand } from './Brand';
|
||||
import { DNSCredentials } from './DNSCredentials';
|
||||
import {NodeIPPool} from './NodeIPPool';
|
||||
import { NodeManagement,NodeEnvironment } from './NodeManagement';
|
||||
import {BatchComposer,BatchJobs,type BatchSelection} from './AdminBatches';
|
||||
|
||||
interface Props { onPlansChanged?:()=>Promise<void>; onImpersonate?:(input:{tenantId?:number;projectId?:number})=>Promise<void>; user: User; tenants: Tenant[]; plans: Plan[]; pendingDomains: DomainResource[]; approval: boolean; onApproval: (value: boolean) => Promise<void>; onReviewDomain: (id: number, approved: boolean) => Promise<void>; onCreate: (input: Record<string, unknown>) => Promise<void>; onCreatePlan: (input: PlanInput) => Promise<void>; onLogout: () => void; onSecurity: () => void; }
|
||||
type Page = 'integration' | 'batches' | 'nodes' | 'overview' | 'users' | 'hosts' | 'environment' | 'plans' | 'domains' | 'dns' | 'ips' | 'lifecycle' | 'settings' | 'logs';
|
||||
const navigation: Array<{ id: Page; label: string; icon: typeof LayoutGrid }> = [
|
||||
{ id: 'overview', label: '总览', icon: LayoutGrid }, {id:'batches',label:'批量任务',icon:Boxes}, { id: 'users', label: '用户管理', icon: UsersRound },
|
||||
{id:'nodes',label:'节点管理',icon:Network}, { id: 'hosts', label: '虚拟主机', icon: Server }, { id: 'environment', label: '环境配置', icon: Cpu }, { id: 'plans', label: '套餐管理', icon: Boxes },
|
||||
{ id: 'domains', label: '域名管理', icon: Globe2 }, { id: 'dns', label: 'DNS 管理', icon: CloudCog },
|
||||
{ id: 'ips', label: 'IP 地址池', icon: Network }, { id: 'lifecycle', label: '到期与回收', icon: Activity },
|
||||
{id:'integration',label:'对接 API',icon:KeyRound},{ id: 'settings', label: '系统设置', icon: Settings }, { id: 'logs', label: '操作日志', icon: Database },
|
||||
];
|
||||
const emptyOverview: AdminOverview = { users: [], projects: [], domains: [], ipAddresses: [], logs: [] };
|
||||
const defaultSettings: AdminSettings = { domainApproval: true, filingRequired: false, cdnCnameTarget: '', graceDays: 3, recycleDays: 7, backupRetentionDays: 14, smtp: { enabled: false, host: '', port: 465, username: '', from: '', adminRecipients: '', startTls: true, secretConfigured: false }, oidc: { enabled: false, issuer: '', clientId: '', redirectUri: '', secretConfigured: false, bindingOnly: true, passwordLogin: true,autoCreate:false,userPasswordLogin:true,adminPasswordLogin:true } };
|
||||
|
||||
export function AdminConsole(props: Props) {
|
||||
const [page, setPage] = useState<Page>('overview'); const [overview, setOverview] = useState<AdminOverview>(() => ({ ...emptyOverview, users: props.tenants, domains: props.pendingDomains })); const [settings, setSettings] = useState<AdminSettings>(() => ({ ...defaultSettings, domainApproval: props.approval }));
|
||||
const [loading, setLoading] = useState(true); const [loadError,setLoadError]=useState(''); const [notice, setNotice] = useState(''); const [query, setQuery] = useState('');
|
||||
const [showUserForm, setShowUserForm] = useState(false); const [showPlanForm, setShowPlanForm] = useState(false); const [networkProject, setNetworkProject] = useState<AdminProject>();
|
||||
const [showAdoption, setShowAdoption] = useState(false);
|
||||
const [batch,setBatch]=useState<BatchSelection>();
|
||||
const [mobileNavOpen,setMobileNavOpen]=useState(false);
|
||||
useNavigationOverlay(mobileNavOpen,setMobileNavOpen);
|
||||
function navigate(next:Page){setPage(next);setQuery('');setMobileNavOpen(false)}
|
||||
const refresh = useCallback(async () => { try { const [data, config] = await Promise.all([api.adminOverview(), api.adminSettings()]); setOverview(data); setSettings(config);setLoadError(''); } catch(reason) {setLoadError(reason instanceof Error?reason.message:'管理数据读取失败');} finally { setLoading(false); } }, [props.pendingDomains, props.tenants]);
|
||||
useEffect(() => { void refresh().catch(()=>{}); }, [refresh]);
|
||||
const users = overview.users; const domains = overview.domains;
|
||||
const title = navigation.find((item) => item.id === page)?.label || '总览'; const notify = (message: string) => { setNotice(message); window.setTimeout(() => setNotice(''), 2600); };
|
||||
return <div className="admin-app"><button className={mobileNavOpen?"admin-nav-overlay visible":"admin-nav-overlay"} aria-label="关闭管理导航" onClick={()=>setMobileNavOpen(false)}/><aside className={mobileNavOpen?"admin-sidebar open":"admin-sidebar"} aria-label="管理导航"><Brand /><nav>{navigation.map(({ id, label, icon: Icon }) => <button key={id} aria-label={label} aria-current={page===id?"page":undefined} className={page === id ? 'active' : ''} onClick={() => navigate(id)}><Icon size={18} /><span>{label}</span>{id === 'domains' && domains.some((item) => item.status === 'pending') ? <i>{domains.filter((item) => item.status === 'pending').length}</i> : null}</button>)}</nav><div className="admin-side-foot"><span className="online-dot" />管理员控制台</div></aside><div className="admin-stage"><header className="admin-topbar"><button className="mobile-menu" aria-label={mobileNavOpen?"关闭管理导航":"打开管理导航"} aria-expanded={mobileNavOpen} onClick={()=>setMobileNavOpen(v=>!v)}><Menu size={21}/></button><div className="admin-breadcrumb"><span>Sea vHost</span><b>/</b><strong>{title}</strong></div><label className="host-jump"><Server size={15} /><select aria-label="快速选择虚拟主机" value="" onChange={e=>{const id=Number(e.target.value);if(id&&props.onImpersonate)void props.onImpersonate({projectId:id}).catch(reason=>notify(reason instanceof Error?reason.message:"进入失败"))}} disabled={!props.onImpersonate}><option value="">全部虚拟主机</option>{overview.projects.filter(item=>!item.manualRecycledAt&&!item.managementLocked).map((item) => <option key={item.id} value={item.id}>{item.hostName} · {item.name}</option>)}</select><ChevronDown size={14} /></label><div className="admin-account"><span className="avatar">{props.user.displayName.slice(0, 1)}</span><span><b>{props.user.displayName}</b><small>平台管理员</small></span><button title="账号安全" onClick={props.onSecurity}><KeyRound size={17} /></button><button title="退出" onClick={props.onLogout}><LogOut size={17} /></button></div></header><main className="admin-content">{loading ? <div className="admin-loading">正在读取管理数据…</div> : null}{loadError?<div className="form-error load-error" role="alert">{loadError}<button className="secondary" onClick={()=>{setLoading(true);void refresh().catch(()=>{})}}>重新读取管理数据</button></div>:null}{!loading&&!loadError ? <AdminPage page={page} users={users} domains={domains} overview={overview} settings={settings} plans={props.plans} query={query} setQuery={setQuery} setPage={navigate} setShowUserForm={setShowUserForm} setShowPlanForm={setShowPlanForm} setNetworkProject={setNetworkProject} setShowAdoption={setShowAdoption} setSettings={setSettings} refresh={refresh} notify={notify} openBatch={setBatch} props={props} /> : null}</main></div>{showUserForm ? <UserForm plans={props.plans} onClose={() => setShowUserForm(false)} onCreate={async (input) => { await props.onCreate(input); setShowUserForm(false); await refresh(); }} /> : null}{showPlanForm ? <PlanForm onClose={() => setShowPlanForm(false)} onCreate={async (input) => { await props.onCreatePlan(input); setShowPlanForm(false); }} /> : null}{showAdoption ? <AdoptionForm plans={props.plans} users={users} onClose={() => setShowAdoption(false)} onComplete={async () => { setShowAdoption(false); await refresh(); notify('宝塔站点已迁移并分配'); }} /> : null}{networkProject ? <NetworkForm project={networkProject} ips={overview.ipAddresses} onClose={() => setNetworkProject(undefined)} onSave={async (input) => { await api.setProjectNetwork(networkProject.id, input); setNetworkProject(undefined); await refresh(); notify('网络配置已保存'); }} /> : null}{batch?<BatchComposer {...batch} users={users} projects={overview.projects} plans={props.plans} onClose={()=>{setBatch(undefined);void refresh().catch(()=>{})}} onChanged={refresh}/>:null}{notice ? <div className="toast">{notice}</div> : null}</div>;
|
||||
}
|
||||
|
||||
function AdminPage({ page, users, domains, overview, settings, plans, query, setQuery, setPage, setShowUserForm, setShowPlanForm, setNetworkProject, setShowAdoption, setSettings, refresh, notify, openBatch, props }: { page: Page; users: Tenant[]; domains: DomainResource[]; overview: AdminOverview; settings?: AdminSettings; plans: Plan[]; query: string; setQuery: (v: string) => void; setPage: (v: Page) => void; setShowUserForm: (v: boolean) => void; setShowPlanForm: (v: boolean) => void; setNetworkProject: (v: AdminProject) => void; setShowAdoption: (v: boolean) => void; setSettings: (v: AdminSettings) => void; refresh: () => Promise<void>; notify: (v: string) => void; openBatch:(selection:BatchSelection)=>void; props: Props }) {
|
||||
if (page === 'overview') return <Overview users={users} projects={overview.projects} domains={domains} logs={overview.logs} navigate={setPage} review={props.onReviewDomain} />;
|
||||
if (page === 'batches') return <BatchJobs create={openBatch} onChanged={refresh}/>;
|
||||
if (page === 'users') return <Users refresh={refresh} bulk={openBatch} enter={id=>{if(props.onImpersonate)void props.onImpersonate({tenantId:id}).catch(reason=>notify(reason instanceof Error?reason.message:'进入失败'))}} users={users} query={query} setQuery={setQuery} create={() => setShowUserForm(true)} expiry={async (id, value) => { await api.setTenantExpiry(id, value); await refresh(); notify('用户到期时间已更新'); }} />;
|
||||
if(page==='nodes') return <NodeManagement/>;
|
||||
if (page === 'hosts') return <Hosts bulk={openBatch} enter={id=>{if(props.onImpersonate)void props.onImpersonate({projectId:id}).catch(reason=>notify(reason instanceof Error?reason.message:'进入失败'))}} users={users} plans={plans} refresh={refresh} projects={overview.projects} query={query} setQuery={setQuery} network={setNetworkProject} adopt={() => setShowAdoption(true)} />;
|
||||
if (page === 'environment') return <NodeEnvironment />;
|
||||
if (page === 'plans') return <Plans plans={plans} create={() => setShowPlanForm(true)} save={props.onCreatePlan} changed={props.onPlansChanged} />;
|
||||
if (page === 'domains') return <Domains unbind={async item=>{await api.unbindDomain(item.id,item.domain,true);await refresh();notify('自定义域名已解绑')}} domains={domains} approval={settings?.domainApproval ?? props.approval} approvalChange={async (value) => { await props.onApproval(value); if (settings) setSettings({ ...settings, domainApproval: value }); }} review={async (id, approved) => { await props.onReviewDomain(id, approved); await refresh(); }} metadata={async (id, input) => { await api.updateDomainMetadata(id, input); await refresh(); notify('域名策略已更新'); }} dns={async (id, remove) => { if (remove) await api.removeDomainDNS(id, true); else await api.provisionDomainDNS(id, true); await refresh(); notify(remove ? '托管 DNS 记录已删除' : 'CNAME 记录已创建'); }} />;
|
||||
if (page === 'dns') return <section className="admin-page"><Heading title="DNS 管理" description="管理平台根域 DNS API,并为自动签发与续期提供凭据。" /><DNSCredentials admin /></section>;
|
||||
if (page === 'ips') return <NodeIPPool overview={overview} refresh={refresh} />;
|
||||
if (page === 'lifecycle') return <Lifecycle projects={overview.projects} onManage={()=>setPage('hosts')} />;
|
||||
if(page==='integration')return <IntegrationAPI/>;
|
||||
if (page === 'settings' && settings) return <SettingsPage settings={settings} save={async (value) => { await api.saveAdminSettings(value); setSettings(value); notify('系统设置已保存'); }} />;
|
||||
if (page === 'logs') return <AdminLogs logs={overview.logs} refresh={refresh} />;
|
||||
return <section className="admin-page"><Heading title="系统设置" description="管理数据正在加载。" /></section>;
|
||||
}
|
||||
|
||||
function Heading({ title, description, action }: { title: string; description: string; action?: ReactNode }) { return <PageHeader title={title} description={description} actions={action}/>; }
|
||||
function KPI({ icon: Icon, label, value, note }: { icon: typeof UsersRound; label: string; value: number; note: string }) { return <article><span><Icon size={19} /></span><div><small>{label}</small><b>{value}</b><em>{note}</em></div></article>; }
|
||||
function Empty({ text }: { text: string }) { return <div className="admin-empty">{text}</div>; }
|
||||
function SearchBox({ value, change, placeholder }: { value: string; change: (v: string) => void; placeholder: string }) { return <label className="admin-search"><Search size={16} /><input value={value} onChange={(event) => change(event.target.value)} placeholder={placeholder} /></label>; }
|
||||
|
||||
function Overview({ users, projects, domains, logs, navigate, review }: { users: Tenant[]; projects: AdminProject[]; domains: DomainResource[]; logs: AdminOverview['logs']; navigate: (v: Page) => void; review: (id: number, approved: boolean) => Promise<void> }) {
|
||||
const running = projects.filter((item) => item.status === 'running').length; const pending = domains.filter((item) => item.status === 'pending').length; const expiring = users.filter((item) => item.expiresAt && new Date(item.expiresAt).getTime() < Date.now() + 7 * 86400000).length;
|
||||
return <section className="admin-page"><Heading title="平台总览" description="虚拟主机资源、解析与生命周期的实时概况。" /><div className="admin-kpis"><KPI icon={UsersRound} label="用户" value={users.length} note="未开放公开注册" /><KPI icon={Server} label="虚拟主机" value={projects.length} note={`${running} 台运行中`} /><KPI icon={Globe2} label="域名" value={domains.length} note={`${pending} 个待审核`} /><KPI icon={Activity} label="7 天内到期" value={expiring} note="到期后宽限 3 天" /></div>{pending ? <section className="admin-card pending-summary"><header><h2>待审核域名</h2><button onClick={() => navigate('domains')}>域名管理</button></header><div className="compact-list">{domains.filter((item) => item.status === 'pending').slice(0, 4).map((item) => <div key={item.id}><Globe2 size={16} /><span><b>{item.domain}</b><small>{item.tenantName} · {item.hostName}</small></span><span className="row-actions"><button onClick={() => void review(item.id, false)}>拒绝</button><button className="primary" onClick={() => void review(item.id, true)}>批准</button></span></div>)}</div></section> : null}<div className="admin-overview-grid"><section className="admin-card"><header><h2>虚拟主机状态</h2><button onClick={() => navigate('hosts')}>查看全部</button></header><div className="compact-list">{projects.slice(0, 6).map((item) => <div key={item.id}><span className={`state-dot ${item.status}`} /><span><b>{item.hostName}</b><small>{item.tenantName} · {item.runtime} {item.version}</small></span><code>{item.domain}</code></div>)}{!projects.length ? <Empty text="暂无虚拟主机" /> : null}</div></section><section className="admin-card"><header><h2>最近操作</h2><button onClick={() => navigate('logs')}>操作日志</button></header><div className="compact-list logs">{logs.slice(0, 6).map((item) => <div key={item.id}><span className={item.success ? 'log-ok' : 'log-fail'}>{item.success ? '成功' : '失败'}</span><span><b>{item.detail}</b><small>{dateText(item.createdAt)}</small></span></div>)}{!logs.length ? <Empty text="暂无操作记录" /> : null}</div></section></div></section>;
|
||||
}
|
||||
|
||||
function Users({users,query,setQuery,create,enter,bulk,refresh}:{refresh:()=>Promise<void>;users:Tenant[];query:string;setQuery:(value:string)=>void;create:()=>void;expiry:(id:number,value?:string)=>Promise<void>;enter?:(id:number)=>void;bulk:(selection:BatchSelection)=>void}){
|
||||
const [editing,setEditing]=useState<Tenant>(),[deleting,setDeleting]=useState<Tenant>();
|
||||
const [selected,setSelected]=useState<number[]>([]);const list=users.filter(item=>`${item.name} ${item.slug}`.toLowerCase().includes(query.toLowerCase()));const ids=selected.filter(id=>users.some(item=>item.id===id));
|
||||
const change=(id:number,checked:boolean)=>setSelected(current=>checked?[...new Set([...current,id])]:current.filter(value=>value!==id));
|
||||
const run=(operation:'user_enable'|'user_disable',targets=ids)=>bulk({operation,rows:targets.map(accountId=>({accountId}))});
|
||||
return <><section className="admin-page"><Heading title="用户管理" description="用户可管理名下多台主机;每台主机可独立绑定或解绑用户。" action={<div className="row-actions"><button className="secondary" onClick={()=>bulk({operation:'create_users'})}>批量创建用户</button><button className="primary" onClick={create}><Plus size={16}/>新建用户</button></div>}/><div className="admin-toolbar"><SearchBox value={query} change={setQuery} placeholder="搜索用户名称或标识"/><span>共 {list.length} 个用户 · 已选 {ids.length} 个</span><button className="secondary" disabled={!ids.length} onClick={()=>run('user_enable')}>批量启用</button><button className="secondary" disabled={!ids.length} onClick={()=>run('user_disable')}>批量停用</button></div><Table><thead><tr><th><input type="checkbox" aria-label="选择全部用户" checked={list.length>0&&list.every(item=>ids.includes(item.id))} onChange={event=>setSelected(event.target.checked?list.map(item=>item.id):[])}/></th><th>用户</th><th>虚拟主机</th><th>状态</th><th>操作</th></tr></thead><tbody>{list.map(item=><tr key={item.id}><td><input type="checkbox" aria-label={'选择用户 '+item.slug} checked={ids.includes(item.id)} onChange={event=>change(item.id,event.target.checked)}/></td><td><b>{item.name}</b><small>{item.slug}</small></td><td>{item.projectCount}</td><td>{item.status==='active'?'正常':'已停用'}</td><td><div className="row-actions"><button className="table-link" aria-label={'编辑用户 '+item.slug} onClick={()=>setEditing(item)}>详情 / 编辑</button><button className="table-link" aria-label={'进入用户 '+item.slug} disabled={item.status!=='active'||!enter} onClick={()=>enter?.(item.id)}>进入用户</button><button className="table-link" aria-label={(item.status==='active'?'停用用户 ':'启用用户 ')+item.slug} onClick={()=>run(item.status==='active'?'user_disable':'user_enable',[item.id])}>{item.status==='active'?'停用':'启用'}</button><button className="table-link danger-text" aria-label={'删除用户 '+item.slug} disabled={item.projectCount>0} title={item.projectCount>0?'请先逐一解绑或转移全部主机,包括回收中的主机':undefined} onClick={()=>setDeleting(item)}>删除</button></div></td></tr>)}</tbody></Table></section>{deleting?<AccountEditor intent="delete" account={deleting} onClose={()=>setDeleting(undefined)} onChanged={refresh}/>:null}{editing?<AccountEditor account={editing} onClose={()=>setEditing(undefined)} onChanged={refresh}/>:null}</>;
|
||||
}
|
||||
|
||||
|
||||
export function Plans({ plans, create,save,changed }: { plans: Plan[]; create: () => void;save:(input:PlanInput)=>Promise<void>;changed?:()=>Promise<void> }) {
|
||||
const [copy,setCopy]=useState<Plan>(),[removing,setRemoving]=useState<Plan>(),[confirmation,setConfirmation]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState(''),[hidden,setHidden]=useState<number[]>([]);
|
||||
return <section className="admin-page"><Heading title="套餐管理" description="套餐按版本保存,已创建套餐配额只读;可复制套餐后调整额度,再为主机更换套餐,避免影响其他主机。" action={<button className="primary" onClick={create}><Plus size={16} />创建套餐</button>} /><div className="plan-cards">{plans.filter(p=>!hidden.includes(p.id)).map((plan) => <article key={plan.id}><header><span><Boxes size={19} /></span><h2>{plan.name}</h2></header><dl><div><dt>存储空间</dt><dd>{formatBytes(plan.storageBytes)}</dd></div><div><dt>数据库空间</dt><dd>{formatBytes(plan.databaseBytes)}</dd></div><div><dt>月流量</dt><dd>{formatBytes(plan.bandwidthBytes)}</dd></div><div><dt>HTTP / FTP 限速</dt><dd>{plan.bandwidthMbps ? `${plan.bandwidthMbps} Mbps` : '不限速'}</dd></div><div><dt>进程上限</dt><dd>{plan.processLimit}</dd></div><div><dt>每主机网站数</dt><dd>{plan.projectLimit}</dd></div><div><dt>FTP 账号</dt><dd>{plan.ftpLimit}</dd></div><div><dt>数据库</dt><dd>{plan.databaseLimit}</dd></div></dl><div className="row-actions"><button aria-label={'复制套餐 '+plan.name} onClick={()=>setCopy(plan)}>复制套餐</button><button aria-label={'删除套餐 '+plan.name} disabled={!!plan.deleteBlockedReason||plan.id===1} title={plan.deleteBlockedReason||(plan.id===1?'系统默认套餐不能删除':'删除未使用套餐')} onClick={()=>{setRemoving(plan);setConfirmation('');setError('')}}>删除</button></div>{plan.deleteBlockedReason||plan.id===1?<p className="field-hint">{plan.deleteBlockedReason||'系统默认套餐不能删除'}</p>:null}</article>)}</div>{copy?<PlanForm initial={copy} onClose={()=>setCopy(undefined)} onCreate={async input=>{await save(input);setCopy(undefined)}}/>:null}{removing?<ModalBackdrop><form className="tenant-modal" onSubmit={async e=>{e.preventDefault();if(busy||confirmation!==removing.name)return;setBusy(true);setError('');try{await api.deletePlan(removing.id,confirmation);setHidden(v=>[...v,removing.id]);setRemoving(undefined);await changed?.()}catch(e){setError(e instanceof Error?e.message:'删除套餐失败')}finally{setBusy(false)}}}><h2>删除未使用套餐</h2><p>仅允许删除未被主机或历史账号引用的套餐,此操作不能恢复。</p><label>输入套餐名称确认删除<input value={confirmation} onChange={e=>setConfirmation(e.target.value)} disabled={busy} placeholder={removing.name}/></label>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={()=>setRemoving(undefined)}>取消</button><button className="primary danger-confirm" disabled={busy||confirmation!==removing.name}>{busy?'正在删除…':'确认删除套餐'}</button></div></form></ModalBackdrop>:null}</section>; }
|
||||
|
||||
function Lifecycle({projects,onManage}:{projects:AdminProject[];onManage:()=>void}){return <section className="admin-page"><Heading title="到期与回收" description="调度器自动处理到期和清理;恢复主机、修改套餐或到期时间请进入虚拟主机管理。宽限 3 天,回收 7 天,清理后的备份保留 14 天。" action={<button className="secondary" onClick={onManage}>管理主机 / 恢复</button>}/><Table><thead><tr><th>虚拟主机</th><th>用户 / 节点</th><th>当前阶段</th><th>到期时间</th></tr></thead><tbody>{projects.map(p=><tr key={p.id}><td>{p.hostName}</td><td>{p.tenantName} / #{p.nodeId}</td><td><LifecycleBadge state={p.lifecycleState as Tenant['lifecycleState']}/></td><td>{p.expiresAt?dateText(p.expiresAt):"长期使用"}</td></tr>)}</tbody></Table></section>}
|
||||
|
||||
function Table({ children }: { children: ReactNode }) { return <div className="admin-table-v2"><table>{children}</table></div>; }
|
||||
|
||||
function UserForm({ plans, onClose, onCreate }: { plans: Plan[]; onClose: () => void; onCreate: (input: Record<string, unknown>) => Promise<void> }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(''); return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal" onSubmit={async (event) => { event.preventDefault(); setBusy(true); const form = new FormData(event.currentTarget); try { await onCreate({ slug: form.get('slug'), name: form.get('name'), email: form.get('email'), displayName: form.get('displayName'), password: form.get('password'), planId: plans[0]?.id }); } catch (reason) { setError(reason instanceof Error ? reason.message : '创建失败'); setBusy(false); } }}><h2>创建用户</h2><p>创建登录账号后,可继续为该用户新增多个虚拟主机。</p><label>用户名称<input name="name" maxLength={120} required /></label><label>用户标识<input name="slug" pattern="[a-z0-9\-]{3,48}" required /></label><label>联系人姓名<input name="displayName" minLength={2} maxLength={80} required /></label><label>登录邮箱<input name="email" type="email" required /></label><label>初始密码<input name="password" type="password" minLength={12} required /></label>{error ? <p className="form-error">{error}</p> : null}<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy || !plans.length}>{busy ? '创建中…' : '创建用户'}</button></div></form></ModalBackdrop>; }
|
||||
export function PlanForm({ onClose, onCreate,initial }: { initial?:Plan; onClose: () => void; onCreate: (input: PlanInput) => Promise<void> }) { const [busy, setBusy] = useState(false);const [error,setError]=useState(''); return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal plan-modal" onSubmit={async (event) => { event.preventDefault(); setBusy(true);setError(''); const form = new FormData(event.currentTarget); const gib = 1024 ** 3; try { await onCreate({ name: String(form.get('name')), storageBytes: Number(form.get('storageGB')) * gib, databaseBytes: Number(form.get('databaseGB')) * gib, bandwidthBytes: Number(form.get('bandwidthGB')) * gib, bandwidthMbps: Number(form.get('bandwidthMbps')), processLimit: Number(form.get('processLimit')), projectLimit: Number(form.get('projectLimit')), ftpLimit: Number(form.get('ftpLimit')), databaseLimit: Number(form.get('databaseLimit')) }); } catch(e){setError(e instanceof Error?e.message:'套餐保存失败')} finally { setBusy(false); } }}><h2>{initial?'复制资源套餐':'创建资源套餐'}</h2><label>套餐名称<input name="name" defaultValue={initial?initial.name+' 副本':''} maxLength={80} required /></label><div className="plan-form-grid">{[['storageGB', '存储空间(GB)', initial?initial.storageBytes/1024**3:50], ['databaseGB', '数据库空间(GB)', initial?initial.databaseBytes/1024**3:20], ['bandwidthGB', '月流量(GB)', initial?initial.bandwidthBytes/1024**3:500], ['bandwidthMbps', 'HTTP 每请求 / FTP 每会话限速(Mbps,0 不限)', initial?.bandwidthMbps??0], ['processLimit', '进程数', initial?.processLimit??100], ['projectLimit', '每主机网站数', initial?.projectLimit??10], ['ftpLimit', 'FTP 账号数', initial?.ftpLimit??10], ['databaseLimit', '数据库数', initial?.databaseLimit??10]].map(([name, label, value]) => <label key={String(name)}>{label}<input name={String(name)} type="number" step={String(name).endsWith('GB')?'any':1} min={name === 'bandwidthMbps' ? 0 : String(name).endsWith('GB')?1/1024:1} max={name === 'bandwidthMbps' ? 10000 : undefined} defaultValue={value} required /></label>)}</div>{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy}>{busy ? '创建中…' : initial?'保存为新套餐':'创建套餐'}</button></div></form></ModalBackdrop>; }
|
||||
|
||||
function AdoptionForm({users,plans,onClose,onComplete}:{users:Tenant[];plans:Plan[];onClose:()=>void;onComplete:()=>Promise<void>}){return <HostProvisioning adopt users={users} plans={plans} onClose={onClose} onComplete={onComplete}/>}
|
||||
|
||||
export function NetworkForm({ project, ips, onClose, onSave }: { project: AdminProject; ips: AdminOverview['ipAddresses']; onClose: () => void; onSave: (input: { ipId?: number; dedicated: boolean; httpPort: number; httpsPort: number }) => Promise<void> }) { const [busy,setBusy]=useState(false),[error,setError]=useState(''); const [dedicated, setDedicated] = useState(project.dedicatedIp); const [ipId, setIPID] = useState<number | undefined>(() => ips.find((item) => item.address === project.ipAddress)?.id); const [httpPort, setHTTPPort] = useState(project.httpPort || 80); const [httpsPort, setHTTPSPort] = useState(project.httpsPort || 443); return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal" onSubmit={async (event) => { event.preventDefault(); if(busy)return;setBusy(true);setError('');try{await onSave({ ipId: dedicated ? ipId : undefined, dedicated, httpPort, httpsPort });}catch(e){setError(e instanceof Error?e.message:'网络配置保存失败')}finally{setBusy(false)} }}><h2>公开网络配置</h2><p>{project.hostName} · 内部反向代理端口与公开端口相互独立。</p><label>IP 模式<select value={dedicated ? 'dedicated' : 'shared'} onChange={(event) => setDedicated(event.target.value === 'dedicated')}><option value="shared">共享 IP(默认)</option><option value="dedicated">独立 IP(增值)</option></select></label>{dedicated ? <label>独立 IP<select required value={ipId || ''} onChange={(event) => setIPID(Number(event.target.value))}><option value="">请选择</option>{ips.filter((item) => item.allocationMode === 'dedicated' && item.nodeId===project.nodeId).map((item) => <option key={item.id} value={item.id}>{item.address} {item.label}</option>)}</select></label> : null}<div className="plan-form-grid"><label>HTTP 公开端口<input type="number" min="1" max="65535" value={httpPort} onChange={(event) => setHTTPPort(Number(event.target.value))} /></label><label>HTTPS 公开端口<input type="number" min="1" max="65535" value={httpsPort} onChange={(event) => setHTTPSPort(Number(event.target.value))} /></label></div>{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy}>{busy?'正在保存…':'保存网络配置'}</button></div></form></ModalBackdrop>; }
|
||||
|
||||
function LifecycleBadge({ state = 'active' }: { state?: Tenant['lifecycleState'] }) { return <span className={`lifecycle-badge ${state}`}>{state === 'grace' ? '宽限期' : state === 'recycle' ? '回收区' : state === 'purged' ? '已清理' : '正常'}</span>; }
|
||||
function statusText(v: string) { return ({ running: '运行中', stopped: '已停止', awaiting_upload: '待上传', quota_suspended: '配额停用', provisioning: '创建中', failed: '失败' } as Record<string, string>)[v] || v; }
|
||||
function filingText(v?: string) { return v === 'approved' ? '已备案' : v === 'pending' ? '待审核' : v === 'rejected' ? '未通过' : '免备案'; }
|
||||
function dateText(v?: string) { return v ? new Date(v).toLocaleString('zh-CN', { hour12: false }) : '—'; }
|
||||
function toLocalInput(v: string) { const date = new Date(v); return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16); }
|
||||
@@ -0,0 +1,23 @@
|
||||
import {useState} from 'react';
|
||||
import type {DomainResource} from '../api';
|
||||
import {PageHeader} from './UI';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import {UnbindDomainDialog} from './UnbindDomainDialog';
|
||||
|
||||
interface Props {domains:DomainResource[];approval:boolean;approvalChange:(v:boolean)=>Promise<void>;review:(id:number,approved:boolean)=>Promise<void>;metadata:(id:number,input:Record<string,unknown>)=>Promise<void>;dns:(id:number,remove:boolean)=>Promise<void>;unbind?:(domain:DomainResource)=>Promise<void>}
|
||||
export function AdminDomains({domains,approval,approvalChange,review,metadata,dns,unbind}:Props){
|
||||
const [removing,setRemoving]=useState<DomainResource>();
|
||||
const [kind,setKind]=useState('all'),[busy,setBusy]=useState(''),[error,setError]=useState(''),[editing,setEditing]=useState<DomainResource>();const {confirm,confirmation}=useConfirmation();
|
||||
const list=domains.filter(v=>kind==='all'||v.kind===kind);
|
||||
async function perform(key:string,action:()=>Promise<void>){setBusy(key);setError('');try{await action()}catch(e){setError(e instanceof Error?e.message:'操作失败')}finally{setBusy('')}}
|
||||
async function dnsAction(v:DomainResource){if(v.dnsRecordId&&!await confirm(`删除 Sea vHost 托管的「${v.domain}」DNS 记录?域名绑定和网站文件保留。`,{title:'删除托管解析',danger:true}))return;await perform('dns'+v.id,()=>dns(v.id,!!v.dnsRecordId))}
|
||||
return <section className="admin-page"><PageHeader title="域名管理" description="查看默认主机子域名、自绑定域名、审核、备案和解析目标。默认域名随主机管理,不提供单独删除入口。" actions={<label className="switch-line"><span>自定义域名审核</span><button aria-label="自定义域名审核" role="switch" aria-checked={approval} disabled={!!busy} className={approval?'toggle on':'toggle'} onClick={()=>void perform('approval',()=>approvalChange(!approval))}><i/></button></label>}/>
|
||||
{error?<p className="form-error" role="alert">{error}</p>:null}<div className="admin-toolbar"><div className="segmented">{[['all','全部'],['assigned','默认子域名'],['custom','自绑定']].map(([v,label])=><button key={v} className={kind===v?'active':''} onClick={()=>setKind(v)}>{label}</button>)}</div><span>共 {list.length} 个域名</span></div><div className="admin-table-v2 table-scroll"><table><thead><tr><th>域名</th><th>用户 / 主机</th><th>类型</th><th>解析</th><th>备案</th><th>网站 SSL</th><th>操作</th></tr></thead><tbody>{list.map(v=><tr key={v.id}><td><b>{v.domain}</b><small>{v.siteName}</small></td><td>{v.tenantName}<small>{v.hostName}</small></td><td>{v.kind==='assigned'?'默认子域名':'自绑定'}</td><td>{v.dnsRecordId?`托管 ${v.dnsRecordType}`:v.resolutionMode==='cdn'?'CDN':v.resolutionMode==='cname'?'CNAME':'直接解析'}<small>{v.dnsLastError||v.cnameTarget}</small></td><td>{filingLabel(v.filingStatus)}<small>{v.filingNumber}</small></td><td>{v.status!=='approved'?'审核后配置':({active:'已启用',pending:'待签发',failed:'失败',off:'未启用'} as Record<string,string>)[v.sslStatus]||v.sslStatus}</td><td>{v.kind==='assigned'?<small>随主机管理</small>:<span className="row-actions">{unbind?<button disabled={!!busy} onClick={()=>setRemoving(v)}>解绑</button>:null}<button disabled={!!busy} aria-label={'配置域名 '+v.domain} onClick={()=>setEditing(v)}>配置</button>{v.status==='pending'?<><button disabled={!!busy} onClick={()=>void perform('reject'+v.id,()=>review(v.id,false))}>拒绝</button><button disabled={!!busy} className="primary" onClick={()=>void perform('approve'+v.id,()=>review(v.id,true))}>批准</button></>:v.status==='approved'?<button disabled={!!busy} onClick={()=>void dnsAction(v)}>{v.dnsRecordId?'删除托管解析':'自动 CNAME'}</button>:<small>审核未通过</small>}</span>}</td></tr>)}</tbody></table>{!list.length?<p className="admin-empty">暂无域名</p>:null}</div>
|
||||
{editing?<DomainPolicyForm key={editing.id} domain={editing} onClose={()=>setEditing(undefined)} onSave={async input=>{await metadata(editing.id,input);setEditing(undefined)}}/>:null}{removing&&unbind?<UnbindDomainDialog domain={removing} onClose={()=>setRemoving(undefined)} onUnbind={()=>unbind(removing)}/>:null}{confirmation}</section>;
|
||||
}
|
||||
export function DomainPolicyForm({domain,onClose,onSave}:{domain:DomainResource;onClose:()=>void;onSave:(input:Record<string,unknown>)=>Promise<void>}){
|
||||
const [mode,setMode]=useState(domain.resolutionMode||'cname'),[target,setTarget]=useState(domain.cnameTarget||''),[filing,setFiling]=useState(domain.filingStatus||'exempt'),[number,setNumber]=useState(domain.filingNumber||''),[note,setNote]=useState(domain.filingNote||''),[busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
return <ModalBackdrop><form className="tenant-modal" onSubmit={async e=>{e.preventDefault();if(busy)return;setBusy(true);setError('');try{await onSave({resolutionMode:mode,cnameTarget:mode==='direct'?'':target,filingStatus:filing,filingNumber:number,filingNote:note})}catch(e){setError(e instanceof Error?e.message:'域名配置保存失败')}finally{setBusy(false)}}}><h2>域名配置</h2><p>{domain.domain}</p><label>解析模式<select disabled={busy} value={mode} onChange={e=>setMode(e.target.value as typeof mode)}><option value="direct">直接解析到节点 IP</option><option value="cname">CNAME 到主机域名</option><option value="cdn">CDN CNAME</option></select></label>{mode!=='direct'?<label>CNAME 目标<input value={target} onChange={e=>setTarget(e.target.value)} maxLength={253} required={mode==='cname'} disabled={busy} placeholder={mode==='cdn'?'留空使用系统 CDN 目标':''}/></label>:null}<label>备案状态<select value={filing} onChange={e=>setFiling(e.target.value as typeof filing)} disabled={busy}><option value="exempt">免备案</option><option value="pending">待审核</option><option value="approved">已备案</option><option value="rejected">未通过</option></select></label><label>备案号<input maxLength={80} value={number} onChange={e=>setNumber(e.target.value)} disabled={busy}/></label><label>备案备注<textarea maxLength={500} value={note} onChange={e=>setNote(e.target.value)} disabled={busy}/></label><p>这里保存解析指引与备案信息。创建或删除托管 DNS 记录使用域名列表中的独立操作。</p>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="form-actions"><button type="button" onClick={onClose}>取消</button><button className="primary" disabled={busy}>{busy?'正在保存…':'保存域名配置'}</button></div></form></ModalBackdrop>;
|
||||
}
|
||||
function filingLabel(v?:string){return ({approved:'已备案',pending:'待审核',rejected:'未通过',exempt:'免备案'} as Record<string,string>)[v||'exempt']||v}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import {api} from '../api';
|
||||
import {HostEditor} from './ResourceEditors';
|
||||
import {useState} from 'react';
|
||||
import {Plus,Search,RotateCcw} from 'lucide-react';
|
||||
import type {AdminProject,Tenant} from '../api';
|
||||
import type {Plan,Runtime} from '../types';
|
||||
import type {BatchSelection} from './AdminBatches';
|
||||
import {HostProvisioning,HostSubscription} from './HostProvisioning';
|
||||
import {PageHeader,Pagination,RuntimeMark,SelectionCheckbox} from './UI';
|
||||
|
||||
export function AdminHosts({projects,query,setQuery,network,adopt,users,plans,refresh,enter,bulk}:{users:Tenant[];plans:Plan[];refresh:()=>Promise<void>;enter?:(id:number)=>void;bulk:(selection:BatchSelection)=>void;projects:AdminProject[];query:string;setQuery:(value:string)=>void;network:(value:AdminProject)=>void;adopt:()=>void}){
|
||||
const {confirm,confirmation}=useConfirmation();const [detachBusy,setDetachBusy]=useState(false),[detachError,setDetachError]=useState('');
|
||||
const [editing,setEditing]=useState<AdminProject>();const [recycling,setRecycling]=useState<AdminProject>();
|
||||
const [create,setCreate]=useState(false),[subscription,setSubscription]=useState<AdminProject>(),[selected,setSelected]=useState<number[]>([]);
|
||||
const [status,setStatus]=useState(''),[runtime,setRuntime]=useState(''),[node,setNode]=useState(''),[plan,setPlan]=useState(''),[page,setPage]=useState(1),[pageSize,setPageSize]=useState(10);
|
||||
const list=projects.filter(p=>`${p.id} ${p.hostName} ${p.name} ${p.tenantName} ${p.domain}`.toLowerCase().includes(query.toLowerCase())&&(!status||(status==='recycle'?!!p.manualRecycledAt:!p.manualRecycledAt&&p.status===status))&&(!runtime||p.runtime===runtime)&&(!node||p.nodeId===Number(node))&&(!plan||p.planId===Number(plan)));
|
||||
const currentPage=Math.min(page,Math.max(1,Math.ceil(list.length/pageSize))),visible=list.slice((currentPage-1)*pageSize,currentPage*pageSize),ids=selected.filter(id=>projects.some(p=>p.id===id&&!p.manualRecycledAt));
|
||||
const eligible=visible.filter(p=>!p.manualRecycledAt);
|
||||
const hiddenSelections=ids.filter(id=>!list.some(p=>p.id===id)).length;
|
||||
const run=(operation:BatchSelection['operation'],targets=ids)=>bulk({operation,rows:targets.map(hostId=>({hostId,ownershipVersion:projects.find(p=>p.id===hostId)?.ownershipVersion}))});
|
||||
const changeFilter=(fn:()=>void)=>{fn();setPage(1)};
|
||||
const reset=()=>{setQuery('');setStatus('');setRuntime('');setNode('');setPlan('');setPage(1)};
|
||||
return <>{confirmation}{detachError?<p className="form-error" role="alert">{detachError}</p>:null}<section className="admin-page"><PageHeader title="虚拟主机" description="管理主机、归属用户与运行配置。" actions={<><button className="primary" onClick={()=>setCreate(true)}><Plus size={16}/>开通虚拟主机</button><button className="secondary" onClick={()=>bulk({operation:'create_hosts'})}>批量创建主机</button></>}/>
|
||||
<section className="admin-table-v2 hosts-table"><div className="host-filters"><label className="admin-search"><Search size={16}/><input value={query} onChange={e=>changeFilter(()=>setQuery(e.target.value))} placeholder="搜索主机、用户或域名" aria-label="搜索主机、用户或域名"/></label><select aria-label="筛选主机状态" value={status} onChange={e=>changeFilter(()=>setStatus(e.target.value))}><option value="">全部状态</option>{Object.entries(statuses).map(([v,l])=><option key={v} value={v}>{l}</option>)}</select><select aria-label="筛选节点" value={node} onChange={e=>changeFilter(()=>setNode(e.target.value))}><option value="">全部节点</option>{[...new Set(projects.map(p=>p.nodeId))].map(id=><option key={id} value={id}>节点 #{id}</option>)}</select><select aria-label="筛选运行环境" value={runtime} onChange={e=>changeFilter(()=>setRuntime(e.target.value))}><option value="">全部运行环境</option>{['PHP','Node.js','Python','Go','Java'].map(v=><option key={v}>{v}</option>)}</select><select aria-label="筛选套餐" value={plan} onChange={e=>changeFilter(()=>setPlan(e.target.value))}><option value="">全部套餐</option>{plans.map(p=><option key={p.id} value={p.id}>{p.name}</option>)}</select><button className="secondary" onClick={reset} title="重置筛选"><RotateCcw size={15}/>重置</button></div>
|
||||
<div className="host-bulk-bar"><span role="status">已选择 <b>{ids.length}</b> 项{hiddenSelections?<small>含 {hiddenSelections} 项不在当前筛选中</small>:null}</span>{ids.length?<button className="table-link" onClick={()=>setSelected([])}>清空选择</button>:null}<div className="batch-toolbar"><button disabled={!ids.length} onClick={()=>run('assign_hosts')}>绑定 / 解绑用户</button><button disabled={!ids.length} onClick={()=>run('host_subscription')}>修改套餐 / 到期</button><button disabled={!ids.length} onClick={()=>run('host_start')}>批量启动</button><button disabled={!ids.length} onClick={()=>run('host_stop')}>批量停止</button><button disabled={!ids.length} onClick={()=>run('host_password_reset')}>重置登录密码</button></div><button className="table-link" onClick={adopt}>迁移宝塔站点</button></div>
|
||||
<div className="table-scroll"><table><thead><tr><th><SelectionCheckbox disabled={!eligible.length} mixed={eligible.some(p=>ids.includes(p.id))&&!eligible.every(p=>ids.includes(p.id))} aria-label="选择本页主机" checked={eligible.length>0&&eligible.every(p=>ids.includes(p.id))} onChange={e=>setSelected(current=>e.target.checked?[...new Set([...current,...eligible.map(p=>p.id)])]:current.filter(id=>!eligible.some(p=>p.id===id)))}/></th><th>虚拟主机</th><th>绑定用户 / 节点</th><th>套餐 / 到期</th><th>运行环境</th><th>站点</th><th>访问地址 / 网络</th><th>状态</th><th>操作</th></tr></thead><tbody>{visible.map(p=><tr key={p.id}><td><input type="checkbox" disabled={!!p.manualRecycledAt} title={p.manualRecycledAt?'回收中的主机只能查看回收详情或恢复':undefined} aria-label={'选择主机 '+p.hostName} checked={ids.includes(p.id)} onChange={e=>setSelected(current=>e.target.checked?[...new Set([...current,p.id])]:current.filter(id=>id!==p.id))}/></td><td><b>{p.hostName}</b><small>#{p.id} · {p.name}</small></td><td><button className="table-link" aria-label={'绑定用户 '+p.hostName} disabled={!!p.manualRecycledAt} onClick={()=>run('assign_hosts',[p.id])}>{p.tenantName||'未绑定用户'}</button><small>节点 #{p.nodeId}</small></td><td><button className="table-link" disabled={!!p.manualRecycledAt} onClick={()=>setSubscription(p)}>{plans.find(plan=>plan.id===p.planId)?.name||'设置套餐'}</button><small>{p.expiresAt?new Date(p.expiresAt).toLocaleDateString('zh-CN'):'长期使用'}</small></td><td><div className="runtime-cell"><RuntimeMark runtime={p.runtime as Runtime}/><span>{p.runtime}<small>{p.version}</small></span></div></td><td>{p.siteCount}</td><td><code>{p.domain}{p.httpPort!==80?':'+p.httpPort:''}</code><button className="table-link network-link" aria-label={'配置网络 '+p.hostName} disabled={!!p.manualRecycledAt} onClick={()=>network(p)}>{p.dedicatedIp?p.ipAddress||'独立 IP':'共享 IP'} · {p.httpPort}/{p.httpsPort}</button></td><td><span className={'status '+(p.managementLocked?'provisioning':p.status)}>{p.manualRecycledAt?'回收中':p.managementLocked?'归属待核验':statuses[p.status]||p.status}</span></td><td><div className="host-row-actions">{p.manualRecycledAt&&p.ownerTenantId?<button className="table-link" disabled={detachBusy||p.managementLocked} aria-label={'解绑回收主机 '+p.hostName} onClick={async()=>{if(!await confirm(`逐一解绑回收主机 ${p.hostName} 与用户 ${p.tenantName}?主机继续回收,保留期限不变。`,{title:'解绑回收主机',danger:true}))return;setDetachBusy(true);setDetachError('');try{await api.detachRecycledHost(p);await refresh()}catch(e){setDetachError(e instanceof Error?e.message:'解绑失败')}finally{setDetachBusy(false)}}}>解绑用户</button>:null}<button className="table-link" aria-label={'进入主机 '+p.hostName} disabled={!!p.manualRecycledAt||!enter||p.managementLocked||['failed','provisioning'].includes(p.status)} onClick={()=>enter?.(p.id)}>进入主机</button><button className="table-link" aria-label={'编辑主机 '+p.hostName} onClick={()=>setEditing(p)}>{p.manualRecycledAt?'回收详情 / 恢复':'详情 / 编辑'}</button>{!p.manualRecycledAt?<button className="table-link danger-text" disabled={p.managementLocked} aria-label={'回收主机 '+p.hostName} onClick={()=>setRecycling(p)}>回收</button>:null}</div></td></tr>)}</tbody></table>{!list.length?<div className="admin-empty">{projects.length?'没有匹配的主机,请调整筛选条件':'暂无虚拟主机,开通后将在这里显示。'}</div>:null}</div>
|
||||
<Pagination total={list.length} page={currentPage} pageSize={pageSize} onPage={setPage} onPageSize={v=>{setPageSize(v);setPage(1)}}/></section></section>
|
||||
{recycling?<HostEditor intent="recycle" host={projects.find(p=>p.id===recycling.id)||recycling} onClose={()=>setRecycling(undefined)} onChanged={refresh}/>:null}
|
||||
{editing?<HostEditor host={projects.find(p=>p.id===editing.id)||editing} onClose={()=>setEditing(undefined)} onChanged={refresh}/>:null}
|
||||
{create?<HostProvisioning users={users} plans={plans} onClose={()=>setCreate(false)} onComplete={async()=>{setCreate(false);await refresh()}}/>:null}{subscription?<HostSubscription project={subscription} plans={plans} onClose={()=>setSubscription(undefined)} onSaved={refresh}/>:null}</>;
|
||||
}
|
||||
const statuses:Record<string,string>={recycle:'回收中',running:'运行中',stopped:'已停止',awaiting_upload:'待上传',provisioning:'开通中',failed:'失败',quota_suspended:'配额暂停'};
|
||||
@@ -0,0 +1,21 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {RefreshCw,Download} from 'lucide-react';
|
||||
import {api,type AdminOverview} from '../api';
|
||||
import {PageHeader} from './UI';
|
||||
|
||||
export function AdminLogs({logs,refresh}:{logs:AdminOverview['logs'];refresh:()=>Promise<void>}){
|
||||
const [query,setQuery]=useState(''),[result,setResult]=useState(''),[action,setAction]=useState(''),[from,setFrom]=useState(''),[to,setTo]=useState(''),[limit,setLimit]=useState(100),[page,setPage]=useState(1),[reload,setReload]=useState(0);
|
||||
const [list,setList]=useState(logs),[total,setTotal]=useState(logs.length),[busy,setBusy]=useState(true),[error,setError]=useState('');
|
||||
const params=()=>{const q=new URLSearchParams({q:query,result,action,limit:String(limit),page:String(page)});if(from)q.set('from',new Date(from).toISOString());if(to)q.set('to',new Date(to).toISOString());return q};
|
||||
useEffect(()=>{let active=true;setBusy(true);setError('');const timer=window.setTimeout(()=>{api.adminAudit(params()).then(data=>{if(active){setList(data.logs);setTotal(data.total)}}).catch(e=>{if(active){setList([]);setError(e instanceof Error?e.message:'日志读取失败')}}).finally(()=>{if(active)setBusy(false)})},250);return()=>{active=false;window.clearTimeout(timer)}},[query,result,action,from,to,limit,page,reload]);
|
||||
const change=(setter:(value:string)=>void,value:string)=>{setter(value);setPage(1)};
|
||||
const [exporting,setExporting]=useState(false);
|
||||
async function download(){setExporting(true);setError('');try{
|
||||
const q=params();q.set('limit','500');q.set('page','1');const first=await api.adminAudit(q);if(first.total>10000)throw new Error('单次最多导出 10000 条,请缩小时间或筛选范围');
|
||||
const records=[...first.logs];if(first.logs.length)q.set('maxId',String(first.logs[0].id));for(let p=2;records.length<first.total;p++){q.set('page',String(p));const next=await api.adminAudit(q);if(!next.logs.length)break;records.push(...next.logs)}
|
||||
const url=URL.createObjectURL(new Blob([JSON.stringify({format:'sea-vhost.admin-audit',version:1,exportedAt:new Date().toISOString(),filters:Object.fromEntries(params()),total:records.length,logs:records},null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='sea-vhost-admin-audit.json';a.click();window.setTimeout(()=>URL.revokeObjectURL(url),1000)
|
||||
}catch(e){setError(e instanceof Error?e.message:'日志导出失败')}finally{setExporting(false)}}
|
||||
|
||||
return <section className="admin-page"><PageHeader title="操作日志" actions={<><button className="secondary" disabled={busy} onClick={()=>{setReload(v=>v+1);void refresh()}}><RefreshCw size={15}/>刷新日志</button><button className="secondary" title={!list.length?'没有可导出的日志':undefined} disabled={busy||exporting||!list.length} onClick={()=>void download()}><Download size={15}/>{exporting?'导出中…':'导出 JSON'}</button></>}/><div className="admin-toolbar"><label>搜索日志<input value={query} onChange={e=>change(setQuery,e.target.value)} placeholder="用户、动作、资源、IP 或详情"/></label><label>结果<select value={result} onChange={e=>change(setResult,e.target.value)}><option value="">全部</option><option value="success">成功</option><option value="failure">失败</option></select></label><label>动作<input value={action} onChange={e=>change(setAction,e.target.value)} placeholder="例如 create"/></label><label>开始时间<input type="datetime-local" value={from} onChange={e=>change(setFrom,e.target.value)}/></label><label>结束时间<input type="datetime-local" value={to} onChange={e=>change(setTo,e.target.value)}/></label><label>每页条数<select value={limit} onChange={e=>{setLimit(Number(e.target.value));setPage(1)}}>{[50,100,200,500].map(n=><option key={n} value={n}>{n} 条</option>)}</select></label><span>共 {total} 条 · 本页 {list.length} 条</span></div>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="admin-table-v2 table-scroll"><table><thead><tr><th>时间</th><th>用户</th><th>操作</th><th>资源</th><th>来源 IP</th><th>结果</th><th>详情</th></tr></thead><tbody>{list.map(v=><tr key={v.id}><td>{new Date(v.createdAt).toLocaleString('zh-CN',{hour12:false})}</td><td>{v.userName||'系统'}{v.impersonatedUserId?<small>代入:{v.impersonatedUserName||'#'+v.impersonatedUserId}</small>:null}</td><td>{v.action}</td><td>{v.resourceType}<small>{v.resourceId}</small></td><td><code>{v.ipAddress||'—'}</code></td><td><span className={v.success?'log-ok':'log-fail'}>{v.success?'成功':'失败'}</span></td><td>{v.detail}</td></tr>)}</tbody></table>{!list.length?<p className="admin-empty">{total?'没有匹配的日志':'暂无操作日志'}</p>:null}</div><div className="admin-toolbar audit-pagination"><button disabled={busy||page<=1} onClick={()=>setPage(v=>v-1)}>上一页</button><span>第 {page} / {Math.max(1,Math.ceil(total/limit))} 页</span><button disabled={busy||page*limit>=total} onClick={()=>setPage(v=>v+1)}>下一页</button><small>导出当前筛选条件的全部记录,最多 10000 条</small></div></section>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Building2, ChevronDown, Menu, UserRound,LogOut } from 'lucide-react';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { Brand } from './Brand';
|
||||
import { Sidebar } from './Sidebar';
|
||||
import {useNavigationOverlay} from './overlay';
|
||||
|
||||
export function AppShell({ page, tenantName, displayName, hostScoped = false, onNavigate, onSecurity,onLogout, children }: { page: string; tenantName: string; displayName: string; hostScoped?: boolean; onNavigate: (page: string) => void; onSecurity: () => void;onLogout?:()=>void; children: ReactNode }) {
|
||||
const [mobileNavOpen, setMobileNavOpen] = useState(false);
|
||||
useNavigationOverlay(mobileNavOpen,setMobileNavOpen);
|
||||
function navigate(pageName: string) {
|
||||
onNavigate(pageName);
|
||||
setMobileNavOpen(false);
|
||||
}
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<header className="topbar">
|
||||
<button className="mobile-menu" aria-label={mobileNavOpen ? '关闭导航' : '打开导航'} aria-expanded={mobileNavOpen} onClick={() => setMobileNavOpen((value) => !value)}><Menu size={21} /></button>
|
||||
<Brand />
|
||||
<div className="tenant-switch"><Building2 size={17} /><span>{tenantName}</span></div>
|
||||
<div className="top-actions">
|
||||
{onLogout?<button className="icon-button" aria-label="退出登录" onClick={onLogout}><LogOut size={18}/></button>:null}
|
||||
<button className="user-menu" onClick={onSecurity} aria-label="账号安全"><span className="avatar"><UserRound size={17} /></span><span>{displayName}</span><ChevronDown size={15} /></button>
|
||||
</div>
|
||||
</header>
|
||||
{mobileNavOpen ? <button className="mobile-nav-backdrop" aria-label="关闭导航" onClick={() => setMobileNavOpen(false)} /> : null}
|
||||
<div className={mobileNavOpen ? 'mobile-sidebar open' : 'mobile-sidebar'}><Sidebar page={page} hostScoped={hostScoped} onNavigate={navigate} /></div>
|
||||
<main className="main-content">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export function Brand() {
|
||||
return (
|
||||
<div className="brand" aria-label="Sea vHost">
|
||||
<svg viewBox="0 0 38 28" aria-hidden="true">
|
||||
<path d="M2 6c4-4 7-4 11 0s7 4 11 0 7-4 11 0" />
|
||||
<path d="M2 14c4-4 7-4 11 0s7 4 11 0 7-4 11 0" />
|
||||
<path d="M2 22c4-4 7-4 11 0s7 4 11 0 7-4 11 0" />
|
||||
</svg>
|
||||
<span><b>Sea</b> vHost</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import {useCallback,useEffect,useId,useRef,useState} from 'react';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
|
||||
interface ConfirmationOptions {title?:string;confirmLabel?:string;danger?:boolean;}
|
||||
interface ConfirmationRequest extends ConfirmationOptions {message:string;}
|
||||
|
||||
export function useConfirmation(){
|
||||
const [request,setRequest]=useState<ConfirmationRequest>();
|
||||
const resolve=useRef<((answer:boolean)=>void)|null>(null);
|
||||
const titleId=useId();
|
||||
const confirm=useCallback((message:string,options:ConfirmationOptions={})=>{
|
||||
if(resolve.current)return Promise.resolve(false);
|
||||
return new Promise<boolean>(finish=>{resolve.current=finish;setRequest({message,...options})});
|
||||
},[]);
|
||||
const settle=useCallback((answer:boolean)=>{const finish=resolve.current;resolve.current=null;setRequest(undefined);finish?.(answer)},[]);
|
||||
useEffect(()=>()=>{resolve.current?.(false);resolve.current=null},[]);
|
||||
const confirmation=request?<ModalBackdrop><section className="confirmation-modal" role="alertdialog" aria-labelledby={titleId}><h2 id={titleId}>{request.title||'确认操作'}</h2><p>{request.message}</p><div className="form-actions"><button type="button" className="secondary" onClick={()=>settle(false)}>取消</button><button type="button" className={request.danger?'primary danger-confirm':'primary'} onClick={()=>settle(true)}>{request.confirmLabel||'确认继续'}</button></div></section></ModalBackdrop>:null;
|
||||
return {confirm,confirmation};
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { ArrowLeft, Box, Database, HardDrive, Network, ShieldCheck } from 'lucide-react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { formatBytes } from '../format';
|
||||
import { normalizeRunPath } from '../runPath';
|
||||
import type { Plan, ProjectDraft, Runtime, RuntimeCatalog } from '../types';
|
||||
|
||||
const runtimes: Runtime[] = ['PHP', 'Node.js', 'Python', 'Go', 'Java'];
|
||||
|
||||
interface CreateProjectProps {
|
||||
runtimeVersions: RuntimeCatalog;
|
||||
rootDomain: string;
|
||||
projectRoot: string;
|
||||
plan: Plan;
|
||||
domainApproval: boolean;
|
||||
onCancel: () => void;
|
||||
onSubmit: (draft: ProjectDraft) => void;
|
||||
}
|
||||
|
||||
export function CreateProject({ runtimeVersions, rootDomain, projectRoot, plan, domainApproval, onCancel, onSubmit }: CreateProjectProps) {
|
||||
const initialRuntime = runtimes.find((runtime) => runtimeVersions[runtime]?.length) ?? 'PHP';
|
||||
const [draft, setDraft] = useState<ProjectDraft>({ name: 'blog-demo', runtime: initialRuntime, version: runtimeVersions[initialRuntime]?.[0] ?? '', runPath: '/', customDomain: '', autoSSL: true });
|
||||
const safeName = useMemo(() => draft.name.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, ''), [draft.name]);
|
||||
const assignedDomain = `<随机主机名>.${rootDomain}`;
|
||||
const root = `${projectRoot.replace(/\/+$/, '')}/<随机主机名>`;
|
||||
const normalizedRunPath = normalizeRunPath(draft.runPath);
|
||||
const publishedRoot = normalizedRunPath === '/' ? root : `${root}${normalizedRunPath}`;
|
||||
|
||||
function selectRuntime(runtime: Runtime) {
|
||||
setDraft((current) => ({ ...current, runtime, version: runtimeVersions[runtime]?.[0] ?? '' }));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page create-page">
|
||||
<button className="back-link" onClick={onCancel}><ArrowLeft size={17} /> 返回</button>
|
||||
<div className="page-heading"><h1>创建虚拟主机</h1></div>
|
||||
<form className="create-layout" onSubmit={(event) => { event.preventDefault(); if (safeName && draft.version && normalizedRunPath) onSubmit({ ...draft, name: safeName, runPath: normalizedRunPath }); }}>
|
||||
<div className="form-main">
|
||||
<section className="form-section"><h2>1. 基本信息</h2><label><span>主机备注 <i>*</i></span><input required minLength={3} maxLength={50} pattern="[A-Za-z0-9\-]+" value={draft.name} onChange={(event) => setDraft({ ...draft, name: event.target.value })} /><small>用于控制台识别,支持英文字母、数字和连字符,长度 3–50 个字符。</small></label></section>
|
||||
<section className="form-section"><h2>2. 运行环境</h2><div className="field-row"><span className="field-label">运行环境 <i>*</i></span><div className="runtime-options">{runtimes.map((runtime) => <button type="button" disabled={!runtimeVersions[runtime]?.length} className={draft.runtime === runtime ? 'runtime-option selected' : 'runtime-option'} onClick={() => selectRuntime(runtime)} key={runtime}><b>{runtime === 'Node.js' ? 'N' : runtime.slice(0, 2)}</b><span>{runtime}</span></button>)}</div></div><label><span>版本 <i>*</i></span><select required value={draft.version} onChange={(event) => setDraft({ ...draft, version: event.target.value })}>{(runtimeVersions[draft.runtime] ?? []).map((version) => <option key={version}>{version}</option>)}</select><small>仅显示当前宝塔服务器已安装的版本。</small></label><label><span>运行目录 <i>*</i></span><input required value={draft.runPath} onChange={(event) => setDraft({ ...draft, runPath: event.target.value })} placeholder="/、/public 或 /dist" /><small>{normalizedRunPath ? `Nginx 将发布主机根目录下的 ${normalizedRunPath};FTP 与文件管理仍可访问完整主机目录。` : '请输入 / 或由字母、数字、点、下划线、连字符组成的相对目录。'}</small></label></section>
|
||||
<section className="form-section"><h2>3. 域名设置</h2><label><span>三级域名 <i>*</i></span><input readOnly value={assignedDomain} /><small>创建时生成不可预测的主机名,并自动分配三级域名。</small></label><label><span>自定义域名</span><input placeholder="例如 blog.example.com" value={draft.customDomain} onChange={(event) => setDraft({ ...draft, customDomain: event.target.value })} /><small>{domainApproval ? '当前策略要求管理员审核,审核前不影响三级域名访问。' : '当前策略无需管理员审核,创建后自动绑定。'}</small></label><div className="info-note">{domainApproval ? '自定义域名提交后进入审核队列。' : '请先将域名解析到服务器,系统会在创建时绑定。'}</div></section>
|
||||
<section className="form-section"><h2>4. 上传网站文件</h2><div className="deploy-options"><div><span><b>Web 文件管理</b><small>适合上传和编辑少量文件,单文件上限为 20 MB。</small></span></div><div><span><b>FTP</b><small>使用系统自动分配的主机账号传输较大或较多文件。</small></span></div></div></section>
|
||||
</div>
|
||||
<aside className="resource-summary">
|
||||
<h2>资源与配置信息</h2>
|
||||
<div className="quota-line"><HardDrive size={18} /><span>存储空间</span><b>{formatBytes(plan.storageBytes)}</b></div><div className="quota-line"><Database size={18} /><span>数据库空间</span><b>{formatBytes(plan.databaseBytes)}</b></div><div className="quota-line"><Network size={18} /><span>月流量</span><b>{formatBytes(plan.bandwidthBytes)}</b></div><div className="quota-line"><Box size={18} /><span>进程数量</span><b>{plan.processLimit}</b></div>
|
||||
<h3>自动分配的资源</h3>
|
||||
{[['主机根目录', root], ['对外发布目录', publishedRoot], ['FTP 账号', '与随机主机名一致'], ['MySQL 数据库', '与随机主机名一致']].map(([label, value]) => <label className="summary-field" key={label}><span>{label}</span><input readOnly value={value} /></label>)}
|
||||
<label className="toggle-row"><button type="button" role="switch" aria-checked={draft.autoSSL} className={draft.autoSSL ? 'toggle on' : 'toggle'} onClick={() => setDraft({ ...draft, autoSSL: !draft.autoSSL })}><i /></button><span><b>自动申请并部署 SSL 证书</b><small>使用 Let’s Encrypt 自动签发和续期。</small></span></label>
|
||||
<div className="isolation-note"><ShieldCheck size={22} /><p><b>权限与隔离说明</b><span>账号仅管理已授权主机与资源;系统配置、面板密钥和其他主机目录不会通过控制台开放。</span></p></div>
|
||||
<div className="form-actions"><button type="button" className="secondary" onClick={onCancel}>取消</button><button type="submit" className="primary" disabled={!draft.version || !normalizedRunPath}>创建虚拟主机</button></div>
|
||||
</aside>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import { Copy, KeyRound, RotateCcw, X } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import type { Credentials } from '../api';
|
||||
|
||||
interface CredentialsModalProps {
|
||||
credentials: Credentials;
|
||||
onClose: () => void;
|
||||
onReset?: () => Promise<void>;
|
||||
}
|
||||
|
||||
const ftpTLSPolicyLabels: Record<string, string> = {
|
||||
unknown: '连接方式尚待节点核验',
|
||||
explicit_tls_required: '显式 FTPS(必须加密)',
|
||||
plain_allowed_no_certificate: '普通 FTP(尚未检测到有效证书)',
|
||||
};
|
||||
|
||||
export function CredentialsModal({ credentials, onClose, onReset }: CredentialsModalProps) {
|
||||
const {confirm,confirmation}=useConfirmation();
|
||||
const [resetting, setResetting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const values: Array<[string, string]> = [
|
||||
['主机登录名', credentials.hostLogin],
|
||||
...(credentials.hostPassword ? [['主机登录密码', credentials.hostPassword] as [string, string]] : []),
|
||||
['FTP 服务地址', credentials.ftpHost],
|
||||
['FTP 加密策略', ftpTLSPolicyLabels[credentials.ftpTLSPolicy] ?? credentials.ftpTLSPolicy],
|
||||
['FTP 账号', credentials.ftpUsername],
|
||||
['FTP 密码', credentials.ftpPassword],
|
||||
['数据库', credentials.databaseName],
|
||||
['数据库用户', credentials.databaseUsername],
|
||||
['数据库密码', credentials.databasePassword],
|
||||
];
|
||||
|
||||
async function resetPassword() {
|
||||
if (!onReset || !await confirm('确定重置主机登录密码?已登录的主机会话将立即失效。',{title:'重置主机密码',danger:true})) return;
|
||||
setResetting(true);
|
||||
setError('');
|
||||
try {
|
||||
await onReset();
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : '重置主机密码失败');
|
||||
} finally {
|
||||
setResetting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ModalBackdrop className="modal-backdrop" role="presentation">
|
||||
<section className="credentials-modal" role="dialog" aria-modal="true" aria-labelledby="credentials-title">
|
||||
{confirmation}<button className="modal-close" onClick={onClose} aria-label="关闭"><X size={18} /></button>
|
||||
<KeyRound size={26} className="modal-icon" />
|
||||
<h2 id="credentials-title">虚拟主机凭据</h2>
|
||||
|
||||
{error ? <p className="form-error" role="alert">{error}</p> : null}
|
||||
<div className="credential-list">
|
||||
{values.map(([label, value]) => <div key={label}><span>{label}</span><code>{value}</code><button onClick={() => navigator.clipboard?.writeText(value)} aria-label={`复制${label}`}><Copy size={15} /></button></div>)}
|
||||
</div>
|
||||
<div className="credential-actions">
|
||||
{onReset ? <button className="secondary" disabled={resetting} onClick={() => void resetPassword()}><RotateCcw size={15} />{resetting ? '重置中…' : '重置主机密码'}</button> : null}
|
||||
<button className="primary" onClick={onClose}>关闭</button>
|
||||
</div>
|
||||
</section>
|
||||
</ModalBackdrop>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import { Cloud, KeyRound, Pencil, Plus, TestTube2, Trash2, X } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api, type DNSCredential, type DNSCredentialInput, type DNSProvider,type DNSZoneChoice } from '../api';
|
||||
|
||||
const providerLabels: Record<DNSProvider, string> = { cloudflare: 'Cloudflare', aliyun: '阿里云 DNS', tencent: '腾讯云 DNSPod',west:'西部数码',dnsmgr:'彩虹聚合 DNS' };
|
||||
|
||||
export function DNSCredentials({ admin = false, live = true }: { admin?: boolean; live?: boolean }) {
|
||||
const {confirm,confirmation}=useConfirmation();
|
||||
const [items, setItems] = useState<DNSCredential[]>([]);
|
||||
const [editing, setEditing] = useState<DNSCredential | null>();
|
||||
const [busy, setBusy] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function reload() {
|
||||
if (!live) { setItems([]); setBusy(false); setError(''); return; }
|
||||
setBusy(true);
|
||||
try { setItems((await api.dnsCredentials(admin)).credentials); setError(''); }
|
||||
catch (reason) { setError(message(reason, '无法读取 DNS 凭据')); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
useEffect(() => { void reload(); }, [admin, live]);
|
||||
|
||||
async function remove(item: DNSCredential) {
|
||||
if (!await confirm(`确定删除“${item.label}”?已安装证书仍然有效,但后续自动续期可能失败。`,{title:'删除 DNS 凭据',danger:true})) return;
|
||||
setBusy(true);
|
||||
try { await api.deleteDNSCredential(item.id, admin); setItems((current) => current.filter(({ id }) => id !== item.id)); }
|
||||
catch (reason) { setError(message(reason, '删除 DNS 凭据失败')); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
async function test(item: DNSCredential) {
|
||||
setBusy(true); setError('');
|
||||
setItems((current) => current.map((candidate) => candidate.id === item.id ? { ...candidate, testStatus: 'testing', testError: undefined } : candidate));
|
||||
try {
|
||||
const tested = live
|
||||
? (await api.testDNSCredential(item.id, admin)).credential
|
||||
: { ...item, testStatus: 'passed' as const, lastTestedAt: new Date().toISOString(), testError: undefined };
|
||||
setItems((current) => current.map((candidate) => candidate.id === item.id ? tested : candidate));
|
||||
}
|
||||
catch (reason) { setError(message(reason, 'DNS 凭据测试失败')); if (live) await reload(); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
return <section className={admin ? 'admin-table dns-credential-panel' : 'resource-page dns-credential-page'}>
|
||||
{confirmation}<div className={admin?"dns-credential-heading":"dns-credential-heading page-heading unified-heading"}>
|
||||
<div><span className="resource-action-icon"><Cloud size={20} /></span><span>{admin?<h2>平台根域 DNS API</h2>:<h1>DNS API</h1>}</span></div>
|
||||
<button className="primary" onClick={() => setEditing(null)}><Plus size={15} />新增凭据</button>
|
||||
</div>
|
||||
{error ? <p className="resource-error" role="alert">{error}</p> : null}
|
||||
<div className="dns-credential-list">
|
||||
<div className="dns-credential-row head"><span>名称</span><span>服务商</span><span>DNS 区域</span><span>更新时间</span><span>操作</span></div>
|
||||
{items.map((item) => <div className="dns-credential-row" key={item.id}>
|
||||
<span><b>{item.label}</b><small>{admin ? '平台凭据' : '用户凭据'} · 密钥已加密</small><CredentialTestStatus item={item} /></span>
|
||||
<span>{providerLabels[item.provider]}</span><code>{item.zoneName}</code>
|
||||
<span>{new Date(item.updatedAt).toLocaleString('zh-CN', { hour12: false })}</span>
|
||||
<span className="site-actions dns-actions"><button aria-label={`测试 ${item.label}`} title="创建并删除随机 TXT 记录" disabled={busy} onClick={() => void test(item)}><TestTube2 size={14} /><span>测试权限</span></button><button aria-label={`替换 ${item.label}`} title="替换凭据" disabled={busy} onClick={() => setEditing(item)}><Pencil size={14} /><span>替换凭据</span></button><button className="danger" aria-label={`删除 ${item.label}`} disabled={busy} onClick={() => void remove(item)}><Trash2 size={14} /><span>删除</span></button></span>
|
||||
</div>)}
|
||||
{!busy && items.length === 0 ? <div className="resource-empty">尚未配置 DNS API 凭据</div> : null}
|
||||
{busy && items.length === 0 ? <div className="resource-empty">正在读取凭据…</div> : null}
|
||||
</div>
|
||||
{editing !== undefined ? <CredentialForm admin={admin} live={live} current={editing} onClose={() => setEditing(undefined)} onSaved={(item) => { setItems((current) => editing ? current.map((candidate) => candidate.id === item.id ? item : candidate) : [...current, item]); setEditing(undefined); }} /> : null}
|
||||
</section>;
|
||||
}
|
||||
|
||||
function CredentialForm({ admin, live, current, onClose, onSaved }: { admin: boolean; live: boolean; current: DNSCredential | null; onClose: () => void; onSaved: (item: DNSCredential) => void }) {
|
||||
const [provider,setProvider]=useState<DNSProvider>(current?.provider??'cloudflare'),[label,setLabel]=useState(current?.label??''),[credential,setCredential]=useState<DNSCredentialInput['credential']>({}),[single,setSingle]=useState(false),[hint,setHint]=useState(''),[zones,setZones]=useState<DNSZoneChoice[]>([]),[selected,setSelected]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
function invalidate(){setZones([]);setSelected('');setError('')}
|
||||
function field(key:keyof DNSCredentialInput['credential'],title:string,secret=false,required=true){return <label>{title}<input type={secret?'password':'text'} autoComplete={secret?'new-password':'off'} value={credential[key]||''} required={required} maxLength={512} onChange={e=>{invalidate();setCredential(c=>({...c,[key]:e.target.value}))}}/></label>}
|
||||
const zone=zones.find(z=>z.id===selected);
|
||||
const input=():DNSCredentialInput=>({label,provider,zoneName:hint,credential});
|
||||
async function discover(){setBusy(true);setError('');invalidate();try{if(!live)throw new Error('请在已连接服务器的环境中读取域名');const r=await api.discoverDNSZones(input(),admin);setZones(r.zones);setSelected(r.zones[0]?.id||'');if(!r.zones.length)setError('票据下没有可管理的域名,请检查域名读取权限')}catch(e){setError(message(e,'读取域名列表失败'))}finally{setBusy(false)}}
|
||||
return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal dns-credential-modal" autoComplete="off" onSubmit={async event=>{event.preventDefault();if(!zone){await discover();return}setBusy(true);setError('');try{
|
||||
const payload:DNSCredentialInput={...input(),zoneName:zone.name,credential:{...credential,...(['cloudflare','dnsmgr'].includes(provider)?{zoneId:zone.id}:{})},verificationToken:zone.verificationToken};
|
||||
const item=current?(await api.updateDNSCredential(current.id,payload,admin)).credential:(await api.createDNSCredential(payload,admin)).credential;onSaved(item)
|
||||
}catch(e){setError(message(e,'保存 DNS 凭据失败'));setBusy(false)}}}>
|
||||
<button type="button" className="modal-close" onClick={onClose} aria-label="关闭"><X size={18}/></button><KeyRound size={25} className="modal-icon"/><h2>{current?'替换 DNS 凭据':'新增 DNS 凭据'}</h2>
|
||||
<fieldset disabled={busy}><label>凭据名称<input value={label} onChange={e=>setLabel(e.target.value)} required minLength={2} maxLength={80}/></label>
|
||||
<label>DNS 服务商<select value={provider} onChange={e=>{invalidate();setProvider(e.target.value as DNSProvider);setCredential({});setHint('');setSingle(false)}}>{Object.entries(providerLabels).map(([value,text])=><option key={value} value={value}>{text}</option>)}</select></label>
|
||||
{provider==='cloudflare'?field('apiToken','API Token',true):null}
|
||||
{provider==='aliyun'?<>{field('accessKeyId','AccessKey ID')}{field('accessKeySecret','AccessKey Secret',true)}</>:null}
|
||||
{provider==='tencent'?<>{field('secretId','SecretId')}{field('secretKey','SecretKey',true)}</>:null}
|
||||
{provider==='west'?<><label>票据类型<select value={single?'domain':'account'} onChange={e=>{invalidate();setSingle(e.target.value==='domain');setCredential({})}}><option value="account">域名业务 API 账号</option><option value="domain">单域名解析密钥</option></select></label>{single?<>{field('domainKey','域名 ApiKey',true)}<label>指定域名<input required value={hint} onChange={e=>{invalidate();setHint(e.target.value)}} placeholder="example.com"/></label></>:<>{field('username','API 用户名')}{field('apiKey','域名业务 API 密码',true)}</>}</>:null}
|
||||
{provider==='dnsmgr'?<>{field('endpoint','彩虹 DNS 站点地址')}<small>填写 HTTPS 公网站点根地址,例如 https://dns.example.com</small>{field('userId','数字用户 ID(UID)')}{field('apiKey','API 密钥',true)}</>:null}
|
||||
<button className="secondary" type="button" disabled={busy} onClick={e=>{const form=e.currentTarget.form;if(form?.reportValidity())void discover()}}>{busy?'正在连接…':'读取可管理域名'}</button>
|
||||
{zones.length?<label>选择 DNS 域名<select value={selected} onChange={e=>setSelected(e.target.value)}>{zones.map(z=><option key={z.id} value={z.id}>{z.name}</option>)}</select></label>:null}
|
||||
</fieldset>{error?<p className="form-error" role="alert">{error}</p>:null}
|
||||
<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy||!zone}>{busy?'处理中…':'加密保存'}</button></div>
|
||||
</form></ModalBackdrop>;
|
||||
}
|
||||
|
||||
function message(reason: unknown, fallback: string) { return reason instanceof Error ? reason.message : fallback; }
|
||||
|
||||
function CredentialTestStatus({ item }: { item: DNSCredential }) {
|
||||
const labels = { untested: '未测试', testing: '正在测试', passed: '测试通过', failed: '测试失败' } as const;
|
||||
const detail = item.testError || (item.lastTestedAt ? new Date(item.lastTestedAt).toLocaleString('zh-CN', { hour12: false }) : '将创建并立即删除一条随机 TXT 记录');
|
||||
return <span className={`dns-test-status ${item.testStatus}`} title={detail}>{labels[item.testStatus]}{item.lastTestedAt ? ` · ${new Date(item.lastTestedAt).toLocaleString('zh-CN', { hour12: false })}` : ''}</span>;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import { AlertTriangle, Check, Download, LoaderCircle, PackageCheck, RefreshCw, TerminalSquare } from 'lucide-react';
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import {PageHeader} from './UI';
|
||||
import { api, type RuntimeEnvironment } from '../api';
|
||||
import { RuntimeMaintenancePanel } from './RuntimeMaintenancePanel';
|
||||
|
||||
|
||||
function safeError(error: unknown) {
|
||||
return error instanceof Error ? error.message : '操作失败,请稍后重试';
|
||||
}
|
||||
|
||||
export function EnvironmentConfiguration({nodeId,nodeSelector,hideHeading=false,onLoadingChange}:{nodeId?:number;nodeSelector?:ReactNode;hideHeading?:boolean;onLoadingChange?:(value:boolean)=>void}) {
|
||||
const {confirm,confirmation}=useConfirmation();
|
||||
const [items, setItems] = useState<RuntimeEnvironment[]>([]);
|
||||
const [selected, setSelected] = useState<Record<string, string>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [notice, setNotice] = useState('');
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const response = await api.runtimeEnvironments(nodeId);
|
||||
setItems(response.environments);
|
||||
setSelected((current) => {
|
||||
const next = { ...current };
|
||||
for (const item of response.environments) {
|
||||
const options = item.available.filter((version) => !item.installed.includes(version) && !item.installing.includes(version));
|
||||
if (!options.includes(next[item.name])) next[item.name] = item.recommended && options.includes(item.recommended) ? item.recommended : (options[0] || '');
|
||||
}
|
||||
return next;
|
||||
});
|
||||
} catch (loadError) {
|
||||
setError(safeError(loadError));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [nodeId]);
|
||||
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
useEffect(()=>{onLoadingChange?.(loading)},[loading,onLoadingChange]);
|
||||
|
||||
const totals = useMemo(() => ({
|
||||
installed: items.reduce((sum, item) => sum + item.installed.length, 0),
|
||||
ready: items.filter((item) => item.componentStatus === 'installed').length,
|
||||
}), [items]);
|
||||
|
||||
const installComponent = async (item: RuntimeEnvironment) => {
|
||||
const action = item.componentUpdateAvailable ? '更新' : '安装';
|
||||
if (!await confirm(`${action}${item.componentTitle}${item.componentLatestVersion ? ` ${item.componentLatestVersion}` : ''}?安装包将由宝塔官方源下载。`)) return;
|
||||
setBusy(`${item.name}:component`); setError(''); setNotice('');
|
||||
try {
|
||||
await api.installRuntimeComponent(item.name,nodeId);
|
||||
setNotice(`组件${action}任务已提交,请稍后刷新状态。`);
|
||||
await load();
|
||||
} catch (installError) { setError(safeError(installError)); }
|
||||
finally { setBusy(''); }
|
||||
};
|
||||
|
||||
const installVersion = async (item: RuntimeEnvironment) => {
|
||||
const version = selected[item.name];
|
||||
const sourceNotice = item.name === 'Python' ? 'Python 将从镜像下载源码、使用官方摘要校验并编译,可能需要较长时间。' : '';
|
||||
if (!version || !await confirm(`安装 ${item.name} ${version}?现有项目和已安装版本不会被删除。${sourceNotice}`)) return;
|
||||
setBusy(`${item.name}:${version}`); setError(''); setNotice('');
|
||||
try {
|
||||
await api.installRuntimeEnvironment(item.name, version,nodeId);
|
||||
setNotice(`${item.name} ${version} 安装任务已提交。`);
|
||||
await load();
|
||||
} catch (installError) { setError(safeError(installError)); }
|
||||
finally { setBusy(''); }
|
||||
};
|
||||
|
||||
return <section className="admin-page environment-page">{confirmation}
|
||||
{!hideHeading?<PageHeader title="环境配置" description="查看并安装虚拟主机项目所需的语言运行环境。" actions={<>{nodeSelector}<button className="secondary" onClick={() => void load()} disabled={loading || !!busy}><RefreshCw size={16} className={loading ? 'spin' : ''} />刷新状态</button></>}/>:null}
|
||||
<div className="environment-summary">
|
||||
<span><PackageCheck size={19} /><b>{totals.ready} / {items.length || 5}</b><small>组件可用</small></span>
|
||||
<span><TerminalSquare size={19} /><b>{totals.installed}</b><small>已安装版本</small></span>
|
||||
</div>
|
||||
{error ? <div className="environment-message error"><AlertTriangle size={17} />{error}</div> : null}
|
||||
{notice ? <div className="environment-message success"><Check size={17} />{notice}</div> : null}
|
||||
{loading && !items.length ? <div className="environment-loading"><LoaderCircle className="spin" size={22} />正在读取宝塔环境清单…</div> : null}
|
||||
<div className="environment-grid">{items.map((item) => {
|
||||
const options = item.available.filter((version) => !item.installed.includes(version) && !item.installing.includes(version));
|
||||
const componentBusy = busy === `${item.name}:component`;
|
||||
const versionBusy = busy === `${item.name}:${selected[item.name]}`;
|
||||
return <article className="environment-card" key={item.name}>
|
||||
<header><span className="runtime-mark">{item.name === 'Node.js' ? 'JS' : item.name.slice(0, 2).toUpperCase()}</span><div><h2>{item.name}</h2></div><i className={`component-state ${item.componentStatus}`}>{item.componentStatus === 'installed' ? '组件可用' : item.componentStatus === 'not_installed' ? '未安装组件' : '检测异常'}</i></header>
|
||||
{item.detail ? <p className="environment-detail">{item.detail}</p> : null}
|
||||
{item.componentVersion || item.componentLatestVersion ? <div className="component-version-line"><span>组件版本</span><b>{item.componentVersion || '尚未安装'}</b>{item.componentLatestVersion ? <small>最新 {item.componentLatestVersion}</small> : null}</div> : null}
|
||||
<div className="environment-versions"><label>已安装</label><div>{item.installed.map((version) => <span key={version}><Check size={13} />{version}</span>)}{!item.installed.length ? <em>暂无版本</em> : null}</div></div>
|
||||
{item.installing.length ? <div className="environment-versions installing"><label>安装中</label><div>{item.installing.map((version) => <span key={version}><LoaderCircle className="spin" size={13} />{version}</span>)}</div></div> : null}
|
||||
<footer>{item.componentInstallable && (item.componentStatus === 'not_installed' || item.componentUpdateAvailable) ? <button className="primary" onClick={() => void installComponent(item)} disabled={!!busy}>{componentBusy ? <LoaderCircle className="spin" size={16} /> : <Download size={16} />}{componentBusy ? '正在提交…' : item.componentUpdateAvailable ? '更新管理组件' : '安装免费组件'}</button> : null}
|
||||
{item.componentStatus === 'installed' && item.name !== 'PHP' ? <><select aria-label={`${item.name} 待安装版本`} value={selected[item.name] || ''} onChange={(event) => setSelected({ ...selected, [item.name]: event.target.value })} disabled={!options.length || !!busy}><option value="">{options.length ? '选择待安装版本' : '无可安装的新版本'}</option>{options.map((version) => <option key={version} value={version}>{version}{version === item.recommended ? '(推荐)' : ''}</option>)}</select><button className="primary" onClick={() => void installVersion(item)} title={busy?'正在处理环境安装':!selected[item.name]?(options.length?'请先选择待安装版本':'当前没有可安装的新版本'):undefined} disabled={!selected[item.name] || !!busy}>{versionBusy ? <LoaderCircle className="spin" size={16} /> : <Download size={16} />}{versionBusy ? '安装中…' : '安装版本'}</button></> : null}
|
||||
{item.name === 'PHP' ? <small>如需新增 PHP 版本,请先在宝塔软件商店安装。</small> : null}
|
||||
</footer>
|
||||
</article>;
|
||||
})}</div>
|
||||
<RuntimeMaintenancePanel nodeId={nodeId} environments={items} onChanged={load} />
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import { ArrowLeft, Download, Edit3, File, Folder, Plus, RefreshCw, Trash2, Upload, X } from 'lucide-react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api, type FileEntry,type TrashEntry } from '../api';
|
||||
import { formatBytes } from '../format';
|
||||
import type { Project } from '../types';
|
||||
|
||||
export function FileManager({ projects, initialProjectID, live = true }: { projects: Project[]; initialProjectID?: number; live?: boolean }) {
|
||||
const {confirm,confirmation}=useConfirmation();
|
||||
const [projectID, setProjectID] = useState(initialProjectID ?? projects[0]?.id ?? 0);
|
||||
const [path, setPath] = useState('');
|
||||
const previousInitialProject = useRef(initialProjectID);
|
||||
const [entries, setEntries] = useState<FileEntry[]>([]);
|
||||
const [uploadLimit, setUploadLimit] = useState(20 * 1024 ** 2);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const requestVersion = useRef(0);
|
||||
const contextKey = `${projectID}:${path}`;
|
||||
const currentContext = useRef(contextKey);
|
||||
currentContext.current = contextKey;
|
||||
const [loadedContext, setLoadedContext] = useState('');
|
||||
const [editor, setEditor] = useState<{ path: string; content: string; isNew: boolean } | null>(null);
|
||||
const [operation,setOperation]=useState<{action:string;path:string;to:string}|null>(null),[trashEntries,setTrashEntries]=useState<TrashEntry[]|null>(null);
|
||||
const trashRequest=useRef(0);
|
||||
function closeTrash(){trashRequest.current++;setTrashEntries(null)}
|
||||
async function showTrash(){const trashVersion=++trashRequest.current;const version=requestVersion.current;setBusy(true);setError('');try{const result=live?(await api.fileTrash(projectID)).entries:[];if(version===requestVersion.current&&trashVersion===trashRequest.current)setTrashEntries(result)}catch(e){if(version===requestVersion.current)setError(message(e,'读取回收站失败'))}finally{if(version===requestVersion.current)setBusy(false)}}
|
||||
async function perform(){if(!operation||busy)return;const target=operation.action==='mkdir'?operation.path:operation.to;if(entries.some(entry=>entry.path===target)){setError(operation.action==='move'&&operation.path===target?'源路径与目标路径不能相同':'目标已存在,请更换目标路径;原文件不会被覆盖');return}setBusy(true);setError('');try{if(live)await api.fileAction(projectID,operation.action,operation.path,operation.to);setOperation(null);if(trashEntries)await showTrash();await load()}catch(e){setError(message(e,'文件操作失败'))}finally{setBusy(false)}}
|
||||
const uploadRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialProjectID && initialProjectID !== previousInitialProject.current && projects.some((project) => project.id === initialProjectID)) {
|
||||
previousInitialProject.current = initialProjectID;
|
||||
setProjectID(initialProjectID);
|
||||
setPath('');
|
||||
}
|
||||
}, [initialProjectID, projects]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const context = `${projectID}:${path}`;
|
||||
if (!projectID || currentContext.current !== context) return;
|
||||
const version = ++requestVersion.current;
|
||||
const current = () => version === requestVersion.current && currentContext.current === context;
|
||||
setBusy(true); setError('');
|
||||
setEntries([]);
|
||||
if (!live) {
|
||||
setEntries(demoEntries(path));
|
||||
setLoadedContext(context);
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await api.files(projectID, path);
|
||||
if (!current()) return;
|
||||
setLoadedContext(context);
|
||||
setEntries([...result.entries].sort((left, right) => Number(right.directory) - Number(left.directory) || left.name.localeCompare(right.name, 'zh-CN')));
|
||||
setUploadLimit(result.uploadLimit);
|
||||
} catch (reason) { if (current()) { setLoadedContext(context); setError(message(reason, '无法读取主机文件')); } }
|
||||
finally { if (current()) setBusy(false); }
|
||||
}, [live, path, projectID]);
|
||||
|
||||
useEffect(() => { trashRequest.current++;setTrashEntries(null); setEditor(null); setOperation(null); void load(); return () => { requestVersion.current++;trashRequest.current++; }; }, [load]);
|
||||
|
||||
async function upload(file: File) {
|
||||
if (file.size > uploadLimit) { setError(`单文件不能超过 ${formatBytes(uploadLimit)}`); return; }
|
||||
if (!live) { setError('预览模式不会写入文件'); return; }
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
await api.uploadFile(projectID, path, file);
|
||||
await load();
|
||||
} catch (reason) {
|
||||
if ((reason as { status?: number })?.status === 409 && await confirm('同名文件已存在,是否覆盖?',{title:'覆盖文件',confirmLabel:'覆盖文件',danger:true})) {
|
||||
try { await api.uploadFile(projectID, path, file, true); await load(); }
|
||||
catch (retryReason) { setError(message(retryReason, '上传失败')); }
|
||||
} else setError(message(reason, '上传失败'));
|
||||
} finally { setBusy(false); if (uploadRef.current) uploadRef.current.value = ''; }
|
||||
}
|
||||
|
||||
async function edit(entry: FileEntry) {
|
||||
if (!live) { setEditor({ path: entry.path, content: `# ${entry.name}\n\n这是本地界面预览内容。`, isNew: false }); return; }
|
||||
const version = requestVersion.current;
|
||||
setBusy(true); setError('');
|
||||
try { const content = await api.fileText(projectID, entry.path); if (version === requestVersion.current) setEditor({ path: entry.path, content, isNew: false }); }
|
||||
catch (reason) { if (version === requestVersion.current) setError(message(reason, '无法读取文本文件')); }
|
||||
finally { if (version === requestVersion.current) setBusy(false); }
|
||||
}
|
||||
|
||||
async function trash(entry: FileEntry) {
|
||||
if (!await confirm(`将“${entry.name}”移入主机回收站?可在回收站恢复。`,{title:'移入回收站',confirmLabel:'移入回收站',danger:true})) return;
|
||||
if (!live) { setEntries((current) => current.filter((item) => item.path !== entry.path)); return; }
|
||||
setBusy(true); setError('');
|
||||
try { await api.trashFile(projectID, entry.path); await load(); }
|
||||
catch (reason) { setError(message(reason, '删除失败')); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
async function emptyTrash() {
|
||||
if (!await confirm('确定永久清空当前主机的回收站?此操作不可恢复。',{title:'永久清空回收站',confirmLabel:'永久清空',danger:true})) return;
|
||||
if (!live) { setError('预览模式不会删除文件'); return; }
|
||||
setBusy(true); setError('');
|
||||
try { await api.emptyTrash(projectID); if (trashEntries) setTrashEntries([]); await load(); }
|
||||
catch (reason) { setError(message(reason, '清空回收站失败')); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
if (projects.length === 0) return <div className="page"><div className="page-heading"><h1>文件管理</h1></div><div className="empty-state"><Folder size={32} /><h2>暂无主机</h2><p>由管理员分配主机后,即可在这里管理文件。</p></div></div>;
|
||||
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
const loading = busy || loadedContext !== contextKey;
|
||||
const visibleEntries = loadedContext === contextKey && !busy ? entries : [];
|
||||
return <div className="page file-page">{confirmation}
|
||||
<div className="page-heading"><h1>文件管理</h1></div>
|
||||
<section className="file-panel">
|
||||
<div className="file-toolbar"><select aria-label="选择虚拟主机" value={projectID} onChange={(event) => { setProjectID(Number(event.target.value)); setPath(''); setError(''); }} disabled={loading}>{projects.map((project) => <option key={project.id} value={project.id}>{project.name} · {project.domain}</option>)}</select><div className="file-actions"><button className="secondary" disabled={loading} onClick={()=>setOperation({action:"mkdir",path:joinPath(path,"new-directory"),to:""})}>新建目录</button><button className="secondary" disabled={loading} onClick={()=>void showTrash()}>回收站</button><button className="secondary" disabled={loading} onClick={() => {setError('');setEditor({ path: joinPath(path, 'new-file.txt'), content: '', isNew: true })}}><Plus size={15} />新建文本</button><button className="secondary" onClick={() => uploadRef.current?.click()} disabled={loading}><Upload size={15} />上传文件</button><button className="secondary" onClick={() => void emptyTrash()} disabled={loading}><Trash2 size={15} />清空回收站</button><input ref={uploadRef} type="file" hidden onChange={(event) => { const file = event.target.files?.[0]; if (file) void upload(file); }} /><button className="icon-button" onClick={() => void load()} disabled={loading} aria-label="刷新文件"><RefreshCw size={16} /></button></div></div>
|
||||
<div className="file-breadcrumb"><button disabled={loading} onClick={() => setPath('')}>根目录</button>{segments.map((segment, index) => <span key={`${segment}-${index}`}>/ <button disabled={loading} onClick={() => setPath(segments.slice(0, index + 1).join('/'))}>{segment}</button></span>)}</div>
|
||||
{error && !editor && !operation ? <p className="file-error" role="alert">{error}</p> : null}
|
||||
<div className="file-table" aria-busy={loading}><div className="file-row file-head"><span>名称</span><span>大小</span><span>修改时间</span><span>操作</span></div>{path ? <button disabled={loading} className="file-row file-parent" onClick={() => setPath(parentPath(path))}><span><ArrowLeft size={17} />返回上级</span><span>—</span><span>—</span><span /></button> : null}{visibleEntries.map((entry) => <div className="file-row" key={entry.path}>{entry.directory||isTextFile(entry)&&entry.size<=1024**2?<button className="file-name" onClick={()=>entry.directory?setPath(entry.path):void edit(entry)}>{entry.directory?<Folder size={18}/>:<File size={18}/>}<span>{entry.name}</span></button>:<span className="file-name" title={isTextFile(entry)?'超过 1 MB,请下载后编辑并重新上传':'此类型不支持在线编辑,请下载或使用 FTP 处理'}><File size={18}/><span>{entry.name}</span></span>}<span>{entry.directory ? '—' : formatBytes(entry.size)}</span><span>{formatDate(entry.modified)}</span><span className="file-row-actions">{!entry.directory && isTextFile(entry) && entry.size <= 1024 ** 2 ? <button onClick={() => void edit(entry)} aria-label={`编辑 ${entry.name}`}><Edit3 size={15} /></button> : null}{!entry.directory ? <a href={api.fileDownloadURL(projectID, entry.path)} aria-label={`下载 ${entry.name}`}><Download size={15} /></a> : null}<select aria-label={'更多操作 '+entry.name} value="" disabled={loading} onChange={e=>{const action=e.target.value;if(action)setOperation({action,path:entry.path,to:operationTarget(action,entry)})}}><option value="">更多</option><option value="move">重命名 / 移动</option><option value="copy">复制</option><option value="zip">压缩为 ZIP</option>{entry.name.toLowerCase().endsWith('.zip')?<option value="extract">解压 ZIP</option>:null}</select><button onClick={() => void trash(entry)} aria-label={`删除 ${entry.name}`}><Trash2 size={15} /></button></span></div>)}{!loading && !error && entries.length === 0 ? <div className="file-empty">目录为空</div> : null}{loading ? <div className="file-empty" role="status">正在读取…</div> : null}</div>
|
||||
</section>
|
||||
{trashEntries?<section className="file-panel"><h2>主机回收站</h2><button className="secondary" onClick={closeTrash}>关闭回收站</button>{!trashEntries.length?<p>回收站为空</p>:trashEntries.map(entry=><div className="file-row" key={entry.id}><span>{entry.originalPath}</span><span>{formatBytes(entry.size)}</span><span>{formatDate(entry.deletedAt)}</span><button onClick={()=>setOperation({action:'restore',path:entry.id,to:entry.originalPath})}>恢复 {entry.name}</button></div>)}</section>:null}
|
||||
{operation?<ModalBackdrop className="modal-backdrop"><form className="file-editor" onSubmit={e=>{e.preventDefault();void perform()}}><h2>{{mkdir:'新建目录',move:'重命名 / 移动',copy:'复制',zip:'压缩 ZIP',extract:'解压 ZIP',restore:'恢复文件'}[operation.action]}</h2><p>路径均相对于当前主机根目录。目标必须不存在;复制、压缩和解压最多处理 256 MiB,并受套餐剩余空间限制。</p>{operation.action!=='restore'?<label>{operation.action==='mkdir'?'目录路径':'源路径'}<input disabled={busy} value={operation.path} readOnly={operation.action!=='mkdir'} required onChange={e=>setOperation({...operation,path:e.target.value})}/></label>:null}{operation.action!=='mkdir'?<label>目标路径<input disabled={busy} value={operation.to} required onChange={e=>setOperation({...operation,to:e.target.value})}/></label>:null}{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={()=>{setOperation(null);setError('')}}>取消</button><button className="primary" disabled={loading}>{busy?'正在处理…':'执行操作'}</button></div></form></ModalBackdrop>:null}
|
||||
{editor ? <ModalBackdrop className="modal-backdrop"><form className="file-editor" onSubmit={async (event) => { event.preventDefault(); if(busy)return; setBusy(true); setError(''); if (!live) { setEditor(null); setBusy(false); return; } try { await api.writeFile(projectID, editor.path, editor.content, !editor.isNew); setEditor(null); await load(); } catch (reason) { setError(message(reason, '保存失败')); } finally { setBusy(false); } }}><button type="button" className="modal-close" disabled={busy} onClick={() => {setEditor(null);setError('')}} aria-label="关闭编辑器"><X size={17} /></button><h2>{editor.isNew ? '新建文本文件' : '编辑文本文件'}</h2><label>主机内路径<input disabled={busy} required value={editor.path} readOnly={!editor.isNew} onChange={(event) => setEditor({ ...editor, path: event.target.value })} /></label><label>内容<textarea disabled={busy} spellCheck={false} value={editor.content} onChange={(event) => setEditor({ ...editor, content: event.target.value })} /></label>{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" className="secondary" disabled={busy} onClick={() => {setEditor(null);setError('')}}>取消</button><button className="primary" disabled={loading}>{busy ? '保存中…' : '保存'}</button></div></form></ModalBackdrop> : null}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function operationTarget(action:string,entry:FileEntry){
|
||||
if(action==='move')return entry.path;
|
||||
if(action==='zip')return entry.path+'.zip';
|
||||
if(action==='extract')return entry.path.replace(/\.zip$/i,'')+'-extracted';
|
||||
const extension=entry.directory?-1:entry.name.lastIndexOf('.');
|
||||
return extension>0?entry.path.slice(0,-(entry.name.length-extension))+'-copy'+entry.name.slice(extension):entry.path+'-copy';
|
||||
}
|
||||
function joinPath(base: string, name: string) { return base ? `${base}/${name}` : name; }
|
||||
function parentPath(value: string) { const parts = value.split('/'); parts.pop(); return parts.join('/'); }
|
||||
function isTextFile(entry: FileEntry) { return /\.(?:txt|md|json|ya?ml|toml|ini|conf|env|html?|css|js|jsx|ts|tsx|php|py|go|java|xml|sql|sh)$/i.test(entry.name); }
|
||||
function formatDate(value: string) { const date = new Date(value); return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false }); }
|
||||
function message(reason: unknown, fallback: string) { return reason instanceof Error ? reason.message : fallback; }
|
||||
function demoEntries(path: string): FileEntry[] {
|
||||
const modified = '2026-10-07T10:30:00+08:00';
|
||||
if (path === 'assets') return [{ name: 'app.css', path: 'assets/app.css', directory: false, size: 4280, modified }];
|
||||
if (path) return [];
|
||||
return [{ name: 'assets', path: 'assets', directory: true, size: 0, modified }, { name: 'index.php', path: 'index.php', directory: false, size: 1260, modified }, { name: 'README.md', path: 'README.md', directory: false, size: 860, modified }];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Cpu, Database, FolderOpen, HardDrive, KeyRound, Network, RefreshCw, Server } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api, type Dashboard } from '../api';
|
||||
import { formatBytes, usagePercent } from '../format';
|
||||
import type { Plan, Project, Usage } from '../types';
|
||||
import { MetricCard } from './MetricCard';
|
||||
|
||||
interface Props {
|
||||
onRefresh?:()=>void|Promise<void>;refreshing?:boolean;
|
||||
onToggle?:(id:number)=>void;pendingProjectIDs?:number[];
|
||||
hostScoped?:boolean;projects: Project[]; plan: Plan; usage: Usage; live: boolean;
|
||||
onRunPath: (project: Project) => void; onSites: (project: Project) => void;
|
||||
onCredentials: (project: Project) => void; onFiles: (id: number) => void;
|
||||
}
|
||||
|
||||
export function HostDetails({onRefresh,refreshing=false,onToggle,pendingProjectIDs=[],hostScoped=false, projects, plan, usage, live, onRunPath, onSites, onCredentials, onFiles }: Props) {
|
||||
const [selectedID, setSelectedID] = useState(projects[0]?.id ?? 0);
|
||||
const project = projects.find(item => item.id === selectedID) ?? projects[0];
|
||||
const projectID = project?.id;
|
||||
const [snapshot, setSnapshot] = useState<Dashboard>();
|
||||
const [error, setError] = useState('');
|
||||
const [refresh, setRefresh] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!live || !projectID) return;
|
||||
let active = true;
|
||||
setSnapshot(undefined); setError('');
|
||||
api.dashboard(projectID).then(result => { if (active) setSnapshot(result); })
|
||||
.catch(reason => { if (active) setError(reason instanceof Error ? reason.message : '无法读取主机资源'); });
|
||||
return () => { active = false; };
|
||||
}, [live, projectID, refresh]);
|
||||
if (!project) return <div className="page"><div className="page-heading"><h1>虚拟主机</h1></div></div>;
|
||||
const scopedSnapshot = snapshot?.projects.some(item => item.id === projectID) ? snapshot : undefined;
|
||||
const currentPlan = live ? scopedSnapshot?.plan : plan;
|
||||
const currentUsage = live ? scopedSnapshot?.usage : usage;
|
||||
return <div className="page host-details-page">
|
||||
<div className="page-heading"><h1>虚拟主机</h1></div>
|
||||
<section className="host-info-card">
|
||||
<header><div><Server size={21}/><h2>{project.hostName}</h2><span className={`status ${project.status}`}>{({running:'运行中',stopped:'已停止',awaiting_upload:'待上传',quota_suspended:'配额暂停',provisioning:'创建中',failed:'异常'})[project.status]}</span></div><button className="secondary" disabled={refreshing} onClick={async () => {try{await onRefresh?.();setRefresh(value=>value+1)}catch(e){setError(e instanceof Error?e.message:'状态刷新失败')}}}><RefreshCw size={15}/>刷新状态</button></header>
|
||||
{projects.length > 1 ? <label className="host-picker">选择虚拟主机<select value={project.id} onChange={event => setSelectedID(Number(event.target.value))}>{projects.map(item => <option key={item.id} value={item.id}>{item.hostName} · {item.name}</option>)}</select></label> : null}
|
||||
<dl className="host-properties"><div><dt>主机本月流量</dt><dd>{formatBytes(project.trafficGB*1024**3)}</dd></div><div><dt>主机名称</dt><dd>{project.name}</dd></div><div><dt>默认域名</dt><dd><a href={`${project.ssl ? 'https' : 'http'}://${project.domain}/`} target="_blank" rel="noreferrer">{project.domain}</a></dd></div><div><dt>主机根目录</dt><dd><code>{project.path}</code></dd></div><div><dt>主站运行目录</dt><dd><code>{project.runPath}</code></dd></div><div><dt>主站运行环境</dt><dd>{project.runtime} {project.version}</dd></div><div><dt>主站证书</dt><dd>{project.ssl ? '已部署' : '未启用'}</dd></div></dl>
|
||||
<div className="host-actions">{onToggle?<button className="secondary" disabled={pendingProjectIDs.includes(project.id)||!['running','stopped'].includes(project.status)} onClick={()=>onToggle(project.id)}>{pendingProjectIDs.includes(project.id)?'处理中…':project.status==='running'?'停止主站':'启动主站'}</button>:null}<button className="primary" onClick={() => onSites(project)}>网站管理</button><button className="secondary" onClick={() => onRunPath(project)}>设置运行目录</button><button className="secondary" onClick={() => onFiles(project.id)}><FolderOpen size={15}/>文件管理</button><button className="secondary" onClick={() => onCredentials(project)}><KeyRound size={15}/>访问凭据</button></div>
|
||||
</section>
|
||||
<div className="host-resource-heading"><h2>资源配置</h2></div>
|
||||
{error ? <p role="alert" className="resource-error">{error}</p> : currentPlan && currentUsage ? <>
|
||||
<div className="metrics-grid"><MetricCard icon={HardDrive} label="存储空间" value={formatBytes(currentUsage.storageBytes)} limit={formatBytes(currentPlan.storageBytes)} percent={usagePercent(currentUsage.storageBytes,currentPlan.storageBytes)}/><MetricCard icon={Database} label="数据库大小" value={formatBytes(currentUsage.databaseBytes)} limit={formatBytes(currentPlan.databaseBytes)} percent={usagePercent(currentUsage.databaseBytes,currentPlan.databaseBytes)}/><MetricCard icon={Network} label="本月流量" value={formatBytes(currentUsage.bandwidthBytes)} limit={formatBytes(currentPlan.bandwidthBytes)} percent={usagePercent(currentUsage.bandwidthBytes,currentPlan.bandwidthBytes)}/><MetricCard icon={Cpu} label="进程数量" value={String(currentUsage.processCount)} limit={String(currentPlan.processLimit)} percent={usagePercent(currentUsage.processCount,currentPlan.processLimit)}/></div>
|
||||
<section className="host-info-card"><h2>套餐与限制</h2><dl className="host-properties"><div><dt>资源套餐</dt><dd>{currentPlan.name}</dd></div><div><dt>带宽限速</dt><dd>{currentPlan.bandwidthMbps ? `${currentPlan.bandwidthMbps} Mbps` : '不限速'}<small>HTTP 每连接,FTP 每账号</small></dd></div><div><dt>网站数量上限</dt><dd>{currentPlan.projectLimit} 个</dd></div><div><dt>FTP 账号上限</dt><dd>{currentPlan.ftpLimit} 个</dd></div><div><dt>数据库数量上限</dt><dd>{currentPlan.databaseLimit} 个</dd></div><div><dt>用量更新时间</dt><dd>{currentUsage.measuredAt ? new Date(currentUsage.measuredAt).toLocaleString('zh-CN',{hour12:false}) : '等待统计'}</dd></div></dl></section>
|
||||
</> : <p role="status" className="resource-empty">正在读取主机资源…</p>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {useEffect,useState} from 'react';
|
||||
import {api,type AdminProject,type ControlNode,type Credentials,type PanelSite,type Tenant} from '../api';
|
||||
import type {Plan,RuntimeCatalog,Runtime} from '../types';
|
||||
import {CredentialsModal} from './CredentialsModal';
|
||||
|
||||
export function HostProvisioning({users,plans,adopt=false,onClose,onComplete}:{users:Tenant[];plans:Plan[];adopt?:boolean;onClose:()=>void;onComplete:()=>Promise<void>}){
|
||||
const [nodes,setNodes]=useState<ControlNode[]>([]);const [nodeId,setNodeId]=useState(0);const [versions,setVersions]=useState<RuntimeCatalog>({PHP:[],"Node.js":[],Python:[],Go:[],Java:[]});const [sites,setSites]=useState<PanelSite[]>([]);const [siteId,setSiteId]=useState(0);const [runtime,setRuntime]=useState<Runtime>('PHP');const [version,setVersion]=useState('');const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [credentials,setCredentials]=useState<Credentials>();
|
||||
useEffect(()=>{let active=true;api.nodes().then(r=>{if(active){setNodes(r.nodes);setNodeId(r.nodes.find(n=>n.enabled)?.id||0)}}).catch(e=>{if(active)setError(e.message)});return()=>{active=false}},[]);
|
||||
useEffect(()=>{let active=true;setVersions({PHP:[],"Node.js":[],Python:[],Go:[],Java:[]});setSites([]);setSiteId(0);setVersion('');if(!nodeId)return;setBusy(true);setError('');api.panelSites(nodeId).then(r=>{if(active){const catalog=Object.fromEntries((["PHP","Node.js","Python","Go","Java"] as Runtime[]).map(name=>[name,Array.isArray(r.versions?.[name])?r.versions[name]:[]])) as RuntimeCatalog;setVersions(catalog);setSites(Array.isArray(r.sites)?r.sites:[]);setRuntime('PHP');setVersion(catalog.PHP?.[0]||'')}}).catch(e=>{if(active)setError(e.message)}).finally(()=>{if(active)setBusy(false)});return()=>{active=false}},[nodeId]);
|
||||
const node=nodes.find(n=>n.id===nodeId);
|
||||
if(credentials)return <CredentialsModal credentials={credentials} onClose={()=>{void onComplete()}}/>;
|
||||
return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal adoption-modal" onSubmit={async e=>{e.preventDefault();const form=new FormData(e.currentTarget);setBusy(true);setError('');try{const data={tenantId:Number(form.get('tenantId')),planId:Number(form.get('planId')),name:String(form.get('name')),runtime,version,runPath:String(form.get('runPath')||'/'),autoSSL:form.get('autoSSL')==='on'};const result=adopt?await api.adoptPanelSite(siteId,data,nodeId):await api.createHost({...data,nodeId,expiresAt:form.get('expiresAt')?new Date(String(form.get('expiresAt'))).toISOString():null});setCredentials(result.credentials)}catch(e){setError(e instanceof Error?e.message:'开通失败')}finally{setBusy(false)}}}>
|
||||
<h2>{adopt?'迁移宝塔站点':'开通虚拟主机'}</h2><p>每台主机独立套餐与到期时间,所属用户可切换管理多台主机。</p>
|
||||
<label>所属节点<select aria-label="所属节点" value={nodeId} required onChange={e=>setNodeId(Number(e.target.value))}><option value="0" disabled>请选择节点</option>{nodes.filter(n=>n.enabled).map(n=><option key={n.id} value={n.id}>{n.name} · {n.rootDomain}</option>)}</select></label>
|
||||
<div className="plan-form-grid"><label>{adopt?'分配用户':'绑定用户(可选)'}<select name="tenantId" required={adopt}><option value={adopt?'':'0'}>{adopt?'请选择':'不绑定用户,独立主机账号登录'}</option>{users.filter(u=>u.status==='active').map(u=><option key={u.id} value={u.id}>{u.name}</option>)}</select></label><label>主机套餐<select name="planId" required><option value="">请选择</option>{plans.map(p=><option key={p.id} value={p.id}>{p.name}</option>)}</select></label></div>
|
||||
{adopt?<label>待迁移站点<select value={siteId||''} required onChange={e=>setSiteId(Number(e.target.value))}><option value="">请选择</option>{sites.map(s=><option key={s.id} value={s.id}>{s.domain} · {s.path}</option>)}</select><small>原目录复制至主机根目录,接管成功前保留原文件。</small></label>:null}
|
||||
<label>主机名称<input name="name" minLength={3} maxLength={50} pattern="[a-z0-9](?:[a-z0-9]|-){1,48}[a-z0-9]" required/></label>
|
||||
<div className="plan-form-grid"><label>运行环境<select value={runtime} onChange={e=>{setRuntime(e.target.value as Runtime);setVersion(versions[e.target.value as Runtime]?.[0]||'')}}>{Object.keys(versions).map(v=><option key={v}>{v}</option>)}</select></label><label>版本<select value={version} required onChange={e=>setVersion(e.target.value)}>{(versions[runtime]||[]).map(v=><option key={v}>{v}</option>)}</select></label></div>
|
||||
<label>运行目录<input name="runPath" defaultValue="/" required/><small>目录位于 {node?.tenantRoot}/随机主机名,默认域名为 随机主机名.{node?.rootDomain}</small></label>
|
||||
{!adopt?<label>到期时间<input name="expiresAt" type="datetime-local"/><small>留空表示长期使用;到期停用,宽限 3 天,回收保留 7 天,备份保留 14 天。</small></label>:null}
|
||||
<label className="check-row"><input type="checkbox" name="autoSSL" defaultChecked/><span>自动申请并续期 SSL</span></label>
|
||||
{!busy&&adopt&&nodeId>0&&!sites.length?<p className="form-error">没有可迁移的宝塔站点</p>:null}{error?<p role="alert" className="form-error">{error}</p>:null}<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy||!nodeId||!version||(adopt&&!siteId)}>{busy?'正在处理…':adopt?'复制并接管':'开通主机'}</button></div>
|
||||
</form></ModalBackdrop>
|
||||
}
|
||||
|
||||
export function HostSubscription({project,plans,onClose,onSaved}:{project:AdminProject;plans:Plan[];onClose:()=>void;onSaved:()=>Promise<void>}){
|
||||
const [busy,setBusy]=useState(false);const [error,setError]=useState('');const expires=project.expiresAt?new Date(project.expiresAt):null;const local=expires?new Date(expires.getTime()-expires.getTimezoneOffset()*60000).toISOString().slice(0,16):'';
|
||||
return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal" onSubmit={async e=>{e.preventDefault();const form=new FormData(e.currentTarget);setBusy(true);setError('');try{await api.hostSubscription(project.id,Number(form.get('planId')),form.get('expiresAt')?new Date(String(form.get('expiresAt'))).toISOString():undefined);await onSaved();onClose()}catch(e){setError(e instanceof Error?e.message:'保存失败')}finally{setBusy(false)}}}><h2>主机套餐与到期</h2><p>{project.hostName} · 节点 #{project.nodeId}</p><label>主机套餐<select required name="planId" defaultValue={project.planId}>{plans.map(p=><option key={p.id} value={p.id}>{p.name}</option>)}</select></label><label>到期时间<input name="expiresAt" type="datetime-local" defaultValue={local}/><small>留空为长期使用;续期后已停止的站点需要手动启动。</small></label>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="form-actions"><button type="button" onClick={onClose}>取消</button><button className="primary" disabled={busy}>{busy?'正在保存…':'保存'}</button></div></form></ModalBackdrop>
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
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`;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useEffect,useState } from 'react';
|
||||
import { api,type User } from '../api';
|
||||
export function ImpersonationBanner({user}:{user:User}) {
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
async function leave(){setBusy(true);try{await api.stopImpersonation();window.location.reload()}catch(reason){setError(reason instanceof Error?reason.message:'无法返回管理视图');setBusy(false)}}
|
||||
useEffect(()=>{if(!user.impersonationExpiresAt)return;const timer=window.setTimeout(()=>{void api.stopImpersonation().then(()=>window.location.reload()).catch(()=>setError('代入已到期,请点击返回管理视图'))},Math.max(0,new Date(user.impersonationExpiresAt).getTime()-Date.now()));return()=>window.clearTimeout(timer)},[user.impersonationExpiresAt]);
|
||||
return <aside className="impersonation-banner" aria-label="管理员代入状态"><div><strong>目前{user.role==='host'?'主机':'用户'} {user.loginName}</strong>{error?<p role="alert">{error}</p>:null}</div><button className="secondary" disabled={busy} onClick={()=>void leave()}>{busy?'正在返回…':'返回管理视图'}</button></aside>
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Check, CheckCircle2, ChevronLeft, ChevronRight, Database, KeyRound, Server, ShieldCheck, UserRound } from 'lucide-react';
|
||||
import { api, type DatabaseSetup, type InstallSetup, type PanelSetup } from '../api';
|
||||
import { demoRuntimeVersions } from '../data';
|
||||
import type { Runtime, RuntimeCapabilities, RuntimeCatalog } from '../types';
|
||||
import { Brand } from './Brand';
|
||||
|
||||
const steps = [
|
||||
{ label: '安装验证', icon: KeyRound },
|
||||
{ label: '数据库', icon: Database },
|
||||
{ label: '服务器', icon: Server },
|
||||
{ label: '管理员', icon: UserRound },
|
||||
];
|
||||
const runtimes: Runtime[] = ['PHP', 'Node.js', 'Python', 'Go', 'Java'];
|
||||
const runtimeStatusText = { available: '可用', not_installed: '未安装', probe_failed: '探测失败' } as const;
|
||||
const demoRuntimeCapabilities = capabilitiesFromVersions(demoRuntimeVersions);
|
||||
|
||||
export function InstallWizard({ preview = false }: { preview?: boolean }) {
|
||||
const [step, setStep] = useState(0);
|
||||
const [controllerOnly,setControllerOnly]=useState(false);
|
||||
const [token, setToken] = useState('');
|
||||
const [database, setDatabase] = useState<DatabaseSetup>({ host: '127.0.0.1', port: 3306, name: 'sea_vhost', user: 'sea_vhost', password: '' });
|
||||
const [panel, setPanel] = useState<PanelSetup>({ url: 'https://127.0.0.1:8888', apiKey: '', tlsInsecure: true });
|
||||
const [rootDomain, setRootDomain] = useState('vhost.ser888.cn');
|
||||
const [managementDomain, setManagementDomain] = useState('host.ser888.cn');
|
||||
const [ftpDomain, setFTPDomain] = useState('host.ser888.cn');
|
||||
const [domainApproval, setDomainApproval] = useState(true);
|
||||
const [admin, setAdmin] = useState({ email: '', name: '平台管理员', password: '', confirm: '' });
|
||||
const [databaseTested, setDatabaseTested] = useState(false);
|
||||
const [panelTested, setPanelTested] = useState(false);
|
||||
const [panelVersions, setPanelVersions] = useState<RuntimeCatalog | null>(null);
|
||||
const [panelCapabilities, setPanelCapabilities] = useState<RuntimeCapabilities | null>(null);
|
||||
const [busy, setBusy] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [installed, setInstalled] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!installed || preview) return;
|
||||
const timer = window.setInterval(() => {
|
||||
api.setupStatus().then(({ required }) => {
|
||||
if (!required) window.location.reload();
|
||||
}).catch(() => undefined);
|
||||
}, 1200);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [installed, preview]);
|
||||
|
||||
useEffect(()=>{if(!preview)void api.setupStatus().then(r=>{if(r.controllerOnly)setControllerOnly(true)}).catch(()=>undefined)},[preview]);
|
||||
|
||||
function goNext() {
|
||||
setError('');
|
||||
if (step === 0 && token.trim().length < 24) return setError('请输入安装脚本生成的完整一次性令牌');
|
||||
if (step === 1 && !databaseTested) return setError('请先完成数据库连接测试');
|
||||
if (step === 2 && !controllerOnly && (!panelTested || !validDomain(rootDomain) || !validDomain(managementDomain) || !validDomain(ftpDomain) || !domainsCompatible(rootDomain, managementDomain, ftpDomain))) return setError(!panelTested ? '请先完成宝塔 API 连接测试' : '控制台域名必须独立;FTP 证书来源不能覆盖用户根域');
|
||||
if(step===2&&controllerOnly&&!validDomain(managementDomain))return setError('请输入有效的控制台域名');
|
||||
setStep((current) => Math.min(3, current + 1));
|
||||
}
|
||||
|
||||
async function testDatabase() {
|
||||
setBusy('database'); setError(''); setDatabaseTested(false);
|
||||
try {
|
||||
if (!preview) await api.testDatabase(token.trim(), database);
|
||||
setDatabaseTested(true);
|
||||
} catch (reason) { setError(message(reason, '数据库连接失败')); }
|
||||
finally { setBusy(''); }
|
||||
}
|
||||
|
||||
async function testPanel() {
|
||||
setBusy('panel'); setError(''); setPanelTested(false); setPanelVersions(null); setPanelCapabilities(null);
|
||||
try {
|
||||
const result = preview ? { versions: demoRuntimeVersions, runtimes: demoRuntimeCapabilities } : await api.testPanel(token.trim(), panel);
|
||||
setPanelVersions(result.versions);
|
||||
setPanelCapabilities(result.runtimes ?? capabilitiesFromVersions(result.versions));
|
||||
setPanelTested(true);
|
||||
} catch (reason) { setError(message(reason, '宝塔 API 连接失败')); }
|
||||
finally { setBusy(''); }
|
||||
}
|
||||
|
||||
async function install() {
|
||||
setError('');
|
||||
if (!admin.email.includes('@')) return setError('请输入有效的管理员邮箱');
|
||||
if (admin.name.trim().length < 2) return setError('管理员名称至少需要 2 个字符');
|
||||
if (admin.password.length < 12) return setError('管理员密码至少需要 12 个字符');
|
||||
if (admin.password !== admin.confirm) return setError('两次输入的管理员密码不一致');
|
||||
const input: InstallSetup = {
|
||||
controllerOnly,database, panel, rootDomain: rootDomain.trim().toLowerCase(), managementDomain: managementDomain.trim().toLowerCase(), ftpDomain: ftpDomain.trim().toLowerCase(), domainApproval,
|
||||
adminEmail: admin.email.trim(), adminName: admin.name.trim(), adminPassword: admin.password,
|
||||
};
|
||||
setBusy('install');
|
||||
try {
|
||||
if (!preview) await api.install(token.trim(), input);
|
||||
setInstalled(true);
|
||||
} catch (reason) { setError(message(reason, '安装失败')); }
|
||||
finally { setBusy(''); }
|
||||
}
|
||||
|
||||
if (installed) {
|
||||
return <main className="setup-page"><section className="setup-success">
|
||||
<div className="setup-success-icon"><CheckCircle2 /></div>
|
||||
<h1>Sea vHost 已安装完成</h1>
|
||||
<p>{preview ? '这是安装成功状态的预览。' : '配置已安全保存,服务正在切换到运行模式。稍后将自动进入登录页面。'}</p>
|
||||
{!preview ? <div className="setup-restarting"><span />正在启动服务…</div> : null}
|
||||
{!preview ? <button className="secondary setup-refresh" onClick={() => window.location.reload()}>手动刷新</button> : null}
|
||||
</section></main>;
|
||||
}
|
||||
|
||||
return <main className="setup-page">
|
||||
<header className="setup-header"><Brand /><span><ShieldCheck size={16} />安全安装向导</span></header>
|
||||
<div className="setup-layout">
|
||||
<aside className="setup-steps" aria-label="安装进度">
|
||||
<div><small>SEA VHOST SETUP</small><h1>开始安装</h1><p>大约需要 3 分钟</p></div>
|
||||
<ol>{steps.map(({ label, icon: Icon }, index) => <li key={label} className={index === step ? 'active' : index < step ? 'done' : ''}>
|
||||
<i>{index < step ? <Check size={15} /> : <Icon size={16} />}</i><span><small>步骤 {index + 1}</small>{label}</span>
|
||||
</li>)}</ol>
|
||||
<p className="setup-side-note"><ShieldCheck size={16} />安装令牌、数据库密码和 API 密钥不会保存在浏览器中。</p>
|
||||
</aside>
|
||||
<section className="setup-card">
|
||||
<div className="setup-progress"><i style={{ width: `${((step + 1) / steps.length) * 100}%` }} /></div>
|
||||
{step === 0 ? <>
|
||||
<div className="setup-title"><span><KeyRound /></span><div><h2>验证安装权限</h2><p>仅服务器管理员可以执行首次安装。</p></div></div>
|
||||
<div className="setup-info"><ShieldCheck size={18} /><p><b>在哪里找到令牌?</b><span>在服务器执行安装脚本后,终端会显示一次性安装令牌。也可由 root 查看 <code>/etc/sea-vhost/sea-vhost.env</code>。</span></p></div>
|
||||
<label className="setup-field"><span>一次性安装令牌 <i>*</i></span><input type="password" autoComplete="off" value={token} onChange={(event) => { setToken(event.target.value); setDatabaseTested(false); setPanelTested(false); }} placeholder="粘贴 SEA_SETUP_TOKEN" /><small>令牌仅随本次请求发送,安装完成后所有安装写接口立即失效。</small></label>
|
||||
</> : null}
|
||||
{step === 1 ? <>
|
||||
<div className="setup-title"><span><Database /></span><div><h2>连接 MySQL</h2><p>请先在宝塔中创建一个空数据库和专用账号。</p></div></div>
|
||||
<div className="setup-grid two">
|
||||
<label className="setup-field"><span>主机</span><input value={database.host} onChange={(e) => { setDatabase({ ...database, host: e.target.value }); setDatabaseTested(false); }} /></label>
|
||||
<label className="setup-field"><span>端口</span><input type="number" value={database.port} onChange={(e) => { setDatabase({ ...database, port: Number(e.target.value) }); setDatabaseTested(false); }} /></label>
|
||||
<label className="setup-field"><span>数据库名</span><input value={database.name} onChange={(e) => { setDatabase({ ...database, name: e.target.value }); setDatabaseTested(false); }} /></label>
|
||||
<label className="setup-field"><span>用户名</span><input value={database.user} onChange={(e) => { setDatabase({ ...database, user: e.target.value }); setDatabaseTested(false); }} /></label>
|
||||
</div>
|
||||
<label className="setup-field"><span>数据库密码 <i>*</i></span><input type="password" autoComplete="new-password" value={database.password} onChange={(e) => { setDatabase({ ...database, password: e.target.value }); setDatabaseTested(false); }} /></label>
|
||||
<div className="connection-test"><button className="secondary" onClick={testDatabase} disabled={busy !== ''}>{busy === 'database' ? '正在连接…' : '测试数据库连接'}</button>{databaseTested ? <span><CheckCircle2 size={17} />连接成功</span> : <small>仅允许本机 127.0.0.1 / localhost</small>}</div>
|
||||
</> : null}
|
||||
{step === 2 ? <>
|
||||
<label className="setup-field"><span>部署模式</span><select aria-label="部署模式" value={controllerOnly?'controller':'combined'} onChange={e=>setControllerOnly(e.target.value==='controller')}><option value="combined">主控与本机托管(宝塔服务器)</option><option value="controller">独立主控(只调度远程被控)</option></select></label>{controllerOnly?<><div className="setup-title"><span><Server/></span><div><h2>独立主控</h2><p>平台数据仅保存在主控;安装后在节点管理中添加被控。</p></div></div><label className="setup-field"><span>管理控制台域名</span><input value={managementDomain} onChange={e=>setManagementDomain(e.target.value)} required/></label></>:<><div className="setup-title"><span><Server /></span><div><h2>连接宝塔与域名</h2><p>通过专用面板代理检查宝塔,并验证 root 隔离代理。</p></div></div>
|
||||
<label className="setup-field"><span>宝塔面板地址 <i>*</i></span><input value={panel.url} onChange={(e) => { setPanel({ ...panel, url: e.target.value }); setPanelTested(false); setPanelVersions(null); setPanelCapabilities(null); }} placeholder="https://127.0.0.1:8888" /></label>
|
||||
<label className="setup-field"><span>宝塔 API 密钥 <i>*</i></span><input type="password" autoComplete="new-password" value={panel.apiKey} onChange={(e) => { setPanel({ ...panel, apiKey: e.target.value }); setPanelTested(false); setPanelVersions(null); setPanelCapabilities(null); }} /></label>
|
||||
<label className="setup-check"><input type="checkbox" checked={panel.tlsInsecure} onChange={(e) => { setPanel({ ...panel, tlsInsecure: e.target.checked }); setPanelTested(false); setPanelVersions(null); setPanelCapabilities(null); }} /><span><b>允许宝塔本机自签名证书</b><small>只对回环地址生效;不会放宽外部 HTTPS 校验。</small></span></label>
|
||||
<div className="connection-test"><button className="secondary" onClick={testPanel} disabled={busy !== ''}>{busy === 'panel' ? '正在检查…' : '检查服务器组件'}</button>{panelTested ? <span><CheckCircle2 size={17} />面板代理与隔离代理均正常</span> : null}</div>
|
||||
{panelVersions && panelCapabilities ? <div className="setup-runtime-inventory" aria-label="运行环境能力">{runtimes.map((runtime) => {
|
||||
const capability = panelCapabilities[runtime];
|
||||
const versions = panelVersions[runtime] ?? [];
|
||||
return <div key={runtime} className={capability.status} title={capability.detail}><b>{runtime}</b><span>{versions.length ? versions.join('、') : runtimeStatusText[capability.status]}</span><em>{capability.policy === 'free_core' ? '基础功能' : '语言项目'}</em></div>;
|
||||
})}</div> : null}
|
||||
<hr />
|
||||
<label className="setup-field"><span>用户三级域名根域 <i>*</i></span><input value={rootDomain} onChange={(e) => setRootDomain(e.target.value)} placeholder="vhost.ser888.cn" /><small>请提前将 <code>*.{rootDomain || 'vhost.ser888.cn'}</code> 解析至本机。</small></label>
|
||||
<div className="setup-grid two">
|
||||
<label className="setup-field"><span>管理控制台域名 <i>*</i></span><input value={managementDomain} onChange={(e) => setManagementDomain(e.target.value)} placeholder="host.ser888.cn" /><small>控制台只接受此 Host 的请求。</small></label>
|
||||
<label className="setup-field"><span>FTP 证书来源域名 <i>*</i></span><input value={ftpDomain} onChange={(e) => setFTPDomain(e.target.value)} placeholder="host.ser888.cn" /><small>Pure-FTPd 复用此域名证书;客户端直接连接各虚拟主机自己的域名,可与管理域名相同。</small></label>
|
||||
</div>
|
||||
<label className="setup-check"><input type="checkbox" checked={domainApproval} onChange={(e) => setDomainApproval(e.target.checked)} /><span><b>用户自绑定域名需要管理员审核</b><small>默认开启,安装后可在管理控制台修改。</small></span></label>
|
||||
</>}</> : null}
|
||||
{step === 3 ? <>
|
||||
<div className="setup-title"><span><UserRound /></span><div><h2>创建首个管理员</h2><p>该账号拥有全部用户与系统设置权限。</p></div></div>
|
||||
<div className="setup-grid two">
|
||||
<label className="setup-field"><span>管理员名称</span><input value={admin.name} onChange={(e) => setAdmin({ ...admin, name: e.target.value })} /></label>
|
||||
<label className="setup-field"><span>管理员邮箱</span><input type="email" autoComplete="username" value={admin.email} onChange={(e) => setAdmin({ ...admin, email: e.target.value })} placeholder="admin@ser888.cn" /></label>
|
||||
<label className="setup-field"><span>密码</span><input type="password" autoComplete="new-password" value={admin.password} onChange={(e) => setAdmin({ ...admin, password: e.target.value })} /></label>
|
||||
<label className="setup-field"><span>确认密码</span><input type="password" autoComplete="new-password" value={admin.confirm} onChange={(e) => setAdmin({ ...admin, confirm: e.target.value })} /></label>
|
||||
</div>
|
||||
<div className="setup-review"><h3>安装摘要</h3><dl><div><dt>数据库</dt><dd>{database.user}@{database.host}:{database.port}/{database.name}</dd></div><div><dt>宝塔面板</dt><dd>{panel.url}</dd></div><div><dt>管理域名</dt><dd>{managementDomain}</dd></div><div><dt>FTP 证书</dt><dd>{ftpDomain}</dd></div><div><dt>FTP 连接</dt><dd>复用各虚拟主机域名</dd></div><div><dt>三级域名</dt><dd>*.{rootDomain}</dd></div><div><dt>自绑定审核</dt><dd>{domainApproval ? '需要审核' : '自动通过'}</dd></div></dl></div>
|
||||
</> : null}
|
||||
{error ? <p className="setup-error" role="alert">{error}</p> : null}
|
||||
<footer className="setup-actions">
|
||||
{step > 0 ? <button className="secondary" onClick={() => { setError(''); setStep((current) => current - 1); }} disabled={busy !== ''}><ChevronLeft size={16} />上一步</button> : <span />}
|
||||
{step < 3 ? <button className="primary" onClick={goNext}>继续<ChevronRight size={16} /></button> : <button className="primary install-button" onClick={install} disabled={busy !== ''}>{busy === 'install' ? '正在初始化…' : '确认并完成安装'}<Check size={16} /></button>}
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
</main>;
|
||||
}
|
||||
|
||||
function validDomain(value: string) {
|
||||
return /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(value.trim().replace(/\.$/, ''));
|
||||
}
|
||||
|
||||
function domainsCompatible(rootValue: string, managementValue: string, ftpValue: string) {
|
||||
const [root, management, ftp] = [rootValue, managementValue, ftpValue].map((value) => value.trim().toLowerCase().replace(/\.$/, ''));
|
||||
const overlaps = (first: string, second: string) => first === second || first.endsWith(`.${second}`) || second.endsWith(`.${first}`);
|
||||
if (overlaps(root, management) || root === ftp || root.endsWith(`.${ftp}`)) return false;
|
||||
if (!ftp.endsWith(`.${root}`)) return true;
|
||||
return !/^sv[0-9a-f]{10}$/.test(ftp.slice(0, -(root.length + 1)));
|
||||
}
|
||||
|
||||
function message(reason: unknown, fallback: string) {
|
||||
return reason instanceof Error ? reason.message : fallback;
|
||||
}
|
||||
|
||||
function capabilitiesFromVersions(versions: RuntimeCatalog): RuntimeCapabilities {
|
||||
return Object.fromEntries(runtimes.map((runtime) => [runtime, {
|
||||
status: versions[runtime]?.length ? 'available' : 'not_installed',
|
||||
versions: versions[runtime] ?? [],
|
||||
policy: runtime === 'PHP' ? 'free_core' : 'free_project',
|
||||
}])) as RuntimeCapabilities;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import {PageHeader} from './UI';
|
||||
import {useEffect,useState,type FormEvent} from 'react';
|
||||
import {api,type IntegrationKey,type IntegrationWebhook} from '../api';
|
||||
export function IntegrationAPI(){const {confirm,confirmation}=useConfirmation();const[keys,setKeys]=useState<IntegrationKey[]>([]),[hooks,setHooks]=useState<IntegrationWebhook[]>([]),[allScopes,setAllScopes]=useState<string[]>([]),[scopes,setScopes]=useState<string[]>(['hosts:read','tasks:read']),[name,setName]=useState(''),[expires,setExpires]=useState(''),[webhook,setWebhook]=useState(''),[created,setCreated]=useState<{token:string;webhookSecret:string}>(),[error,setError]=useState(''),[busy,setBusy]=useState(false);
|
||||
const refresh=()=>api.integrationKeys().then(v=>{setKeys(v.keys.filter(k=>!k.revokedAt));setHooks(v.webhooks);setAllScopes(v.scopes)});useEffect(()=>{refresh().catch(e=>setError(e.message))},[]);
|
||||
async function submit(e:FormEvent){e.preventDefault();setBusy(true);setError('');try{setCreated(await api.createIntegrationKey({name,scopes,expiresAt:new Date(expires).toISOString(),webhookURL:webhook}));setName('');await refresh()}catch(e){setError(e instanceof Error?e.message:'创建失败')}finally{setBusy(false)}}
|
||||
return <section className="admin-page">{confirmation}<PageHeader title="对接 API" description="管理财务站与外部系统的访问密钥、权限及状态回调。" actions={<a className="secondary" href="/api/integration/v1/docs" target="_blank" rel="noopener noreferrer">查看接口文档</a>}/>{error?<p role="alert" className="resource-error">{error}</p>:null}
|
||||
<form onSubmit={submit} className="settings-card form-grid"><label>密钥名称<input required value={name} onChange={e=>setName(e.target.value)}/></label><label>有效期<input type="datetime-local" required value={expires} onChange={e=>setExpires(e.target.value)}/></label><label>状态回调地址(可选)<input type="url" value={webhook} placeholder="https://" onChange={e=>setWebhook(e.target.value)}/></label><fieldset><legend>权限范围</legend>{allScopes.map(scope=><label key={scope}><input type="checkbox" checked={scopes.includes(scope)} onChange={e=>setScopes(e.target.checked?[...scopes,scope]:scopes.filter(v=>v!==scope))}/>{scopeLabel(scope)}</label>)}</fieldset><button disabled={busy||!scopes.length} className="primary">创建 API 密钥</button></form>
|
||||
{created?<section className="settings-card"><h2>请妥善保存密钥</h2><p>API 密钥</p><code className="credential-value">{created.token}</code>{created.webhookSecret?<><p>回调签名密钥</p><code className="credential-value">{created.webhookSecret}</code></>:null}<button className="secondary" onClick={()=>setCreated(undefined)}>已保存,关闭显示</button></section>:null}
|
||||
<section className="resource-table"><h2>已签发密钥</h2><div className="table-scroll"><table><thead><tr><th>名称 / 前缀</th><th>权限</th><th>有效期</th><th>状态</th><th>操作</th></tr></thead><tbody>{keys.map(k=><tr key={k.id}><td>{k.name}<small>{k.prefix}…</small></td><td>{k.scopes.map(scopeLabel).join('、')}</td><td>{new Date(k.expiresAt).toLocaleString('zh-CN')}</td><td>{k.revokedAt?'已吊销':new Date(k.expiresAt)<new Date()?'已过期':'有效'}</td><td><button title={k.revokedAt?'密钥已吊销,无需重复操作':busy?'操作处理中':'立即吊销此密钥'} disabled={busy||!!k.revokedAt} onClick={async()=>{if(!await confirm('吊销此密钥?未执行的 API 任务将停止。',{title:'吊销 API 密钥',danger:true}))return;setBusy(true);try{await api.revokeIntegrationKey(k.id);await refresh()}catch(e){setError(e instanceof Error?e.message:'吊销失败')}finally{setBusy(false)}}}>吊销</button></td></tr>)}{!keys.length?<tr><td colSpan={5} className="empty-row">暂无 API 密钥,创建后将在这里显示。</td></tr>:null}</tbody></table></div></section>
|
||||
<section className="resource-table"><h2>最近状态回调</h2><div className="table-scroll"><table><thead><tr><th>事件 / 批次</th><th>状态</th><th>尝试次数</th><th>HTTP</th><th>详情</th></tr></thead><tbody>{hooks.map(v=><tr key={v.id}><td>{v.eventId}<small>批次 #{v.batchId}</small></td><td>{({pending:'待重试',delivered:'已送达',failed:'失败'} as Record<string,string>)[v.state]||v.state}</td><td>{v.attempts}</td><td>{v.status||'—'}</td><td>{v.lastError||'—'}</td></tr>)}{!hooks.length?<tr><td colSpan={5} className="empty-row">暂无状态回调记录。</td></tr>:null}</tbody></table></div></section></section>
|
||||
}
|
||||
function scopeLabel(scope:string){return ({'users:read':'查询用户','users:write':'创建 / 启停用户','hosts:read':'查询主机','hosts:write':'创建 / 变更主机','tasks:read':'查询任务','credentials:read':'下载任务凭据'} as Record<string,string>)[scope]||scope}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { KeyRound, LockKeyhole, ShieldCheck, UserRound } from 'lucide-react';
|
||||
import {useEffect,useState} from 'react';
|
||||
import {api} from '../api';
|
||||
import {Brand} from './Brand';
|
||||
|
||||
type Policy=Awaited<ReturnType<typeof api.oidcStatus>>;
|
||||
type Pending=Awaited<ReturnType<typeof api.pendingOIDC>>;
|
||||
export function Login({onLogin}:{onLogin:(identifier:string,password:string,totpCode:string)=>Promise<void>}){
|
||||
const [identifier,setIdentifier]=useState(''),[password,setPassword]=useState(''),[totpCode,setTOTPCode]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState(''),[mfaRequired,setMFARequired]=useState(false);
|
||||
const [policy,setPolicy]=useState<Policy>(),[pending,setPending]=useState<Pending>(),[retry,setRetry]=useState(0);
|
||||
useEffect(()=>{let active=true;const complete=new URLSearchParams(window.location.search).get('oidc')==='complete';setError('');Promise.all([api.oidcStatus(),complete?api.pendingOIDC():Promise.resolve({pending:false})]).then(([status,ticket])=>{if(active){setPolicy(status);setPending(ticket);if(complete&&!ticket.pending)setError('SSO 登录请求已失效,请重新发起登录')}}).catch(()=>{if(active)setError('无法读取登录配置,请重试')});return()=>{active=false}},[retry]);
|
||||
async function begin(){setBusy(true);setError('');try{const r=await api.beginOIDC('login');window.location.assign(r.url)}catch(e){setError(message(e));setBusy(false)}}
|
||||
async function complete(action:'bind'|'create'){setBusy(true);setError('');try{await api.completeOIDC({action,identifier,password,totpCode});window.history.replaceState(null,'',window.location.pathname);window.location.reload()}catch(e){if((e as {code?:string}).code==='mfa_required')setMFARequired(true);setError(message(e));setBusy(false)}}
|
||||
const restricted=policy?.userPasswordLogin===false||policy?.adminPasswordLogin===false;
|
||||
const passwordTitle=policy?.userPasswordLogin===false?(policy.adminPasswordLogin===false?'主机账号密码登录':'管理员 / 主机密码登录'):policy?.adminPasswordLogin===false?'用户 / 主机密码登录':'登录';
|
||||
return <main className="login-page"><section className="login-panel"><Brand/><div className="login-copy"><h1>{pending?.pending?'关联 SSO 账号':'登录控制台'}</h1></div>
|
||||
{!policy?<div className="login-loading" role="status">{error||'正在读取登录方式…'}{error?<button className="secondary" onClick={()=>setRetry(v=>v+1)}>重新读取</button>:null}</div>:<>
|
||||
{pending?.pending?<div className="sso-identity"><KeyRound size={20}/><span><b>{pending.displayName||'第三方身份已验证'}</b><small>{pending.email}</small></span></div>:null}
|
||||
{policy.enabled&&!pending?.pending?<><button className="primary oidc-login" disabled={busy} onClick={()=>void begin()}><KeyRound size={17}/>SSO 账号登录</button><div className="login-divider"><span>{restricted?'其他账号登录':'或使用密码登录'}</span></div></>:null}
|
||||
<form onSubmit={async e=>{e.preventDefault();if(pending?.pending){await complete('bind');return}setBusy(true);setError('');try{await onLogin(identifier,password,totpCode)}catch(e){if((e as {code?:string}).code==='mfa_required')setMFARequired(true);setError(message(e))}finally{setBusy(false)}}}>
|
||||
<label><span>{pending?.pending?'已有用户或管理员账号':'账号或主机名'}</span><div><UserRound size={17}/><input required autoComplete="username" value={identifier} onChange={e=>{setIdentifier(e.target.value);setMFARequired(false);setTOTPCode('')}}/></div></label>
|
||||
<label><span>密码</span><div><LockKeyhole size={17}/><input type="password" required autoComplete="current-password" value={password} onChange={e=>{setPassword(e.target.value);setMFARequired(false);setTOTPCode('')}}/></div></label>
|
||||
{mfaRequired?<label><span>动态验证码或恢复码</span><div><ShieldCheck size={17}/><input autoFocus required autoComplete="one-time-code" value={totpCode} onChange={e=>setTOTPCode(e.target.value)} placeholder="6 位验证码"/></div></label>:null}
|
||||
{error?<p className="form-error" role="alert">{error}</p>:null}
|
||||
<button className={pending?.pending?'secondary':'primary'} disabled={busy}>{busy?'正在处理…':pending?.pending?'绑定已有账号并登录':mfaRequired?'验证并登录':passwordTitle}</button></form>
|
||||
{pending?.pending?<div className="sso-create-actions">{pending.allowCreate?<button className="primary" disabled={busy} onClick={()=>void complete('create')}>创建普通用户并登录</button>:null}<button className="text-button" disabled={busy} onClick={()=>void begin()}>更换 SSO 账号</button></div>:null}
|
||||
</>}</section></main>
|
||||
}
|
||||
function message(e:unknown){return e instanceof Error?e.message:'登录失败,请重试'}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
|
||||
export function MetricCard({ icon: Icon, label, value, limit, percent }: { icon: LucideIcon; label: string; value: string; limit: string; percent: number }) {
|
||||
return (
|
||||
<section className="metric-card">
|
||||
<div className="metric-head"><span className="metric-icon"><Icon size={20} /></span><span>{label}</span></div>
|
||||
<div className="metric-value"><strong>{value}</strong><span>/ {limit}</span><em>{percent}%</em></div>
|
||||
<div className="progress" aria-label={`${label}已使用 ${percent}%`}><i style={{ width: `${percent}%` }} /></div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import {Children,cloneElement,isValidElement,useEffect,useRef,type ComponentProps,type ReactElement,type ReactNode} from 'react';
|
||||
import {lockBackgroundScroll} from './overlay';
|
||||
|
||||
const openDialogs=new Set<HTMLElement>();
|
||||
const backgroundElements=new Map<HTMLElement,boolean>();
|
||||
|
||||
function updateDialogBackground(){
|
||||
for(const [element,wasInert] of backgroundElements)element.inert=wasInert;
|
||||
backgroundElements.clear();
|
||||
let branch=[...openDialogs].at(-1);
|
||||
while(branch&&branch!==document.body){
|
||||
const parent=branch.parentElement;if(!parent)break;
|
||||
for(const sibling of parent.children){
|
||||
if(sibling===branch||!(sibling instanceof HTMLElement))continue;
|
||||
backgroundElements.set(sibling,Boolean(sibling.inert));sibling.inert=true;
|
||||
}
|
||||
branch=parent;
|
||||
}
|
||||
}
|
||||
|
||||
function textContent(node:ReactNode):string{
|
||||
if(typeof node==='string'||typeof node==='number')return String(node);
|
||||
return Children.toArray(node).map(child=>typeof child==='string'||typeof child==='number'?String(child):isValidElement<{children?:ReactNode}>(child)?textContent(child.props.children):'').join('');
|
||||
}
|
||||
function heading(node:ReactNode):string{
|
||||
for(const child of Children.toArray(node)){
|
||||
if(!isValidElement<{children?:ReactNode}>(child))continue;
|
||||
if(child.type==='h2')return textContent(child.props.children);
|
||||
const title=heading(child.props.children);if(title)return title;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
function focusable(root:HTMLElement){return [...root.querySelectorAll<HTMLElement>('button,input,select,textarea,a[href],[tabindex]')].filter(e=>!e.matches(':disabled,[tabindex="-1"],[hidden],input[type="hidden"]')&&e.getClientRects().length>0)}
|
||||
|
||||
export function ModalBackdrop({children,...props}:ComponentProps<'div'>){
|
||||
const ref=useRef<HTMLDivElement>(null);
|
||||
useEffect(()=>{
|
||||
const root=ref.current;if(!root)return;
|
||||
const previous=document.activeElement instanceof HTMLElement?document.activeElement:null;
|
||||
const releaseScroll=lockBackgroundScroll();
|
||||
openDialogs.add(root);
|
||||
updateDialogBackground();
|
||||
const frame=requestAnimationFrame(()=>{if([...openDialogs].at(-1)===root)(focusable(root)[0]||root).focus({preventScroll:true})});
|
||||
function keydown(e:KeyboardEvent){
|
||||
if([...openDialogs].at(-1)!==root)return;
|
||||
if(e.key==='Escape'){const close=[...root.querySelectorAll<HTMLButtonElement>('button')].find(b=>!b.disabled&&/^(关闭|取消|返回)/.test((b.getAttribute('aria-label')||b.textContent||'').trim()));if(close){e.preventDefault();e.stopPropagation();close.click()}return}
|
||||
if(e.key!=='Tab')return;const items=focusable(root),first=items[0],last=items.at(-1);
|
||||
if(!first){e.preventDefault();root.focus();return}
|
||||
if(e.shiftKey&&(document.activeElement===first||!root.contains(document.activeElement))){e.preventDefault();last?.focus()}else if(!e.shiftKey&&(document.activeElement===last||!root.contains(document.activeElement))){e.preventDefault();first.focus()}
|
||||
}
|
||||
document.addEventListener('keydown',keydown,true);
|
||||
return()=>{cancelAnimationFrame(frame);document.removeEventListener('keydown',keydown,true);openDialogs.delete(root);updateDialogBackground();releaseScroll();if(previous?.isConnected)previous.focus({preventScroll:true})};
|
||||
},[]);
|
||||
const content=Children.map(children,child=>{
|
||||
if(!isValidElement<Record<string,unknown>>(child))return child;
|
||||
const attributes:Record<string,unknown>={role:child.props.role||'dialog','aria-modal':true};
|
||||
if(!child.props['aria-label']&&!child.props['aria-labelledby'])attributes['aria-label']=heading((child as ReactElement<{children?:ReactNode}>).props.children)||'配置';
|
||||
return cloneElement(child,attributes);
|
||||
});
|
||||
return <div {...props} className="modal-backdrop" ref={ref} role="presentation" tabIndex={-1}>{content}</div>;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {Network,Plus,RefreshCw,Search,Server} from 'lucide-react';
|
||||
import {api,type AdminOverview,type ControlNode} from '../api';
|
||||
import {PageHeader} from './UI';
|
||||
import {useConfirmation} from './Confirmation';
|
||||
export function NodeIPPool({overview,refresh}:{overview:AdminOverview;refresh:()=>Promise<void>}){
|
||||
const [nodes,setNodes]=useState<ControlNode[]>([]),[nodeId,setNodeId]=useState(0),[query,setQuery]=useState(''),[mode,setMode]=useState(''),[adding,setAdding]=useState(false),[error,setError]=useState(''),[busy,setBusy]=useState(false);const {confirm,confirmation}=useConfirmation();
|
||||
useEffect(()=>{let active=true;api.nodes().then(r=>{if(active){setNodes(r.nodes);setNodeId(r.nodes.find(n=>n.enabled)?.id||0)}}).catch(e=>{if(active)setError(e.message)});return()=>{active=false}},[]);
|
||||
const nodeIPs=overview.ipAddresses.filter(ip=>!nodeId||ip.nodeId===nodeId),list=nodeIPs.filter(ip=>(!mode||ip.allocationMode===mode)&&`${ip.address} ${ip.label}`.toLowerCase().includes(query.toLowerCase()));
|
||||
async function remove(ip:AdminOverview['ipAddresses'][number]){if(!await confirm(`删除未分配的 IP ${ip.address}?`,{title:'删除 IP 地址',danger:true}))return;setBusy(true);setError('');try{await api.deleteIPAddress(ip.id);await refresh()}catch(e){setError(e instanceof Error?e.message:'删除失败')}finally{setBusy(false)}}
|
||||
return <section className="admin-page ip-pool-page">{confirmation}<PageHeader title="IP 地址池" actions={<><button className="secondary" disabled={busy} onClick={async()=>{setBusy(true);setError('');try{await refresh()}catch(e){setError(e instanceof Error?e.message:'刷新失败')}finally{setBusy(false)}}}><RefreshCw size={15}/>刷新地址</button><button className="primary" onClick={()=>setAdding(v=>!v)}><Plus size={15}/>{adding?'收起添加':'添加 IP'}</button></>}/>
|
||||
<div className="ip-pool-summary"><article><Network size={20}/><span>地址总数<b>{nodeIPs.length}</b></span></article><article><Server size={20}/><span>共享地址<b>{nodeIPs.filter(ip=>ip.allocationMode==='shared').length}</b></span></article><article><Network size={20}/><span>可分配独立地址<b>{nodeIPs.filter(ip=>ip.allocationMode==='dedicated'&&ip.enabled&&!ip.assignedSites).length}</b></span></article></div>
|
||||
<div className="admin-toolbar"><label>所属节点<select aria-label="IP 所属节点" value={nodeId} onChange={e=>setNodeId(Number(e.target.value))}><option value="0">全部节点</option>{nodes.map(n=><option key={n.id} value={n.id}>{n.name}</option>)}</select></label><label>分配方式<select value={mode} onChange={e=>setMode(e.target.value)}><option value="">全部</option><option value="shared">共享 IP</option><option value="dedicated">独立 IP</option></select></label><label className="admin-search"><Search size={16}/><input aria-label="搜索 IP" placeholder="地址或备注" value={query} onChange={e=>setQuery(e.target.value)}/></label><span>共 {list.length} 个地址</span></div>
|
||||
{error?<p role="alert" className="form-error">{error}</p>:null}
|
||||
{adding?<section className="admin-card"><header><h2>添加 IP 地址</h2></header><form className="ip-pool-form" onSubmit={async e=>{e.preventDefault();const element=e.currentTarget,f=new FormData(element);setBusy(true);setError('');try{await api.addIPAddress({nodeId:Number(f.get('nodeId')),address:String(f.get('address')),allocationMode:String(f.get('mode')) as 'shared'|'dedicated',label:String(f.get('label'))});await refresh();element.reset();setAdding(false)}catch(e){setError(e instanceof Error?e.message:'添加失败')}finally{setBusy(false)}}}><label>所属节点<select name="nodeId" required defaultValue={nodeId||''}><option value="" disabled>请选择节点</option>{nodes.filter(n=>n.enabled).map(n=><option key={n.id} value={n.id}>{n.name}</option>)}</select></label><label>IP 地址<input name="address" placeholder="IPv4 或 IPv6 地址" required/></label><label>分配方式<select name="mode"><option value="shared">共享 IP</option><option value="dedicated">独立 IP</option></select></label><label>备注<input name="label" maxLength={120} placeholder="可选"/></label><button className="primary" disabled={busy}>添加地址</button></form></section>:null}
|
||||
<div className="admin-table-v2 table-scroll"><table><thead><tr><th>地址 / 节点</th><th>模式</th><th>备注</th><th>已分配网站</th><th>状态</th><th>操作</th></tr></thead><tbody>{list.map(ip=><tr key={ip.id}><td><code>{ip.address}</code><small>{ip.address.includes(':')?'IPv6':'IPv4'} · {nodes.find(n=>n.id===ip.nodeId)?.name||'#'+ip.nodeId}</small></td><td><span className="resource-tag">{ip.allocationMode==='shared'?'共享 IP':'独立 IP'}</span></td><td>{ip.label||'—'}</td><td>{ip.assignedSites}</td><td>{ip.enabled?'可用':'已停用'}</td><td><button className="table-link danger-text" title={ip.assignedSites>0?'地址已分配,需先解除网站关联':undefined} disabled={busy||ip.assignedSites>0} onClick={()=>void remove(ip)}>删除</button></td></tr>)}</tbody></table>{!list.length?<div className="admin-empty">暂无匹配的 IP 地址</div>:null}</div></section>
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {NodeEditor} from './ResourceEditors';
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import {PageHeader} from './UI';
|
||||
import {RefreshCw} from 'lucide-react';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {useCallback,useEffect,useState} from 'react';
|
||||
import {api,type ControlNode} from '../api';
|
||||
import {NodeTasks} from './NodeTasks';
|
||||
import {EnvironmentConfiguration} from './EnvironmentConfiguration';
|
||||
|
||||
function errorText(e:unknown){return e instanceof Error?e.message:'操作失败'}
|
||||
export function NodeEnvironment(){
|
||||
const [nodes,setNodes]=useState<ControlNode[]>([]);const [selected,setSelected]=useState(0);const [error,setError]=useState('');const [epoch,setEpoch]=useState(0),[refreshing,setRefreshing]=useState(false);
|
||||
useEffect(()=>{let active=true;api.nodes().then(r=>{if(active){setNodes(r.nodes);setSelected(r.nodes.find(n=>n.enabled)?.id||0)}}).catch(e=>{if(active)setError(errorText(e))});return()=>{active=false}},[]);
|
||||
return <section className="admin-page"><PageHeader title="环境配置" description="查看并安装虚拟主机项目所需的语言运行环境。" actions={<><label className="node-picker">所属节点<select aria-label="环境所属节点" value={selected} onChange={e=>setSelected(Number(e.target.value))}><option value="0" disabled>请选择节点</option>{nodes.filter(n=>n.enabled).map(n=><option value={n.id} key={n.id}>{n.name} · {n.rootDomain}</option>)}</select></label><button className="secondary" disabled={!selected||refreshing} onClick={()=>setEpoch(v=>v+1)}><RefreshCw size={15} className={refreshing?'spin':undefined}/>刷新状态</button></>}/>{error?<p role="alert" className="form-error">{error}</p>:null}{selected?<EnvironmentConfiguration key={selected+':'+epoch} nodeId={selected} hideHeading onLoadingChange={setRefreshing}/>:<p className="admin-empty">{error?'节点信息读取失败':'正在读取可用节点;请确保至少一个节点已启用。'}</p>}</section>
|
||||
}
|
||||
export function NodeManagement(){
|
||||
const {confirm,confirmation}=useConfirmation();
|
||||
const [editing,setEditing]=useState<ControlNode>();
|
||||
const [taskNode,setTaskNode]=useState(0);const [nodes,setNodes]=useState<ControlNode[]>([]);const [creating,setCreating]=useState(false);const [busy,setBusy]=useState('');const [error,setError]=useState('');const [notice,setNotice]=useState('');
|
||||
const load=useCallback(async()=>{const r=await api.nodes();setNodes(r.nodes)},[]);
|
||||
useEffect(()=>{void load().catch(e=>setError(errorText(e)))},[load]);
|
||||
async function perform(key:string,action:()=>Promise<unknown>,message:string){setBusy(key);setError('');setNotice('');try{await action();await load();setNotice(message)}catch(e){setError(errorText(e))}finally{setBusy('')}}
|
||||
async function pair(n:ControlNode){if(!await confirm(`为「${n.name}」生成配对文件?现有节点身份将失效,节点会停用,部署新文件并探测后再启用。`))return;await perform('pair'+n.id,async()=>{const data=await api.pairNode(n.id);const url=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));const link=document.createElement('a');link.href=url;link.download=`sea-node-${n.id}.json`;link.click();window.setTimeout(()=>URL.revokeObjectURL(url),1000)},'配对文件已下载。请在对应被控运行节点安装脚本,再进行连接探测。')}
|
||||
return <section className="admin-page">{confirmation}<div className="admin-page-heading"><div><h1>节点管理</h1></div><button className="primary" onClick={()=>setCreating(true)}>新增节点</button></div>
|
||||
{error?<p className="form-error" role="alert">{error}</p>:null}{notice?<p className="environment-message success" role="status">{notice}</p>:null}
|
||||
<section className="admin-card"><div className="table-scroll"><table><thead><tr><th>节点</th><th>连接地址</th><th>默认域名</th><th>FTP 证书来源</th><th>连接状态</th><th>操作</th></tr></thead><tbody>{nodes.map(n=><tr key={n.id}><td><b>{n.name}</b><small>#{n.id} · {n.transport==='local'?'本机':'HTTPS 被控'}</small></td><td><code>{n.endpoint}</code><small>{n.tenantRoot}</small></td><td>{n.rootDomain||'未配置'}</td><td>{n.ftpCertificateDomain||'未配置'}</td><td><span className={`status ${n.enabled?'running':'stopped'}`}>{n.enabled?'已启用':'已停用'}</span><small>{n.lastError||(n.lastSeenAt?`最近连接 ${new Date(n.lastSeenAt).toLocaleString()}`:'尚无远程探测记录')}</small></td><td><div className="row-actions"><button disabled={!!busy} aria-label={'编辑节点 '+n.name} onClick={()=>setEditing(n)}>详情 / 编辑</button>{n.transport==='https'?<><button disabled={!!busy} onClick={()=>setTaskNode(n.id)}>执行记录</button><button disabled={!!busy} onClick={()=>void pair(n)}>下载配对文件</button><button disabled={!!busy} onClick={()=>void perform('probe'+n.id,()=>api.probeNode(n.id),'双向 TLS 和节点身份验证通过')}>探测</button></>:null}<button disabled={!!busy||!n.enabled} onClick={()=>void perform("identity"+n.id,()=>api.reconcileNode(n.id),"主机身份核验完成")}>核验身份</button><button disabled={!!busy} onClick={()=>void perform('enable'+n.id,()=>api.enableNode(n.id,!n.enabled),n.enabled?'节点已停用':'节点已启用')}>{n.enabled?'停用':'启用'}</button></div></td></tr>)}</tbody></table></div>{!nodes.length?<p className="admin-empty">暂无节点</p>:null}</section>
|
||||
{editing?<NodeEditor node={editing} onClose={()=>setEditing(undefined)} onChanged={load}/>:null}
|
||||
{taskNode?<NodeTasks nodeId={taskNode} onClose={()=>setTaskNode(0)}/>:null}
|
||||
{creating?<ModalBackdrop className="modal-backdrop"><form className="tenant-modal" onSubmit={async e=>{e.preventDefault();const form=new FormData(e.currentTarget);await perform('create',async()=>{await api.createNode(Object.fromEntries(form.entries()));setCreating(false)},'节点已新增,请下载配对文件并安装被控。')}}><h2>新增被控节点</h2><label>节点名称<input name="name" required maxLength={80}/></label><label>HTTPS 执行入口<input name="endpoint" type="url" placeholder="https://node.vhost.ser888.cn:9443" required/></label><label>默认域名后缀<input name="rootDomain" placeholder="vhost.ser888.cn" required/></label><label>FTP 证书来源域名<input name="ftpCertificateDomain" placeholder="host.vhost.ser888.cn" required/></label><label>主机根目录<input name="tenantRoot" defaultValue="/www/wwwroot/seavHost/vHost" required/></label>{error?<p className="form-error">{error}</p>:null}<div className="form-actions"><button type="button" onClick={()=>setCreating(false)}>取消</button><button className="primary" disabled={!!busy}>新增节点</button></div></form></ModalBackdrop>:null}
|
||||
</section>
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {useCallback,useEffect,useState} from 'react';
|
||||
import {api,type NodeTask} from '../api';
|
||||
|
||||
export function NodeTasks({nodeId,onClose}:{nodeId:number;onClose:()=>void}){
|
||||
const [tasks,setTasks]=useState<NodeTask[]>([]);const [error,setError]=useState('');const [busy,setBusy]=useState(false);
|
||||
const load=useCallback(async()=>{try{setError('');const r=await api.nodeTasks(nodeId);setTasks(r.tasks)}catch(e){setError(e instanceof Error?e.message:'读取失败')}},[nodeId]);
|
||||
useEffect(()=>{void load()},[load]);
|
||||
async function resolve(task:NodeTask){const note=window.prompt('请先在对应被控核对资源及操作结果,填写实际核验情况(至少六个字)。解除后应再次执行主机身份核验。');if(!note)return;setBusy(true);try{await api.resolveNodeTask(nodeId,task.id,note);await load()}catch(e){setError(e instanceof Error?e.message:'操作失败')}finally{setBusy(false)}}
|
||||
return <ModalBackdrop className="modal-backdrop"><section className="tenant-modal adoption-modal"><h2>节点 #{nodeId} 执行记录</h2>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="table-scroll"><table><thead><tr><th>操作</th><th>作用范围</th><th>状态</th><th>说明</th><th>核验</th></tr></thead><tbody>{tasks.map(t=><tr key={t.id}><td>#{t.id}<small>{t.operation}</small></td><td>{t.projectId?`主机 #${t.projectId}`:"整个节点"}</td><td>{({running:'执行中',succeeded:'成功',failed:'已结束',uncertain:'待核验'} as Record<string,string>)[t.state]||t.state}</td><td>{t.detail||'—'}<small>{new Date(t.startedAt).toLocaleString()}</small></td><td>{t.state==='uncertain'?<button disabled={busy} onClick={()=>void resolve(t)}>登记核验结果</button>:null}</td></tr>)}</tbody></table></div>{!tasks.length?<p className="admin-empty">暂无远程执行记录</p>:null}<div className="form-actions"><button onClick={()=>void load()} disabled={busy}>刷新</button><button className="primary" onClick={onClose}>关闭</button></div></section></ModalBackdrop>
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import {PageHeader} from './UI';
|
||||
import { RefreshCw, Activity, ArrowRight, Cpu, Database, HardDrive, Network } from 'lucide-react';
|
||||
import { formatBytes, usagePercent } from '../format';
|
||||
import type { ActivityEntry, Plan, Project, Usage } from '../types';
|
||||
import { MetricCard } from './MetricCard';
|
||||
import { ProjectTable } from './ProjectTable';
|
||||
|
||||
const resourceLabels: Record<string, string> = { file: '文件管理', database: '数据库', project: '虚拟主机', domain: '域名', ftp: 'FTP', session:'会话', site:'网站', startup:'启动设置', website_settings:'网站设置', schedule:'计划任务', run_path:'运行目录', host_password:'主机密码', account_password:'账号密码', account_mfa:'双重认证', deployment:'部署', manual_certificate:'手动证书', automatic_certificate:'自动证书', certificate:'证书', dns_certificate:'DNS 证书', dns_credential:'DNS 凭据', domain_dns:'域名解析', oidc_identity:'第三方绑定', oidc_session:'第三方会话', project_network:'主机网络', panel_site:'站点接管', host_subscription:'主机套餐' };
|
||||
|
||||
interface OverviewProps {
|
||||
onRefresh?:()=>void;refreshing?:boolean;
|
||||
pendingProjectIDs?:number[];
|
||||
projects: Project[];
|
||||
plan: Plan;
|
||||
usage: Usage;
|
||||
activities: ActivityEntry[];
|
||||
hostScoped: boolean;
|
||||
onCreate: () => void;
|
||||
onToggle: (id: number) => void;
|
||||
onFiles: (id: number) => void;
|
||||
onRunPath: (project: Project) => void;
|
||||
onSites: (project: Project) => void;
|
||||
onCredentials: (project: Project) => void;
|
||||
canCreate: boolean;
|
||||
onLogs?: () => void;
|
||||
}
|
||||
|
||||
export function Overview({ onRefresh,refreshing,pendingProjectIDs,projects, plan, usage, activities, hostScoped, onCreate, onToggle, onFiles, onRunPath, onSites, onCredentials, canCreate, onLogs }: OverviewProps) {
|
||||
const resources = [
|
||||
{ label: '存储空间', value: usage.storageBytes, limit: plan.storageBytes },
|
||||
{ label: '本月流量', value: usage.bandwidthBytes, limit: plan.bandwidthBytes },
|
||||
{ label: '进程数量', value: usage.processCount, limit: plan.processLimit, count: true },
|
||||
{ label: '数据库大小', value: usage.databaseBytes, limit: plan.databaseBytes },
|
||||
];
|
||||
return (
|
||||
<div className="page">
|
||||
<PageHeader title="总览" description={hostScoped ? '管理当前虚拟主机的网站、文件与访问凭据。' : '查看当前账号下的资源使用情况和业务概览。'} actions={onRefresh?<button className="secondary" disabled={refreshing} onClick={onRefresh}><RefreshCw size={15}/>{refreshing?'正在刷新…':'刷新状态'}</button>:null}/>
|
||||
{!hostScoped ? <div className="metrics-grid">
|
||||
<MetricCard icon={HardDrive} label="存储空间" value={formatBytes(usage.storageBytes)} limit={formatBytes(plan.storageBytes)} percent={usagePercent(usage.storageBytes, plan.storageBytes)} />
|
||||
<MetricCard icon={Network} label="本月流量" value={formatBytes(usage.bandwidthBytes)} limit={formatBytes(plan.bandwidthBytes)} percent={usagePercent(usage.bandwidthBytes, plan.bandwidthBytes)} />
|
||||
<MetricCard icon={Cpu} label="进程数量" value={String(usage.processCount)} limit={String(plan.processLimit)} percent={usagePercent(usage.processCount, plan.processLimit)} />
|
||||
<MetricCard icon={Database} label="数据库大小" value={formatBytes(usage.databaseBytes)} limit={formatBytes(plan.databaseBytes)} percent={usagePercent(usage.databaseBytes, plan.databaseBytes)} />
|
||||
</div> : null}
|
||||
<ProjectTable pendingProjectIDs={pendingProjectIDs} projects={projects} canCreate={canCreate} onCreate={onCreate} onToggle={onToggle} onFiles={onFiles} onRunPath={onRunPath} onSites={onSites} onCredentials={onCredentials} />
|
||||
{!hostScoped ? <div className="lower-grid">
|
||||
<section className="activity-panel">
|
||||
<div className="section-title"><h2>最近操作日志</h2>{onLogs?<button onClick={onLogs}>查看全部 <ArrowRight size={15} /></button>:null}</div>
|
||||
<div className="activity-list">
|
||||
{activities.map((entry) => <div className="activity-row" key={`${entry.createdAt}-${entry.action}-${entry.detail}`}><span>{formatTime(entry.createdAt)}</span><b>{resourceLabels[entry.resourceType] ?? entry.resourceType}</b><p>{entry.detail}</p><em className={entry.success ? '' : 'failed'}><i />{entry.success ? '成功' : '失败'}</em></div>)}
|
||||
{activities.length === 0 ? <div className="activity-empty">暂无操作记录</div> : null}
|
||||
</div>
|
||||
</section>
|
||||
<section className="usage-panel">
|
||||
<div className="section-title"><h2>资源使用详情</h2><Activity size={18} /></div>
|
||||
{resources.map((resource) => {
|
||||
const percent = usagePercent(resource.value, resource.limit);
|
||||
const value = resource.count ? `${resource.value} / ${resource.limit}` : `${formatBytes(resource.value)} / ${formatBytes(resource.limit)}`;
|
||||
return <div className="usage-row" key={resource.label}><span>{resource.label}</span><b>{value}</b><div className="progress"><i style={{ width: `${percent}%` }} /></div><em>{percent}%</em></div>;
|
||||
})}
|
||||
</section>
|
||||
</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatTime(value: string) {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
return new Intl.DateTimeFormat('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }).format(date).replace('/', '-');
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { LockKeyhole, Plus, Search } from 'lucide-react';
|
||||
import { useDeferredValue, useMemo, useState } from 'react';
|
||||
import type { Project } from '../types';
|
||||
import {formatBytes} from '../format';
|
||||
import {RuntimeMark} from './UI';
|
||||
const statusLabels: Record<Project['status'], string> = { running: '运行中', stopped: '已停止', provisioning: '创建中', awaiting_upload: '待上传', failed: '创建失败', quota_suspended: '配额暂停' };
|
||||
|
||||
export function ProjectTable({pendingProjectIDs=[], projects, canCreate, onCreate, onToggle, onFiles, onRunPath, onSites, onCredentials }: {pendingProjectIDs?:number[]; projects: Project[]; canCreate: boolean; onCreate: () => void; onToggle: (id: number) => void; onFiles: (id: number) => void; onRunPath: (project: Project) => void; onSites: (project: Project) => void; onCredentials: (project: Project) => void }) {
|
||||
const [query, setQuery] = useState('');
|
||||
const deferredQuery = useDeferredValue(query);
|
||||
const filtered = useMemo(() => {
|
||||
const value = deferredQuery.trim().toLowerCase();
|
||||
return value ? projects.filter((project) => `${project.domain} ${project.hostName} ${project.name}`.toLowerCase().includes(value)) : projects;
|
||||
}, [deferredQuery, projects]);
|
||||
|
||||
return (
|
||||
<section className="table-panel">
|
||||
<div className="panel-toolbar">
|
||||
<h2>虚拟主机 <span>共 {projects.length} 个</span></h2>
|
||||
<div className="toolbar-actions">
|
||||
<label className="search"><Search size={17} /><input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="搜索域名、主机名或备注" /></label>
|
||||
{canCreate ? <button className="primary" onClick={onCreate}><Plus size={16}/>创建虚拟主机</button> : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th>#</th><th>域名(主机名 / 目录)</th><th>运行环境</th><th>状态</th><th>SSL 证书</th><th>本月流量</th><th>创建时间</th><th>操作</th></tr></thead>
|
||||
<tbody>
|
||||
{filtered.map((project, index) => (
|
||||
<tr key={project.id}>
|
||||
<td className="muted">{index + 1}</td>
|
||||
<td><b>{project.domain}</b><small>{project.name} · {project.hostName} · {project.path} · 发布 {project.runPath}</small></td>
|
||||
<td><RuntimeMark runtime={project.runtime}/>{project.runtime} {project.version}</td>
|
||||
<td><span className={`status ${project.status}`}>{statusLabels[project.status]}</span></td>
|
||||
<td className={project.ssl ? 'success' : 'muted'}><LockKeyhole size={14} /> {project.ssl ? '已部署' : '未部署'}</td>
|
||||
<td>{formatBytes(project.trafficGB*1024**3)}</td>
|
||||
<td className="muted">{project.createdAt}</td>
|
||||
<td className="row-actions"><button title={pendingProjectIDs.includes(project.id)?'正在应用主站状态':!['running','stopped'].includes(project.status)?'主站尚未完成部署或已受配额限制':undefined} disabled={pendingProjectIDs.includes(project.id)||!['running', 'stopped'].includes(project.status)} onClick={() => onToggle(project.id)}>{pendingProjectIDs.includes(project.id)?'处理中…':project.status === 'running' ? '停止' : '启动'}</button><button onClick={() => onSites(project)}>网站</button><button onClick={() => onFiles(project.id)}>文件</button><button onClick={() => onCredentials(project)}>凭据</button><button disabled={['failed', 'provisioning'].includes(project.status)} onClick={() => onRunPath(project)}>主站目录</button></td>
|
||||
</tr>
|
||||
))}
|
||||
{filtered.length === 0 ? <tr><td colSpan={8} className="empty-row">没有匹配的虚拟主机</td></tr> : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import {UnbindDomainDialog} from './UnbindDomainDialog';
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import { Eye, FolderKey, Globe2, Plus, RefreshCw } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState, type Dispatch, type FormEvent, type ReactNode, type SetStateAction } from 'react';
|
||||
import { api, type DatabaseResource, type DomainResource, type FTPResource, type ResourceInventory } from '../api';
|
||||
import { formatBytes } from '../format';
|
||||
import type { ActivityEntry, Project, Site } from '../types';
|
||||
|
||||
interface ResourceCenterProps {
|
||||
page: string;
|
||||
projects: Project[];
|
||||
activities: ActivityEntry[];
|
||||
hostScoped: boolean;
|
||||
domainApproval: boolean;
|
||||
live: boolean;
|
||||
onCredentials: (projectID: number) => void;
|
||||
onNotify: (message: string) => void;
|
||||
}
|
||||
|
||||
export function ResourceCenter({ page, projects, activities, hostScoped, domainApproval, live, onCredentials, onNotify }: ResourceCenterProps) {
|
||||
const demoInventory = useMemo(() => inventoryFromProjects(projects), [projects]);
|
||||
const [inventory, setInventory] = useState<ResourceInventory>(()=>live?{sites:[],domains:[],ftpAccounts:[],databases:[]}:demoInventory);
|
||||
const [busy, setBusy] = useState(live);
|
||||
const [error, setError] = useState('');const [epoch,setEpoch]=useState(0);const reload=()=>setEpoch(v=>v+1);
|
||||
|
||||
useEffect(() => {
|
||||
if (page === 'logs') return;
|
||||
if (!live) {
|
||||
setInventory(demoInventory);
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
api.resources()
|
||||
.then((result) => { if (active) setInventory(result); })
|
||||
.catch((reason) => { if (active) setError(reason instanceof Error ? reason.message : '无法读取资源'); })
|
||||
.finally(() => { if (active) setBusy(false); });
|
||||
return () => { active = false; };
|
||||
}, [demoInventory, live, page,epoch]);
|
||||
|
||||
if (page === 'domains') return <DomainPage onRefresh={reload} inventory={inventory} setInventory={setInventory} approval={domainApproval} live={live} busy={busy} error={error} onNotify={onNotify} />;
|
||||
if (page === 'databases') return <DatabasePage onRefresh={reload} items={inventory.databases} busy={busy} error={error} onCredentials={onCredentials} />;
|
||||
if (page === 'ftp') return <FTPPage pausedProjectIDs={projects.filter(p=>p.status==='quota_suspended').map(p=>p.id)} onRefresh={reload} items={inventory.ftpAccounts} busy={busy} error={error} onCredentials={onCredentials} live={live} onNotify={onNotify} onChanged={async()=>setInventory(await api.resources())}/>;
|
||||
return <ActivityPage activities={activities} hostScoped={hostScoped} projects={projects} live={live} />;
|
||||
}
|
||||
|
||||
function DomainPage({ onRefresh,inventory, setInventory, approval, live, busy, error, onNotify }: { onRefresh:()=>void;inventory: ResourceInventory; setInventory: Dispatch<SetStateAction<ResourceInventory>>; approval: boolean; live: boolean; busy: boolean; error: string; onNotify: (message: string) => void }) {
|
||||
const bindableSites = inventory.sites.filter((site) => !['failed', 'provisioning'].includes(site.status));
|
||||
const [siteID, setSiteID] = useState(0);
|
||||
const [domain, setDomain] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [formError, setFormError] = useState('');
|
||||
const [dnsBusy, setDNSBusy] = useState(0);
|
||||
const [removing,setRemoving]=useState<DomainResource>();
|
||||
const selectedSite = bindableSites.find((site) => site.id === siteID) ?? bindableSites[0];
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
if (!selectedSite) return;
|
||||
setSubmitting(true);
|
||||
setFormError('');
|
||||
try {
|
||||
const normalized = domain.trim().toLowerCase();
|
||||
const host = inventory.ftpAccounts.find((item) => item.projectId === selectedSite.projectId);
|
||||
const item = live
|
||||
? (await api.bindSiteDomain(selectedSite.projectId, selectedSite.id, normalized)).domain
|
||||
: demoDomain(selectedSite, host?.hostName ?? selectedSite.domain.split('.')[0], host?.projectName ?? selectedSite.name, normalized, approval);
|
||||
setInventory((current) => ({ ...current, domains: [item, ...current.domains] }));
|
||||
setDomain('');
|
||||
onNotify(item.status === 'pending' ? '域名已提交管理员审核' : '域名已绑定');
|
||||
} catch (reason) {
|
||||
setFormError(reason instanceof Error ? reason.message : '绑定域名失败');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleDNS(item: DomainResource) {
|
||||
if (!live) return;
|
||||
setDNSBusy(item.id);
|
||||
setFormError('');
|
||||
try {
|
||||
const updated = item.dnsRecordId ? await api.removeDomainDNS(item.id) : await api.provisionDomainDNS(item.id);
|
||||
setInventory((current) => ({ ...current, domains: current.domains.map((domainItem) => domainItem.id === item.id ? updated.domain : domainItem) }));
|
||||
onNotify(item.dnsRecordId ? '托管 DNS 记录已删除' : 'CNAME 记录已自动创建');
|
||||
} catch (reason) {
|
||||
setFormError(reason instanceof Error ? reason.message : 'DNS 操作失败');
|
||||
} finally {
|
||||
setDNSBusy(0);
|
||||
}
|
||||
}
|
||||
|
||||
return <div className="page resource-page">
|
||||
<div className="page-heading"><h1>域名</h1></div>
|
||||
<form className="resource-action-card" onSubmit={submit}>
|
||||
<span className="resource-action-icon"><Globe2 size={21} /></span>
|
||||
<label><span>目标网站</span><select aria-label="目标网站" value={selectedSite?.id ?? ''} onChange={(event) => setSiteID(Number(event.target.value))} disabled={busy || bindableSites.length === 0}>{bindableSites.map((site) => <option value={site.id} key={site.id}>{site.domain} · {site.name}</option>)}</select></label>
|
||||
<label><span>自定义域名</span><input aria-label="自定义域名" value={domain} onChange={(event) => setDomain(event.target.value)} placeholder="例如 app.example.com" required /></label>
|
||||
<button className="primary" disabled={busy || submitting || !selectedSite}><Plus size={15} />{submitting ? '提交中…' : approval ? '提交审核' : '绑定域名'}</button>
|
||||
<small>{approval ? '批准后写入网站配置;仅在网站启用自动证书时申请。' : '域名会立即写入网站配置;请先完成 DNS 解析,并确认证书包含新增域名。'}</small>
|
||||
{formError ? <p className="form-error" role="alert">{formError}</p> : null}
|
||||
</form>
|
||||
<ResourceTable onRefresh={onRefresh} title={`域名记录 · ${inventory.domains.length}`} busy={busy} error={error} empty="暂无域名记录" hasItems={inventory.domains.length > 0}>
|
||||
<table><thead><tr><th>域名</th><th>网站</th><th>类型</th><th>审核状态</th><th>DNS</th><th>网站 SSL</th><th>操作</th></tr></thead><tbody>{inventory.domains.map((item) => <tr key={item.id}><td><b>{item.domain}</b><small>{item.hostName}</small></td><td>{item.siteName}</td><td>{item.kind === 'assigned' ? '系统分配' : '自定义'}</td><td><DomainStatus status={item.status} /></td><td>{item.dnsRecordId ? `托管 ${item.dnsRecordType}` : item.dnsLastError || '未托管'}</td><td>{item.status==='approved'?sslLabel(item.sslStatus):'审核后配置'}</td><td>{item.kind === 'custom'?<span className="row-actions"><button className="resource-link" disabled={dnsBusy!==0} onClick={()=>setRemoving(item)}>解绑</button>{item.status === 'approved' ? <button className="resource-link" disabled={dnsBusy === item.id} onClick={() => void toggleDNS(item)}>{dnsBusy === item.id ? '处理中…' : item.dnsRecordId ? '删除解析' : '自动 CNAME'}</button> : <small>审核通过后管理解析</small>}</span>:<small>随主机管理,不可解绑</small>}</td></tr>)}</tbody></table>
|
||||
</ResourceTable>
|
||||
{removing?<UnbindDomainDialog domain={removing} onClose={()=>setRemoving(undefined)} onUnbind={async()=>{if(live)await api.unbindDomain(removing.id,removing.domain);setInventory(current=>({...current,domains:current.domains.filter(v=>v.id!==removing.id)}));onNotify('自定义域名已解绑')}}/>:null}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function DatabasePage({onRefresh, items, busy, error, onCredentials }: {onRefresh:()=>void; items: DatabaseResource[]; busy: boolean; error: string; onCredentials: (projectID: number) => void }) {
|
||||
return <div className="page resource-page"><div className="page-heading"><h1>数据库</h1></div><ResourceTable onRefresh={onRefresh} title={`MySQL 数据库 · ${items.length}`} busy={busy} error={error} empty="暂无数据库" hasItems={items.length > 0}><table><thead><tr><th>数据库</th><th>所属主机</th><th>用户</th><th>已用空间</th><th>状态</th><th>操作</th></tr></thead><tbody>{items.map((item) => <tr key={item.id}><td><b>{item.name}</b></td><td>{item.projectName}<small>{item.hostName}</small></td><td><code>{item.username}</code></td><td>{formatBytes(item.sizeBytes)}</td><td><span className={`status ${item.status === 'active' ? 'running' : 'quota_suspended'}`}>{item.status === 'active' ? '正常' : '配额暂停'}</span></td><td><button className="resource-link" onClick={() => onCredentials(item.projectId)} aria-label={`查看数据库凭据 ${item.name}`}><Eye size={14} />查看凭据</button><a className="resource-link" href={`/api/v1/projects/${item.projectId}/database-admin/?route=/database/structure&db=${encodeURIComponent(item.name)}&lang=zh_cn`} target="_blank" rel="noopener noreferrer">进入 phpMyAdmin</a></td></tr>)}</tbody></table></ResourceTable></div>;
|
||||
}
|
||||
|
||||
function FTPPage({pausedProjectIDs=[],onRefresh,items,busy,error,onCredentials,live,onNotify,onChanged}:{pausedProjectIDs?:number[];onRefresh:()=>void;items:FTPResource[];busy:boolean;error:string;onCredentials:(id:number)=>void;live:boolean;onNotify:(v:string)=>void;onChanged:()=>Promise<void>}) {
|
||||
const {confirm,confirmation}=useConfirmation();
|
||||
const [pending,setPending]=useState(0),[failure,setFailure]=useState('');
|
||||
const action=async(item:FTPResource,op:string)=>{if(op==='reset'&&!await confirm('随机重置 FTP 密码并断开旧连接?',{title:'重置 FTP 密码',danger:true}))return;setPending(item.id);setFailure('');try{if(live){await api.manageFTP(item.projectId,op);await onChanged()}onNotify(op==='reset'?'FTP 密码已重置,可在凭据中查看':'FTP 状态已更新')}catch(e){setFailure(e instanceof Error?e.message:'操作失败')}finally{setPending(0)}};
|
||||
|
||||
return <div className="page resource-page"><div className="page-heading"><h1>FTP</h1>{confirmation}</div><ResourceTable onRefresh={onRefresh} title={`FTP 账号 · ${items.length}`} busy={busy} error={failure||error} empty="暂无 FTP 账号" hasItems={items.length > 0}><table><thead><tr><th>账号</th><th>所属主机</th><th>根目录</th><th>创建时间</th><th>操作</th></tr></thead><tbody>{items.map((item) => <tr key={item.id}><td><b>{item.username}</b><small>{pausedProjectIDs.includes(item.projectId)?'配额暂停':item.enabled===false?'已停用':'已启用'}</small>{pausedProjectIDs.includes(item.projectId)?<small>{item.enabled===false?'开关已停用,解除超额后仍保持停用':'开关已启用,解除超额后自动恢复'}</small>:null}</td><td>{item.projectName}<small>{item.hostName}</small></td><td><code>{item.rootPath}</code></td><td>{formatDate(item.createdAt)}</td><td><button className="resource-link" onClick={() => onCredentials(item.projectId)} aria-label={`查看 FTP 凭据 ${item.username}`}><FolderKey size={14} />查看凭据</button><button disabled={pending!==0||(pausedProjectIDs.includes(item.projectId)&&item.enabled===false)} title={pausedProjectIDs.includes(item.projectId)&&item.enabled===false?'资源超额,清理数据后可启用':undefined} onClick={()=>void action(item,item.enabled===false?'enable':'disable')}>{item.enabled===false?'启用':'停用'}</button><button disabled={pending!==0||pausedProjectIDs.includes(item.projectId)} title={pausedProjectIDs.includes(item.projectId)?'资源超额,清理数据后可重置密码':undefined} onClick={()=>void action(item,'reset')}>重置密码</button></td></tr>)}</tbody></table></ResourceTable></div>;
|
||||
}
|
||||
|
||||
function ActivityPage({ activities, hostScoped, projects, live }: { activities: ActivityEntry[]; hostScoped: boolean; projects: Project[]; live: boolean }) {
|
||||
const [query,setQuery]=useState(''),[result,setResult]=useState(''),[from,setFrom]=useState(''),[to,setTo]=useState('');
|
||||
const [selectedID, setSelectedID] = useState(0);
|
||||
const projectID = hostScoped ? projects[0]?.id : selectedID;
|
||||
const [items, setItems] = useState(activities);
|
||||
const [busy, setBusy] = useState(live);
|
||||
const [error, setError] = useState('');
|
||||
const [refresh, setRefresh] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!live) { setItems(activities.filter(item => !projectID || item.projectId === projectID || (hostScoped && item.projectId === undefined))); return; }
|
||||
let active = true;
|
||||
setBusy(true); setItems([]); setError('');
|
||||
api.activities(projectID || undefined).then(result => { if (active) setItems(result.activities); })
|
||||
.catch(reason => { if (active) setError(reason instanceof Error ? reason.message : '无法读取操作日志'); })
|
||||
.finally(() => { if (active) setBusy(false); });
|
||||
return () => { active = false; };
|
||||
}, [activities, hostScoped, live, projectID, refresh]);
|
||||
const filtered=items.filter(item=>(!query||`${item.action} ${item.resourceType} ${item.detail} ${item.ipAddress||''} ${item.hostName||''}`.toLowerCase().includes(query.toLowerCase()))&&(!result||item.success===(result==='success'))&&(!from||new Date(item.createdAt)>=new Date(from))&&(!to||new Date(item.createdAt)<new Date(to)));
|
||||
return <div className="page resource-page"><div className="page-heading"><h1>操作日志</h1></div>
|
||||
<div className="host-log-toolbar"><label>搜索日志<input value={query} onChange={e=>setQuery(e.target.value)} placeholder="动作、资源、IP 或详情"/></label><label>结果<select value={result} onChange={e=>setResult(e.target.value)}><option value="">全部</option><option value="success">成功</option><option value="failure">失败</option></select></label><label>开始时间<input type="datetime-local" value={from} onChange={e=>setFrom(e.target.value)}/></label><label>结束时间<input type="datetime-local" value={to} onChange={e=>setTo(e.target.value)}/></label>{!hostScoped ? <label>日志范围<select aria-label="日志范围" value={selectedID} onChange={event => setSelectedID(Number(event.target.value))}><option value="0">全部操作</option>{projects.map(project => <option key={project.id} value={project.id}>{project.hostName} · {project.name}</option>)}</select></label> : <span>{projects[0]?.hostName} · 最近 100 条操作</span>}<button className="secondary" onClick={() => setRefresh(value => value + 1)} disabled={busy}><RefreshCw size={15}/>刷新日志</button></div>
|
||||
<ResourceTable title={`最近操作 · ${filtered.length}`} busy={busy} error={error} empty="暂无操作日志" hasItems={filtered.length > 0}><table className="host-log-table"><thead><tr><th>时间</th>{!hostScoped ? <th>主机</th> : null}<th>操作方</th><th>资源</th><th>动作</th><th>详情</th><th>来源 IP</th><th>结果</th></tr></thead><tbody>{filtered.map((item, index) => <tr key={item.id ?? `${item.createdAt}-${index}`}><td>{formatDateTime(item.createdAt)}</td>{!hostScoped ? <td>{item.hostName || '账号级'}</td> : null}<td>{item.actor || '用户'}</td><td>{resourceLabel(item.resourceType)}</td><td>{actionLabel(item.action)}</td><td>{item.detail}</td><td>{item.ipAddress || '—'}</td><td><span className={`status ${item.success ? 'running' : 'failed'}`}>{item.success ? '成功' : '失败'}</span></td></tr>)}</tbody></table></ResourceTable>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ResourceTable({onRefresh, title, busy, error, empty, hasItems, children }: {onRefresh?:()=>void; title: string; busy: boolean; error: string; empty: string; hasItems: boolean; children: ReactNode }) {
|
||||
return <section className="resource-table"><header><h2>{title}</h2>{onRefresh?<button className="secondary" disabled={busy} onClick={onRefresh}><RefreshCw size={15}/>刷新资源</button>:null}</header>{error ? <p className="resource-error" role="alert">{error}</p> : busy ? <div className="resource-empty">正在读取…</div> : !hasItems ? <div className="resource-empty">{empty}</div> : <div className="table-scroll">{children}</div>}</section>;
|
||||
}
|
||||
|
||||
function DomainStatus({ status }: { status: DomainResource['status'] }) {
|
||||
const labels = { pending: '待审核', approved: '已批准', rejected: '已拒绝' };
|
||||
return <span className={`resource-status ${status}`}>{labels[status]}</span>;
|
||||
}
|
||||
|
||||
function inventoryFromProjects(projects: Project[]): ResourceInventory {
|
||||
const sites: Site[] = projects.map((project) => ({ 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 }));
|
||||
return {
|
||||
sites,
|
||||
domains: projects.map((project) => ({ id: project.id, projectId: project.id, siteId: project.id, hostName: project.hostName, projectName: project.name, siteName: project.name, domain: project.domain, kind: 'assigned', status: 'approved', sslStatus: project.ssl ? 'active' : 'off', createdAt: project.createdAt })),
|
||||
ftpAccounts: projects.map((project) => ({ id: project.id, projectId: project.id, hostName: project.hostName, projectName: project.name, username: project.hostName, rootPath: project.path, createdAt: project.createdAt })),
|
||||
databases: projects.map((project) => ({ id: project.id, projectId: project.id, hostName: project.hostName, projectName: project.name, name: project.hostName, username: project.hostName, sizeBytes: 0, status: 'active', createdAt: project.createdAt })),
|
||||
};
|
||||
}
|
||||
|
||||
function demoDomain(site: Site, hostName: string, projectName: string, domain: string, approval: boolean): DomainResource {
|
||||
return { id: Date.now(), projectId: site.projectId, siteId: site.id, hostName, projectName, siteName: site.name, domain, kind: 'custom', status: approval ? 'pending' : 'approved', sslStatus: approval ? 'off' : 'pending', createdAt: new Date().toISOString() };
|
||||
}
|
||||
|
||||
function sslLabel(status: string) { return ['active', 'valid', 'issued', 'deployed'].includes(status.toLowerCase()) ? '已启用' : status === 'pending' ? '签发中' : '未启用'; }
|
||||
function formatDate(value: string) { return new Date(value).toLocaleDateString('zh-CN'); }
|
||||
function formatDateTime(value: string) { return new Date(value).toLocaleString('zh-CN', { hour12: false }); }
|
||||
function resourceLabel(value: string) { return ({ schedule:'计划任务',startup:'启动设置',website_settings:'网站设置',file: '文件', database: '数据库', project: '虚拟主机', site: '网站', domain: '域名', ftp: 'FTP', host_password: '主机密码', run_path: '运行目录', session: '会话', manual_certificate:'手动证书',automatic_certificate:'自动证书',certificate:'证书',dns_certificate:'DNS 证书',deployment:'部署',project_network:'主机网络',panel_site:'站点接管',host_subscription:'主机套餐',account_password:'账号密码',account_mfa:'双重认证',dns_credential:'DNS 凭据',domain_dns:'域名解析',oidc_identity:'第三方绑定',oidc_session:'第三方会话' } as Record<string, string>)[value] ?? value; }
|
||||
function actionLabel(value: string) { return ({ mkdir:'新建目录',move:'重命名 / 移动',copy:'复制',zip:'ZIP 压缩',extract:'ZIP 解压',restore:'恢复', execute:'执行',manage:'管理',queue:'排队',create: '创建', update: '更新', upload: '上传', write:'保存',trash:'移入回收站',empty_trash:'清空回收站',file_operation:'文件操作',logout:'退出',install:'安装',enable:'启用',unbind:'解绑',issue:'签发',disable:'关闭',adopt:'接管',bind: '绑定', state: '启停', check:'检查',deploy:'部署',delete: '删除', reset: '重置', login: '登录', review: '审核' } as Record<string, string>)[value] ?? value; }
|
||||
@@ -0,0 +1,31 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {Cpu,Database,Gauge,HardDrive,MemoryStick,Network,RefreshCw} from 'lucide-react';
|
||||
import {api,type HostMetric} from '../api';
|
||||
import type {Project} from '../types';
|
||||
import {PageHeader} from './UI';
|
||||
|
||||
const plots=[
|
||||
['CPU 使用率','cpuPercent',1,'% · 100% 为一个核心',Cpu],
|
||||
['内存','memoryBytes',1048576,'MiB',MemoryStick],
|
||||
['进程数','processCount',1,'个',Gauge],
|
||||
['磁盘','storageBytes',1048576,'MiB',HardDrive],
|
||||
['数据库','databaseBytes',1048576,'MiB',Database],
|
||||
['当月累计流量','bandwidthBytes',1048576,'MiB',Network],
|
||||
] as const;
|
||||
|
||||
export function ResourceCharts({projects,live}:{projects:Project[];live:boolean}){
|
||||
const [selected,setSelected]=useState(0),[days,setDays]=useState(1),[samples,setSamples]=useState<HostMetric[]>([]),[error,setError]=useState(''),[refresh,setRefresh]=useState(0),[busy,setBusy]=useState(false);
|
||||
const id=projects.some(p=>p.id===selected)?selected:projects[0]?.id||0;
|
||||
useEffect(()=>{if(!live||!id)return;let active=true;setBusy(true);setSamples([]);setError('');api.hostMetrics(id,days).then(r=>{if(active)setSamples(r.samples)}).catch(e=>{if(active)setError(e.message)}).finally(()=>{if(active)setBusy(false)});return()=>{active=false}},[id,days,live,refresh]);
|
||||
if(!projects.length)return <div className="page"><PageHeader title="资源图表" description="资源由后台自动采集,此页提供查看与刷新;历史数据保留 30 天。"/><section className="empty-state"><Gauge size={30}/><h2>暂无可用主机</h2><p>由管理员分配主机后,即可在这里查看资源趋势。</p></section></div>;
|
||||
return <div className="page"><PageHeader title="资源图表" description="资源由后台自动采集,此页提供查看与刷新;历史数据保留 30 天。"/>
|
||||
<div className="chart-filters"><label>虚拟主机<select aria-label="图表虚拟主机" value={id} onChange={e=>setSelected(Number(e.target.value))} disabled={!projects.length}>{!projects.length?<option value="0">暂无可用主机</option>:null}{projects.map(p=><option key={p.id} value={p.id}>{p.hostName} · {p.name}</option>)}</select></label><label>时间范围<select aria-label="时间范围" value={days} onChange={e=>setDays(Number(e.target.value))}><option value="1">24 小时</option><option value="7">7 天</option><option value="30">30 天</option></select></label><button className="secondary" disabled={busy||!id} onClick={()=>setRefresh(v=>v+1)}><RefreshCw size={15} className={busy?'spin':undefined}/>{busy?'正在读取…':'刷新图表'}</button></div>
|
||||
{error?<p role="alert" className="resource-error">{error}</p>:null}
|
||||
<div className="resource-charts" aria-busy={busy}>{plots.map(([title,key,divisor,unit,Icon])=>{
|
||||
const values=samples.map(s=>Number(s[key as keyof HostMetric])/divisor),max=Math.max(...values,1),points=values.map((v,i)=>`${values.length>1?i/(values.length-1)*560:280},${140-v/max*120}`),last=values.at(-1);
|
||||
return <section className="chart-card" key={key}><header><Icon aria-hidden="true"/><h2>{title}</h2></header><div className="chart-value"><b>{last===undefined?'—':last.toFixed(key==='processCount'?0:2)}</b><span>{unit}</span></div>
|
||||
<svg viewBox="0 0 560 160" role="img" aria-label={title+'历史趋势'}><path d="M0 20H560M0 80H560M0 140H560" className="chart-grid"/>{values.length>1?<polygon points={`0,140 ${points.join(' ')} 560,140`} className="chart-area"/>:null}<polyline points={points.join(' ')} className="chart-line"/>{values.length===1?<circle cx="280" cy={140-values[0]/max*120} r="3" fill="var(--blue)"/>:null}{!values.length?<text x="280" y="85" textAnchor="middle" fill="#8997aa" fontSize="13">{busy?'正在读取历史数据':error?'历史数据读取失败':'等待首次采样'}</text>:null}</svg>
|
||||
<div className="chart-range"><span>{samples.length?formatTime(samples[0].sampledAt):busy?'正在读取历史数据':error?'历史数据读取失败':'新主机创建后自动采样'}</span><span>{samples.length?formatTime(samples.at(-1)!.sampledAt):''}</span></div></section>
|
||||
})}</div></div>;
|
||||
}
|
||||
function formatTime(value:string){return new Date(value).toLocaleString('zh-CN',{month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hour12:false})}
|
||||
@@ -0,0 +1,34 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {api,type AccountProfile,type AdminProject,type ControlNode,type Tenant} from '../api';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {useConfirmation} from './Confirmation';
|
||||
|
||||
const message=(e:unknown)=>e instanceof Error?e.message:'操作失败,请重试';
|
||||
const date=(v?:string)=>v?new Date(v).toLocaleString('zh-CN'):'—';
|
||||
|
||||
export function AccountEditor({account,onClose,onChanged,intent='edit'}:{intent?:'edit'|'delete';account:Tenant;onClose:()=>void;onChanged:()=>Promise<void>}){
|
||||
const [profile,setProfile]=useState<AccountProfile>(),[error,setError]=useState(''),[busy,setBusy]=useState(false),[retry,setRetry]=useState(0);
|
||||
const {confirm,confirmation}=useConfirmation();
|
||||
useEffect(()=>{let active=true;setProfile(undefined);setError('');api.accountProfile(account.id).then(p=>{if(active)setProfile(p)}).catch(e=>{if(active)setError(message(e))});return()=>{active=false}},[account.id,retry]);
|
||||
async function save(){if(!profile)return;setBusy(true);setError('');try{await api.updateAccount(account.id,profile);await onChanged();onClose()}catch(e){setError(message(e))}finally{setBusy(false)}}
|
||||
async function remove(){if(!profile||!await confirm(`删除用户「${profile.name}」?登录权限将被撤销,用户标识和历史审计保留。名下主机必须先解绑或转移。`,{title:'删除用户',confirmLabel:'确认删除用户',danger:true}))return;setBusy(true);setError('');try{await api.deleteAccount(account.id,account.slug);await onChanged();onClose()}catch(e){setError(message(e))}finally{setBusy(false)}}
|
||||
return <><ModalBackdrop><section className="tenant-modal resource-editor"><h2>{intent==='delete'?'删除用户':'用户详情与编辑'}</h2><p>用户标识:<code>{account.slug}</code> · #{account.id}</p>{error?<p className="form-error" role="alert">{error}</p>:null}{profile?<>{intent==='edit'?<form onSubmit={e=>{e.preventDefault();void save()}}><fieldset disabled={busy}><label>用户名称<input required maxLength={120} value={profile.name} onChange={e=>setProfile({...profile,name:e.target.value})}/></label><label>联系人姓名<input required minLength={2} maxLength={80} value={profile.displayName} onChange={e=>setProfile({...profile,displayName:e.target.value})}/></label><label>登录邮箱<input type="email" required maxLength={190} value={profile.email} onChange={e=>setProfile({...profile,email:e.target.value})}/></label><p>关联主机:{profile.projectCount} 台</p><div className="form-actions"><button type="button" className="secondary" onClick={onClose}>关闭</button><button className="primary">{busy?'保存中…':'保存用户资料'}</button></div></fieldset></form>:null}<div className="resource-danger-zone"><p>删除前需逐一解绑或转移全部主机,包括回收中的主机。用户标识与日志保留。</p><button type="button" className="secondary danger-text" title={profile.projectCount>0?'需先逐一解绑或转移全部主机,包括回收中的主机':undefined} disabled={busy||profile.projectCount>0} onClick={()=>void remove()}>删除用户</button>{intent==='delete'?<button type="button" className="secondary" onClick={onClose}>取消</button>:null}</div></>:<><p>{error?'用户资料读取失败':'正在读取用户资料…'}</p><div className="form-actions"><button onClick={onClose}>关闭</button>{error?<button onClick={()=>setRetry(v=>v+1)}>重新读取</button>:null}</div></>}</section></ModalBackdrop>{confirmation}</>;
|
||||
}
|
||||
|
||||
export function HostEditor({host,onClose,onChanged,intent='edit'}:{intent?:'edit'|'recycle';host:AdminProject;onClose:()=>void;onChanged:()=>Promise<void>}){
|
||||
const [allowRuntimeChange,setAllowRuntimeChange]=useState(!!host.allowRuntimeChange);
|
||||
const [name,setName]=useState(host.name),[error,setError]=useState(''),[busy,setBusy]=useState(false),[typed,setTyped]=useState('');
|
||||
const {confirm,confirmation}=useConfirmation();const recycled=!!host.manualRecycledAt;
|
||||
async function action(kind:'save'|'recycle'|'restore'){
|
||||
if(kind!=='save'&&!await confirm(kind==='recycle'?`回收「${host.hostName}」?立即撤销主机登录并停止网站、进程和 FTP,暂停计划任务;7 天后清理数据,清理后的备份保留 14 天。`:'恢复该主机?网站和 FTP 保持停止,计划任务保持暂停;已到期主机需要续期后才能继续使用。',{title:kind==='recycle'?'回收虚拟主机':'恢复虚拟主机',confirmLabel:kind==='recycle'?'确认回收':'确认恢复',danger:kind==='recycle'}))return;
|
||||
setBusy(true);setError('');try{if(kind==='save')await api.renameHost(host.id,name,allowRuntimeChange);else if(kind==='recycle')await api.recycleHost(host.id,recycled?host.hostName:typed);else await api.restoreHost(host.id);await onChanged();onClose()}catch(e){setError(message(e));await onChanged().catch(()=>{})}finally{setBusy(false)}
|
||||
}
|
||||
return <><ModalBackdrop><section className="tenant-modal resource-editor"><h2>{intent==='recycle'?'回收主机':'主机详情与编辑'}</h2><dl className="resource-facts"><div><dt>主机名</dt><dd><code>{host.hostName}</code></dd></div><div><dt>所属节点 / 用户</dt><dd>#{host.nodeId} · {host.tenantName}</dd></div><div><dt>主机目录</dt><dd><code>{host.path}</code></dd></div><div><dt>运行目录</dt><dd><code>{host.runPath}</code></dd></div><div><dt>到期时间</dt><dd>{host.expiresAt?date(host.expiresAt):'长期使用'}</dd></div>{recycled?<><div><dt>回收时间</dt><dd>{date(host.manualRecycledAt)}</dd></div><div><dt>预计清理时间</dt><dd>{date(host.purgeAfter)}</dd></div></>:null}</dl>{error||host.recycleError?<p className="form-error" role="alert">{error||host.recycleError}</p>:null}{intent==='edit'?<form onSubmit={e=>{e.preventDefault();void action('save')}}><fieldset disabled={busy||recycled||host.managementLocked}><label>主机显示名称<input required maxLength={50} value={name} onChange={e=>setName(e.target.value)}/></label><label className="check-row"><input type="checkbox" checked={allowRuntimeChange} onChange={e=>setAllowRuntimeChange(e.target.checked)}/>允许切换运行环境</label><small>始终可切换已安装的同语言版本;启用后可跨语言切换,切换时先停站。</small><div className="form-actions"><button type="button" className="secondary" onClick={onClose}>关闭</button><button className="primary">保存主机配置</button></div></fieldset></form>:null}{intent==='recycle'||recycled?<div className="resource-danger-zone">{recycled?<><p>回收期内可以恢复。恢复后请手动检查并启动网站、启用 FTP。</p><div className="form-actions"><button type="button" onClick={onClose}>关闭</button><button type="button" className="primary" disabled={busy||!host.purgeAfter||new Date(host.purgeAfter).getTime()<=Date.now()} onClick={()=>void action('restore')}>恢复主机</button>{host.recycleError?<button type="button" disabled={busy} onClick={()=>void action('recycle')}>重试停用服务</button>:null}</div></>:<><p>回收后立即停用,保留 7 天可恢复;期满备份并清理,备份保留 14 天。</p><label>输入主机名确认回收<input value={typed} onChange={e=>setTyped(e.target.value)} placeholder={host.hostName} autoComplete="off"/></label><button type="button" className="secondary danger-text" disabled={busy||host.managementLocked||typed!==host.hostName} onClick={()=>void action('recycle')}>回收主机</button></>}</div>:null}{intent==='recycle'?<button type="button" className="secondary" onClick={onClose}>关闭</button>:null}</section></ModalBackdrop>{confirmation}</>;
|
||||
}
|
||||
|
||||
export function NodeEditor({node,onClose,onChanged}:{node:ControlNode;onClose:()=>void;onChanged:()=>Promise<void>}){
|
||||
const [value,setValue]=useState(node),[busy,setBusy]=useState(false),[error,setError]=useState('');const {confirm,confirmation}=useConfirmation();
|
||||
async function save(){setBusy(true);setError('');try{await api.updateNode(node.id,{name:value.name,endpoint:value.endpoint,rootDomain:value.rootDomain,tenantRoot:value.tenantRoot,ftpCertificateDomain:value.ftpCertificateDomain});await onChanged();onClose()}catch(e){setError(message(e))}finally{setBusy(false)}}
|
||||
async function remove(){if(!await confirm(`删除节点「${node.name}」?仅允许删除已停用且无主机、备份、未完成任务和宝塔资源登记的远程节点。主控保存的连接凭据会被撤销,历史审计保留。`,{title:'删除节点',confirmLabel:'确认删除节点',danger:true}))return;setBusy(true);setError('');try{await api.deleteNode(node.id,node.name);await onChanged();onClose()}catch(e){setError(message(e))}finally{setBusy(false)}}
|
||||
return <><ModalBackdrop><section className="tenant-modal resource-editor"><h2>节点详情与编辑</h2><p>#{node.id} · {node.transport==='local'?'本机节点':'HTTPS 被控节点'} · {node.enabled?'已启用':'已停用'}</p>{error?<p role="alert" className="form-error">{error}</p>:null}<form onSubmit={e=>{e.preventDefault();void save()}}><fieldset disabled={busy}><label>节点名称<input required maxLength={80} value={value.name} onChange={e=>setValue({...value,name:e.target.value})}/></label><label>执行入口<input required disabled={node.transport==='local'||node.enabled} value={value.endpoint} onChange={e=>setValue({...value,endpoint:e.target.value})}/></label><label>默认域名后缀<input required value={value.rootDomain} onChange={e=>setValue({...value,rootDomain:e.target.value})}/></label><label>FTP 证书来源域名<input required value={value.ftpCertificateDomain} onChange={e=>setValue({...value,ftpCertificateDomain:e.target.value})}/></label><label>主机根目录<input required disabled={node.transport==='local'||node.enabled} value={value.tenantRoot} onChange={e=>setValue({...value,tenantRoot:e.target.value})}/></label><p>域名后缀用于后续开通的主机。修改执行入口或根目录前,须停用节点并清空关联资源。</p><div className="form-actions"><button type="button" onClick={onClose}>关闭</button><button className="primary">保存节点配置</button></div></fieldset></form><div className="resource-danger-zone"><p>{node.id===1?'本机节点禁止删除。':'删除节点不会卸载远程服务;历史节点编号与执行入口保留。'}</p><button type="button" className="secondary danger-text" disabled={busy||node.enabled||node.id===1} onClick={()=>void remove()}>删除节点</button></div></section></ModalBackdrop>{confirmation}</>;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import { FolderCog, X } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { normalizeRunPath } from '../runPath';
|
||||
import type { Project } from '../types';
|
||||
|
||||
export function RunPathModal({ project, onClose, onSubmit }: { project: Project; onClose: () => void; onSubmit: (runPath: string) => void|Promise<void> }) {
|
||||
const [value, setValue] = useState(project.runPath || '/');const [busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const normalized = normalizeRunPath(value);
|
||||
return <ModalBackdrop className="modal-backdrop" role="presentation"><form className="run-path-modal" role="dialog" aria-modal="true" aria-labelledby="run-path-title" onSubmit={async(event)=>{event.preventDefault();if(!normalized||busy)return;setBusy(true);setError('');try{await onSubmit(normalized)}catch(e){setError(e instanceof Error?e.message:'运行目录保存失败')}finally{setBusy(false)}}}><button type="button" className="modal-close" onClick={onClose} aria-label="关闭"><X size={18} /></button><FolderCog size={26} className="modal-icon" /><h2 id="run-path-title">设置运行目录</h2><p>{project.domain}</p><label><span>主机根目录</span><input readOnly value={project.path} /></label><label><span>运行目录</span><input autoFocus value={value} onChange={(event) => setValue(event.target.value)} placeholder="/、/public 或 /dist" /><small>{normalized ? `实际发布:${project.path}${normalized === '/' ? '' : normalized}` : '目录必须位于主机根目录内,不能包含空格、反斜杠或 ..。'}</small></label>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="modal-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button type="submit" className="primary" title={!normalized?'请输入主机目录内的有效相对运行目录':undefined} disabled={busy||!normalized}>{busy?'正在保存…':'保存'}</button></div></form></ModalBackdrop>;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api, type RuntimeEnvironment, type RuntimeMaintenanceJob, type RuntimeMaintenanceSite } from '../api';
|
||||
import { RefreshCw, ShieldCheck } from 'lucide-react';
|
||||
|
||||
const statusLabels: Record<string, string> = { queued: '待执行', running: '运行中', completed: '已完成', failed: '失败', rolled_back: '已回退', interrupted: '待核验' };
|
||||
const phaseLabels: Record<string, string> = { queued: '等待处理', checking: '检查更新', backing_up: '备份环境', installing: '安装版本', restarting: '重启站点', preparing: '准备依赖', switching: '切换版本', verifying: '核验进程', verified: '验证完成', failed: '处理失败', rolling_back: '恢复旧版', rolled_back: '已恢复旧版' };
|
||||
const actionLabels: Record<string, string> = { install: '安装版本', php_patch: 'PHP 补丁更新', migrate: '站点版本切换', check: '检查更新与运行状态',runtime_change:'站点环境切换' };
|
||||
|
||||
export function runtimeBranch(name: string, version: string) {
|
||||
const parts = version.replace(/^(jdk-|go|v)/, '').split('.');
|
||||
return name === 'Node.js' || name === 'Java' ? parts[0] : parts.slice(0, 2).join('.');
|
||||
}
|
||||
export function RuntimeMaintenancePanel({ environments, onChanged,nodeId }: {nodeId?:number; environments: RuntimeEnvironment[]; onChanged: () => Promise<void> }) {
|
||||
const {confirm,confirmation}=useConfirmation();
|
||||
const [sites, setSites] = useState<RuntimeMaintenanceSite[]>([]);
|
||||
const [jobs, setJobs] = useState<RuntimeMaintenanceJob[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [notice, setNotice] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const loading = useRef(false);
|
||||
const previouslyActive = useRef(false);
|
||||
const load = useCallback(async () => {
|
||||
if (loading.current) return;
|
||||
loading.current = true;
|
||||
try {
|
||||
const result = await api.runtimeMaintenance(nodeId);
|
||||
setSites(result.sites);
|
||||
setJobs(result.jobs);
|
||||
setError('');
|
||||
const nowActive = result.jobs.some((job) => ['queued', 'running'].includes(job.status));
|
||||
if (previouslyActive.current && !nowActive) void onChanged();
|
||||
previouslyActive.current = nowActive;
|
||||
} catch (reason) { setError(reason instanceof Error ? reason.message : '维护状态读取失败'); }
|
||||
finally { loading.current = false; }
|
||||
}, [onChanged,nodeId]);
|
||||
useEffect(() => { void load(); }, [load, environments]);
|
||||
const queued = (action:string,target?:string) => jobs.some(job => ['queued','running','interrupted'].includes(job.status) && job.action===action && (!target || job.targetVersion===target));
|
||||
const polling = jobs.some((job) => ['queued', 'running'].includes(job.status));
|
||||
useEffect(() => {
|
||||
if (!polling) return;
|
||||
const timer = window.setInterval(() => { void load(); }, 8000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [polling, load]);
|
||||
const submit = async (operation: () => Promise<unknown>, message: string) => {
|
||||
setBusy(true); setError(''); setNotice('');
|
||||
try { await operation(); setNotice(message); await load(); }
|
||||
catch (reason) { setError(reason instanceof Error ? reason.message : '维护任务提交失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const php = environments.find((item) => item.name === 'PHP');
|
||||
const patches = php?.patches || [];
|
||||
return <div className="runtime-maintenance">{confirmation}
|
||||
<section className="admin-card">
|
||||
<header><h2><ShieldCheck size={17} />补丁更新与生效验证</h2><button className="secondary" disabled={busy || queued('check')} onClick={() => void submit(()=>api.checkRuntimeUpdates(nodeId), '已提交更新检查与站点进程核验。')}><RefreshCw size={15} />检查更新</button></header>
|
||||
<p className="runtime-maintenance-note">更新按节点排队串行执行。PHP 补丁更新会影响该分支的全部网站。</p>
|
||||
{error ? <p className="form-error" role="alert">{error}</p> : null}
|
||||
{notice ? <p className="environment-message success" role="status">{notice}</p> : null}
|
||||
<div className="table-scroll"><table><thead><tr><th>PHP 分支</th><th>已安装补丁</th><th>可用补丁</th><th>本站托管站点</th><th>操作</th></tr></thead><tbody>
|
||||
{patches.map((patch) => <tr key={patch.branch}><td>PHP {patch.branch}</td><td>{patch.installed || '未识别'}</td><td>{patch.latest}</td><td>{sites.filter((item) => item.site.runtime === 'PHP' && item.site.version === patch.branch).length}</td><td>{patch.updateAvailable ? <button className="table-link" disabled={busy || queued('php_patch',patch.latest)} onClick={async () => {
|
||||
if (await confirm('将 PHP ' + patch.installed + ' 更新至 ' + patch.latest + '?将备份该分支环境、核验扩展,并重启使用此分支的运行中站点。包括 Sea vHost 之外的网站在内,该分支共享环境会受影响。')) void submit(() => api.updatePHPPatch(patch.branch, patch.latest,nodeId), 'PHP 补丁更新已排队,可在任务记录中查看进度。');
|
||||
}}>更新 PHP {patch.branch}</button> : <span className="runtime-success">已是最新</span>}</td></tr>)}
|
||||
</tbody></table>{!patches.length ? <p className="runtime-empty">PHP 补丁清单暂不可用,请刷新状态。</p> : null}</div>
|
||||
</section>
|
||||
<section className="admin-card">
|
||||
<header><h2>维护任务记录</h2><small>最近 50 项 · 状态自动刷新</small></header>
|
||||
<div className="table-scroll"><table><thead><tr><th>任务</th><th>版本</th><th>状态 / 阶段</th><th>结果</th></tr></thead><tbody>{jobs.map((job) => <tr key={job.id}><td>#{job.id} {actionLabels[job.action] || job.action}</td><td>{job.runtime === 'all' ? '全部环境' : job.runtime + ' ' + (job.fromVersion ? job.fromVersion + ' → ' : '') + job.targetVersion}</td><td><span>{statusLabels[job.status] || job.status}</span><small>{phaseLabels[job.phase] || job.phase}</small></td><td>{job.message || '—'}{job.backupAvailable ? <small>已保留迁移前环境或配置</small> : null}{job.status === 'interrupted' ? <button className="table-link" disabled={busy} onClick={() => void submit(() => api.resumeRuntimeMaintenance(job.id,nodeId), '已提交恢复核验,系统会先检查当前状态。')}>恢复核验</button> : null}</td></tr>)}</tbody></table>{!jobs.length ? <p className="runtime-empty">暂无维护任务。</p> : null}</div>
|
||||
</section>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import { KeyRound, Link2, ShieldCheck, X } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api } from '../api';
|
||||
|
||||
export function SecurityModal({ onClose, onSessionEnded }: { onClose: () => void; onSessionEnded: () => void }) {
|
||||
const [mfaEnabled, setMFAEnabled] = useState(false);
|
||||
const [oidc, setOIDC] = useState({ enabled: false, bound: false, email: '',canUnbind:true });
|
||||
const [setup, setSetup] = useState<{ secret: string; otpauthURI: string }>();
|
||||
const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
|
||||
const [busy, setBusy] = useState('loading');
|
||||
const [error, setError] = useState('');
|
||||
const [notice, setNotice] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
Promise.all([api.accountSecurity(), api.accountOIDC()]).then(([security, identity]) => { if (active) { setMFAEnabled(security.mfaEnabled); setOIDC({ enabled: identity.enabled, bound: identity.bound, email: identity.email || '',canUnbind:identity.canUnbind!==false }); } }).catch((reason) => { if (active) setError(message(reason)); }).finally(() => { if (active) setBusy(''); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
|
||||
async function changePassword(form: HTMLFormElement) {
|
||||
const data = new FormData(form);
|
||||
const current = String(data.get('currentPassword') ?? '');
|
||||
const next = String(data.get('newPassword') ?? '');
|
||||
const confirm = String(data.get('confirmPassword') ?? '');
|
||||
if (next !== confirm) throw new Error('两次输入的新密码不一致');
|
||||
await api.changePassword(current, next);
|
||||
form.reset();
|
||||
setNotice('密码已更新,其他登录会话已注销。');
|
||||
}
|
||||
|
||||
async function beginMFA(form: HTMLFormElement) {
|
||||
const current = String(new FormData(form).get('currentPassword') ?? '');
|
||||
setSetup(await api.setupMFA(current));
|
||||
form.reset();
|
||||
setNotice('请将密钥加入认证器,再输入 6 位动态验证码。');
|
||||
}
|
||||
|
||||
async function enableMFA(form: HTMLFormElement) {
|
||||
const code = String(new FormData(form).get('code') ?? '');
|
||||
const result = await api.enableMFA(code);
|
||||
setRecoveryCodes(result.recoveryCodes);
|
||||
setSetup(undefined);
|
||||
setMFAEnabled(true);
|
||||
setNotice('双重认证已启用。恢复码只显示这一次,请立即保存。');
|
||||
}
|
||||
|
||||
async function disableMFA(form: HTMLFormElement) {
|
||||
const data = new FormData(form);
|
||||
await api.disableMFA(String(data.get('currentPassword') ?? ''), String(data.get('code') ?? ''));
|
||||
onSessionEnded();
|
||||
}
|
||||
|
||||
async function submit(name: string, action: () => Promise<void>) {
|
||||
setBusy(name); setError(''); setNotice('');
|
||||
try { await action(); } catch (reason) { setError(message(reason)); } finally { setBusy(''); }
|
||||
}
|
||||
|
||||
async function bindOIDC() { const result = await api.beginOIDC('bind'); window.location.assign(result.url); }
|
||||
async function unbindOIDC(form: HTMLFormElement) { const password = String(new FormData(form).get('currentPassword') ?? ''); await api.unbindOIDC(password); setOIDC((current) => ({ ...current, bound: false, email: '' })); form.reset(); setNotice('第三方账号绑定已解除,密码登录不受影响。'); }
|
||||
|
||||
return <ModalBackdrop className="modal-backdrop" role="presentation"><section className="security-modal" role="dialog" aria-modal="true" aria-labelledby="security-title">
|
||||
<button className="modal-close" onClick={onClose} aria-label="关闭"><X size={18} /></button>
|
||||
<ShieldCheck size={28} className="modal-icon" /><h2 id="security-title">账号安全</h2><p>修改密码、管理动态验证码与一次性恢复码。</p>
|
||||
{error ? <p className="form-error" role="alert">{error}</p> : null}{notice ? <p className="security-notice" role="status">{notice}</p> : null}
|
||||
<form className="security-section" onSubmit={(event) => { event.preventDefault(); void submit('password', () => changePassword(event.currentTarget)); }}>
|
||||
<h3><KeyRound size={17} />修改密码</h3><label>当前密码<input name="currentPassword" type="password" autoComplete="current-password" required /></label><div className="security-grid"><label>新密码<input name="newPassword" type="password" autoComplete="new-password" minLength={12} maxLength={128} required /></label><label>确认新密码<input name="confirmPassword" type="password" autoComplete="new-password" minLength={12} maxLength={128} required /></label></div><button className="secondary" disabled={busy !== ''}>{busy === 'password' ? '正在保存…' : '更新密码'}</button>
|
||||
</form>
|
||||
<div className="security-section"><h3><ShieldCheck size={17} />双重认证 <span className={`status ${mfaEnabled ? 'running' : 'stopped'}`}>{mfaEnabled ? '已启用' : '未启用'}</span></h3>
|
||||
{!mfaEnabled && !setup ? <form onSubmit={(event) => { event.preventDefault(); void submit('mfa-setup', () => beginMFA(event.currentTarget)); }}><label>当前密码<input name="currentPassword" type="password" autoComplete="current-password" required /></label><button className="secondary" disabled={busy !== ''}>{busy === 'mfa-setup' ? '正在生成…' : '开始配置'}</button></form> : null}
|
||||
{setup ? <form onSubmit={(event) => { event.preventDefault(); void submit('mfa-enable', () => enableMFA(event.currentTarget)); }}><label>认证器密钥<input readOnly value={setup.secret} onFocus={(event) => event.currentTarget.select()} /></label><small className="security-uri">兼容 URI:{setup.otpauthURI}</small><label>6 位动态验证码<input name="code" inputMode="numeric" autoComplete="one-time-code" pattern="[0-9]{6}" required /></label><button className="primary" disabled={busy !== ''}>{busy === 'mfa-enable' ? '正在验证…' : '验证并启用'}</button></form> : null}
|
||||
{mfaEnabled && recoveryCodes.length === 0 ? <form onSubmit={(event) => { event.preventDefault(); void submit('mfa-disable', () => disableMFA(event.currentTarget)); }}><label>当前密码<input name="currentPassword" type="password" autoComplete="current-password" required /></label><label>动态验证码或恢复码<input name="code" autoComplete="one-time-code" required /></label><button className="danger-button" disabled={busy !== ''}>{busy === 'mfa-disable' ? '正在关闭…' : '关闭双重认证并注销全部会话'}</button></form> : null}
|
||||
{recoveryCodes.length ? <div className="recovery-codes"><b>一次性恢复码</b><div>{recoveryCodes.map((code) => <code key={code}>{code}</code>)}</div><button className="secondary" onClick={() => navigator.clipboard?.writeText(recoveryCodes.join('\n'))}>复制全部</button></div> : null}
|
||||
</div>
|
||||
{oidc.enabled || oidc.bound ? <div className="security-section"><h3><Link2 size={17} />第三方账号 <span className={`status ${oidc.bound ? 'running' : 'stopped'}`}>{oidc.bound ? '已绑定' : '未绑定'}</span></h3>{oidc.bound&&!oidc.canUnbind?<p className="security-identity">当前已关闭密码登录,恢复密码登录后才可解除 SSO 绑定。</p>:oidc.bound ? <form onSubmit={(event) => { event.preventDefault(); void submit('oidc-unbind', () => unbindOIDC(event.currentTarget)); }}><p className="security-identity">{oidc.email || '已绑定 OIDC 身份'}</p><label>当前密码<input name="currentPassword" type="password" autoComplete="current-password" required /></label><button className="danger-button" disabled={busy !== ''}>{busy === 'oidc-unbind' ? '正在解除…' : '解除绑定'}</button></form> : <><p className="security-identity">绑定当前账号的第三方身份;密码登录方式由管理员设置。</p><button className="secondary" disabled={busy !== ''} onClick={() => void submit('oidc-bind', bindOIDC)}>{busy === 'oidc-bind' ? '正在跳转…' : '绑定第三方账号'}</button></>}</div> : null}
|
||||
<div className="modal-actions"><button className="primary" onClick={onClose}>完成</button></div>
|
||||
</section></ModalBackdrop>;
|
||||
}
|
||||
|
||||
function message(reason: unknown) {
|
||||
return reason instanceof Error ? reason.message : '操作失败';
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Cloud, Database, FileText, Folder, Gauge, Globe2, HardDrive, ScrollText } from 'lucide-react';
|
||||
|
||||
const items = [
|
||||
['overview', '总览', Gauge],
|
||||
['projects', '虚拟主机', HardDrive],
|
||||
['domains', '域名', Globe2],
|
||||
['dns', 'DNS API', Cloud],
|
||||
['databases', '数据库', Database],
|
||||
['ftp', 'FTP', Folder],
|
||||
['files', '文件管理', FileText],
|
||||
['metrics','资源图表',Gauge],
|
||||
['schedules','计划任务',ScrollText],
|
||||
['logs', '操作日志', ScrollText],
|
||||
] as const;
|
||||
|
||||
export function Sidebar({ page, onNavigate, hostScoped = false }: { page: string; onNavigate: (page: string) => void; hostScoped?: boolean }) {
|
||||
return (
|
||||
<aside className="sidebar" aria-label="主导航">
|
||||
<nav>
|
||||
{items.filter(([key]) => !(hostScoped && (key === 'overview'||key === 'dns'||key==='schedules'))).map(([key, label, Icon]) => (
|
||||
<button key={key} aria-current={page === key ? "page" : undefined} className={page === key ? 'nav-item active' : 'nav-item'} onClick={() => onNavigate(key)}>
|
||||
<Icon size={19} aria-hidden="true" />
|
||||
<span>{label}</span>
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<div className="sidebar-foot">
|
||||
<span className="health-dot" />
|
||||
Sea vHost 控制台
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {api,type RuntimeMaintenanceJob} from '../api';
|
||||
import type {Project,Site,Runtime,RuntimeCatalog} from '../types';
|
||||
import {useConfirmation} from './Confirmation';
|
||||
const labels:Record<string,string>={queued:'排队中',running:'正在切换',completed:'已完成',failed:'失败',interrupted:'待管理员核验',rolled_back:'已回退'};
|
||||
export function SiteRuntime({project,site,catalog,onClose,onChanged,live}:{project:Project;site:Site;catalog:RuntimeCatalog;onClose:()=>void;onChanged:()=>Promise<void>;live:boolean}){
|
||||
const [runtime,setRuntime]=useState<Runtime>(site.runtime),[version,setVersion]=useState(site.version),[entry,setEntry]=useState(''),[jobs,setJobs]=useState<RuntimeMaintenanceJob[]>([]),[busy,setBusy]=useState(false),[error,setError]=useState('');const {confirm,confirmation}=useConfirmation();
|
||||
const pending=jobs.some(j=>['queued','running','interrupted'].includes(j.status));
|
||||
useEffect(()=>{if(!live)return;let active=true;const load=()=>api.siteRuntimeJobs(project.id,site.id).then(r=>{if(active)setJobs(r.jobs)}).catch(e=>{if(active)setError(e.message)});void load();const timer=window.setInterval(()=>void load(),5000);return()=>{active=false;window.clearInterval(timer)}},[project.id,site.id,live]);
|
||||
useEffect(()=>{if(jobs[0]?.status==='completed')void onChanged()},[jobs[0]?.id,jobs[0]?.status]);
|
||||
const choices=(Object.keys(catalog) as Runtime[]).filter(r=>(project.allowRuntimeChange||r===site.runtime)&&catalog[r].length);
|
||||
return <section className="site-runtime-form">{confirmation}<header><h3>运行环境 · {site.name}</h3><button type="button" className="secondary" onClick={onClose}>关闭配置</button></header><form onSubmit={async e=>{e.preventDefault();if(!await confirm(`将 ${site.domain} 切换到 ${runtime} ${version}?网站将先停止;文件和数据库保留。切换后请检查兼容性,再部署或手动启动。`))return;setBusy(true);setError('');try{if(live){await api.changeSiteRuntime(project.id,site.id,runtime,version,entry);setJobs((await api.siteRuntimeJobs(project.id,site.id)).jobs)}else setError('演示模式无法执行环境切换')}catch(e){setError(e instanceof Error?e.message:'环境切换失败')}finally{setBusy(false)}}}>
|
||||
<div className="settings-grid"><label>运行环境<select value={runtime} disabled={pending||busy} onChange={e=>{const r=e.target.value as Runtime;setRuntime(r);setVersion(catalog[r][0]||'')}}>{choices.map(r=><option key={r}>{r}</option>)}</select></label><label>运行版本<select value={version} disabled={pending||busy} onChange={e=>setVersion(e.target.value)}>{(catalog[runtime]||[]).map(v=><option key={v}>{v}</option>)}</select></label>{runtime==='Go'&&site.runtime==='Go'?<label>新程序文件<input value={entry} onChange={e=>setEntry(e.target.value)} placeholder="app-new"/><small>使用目标 SDK 编译,保留原程序以便回退。</small></label>:null}</div>
|
||||
{!project.allowRuntimeChange?<small>当前主机仅允许切换同语言的已安装版本。</small>:null}
|
||||
{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button className="primary" disabled={busy||pending||!version||(runtime===site.runtime&&version===site.version&&(runtime!=='Go'||site.status==='awaiting_upload'||!entry.trim()))}>{busy?'提交中…':pending?'环境任务处理中':'停止并切换'}</button></div></form>
|
||||
{jobs.length?<div className="runtime-job-summary" aria-live="polite">{jobs.slice(0,3).map(j=><p key={j.id}>#{j.id} · {j.runtime} {j.targetVersion} · {labels[j.status]||j.status}<small>{j.message}</small></p>)}</div>:null}</section>
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {useEffect,useState} from 'react';
|
||||
import {api,type WebsiteSettings} from '../api';
|
||||
import type {Site} from '../types';
|
||||
const defaults:WebsiteSettings={rewrite:'none',redirectURL:'',redirectCode:301,forceHTTPS:false,index:['index.php','index.html','index.htm'],error404:'',error503:'',maintenance:false};
|
||||
export function SiteTools({site,projectId,live,onClose}:{site:Site;projectId:number;live:boolean;onClose:()=>void}){
|
||||
const [tab,setTab]=useState('settings'),[settings,setSettings]=useState(defaults),[busy,setBusy]=useState(live),[settingsReady,setSettingsReady]=useState(!live),[error,setError]=useState(''),[notice,setNotice]=useState(''),[kind,setKind]=useState('error'),[search,setSearch]=useState(''),[lines,setLines]=useState<string[]>([]),[refresh,setRefresh]=useState(0);
|
||||
useEffect(()=>{let active=true;if(!live)return;setBusy(true);setError('');setNotice('');if(tab==='settings')setSettingsReady(false);else setLines([]);const pending=tab==='settings'?api.websiteSettings(projectId,site.id).then(r=>{if(active){setSettings(r.settings);setSettingsReady(true)}}):api.siteLog(projectId,site.id,kind,search).then(r=>{if(active)setLines(r.lines)});pending.catch(e=>{if(active)setError(e.message)}).finally(()=>{if(active)setBusy(false)});return()=>{active=false}},[projectId,site.id,live,tab,kind,refresh]);
|
||||
async function save(){if(busy||!settingsReady)return;setBusy(true);setError('');setNotice('');try{if(live)await api.saveWebsiteSettings(projectId,site.id,settings);setNotice('设置已保存,Nginx 校验通过')}catch(e){setError(e instanceof Error?e.message:'保存失败')}finally{setBusy(false)}}
|
||||
return <ModalBackdrop className="modal-backdrop"><section className="batch-modal" role="dialog" aria-modal="true" aria-label="网站设置与日志"><header className="batch-heading"><h2>{site.name} · 网站工具</h2><button aria-label="关闭网站工具" onClick={onClose}>关闭</button></header><div className="batch-actions"><button className={tab==='settings'?'primary':'secondary'} onClick={()=>setTab('settings')}>网站设置</button><button className={tab==='logs'?'primary':'secondary'} onClick={()=>setTab('logs')}>网站日志</button></div>{error?<div role="alert" className="form-error load-error">{error}{tab==='settings'&&!settingsReady?<button type="button" className="secondary" disabled={busy} onClick={()=>setRefresh(v=>v+1)}>重新读取设置</button>:null}</div>:null}{notice?<p role="status">{notice}</p>:null}{tab==='settings'?<form aria-busy={busy} onSubmit={e=>{e.preventDefault();void save()}}>{busy&&!settingsReady?<p role="status">正在读取网站设置…</p>:null}<fieldset disabled={busy||!settingsReady}><div className="batch-controls"><label>伪静态模板<select value={settings.rewrite} disabled={site.runtime!=='PHP'||busy} onChange={e=>setSettings({...settings,rewrite:e.target.value})}><option value="none">不启用</option><option value="wordpress">WordPress</option><option value="laravel">Laravel</option><option value="thinkphp">ThinkPHP</option><option value="spa">单页应用 SPA</option></select></label><label>默认首页(逗号分隔)<input value={settings.index.join(',')} onChange={e=>setSettings({...settings,index:e.target.value.split(',').map(v=>v.trim())})}/></label><label>跳转地址<input value={settings.redirectURL} placeholder="https://www.vhost.ser888.cn/" onChange={e=>setSettings({...settings,redirectURL:e.target.value})}/></label><label>跳转方式<select value={settings.redirectCode} onChange={e=>setSettings({...settings,redirectCode:Number(e.target.value)})}><option value="301">301 永久跳转</option><option value="302">302 临时跳转</option></select></label><label>404 页面<input value={settings.error404} placeholder="404.html" onChange={e=>setSettings({...settings,error404:e.target.value})}/></label><label>503 页面<input value={settings.error503} placeholder="503.html" onChange={e=>setSettings({...settings,error503:e.target.value})}/></label><label className="batch-check"><input type="checkbox" checked={settings.forceHTTPS} onChange={e=>setSettings({...settings,forceHTTPS:e.target.checked})}/>强制 HTTPS(需有效证书)</label><label className="batch-check"><input type="checkbox" checked={settings.maintenance} onChange={e=>setSettings({...settings,maintenance:e.target.checked})}/>维护模式(返回 503)</label></div><p>错误页面位于当前网站运行目录内。配置校验失败会恢复原配置。</p><button className="primary" disabled={busy||!settingsReady}>{busy&&settingsReady?'正在保存…':'保存网站设置'}</button></fieldset></form>:<><div className="batch-controls"><label>日志类型<select value={kind} onChange={e=>setKind(e.target.value)}><option value="access">访问日志</option><option value="error">Nginx 错误日志</option><option value="runtime">程序运行日志</option>{site.runtime==='PHP'?<option value="php">PHP-FPM 日志</option>:null}</select></label><label>搜索关键词<input value={search} onChange={e=>setSearch(e.target.value)}/></label><button disabled={busy} onClick={()=>setRefresh(v=>v+1)}>查询 / 刷新日志</button></div><pre className="site-log-view">{busy?'正在读取…':lines.length?lines.join('\n'):error?'日志读取失败,请重试':'暂无匹配日志'}</pre><button className="secondary" disabled={busy||!!error} onClick={()=>{if(busy||error)return;const url=URL.createObjectURL(new Blob([JSON.stringify({siteId:site.id,kind,lines},null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download=`site-${site.id}-${kind}.json`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)}}>下载日志 JSON</button></>}</section></ModalBackdrop>
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { RefreshCw, ServerOff } from 'lucide-react';
|
||||
import { Brand } from './Brand';
|
||||
|
||||
export function StartupError({ message, onRetry }: { message: string; onRetry?: () => void }) {
|
||||
return <main className="startup-error-page"><section className="startup-error-panel">
|
||||
<Brand />
|
||||
<div className="startup-error-icon"><ServerOff /></div>
|
||||
<h1>暂时无法连接服务</h1>
|
||||
<p>{message}</p>
|
||||
{onRetry?<button className="primary" onClick={onRetry}><RefreshCw size={16} />重新连接</button>:null}
|
||||
{onRetry?<small>如果服务刚完成安装,通常等待几秒后重试即可。</small>:null}
|
||||
</section></main>;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {useEffect,useState} from 'react';
|
||||
import {api,type StartupSettings as Settings} from '../api';
|
||||
import type {Site} from '../types';
|
||||
export function StartupSettings({site,projectId,live,onClose}:{site:Site;projectId:number;live:boolean;onClose:()=>void}){
|
||||
const [config,setConfig]=useState<Settings>({entryFile:'',workDir:'.',arguments:[],environment:{}}),[argumentsJSON,setArguments]=useState('[]'),[environmentJSON,setEnvironment]=useState('{}'),[show,setShow]=useState(false),[busy,setBusy]=useState(live),[error,setError]=useState(''),[notice,setNotice]=useState(''),[loaded,setLoaded]=useState(!live),[retry,setRetry]=useState(0);
|
||||
useEffect(()=>{if(!live)return;let active=true;setBusy(true);setLoaded(false);setError('');api.siteStartup(projectId,site.id).then(r=>{if(active){setLoaded(true);setConfig(r.startup);setArguments(JSON.stringify(r.startup.arguments||[],null,2));setEnvironment(JSON.stringify(r.startup.environment||{},null,2))}}).catch(e=>{if(active)setError(e.message)}).finally(()=>{if(active)setBusy(false)});return()=>{active=false}},[projectId,site.id,live,retry]);
|
||||
async function save(){if(!loaded||busy)return;setBusy(true);setError('');setNotice('');try{const args:unknown=JSON.parse(argumentsJSON),env:unknown=JSON.parse(environmentJSON);if(!Array.isArray(args)||args.some(v=>typeof v!=='string')||!env||typeof env!=='object'||Array.isArray(env)||Object.values(env).some(v=>typeof v!=='string'))throw Error('参数应为字符串数组,环境变量应为字符串键值对象');if(live)await api.saveSiteStartup(projectId,site.id,{...config,arguments:args,environment:env as Record<string,string>});setConfig({...config,arguments:args,environment:env as Record<string,string>});setNotice(site.status==='awaiting_upload'?'设置已保存,部署时生效':'设置已应用,原先停止的网站保持停止')}catch(e){setError(e instanceof Error?e.message:'保存失败')}finally{setBusy(false)}}
|
||||
return <ModalBackdrop className="modal-backdrop"><section className="batch-modal startup-modal" role="dialog" aria-modal="true" aria-label="环境变量与启动设置"><header className="batch-heading"><h2>{site.name} · 启动设置</h2><button onClick={onClose}>关闭启动设置</button></header><p>保存会重启运行中的网站,已停止的网站保持停止。PORT、PATH 等系统保留变量不可覆盖。</p><form onSubmit={e=>{e.preventDefault();void save()}}>{busy&&!loaded?<p role="status">正在读取启动配置…</p>:null}{error?<div className="form-error" role="alert">{error}{!loaded?<button type="button" className="secondary" disabled={busy} onClick={()=>setRetry(v=>v+1)}>重新读取配置</button>:null}</div>:null}<fieldset disabled={busy||!loaded}><div className="batch-controls"><label>入口文件<input value={config.entryFile} title={site.runtime==='PHP'?'PHP 使用网站运行目录和默认首页,无独立程序入口':undefined} disabled={site.runtime==='PHP'} onChange={e=>setConfig({...config,entryFile:e.target.value})}/></label><label>工作子目录<input value={config.workDir} title={site.runtime==='PHP'?'PHP 使用网站运行目录和默认首页,无独立程序入口':undefined} disabled={site.runtime==='PHP'} onChange={e=>setConfig({...config,workDir:e.target.value})}/></label></div>{site.runtime!=='PHP'?<label>启动参数 JSON<textarea rows={5} value={argumentsJSON} onChange={e=>setArguments(e.target.value)}/></label>:null}<label className="batch-check"><input type="checkbox" checked={show} onChange={e=>setShow(e.target.checked)}/>显示 / 编辑环境变量值</label>{show?<label>环境变量 JSON<textarea rows={8} value={environmentJSON} onChange={e=>setEnvironment(e.target.value)}/></label>:<p>已配置 {Object.keys(config.environment||{}).length} 个变量,值已隐藏。</p>}{notice?<p role="status">{notice}</p>:null}<button className="primary" disabled={busy||!loaded}>{busy&&loaded?'正在保存…':'保存并应用启动配置'}</button></fieldset></form></section></ModalBackdrop>
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {api,type ControlNode} from '../api';
|
||||
export function SystemScheduler(){const[node,setNode]=useState(0),[nodes,setNodes]=useState<ControlNode[]>([]),[last,setLast]=useState(''),[message,setMessage]=useState(''),[busy,setBusy]=useState(false);
|
||||
useEffect(()=>{Promise.all([api.nodes(),api.scheduler()]).then(([n,s])=>{setNodes(n.nodes);setNode(s.nodeId||n.nodes.find(v=>v.enabled)?.id||0);setLast(s.lastTick||'')}).catch(e=>setMessage(e.message))},[]);
|
||||
return <section className="settings-card system-scheduler"><h2>系统调度器</h2><label>触发节点<select value={node} onChange={e=>setNode(Number(e.target.value))}>{nodes.filter(n=>n.enabled).map(n=><option key={n.id} value={n.id}>{n.name}</option>)}</select></label><p>最近触发:{last?new Date(last).toLocaleString('zh-CN'):'尚未触发'}</p><button className="primary" disabled={busy||!node} onClick={async()=>{setBusy(true);try{await api.configureScheduler(node);setMessage('已配置,每分钟自动触发')}catch(e){setMessage(e instanceof Error?e.message:'配置失败')}finally{setBusy(false)}}}>配置 / 检查宝塔计划任务</button>{message?<p role="status">{message}</p>:null}</section>
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import {useState} from 'react';
|
||||
import {KeyRound,Mail,ShieldCheck} from 'lucide-react';
|
||||
import type {AdminSettings} from '../api';
|
||||
import {PageHeader} from './UI';
|
||||
import {SystemScheduler} from './SystemScheduler';
|
||||
|
||||
export function SystemSettingsForm({settings,save}:{settings:AdminSettings;save:(v:AdminSettings)=>Promise<void>}){
|
||||
const [value,setValue]=useState(settings),[busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const updateSSO=(patch:Partial<AdminSettings['oidc']>)=>setValue(v=>({...v,oidc:{...v.oidc,...patch}}));
|
||||
const passwordUser=value.oidc.userPasswordLogin!==false,passwordAdmin=value.oidc.adminPasswordLogin!==false;
|
||||
return <section className="admin-page settings-page"><PageHeader title="系统设置"/><SystemScheduler/>
|
||||
<form className="settings-layout" onSubmit={async e=>{e.preventDefault();setBusy(true);setError('');try{await save(value)}catch(e){setError(e instanceof Error?e.message:'系统设置保存失败')}finally{setBusy(false)}}}>
|
||||
<fieldset disabled={busy} className="settings-fields">
|
||||
<section className="settings-card"><header><ShieldCheck size={19}/><h2>域名与生命周期</h2></header>
|
||||
<SettingCheck checked={value.domainApproval} change={v=>setValue({...value,domainApproval:v})} title="自定义域名需要审核" note="默认主机域名无需审核"/>
|
||||
<SettingCheck checked={value.filingRequired} change={v=>setValue({...value,filingRequired:v})} title="启用备案引导" note="自定义域名须先通过备案审核"/>
|
||||
<SettingField label="平台 CDN CNAME 目标" value={value.cdnCnameTarget} change={v=>setValue({...value,cdnCnameTarget:v})} placeholder="可选"/>
|
||||
<div className="setting-numbers">{[['宽限期',value.graceDays],['回收保留',value.recycleDays],['备份保留',value.backupRetentionDays]].map(([label,n])=><label key={label}>{label}<input value={n} readOnly/><small>天</small></label>)}</div></section>
|
||||
<section className="settings-card"><header><Mail size={19}/><h2>SMTP 管理员通知</h2></header>
|
||||
<SettingCheck checked={value.smtp.enabled} change={v=>setValue({...value,smtp:{...value.smtp,enabled:v}})} title="启用邮件通知" note="服务异常、安全事件和资源超限通知"/>
|
||||
<div className="settings-grid">{([['host','SMTP 主机'],['port','端口'],['username','用户名'],['from','发件地址'],['adminRecipients','管理员收件人']] as const).map(([key,label])=><SettingField key={key} label={label} value={String(value.smtp[key]||'')} type={key==='port'?'number':'text'} change={v=>setValue({...value,smtp:{...value.smtp,[key]:key==='port'?Number(v):v}})}/>)}
|
||||
<SettingField label="SMTP 密码" type="password" value={value.smtp.secret||''} placeholder={value.smtp.secretConfigured?'已保存;留空保持不变':''} change={v=>setValue({...value,smtp:{...value.smtp,secret:v}})}/></div>
|
||||
<SettingCheck checked={value.smtp.startTls} change={v=>setValue({...value,smtp:{...value.smtp,startTls:v}})} title="启用 STARTTLS" note="465 端口使用隐式 TLS;其他认证连接使用 STARTTLS"/></section>
|
||||
<section className="settings-card sso-settings"><header><KeyRound size={19}/><h2>SSO 登录</h2></header>
|
||||
<SettingCheck checked={value.oidc.enabled} change={enabled=>updateSSO({enabled})} title="启用 OIDC 登录" note="使用已绑定的第三方身份登录"/>
|
||||
<div className="settings-grid">{([['issuer','Issuer URL'],['clientId','Client ID'],['redirectUri','回调地址']] as const).map(([key,label])=><SettingField key={key} label={label} value={value.oidc[key]} change={v=>updateSSO({[key]:v})}/>)}
|
||||
<SettingField label="Client Secret" type="password" value={value.oidc.secret||''} placeholder={value.oidc.secretConfigured?'已保存;留空保持不变':''} change={secret=>updateSSO({secret})}/></div>
|
||||
<div className="sso-policy-grid"><SettingCheck checked={value.oidc.autoCreate===true} change={autoCreate=>updateSSO({autoCreate,bindingOnly:!autoCreate})} title="允许首次 SSO 登录创建用户" note="前台可选择创建普通用户或绑定已有账号,不开通主机、不按邮箱合并"/>
|
||||
<SettingCheck checked={passwordUser} change={userPasswordLogin=>updateSSO({userPasswordLogin,passwordLogin:userPasswordLogin})} title="允许普通用户密码登录" note="关闭后普通用户须使用已绑定的 SSO 身份"/>
|
||||
<SettingCheck checked={passwordAdmin} change={adminPasswordLogin=>updateSSO({adminPasswordLogin})} title="允许管理员密码登录" note="关闭前须先为当前管理员绑定有效 SSO 身份"/></div>
|
||||
<p className="settings-hint">主机账号不支持 SSO,始终保留独立密码登录。关闭 SSO 前须先恢复管理员和用户的密码登录。</p>
|
||||
</section></fieldset>
|
||||
{error?<p className="form-error" role="alert">{error}</p>:null}<div className="settings-submit"><button className="primary" disabled={busy}>{busy?'保存中…':'保存系统设置'}</button></div></form></section>
|
||||
}
|
||||
function SettingCheck({checked,change,title,note}:{checked:boolean;change:(v:boolean)=>void;title:string;note:string}){return <label className="check-row"><input type="checkbox" checked={checked} onChange={e=>change(e.target.checked)}/><span><b>{title}</b><small>{note}</small></span></label>}
|
||||
function SettingField({label,value,change,type='text',placeholder=''}:{label:string;value:string;change:(v:string)=>void;type?:string;placeholder?:string}){return <label>{label}<input type={type} value={value} onChange={e=>change(e.target.value)} placeholder={placeholder} autoComplete={type==='password'?'new-password':'off'}/></label>}
|
||||
@@ -0,0 +1,21 @@
|
||||
import {ChevronLeft, ChevronRight} from 'lucide-react';
|
||||
import type {ComponentProps,ReactNode} from 'react';
|
||||
import type {Runtime} from '../types';
|
||||
|
||||
export function PageHeader({title,actions}:{title:string;description?:string;actions?:ReactNode}){
|
||||
return <div className="page-heading unified-heading"><div><h1>{title}</h1></div>{actions?<div className="page-heading-actions">{actions}</div>:null}</div>;
|
||||
}
|
||||
|
||||
export function RuntimeMark({runtime}:{runtime:Runtime}){
|
||||
const kind=runtime==='Node.js'?'node':runtime.toLowerCase();
|
||||
return <span className={`runtime-mark ${kind}`} aria-hidden="true">{({'PHP':'PHP','Node.js':'JS',Python:'PY',Go:'GO',Java:'JA'} as Record<Runtime,string>)[runtime]}</span>;
|
||||
}
|
||||
|
||||
export function SelectionCheckbox({mixed=false,...props}:ComponentProps<'input'>&{mixed?:boolean}){
|
||||
return <input {...props} type="checkbox" aria-checked={mixed?'mixed':props.checked} ref={element=>{if(element)element.indeterminate=mixed}}/>;
|
||||
}
|
||||
|
||||
export function Pagination({total,page,pageSize,onPage,onPageSize}:{total:number;page:number;pageSize:number;onPage:(value:number)=>void;onPageSize:(value:number)=>void}){
|
||||
const pages=Math.max(1,Math.ceil(total/pageSize));
|
||||
return <footer className="table-pagination"><label>每页显示<select aria-label="每页条数" value={pageSize} onChange={e=>onPageSize(Number(e.target.value))}>{[10,20,50].map(v=><option key={v} value={v}>{v}</option>)}</select>条</label><span>共 {total} 条记录</span><div><button title={page<=1?'已经是第一页':'上一页'} aria-label="上一页" disabled={page<=1} onClick={()=>onPage(page-1)}><ChevronLeft size={16}/></button><span aria-live="polite">{page} / {pages}</span><button title={page>=pages?'已经是最后一页':'下一页'} aria-label="下一页" disabled={page>=pages} onClick={()=>onPage(page+1)}><ChevronRight size={16}/></button></div></footer>;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import {useState} from 'react';
|
||||
import type {DomainResource} from '../api';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
|
||||
export function UnbindDomainDialog({domain,onClose,onUnbind}:{domain:DomainResource;onClose:()=>void;onUnbind:()=>Promise<void>}){
|
||||
const [value,setValue]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
return <ModalBackdrop><form className="tenant-modal" onSubmit={async e=>{e.preventDefault();if(busy||value!==domain.domain)return;setBusy(true);setError('');try{await onUnbind();onClose()}catch(e){setError(e instanceof Error?e.message:'解绑失败')}finally{setBusy(false)}}}><h2>解绑自定义域名</h2><p>移除宝塔中的域名绑定及 Sea vHost 创建的托管 DNS 记录。网站文件、数据库、证书和其他域名保留;重新绑定需遵循当前审核规则。</p><label>输入域名确认解绑<input aria-label="输入域名确认解绑" autoComplete="off" value={value} onChange={e=>setValue(e.target.value)} disabled={busy} placeholder={domain.domain}/></label>{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={onClose}>取消</button><button className="primary danger-confirm" disabled={busy||value!==domain.domain}>{busy?'正在解绑…':'确认解绑'}</button></div></form></ModalBackdrop>
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import {useConfirmation} from './Confirmation';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {PageHeader} from './UI';
|
||||
import {useEffect,useState,type FormEvent} from 'react';
|
||||
import {api,type UserSchedule,type ScheduleRun} from '../api';
|
||||
import type {Project,Site} from '../types';
|
||||
const blank:UserSchedule={id:0,projectId:0,siteId:0,name:'',cron:'*/5 * * * *',timezone:'Asia/Shanghai',kind:'php',version:'',target:'',arguments:[],useHTTPS:false,enabled:true,nextRunAt:'',lastState:'ready'};
|
||||
export function UserSchedules({projects,live}:{projects:Project[];live:boolean}){
|
||||
const {confirm,confirmation}=useConfirmation();
|
||||
const [items,setItems]=useState<UserSchedule[]>([]),[draft,setDraft]=useState<UserSchedule>(),[sites,setSites]=useState<Site[]>([]),[args,setArgs]=useState('[]'),[error,setError]=useState(''),[notice,setNotice]=useState(''),[busy,setBusy]=useState(false),[runs,setRuns]=useState<ScheduleRun[]>(),[versions,setVersions]=useState<Record<string,string[]>>({});
|
||||
const refresh=()=>live?api.schedules().then(v=>setItems(v.schedules)):Promise.resolve();
|
||||
useEffect(()=>{refresh().catch(e=>setError(e.message))},[live]);
|
||||
useEffect(()=>{if(!draft?.projectId){setSites([]);return};let active=true;if(live)Promise.all([api.projectSites(draft.projectId),api.runtimeCatalog(draft.projectId)]).then(([s,c])=>{if(active){setSites(s.sites);setVersions(c.versions)}}).catch(e=>{if(active)setError(e.message)});return()=>{active=false}},[draft?.projectId,live]);
|
||||
const act=async(fn:()=>Promise<unknown>,success='')=>{setBusy(true);setError('');setNotice('');try{await fn();await refresh();if(success)setNotice(success)}catch(e){setError(e instanceof Error?e.message:'操作失败')}finally{setBusy(false)}};
|
||||
const edit=(v:UserSchedule)=>{setDraft({...v});setArgs(JSON.stringify(v.arguments));setError('')};
|
||||
const submit=(event:FormEvent)=>{event.preventDefault();if(!draft)return;void act(async()=>{const argumentsValue:unknown=JSON.parse(args);if(!Array.isArray(argumentsValue)||argumentsValue.some(v=>typeof v!=='string'))throw Error('启动参数必须为 JSON 字符串数组');await api.saveSchedule({...draft,arguments:argumentsValue});setDraft(undefined)})};
|
||||
const runtime=draft?({php:'PHP',python:'Python',node:'Node.js'} as Record<string,string>)[draft.kind]:'';
|
||||
return <div className="page resource-page">{confirmation}<PageHeader title="计划任务" description="为名下网站安排脚本与本站 URL 任务。每个用户最多 10 条,单次最长 5 分钟。" actions={<button className="primary" onClick={()=>edit({...blank,projectId:projects[0]?.id||0})} title={!projects.length?'需先分配可用主机':items.length>=10?'每用户最多 10 条任务':undefined} disabled={items.length>=10||!projects.length}>新增任务</button>}/>{error?<p role="alert" className="resource-error">{error}</p>:null}{notice?<p role="status" className="environment-message success">{notice}</p>:null}
|
||||
<section className="resource-table"><div className="table-scroll"><table><thead><tr><th>名称 / 网站</th><th>时间</th><th>状态 / 下次执行</th><th>操作</th></tr></thead><tbody>{items.map(v=><tr key={v.id}><td>{v.name}<small>主机 #{v.projectId} · 网站 #{v.siteId}</small></td><td><code>{v.cron}</code><small>{v.timezone}</small></td><td>{v.enabled?'启用':'暂停'} · {stateLabel(v.lastState)}<small>{new Date(v.nextRunAt).toLocaleString('zh-CN')}</small></td><td><span className="row-actions"><button disabled={busy} onClick={()=>edit(v)}>编辑</button><button title={v.lastState==='ownership_paused'?'主机归属已变化,请先编辑并重新启用任务':busy?'操作处理中':undefined} disabled={busy||v.lastState==='ownership_paused'} onClick={()=>void act(()=>api.runSchedule(v.id),'已排队,将在下一次系统调度时执行。')}>执行一次</button><button disabled={busy} onClick={()=>void act(async()=>setRuns((await api.scheduleRuns(v.id)).runs))}>执行记录</button><button disabled={busy} onClick={async()=>{if(await confirm('删除此计划任务及其执行记录?',{title:'删除计划任务',danger:true}))void act(()=>api.deleteSchedule(v.id))}}>删除</button></span></td></tr>)}</tbody></table>{!items.length?<p className="resource-empty">暂无计划任务</p>:null}</div></section>
|
||||
{draft?<ModalBackdrop className="modal-backdrop"><section className="modal" role="dialog" aria-modal="true" aria-label="计划任务配置"><header><h2>{draft.id?'编辑':'新增'}计划任务</h2><button onClick={()=>setDraft(undefined)}>关闭</button></header><form onSubmit={submit} className="form-grid"><label>任务名称<input required maxLength={120} value={draft.name} onChange={e=>setDraft({...draft,name:e.target.value})}/></label><label>主机<select value={draft.projectId} onChange={e=>setDraft({...draft,projectId:Number(e.target.value),siteId:0,version:''})}><option value="0">请选择</option>{projects.map(p=><option key={p.id} value={p.id}>{p.hostName} · {p.name}</option>)}</select></label><label>网站<select required value={draft.siteId||''} onChange={e=>setDraft({...draft,siteId:Number(e.target.value)})}><option value="">请选择</option>{sites.map(s=><option key={s.id} value={s.id}>{s.domain}</option>)}</select></label><label>任务类型<select value={draft.kind} onChange={e=>setDraft({...draft,kind:e.target.value,version:'',arguments:[]})}>{[['php','PHP 脚本'],['python','Python 脚本'],['node','Node 脚本'],['url','访问本站 URL']].map(([v,l])=><option key={v} value={v}>{l}</option>)}</select></label>{draft.kind!=='url'?<label>运行版本<select required value={draft.version} onChange={e=>setDraft({...draft,version:e.target.value})}><option value="">请选择已安装版本</option>{(versions[runtime]||[]).map(v=><option key={v}>{v}</option>)}</select></label>:null}<label>{draft.kind==='url'?'本站 URL 路径':'相对于网站运行目录的脚本路径'}<input required value={draft.target} onChange={e=>setDraft({...draft,target:e.target.value})}/></label><label>Cron 表达式<input required value={draft.cron} onChange={e=>setDraft({...draft,cron:e.target.value})}/></label><label>时区<input required value={draft.timezone} onChange={e=>setDraft({...draft,timezone:e.target.value})}/></label>{draft.kind!=='url'?<label>启动参数(JSON 数组)<textarea value={args} onChange={e=>setArgs(e.target.value)}/></label>:<label><input type="checkbox" checked={draft.useHTTPS} onChange={e=>setDraft({...draft,useHTTPS:e.target.checked})}/>使用 HTTPS</label>}<label><input type="checkbox" checked={draft.enabled} onChange={e=>setDraft({...draft,enabled:e.target.checked})}/>启用定时执行</label>{error?<p role="alert">{error}</p>:null}<p>“执行一次”会排队,在下一次系统调度时执行。</p><button type="submit" className="primary" disabled={busy||!draft.siteId}>保存</button></form></section></ModalBackdrop>:null}
|
||||
{runs?<ModalBackdrop className="modal-backdrop"><section className="modal" role="dialog" aria-modal="true" aria-label="执行记录"><header><h2>最近执行记录</h2><button onClick={()=>setRuns(undefined)}>关闭</button></header>{runs.length?runs.map(v=><article key={v.id}><p>{new Date(v.startedAt).toLocaleString('zh-CN')} · {stateLabel(v.state)} · 退出码 {v.exitCode??'—'}</p><pre className="site-log-view">{v.output||'无输出'}</pre></article>):<p>暂无执行记录</p>}</section></ModalBackdrop>:null}</div>
|
||||
}
|
||||
function stateLabel(v:string){return ({ready:'待执行',running:'执行中',succeeded:'成功',failed:'失败',uncertain:'结果待核验',skipped:'已跳过',ownership_paused:'主机归属变更,已暂停'} as Record<string,string>)[v]||v}
|
||||
@@ -0,0 +1,26 @@
|
||||
import {useEffect,type Dispatch,type SetStateAction} from 'react';
|
||||
|
||||
let locks=0,previousOverflow='',previousPadding='';
|
||||
export function lockBackgroundScroll(){
|
||||
if(!locks){previousOverflow=document.body.style.overflow;previousPadding=document.body.style.paddingRight;const gap=window.innerWidth-document.documentElement.clientWidth;document.body.style.overflow='hidden';if(gap>0)document.body.style.paddingRight=gap+'px'}
|
||||
locks++;let released=false;
|
||||
return()=>{if(released)return;released=true;locks--;if(!locks){document.body.style.overflow=previousOverflow;document.body.style.paddingRight=previousPadding}};
|
||||
}
|
||||
|
||||
export function useNavigationOverlay(open:boolean,setOpen:Dispatch<SetStateAction<boolean>>){
|
||||
useEffect(()=>{
|
||||
if(!open)return;
|
||||
const release=lockBackgroundScroll(),previous=document.activeElement instanceof HTMLElement?document.activeElement:null;
|
||||
const drawer=document.querySelector<HTMLElement>('.admin-sidebar.open,.mobile-sidebar.open .sidebar');
|
||||
const frame=requestAnimationFrame(()=>drawer?.querySelector<HTMLButtonElement>('nav button')?.focus({preventScroll:true}));
|
||||
function keydown(e:KeyboardEvent){
|
||||
if(document.querySelector('.modal-backdrop'))return;
|
||||
if(e.key==='Escape'){e.preventDefault();setOpen(false);return}
|
||||
if(e.key!=='Tab'||!drawer)return;
|
||||
const items=[...drawer.querySelectorAll<HTMLButtonElement>('nav button')].filter(b=>!b.disabled),first=items[0],last=items.at(-1);
|
||||
if(e.shiftKey&&(document.activeElement===first||!drawer.contains(document.activeElement))){e.preventDefault();last?.focus()}else if(!e.shiftKey&&(document.activeElement===last||!drawer.contains(document.activeElement))){e.preventDefault();first?.focus()}
|
||||
}
|
||||
document.addEventListener('keydown',keydown);
|
||||
return()=>{cancelAnimationFrame(frame);document.removeEventListener('keydown',keydown);release();if(previous?.isConnected)previous.focus({preventScroll:true})};
|
||||
},[open,setOpen]);
|
||||
}
|
||||
Reference in new issue
Block a user