Compare commits

...
1 Commits
Author SHA1 Message Date
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
13 changed files with 188 additions and 14 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",
+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 })
@@ -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), /истекла/)
})
+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**.