Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67c3a4fd73 | ||
|
|
9beb24273b | ||
|
|
5cc6128086 | ||
|
|
569b6be2b4 | ||
|
|
752256f12e |
@@ -20,9 +20,10 @@
|
||||
"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: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: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"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
||||
import type { FastifyReply } from "fastify"
|
||||
import {
|
||||
IPSEC_MIN_PASSPHRASE,
|
||||
ipsecCertDeleteRequestSchema,
|
||||
ipsecCertExportByNameRequestSchema,
|
||||
ipsecCertExportRequestSchema,
|
||||
@@ -97,6 +98,22 @@ function errReply(reply: FastifyReply, e: unknown) {
|
||||
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(
|
||||
server: NonNullable<Awaited<ReturnType<typeof getEnabledIpsecServerById>>>,
|
||||
source: ConfigRevisionSource,
|
||||
@@ -122,7 +139,7 @@ async function buildCertBundle(
|
||||
args: { userName: string; certName?: string; serverEndpoint: string; passphrase: string; dns?: string },
|
||||
): Promise<IpsecCertBundle> {
|
||||
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")
|
||||
return {
|
||||
user: args.userName,
|
||||
@@ -130,7 +147,7 @@ async function buildCertBundle(
|
||||
filename: fileName,
|
||||
contentB64: p12B64,
|
||||
mime: "application/x-pkcs12",
|
||||
passphrase: args.passphrase,
|
||||
passphrase,
|
||||
sswanFilename: `${certName}.sswan`,
|
||||
sswanContent: buildSswanConfig({
|
||||
name: `IKEv2 ${args.serverEndpoint}`,
|
||||
@@ -142,7 +159,7 @@ async function buildCertBundle(
|
||||
userName: args.userName,
|
||||
serverEndpoint: args.serverEndpoint,
|
||||
p12Filename: fileName,
|
||||
passphrase: args.passphrase,
|
||||
passphrase,
|
||||
dns: args.dns,
|
||||
}),
|
||||
}
|
||||
@@ -243,7 +260,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
app.post("/ipsec/users", async (req, reply) => {
|
||||
const parsed = ipsecUserCreateRequestSchema.safeParse(req.body ?? {})
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
||||
return badBodyReply(reply, parsed.error)
|
||||
}
|
||||
const body = parsed.data
|
||||
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 parsed = ipsecCertExportRequestSchema.safeParse({ ...(req.body as object), serverId, clientId: rosId })
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
||||
return badBodyReply(reply, parsed.error)
|
||||
}
|
||||
const body = parsed.data
|
||||
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 dns = sharedMc?.["static-dns"]?.trim() || undefined
|
||||
// export работает по имени сертификата (certName), не по userName
|
||||
const { fileName, content } = await client.exportCertificatePkcs12({
|
||||
const { fileName, content, passphrase } = await client.exportCertificatePkcs12({
|
||||
name: certName,
|
||||
passphrase: body.passphrase,
|
||||
})
|
||||
@@ -640,7 +657,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
filename: fileName,
|
||||
contentB64: p12B64,
|
||||
mime: "application/x-pkcs12",
|
||||
passphrase: body.passphrase,
|
||||
passphrase,
|
||||
sswanFilename: `${certName}.sswan`,
|
||||
sswanContent: buildSswanConfig({
|
||||
name: `IKEv2 ${serverEndpoint}`,
|
||||
@@ -652,7 +669,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
userName,
|
||||
serverEndpoint,
|
||||
p12Filename: fileName,
|
||||
passphrase: body.passphrase,
|
||||
passphrase,
|
||||
dns,
|
||||
}),
|
||||
}
|
||||
@@ -667,7 +684,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const { serverId } = req.params as { serverId: string }
|
||||
const parsed = ipsecCertExportByNameRequestSchema.safeParse(req.body ?? {})
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
||||
return badBodyReply(reply, parsed.error)
|
||||
}
|
||||
const { name, passphrase } = parsed.data
|
||||
const server = await getEnabledIpsecServerById(serverIdParam(serverId))
|
||||
|
||||
@@ -112,12 +112,12 @@ export async function exportCertificateP12ByName(
|
||||
client: MikrotikClient,
|
||||
certName: string,
|
||||
passphrase: string,
|
||||
): Promise<{ fileName: string; content: Buffer; certName: string }> {
|
||||
): Promise<{ fileName: string; content: Buffer; certName: string; passphrase: string }> {
|
||||
const name = certName.trim()
|
||||
const cert = await findCertificate(client, name)
|
||||
if (!cert) throw new Error(`Сертификат ${name} не найден на роутере`)
|
||||
const { fileName, content } = await client.exportCertificatePkcs12({ name, passphrase })
|
||||
return { fileName, content, certName: name }
|
||||
const { fileName, content, passphrase: effective } = await client.exportCertificatePkcs12({ name, passphrase })
|
||||
return { fileName, content, certName: name, passphrase: effective }
|
||||
}
|
||||
|
||||
/** Экспорт клиентского .p12 (сертификат + ключ; CA в цепочке) с роутера. */
|
||||
@@ -125,6 +125,6 @@ export async function exportClientP12(
|
||||
client: MikrotikClient,
|
||||
userName: 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)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import http from "node:http"
|
||||
import https from "node:https"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import type { Server } from "../db/schema.js"
|
||||
import { parseRosDataSizeBytes } from "./ros-metric-parse.js"
|
||||
import type {
|
||||
@@ -267,22 +268,27 @@ function rosDelete(
|
||||
})
|
||||
}
|
||||
|
||||
/** GET бинарного содержимого (файлы RouterOS): без utf8-декодирования, JSON-ответ = ошибка. */
|
||||
function rosDownload(
|
||||
/** Запрос к RouterOS с сырым (не обязательно JSON) ответом — для содержимого файлов. */
|
||||
function rosRawRequest(
|
||||
params: MikrotikConnectParams,
|
||||
path: string,
|
||||
timeoutMs: number,
|
||||
opts: { method: "GET" | "POST"; path: string; body?: Record<string, string>; timeoutMs: number },
|
||||
): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const basePath = params.apiPath ?? "/rest"
|
||||
const authHeader = "Basic " + Buffer.from(`${params.username}:${params.password}`).toString("base64")
|
||||
const payload = opts.body ? JSON.stringify(opts.body) : undefined
|
||||
|
||||
const options: https.RequestOptions = {
|
||||
hostname: params.host,
|
||||
port: params.port,
|
||||
path: basePath + path,
|
||||
method: "GET",
|
||||
headers: { Authorization: authHeader },
|
||||
path: basePath + opts.path,
|
||||
method: opts.method,
|
||||
headers: {
|
||||
Authorization: authHeader,
|
||||
...(payload
|
||||
? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) }
|
||||
: {}),
|
||||
},
|
||||
rejectUnauthorized: params.useSsl ? params.verifySsl : undefined,
|
||||
}
|
||||
|
||||
@@ -294,12 +300,7 @@ function rosDownload(
|
||||
res.on("end", () => {
|
||||
const buf = Buffer.concat(chunks)
|
||||
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
||||
reject(new MikrotikError(res.statusCode ?? 0, 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}`))
|
||||
reject(new MikrotikError(res.statusCode ?? 0, opts.path, buf.toString("utf8").slice(0, 200)))
|
||||
return
|
||||
}
|
||||
resolve(buf)
|
||||
@@ -307,13 +308,14 @@ function rosDownload(
|
||||
})
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
req.destroy(new Error(`Connection to ${params.host}:${params.port} timed out after ${timeoutMs / 1000}s`))
|
||||
}, timeoutMs)
|
||||
req.destroy(new Error(`Connection to ${params.host}:${params.port} timed out after ${opts.timeoutMs / 1000}s`))
|
||||
}, opts.timeoutMs)
|
||||
req.on("close", () => clearTimeout(timer))
|
||||
req.on("error", (err) => {
|
||||
clearTimeout(timer)
|
||||
reject(err)
|
||||
})
|
||||
if (payload) req.write(payload)
|
||||
req.end()
|
||||
})
|
||||
}
|
||||
@@ -400,6 +402,74 @@ function matchesUploadedFile(entryName: string, requested: string): boolean {
|
||||
|| 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(
|
||||
family: FirewallFamily,
|
||||
table: FirewallTable | "address-list",
|
||||
@@ -422,6 +492,31 @@ function unknownParameterName(error: MikrotikError): string | undefined {
|
||||
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 {
|
||||
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")
|
||||
}
|
||||
|
||||
async listFiles(): Promise<Array<{ name: string }>> {
|
||||
async listFiles(): Promise<Array<{ id: string; name: string; size: number }>> {
|
||||
const raw = await this.get<unknown>("/file")
|
||||
if (!Array.isArray(raw)) return []
|
||||
return raw
|
||||
.filter((row): row is Record<string, unknown> => row != null && typeof row === "object")
|
||||
.map((row) => ({ name: String(row.name ?? "") }))
|
||||
.filter((row) => row.name.length > 0)
|
||||
.map((row) => ({
|
||||
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> {
|
||||
@@ -679,21 +788,48 @@ export class MikrotikClient {
|
||||
}
|
||||
}
|
||||
|
||||
/** Скачивание содержимого файла RouterOS (GET /rest/file/<name>, бинарно). */
|
||||
async downloadFile(fileName: string, timeoutMs = 30_000): Promise<Buffer> {
|
||||
const normalized = routerFileBasename(fileName)
|
||||
const candidates = [normalized, `flash/${normalized}`]
|
||||
let lastError: unknown
|
||||
for (const name of candidates) {
|
||||
try {
|
||||
return await rosDownload(this.params, `/file/${encodeURIComponent(name)}`, timeoutMs)
|
||||
} catch (error) {
|
||||
lastError = error
|
||||
}
|
||||
}
|
||||
throw lastError instanceof Error
|
||||
? lastError
|
||||
: new Error(`Не удалось скачать файл ${normalized} с RouterOS`)
|
||||
/**
|
||||
* Чтение содержимого файла RouterOS командой `/file/get` (REST: POST).
|
||||
* Путь `GET /file/<name>` не существует — RouterOS отвечает `no such command prefix`.
|
||||
* @see https://help.mikrotik.com/docs/spaces/ROS/pages/2555971/Files
|
||||
*/
|
||||
private async readFileContents(
|
||||
target: { id?: string; name?: string },
|
||||
timeoutMs = 30_000,
|
||||
): Promise<Buffer> {
|
||||
const body: Record<string, string> = { ".proplist": "contents" }
|
||||
if (target.id) body[".id"] = target.id
|
||||
else if (target.name) body.name = target.name
|
||||
else throw new Error("RouterOS: не задан файл для чтения")
|
||||
const raw = await rosRawRequest(this.params, {
|
||||
method: "POST",
|
||||
path: "/file/get",
|
||||
body,
|
||||
timeoutMs,
|
||||
})
|
||||
return extractRosContentsField(raw)
|
||||
}
|
||||
|
||||
/** Скачивание содержимого файла RouterOS: `/file/get` + побайтовый разбор (лимит 60 КБ). */
|
||||
async downloadFile(
|
||||
target: { name: string; id?: string; size?: number },
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -745,12 +881,12 @@ export class MikrotikClient {
|
||||
}
|
||||
}
|
||||
|
||||
/** Экспорт сертификата в файл на роутере (pkcs12/pem); возвращает имя созданного файла. */
|
||||
/** Экспорт сертификата в файл на роутере (pkcs12/pem); возвращает созданный файл. */
|
||||
async exportCertificate(params: {
|
||||
name: string
|
||||
type: "pkcs12" | "pem"
|
||||
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 }
|
||||
if (params.passphrase?.trim()) body["export-passphrase"] = params.passphrase.trim()
|
||||
let raw: unknown
|
||||
@@ -770,14 +906,35 @@ export class MikrotikClient {
|
||||
const hit = files.find((f) => wanted.includes(f.name))
|
||||
?? files.find((f) => f.name.endsWith(`.${ext}`) && f.name.includes(params.name))
|
||||
if (!hit) throw new Error(`Файл экспорта ${params.name}.${ext} не найден на RouterOS`)
|
||||
return hit.name
|
||||
return { fileName: hit.name, fileId: hit.id, size: hit.size }
|
||||
}
|
||||
|
||||
/** Скачивание .p12 (сертификат + ключ + цепочка) как бинарный Buffer. */
|
||||
async exportCertificatePkcs12(params: { name: string; passphrase?: string }): Promise<{ fileName: string; content: Buffer }> {
|
||||
const fileName = await this.exportCertificate({ name: params.name, type: "pkcs12", passphrase: params.passphrase })
|
||||
const content = await this.downloadFile(fileName)
|
||||
return { fileName, content }
|
||||
async exportCertificatePkcs12(params: { name: string; passphrase?: string }): Promise<{ fileName: string; content: Buffer; passphrase: string }> {
|
||||
let passphrase = params.passphrase?.trim() || generateExportPassphrase()
|
||||
let exported: { fileName: string; fileId: string; size: number }
|
||||
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> {
|
||||
|
||||
@@ -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"
|
||||
|
||||
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 { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
@@ -33,7 +33,8 @@ function downloadB64(filename: string, b64: string, mime: string) {
|
||||
}
|
||||
|
||||
function randomPassphrase(): string {
|
||||
const bytes = new Uint8Array(9)
|
||||
// RouterOS требует ≥ IPSEC_MIN_PASSPHRASE символов
|
||||
const bytes = new Uint8Array(IPSEC_MIN_PASSPHRASE + 1)
|
||||
crypto.getRandomValues(bytes)
|
||||
let s = ""
|
||||
for (const b of bytes) s += "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"[b % 56]
|
||||
@@ -62,7 +63,10 @@ function IpsecCertSheet({
|
||||
queueMicrotask(() => setPassphrase(initial))
|
||||
}, [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 (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
@@ -83,7 +87,15 @@ function IpsecCertSheet({
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<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">
|
||||
<Input
|
||||
className="font-mono"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
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 { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
@@ -91,6 +91,9 @@ function IpsecUserSheet({
|
||||
if (!form.name.trim()) 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
|
||||
// RouterOS отклоняет export-passphrase короче 8 символов
|
||||
const passphrase = form.passphrase.trim()
|
||||
if (!editing && passphrase.length > 0 && passphrase.length < IPSEC_MIN_PASSPHRASE) return false
|
||||
return true
|
||||
}, [form, editing])
|
||||
|
||||
@@ -201,7 +204,14 @@ function IpsecUserSheet({
|
||||
</>
|
||||
) : (
|
||||
!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
|
||||
className="font-mono"
|
||||
placeholder="например MySecret123"
|
||||
|
||||
@@ -2,6 +2,12 @@ import { z } from "zod"
|
||||
|
||||
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). */
|
||||
export const ipsecClientDtoSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
@@ -166,8 +172,8 @@ export const ipsecUserCreateRequestSchema = z.object({
|
||||
remoteId: z.string().optional(),
|
||||
/** Конкретный IP клиента; без — выдаётся из пула. */
|
||||
staticIp: z.string().optional(),
|
||||
/** Пароль на экспортируемый .p12. */
|
||||
passphrase: z.string().min(4).optional(),
|
||||
/** Пароль на экспортируемый .p12 (RouterOS требует ≥ IPSEC_MIN_PASSPHRASE). */
|
||||
passphrase: z.string().min(IPSEC_MIN_PASSPHRASE).optional(),
|
||||
daysValid: z.number().int().positive().optional(),
|
||||
})
|
||||
|
||||
@@ -183,13 +189,13 @@ export const ipsecUserPatchSchema = z.object({
|
||||
export const ipsecCertExportRequestSchema = z.object({
|
||||
serverId: z.union([z.string(), z.number()]),
|
||||
clientId: z.string().min(1),
|
||||
passphrase: z.string().min(4),
|
||||
passphrase: z.string().min(IPSEC_MIN_PASSPHRASE),
|
||||
})
|
||||
|
||||
/** Экспорт .p12 существующего клиентского сертификата по имени (client1/anakondra и т.п.). */
|
||||
export const ipsecCertExportByNameRequestSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
passphrase: z.string().min(4),
|
||||
passphrase: z.string().min(IPSEC_MIN_PASSPHRASE),
|
||||
})
|
||||
|
||||
/** Бандл для авторизации клиента: .p12 (+ strongSwan .sswan + инструкция). */
|
||||
|
||||
Reference in New Issue
Block a user