diff --git a/app/(main)/ix/ix-client-bonds.tsx b/app/(main)/ix/ix-client-bonds.tsx index 1a913f23..c36cf50e 100644 --- a/app/(main)/ix/ix-client-bonds.tsx +++ b/app/(main)/ix/ix-client-bonds.tsx @@ -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 + } ) const rows = children(binding => { diff --git a/app/(main)/ix/ix-import-link.ts b/app/(main)/ix/ix-import-link.ts new file mode 100644 index 00000000..6d09e651 --- /dev/null +++ b/app/(main)/ix/ix-import-link.ts @@ -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()) +} diff --git a/app/(main)/ix/ix-linux-clients.tsx b/app/(main)/ix/ix-linux-clients.tsx index 5eb35bb9..ad0b8174 100644 --- a/app/(main)/ix/ix-linux-clients.tsx +++ b/app/(main)/ix/ix-linux-clients.tsx @@ -239,11 +239,11 @@ function TunnelTable({ data, columns, busy }: { return } -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; 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 && {bond.label}} {live && (binding.policy || catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === live.serverId && c.interfaceName === live.interfaceName)) && view(live, true)}>Конфиг для группы ix-client} + {!readOnly && live?.policy && (live.managedWireguard || live.kind === "gre-ipsec") && + copyImport(live)}>Скопировать ссылку для ix-client} {live?.policy && inspect(live)}>Проверить путь} {!readOnly && site && saved?.linux && { setEdit({ site, binding: saved, addProtocol: true, chooseTransport: true }); setOpen(true) }}>Добавить туннель} @@ -339,7 +341,7 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, } } }, - ], [nodes, applied, segment, readOnly, busy, view, revoke, inspect, bondAction, catalog.candidates]) + ], [nodes, applied, segment, readOnly, busy, view, copyImport, revoke, inspect, bondAction, catalog.candidates]) return Linux-клиенты diff --git a/app/(main)/ix/page.tsx b/app/(main)/ix/page.tsx index 098f6695..c2190023 100644 --- a/app/(main)/ix/page.tsx +++ b/app/(main)/ix/page.tsx @@ -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))} />} : } diff --git a/backend/mcp-coverage.json b/backend/mcp-coverage.json index d2c2e65a..83c122fd 100644 --- a/backend/mcp-coverage.json +++ b/backend/mcp-coverage.json @@ -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", diff --git a/backend/package.json b/backend/package.json index 4ce7f895..a05058e1 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/src/modules/mcp/coverage.test.ts b/backend/src/modules/mcp/coverage.test.ts index c2f47bcf..a280df19 100644 --- a/backend/src/modules/mcp/coverage.test.ts +++ b/backend/src/modules/mcp/coverage.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", diff --git a/backend/src/plugins/auth.ts b/backend/src/plugins/auth.ts index 90676931..6ee8d7c8 100644 --- a/backend/src/plugins/auth.ts +++ b/backend/src/plugins/auth.ts @@ -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 { 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) } diff --git a/backend/src/routes/internet-exchange.ts b/backend/src/routes/internet-exchange.ts index 95289a05..71e3ae40 100644 --- a/backend/src/routes/internet-exchange.ts +++ b/backend/src/routes/internet-exchange.ts @@ -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>["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 }) diff --git a/backend/src/services/internet-exchange-execution.ts b/backend/src/services/internet-exchange-execution.ts index f2414f4d..a4f47e72 100644 --- a/backend/src/services/internet-exchange-execution.ts +++ b/backend/src/services/internet-exchange-execution.ts @@ -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 { +export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false, transportOnly = false, forImportLink = false): Promise { 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"]) diff --git a/backend/src/services/ix-import-links.test.ts b/backend/src/services/ix-import-links.test.ts new file mode 100644 index 00000000..371f537d --- /dev/null +++ b/backend/src/services/ix-import-links.test.ts @@ -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), /истекла/) +}) diff --git a/backend/src/services/ix-import-links.ts b/backend/src/services/ix-import-links.ts new file mode 100644 index 00000000..3a1c4316 --- /dev/null +++ b/backend/src/services/ix-import-links.ts @@ -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 Promise }>() + return { + issue(deadline: number, load: () => Promise) { + 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 + }, + } +} diff --git a/docs/ix.md b/docs/ix.md index 369c865d..beec2005 100644 --- a/docs/ix.md +++ b/docs/ix.md @@ -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**.