Compare commits

...
3 Commits
Author SHA1 Message Date
Denozordec 63c0fc6506 fix(ix): ограничивать размер сегмента TCP для туннелей VPS
Docker images / prepare-release (push) Successful in 10s
Docker images / backend-test (push) Successful in 10m38s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / backend-image (push) Successful in 2m2s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-25 19:29:56 +07:00
Denozordec 682d6c8d55 fix(mcp): разрешить настройку размера сегмента TCP
Docker images / prepare-release (push) Successful in 9s
Docker images / backend-test (push) Successful in 10m27s
Docker images / backend-image (push) Successful in 2m19s
Docker images / frontend-image (push) Successful in 2m16s
Docker images / updater-image (push) Successful in 38s
Docker images / netflow-agent-image (push) Successful in 45s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-25 13:35:20 +07:00
Denozordec a41c70b104 feat(ix): добавить одноразовые ссылки импорта конфигураций
Docker images / prepare-release (push) Successful in 9s
Docker images / updater-image (push) Successful in 42s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / backend-test (push) Successful in 9m43s
Docker images / backend-image (push) Successful in 1m59s
Docker images / frontend-image (push) Successful in 15m47s
Docker images / notify-webhook (push) Successful in 0s
Docker images / publish-release (push) Successful in 10s
2026-11-25 11:46:51 +07:00
20 changed files with 296 additions and 19 deletions

No files matched your search

+10
View File
@@ -12,6 +12,8 @@ import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetT
import { requestJson } from "@/shared/api/http-client"
import { nodeLabel, type IxNode } from "./ix-view"
import { IxExistingTransport } from "./ix-existing-transport"
import { toast } from "sonner"
import { copyIxImportLink } from "./ix-import-link"
const modes = [
{ value: "failover", label: "Основной и резервные" },
@@ -107,6 +109,14 @@ export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly
{ method: "POST", body: JSON.stringify({ revision: g.revision }) })
download("ix-bond-" + g.id + ".json", JSON.stringify(bundle, null, 2))
})}>Скачать для ix-client</Button>
<Button size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
try {
await copyIxImportLink(backendUrl, `/api/ix/segments/${g.ownerSegmentId}/linux-bonds/${g.id}/export`, { revision: g.revision })
toast.success("Ссылка скопирована. На VPS откройте ix-client → L.")
} catch (error) {
toast.error(error instanceof Error ? error.message : "Не удалось скопировать ссылку")
}
})}>Скопировать ссылку для ix-client</Button>
</div>}
</div>)
const rows = children(binding => {
+12
View File
@@ -0,0 +1,12 @@
import { requestJson } from "@/shared/api/http-client"
export async function copyIxImportLink(backendUrl: string, path: string, params: object) {
const link = new URL(backendUrl.replace(/\/$/, "") + "/api/ix/import", window.location.origin)
if (link.protocol !== "https:" || !navigator.clipboard) throw new Error("Для одноразовой ссылки откройте Manager по HTTPS")
const { code } = await requestJson<{ code: string }>(backendUrl, path, {
method: "POST", body: JSON.stringify({ ...params, importLink: true }),
})
if (!/^[A-Za-z0-9_-]{32}$/.test(code)) throw new Error("Manager вернул неверный код импорта")
link.hash = code
await navigator.clipboard.writeText(link.toString())
}
+5 -3
View File
@@ -239,11 +239,11 @@ function TunnelTable({ data, columns, busy }: {
return <DataGridShell table={table} recordCount={data.length} isLoading={busy && !data.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
}
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect, bondAction, catalog, renderGroups, manualGroup }: {
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, copyImport, inspect, bondAction, catalog, renderGroups, manualGroup }: {
segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
view: (binding: IxLinuxBinding, transportOnly?: boolean) => void; revoke: (binding: IxLinuxBinding) => void
inspect: (binding: IxLinuxBinding) => void
copyImport: (binding: IxLinuxBinding) => void; inspect: (binding: IxLinuxBinding) => void
bondAction: IxRowBondAction; catalog: IxBondCatalog
renderGroups: (clientId: string) => ReactNode; manualGroup: ReactNode
}) {
@@ -331,6 +331,8 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
{bond && <DropdownMenuItem onClick={bond.open}>{bond.label}</DropdownMenuItem>}
{live && (binding.policy || catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === live.serverId && c.interfaceName === live.interfaceName)) &&
<DropdownMenuItem onClick={() => view(live, true)}>Конфиг для группы ix-client</DropdownMenuItem>}
{!readOnly && live?.policy && (live.managedWireguard || live.kind === "gre-ipsec") &&
<DropdownMenuItem onClick={() => copyImport(live)}>Скопировать ссылку для ix-client</DropdownMenuItem>}
{live?.policy && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
{!readOnly && site && saved?.linux && <DropdownMenuItem
onClick={() => { setEdit({ site, binding: saved, addProtocol: true, chooseTransport: true }); setOpen(true) }}>Добавить туннель</DropdownMenuItem>}
@@ -339,7 +341,7 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
</DropdownMenu>}
</div>
} },
], [nodes, applied, segment, readOnly, busy, view, revoke, inspect, bondAction, catalog.candidates])
], [nodes, applied, segment, readOnly, busy, view, copyImport, revoke, inspect, bondAction, catalog.candidates])
return <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<FrameTitle>Linux-клиенты</FrameTitle>
+10
View File
@@ -24,6 +24,7 @@ import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, Segmen
import { IxLinuxClients } from "./ix-linux-clients"
import { IxExits } from "./ix-exits"
import { IxClientBonds } from "./ix-client-bonds"
import { copyIxImportLink } from "./ix-import-link"
type Tab = "configuration" | "routes" | "linux"
@@ -281,6 +282,14 @@ export default function IxPage() {
setLinux({ ...binding, ...access, transportOnly })
}
async function copyLinuxImport(binding: IxLinuxBinding) {
if (!selected) return
await copyIxImportLink(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`, {
serverId: binding.serverId, interfaceName: binding.interfaceName,
})
setNotice("Ссылка скопирована. На VPS откройте ix-client → L. Ссылка действует до 5 минут.")
}
async function inspectLinux(binding: IxLinuxBinding) {
if (!selected) return
setLinuxPath(null)
@@ -474,6 +483,7 @@ export default function IxPage() {
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
copyImport={binding => void perform(() => copyLinuxImport(binding))}
inspect={binding => void perform(() => inspectLinux(binding))} />}
</IxClientBonds>
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
+7
View File
@@ -464,6 +464,13 @@
],
"reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся."
},
{
"method": "POST",
"path": "/api/ix/import",
"status": "excluded",
"operations": [],
"reason": "Одноразовый импорт Linux-клиента: выдаёт конфигурацию только по коду, созданному оператором IX."
},
{
"method": "GET",
"path": "/api/ix/linux-bonds",
+1 -1
View File
@@ -60,7 +60,7 @@
"test:ipsec": "tsx src/services/ipsec-config.test.ts && tsx src/services/ipsec-state.test.ts && tsx src/routes/ipsec-history.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-operation.test.ts && tsx src/routes/ipsec-mutation.test.ts && tsx src/routes/ipsec-nat.test.ts && tsx src/routes/ipsec-group.test.ts && tsx src/services/ipsec-peer-delete.test.ts && tsx src/modules/mcp/ipsec-peer-delete-actions.test.ts && tsx src/services/ipsec-user-delete.test.ts && tsx src/modules/mcp/ipsec-user-delete-actions.test.ts && tsx src/services/ipsec-certificate-delete.test.ts && tsx src/modules/mcp/ipsec-certificate-delete-actions.test.ts && tsx src/services/ipsec-peer-update.test.ts && tsx src/modules/mcp/ipsec-peer-update-actions.test.ts && tsx src/services/ipsec-user-update-model.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/services/ipsec-server-delete-model.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/ipsec-user-create-model.test.ts",
"test:live-maps": "tsx src/services/gre-revision-restore.test.ts && tsx src/services/gre-native-mutation.test.ts && tsx src/services/gre-mutation.test.ts && tsx src/services/filter-rules-observed.test.ts && tsx src/services/firewall-revision-restore.test.ts && tsx src/services/firewall-address-write.test.ts && tsx src/services/firewall-rule-write.test.ts && tsx src/services/gre-observed-read.test.ts && tsx src/services/network-observed-read.test.ts && tsx src/services/firewall-rule-move.test.ts && tsx src/services/ospf-state-read.test.ts && tsx src/modules/mcp/readiness-http.test.ts && tsx src/services/probe-interface-model.test.ts && tsx src/services/wan-runtime-model.test.ts && tsx src/services/gre-keepalive.test.ts && tsx src/services/gre-read.test.ts && tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/routes/vxlan.test.ts && tsx src/services/containers-live.test.ts && tsx src/services/firewall-poll.test.ts && tsx src/services/gre-catalog-poll.test.ts && tsx src/routes/filters-gre-catalog.test.ts && tsx src/routes/bgp-catalog.test.ts && tsx src/services/bgp-catalog-parse.test.ts && tsx src/routes/ospf-catalog.test.ts && tsx src/services/ospf-observed-values.test.ts && tsx src/routes/ospf-legacy.test.ts",
"test": "node scripts/test.mjs",
"test:ix": "tsx --test src/services/internet-exchange-plan.test.ts src/services/internet-exchange-execution.test.ts src/services/internet-exchange-bonds.test.ts src/services/ix-bond-transport.test.ts",
"test:ix": "tsx --test src/services/internet-exchange-plan.test.ts src/services/internet-exchange-execution.test.ts src/services/internet-exchange-bonds.test.ts src/services/ix-bond-transport.test.ts src/services/ix-import-links.test.ts",
"test:evolution": "tsx src/services/evobgp-catalog.test.ts && tsx src/services/evobgp-client.test.ts && tsx src/routes/evobgp-catalog.test.ts && tsx src/routes/evobgp-settings.test.ts && tsx src/plugins/auth.evolution-settings.test.ts",
"test:netflow-purge": "tsx src/db/operation-lock.test.ts && tsx src/services/traffic-flow-purge-execution.test.ts && tsx src/services/flow-purge-partitions.test.ts && tsx --test src/services/traffic-flow-worker-lifecycle.test.ts && tsx src/routes/traffic-flow-purge.test.ts",
"test:netflow-settings": "tsx src/services/traffic-flow-host-file-builders.test.ts && tsx src/services/traffic-flow-key-execution.test.ts && tsx src/routes/traffic-flow-settings.test.ts && tsx src/plugins/auth.netflow-settings.test.ts && tsx src/services/traffic-flow-agent-install.test.ts && tsx src/services/traffic-flow-agent-client.test.ts && tsx src/services/traffic-flow-operation-queue.test.ts && tsx src/routes/traffic-flow-host.test.ts && tsx src/services/traffic-flow-settings-execution.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/traffic-flow-lifecycle-fence.test.ts && tsx src/services/traffic-flow-settings-store.test.ts && tsx src/services/traffic-flow-settings-service.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts",
+1
View File
@@ -9,6 +9,7 @@ assert.equal(new Set(coverage.routes.map(routeKey)).size, coverage.routes.length
assert.deepEqual(coverage.routes.map(routeKey).sort(), actual.map(routeKey).sort(), "REST routes changed: update mcp-coverage.json with a typed tool, human-only reason, or explicit pending adapter")
const implemented = new Set(listActions().map(action => action.operation.id))
const ixInterfaceRoutes = new Set([
"POST /api/ix/import",
"GET /api/ix/linux-bonds",
"POST /api/ix/segments/:id/linux-bonds",
"DELETE /api/ix/segments/:id/linux-bonds/:bondId",
+13 -2
View File
@@ -85,6 +85,17 @@ const firewall = {
"src-address-list": text.optional(), "dst-address-list": text.optional(), "connection-state": text.optional(),
comment: text.optional(), disabled: bool.optional(), log: bool.optional(), "log-prefix": text.optional(),
}
const ipv4Mangle = {
...firewall,
"tcp-flags": z.string().regex(/^!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)(?:,!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)){0,7}$/)
.refine(value => new Set(value.replaceAll("!", "").split(",")).size === value.split(",").length, "Флаги TCP не должны повторяться").optional(),
"tcp-mss": z.string().regex(/^(?:0|[1-9]\d{0,4})(?:-(?:0|[1-9]\d{0,4}))?$/).refine(value => {
const [min, max = min] = value.split("-").map(Number)
return min <= max && max <= 65535
}, "Требуется значение или диапазон TCP MSS от 0 до 65535").optional(),
"new-mss": integer(1, 65535).optional(),
passthrough: bool.optional(),
}
const route = {
"dst-address": name.optional(), gateway: name.optional(), distance: integer(1, 255).optional(), scope: integer(0, 255).optional(),
"target-scope": integer(0, 255).optional(), "routing-table": name.optional(), "check-gateway": z.enum(["none", "ping", "arp", "bfd"]).optional(),
@@ -112,7 +123,7 @@ export const rosResources: RosResourceSpec[] = [
{ id: "vrf", path: "/ip/vrf", title: "VRF", permission: "mm:network", fields: z.object({ name: name.optional(), interfaces: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interfaces"] },
{ id: "ip_settings", path: "/ip/settings", title: "RPF и IPv4 hash-policy", permission: "mm:network", fields: z.object({ "rp-filter": z.enum(["no", "loose", "strict"]).optional(), "ipv4-multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
{ id: "ipv6_settings", path: "/ipv6/settings", title: "IPv6 hash-policy", permission: "mm:network", fields: z.object({ "multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))),
...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(family === "ip" && table === "mangle" ? ipv4Mangle : firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))),
{ id: "gre", path: "/interface/gre", title: "GRE", permission: "mm:network", fields: greNativeFieldsSchema, create: true, remove: true, requiredOnCreate: ["name", "remote-address"] },
{ id: "wireguard", path: "/interface/wireguard", title: "WireGuard", permission: "mm:network", fields: z.object({ ...common, "listen-port": integer(1, 65535).optional(), mtu: integer(68, 65535).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name"] },
{ id: "wireguard_peer", path: "/interface/wireguard/peers", title: "WireGuard peers", permission: "mm:network", fields: z.object({ interface: name.optional(), "public-key": name.optional(), "allowed-address": text.optional(), "endpoint-address": text.optional(), "endpoint-port": integer(0, 65535).optional(), "persistent-keepalive": text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["interface", "public-key", "allowed-address"] },
@@ -154,7 +165,7 @@ export function supportsRosPlacement(step: Pick<RosStep, "resource" | "action" |
export const ROS_SNAPSHOT_VERSION = 3
// OSPF cost plans and archived inverses issued before prefix-list evidence cannot be reused.
export const isSingletonRosResource = (resource: string) => ["ip_settings", "ipv6_settings", "ipv6_nd_settings"].includes(resource)
export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd", "ip_mangle"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
export interface RosSnapshot { serverId: number; resource: string; rows: ConfigurationRow[]; fingerprint: string; projectionVersion?: number; sourceProof?: string }
const firewallAddressListResources = ["ip_address_list", "ipv6_address_list"]
const routingPolicyResources = new Set(["routing_rule", "routing_filter", "routing_filter_select", "bfd_configuration", ...firewallAddressListResources, "ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"])
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, validateRosStep, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
import { fingerprint } from "./security.js"
import { proveRosDriftExpectation, verifyRosStepSnapshots } from "./ros-step-verification.js"
import { readOspfTemplateFlags } from "../../services/ospf-template-flags.js"
@@ -24,6 +24,26 @@ assert.equal(check(create, ack, [a, b], [a, b, { ...c, action: "drop" }]), false
assert.equal(check(create, undefined, [a], [a, c]), false, "Observed object never substitutes a lost acknowledgement")
assert.equal(check({ ...create, id: "*A" }, ack, [a], [a, c]), false)
const mangle = resourceById("ip_mangle")
const mssFields = {
chain: "forward", "out-interface": "gre-ix", "dst-address": "192.0.2.2/32", protocol: "tcp",
"tcp-flags": "syn,ack", "tcp-mss": "1381-65535", action: "change-mss", "new-mss": 1380, passthrough: true,
}
const mss = { ...create, resource: mangle.id, fields: validateRosStep(mangle, "create", mssFields) }
const liveMss = { ...mss.fields, ".id": "*C", "dst-address": "192.0.2.2", "tcp-flags": "ack,syn", passthrough: "yes", packets: "3" }
const mangleRows = (rows: ConfigurationRow[]) => configurationRows(mangle, rows)
assert.equal(check(mss, ack, [], mangleRows([liveMss])), true)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "new-mss": "1460" }])), false)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "dst-address": "192.0.2.2/24" }])), false)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "tcp-flags": "syn,!ack" }])), false)
const mssUpdate = { ...mss, action: "update" as const, id: "*C", fields: validateRosStep(mangle, "update", { "new-mss": 1360 }, "*C") }
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360" }])), true)
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360", "tcp-mss": "1361-65535" }])), false)
for (const bad of [{ "new-mss": 65536 }, { "tcp-mss": "1400-1300" }, { "tcp-mss": "1-65536" }, { "tcp-flags": "syn,!syn" }, { passthrough: "yes" }]) {
assert.throws(() => validateRosStep(mangle, "create", { ...mssFields, ...bad }))
}
assert.equal(resourceById("ip_filter").fields.safeParse(mssFields).success, false)
const update: RosStep = { ...create, action: "update", id: "*A", fields: { action: "accept" } }
const updated = { ...a, action: "accept" }
assert.equal(check(update, {}, [a, b], [updated, b]), true)
@@ -29,6 +29,10 @@ function requested(resource: RosResourceSpec, fields: RosStep["fields"], row: Co
if (resource.id === "bridge_vlan" && ["vlan-ids", "tagged", "untagged"].includes(key)) {
try { return canonicalBridgeVlanValue(key, row[key]) === canonicalBridgeVlanValue(key, value) } catch { return false }
}
if (resource.id === "ip_mangle") {
if (key === "dst-address" || key === "src-address") return String(row[key]).replace(/\/32$/, "") === value.replace(/\/32$/, "")
if (key === "tcp-flags" && schema.safeParse(row[key]).success) return String(row[key]).split(",").sort().join(",") === value.split(",").sort().join(",")
}
return String(row[key]) === value
})
}
+2 -1
View File
@@ -276,7 +276,8 @@ export async function requireAuth(
/** Gate the matched route, including encoded static segments in the raw URL. */
export async function requireApiAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const pathname = request.routeOptions.url ?? request.url.split("?")[0] ?? request.url
if (!pathname.startsWith("/api/") || pathname === "/api/auth/config") return
if (!pathname.startsWith("/api/") || pathname === "/api/auth/config" ||
request.method === "POST" && pathname === "/api/ix/import") return
await requireAuth(request, reply)
}
+63 -7
View File
@@ -5,7 +5,9 @@ import { ixBondEditSchema, ixChangeSchema, ixLinuxClientRequest, ixTransitReques
import { fingerprint, McpError } from "../modules/mcp/security.js"
import { audit } from "../modules/mcp/store.js"
import { pool } from "../db/index.js"
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError } from "../plugins/auth.js"
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError, type VerifiedRestRequestAuthority } from "../plugins/auth.js"
import { assertPortalClaimsCurrent } from "../modules/mcp/portal-revocation.js"
import { createIxImportLinks } from "../services/ix-import-links.js"
import { withApplicationCollectorLock, withApplicationMutationLock } from "../services/config-mutation-lock.js"
import { withConfigurationActor } from "../services/config-mutation-policy.js"
import { applyIxChange, assignIxRouterIds, configureIxLinuxClient, configureIxTransit, listIxLinuxClients, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, readIxNodeInventory, removeIxSegment } from "../services/internet-exchange-execution.js"
@@ -49,7 +51,23 @@ function summarizeTasks(tasks: Awaited<ReturnType<typeof prepareIxChange>>["nati
}))
}
const importLinkLifetime = 5 * 60_000
function importLinkOwner(authority: VerifiedRestRequestAuthority) {
const { ownerId, issuedAt, authentication, expiresAt } = authority
return async () => {
if (Date.now() >= expiresAt) throw new IxConflict("Ссылка истекла", 410)
if (authentication === "jwt") await assertPortalClaimsCurrent({ id: ownerId, issuedAt })
}
}
const ixRoutes: FastifyPluginAsync = async app => {
const links = createIxImportLinks()
app.post("/ix/import", { bodyLimit: 256 }, async (request, reply) => {
reply.header("Cache-Control", "private, no-store")
const { code } = z.object({ code: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict().parse(request.body)
return links.redeem(code)
})
app.setErrorHandler((error, request, reply) => {
if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues })
if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message })
@@ -81,11 +99,25 @@ const ixRoutes: FastifyPluginAsync = async app => {
})
app.post("/ix/segments/:id/linux-bonds/:bondId/export", async (request, reply) => {
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
const { revision } = planRequest.parse(request.body)
const scope = { deadlineAt: Date.now() + 90_000 }
const { revision, importLink } = planRequest.extend({ importLink: z.boolean().optional() }).parse(request.body)
const scope = { deadlineAt: Date.now() + (importLink ? importLinkLifetime : 90_000) }
const token = await captureVerifiedRestRequest(request, scope)
const authorize = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = await authorize()
const authority = await authorize()
const { ownerId } = authority
if (importLink) {
const authorizeOwner = importLinkOwner(authority)
await audit(pool, ownerId, "ix.bond.import_link_issued", null, { segmentId: id, bondId, revision })
await authorize()
reply.header("Cache-Control", "private, no-store")
return { code: links.issue(authority.monotonicDeadline, () => withApplicationCollectorLock(async () => {
await authorizeOwner()
const bond = await exportIxBond(id, bondId, revision, authorizeOwner)
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
await authorizeOwner()
return { version: 1, kind: "bond", bond }
})) }
}
return withApplicationCollectorLock(async () => {
const bundle = await exportIxBond(id, bondId, revision, authorize)
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
@@ -158,12 +190,36 @@ const ixRoutes: FastifyPluginAsync = async app => {
})
app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
const { id } = segmentParams.parse(request.params)
const { serverId, interfaceName, transportOnly } = clientKey.extend({ transportOnly: z.boolean().optional() }).parse(request.body)
const scope = { deadlineAt: Date.now() + 60_000 }
const { serverId, interfaceName, transportOnly, importLink } = clientKey.extend({
transportOnly: z.boolean().optional(), importLink: z.boolean().optional(),
}).parse(request.body)
const scope = { deadlineAt: Date.now() + (importLink ? importLinkLifetime : 60_000) }
const token = await captureVerifiedRestRequest(request, scope)
const { ownerId } = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
const authority = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = authority
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
if (importLink) {
const revision = segment.appliedRevision
if (revision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
const authorizeOwner = importLinkOwner(authority)
await audit(pool, ownerId, "ix.linux.import_link_issued", null, { segmentId: id, serverId, interfaceName, revision })
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
reply.header("Cache-Control", "private, no-store")
return { code: links.issue(authority.monotonicDeadline, async () => {
await authorizeOwner()
const current = await readIxSegment(id)
if (!current || current.appliedRevision !== revision) throw new IxConflict("Ревизия IX изменилась; получите новую ссылку", 410)
const access = await readIxLinuxClient(current, serverId, interfaceName, true, true, true)
if ((await readIxSegment(id))?.appliedRevision !== revision) throw new IxConflict("Ревизия IX изменилась; получите новую ссылку", 410)
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision })
await authorizeOwner()
const name = access.filename.replace(/\.conf$/, "")
if (access.kind === "wireguard") return { version: 1, kind: "wireguard", name, config: access.template }
if (!access.greImport) throw new IxConflict("Нет параметров управляемого GRE/IPsec")
return { version: 1, kind: "gre-ipsec", name, gre: access.greImport }
}) }
}
const access = await readIxLinuxClient(segment, serverId, interfaceName, true, transportOnly)
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision: access.revision })
@@ -14,6 +14,26 @@ const route: IxRouterObject = {
}
const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serverId: 17, source: "", rows }]
test("managed MSS rules are backfilled and removed without adopting a hand-written rule", () => {
const path = "/ip/firewall/mangle"
const from = { serverId: 17, path, fields: { comment: name + ":linux-mss-from-il-wg", action: "change-mss",
chain: "prerouting", "in-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const to = { serverId: 17, path, fields: { comment: name + ":linux-mss-to-il-wg", action: "change-mss",
chain: "postrouting", "out-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const manual = { ...to.fields, comment: "manual MSS", ".id": "*A" }
const fromRow = { ...from.fields, ".id": "*B" }
const toRow = { ...to.fields, ".id": "*C" }
const desired = [from, to]
const live = (rows: Array<Record<string, string>>) => device({ [path]: rows })
assert.deepEqual(planIxNative(id, desired, desired, live([manual])).map(task => [task.fields, task.placeBefore]),
[[from.fields, "*A"], [to.fields, "*A"]])
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, manual])).map(task => task.fields), [to.fields])
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, toRow, manual])), [])
assert.deepEqual(planIxNative(id, [], desired, live([fromRow, toRow, manual])).map(task => task.rosId), ["*C", "*B"])
assert.throws(() => planIxNative(id, desired, [], live([fromRow, manual])), /незавершённой операции/)
assert.throws(() => planIxNative(id, desired, desired, live([{ ...fromRow, "new-mss": "1460" }, toRow])), /изменён вне операции/)
})
test("a new VRF is inserted before main and no foreign route is altered", () => {
const changes = planIxNative(id, [vrf, route], [], device({
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
@@ -98,6 +98,9 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
// An older applied revision had no egress list. A partial set still needs reconciliation.
previous = previous.filter(object => !egressObject(object.fields.comment) || withEgressList.has(object.serverId))
// Older revisions were compiled without MSS rules. Backfill only absent managed MSS rules.
previous = previous.filter(object => !object.fields.comment?.startsWith(namespace + ":linux-mss-") ||
devices.some(device => device.serverId === object.serverId && managedRow(device, object)))
const desiredKeys = new Set(desired.map(deviceMarker))
const previousByKey = new Map(previous.map(object => [deviceMarker(object), object]))
const result: Task[] = []
@@ -356,7 +359,7 @@ async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRe
const binding: IxSite["interfaces"][number] = {
name, kind: input.kind, prefixes: input.prefixes,
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 },
tunnelMtu: input.tunnelMtu ?? previous?.linux?.tunnelMtu, exit: input.exit === "local-wan" ? localExit : input.exit },
}
if (input.kind === "wireguard") {
const existing = previous?.provisionWireguard
@@ -870,7 +873,7 @@ export async function observeIxLinuxPath(segment: IxSegment, serverId: number, n
})) }
}
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false, transportOnly = false): Promise<IxLinuxAccess> {
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false, transportOnly = false, forImportLink = false): Promise<IxLinuxAccess & { greImport?: import("./ix-import-links.js").IxImportGre }> {
if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
const configuration = await readIxRevision(segment.id, segment.appliedRevision)
const site = configuration.sites.find(site => site.serverId === serverId)
@@ -902,7 +905,15 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
throw new IxConflict("Действующий PSK не совпал с применённой ревизией. Выполните сверку")
}
}
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential, transportOnly) }
const access = ixGreClientTemplate(binding, serverId, peer, credential, transportOnly)
if (forImportLink && (!credential || !binding.provisionGre || !binding.endpoint || !binding.localEndpoint)) {
throw new IxConflict("Для импорта по ссылке нужен управляемый GRE/IPsec")
}
return { ...clientInfo, kind: "gre-ipsec", ...access,
...(forImportLink && credential && binding.provisionGre && binding.endpoint && binding.localEndpoint && {
greImport: { local: binding.endpoint, remote: binding.localEndpoint, address: binding.provisionGre.peerAddress, psk: credential },
}),
}
}
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
@@ -32,6 +32,8 @@ test("managed clients get their own return path and fail closed if both exit pro
provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900,
localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } })
const objects = compileIxConfiguration(id, value)
const clamp = objects.findIndex(object => object.fields.comment === table + ":linux-mss-from-linux-wg")
assert.ok(clamp >= 0 && clamp < objects.findIndex(object => object.fields.comment === table + ":linux-linux-wg-route"))
const clientTable = ixClientRoutingTable(table, "linux-wg")
const defaults = objects.filter(object => object.fields["routing-table"] === clientTable)
assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"])
@@ -45,6 +47,35 @@ test("managed clients get their own return path and fail closed if both exit pro
assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1")))
})
test("managed Linux tunnels clamp TCP SYN in both directions before routing marks can end prerouting", () => {
const value = fixture(), site = value.sites[0]
site.interfaces.push(
{ name: "linux-wg", kind: "wireguard", prefixes: [], linux: { name: "vps", enabled: true, destinations: [] },
provisionWireguard: { localAddress: "10.254.0.1/30", peerAddress: "10.254.0.2", listenPort: 51820, peerPublicKey: "A".repeat(43) + "=" } },
{ name: "linux-gre", kind: "gre-ipsec", prefixes: [], endpoint: "192.0.2.90", localEndpoint: "192.0.2.17",
linux: { name: "vps", enabled: false, destinations: [] },
provisionGre: { localAddress: "10.254.0.5/30", peerAddress: "10.254.0.6", credentialId: id } },
{ name: "linux-wg6", kind: "wireguard", prefixes: [],
linux: { name: "vps6", enabled: true, destinations: [], tunnelMtu: 1360 },
provisionWireguard: { localAddress: "fd00:254::1/126", peerAddress: "fd00:254::2", listenPort: 51821, peerPublicKey: "B".repeat(43) + "=" } },
)
const rules = compileIxConfiguration(id, ixSegmentConfigurationSchema.parse(value)).filter(object => object.fields.action === "change-mss")
assert.equal(rules.length, 6)
for (const [binding, family, mss, disabled] of [
["linux-wg", "ip", 1380, "false"], ["linux-gre", "ip", 1380, "true"], ["linux-wg6", "ipv6", 1300, "false"],
] as const) {
const list = ixClientRoutingTable(table, binding) + "-src"
const shared = { protocol: "tcp", "tcp-flags": "syn", "tcp-mss": (mss + 1) + "-65535",
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled }
assert.deepEqual(rules.filter(object => object.fields.comment.endsWith("-" + binding)), [
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "prerouting", "in-interface": binding, "src-address-list": list, comment: table + ":linux-mss-from-" + binding } },
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "postrouting", "out-interface": binding, "dst-address-list": list, comment: table + ":linux-mss-to-" + binding } },
])
}
})
test("a managed remote exit prepares both CHRs and returns only prefixes of users assigned to it", () => {
const value = fixture(), site = value.sites[0]
site.interfaces.push({ name: "it-abc", kind: "wireguard", prefixes: [], peerServerId: 99,
+13 -1
View File
@@ -84,6 +84,11 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
const permitted = privateTable + "-dst"
const sourcesCidr = [...new Set([host(tunnel.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])]
const destinations = [...new Set([host(tunnel.localAddress.split("/")[0]), ...policy.destinations.map(canonicalBgpPolicyPrefix)])]
// Use the WireGuard default as a conservative ceiling for both managed tunnel types.
const mss = (policy.tunnelMtu ?? 1420) - (family === 4 ? 40 : 60)
const clamp = { protocol: "tcp", "tcp-flags": "syn", "tcp-mss": (mss + 1) + "-65535",
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled: String(!policy.enabled) }
const mangle = ip + "/firewall/mangle"
const ingress = { chain: "prerouting", "in-interface": binding.name }
const exit = site.groups.find(group => group.id === policy.exit)
const paths = exit ? groupPaths(exit) : []
@@ -114,6 +119,13 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace,
action: "accept", disabled: String(!policy.enabled) })
add(filter, key + "-deny-inbound", { ...inbound, action: "drop" })
// The real VRF member is visible before routing and after routing, respectively.
add(mangle, "linux-mss-from-" + binding.name, {
...clamp, ...ingress, "src-address-list": sources,
})
add(mangle, "linux-mss-to-" + binding.name, {
...clamp, chain: "postrouting", "out-interface": binding.name, "dst-address-list": sources,
})
if (!exit) return
add("/routing/table", key + "-table", { name: privateTable, fib: "true" })
for (const [index, path] of paths.entries()) {
@@ -122,7 +134,7 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
})
}
add(routePath(family), key + "-default-drop", { "routing-table": privateTable, "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" })
add(ip + "/firewall/mangle", key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted,
add(mangle, key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted,
action: "mark-routing", "new-routing-mark": privateTable, passthrough: "false", disabled: String(!policy.enabled) })
const mainPaths = paths.filter(path => path.viaMain)
for (const [index, path] of mainPaths.entries()) {
@@ -0,0 +1,26 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { createIxImportLinks, type IxImportBundle } from "./ix-import-links.js"
const bundle: IxImportBundle = { version: 1, kind: "wireguard", name: "ixw000000000000", config: "fixture" }
test("only one concurrent request can claim a link", async () => {
const links = createIxImportLinks(() => 10)
let reads = 0
const code = links.issue(20, async () => { reads++; return bundle })
assert.match(code, /^[A-Za-z0-9_-]{32}$/)
const responses = await Promise.allSettled([links.redeem(code), links.redeem(code)])
assert.deepEqual(responses[0], { status: "fulfilled", value: bundle })
assert.equal(responses[1].status, "rejected")
assert.equal(reads, 1)
})
test("expiry is enforced before and after loading the bundle", async () => {
let now = 10
const links = createIxImportLinks(() => now)
const expired = links.issue(20, async () => { assert.fail("expired link read its source") })
const tooSlow = links.issue(30, async () => { now = 31; return bundle })
now = 20
await assert.rejects(links.redeem(expired), /истекла/)
await assert.rejects(links.redeem(tooSlow), /истекла/)
})
+39
View File
@@ -0,0 +1,39 @@
import { createHash, randomBytes } from "node:crypto"
import { performance } from "node:perf_hooks"
import type { IxBondBundle } from "@mmapp/contracts/internet-exchange"
import { IxConflict } from "./internet-exchange-plan.js"
export type IxImportGre = { local: string; remote: string; address: string; psk: string }
export type IxImportBundle =
| { version: 1; kind: "wireguard"; name: string; config: string }
| { version: 1; kind: "gre-ipsec"; name: string; gre: IxImportGre }
| { version: 1; kind: "bond"; bond: IxBondBundle }
const digest = (code: string) => createHash("sha256").update(code).digest("hex")
const maxLinks = 256
const expired = () => new IxConflict("Ссылка истекла или уже использована", 410)
export function createIxImportLinks(now = () => performance.now()) {
const links = new Map<string, { deadline: number; load: () => Promise<IxImportBundle> }>()
return {
issue(deadline: number, load: () => Promise<IxImportBundle>) {
const current = now()
for (const [key, entry] of links) if (entry.deadline <= current) links.delete(key)
if (deadline <= current) throw expired()
if (links.size >= maxLinks) throw new IxConflict("Слишком много активных ссылок импорта", 429)
const code = randomBytes(24).toString("base64url")
// shortcut: pending links live in this backend process, use shared storage if the backend is replicated.
links.set(digest(code), { deadline, load })
return code
},
async redeem(code: string) {
const key = digest(code), entry = links.get(key)
links.delete(key)
if (!entry || entry.deadline <= now()) throw expired()
const bundle = await entry.load()
if (entry.deadline <= now()) throw expired()
return bundle
},
}
}
+2
View File
@@ -66,6 +66,8 @@
### Несколько туннелей на одном VPS
Для подготовки транспорта из меню WireGuard или GRE/IPsec выберите **Скопировать ссылку для ix-client**. На VPS нажмите **L** в ix-client, вставьте ссылку и нажмите **F2**. Ссылка действует до пяти минут и погашается при первой попытке загрузки. В **P → Зависимости** можно проверить и по подтверждению установить недостающие пакеты. После подготовки транспорта сохраните группу и скопируйте её ссылку рядом с кнопкой **Скачать для ix-client**. JSON по-прежнему можно импортировать через **B → I**.
Карточка Linux-клиента объединяет его туннели и группы резервирования. Для нового интерфейса RouterOS имя включает протокол, имя клиента и уникальный суффикс, например `il-gre-tg-a1b2c3d4e5f6`. Существующие подключения сохраняют свои имена. RX и TX в строке GRE/IPsec показывают накопленные байты интерфейса на CHR.
1. В **Linux-клиенты** откройте меню действующего подключения и выберите **Создать группу с этим туннелем**. Интерфейс уже будет первым в списке. Для участника существующей группы это же меню открывает её редактор. Ключи VPS и CHR при создании группы сохраняются. Для нового транспорта откройте меню клиента и скачайте **Конфиг для группы ix-client**.
@@ -48,6 +48,7 @@ const linuxPolicy = z.object({
clientId: z.string().uuid().optional(),
enabled: z.boolean(),
destinations: z.array(prefix).max(64),
tunnelMtu: z.number().int().min(1280).max(1420).optional(),
exit: key.optional(),
peerEndpoint: address.optional(),
}).strict()
@@ -152,6 +153,7 @@ export const ixLinuxClientRequest = z.object({
peerAddress: address.optional(),
prefixes: z.array(prefix).max(64).default([]),
destinations: linuxPolicy.shape.destinations.default([]),
tunnelMtu: linuxPolicy.shape.tunnelMtu,
exit: key.optional(),
transit: ixTransitOptions.optional(),
rotate: z.boolean().optional(),