Compare commits

...
2 Commits
Author SHA1 Message Date
Denozordec 676be13251 fix(ix): открыть добавление протокола из формы клиента
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m31s
Docker images / frontend-image (push) Successful in 3m20s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m4s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-11-23 21:48:52 +07:00
Denozordec ca1bc1ab38 feat(ix): добавить два протокола для одного клиента
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m29s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m58s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Выдавать профиль и скрипт настройки туннеля с прямым доступом по внешнему адресу. Учитывать собственные маршруты возврата при применении черновика.
2026-11-23 18:48:10 +07:00
8 changed files with 344 additions and 103 deletions

No files matched your search

+96 -50
View File
@@ -9,20 +9,23 @@ import { Badge } from "@/components/reui/badge"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
import { Field, FieldDescription, FieldLabel, FieldTitle } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { Textarea } from "@/components/ui/textarea"
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
import { publicEndpoint, transitName } from "./ix-exits"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
type Binding = IxSite["interfaces"][number]
type ClientSelection = { site: IxSite; binding: Binding; addProtocol?: boolean }
type FormState = {
serverId: number
name: string
kind: IxLinuxClientRequest["kind"]
kind: IxLinuxClientRequest["kind"] | "both"
hub: string
peer: string
key: string
@@ -32,9 +35,20 @@ type FormState = {
destinations: string
exit: string
enabled: boolean
transitLocal: string
transitRemote: string
}
const lines = (value: string) => value.split(/[,\n]/).map(line => line.trim()).filter(Boolean)
const protocols = [
{ kind: "wireguard", label: "WireGuard" },
{ kind: "gre-ipsec", label: "GRE/IPsec" },
] as const
function hasCompanion(site: IxSite, binding: Binding) {
const clientId = binding.linux?.clientId
return !!clientId && site.interfaces.some(item => item.kind !== binding.kind && item.linux?.clientId === clientId)
}
function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode[]) {
const target = site.interfaces.find(binding => binding.name === group.primary.interface)?.peerServerId
@@ -42,36 +56,50 @@ function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode
return [label, group.backup && "с резервом"].filter(Boolean).join(" · ")
}
function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
segment: IxSegment; edit: { site: IxSite; binding: Binding } | null; nodes: IxNode[]; backendUrl: string
function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, busy, save, cancel }: {
segment: IxSegment; edit: ClientSelection | null; nodes: IxNode[]; backendUrl: string
setAddProtocol: (add: boolean) => void
busy: boolean; save: (input: IxLinuxClientRequest) => Promise<void>; cancel: () => void
}) {
const binding = edit?.binding
const [form, setForm] = useState<FormState>(() => ({
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
name: binding?.linux?.name ?? "", kind: binding?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
hub: binding?.localEndpoint ?? binding?.provisionWireguard?.hubEndpoint ?? "",
peer: binding?.linux?.peerEndpoint ?? binding?.endpoint ?? "",
key: binding?.provisionWireguard?.credentialId ? "" : binding?.provisionWireguard?.peerPublicKey ?? "",
localAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.localAddress ?? "",
peerAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.peerAddress ?? "",
prefixes: binding?.prefixes.join("\n") ?? "", destinations: binding?.linux?.destinations.join("\n") ?? "",
exit: binding?.linux?.exit ?? "isolated", enabled: binding?.linux?.enabled ?? true,
}))
const existing = edit?.binding
const companion = edit?.addProtocol ? existing : undefined
const binding = companion ? undefined : existing
const paired = !!edit && hasCompanion(edit.site, edit.binding)
const initialForm = (addProtocol: boolean): FormState => {
const current = addProtocol ? undefined : existing
const tunnel = current?.provisionWireguard ?? current?.provisionGre
return {
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
name: existing?.linux?.name ?? "",
kind: addProtocol ? (existing?.kind === "wireguard" ? "gre-ipsec" : "wireguard")
: current?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
hub: existing?.localEndpoint ?? existing?.provisionWireguard?.hubEndpoint ?? "",
peer: existing?.linux?.peerEndpoint ?? existing?.endpoint ?? "",
key: current?.provisionWireguard?.credentialId ? "" : current?.provisionWireguard?.peerPublicKey ?? "",
localAddress: tunnel?.localAddress ?? "", peerAddress: tunnel?.peerAddress ?? "",
prefixes: current?.prefixes.join("\n") ?? "", destinations: current?.linux?.destinations.join("\n") ?? "",
exit: current?.linux?.exit ?? "isolated", enabled: current?.linux?.enabled ?? true,
transitLocal: "", transitRemote: "",
}
}
const [currentForm, setCurrentForm] = useState(() => initialForm(false))
const [companionForm, setCompanionForm] = useState(() => initialForm(true))
const form = companion ? companionForm : currentForm
const setForm = companion ? setCompanionForm : setCurrentForm
const wireguard = form.kind !== "gre-ipsec"
const gre = form.kind !== "wireguard"
const [rotate, setRotate] = useState(false)
const origin = useIxNodeInventory(backendUrl, form.serverId, segment.id)
const [transitLocal, setTransitLocal] = useState("")
const [transitRemote, setTransitRemote] = useState("")
const site = segment.configuration.sites.find(site => site.serverId === form.serverId)
const suggested = publicEndpoint(origin.inventory)
const hub = form.hub.trim() || suggested
const targetId = form.exit.startsWith("remote:") ? Number(form.exit.slice(7)) : 0
const target = useIxNodeInventory(backendUrl, targetId, segment.id)
const localEndpoint = transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
const remoteEndpoint = transitRemote.trim() || publicEndpoint(target.inventory)
const family = form.peerAddress.includes(":") ? 6 : 4
const localEndpoint = form.transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
const remoteEndpoint = form.transitRemote.trim() || publicEndpoint(target.inventory)
const family = form.kind !== "both" && form.peerAddress.includes(":") ? 6 : 4
const patch = (fields: Partial<FormState>) => setForm(value => ({ ...value, ...fields }))
const nodeChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
const transports = [{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec (IKEv2)" }]
const groups = site?.groups.filter(group => group.onFailure === "block" && group.gateway.includes(":") === (family === 6)) ?? []
const local = groups.find(group => group.id === "ix-wan" + family && group.primary.viaMain)
const targets = nodes.filter(node => node.enabled && node.id !== form.serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
@@ -82,7 +110,7 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
...targets.filter(node => !groups.some(group => site?.interfaces.some(link => link.name === group.primary.interface && link.peerServerId === node.id)))
.map(node => ({ value: "remote:" + node.id, label: "Через " + node.name + (node.type === "exit-node" ? " · ExitNode" : " · IX") })),
]
const valid = !!form.name.trim() && !!(form.hub || suggested) && (form.kind === "wireguard" || !!form.peer) &&
const valid = !!form.name.trim() && !!hub && (!gre || isIpv4String(form.peer.trim()) && isIpv4String(hub)) &&
(!targetId || !!localEndpoint && !!remoteEndpoint) && exits.some(exit => exit.value === form.exit)
const destinationsField = <Field><FieldLabel htmlFor="ix-linux-destinations">Разрешённые сети IX</FieldLabel>
<Textarea id="ix-linux-destinations" rows={2} value={form.destinations} placeholder="По одному CIDR на строку" onChange={event => patch({ destinations: event.target.value })} />
@@ -92,36 +120,49 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
if (!valid || busy) return
void save({
revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name,
kind: form.kind, hubEndpoint: form.hub.trim() || suggested, peerEndpoint: form.peer.trim() || undefined,
peerPublicKey: form.kind === "wireguard" ? form.key.trim() || undefined : undefined,
localAddress: form.localAddress.trim() || undefined, peerAddress: form.peerAddress.trim() || undefined,
kind: wireguard ? "wireguard" : "gre-ipsec", additionalGre: form.kind === "both" || undefined, companionOf: companion?.name,
hubEndpoint: hub, peerEndpoint: form.peer.trim() || undefined,
peerPublicKey: wireguard ? form.key.trim() || undefined : undefined,
localAddress: form.kind === "both" ? undefined : form.localAddress.trim() || undefined,
peerAddress: form.kind === "both" ? undefined : form.peerAddress.trim() || undefined,
prefixes: lines(form.prefixes), destinations: lines(form.destinations), exit: form.exit === "isolated" || targetId ? undefined : form.exit,
transit: targetId ? { targetServerId: targetId, name: transitName(segment, form.serverId, targetId, family), family,
localEndpoint, remoteEndpoint } : undefined,
enabled: form.enabled, rotate,
enabled: form.enabled, rotate: !!binding && rotate,
})
}}>
<div className="grid min-h-0 gap-4 overflow-y-auto px-4 pb-4">
<Field><FieldLabel htmlFor="ix-linux-name">Имя клиента</FieldLabel>
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" required onChange={event => patch({ name: event.target.value })} /></Field>
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" readOnly={!!companion} required onChange={event => patch({ name: event.target.value })} /></Field>
{nodeChoices.length > 1 && <Field><FieldLabel htmlFor="ix-linux-node">Узел IX</FieldLabel>
<Select value={String(form.serverId)} items={nodeChoices} disabled={!!edit}
onValueChange={value => value && patch({ serverId: Number(value), hub: "", exit: "isolated" })}>
<SelectTrigger id="ix-linux-node" className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>{nodeChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select></Field>}
<Field><FieldLabel htmlFor="ix-linux-transport">Туннель</FieldLabel>
<Select value={form.kind} items={transports} disabled={!!edit}
onValueChange={value => (value === "wireguard" || value === "gre-ipsec") && patch({ kind: value })}>
<SelectTrigger id="ix-linux-transport" className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>{transports.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select></Field>
<Field>
<FieldTitle id="ix-linux-transport">Протоколы подключения</FieldTitle>
<ButtonGroup aria-labelledby="ix-linux-transport" className="max-w-full">
{protocols.map(({ kind, label }) => {
const selected = paired || !!companion || form.kind === "both" || form.kind === kind
return <Button key={kind} type="button" size="sm" variant={selected ? "secondary" : "outline"} aria-pressed={selected}
disabled={busy || (existing ? paired || existing.kind === kind : form.kind === kind)}
onClick={() => existing ? setAddProtocol(!companion)
: patch({ kind: form.kind === "both" ? (kind === "wireguard" ? "gre-ipsec" : "wireguard") : "both" })}>{label}</Button>
})}
</ButtonGroup>
{form.kind === "both" ? <FieldDescription>Оба туннеля получат свои адреса в одной VRF сегмента.</FieldDescription>
: companion ? <FieldDescription>Настройки ниже относятся к новому туннелю в той же VRF.</FieldDescription>
: paired ? <FieldDescription>Оба протокола настроены. Здесь редактируется {binding?.kind === "gre-ipsec" ? "GRE/IPsec" : "WireGuard"}.</FieldDescription>
: edit ? <FieldDescription>Выберите второй протокол, чтобы добавить туннель в ту же VRF.</FieldDescription>
: <FieldDescription>Можно отметить оба протокола.</FieldDescription>}
</Field>
<Field><FieldLabel htmlFor="ix-linux-peer">Внешний адрес Linux</FieldLabel>
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={form.kind === "gre-ipsec"} onChange={event => patch({ peer: event.target.value })} />
<FieldDescription>{form.kind === "gre-ipsec" ? "Фиксированный IPv4 на стороне VPS для GRE/IPsec." : form.exit === "isolated"
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={gre} onChange={event => patch({ peer: event.target.value })} />
<FieldDescription>{gre ? "Фиксированный IPv4 на VPS для GRE/IPsec. Ответы на SSH по этому адресу пойдут напрямую." : form.exit === "isolated"
? "Для WireGuard это поле необязательно." : "Укажите публичный IP VPS, чтобы сохранить доступ по SSH при выходе через IX."}</FieldDescription></Field>
<Field><FieldLabel htmlFor="ix-linux-exit">Выход трафика</FieldLabel>
<Select value={form.exit} items={exits} onValueChange={value => { if (value) { patch({ exit: value }); setTransitLocal(""); setTransitRemote("") } }}>
<Select value={form.exit} items={exits} onValueChange={value => { if (value) patch({ exit: value, transitLocal: "", transitRemote: "" }) }}>
<SelectTrigger id="ix-linux-exit" className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>{exits.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select>
@@ -129,40 +170,40 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
</Field>
{!!targetId && !publicEndpoint(target.inventory) && (target.loading ? <p role="status" className="text-sm text-muted-foreground">Читаем WAN выходного узла…</p> :
<Field><FieldLabel htmlFor="ix-transit-target">IPv4 выходного узла</FieldLabel>
<Input id="ix-transit-target" value={transitRemote} onChange={event => setTransitRemote(event.target.value)} />
<Input id="ix-transit-target" value={form.transitRemote} onChange={event => patch({ transitRemote: event.target.value })} />
<FieldDescription>Укажите адрес интерфейса CHR для межузлового туннеля.</FieldDescription></Field>)}
{!!targetId && !suggested && !origin.loading && <Field><FieldLabel htmlFor="ix-transit-source">IPv4 узла IX для транзита</FieldLabel>
<Input id="ix-transit-source" value={localEndpoint} onChange={event => setTransitLocal(event.target.value)} /></Field>}
<Input id="ix-transit-source" value={localEndpoint} onChange={event => patch({ transitLocal: event.target.value })} /></Field>}
{form.exit === "isolated" && destinationsField}
<details className="grid gap-3" key={form.serverId + ":" + origin.loading}
open={!origin.loading && !suggested && !binding?.provisionWireguard?.hubEndpoint && !binding?.localEndpoint}>
<details className="grid gap-3" key={form.serverId + ":" + origin.loading + ":" + gre}
open={!origin.loading && (!hub || gre && !isIpv4String(hub)) || undefined}>
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
<div className="mt-3 grid gap-3">
<Field><FieldLabel htmlFor="ix-linux-hub">Внешний адрес IX</FieldLabel>
<Input id="ix-linux-hub" value={form.hub || suggested} onChange={event => patch({ hub: event.target.value })} />
<FieldDescription>{origin.loading ? "Читаем адрес WAN с CHR…" : suggested ? "Адрес WAN для подключения VPS." : "Введите адрес IX, доступный с VPS."}</FieldDescription>
</Field>
{form.kind === "wireguard" && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
{wireguard && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
<Input id="ix-linux-key" value={form.key} placeholder="Создать автоматически" onChange={event => patch({ key: event.target.value })} />
<FieldDescription>Укажите ключ только для своей пары WireGuard.</FieldDescription></Field>}
{form.exit !== "isolated" && destinationsField}
<Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
{form.kind !== "both" && <><Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
<Input id="ix-linux-tunnel-local" value={form.localAddress} placeholder="Автоматический IPv4" onChange={event => patch({ localAddress: event.target.value })} /></Field>
<Field><FieldLabel htmlFor="ix-linux-tunnel-peer">Адрес Linux в туннеле</FieldLabel>
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field>
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field></>}
<Field><FieldLabel htmlFor="ix-linux-prefixes">Сети за Linux</FieldLabel>
<Textarea id="ix-linux-prefixes" rows={2} value={form.prefixes} onChange={event => patch({ prefixes: event.target.value })} /></Field>
</div>
</details>
{edit && <div className="flex flex-wrap gap-2">
{binding && <div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant={form.enabled ? "outline" : "secondary"} aria-pressed={!form.enabled}
onClick={() => patch({ enabled: !form.enabled })}>{form.enabled ? "Приостановить доступ" : "Возобновить доступ"}</Button>
{form.kind === "gre-ipsec" && <Button type="button" size="sm" variant={rotate ? "secondary" : "outline"}
aria-pressed={rotate} onClick={() => setRotate(!rotate)}>Выпустить новый PSK</Button>}
</div>}
</div>
<SheetFooter>{form.kind === "wireguard" && !form.key && <p className="text-sm text-muted-foreground">После подтверждения можно скачать готовый файл WireGuard для Linux.</p>}
<Button type="submit" disabled={!valid || busy}>Сохранить</Button>
<SheetFooter>{(gre || !form.key) && <p className="text-sm text-muted-foreground">После подтверждения файлы подключения будут доступны в таблице.</p>}
<Button type="submit" disabled={!valid || busy}>{companion ? "Добавить туннель" : "Сохранить"}</Button>
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button></SheetFooter>
</form>
}
@@ -174,7 +215,7 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
inspect: (binding: IxLinuxBinding) => void
}) {
const [open, setOpen] = useState(false)
const [edit, setEdit] = useState<{ site: IxSite; binding: Binding } | null>(null)
const [edit, setEdit] = useState<ClientSelection | null>(null)
const rows = useMemo(() => {
const saved = segment.configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux ? [{
serverId: site.serverId, interfaceName: binding.name, kind: binding.kind as IxLinuxBinding["kind"],
@@ -218,9 +259,11 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
const binding = row.original
const site = segment.configuration.sites.find(site => site.serverId === binding.serverId)
const saved = site?.interfaces.find(candidate => candidate.name === binding.interfaceName)
const paired = !!site && !!saved && hasCompanion(site, saved)
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
return <div className="flex flex-wrap gap-1">
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName)}
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName) +
(paired ? binding.kind === "wireguard" ? " · WireGuard" : " · GRE/IPsec" : "")}
onClick={() => view(live)}>Конфиг Linux</Button>}
{binding.policy && (live || !readOnly && saved?.linux) && <DropdownMenu>
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " + binding.name} />}>
@@ -228,6 +271,8 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{live && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
{!readOnly && site && saved?.linux && !paired && <DropdownMenuItem
onClick={() => { setEdit({ site, binding: saved, addProtocol: true }); setOpen(true) }}>Добавить другой протокол</DropdownMenuItem>}
{!readOnly && saved?.linux && <DropdownMenuItem variant="destructive" onClick={() => revoke(binding)}>Отозвать доступ…</DropdownMenuItem>}
</DropdownMenuContent>
</DropdownMenu>}
@@ -249,11 +294,12 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
</FramePanel>
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
<SheetHeader><SheetTitle>{edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
<SheetHeader><SheetTitle>{edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
<SheetDescription>Укажите VPS и выберите, куда направлять его трафик.</SheetDescription>
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
</SheetHeader>
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} busy={busy}
setAddProtocol={addProtocol => setEdit(selection => selection && { ...selection, addProtocol })}
save={async input => { if (await save(input)) setOpen(false) }} cancel={() => setOpen(false)} />}
</SheetContent>
</Sheet>
+6 -3
View File
@@ -492,16 +492,19 @@ export default function IxPage() {
<p className="text-sm text-muted-foreground">{linux.kind === "wireguard"
? linux.managedWireguard ? "Готовый файл с ключом доступен пользователю с правом управления сетью."
: "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления."
: linux.policy && write ? "Подключите файл к strongSwan. Храните конфиг с PSK с правами доступа только для root."
: linux.policy && write ? "Скачайте оба файла в одну папку на VPS. Скрипт установит профиль strongSwan и поднимет GRE. SSH по внешнему IPv4 VPS останется прямым."
: "Для подключения нужен индивидуальный PSK, выданный оператором."}</p>
{(!linux.policy || linux.kind === "wireguard") && <pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>}
<Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => download(linux.filename, linux.template)}>
Скачать {linux.managedWireguard ? "шаблон" : linux.filename}
</Button>
{linux.setup && <>
<pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>
{linux.policy && write ? <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{
"sudo apt install charon-systemd strongswan-swanctl\nsudo systemctl start strongswan\nsudo sh ./" +
linux.filename.replace(/\.conf$/, "-setup.sh")
}</pre> : <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>}
<Button type="button" variant="outline" size="sm" className="w-fit"
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать команды настройки</Button>
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать скрипт GRE</Button>
</>}
{linux.bgp && <p className="wrap-anywhere text-sm text-muted-foreground">
BGP · ASN Linux {linux.bgp.localAs} · ASN IX {linux.bgp.remoteAs} · сосед {linux.bgp.neighbor}
+65 -12
View File
@@ -49,11 +49,21 @@ const router = createServer(async (request, response) => {
const list = rows[path] ??= []
const index = list.findIndex(entry => entry[".id"] === place)
list.splice(index < 0 ? list.length : index, 0, row)
if (path === "/ip/vrf" || path === "/interface/wireguard" || path === "/interface/bridge") {
if (["/ip/vrf", "/interface/wireguard", "/interface/bridge", "/interface/gre"].includes(path)) {
rows["/interface"].push({ ".id": row[".id"], name: row.name,
type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment })
}
result = row
} else if (request.method === "PATCH") {
const parent = path.slice(0, path.lastIndexOf("/"))
const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1))
const row = rows[parent]?.find(entry => entry[".id"] === id)
assert(row)
let raw = ""
for await (const chunk of request) raw += chunk
Object.assign(row, JSON.parse(raw))
writes++
result = row
} else if (request.method === "DELETE") {
if (deletes === failDeleteAt) throw Error("Synthetic RouterOS deletion failure")
const parent = path.slice(0, path.lastIndexOf("/"))
@@ -281,8 +291,15 @@ try {
{ serverId: Number(server.id), autonomousSystem: 64512, routerId: "192.0.2.6" },
] } }, 200)).segment
const managedPath = "/" + managed.id
rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" })
;(rows["/ip/address"] ??= []).push(
{ ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" },
{ ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" },
)
;(rows["/ip/route"] ??= []).push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0",
gateway: "192.0.2.1%ether1", "immediate-gw": "192.0.2.1%ether1", active: "true" })
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
peerEndpoint: "192.0.2.40", exit: "local-wan", prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName }
await post(managedPath + "/linux/credential", clientKey, 409)
@@ -341,23 +358,53 @@ try {
assert.equal(inactive.status, 409)
delete appliedPeer.disabled
const companionInput = { ...clientInput, kind: "gre-ipsec", companionOf: clientKey.interfaceName }
const canceled = await post(managedPath + "/linux", { ...companionInput, revision: credential.revision }, 200)
const canceledKey = { serverId: clientKey.serverId, interfaceName: canceled.interfaceName }
const reverted = await post(managedPath + "/linux/revoke", { ...canceledKey, revision: canceled.segment.revision }, 200)
const noChanges = await post(managedPath + "/plan", { revision: reverted.segment.revision }, 200)
assert.deepEqual(noChanges.changes, [])
const resumed = await post(managedPath + "/apply", { revision: reverted.segment.revision, digest: noChanges.digest }, 200)
const paired = await post(managedPath + "/linux", { ...companionInput, revision: resumed.segment.revision }, 200)
const bindings = paired.segment.configuration.sites[0].interfaces
const [wireguard, greBinding] = bindings
assert.ok(wireguard.linux.clientId)
const original = resumed.segment.configuration.sites[0].interfaces[0]
assert.deepEqual(wireguard, { ...original, linux: { ...original.linux, clientId: wireguard.linux.clientId } })
assert.equal(wireguard.linux.clientId, greBinding.linux.clientId)
assert.notEqual(wireguard.provisionWireguard.peerAddress, greBinding.provisionGre.peerAddress)
const foreignRoute = { ".id": "*FE", "routing-table": "main", "dst-address": "198.51.100.0/24",
gateway: "10.254.0.2%" + clientKey.interfaceName }
rows["/ip/route"].push(foreignRoute)
const blockedForeign = await post(managedPath + "/plan", { revision: paired.segment.revision }, 409)
assert.match(blockedForeign.error, /другой маршрутизацией/)
assert.equal(rows["/ip/route"].pop(), foreignRoute)
const pairPlan = await post(managedPath + "/plan", { revision: paired.segment.revision }, 200)
assert(!pairPlan.changes.some(change => change.path.startsWith("/interface/wireguard")))
const pairedApplied = await post(managedPath + "/apply", { revision: paired.segment.revision, digest: pairPlan.digest }, 200)
const pairVrf = rows["/ip/vrf"].find(row => row.interfaces?.includes(wireguard.name))!
assert(pairVrf.interfaces.split(",").includes(greBinding.name))
const greCredential = await post(managedPath + "/linux/credential",
{ serverId: clientKey.serverId, interfaceName: paired.interfaceName }, 200)
assert.match(greCredential.template, /secret = "[a-f0-9]{64}"/)
assert.match(greCredential.setup, /install -m 0600 "\$conf" \/etc\/swanctl\/conf\.d\//)
assert.match(greCredential.setup, /ip -4 rule add pref \d+ from 192\.0\.2\.40\/32 lookup main/)
assert.match(greCredential.setup, /ip -4 route replace default dev ixg\w+ src \S+ table \d+/)
assert(greCredential.setup.indexOf(" lookup main\n") < greCredential.setup.indexOf("swanctl --initiate"))
assert.equal((await post(managedPath + "/linux/credential", clientKey, 200)).template, credential.template)
const { rows: [exit] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-exit','127.0.0.1',$1,true,'exit-node','synthetic','synthetic',false,true) RETURNING id`, [port])
rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" })
rows["/ip/address"].push(
{ ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" },
{ ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" },
)
rows["/ip/route"].push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0", "immediate-gw": "192.0.2.1%ether1", active: "true" })
const transit = { targetServerId: Number(exit.id), localEndpoint: "192.0.2.20", remoteEndpoint: "192.0.2.30", family: 4, name: "remote-exit" }
const remoteClient = { ...clientInput, name: "linux-remote", revision: credential.revision, transit }
const appliedRevision = pairedApplied.segment.revision
const remoteClient = { ...clientInput, name: "linux-remote", revision: appliedRevision, exit: undefined, transit }
const beforeStage = writes
await post(managedPath + "/linux", { ...remoteClient, localAddress: "10.254.21.1/30" }, 400)
const stagedRemote = await post(managedPath + "/linux", remoteClient, 200)
assert.equal(writes, beforeStage)
assert.equal(stagedRemote.segment.revision, credential.revision + 1)
assert.equal(stagedRemote.segment.appliedRevision, credential.revision)
assert.equal(stagedRemote.segment.revision, appliedRevision + 1)
assert.equal(stagedRemote.segment.appliedRevision, appliedRevision)
const remoteSite = stagedRemote.segment.configuration.sites[0]
assert.equal(remoteSite.interfaces.find(row => row.name === stagedRemote.interfaceName).linux.exit, transit.name)
const transitBinding = remoteSite.interfaces.find(row => row.name === remoteSite.groups.find(group => group.id === transit.name).primary.interface)
@@ -369,11 +416,17 @@ try {
change.path === "/ip/firewall/nat" && change.fields["out-interface"] === "ether1"))
assert(remotePlan.changes.some(change => change.serverId === Number(server.id) && change.path === "/interface/wireguard"))
assert.equal(writes, beforeStage)
const both = await post(managedPath + "/linux", { ...clientInput, name: "both", peerEndpoint: "192.0.2.41",
revision: stagedRemote.segment.revision, additionalGre: true }, 200)
const added = both.segment.configuration.sites[0].interfaces.filter(binding => binding.linux?.name === "both")
assert.deepEqual(added.map(binding => binding.kind), ["wireguard", "gre-ipsec"])
assert.ok(added[0].linux.clientId)
assert.equal(added[0].linux.clientId, added[1].linux.clientId)
console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n,
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length,
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions,
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true }))
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true }))
} finally {
await mcp?.close()
await app?.close()
@@ -55,13 +55,23 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
const tunnel = binding.provisionGre
const family = tunnel ? isIP(tunnel.peerAddress) : 4
const protocol = "ip -" + family
const local = tunnel?.localAddress.split("/")[0]
const table = 30000 + parseInt(id.slice(-4), 16)
const management = 10000 + parseInt(id.slice(-3), 16)
const management = 12000 + 2 * parseInt(id.slice(-3), 16)
const managementRules = [
["ip -4", "to " + hub + "/32 lookup main"],
["ip -4", "from " + client + "/32 lookup main"],
...(family === 6 && binding.linux?.exit ? [["ip -6", "ipproto tcp sport 22 lookup main"]] : []),
]
const greParameters = id + " mode gre local " + client + " remote " + hub
const common = [
"swanctl --load-all",
"swanctl --initiate --child " + id + " --timeout 20",
"ip tunnel add " + greParameters,
]
return {
filename: id + ".conf",
template: [
"# Сверьте предложения и идентификаторы IKE с профилем узла IX.",
...(tunnel ? [] : ["# Сверьте предложения и идентификаторы IKE с профилем узла IX."]),
"connections {",
" " + id + " {",
" version = 2",
@@ -97,28 +107,36 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
"}",
"",
].join("\n"),
setup: [
"swanctl --load-all",
"swanctl --initiate --child " + id,
"# Создайте GRE после успешного установления IPsec.",
"ip tunnel add " + id + " mode gre local " + client + " remote " + hub,
tunnel ? "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id :
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
setup: (tunnel ? [
'conf="$(dirname -- "$0")/' + id + '.conf"',
'if [ ! -r "$conf" ]; then echo "Положите файл ' + id + '.conf рядом со скриптом" >&2; exit 1; fi',
'if ip link show dev ' + id + ' >/dev/null 2>&1; then echo "GRE уже поднят" >&2; exit 1; fi',
'install -d -m 0700 /etc/swanctl/conf.d',
'install -m 0600 "$conf" /etc/swanctl/conf.d/' + id + '.conf',
"cleanup() {",
" " + protocol + " rule del pref " + (management + 1) + " lookup " + table + " 2>/dev/null || :",
" ip link del dev " + id + " 2>/dev/null || :",
...managementRules.map(([ip, selector]) => " " + ip + " rule del pref " + management + " " + selector + " 2>/dev/null || :"),
" swanctl --terminate --ike " + id + " --timeout 5 >/dev/null 2>&1 || :",
"}",
"trap cleanup 0",
...managementRules.map(([ip, selector]) => ip + " rule add pref " + management + " " + selector),
...common,
"ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id,
"ip link set " + id + " up",
...[...new Set([
tunnel.localAddress.split("/")[0] + (family === 4 ? "/32" : "/128"),
...(binding.linux?.destinations ?? []).map(canonicalBgpPolicyPrefix),
...(bgp && isIP(bgp.localAddress) === family ? [bgp.localAddress + hostMask] : []),
...(binding.linux?.exit ? ["default"] : []),
])].map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress + " table " + table),
protocol + " rule add pref " + (management + 1) + " lookup " + table,
"trap - 0",
] : [
...common,
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
"ip link set " + id + " up",
...(tunnel ? [
protocol + " route replace " + local + (family === 4 ? "/32" : "/128") + " dev " + id + " src " + tunnel.peerAddress,
...(binding.linux?.destinations ?? []).map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress),
...(binding.linux?.exit ? [
protocol + " route replace default dev " + id + " src " + tunnel.peerAddress + " table " + table,
...(family === 4 ? [
"ip -4 rule add pref " + management + " to " + hub + "/32 lookup main",
"ip -4 rule add pref " + management + " from " + client + "/32 lookup main",
] : []),
protocol + " rule add pref " + (management + 1) + " lookup " + table,
"# Удаление политик: " + protocol + " rule del pref " + (management + 1) + " lookup " + table,
] : []),
] : []),
...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []),
].join("\n"),
]).join("\n"),
}
}
@@ -260,6 +260,38 @@ export async function assignIxRouterIds(id: string, configuration: IxConfigurati
}
export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxClientRequest) {
if (input.additionalGre && (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4)) {
throw new IxConflict("Для подключения по обоим протоколам укажите два внешних IPv4-адреса", 400)
}
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
const companion = input.companionOf && site?.interfaces.find(binding => binding.name === input.companionOf && binding.linux)
if (input.companionOf && !companion) throw new IxConflict("Исходное подключение Linux не найдено", 404)
const existingId = companion ? companion.linux?.clientId : undefined
if (companion && (companion.kind === input.kind || existingId &&
site?.interfaces.some(binding => binding.linux?.clientId === existingId && binding.kind === input.kind))) {
throw new IxConflict("Этот протокол уже подключён для клиента")
}
const name = companion ? companion.linux!.name : input.name
const first = await configureIxLinuxTunnel(segment, { ...input, name })
const second = input.additionalGre ? await configureIxLinuxTunnel({ ...segment, configuration: first.configuration }, {
...input, kind: "gre-ipsec", localAddress: undefined, peerAddress: undefined, peerPublicKey: undefined, prefixes: [],
}) : undefined
const result = second ?? first
const currentId = site?.interfaces.find(binding => binding.name === input.interfaceName)?.linux?.clientId
const clientId = existingId ?? currentId ?? (companion || second ? randomUUID() : undefined)
if (!clientId) return result
const siblings = new Set([first.interfaceName, second?.interfaceName, companion ? companion.name : undefined])
return { interfaceName: first.interfaceName, configuration: {
...result.configuration,
sites: result.configuration.sites.map(site => site.serverId !== input.serverId ? site : {
...site, interfaces: site.interfaces.map(binding =>
binding.linux && (siblings.has(binding.name) || binding.linux.clientId === clientId)
? { ...binding, linux: { ...binding.linux, name, clientId } } : binding),
}),
} }
}
async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRequest) {
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
if (!site) throw new IxConflict("Узел не входит в сегмент IX", 404)
const previous = site.interfaces.find(binding => binding.name === input.interfaceName && binding.linux)
@@ -313,7 +345,7 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
}
const binding: IxSite["interfaces"][number] = {
name, kind: input.kind, prefixes: input.prefixes,
linux: { name: input.name, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
linux: { name: input.name, clientId: previous?.linux?.clientId, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
exit: input.exit === "local-wan" ? localExit : input.exit },
}
if (input.kind === "wireguard") {
@@ -440,12 +472,25 @@ function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: Nat
return gre
}
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[]) {
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[], knownObjects: IxRouterObject[]) {
for (const site of configuration.sites) {
const device = devices.find(entry => entry.serverId === site.serverId)!
if (rowsFor(device, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) {
throw new IxConflict("Изолированный bridge отбрасывания IX содержит порты")
}
// Активация WAN-выхода создаёт в main обратный маршрут через клиентский туннель.
const ownedMainRoutes = new Map<string, IxRouterObject[]>()
for (const object of knownObjects) {
if (object.serverId !== site.serverId || !["/ip/route", "/ipv6/route"].includes(object.path) || object.fields["routing-table"] !== "main") continue
const key = objectMarker(object)
const known = ownedMainRoutes.get(key) ?? []
known.push(object)
ownedMainRoutes.set(key, known)
}
const foreignMainRoutes = ["/ip/route", "/ipv6/route"].flatMap(path => rowsFor(device, path).filter(row => {
if (row["routing-table"] !== "main" || isTrue(row.dynamic)) return false
return !ownedMainRoutes.get(marker(path, row.comment ?? ""))?.some(known => matches(row, known.fields))
}))
for (const binding of site.interfaces) {
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
if (!iface && (binding.provisionWireguard || binding.provisionGre || binding.provisionTransit)) continue
@@ -463,8 +508,8 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
throw new IxConflict("Интерфейс " + binding.name + " не выделен для данного сегмента IX")
}
const foreignVrf = rowsFor(device, "/ip/vrf").find(row => row.name !== "main" && row.name !== ixNamespace(id) && row.interfaces?.split(",").includes(binding.name))
const mainRoutes = [...rowsFor(device, "/ip/route"), ...rowsFor(device, "/ipv6/route")].filter(row => row["routing-table"] === "main" && !isTrue(row.dynamic))
if (foreignVrf || mainRoutes.some(row => row.gateway === binding.name || row.gateway?.includes("%" + binding.name))) {
if (foreignVrf || foreignMainRoutes.some(row => row.gateway?.split(",").some(gateway =>
gateway.trim().split("@")[0].split("%").at(-1) === binding.name))) {
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
}
if (binding.kind === "gre-ipsec") {
@@ -535,7 +580,7 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
verifyIxMainGateways(before.at(-1)!, objects.filter(object => object.serverId === serverId))
}
if (configuration) validateBindings(configuration, id, before)
if (configuration) validateBindings(configuration, id, before, resume ? objects.concat(previous) : previous)
for (const device of before) verifyEgressMembers(device, id, resume ? previous.concat(objects) : previous)
for (const old of previousConfiguration?.sites ?? []) {
const next = configuration?.sites.find(site => site.serverId === old.serverId)
+2 -1
View File
@@ -61,7 +61,8 @@
- **WireGuard.** IX автоматически создаёт пару ключей Linux. После применения скачайте готовый `.conf` из карточки клиента, сохраните под исходным именем в `/etc/wireguard/` с правами `0600` и запустите `sudo wg-quick up <имя-файла-без-.conf>`. Указанный внешний IP Linux сохраняет исходный путь управления при полном туннеле. Для клиента со своей парой ключей доступен шаблон с полем для его приватного ключа.
- **Получение WireGuard через MCP.** Вызовите `mm_wireguard_export_plan` с полями `serverId`, `interfaceName` клиента, `ixSegmentId` и `format: "peer-conf"`. После подтверждения и выполнения плана ссылка на готовый файл доступна авторизованному владельцу подключения 15 минут. Ключ находится только в скачиваемом файле.
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. Менеджер создаёт на CHR GRE с выключенным FastPath и IKEv2/IPsec в транспортном режиме. Оператор с правами записи скачивает конфиг strongSwan с индивидуальным PSK и команды настройки Linux. Старые вручную подготовленные подключения остаются доступны по прежнему шаблону.
- **Два протокола.** Отметьте WireGuard и GRE/IPsec при создании. Для существующего клиента откройте **Доступ и выход**, выберите свободный протокол и нажмите **Добавить туннель**. Туннели имеют отдельные адреса и ключи, входят в одну VRF сегмента на выбранном IX, настраиваются и отключаются отдельно. Для второго туннеля по умолчанию предложен доступ к разрешённым сетям. Если на VPS одновременно запущены оба туннеля с маршрутом по умолчанию, сгенерированные правила GRE направляют обычный трафик через GRE.
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. После применения скачайте конфиг strongSwan и скрипт GRE в одну папку на VPS. На Ubuntu установите `charon-systemd strongswan-swanctl`, запустите `sudo systemctl start strongswan` и выполните показанную в карточке команду `sudo sh ./…-setup.sh`. Скрипт копирует профиль с правами `0600`, устанавливает IKEv2/IPsec, создаёт GRE и использует отдельную таблицу для туннельных маршрутов. Транспорт до IX и ответы с внешнего IPv4 VPS, включая SSH, идут по основной таблице Linux.
### Выход и резерв
@@ -43,6 +43,7 @@ const greProvision = z.object({
const linuxPolicy = z.object({
name: z.string().trim().min(1).max(80),
clientId: z.string().uuid().optional(),
enabled: z.boolean(),
destinations: z.array(prefix).max(64),
exit: key.optional(),
@@ -139,6 +140,8 @@ export const ixLinuxClientRequest = z.object({
name: linuxPolicy.shape.name,
enabled: z.boolean().default(true),
kind: z.enum(["wireguard", "gre-ipsec"]),
additionalGre: z.boolean().optional(),
companionOf: interfaceName.optional(),
hubEndpoint: address,
peerEndpoint: address.optional(),
peerPublicKey: wireguardProvision.shape.peerPublicKey.optional(),
@@ -151,6 +154,9 @@ export const ixLinuxClientRequest = z.object({
rotate: z.boolean().optional(),
}).strict().refine(input => !input.transit || !input.exit || input.exit === input.transit.name,
{ path: ["exit"], message: "Выход клиента должен совпадать с выбранным транзитом" })
.refine(input => (!input.companionOf || !input.interfaceName) &&
(!input.additionalGre || input.kind === "wireguard" && !input.interfaceName && !input.companionOf),
"Оба протокола можно создать для нового клиента. Для существующего добавьте второй протокол.")
export type IxLinuxClientRequest = z.infer<typeof ixLinuxClientRequest>
+77 -8
View File
@@ -219,14 +219,17 @@ test("IX: новый сегмент сохраняется одним подтв
expect(applies).toBe(1)
})
for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN-адресами"]) test("IX: VPS подключается через " + mode, async ({ page }, testInfo) => {
const remote = mode !== "WAN IX", manual = mode === "ExitNode с двумя WAN-адресами"
for (const mode of ["WAN IX", "два протокола", "новый ExitNode", "ExitNode с двумя WAN-адресами"]) test("IX: VPS подключается · " + mode, async ({ page }, testInfo) => {
const both = mode === "два протокола"
const remote = mode.includes("ExitNode"), manual = mode === "ExitNode с двумя WAN-адресами"
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-vps", sites: [
{ serverId: 1, autonomousSystem: 64512, routerId: "10.255.0.1", autoRouterId: true },
] })
let segment = { id, revision: 1, appliedRevision: 1, configuration, updatedAt: observedAt }
const digest = "c".repeat(64)
let client: { name: string; kind: "wireguard"; serverId: number; interfaceName: string; managedWireguard: boolean } | undefined
let extended = false
const clientId = "6677cc81-0ac8-48fd-902a-cecd0ce8633a"
const configFile = "[Interface]\nPrivateKey = TEST_PRIVATE_KEY\n[Peer]\nAllowedIPs = 0.0.0.0/0\n"
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => {
@@ -241,14 +244,32 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
defaultRoutes: [{ family: 4, gateway: "192.0.2.1", interface: "ether1" }] })
if (path === "/api/ix/segments") return json({ items: [segment] })
if (path === `/api/ix/segments/${id}/linux` && req.method() === "POST") {
if (req.postDataJSON().companionOf) {
expect(req.postDataJSON()).toMatchObject({ revision: 3, serverId: 1, name: "vps-01", kind: "gre-ipsec",
companionOf: "il-vps", hubEndpoint: "192.0.2.11", peerEndpoint: "123.123.123.123", prefixes: [], destinations: [] })
expect(req.postDataJSON()).not.toHaveProperty("interfaceName")
expect(req.postDataJSON()).not.toHaveProperty("exit")
const site = segment.configuration.sites[0]
segment = { ...segment, revision: 4, configuration: ixSegmentConfigurationSchema.parse({
...segment.configuration, sites: [{ ...site, interfaces: [
{ ...site.interfaces[0], linux: { ...site.interfaces[0].linux, clientId } },
{ name: "il-gre", kind: "gre-ipsec", linux: { name: "vps-01", enabled: true, destinations: [], clientId } },
] }],
}) }
extended = true
return json({ segment, interfaceName: "il-gre" })
}
expect(req.postDataJSON()).toMatchObject({ name: "vps-01", kind: "wireguard", hubEndpoint: "192.0.2.11",
peerEndpoint: "123.123.123.123", ...(remote ? { transit: { targetServerId: 3, localEndpoint: "192.0.2.11", remoteEndpoint: "192.0.2.13", family: 4 } } : { exit: "local-wan" }) })
expect(req.postDataJSON()).not.toHaveProperty("peerPublicKey")
expect(req.postDataJSON().additionalGre).toBe(both ? true : undefined)
client = { name: "vps-01", kind: "wireguard", serverId: 1, interfaceName: "il-vps", managedWireguard: true }
const exit = remote ? req.postDataJSON().transit.name : "ix-wan4"
segment = { ...segment, revision: 2, configuration: ixSegmentConfigurationSchema.parse({
...configuration, sites: [{ ...configuration.sites[0], interfaces: [
{ name: "il-vps", kind: "wireguard", linux: { name: "vps-01", enabled: true, destinations: [], exit } },
{ name: "il-vps", kind: "wireguard", linux: { name: "vps-01", enabled: true, destinations: [], exit, clientId: both ? clientId : undefined,
peerEndpoint: "123.123.123.123" } },
...(both ? [{ name: "il-gre", kind: "gre-ipsec", linux: { name: "vps-01", enabled: true, destinations: [], exit, clientId } }] : []),
...(remote ? [{ name: "it-to-exit", kind: "wireguard", peerServerId: 3 }] : []),
], groups: [{ id: exit, gateway: "198.19.253.5", onFailure: "block",
primary: { interface: remote ? "it-to-exit" : "ether1", nextHop: "192.0.2.1", probe: "192.0.2.1", viaMain: !remote } }] }],
@@ -257,16 +278,25 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
}
if (path === `/api/ix/segments/${id}/linux/credential`) {
expect(req.method()).toBe("POST")
if (req.postDataJSON().interfaceName === "il-gre") {
expect(both || extended).toBe(true)
return json({ kind: "gre-ipsec", revision: 3, filename: "vps-gre.conf", template: "secret = TEST_PSK", setup: "ip tunnel add vps-gre mode gre" })
}
expect(req.postDataJSON()).toEqual({ serverId: 1, interfaceName: "il-vps" })
return json({ kind: "wireguard", revision: 3, filename: "vps.conf", template: configFile })
}
if (path === `/api/ix/segments/${id}/linux`) {
return json({ revision: segment.appliedRevision, items: segment.appliedRevision === 3 && client ? [client] : [] })
return json({ revision: segment.appliedRevision, items: segment.appliedRevision >= 3 && client ? [
client, ...(both || segment.appliedRevision === 5 ? [{ name: "vps-01", kind: "gre-ipsec", serverId: 1, interfaceName: "il-gre",
policy: segment.configuration.sites[0].interfaces[1].linux }] : []),
] : [] })
}
if (path.endsWith("/plan")) return json({ revision: 2, digest, changes: [{ serverId: 1, action: "create", path: "/interface/wireguard", fields: {} }] })
if (path.endsWith("/plan")) return json({ revision: segment.revision, digest, changes: [
{ serverId: 1, action: "create", path: extended ? "/interface/gre" : "/interface/wireguard", fields: {} },
] })
if (path.endsWith("/apply")) {
expect(req.postDataJSON()).toEqual({ revision: 2, digest })
segment = { ...segment, revision: 3, appliedRevision: 3 }
expect(req.postDataJSON()).toEqual({ revision: extended ? 4 : 2, digest })
segment = { ...segment, revision: segment.revision + 1, appliedRevision: segment.revision + 1 }
return json({ segment })
}
expect(path.startsWith("/api/mcp/")).toBe(false)
@@ -279,6 +309,13 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
await page.getByLabel("Имя клиента").fill("vps-01")
await page.getByLabel("Внешний адрес Linux").fill("123.123.123.123")
await expect(page.getByLabel("Публичный ключ Linux")).toBeHidden()
const protocols = page.getByRole("group", { name: "Протоколы подключения" })
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
if (both) {
await protocols.getByRole("button", { name: "GRE/IPsec" }).click()
await expect(protocols.getByRole("button", { name: "GRE/IPsec" })).toHaveAttribute("aria-pressed", "true")
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
}
await page.getByLabel("Выход трафика").click()
await page.getByRole("option", { name: remote ? "Через exit-arn · ExitNode" : "Интернет с этого IX" }).click()
await expect(page.getByLabel("Внешний адрес IX")).toHaveValue("192.0.2.11")
@@ -291,11 +328,22 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
await page.getByRole("button", { name: "Сохранить", exact: true }).click()
await page.getByRole("dialog", { name: "Подтвердите сохранение" }).getByRole("button", { name: "Подтвердить" }).click()
const download = page.waitForEvent("download")
await page.getByRole("button", { name: "Получить конфиг vps-01" }).click()
await page.getByRole("button", { name: both ? "Получить конфиг vps-01 · WireGuard" : "Получить конфиг vps-01", exact: true }).click()
const file = await download
expect(file.suggestedFilename()).toBe("vps.conf")
expect(await readFile((await file.path())!, "utf8")).toBe(configFile)
await expect(page.getByText("TEST_PRIVATE_KEY")).toHaveCount(0)
if (both) {
await page.getByRole("button", { name: "Получить конфиг vps-01 · GRE/IPsec", exact: true }).click()
await expect(page.getByText(/sudo sh .\/vps-gre-setup\.sh/)).toBeVisible()
await expect(page.getByText("TEST_PSK")).toHaveCount(0)
const greDownload = page.waitForEvent("download")
await page.getByRole("button", { name: "Скачать скрипт GRE" }).click()
const greFile = await greDownload
expect(greFile.suggestedFilename()).toBe("vps-gre-setup.sh")
expect(await readFile((await greFile.path())!, "utf8")).toContain("ip tunnel add")
return
}
const editExit = page.getByRole("button", { name: "Доступ и выход клиента vps-01" })
await expect(editExit).toContainText(remote ? "Через exit-arn" : "Интернет с этого IX")
if (remote) {
@@ -303,5 +351,26 @@ for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN
await page.getByLabel("Выход трафика").click()
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveCount(1)
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveAttribute("aria-selected", "true")
} else {
await editExit.click()
await page.getByLabel("Имя клиента").fill("Несохранённое имя")
const gre = protocols.getByRole("button", { name: "GRE/IPsec" })
await expect(gre).toBeEnabled()
await gre.click()
await expect(page.getByRole("heading", { name: "Добавить другой протокол" })).toBeVisible()
await expect(page.getByLabel("Имя клиента")).toHaveValue("vps-01")
await expect(page.getByLabel("Внешний адрес Linux")).toHaveValue("123.123.123.123")
await expect(gre).toHaveAttribute("aria-pressed", "true")
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
await gre.click()
await expect(page.getByLabel("Имя клиента")).toHaveValue("Несохранённое имя")
await gre.click()
await page.getByRole("button", { name: "Добавить туннель", exact: true }).click()
const dialog = page.getByRole("dialog", { name: "Подтвердите сохранение" })
await expect(dialog.getByText("/interface/gre", { exact: true })).toBeVisible()
await dialog.getByRole("button", { name: "Подтвердить" }).click()
await expect(page.getByRole("button", { name: "Получить конфиг vps-01 · GRE/IPsec", exact: true })).toBeVisible()
await expect(page.getByRole("button", { name: "Получить конфиг vps-01 · WireGuard", exact: true })).toBeVisible()
expect(segment.configuration.sites[0].interfaces[0].linux?.exit).toBe("ix-wan4")
}
})