feat: import Sea vHost single-server testing release

This commit is contained in:
canglan committed 2026-10-30 08:39:10 +08:00
commit 248badd33e
441 files changed
+63221

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#0878f9" />
<meta name="description" content="Sea vHost 多租户虚拟主机控制台" />
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' rx='9' fill='%230878f9'/%3E%3Cpath d='M5 12c3-3 6-3 10 0s6 3 10 0 6-3 10 0M5 20c3-3 6-3 10 0s6 3 10 0 6-3 10 0M5 28c3-3 6-3 10 0s6 3 10 0 6-3 10 0' fill='none' stroke='white' stroke-width='2' stroke-linecap='round'/%3E%3C/svg%3E" />
<title>Sea vHost</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+2382
View File
File diff suppressed because it is too large. Load diff
+29
View File
@@ -0,0 +1,29 @@
{
"name": "sea-vhost-web",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0",
"build": "tsc -b && vite build",
"preview": "vite preview --host 0.0.0.0",
"test": "vitest run"
},
"dependencies": {
"@vitejs/plugin-react": "latest",
"lucide-react": "latest",
"react": "latest",
"react-dom": "latest"
},
"devDependencies": {
"@testing-library/jest-dom": "latest",
"@testing-library/react": "latest",
"@types/react": "latest",
"@types/react-dom": "latest",
"jsdom": "latest",
"playwright": "^1.63.0",
"typescript": "latest",
"vite": "latest",
"vitest": "latest"
}
}
+17
View File
@@ -0,0 +1,17 @@
import {afterEach,expect,it,vi} from 'vitest';
import {api,type AdminSettings} from './api';
afterEach(()=>vi.unstubAllGlobals());
it('can save a read settings object without returning readonly server metadata',async()=>{
const fetch=vi.fn().mockResolvedValue(new Response(null,{status:204}));vi.stubGlobal('fetch',fetch);
const settings:AdminSettings={domainApproval:true,filingRequired:false,cdnCnameTarget:'',graceDays:3,recycleDays:7,backupRetentionDays:14,smtp:{enabled:false,host:'mail.example.invalid',port:465,username:'test',from:'',adminRecipients:'',startTls:true,secretConfigured:true},oidc:{enabled:false,issuer:'',clientId:'',redirectUri:'',secretConfigured:true,bindingOnly:true,passwordLogin:true}};
await api.saveAdminSettings(settings);
const body=JSON.parse(fetch.mock.calls[0][1].body);
expect(body.smtp).not.toHaveProperty('secretConfigured');expect(body.oidc).not.toHaveProperty('secretConfigured');expect(body.oidc).not.toHaveProperty('bindingOnly');expect(body.oidc).not.toHaveProperty('passwordLogin');
expect(body.smtp).not.toHaveProperty('secret');expect(body.oidc).not.toHaveProperty('secret');expect(body.smtp.host).toBe(settings.smtp.host);expect(body.graceDays).toBe(3);
});
it('sends SSO login policies without readonly metadata',async()=>{
const fetch=vi.fn().mockResolvedValue(new Response(null,{status:204}));vi.stubGlobal('fetch',fetch);
const input={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:true,issuer:'https://id.example.invalid',clientId:'vhost',redirectUri:'https://control.example.invalid/api/v1/auth/oidc/callback',secretConfigured:true,bindingOnly:false,passwordLogin:false,autoCreate:true,userPasswordLogin:false,adminPasswordLogin:true}} satisfies AdminSettings;
await api.saveAdminSettings(input);const body=JSON.parse(fetch.mock.calls[0][1].body);expect(body.oidc).toMatchObject({autoCreate:true,userPasswordLogin:false,adminPasswordLogin:true});expect(body.oidc).not.toHaveProperty('secretConfigured');
});
+72
View File
@@ -0,0 +1,72 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {PlanForm,Plans,NetworkForm,AdminConsole} from './components/AdminConsole';
import {AdminDomains,DomainPolicyForm} from './components/AdminDomains';
import {AdminLogs} from './components/AdminLogs';
import {ResourceCenter} from './components/ResourceCenter';
import {api,type AdminProject,type DomainResource,type User} from './api';
import {demoPlan} from './data';
import {initialProjects} from './data';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
it('retains a rejected plan form and explains the failure',async()=>{
const create=vi.fn().mockRejectedValue(new Error('套餐名称重复'));
render(<PlanForm onCreate={create} onClose={vi.fn()}/>);fireEvent.change(screen.getByLabelText('套餐名称'),{target:{value:'重复套餐'}});fireEvent.click(screen.getByRole('button',{name:'创建套餐'}));
expect(await screen.findByRole('alert')).toHaveTextContent('套餐名称重复');expect(screen.getByLabelText('套餐名称')).toHaveValue('重复套餐');expect(screen.getByRole('button',{name:'创建套餐'})).toBeEnabled();
});
it('shows a network save failure instead of closing or silently rejecting',async()=>{
render(<NetworkForm project={{id:1,hostName:'sv1111111111',nodeId:1,httpPort:80,httpsPort:443,dedicatedIp:false} as AdminProject} ips={[]} onClose={vi.fn()} onSave={vi.fn().mockRejectedValue(new Error('端口冲突'))}/>);
fireEvent.click(screen.getByRole('button',{name:'保存网络配置'}));expect(await screen.findByRole('alert')).toHaveTextContent('端口冲突');expect(screen.getByRole('button',{name:'保存网络配置'})).toBeEnabled();
});
it('blocks default settings from being edited after an initial admin read failure',async()=>{
vi.spyOn(api,'adminOverview').mockRejectedValue(new Error('管理数据读取失败'));vi.spyOn(api,'adminSettings').mockRejectedValue(new Error('设置读取失败'));
render(<AdminConsole user={{displayName:'管理员',role:'admin'} as User} tenants={[]} plans={[demoPlan]} pendingDomains={[]} approval onApproval={vi.fn()} onReviewDomain={vi.fn()} onCreate={vi.fn()} onCreatePlan={vi.fn()} onLogout={vi.fn()} onSecurity={vi.fn()}/>);
expect(await screen.findByRole('alert')).toHaveTextContent('读取失败');expect(screen.getByRole('button',{name:'重新读取管理数据'})).toBeEnabled();expect(screen.queryByRole('heading',{name:'平台总览'})).not.toBeInTheDocument();
});
it('reports a rejected domain action and preserves the current approval switch',async()=>{
render(<AdminDomains domains={[]} approval approvalChange={vi.fn().mockRejectedValue(new Error('策略保存失败'))} review={vi.fn()} metadata={vi.fn()} dns={vi.fn()}/>);
fireEvent.click(screen.getByRole('switch',{name:'自定义域名审核'}));expect(await screen.findByRole('alert')).toHaveTextContent('策略保存失败');expect(screen.getByRole('switch')).toBeChecked();
});
it('saves explicit filing exemptions and preserves the form on rejection',async()=>{
const save=vi.fn().mockRejectedValue(new Error('配置未保存'));
render(<DomainPolicyForm domain={{id:1,domain:'qa.example.invalid',resolutionMode:'cname',cnameTarget:'host.example.invalid',filingStatus:'approved'} as DomainResource} onClose={vi.fn()} onSave={save}/>);
fireEvent.change(screen.getByLabelText('备案状态'),{target:{value:'exempt'}});fireEvent.click(screen.getByRole('button',{name:'保存域名配置'}));
expect(await screen.findByRole('alert')).toHaveTextContent('配置未保存');expect(save).toHaveBeenCalledWith(expect.objectContaining({filingStatus:'exempt',cnameTarget:'host.example.invalid'}));
});
it('filters admin audit records on the server and disables empty exports',async()=>{
const fetch=vi.spyOn(api,'adminAudit').mockResolvedValue({logs:[],total:0,page:1,limit:100});
render(<AdminLogs logs={[]} refresh={vi.fn()}/>);
fireEvent.change(screen.getByLabelText('搜索日志'),{target:{value:'不存在的日志'}});
await waitFor(()=>expect(fetch).toHaveBeenCalled());expect(await screen.findByText('暂无操作日志')).toBeInTheDocument();expect(screen.getByRole('button',{name:'导出 JSON'})).toBeDisabled();
expect(fetch.mock.calls.at(-1)?.[0].get('q')).toBe('不存在的日志');
fireEvent.change(screen.getByLabelText('每页条数'),{target:{value:'200'}});await waitFor(()=>expect(fetch.mock.calls.at(-1)?.[0].get('limit')).toBe('200'));
});
it('does not manufacture live database rows when resource loading fails and supports retry',async()=>{
vi.spyOn(api,'resources').mockRejectedValueOnce(new Error('资源读取失败')).mockResolvedValueOnce({sites:[],domains:[],ftpAccounts:[],databases:[]});
render(<ResourceCenter page="databases" projects={[]} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
expect(await screen.findByRole('alert')).toHaveTextContent('资源读取失败');expect(screen.queryByText('进入 phpMyAdmin')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'刷新资源'}));await waitFor(()=>expect(screen.getByText('暂无数据库')).toBeInTheDocument());
});
it('copies exact plan quotas into a new editable form without changing the source',async()=>{
const save=vi.fn().mockResolvedValue(undefined);const plan={...demoPlan,storageBytes:123*1024**2,bandwidthMbps:7,projectLimit:2};
render(<Plans plans={[plan]} create={vi.fn()} save={save}/>);fireEvent.click(screen.getByRole('button',{name:'复制套餐 '+plan.name}));
expect(screen.getByLabelText('套餐名称')).toHaveValue(plan.name+' 副本');fireEvent.click(screen.getByRole('button',{name:'保存为新套餐'}));
await waitFor(()=>expect(save).toHaveBeenCalledWith(expect.objectContaining({name:plan.name+' 副本',storageBytes:plan.storageBytes,bandwidthMbps:7,projectLimit:2})));
expect(plan.name).toBe(demoPlan.name);
});
it('explains plan deletion restrictions and retains a rejected deletion dialog',async()=>{
vi.spyOn(api,'deletePlan').mockRejectedValue(new Error('套餐刚被主机使用'));
render(<Plans plans={[{...demoPlan,id:1,deleteBlockedReason:'系统默认套餐不能删除'},{...demoPlan,id:5,name:'可删除套餐'}]} create={vi.fn()} save={vi.fn()}/>);
expect(screen.getByRole('button',{name:'删除套餐 '+demoPlan.name})).toBeDisabled();fireEvent.click(screen.getByRole('button',{name:'删除套餐 可删除套餐'}));expect(screen.getByRole('button',{name:'确认删除套餐'})).toBeDisabled();fireEvent.change(screen.getByLabelText('输入套餐名称确认删除'),{target:{value:'可删除套餐'}});fireEvent.click(screen.getByRole('button',{name:'确认删除套餐'}));expect(await screen.findByRole('alert')).toHaveTextContent('套餐刚被主机使用');
});
it('unbinds only a confirmed custom domain and never offers assigned-domain removal',async()=>{
const domain={id:9,domain:'custom.example.invalid',kind:'custom',status:'pending'} as DomainResource;const unbind=vi.fn().mockResolvedValue(undefined);
render(<AdminDomains domains={[domain,{...domain,id:10,domain:'assigned.example.invalid',kind:'assigned'}]} approval approvalChange={vi.fn()} review={vi.fn()} metadata={vi.fn()} dns={vi.fn()} unbind={unbind}/>);
expect(screen.getAllByRole('button',{name:/^解绑$/})).toHaveLength(1);fireEvent.click(screen.getByRole('button',{name:/^解绑$/}));expect(screen.getByRole('button',{name:'确认解绑'})).toBeDisabled();fireEvent.change(screen.getByLabelText('输入域名确认解绑'),{target:{value:domain.domain}});fireEvent.click(screen.getByRole('button',{name:'确认解绑'}));await waitFor(()=>expect(unbind).toHaveBeenCalledWith(domain));
});
it('shows effective FTP quota suspension separately from the saved enable switch',async()=>{
const project={...initialProjects[0],status:'quota_suspended' as const};vi.spyOn(api,'resources').mockResolvedValue({sites:[],domains:[],databases:[],ftpAccounts:[{id:1,projectId:project.id,hostName:project.hostName,projectName:project.name,username:project.hostName,rootPath:project.path,createdAt:project.createdAt,enabled:true}]});
render(<ResourceCenter page="ftp" projects={[project]} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);expect(await screen.findByText('配额暂停')).toBeInTheDocument();expect(screen.getByText('开关已启用,解除超额后自动恢复')).toBeInTheDocument();expect(screen.getByRole('button',{name:'重置密码'})).toBeDisabled();expect(screen.getByRole('button',{name:'停用'})).toBeEnabled();
});
+55
View File
@@ -0,0 +1,55 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {BatchComposer,BatchJobs} from './components/AdminBatches';
import {api,type AdminBatch,type BatchPreviewRow} from './api';
import {demoPlan} from './data';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
it('describes a start batch as an execution result without claiming it generated passwords',async()=>{
const job:AdminBatch={id:9,administratorId:1,operation:'host_start',state:'completed',total:1,succeeded:1,failed:0,uncertain:0,pending:0,createdAt:new Date().toISOString(),secretsExpireAt:'2099-01-01T00:00:00Z',items:[]};
vi.spyOn(api,'batches').mockResolvedValue({batches:[job]});vi.spyOn(api,'batch').mockResolvedValue({batch:job});
render(<BatchJobs create={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
fireEvent.click(await screen.findByRole('button',{name:'查看结果 #9'}));
expect(await screen.findByRole('link',{name:'下载结果 JSON'})).toHaveAttribute('href','/api/v1/admin/batches/9/download');
expect(screen.getByText(/本次操作不会生成新密码/)).toBeInTheDocument();
expect(screen.queryByRole('link',{name:'下载结果与凭据 JSON'})).not.toBeInTheDocument();
});
it('locks the batch draft while its preview is being verified',async()=>{
let finish!:(value:{rows:BatchPreviewRow[]})=>void;
vi.spyOn(api,'previewBatch').mockReturnValue(new Promise(resolve=>{finish=resolve}));
render(<BatchComposer operation="create_users" users={[]} projects={[]} plans={[demoPlan]} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));
expect(screen.getByLabelText('名称前缀')).toBeDisabled();
expect(screen.getByLabelText('输入方式')).toBeDisabled();
expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled();
finish({rows:[{row:1,label:'user',valid:true,detail:'可以执行'}]});
await waitFor(()=>expect(screen.getByLabelText('名称前缀')).toBeEnabled());
fireEvent.change(screen.getByLabelText('名称前缀'),{target:{value:'changed-name'}});
expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled();
});
it('defaults ownership changes to preserve credentials and stop sites, with explicit alternatives',async()=>{
const preview=vi.spyOn(api,'previewBatch').mockResolvedValue({rows:[{row:1,label:'sv0123456789',valid:true,detail:'可以执行'}]});
render(<BatchComposer operation="assign_hosts" rows={[{hostId:9,ownershipVersion:3}]} users={[]} projects={[]} plans={[demoPlan]} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));await waitFor(()=>expect(preview).toHaveBeenCalledWith('assign_hosts',[expect.objectContaining({hostId:9,ownershipVersion:3,credentialMode:'preserve',stopServices:true,resumeOwnership:false,tenantId:0})]));
fireEvent.change(screen.getByLabelText('凭据处理'),{target:{value:'reset'}});fireEvent.click(screen.getByLabelText('变更前停止全部网站(默认)'));expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled();
fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));await waitFor(()=>expect(preview).toHaveBeenLastCalledWith('assign_hosts',[expect.objectContaining({credentialMode:'reset',stopServices:false})]));
});
it('requires preview before queueing users and only exposes credentials through the explicit download',async()=>{
const preview=vi.spyOn(api,'previewBatch').mockResolvedValue({rows:[{row:1,label:'ui-batch-0001@vhost.ser888.cn',valid:true,detail:'可以执行'}]});
const job:AdminBatch={id:31,administratorId:1,operation:'create_users',state:'completed',total:1,succeeded:1,failed:0,uncertain:0,pending:0,createdAt:new Date().toISOString(),secretsExpireAt:'2099-01-01T00:00:00Z',items:[]};
const submit=vi.spyOn(api,'createBatch').mockResolvedValue({batch:job});vi.spyOn(api,'batch').mockResolvedValueOnce({batch:{...job,state:'running',secretsExpireAt:undefined}}).mockResolvedValue({batch:job});
render(<BatchComposer operation="create_users" users={[]} projects={[]} plans={[demoPlan]} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled();fireEvent.change(screen.getByLabelText('创建数量'),{target:{value:'1'}});fireEvent.change(screen.getByLabelText('名称前缀'),{target:{value:'ui-batch'}});
fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));await waitFor(()=>expect(preview).toHaveBeenCalled());expect(preview.mock.calls[0][1][0]).toMatchObject({slug:'ui-batch-0001',email:'ui-batch-0001@vhost.ser888.cn'});expect(preview.mock.calls[0][1][0].password).toBeUndefined();
fireEvent.click(await screen.findByRole('button',{name:'提交 1 项任务'}));await waitFor(()=>expect(submit).toHaveBeenCalled());expect(submit.mock.calls[0][2]).toMatch(/^[0-9a-f]{32}$/);
expect(await screen.findByText('正在保存任务结果…')).toBeInTheDocument();expect(screen.queryByText('批次凭据已过期')).not.toBeInTheDocument();
expect(await screen.findByRole('link',{name:'下载结果与凭据 JSON'},{timeout:5000})).toHaveAttribute('href','/api/v1/admin/batches/31/download');
});
it('allows a host without a bound user and chooses the installed version after async catalog loading',async()=>{
vi.spyOn(api,'nodes').mockResolvedValue({nodes:[{id:1,name:'本机',transport:'local',endpoint:'local',rootDomain:'vhost.ser888.cn',tenantRoot:'/www/wwwroot/seavHost/vHost',ftpCertificateDomain:'host.ser888.cn',enabled:true,lastError:''}]});
vi.spyOn(api,'panelSites').mockResolvedValue({sites:[],versions:{PHP:['8.4'],'Node.js':[],Python:[],Go:[],Java:[]}});
const preview=vi.spyOn(api,'previewBatch').mockResolvedValue({rows:[{row:1,label:'ui-host-0001',valid:true,detail:'可以执行'}]});
render(<BatchComposer operation="create_hosts" users={[]} projects={[]} plans={[demoPlan]} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
fireEvent.change(screen.getByLabelText('创建数量'),{target:{value:'1'}});fireEvent.change(screen.getByLabelText('名称前缀'),{target:{value:'ui-host'}});await waitFor(()=>expect(screen.getByRole('combobox',{name:'批量运行版本'})).toHaveValue('8.4'));
fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));await waitFor(()=>expect(preview).toHaveBeenCalledWith('create_hosts',[expect.objectContaining({name:'ui-host-0001',tenantId:0,nodeId:1,version:'8.4'})]));
});
+26
View File
@@ -0,0 +1,26 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,within} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {AdminHosts} from './components/AdminHosts';
import type {AdminProject} from './api';
import {demoPlan} from './data';
afterEach(cleanup);
const projects:AdminProject[]=Array.from({length:12},(_,i)=>({id:i+1,tenantName:'用户',hostName:'sv'+String(i).padStart(10,'0'),name:'站点'+i,domain:'site'+i+'.vhost.ser888.cn',path:'/www/wwwroot/test',runPath:'/public',runtime:i%2?'PHP':'Python',version:i%2?'8.4':'3.12.15',status:'running',sslStatus:'off',siteCount:1,dedicatedIp:false,httpPort:80,httpsPort:443,createdAt:'',nodeId:1,planId:demoPlan.id,ownershipVersion:7}));
it('filters hosts, resets the filter and paginates without losing the selected batch target',()=>{
const bulk=vi.fn();render(<AdminHosts projects={projects} query="" setQuery={vi.fn()} network={vi.fn()} adopt={vi.fn()} users={[]} plans={[demoPlan]} refresh={vi.fn()} bulk={bulk}/>);
expect(screen.getAllByRole('checkbox')).toHaveLength(11);
fireEvent.click(screen.getByLabelText('选择主机 '+projects[0].hostName));
expect(screen.getByLabelText('选择本页主机')).toBePartiallyChecked();
fireEvent.click(screen.getByRole('button',{name:'下一页'}));
expect(screen.getAllByRole('checkbox')).toHaveLength(3);
fireEvent.click(screen.getByRole('button',{name:'绑定 / 解绑用户'}));
expect(bulk).toHaveBeenCalledWith({operation:'assign_hosts',rows:[{hostId:1,ownershipVersion:7}]});
fireEvent.change(screen.getByLabelText('筛选运行环境'),{target:{value:'Python'}});
expect(within(screen.getByRole('table')).getAllByRole('row')).toHaveLength(7);
expect(screen.getByText('1 / 1')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'重置'}));
expect(screen.getByText('1 / 2')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'清空选择'}));
expect(screen.getByRole('button',{name:'绑定 / 解绑用户'})).toBeDisabled();
expect(screen.getByLabelText('选择本页主机')).not.toBePartiallyChecked();
});
+319
View File
@@ -0,0 +1,319 @@
import '@testing-library/jest-dom/vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
import {DNSCredentials} from './components/DNSCredentials';
import { App } from './App';
import { AdminConsole } from './components/AdminConsole';
import { InstallWizard } from './components/InstallWizard';
import { Overview } from './components/Overview';
import { StartupError } from './components/StartupError';
import { api } from './api';
import { demoPlan, demoUsage, initialProjects } from './data';
beforeEach(()=>{
vi.spyOn(api,'adminOverview').mockResolvedValue({users:[],projects:[],domains:[],ipAddresses:[],logs:[]});
vi.spyOn(api,'adminSettings').mockResolvedValue({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}});
vi.spyOn(api,'nodes').mockResolvedValue({nodes:[{id:1,name:'本机节点',transport:'local',endpoint:'local',rootDomain:'vhost.ser888.cn',tenantRoot:'/www/wwwroot/seavHost/vHost',ftpCertificateDomain:'host.ser888.cn',enabled:true,lastError:''}]})});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('Sea vHost', () => {
it('opens the create project workflow', () => {
render(<App />);
fireEvent.click(screen.getByRole('button', { name: /创建虚拟主机/ }));
expect(screen.getByRole('heading', { name: '创建虚拟主机' })).toBeInTheDocument();
expect(screen.getByDisplayValue('<随机主机名>.vhost.ser888.cn')).toBeInTheDocument();
expect(screen.getByDisplayValue('/')).toBeInTheDocument();
expect(screen.getAllByDisplayValue('/www/wwwroot/seavHost/vHost/<随机主机名>')).toHaveLength(2);
expect(screen.queryByText('Docker')).not.toBeInTheDocument();
expect(screen.queryByText('容器')).not.toBeInTheDocument();
});
it('lets a tenant configure a host-relative run directory', () => {
render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '主站目录' })[0]);
expect(screen.getByRole('dialog', { name: '设置运行目录' })).toBeInTheDocument();
const input = screen.getByDisplayValue('/public');
fireEvent.change(input, { target: { value: '/../etc' } });
expect(screen.getByRole('button', { name: '保存' })).toBeDisabled();
});
it('opens file management for a selected project', async () => {
render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '文件' })[0]);
expect(screen.getByRole('heading', { name: '文件管理' })).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: '选择虚拟主机' })).toHaveValue('1');
});
it('adds another website with an independent runtime and directory', () => {
render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
expect(screen.getByRole('dialog', { name: '主机网站' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
fireEvent.change(screen.getByLabelText('网站名称'), { target: { value: 'docs-site' } });
fireEvent.change(screen.getByLabelText(/^运行目录/), { target: { value: '/docs' } });
fireEvent.change(screen.getByLabelText('运行环境'), { target: { value: 'Node.js' } });
expect(screen.getByLabelText('版本')).toHaveValue('v24.21.0');
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
expect(screen.getByText('docs-site')).toBeInTheDocument();
expect(screen.getByText('/docs')).toBeInTheDocument();
});
it('checks and deploys an uploaded language project before reporting it running', async () => {
render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
fireEvent.change(screen.getByLabelText('运行环境'), { target: { value: 'Node.js' } });
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
fireEvent.click(screen.getByRole('button', { name: '部署检查 site-two' }));
expect(screen.getByLabelText('入口文件')).toHaveValue('package.json');
fireEvent.click(screen.getByRole('button', { name: '检查文件' }));
expect(await screen.findByText('可以继续')).toBeInTheDocument();
expect(screen.getByRole('status')).toHaveTextContent('创建宝塔语言项目并验证运行状态');
fireEvent.click(screen.getByRole('button', { name: '开始部署' }));
await waitFor(() => expect(screen.queryByLabelText('入口文件')).not.toBeInTheDocument());
expect(screen.getByText('site-two').closest('.sites-row')).toHaveTextContent('运行中');
});
it('installs a manual certificate without retaining the private key form', async () => {
render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
fireEvent.click(screen.getByRole('button', { name: '安装证书 main-site' }));
expect(screen.getByText(/私钥仅用于本次请求/)).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('证书链(PEM)'), { target: { value: '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----' } });
fireEvent.change(screen.getByLabelText('私钥(PEM,无口令)'), { target: { value: '-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----' } });
fireEvent.click(screen.getByRole('button', { name: '校验并安装' }));
await waitFor(() => expect(screen.queryByLabelText('私钥(PEM,无口令)')).not.toBeInTheDocument());
});
it('lets a tenant retry automatic certificate issuance for a managed site', async () => {
render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'HTTP-01 申请证书 main-site' }));
await waitFor(() => expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument());
});
it('lets a tenant explicitly disable SSL and automatic renewal', async () => {
render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
fireEvent.click(screen.getByRole('button', { name: '关闭 SSL main-site' }));
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
await waitFor(() => expect(screen.getByText(/SSL 未启用/)).toBeInTheDocument());
expect(screen.queryByRole('button', { name: '关闭 SSL main-site' })).not.toBeInTheDocument();
});
it('shows reusable FTP and database credentials', () => {
render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '凭据' })[0]);
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).not.toHaveTextContent('FTP 与数据库密码已加密保存');
expect(screen.getByText('demo-ftp-password')).toBeInTheDocument();
expect(screen.getByText('demo-database-password')).toBeInTheDocument();
});
it('resets the independent host login password', async () => {
render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '凭据' })[0]);
fireEvent.click(screen.getByRole('button', { name: '重置主机密码' }));
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
expect(await screen.findByText('demo-host-password-reset')).toBeInTheDocument();
});
it('stops and deletes an additional website without deleting host files', async () => {
render(<App />);
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
fireEvent.click(await screen.findByRole('button', { name: '停止 site-two' }));
expect(await screen.findByRole('button', { name: '启动 site-two' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '删除 site-two' }));
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
await waitFor(()=>expect(screen.queryByText('site-two')).not.toBeInTheDocument());
expect(screen.getByText(/保留主机目录中的文件/)).toBeInTheDocument();
});
it('submits a custom domain for the selected website', async () => {
render(<App />);
fireEvent.click(screen.getByRole('button', { name: '域名' }));
expect(screen.getByRole('heading', { name: '域名' })).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('自定义域名'), { target: { value: 'tenant.example.com' } });
fireEvent.click(screen.getByRole('button', { name: '提交审核' }));
expect(await screen.findByText('tenant.example.com')).toBeInTheDocument();
expect(screen.getByText('待审核')).toBeInTheDocument();
});
it('opens encrypted credentials from the FTP resource page', () => {
render(<App />);
fireEvent.click(screen.getByRole('button', { name: 'FTP' }));
fireEvent.click(screen.getByRole('button', { name: /查看 FTP 凭据 sv8c0a6d2f91/ }));
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).toHaveTextContent('demo-ftp-password');
});
it('opens the mobile navigation and navigates to a resource page', () => {
render(<App />);
const menu = screen.getByRole('button', { name: '打开导航' });
fireEvent.click(menu);
expect(menu).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(screen.getByRole('button', { name: '数据库' }));
expect(screen.getByRole('heading', { name: '数据库' })).toBeInTheDocument();
});
it('offers an encrypted tenant DNS credential form without displaying saved secrets', async () => {
render(<App />);
fireEvent.click(screen.getByRole('button', { name: 'DNS API' }));
expect(screen.getByRole('heading', { name: 'DNS API', level: 1 })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '新增凭据' }));
expect(screen.getByRole('heading', { name: '新增 DNS 凭据' })).toBeInTheDocument();
expect(screen.getByLabelText('API Token')).toHaveAttribute('type', 'password');
fireEvent.change(screen.getByLabelText('DNS 服务商'), { target: { value: 'aliyun' } });
expect(screen.getByLabelText('AccessKey Secret')).toHaveAttribute('type', 'password');
expect(screen.queryByLabelText('Zone ID')).not.toBeInTheDocument();expect(screen.getByRole('button',{name:'加密保存'})).toBeDisabled();
});
it('discovers a DNS zone before saving and testing its credential',async()=>{
const item={id:9,scope:'tenant:1',label:'站点 DNS',provider:'cloudflare' as const,zoneName:'customer.example',testStatus:'untested' as const,createdAt:'',updatedAt:''};
vi.spyOn(api,'dnsCredentials').mockResolvedValue({credentials:[]});
const discover=vi.spyOn(api,'discoverDNSZones').mockResolvedValue({zones:[{id:'zone12345678',name:'customer.example',verificationToken:'proof'}]});
const save=vi.spyOn(api,'createDNSCredential').mockResolvedValue({credential:item});
vi.spyOn(api,'testDNSCredential').mockResolvedValue({credential:{...item,testStatus:'passed'}});
render(<DNSCredentials/>);await waitFor(()=>expect(api.dnsCredentials).toHaveBeenCalled());fireEvent.click(screen.getByRole('button',{name:'新增凭据'}));
fireEvent.change(screen.getByLabelText('凭据名称'),{target:{value:'站点 DNS'}});fireEvent.change(screen.getByLabelText('API Token'),{target:{value:'token-12345678901234567890'}});
expect(screen.getByRole('button',{name:'加密保存'})).toBeDisabled();fireEvent.click(screen.getByRole('button',{name:'读取可管理域名'}));await screen.findByLabelText('选择 DNS 域名');
expect(discover).toHaveBeenCalled();fireEvent.click(screen.getByRole('button',{name:'加密保存'}));await waitFor(()=>expect(save).toHaveBeenCalledWith(expect.objectContaining({zoneName:'customer.example',verificationToken:'proof',credential:{apiToken:'token-12345678901234567890',zoneId:'zone12345678'}}),false));
fireEvent.click(await screen.findByRole('button',{name:'测试 站点 DNS'}));expect(await screen.findByText('测试通过')).toBeInTheDocument();
});});
describe('安装向导', () => {
it('requires connection checks before completing a preview install', async () => {
render(<InstallWizard preview />);
fireEvent.change(screen.getByPlaceholderText('粘贴 SEA_SETUP_TOKEN'), { target: { value: '12345678901234567890123456789012' } });
fireEvent.click(screen.getByRole('button', { name: /继续/ }));
fireEvent.change(screen.getByLabelText(/数据库密码/), { target: { value: 'database-secret' } });
fireEvent.click(screen.getByRole('button', { name: '测试数据库连接' }));
expect(await screen.findByText('连接成功')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /继续/ }));
fireEvent.change(screen.getByLabelText(/宝塔 API 密钥/), { target: { value: '12345678901234567890123456789012' } });
fireEvent.click(screen.getByRole('button', { name: '检查服务器组件' }));
expect(await screen.findByText('面板代理与隔离代理均正常')).toBeInTheDocument();
expect(screen.getByLabelText('运行环境能力')).toHaveTextContent('v24.21.0');
expect(screen.getByLabelText('运行环境能力')).toHaveTextContent('基础功能');
fireEvent.change(screen.getByLabelText(/用户三级域名根域/), { target: { value: 'vhost.ser888.cn' } });
fireEvent.change(screen.getByLabelText(/管理控制台域名/), { target: { value: 'host.ser888.cn' } });
fireEvent.change(screen.getByLabelText(/FTP 证书来源域名/), { target: { value: 'host.ser888.cn' } });
fireEvent.click(screen.getByRole('button', { name: /继续/ }));
fireEvent.change(screen.getByLabelText('管理员邮箱'), { target: { value: 'admin@example.com' } });
fireEvent.change(screen.getByLabelText('密码'), { target: { value: 'correct-horse-battery' } });
fireEvent.change(screen.getByLabelText('确认密码'), { target: { value: 'correct-horse-battery' } });
fireEvent.click(screen.getByRole('button', { name: /确认并完成安装/ }));
expect(await screen.findByRole('heading', { name: 'Sea vHost 已安装完成' })).toBeInTheDocument();
});
});
describe('平台域名审核', () => {
it('submits a numeric bandwidth cap separately from monthly traffic', async () => {
const create = vi.fn().mockResolvedValue(undefined);
render(<AdminConsole
user={{ id: 1, email: 'admin@example.com', loginName: 'admin@example.com', displayName: '管理员', role: 'admin', mfaEnabled: false }}
tenants={[]} plans={[demoPlan]} pendingDomains={[]} approval
onApproval={async () => undefined} onReviewDomain={async () => undefined}
onCreate={async () => undefined} onCreatePlan={create}
onSecurity={() => undefined} onLogout={() => undefined}
/>);
fireEvent.click(screen.getByRole('button', { name: '套餐管理' }));
fireEvent.click(await screen.findByRole('button', { name: '创建套餐' }));
fireEvent.change(screen.getByLabelText('套餐名称'), { target: { value: '限速测试套餐' } });
const cap = screen.getByLabelText(/HTTP 每请求/);
expect(cap).toHaveAttribute('min', '0');
fireEvent.change(cap, { target: { value: '5' } });
fireEvent.submit(cap.closest('form')!);
await waitFor(() => expect(create).toHaveBeenCalledWith(expect.objectContaining({ bandwidthMbps: 5, bandwidthBytes: 500 * 1024 ** 3 })));
});
it('lets an administrator approve a pending domain', async () => {
vi.mocked(api.adminOverview).mockResolvedValue({users:[],projects:[],ipAddresses:[],logs:[],domains:[{id:9,projectId:2,siteId:3,tenantName:'示例用户',hostName:'svdemo',projectName:'官网',siteName:'主站',domain:'www.customer.example',kind:'custom',status:'pending',sslStatus:'off',createdAt:'2026-10-09T10:00:00+08:00'}]});
const review = vi.fn().mockResolvedValue(undefined);
render(<AdminConsole
user={{ id: 1, email: 'admin@example.com', loginName: 'admin@example.com', displayName: '管理员', role: 'admin', mfaEnabled: false }}
tenants={[]}
plans={[demoPlan]}
pendingDomains={[{ id: 9, projectId: 2, siteId: 3, tenantName: '示例用户', hostName: 'svdemo', projectName: '官网', siteName: '主站', domain: 'www.customer.example', kind: 'custom', status: 'pending', sslStatus: 'off', createdAt: '2026-10-09T10:00:00+08:00' }]}
approval
onApproval={async () => undefined}
onReviewDomain={review}
onCreate={async () => undefined}
onCreatePlan={async () => undefined}
onSecurity={() => undefined}
onLogout={() => undefined}
/>);
fireEvent.click(await screen.findByRole('button', { name: '批准' }));
await waitFor(() => expect(review).toHaveBeenCalledWith(9, true));
});
});
describe('环境配置', () => {
it('shows only panel-advertised runtime versions to administrators', async () => {
vi.spyOn(api, 'runtimeMaintenance').mockResolvedValue({ sites: [], jobs: [] });
vi.spyOn(api, 'runtimeEnvironments').mockResolvedValue({ environments: [
{ name: 'PHP', componentTitle: 'PHP 运行环境', componentStatus: 'installed', componentInstallable: false, installed: ['8.4'], available: [], installing: [] },
{ name: 'Node.js', componentTitle: 'Node.js 版本管理器', componentStatus: 'not_installed', componentInstallable: true, installed: [], available: [], installing: [], detail: '可安装宝塔官方免费 Node.js 版本管理器。' },
{ name: 'Python', componentTitle: 'Python 项目管理器', componentStatus: 'installed', componentInstallable: false, installed: ['3.12.3'], available: ['3.13.1', '3.12.3'], installing: [], recommended: '3.13.1' },
] });
render(<AdminConsole
user={{ id: 1, email: 'admin@example.com', loginName: 'admin@example.com', displayName: '管理员', role: 'admin', mfaEnabled: false }}
tenants={[]} plans={[demoPlan]} pendingDomains={[]} approval
onApproval={async () => undefined} onReviewDomain={async () => undefined}
onCreate={async () => undefined} onCreatePlan={async () => undefined}
onSecurity={() => undefined} onLogout={() => undefined}
/>);
fireEvent.click(screen.getByRole('button', { name: '环境配置' }));
expect(await screen.findByRole('heading', { name: '环境配置' })).toBeInTheDocument();
expect(await screen.findByRole('button', { name: '安装免费组件' })).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: 'Python 待安装版本' })).toHaveValue('3.13.1');
expect(screen.queryByRole('textbox', { name: /版本/ })).not.toBeInTheDocument();
});
});
describe('宝塔站点迁移', () => {
it('handles an empty legacy response without blanking the console', async () => {
vi.spyOn(api, 'panelSites').mockResolvedValue({ sites: null, versions: null } as never);
render(<AdminConsole
user={{ id: 1, email: 'admin@example.com', loginName: 'admin@example.com', displayName: '管理员', role: 'admin', mfaEnabled: false }}
tenants={[]}
plans={[demoPlan]}
pendingDomains={[]}
approval
onApproval={async () => undefined}
onReviewDomain={async () => undefined}
onCreate={async () => undefined}
onCreatePlan={async () => undefined}
onSecurity={() => undefined}
onLogout={() => undefined}
/>);
fireEvent.click(screen.getByRole('button', { name: '虚拟主机' }));
fireEvent.click(await screen.findByRole('button', { name: '迁移宝塔站点' }));
expect(await screen.findByRole('heading', { name: '迁移宝塔站点' })).toBeInTheDocument();
expect(await screen.findByText('没有可迁移的宝塔站点')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '复制并接管' })).toBeDisabled();
});
});
describe('主机账号边界', () => {
it('不显示用户级聚合用量和创建主机入口', () => {
const noop = () => undefined;
render(<Overview projects={[initialProjects[0]]} plan={demoPlan} usage={demoUsage} activities={[]} hostScoped canCreate={false} onCreate={noop} onToggle={noop} onFiles={noop} onRunPath={noop} onSites={noop} onCredentials={noop} />);
expect(screen.queryByText('存储空间')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /创建虚拟主机/ })).not.toBeInTheDocument();
expect(screen.queryByText('管理当前虚拟主机的网站、文件与访问凭据。')).not.toBeInTheDocument();
});
});
describe('启动错误', () => {
it('offers a retry action instead of silently showing login', () => {
let retried = false;
render(<StartupError message="后端服务没有响应" onRetry={() => { retried = true; }} />);
fireEvent.click(screen.getByRole('button', { name: '重新连接' }));
expect(retried).toBe(true);
});
});
+274
View File
@@ -0,0 +1,274 @@
import {UserSchedules} from './components/UserSchedules';
import {useLiveDashboard} from './useLiveDashboard';
import {ResourceCharts} from './components/ResourceCharts';
import { lazy,Suspense,type ComponentProps,useCallback, useEffect, useRef, useState } from 'react';
import { api, type Credentials, type Dashboard, type DomainResource, type PlanInput, type Tenant, type User } from './api';
const LazyAdminConsole=lazy(()=>import('./components/AdminConsole').then(module=>({default:module.AdminConsole})));
function AdminConsole(props:ComponentProps<typeof LazyAdminConsole>){return <Suspense fallback={<p className="admin-loading" role="status">正在加载管理员控制台…</p>}><LazyAdminConsole {...props}/></Suspense>}
import { AppShell } from './components/AppShell';
import { CredentialsModal } from './components/CredentialsModal';
import { CreateProject } from './components/CreateProject';
import { DNSCredentials } from './components/DNSCredentials';
import { FileManager } from './components/FileManager';
import { Login } from './components/Login';
import { HostSitesModal } from './components/HostSitesModal';
import { HostDetails } from './components/HostDetails';
import { ImpersonationBanner } from './components/ImpersonationBanner';
import { InstallWizard } from './components/InstallWizard';
import { Overview } from './components/Overview';
import { RunPathModal } from './components/RunPathModal';
import { SecurityModal } from './components/SecurityModal';
import { ResourceCenter } from './components/ResourceCenter';
import { StartupError } from './components/StartupError';
import { demoActivities, demoPlan, demoRuntimeVersions, demoUsage, initialProjects } from './data';
import type { ActivityEntry, APIProject, Plan, Project, ProjectDraft, ProjectStatus, Runtime, RuntimeCatalog, Usage } from './types';
export function App() {
const apiMode = import.meta.env.VITE_API_MODE === 'true';
const setupPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('setup') === '1';
const adminPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('admin') === '1';
const [page, setPage] = useState('overview');
const [projects, setProjects] = useState<Project[]>(initialProjects);
const changingProjects=useRef(new Set<number>()),dashboardRevision=useRef(0);const [pendingProjectIDs,setPendingProjectIDs]=useState<number[]>([]);
const [fileProjectID, setFileProjectID] = useState<number>();
const [runPathProject, setRunPathProject] = useState<Project>();
const [sitesProject, setSitesProject] = useState<Project>();
const [plan, setPlan] = useState<Plan>(demoPlan);
const [usage, setUsage] = useState<Usage>(demoUsage);
const [activities, setActivities] = useState<ActivityEntry[]>(demoActivities);
const [hostScoped, setHostScoped] = useState(false);
const [runtimeVersions, setRuntimeVersions] = useState<RuntimeCatalog>(demoRuntimeVersions);
const [rootDomain, setRootDomain] = useState('vhost.ser888.cn');
const [projectRoot, setProjectRoot] = useState('/www/wwwroot/seavHost/vHost');
const [toast, setToast] = useState('');
const [user, setUser] = useState<User | null>(null);
const [authChecked, setAuthChecked] = useState(!apiMode);
const [tenants, setTenants] = useState<Tenant[]>([]);
const [plans, setPlans] = useState<Plan[]>([demoPlan]);
const [domainApproval, setDomainApproval] = useState(true);
const [pendingDomains, setPendingDomains] = useState<DomainResource[]>([]);
const [credentials, setCredentials] = useState<Credentials | null>(null);
const [credentialProjectID, setCredentialProjectID] = useState<number>();
const [setupRequired, setSetupRequired] = useState<boolean | null>(apiMode ? null : false);
const [bootError, setBootError] = useState('');const [bootStatus,setBootStatus]=useState<number>();
const [bootAttempt, setBootAttempt] = useState(0);
const [showSecurity, setShowSecurity] = useState(false);
const applyDashboard=useCallback((dashboard:Dashboard)=>{
setProjects(dashboard.projects.map(normalizeProject));setPlan(dashboard.plan);setUsage(dashboard.usage);setActivities(dashboard.activities);setHostScoped(dashboard.hostScoped);setDomainApproval(dashboard.domainApproval);setRootDomain(dashboard.rootDomain);setProjectRoot(dashboard.projectRoot);
},[]);
const dashboardSync=useLiveDashboard(apiMode&&authChecked&&!!user&&user.role!=='admin',`${user?.id}:${page}`,applyDashboard,dashboardRevision,changingProjects,()=>window.location.reload());
const loadAccount = useCallback(async (current: User) => {
if (current.role === 'admin') {
const [tenantResult, setting, planResult, pendingResult] = await Promise.all([api.tenants(), api.domainApproval(), api.plans(), api.pendingDomains()]);
setTenants(tenantResult.tenants);
setDomainApproval(setting.enabled);
setPlans(planResult.plans);
setPendingDomains(pendingResult.domains);
} else {
const dashboard = await api.dashboard();
applyDashboard(dashboard);
if(dashboard.hostScoped)setPage('projects');
setRuntimeVersions(normalizeCatalog({}));
}
setUser(current);
setAuthChecked(true);
}, [applyDashboard]);
useEffect(() => {
if (!apiMode || setupPreview) return;
let active = true;
setBootError('');setBootStatus(undefined);
setAuthChecked(false);
setSetupRequired(null);
(async () => {
try {
const { required } = await api.setupStatus();
if (!active) return;
setSetupRequired(required);
if (required) return;
try {
const { user: current } = await api.me();
if (active) await loadAccount(current);
} catch (reason) {
if (httpStatus(reason) === 401) {
if (active) setAuthChecked(true);
return;
}
throw reason;
}
} catch (reason) {
if (!active) return;
setSetupRequired(false);
setAuthChecked(true);
setBootError(startupMessage(reason));setBootStatus(httpStatus(reason));
}
})();
return () => { active = false; };
}, [apiMode, bootAttempt, loadAccount, setupPreview]);
function notify(message: string) {
setToast(message);
window.setTimeout(() => setToast(''), 2600);
}
async function createProject(draft: ProjectDraft) {
if (apiMode) {
try {
const result = await api.createProject(draft);
setProjects((current) => [normalizeProject(result.project), ...current]);
setCredentials(result.credentials);
setCredentialProjectID(result.project.id);
setPage('overview');
notify('虚拟主机已创建,FTP 与数据库凭据可随时查看');
} catch (reason) { notify(reason instanceof Error ? reason.message : '创建虚拟主机失败'); }
return;
}
const project: Project = {
id: Math.max(0, ...projects.map(({ id }) => id)) + 1,
hostName: `svdemo${String(Math.max(0, ...projects.map(({ id }) => id)) + 1).padStart(6, '0')}`,
name: draft.name,
domain: '',
path: '',
runPath: draft.runPath,
runtime: draft.runtime,
version: draft.version,
status: 'provisioning',
ssl: draft.autoSSL,
trafficGB: 0,
createdAt: '刚刚',
};
project.domain = draft.customDomain || `${project.hostName}.${rootDomain}`;
project.path = `${projectRoot}/${project.hostName}`;
setProjects((current) => [project, ...current]);
setPage('overview');
notify('虚拟主机已进入部署队列');
}
async function toggleProject(id:number){
if(changingProjects.current.has(id))return;
const target=projects.find(p=>p.id===id);
if(!target||!['running','stopped'].includes(target.status)){notify('主站尚未完成部署,暂不能启停');return}
const enabled=target.status!=='running';dashboardRevision.current++;changingProjects.current.add(id);setPendingProjectIDs([...changingProjects.current]);
try{if(apiMode)await api.setProjectState(id,enabled);setProjects(current=>current.map(p=>p.id===id?{...p,status:enabled?'running':'stopped'}:p));notify('主站状态已更新')}
catch(e){notify(e instanceof Error?e.message:'状态更新失败')}
finally{dashboardRevision.current++;changingProjects.current.delete(id);setPendingProjectIDs([...changingProjects.current])}
}
async function updateRunPath(runPath: string) {
if (!runPathProject) return;
if (apiMode) {
dashboardRevision.current++;
try {
const result = await api.setProjectRunPath(runPathProject.id, runPath);
const updated = normalizeProject(result.project);
setProjects((current) => current.map((project) => project.id === updated.id ? updated : project));
} catch (reason) {
throw reason;
} finally { dashboardRevision.current++; }
} else {
setProjects((current) => current.map((project) => project.id === runPathProject.id ? { ...project, runPath } : project));
}
setRunPathProject(undefined);
notify('运行目录已更新');
}
async function showCredentials(project: Project) {
setCredentialProjectID(project.id);
if (!apiMode) {
setCredentials({ hostLogin: project.hostName, ftpHost: project.domain, ftpTLSPolicy: 'explicit_tls_required', ftpUsername: project.hostName, ftpPassword: 'demo-ftp-password', databaseName: project.hostName, databaseUsername: project.hostName, databasePassword: 'demo-database-password' });
return;
}
try { setCredentials((await api.projectCredentials(project.id)).credentials); }
catch (reason) { notify(reason instanceof Error ? reason.message : '无法读取主机凭据'); }
}
async function resetHostPassword() {
if (!credentialProjectID) return;
const password = apiMode ? (await api.resetHostPassword(credentialProjectID)).password : 'demo-host-password-reset';
setCredentials((current) => current ? { ...current, hostPassword: password } : current);
notify('主机登录密码已重置,旧会话已失效');
}
function showCredentialsByID(projectID: number) {
const project = projects.find((item) => item.id === projectID);
if (project) void showCredentials(project);
}
function showSites(project: Project) {
setSitesProject(project);
setRuntimeVersions(apiMode ? normalizeCatalog({}) : demoRuntimeVersions);
if (apiMode) void api.runtimeCatalog(project.id).then(result => setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason => notify(reason instanceof Error ? reason.message : '节点环境读取失败'));
}
if (adminPreview) return <AdminConsole user={{ id: 1, email: 'admin@ser888.cn', loginName: 'admin@ser888.cn', displayName: '平台管理员', role: 'admin', mfaEnabled: true }} tenants={[{ id: 1, slug: 'sea-demo', name: '示例用户', status: 'active', lifecycleState: 'active', planName: '标准套餐', userCount: 1, projectCount: 3, expiresAt: '2026-12-31T16:00:00Z', createdAt: '2026-10-01T08:00:00Z' }]} plans={[demoPlan]} pendingDomains={[{ id: 9, projectId: 1, siteId: 1, tenantName: '示例用户', hostName: 'sv8c0a6d2f91', projectName: '企业官网', siteName: '主站', domain: 'www.customer.example', kind: 'custom', status: 'pending', resolutionMode: 'cname', cnameTarget: 'sv8c0a6d2f91.vhost.ser888.cn', filingStatus: 'pending', sslStatus: 'pending', createdAt: '2026-10-22T08:00:00Z' }]} approval onApproval={async () => undefined} onReviewDomain={async () => undefined} onCreate={async () => undefined} onCreatePlan={async () => undefined} onSecurity={() => undefined} onLogout={() => undefined} />;
if (setupPreview) return <InstallWizard preview />;
if (apiMode && setupRequired === true) return <InstallWizard />;
if (apiMode && bootError) return <StartupError message={bootError} onRetry={bootStatus===421?undefined:() => setBootAttempt((value) => value + 1)} />;
if (apiMode && (!authChecked || setupRequired === null)) return <div className="loading-screen"><span />正在载入 Sea vHost…</div>;
if (apiMode && !user) return <Login onLogin={async (email, password, totpCode) => { const result = await api.login(email, password, totpCode); await loadAccount(result.user); }} />;
if (apiMode && user?.role === 'admin') return <><AdminConsole onPlansChanged={async()=>{setPlans((await api.plans()).plans)}} onImpersonate={async input=>{await api.startImpersonation(input);window.location.reload()}} user={user} tenants={tenants} plans={plans} pendingDomains={pendingDomains} approval={domainApproval} onApproval={async (enabled) => { await api.setDomainApproval(enabled); setDomainApproval(enabled); }} onReviewDomain={async (id, approved) => { await api.reviewDomain(id, approved); setPendingDomains((current) => current.filter((item) => item.id !== id)); }} onCreate={async (input) => { await api.createTenant(input); setTenants((await api.tenants()).tenants); }} onCreatePlan={async (input: PlanInput) => { await api.createPlan(input); setPlans((await api.plans()).plans); }} onSecurity={() => setShowSecurity(true)} onLogout={async () => { await api.logout(); window.location.reload(); }} />{showSecurity ? <SecurityModal onClose={() => setShowSecurity(false)} onSessionEnded={() => { setShowSecurity(false); setUser(null); }} /> : null}</>;
return (
<AppShell page={page === 'create' ? 'projects' : page} tenantName={user?.tenantName ?? '示例科技有限公司'} displayName={user?.displayName ?? '张三'} hostScoped={hostScoped} onNavigate={setPage} onLogout={()=>{void api.logout().then(()=>window.location.reload()).catch(reason=>notify(reason instanceof Error?reason.message:'退出失败'))}} onSecurity={() => user?.impersonating?notify('请先返回管理员后操作账号安全'):setShowSecurity(true)}>
{user?.impersonating?<ImpersonationBanner user={user}/>:null}
{dashboardSync.error?<p className="resource-error" role="alert">状态刷新失败:{dashboardSync.error}。<button className="secondary" onClick={dashboardSync.refresh}>重新读取状态</button></p>:null}
{page === 'overview' ? <Overview onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} pendingProjectIDs={pendingProjectIDs} onLogs={() => setPage('logs')} projects={projects} plan={plan} usage={usage} activities={activities} hostScoped={hostScoped} canCreate={!apiMode} onCreate={() => setPage('create')} onToggle={toggleProject} onFiles={(id) => { setFileProjectID(id); setPage('files'); }} onRunPath={(project) => setRunPathProject(project)} onSites={(project)=>{setRuntimeVersions(normalizeCatalog({}));setSitesProject(project);if(apiMode) void api.runtimeCatalog(project.id).then(result=>setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason=>notify(reason instanceof Error?reason.message:"节点环境读取失败"));else setRuntimeVersions(demoRuntimeVersions);}} onCredentials={(project) => void showCredentials(project)} /> : null}
{page === 'create' ? <CreateProject runtimeVersions={runtimeVersions} rootDomain={rootDomain} projectRoot={projectRoot} plan={plan} domainApproval={domainApproval} onCancel={() => setPage('overview')} onSubmit={createProject} /> : null}
{page==='schedules'&&!hostScoped?<UserSchedules projects={projects} live={apiMode}/>:null}
{page==='metrics'?<ResourceCharts projects={projects} live={apiMode}/>:null}
{page === 'files' ? <FileManager projects={projects} initialProjectID={fileProjectID} live={apiMode} /> : null}
{page === 'projects' ? <HostDetails onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} onToggle={toggleProject} pendingProjectIDs={pendingProjectIDs} hostScoped={hostScoped} projects={projects} plan={plan} usage={usage} live={apiMode} onRunPath={setRunPathProject} onSites={showSites} onCredentials={project => void showCredentials(project)} onFiles={id => { setFileProjectID(id); setPage('files'); }} /> : null}
{page === 'dns' && !hostScoped ? <DNSCredentials live={apiMode} /> : null}
{['domains', 'databases', 'ftp', 'logs'].includes(page) ? <ResourceCenter page={page} projects={projects} activities={activities} hostScoped={hostScoped} domainApproval={domainApproval} live={apiMode} onCredentials={showCredentialsByID} onNotify={notify} /> : null}
{toast ? <div className="toast" role="status"><CheckIcon />{toast}</div> : null}
{credentials ? <CredentialsModal credentials={credentials} onReset={user?.role !== 'host' ? resetHostPassword : undefined} onClose={() => { setCredentials(null); setCredentialProjectID(undefined); }} /> : null}
{runPathProject ? <RunPathModal project={runPathProject} onClose={() => setRunPathProject(undefined)} onSubmit={updateRunPath} /> : null}
{sitesProject ? <HostSitesModal project={sitesProject} runtimeVersions={runtimeVersions} live={apiMode} onClose={() => {setSitesProject(undefined);dashboardSync.refresh()}} /> : null}
{showSecurity ? <SecurityModal onClose={() => setShowSecurity(false)} onSessionEnded={() => { setShowSecurity(false); setUser(null); }} /> : null}
</AppShell>
);
}
const runtimes: Runtime[] = ['PHP', 'Node.js', 'Python', 'Go', 'Java'];
function normalizeCatalog(catalog: Partial<RuntimeCatalog>): RuntimeCatalog {
return Object.fromEntries(runtimes.map((runtime) => [runtime, Array.isArray(catalog?.[runtime]) ? catalog[runtime] : []])) as RuntimeCatalog;
}
function normalizeProject(project: APIProject): Project {
const certificateReady = ['active', 'valid', 'issued', 'deployed'].includes(project.sslStatus?.toLowerCase());
const knownStatuses: ProjectStatus[] = ['running', 'stopped', 'provisioning', 'awaiting_upload', 'failed', 'quota_suspended'];
return {
id: project.id,
allowRuntimeChange:project.allowRuntimeChange,
hostName: project.hostName,
name: project.name,
domain: project.domain,
path: project.path,
runPath: project.runPath || '/',
runtime: project.runtime,
version: project.version,
status: knownStatuses.includes(project.status as ProjectStatus) ? project.status as ProjectStatus : 'provisioning',
ssl: certificateReady,
trafficGB: Math.max(0,Number(project.bandwidthBytes)||0)/1024**3,
createdAt: project.createdAt,
};
}
function httpStatus(reason: unknown) {
return (reason as { status?: number } | null)?.status;
}
function startupMessage(reason: unknown) {
const status = httpStatus(reason);
if(status===421)return '当前域名不是管理入口,或该网站尚未配置 HTTPS。请使用对应的管理域名或网站访问地址。';
if (status) return `后端服务返回 HTTP ${status},请检查 sea-vhost-api 服务。`;
return '后端服务没有响应,请检查 sea-vhost-api 服务与 Nginx 反向代理。';
}
function CheckIcon() {
return <svg viewBox="0 0 20 20" aria-hidden="true"><path d="m4 10 4 4 8-9" /></svg>;
}
+89
View File
@@ -0,0 +1,89 @@
import '@testing-library/jest-dom/vitest';
import {act,cleanup,fireEvent,render,screen,waitFor,within} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {api,type FileListing} from './api';
import {FileManager} from './components/FileManager';
import {initialProjects} from './data';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
const listing=(name:string):FileListing=>({path:'',uploadLimit:20971520,entries:[{name,path:name,directory:false,size:10,modified:'2026-10-28T00:00:00Z'}]});
it('does not present binary filenames as buttons that cannot do anything',async()=>{
vi.spyOn(api,'files').mockResolvedValue(listing('program.bin'));
render(<FileManager projects={initialProjects}/>);
await screen.findByText('program.bin');
expect(screen.queryByRole('button',{name:'program.bin'})).not.toBeInTheDocument();
expect(screen.getByRole('link',{name:'下载 program.bin'})).toBeInTheDocument();
expect(screen.getByTitle('此类型不支持在线编辑,请下载或使用 FTP 处理')).toBeInTheDocument();
});
it('requires the in-page confirmation before moving a file to trash and supports cancellation',async()=>{
vi.spyOn(api,'files').mockResolvedValue(listing('index.txt'));
const trash=vi.spyOn(api,'trashFile').mockResolvedValue(undefined);
render(<FileManager projects={initialProjects}/>);
fireEvent.click(await screen.findByRole('button',{name:'删除 index.txt'}));
const dialog=screen.getByRole('alertdialog',{name:'移入回收站'});
expect(trash).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole('button',{name:'取消'}));
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();expect(trash).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button',{name:'删除 index.txt'}));
fireEvent.click(screen.getByRole('button',{name:'移入回收站'}));
await waitFor(()=>expect(trash).toHaveBeenCalledWith(1,'index.txt'));
});
it('discards late responses from a previous host and hides stale directory actions',async()=>{
let old!:(value:FileListing)=>void;
vi.spyOn(api,'files').mockImplementation(id=>id===1?new Promise(resolve=>{old=resolve}):Promise.resolve(listing('current.txt')));
const view=render(<FileManager projects={initialProjects} initialProjectID={1}/>);
view.rerender(<FileManager projects={initialProjects} initialProjectID={2}/>);
expect(await screen.findByRole('button',{name:'current.txt'})).toBeInTheDocument();
await act(async()=>old(listing('previous-secret.txt')));
expect(screen.queryByText('previous-secret.txt')).not.toBeInTheDocument();
expect(screen.getByRole('button',{name:'current.txt'})).toBeInTheDocument();
expect(screen.getByLabelText('选择虚拟主机')).toHaveValue('2');
});
it('allows a failed directory read to retry and displays save failures inside the editor',async()=>{
const files=vi.spyOn(api,'files').mockRejectedValueOnce(new Error('目录读取失败')).mockResolvedValue(listing('index.txt'));
vi.spyOn(api,'fileText').mockResolvedValue('keep this content');
const save=vi.spyOn(api,'writeFile').mockRejectedValue(new Error('磁盘空间不足'));
render(<FileManager projects={initialProjects}/>);
expect(await screen.findByRole('alert')).toHaveTextContent('目录读取失败');
expect(screen.getByRole('button',{name:'刷新文件'})).toBeEnabled();
expect(screen.queryByText('目录为空')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'刷新文件'}));
fireEvent.click(await screen.findByRole('button',{name:'编辑 index.txt'}));
const editor=await screen.findByRole('dialog',{name:'编辑文本文件'});
await waitFor(()=>expect(within(editor).getByLabelText('内容')).toHaveValue('keep this content'));
fireEvent.click(within(editor).getByRole('button',{name:'保存'}));
expect(await within(editor).findByRole('alert')).toHaveTextContent('磁盘空间不足');
expect(within(editor).getByLabelText('内容')).toHaveValue('keep this content');
expect(files).toHaveBeenCalledTimes(2);
expect(save).toHaveBeenCalledWith(1,'index.txt','keep this content',true);
});
it('does not open an old host file after the selected host changes',async()=>{
let finish!:(content:string)=>void;
vi.spyOn(api,'files').mockImplementation(id=>Promise.resolve(listing(id===1?'old.txt':'new.txt')));
vi.spyOn(api,'fileText').mockReturnValue(new Promise(resolve=>{finish=resolve}));
const view=render(<FileManager projects={initialProjects} initialProjectID={1}/>);
fireEvent.click(await screen.findByRole('button',{name:'编辑 old.txt'}));
view.rerender(<FileManager projects={initialProjects} initialProjectID={2}/>);
expect(await screen.findByRole('button',{name:'new.txt'})).toBeInTheDocument();
await act(async()=>finish('previous host secret'));
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('does not reopen trash when an in-flight restore refresh finishes after closing',async()=>{
vi.spyOn(api,'files').mockResolvedValue(listing('index.txt'));
const item={id:'qa-trash',name:'old.txt',originalPath:'old.txt',deletedAt:'2026-10-29T00:00:00Z',size:10};
let finish!:(value:{entries:typeof item[]})=>void;
vi.spyOn(api,'fileTrash').mockResolvedValueOnce({entries:[item]}).mockReturnValueOnce(new Promise(resolve=>{finish=resolve}));
vi.spyOn(api,'fileAction').mockResolvedValue(undefined);
render(<FileManager projects={initialProjects}/>);
await screen.findByRole('button',{name:'index.txt'});fireEvent.click(screen.getByRole('button',{name:'回收站'}));
fireEvent.click(await screen.findByRole('button',{name:'恢复 old.txt'}));fireEvent.click(screen.getByRole('button',{name:'执行操作'}));
await waitFor(()=>expect(screen.queryByRole('dialog',{name:'恢复文件'})).not.toBeInTheDocument());
fireEvent.click(screen.getByRole('button',{name:'关闭回收站'}));await act(async()=>finish({entries:[]}));
expect(screen.queryByRole('heading',{name:'主机回收站'})).not.toBeInTheDocument();
});
+36
View File
@@ -0,0 +1,36 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {HostDetails} from './components/HostDetails';
import {ResourceCenter} from './components/ResourceCenter';
import {demoPlan,demoUsage,initialProjects} from './data';
import {api} from './api';
import {HostSitesModal} from './components/HostSitesModal';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
it('opens real host configuration controls with administrator-assigned limits',()=>{
const onRunPath=vi.fn(),onSites=vi.fn();render(<HostDetails projects={initialProjects} plan={demoPlan} usage={demoUsage} live={false} onRunPath={onRunPath} onSites={onSites} onCredentials={vi.fn()} onFiles={vi.fn()}/>);
expect(screen.getByRole('heading',{name:'资源配置'})).toBeInTheDocument();
expect(screen.getByText(demoPlan.name)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'设置运行目录'}));expect(onRunPath).toHaveBeenCalledWith(initialProjects[0]);
fireEvent.click(screen.getByRole('button',{name:'网站管理'}));expect(onSites).toHaveBeenCalledWith(initialProjects[0]);
});
it('loads and refreshes logs scoped to the signed-in host',async()=>{
const load=vi.spyOn(api,'activities').mockResolvedValue({activities:[{id:91,projectId:initialProjects[0].id,actor:'用户',action:'update',resourceType:'run_path',detail:'用户更新当前主机目录',success:true,createdAt:'2026-10-26T00:00:00Z'}]});
render(<ResourceCenter page="logs" projects={initialProjects.slice(0,1)} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
expect(await screen.findByText('用户更新当前主机目录')).toBeInTheDocument();expect(load).toHaveBeenCalledWith(initialProjects[0].id);
expect(screen.queryByText('主机账号不显示用户级审计日志')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'刷新日志'}));await waitFor(()=>expect(load).toHaveBeenCalledTimes(2));
});
it('filters the account log view by its selected host',async()=>{
const load=vi.spyOn(api,'activities').mockResolvedValue({activities:[]});render(<ResourceCenter page="logs" projects={initialProjects} activities={[]} hostScoped={false} live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
await waitFor(()=>expect(load).toHaveBeenCalledWith(undefined));fireEvent.change(screen.getByRole('combobox',{name:'日志范围'}),{target:{value:String(initialProjects[1].id)}});await waitFor(()=>expect(load).toHaveBeenLastCalledWith(initialProjects[1].id));
});
it('uses installed versions when the environment catalog arrives after opening website management',async()=>{
const view=render(<HostSitesModal project={initialProjects[0]} runtimeVersions={{PHP:[], 'Node.js':[],Python:[],Go:[],Java:[]}} live={false} onClose={vi.fn()}/>);
fireEvent.click(screen.getByRole('button',{name:'新增网站'}));
expect(screen.getByRole('button',{name:'创建网站'})).toBeDisabled();
view.rerender(<HostSitesModal project={initialProjects[0]} runtimeVersions={{PHP:['8.4'], 'Node.js':['v24.22.1'],Python:[],Go:[],Java:[]}} live={false} onClose={vi.fn()}/>);
await waitFor(()=>expect(screen.getByRole('button',{name:'创建网站'})).toBeEnabled());
const version=screen.getAllByRole('combobox').find(select=>select.querySelector('option')?.textContent==='8.4');
expect(version).toHaveValue('8.4');
});
+25
View File
@@ -0,0 +1,25 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {AdminConsole} from './components/AdminConsole';
import {ImpersonationBanner} from './components/ImpersonationBanner';
import {api,type AdminSettings,type Tenant,type AdminProject} from './api';
import {demoPlan} from './data';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
it('routes each administrator entry to its exact tenant or host without asking for credentials',async()=>{
const customer:Tenant={id:11,slug:'ui-qa',name:'界面测试用户',status:'active',planName:'测试',userCount:1,projectCount:1,createdAt:'2026-10-26T00:00:00Z'};
const project:AdminProject={nodeId:1,planId:1,id:21,tenantName:customer.name,hostName:'sv0123456789',name:'ui-site',domain:'sv0123456789.example.invalid',path:'/www/wwwroot/seavHost/vHost/sv0123456789',runPath:'/public',runtime:'PHP',version:'8.4',status:'running',sslStatus:'off',siteCount:1,dedicatedIp:false,httpPort:80,httpsPort:443,createdAt:'2026-10-26T00:00:00Z'};
vi.spyOn(api,'adminOverview').mockResolvedValue({users:[customer],projects:[project],domains:[],logs:[],ipAddresses:[]});
vi.spyOn(api,'adminSettings').mockResolvedValue({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}} satisfies AdminSettings);
const enter=vi.fn().mockResolvedValue(undefined);
render(<AdminConsole user={{id:1,email:'admin@example.invalid',loginName:'admin@example.invalid',displayName:'管理员',role:'admin',mfaEnabled:false}} tenants={[customer]} plans={[demoPlan]} pendingDomains={[]} approval onApproval={vi.fn()} onReviewDomain={vi.fn()} onCreate={vi.fn()} onCreatePlan={vi.fn()} onSecurity={vi.fn()} onLogout={vi.fn()} onImpersonate={enter}/>);
fireEvent.click(screen.getByRole('button',{name:'用户管理'}));fireEvent.click(await screen.findByRole('button',{name:'进入用户 ui-qa'}));expect(enter).toHaveBeenCalledWith({tenantId:11});
fireEvent.click(screen.getByRole('button',{name:'虚拟主机'}));fireEvent.click(await screen.findByRole('button',{name:'进入主机 sv0123456789'}));expect(enter).toHaveBeenLastCalledWith({projectId:21});
});
it('keeps an explicit return control and reports a failed return instead of hiding delegation',async()=>{
vi.spyOn(api,'stopImpersonation').mockRejectedValue(new Error('返回暂时失败'));
render(<ImpersonationBanner user={{id:3,email:'',loginName:'sv0123456789',displayName:'主机',role:'host',mfaEnabled:false,impersonating:true}}/>);
expect(screen.getByLabelText('管理员代入状态')).toHaveTextContent('sv0123456789');
fireEvent.click(screen.getByRole('button',{name:'返回管理视图'}));await waitFor(()=>expect(api.stopImpersonation).toHaveBeenCalledTimes(1));expect(await screen.findByRole('alert')).toHaveTextContent('返回暂时失败');
expect(screen.getByRole('button',{name:'返回管理视图'})).toBeEnabled();
});
+26
View File
@@ -0,0 +1,26 @@
import '@testing-library/jest-dom/vitest';
import {useState} from 'react';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,expect,it} from 'vitest';
import {ModalBackdrop} from './components/ModalBackdrop';
afterEach(()=>{cleanup();document.body.style.overflow='';document.body.style.paddingRight=''});
it('labels dialogs, closes using Escape and restores scroll and the triggering control',async()=>{
function Fixture(){const[open,setOpen]=useState(false);return <><button onClick={()=>setOpen(true)}>打开配置</button>{open?<ModalBackdrop><section><h2>安全设置</h2><label>用户名<input/></label><button onClick={()=>setOpen(false)}>关闭配置</button></section></ModalBackdrop>:null}</>}
document.body.style.overflow='scroll';render(<Fixture/>);const trigger=screen.getByRole('button',{name:'打开配置'});trigger.focus();fireEvent.click(trigger);
expect(screen.getByRole('dialog',{name:'安全设置'})).toHaveAttribute('aria-modal','true');expect(document.body.style.overflow).toBe('hidden');
fireEvent.keyDown(document,{key:'Escape'});
await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(document.body.style.overflow).toBe('scroll');expect(trigger).toHaveFocus();
});
it('makes background controls inert and restores them when nested dialogs close',()=>{
function Fixture(){const[open,setOpen]=useState(false),[nested,setNested]=useState(false);return <><main data-testid="background"><button onClick={()=>setOpen(true)}>打开外层</button></main>{open?<ModalBackdrop><section><h2>外层配置</h2><button onClick={()=>setNested(true)}>打开内层</button><button onClick={()=>setOpen(false)}>关闭外层</button>{nested?<ModalBackdrop><section><h2>内层配置</h2><button onClick={()=>setNested(false)}>关闭内层</button></section></ModalBackdrop>:null}</section></ModalBackdrop>:null}</>}
render(<Fixture/>);const background=screen.getByTestId('background');
fireEvent.click(screen.getByRole('button',{name:'打开外层'}));
expect(background).toHaveProperty('inert',true);
const outerButton=screen.getByRole('button',{name:'打开内层'});
fireEvent.click(outerButton);expect(outerButton).toHaveProperty('inert',true);
fireEvent.click(screen.getByRole('button',{name:'关闭内层'}));
expect(outerButton).toHaveProperty('inert',false);expect(background).toHaveProperty('inert',true);
fireEvent.click(screen.getByRole('button',{name:'关闭外层'}));expect(background).toHaveProperty('inert',false);
});
+30
View File
@@ -0,0 +1,30 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {App} from './App';
import {api,type Dashboard,type User} from './api';
import {demoPlan,demoUsage} from './data';
import {RunPathModal} from './components/RunPathModal';
import {initialProjects} from './data';
afterEach(()=>{cleanup();vi.restoreAllMocks();vi.unstubAllEnvs()});
it('submits one state change during rapid clicks and shows the requested final state',async()=>{
vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});vi.spyOn(api,'me').mockResolvedValue({user:{id:4,role:'tenant',displayName:'测试用户',tenantName:'测试账号'} as User});
vi.spyOn(api,'dashboard').mockResolvedValue({plan:demoPlan,usage:demoUsage,activities:[],hostScoped:false,domainApproval:true,rootDomain:'vhost.ser888.cn',projectRoot:'/www/wwwroot/seavHost/vHost',projects:[{id:9,hostName:'sv9999999999',name:'主机',domain:'qa.vhost.ser888.cn',path:'/www/wwwroot/seavHost/vHost/sv9999999999',runPath:'/public',runtime:'PHP',version:'8.4',status:'stopped',sslStatus:'off',autoSSL:false,processLimit:10,createdAt:'2026-10-29T00:00:00Z'}]} as Dashboard);
let finish!:()=>void;const pending=new Promise<void>(resolve=>{finish=resolve});const update=vi.spyOn(api,'setProjectState').mockReturnValue(pending);
render(<App/>);const start=await screen.findByRole('button',{name:'启动'});fireEvent.click(start);fireEvent.click(start);expect(update).toHaveBeenCalledTimes(1);expect(screen.getByRole('button',{name:'处理中…'})).toBeDisabled();finish();await waitFor(()=>expect(screen.getByRole('button',{name:'停止'})).toBeEnabled());expect(update).toHaveBeenCalledWith(9,true);
});
it('keeps a rejected run directory visible with an inline reason',async()=>{
render(<RunPathModal project={initialProjects[0]} onClose={vi.fn()} onSubmit={vi.fn().mockRejectedValue(new Error('目标目录不存在'))}/>);fireEvent.click(screen.getByRole('button',{name:'保存'}));expect(await screen.findByRole('alert')).toHaveTextContent('目标目录不存在');expect(screen.getByRole('button',{name:'保存'})).toBeEnabled();
});
it('explains an invalid management hostname without offering a pointless reconnect loop',async()=>{
vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockRejectedValue(Object.assign(new Error('wrong host'),{status:421}));
render(<App/>);expect(await screen.findByText(/当前域名不是管理入口/)).toBeInTheDocument();expect(screen.queryByRole('button',{name:'重新连接'})).not.toBeInTheDocument();
});
it('refreshes a backend quota pause and shows measured per-host traffic',async()=>{
vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});vi.spyOn(api,'me').mockResolvedValue({user:{id:8,role:'host',displayName:'主机账号'} as User});
const project={id:15,hostName:'sv1111111111',name:'测试主机',domain:'qa.example.invalid',path:'/test',runPath:'/public',runtime:'PHP',version:'8.4',status:'running',sslStatus:'off',autoSSL:false,processLimit:20,createdAt:'2026-10-29T00:00:00Z',bandwidthBytes:36*1024**2};let paused=false;
vi.spyOn(api,'dashboard').mockImplementation(async()=>({plan:demoPlan,usage:demoUsage,projects:[{...project,status:paused?'quota_suspended':'running'}],activities:[],hostScoped:true,domainApproval:true,rootDomain:'example.invalid',projectRoot:'/test'} as Dashboard));
render(<App/>);expect(await screen.findByRole('button',{name:'停止主站'})).toBeEnabled();expect(screen.getByText('36 MB')).toBeInTheDocument();await screen.findByRole('button',{name:'刷新状态'});paused=true;fireEvent.click(screen.getByRole('button',{name:'刷新状态'}));expect(await screen.findByText('配额暂停')).toBeInTheDocument();expect(screen.getByRole('button',{name:'启动主站'})).toBeDisabled();
});
+38
View File
@@ -0,0 +1,38 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {AccountEditor,HostEditor,NodeEditor} from './components/ResourceEditors';
import {api,type AdminProject,type ControlNode,type Tenant} from './api';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
const host={id:3,name:'测试主机',hostName:'sv1234567890',nodeId:1,path:'/www/wwwroot/seavHost/vHost/sv1234567890',runPath:'/web',tenantName:'用户'} as AdminProject;
it('requires the exact host identity and confirmation before recycling',async()=>{
const remove=vi.spyOn(api,'recycleHost').mockResolvedValue();const changed=vi.fn().mockResolvedValue(undefined);
render(<HostEditor intent="recycle" host={host} onClose={vi.fn()} onChanged={changed}/>);
expect(screen.getByRole('button',{name:'回收主机'})).toBeDisabled();
fireEvent.change(screen.getByLabelText('输入主机名确认回收'),{target:{value:host.hostName}});
fireEvent.click(screen.getByRole('button',{name:'回收主机'}));expect(remove).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button',{name:'取消'}));expect(remove).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button',{name:'回收主机'}));fireEvent.click(screen.getByRole('button',{name:'确认回收'}));
await waitFor(()=>expect(remove).toHaveBeenCalledWith(3,host.hostName));expect(changed).toHaveBeenCalled();
});
it('offers restoration without allowing an ordinary rename of a recycled host',()=>{
render(<HostEditor host={{...host,manualRecycledAt:'2026-10-28T00:00:00Z',purgeAfter:'2099-01-01T00:00:00Z'}} onClose={vi.fn()} onChanged={vi.fn()}/>);
expect(screen.getByLabelText('主机显示名称')).toBeDisabled();expect(screen.getByRole('button',{name:'恢复主机'})).toBeEnabled();
});
it('does not expose editable user fields after a failed profile load',async()=>{
vi.spyOn(api,'accountProfile').mockRejectedValue(new Error('读取失败'));
render(<AccountEditor account={{id:4,slug:'customer'} as Tenant} onClose={vi.fn()} onChanged={vi.fn()}/>);
await screen.findByRole('alert');expect(screen.queryByLabelText('登录邮箱')).not.toBeInTheDocument();expect(screen.getByRole('button',{name:'重新读取'})).toBeEnabled();
});
it('blocks account deletion while hosts remain and saves only after loading',async()=>{
const profile={id:4,slug:'customer',name:'用户甲',email:'qa@example.invalid',displayName:'联系人',projectCount:1};
vi.spyOn(api,'accountProfile').mockResolvedValue(profile);const update=vi.spyOn(api,'updateAccount').mockResolvedValue();
render(<AccountEditor account={{id:4,slug:'customer'} as Tenant} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
await screen.findByLabelText('用户名称');expect(screen.getByRole('button',{name:'删除用户'})).toBeDisabled();
fireEvent.change(screen.getByLabelText('用户名称'),{target:{value:'新名称'}});fireEvent.click(screen.getByRole('button',{name:'保存用户资料'}));
await waitFor(()=>expect(update).toHaveBeenCalledWith(4,{...profile,name:'新名称'}));
});
it('keeps local node transport and storage root immutable and disallows deletion',()=>{
render(<NodeEditor node={{id:1,name:'本机节点',transport:'local',endpoint:'local',rootDomain:'vhost.ser888.cn',tenantRoot:'/www/wwwroot/seavHost/vHost',ftpCertificateDomain:'host.ser888.cn',enabled:true} as ControlNode} onClose={vi.fn()} onChanged={vi.fn()}/>);
expect(screen.getByLabelText('执行入口')).toBeDisabled();expect(screen.getByLabelText('主机根目录')).toBeDisabled();expect(screen.getByRole('button',{name:'删除节点'})).toBeDisabled();
});
+38
View File
@@ -0,0 +1,38 @@
import '@testing-library/jest-dom/vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { api, type RuntimeEnvironment, type RuntimeMaintenanceSite } from './api';
import { RuntimeMaintenancePanel } from './components/RuntimeMaintenancePanel';
afterEach(() => { cleanup(); vi.restoreAllMocks(); });
const php: RuntimeEnvironment = { name: 'PHP', componentTitle: 'PHP', componentStatus: 'installed', componentInstallable: false, installed: ['8.4', '8.5'], available: [], installing: [], patches: [{ branch: '8.4', installed: '8.4.25', latest: '8.4.27', updateAvailable: true }] };
const site: RuntimeMaintenanceSite = { site: { id: 7, projectId: 2, name: 'site', domain: 'app.example.com', runtime: 'Python', version: '3.12.0', status: 'running' }, hostName: 'sv0123456789', installedVersion: '3.12.0', runningVersion: '3.12.0', healthy: true, detail: '' };
describe('运行环境维护', () => {
it('submits the advertised PHP patch after explicit confirmation', async () => {
vi.spyOn(api, 'runtimeMaintenance').mockResolvedValue({ sites: [], jobs: [] });
const update = vi.spyOn(api, 'updatePHPPatch').mockResolvedValue({ jobId: 1 });
render(<RuntimeMaintenancePanel nodeId={7} environments={[php]} onChanged={async () => undefined} />);
await screen.findByText('8.4.27');
fireEvent.click(screen.getByRole('button', { name: '更新 PHP 8.4' }));
expect(screen.getByRole('alertdialog')).toHaveTextContent('Sea vHost 之外的网站');
expect(update).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
await waitFor(() => expect(update).toHaveBeenCalledWith('8.4', '8.4.27', 7));
});
it('keeps the environment page free of per-site selectors and accepts another queued update',async()=>{
vi.spyOn(api,'runtimeMaintenance').mockResolvedValue({sites:[site],jobs:[{id:9,action:'php_patch',runtime:'PHP',fromVersion:'8.4.25',targetVersion:'8.4.27',status:'queued',phase:'queued',message:'',backupAvailable:false,createdAt:'',updatedAt:''}]});
const check=vi.spyOn(api,'checkRuntimeUpdates').mockResolvedValue({jobId:10});
render(<RuntimeMaintenancePanel environments={[php]} onChanged={async()=>undefined}/>);
await screen.findByText('待执行');expect(screen.queryByText('站点运行版本')).not.toBeInTheDocument();expect(screen.getByRole('button',{name:'更新 PHP 8.4'})).toBeDisabled();expect(screen.getByRole('button',{name:'检查更新'})).toBeEnabled();
fireEvent.click(screen.getByRole('button',{name:'检查更新'}));await waitFor(()=>expect(check).toHaveBeenCalled());
});
it('keeps interrupted maintenance visible and blocks new upgrades until resumed', async () => {
vi.spyOn(api, 'runtimeMaintenance').mockResolvedValue({ sites: [], jobs: [{ id: 4, action: 'php_patch', runtime: 'PHP', fromVersion: '8.4.25', targetVersion: '8.4.27', status: 'interrupted', phase: 'installing', message: '服务重启', backupAvailable: true, createdAt: '', updatedAt: '' }] });
const resume = vi.spyOn(api, 'resumeRuntimeMaintenance').mockResolvedValue({ ok: true });
render(<RuntimeMaintenancePanel environments={[php]} onChanged={async () => undefined} />);
expect(await screen.findByText('待核验')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '更新 PHP 8.4' })).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: '恢复核验' }));
await waitFor(() => expect(resume).toHaveBeenCalledWith(4, undefined));
});
});
+29
View File
@@ -0,0 +1,29 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {api,type AdminSettings} from './api';
import {Login} from './components/Login';
import {SystemSettingsForm} from './components/SystemSettingsForm';
vi.mock('./components/SystemScheduler',()=>({SystemScheduler:()=>null}));
afterEach(()=>{cleanup();vi.restoreAllMocks();window.history.replaceState(null,'','/')});
it('keeps a clearly named administrator and host password entry when user passwords are disabled',async()=>{
vi.spyOn(api,'oidcStatus').mockResolvedValue({enabled:true,userPasswordLogin:false,adminPasswordLogin:true});render(<Login onLogin={vi.fn()}/>);
expect(await screen.findByRole('button',{name:'管理员 / 主机密码登录'})).toBeInTheDocument();expect(screen.getByRole('button',{name:'SSO 账号登录'})).toBeInTheDocument();
});
it('lets an unbound SSO user bind an existing account and enforces the MFA step',async()=>{
window.history.replaceState(null,'','/?oidc=complete');vi.spyOn(api,'oidcStatus').mockResolvedValue({enabled:true});vi.spyOn(api,'pendingOIDC').mockResolvedValue({pending:true,allowCreate:true,email:'verified@example.invalid'});
const complete=vi.spyOn(api,'completeOIDC').mockRejectedValue(Object.assign(new Error('需要动态码'),{code:'mfa_required'}));render(<Login onLogin={vi.fn()}/>);
const bind=await screen.findByRole('button',{name:'绑定已有账号并登录'});expect(screen.getByRole('button',{name:'创建普通用户并登录'})).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('已有用户或管理员账号'),{target:{value:'customer'}});fireEvent.change(screen.getByLabelText('密码'),{target:{value:'password-12345'}});fireEvent.click(bind);
await waitFor(()=>expect(complete).toHaveBeenCalledWith({action:'bind',identifier:'customer',password:'password-12345',totpCode:''}));expect(await screen.findByLabelText('动态验证码或恢复码')).toBeInTheDocument();
});
it('does not expose account creation when the backend disallows it',async()=>{
window.history.replaceState(null,'','/?oidc=complete');vi.spyOn(api,'oidcStatus').mockResolvedValue({enabled:true});vi.spyOn(api,'pendingOIDC').mockResolvedValue({pending:true,allowCreate:false});render(<Login onLogin={vi.fn()}/>);
expect(await screen.findByRole('button',{name:'绑定已有账号并登录'})).toBeInTheDocument();expect(screen.queryByRole('button',{name:'创建普通用户并登录'})).not.toBeInTheDocument();
});
it('saves independent administrator/user password policies and the creation switch',async()=>{
const settings: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:true,issuer:'https://id.example.invalid',clientId:'control',redirectUri:'https://control.example.invalid/api/v1/auth/oidc/callback',secretConfigured:true,bindingOnly:true,passwordLogin:true,userPasswordLogin:true,adminPasswordLogin:true,autoCreate:false}};
const save=vi.fn().mockResolvedValue(undefined);render(<SystemSettingsForm settings={settings} save={save}/>);fireEvent.click(screen.getByRole('checkbox',{name:/允许普通用户密码登录/}));fireEvent.click(screen.getByRole('checkbox',{name:/允许首次 SSO 登录创建用户/}));fireEvent.click(screen.getByRole('button',{name:'保存系统设置'}));
await waitFor(()=>expect(save).toHaveBeenCalledWith(expect.objectContaining({oidc:expect.objectContaining({autoCreate:true,userPasswordLogin:false,adminPasswordLogin:true})})));
});
+15
View File
@@ -0,0 +1,15 @@
import {afterEach, expect, it, vi} from 'vitest';
import {api, type UserSchedule} from './api';
afterEach(() => vi.unstubAllGlobals());
it('writes editable schedule fields without response-only metadata', async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response('{"id":9}', {status:200,headers:{'Content-Type':'application/json'}}));
vi.stubGlobal('fetch',fetchMock);
const task:UserSchedule={id:9,projectId:3,siteId:7,name:'定时检查',kind:'php',version:'8.4',target:'task.php',cron:'*/5 * * * *',timezone:'Asia/Shanghai',arguments:[],useHTTPS:false,enabled:true,nextRunAt:'',lastState:'succeeded'};
await api.saveSchedule(task);
const [url,init]=fetchMock.mock.calls[0];
expect(url).toBe('/api/v1/schedules/9');
expect(init.method).toBe('PUT');
expect(JSON.parse(init.body)).toEqual({projectId:3,siteId:7,name:'定时检查',kind:'php',version:'8.4',target:'task.php',cron:'*/5 * * * *',timezone:'Asia/Shanghai',arguments:[],useHTTPS:false,enabled:true});
});
+21
View File
@@ -0,0 +1,21 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,it,expect,vi} from 'vitest';
import {SiteRuntime} from './components/SiteRuntime';
import {api} from './api';
import type {Project,Site,RuntimeCatalog} from './types';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
const project={id:4,hostName:'sv0123456789',runtime:'Python'} as Project;
const site={id:8,name:'main',domain:'app.example.com',runtime:'Python',version:'3.12.15',status:'running'} as Site;
const catalog:RuntimeCatalog={PHP:['8.4','8.3'],'Node.js':['v26.12.1'],Python:['3.12.15','3.13.1'],Go:[],Java:[]};
it('allows installed same-language versions without offering unauthorized languages',async()=>{
vi.spyOn(api,'siteRuntimeJobs').mockResolvedValue({jobs:[]});const change=vi.spyOn(api,'changeSiteRuntime').mockResolvedValue({jobId:9});
render(<SiteRuntime project={project} site={site} catalog={catalog} onClose={vi.fn()} onChanged={vi.fn()} live/>);
expect(screen.queryByRole('option',{name:'Node.js'})).not.toBeInTheDocument();fireEvent.change(screen.getByLabelText('运行版本'),{target:{value:'3.13.1'}});fireEvent.click(screen.getByRole('button',{name:'停止并切换'}));
expect(change).not.toHaveBeenCalled();expect(screen.getByRole('alertdialog')).toHaveTextContent('文件和数据库保留');fireEvent.click(screen.getByRole('button',{name:'确认继续'}));await waitFor(()=>expect(change).toHaveBeenCalledWith(4,8,'Python','3.13.1',''));
});
it('offers cross-language selection only for a host with the explicit grant',async()=>{
vi.spyOn(api,'siteRuntimeJobs').mockResolvedValue({jobs:[]});const change=vi.spyOn(api,'changeSiteRuntime').mockResolvedValue({jobId:9});
render(<SiteRuntime project={{...project,allowRuntimeChange:true}} site={site} catalog={catalog} onClose={vi.fn()} onChanged={vi.fn()} live/>);
fireEvent.change(screen.getByLabelText('运行环境'),{target:{value:'Node.js'}});expect(screen.getByLabelText('运行版本')).toHaveValue('v26.12.1');fireEvent.click(screen.getByRole('button',{name:'停止并切换'}));fireEvent.click(screen.getByRole('button',{name:'确认继续'}));await waitFor(()=>expect(change).toHaveBeenCalledWith(4,8,'Node.js','v26.12.1',''));
});
+33
View File
@@ -0,0 +1,33 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {api,type WebsiteSettings} from './api';
import {SiteTools} from './components/SiteTools';
import type {Site} from './types';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
const site:Site={id:9,projectId:3,name:'php',runPath:'/public',domain:'site.vhost.ser888.cn',runtime:'PHP',version:'8.4',status:'running',sslStatus:'active',autoSSL:true,processLimit:10,primary:true,createdAt:''};
const settings:WebsiteSettings={rewrite:'wordpress',redirectURL:'',redirectCode:301,forceHTTPS:true,index:['index.php'],error404:'404.html',error503:'',maintenance:false};
it('blocks default settings after a failed read and saves the recovered configuration',async()=>{
vi.spyOn(api,'websiteSettings').mockRejectedValueOnce(new Error('网站设置读取失败')).mockResolvedValue({settings});
const save=vi.spyOn(api,'saveWebsiteSettings').mockResolvedValue(undefined);
render(<SiteTools site={site} projectId={3} live onClose={()=>undefined}/>);
expect(await screen.findByRole('alert')).toHaveTextContent('网站设置读取失败');
expect(screen.getByRole('button',{name:'保存网站设置'})).toBeDisabled();expect(save).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button',{name:'重新读取设置'}));
await waitFor(()=>expect(screen.getByLabelText('默认首页(逗号分隔)')).toBeEnabled());
expect(screen.getByLabelText('强制 HTTPS(需有效证书)')).toBeChecked();
fireEvent.click(screen.getByRole('button',{name:'保存网站设置'}));
await waitFor(()=>expect(save).toHaveBeenCalledWith(3,9,settings));
});
it('renders separate log lines and prevents exporting stale lines after a read error',async()=>{
vi.spyOn(api,'websiteSettings').mockResolvedValue({settings});
vi.spyOn(api,'siteLog').mockResolvedValueOnce({lines:['first log line','second log line'],available:true}).mockRejectedValue(new Error('日志读取失败'));
render(<SiteTools site={site} projectId={3} live onClose={()=>undefined}/>);
fireEvent.click(screen.getByRole('button',{name:'网站日志'}));
await waitFor(()=>expect(document.querySelector('.site-log-view')?.textContent).toBe('first log line\nsecond log line'));
fireEvent.change(screen.getByLabelText('日志类型'),{target:{value:'access'}});
expect(await screen.findByRole('alert')).toHaveTextContent('日志读取失败');
expect(screen.queryByText('first log line',{exact:false})).not.toBeInTheDocument();
expect(screen.getByRole('button',{name:'下载日志 JSON'})).toBeDisabled();
});
+34
View File
@@ -0,0 +1,34 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {api,type StartupSettings as Settings} from './api';
import {StartupSettings} from './components/StartupSettings';
import type {Site} from './types';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
it('blocks edits until existing encrypted startup settings have loaded',async()=>{
let resolve!:(value:{startup:Settings})=>void;
vi.spyOn(api,'siteStartup').mockReturnValue(new Promise(r=>{resolve=r}));
const site:Site={id:9,projectId:3,name:'node',runPath:'/app',domain:'node.vhost.ser888.cn',runtime:'Node.js',version:'v26.12.1',status:'running',sslStatus:'off',autoSSL:false,processLimit:10,primary:false,createdAt:''};
render(<StartupSettings site={site} projectId={3} live onClose={()=>undefined}/>);
expect(screen.getByLabelText('工作子目录')).toBeDisabled();
expect(screen.getByRole('button',{name:'保存并应用启动配置'})).toBeDisabled();
resolve({startup:{entryFile:'package.json',workDir:'app',arguments:['--literal'],environment:{SECRET:'kept'}}});
await waitFor(()=>expect(screen.getByLabelText('工作子目录')).toBeEnabled());
expect(screen.getByLabelText('工作子目录')).toHaveValue('app');
expect(screen.getByText('已配置 1 个变量,值已隐藏。')).toBeInTheDocument();
});
it('keeps a failed initial read read-only and retries without overwriting saved settings',async()=>{
const read=vi.spyOn(api,'siteStartup').mockRejectedValueOnce(new Error('读取失败,请重试')).mockResolvedValue({startup:{entryFile:'server.js',workDir:'app',arguments:[],environment:{EXISTING:'preserved'}}});
const save=vi.spyOn(api,'saveSiteStartup').mockResolvedValue(undefined);
const site:Site={id:9,projectId:3,name:'node',runPath:'/app',domain:'node.vhost.ser888.cn',runtime:'Node.js',version:'v26.12.1',status:'running',sslStatus:'off',autoSSL:false,processLimit:10,primary:false,createdAt:''};
render(<StartupSettings site={site} projectId={3} live onClose={()=>undefined}/>);
expect(await screen.findByRole('alert')).toHaveTextContent('读取失败');
expect(screen.getByRole('button',{name:'保存并应用启动配置'})).toBeDisabled();
expect(save).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button',{name:'重新读取配置'}));
await waitFor(()=>expect(screen.getByLabelText('工作子目录')).toBeEnabled());
expect(read).toHaveBeenCalledTimes(2);
fireEvent.click(screen.getByRole('button',{name:'保存并应用启动配置'}));
await waitFor(()=>expect(save).toHaveBeenCalledWith(3,9,expect.objectContaining({entryFile:'server.js',environment:{EXISTING:'preserved'}})));
});
+11
View File
@@ -0,0 +1,11 @@
import '@testing-library/jest-dom/vitest';
import {cleanup,fireEvent,render,screen} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {UserSchedules} from './components/UserSchedules';
import {api,type UserSchedule} from './api';
import {initialProjects} from './data';
afterEach(()=>{cleanup();vi.restoreAllMocks()});
it('tells the user a manual schedule execution was queued rather than already executed',async()=>{
vi.spyOn(api,'schedules').mockResolvedValue({schedules:[{id:1,projectId:1,siteId:1,name:'URL 检查',cron:'0 0 1 1 *',timezone:'Asia/Shanghai',enabled:true,lastState:'ready',nextRunAt:'2027-01-01T00:00:00Z'} as UserSchedule]});const run=vi.spyOn(api,'runSchedule').mockResolvedValue();
render(<UserSchedules projects={initialProjects} live/>);fireEvent.click(await screen.findByRole('button',{name:'执行一次'}));expect(await screen.findByRole('status')).toHaveTextContent('已排队,将在下一次系统调度时执行');expect(run).toHaveBeenCalledWith(1);
});
+250
View File
@@ -0,0 +1,250 @@
import type { ActivityEntry, APIProject, DeploymentCheck, Plan, ProjectDraft, RuntimeCapabilities, RuntimeCatalog, Site, SiteDraft, Usage } from './types';
export interface UserSchedule{id:number;projectId:number;siteId:number;name:string;cron:string;timezone:string;kind:string;version:string;target:string;arguments:string[];useHTTPS:boolean;enabled:boolean;nextRunAt:string;lastState:string;}
export interface ScheduleRun{id:number;state:string;exitCode:number|null;startedAt:string;finishedAt?:string;output:string;}
export interface IntegrationKey{id:number;name:string;prefix:string;scopes:string[];expiresAt:string;revokedAt?:string;webhookURL:string;}
export interface IntegrationWebhook{id:number;eventId:string;batchId:number;state:string;attempts:number;status:number;lastError:string;}
export interface User { id: number; email: string; loginName: string; displayName: string; role: 'admin' | 'tenant' | 'host'; tenantName?: string; tenantSlug?: string; projectId?: number; mfaEnabled: boolean; impersonating?:boolean;impersonationExpiresAt?:string; }
export interface Credentials { ftpHost: string; ftpTLSPolicy: string; ftpUsername: string; ftpPassword: string; databaseName: string; databaseUsername: string; databasePassword: string; hostLogin: string; hostPassword?: string; }
export interface AccountSecurity { mfaEnabled: boolean; }
export interface OIDCAccount {canUnbind?:boolean; enabled: boolean; bound: boolean; email?: string; }
export interface DomainResource { id: number; projectId: number; siteId: number; tenantName?: string; hostName: string; projectName: string; siteName: string; domain: string; kind: 'assigned' | 'custom'; status: 'pending' | 'approved' | 'rejected'; resolutionMode?: 'direct' | 'cname' | 'cdn'; cnameTarget?: string; dnsCredentialId?: number; dnsRecordId?: string; dnsRecordType?: 'A' | 'AAAA' | 'CNAME'; dnsLastError?: string; filingStatus?: 'exempt' | 'pending' | 'approved' | 'rejected'; filingNumber?: string; filingNote?: string; sslStatus: string; createdAt: string; }
export interface FTPResource { enabled?:boolean; id: number; projectId: number; hostName: string; projectName: string; username: string; rootPath: string; createdAt: string; }
export interface DatabaseResource { id: number; projectId: number; hostName: string; projectName: string; name: string; username: string; sizeBytes: number; status: 'active' | 'quota_suspended'; createdAt: string; }
export interface ResourceInventory { domains: DomainResource[]; ftpAccounts: FTPResource[]; databases: DatabaseResource[]; sites: Site[]; }
export interface Tenant { id: number; slug: string; name: string; status: string; lifecycleState?: 'active' | 'grace' | 'recycle' | 'purged'; planName: string; userCount: number; projectCount: number; expiresAt?: string; graceUntil?: string; purgeAfter?: string; backupPurgeAfter?: string; createdAt: string; }
export interface ControlNode {id:number;name:string;transport:"local"|"https";endpoint:string;rootDomain:string;tenantRoot:string;ftpCertificateDomain:string;enabled:boolean;lastSeenAt?:string;lastError:string}
export interface AccountProfile {id:number;slug:string;name:string;email:string;displayName:string;projectCount:number;}
export interface AdminProject {allowRuntimeChange?:boolean;manualRecycledAt?:string;purgeAfter?:string;recycleError?:string;pendingOwnership?:{targetOwnerId:number|null;credentialMode:"preserve"|"reset";stopServices:boolean;expectedVersion:number}; ownerTenantId?:number|null;managementLocked?:boolean;ownershipVersion?:number;nodeId:number;planId:number;expiresAt?:string;lifecycleState?:string; id: number; tenantName: string; hostName: string; name: string; domain: string; path: string; runPath: string; runtime: string; version: string; status: string; sslStatus: string; siteCount: number; ipAddress?: string; dedicatedIp: boolean; httpPort: number; httpsPort: number; createdAt: string; }
export type BatchOperation='create_users'|'create_hosts'|'assign_hosts'|'host_subscription'|'host_start'|'host_stop'|'host_password_reset'|'user_enable'|'user_disable';
export interface BatchRow {credentialMode?:string;stopServices?:boolean;resumeOwnership?:boolean;name?:string;slug?:string;email?:string;displayName?:string;password?:string;accountId?:number;account?:string;owner?:string;tenantId?:number;hostId?:number;host?:string;ownershipVersion?:number;nodeId?:number;planId?:number;runtime?:string;version?:string;runPath?:string;expiresAt?:string|null;setExpiry?:boolean;autoSSL?:boolean;}
export interface BatchPreviewRow {row:number;label:string;valid:boolean;detail:string;}
export interface AdminBatchItem {id:number;batchId:number;row:number;label:string;state:string;resourceId?:number;detail:string;}
export interface AdminBatch {id:number;administratorId:number;operation:BatchOperation;state:string;total:number;succeeded:number;failed:number;uncertain:number;pending:number;createdAt:string;finishedAt?:string;secretsExpireAt?:string;items?:AdminBatchItem[];}
export interface PanelSite { id: number; domain: string; path: string; phpVersion?: string; status: string; }
export interface RuntimeEnvironment { name: 'PHP' | 'Node.js' | 'Python' | 'Go' | 'Java'; componentTitle: string; componentStatus: 'installed' | 'not_installed' | 'probe_failed'; componentVersion?: string; componentLatestVersion?: string; componentUpdateAvailable?: boolean; componentInstallable: boolean; installed: string[]; available: string[]; installing: string[]; recommended?: string; detail?: string; patches?: { branch: string; installed: string; latest: string; updateAvailable: boolean }[]; }
export interface RuntimeMaintenanceJob { id: number; action: string; runtime: string; fromVersion: string; targetVersion: string; siteId?: number; status: string; phase: string; message: string; backupAvailable: boolean; createdAt: string; updatedAt: string; }
export interface RuntimeMaintenanceSite { site: { id: number; projectId: number; name: string; domain: string; runtime: string; version: string; status: string }; hostName: string; installedVersion: string; runningVersion: string; healthy: boolean; detail: string; checkedAt?: string; }
export interface IPAddress {nodeId:number; id: number; address: string; family: 'ipv4' | 'ipv6'; allocationMode: 'shared' | 'dedicated'; label: string; enabled: boolean; assignedSites: number; createdAt: string; }
export interface AdminActivity { administratorId?:number;impersonatedUserId?:number;impersonatedUserName?:string; id: number; userName?: string; action: string; resourceType: string; resourceId?: string; ipAddress?: string; success: boolean; detail: string; createdAt: string; }
export interface AdminOverview { users: Tenant[]; projects: AdminProject[]; domains: DomainResource[]; ipAddresses: IPAddress[]; logs: AdminActivity[]; }
export interface AdminSettings { domainApproval: boolean; filingRequired: boolean; cdnCnameTarget: string; graceDays: number; recycleDays: number; backupRetentionDays: number; smtp: { enabled: boolean; host: string; port: number; username: string; from: string; adminRecipients: string; startTls: boolean; secretConfigured: boolean; secret?: string }; oidc: { enabled: boolean; issuer: string; clientId: string; redirectUri: string; secretConfigured: boolean; secret?: string; bindingOnly: boolean; passwordLogin: boolean; autoCreate?:boolean; userPasswordLogin?:boolean; adminPasswordLogin?:boolean }; }
export interface PlanInput { name: string; storageBytes: number; databaseBytes: number; bandwidthBytes: number; bandwidthMbps?: number; processLimit: number; ftpLimit: number; databaseLimit: number; projectLimit: number; }
export interface TrashEntry {id:string;originalPath:string;name:string;deletedAt:string;size:number;}
export interface StartupSettings {entryFile:string;workDir:string;arguments:string[];environment:Record<string,string>;}
export interface WebsiteSettings {rewrite:string;redirectURL:string;redirectCode:number;forceHTTPS:boolean;index:string[];error404:string;error503:string;maintenance:boolean;}
export interface HostMetric {sampledAt:string;cpuPercent:number;memoryBytes:number;processCount:number;storageBytes:number;databaseBytes:number;bandwidthBytes:number;}
export interface FileEntry { name: string; path: string; directory: boolean; size: number; modified: string; }
export interface FileListing { path: string; entries: FileEntry[]; uploadLimit: number; }
export interface DatabaseSetup { host: string; port: number; name: string; user: string; password: string; }
export interface PanelSetup { url: string; apiKey: string; tlsInsecure: boolean; }
export type DNSProvider = 'cloudflare' | 'aliyun' | 'tencent' | 'west' | 'dnsmgr';
export interface DNSZoneChoice{id:string;name:string;verificationToken:string}
export interface DNSCredential { id: number; scope: string; label: string; provider: DNSProvider; zoneName: string; testStatus: 'untested' | 'testing' | 'passed' | 'failed'; lastTestedAt?: string; testError?: string; createdAt: string; updatedAt: string; }
export interface DNSCredentialInput {
verificationToken?:string;
label: string;
provider: DNSProvider;
zoneName: string;
credential: {endpoint?:string;userId?:string;apiKey?:string;username?:string;domainKey?:string; apiToken?: string; zoneId?: string; accessKeyId?: string; accessKeySecret?: string; secretId?: string; secretKey?: string };
}
export interface CertificateAutomation { siteId: number; mode: 'off' | 'manual' | 'http-01' | 'dns-01'; expiresAt?: string; lastAttemptAt?: string; nextAttemptAt?: string; lastError?: string; }
export interface InstallSetup {
controllerOnly?:boolean;
database: DatabaseSetup;
panel: PanelSetup;
rootDomain: string;
managementDomain: string;
ftpDomain: string;
domainApproval: boolean;
adminEmail: string;
adminName: string;
adminPassword: string;
}
export interface Dashboard {
plan: Plan;
usage: Usage;
projects: APIProject[];
activities: ActivityEntry[];
hostScoped: boolean;
domainApproval: boolean;
rootDomain: string;
projectRoot: string;
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const response = await fetch(path, { credentials: 'same-origin', ...init, headers: { 'Content-Type': 'application/json', ...init?.headers } });
if (!response.ok) {
throw await responseError(response);
}
if (response.status === 204) return undefined as T;
return response.json() as Promise<T>;
}
async function responseError(response: Response) {
const payload = await response.json().catch(() => null) as { error?: { message?: string; code?: string } } | null;
const error = new Error(payload?.error?.message || `请求失败(${response.status})`) as Error & { status?: number; code?: string };
error.status = response.status;
error.code = payload?.error?.code;
return error;
}
function fileURL(projectID: number, path: string, download = false) {
const query = new URLSearchParams({ path });
if (download) query.set('download', '1');
return `/api/v1/projects/${projectID}/files?${query}`;
}
function nodeQuery(nodeId?:number){return nodeId ? '?nodeId='+nodeId : ''}
export interface NodeTask{projectId?:number;id:number;nodeId:number;operation:string;state:string;detail:string;startedAt:string}
export const api = {
integrationKeys:()=>request<{keys:IntegrationKey[];scopes:string[];webhooks:IntegrationWebhook[]}>('/api/v1/admin/integration-keys'),
createIntegrationKey:(v:{name:string;scopes:string[];expiresAt:string;webhookURL:string})=>request<{token:string;webhookSecret:string}>('/api/v1/admin/integration-keys',{method:'POST',body:JSON.stringify(v)}),
revokeIntegrationKey:(id:number)=>request<void>(`/api/v1/admin/integration-keys/${id}`,{method:'DELETE'}),
schedules:()=>request<{schedules:UserSchedule[]}>('/api/v1/schedules'),
saveSchedule:(v:UserSchedule)=>{const{id,nextRunAt:_next,lastState:_state,...input}=v;return request<{id:number}>('/api/v1/schedules'+(id?'/'+id:''),{method:id?'PUT':'POST',body:JSON.stringify(input)})},
deleteSchedule:(id:number)=>request<void>(`/api/v1/schedules/${id}`,{method:'DELETE'}),
deletePlan:(id:number,confirmation:string)=>request<void>(`/api/v1/admin/plans/${id}`,{method:'DELETE',body:JSON.stringify({confirmation})}),
unbindDomain:(id:number,confirmation:string,admin=false)=>request<void>(`/api/v1/${admin?'admin/':''}domains/${id}`,{method:'DELETE',body:JSON.stringify({confirmation})}),
runSchedule:(id:number)=>request<void>(`/api/v1/schedules/${id}/run`,{method:'POST'}),
scheduleRuns:(id:number)=>request<{runs:ScheduleRun[]}>(`/api/v1/schedules/${id}/runs`),
scheduler:()=>request<{nodeId:number;lastTick?:string}>('/api/v1/admin/scheduler'),
configureScheduler:(nodeId:number)=>request<void>('/api/v1/admin/scheduler',{method:'POST',body:JSON.stringify({nodeId})}),
manageFTP:(id:number,action:string)=>request<{password?:string}>(`/api/v1/projects/${id}/ftp`,{method:'POST',body:JSON.stringify({action})}),
previewBatch:(operation:BatchOperation,rows:BatchRow[])=>request<{rows:BatchPreviewRow[]}>('/api/v1/admin/batches/preview',{method:'POST',body:JSON.stringify({operation,rows})}),
createBatch:(operation:BatchOperation,rows:BatchRow[],requestKey:string)=>request<{batch:AdminBatch}>('/api/v1/admin/batches',{method:'POST',body:JSON.stringify({operation,rows,requestKey})}),
batches:()=>request<{batches:AdminBatch[]}>('/api/v1/admin/batches',{cache:'no-store'}),
batch:(id:number)=>request<{batch:AdminBatch}>(`/api/v1/admin/batches/${id}`,{cache:'no-store'}),
cancelBatch:(id:number)=>request<void>(`/api/v1/admin/batches/${id}/cancel`,{method:'POST'}),
batchDownloadURL:(id:number)=>`/api/v1/admin/batches/${id}/download`,
startImpersonation:(input:{tenantId?:number;projectId?:number})=>request<{user:User}>('/api/v1/admin/impersonation',{method:'POST',body:JSON.stringify(input)}),
stopImpersonation:()=>request<{user:User}>('/api/v1/auth/impersonation/stop',{method:'POST'}),
nodeTasks:(id:number)=>request<{tasks:NodeTask[]}>('/api/v1/admin/nodes/'+id+'/tasks'),
resolveNodeTask:(node:number,id:number,note:string)=>request<void>('/api/v1/admin/nodes/'+node+'/tasks/'+id+'/resolve',{method:'POST',body:JSON.stringify({note})}),
reconcileNode:(id:number)=>request<void>('/api/v1/admin/nodes/'+id+'/reconcile',{method:'POST'}),
accountProfile:(id:number)=>request<AccountProfile>('/api/v1/admin/tenants/'+id),
updateAccount:(id:number,p:AccountProfile)=>request<void>('/api/v1/admin/tenants/'+id,{method:'PUT',body:JSON.stringify(p)}),
deleteAccount:(id:number,confirmation:string)=>request<void>('/api/v1/admin/tenants/'+id,{method:'DELETE',body:JSON.stringify({confirmation})}),
detachRecycledHost:(host:AdminProject)=>request<void>(`/api/v1/admin/projects/${host.id}/recycled-owner`,{method:'DELETE',body:JSON.stringify({confirmation:host.hostName,ownershipVersion:host.ownershipVersion})}),
renameHost:(id:number,name:string,allowRuntimeChange?:boolean)=>request<void>('/api/v1/admin/projects/'+id,{method:'PUT',body:JSON.stringify({name,allowRuntimeChange})}),
recycleHost:(id:number,confirmation:string)=>request<void>('/api/v1/admin/projects/'+id,{method:'DELETE',body:JSON.stringify({confirmation})}),
restoreHost:(id:number)=>request<void>('/api/v1/admin/projects/'+id+'/restore',{method:'POST'}),
updateNode:(id:number,input:Record<string,unknown>)=>request<void>('/api/v1/admin/nodes/'+id,{method:'PATCH',body:JSON.stringify(input)}),
deleteNode:(id:number,confirmation:string)=>request<void>('/api/v1/admin/nodes/'+id,{method:'DELETE',body:JSON.stringify({confirmation})}),
nodes:()=>request<{nodes:ControlNode[]}>('/api/v1/admin/nodes'),
createNode:(input:Record<string,unknown>)=>request<{id:number}>('/api/v1/admin/nodes',{method:'POST',body:JSON.stringify(input)}),
pairNode:(id:number)=>request<Record<string,unknown>>('/api/v1/admin/nodes/'+id+'/pair',{method:'POST'}),
probeNode:(id:number)=>request<void>('/api/v1/admin/nodes/'+id+'/probe',{method:'POST'}),
enableNode:(id:number,enabled:boolean)=>request<void>('/api/v1/admin/nodes/'+id,{method:'PUT',body:JSON.stringify({enabled})}),
createHost:(input:Record<string,unknown>)=>request<{project:APIProject;credentials:Credentials}>('/api/v1/admin/projects',{method:'POST',body:JSON.stringify(input)}),
hostSubscription:(id:number,planId:number,expiresAt?:string)=>request<void>('/api/v1/admin/projects/'+id+'/subscription',{method:'PUT',body:JSON.stringify({planId,expiresAt:expiresAt||null})}),
setupStatus: () => request<{required:boolean;controllerOnly?:boolean}>('/api/v1/setup/status', { cache: 'no-store' }),
testDatabase: (token: string, database: DatabaseSetup) => request<{ ok: boolean; message: string }>('/api/v1/setup/test-database', { method: 'POST', headers: { 'X-Setup-Token': token }, body: JSON.stringify(database) }),
testPanel: (token: string, panel: PanelSetup) => request<{ ok: boolean; message: string; versions: RuntimeCatalog; runtimes: RuntimeCapabilities }>('/api/v1/setup/test-panel', { method: 'POST', headers: { 'X-Setup-Token': token }, body: JSON.stringify(panel) }),
install: (token: string, input: InstallSetup) => request<{ ok: boolean; message: string }>('/api/v1/setup/install', { method: 'POST', headers: { 'X-Setup-Token': token }, body: JSON.stringify(input) }),
me: () => request<{ user: User }>('/api/v1/me'),
login: (identifier: string, password: string, totpCode = '') => request<{ user: User }>('/api/v1/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password, totpCode }) }),
oidcStatus: () => request<{ enabled: boolean; autoCreate?:boolean;userPasswordLogin?:boolean;adminPasswordLogin?:boolean;hostPasswordLogin?:boolean }>('/api/v1/auth/oidc/status'),
pendingOIDC:()=>request<{pending:boolean;allowCreate?:boolean;email?:string;displayName?:string}>('/api/v1/auth/oidc/pending'),
completeOIDC:(input:{action:'bind'|'create';identifier?:string;password?:string;totpCode?:string})=>request<{completed:boolean}>('/api/v1/auth/oidc/complete',{method:'POST',body:JSON.stringify(input)}),
beginOIDC: (mode: 'login' | 'bind') => request<{ url: string }>(`/api/v1/auth/oidc/start?mode=${mode}`),
logout: () => request<void>('/api/v1/auth/logout', { method: 'POST' }),
accountSecurity: () => request<AccountSecurity>('/api/v1/account/security'),
accountOIDC: () => request<OIDCAccount>('/api/v1/account/oidc'),
unbindOIDC: (currentPassword: string) => request<void>('/api/v1/account/oidc', { method: 'DELETE', body: JSON.stringify({ currentPassword }) }),
changePassword: (currentPassword: string, newPassword: string) => request<void>('/api/v1/account/password', { method: 'PUT', body: JSON.stringify({ currentPassword, newPassword }) }),
setupMFA: (currentPassword: string) => request<{ secret: string; otpauthURI: string }>('/api/v1/account/mfa/setup', { method: 'POST', body: JSON.stringify({ currentPassword }) }),
enableMFA: (code: string) => request<{ recoveryCodes: string[] }>('/api/v1/account/mfa/enable', { method: 'POST', body: JSON.stringify({ code }) }),
disableMFA: (currentPassword: string, code: string) => request<void>('/api/v1/account/mfa/disable', { method: 'POST', body: JSON.stringify({ currentPassword, code }) }),
dashboard: (projectID?: number) => request<Dashboard>('/api/v1/dashboard' + (projectID ? '?projectId=' + projectID : '')),
adminAudit: (query:URLSearchParams) => request<{logs:AdminActivity[];total:number;page:number;limit:number}>('/api/v1/admin/audit?'+query.toString(),{cache:'no-store'}),
activities: (projectID?: number) => request<{ activities: ActivityEntry[] }>('/api/v1/activities' + (projectID ? '?projectId=' + projectID : ''), { cache: 'no-store' }),
runtimeCatalog: (projectId?:number) => request<{ versions: RuntimeCatalog }>('/api/v1/runtime-catalog'+(projectId ? "?projectId="+projectId : "")),
createProject: (draft: ProjectDraft) => request<{ project: APIProject; credentials: Credentials }>('/api/v1/projects', { method: 'POST', body: JSON.stringify(draft) }),
setProjectState: (id: number, enabled: boolean) => request<void>(`/api/v1/projects/${id}/state`, { method: 'POST', body: JSON.stringify({ enabled }) }),
siteRuntimeJobs:(id:number,site:number)=>request<{jobs:RuntimeMaintenanceJob[]}>(`/api/v1/projects/${id}/sites/${site}/runtime`,{cache:'no-store'}),
changeSiteRuntime:(id:number,site:number,runtime:string,version:string,entryFile:string) => request<{jobId:number}>(`/api/v1/projects/${id}/sites/${site}/runtime`,{method:'PUT',body:JSON.stringify({runtime,version,entryFile})}),
setProjectRunPath: (id: number, runPath: string) => request<{ project: APIProject }>(`/api/v1/projects/${id}/run-path`, { method: 'PUT', body: JSON.stringify({ runPath }) }),
projectCredentials: (id: number) => request<{ credentials: Credentials }>(`/api/v1/projects/${id}/credentials`),
resetHostPassword: (id: number) => request<{ password: string }>(`/api/v1/projects/${id}/host-password/reset`, { method: 'POST' }),
projectSites: (id: number) => request<{ sites: Site[] }>(`/api/v1/projects/${id}/sites`),
createSite: (id: number, input: SiteDraft) => request<{ site: Site }>(`/api/v1/projects/${id}/sites`, { method: 'POST', body: JSON.stringify(input) }),
setSiteState: (projectID: number, siteID: number, enabled: boolean) => request<{ site: Site }>(`/api/v1/projects/${projectID}/sites/${siteID}/state`, { method: 'POST', body: JSON.stringify({ enabled }) }),
checkSiteDeployment: (projectID: number, siteID: number, entryFile: string) => request<{ check: DeploymentCheck }>(`/api/v1/projects/${projectID}/sites/${siteID}/deployment/check`, { method: 'POST', body: JSON.stringify({ entryFile }) }),
deploySite: (projectID: number, siteID: number, entryFile: string) => request<{ site: Site }>(`/api/v1/projects/${projectID}/sites/${siteID}/deployment`, { method: 'POST', body: JSON.stringify({ entryFile }) }),
requestAutoCertificate: (projectID: number, siteID: number) => request<{ site: Site }>(`/api/v1/projects/${projectID}/sites/${siteID}/certificate/auto`, { method: 'POST' }),
requestDNSCertificate: (projectID: number, siteID: number) => request<{ site: Site; automation: CertificateAutomation }>(`/api/v1/projects/${projectID}/sites/${siteID}/certificate/dns`, { method: 'POST' }),
certificateAutomation: (projectID: number, siteID: number) => request<{ automation: CertificateAutomation }>(`/api/v1/projects/${projectID}/sites/${siteID}/certificate`),
installManualCertificate: (projectID: number, siteID: number, certificate: string, privateKey: string) => request<{ site: Site }>(`/api/v1/projects/${projectID}/sites/${siteID}/certificate/manual`, { method: 'PUT', body: JSON.stringify({ certificate, privateKey }) }),
disableCertificate: (projectID: number, siteID: number) => request<{ site: Site }>(`/api/v1/projects/${projectID}/sites/${siteID}/certificate`, { method: 'DELETE' }),
deleteSite: (projectID: number, siteID: number) => request<void>(`/api/v1/projects/${projectID}/sites/${siteID}`, { method: 'DELETE' }),
resources: () => request<ResourceInventory>('/api/v1/resources'),
bindDomain: (projectID: number, domain: string) => request<{ domain: DomainResource }>(`/api/v1/projects/${projectID}/domains`, { method: 'POST', body: JSON.stringify({ domain }) }),
bindSiteDomain: (projectID: number, siteID: number, domain: string) => request<{ domain: DomainResource }>(`/api/v1/projects/${projectID}/sites/${siteID}/domains`, { method: 'POST', body: JSON.stringify({ domain }) }),
files: (projectID: number, path: string) => request<FileListing>(fileURL(projectID, path)),
fileText: async (projectID: number, path: string) => {
const response = await fetch(fileURL(projectID, path, true), { credentials: 'same-origin' });
if (!response.ok) throw await responseError(response);
return response.text();
},
fileDownloadURL: (projectID: number, path: string) => fileURL(projectID, path, true),
uploadFile: async (projectID: number, path: string, file: File, overwrite = false) => {
const body = new FormData(); body.set('path', path); body.set('file', file); body.set('overwrite', String(overwrite));
const response = await fetch(`/api/v1/projects/${projectID}/files`, { method: 'POST', credentials: 'same-origin', body });
if (!response.ok) throw await responseError(response);
return response.json() as Promise<{ name: string; size: number }>;
},
writeFile: (projectID: number, path: string, content: string, overwrite: boolean) => request<void>(`/api/v1/projects/${projectID}/files`, { method: 'PUT', body: JSON.stringify({ path, content, overwrite }) }),
siteStartup:(id:number,site:number)=>request<{startup:StartupSettings}>(`/api/v1/projects/${id}/sites/${site}/startup`),
saveSiteStartup:(id:number,site:number,startup:StartupSettings)=>request<void>(`/api/v1/projects/${id}/sites/${site}/startup`,{method:'PUT',body:JSON.stringify(startup)}),
websiteSettings:(id:number,site:number)=>request<{settings:WebsiteSettings}>(`/api/v1/projects/${id}/sites/${site}/settings`),
saveWebsiteSettings:(id:number,site:number,settings:WebsiteSettings)=>request<void>(`/api/v1/projects/${id}/sites/${site}/settings`,{method:'PUT',body:JSON.stringify(settings)}),
siteLog:(id:number,site:number,kind:string,search='')=>request<{lines:string[];available:boolean}>(`/api/v1/projects/${id}/sites/${site}/logs?`+new URLSearchParams({kind,search,lines:'500'})),
hostMetrics:(id:number,days:number)=>request<{samples:HostMetric[]}>(`/api/v1/projects/${id}/metrics?days=${days}`),
fileAction:(id:number,action:string,path:string,to='')=>request<void>(`/api/v1/projects/${id}/file-actions`,{method:'POST',body:JSON.stringify({action,path,to})}),
fileTrash:(id:number)=>request<{entries:TrashEntry[]}>(`/api/v1/projects/${id}/file-actions`),
trashFile: (projectID: number, path: string) => request<void>(fileURL(projectID, path), { method: 'DELETE' }),
emptyTrash: (projectID: number) => request<void>(`/api/v1/projects/${projectID}/files?emptyTrash=1`, { method: 'DELETE' }),
tenants: () => request<{ tenants: Tenant[] }>('/api/v1/admin/tenants'),
createTenant: (input: Record<string, unknown>) => request<{ id: number }>('/api/v1/admin/tenants', { method: 'POST', body: JSON.stringify(input) }),
plans: () => request<{ plans: Plan[] }>('/api/v1/admin/plans'),
createPlan: (input: PlanInput) => request<{ id: number }>('/api/v1/admin/plans', { method: 'POST', body: JSON.stringify(input) }),
domainApproval: () => request<{ enabled: boolean }>('/api/v1/admin/settings/domain-approval'),
setDomainApproval: (enabled: boolean) => request<void>('/api/v1/admin/settings/domain-approval', { method: 'PUT', body: JSON.stringify({ enabled }) }),
pendingDomains: () => request<{ domains: DomainResource[] }>('/api/v1/admin/domains/pending'),
reviewDomain: (id: number, approved: boolean) => request<{ domain: DomainResource }>(`/api/v1/admin/domains/${id}/review`, { method: 'POST', body: JSON.stringify({ approved }) }),
adminOverview: () => request<AdminOverview>('/api/v1/admin/overview'),
adminSettings: () => request<AdminSettings>('/api/v1/admin/settings'),
saveAdminSettings: (input: AdminSettings) => {
const {domainApproval,filingRequired,cdnCnameTarget,graceDays,recycleDays,backupRetentionDays,smtp,oidc}=input;
return request<void>('/api/v1/admin/settings',{method:'PUT',body:JSON.stringify({domainApproval,filingRequired,cdnCnameTarget,graceDays,recycleDays,backupRetentionDays,smtp:{enabled:smtp.enabled,host:smtp.host,port:smtp.port,username:smtp.username,secret:smtp.secret,from:smtp.from,adminRecipients:smtp.adminRecipients,startTls:smtp.startTls},oidc:{enabled:oidc.enabled,issuer:oidc.issuer,clientId:oidc.clientId,secret:oidc.secret,redirectUri:oidc.redirectUri,autoCreate:oidc.autoCreate===true,userPasswordLogin:oidc.userPasswordLogin!==false,adminPasswordLogin:oidc.adminPasswordLogin!==false}})});
},
addIPAddress: (input: {nodeId?:number; address: string; allocationMode: 'shared' | 'dedicated'; label: string }) => request<{ id: number }>('/api/v1/admin/ip-addresses'+nodeQuery(input.nodeId), { method: 'POST', body: JSON.stringify({...input,nodeId:undefined}) }),
deleteIPAddress: (id: number) => request<void>(`/api/v1/admin/ip-addresses/${id}`, { method: 'DELETE' }),
setProjectNetwork: (id: number, input: { ipId?: number; dedicated: boolean; httpPort: number; httpsPort: number }) => request<void>(`/api/v1/admin/projects/${id}/network`, { method: 'PUT', body: JSON.stringify(input) }),
panelSites: (nodeId?:number) => request<{ sites: PanelSite[]; versions: RuntimeCatalog }>('/api/v1/admin/panel-sites'+nodeQuery(nodeId)),
runtimeEnvironments: (nodeId?:number) => request<{ environments: RuntimeEnvironment[] }>('/api/v1/admin/runtime-environments'+nodeQuery(nodeId), { cache: 'no-store' }),
runtimeMaintenance: (nodeId?:number) => request<{ sites: RuntimeMaintenanceSite[]; jobs: RuntimeMaintenanceJob[] }>('/api/v1/admin/runtime-maintenance'+nodeQuery(nodeId), { cache: 'no-store' }),
checkRuntimeUpdates: (nodeId?:number) => request<{ jobId: number }>('/api/v1/admin/runtime-maintenance/check'+nodeQuery(nodeId), { method: 'POST' }),
updatePHPPatch: (branch: string, target: string,nodeId?:number) => request<{ jobId: number }>('/api/v1/admin/runtime-maintenance/php'+nodeQuery(nodeId), { method: 'POST', body: JSON.stringify({ branch, target }) }),
migrateSiteRuntime: (siteID: number, version: string, allowBranchChange = false, entryFile = '') => request<{ jobId: number }>(`/api/v1/admin/runtime-maintenance/sites/${siteID}`, { method: 'POST', body: JSON.stringify({ version, allowBranchChange, entryFile }) }),
resumeRuntimeMaintenance: (id: number,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-maintenance/jobs/${id}/resume`+nodeQuery(nodeId), { method: 'POST' }),
installRuntimeComponent: (runtime: string,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-components/${encodeURIComponent(runtime)}/install`+nodeQuery(nodeId), { method: 'POST' }),
installRuntimeEnvironment: (runtime: string, version: string,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-environments/${encodeURIComponent(runtime)}/install`+nodeQuery(nodeId), { method: 'POST', body: JSON.stringify({ version }) }),
adoptPanelSite: (id: number, input: { tenantId: number; name: string; runtime: string; version: string; runPath: string; autoSSL: boolean;planId:number },nodeId?:number) => request<{ project: APIProject; credentials: Credentials }>(`/api/v1/admin/panel-sites/${id}/adopt`+nodeQuery(nodeId), { method: 'POST', body: JSON.stringify(input) }),
updateDomainMetadata: (id: number, input: Record<string, unknown>) => request<void>(`/api/v1/admin/domains/${id}/metadata`, { method: 'PUT', body: JSON.stringify(input) }),
provisionDomainDNS: (id: number, admin = false) => request<{ domain: DomainResource }>(`${admin ? '/api/v1/admin' : '/api/v1'}/domains/${id}/dns`, { method: 'POST' }),
removeDomainDNS: (id: number, admin = false) => request<{ domain: DomainResource }>(`${admin ? '/api/v1/admin' : '/api/v1'}/domains/${id}/dns`, { method: 'DELETE' }),
setTenantExpiry: (id: number, expiresAt?: string) => request<void>(`/api/v1/admin/tenants/${id}/expiry`, { method: 'PUT', body: JSON.stringify({ expiresAt: expiresAt || null }) }),
discoverDNSZones:(input:DNSCredentialInput,admin=false)=>request<{zones:DNSZoneChoice[]}>(`${admin?'/api/v1/admin':'/api/v1'}/dns-credentials/discover`,{method:'POST',body:JSON.stringify(input)}),
dnsCredentials: (admin = false) => request<{ credentials: DNSCredential[] }>(`${admin ? '/api/v1/admin' : '/api/v1'}/dns-credentials`),
createDNSCredential: (input: DNSCredentialInput, admin = false) => request<{ credential: DNSCredential }>(`${admin ? '/api/v1/admin' : '/api/v1'}/dns-credentials`, { method: 'POST', body: JSON.stringify(input) }),
updateDNSCredential: (id: number, input: DNSCredentialInput, admin = false) => request<{ credential: DNSCredential }>(`${admin ? '/api/v1/admin' : '/api/v1'}/dns-credentials/${id}`, { method: 'PUT', body: JSON.stringify(input) }),
testDNSCredential: (id: number, admin = false) => request<{ credential: DNSCredential }>(`${admin ? '/api/v1/admin' : '/api/v1'}/dns-credentials/${id}/test`, { method: 'POST' }),
deleteDNSCredential: (id: number, admin = false) => request<void>(`${admin ? '/api/v1/admin' : '/api/v1'}/dns-credentials/${id}`, { method: 'DELETE' }),
};
+5
View File
@@ -0,0 +1,5 @@
import {expect,it} from 'vitest';
import {batchTemplate,parseBatchJSON} from './batchJSON';
it('imports typed JSON and preserves supplied passwords exactly',()=>{const input=batchTemplate('create_users');input.rows[0].password=' =secret,with\nquotes" ';expect(parseBatchJSON('\uFEFF'+JSON.stringify(input),'create_users')[0].password).toBe(input.rows[0].password)});
it('rejects result files, wrong operations, untyped booleans and prototype keys',()=>{for(const input of ['{}','[]','{"format":"sea-vhost.batch-result","version":1,"operation":"create_users","rows":[{}]}',JSON.stringify(batchTemplate('create_hosts')),'{"format":"sea-vhost.batch","version":1,"operation":"create_users","rows":[{"autoSSL":"false"}]}','{"format":"sea-vhost.batch","version":1,"operation":"create_users","rows":[{"__proto__":{"admin":true}}]}'])expect(()=>parseBatchJSON(input,'create_users')).toThrow()});
it('explicitly unbinds owners and accepts expiry null without losing boolean values',()=>{const input=batchTemplate('assign_hosts');input.rows[0].stopServices=false;const row=parseBatchJSON(JSON.stringify(input),'assign_hosts')[0];expect(row).toMatchObject({tenantId:0,owner:'',stopServices:false});expect(parseBatchJSON(JSON.stringify(batchTemplate('host_subscription')),'host_subscription')[0]).toMatchObject({expiresAt:null,setExpiry:true})});
+42
View File
@@ -0,0 +1,42 @@
import type {BatchOperation,BatchRow} from './api';
const strings=new Set(['name','slug','email','displayName','password','account','owner','host','credentialMode','runtime','version','runPath']);
const numbers=new Set(['accountId','tenantId','hostId','ownershipVersion','nodeId','planId']);
const booleans=new Set(['stopServices','resumeOwnership','setExpiry','autoSSL']);
export function parseBatchJSON(source:string,operation:BatchOperation):BatchRow[]{
if(new TextEncoder().encode(source).length>256*1024)throw new Error('JSON 文件不能超过 256 KiB');
let data:unknown;try{data=JSON.parse(source.replace(/^\uFEFF/,''))}catch{throw new Error('JSON 格式错误,请使用下载的模板')}
if(!data||typeof data!=='object'||Array.isArray(data))throw new Error('JSON 顶层必须为批量模板对象');
const envelope=data as Record<string,unknown>;
if(Object.keys(envelope).some(key=>!['format','version','operation','rows'].includes(key))||envelope.format!=='sea-vhost.batch'||envelope.version!==1||envelope.operation!==operation)throw new Error('JSON 模板类型、版本或操作不匹配');
if(!Array.isArray(envelope.rows)||envelope.rows.length<1||envelope.rows.length>500)throw new Error('JSON rows 需要 1–500 条记录,请按操作上限分批导入');
return envelope.rows.map((record,index)=>{
if(!record||typeof record!=='object'||Array.isArray(record))throw new Error(`第 ${index+1} 条必须为对象`);
const out:Record<string,unknown>={};
for(const [field,value]of Object.entries(record)){
if(strings.has(field)){if(field==='owner'&&value===null){out.owner='';continue}if(typeof value!=='string')throw new Error(`第 ${index+1} 条 ${field} 必须为字符串`);out[field]=field==='password'?value:value.trim()}
else if(numbers.has(field)){if(typeof value!=='number'||!Number.isSafeInteger(value)||value<0)throw new Error(`第 ${index+1} 条 ${field} 必须为非负安全整数`);out[field]=value}
else if(booleans.has(field)){if(typeof value!=='boolean')throw new Error(`第 ${index+1} 条 ${field} 必须为布尔值`);out[field]=value}
else if(field==='expiresAt'){if(value!==null&&(typeof value!=='string'||Number.isNaN(new Date(value).getTime())))throw new Error(`第 ${index+1} 条到期时间无效`);out.expiresAt=value===null?null:new Date(value as string).toISOString();out.setExpiry=true}
else throw new Error(`第 ${index+1} 条包含未知字段:${field}`);
}
if('owner'in out)out.tenantId=0;
if(operation==='create_users'&&!out.displayName)out.displayName=out.name;
return out as BatchRow;
});
}
export function batchTemplate(operation:BatchOperation){
const row:BatchRow=operation==='create_users'?{slug:'demo-0001',name:'示例用户',email:'demo-0001@vhost.ser888.cn',displayName:'示例用户',password:''}
:operation==='create_hosts'?{name:'site-0001',owner:'',runtime:'PHP',version:'8.4',runPath:'/public',expiresAt:null,autoSSL:false}
:operation==='user_enable'||operation==='user_disable'?{account:'demo-0001@vhost.ser888.cn'}
:operation==='assign_hosts'?{host:'sv0123456789',owner:'',credentialMode:'preserve',stopServices:true,resumeOwnership:false}
:operation==='host_subscription'?{host:'sv0123456789',expiresAt:null,setExpiry:true}
:{host:'sv0123456789'};
return {format:'sea-vhost.batch',version:1,operation,rows:[row]};
}
export function downloadBatchTemplate(operation:BatchOperation){
const url=URL.createObjectURL(new Blob([JSON.stringify(batchTemplate(operation),null,2)+'\n'],{type:'application/json;charset=utf-8'}));
const link=document.createElement('a');link.href=url;link.download=`sea-vhost-${operation}-template.json`;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
}
+83
View File
@@ -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>
}
+107
View File
@@ -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); }
+23
View File
@@ -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}
+33
View File
@@ -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:'配额暂停'};
+21
View File
@@ -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>;
}
+30
View File
@@ -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>
);
}
+13
View File
@@ -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>
);
}
+19
View File
@@ -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};
}
+55
View File
@@ -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>
);
}
+100
View File
@@ -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>;
}
+142
View File
@@ -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 }];
}
+49
View File
@@ -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>
}
+316
View File
@@ -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>
}
+195
View File
@@ -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}
+29
View File
@@ -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:'登录失败,请重试'}
+12
View File
@@ -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>
);
}
+61
View File
@@ -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>;
}
+17
View File
@@ -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>
}
+11
View File
@@ -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>
}
+70
View File
@@ -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('/', '-');
}
+47
View File
@@ -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>
);
}
+175
View File
@@ -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}</>;
}
+11
View File
@@ -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>;
}
+82
View File
@@ -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 : '操作失败';
}
+33
View File
@@ -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>
);
}
+17
View File
@@ -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>
}
+11
View File
@@ -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>
}
+13
View File
@@ -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>}
+21
View File
@@ -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>
}
+23
View File
@@ -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}
+26
View File
@@ -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]);
}
+27
View File
@@ -0,0 +1,27 @@
import type { ActivityEntry, Plan, Project, RuntimeCatalog, Usage } from './types';
export const demoRuntimeVersions: RuntimeCatalog = {
PHP: ['8.4', '8.2', '8.1', '8.0', '7.4', '7.2'],
'Node.js': ['v24.21.0', 'v22.23.3'],
Python: ['3.12.3', '3.9.19'],
Go: ['go1.27.1', 'go1.26.8', 'go1.25.14'],
Java: ['jdk-25.0.3', 'jdk-21.0.2', 'jdk-20.0.2'],
};
export const initialProjects: Project[] = [
{ allowRuntimeChange:true, id: 1, hostName: 'sv8c0a6d2f91', name: 'main-site', domain: 'sv8c0a6d2f91.vhost.ser888.cn', path: '/www/wwwroot/seavHost/vHost/sv8c0a6d2f91', runPath: '/public', runtime: 'PHP', version: '8.2', status: 'running', ssl: true, trafficGB: 12.6, createdAt: '2026-09-12 10:24' },
{ id: 2, hostName: 'sv2f18b470ce', name: 'blog', domain: 'sv2f18b470ce.vhost.ser888.cn', path: '/www/wwwroot/seavHost/vHost/sv2f18b470ce', runPath: '/dist', runtime: 'Node.js', version: 'v22.23.3', status: 'running', ssl: true, trafficGB: 8.3, createdAt: '2026-09-18 14:37' },
{ id: 3, hostName: 'sv75e41d09ab', name: 'api', domain: 'sv75e41d09ab.vhost.ser888.cn', path: '/www/wwwroot/seavHost/vHost/sv75e41d09ab', runPath: '/', runtime: 'Python', version: '3.12.3', status: 'running', ssl: true, trafficGB: 21.4, createdAt: '2026-09-25 09:21' },
{ id: 4, hostName: 'sv19a3f2c8d4', name: 'worker', domain: 'sv19a3f2c8d4.vhost.ser888.cn', path: '/www/wwwroot/seavHost/vHost/sv19a3f2c8d4', runPath: '/', runtime: 'Go', version: 'go1.25.14', status: 'running', ssl: true, trafficGB: 6.7, createdAt: '2026-10-01 16:02' },
{ id: 5, hostName: 'sve0c4217b9d', name: 'service', domain: 'sve0c4217b9d.vhost.ser888.cn', path: '/www/wwwroot/seavHost/vHost/sve0c4217b9d', runPath: '/web', runtime: 'Java', version: 'jdk-21.0.2', status: 'stopped', ssl: false, trafficGB: 1.2, createdAt: '2026-10-03 11:10' },
];
export const demoPlan: Plan = { id: 1, name: '标准版', storageBytes: 50 * 1024 ** 3, databaseBytes: 20 * 1024 ** 3, bandwidthBytes: 500 * 1024 ** 3, processLimit: 100, ftpLimit: 10, databaseLimit: 10, projectLimit: 10 };
export const demoUsage: Usage = { storageBytes: 12.6 * 1024 ** 3, databaseBytes: 3.2 * 1024 ** 3, bandwidthBytes: 86.4 * 1024 ** 3, processCount: 18, measuredAt: '2026-10-06T10:21:00+08:00' };
export const demoActivities: ActivityEntry[] = [
{ createdAt: '2026-10-06T10:21:00+08:00', action: 'upload', resourceType: 'file', detail: '上传文件 /main-site/public/index.php', success: true },
{ createdAt: '2026-10-06T09:17:00+08:00', action: 'create', resourceType: 'database', detail: '创建数据库 sv_acme_blog', success: true },
{ createdAt: '2026-10-05T18:42:00+08:00', action: 'state', resourceType: 'project', detail: '重启项目 blog', success: true },
{ createdAt: '2026-10-05T16:05:00+08:00', action: 'bind', resourceType: 'domain', detail: '绑定域名 api.vhost.ser888.cn', success: true },
{ createdAt: '2026-10-04T11:33:00+08:00', action: 'update', resourceType: 'ftp', detail: '更新 FTP 密码', success: true },
];
+12
View File
@@ -0,0 +1,12 @@
export function formatBytes(bytes: number) {
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
const power = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
const value = bytes / 1024 ** power;
return `${value >= 10 || power === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[power]}`;
}
export function usagePercent(value: number, limit: number) {
if (limit <= 0) return 0;
return Math.min(100, Math.max(0, Math.round((value / limit) * 100)));
}
+11
View File
@@ -0,0 +1,11 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
import './styles.css';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
);
+8
View File
@@ -0,0 +1,8 @@
export function normalizeRunPath(value: string) {
const trimmed = value.trim();
const candidate = trimmed === '' ? '/' : trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
if (candidate === '/') return candidate;
if (candidate.length > 255 || candidate.includes('\\') || candidate.includes('//')) return '';
const segments = candidate.slice(1).split('/');
return segments.every((segment) => segment !== '.' && segment !== '..' && segment.length <= 80 && /^[A-Za-z0-9._-]+$/.test(segment)) ? candidate : '';
}
+6
View File
@@ -0,0 +1,6 @@
@import "./styles/tokens.css";
@import "./styles/primitives.css";
@import "./styles/components.css";
@import "./styles/console.css";
@import "./styles/finish.css";
File diff suppressed because it is too large. Load diff
+281
View File
@@ -0,0 +1,281 @@
/* Shared surfaces. These are also used by infrequent dialogs and empty states. */
.unified-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; margin-bottom: 24px; }
.page-heading-actions { display: flex; flex: 0 0 auto; flex-wrap: wrap; align-items: center; gap: 10px; padding-top: 2px; }
.page-heading-actions button { white-space: nowrap; }
.batch-create-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.batch-list-toolbar { justify-content: flex-end; }
.host-row-actions { display: grid; grid-template-columns: repeat(2,max-content); gap: 8px 14px; align-items: center; min-width: 140px; }
.host-row-actions .danger-text { grid-column: 2; }
.impersonation-banner { align-items: center; }
.page-heading-actions .row-actions { gap: 10px; }
.table-scroll { max-width: 100%; overscroll-behavior-x: contain; scrollbar-width: thin; scrollbar-color: #c6d3e4 transparent; }
.table-scroll:focus-visible { outline: 2px solid var(--blue); }
tbody tr:hover { background: #fafcff; }
.admin-page, .page, .admin-stage, .admin-content, .main-content, .resource-table { min-width: 0; }
.row-actions { min-width: 0; }
.row-actions > button:not(.primary):not(.secondary) { min-height: 30px; border-radius: 6px; }
.row-actions > button:not(.primary):not(.secondary):hover { color: var(--blue-strong); background: var(--blue-soft); }
.table-link { display: inline-flex; align-items: center; gap: 5px; min-height: 28px; max-width: 100%; padding: 0; border: 0; background: transparent; color: var(--blue-strong); font-size: 13px; text-align: left; }
.table-link:hover:not(:disabled) { background: transparent; text-decoration: underline; }
.status, .component-state { font-style: normal; font-weight: 500; }
.status::before { flex: 0 0 auto; }
.admin-empty, .resource-empty, .file-empty, .sites-empty { color: var(--muted); font-size: 13px; line-height: 1.8; }
.resource-error, .file-error, .form-error { line-height: 1.8; }
.form-error:not(:empty), .resource-error:not(:empty), .file-error:not(:empty) { padding: 10px 12px; border: 1px solid #f4d1d6; border-radius: 8px; color: #b92e41; background: #fff5f6; overflow-wrap: anywhere; }
.settings-card > p:last-child, .admin-card > p:last-child { margin-bottom: 0; }
.resource-table > h2 { margin: 0; padding: 18px 20px 10px; font-size: 16px; }
.resource-table > p { margin: 0; padding: 0 20px 16px; color: var(--muted); }
.resource-table + .resource-table { margin-top: 20px; }
.settings-card + .resource-table { margin-top: 20px; }
.settings-card > label { margin: 0; }
.settings-card > label select { margin-top: 7px; }
.settings-card > button, .settings-card > .primary { justify-self: start; }
.settings-layout { margin-top: 20px;align-items:start; }
.settings-layout .settings-card:first-child { grid-column: auto; }
.admin-page > .settings-card { margin-bottom: 20px; }
.form-grid > label { margin: 0; }
.form-grid > :is(p, .form-error, .form-actions) { grid-column: 1 / -1; }
.form-grid > button[type="submit"], .form-grid > button.primary { justify-self: start; }
.form-grid label:has(> input[type="checkbox"]) { display: flex; align-items: center; gap: 9px; }
.form-grid fieldset { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 12px; }
.form-grid fieldset label { margin: 0; font-size: 12px; }
.form-grid fieldset:has(legend) { grid-column: 1 / -1; }
.batch-modal form > label { display: grid; gap: 8px; margin: 18px 0; }
.batch-modal form > fieldset { border: 0; margin: 0; padding: 0; }
.batch-modal form > fieldset > label { margin: 16px 0; }
.batch-modal form > fieldset > .batch-check { display: flex; flex-direction: row; align-items: center; gap: 9px; }
.batch-modal textarea, .certificate-form textarea, .file-editor textarea, .security-uri { font-family: "Cascadia Code", Consolas, monospace; font-size: 12px; line-height: 1.8; }
.batch-modal textarea { min-height: 128px; background: var(--surface-subtle); }
.batch-modal :is(input, select, textarea), .file-editor :is(input, textarea), .tenant-modal :is(input, select) { max-width: 100%; }
.batch-heading { align-items: center; padding-bottom: 16px; border-bottom: 1px solid var(--line); margin-bottom: 18px; }
.batch-heading h2 { min-width:0;overflow-wrap:anywhere;font-size:20px;line-height:1.5; }
.batch-heading > button { flex-shrink:0;min-height:32px; padding: 6px 10px; white-space: nowrap; }
.modal > header > button { min-height: 32px; padding: 5px 10px; }
.modal :is(form, article) + article { padding-top: 18px; border-top: 1px solid var(--line); }
.modal-backdrop > :is(section, form) { max-width: 100%; max-height: calc(100dvh - 48px); overflow-y: auto; border: 1px solid var(--line); border-radius: 12px; box-shadow: var(--shadow-dialog); }
.modal-backdrop > :is(section, form) > h2 { padding-right: 28px; }
.modal-close, .icon-button, .mobile-menu { min-height: 32px; padding: 6px; }
.modal-close { background: var(--surface-subtle); color: var(--muted); }
.modal-close:hover { background: var(--blue-soft); color: var(--blue); }
.modal-actions, .form-actions { align-items: center; flex-wrap: wrap; padding-top: 18px; border-top: 1px solid var(--line); }
.credential-value { display: block; max-width: 100%; line-height: 1.8; }
.credential-actions { flex-wrap: wrap; }
.site-log-view { margin: 12px 0 0; line-height: 1.8; }
.file-editor > p, .batch-modal > p { margin: 0 0 18px; color: var(--muted); }
.file-editor > label { margin: 0; }
.file-editor textarea { min-height: 260px; }
.file-panel + .file-panel { margin-top: 20px; padding: 20px; }
.file-toolbar, .file-actions { row-gap: 10px; }
.file-toolbar > select { flex: 1 1 240px; max-width: 420px; }
.file-table { overflow-x: auto; }
.file-name, .file-parent, .file-breadcrumb button { min-height: 0; border: 0; background: transparent; box-shadow: none; }
.file-row-actions :is(button,a) { min-height: 30px; }
.file-row-actions select { width: 108px; min-height: 30px; padding: 3px 7px; }
.file-actions .icon-button { border: 1px solid var(--line); min-height: 38px; width: 38px; }
.file-actions { margin-left: auto; }
.security-section input[type="checkbox"], .setup-check input[type="checkbox"], .check-row input[type="checkbox"] { width: 16px; height: 16px; }
.security-section p, .setup-side-note p { color: var(--muted); }
.login-panel label div:focus-within { border-color: var(--blue); box-shadow: var(--focus-ring); }
.login-panel input { min-height: 0; width: 100%; padding: 0; border: 0; box-shadow: none; background: transparent; font-size: 14px; }
.login-panel input:focus-visible { outline: 0; }
.login-panel .brand { height: auto; }
.startup-error-panel, .setup-success { box-shadow: var(--shadow-panel); }
.runtime-cell { display: flex; align-items: center; gap: 9px; white-space: nowrap; }
.runtime-cell .runtime-mark { flex-shrink: 0; margin: 0; }
.runtime-cell small { margin: 0; }
.host-filters { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; padding: 18px; }
.host-filters .admin-search { flex: 2 1 240px; width: auto; }
.host-filters > select { flex: 1 1 115px; width: auto; }
.host-filters > button { flex: 0 0 auto; }
.host-bulk-bar { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; padding: 0 18px 16px; }
.host-bulk-bar > span { font-size: 12px; color: var(--muted); }
.host-bulk-bar > .table-link { margin-left: auto; }
.host-bulk-bar .batch-toolbar { margin: 0; gap: 8px; }
.host-bulk-bar .batch-toolbar button { min-height: 32px; padding: 5px 9px; font-size: 12px; }
.hosts-table .table-scroll { border-top: 1px solid var(--line); }
.hosts-table table { min-width: 1080px; }
.hosts-table th:first-child, .hosts-table td:first-child { padding-right: 0; width: 40px; }
.hosts-table td:nth-child(7) code { display: block; max-width: 250px; overflow: hidden; text-overflow: ellipsis; }
.network-link { display: block; color: var(--muted); min-height: 24px; font-size: 12px; }
.table-pagination { display: flex; align-items: center; gap: 16px; padding: 16px 18px; border-top: 1px solid var(--line); font-size: 12px; color: var(--muted); }
.table-pagination > label, .table-pagination > div { display: flex; align-items: center; gap: 9px; }
.table-pagination select { min-height: 32px; width: 64px; padding: 4px 7px; }
.table-pagination > div { margin-left: auto; }
.table-pagination button { min-height: 30px; width: 30px; padding: 5px; }
.admin-nav-overlay { display: none; }
.admin-sidebar nav button[aria-current="page"] { color: var(--blue); background: var(--blue-soft); }
.sidebar-foot .health-dot, .admin-side-foot .online-dot { display: none; }
.tenant-switch { max-width: min(38vw,420px); }
.tenant-switch span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.admin-content > .admin-page { margin: 0; }
.chart-filters { margin: 0; display: flex; align-items: flex-end; flex-wrap: wrap; padding: 18px 20px; gap: 16px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius-panel); }
.chart-filters label { display: grid; gap: 7px; min-width: 160px; }
.chart-filters label:first-child { flex: 1; }
.chart-filters button { margin-left: auto; }
.chart-card { min-width: 0; padding: 20px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius-panel); }
.chart-card header { display: flex; align-items: center; gap: 9px; margin-bottom: 14px; }
.chart-card header > svg { color: var(--blue); width: 18px; height: 18px; }
.chart-card h2 { margin: 0; font-size: 14px; font-weight: 600; color: #43556f; }
.chart-value { min-height: 42px; display: flex; align-items: baseline; gap: 8px; }
.chart-value b { font-size: 26px; letter-spacing: -.6px; font-weight: 650; }
.chart-value span { font-size: 12px; color: var(--muted); }
.chart-card > svg { display: block; width: 100%; height: 145px; margin: 8px 0; }
.chart-range { display: flex; justify-content: space-between; gap: 10px; color: #8795a8; font-size: 11px; }
.chart-empty { min-height: 160px; display: grid; place-items: center; color: var(--muted); font-size: 12px; }
.chart-card .chart-grid { stroke: #e7eef7; stroke-dasharray: 4 5; }
.chart-card .chart-line { stroke: var(--blue); stroke-width: 2.3; fill: none; stroke-linejoin: round; stroke-linecap: round; }
.chart-card .chart-area { fill: rgba(8,120,249,.06); }
.page-notice { color: var(--muted); font-size: 13px; padding: 14px 0; }
.settings-card :is(input,select,textarea), .modal :is(input,select,textarea), .batch-modal :is(input,select,textarea) { accent-color: var(--blue); }
.batch-modal .batch-check input[type="checkbox"], .form-grid input[type="checkbox"], .settings-card input[type="checkbox"] { width: 16px; height: 16px; min-height: 0; }
.resource-table td > button { margin-right: 6px; }
.batch-toolbar button:disabled { opacity: .5; }
.toggle{min-height:0}
.admin-sidebar nav button,.nav-item{justify-content:flex-start;color:#344662}
.admin-sidebar nav button.active,.nav-item.active{color:var(--blue)}
.admin-search input,.search input{min-height:0;height:100%;padding:0;border:0;box-shadow:none;background:transparent;outline:0;font-size:13px}
.admin-table-v2 td{font-size:14px;padding:11px 16px}
.admin-table-v2 td>b,td b{font-size:14px}
.admin-table-v2 td small{margin-top:2px;line-height:1.6}
.admin-table-v2 .table-link{min-height:22px;font-size:13px}
.admin-page-heading h1{font-size:26px}
.admin-page{display:block}
.admin-page>.admin-card+.admin-card,.admin-page>.resource-table+.resource-table{margin-top:20px}
.settings-layout>.settings-card:first-child{grid-row:auto}
.settings-layout>.settings-card:nth-child(3){grid-column:1/-1}
.settings-card h2{font-size:16px;line-height:1.6}
.system-scheduler>label{max-width:500px}
.site-actions button{width:auto;display:inline-flex;white-space:nowrap;flex:0 0 auto}
.login-panel form>label{margin:0}
.startup-modal{width:min(840px,calc(100vw - 32px))}
.startup-modal .batch-controls{grid-template-columns:repeat(2,minmax(0,1fr))}
.file-name{justify-content:flex-start;text-align:left}
.host-picker{white-space:nowrap}
.host-picker select{flex:1;min-width:0;width:auto}
.environment-card footer button{flex:0 0 auto;white-space:nowrap;min-width:104px}
.environment-card footer select{flex:1;min-width:0;width:auto}
.node-picker{display:flex;align-items:center;gap:9px;white-space:nowrap}
.node-picker select{width:auto;max-width:300px}
.impersonation-banner{top:64px}
.resource-summary{top:84px}
.mobile-nav-backdrop{border-radius:0;padding:0}
.empty-state{min-height:280px;display:grid;align-content:center;justify-items:center;gap:12px;padding:32px;border:1px solid var(--line);border-radius:10px;background:var(--surface);color:var(--muted);text-align:center}
.empty-state h2{margin:0;font-size:17px;color:var(--ink)}
.empty-state p{margin:0;max-width:440px}
.empty-state>svg{color:#7a9cc5}
.dns-credential-page .page-heading .resource-action-icon{display:none}
.tenant-switch,.top-actions{min-width:0}
.user-menu{min-width:0;max-width:260px}
.user-menu>span:nth-child(2){max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.admin-account b{display:block;max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.batch-heading>div{min-width:0}
.batch-composer-fields{border:0;margin:0;padding:0;min-width:0}
.startup-modal .form-error,.load-error{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}
.startup-modal .form-error button,.load-error button{flex-shrink:0}
.host-bulk-bar>span small{display:block;color:var(--muted)}
.host-bulk-bar>.table-link:last-child{margin-left:auto}
.host-bulk-bar>.table-link:not(:last-child){margin-left:0}
.confirmation-modal{width:min(460px,100%);padding:24px;background:var(--surface)}
.confirmation-modal h2{margin:0 0 14px;font-size:20px}
.confirmation-modal p{margin:0 0 22px;color:var(--muted);overflow-wrap:anywhere;white-space:pre-line}
.primary.danger-confirm,.primary.danger-confirm:hover{background:var(--danger);border-color:var(--danger);color:#fff}
.primary.danger-confirm:hover{filter:brightness(.94)}
@media (max-width: 1100px) {
.admin-topbar .host-jump { display: none; }
.page, .admin-content { padding: 24px; }
.settings-layout { grid-template-columns: 1fr; }
.host-bulk-bar > .table-link { margin-left: 0; }
}
@media (max-width: 980px) {
.file-row{min-width:0;grid-template-columns:minmax(160px,1fr) 80px 220px}
.file-row>span:nth-child(3){display:none}
.admin-app { padding-left: 0; }
.admin-sidebar { inset: 0 auto 0 0; width: 224px; transform: translateX(-100%); transition: transform .18s; z-index: 70; visibility:hidden; }
.admin-sidebar.open { transform: translateX(0); visibility:visible; }
.admin-nav-overlay.visible { position: fixed; inset: 0; z-index: 60; display: block; border: 0; border-radius: 0; background: rgba(15,31,55,.38); }
.admin-topbar { padding: 0 20px; gap: 12px; }
.admin-topbar .mobile-menu { display: inline-flex; }
.admin-account { margin-left: auto; }
.app-shell { padding: 64px 0 0; }
.topbar .brand { padding-left: 12px; }
.sidebar { z-index: 70; }
.mobile-nav-backdrop {z-index:60; }
.mobile-sidebar.open .sidebar { transform: translateX(0); visibility:visible; }.mobile-sidebar{z-index:70}.mobile-sidebar .sidebar{z-index:70;visibility:hidden}
}
@media (max-width: 700px) {
.file-row{grid-template-columns:minmax(0,1fr) 116px;gap:4px 12px;padding:12px 14px}
.file-row>.file-name{grid-column:1;grid-row:1}
.file-row>span:nth-child(2){grid-column:1;grid-row:2;color:var(--muted)}
.file-row>.file-row-actions{grid-column:2;grid-row:1/span 2;width:116px;display:flex;flex-wrap:wrap;justify-content:flex-end;gap:6px}
.file-row-actions select{order:2}
.file-head>span:nth-child(2){display:none}
.file-head>span:last-child{grid-column:2;grid-row:1}
.file-head{padding:8px 14px}
.file-parent>span:first-child{grid-column:1/-1}
.file-parent>span:not(:first-child){display:none}
.page, .admin-content { padding: 20px 16px 32px; }
.page-heading h1, .admin-page-heading h1 { font-size: 24px; }
.unified-heading { flex-direction: column; gap: 14px; }
.page-heading-actions { width: 100%; }
.admin-topbar { height: 64px; padding: 0 12px; }
.admin-breadcrumb { font-size: 12px; gap: 7px; }
.admin-breadcrumb > span { display: none; }
.admin-breadcrumb > b { display: none; }
.admin-account { gap: 8px; }
.admin-account > span:nth-child(2) { display: none; }
.admin-account button { width: 32px; }
.host-filters { padding: 14px; gap: 9px; }
.host-filters .admin-search { flex-basis: 100%; }
.host-filters > select { flex-basis: calc(50% - 8px); }
.host-bulk-bar { padding: 0 14px 14px; }
.host-bulk-bar .batch-toolbar { flex-basis: 100%; }
.table-pagination { gap: 8px; flex-wrap: wrap; padding: 14px; }
.table-pagination > span { display: none; }
.modal-backdrop { padding: 12px; }
.modal-backdrop > :is(section,form) { max-height: calc(100dvh - 24px); padding: 20px; border-radius: 12px; }
.modal-backdrop .batch-modal { width: 100%; }
.form-grid, .batch-controls, .plan-form-grid { grid-template-columns: 1fr; }
.form-grid fieldset { grid-template-columns: 1fr; }
.form-actions > button, .modal-actions > button { flex: 1; min-width: 100px; }
.sites-heading { flex-wrap: wrap; gap: 12px; align-items: flex-start; }
.sites-head { display: none; }
.sites-row { grid-template-columns: minmax(0,1fr) auto; gap: 12px; }
.sites-row > .site-identity { grid-column: 1 / -1; }
.sites-row .site-actions { grid-column: 1 / -1; display: flex; }
.sites-row .site-actions button { min-height: 36px; }
.site-runtime { white-space: normal; }
.chart-filters { align-items: stretch; padding: 16px; gap: 12px; }
.chart-filters label, .chart-filters label:first-child { flex: 1 1 100%; min-width: 0; }
.chart-filters button { margin: 0; flex: 1; }
.resource-charts { gap: 14px; }
.chart-card { padding: 18px; }
.chart-value b { font-size: 25px; }
.file-toolbar > select { flex:none;width:100%;min-height:38px;max-width:none; }
.file-actions { margin-left: 0; }
.login-panel { padding: 28px; }
.topbar .brand { font-size: 18px; width: auto; border: 0; }
.topbar .brand svg { width: 30px; }
.topbar .tenant-switch { display: none; }
.top-actions { padding: 0 12px; gap: 8px; }
.startup-modal .batch-controls{grid-template-columns:1fr}
.setup-steps ol{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}
.setup-steps li{min-width:0;display:flex;flex-direction:column;padding:8px 4px;gap:6px;justify-content:center}
.setup-steps li span{white-space:nowrap;font-size:12px}
.setup-steps li span small{display:none}.host-picker{white-space:normal}.host-picker select{width:100%}.node-picker{width:100%;flex-wrap:wrap}.node-picker select{flex:1;max-width:100%}.topbar,.topbar .brand{height:64px}
}
.resource-editor{max-height:90dvh;overflow-y:auto}.resource-editor form,.resource-editor fieldset{display:grid;gap:14px}.resource-editor fieldset{border:0;padding:0;margin:0;min-width:0}.resource-editor p{font-size:13px;line-height:1.65;color:var(--muted)}.resource-facts{display:grid;gap:10px;margin:16px 0}.resource-facts>div{display:grid;grid-template-columns:110px minmax(0,1fr);gap:12px}.resource-facts dt{color:var(--muted);font-size:13px}.resource-facts dd{margin:0;overflow-wrap:anywhere;font-size:13px}.resource-danger-zone{border-top:1px solid var(--line);margin-top:20px;padding-top:16px;display:grid;gap:12px}.danger-text{color:var(--danger,#dc2626)!important}.resource-editor .form-actions{flex-wrap:wrap}
.ip-pool-summary{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;margin-bottom:24px}.ip-pool-summary article{display:flex;align-items:center;gap:14px;padding:20px;border:1px solid var(--line);border-radius:12px;background:var(--surface,#fff)}.ip-pool-summary svg{color:var(--primary,#2563eb)}.ip-pool-summary span{display:grid;gap:8px;color:var(--muted);font-size:13px}.ip-pool-summary b{font-size:26px;color:var(--text,#1e293b)}.ip-pool-form{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.ip-pool-form label,.audit-pagination{display:grid;gap:8px}.ip-pool-form>button{justify-self:start}.audit-pagination{display:flex;justify-content:flex-end;align-items:center;margin-top:18px}.admin-toolbar{align-items:end}.admin-toolbar>label:not(.admin-search){display:grid;gap:7px}.host-log-toolbar{flex-wrap:wrap;align-items:end}.host-log-toolbar label{display:grid;gap:7px}.site-runtime-form{padding:20px;margin:18px 0;border:1px solid var(--line);border-radius:10px;background:var(--surface,#fff)}.site-runtime-form header{display:flex;justify-content:space-between;gap:12px;align-items:center;margin-bottom:18px}.site-runtime-form form{display:grid;gap:14px}.runtime-job-summary small{display:block;color:var(--muted);margin-top:5px}.dns-credential-modal fieldset{display:grid;gap:16px;min-width:0;border:0;padding:0}.dns-credential-modal .secondary{justify-self:start}.sites-row .site-actions{flex-wrap:wrap}.host-row-actions button{justify-self:start}.plan-cards dl{grid-template-columns:repeat(2,minmax(0,1fr))}
@media(max-width:680px){.ip-pool-summary{grid-template-columns:1fr}.ip-pool-form{grid-template-columns:1fr}.site-runtime-form header{align-items:flex-start;flex-direction:column}.audit-pagination{flex-wrap:wrap;justify-content:flex-start}.batch-create-actions{width:100%}}
.ip-pool-form{padding:20px}.ip-pool-page .admin-toolbar .admin-search{display:flex;align-items:center;gap:8px;min-height:38px}.ip-pool-page .admin-toolbar .admin-search svg{flex-shrink:0}
+50
View File
@@ -0,0 +1,50 @@
/* Final polish within the existing Sea vHost design system. */
.admin-page { min-width: 0; }
.admin-table-v2 { box-shadow: 0 3px 14px rgb(23 48 86 / 3%); }
.admin-table-v2 tbody tr { transition: background-color .15s; }
.admin-table-v2 tbody tr:hover { background: var(--surface-subtle); }
.admin-table-v2 th { font-size: 12px; font-weight: 600; letter-spacing: .02em; }
.admin-table-v2 td { vertical-align: middle; }
.admin-toolbar { row-gap: 12px; }
.form-actions { gap: 10px; }
.dns-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.dns-actions button { width: auto; min-width: 0; min-height: 32px; padding: 6px 10px; gap: 6px; display: inline-flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 500; white-space: nowrap; }
.dns-credential-row:not(.head) { align-items: center; }
.dns-credential-row code { overflow-wrap: anywhere; }
.settings-fields { display: contents; border: 0; padding: 0; margin: 0; min-width: 0; }
.settings-card { min-width: 0; }
.settings-card > header { padding-bottom: 16px; border-bottom: 1px solid var(--line); margin-bottom: 20px; color: var(--blue); }
.settings-card > header h2 { color: var(--ink); }
.settings-grid { gap: 16px; }
.settings-grid label { min-width: 0; }
.settings-layout .sso-settings { grid-column: 1 / -1; }
.sso-policy-grid { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 16px; margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--line); }
.sso-policy-grid .check-row { align-items: flex-start; margin: 0; }
.sso-policy-grid .check-row input { flex-shrink: 0; margin-top: 4px; }
.sso-policy-grid small { line-height: 1.65; }
.settings-hint { margin: 16px 0 0; color: var(--muted); font-size: 12px; }
.settings-submit { display: flex; justify-content: flex-end; grid-column: 1 / -1; padding: 16px 0 8px; }
.login-panel { border: 1px solid var(--line); box-shadow: 0 20px 64px rgb(23 48 86 / 9%); }
.login-panel .oidc-login { display: flex; align-items: center; justify-content: center; gap: 9px; width: 100%; }
.login-panel .login-divider { margin: 22px 0; }
.login-panel form button { width: 100%; }
.login-loading { display: grid; gap: 14px; padding: 18px 0; color: var(--muted); }
.sso-identity { display: flex; align-items: center; gap: 12px; background: var(--blue-soft); border-radius: 8px; padding: 14px 16px; color: var(--blue); margin: 0 0 24px; }
.sso-identity span { min-width: 0; display: grid; gap: 3px; }
.sso-identity small { color: var(--muted); overflow-wrap: anywhere; }
.sso-create-actions { display: grid; gap: 14px; margin-top: 14px; }
.sso-create-actions .text-button { background: none; border: none; color: var(--muted); }
@media (min-width: 980px) {
.dns-credential-row { grid-template-columns: minmax(160px,1.2fr) 110px minmax(150px,1fr) 140px minmax(258px,auto); gap: 16px; }
}
@media (max-width: 900px) {
.sso-policy-grid { grid-template-columns: 1fr; }
}
@media (max-width: 620px) {
.dns-credential-row:not(.head) { grid-template-areas: "name provider" "zone zone" "updated updated" "actions actions"; padding: 18px; }
.dns-actions { justify-content: flex-start; }
.dns-actions button { flex: 1; }
.settings-layout .sso-settings { grid-column: auto; }
.settings-submit > button { width: 100%; }
.login-panel { width: min(100%,420px); }
}
+90
View File
@@ -0,0 +1,90 @@
* { box-sizing: border-box; }
html, body, #root { min-width: 320px; min-height: 100%; margin: 0; }
body { min-height: 100vh; }
button, input, select, textarea { font: inherit; }
button, a, input, select, textarea { -webkit-tap-highlight-color: transparent; }
:where(button) {
min-height: var(--control-height);
padding: 8px 12px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 7px;
border: 1px solid var(--line);
border-radius: var(--radius-control);
color: #334762;
background: var(--surface);
font-size: 13px;
font-weight: 500;
line-height: 1.5;
text-decoration: none;
cursor: pointer;
transition: background-color .15s, border-color .15s, box-shadow .15s;
}
:where(button:hover:not(:disabled)) { border-color: #b7c9df; background: var(--surface-subtle); }
button:disabled { cursor: not-allowed; opacity: .48; box-shadow: none; }
button svg, a svg { flex-shrink: 0; }
:where(a) { color: var(--blue-strong); text-underline-offset: 3px; }
:where(a:hover) { color: var(--blue-strong); }
:where(input:not([type="checkbox"]):not([type="radio"]):not([type="hidden"]):not([type="file"]), select, textarea) {
width: 100%;
min-width: 0;
min-height: var(--control-height);
padding: 8px 11px;
border: 1px solid #ccd8e7;
border-radius: var(--radius-control);
color: var(--ink);
background: var(--surface);
font-size: 13px;
line-height: 1.6;
transition: border-color .15s, box-shadow .15s;
}
:where(textarea) { display: block; min-height: 120px; resize: vertical; }
:where(input::placeholder, textarea::placeholder) { color: #8997aa; opacity: 1; }
:where(input:disabled, select:disabled, textarea:disabled) { color: var(--muted); background: #f2f5f9; cursor: not-allowed; }
:where(input[readonly], textarea[readonly]) { color: #53667e; background: var(--surface-subtle); }
:where(select) { padding-right: 28px; }
input:is([type="checkbox"], [type="radio"]) { flex: 0 0 auto; width: 16px; height: 16px; min-height: 0; margin: 0; padding: 0; accent-color: var(--blue); cursor: pointer; }
:where(label) { font-size: 13px; color: #43556f; }
:where(form > label, fieldset > label) { display: grid; gap: 8px; margin: 14px 0; }
:where(fieldset) { min-width: 0; margin: 0; padding: 16px; border: 1px solid var(--line); border-radius: var(--radius-control); }
:where(legend) { padding: 0 6px; font-size: 13px; font-weight: 600; color: #43556f; }
:where(h1, h2, h3, h4, p) { overflow-wrap: anywhere; }
:where(h2) { margin: 0 0 12px; font-size: 17px; font-weight: 600; line-height: 1.6; }
:where(h3) { margin: 0 0 10px; font-size: 14px; font-weight: 600; }
:where(p) { margin: 0 0 14px; font-size: 13px; line-height: 1.8; }
:where(small) { font-size: 12px; line-height: 1.6; color: var(--muted); }
:where(code, pre, .code-input) { font-family: "Cascadia Code", "SFMono-Regular", Consolas, monospace; }
:where(code) { font-size: 12px; }
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible {
outline: 2px solid var(--blue);
outline-offset: 2px;
}
:where(input:focus, select:focus, textarea:focus) { border-color: var(--blue); box-shadow: var(--focus-ring); }
.primary, .secondary, a.primary, a.secondary {
min-height: var(--control-height);
padding: 8px 15px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 7px;
border: 1px solid var(--line);
border-radius: var(--radius-control);
background: var(--surface);
font-size: 13px;
font-weight: 600;
line-height: 1.5;
text-decoration: none;
cursor: pointer;
}
.primary, a.primary { color: #fff; border-color: var(--blue); background: var(--blue); box-shadow: 0 2px 5px rgba(8,120,249,.12); }
.primary:hover:not(:disabled), a.primary:hover { color: #fff; border-color: var(--blue-strong); background: var(--blue-strong); }
.secondary { color: #334762; }
.secondary:hover:not(:disabled) { border-color: #a8bdd6; background: var(--surface-subtle); }
.danger-button { color: var(--danger); border-color: #efc9ce; background: var(--surface); }
.danger-button:hover:not(:disabled) { border-color: var(--danger); background: var(--danger-soft); }
.danger { color: var(--danger); }
:where([hidden]) { display: none; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { scroll-behavior: auto; animation-duration: .01ms; transition-duration: .01ms; }
}
+29
View File
@@ -0,0 +1,29 @@
:root {
color-scheme: light;
font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
color: #0b1736;
background: #f6f8fc;
font-size: 14px;
line-height: 1.6;
--blue: #0878f9;
--blue-strong: #0067e6;
--blue-soft: #eaf4ff;
--ink: #0b1736;
--muted: #657493;
--line: #dce5f0;
--canvas: #f6f8fc;
--surface: #fff;
--surface-subtle: #f8fafd;
--green: #138857;
--danger: #cf3d4d;
--danger-soft: #fff2f3;
--radius-control: 8px;
--radius-panel: 10px;
--control-height: 38px;
--shadow-panel: 0 8px 32px rgba(23, 48, 86, .06);
--shadow-dialog: 0 24px 80px rgba(15, 31, 55, .2);
--focus-ring: 0 0 0 3px rgba(8, 120, 249, .15);
}
+125
View File
@@ -0,0 +1,125 @@
export type Runtime = 'PHP' | 'Node.js' | 'Python' | 'Go' | 'Java';
export type ProjectStatus = 'running' | 'stopped' | 'provisioning' | 'awaiting_upload' | 'failed' | 'quota_suspended';
export type RuntimeCatalog = Record<Runtime, string[]>;
export type RuntimeProbeStatus = 'available' | 'not_installed' | 'probe_failed';
export interface RuntimeCapability {
status: RuntimeProbeStatus;
versions: string[];
policy: 'free_core' | 'free_project';
detail?: string;
}
export type RuntimeCapabilities = Record<Runtime, RuntimeCapability>;
export interface Plan {
deleteBlockedReason?: string;
id: number;
name: string;
storageBytes: number;
databaseBytes: number;
bandwidthBytes: number;
bandwidthMbps?: number;
processLimit: number;
ftpLimit: number;
databaseLimit: number;
projectLimit: number;
}
export interface Usage {
storageBytes: number;
databaseBytes: number;
bandwidthBytes: number;
processCount: number;
measuredAt: string;
}
export interface ActivityEntry {
id?: number;
projectId?: number;
hostName?: string;
actor?: string;
ipAddress?: string;
action: string;
resourceType: string;
detail: string;
success: boolean;
createdAt: string;
}
export interface Project {
allowRuntimeChange?:boolean;
id: number;
hostName: string;
name: string;
domain: string;
path: string;
runPath: string;
runtime: Runtime;
version: string;
status: ProjectStatus;
ssl: boolean;
trafficGB: number;
createdAt: string;
}
export interface APIProject {
allowRuntimeChange?:boolean;
bandwidthBytes?:number;
id: number;
hostName: string;
name: string;
domain: string;
path: string;
runPath: string;
runtime: Runtime;
version: string;
status: string;
sslStatus: string;
autoSSL: boolean;
processLimit: number;
backendPort?: number;
createdAt: string;
}
export interface ProjectDraft {
name: string;
runtime: Runtime;
version: string;
runPath: string;
customDomain: string;
autoSSL: boolean;
}
export interface Site {
id: number;
projectId: number;
name: string;
domain: string;
runPath: string;
runtime: Runtime;
version: string;
status: ProjectStatus;
sslStatus: string;
autoSSL: boolean;
processLimit: number;
backendPort?: number;
primary: boolean;
createdAt: string;
}
export interface SiteDraft {
name: string;
runtime: Runtime;
version: string;
runPath: string;
customDomain: string;
autoSSL: boolean;
}
export interface DeploymentCheck {
runtime: Runtime;
entryFile: string;
ready: boolean;
adapterReady: boolean;
size?: number;
message: string;
}
+42
View File
@@ -0,0 +1,42 @@
import '@testing-library/jest-dom/vitest';
import {act,cleanup,fireEvent,render,screen} from '@testing-library/react';
import {afterEach,expect,it,vi} from 'vitest';
import {useState} from 'react';
import {useLiveDashboard} from './useLiveDashboard';
import {api,type Dashboard} from './api';
afterEach(()=>{cleanup();vi.useRealTimers();vi.restoreAllMocks()});
const sample=(status:string)=>({projects:[{status}]} as Dashboard);
const defaultRevision={current:0},defaultMutations={current:new Set<number>()};
function Harness({context='overview',revision=defaultRevision,mutations=defaultMutations,onSessionExpired}:{context?:string;revision?:{current:number};mutations?:{current:Set<number>};onSessionExpired?:()=>void}){
const [status,setStatus]=useState('last-known');const sync=useLiveDashboard(true,context,v=>setStatus(v.projects[0].status),revision,mutations,onSessionExpired);
return <><p>{status}</p><p role="alert">{sync.error}</p><button onClick={sync.refresh}>刷新</button></>;
}
it('updates background quota changes and retries an unavailable refresh',async()=>{
vi.useFakeTimers();vi.spyOn(document,'hidden','get').mockReturnValue(false);
const load=vi.spyOn(api,'dashboard').mockResolvedValueOnce(sample('running')).mockRejectedValueOnce(new Error('暂时不可用')).mockResolvedValueOnce(sample('quota_suspended'));
render(<Harness/>);await act(async()=>{});expect(screen.getByText('running')).toBeInTheDocument();
await act(()=>vi.advanceTimersByTimeAsync(30000));expect(screen.getByRole('alert')).toHaveTextContent('暂时不可用');expect(screen.getByText('running')).toBeInTheDocument();
await act(async()=>fireEvent.click(screen.getByRole('button',{name:'刷新'})));expect(screen.getByText('quota_suspended')).toBeInTheDocument();expect(screen.getByRole('alert')).toBeEmptyDOMElement();expect(load).toHaveBeenCalledTimes(3);
});
it('does not let a pre-mutation response overwrite the changed host state',async()=>{
let finish!:(v:Dashboard)=>void;const first=new Promise<Dashboard>(resolve=>{finish=resolve});vi.spyOn(document,'hidden','get').mockReturnValue(false);
const load=vi.spyOn(api,'dashboard').mockReturnValueOnce(first).mockResolvedValue(sample('quota_suspended'));const revision={current:0},mutations={current:new Set<number>()};
render(<Harness revision={revision} mutations={mutations}/>);revision.current++;mutations.current.add(1);await act(async()=>finish(sample('running')));expect(screen.getByText('last-known')).toBeInTheDocument();
mutations.current.clear();revision.current++;await act(async()=>fireEvent(window,new Event('focus')));expect(screen.getByText('quota_suspended')).toBeInTheDocument();expect(load).toHaveBeenCalledTimes(2);
});
it('discards a late response from the previous page and stops polling after unmount',async()=>{
vi.useFakeTimers();let finish!:(v:Dashboard)=>void;const first=new Promise<Dashboard>(resolve=>{finish=resolve});const load=vi.spyOn(api,'dashboard').mockReturnValueOnce(first).mockResolvedValue(sample('stopped'));
const revision={current:0},mutations={current:new Set<number>()};const view=render(<Harness revision={revision} mutations={mutations}/>);view.rerender(<Harness context="projects" revision={revision} mutations={mutations}/>);await act(async()=>{});expect(screen.getByText('stopped')).toBeInTheDocument();await act(async()=>finish(sample('running')));expect(screen.queryByText('running')).not.toBeInTheDocument();view.unmount();await act(()=>vi.advanceTimersByTimeAsync(60000));expect(load).toHaveBeenCalledTimes(2);
});
it('invokes session recovery on authentication failure instead of leaving a stuck account view',async()=>{
const expired=vi.fn();vi.spyOn(api,'dashboard').mockRejectedValue(Object.assign(new Error('unauthorized'),{status:401}));render(<Harness onSessionExpired={expired}/>);await act(async()=>{});expect(expired).toHaveBeenCalledOnce();expect(screen.getByRole('alert')).toHaveTextContent('登录已失效');
});
it('automatically recovers a transient host maintenance lock and cancels its retry on unmount',async()=>{
vi.useFakeTimers();vi.spyOn(document,'hidden','get').mockReturnValue(false);
const load=vi.spyOn(api,'dashboard').mockRejectedValueOnce(Object.assign(new Error('环境处理中'),{status:423})).mockResolvedValueOnce(sample('stopped')).mockRejectedValue(Object.assign(new Error('环境处理中'),{status:423}));
const view=render(<Harness/>);await act(async()=>{});expect(screen.getByRole('alert')).toHaveTextContent('环境处理中');
await act(()=>vi.advanceTimersByTimeAsync(3000));expect(screen.getByText('stopped')).toBeInTheDocument();expect(screen.getByRole('alert')).toBeEmptyDOMElement();
await act(async()=>fireEvent.click(screen.getByRole('button',{name:'刷新'})));view.unmount();await act(()=>vi.advanceTimersByTimeAsync(60000));expect(load).toHaveBeenCalledTimes(3);
});
+27
View File
@@ -0,0 +1,27 @@
import {useEffect,useRef,useState,type RefObject} from 'react';
import {api,type Dashboard} from './api';
// The current page keeps its editor state. Only the shared status snapshot is
// refreshed, and a response started before a host mutation cannot overwrite it.
export function useLiveDashboard(enabled:boolean,context:string,apply:(value:Dashboard)=>void,revision:RefObject<number>,mutations:RefObject<Set<number>>,onSessionExpired?:()=>void){
const applyRef=useRef(apply);applyRef.current=apply;
const expiredRef=useRef(onSessionExpired);expiredRef.current=onSessionExpired;
const [attempt,setAttempt]=useState(0),[refreshing,setRefreshing]=useState(false),[error,setError]=useState('');
useEffect(()=>{
if(!enabled){setRefreshing(false);setError('');return}
let active=true,pending=false;let retry:ReturnType<typeof setTimeout>|undefined;
async function refresh(force=false){
if(!active||pending||mutations.current.size||(!force&&document.hidden))return;
const version=revision.current;pending=true;setRefreshing(true);
try{const value=await api.dashboard();if(active&&version===revision.current&&!mutations.current.size){applyRef.current(value);setError('')}}
catch(e){if(active&&version===revision.current){const expired=(e as {status?:number})?.status===401;setError(expired?'登录已失效,请重新登录':e instanceof Error?e.message:'主机状态刷新失败');if(expired)expiredRef.current?.();else if((e as {status?:number})?.status===423){if(retry)window.clearTimeout(retry);retry=window.setTimeout(()=>void refresh(),3000)}}}
finally{pending=false;if(active)setRefreshing(false)}
}
void refresh(true);
const timer=window.setInterval(()=>void refresh(),30000);
const focus=()=>void refresh();
window.addEventListener('focus',focus);document.addEventListener('visibilitychange',focus);
return()=>{active=false;window.clearInterval(timer);if(retry)window.clearTimeout(retry);window.removeEventListener('focus',focus);document.removeEventListener('visibilitychange',focus)};
},[enabled,context,attempt,revision,mutations]);
return {refreshing,error,refresh:()=>setAttempt(value=>value+1)};
}
+2
View File
@@ -0,0 +1,2 @@
/// <reference types="vite/client" />
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
+8
View File
@@ -0,0 +1,8 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+11
View File
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"noEmit": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true
},
"include": ["vite.config.ts"]
}
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
pool: 'threads',
maxWorkers: 1,
},
server: {
port: 5173,
proxy: { '/api': 'http://127.0.0.1:8080' },
},
});