Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67c3a4fd73 | ||
|
|
9beb24273b | ||
|
|
5cc6128086 | ||
|
|
569b6be2b4 | ||
|
|
752256f12e | ||
|
|
a3502b9755 |
@@ -20,9 +20,10 @@
|
|||||||
"test:users": "tsx src/modules/users/iface-type.test.ts && tsx src/modules/users/bindings.test.ts",
|
"test:users": "tsx src/modules/users/iface-type.test.ts && tsx src/modules/users/bindings.test.ts",
|
||||||
"test:pg": "tsx src/db/sql-bind.test.ts && tsx src/db/sqlite-json.test.ts && tsx src/db/traffic-flags.test.ts && tsx src/db/pg-schema.test.ts && tsx src/services/config-revisions.test.ts",
|
"test:pg": "tsx src/db/sql-bind.test.ts && tsx src/db/sqlite-json.test.ts && tsx src/db/traffic-flags.test.ts && tsx src/db/pg-schema.test.ts && tsx src/services/config-revisions.test.ts",
|
||||||
"test:config-sync": "tsx src/services/config-apply-plan.test.ts && tsx src/services/entity-snapshots.test.ts",
|
"test:config-sync": "tsx src/services/config-apply-plan.test.ts && tsx src/services/entity-snapshots.test.ts",
|
||||||
|
"test:ros-file": "tsx src/services/ros-file-contents.test.ts",
|
||||||
"test:backups": "tsx src/services/s3-backup-client.test.ts",
|
"test:backups": "tsx src/services/s3-backup-client.test.ts",
|
||||||
"test:live-maps": "tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/services/containers-live.test.ts",
|
"test:live-maps": "tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/services/containers-live.test.ts",
|
||||||
"test": "npm run test:alert-engine && npm run test:auth && npm run test:wireguard && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:backups && npm run test:live-maps && npm run test:config-sync",
|
"test": "npm run test:alert-engine && npm run test:auth && npm run test:wireguard && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:backups && npm run test:live-maps && npm run test:config-sync && npm run test:ros-file",
|
||||||
"test:geoip": "tsx src/services/traffic-flow-geoip.test.ts"
|
"test:geoip": "tsx src/services/traffic-flow-geoip.test.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
||||||
import type { FastifyReply } from "fastify"
|
import type { FastifyReply } from "fastify"
|
||||||
import {
|
import {
|
||||||
|
IPSEC_MIN_PASSPHRASE,
|
||||||
ipsecCertDeleteRequestSchema,
|
ipsecCertDeleteRequestSchema,
|
||||||
ipsecCertExportByNameRequestSchema,
|
ipsecCertExportByNameRequestSchema,
|
||||||
ipsecCertExportRequestSchema,
|
ipsecCertExportRequestSchema,
|
||||||
@@ -97,6 +98,22 @@ function errReply(reply: FastifyReply, e: unknown) {
|
|||||||
return reply.status(502).send({ error: `RouterOS: ${msg}` })
|
return reply.status(502).send({ error: `RouterOS: ${msg}` })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 400 по невалидному телу. Для короткого пароля .p12 — понятный текст вместо generic-сообщения:
|
||||||
|
* RouterOS отклоняет `export-passphrase` короче 8 символов.
|
||||||
|
*/
|
||||||
|
function badBodyReply(reply: FastifyReply, error: z.ZodError) {
|
||||||
|
const shortPassphrase = error.issues.some(
|
||||||
|
(issue) => issue.path[0] === "passphrase" && issue.code === "too_small",
|
||||||
|
)
|
||||||
|
if (shortPassphrase) {
|
||||||
|
return reply.status(400).send({
|
||||||
|
error: `Пароль архива .p12 должен быть не короче ${IPSEC_MIN_PASSPHRASE} символов (требование RouterOS)`,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return reply.status(400).send({ error: "Некорректное тело запроса", details: error.flatten() })
|
||||||
|
}
|
||||||
|
|
||||||
async function recordIpsec(
|
async function recordIpsec(
|
||||||
server: NonNullable<Awaited<ReturnType<typeof getEnabledIpsecServerById>>>,
|
server: NonNullable<Awaited<ReturnType<typeof getEnabledIpsecServerById>>>,
|
||||||
source: ConfigRevisionSource,
|
source: ConfigRevisionSource,
|
||||||
@@ -122,7 +139,7 @@ async function buildCertBundle(
|
|||||||
args: { userName: string; certName?: string; serverEndpoint: string; passphrase: string; dns?: string },
|
args: { userName: string; certName?: string; serverEndpoint: string; passphrase: string; dns?: string },
|
||||||
): Promise<IpsecCertBundle> {
|
): Promise<IpsecCertBundle> {
|
||||||
const certName = args.certName?.trim() || clientCertName(args.userName)
|
const certName = args.certName?.trim() || clientCertName(args.userName)
|
||||||
const { fileName, content } = await exportCertificateP12ByName(client, certName, args.passphrase)
|
const { fileName, content, passphrase } = await exportCertificateP12ByName(client, certName, args.passphrase)
|
||||||
const p12B64 = content.toString("base64")
|
const p12B64 = content.toString("base64")
|
||||||
return {
|
return {
|
||||||
user: args.userName,
|
user: args.userName,
|
||||||
@@ -130,7 +147,7 @@ async function buildCertBundle(
|
|||||||
filename: fileName,
|
filename: fileName,
|
||||||
contentB64: p12B64,
|
contentB64: p12B64,
|
||||||
mime: "application/x-pkcs12",
|
mime: "application/x-pkcs12",
|
||||||
passphrase: args.passphrase,
|
passphrase,
|
||||||
sswanFilename: `${certName}.sswan`,
|
sswanFilename: `${certName}.sswan`,
|
||||||
sswanContent: buildSswanConfig({
|
sswanContent: buildSswanConfig({
|
||||||
name: `IKEv2 ${args.serverEndpoint}`,
|
name: `IKEv2 ${args.serverEndpoint}`,
|
||||||
@@ -142,7 +159,7 @@ async function buildCertBundle(
|
|||||||
userName: args.userName,
|
userName: args.userName,
|
||||||
serverEndpoint: args.serverEndpoint,
|
serverEndpoint: args.serverEndpoint,
|
||||||
p12Filename: fileName,
|
p12Filename: fileName,
|
||||||
passphrase: args.passphrase,
|
passphrase,
|
||||||
dns: args.dns,
|
dns: args.dns,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
@@ -243,7 +260,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
|||||||
app.post("/ipsec/users", async (req, reply) => {
|
app.post("/ipsec/users", async (req, reply) => {
|
||||||
const parsed = ipsecUserCreateRequestSchema.safeParse(req.body ?? {})
|
const parsed = ipsecUserCreateRequestSchema.safeParse(req.body ?? {})
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
return badBodyReply(reply, parsed.error)
|
||||||
}
|
}
|
||||||
const body = parsed.data
|
const body = parsed.data
|
||||||
const server = await getEnabledIpsecServerById(body.serverId)
|
const server = await getEnabledIpsecServerById(body.serverId)
|
||||||
@@ -608,7 +625,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
|||||||
const { serverId, rosId } = req.params as { serverId: string; rosId: string }
|
const { serverId, rosId } = req.params as { serverId: string; rosId: string }
|
||||||
const parsed = ipsecCertExportRequestSchema.safeParse({ ...(req.body as object), serverId, clientId: rosId })
|
const parsed = ipsecCertExportRequestSchema.safeParse({ ...(req.body as object), serverId, clientId: rosId })
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
return badBodyReply(reply, parsed.error)
|
||||||
}
|
}
|
||||||
const body = parsed.data
|
const body = parsed.data
|
||||||
const server = await getEnabledIpsecServerById(serverIdParam(serverId))
|
const server = await getEnabledIpsecServerById(serverIdParam(serverId))
|
||||||
@@ -629,7 +646,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
|||||||
const sharedMc = state.modeConfigs.find((m) => (m.name ?? "").trim() === IPSEC_COMMON_NAME)
|
const sharedMc = state.modeConfigs.find((m) => (m.name ?? "").trim() === IPSEC_COMMON_NAME)
|
||||||
const dns = sharedMc?.["static-dns"]?.trim() || undefined
|
const dns = sharedMc?.["static-dns"]?.trim() || undefined
|
||||||
// export работает по имени сертификата (certName), не по userName
|
// export работает по имени сертификата (certName), не по userName
|
||||||
const { fileName, content } = await client.exportCertificatePkcs12({
|
const { fileName, content, passphrase } = await client.exportCertificatePkcs12({
|
||||||
name: certName,
|
name: certName,
|
||||||
passphrase: body.passphrase,
|
passphrase: body.passphrase,
|
||||||
})
|
})
|
||||||
@@ -640,7 +657,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
|||||||
filename: fileName,
|
filename: fileName,
|
||||||
contentB64: p12B64,
|
contentB64: p12B64,
|
||||||
mime: "application/x-pkcs12",
|
mime: "application/x-pkcs12",
|
||||||
passphrase: body.passphrase,
|
passphrase,
|
||||||
sswanFilename: `${certName}.sswan`,
|
sswanFilename: `${certName}.sswan`,
|
||||||
sswanContent: buildSswanConfig({
|
sswanContent: buildSswanConfig({
|
||||||
name: `IKEv2 ${serverEndpoint}`,
|
name: `IKEv2 ${serverEndpoint}`,
|
||||||
@@ -652,7 +669,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
|||||||
userName,
|
userName,
|
||||||
serverEndpoint,
|
serverEndpoint,
|
||||||
p12Filename: fileName,
|
p12Filename: fileName,
|
||||||
passphrase: body.passphrase,
|
passphrase,
|
||||||
dns,
|
dns,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
@@ -667,7 +684,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
|||||||
const { serverId } = req.params as { serverId: string }
|
const { serverId } = req.params as { serverId: string }
|
||||||
const parsed = ipsecCertExportByNameRequestSchema.safeParse(req.body ?? {})
|
const parsed = ipsecCertExportByNameRequestSchema.safeParse(req.body ?? {})
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
return badBodyReply(reply, parsed.error)
|
||||||
}
|
}
|
||||||
const { name, passphrase } = parsed.data
|
const { name, passphrase } = parsed.data
|
||||||
const server = await getEnabledIpsecServerById(serverIdParam(serverId))
|
const server = await getEnabledIpsecServerById(serverIdParam(serverId))
|
||||||
|
|||||||
@@ -112,12 +112,12 @@ export async function exportCertificateP12ByName(
|
|||||||
client: MikrotikClient,
|
client: MikrotikClient,
|
||||||
certName: string,
|
certName: string,
|
||||||
passphrase: string,
|
passphrase: string,
|
||||||
): Promise<{ fileName: string; content: Buffer; certName: string }> {
|
): Promise<{ fileName: string; content: Buffer; certName: string; passphrase: string }> {
|
||||||
const name = certName.trim()
|
const name = certName.trim()
|
||||||
const cert = await findCertificate(client, name)
|
const cert = await findCertificate(client, name)
|
||||||
if (!cert) throw new Error(`Сертификат ${name} не найден на роутере`)
|
if (!cert) throw new Error(`Сертификат ${name} не найден на роутере`)
|
||||||
const { fileName, content } = await client.exportCertificatePkcs12({ name, passphrase })
|
const { fileName, content, passphrase: effective } = await client.exportCertificatePkcs12({ name, passphrase })
|
||||||
return { fileName, content, certName: name }
|
return { fileName, content, certName: name, passphrase: effective }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Экспорт клиентского .p12 (сертификат + ключ; CA в цепочке) с роутера. */
|
/** Экспорт клиентского .p12 (сертификат + ключ; CA в цепочке) с роутера. */
|
||||||
@@ -125,6 +125,6 @@ export async function exportClientP12(
|
|||||||
client: MikrotikClient,
|
client: MikrotikClient,
|
||||||
userName: string,
|
userName: string,
|
||||||
passphrase: string,
|
passphrase: string,
|
||||||
): Promise<{ fileName: string; content: Buffer; certName: string }> {
|
): Promise<{ fileName: string; content: Buffer; certName: string; passphrase: string }> {
|
||||||
return exportCertificateP12ByName(client, clientCertName(userName), passphrase)
|
return exportCertificateP12ByName(client, clientCertName(userName), passphrase)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import http from "node:http"
|
import http from "node:http"
|
||||||
import https from "node:https"
|
import https from "node:https"
|
||||||
|
import { randomBytes } from "node:crypto"
|
||||||
import type { Server } from "../db/schema.js"
|
import type { Server } from "../db/schema.js"
|
||||||
import { parseRosDataSizeBytes } from "./ros-metric-parse.js"
|
import { parseRosDataSizeBytes } from "./ros-metric-parse.js"
|
||||||
import type {
|
import type {
|
||||||
@@ -267,22 +268,27 @@ function rosDelete(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** GET бинарного содержимого (файлы RouterOS): без utf8-декодирования, JSON-ответ = ошибка. */
|
/** Запрос к RouterOS с сырым (не обязательно JSON) ответом — для содержимого файлов. */
|
||||||
function rosDownload(
|
function rosRawRequest(
|
||||||
params: MikrotikConnectParams,
|
params: MikrotikConnectParams,
|
||||||
path: string,
|
opts: { method: "GET" | "POST"; path: string; body?: Record<string, string>; timeoutMs: number },
|
||||||
timeoutMs: number,
|
|
||||||
): Promise<Buffer> {
|
): Promise<Buffer> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const basePath = params.apiPath ?? "/rest"
|
const basePath = params.apiPath ?? "/rest"
|
||||||
const authHeader = "Basic " + Buffer.from(`${params.username}:${params.password}`).toString("base64")
|
const authHeader = "Basic " + Buffer.from(`${params.username}:${params.password}`).toString("base64")
|
||||||
|
const payload = opts.body ? JSON.stringify(opts.body) : undefined
|
||||||
|
|
||||||
const options: https.RequestOptions = {
|
const options: https.RequestOptions = {
|
||||||
hostname: params.host,
|
hostname: params.host,
|
||||||
port: params.port,
|
port: params.port,
|
||||||
path: basePath + path,
|
path: basePath + opts.path,
|
||||||
method: "GET",
|
method: opts.method,
|
||||||
headers: { Authorization: authHeader },
|
headers: {
|
||||||
|
Authorization: authHeader,
|
||||||
|
...(payload
|
||||||
|
? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
rejectUnauthorized: params.useSsl ? params.verifySsl : undefined,
|
rejectUnauthorized: params.useSsl ? params.verifySsl : undefined,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,12 +300,7 @@ function rosDownload(
|
|||||||
res.on("end", () => {
|
res.on("end", () => {
|
||||||
const buf = Buffer.concat(chunks)
|
const buf = Buffer.concat(chunks)
|
||||||
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
||||||
reject(new MikrotikError(res.statusCode ?? 0, path, buf.toString("utf8").slice(0, 200)))
|
reject(new MikrotikError(res.statusCode ?? 0, opts.path, buf.toString("utf8").slice(0, 200)))
|
||||||
return
|
|
||||||
}
|
|
||||||
const contentType = String(res.headers["content-type"] ?? "")
|
|
||||||
if (contentType.includes("application/json")) {
|
|
||||||
reject(new Error(`RouterOS вернул метаданные вместо содержимого файла ${path}`))
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
resolve(buf)
|
resolve(buf)
|
||||||
@@ -307,13 +308,14 @@ function rosDownload(
|
|||||||
})
|
})
|
||||||
|
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
req.destroy(new Error(`Connection to ${params.host}:${params.port} timed out after ${timeoutMs / 1000}s`))
|
req.destroy(new Error(`Connection to ${params.host}:${params.port} timed out after ${opts.timeoutMs / 1000}s`))
|
||||||
}, timeoutMs)
|
}, opts.timeoutMs)
|
||||||
req.on("close", () => clearTimeout(timer))
|
req.on("close", () => clearTimeout(timer))
|
||||||
req.on("error", (err) => {
|
req.on("error", (err) => {
|
||||||
clearTimeout(timer)
|
clearTimeout(timer)
|
||||||
reject(err)
|
reject(err)
|
||||||
})
|
})
|
||||||
|
if (payload) req.write(payload)
|
||||||
req.end()
|
req.end()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -400,6 +402,74 @@ function matchesUploadedFile(entryName: string, requested: string): boolean {
|
|||||||
|| entryName.endsWith(`/${base}`)
|
|| entryName.endsWith(`/${base}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Лимит команды `/file/get`: RouterOS отдаёт содержимое файлов не больше 60 KB. */
|
||||||
|
const MAX_FILE_GET_BYTES = 60 * 1024
|
||||||
|
|
||||||
|
const CONTENTS_MARKER = Buffer.from('"contents":', "latin1")
|
||||||
|
|
||||||
|
function assertRosFileReadable(entry: { name: string; size: number }): void {
|
||||||
|
if (entry.size > MAX_FILE_GET_BYTES) {
|
||||||
|
throw new Error(
|
||||||
|
`Файл ${routerFileBasename(entry.name)} больше ${MAX_FILE_GET_BYTES / 1024} КБ — `
|
||||||
|
+ "RouterOS REST отдаёт содержимое только до 60 КБ (используйте SCP/FTP)",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RouterOS REST отдаёт содержимое файла в JSON-подобной обёртке, но строку — в single-byte
|
||||||
|
* кодировке и экранирует лишь часть символов, из-за чего `JSON.parse` падает
|
||||||
|
* (см. https://forum.mikrotik.com/t/bug-rest-endpoint-producing-invalid-json/177486).
|
||||||
|
* Поле `contents` извлекаем напрямую из сырых байтов, без парсинга всего ответа.
|
||||||
|
* @see https://help.mikrotik.com/docs/spaces/ROS/pages/2555971/Files
|
||||||
|
*/
|
||||||
|
export function extractRosContentsField(raw: Buffer): Buffer {
|
||||||
|
const marker = raw.indexOf(CONTENTS_MARKER)
|
||||||
|
if (marker < 0) throw new Error("RouterOS: ответ не содержит поле contents")
|
||||||
|
|
||||||
|
let i = marker + CONTENTS_MARKER.length
|
||||||
|
while (i < raw.length && isRosJsonSpace(raw[i])) i += 1
|
||||||
|
if (raw[i] !== 0x22) throw new Error("RouterOS: поле contents не является строкой")
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
const out: number[] = []
|
||||||
|
while (i < raw.length) {
|
||||||
|
const byte = raw[i]
|
||||||
|
if (byte === 0x22) return Buffer.from(out) // закрывающая кавычка
|
||||||
|
if (byte !== 0x5c) { // обычный байт
|
||||||
|
out.push(byte)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const esc = raw[i + 1]
|
||||||
|
if (esc === undefined) break
|
||||||
|
i += 2
|
||||||
|
switch (esc) {
|
||||||
|
case 0x22: out.push(0x22); break // \"
|
||||||
|
case 0x5c: out.push(0x5c); break // \\
|
||||||
|
case 0x2f: out.push(0x2f); break // \/
|
||||||
|
case 0x62: out.push(0x08); break // \b
|
||||||
|
case 0x66: out.push(0x0c); break // \f
|
||||||
|
case 0x6e: out.push(0x0a); break // \n
|
||||||
|
case 0x72: out.push(0x0d); break // \r
|
||||||
|
case 0x74: out.push(0x09); break // \t
|
||||||
|
case 0x75: { // \uXXXX
|
||||||
|
const hex = raw.subarray(i, i + 4).toString("latin1")
|
||||||
|
if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw new Error("RouterOS: некорректный \\u-escape в contents")
|
||||||
|
i += 4
|
||||||
|
for (const b of Buffer.from(String.fromCharCode(parseInt(hex, 16)), "utf8")) out.push(b)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
default: out.push(esc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error("RouterOS: строка contents не закрыта")
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRosJsonSpace(byte: number): boolean {
|
||||||
|
return byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d
|
||||||
|
}
|
||||||
|
|
||||||
export function firewallRestPath(
|
export function firewallRestPath(
|
||||||
family: FirewallFamily,
|
family: FirewallFamily,
|
||||||
table: FirewallTable | "address-list",
|
table: FirewallTable | "address-list",
|
||||||
@@ -422,6 +492,31 @@ function unknownParameterName(error: MikrotikError): string | undefined {
|
|||||||
return match?.[1]
|
return match?.[1]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RouterOS отклоняет `export-passphrase` короче 8 символов:
|
||||||
|
* `Failure: If used, passphrase must be at least 8 chars long!`.
|
||||||
|
* Та же ошибка приходит, если политика `sensitive` не даёт применить sensitive-параметр.
|
||||||
|
*/
|
||||||
|
export function isPassphraseTooShortError(error: unknown): boolean {
|
||||||
|
return (
|
||||||
|
error instanceof MikrotikError &&
|
||||||
|
error.statusCode === 400 &&
|
||||||
|
/passphrase/i.test(error.body) &&
|
||||||
|
/at least\s*8/i.test(error.body)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Пароль .p12, который RouterOS примет гарантированно (≥8 символов). */
|
||||||
|
function generateExportPassphrase(): string {
|
||||||
|
return randomBytes(12).toString("base64url")
|
||||||
|
}
|
||||||
|
|
||||||
|
const EXPORT_PASSPHRASE_HINT =
|
||||||
|
"RouterOS отклонил пароль .p12. Экспорт приватного ключа (export-passphrase — sensitive-параметр) " +
|
||||||
|
"разрешён только пользователю, у которого в политике группы есть «sensitive». " +
|
||||||
|
"Проверьте: /user print → группа API-пользователя → /user group print; добавьте sensitive в policy группы " +
|
||||||
|
"(в группе full она уже есть)."
|
||||||
|
|
||||||
export class MikrotikClient {
|
export class MikrotikClient {
|
||||||
constructor(private readonly params: MikrotikConnectParams) {}
|
constructor(private readonly params: MikrotikConnectParams) {}
|
||||||
|
|
||||||
@@ -599,13 +694,27 @@ export class MikrotikClient {
|
|||||||
return raw.filter((row): row is Record<string, string | undefined> => row != null && typeof row === "object")
|
return raw.filter((row): row is Record<string, string | undefined> => row != null && typeof row === "object")
|
||||||
}
|
}
|
||||||
|
|
||||||
async listFiles(): Promise<Array<{ name: string }>> {
|
async listFiles(): Promise<Array<{ id: string; name: string; size: number }>> {
|
||||||
const raw = await this.get<unknown>("/file")
|
const raw = await this.get<unknown>("/file")
|
||||||
if (!Array.isArray(raw)) return []
|
if (!Array.isArray(raw)) return []
|
||||||
return raw
|
return raw
|
||||||
.filter((row): row is Record<string, unknown> => row != null && typeof row === "object")
|
.filter((row): row is Record<string, unknown> => row != null && typeof row === "object")
|
||||||
.map((row) => ({ name: String(row.name ?? "") }))
|
.map((row) => ({
|
||||||
.filter((row) => row.name.length > 0)
|
id: String(row[".id"] ?? ""),
|
||||||
|
name: String(row.name ?? ""),
|
||||||
|
size: Number(row.size ?? 0),
|
||||||
|
}))
|
||||||
|
.filter((row) => row.name.length > 0 && row.id.length > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Поиск файла в `/file` по полному имени, базовому имени или `flash/<base>`. */
|
||||||
|
private async findFileEntry(name: string): Promise<{ id: string; name: string; size: number } | undefined> {
|
||||||
|
const base = routerFileBasename(name)
|
||||||
|
const files = await this.listFiles()
|
||||||
|
return files.find((file) => file.name === name)
|
||||||
|
?? files.find((file) => file.name === base)
|
||||||
|
?? files.find((file) => file.name === `flash/${base}`)
|
||||||
|
?? files.find((file) => routerFileBasename(file.name) === base)
|
||||||
}
|
}
|
||||||
|
|
||||||
private async resolveUploadedFileName(requested: string): Promise<string> {
|
private async resolveUploadedFileName(requested: string): Promise<string> {
|
||||||
@@ -679,38 +788,76 @@ export class MikrotikClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Скачивание содержимого файла RouterOS (GET /rest/file/<name>, бинарно). */
|
/**
|
||||||
async downloadFile(fileName: string, timeoutMs = 30_000): Promise<Buffer> {
|
* Чтение содержимого файла RouterOS командой `/file/get` (REST: POST).
|
||||||
const normalized = routerFileBasename(fileName)
|
* Путь `GET /file/<name>` не существует — RouterOS отвечает `no such command prefix`.
|
||||||
const candidates = [normalized, `flash/${normalized}`]
|
* @see https://help.mikrotik.com/docs/spaces/ROS/pages/2555971/Files
|
||||||
let lastError: unknown
|
*/
|
||||||
for (const name of candidates) {
|
private async readFileContents(
|
||||||
try {
|
target: { id?: string; name?: string },
|
||||||
return await rosDownload(this.params, `/file/${encodeURIComponent(name)}`, timeoutMs)
|
timeoutMs = 30_000,
|
||||||
} catch (error) {
|
): Promise<Buffer> {
|
||||||
lastError = error
|
const body: Record<string, string> = { ".proplist": "contents" }
|
||||||
}
|
if (target.id) body[".id"] = target.id
|
||||||
}
|
else if (target.name) body.name = target.name
|
||||||
throw lastError instanceof Error
|
else throw new Error("RouterOS: не задан файл для чтения")
|
||||||
? lastError
|
const raw = await rosRawRequest(this.params, {
|
||||||
: new Error(`Не удалось скачать файл ${normalized} с RouterOS`)
|
method: "POST",
|
||||||
|
path: "/file/get",
|
||||||
|
body,
|
||||||
|
timeoutMs,
|
||||||
|
})
|
||||||
|
return extractRosContentsField(raw)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Создание ключевой пары + заявки: /certificate add (поля common-name, key-size, key-usage…). */
|
/** Скачивание содержимого файла RouterOS: `/file/get` + побайтовый разбор (лимит 60 КБ). */
|
||||||
async addCertificate(body: Record<string, string>, timeoutMs = 30_000): Promise<unknown> {
|
async downloadFile(
|
||||||
// Набор параметров `/certificate/add` зависит от версии RouterOS (напр. `comment`).
|
target: { name: string; id?: string; size?: number },
|
||||||
// Деградируем: при 400 «unknown parameter X» убираем X из тела и повторяем.
|
timeoutMs = 30_000,
|
||||||
|
): Promise<Buffer> {
|
||||||
|
let entry = target.id
|
||||||
|
? { id: target.id, name: target.name, size: target.size ?? 0 }
|
||||||
|
: await this.findFileEntry(target.name)
|
||||||
|
if (!entry) throw new Error(`Файл ${routerFileBasename(target.name)} не найден на RouterOS`)
|
||||||
|
assertRosFileReadable(entry)
|
||||||
|
return this.readFileContents({ id: entry.id, name: entry.name }, timeoutMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Удаление файла RouterOS по `.id` или имени (для временных артефактов экспорта). */
|
||||||
|
async removeFile(idOrName: string, timeoutMs = 10_000): Promise<void> {
|
||||||
|
const id = idOrName.startsWith("*")
|
||||||
|
? idOrName
|
||||||
|
: (await this.findFileEntry(idOrName))?.id
|
||||||
|
if (!id) return
|
||||||
|
await this.delete(`/file/${encodeURIComponent(id)}`, timeoutMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST с деградацией по несовместимым параметрам: набор полей `/certificate/*` зависит от версии
|
||||||
|
* RouterOS (напр. `comment`, `days-valid`). При 400 «unknown parameter X» убираем X и повторяем.
|
||||||
|
*/
|
||||||
|
private async postTolerant(
|
||||||
|
path: string,
|
||||||
|
body: Record<string, string>,
|
||||||
|
timeoutMs: number,
|
||||||
|
maxAttempts = 4,
|
||||||
|
): Promise<unknown> {
|
||||||
const payload: Record<string, string> = { ...body }
|
const payload: Record<string, string> = { ...body }
|
||||||
for (let attempt = 0; attempt < 4; attempt += 1) {
|
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
||||||
try {
|
try {
|
||||||
return await this.post("/certificate/add", payload, timeoutMs)
|
return await this.post(path, payload, timeoutMs)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const param = error instanceof MikrotikError ? unknownParameterName(error) : undefined
|
const param = error instanceof MikrotikError ? unknownParameterName(error) : undefined
|
||||||
if (!param || !(param in payload)) throw error
|
if (!param || !(param in payload)) throw error
|
||||||
delete payload[param]
|
delete payload[param]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw new Error(`RouterOS: не удалось добавить сертификат (несовместимые параметры): ${Object.keys(body).join(", ")}`)
|
throw new Error(`RouterOS: не удалось выполнить ${path} (несовместимые параметры): ${Object.keys(body).join(", ")}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Создание ключевой пары + заявки: /certificate add (поля common-name, key-size, key-usage…). */
|
||||||
|
async addCertificate(body: Record<string, string>, timeoutMs = 30_000): Promise<unknown> {
|
||||||
|
return this.postTolerant("/certificate/add", body, timeoutMs)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Подпись сертификата локальным CA; sign небыстрый — увеличенный таймаут. */
|
/** Подпись сертификата локальным CA; sign небыстрый — увеличенный таймаут. */
|
||||||
@@ -723,33 +870,33 @@ export class MikrotikClient {
|
|||||||
if (params.ca) body.ca = params.ca
|
if (params.ca) body.ca = params.ca
|
||||||
if (params.daysValid != null) body["days-valid"] = String(params.daysValid)
|
if (params.daysValid != null) body["days-valid"] = String(params.daysValid)
|
||||||
try {
|
try {
|
||||||
return await this.post("/certificate/sign", body, timeoutMs)
|
return await this.postTolerant("/certificate/sign", body, timeoutMs)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// Некоторые версии REST принимают цель подписи только как .id.
|
// Некоторые версии REST принимают цель подписи только как .id.
|
||||||
const certs = await this.getCertificates()
|
const certs = await this.getCertificates()
|
||||||
const row = certs.find((c) => String(c.name ?? "") === params.name)
|
const row = certs.find((c) => String(c.name ?? "") === params.name)
|
||||||
const id = row?.[".id"]
|
const id = row?.[".id"]
|
||||||
if (!id) throw e
|
if (!id) throw e
|
||||||
return await this.post("/certificate/sign", { ".id": id, ...body }, timeoutMs)
|
return await this.postTolerant("/certificate/sign", { ".id": id, ...body }, timeoutMs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Экспорт сертификата в файл на роутере (pkcs12/pem); возвращает имя созданного файла. */
|
/** Экспорт сертификата в файл на роутере (pkcs12/pem); возвращает созданный файл. */
|
||||||
async exportCertificate(params: {
|
async exportCertificate(params: {
|
||||||
name: string
|
name: string
|
||||||
type: "pkcs12" | "pem"
|
type: "pkcs12" | "pem"
|
||||||
passphrase?: string
|
passphrase?: string
|
||||||
}, timeoutMs = 60_000): Promise<string> {
|
}, timeoutMs = 60_000): Promise<{ fileName: string; fileId: string; size: number }> {
|
||||||
const body: Record<string, string> = { name: params.name, type: params.type }
|
const body: Record<string, string> = { name: params.name, type: params.type }
|
||||||
if (params.passphrase?.trim()) body["export-passphrase"] = params.passphrase.trim()
|
if (params.passphrase?.trim()) body["export-passphrase"] = params.passphrase.trim()
|
||||||
let raw: unknown
|
let raw: unknown
|
||||||
try {
|
try {
|
||||||
raw = await this.post("/certificate/export-certificate", body, timeoutMs)
|
raw = await this.postTolerant("/certificate/export-certificate", body, timeoutMs)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const certs = await this.getCertificates()
|
const certs = await this.getCertificates()
|
||||||
const id = certs.find((c) => String(c.name ?? "") === params.name)?.[".id"]
|
const id = certs.find((c) => String(c.name ?? "") === params.name)?.[".id"]
|
||||||
if (!id) throw e
|
if (!id) throw e
|
||||||
raw = await this.post("/certificate/export-certificate", { ".id": id, ...body }, timeoutMs)
|
raw = await this.postTolerant("/certificate/export-certificate", { ".id": id, ...body }, timeoutMs)
|
||||||
}
|
}
|
||||||
void raw
|
void raw
|
||||||
// RouterOS создаёт cert_export_<name>.p12 либо <name>.p12 — ищем по списку файлов.
|
// RouterOS создаёт cert_export_<name>.p12 либо <name>.p12 — ищем по списку файлов.
|
||||||
@@ -759,14 +906,35 @@ export class MikrotikClient {
|
|||||||
const hit = files.find((f) => wanted.includes(f.name))
|
const hit = files.find((f) => wanted.includes(f.name))
|
||||||
?? files.find((f) => f.name.endsWith(`.${ext}`) && f.name.includes(params.name))
|
?? files.find((f) => f.name.endsWith(`.${ext}`) && f.name.includes(params.name))
|
||||||
if (!hit) throw new Error(`Файл экспорта ${params.name}.${ext} не найден на RouterOS`)
|
if (!hit) throw new Error(`Файл экспорта ${params.name}.${ext} не найден на RouterOS`)
|
||||||
return hit.name
|
return { fileName: hit.name, fileId: hit.id, size: hit.size }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Скачивание .p12 (сертификат + ключ + цепочка) как бинарный Buffer. */
|
/** Скачивание .p12 (сертификат + ключ + цепочка) как бинарный Buffer. */
|
||||||
async exportCertificatePkcs12(params: { name: string; passphrase?: string }): Promise<{ fileName: string; content: Buffer }> {
|
async exportCertificatePkcs12(params: { name: string; passphrase?: string }): Promise<{ fileName: string; content: Buffer; passphrase: string }> {
|
||||||
const fileName = await this.exportCertificate({ name: params.name, type: "pkcs12", passphrase: params.passphrase })
|
let passphrase = params.passphrase?.trim() || generateExportPassphrase()
|
||||||
const content = await this.downloadFile(fileName)
|
let exported: { fileName: string; fileId: string; size: number }
|
||||||
return { fileName, content }
|
try {
|
||||||
|
exported = await this.exportCertificate({ name: params.name, type: "pkcs12", passphrase })
|
||||||
|
} catch (error) {
|
||||||
|
if (!isPassphraseTooShortError(error)) throw error
|
||||||
|
// RouterOS мог отклонить пароль пользователя — повторяем со сгенерированным и отдаём его в бандл.
|
||||||
|
const forced = generateExportPassphrase()
|
||||||
|
try {
|
||||||
|
exported = await this.exportCertificate({ name: params.name, type: "pkcs12", passphrase: forced })
|
||||||
|
passphrase = forced
|
||||||
|
} catch (retryError) {
|
||||||
|
if (isPassphraseTooShortError(retryError)) throw new Error(EXPORT_PASSPHRASE_HINT)
|
||||||
|
throw retryError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const content = await this.downloadFile({
|
||||||
|
name: exported.fileName,
|
||||||
|
id: exported.fileId,
|
||||||
|
size: exported.size,
|
||||||
|
})
|
||||||
|
// Временный файл экспорта на роутере больше не нужен (best-effort, не влияет на результат).
|
||||||
|
await this.removeFile(exported.fileId).catch(() => undefined)
|
||||||
|
return { fileName: exported.fileName, content, passphrase }
|
||||||
}
|
}
|
||||||
|
|
||||||
async removeCertificate(nameOrId: string, timeoutMs = 30_000): Promise<void> {
|
async removeCertificate(nameOrId: string, timeoutMs = 30_000): Promise<void> {
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import assert from "node:assert/strict"
|
||||||
|
import { extractRosContentsField } from "./mikrotik.js"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Собирает ответ RouterOS на `/file/get` (.proplist=contents) в том виде, в каком его
|
||||||
|
* отдаёт устройство: single-byte строка, экранируются только кавычка и обратный слэш.
|
||||||
|
*/
|
||||||
|
function rosFileGetResponse(contents: Buffer): Buffer {
|
||||||
|
const escaped: number[] = []
|
||||||
|
for (const byte of contents) {
|
||||||
|
if (byte === 0x22 || byte === 0x5c) escaped.push(0x5c, byte)
|
||||||
|
else escaped.push(byte)
|
||||||
|
}
|
||||||
|
return Buffer.concat([
|
||||||
|
Buffer.from('[{".id":"*A","contents":"', "latin1"),
|
||||||
|
Buffer.from(escaped),
|
||||||
|
Buffer.from('"}]', "latin1"),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// ASCII-содержимое
|
||||||
|
const content = Buffer.from("hello p12", "latin1")
|
||||||
|
assert.deepEqual(extractRosContentsField(rosFileGetResponse(content)), content)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// Экранированные кавычки и обратный слэш
|
||||||
|
const content = Buffer.from('a"b\\c"d', "latin1")
|
||||||
|
assert.deepEqual(extractRosContentsField(rosFileGetResponse(content)), content)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// Пустой файл
|
||||||
|
assert.equal(extractRosContentsField(rosFileGetResponse(Buffer.alloc(0))).length, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// Управляющие escape-последовательности
|
||||||
|
const raw = Buffer.from('{"contents":"a\\nb\\tc\\u0041"}', "latin1")
|
||||||
|
assert.deepEqual(extractRosContentsField(raw), Buffer.from("a\nb\tcA", "latin1"))
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// contents не первый ключ в объекте
|
||||||
|
const raw = Buffer.from('{".id":"*B","name":"x.p12","contents":"DATA"}', "latin1")
|
||||||
|
assert.deepEqual(extractRosContentsField(raw), Buffer.from("DATA", "latin1"))
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// Все 256 байт: single-byte кодировка не должна терять значения 0x80–0xFF и NUL
|
||||||
|
const content = Buffer.from(Array.from({ length: 256 }, (_, i) => i))
|
||||||
|
const decoded = extractRosContentsField(rosFileGetResponse(content))
|
||||||
|
assert.equal(decoded.length, 256)
|
||||||
|
assert.deepEqual(decoded, content)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// Нет поля contents — понятная ошибка
|
||||||
|
assert.throws(
|
||||||
|
() => extractRosContentsField(Buffer.from('{".id":"*A"}', "latin1")),
|
||||||
|
/не содержит поле contents/,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("ros-file-contents.test.ts: ok")
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from "react"
|
import { useEffect, useMemo, useState } from "react"
|
||||||
import type { IpsecCertBundle } from "@mmapp/contracts/ipsec"
|
import { IPSEC_MIN_PASSPHRASE, type IpsecCertBundle } from "@mmapp/contracts/ipsec"
|
||||||
import { FormField, SectionTitle } from "@/components/form-kit"
|
import { FormField, SectionTitle } from "@/components/form-kit"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input"
|
||||||
@@ -33,7 +33,8 @@ function downloadB64(filename: string, b64: string, mime: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function randomPassphrase(): string {
|
function randomPassphrase(): string {
|
||||||
const bytes = new Uint8Array(9)
|
// RouterOS требует ≥ IPSEC_MIN_PASSPHRASE символов
|
||||||
|
const bytes = new Uint8Array(IPSEC_MIN_PASSPHRASE + 1)
|
||||||
crypto.getRandomValues(bytes)
|
crypto.getRandomValues(bytes)
|
||||||
let s = ""
|
let s = ""
|
||||||
for (const b of bytes) s += "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"[b % 56]
|
for (const b of bytes) s += "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"[b % 56]
|
||||||
@@ -62,7 +63,10 @@ function IpsecCertSheet({
|
|||||||
queueMicrotask(() => setPassphrase(initial))
|
queueMicrotask(() => setPassphrase(initial))
|
||||||
}, [open, bundle])
|
}, [open, bundle])
|
||||||
|
|
||||||
const canDownload = useMemo(() => Boolean(bundle && passphrase.trim().length >= 4), [bundle, passphrase])
|
const canDownload = useMemo(
|
||||||
|
() => Boolean(bundle && passphrase.trim().length >= IPSEC_MIN_PASSPHRASE),
|
||||||
|
[bundle, passphrase],
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||||
@@ -83,7 +87,15 @@ function IpsecCertSheet({
|
|||||||
<>
|
<>
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
<SectionTitle>Пароль архива .p12</SectionTitle>
|
<SectionTitle>Пароль архива .p12</SectionTitle>
|
||||||
<FormField label="Passphrase" required hint="Нужна при импорте .p12 на устройстве">
|
<FormField
|
||||||
|
label="Passphrase"
|
||||||
|
required
|
||||||
|
hint={
|
||||||
|
passphrase.trim().length > 0 && passphrase.trim().length < IPSEC_MIN_PASSPHRASE
|
||||||
|
? `Минимум ${IPSEC_MIN_PASSPHRASE} символов — требование RouterOS`
|
||||||
|
: `Нужна при импорте .p12 на устройстве (минимум ${IPSEC_MIN_PASSPHRASE} символов)`
|
||||||
|
}
|
||||||
|
>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Input
|
<Input
|
||||||
className="font-mono"
|
className="font-mono"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from "react"
|
import { useEffect, useMemo, useState } from "react"
|
||||||
import type { IpsecClientDto } from "@mmapp/contracts/ipsec"
|
import { IPSEC_MIN_PASSPHRASE, type IpsecClientDto } from "@mmapp/contracts/ipsec"
|
||||||
import { FormField, FormToggle, SectionTitle } from "@/components/form-kit"
|
import { FormField, FormToggle, SectionTitle } from "@/components/form-kit"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input"
|
||||||
@@ -91,6 +91,9 @@ function IpsecUserSheet({
|
|||||||
if (!form.name.trim()) return false
|
if (!form.name.trim()) return false
|
||||||
if (!editing && form.authMethod === "pre-shared-key" && form.psk.trim().length < 8) return false
|
if (!editing && form.authMethod === "pre-shared-key" && form.psk.trim().length < 8) return false
|
||||||
if (form.useStaticIp && form.staticIp.trim() && !/^\d{1,3}(?:\.\d{1,3}){3}$/.test(form.staticIp.trim())) return false
|
if (form.useStaticIp && form.staticIp.trim() && !/^\d{1,3}(?:\.\d{1,3}){3}$/.test(form.staticIp.trim())) return false
|
||||||
|
// RouterOS отклоняет export-passphrase короче 8 символов
|
||||||
|
const passphrase = form.passphrase.trim()
|
||||||
|
if (!editing && passphrase.length > 0 && passphrase.length < IPSEC_MIN_PASSPHRASE) return false
|
||||||
return true
|
return true
|
||||||
}, [form, editing])
|
}, [form, editing])
|
||||||
|
|
||||||
@@ -201,7 +204,14 @@ function IpsecUserSheet({
|
|||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
!editing ? (
|
!editing ? (
|
||||||
<FormField label="Пароль архива .p12" hint="Пусто — сгенерируем автоматически">
|
<FormField
|
||||||
|
label="Пароль архива .p12"
|
||||||
|
hint={
|
||||||
|
form.passphrase.trim().length > 0 && form.passphrase.trim().length < IPSEC_MIN_PASSPHRASE
|
||||||
|
? `Минимум ${IPSEC_MIN_PASSPHRASE} символов — требование RouterOS`
|
||||||
|
: `Пусто — сгенерируем автоматически (минимум ${IPSEC_MIN_PASSPHRASE} символов)`
|
||||||
|
}
|
||||||
|
>
|
||||||
<Input
|
<Input
|
||||||
className="font-mono"
|
className="font-mono"
|
||||||
placeholder="например MySecret123"
|
placeholder="например MySecret123"
|
||||||
|
|||||||
@@ -2,6 +2,12 @@ import { z } from "zod"
|
|||||||
|
|
||||||
export const ipsecAuthMethodSchema = z.enum(["certificate", "pre-shared-key"])
|
export const ipsecAuthMethodSchema = z.enum(["certificate", "pre-shared-key"])
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Минимальная длина пароля .p12. Ограничение RouterOS REST:
|
||||||
|
* `Failure: If used, passphrase must be at least 8 chars long!` (см. /certificate/export-certificate).
|
||||||
|
*/
|
||||||
|
export const IPSEC_MIN_PASSPHRASE = 8
|
||||||
|
|
||||||
/** Клиент IKEv2 — /ip/ipsec/identity (+ опциональный персональный mode-config). */
|
/** Клиент IKEv2 — /ip/ipsec/identity (+ опциональный персональный mode-config). */
|
||||||
export const ipsecClientDtoSchema = z.object({
|
export const ipsecClientDtoSchema = z.object({
|
||||||
id: z.string().min(1),
|
id: z.string().min(1),
|
||||||
@@ -166,8 +172,8 @@ export const ipsecUserCreateRequestSchema = z.object({
|
|||||||
remoteId: z.string().optional(),
|
remoteId: z.string().optional(),
|
||||||
/** Конкретный IP клиента; без — выдаётся из пула. */
|
/** Конкретный IP клиента; без — выдаётся из пула. */
|
||||||
staticIp: z.string().optional(),
|
staticIp: z.string().optional(),
|
||||||
/** Пароль на экспортируемый .p12. */
|
/** Пароль на экспортируемый .p12 (RouterOS требует ≥ IPSEC_MIN_PASSPHRASE). */
|
||||||
passphrase: z.string().min(4).optional(),
|
passphrase: z.string().min(IPSEC_MIN_PASSPHRASE).optional(),
|
||||||
daysValid: z.number().int().positive().optional(),
|
daysValid: z.number().int().positive().optional(),
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -183,13 +189,13 @@ export const ipsecUserPatchSchema = z.object({
|
|||||||
export const ipsecCertExportRequestSchema = z.object({
|
export const ipsecCertExportRequestSchema = z.object({
|
||||||
serverId: z.union([z.string(), z.number()]),
|
serverId: z.union([z.string(), z.number()]),
|
||||||
clientId: z.string().min(1),
|
clientId: z.string().min(1),
|
||||||
passphrase: z.string().min(4),
|
passphrase: z.string().min(IPSEC_MIN_PASSPHRASE),
|
||||||
})
|
})
|
||||||
|
|
||||||
/** Экспорт .p12 существующего клиентского сертификата по имени (client1/anakondra и т.п.). */
|
/** Экспорт .p12 существующего клиентского сертификата по имени (client1/anakondra и т.п.). */
|
||||||
export const ipsecCertExportByNameRequestSchema = z.object({
|
export const ipsecCertExportByNameRequestSchema = z.object({
|
||||||
name: z.string().min(1),
|
name: z.string().min(1),
|
||||||
passphrase: z.string().min(4),
|
passphrase: z.string().min(IPSEC_MIN_PASSPHRASE),
|
||||||
})
|
})
|
||||||
|
|
||||||
/** Бандл для авторизации клиента: .p12 (+ strongSwan .sswan + инструкция). */
|
/** Бандл для авторизации клиента: .p12 (+ strongSwan .sswan + инструкция). */
|
||||||
|
|||||||
Reference in New Issue
Block a user