Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
165f5e1260 | ||
|
|
1af3755a77 | ||
|
|
42efc3191b |
No files matched your search
@@ -68,14 +68,14 @@ export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
analytics[key] = value.slice(offset, offset + limit)
|
||||
pages[key] = { total: value.length, nextOffset: offset + limit < value.length ? offset + limit : null }
|
||||
}
|
||||
// Ring rates are server context, including when the retained rows are filtered by user/interface.
|
||||
// Wire rate uses interface counters. Keep rate estimates separate from retained volume.
|
||||
const { bpsNow: _bpsNow, bpsWire: _bpsWire, bpsOverlay: _bpsOverlay, bytesWire: _bytesWire, live: _live, ...retained } = analytics
|
||||
await authorize()
|
||||
if ((await readFlowSourceLimits()).topN !== limits.topN) throw new McpError("STATE_CONFLICT", "Предел источника NetFlow изменился во время чтения", 409)
|
||||
await authorize()
|
||||
const output = { serverId: server.id, minutes: sourceWindow?.effectiveMinutes ?? Number(input.minutes), sourceWindow, interface: input.interface ?? null, userId: input.userId ?? null,
|
||||
analytics: retained, pages, contextRates: { bpsNowEstimate: _bpsNow, bpsWireEstimate: _bpsWire, bpsOverlayEstimate: _bpsOverlay, bytesWireEstimate: _bytesWire,
|
||||
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: current server/interface ring with retained-window fallback; wire projection uses current interface snapshots" },
|
||||
listenerBound: _live, userAttributionVerified: false, semantics: "REST estimates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback; wire uses current interface snapshots" },
|
||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false,
|
||||
source: "retained flow_buckets plus pending; same REST analytics engine with scoped topology",
|
||||
rowLimit: 20000, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
|
||||
|
||||
@@ -57,7 +57,7 @@ export function registerFlowLiveActions(register: typeof add) {
|
||||
source: "REST live sample engine: current ring estimates and rolling flow_buckets plus pending; uncached scoped reads",
|
||||
rowLimit: 20000, incomplete: true, coverageVerified: false, forwardingVerified: false, rowSumIsNetworkTotal: false,
|
||||
historicalOwnershipVerified: false, currentTrafficVerified: false,
|
||||
rateSemantics: "REST live rates: current server/interface ring; retained-window fallback; user filter does not attribute ring rates",
|
||||
rateSemantics: "REST live rates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback",
|
||||
liveMeaning: "events[].data.live means listener bound; it does not prove exporter freshness or forwarding",
|
||||
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
collectorStarted: false, backgroundEnrichmentStarted: false }
|
||||
|
||||
@@ -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"].unshift({ ".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))
|
||||
|
||||
@@ -42,19 +42,30 @@ 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"
|
||||
: path === "/certificate/sign" && ("days-valid" in fields || "name" in fields) ? ("days-valid" in fields ? "unknown parameter days-valid" : "missing =.id=")
|
||||
: path === "/certificate/export-certificate" && "name" in fields ? "unknown parameter name" : undefined
|
||||
if (refusal) { res.statusCode = 400; res.end(JSON.stringify({ error: 400, message: "Bad Request", detail: refusal })); return }
|
||||
if ((mode === "export-refused" && path === "/certificate/export-certificate") || (mode === "cleanup-refused" && req.method === "DELETE" && path.startsWith("/file/"))) {
|
||||
res.statusCode = 400; res.end(JSON.stringify({ error: 400, detail: "NEVER_NATIVE_ERROR_DETAILS" })); return
|
||||
}
|
||||
let result: Row = {}
|
||||
if (mode !== "ignored") {
|
||||
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"].unshift({ ".id": `**New${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" })
|
||||
if (mode === "other-file-changed") catalogs["/file"][1].size = "99"
|
||||
}
|
||||
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 +112,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 +122,29 @@ 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(); mode = "other-file-changed"
|
||||
const unrelatedChange = await rest.inject({ method: "POST", url: "/api/ipsec/users", payload: { serverId, name: "Alice" } })
|
||||
assert.equal(unrelatedChange.statusCode, 502)
|
||||
assert.equal(unrelatedChange.json().completedCommands, 2)
|
||||
assert.equal(catalogs["/file"].length, 2, "failed proof must stop before deletion")
|
||||
for (const [fault, stage, completed] of [["export-refused", "экспорт .p12", 2], ["cleanup-refused", "удаление временного .p12", 3]] as const) {
|
||||
reset(); mode = fault
|
||||
const response = await rest.inject({ method: "POST", url: "/api/ipsec/users", payload: { serverId, name: "Alice", staticIp: "192.0.2.7" } })
|
||||
assert.equal(response.statusCode, 502)
|
||||
const error = response.json()
|
||||
assert.equal(error.completedCommands, completed)
|
||||
assert(error.error.includes(stage))
|
||||
assert(error.error.includes("HTTP 400"))
|
||||
hidden(error)
|
||||
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)
|
||||
|
||||
@@ -148,5 +148,5 @@ export function createIpsecUserCreateAdapter(overrides: Partial<typeof productio
|
||||
export function registerIpsecUserCreateActions(register: typeof add) {
|
||||
const adapter = createIpsecUserCreateAdapter()
|
||||
registerMcpService(operation, adapter.service)
|
||||
register(operation, "mm_ipsec_user_create_plan", "Создать клиента IPsec с проверкой всех native-команд, явным приватным экспортом и managed-only историей", "network", "mm:network:write", "write", "servers", ipsecUserCreateActionSchema, { version: 3, prepare: adapter.prepare })
|
||||
register(operation, "mm_ipsec_user_create_plan", "Создать клиента IPsec с проверкой всех native-команд, явным приватным экспортом и managed-only историей", "network", "mm:network:write", "write", "servers", ipsecUserCreateActionSchema, { version: 4, prepare: adapter.prepare })
|
||||
}
|
||||
@@ -10,7 +10,7 @@ assert.equal(findMcpOperation(fullFlowSettings.operation.id)?.version, 3)
|
||||
assert.equal(fullFlowSettings.schema.safeParse({ settings: { collectorIp: "10.255.254.1", enabled: false, mapServiceMinSharePct: 0 } }).success, true)
|
||||
assert.equal(fullFlowSettings.schema.safeParse({ topN: 10 }).success, false)
|
||||
assert.equal(findAction("mm_netflow_host_keys_generate_plan").operation.id, "traffic.flow.settings.generate-keys")
|
||||
assert.equal(findAction("mm_ipsec_user_create_plan").operation.version, 3)
|
||||
assert.equal(findAction("mm_ipsec_user_create_plan").operation.version, 4)
|
||||
assert.equal(findAction("mm_ipsec_server_init_plan").operation.version, 5)
|
||||
// RouterOS 7.24 certificate bodies (no comment, sign/export by .id): earlier prepared plans need a new approval.
|
||||
assert.equal(findAction("mm_ipsec_existing_certificate_export_plan").operation.version, 2)
|
||||
|
||||
@@ -134,15 +134,7 @@ export function isReleasableIpsecCryptoRow(row: { name?: string; comment?: strin
|
||||
return isIpsecManagedComment(row.comment) || (!row.comment?.trim() && row.name === IPSEC_COMMON_NAME)
|
||||
}
|
||||
export const IPSEC_CA_COMMON_NAME = "MikrotikManager IPsec CA"
|
||||
/** RouterOS native id: `*<hex>` for configuration rows; RouterOS 7.24 `/file` rows use case-sensitive `**<base62>` 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
|
||||
|
||||
@@ -96,12 +96,14 @@ export function normalizeIpsecExistingExportPassphrase(raw: string | undefined,
|
||||
}
|
||||
export function projectIpsecExistingCertificateExport(state: IpsecExistingCertificateExportState, filename: string, after: IpsecExistingCertificateExportState) {
|
||||
validateIpsecExistingCertificateExportState(after)
|
||||
const old = state.catalogs["/file"], candidates = after.catalogs["/file"].filter(row => row.name === filename && !old.some(prior => idKey(prior[".id"]) === idKey(row[".id"])))
|
||||
const old = state.catalogs["/file"], files = after.catalogs["/file"]
|
||||
const candidates = files.filter(row => row.name === filename && !old.some(prior => idKey(prior[".id"]) === idKey(row[".id"])))
|
||||
if (candidates.length !== 1) throw fail("Не подтверждён единственный receipt-owned файл экспорта", "VERIFICATION_FAILED")
|
||||
const row = candidates[0], size = Number(row.size)
|
||||
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_OWNED_FILE_BYTES) throw fail("Размер приватного файла вне предела точного /file/get (61438 байт)", "VERIFICATION_FAILED")
|
||||
const projected = structuredClone(state)
|
||||
projected.catalogs["/file"].push(structuredClone(row))
|
||||
// The new file can appear anywhere. The proof still checks the relative order and contents of every pre-existing row.
|
||||
projected.catalogs["/file"].splice(files.indexOf(row), 0, structuredClone(row))
|
||||
return { projected, file: { id: row[".id"], name: filename, size } }
|
||||
}
|
||||
export function projectIpsecExistingCertificateCleanup(state: IpsecExistingCertificateExportState, file: { id: string; name: string; size: number }) {
|
||||
|
||||
@@ -69,12 +69,13 @@ assert.throws(() => project(withCert, cert.commands[1], { observedRow: signed })
|
||||
const signedState = project(withCert, cert.commands[1], { observedRow: signed, ownedCertificateIds: new Set(["*new"]) })
|
||||
assert.deepEqual(signedState.catalogs["/certificate"].slice(0, 2), state.catalogs["/certificate"])
|
||||
assert.throws(() => project(withCert, cert.commands[1], { observedRow: { ...signed, opaque: "changed" }, ownedCertificateIds: new Set(["*new"]) }), /исходные поля/)
|
||||
const withFile = project(signedState, cert.commands[2], { assignedId: "*export", observedRow: { ".id": "*export", name: "mm-ipsec-fixture.p12", size: "256", type: "file" } })
|
||||
const withFile = project(signedState, cert.commands[2], { assignedId: "*export", observedRow: { ".id": "*export", name: "mm-ipsec-fixture.p12", size: "256", type: "file" }, exportIndex: 0 })
|
||||
assert.equal(withFile.catalogs["/file"][0][".id"], "*export")
|
||||
assert.deepEqual(project(withFile, cert.commands[3], { assignedId: "*export" }).catalogs["/file"], state.catalogs["/file"])
|
||||
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")
|
||||
@@ -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<string, string> = { "/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<string, string> = { 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)) {
|
||||
@@ -104,7 +105,7 @@ export function planIpsecUserCreate(state: IpsecUserCreateState, server: ServerR
|
||||
|
||||
/** Native defaults are admitted solely for the ACK-owned newly created row.
|
||||
* Signing can change only documented generated fields of that new certificate. */
|
||||
export function projectIpsecUserCreate(state: IpsecUserCreateState, command: IpsecUserCreateCommand, options: { assignedId?: string; observedRow?: Row; ownedCertificateIds?: Set<string> } = {}) {
|
||||
export function projectIpsecUserCreate(state: IpsecUserCreateState, command: IpsecUserCreateCommand, options: { assignedId?: string; observedRow?: Row; ownedCertificateIds?: Set<string>; exportIndex?: number } = {}) {
|
||||
const next = structuredClone(state)
|
||||
const path = command.action === "sign" ? "/certificate" : command.action === "export" || command.action === "cleanup" ? "/file" : command.path
|
||||
const rows = next.catalogs[path]
|
||||
@@ -126,11 +127,17 @@ 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")
|
||||
rows.push(structuredClone(row))
|
||||
if (command.action === "export") {
|
||||
const index = options.exportIndex
|
||||
if (index === undefined || !Number.isInteger(index) || index < 0 || index > rows.length) throw fail("Не подтверждена позиция нового файла экспорта", "VERIFICATION_FAILED")
|
||||
rows.splice(index, 0, structuredClone(row))
|
||||
} else {
|
||||
rows.push(structuredClone(row))
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { randomBytes, randomUUID } from "node:crypto"
|
||||
import type { IpsecCertBundle } from "@mmapp/contracts/ipsec"
|
||||
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
|
||||
import { McpError, fingerprint, privateFingerprinter } from "../modules/mcp/security.js"
|
||||
import { MAX_OWNED_FILE_BYTES, MikrotikClient } from "./mikrotik.js"
|
||||
import { MAX_OWNED_FILE_BYTES, MikrotikClient, MikrotikError } from "./mikrotik.js"
|
||||
import { readIpsecPeerDeleteState, ipsecPeerDeleteRows } from "./ipsec-peer-delete.js"
|
||||
import { ipsecUserUpdateValue } from "./ipsec-user-update.js"
|
||||
import { sameWireguardEndpoint } from "./wireguard-source.js"
|
||||
@@ -37,6 +37,15 @@ export async function createIpsecUserGuarded(server: ServerRow, raw: unknown, ex
|
||||
let completedCommands = 0, confirmedWrites = 0, bundle: IpsecCertBundle | undefined, artifactReceipt: Record<string, unknown> | undefined
|
||||
const stopped = (code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", message: string) => new IpsecUserCreateExecutionError(code, message, confirmedWrites, completedCommands, plan.commands.length)
|
||||
for (const command of plan.commands) {
|
||||
const stage = {
|
||||
create: command.path === "/certificate" ? "создание сертификата" : command.path === "/ip/ipsec/mode-config" ? "назначение персонального IP" : "создание привязки IKEv2",
|
||||
update: "обновление персонального IP",
|
||||
sign: "подпись сертификата",
|
||||
export: "экспорт .p12",
|
||||
cleanup: "удаление временного .p12",
|
||||
}[command.action]
|
||||
const stoppedAtStage = (code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", detail: string) =>
|
||||
stopped(code, `Создание IKEv2 остановлено на этапе «${stage}». ${detail}`)
|
||||
let dispatched = false, response: unknown, assignedId: string | undefined
|
||||
const fence = async () => { const fresh = await readIpsecUserCreateState(server, source); if (fresh.proof !== state.proof) throw new McpError("STATE_CONFLICT", "IPsec изменился после durable intent; команда не отправлена", 409); await source(); dispatched = true }
|
||||
try {
|
||||
@@ -57,7 +66,8 @@ export async function createIpsecUserGuarded(server: ServerRow, raw: unknown, ex
|
||||
confirmedWrites++
|
||||
} catch (error) {
|
||||
if (!dispatched && !completedCommands && error instanceof McpError) throw error
|
||||
throw stopped(dispatched ? "MUTATION_OUTCOME_UNKNOWN" : "VERIFICATION_FAILED", "Создание IPsec остановлено; повтор native-команды запрещён, требуется сверка")
|
||||
const detail = !dispatched ? "Команда не отправлена." : error instanceof MikrotikError ? `RouterOS вернул HTTP ${error.statusCode}.` : "Ответ RouterOS не подтверждён."
|
||||
throw stoppedAtStage(dispatched ? "MUTATION_OUTCOME_UNKNOWN" : "VERIFICATION_FAILED", `${detail} Перед повтором требуется сверка.`)
|
||||
}
|
||||
let after: IpsecUserCreateState
|
||||
try {
|
||||
@@ -67,23 +77,27 @@ export async function createIpsecUserGuarded(server: ServerRow, raw: unknown, ex
|
||||
const deadline = Date.now() + 90000
|
||||
while (!after.catalogs["/certificate"].find(row => row.name === command.name)?.["invalid-after"] && Date.now() < deadline) { await new Promise(resolve => setTimeout(resolve, 1000)); after = await readIpsecUserCreateState(server, source) }
|
||||
}
|
||||
} catch { throw stopped("MUTATION_OUTCOME_UNKNOWN", "Команда отправлена, но read-back недоступен; повтор запрещён") }
|
||||
} catch { throw stoppedAtStage("MUTATION_OUTCOME_UNKNOWN", "Команда отправлена. Не удалось перечитать состояние RouterOS.") }
|
||||
let exportIndex: number | undefined
|
||||
if (command.action === "export") {
|
||||
const files = after.catalogs["/file"]
|
||||
const candidates = files.filter(row => row.name === command.name && !state.catalogs["/file"].some(old => old[".id"] === row[".id"]))
|
||||
if (candidates.length !== 1) throw stoppedAtStage("VERIFICATION_FAILED", "В списке RouterOS не найден единственный новый файл с ожидаемым именем.")
|
||||
assignedId = candidates[0][".id"]
|
||||
exportIndex = files.indexOf(candidates[0])
|
||||
}
|
||||
try {
|
||||
const path = command.action === "sign" ? "/certificate" : command.action === "export" ? "/file" : command.path
|
||||
if (command.action === "create") {
|
||||
const ack = response as Record<string, unknown> | null
|
||||
if (typeof ack?.[".id"] !== "string") throw Error("missing create ACK")
|
||||
assignedId = ack[".id"]
|
||||
} else if (command.action === "export") {
|
||||
const candidates = after.catalogs["/file"].filter(row => row.name === command.name && !state.catalogs["/file"].some(old => old[".id"] === row[".id"]))
|
||||
if (candidates.length !== 1) throw Error("missing unique export file")
|
||||
assignedId = candidates[0][".id"]
|
||||
}
|
||||
const observedRow = after.catalogs[path].find(row => command.action === "sign" ? row.name === command.name : row[".id"] === assignedId)
|
||||
const projected = projectIpsecUserCreate(state, command, { assignedId, observedRow, ownedCertificateIds })
|
||||
const projected = projectIpsecUserCreate(state, command, { assignedId, observedRow, ownedCertificateIds, exportIndex })
|
||||
if (await ipsecUserCreateProof(projected) !== after.proof) throw Error("configuration mismatch")
|
||||
if (command.action === "create" && command.path === "/certificate") ownedCertificateIds.add(assignedId!)
|
||||
} catch { throw stopped("VERIFICATION_FAILED", "Не подтверждены команда и сохранность полного состояния IPsec; повтор запрещён") }
|
||||
} catch { throw stoppedAtStage("VERIFICATION_FAILED", "Проверка результата команды и состояния IPsec не пройдена.") }
|
||||
state = after; completedCommands++
|
||||
try {
|
||||
await source(); await options.checkpoint?.({ receiptId, commandCount: plan.commands.length, completedCommands, afterProof: state.proof })
|
||||
@@ -100,7 +114,7 @@ export async function createIpsecUserGuarded(server: ServerRow, raw: unknown, ex
|
||||
bundle = { user: body.name, serverEndpoint: plan.serverEndpoint, filename: file.name, contentB64: p12B64, mime: "application/x-pkcs12", passphrase, sswanFilename: `${plan.certName}.sswan`, sswanContent: buildSswanConfig({ name: `IKEv2 ${plan.serverEndpoint}`, serverEndpoint: plan.serverEndpoint, serverId: plan.serverEndpoint, p12B64 }), instructions: buildClientInstructions({ userName: body.name, serverEndpoint: plan.serverEndpoint, p12Filename: file.name, passphrase, dns: plan.dns }) }
|
||||
} finally { content.fill(0) }
|
||||
}
|
||||
} catch { throw stopped("MUTATION_OUTCOME_UNKNOWN", "Команда проверена, но checkpoint или приватный артефакт не сохранён; повтор запрещён") }
|
||||
} catch { throw stoppedAtStage("MUTATION_OUTCOME_UNKNOWN", "Команда подтверждена. Не удалось прочитать приватный файл или сохранить квитанцию.") }
|
||||
}
|
||||
const reader = { get: async (path: string) => { await source(); if (!Object.hasOwn(state.catalogs, path)) throw new McpError("STATE_UNAVAILABLE", "Неизвестный каталог истории IPsec", 502); return structuredClone(state.catalogs[path]) } } as unknown as MikrotikClient
|
||||
let historyRecorded = false
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<unknown>; signal?: AbortSignal; timeoutMs?: number }): Promise<Buffer> {
|
||||
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<unknown>("/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])
|
||||
}
|
||||
|
||||
@@ -3,6 +3,15 @@ export function encodeRosId(rosId: string): string {
|
||||
return encodeURIComponent(id)
|
||||
}
|
||||
|
||||
/** RouterOS 7.24 file IDs use case-sensitive `**<base62>` 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",
|
||||
|
||||
@@ -22,11 +22,11 @@ import {
|
||||
listFlowRowsForWindow,
|
||||
type PendingFlowRow,
|
||||
} from "./traffic-flow-ingest.js"
|
||||
import { flowDataEpoch, MAX_PENDING, RING_OVERLAY } from "./traffic-flow-engine.js"
|
||||
import { flowDataEpoch, MAX_PENDING } from "./traffic-flow-engine.js"
|
||||
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { applicationName, flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
import { dedupFlowRowsMaxBytes, flowTupleKey } from "./traffic-flow-dedup.js"
|
||||
import { collapseGreEspRows, dedupFlowRowsMaxBytes, flowTupleKey } from "./traffic-flow-dedup.js"
|
||||
import { enqueueRipeMisses } from "./traffic-flow-ripe.js"
|
||||
import { classifyFlowPlane, flowBps, shouldKeepPlane } from "./traffic-flow-planes.js"
|
||||
import { flowRateDirection, resolveInternetDest } from "./traffic-flow-dest.js"
|
||||
@@ -215,6 +215,23 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
|
||||
if (!scope) refreshFlowCatalogInBackground()
|
||||
|
||||
const matchesIngress = (row: PendingFlowRow) => flowRowMatchesFilter(row, resolveIfaceName(row.serverId, row.inIface).name, q, allow)
|
||||
const matchesEgress = (row: PendingFlowRow) => flowRowMatchesFilter({ serverId: row.serverId, inIface: row.outIface }, resolveIfaceName(row.serverId, row.outIface).name, q, allow)
|
||||
const serverDirection = (row: PendingFlowRow) => flowRateDirection(row.serverId, row, topo, catalog.byId.get(row.serverId)?.host)
|
||||
const interfaceDirection = (row: PendingFlowRow) => {
|
||||
const ingress = matchesIngress(row), egress = matchesEgress(row)
|
||||
return ingress === egress ? null : ingress ? "rx" : "tx"
|
||||
}
|
||||
const selected = ifaceFilter || allow ? raw.filter(row => matchesIngress(row) || matchesEgress(row)) : raw
|
||||
const { rows, espDirections } = collapseGreEspRows(selected, ifaceFilter ? interfaceDirection : serverDirection)
|
||||
const previousMinute = new Date(Math.floor(Date.now() / 60_000) * 60_000 - 60_000).toISOString()
|
||||
const ifacesForWire = new Set<string>()
|
||||
for (const row of selected) {
|
||||
ifacesForWire.add(resolveIfaceName(row.serverId, row.inIface).name)
|
||||
const egress = resolveIfaceName(row.serverId, row.outIface).name
|
||||
if (egress && egress !== "—") ifacesForWire.add(egress)
|
||||
}
|
||||
|
||||
const applications = new Map<string, { bytes: number; packets: number; label?: string }>()
|
||||
const protocols = new Map<string, { bytes: number; packets: number; label?: string }>()
|
||||
const sources = new Map<string, { bytes: number; packets: number; label?: string }>()
|
||||
@@ -234,16 +251,12 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const skipHeavy = Boolean(q.skipHeavy)
|
||||
let bytesPayload = 0
|
||||
let bytesOverlay = 0
|
||||
let recentOverlayBytes = 0
|
||||
let bytesMesh = 0
|
||||
const ifacesForWire = new Set<string>()
|
||||
|
||||
for (const r of raw) {
|
||||
for (const r of rows) {
|
||||
const resolved = resolveIfaceName(r.serverId, r.inIface)
|
||||
const outResolved = resolveIfaceName(r.serverId, r.outIface)
|
||||
if (!flowRowMatchesFilter(r, resolved.name, q, allow)
|
||||
&& !flowRowMatchesFilter({ serverId: r.serverId, inIface: r.outIface }, outResolved.name, q, allow)) continue
|
||||
ifacesForWire.add(resolved.name)
|
||||
if (outResolved.name && outResolved.name !== "—") ifacesForWire.add(outResolved.name)
|
||||
const plane = classifyFlowPlane({
|
||||
src: r.src,
|
||||
dst: r.dst,
|
||||
@@ -254,7 +267,10 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
outIface: outResolved.name,
|
||||
}, topo.plane)
|
||||
if (plane === "payload") bytesPayload += r.bytes
|
||||
else if (plane === "overlay") bytesOverlay += r.bytes
|
||||
else if (plane === "overlay") {
|
||||
bytesOverlay += r.bytes
|
||||
if (r.bucketAt === previousMinute) recentOverlayBytes += r.bytes
|
||||
}
|
||||
else if (plane === "client_mesh") bytesMesh += r.bytes
|
||||
if (!shouldKeepPlane(plane, { excludeMesh, excludeOverlay })) continue
|
||||
matched.push(r)
|
||||
@@ -444,9 +460,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const topCategory = topLabel(categories)
|
||||
|
||||
const ringServer = q.serverId ?? (matched[0]?.serverId ?? 0)
|
||||
const ring = ringServer
|
||||
? getRingMbps(ringServer, ifaceFilter === "" ? "__all__" : (ifacesMap.get(ifaceFilter)?.index || ifaceFilter))
|
||||
: { rx: Array(60).fill(0) as number[], tx: Array(60).fill(0) as number[], rxNow: 0, txNow: 0 }
|
||||
const ring = ringServer && !ifaceFilter && !allow && excludeOverlay ? getRingMbps(ringServer) : null
|
||||
|
||||
// The live ring covers about one minute; historical charts must use the requested window.
|
||||
// Keep the winning interface's individual minute buckets when deduplicating.
|
||||
@@ -454,13 +468,16 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const chartRows = chosenIfaces ? matched.filter(r => chosenIfaces.get(flowTupleKey(r)) === r.inIface) : matched
|
||||
const fromBuckets = seriesFromRows(chartRows, q.minutes, row => {
|
||||
if (ifaceFilter || allow) {
|
||||
const ingress = flowRowMatchesFilter(row, resolveIfaceName(row.serverId, row.inIface).name, q, allow)
|
||||
const egress = flowRowMatchesFilter({ serverId: row.serverId, inIface: row.outIface }, resolveIfaceName(row.serverId, row.outIface).name, q, allow)
|
||||
if (ingress && egress) return "both"
|
||||
const ingress = matchesIngress(row), egress = matchesEgress(row)
|
||||
if (ingress && egress) {
|
||||
// A repeated WAN interface in an overlay record does not prove two wire directions.
|
||||
if (ifaceFilter && (row.proto === 47 || row.proto === 50)) return espDirections.get(row) ?? serverDirection(row)
|
||||
return "both"
|
||||
}
|
||||
// At a client binding, ingress is the client's upload.
|
||||
return allow && !ifaceFilter ? (ingress ? "tx" : "rx") : (ingress ? "rx" : "tx")
|
||||
}
|
||||
return flowRateDirection(row.serverId, row, topo, catalog.byId.get(row.serverId)?.host)
|
||||
return espDirections.get(row) ?? serverDirection(row)
|
||||
})
|
||||
const rxSeries = fromBuckets.rx
|
||||
const txSeries = fromBuckets.tx
|
||||
@@ -499,9 +516,11 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
.sort((a, b) => b.bytes - a.bytes)
|
||||
.slice(0, top)
|
||||
|
||||
const overlayRing = ringServer
|
||||
? getRingMbps(ringServer, RING_OVERLAY)
|
||||
: { rxNow: 0, txNow: 0 }
|
||||
// Filtered and overlay-inclusive rates must use the same records as their totals.
|
||||
const recentBytes = ring ? 0 : chartRows.reduce((sum, row) => sum + (row.bucketAt === previousMinute ? row.bytes : 0), 0)
|
||||
const bpsNow = ring
|
||||
? (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec
|
||||
: (recentBytes * 8) / 60 || (totalBytes * 8) / windowSec
|
||||
const greNames = ringServer ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
|
||||
await authorize()
|
||||
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
|
||||
@@ -511,7 +530,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || (await readFlowSourceLimits()).topN !== settings.topN)) throw new Error("Топология или предел источника NetFlow изменились во время чтения")
|
||||
await authorize()
|
||||
return {
|
||||
bpsNow: (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec,
|
||||
bpsNow,
|
||||
bytes: totalBytes,
|
||||
packets: totalPackets,
|
||||
conversations: conv.size,
|
||||
@@ -549,7 +568,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
bytesOverlay,
|
||||
bytesMesh,
|
||||
bytesWire: wire.bytes,
|
||||
bpsOverlay: (overlayRing.rxNow + overlayRing.txNow) * 1_000_000 || (bytesOverlay * 8) / windowSec,
|
||||
bpsOverlay: (recentOverlayBytes * 8) / 60 || (bytesOverlay * 8) / windowSec,
|
||||
bpsWire: wire.bps,
|
||||
excludeMeshApplied: excludeMesh,
|
||||
excludeOverlayApplied: excludeOverlay,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from "node:assert/strict"
|
||||
import {
|
||||
collapseGreEspRows,
|
||||
dedupFlowRowsAcrossExporters,
|
||||
dedupFlowRowsMaxBytes,
|
||||
flowConversationKey,
|
||||
@@ -36,4 +37,28 @@ assert.equal(across.length, 1)
|
||||
assert.equal(across[0]?.serverId, 7)
|
||||
assert.equal(across[0]?.bytes, 9_000)
|
||||
|
||||
const minute = "2026-11-22T06:26:00.000Z"
|
||||
const nextMinute = "2026-11-22T06:27:00.000Z"
|
||||
const gre = { ...a, bucketAt: minute, proto: 47, srcPort: 0, dstPort: 0 }
|
||||
const esp = { ...gre, proto: 50, bytes: gre.bytes + gre.packets * 40, inIface: "10" }
|
||||
const plain = { ...gre, dst: "198.51.100.3" }
|
||||
const reverse = { ...esp, src: esp.dst, dst: esp.src }
|
||||
const foreign = { ...esp, serverId: 9 }
|
||||
const collapse = (rows: typeof gre[]) => collapseGreEspRows(rows, row => row.inIface === "2" ? "tx" : null)
|
||||
const layerPair = collapse([gre, esp, plain, reverse, foreign])
|
||||
assert.deepEqual(layerPair.rows, [esp, plain, reverse, foreign])
|
||||
assert.equal(layerPair.espDirections.get(esp), "tx")
|
||||
|
||||
const splitGre = [{ ...gre, bytes: 8_400, packets: 7 }, { ...gre, bucketAt: nextMinute, bytes: 3_600, packets: 3 }]
|
||||
const laterEsp = { ...esp, bucketAt: nextMinute }
|
||||
assert.deepEqual(collapse([...splitGre, laterEsp]).rows, [laterEsp])
|
||||
for (const unrelated of [
|
||||
{ ...esp, packets: esp.packets - 1 },
|
||||
{ ...esp, bytes: gre.bytes },
|
||||
{ ...esp, bytes: gre.bytes + gre.packets * 500 },
|
||||
{ ...esp, bucketAt: "2026-11-22T06:29:00.000Z" },
|
||||
{ ...esp, srcPort: 123 },
|
||||
]) assert.deepEqual(collapse([gre, unrelated]).rows, [gre, unrelated])
|
||||
assert.deepEqual(collapseGreEspRows([gre, esp], row => row.proto === 47 ? "rx" : "tx").rows, [gre, esp])
|
||||
|
||||
console.log("traffic-flow-dedup.test.ts: ok")
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isUnspecifiedIp } from "./traffic-flow-ip.js"
|
||||
|
||||
export interface FlowTupleRow {
|
||||
serverId: number
|
||||
src: string
|
||||
@@ -68,3 +70,66 @@ export function dedupFlowRowsMaxBytes<T extends FlowTupleRow>(rows: T[]): T[] {
|
||||
}
|
||||
return [...byTuple.values()]
|
||||
}
|
||||
|
||||
type TimedFlowRow = FlowTupleRow & { bucketAt: string }
|
||||
type FlowDirection = "rx" | "tx"
|
||||
type OverlayRows<T> = { gre: T[]; esp: T[] }
|
||||
|
||||
function account(rows: readonly FlowTupleRow[]) {
|
||||
return rows.reduce((total, row) => ({ bytes: total.bytes + row.bytes, packets: total.packets + row.packets }), { bytes: 0, packets: 0 })
|
||||
}
|
||||
|
||||
/** GRE and its IPsec envelope can both be exported for the same packet sequence. */
|
||||
export function collapseGreEspRows<T extends TimedFlowRow>(rows: readonly T[], direction: (row: T) => FlowDirection | null) {
|
||||
const groups = new Map<string, OverlayRows<T>>()
|
||||
for (const row of rows) {
|
||||
if ((row.proto !== 47 && row.proto !== 50) || row.srcPort !== 0 || row.dstPort !== 0 ||
|
||||
row.packets <= 0 || isUnspecifiedIp(row.src) || isUnspecifiedIp(row.dst) || row.src === row.dst) continue
|
||||
const key = JSON.stringify([row.serverId, row.src, row.dst])
|
||||
const group = groups.get(key) ?? { gre: [], esp: [] }
|
||||
if (row.proto === 47) group.gre.push(row)
|
||||
else group.esp.push(row)
|
||||
groups.set(key, group)
|
||||
}
|
||||
|
||||
const copies = new Set<T>()
|
||||
const espDirections = new Map<T, FlowDirection>()
|
||||
const match = (gre: T[], esp: T[]) => {
|
||||
if (!gre.length || !esp.length) return
|
||||
const inner = account(gre), outer = account(esp)
|
||||
if (inner.packets !== outer.packets) return
|
||||
const overhead = (outer.bytes - inner.bytes) / inner.packets
|
||||
// Keep ambiguous records. An ESP envelope adds its headers, trailer and padding.
|
||||
if (overhead < 8 || overhead > 128) return
|
||||
const directions = new Set([...gre, ...esp].map(direction).filter(side => side !== null))
|
||||
if (directions.size > 1) return
|
||||
const [side] = directions
|
||||
if (side) for (const row of esp) espDirections.set(row, side)
|
||||
for (const row of gre) copies.add(row)
|
||||
}
|
||||
|
||||
for (const group of groups.values()) {
|
||||
if (!group.gre.length || !group.esp.length) continue
|
||||
const byMinute = new Map<string, OverlayRows<T>>()
|
||||
for (const plane of ["gre", "esp"] as const) for (const row of group[plane]) {
|
||||
const bucket = byMinute.get(row.bucketAt) ?? { gre: [], esp: [] }
|
||||
bucket[plane].push(row)
|
||||
byMinute.set(row.bucketAt, bucket)
|
||||
}
|
||||
const unmatched: OverlayRows<T> = { gre: [], esp: [] }
|
||||
for (const [, bucket] of [...byMinute].sort(([a], [b]) => a.localeCompare(b))) {
|
||||
match(bucket.gre, bucket.esp)
|
||||
if (!bucket.gre.length || !copies.has(bucket.gre[0])) {
|
||||
unmatched.gre.push(...bucket.gre)
|
||||
unmatched.esp.push(...bucket.esp)
|
||||
}
|
||||
}
|
||||
// The exporter can flush the two layers in different minute buckets.
|
||||
if (unmatched.gre.length && unmatched.esp.length &&
|
||||
Math.abs(Date.parse(unmatched.gre[0].bucketAt) - Date.parse(unmatched.esp[0].bucketAt)) <= 60_000 &&
|
||||
Math.abs(Date.parse(unmatched.gre.at(-1)!.bucketAt) - Date.parse(unmatched.esp.at(-1)!.bucketAt)) <= 60_000) {
|
||||
match(unmatched.gre, unmatched.esp)
|
||||
}
|
||||
}
|
||||
return { rows: rows.filter(row => !copies.has(row)), espDirections }
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { applySqlMigrations } from '../db/migrate.js'
|
||||
import { ensurePartitionFor } from '../db/partitions.js'
|
||||
import { createMcpConnection,updateMcpSettings,setConnectionStatus } from '../modules/mcp/store.js'
|
||||
import { mcpConnectionCreateSchema } from '@mmapp/contracts/mcp'
|
||||
import type { FlowAnalyticsDto } from '@mmapp/contracts/traffic-flow'
|
||||
import mcpTransport from '../routes/mcp-transport.js'
|
||||
import trafficFlowRoutes from '../routes/traffic-flow.js'
|
||||
import logsRoutes from '../routes/logs.js'
|
||||
@@ -167,6 +168,38 @@ try{
|
||||
invalidateFlowAnalyticsCache()
|
||||
}
|
||||
console.log('PASS five-minute REST analysis uses one latest counter per interface despite 50,010 historical samples')
|
||||
const overlayBucket = new Date(Math.floor(Date.now()/60000)*60000-120000)
|
||||
await ensurePartitionFor(pool,'flow_buckets','day',overlayBucket)
|
||||
await pool.query(`INSERT INTO flow_buckets(server_id,bucket_at,src,dst,proto,src_port,dst_port,bytes,packets,in_iface,out_iface) VALUES
|
||||
(1,$1,'192.0.2.1','203.0.113.9',47,0,0,12000,10,'gre-test','ether1'),
|
||||
(1,$1,'192.0.2.1','203.0.113.9',50,0,0,12400,10,'ether1','ether1'),
|
||||
(1,$1,'203.0.113.9','192.0.2.1',47,0,0,24000,20,'ether1','gre-test'),
|
||||
(1,$1,'203.0.113.9','192.0.2.1',50,0,0,24800,20,'ether1','ether1'),
|
||||
(1,$1,'203.0.113.10','192.0.2.1',47,0,0,1000,1,'ether1','gre-other'),
|
||||
(1,$1,'203.0.113.11','203.0.113.12',50,0,0,2000,2,'ether1','ether1')`,[overlayBucket])
|
||||
try {
|
||||
const args={serverId:1,interface:'ether1',dedup:false,excludeOverlay:false}
|
||||
const rest=await fetch(endpoint+'/api/traffic/flow/analytics?range=5m&serverId=1&iface=ether1&dedup=false&excludeOverlay=false')
|
||||
assert.equal(rest.status,200,await rest.clone().text())
|
||||
const filtered=await client.callTool({name:'mm_netflow_analytics_report_get',arguments:{...args,minutes:5}})
|
||||
const live=await client.callTool({name:'mm_netflow_live_observe',arguments:args})
|
||||
assert.ok(!filtered.isError,JSON.stringify(filtered))
|
||||
assert.ok(!live.isError,JSON.stringify(live))
|
||||
const mcp=(filtered.structuredContent as {result:{analytics:FlowAnalyticsDto}}).result.analytics
|
||||
const sample=(live.structuredContent as {result:{events:{data:FlowAnalyticsDto}[]}}).result.events[0].data
|
||||
const fromSeries=(series:number[])=>Math.round(series.reduce((sum,value)=>sum+value,0)*60*1e6/8)
|
||||
for(const analytics of [await rest.json() as FlowAnalyticsDto,mcp,sample]){
|
||||
assert.equal(analytics.bytes,40300,'Each overlay packet sequence contributes only the ESP bytes')
|
||||
assert.equal(analytics.bytesOverlay,40200,'Plain GRE and undirected ESP remain part of the volume')
|
||||
assert.equal(fromSeries(analytics.rxSeries),25900)
|
||||
assert.equal(fromSeries(analytics.txSeries),12400)
|
||||
}
|
||||
assert.equal(sample.bpsOverlay,40200*8/300)
|
||||
}finally{
|
||||
await pool.query("DELETE FROM flow_buckets WHERE server_id=1 AND bucket_at=$1 AND proto IN (47,50)",[overlayBucket])
|
||||
invalidateFlowAnalyticsCache()
|
||||
}
|
||||
console.log('PASS REST and MCP history and live analytics collapse GRE/ESP and place each confirmed ESP direction once')
|
||||
const globalAccess=await createMcpConnection(mcpConnectionCreateSchema.parse({name:'owned global telemetry',mode:'observer',permissions:['mm:traffic:read'],expiresAt:new Date(Date.now()+600000).toISOString(),scope:{serverIds:[1],operationIds:['traffic.flow.talkers.read','netflow.settings.read'],allowGlobal:true},limits:{callsPerMinute:240}}),actor)
|
||||
const globalClient=new Client({name:'owned-global-quality',version:'1'})
|
||||
try{
|
||||
|
||||
Reference in new issue
Block a user