49 lines
9.1 KiB
TypeScript
49 lines
9.1 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
||
import { Download, Link2, ShieldCheck, Smartphone, X } from 'lucide-react';
|
||
import { api, downloadCompanionCertificate } from './api';
|
||
import type { Project } from './types';
|
||
import type { CompanionStatus, CompanionAudit } from './companion-types';
|
||
import { useRecordPages } from './useRecordPages';
|
||
import './companion-panel.css';
|
||
|
||
export function CompanionPanel({ projects, selectedProjectId }: { projects: Project[]; selectedProjectId: string }) {
|
||
const [status, setStatus] = useState<CompanionStatus | null>(null), [address, setAddress] = useState(''), [port, setPort] = useState(4319);
|
||
const [selected, setSelected] = useState<string[]>(selectedProjectId ? [selectedProjectId] : []);
|
||
const [approve, setApprove] = useState(false), [stop, setStop] = useState(false), [hours, setHours] = useState(24);
|
||
const [pair, setPair] = useState<{ url: string; qr: string; expiresAt: string } | null>(null), [busy, setBusy] = useState(''), [error, setError] = useState('');
|
||
const mounted = useRef(true);
|
||
const audit = useRecordPages<CompanionAudit>('/companion/audit', value => setError(value instanceof Error ? value.message : String(value)));
|
||
async function refresh() { const result = await api<CompanionStatus>('/companion'); if (mounted.current) { setStatus(result); setAddress(previous => previous || result.addresses[0]?.address || ''); await audit.refresh(); } }
|
||
useEffect(() => {
|
||
mounted.current = true; void refresh().catch(value => { if (mounted.current) setError(value.message); });
|
||
const timer = setInterval(() => void refresh().catch(() => {}), 5000);
|
||
return () => { mounted.current = false; clearInterval(timer); };
|
||
}, []);
|
||
useEffect(() => { if (!pair) return; const timer = setTimeout(() => setPair(null), Math.max(0, Date.parse(pair.expiresAt) - Date.now())); return () => clearTimeout(timer); }, [pair]);
|
||
async function act(name: string, action: () => Promise<unknown>) {
|
||
if (busy) return; setBusy(name); setError('');
|
||
try { await action(); await refresh(); } catch (value) { if (mounted.current) setError(value instanceof Error ? value.message : '手机连接操作失败。'); }
|
||
finally { if (mounted.current) setBusy(''); }
|
||
}
|
||
return <div className="companion-panel">
|
||
<div className="companion-heading"><Smartphone size={25} /><div><strong>{status?.enabled ? '手机连接已开启' : '在 iPhone 上接续任务'}</strong><p>同一 Wi-Fi,通过 Safari 查看原任务、确认审批和停止执行。</p></div><span className="companion-state">{status?.enabled ? 'HTTPS' : '默认关闭'}</span></div>
|
||
{error && <p className="companion-error" role="alert">{error}</p>}
|
||
<section className="companion-network"><h3>Windows 连接地址</h3>
|
||
{status?.enabled ? <div className="companion-address"><code>{status.origin}</code><button className="button secondary" disabled={!!busy} onClick={() => void act('close', async () => { await api('/companion/close', {}); setPair(null); })}>关闭手机连接</button></div>
|
||
: <form onSubmit={event => { event.preventDefault(); void act('start', () => api('/companion/start', { address, port })); }}><label>局域网地址<select aria-label="手机连接地址" value={address} onChange={event => setAddress(event.target.value)}>{!address && <option value="">请选择网络</option>}{status?.addresses.map(item => <option key={item.address} value={item.address}>{item.name} · {item.address}</option>)}</select></label><label>端口<input aria-label="手机连接端口" type="number" min={1024} max={65535} value={port} onChange={event => setPort(Number(event.target.value))} /></label><button className="button primary" disabled={!!busy || !address || !!status?.busy}><Link2 size={15} />{busy === 'start' ? '正在生成证书…' : '开启 HTTPS'}</button></form>}
|
||
{status && !status.addresses.length && !status.enabled && <p>尚未找到局域网地址。请先让电脑连接 Wi-Fi 或有线局域网,再刷新此窗口。</p>}
|
||
<p className="companion-note">关闭手机连接后,电脑上的任务继续运行。宿主重启后,需要在这里重新开启。</p>
|
||
</section>
|
||
{status?.certificate && <details className="companion-certificate" open={!status.devices.length}><summary><ShieldCheck size={16} />首次连接:在 iPhone 信任证书</summary><ol><li>下载本机根证书,用你自己的文件传输方式保存到 iPhone「文件」,点开安装。</li><li>在 iPhone「设置 → 通用 → VPN 与设备管理」安装此证书描述文件。</li><li>在「设置 → 通用 → 关于本机 → 证书信任设置」开启此根证书的完全信任。</li><li>核对下方证书指纹,然后扫描新的配对码。连接地址发生变化时,在电脑重新开启网关。</li></ol><button className="button secondary" disabled={!!busy} onClick={() => void act('certificate', downloadCompanionCertificate)}><Download size={14} />下载手机根证书</button><code className="companion-fingerprint">SHA-256 {status.certificate.sha256}</code><p className="companion-note">证书到期 {new Date(status.certificate.expiresAt).toLocaleDateString()}。若无法连接,请核对同一 Wi-Fi、访客网络隔离和 Windows 防火墙的当前端口;这里不会修改系统信任或防火墙。</p></details>}
|
||
<section><h3>连接一台手机</h3><p className="companion-note">仅授予选中项目。配对链接两分钟内有效,用过即失效。</p>
|
||
<fieldset disabled={!!busy || !status?.enabled}><legend>允许查看的项目</legend><div className="companion-projects">{projects.map(project => <label key={project.id}><input type="checkbox" checked={selected.includes(project.id)} onChange={event => { setPair(null); setSelected(previous => event.target.checked ? [...previous, project.id] : previous.filter(id => id !== project.id)); }} />{project.name}</label>)}</div></fieldset>
|
||
<div className="companion-grant"><span>观察任务 · 必选</span><label><input type="checkbox" checked={approve} onChange={event => { setApprove(event.target.checked); setPair(null); }} />允许审批命令</label><label><input type="checkbox" checked={stop} onChange={event => { setStop(event.target.checked); setPair(null); }} />允许停止任务</label><label>有效期<select aria-label="手机设备有效期" value={hours} onChange={event => { setHours(Number(event.target.value)); setPair(null); }}><option value={24}>24 小时</option><option value={168}>7 天</option><option value={720}>30 天</option></select></label></div>
|
||
<button className="button primary" disabled={!!busy || !status?.enabled || !selected.length || selected.length > 16} onClick={() => void act('pair', async () => { const result = await api<{ url: string; qr: string; expiresAt: string }>('/companion/pair', { projectIds: selected, permissions: { observe: true, approve, stop }, expiresInHours: hours }); if (mounted.current) setPair(result); })}>生成一次性配对码</button>
|
||
{pair && status?.enabled && <div className="companion-pair"><img src={pair.qr} alt="手机一次性配对二维码" width={224} height={224} /><div><strong>使用 iPhone 相机扫描</strong><p>请先完成证书信任。{new Date(pair.expiresAt).toLocaleTimeString()} 失效。</p><p className="companion-pair-url">{pair.url}</p><p>把链接发给自己时,接收者可以取得所选项目权限。完成配对后此链接立即失效。</p></div></div>}
|
||
</section>
|
||
<section><h3>已登记设备 <span>{status?.devices.length ?? 0}</span></h3>{!status?.devices.length && <p className="companion-note">配对完成后,设备和授权范围会显示在这里。</p>}{status?.devices.map(device => <div key={device.id} className="companion-device"><Smartphone size={18} /><div><strong>{device.name}</strong><p>{device.projectIds.map(id => projects.find(project => project.id === id)?.name ?? '原项目').join('、')} · {device.permissions.approve ? '可审批' : '观察'}{device.permissions.stop ? ' · 可停止' : ''}</p><small>{({ active: '已授权', revoked: '已撤销', expired: '已到期', reconnect_required: '需重新配对' } as Record<string, string>)[device.status ?? ''] ?? device.status} · {new Date(device.expiresAt).toLocaleString()} 到期</small></div><button className="button secondary" disabled={!!busy || device.status !== 'active'} onClick={() => void act('revoke', async () => { await api('/companion/devices/' + device.id + '/revoke', { revision: device.revision }); setPair(null); })}><X size={13} />撤销</button></div>)}</section>
|
||
{status && <details className="companion-audit"><summary>设备操作记录 · 已加载 {audit.items.length} / {audit.total} 项</summary>{audit.items.map(item => <p key={item.id}><time>{new Date(item.at).toLocaleString('zh-CN')}</time><span>{status.devices.find(device => device.id === item.deviceId)?.name ?? '原设备'} · {({ pair: '配对', rotate: '轮换会话', revoke: '撤销', approve: '审批', stop: '停止' } as Record<string, string>)[item.action] ?? item.action}</span><code>{item.status}</code></p>)}
|
||
{audit.hasMore && <button type="button" className="button secondary" disabled={audit.loading} onClick={() => void audit.loadMore()}>加载更早的设备操作</button>}</details>}
|
||
</div>;
|
||
}
|