Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
682d6c8d55 | ||
|
|
a41c70b104 |
No files matched your search
@@ -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 => {
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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="После сохранения можно подключать клиентов." />}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 })
|
||||
|
||||
@@ -870,7 +870,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 +902,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"])
|
||||
|
||||
@@ -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), /истекла/)
|
||||
})
|
||||
@@ -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
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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**.
|
||||
|
||||
Reference in new issue
Block a user