Add per-device VPN and direct routing policies
Build and Deploy Gateway / build-and-push (push) Successful in 10s
Build and Deploy Gateway / deploy (push) Successful in 16s

This commit is contained in:
2026-08-07 16:18:31 +03:00
parent 307ad02cd7
commit 560c243047
20 changed files with 1090 additions and 114 deletions
+88 -16
View File
@@ -130,6 +130,37 @@ export function DevicesPanel({ open, panelRef, closeRef, onClose }) {
setEditingId('');
}
async function updatePolicy(device, mode) {
setSavingId(device.id);
try {
let next;
try {
next = await api.devices.setPolicy(device.id, mode, snapshot.revision);
} catch (requestError) {
if (requestError.code !== 'STATE_CONFLICT') throw requestError;
const latest = await api.devices.list();
setSnapshot((current) => !current || latest.revision >= current.revision ? latest : current);
const latestDevice = latest.devices.find((candidate) => candidate.id === device.id);
if (!latestDevice || latestDevice.desiredPolicy !== device.desiredPolicy) throw requestError;
next = await api.devices.setPolicy(device.id, mode, latest.revision);
}
setSnapshot((current) => !current || next.revision >= current.revision ? next : current);
setError(null);
} catch (requestError) {
if (requestError.code === 'DEVICE_POLICY_APPLY_FAILED') {
try {
const latest = await api.devices.list();
setSnapshot((current) => !current || latest.revision >= current.revision ? latest : current);
} catch {
// Keep the policy error as the actionable result.
}
}
setError(requestError);
} finally {
setSavingId('');
}
}
return (
<aside
ref={panelRef}
@@ -197,6 +228,11 @@ export function DevicesPanel({ open, panelRef, closeRef, onClose }) {
Трафик временно не обновляется. Показаны последние сохранённые значения.
</p>
)}
{snapshot?.source?.policy?.error && (
<p className="client-devices-source" role="status">
Маршруты устройств временно не обновляются. Показано последнее подтверждённое состояние.
</p>
)}
{error && (
<div className="client-devices-error" role="alert">
<span>{error.message}</span>
@@ -217,6 +253,29 @@ export function DevicesPanel({ open, panelRef, closeRef, onClose }) {
const uncertainIdentity = device.confidence !== 'high';
const download = formatByteString(device.downloadBytes);
const upload = formatByteString(device.uploadBytes);
const policyBusy = device.policyStatus === 'applying';
const policyFailed = device.policyStatus === 'failed';
const policyPending = device.policyStatus === 'pending';
const displayPolicy = device.appliedPolicy;
const policyTarget = device.policyStatus === 'applied'
? device.appliedPolicy === 'direct' ? 'vpn' : 'direct'
: device.appliedPolicy;
const cannotEnableDirect = device.policyStatus === 'applied'
&& device.appliedPolicy !== 'direct'
&& (!device.pinned || device.confidence === 'ambiguous');
const policyTooltip = policyBusy
? `Применяем: ${device.desiredPolicy === 'direct' ? 'полностью напрямую' : 'через правила Gateway'}`
: policyFailed
? `${device.policyError || 'Маршрут не применён'}. Сейчас: ${device.appliedPolicy === 'direct' ? 'напрямую' : 'через Gateway'}. Нажмите, чтобы оставить текущий маршрут`
: policyPending
? 'Gateway должен однозначно распознать устройство. Нажмите, чтобы отменить ожидание'
: !device.pinned
? 'Закрепите устройство, чтобы изменить маршрут'
: device.confidence === 'ambiguous' && device.desiredPolicy !== 'direct'
? 'Маршрут недоступен, пока Gateway видит несколько сетевых адресов одного устройства'
: displayPolicy === 'direct'
? 'Полностью обходит sing-box. Нажмите, чтобы вернуть обработку Gateway'
: 'Проходит через sing-box и правила Gateway. Нажмите, чтобы пустить полностью напрямую';
return <article
ref={(node) => {
if (node) deviceNodes.current.set(device.id, node);
@@ -260,53 +319,66 @@ export function DevicesPanel({ open, panelRef, closeRef, onClose }) {
</span>
</div>
)}
<span className="client-device-traffic-slot">
{device.trafficObservedAt && <span
className="client-device-traffic"
aria-label={`Получено ${download}, отдано ${upload}`}
>
<span aria-hidden="true"> {download} · {upload}</span>
</span>}
</span>
<span className="client-device-pin-wrap client-tooltip-anchor">
<button
className="client-device-pin"
type="button"
aria-pressed={device.pinned}
aria-label={device.pinned ? `Открепить ${title}` : `Закрепить ${title}`}
disabled={saving}
disabled={saving || device.desiredPolicy === 'direct' || device.appliedPolicy === 'direct'}
onClick={() => updateDevice(device, { pinned: !device.pinned })}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M9 3h6l-1 5 3 3v2H7v-2l3-3-1-5ZM12 13v8" />
</svg>
</button>
<Tooltip>{device.pinned ? 'Открепить' : 'Закрепить'}</Tooltip>
<Tooltip>{device.desiredPolicy === 'direct' || device.appliedPolicy === 'direct'
? 'Сначала верните маршрут через Gateway'
: device.pinned ? 'Открепить' : 'Закрепить'}</Tooltip>
</span>
</div>
<div className="client-device-meta">
<div className="client-device-addresses">
{title !== device.ip && device.ip && <span>{device.ip}</span>}
{device.mac && <span className="client-device-mac">
{device.mac}
{uncertainIdentity && <span className="client-device-identity client-tooltip-anchor" tabIndex="0" aria-label="Пояснение идентификации устройства">
{device.manufacturer && <span className="client-device-manufacturer">{device.manufacturer}</span>}
{uncertainIdentity && <span className="client-device-identity client-tooltip-anchor" tabIndex="0" aria-label="Пояснение идентификации устройства">
<Tooltip>{device.confidence === 'medium'
? 'Устройство использует приватный MAC, производитель может не определиться'
: device.confidence === 'ambiguous'
? 'Один MAC наблюдается у нескольких IP, индивидуальные правила могут быть неточными'
? 'Gateway видит это устройство с несколькими IP или интерфейсами, поэтому индивидуальное правило небезопасно'
: 'Устройство определено приблизительно'}</Tooltip>
</span>}
</span>}
</div>
<span className="client-device-policy-wrap client-tooltip-anchor">
<button
className={`client-device-policy is-${displayPolicy}${policyFailed ? ' is-failed' : ''}${policyPending ? ' is-pending' : ''}`}
type="button"
aria-label={`Маршрут устройства: ${displayPolicy === 'direct' ? 'полностью напрямую' : 'через правила Gateway'}. ${policyTooltip}`}
aria-pressed={displayPolicy === 'direct'}
aria-busy={policyBusy}
disabled={saving || policyBusy || cannotEnableDirect}
onClick={() => updatePolicy(device, policyTarget)}
>
{displayPolicy === 'direct' ? 'Напрямую' : 'VPN'}
</button>
<Tooltip>{policyTooltip}</Tooltip>
</span>
<span className="client-device-last-seen" tabIndex="0">
<time dateTime={device.lastSeenAt} aria-label={seen.tooltip}>
<TextMorph from={seen.label} to={seen.relative} />
</time>
</span>
</div>
{(device.manufacturer || device.trafficObservedAt) && <div className="client-device-details">
{device.manufacturer && <span className="client-device-manufacturer">{device.manufacturer}</span>}
{device.trafficObservedAt && <span
className="client-device-traffic"
aria-label={`Получено ${download}, отдано ${upload}`}
>
<span aria-hidden="true"> {download} · {upload}</span>
</span>}
</div>}
</article>;
})}
</div>