From 1af3755a77ac8db4e81f424dd3f6d053c3753281 Mon Sep 17 00:00:00 2001 From: Denozordec Date: Sun, 22 Nov 2026 14:24:19 +0700 Subject: [PATCH] =?UTF-8?q?fix(ipsec):=20=D0=B2=D0=BE=D1=81=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2=D0=B8=D1=82=D1=8C=20=D1=81=D0=BE=D0=B7?= =?UTF-8?q?=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=BA=D0=BB=D0=B8=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D0=BE=D0=B2=20=D0=B8=20=D1=8D=D0=BA=D1=81=D0=BF=D0=BE?= =?UTF-8?q?=D1=80=D1=82=20=D1=81=D0=B5=D1=80=D1=82=D0=B8=D1=84=D0=B8=D0=BA?= =?UTF-8?q?=D0=B0=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...existing-certificate-export-http.sql.test.ts | 12 +++++++++--- .../modules/mcp/ipsec-user-create-acceptance.ts | 15 +++++++++++++-- .../modules/mcp/ipsec-user-create-actions.ts | 2 +- .../src/modules/mcp/operation-revisions.test.ts | 2 +- backend/src/services/ipsec-config.ts | 10 +--------- .../services/ipsec-user-create-model.test.ts | 6 +++--- backend/src/services/ipsec-user-create-model.ts | 11 ++++++----- .../mikrotik-owned-file-zeroization.test.ts | 5 ++++- .../src/services/mikrotik-owned-file.test.ts | 17 +++++++++++++++++ backend/src/services/mikrotik.ts | 6 ++++-- backend/src/services/routeros-native-paths.ts | 9 +++++++++ 11 files changed, 68 insertions(+), 27 deletions(-) diff --git a/backend/src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts b/backend/src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts index 3b0831d7..4f9d4fb1 100644 --- a/backend/src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts +++ b/backend/src/modules/mcp/ipsec-existing-certificate-export-http.sql.test.ts @@ -62,11 +62,17 @@ const router = createServer(async (req, res) => { if (req.method === "GET") { res.end(JSON.stringify(catalogs[path] ?? [])); return } let raw = ""; for await (const chunk of req) raw += chunk const fields = raw ? JSON.parse(raw) as Row : {} - if (path === "/file/get" || path === "/file/print") { res.end(JSON.stringify({ ret: fakeP12 })); return } + if (path === "/file/get") { + assert(catalogs["/file"].some(row => row[".id"] === fields[".id"] && row[".id"].startsWith("**"))) + res.end(JSON.stringify({ ret: fakeP12 })) + return + } commands.push({ method: req.method!, path, ...(fields.name ? { name: fields.name } : {}) }) if (req.method === "POST" && path === "/certificate/export-certificate") { - assert(catalogs["/certificate"].some(row => row.name === fields.name)) - catalogs["/file"].push({ ".id": `*new${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" }) + const certificate = catalogs["/certificate"].find(row => row[".id"] === fields[".id"]) + assert(certificate && !("name" in fields)) + commands.at(-1)!.name = certificate.name + catalogs["/file"].push({ ".id": `**New${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" }) if (mode === "lost") { req.socket.destroy(); return } } else if (req.method === "DELETE" && path.startsWith("/file/")) { catalogs["/file"] = catalogs["/file"].filter(row => row[".id"] !== path.slice("/file/".length)) diff --git a/backend/src/modules/mcp/ipsec-user-create-acceptance.ts b/backend/src/modules/mcp/ipsec-user-create-acceptance.ts index 730d38cd..f3680721 100644 --- a/backend/src/modules/mcp/ipsec-user-create-acceptance.ts +++ b/backend/src/modules/mcp/ipsec-user-create-acceptance.ts @@ -42,7 +42,11 @@ export async function acceptIpsecUserCreate(actor: AuthUser) { if (req.method === "GET") { res.end(JSON.stringify(catalogs[path] ?? [])); return } let raw = ""; for await (const chunk of req) raw += chunk const fields = raw ? JSON.parse(raw) as Row : {} - if (path === "/file/get" || path === "/file/print") { res.end(JSON.stringify({ ret: fakeP12 })); return } + if (path === "/file/get") { + assert(catalogs["/file"].some(row => row[".id"] === fields[".id"] && row[".id"].startsWith("**"))) + res.end(JSON.stringify({ ret: mode === "download-failed" ? "short" : fakeP12 })) + return + } commands.push({ method: req.method!, path, fields }) // RouterOS 7.24 (stand probe 2026-11-21): no `comment` on /certificate; sign and export by `.id` only, no `name`/`days-valid`. const refusal = req.method === "PUT" && path === "/certificate" && "comment" in fields ? "unknown parameter comment" @@ -54,7 +58,7 @@ export async function acceptIpsecUserCreate(actor: AuthUser) { if (path === "/certificate/sign") { const row = catalogs["/certificate"].find(row => row[".id"] === fields[".id"]); assert(row) Object.assign(row, { ca: fields.ca, "digest-algorithm": "sha256", fingerprint: "synthetic-fingerprint", "invalid-before": "2026-01-01", "invalid-after": "2030-01-01", "private-key": "true", "serial-number": "synthetic" }) - } else if (path === "/certificate/export-certificate") assert(catalogs["/certificate"].some(row => row[".id"] === fields[".id"])), catalogs["/file"].push({ ".id": `*new${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" }) + } else if (path === "/certificate/export-certificate") assert(catalogs["/certificate"].some(row => row[".id"] === fields[".id"])), catalogs["/file"].push({ ".id": `**New${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" }) else { const catalog = Object.keys(catalogs).find(value => path === value || path.startsWith(value + "/")); assert(catalog) if (req.method === "PUT") { result = { ".id": `*new${++serial}`, ...fields, "native-default": "NEVER_NATIVE_DEFAULT" }; catalogs[catalog].push(result) } @@ -101,6 +105,7 @@ export async function acceptIpsecUserCreate(actor: AuthUser) { const stored = (await query("SELECT * FROM mcp_artifacts WHERE id=$1", [saved.artifactId])).rows[0]; hidden(stored); assert.equal(stored.access_scope.kind, "ipsec-user-bundle"); assert(stored.expires_at.getTime() <= Date.now() + 900000) const download = await portal.inject({ url: saved.downloadPath, headers }); assert.equal(download.statusCode, 200, download.body); assert.equal(download.headers["cache-control"], "private, no-store") const bundle = download.json(); assert.equal(Buffer.from(bundle.contentB64, "base64").toString(), fakeP12); assert.equal(bundle.passphrase, "NEVER_EXPORT_PASSPHRASE") + assert.equal(JSON.parse(bundle.sswanContent).local.p12, bundle.contentB64) assert.equal((await portal.inject({ url: saved.downloadPath, headers: { authorization: `Bearer ${token("other-owner")}` } })).statusCode, 403) assert.equal((await portal.inject({ url: saved.downloadPath, headers: { authorization: `Bearer ${token(actor.id, ["mm:network:read"])}` } })).statusCode, 403) const listing: { statusCode: number; body: string; json: () => { items: Array<{ id: string; artifactReceipts: Array<{ artifactId: string }> }> } } = await portal.inject({ url: `/api/mcp/operations?connectionId=${connectionId}`, headers }); assert.equal(listing.statusCode, 200, listing.body); hidden(listing.json()); assert(listing.json().items.find((row: { id: string }) => row.id === result.operation.id)!.artifactReceipts.some((row: { artifactId: string }) => row.artifactId === saved.artifactId)) @@ -110,6 +115,12 @@ export async function acceptIpsecUserCreate(actor: AuthUser) { const response = await rest.inject({ method: "POST", url: "/api/ipsec/users", payload: { serverId, name: "Alice", authMethod, ...(staticIp ? { staticIp } : {}), ...(authMethod === "certificate" ? { daysValid: 365, passphrase: "NEVER_EXPORT_PASSPHRASE" } : { psk: "NEVER_PSK_SECRET", remoteId: "alice.example.test" }) } }); assert.equal(response.statusCode, 201, response.body) assert.deepEqual(normalize(commands.slice(restStart)), accepted) } + reset(); mode = "download-failed" + const failedExport = await rest.inject({ method: "POST", url: "/api/ipsec/users", payload: { serverId, name: "Alice", staticIp: "192.0.2.7" } }) + assert.equal(failedExport.statusCode, 502, failedExport.body) + assert.equal(failedExport.json().state, "partial") + assert.deepEqual(catalogs["/ip/ipsec/identity"], base["/ip/ipsec/identity"]) + assert.deepEqual(catalogs["/ip/ipsec/mode-config"], base["/ip/ipsec/mode-config"]) reset(); const rawStart = commands.length for (const request of [{ name: "Alice" }, { name: "Alice", authMethod: "pre-shared-key", psk: "NEVER_RAW" }, { name: "Alice", privateKeyExport: true, staticIp: "bad" }]) await assert.rejects(prepare(request)) assert.equal(commands.length, rawStart) diff --git a/backend/src/modules/mcp/ipsec-user-create-actions.ts b/backend/src/modules/mcp/ipsec-user-create-actions.ts index 209e35ec..99e2c369 100644 --- a/backend/src/modules/mcp/ipsec-user-create-actions.ts +++ b/backend/src/modules/mcp/ipsec-user-create-actions.ts @@ -148,5 +148,5 @@ export function createIpsecUserCreateAdapter(overrides: Partial` for configuration rows; RouterOS 7.24 `/file` rows use case-sensitive `**` ids - * whose length follows the file path (stand probe 2026-11-21). */ -export function isRouterOsNativeId(value: unknown): value is string { - return typeof value === "string" && value.length <= 256 && /^\*\*?[a-z0-9]+$/i.test(value) -} -/** Duplicate key: hex ids compare case-insensitively without leading zeros; `**` file ids compare exactly. */ -export function routerOsIdKey(value: string): string { - return value.startsWith("**") ? value : value.toLowerCase().replace(/^\*0+(?=[a-z0-9])/, "*") -} +export { isRouterOsNativeId, routerOsIdKey } from "./routeros-native-paths.js" /** RouterOS 7.24 omits a peer `address` equal to the any-address from REST rows (stand probe 2026-11-21). */ export const IPSEC_ANY_PEER_ADDRESS = "0.0.0.0/0" /** RouterOS 7.24 `/certificate` has no `comment` (PUT refuses it), so product certificates are recognised by their diff --git a/backend/src/services/ipsec-user-create-model.test.ts b/backend/src/services/ipsec-user-create-model.test.ts index 2a741543..ec66bb8d 100644 --- a/backend/src/services/ipsec-user-create-model.test.ts +++ b/backend/src/services/ipsec-user-create-model.test.ts @@ -74,7 +74,7 @@ assert.deepEqual(project(withFile, cert.commands[3], { assignedId: "*export" }). assert.throws(() => project(state, psk.commands[0], { assignedId: "*l", observedRow: { ".id": "*l", ...psk.commands[0].fields } }), /ACK/) assert.throws(() => project(state, psk.commands[0], { assignedId: "*new", observedRow: { ".id": "*new", ...psk.commands[0].fields, "remote-id": "key-id:mallory" } }), /Поля/) const staticCert = plan(state, server, { serverId: 1, name: "Alice", staticIp: "192.0.2.7" }, "mm-ipsec-fixture") -assert.deepEqual(staticCert.commands.map(row => row.action), ["create", "create", "sign", "create", "export", "cleanup"]) -assert.equal(staticCert.commands[3].fields["remote-certificate"], cert.certName) -assert.equal(staticCert.commands[3].fields["match-by"], "certificate") +assert.deepEqual(staticCert.commands.map(row => row.path), ["/certificate", "/certificate/sign", "/certificate/export-certificate", "/file", "/ip/ipsec/mode-config", "/ip/ipsec/identity"]) +assert.equal(staticCert.commands[5].fields["remote-certificate"], cert.certName) +assert.equal(staticCert.commands[5].fields["match-by"], "certificate") console.log("ipsec-user-create-model: full PSK/certificate/static/export plans and raw conservation passed") diff --git a/backend/src/services/ipsec-user-create-model.ts b/backend/src/services/ipsec-user-create-model.ts index 9a23c807..c3f915a0 100644 --- a/backend/src/services/ipsec-user-create-model.ts +++ b/backend/src/services/ipsec-user-create-model.ts @@ -45,6 +45,7 @@ export function planIpsecUserCreate(state: IpsecUserCreateState, server: ServerR if (mapClients(live).some(row => row.name === body.name.trim()) || (certName && live.certs.some(row => row.name === certName))) throw fail("Клиент уже существует") if (body.authMethod === "pre-shared-key" && live.identities.some(row => row.peer === peer.name && row["auth-method"] === "pre-shared-key" && row["remote-id"] === normalizeIpsecRemoteId(body.remoteId ?? body.name))) throw fail("Remote ID уже используется клиентом этого peer") const commands: IpsecUserCreateCommand[] = [], seeds: Array<{ path: string; row: Row }> = [] + let staticModeConfig: IpsecUserCreateCommand | undefined const seed = (path: string, row: unknown) => { if (row) seeds.push({ path, row: row as Row }) } seed("/ip/ipsec/peer", peer); seed("/ip/ipsec/mode-config", sharedMc) const sharedIdentity = selectSharedIke2Identity(live.identities, names) @@ -58,18 +59,18 @@ export function planIpsecUserCreate(state: IpsecUserCreateState, server: ServerR if (existing && (!isManagedIpsecModeConfig(existing) || c["/ip/ipsec/identity"].some(row => row["mode-config"] === existing.name || row["mode-config"]?.toLowerCase() === existing[".id"].toLowerCase()))) throw fail("Персональный mode-config уже используется другим клиентом; адрес чужого или общего объекта изменять нельзя") if (existing) for (const flag of ["dynamic", "builtin", "default"]) if (existing[flag] !== undefined && observedBoolean(existing[flag]) !== false) throw fail("Системный mode-config нельзя изменять", "PROTECTED_OBJECT") seed("/ip/ipsec/mode-config", existing) - commands.push({ action: existing ? "update" : "create", path: "/ip/ipsec/mode-config", ...(existing ? { id: existing[".id"] } : {}), fields: { name: modeConfig, address: body.staticIp.trim(), responder: "yes", "address-prefix-length": "32" } }) + staticModeConfig = { action: existing ? "update" : "create", path: "/ip/ipsec/mode-config", ...(existing ? { id: existing[".id"] } : {}), fields: { name: modeConfig, address: body.staticIp.trim(), responder: "yes", "address-prefix-length": "32" } } } if (certName) { seed("/certificate", serverCert); seed("/certificate", c["/certificate"].find(row => row.name === caName)) commands.push({ action: "create", path: "/certificate", fields: { name: certName, "common-name": body.name.trim(), "key-size": "2048", "key-usage": "digital-signature,key-encipherment,tls-client", "days-valid": String(body.daysValid ?? 1825) } }) commands.push({ action: "sign", path: "/certificate/sign", name: certName, fields: { ca: caName! } }) - } - if (body.authMethod !== "certificate" || body.staticIp || !sharedIdentity) commands.push({ action: "create", path: "/ip/ipsec/identity", fields: identityRosBody({ peerName: peer.name, modeConfig, comment: certName && !body.staticIp ? ipsecManagedComment("IKEv2 listener") : ipsecUserComment(body.name), authMethod: body.authMethod, certificate: certName ? serverCert!.name : undefined, remoteCertificate: body.staticIp ? certName : undefined, secret: body.psk, remoteId: body.authMethod === "pre-shared-key" ? body.remoteId ?? body.name : undefined, policyTemplateGroup: sharedIdentity?.["policy-template-group"] }) }) - if (certName) { if (c["/file"].some(row => row.name === `${exportPrefix}.p12`)) throw fail("Имя файла экспорта занято") commands.push({ action: "export", path: "/certificate/export-certificate", name: `${exportPrefix}.p12`, certificate: certName, fields: { type: "pkcs12", "file-name": exportPrefix, "export-passphrase": body.passphrase ?? "" } }, { action: "cleanup", path: "/file", name: `${exportPrefix}.p12`, fields: {} }) } + // Leave the client-specific IPsec settings untouched if the private export fails. + if (staticModeConfig) commands.push(staticModeConfig) + if (body.authMethod !== "certificate" || body.staticIp || !sharedIdentity) commands.push({ action: "create", path: "/ip/ipsec/identity", fields: identityRosBody({ peerName: peer.name, modeConfig, comment: certName && !body.staticIp ? ipsecManagedComment("IKEv2 listener") : ipsecUserComment(body.name), authMethod: body.authMethod, certificate: certName ? serverCert!.name : undefined, remoteCertificate: body.staticIp ? certName : undefined, secret: body.psk, remoteId: body.authMethod === "pre-shared-key" ? body.remoteId ?? body.name : undefined, policyTemplateGroup: sharedIdentity?.["policy-template-group"] }) }) const kinds: Record = { "/ip/ipsec/peer": "ipsec_peer", "/ip/ipsec/identity": "ipsec_identity", "/ip/ipsec/mode-config": "ipsec_mode_config", "/ip/pool": "ip_pool", "/certificate": "certificate", "/ip/ipsec/profile": "ipsec_profile", "/ip/ipsec/proposal": "ipsec_proposal", "/ip/ipsec/policy/group": "ipsec_policy_group", "/ip/ipsec/policy": "ipsec_policy" } const refs: Record = { peer: "/ip/ipsec/peer", "mode-config": "/ip/ipsec/mode-config", "address-pool": "/ip/pool", certificate: "/certificate", "remote-certificate": "/certificate", ca: "/certificate", profile: "/ip/ipsec/profile", proposal: "/ip/ipsec/proposal", "policy-template-group": "/ip/ipsec/policy/group" } for (const command of commands) for (const [field, refPath] of Object.entries(refs)) { @@ -126,7 +127,7 @@ export function projectIpsecUserCreate(state: IpsecUserCreateState, command: Ips rows[rows.indexOf(row)] = structuredClone(observed) } else { const row = options.observedRow, id = options.assignedId - if (!row || !exactId(id) || row[".id"] !== id || rows.some(item => item[".id"].toLowerCase() === id.toLowerCase()) || Object.values(row).some(value => typeof value !== "string")) throw fail("Не подтверждён ACK нового объекта", "VERIFICATION_FAILED") + if (!row || !exactId(id) || row[".id"] !== id || rows.some(item => routerOsIdKey(item[".id"]) === routerOsIdKey(id)) || Object.values(row).some(value => typeof value !== "string")) throw fail("Не подтверждён ACK нового объекта", "VERIFICATION_FAILED") for (const flag of ["dynamic", "builtin", "default"]) if (row[flag] !== undefined && observedBoolean(row[flag]) !== false) throw fail("Создан системный объект", "VERIFICATION_FAILED") const fields = command.action === "export" ? { name: command.name! } : command.fields for (const [key, value] of Object.entries(fields)) if (row[key] !== value && !(["disabled", "responder"].includes(key) && observedBoolean(row[key]) !== null && observedBoolean(row[key]) === observedBoolean(value))) throw fail("Поля нового объекта не подтверждены", "VERIFICATION_FAILED") diff --git a/backend/src/services/mikrotik-owned-file-zeroization.test.ts b/backend/src/services/mikrotik-owned-file-zeroization.test.ts index 3380ae4f..738553b6 100644 --- a/backend/src/services/mikrotik-owned-file-zeroization.test.ts +++ b/backend/src/services/mikrotik-owned-file-zeroization.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict" import { readFileSync } from "node:fs" import test from "node:test" import ts from "typescript" +import { isRouterOsNativeId, routerOsIdKey } from "./routeros-native-paths.js" // Execute the actual method with inert I/O and retained buffer references, so // cleanup is observable without intercepting global Buffer methods or networking. @@ -10,7 +11,7 @@ const begin = source.indexOf(" async downloadOwnedFile(") const end = source.indexOf(" /** Native text exports", begin) assert.ok(begin > 0 && end > begin) const script = ts.transpileModule(` - const {rosRawRequest,extractRosContentsField,MAX_OWNED_FILE_BYTES,MikrotikError}=deps; + const {rosRawRequest,extractRosContentsField,MAX_OWNED_FILE_BYTES,MikrotikError,isRouterOsNativeId,routerOsIdKey}=deps; class Reader { params={}; get=deps.get; ${source.slice(begin, end)} } return new Reader(); `, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None } }).outputText @@ -24,6 +25,8 @@ for (const mode of ["success", "raw-revoked", "decode-error", "wrong-size", "met const reader = new Function("deps", script)({ MAX_OWNED_FILE_BYTES: 61438, MikrotikError: class extends Error {}, + isRouterOsNativeId, + routerOsIdKey, get: async () => [{ ".id": "*owned", name: "owned.p12", size: Buffer.byteLength(secret), revision: mode === "metadata-drift" && ++metadataCalls > 1 ? "changed" : "initial" }], rosRawRequest: async () => { reads++; return raw }, extractRosContentsField: (value: Buffer) => { assert.equal(value, raw); if (mode === "decode-error") throw Error(secret); return decoded }, diff --git a/backend/src/services/mikrotik-owned-file.test.ts b/backend/src/services/mikrotik-owned-file.test.ts index 33c371c8..d688ebd7 100644 --- a/backend/src/services/mikrotik-owned-file.test.ts +++ b/backend/src/services/mikrotik-owned-file.test.ts @@ -4,11 +4,20 @@ import { setTimeout as delay } from "node:timers/promises" import { MAX_OWNED_FILE_BYTES, MikrotikClient } from "./mikrotik.js" const content = "synthetic-private-file-bytes", target = { id: "*owned", name: "owned.p12", size: Buffer.byteLength(content) } +const currentTarget = { ...target, id: "**Qo24Mn6Ay8FA4" } let mode = "normal", allowed = true, requests: string[] = [], bodies: unknown[] = [], metadataCalls = 0, closed = false, sent = 0, controller: AbortController | undefined const router = createServer(async (req, res) => { const path = req.url ?? ""; requests.push(path); res.setHeader("content-type", "application/json") if (req.method === "GET") { metadataCalls++ + if (mode.startsWith("current-id")) { + const id = mode === "current-id-replaced" && metadataCalls > 1 ? currentTarget.id.toLowerCase() : currentTarget.id + res.end(JSON.stringify([ + { ".id": id, name: target.name, size: String(target.size) }, + { ".id": currentTarget.id.toUpperCase(), name: "other.p12", size: String(target.size) }, + ])) + return + } const id = mode === "replace-before" || ["replace-after", "compat-replace"].includes(mode) && metadataCalls > 1 ? "*replacement" : target.id res.end(JSON.stringify([{ ".id": id, name: target.name, size: String(target.size), opaque: "stable" }])); return } @@ -39,6 +48,14 @@ try { assert.equal((await client.downloadOwnedFile(target, { authorize })).toString(), content) assert.deepEqual(requests, ["/rest/file", "/rest/file/get", "/rest/file"]) assert.deepEqual(bodies, [{ ".id": target.id, "value-name": "contents" }]) + for (const mode of ["current-id", "current-id-replaced"]) { + reset(mode) + const request = client.downloadOwnedFile(currentTarget, { authorize }) + if (mode === "current-id") assert.equal((await request).toString(), content) + else await assert.rejects(request, /ID\/name\/size/) + assert.deepEqual(requests, ["/rest/file", "/rest/file/get", "/rest/file"]) + assert.deepEqual(bodies, [{ ".id": currentTarget.id, "value-name": "contents" }]) + } for (const compatibility of ["compat-400", "compat-404"]) { reset(compatibility) assert.equal((await client.downloadOwnedFile(target, { authorize })).toString(), content) diff --git a/backend/src/services/mikrotik.ts b/backend/src/services/mikrotik.ts index d291f195..ccba6607 100644 --- a/backend/src/services/mikrotik.ts +++ b/backend/src/services/mikrotik.ts @@ -6,6 +6,7 @@ import type { BandwidthNativeRequestBinder } from "./bandwidth-native-dispatch.j import { withConfigMutationLock, withApplicationMutationLock } from "./config-mutation-lock.js" import { executeGuardedConfigurationWrite } from "./config-mutation-policy.js" import { exportRouterConfiguration } from "./router-config-export.js" +import { isRouterOsNativeId, routerOsIdKey } from "./routeros-native-paths.js" import type { Server } from "../db/schema.js" import { parseRosDataSizeBytes } from "./ros-metric-parse.js" import { readOspfTemplateFlags } from "./ospf-template-flags.js" @@ -1168,7 +1169,8 @@ export class MikrotikClient { * unsupported value-name parameter permits the older .proplist spelling. * Metadata and grants are checked around every request; never retarget by name. */ async downloadOwnedFile(target: { id: string; name: string; size: number }, control: { authorize: () => Promise; signal?: AbortSignal; timeoutMs?: number }): Promise { - if (!/^\*[a-z0-9]+$/i.test(target.id) || !target.name || /[\x00-\x1f\x7f]/.test(target.name) || !Number.isSafeInteger(target.size) || target.size <= 0 || target.size > MAX_OWNED_FILE_BYTES) throw new Error("Private export must have an exact ID/name and size between 1 and 61438 bytes") + if (!isRouterOsNativeId(target.id) || !target.name || /[\x00-\x1f\x7f]/.test(target.name) || !Number.isSafeInteger(target.size) || target.size <= 0 || target.size > MAX_OWNED_FILE_BYTES) throw new Error("Private export must have an exact ID/name and size between 1 and 61438 bytes") + const idKey = routerOsIdKey(target.id) const duration = control.timeoutMs ?? 30000 if (!Number.isSafeInteger(duration) || duration <= 0 || duration > 45000) throw new Error("Invalid private export deadline") const deadline = Date.now() + duration, timerSignal = AbortSignal.timeout(duration) @@ -1186,7 +1188,7 @@ export class MikrotikClient { const rows = await this.get("/file", remaining(), signal, 1048576) await authorize() if (!Array.isArray(rows) || rows.length > 2000) throw new Error("Private export metadata unavailable") - const matches = rows.filter(row => row && typeof row === "object" && (row[".id"]?.toLowerCase() === target.id.toLowerCase() || row.name === target.name)) + const matches = rows.filter(row => row && typeof row === "object" && ((isRouterOsNativeId(row[".id"]) && routerOsIdKey(row[".id"]) === idKey) || row.name === target.name)) if (matches.length !== 1 || matches[0][".id"] !== target.id || matches[0].name !== target.name || Number(matches[0].size) !== target.size) throw new Error("Private export ID/name/size changed") return JSON.stringify(matches[0]) } diff --git a/backend/src/services/routeros-native-paths.ts b/backend/src/services/routeros-native-paths.ts index 445c45cf..9bf2402d 100644 --- a/backend/src/services/routeros-native-paths.ts +++ b/backend/src/services/routeros-native-paths.ts @@ -3,6 +3,15 @@ export function encodeRosId(rosId: string): string { return encodeURIComponent(id) } +/** RouterOS 7.24 file IDs use case-sensitive `**` instead of the legacy single asterisk. */ +export function isRouterOsNativeId(value: unknown): value is string { + return typeof value === "string" && value.length <= 256 && /^\*\*?[a-z0-9]+$/i.test(value) +} + +export function routerOsIdKey(value: string): string { + return value.startsWith("**") ? value : value.toLowerCase().replace(/^\*0+(?=[a-z0-9])/, "*") +} + export const greDependencyPaths = ["/interface", "/interface/bridge/port", "/interface/vlan", "/interface/list/member", "/ip/vrf", "/ip/route", "/ipv6/route", "/routing/filter/rule", "/routing/ospf/interface-template", "/routing/bfd/configuration", "/routing/bgp/connection", "/routing/rule",