@usex/mikrotik-mcp 5.19.0 → 5.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +172 -8
- package/dist/cli.js +2751 -679
- package/dist/index.js +148 -27
- package/dist/shared/{library-7wcv2ckk.js → library-73y8qdjr.js} +2231 -540
- package/dist/shared/{library-tqrvrykj.js → library-76naf20r.js} +1 -1
- package/dist/shared/{library-ppnv0f07.js → library-81amv3az.js} +1 -1
- package/dist/shared/{library-z7qsdq88.js → library-krajvnj9.js} +1 -1
- package/dist/shared/{library-f3be6g03.js → library-y9tt30y1.js} +1 -1
- package/dist/ui/aaa.html +8 -8
- package/dist/ui/connected-devices.html +8 -8
- package/dist/ui/dashboard.html +16 -16
- package/dist/ui/fabric.html +11 -11
- package/dist/ui/firewall-audit.html +8 -8
- package/dist/ui/firewall.html +9 -9
- package/dist/ui/interfaces.html +8 -8
- package/dist/ui/investigations.html +11 -11
- package/dist/ui/observability.html +63 -61
- package/dist/ui/operations.html +11 -11
- package/dist/ui/records.html +12 -12
- package/dist/ui/reports.html +11 -11
- package/dist/ui/round-trip.html +11 -11
- package/dist/ui/service-health.html +11 -11
- package/package.json +22 -22
- package/prompts/audit-routeros-containers.md +27 -0
- package/prompts/audit-vlan-segmentation.md +31 -0
- package/prompts/setup-guest-wifi.md +23 -24
- package/prompts/setup-routeros-container.md +36 -0
- package/prompts/setup-v2ray-container-proxy.md +68 -194
- package/prompts/setup-vlan-network.md +27 -33
- package/schemas/README.md +1 -1
- package/schemas/devtools-manifest.json +287 -16
- package/schemas/tool-catalog.json +785 -109
- package/schemas/tools/add_container.json +42 -30
- package/schemas/tools/add_container_env.json +3 -4
- package/schemas/tools/add_container_mount.json +10 -4
- package/schemas/tools/apply_service_routing.json +23 -0
- package/schemas/tools/arm_service_routing.json +23 -0
- package/schemas/tools/configure_flight_recorder.json +30 -0
- package/schemas/tools/create_service_routing.json +78 -0
- package/schemas/tools/design_network_segment.json +22 -6
- package/schemas/tools/destroy_recovery_lab.json +18 -0
- package/schemas/tools/export_network_incident.json +14 -0
- package/schemas/tools/freeze_network_incident.json +14 -0
- package/schemas/tools/get_container.json +11 -4
- package/schemas/tools/get_flight_recorder.json +7 -0
- package/schemas/tools/get_recovery_lab.json +7 -0
- package/schemas/tools/get_routeros_container_guide.json +22 -0
- package/schemas/tools/get_vlan_segmentation_guide.json +14 -0
- package/schemas/tools/list_container_envs.json +1 -1
- package/schemas/tools/list_container_mounts.json +7 -2
- package/schemas/tools/list_containers.json +2 -4
- package/schemas/tools/list_service_routing.json +7 -0
- package/schemas/tools/poll_recovery_lab.json +14 -0
- package/schemas/tools/prepare_recovery_lab.json +23 -0
- package/schemas/tools/preview_service_routing.json +23 -0
- package/schemas/tools/probe_service_routing.json +14 -0
- package/schemas/tools/recovery_lab_inventory.json +7 -0
- package/schemas/tools/remove_container.json +11 -4
- package/schemas/tools/remove_container_env.json +7 -3
- package/schemas/tools/remove_container_mount.json +18 -2
- package/schemas/tools/service_routing_inventory.json +7 -0
- package/schemas/tools/set_container_config.json +4 -6
- package/schemas/tools/start_container.json +11 -4
- package/schemas/tools/start_recovery_lab.json +18 -0
- package/schemas/tools/stop_container.json +11 -4
- package/schemas/tools/update_container.json +46 -6
- /package/dist/shared/{cli-j07tbrke.js → cli-426pkqe9.js} +0 -0
- /package/dist/shared/{cli-y00nwzxx.js → cli-6wdstvdq.js} +0 -0
- /package/dist/shared/{cli-s0rxncz4.js → cli-cvt06346.js} +0 -0
- /package/dist/shared/{cli-gtq5bw8q.js → cli-z1kavk0z.js} +0 -0
package/dist/cli.js
CHANGED
|
@@ -15627,6 +15627,27 @@ async function openSnapshotStore2(path) {
|
|
|
15627
15627
|
|
|
15628
15628
|
// src/logger.ts
|
|
15629
15629
|
import { stderr } from "process";
|
|
15630
|
+
|
|
15631
|
+
// src/utils/container-redaction.ts
|
|
15632
|
+
function redactContainerText(text) {
|
|
15633
|
+
return text.replace(/^(\s*(?:env(?:-current)?|password|(?:default-)?(?:cmd|entrypoint|shell|healthcheck-cmd)|config-json):)[ \t]*[^\r\n]*/gm, "$1 ***").replace(/(^|\s)(env(?:-current)?|value|password|(?:default-)?(?:cmd|entrypoint|shell|healthcheck-cmd)|config-json)=("(?:\\.|[^"\\])*(?:"|$)|[^\s]*)/g, '$1$2="***"');
|
|
15634
|
+
}
|
|
15635
|
+
function containerCommandForLog(command) {
|
|
15636
|
+
if (!/\/container(?:[\s/]|$)/.test(command))
|
|
15637
|
+
return command;
|
|
15638
|
+
const prefix = command.match(/^\[[^\]\r\n]+\] Executing (?:MikroTik command|\(safe mode\)): /)?.[0] ?? "";
|
|
15639
|
+
return `${prefix}${command.match(/\/container(?:[ /](?:config|envs|mounts))?[ /](?:[a-z-]+)/)?.[0] ?? "/container"} [arguments omitted]`;
|
|
15640
|
+
}
|
|
15641
|
+
function redactContainerInput(tool, args) {
|
|
15642
|
+
if (!/(?:^|_)container(?:_|$)/.test(tool) || !args || typeof args !== "object" || Array.isArray(args))
|
|
15643
|
+
return args;
|
|
15644
|
+
return Object.fromEntries(Object.entries(args).map(([key, value]) => [
|
|
15645
|
+
key,
|
|
15646
|
+
["env", "value", "cmd", "entrypoint", "password"].includes(key) && value != null && value !== "" ? "\xABredacted\xBB" : value
|
|
15647
|
+
]));
|
|
15648
|
+
}
|
|
15649
|
+
|
|
15650
|
+
// src/logger.ts
|
|
15630
15651
|
var LEVELS = {
|
|
15631
15652
|
debug: 10,
|
|
15632
15653
|
info: 20,
|
|
@@ -15644,7 +15665,7 @@ var COLORS = {
|
|
|
15644
15665
|
var RESET = "\x1B[0m";
|
|
15645
15666
|
var useColor = stderr.isTTY ?? false;
|
|
15646
15667
|
function formatLogMessage(message) {
|
|
15647
|
-
const compact = message.replace(/\bfrom=\*[\da-f]+(?:,\*[\da-f]+)+/gi, (list) => `from=<${list.split(",").length} IDs omitted>`);
|
|
15668
|
+
const compact = containerCommandForLog(message).replace(/\bfrom=\*[\da-f]+(?:,\*[\da-f]+)+/gi, (list) => `from=<${list.split(",").length} IDs omitted>`);
|
|
15648
15669
|
const maxLength = 1024;
|
|
15649
15670
|
return compact.length <= maxLength ? compact : `${compact.slice(0, maxLength)}\u2026 [${compact.length - maxLength} chars omitted]`;
|
|
15650
15671
|
}
|
|
@@ -17882,7 +17903,7 @@ function buildPrint(path, rest) {
|
|
|
17882
17903
|
const [k, v] = pair;
|
|
17883
17904
|
if (/[~<>!]/.test(k))
|
|
17884
17905
|
return null;
|
|
17885
|
-
query[k] = v;
|
|
17906
|
+
query[k === "proplist" ? ".proplist" : k] = v;
|
|
17886
17907
|
}
|
|
17887
17908
|
return { method: "GET", path, query, countOnly };
|
|
17888
17909
|
}
|
|
@@ -18704,11 +18725,11 @@ async function executeMikrotikCommand(command, ctx, opts) {
|
|
|
18704
18725
|
const deviceName = resolveDeviceName(ctx.device);
|
|
18705
18726
|
const safe = getSafeModeManager(deviceName);
|
|
18706
18727
|
if (safe.isActive) {
|
|
18707
|
-
ctx.info(`[${deviceName}] Executing (safe mode): ${command}`);
|
|
18728
|
+
ctx.info(`[${deviceName}] Executing (safe mode): ${containerCommandForLog(command)}`);
|
|
18708
18729
|
ctx.transport = "ssh";
|
|
18709
18730
|
return safe.execute(command);
|
|
18710
18731
|
}
|
|
18711
|
-
ctx.info(`[${deviceName}] Executing MikroTik command: ${command}`);
|
|
18732
|
+
ctx.info(`[${deviceName}] Executing MikroTik command: ${containerCommandForLog(command)}`);
|
|
18712
18733
|
return runOnce(command, ctx.device, opts, ctx);
|
|
18713
18734
|
}
|
|
18714
18735
|
async function uploadFileToDevice(deviceName, remotePath, data) {
|
|
@@ -18936,7 +18957,7 @@ function buildEvent(raw, id, opts) {
|
|
|
18936
18957
|
let output = "";
|
|
18937
18958
|
let truncated = false;
|
|
18938
18959
|
if (opts.captureBody) {
|
|
18939
|
-
const args = opts.redactInput === false ? raw.args : redact(raw.args);
|
|
18960
|
+
const args = opts.redactInput === false ? raw.args : redact(redactContainerInput(raw.tool, raw.args));
|
|
18940
18961
|
const rin = truncate(JSON.stringify(args ?? {}), opts.maxBodyBytes);
|
|
18941
18962
|
const rout = truncate(raw.tool === "create_client_check" ? "Client check created. Private invitation omitted from activity history." : raw.output, opts.maxBodyBytes);
|
|
18942
18963
|
input = rin.text;
|
|
@@ -21871,13 +21892,13 @@ async function undoMigration(id, confirm, selected) {
|
|
|
21871
21892
|
throw new Error("Undo lost Safe Mode or exceeded its time budget.");
|
|
21872
21893
|
await checkedRead(item.undo, createContext(undefined, device));
|
|
21873
21894
|
}
|
|
21874
|
-
const beforeTarget = (await import("./shared/cli-
|
|
21875
|
-
const db = await beforeTarget((await import("./shared/cli-
|
|
21895
|
+
const beforeTarget = (await import("./shared/cli-cvt06346.js")).openSnapshotStore;
|
|
21896
|
+
const db = await beforeTarget((await import("./shared/cli-426pkqe9.js")).DEFAULT_SNAPSHOT_DB);
|
|
21876
21897
|
try {
|
|
21877
21898
|
const original = db.get(p.snapshots.target);
|
|
21878
21899
|
if (!original)
|
|
21879
21900
|
throw new Error("Original target snapshot unavailable.");
|
|
21880
|
-
const { normalizeExport } = await import("./shared/cli-
|
|
21901
|
+
const { normalizeExport } = await import("./shared/cli-z1kavk0z.js");
|
|
21881
21902
|
if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
|
|
21882
21903
|
throw new Error("Target differs from its backup. Undo verification failed.");
|
|
21883
21904
|
} finally {
|
|
@@ -26873,6 +26894,1383 @@ var serviceContractTools = [
|
|
|
26873
26894
|
})
|
|
26874
26895
|
];
|
|
26875
26896
|
|
|
26897
|
+
// src/service-routing/model.ts
|
|
26898
|
+
import ipaddr2 from "ipaddr.js";
|
|
26899
|
+
import { createHash as createHash5 } from "crypto";
|
|
26900
|
+
var name2 = string2().trim().min(1).max(64).regex(/^[a-zA-Z0-9_.-]+$/);
|
|
26901
|
+
var routingInput = object({
|
|
26902
|
+
name: string2().trim().min(1).max(80),
|
|
26903
|
+
target: name2.describe("Approved HTTPS alias in serviceProbes.targets; its exact hostname is routed"),
|
|
26904
|
+
family: _enum(["ipv4", "ipv6"]),
|
|
26905
|
+
sources: array(string2().refine((v) => ipaddr2.isValidCIDR(v), "Use an explicit client subnet CIDR")).min(1).max(8),
|
|
26906
|
+
tables: array(name2).min(1).max(3),
|
|
26907
|
+
primary: name2,
|
|
26908
|
+
maxLatencyMs: number2().int().min(100).max(15000).default(5000),
|
|
26909
|
+
failuresBeforeSwitch: number2().int().min(2).max(10).default(3),
|
|
26910
|
+
cooldownSeconds: number2().int().min(120).max(3600).default(300)
|
|
26911
|
+
}).superRefine((v, ctx) => {
|
|
26912
|
+
if (!v.tables.includes(v.primary) || new Set(v.tables).size !== v.tables.length)
|
|
26913
|
+
ctx.addIssue({ code: "custom", message: "Choose one unique candidate table as primary" });
|
|
26914
|
+
for (const s of v.sources) {
|
|
26915
|
+
const [ip, bits] = ipaddr2.parseCIDR(s);
|
|
26916
|
+
if (ip.kind() !== v.family || bits === 0)
|
|
26917
|
+
ctx.addIssue({
|
|
26918
|
+
code: "custom",
|
|
26919
|
+
message: "Sources must match the selected IP family and cannot be a default route"
|
|
26920
|
+
});
|
|
26921
|
+
}
|
|
26922
|
+
});
|
|
26923
|
+
var enabled3 = (r) => !["yes", "true"].includes(r.disabled) && !(r.flags ?? "").includes("X");
|
|
26924
|
+
var ownerTag = (id) => `mcp-sr-${id}`;
|
|
26925
|
+
var selector = (tag) => `[find where comment=${quoteValue(tag)}]`;
|
|
26926
|
+
var routingPath = (family) => family === "ipv4" ? "/ip firewall" : "/ipv6 firewall";
|
|
26927
|
+
function fingerprint(facts) {
|
|
26928
|
+
return createHash5("sha256").update(JSON.stringify(facts, (key, value) => ["#", ".id", "bytes", "packets", "last-handshake", "expires-after"].includes(key) ? undefined : value)).digest("hex");
|
|
26929
|
+
}
|
|
26930
|
+
function planCommands(policy, table, facts, remove = false) {
|
|
26931
|
+
const path = routingPath(policy.family), tag = ownerTag(policy.id), chain = `sr-${policy.id.slice(0, 12)}`;
|
|
26932
|
+
if (policy.state === "uncertain")
|
|
26933
|
+
throw new Error("Reconcile uncertain router state before another change.");
|
|
26934
|
+
const owned = facts.mangle.filter((r) => r.comment === tag);
|
|
26935
|
+
if (facts.mangle.some((r) => r.chain === chain && r.comment !== tag))
|
|
26936
|
+
throw new Error("Private chain contains foreign rules; review it first.");
|
|
26937
|
+
if (owned.some((r) => r.chain !== chain && r.chain !== "prerouting"))
|
|
26938
|
+
throw new Error("Owned rules were edited externally; review them first.");
|
|
26939
|
+
if (remove)
|
|
26940
|
+
return [
|
|
26941
|
+
new Cmd(`${path} mangle remove ${selector(tag)}`).build(),
|
|
26942
|
+
new Cmd(`${path} address-list remove ${selector(tag)}`).build()
|
|
26943
|
+
];
|
|
26944
|
+
const listRows = facts.addresses.filter((r) => [`${tag}-src`, `${tag}-dst`].includes(r.list));
|
|
26945
|
+
const staticRows = listRows.filter((r) => !["yes", "true"].includes(r.dynamic) && !(r.flags ?? "").includes("D"));
|
|
26946
|
+
if (owned.length) {
|
|
26947
|
+
const expectedLists = [
|
|
26948
|
+
...policy.sources.map((address) => ({ list: `${tag}-src`, address })),
|
|
26949
|
+
{ list: `${tag}-dst`, address: policy.host }
|
|
26950
|
+
];
|
|
26951
|
+
if (staticRows.length !== expectedLists.length || expectedLists.some((e) => !staticRows.some((r) => r.list === e.list && r.address === e.address && r.comment === tag && enabled3(r))))
|
|
26952
|
+
throw new Error("Owned address-list scope changed externally.");
|
|
26953
|
+
if (listRows.some((r) => r.list === `${tag}-src` && !staticRows.includes(r)))
|
|
26954
|
+
throw new Error("Unexpected dynamic source scope.");
|
|
26955
|
+
} else if (policy.state === "active" || listRows.length) {
|
|
26956
|
+
throw new Error("Owned policy is missing or partially present; reconcile first.");
|
|
26957
|
+
}
|
|
26958
|
+
if (!policy.tables.includes(table))
|
|
26959
|
+
throw new Error("This exit is not approved by the policy.");
|
|
26960
|
+
if (!facts.tables.some((r) => r.name === table && enabled3(r) && ["yes", "true"].includes(r.fib)))
|
|
26961
|
+
throw new Error("Exit needs an existing enabled FIB table.");
|
|
26962
|
+
const dst = policy.family === "ipv4" ? "0.0.0.0/0" : "::/0";
|
|
26963
|
+
if (!facts.routes.some((r) => r["routing-table"] === table && r["dst-address"] === dst && enabled3(r) && (["yes", "true"].includes(r.active) || (r.flags ?? "").includes("A"))))
|
|
26964
|
+
throw new Error("Exit has no observed active default route for this family.");
|
|
26965
|
+
if (facts.filters.some((r) => enabled3(r) && r.action === "fasttrack-connection"))
|
|
26966
|
+
throw new Error("FastTrack may bypass this policy. Configure an explicit exclusion before applying.");
|
|
26967
|
+
if (facts.mangle.some((r) => enabled3(r) && r.comment !== tag && ["mark-routing", "jump", "route"].includes(r.action)))
|
|
26968
|
+
throw new Error("Existing routing/jump rules need an administrator conflict review. They will not be overridden.");
|
|
26969
|
+
const result = [];
|
|
26970
|
+
if (owned.length) {
|
|
26971
|
+
if (policy.state !== "active" || !policy.activeTable)
|
|
26972
|
+
throw new Error("Unexpected owned rules exist. Reconcile the router before applying a draft.");
|
|
26973
|
+
const expected = planCommands({ ...policy, state: "draft" }, policy.activeTable, {
|
|
26974
|
+
...facts,
|
|
26975
|
+
mangle: facts.mangle.filter((r) => r.comment !== tag),
|
|
26976
|
+
addresses: facts.addresses.filter((r) => ![`${tag}-src`, `${tag}-dst`].includes(r.list))
|
|
26977
|
+
}).filter((command) => command.startsWith(`${path} mangle add`)).map((command) => parseRecords(`0 ${command}`).rows[0]);
|
|
26978
|
+
if (owned.length !== expected.length || expected.some((e) => !e || !owned.some((r) => Object.entries(e).filter(([key]) => !["place-before", "#"].includes(key)).every(([key, value]) => r[key] === value) && enabled3(r))))
|
|
26979
|
+
throw new Error("Owned rule scope changed externally. Automatic edits are blocked.");
|
|
26980
|
+
if (owned.filter((r) => r.action === "mark-routing").length !== 1)
|
|
26981
|
+
throw new Error("Owned routing mark is missing or ambiguous.");
|
|
26982
|
+
result.push(new Cmd(`${path} mangle set [find where comment=${quoteValue(tag)} action=mark-routing]`).set("new-routing-mark", table).build());
|
|
26983
|
+
return result;
|
|
26984
|
+
}
|
|
26985
|
+
for (const address of policy.sources)
|
|
26986
|
+
result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-src`).set("address", address).set("comment", tag).build());
|
|
26987
|
+
result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-dst`).set("address", policy.host).set("comment", tag).build());
|
|
26988
|
+
const exclude = policy.family === "ipv4" ? [
|
|
26989
|
+
"0.0.0.0/8",
|
|
26990
|
+
"10.0.0.0/8",
|
|
26991
|
+
"100.64.0.0/10",
|
|
26992
|
+
"127.0.0.0/8",
|
|
26993
|
+
"169.254.0.0/16",
|
|
26994
|
+
"172.16.0.0/12",
|
|
26995
|
+
"192.168.0.0/16",
|
|
26996
|
+
"224.0.0.0/3"
|
|
26997
|
+
] : ["::/128", "::1/128", "::ffff:0:0/96", "fc00::/7", "fe80::/10", "ff00::/8"];
|
|
26998
|
+
for (const subnet of exclude)
|
|
26999
|
+
result.push(new Cmd(`${path} mangle add`).set("chain", chain).set("dst-address", subnet).set("action", "return").set("comment", tag).build());
|
|
27000
|
+
result.push(new Cmd(`${path} mangle add`).set("chain", chain).set("action", "mark-routing").set("new-routing-mark", table).bool("passthrough", false).set("comment", tag).build());
|
|
27001
|
+
result.push(new Cmd(`${path} mangle add`).set("chain", "prerouting").set("src-address-list", `${tag}-src`).set("dst-address-list", `${tag}-dst`).set("dst-address-type", "!local").set("action", "jump").set("jump-target", chain).set("comment", tag).raw(facts.mangle.length ? "place-before=0" : "").build());
|
|
27002
|
+
return result;
|
|
27003
|
+
}
|
|
27004
|
+
function chooseExit(policy, now) {
|
|
27005
|
+
if (policy.state !== "active" || !policy.activeTable || (policy.armedUntil ?? 0) <= now || now - (policy.lastSwitchAt ?? 0) < policy.cooldownSeconds * 1000)
|
|
27006
|
+
return;
|
|
27007
|
+
const recent = (table) => policy.samples.filter((s) => s.table === table && s.at <= now && now - s.at < 180000).sort((a, b) => b.at - a.at);
|
|
27008
|
+
const active = recent(policy.activeTable).slice(0, policy.failuresBeforeSwitch);
|
|
27009
|
+
if (active.length < policy.failuresBeforeSwitch || active.some((s) => s.state !== "fail"))
|
|
27010
|
+
return;
|
|
27011
|
+
return [policy.primary, ...policy.tables.filter((t) => t !== policy.primary)].find((table) => table !== policy.activeTable && recent(table).slice(0, 2).length === 2 && recent(table).slice(0, 2).every((s) => s.state === "pass"));
|
|
27012
|
+
}
|
|
27013
|
+
|
|
27014
|
+
// src/service-routing/service.ts
|
|
27015
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
27016
|
+
import { isIP as isIP4 } from "net";
|
|
27017
|
+
|
|
27018
|
+
// src/operations/store.ts
|
|
27019
|
+
import { mkdirSync as mkdirSync9, chmodSync } from "fs";
|
|
27020
|
+
import { dirname as dirname9, join as join2 } from "path";
|
|
27021
|
+
class OperationsStore {
|
|
27022
|
+
db;
|
|
27023
|
+
constructor(db) {
|
|
27024
|
+
this.db = db;
|
|
27025
|
+
db.run("PRAGMA busy_timeout = 3000");
|
|
27026
|
+
db.run("CREATE TABLE IF NOT EXISTS workspace_records (kind TEXT, id TEXT, device TEXT, updated INTEGER, body TEXT, PRIMARY KEY(kind,id))");
|
|
27027
|
+
db.run("CREATE INDEX IF NOT EXISTS workspace_device ON workspace_records(kind,device,updated DESC)");
|
|
27028
|
+
db.run("CREATE TABLE IF NOT EXISTS workspace_locks (device TEXT PRIMARY KEY, owner TEXT NOT NULL)");
|
|
27029
|
+
}
|
|
27030
|
+
get(kind, id, device) {
|
|
27031
|
+
const row = this.db.query("SELECT body FROM workspace_records WHERE kind=? AND id=? AND device=?").get(kind, id, device);
|
|
27032
|
+
return row ? JSON.parse(row.body) : undefined;
|
|
27033
|
+
}
|
|
27034
|
+
list(kind, device, limit = 100) {
|
|
27035
|
+
return this.db.query("SELECT body FROM workspace_records WHERE kind=? AND device=? ORDER BY updated DESC LIMIT ?").all(kind, device, Math.min(500, limit)).map((r) => JSON.parse(r.body));
|
|
27036
|
+
}
|
|
27037
|
+
put(kind, record) {
|
|
27038
|
+
this.db.query("INSERT INTO workspace_records VALUES (?,?,?,?,?) ON CONFLICT(kind,id) DO UPDATE SET updated=excluded.updated,body=excluded.body WHERE device=excluded.device").run(kind, record.id, record.device, record.updatedAt, JSON.stringify(record));
|
|
27039
|
+
}
|
|
27040
|
+
delete(kind, id, device) {
|
|
27041
|
+
this.db.query("DELETE FROM workspace_records WHERE kind=? AND id=? AND device=?").run(kind, id, device);
|
|
27042
|
+
}
|
|
27043
|
+
prune(kind, device, before) {
|
|
27044
|
+
this.db.query("DELETE FROM workspace_records WHERE kind=? AND device=? AND updated<?").run(kind, device, before);
|
|
27045
|
+
}
|
|
27046
|
+
lock(device, owner) {
|
|
27047
|
+
const result = this.db.query("INSERT OR IGNORE INTO workspace_locks VALUES (?,?)").run(device, owner);
|
|
27048
|
+
if (!result.changes)
|
|
27049
|
+
throw new Error("Another workspace operation holds this router. An interrupted operation requires reconciliation before retrying.");
|
|
27050
|
+
}
|
|
27051
|
+
unlock(device, owner) {
|
|
27052
|
+
this.db.query("DELETE FROM workspace_locks WHERE device=? AND owner=?").run(device, owner);
|
|
27053
|
+
}
|
|
27054
|
+
}
|
|
27055
|
+
var pending5;
|
|
27056
|
+
function operationsStore() {
|
|
27057
|
+
pending5 ??= (async () => {
|
|
27058
|
+
const path = join2(dirname9(DEFAULT_SNAPSHOT_DB2), "operations.db");
|
|
27059
|
+
mkdirSync9(dirname9(path), { recursive: true, mode: 448 });
|
|
27060
|
+
const { Database } = await import("bun:sqlite");
|
|
27061
|
+
const db = new Database(path, { create: true });
|
|
27062
|
+
chmodSync(path, 384);
|
|
27063
|
+
db.run("PRAGMA journal_mode = WAL");
|
|
27064
|
+
return new OperationsStore(db);
|
|
27065
|
+
})().catch((error) => {
|
|
27066
|
+
pending5 = undefined;
|
|
27067
|
+
throw error;
|
|
27068
|
+
});
|
|
27069
|
+
return pending5;
|
|
27070
|
+
}
|
|
27071
|
+
|
|
27072
|
+
// src/service-routing/service.ts
|
|
27073
|
+
var kind = "service-routing";
|
|
27074
|
+
function access(ctx, tool, write = false) {
|
|
27075
|
+
const device = resolveDeviceName(ctx.device);
|
|
27076
|
+
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
27077
|
+
return device;
|
|
27078
|
+
}
|
|
27079
|
+
async function locked(device, work) {
|
|
27080
|
+
const store = await operationsStore(), owner = randomUUID8();
|
|
27081
|
+
store.lock(device, owner);
|
|
27082
|
+
try {
|
|
27083
|
+
return await work();
|
|
27084
|
+
} finally {
|
|
27085
|
+
store.unlock(device, owner);
|
|
27086
|
+
}
|
|
27087
|
+
}
|
|
27088
|
+
async function routingPolicy(id, device) {
|
|
27089
|
+
const policy = (await operationsStore()).get(kind, id, device);
|
|
27090
|
+
if (!policy)
|
|
27091
|
+
throw new Error("Policy not found on the selected router.");
|
|
27092
|
+
return policy;
|
|
27093
|
+
}
|
|
27094
|
+
function save(policy, message) {
|
|
27095
|
+
policy.updatedAt = Date.now();
|
|
27096
|
+
if (message)
|
|
27097
|
+
policy.history = [{ at: policy.updatedAt, message }, ...policy.history].slice(0, 100);
|
|
27098
|
+
return operationsStore().then((store) => store.put(kind, policy));
|
|
27099
|
+
}
|
|
27100
|
+
async function routingInventory(ctx) {
|
|
27101
|
+
access(ctx, "service_routing_inventory");
|
|
27102
|
+
const tables = await rows("/routing table", "name,fib,disabled", ctx);
|
|
27103
|
+
return {
|
|
27104
|
+
tables: tables.filter((r) => enabled3(r) && ["yes", "true"].includes(r.fib)).map((r) => r.name),
|
|
27105
|
+
targets: Object.entries(getConfig().serviceProbes.targets).filter(([, t]) => t.kind === "https").map(([alias, t]) => ({ alias, host: t.host }))
|
|
27106
|
+
};
|
|
27107
|
+
}
|
|
27108
|
+
async function listRouting(ctx) {
|
|
27109
|
+
const device = access(ctx, "list_service_routing");
|
|
27110
|
+
return { policies: (await operationsStore()).list(kind, device) };
|
|
27111
|
+
}
|
|
27112
|
+
async function createRouting(input, ctx) {
|
|
27113
|
+
const device = access(ctx, "create_service_routing", true), a = routingInput.parse(input);
|
|
27114
|
+
const target = getConfig().serviceProbes.targets[a.target];
|
|
27115
|
+
if (!target || target.kind !== "https")
|
|
27116
|
+
throw new Error("Select an administrator-approved HTTPS probe alias first.");
|
|
27117
|
+
const store = await operationsStore();
|
|
27118
|
+
if (store.list(kind, device).length >= 100)
|
|
27119
|
+
throw new Error("Router policy limit reached (100).");
|
|
27120
|
+
const policy = {
|
|
27121
|
+
...a,
|
|
27122
|
+
id: randomUUID8(),
|
|
27123
|
+
device,
|
|
27124
|
+
host: target.host,
|
|
27125
|
+
updatedAt: Date.now(),
|
|
27126
|
+
state: "draft",
|
|
27127
|
+
samples: [],
|
|
27128
|
+
history: []
|
|
27129
|
+
};
|
|
27130
|
+
await save(policy, "Draft saved. No router changes or probes yet.");
|
|
27131
|
+
return policy;
|
|
27132
|
+
}
|
|
27133
|
+
async function facts(policy, ctx) {
|
|
27134
|
+
const base = routingPath(policy.family);
|
|
27135
|
+
const tables = await rows("/routing table", "name,fib,disabled", ctx);
|
|
27136
|
+
const routes = await rows(policy.family === "ipv4" ? "/ip route" : "/ipv6 route", "routing-table,dst-address,gateway,active,disabled", ctx);
|
|
27137
|
+
const mangle = await rows(`${base} mangle`, "chain,action,new-routing-mark,jump-target,src-address-list,dst-address-list,dst-address-type,dst-address,passthrough,disabled,comment", ctx);
|
|
27138
|
+
const filters = await rows(`${base} filter`, "action,disabled", ctx);
|
|
27139
|
+
if (policy.family === "ipv4") {
|
|
27140
|
+
const active = (await checkedRead("/ip firewall connection print count-only where fasttrack=yes", ctx)).trim();
|
|
27141
|
+
if (!/^\d+$/.test(active) || Number(active) > 0)
|
|
27142
|
+
throw new Error("Active FastTrack connections must drain before routing can be changed.");
|
|
27143
|
+
}
|
|
27144
|
+
const vrfs = await rows("/ip vrf", "name,interfaces,disabled", ctx);
|
|
27145
|
+
const addresses = await rows(`${base} address-list`, "list,address,comment,dynamic,disabled", ctx);
|
|
27146
|
+
return { tables, routes, mangle, filters, vrfs, addresses };
|
|
27147
|
+
}
|
|
27148
|
+
function fetchCommand(address, table, host, path, port) {
|
|
27149
|
+
return `:put [:serialize to=json value=[${new Cmd("/tool fetch").set("address", `${address}@${table}`).set("host", host).set("mode", "https").set("src-path", path).set("port", port).set("http-method", "head").set("check-certificate", "yes").set("http-max-redirect-count", 0).set("idle-timeout", "5s").set("output", "none").flag("as-value", true).build()}]]`;
|
|
27150
|
+
}
|
|
27151
|
+
async function probe(policy, ctx) {
|
|
27152
|
+
const target = getConfig().serviceProbes.targets[policy.target];
|
|
27153
|
+
if (!target || target.kind !== "https" || target.host !== policy.host)
|
|
27154
|
+
throw new Error("Probe approval changed. Create a new policy.");
|
|
27155
|
+
const vrfs = await rows("/ip vrf", "name,disabled", ctx);
|
|
27156
|
+
let addresses = [];
|
|
27157
|
+
try {
|
|
27158
|
+
addresses = await nativeProbeIO.resolve(target.host, 3000);
|
|
27159
|
+
if (addresses.some((a) => !addressAllowed(a, target.addresses)))
|
|
27160
|
+
addresses = [];
|
|
27161
|
+
} catch {}
|
|
27162
|
+
const address = addresses.find((a) => isIP4(a) === (policy.family === "ipv4" ? 4 : 6));
|
|
27163
|
+
for (const table of policy.tables) {
|
|
27164
|
+
const sample = {
|
|
27165
|
+
table,
|
|
27166
|
+
at: Date.now(),
|
|
27167
|
+
state: "unknown",
|
|
27168
|
+
detail: "No approved DNS answer for this IP family."
|
|
27169
|
+
};
|
|
27170
|
+
if (address) {
|
|
27171
|
+
sample.address = address;
|
|
27172
|
+
sample.detail = "This routing table is not a VRF. A table-only HTTPS path cannot be proved by fetch.";
|
|
27173
|
+
if (vrfs.some((v) => v.name === table && enabled3(v))) {
|
|
27174
|
+
const start = Date.now();
|
|
27175
|
+
try {
|
|
27176
|
+
const raw = await executeMikrotikCommand(fetchCommand(address, table, target.host, target.path, target.port), ctx, { maxMs: 8000 });
|
|
27177
|
+
sample.elapsedMs = Date.now() - start;
|
|
27178
|
+
if (looksLikeError(raw)) {
|
|
27179
|
+
if (/failure:.*(?:fetch|SSL|connection|timeout|resolving|status)/i.test(raw)) {
|
|
27180
|
+
sample.state = "fail";
|
|
27181
|
+
sample.detail = "Router fetch reported an HTTP, TLS or connection failure.";
|
|
27182
|
+
} else
|
|
27183
|
+
sample.detail = "Router fetch was rejected or unsupported; path health is unknown.";
|
|
27184
|
+
} else {
|
|
27185
|
+
const result = JSON.parse(raw.trim());
|
|
27186
|
+
if (result.status === "finished" && (result.code === undefined || Number(result.code) >= 200 && Number(result.code) < 300)) {
|
|
27187
|
+
sample.state = sample.elapsedMs <= policy.maxLatencyMs ? "pass" : "fail";
|
|
27188
|
+
sample.detail = `HTTPS HEAD completed via VRF ${table}; elapsed includes SSH overhead. Not a client-path or throughput test.`;
|
|
27189
|
+
}
|
|
27190
|
+
}
|
|
27191
|
+
} catch {
|
|
27192
|
+
sample.detail = "Router query did not produce verified fetch evidence. Connection or capability may be unavailable.";
|
|
27193
|
+
}
|
|
27194
|
+
}
|
|
27195
|
+
}
|
|
27196
|
+
policy.samples.push(sample);
|
|
27197
|
+
}
|
|
27198
|
+
policy.samples = policy.samples.slice(-180);
|
|
27199
|
+
await save(policy);
|
|
27200
|
+
}
|
|
27201
|
+
async function probeRouting(id, ctx) {
|
|
27202
|
+
const device = access(ctx, "probe_service_routing");
|
|
27203
|
+
return locked(device, async () => {
|
|
27204
|
+
const policy = await routingPolicy(id, device);
|
|
27205
|
+
await probe(policy, ctx);
|
|
27206
|
+
return policy;
|
|
27207
|
+
});
|
|
27208
|
+
}
|
|
27209
|
+
async function preview(policy, table, remove, ctx) {
|
|
27210
|
+
const snapshot = await facts(policy, ctx);
|
|
27211
|
+
policy.plan = {
|
|
27212
|
+
id: randomUUID8(),
|
|
27213
|
+
table,
|
|
27214
|
+
remove,
|
|
27215
|
+
expiresAt: Date.now() + 120000,
|
|
27216
|
+
fingerprint: fingerprint(snapshot),
|
|
27217
|
+
commands: planCommands(policy, table, snapshot, remove)
|
|
27218
|
+
};
|
|
27219
|
+
await save(policy, "Preview created. Review scope and commands; valid for two minutes.");
|
|
27220
|
+
return policy;
|
|
27221
|
+
}
|
|
27222
|
+
async function previewRouting(id, table, remove, ctx) {
|
|
27223
|
+
const device = access(ctx, "preview_service_routing");
|
|
27224
|
+
return locked(device, async () => preview(await routingPolicy(id, device), table, remove, ctx));
|
|
27225
|
+
}
|
|
27226
|
+
async function apply(policy, planId, ctx) {
|
|
27227
|
+
const plan = policy.plan;
|
|
27228
|
+
if (!plan || plan.id !== planId || plan.expiresAt < Date.now())
|
|
27229
|
+
throw new Error("Preview expired or changed. Preview again before confirming.");
|
|
27230
|
+
access(ctx, "apply_service_routing", true);
|
|
27231
|
+
if (fingerprint(await facts(policy, ctx)) !== plan.fingerprint)
|
|
27232
|
+
throw new Error("Router configuration changed after preview.");
|
|
27233
|
+
const safe = getSafeModeManager(policy.device);
|
|
27234
|
+
if (safe.isActive)
|
|
27235
|
+
throw new Error("Finish the existing Safe Mode session first.");
|
|
27236
|
+
policy.snapshot = await captureSnapshot(ctx, `Before service route ${policy.name}`, true);
|
|
27237
|
+
policy.state = "uncertain";
|
|
27238
|
+
policy.armedUntil = undefined;
|
|
27239
|
+
await save(policy, "Apply started; outcome must be read back before being considered active.");
|
|
27240
|
+
let owned = false, commitAttempted = false;
|
|
27241
|
+
try {
|
|
27242
|
+
if (!(await safe.enable()).startsWith("Safe mode ENABLED"))
|
|
27243
|
+
throw new Error("Could not acquire Safe Mode.");
|
|
27244
|
+
owned = true;
|
|
27245
|
+
if (fingerprint(await facts(policy, ctx)) !== plan.fingerprint)
|
|
27246
|
+
throw new Error("Router changed while entering Safe Mode.");
|
|
27247
|
+
for (const command of plan.commands)
|
|
27248
|
+
await checkedRead(command, ctx);
|
|
27249
|
+
const after = await facts(policy, ctx);
|
|
27250
|
+
const matched = after.mangle.filter((r) => r.comment === ownerTag(policy.id));
|
|
27251
|
+
if (plan.remove ? matched.length !== 0 : matched.filter((r) => r.action === "mark-routing" && r["new-routing-mark"] === plan.table && enabled3(r)).length !== 1)
|
|
27252
|
+
throw new Error("Router read-back did not match this preview.");
|
|
27253
|
+
if (plan.remove) {
|
|
27254
|
+
if (after.addresses.some((r) => r.comment === ownerTag(policy.id)))
|
|
27255
|
+
throw new Error("Owned address-list removal not confirmed.");
|
|
27256
|
+
} else {
|
|
27257
|
+
planCommands({ ...policy, state: "active", activeTable: plan.table }, plan.table, after);
|
|
27258
|
+
}
|
|
27259
|
+
await checkedRead("/system identity print", ctx);
|
|
27260
|
+
commitAttempted = true;
|
|
27261
|
+
if (!(await safe.commit()).ok)
|
|
27262
|
+
throw new Error("Commit outcome uncertain. Do not replay the change.");
|
|
27263
|
+
owned = false;
|
|
27264
|
+
policy.state = plan.remove ? "removed" : "active";
|
|
27265
|
+
policy.activeTable = plan.remove ? undefined : plan.table;
|
|
27266
|
+
policy.lastSwitchAt = Date.now();
|
|
27267
|
+
policy.plan = undefined;
|
|
27268
|
+
policy.error = undefined;
|
|
27269
|
+
await save(policy, plan.remove ? "Owned routing policy removed." : `Routing read-back verified: ${plan.table}. Client delivery still requires a client check.`);
|
|
27270
|
+
} catch (error) {
|
|
27271
|
+
if (owned && !commitAttempted)
|
|
27272
|
+
await safe.rollback().catch(() => {});
|
|
27273
|
+
policy.error = error instanceof Error ? error.message : "Apply failed";
|
|
27274
|
+
await save(policy, "Apply not confirmed; automation stopped. Inspect the saved backup and router state.");
|
|
27275
|
+
throw error;
|
|
27276
|
+
}
|
|
27277
|
+
return policy;
|
|
27278
|
+
}
|
|
27279
|
+
async function applyRouting(id, planId, confirm, ctx) {
|
|
27280
|
+
const device = access(ctx, "apply_service_routing", true);
|
|
27281
|
+
if (!confirm)
|
|
27282
|
+
throw new Error("Explicit confirmation of the exact preview is required.");
|
|
27283
|
+
return locked(device, async () => apply(await routingPolicy(id, device), planId, ctx));
|
|
27284
|
+
}
|
|
27285
|
+
async function armRouting(id, minutes, confirm, ctx) {
|
|
27286
|
+
const device = access(ctx, "arm_service_routing", true);
|
|
27287
|
+
if (!confirm)
|
|
27288
|
+
throw new Error("Confirm the time-limited automatic failover authorization.");
|
|
27289
|
+
if (!Number.isInteger(minutes) || minutes < 0 || minutes > 60)
|
|
27290
|
+
throw new Error("Authorization must be 0\u201360 minutes.");
|
|
27291
|
+
return locked(device, async () => {
|
|
27292
|
+
const policy = await routingPolicy(id, device);
|
|
27293
|
+
if (minutes) {
|
|
27294
|
+
const other = (await operationsStore()).list(kind, device).some((p) => p.id !== id && (p.armedUntil ?? 0) > Date.now());
|
|
27295
|
+
if (other)
|
|
27296
|
+
throw new Error("Only one automatic service policy per router can be armed at a time.");
|
|
27297
|
+
if (policy.state !== "active" || policy.tables.length < 2)
|
|
27298
|
+
throw new Error("Apply a policy with at least two exits first.");
|
|
27299
|
+
const now = Date.now();
|
|
27300
|
+
if (policy.tables.some((t) => !policy.samples.some((s) => s.table === t && s.state === "pass" && now - s.at < 120000)))
|
|
27301
|
+
throw new Error("Every authorized exit needs a fresh passing VRF probe before arming.");
|
|
27302
|
+
}
|
|
27303
|
+
policy.armedUntil = minutes ? Date.now() + minutes * 60000 : undefined;
|
|
27304
|
+
await save(policy, minutes ? `Automatic failover authorized for ${minutes} minutes, only between the saved exits.` : "Automatic failover paused; the current route stays in place.");
|
|
27305
|
+
return policy;
|
|
27306
|
+
});
|
|
27307
|
+
}
|
|
27308
|
+
var timer;
|
|
27309
|
+
var ticking = false;
|
|
27310
|
+
function startRoutingMonitor() {
|
|
27311
|
+
if (timer)
|
|
27312
|
+
return;
|
|
27313
|
+
timer = setInterval(() => {
|
|
27314
|
+
routingTick().catch(() => {});
|
|
27315
|
+
}, 30000);
|
|
27316
|
+
timer.unref();
|
|
27317
|
+
}
|
|
27318
|
+
function stopRoutingMonitor() {
|
|
27319
|
+
if (timer)
|
|
27320
|
+
clearInterval(timer);
|
|
27321
|
+
timer = undefined;
|
|
27322
|
+
}
|
|
27323
|
+
async function routingTick() {
|
|
27324
|
+
if (ticking)
|
|
27325
|
+
return;
|
|
27326
|
+
ticking = true;
|
|
27327
|
+
try {
|
|
27328
|
+
const store = await operationsStore();
|
|
27329
|
+
for (const device of Object.keys(getConfig().devices)) {
|
|
27330
|
+
for (const saved of store.list(kind, device).filter((p) => (p.armedUntil ?? 0) > Date.now())) {
|
|
27331
|
+
try {
|
|
27332
|
+
const ctx = createContext(undefined, device);
|
|
27333
|
+
access(ctx, "arm_service_routing", true);
|
|
27334
|
+
access(ctx, "probe_service_routing");
|
|
27335
|
+
access(ctx, "apply_service_routing", true);
|
|
27336
|
+
await locked(device, async () => {
|
|
27337
|
+
const policy = await routingPolicy(saved.id, device), until = policy.armedUntil;
|
|
27338
|
+
if ((until ?? 0) <= Date.now())
|
|
27339
|
+
return;
|
|
27340
|
+
await probe(policy, ctx);
|
|
27341
|
+
const next = chooseExit(policy, Date.now());
|
|
27342
|
+
if (!next)
|
|
27343
|
+
return;
|
|
27344
|
+
await preview(policy, next, false, ctx);
|
|
27345
|
+
if ((until ?? 0) <= Date.now())
|
|
27346
|
+
return;
|
|
27347
|
+
await apply(policy, policy.plan.id, ctx);
|
|
27348
|
+
policy.armedUntil = until;
|
|
27349
|
+
await save(policy, "Automatic failover completed within the saved authorization.");
|
|
27350
|
+
});
|
|
27351
|
+
} catch {}
|
|
27352
|
+
}
|
|
27353
|
+
}
|
|
27354
|
+
} finally {
|
|
27355
|
+
ticking = false;
|
|
27356
|
+
}
|
|
27357
|
+
}
|
|
27358
|
+
|
|
27359
|
+
// src/tools/service-routing.ts
|
|
27360
|
+
var serviceRoutingTools = [
|
|
27361
|
+
defineTool({
|
|
27362
|
+
name: "list_service_routing",
|
|
27363
|
+
title: "List Service Routing Policies",
|
|
27364
|
+
annotations: READ,
|
|
27365
|
+
description: "Read persistent domain routing policies, path evidence, primary exit, history and authorization expiry for this router. No probes or router changes.",
|
|
27366
|
+
inputSchema: {},
|
|
27367
|
+
async handler(_, ctx) {
|
|
27368
|
+
return JSON.stringify(await listRouting(ctx));
|
|
27369
|
+
}
|
|
27370
|
+
}),
|
|
27371
|
+
defineTool({
|
|
27372
|
+
name: "service_routing_inventory",
|
|
27373
|
+
title: "Discover Service Routing Exits",
|
|
27374
|
+
annotations: READ,
|
|
27375
|
+
description: "Read enabled FIB tables and administrator-approved HTTPS target aliases. A table is not proof of a working path; HTTPS per-exit probes require a matching VRF.",
|
|
27376
|
+
inputSchema: {},
|
|
27377
|
+
async handler(_, ctx) {
|
|
27378
|
+
return JSON.stringify(await routingInventory(ctx));
|
|
27379
|
+
}
|
|
27380
|
+
}),
|
|
27381
|
+
defineTool({
|
|
27382
|
+
name: "create_service_routing",
|
|
27383
|
+
title: "Create Service Routing Draft",
|
|
27384
|
+
annotations: WRITE,
|
|
27385
|
+
description: "Save a single-family policy for one approved exact hostname and explicit client subnets. No router changes. Create separate IPv4/IPv6 policies. Shared CDN IPs can affect other services. Preview, then explicitly confirm apply; never infer authorization from a draft.",
|
|
27386
|
+
inputSchema: routingInput.shape,
|
|
27387
|
+
async handler(a, ctx) {
|
|
27388
|
+
return JSON.stringify(await createRouting(a, ctx));
|
|
27389
|
+
}
|
|
27390
|
+
}),
|
|
27391
|
+
defineTool({
|
|
27392
|
+
name: "probe_service_routing",
|
|
27393
|
+
title: "Probe Service Exits",
|
|
27394
|
+
annotations: READ,
|
|
27395
|
+
description: "Run bounded, IP-approved HTTPS HEAD fetches from the router through matching VRFs, certificate validation on, redirects off. No files/bodies stored. Table-only exits remain UNKNOWN. SSH overhead is included; not end-client reachability or throughput proof.",
|
|
27396
|
+
inputSchema: { id: uuid2() },
|
|
27397
|
+
async handler(a, ctx) {
|
|
27398
|
+
return JSON.stringify(await probeRouting(a.id, ctx));
|
|
27399
|
+
}
|
|
27400
|
+
}),
|
|
27401
|
+
defineTool({
|
|
27402
|
+
name: "preview_service_routing",
|
|
27403
|
+
title: "Preview Service Routing Change",
|
|
27404
|
+
annotations: READ,
|
|
27405
|
+
description: "Read router state and save a two-minute, state-bound preview for applying/switching or removing only owned rules. Reject FastTrack and foreign policy-routing conflicts. Does not create exits, NAT, DNS interception or change router configuration.",
|
|
27406
|
+
inputSchema: {
|
|
27407
|
+
id: uuid2(),
|
|
27408
|
+
table: string2().min(1).max(64),
|
|
27409
|
+
remove: boolean2().default(false)
|
|
27410
|
+
},
|
|
27411
|
+
async handler(a, ctx) {
|
|
27412
|
+
return JSON.stringify(await previewRouting(a.id, a.table, a.remove, ctx));
|
|
27413
|
+
}
|
|
27414
|
+
}),
|
|
27415
|
+
defineTool({
|
|
27416
|
+
name: "apply_service_routing",
|
|
27417
|
+
title: "Apply Approved Service Routing Preview",
|
|
27418
|
+
annotations: WRITE,
|
|
27419
|
+
description: "After explicit user confirmation, apply the exact fresh preview with a backup, exclusive Safe Mode and read-back. Router DNS maintains the owned destination list. Does not touch output/input chains. An ambiguous write is never retried; inspect router state. An apply pauses automatic failover.",
|
|
27420
|
+
inputSchema: { id: uuid2(), planId: uuid2(), confirm: boolean2().default(false) },
|
|
27421
|
+
async handler(a, ctx) {
|
|
27422
|
+
return JSON.stringify(await applyRouting(a.id, a.planId, a.confirm, ctx));
|
|
27423
|
+
}
|
|
27424
|
+
}),
|
|
27425
|
+
defineTool({
|
|
27426
|
+
name: "arm_service_routing",
|
|
27427
|
+
title: "Authorize Time-Limited Service Failover",
|
|
27428
|
+
annotations: WRITE,
|
|
27429
|
+
description: "Explicitly authorize automatic switching between saved exits for 1-60 minutes, or pause with 0. Requires fresh passing VRF evidence for every exit, consecutive definite failures and cooldown; UNKNOWN never triggers a switch. Expiry stops automation but retains the current route. No new exits or global policy rewrites.",
|
|
27430
|
+
inputSchema: {
|
|
27431
|
+
id: uuid2(),
|
|
27432
|
+
minutes: number2().int().min(0).max(60),
|
|
27433
|
+
confirm: boolean2().default(false)
|
|
27434
|
+
},
|
|
27435
|
+
async handler(a, ctx) {
|
|
27436
|
+
return JSON.stringify(await armRouting(a.id, a.minutes, a.confirm, ctx));
|
|
27437
|
+
}
|
|
27438
|
+
})
|
|
27439
|
+
];
|
|
27440
|
+
|
|
27441
|
+
// src/flight-recorder/model.ts
|
|
27442
|
+
import { createHash as createHash6 } from "crypto";
|
|
27443
|
+
var recorderInput = object({
|
|
27444
|
+
enabled: boolean2(),
|
|
27445
|
+
intervalSeconds: number2().int().min(30).max(300).default(60),
|
|
27446
|
+
windowMinutes: number2().int().min(15).max(360).default(60),
|
|
27447
|
+
retentionDays: number2().int().min(1).max(30).default(7)
|
|
27448
|
+
});
|
|
27449
|
+
function blankFlight(device, now) {
|
|
27450
|
+
return {
|
|
27451
|
+
id: device,
|
|
27452
|
+
device,
|
|
27453
|
+
updatedAt: now,
|
|
27454
|
+
enabled: false,
|
|
27455
|
+
intervalSeconds: 60,
|
|
27456
|
+
windowMinutes: 60,
|
|
27457
|
+
retentionDays: 7,
|
|
27458
|
+
samples: [],
|
|
27459
|
+
events: [],
|
|
27460
|
+
incidents: [],
|
|
27461
|
+
seenLogs: []
|
|
27462
|
+
};
|
|
27463
|
+
}
|
|
27464
|
+
function logEvidence(row, at) {
|
|
27465
|
+
const message = typeof row.message === "string" ? row.message : "";
|
|
27466
|
+
const topics = Array.isArray(row.topics) ? row.topics.filter((v) => typeof v === "string").join(",") : typeof row.topics === "string" ? row.topics : "unknown";
|
|
27467
|
+
const title = /login failure|authentication failed/i.test(message) ? "Authentication failure reported" : /logged in/i.test(message) ? "Login reported" : /logged out/i.test(message) ? "Logout reported" : /link down|disconnected|terminating/i.test(message) ? "Link or session interruption reported" : /link up|connected/i.test(message) ? "Link or session connection reported" : /changed|added|removed|disabled|enabled/i.test(message) ? "Configuration activity reported" : "Router event observed";
|
|
27468
|
+
return {
|
|
27469
|
+
id: createHash6("sha256").update(JSON.stringify([row[".id"], row.time, row.topics, message])).digest("hex"),
|
|
27470
|
+
at,
|
|
27471
|
+
source: "router-log",
|
|
27472
|
+
title: `${title} \xB7 ${topics.replace(/[^a-zA-Z0-9,.-]/g, "").slice(0, 100)}`,
|
|
27473
|
+
routerTime: typeof row.time === "string" ? row.time.slice(0, 64) : undefined
|
|
27474
|
+
};
|
|
27475
|
+
}
|
|
27476
|
+
function detectFlightIncident(record) {
|
|
27477
|
+
const recent = record.samples.slice(-3), last = recent.at(-1), previous = recent.at(-2);
|
|
27478
|
+
if (!last)
|
|
27479
|
+
return;
|
|
27480
|
+
if (last.reachable === false && previous?.reachable === false)
|
|
27481
|
+
return { trigger: "management", title: "Two management reads failed" };
|
|
27482
|
+
if (previous && last.interfaces.some((i) => !i.running && previous.interfaces.some((p) => p.name === i.name && p.running)))
|
|
27483
|
+
return { trigger: "interface", title: "An observed interface stopped running" };
|
|
27484
|
+
if (recent.length === 3 && recent.every((s) => (s.cpu ?? -1) >= 90))
|
|
27485
|
+
return { trigger: "resources", title: "Sustained CPU pressure observed" };
|
|
27486
|
+
}
|
|
27487
|
+
function trimFlight(record, now) {
|
|
27488
|
+
const since = now - record.windowMinutes * 60000;
|
|
27489
|
+
record.samples = record.samples.filter((s) => s.at >= since).slice(-720);
|
|
27490
|
+
record.events = record.events.filter((s) => s.at >= since).slice(-500);
|
|
27491
|
+
record.seenLogs = record.seenLogs.slice(-500);
|
|
27492
|
+
record.incidents = record.incidents.filter((i) => i.at >= now - record.retentionDays * 86400000).slice(-30);
|
|
27493
|
+
for (const i of record.incidents) {
|
|
27494
|
+
i.samples = i.samples.slice(-720);
|
|
27495
|
+
i.events = i.events.slice(-500);
|
|
27496
|
+
i.complete = now >= i.until || !record.enabled;
|
|
27497
|
+
}
|
|
27498
|
+
record.updatedAt = now;
|
|
27499
|
+
return record;
|
|
27500
|
+
}
|
|
27501
|
+
function freezeFlight(record, title, trigger, now) {
|
|
27502
|
+
const incident = {
|
|
27503
|
+
id: crypto.randomUUID(),
|
|
27504
|
+
at: now,
|
|
27505
|
+
until: record.enabled ? now + 120000 : now,
|
|
27506
|
+
title,
|
|
27507
|
+
trigger,
|
|
27508
|
+
samples: structuredClone(record.samples),
|
|
27509
|
+
events: structuredClone(record.events),
|
|
27510
|
+
complete: !record.enabled
|
|
27511
|
+
};
|
|
27512
|
+
record.incidents.push(incident);
|
|
27513
|
+
return incident;
|
|
27514
|
+
}
|
|
27515
|
+
|
|
27516
|
+
// src/flight-recorder/service.ts
|
|
27517
|
+
var kind2 = "flight-recorder";
|
|
27518
|
+
var queues = new Map;
|
|
27519
|
+
function access2(ctx, tool, write = false) {
|
|
27520
|
+
const device = resolveDeviceName(ctx.device);
|
|
27521
|
+
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
27522
|
+
return device;
|
|
27523
|
+
}
|
|
27524
|
+
async function record2(device) {
|
|
27525
|
+
return (await operationsStore()).get(kind2, device, device) ?? blankFlight(device, Date.now());
|
|
27526
|
+
}
|
|
27527
|
+
async function edit(device, work) {
|
|
27528
|
+
const task = (queues.get(device) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
|
27529
|
+
const store = await operationsStore(), owner = crypto.randomUUID(), key = `flight:${device}`;
|
|
27530
|
+
store.lock(key, owner);
|
|
27531
|
+
try {
|
|
27532
|
+
const r = await record2(device), result = await work(r);
|
|
27533
|
+
store.put(kind2, trimFlight(r, Date.now()));
|
|
27534
|
+
return result;
|
|
27535
|
+
} finally {
|
|
27536
|
+
store.unlock(key, owner);
|
|
27537
|
+
}
|
|
27538
|
+
});
|
|
27539
|
+
queues.set(device, task);
|
|
27540
|
+
try {
|
|
27541
|
+
return await task;
|
|
27542
|
+
} finally {
|
|
27543
|
+
if (queues.get(device) === task)
|
|
27544
|
+
queues.delete(device);
|
|
27545
|
+
}
|
|
27546
|
+
}
|
|
27547
|
+
async function getFlight(ctx) {
|
|
27548
|
+
const device = access2(ctx, "get_flight_recorder");
|
|
27549
|
+
return {
|
|
27550
|
+
recorder: trimFlight(await record2(device), Date.now()),
|
|
27551
|
+
toolEventsAvailable: isRecording(),
|
|
27552
|
+
limitations: [
|
|
27553
|
+
"SSH-polled log metadata, not a lossless syslog receiver.",
|
|
27554
|
+
"Receive-time correlation is not proof of cause or actor identity.",
|
|
27555
|
+
"No capture while MCP is stopped; missing observations are not healthy samples."
|
|
27556
|
+
]
|
|
27557
|
+
};
|
|
27558
|
+
}
|
|
27559
|
+
async function configureFlight(input, ctx) {
|
|
27560
|
+
const device = access2(ctx, "configure_flight_recorder", true), a = recorderInput.parse(input);
|
|
27561
|
+
await edit(device, async (r) => {
|
|
27562
|
+
Object.assign(r, a);
|
|
27563
|
+
r.error = undefined;
|
|
27564
|
+
});
|
|
27565
|
+
return getFlight(ctx);
|
|
27566
|
+
}
|
|
27567
|
+
async function freezeIncident(title, ctx) {
|
|
27568
|
+
const device = access2(ctx, "freeze_network_incident", true);
|
|
27569
|
+
if (!title.trim() || title.length > 120)
|
|
27570
|
+
throw new Error("Use a 1\u2013120 character incident title.");
|
|
27571
|
+
await edit(device, async (r) => {
|
|
27572
|
+
freezeFlight(r, title.trim(), "manual", Date.now());
|
|
27573
|
+
});
|
|
27574
|
+
return getFlight(ctx);
|
|
27575
|
+
}
|
|
27576
|
+
async function exportIncident(id, ctx) {
|
|
27577
|
+
const device = access2(ctx, "export_network_incident"), r = await record2(device);
|
|
27578
|
+
const incident = trimFlight(r, Date.now()).incidents.find((i) => i.id === id);
|
|
27579
|
+
if (!incident)
|
|
27580
|
+
throw new Error("Incident not found on the selected router or retention expired.");
|
|
27581
|
+
return {
|
|
27582
|
+
format: "mikrotik-flight-recorder/v1",
|
|
27583
|
+
device,
|
|
27584
|
+
exportedAt: Date.now(),
|
|
27585
|
+
incident,
|
|
27586
|
+
privacy: "Review device/interface names before sharing. Raw logs, commands, arguments and credentials are excluded.",
|
|
27587
|
+
interpretation: "Chronology is receipt time on the MCP host. Correlation is not causation; routerTime is untrusted, uncorrected router text."
|
|
27588
|
+
};
|
|
27589
|
+
}
|
|
27590
|
+
var numeric = (v) => v && /^\d+$/.test(v) && Number.isSafeInteger(Number(v)) ? Number(v) : undefined;
|
|
27591
|
+
var FLIGHT_LOG_COMMAND = ":local ids [/log find]; :local n [:len $ids]; :local start ($n - 50); :if ($start < 0) do={ :set start 0 }; :foreach id in=[:pick $ids $start $n] do={ :put [:serialize to=json value=[/log get $id]] }";
|
|
27592
|
+
async function sampleFlight(device) {
|
|
27593
|
+
const ctx = createContext(undefined, device);
|
|
27594
|
+
access2(ctx, "get_flight_recorder");
|
|
27595
|
+
await edit(device, async (r) => {
|
|
27596
|
+
if (!r.enabled || Date.now() - (r.lastAttempt ?? 0) < r.intervalSeconds * 1000)
|
|
27597
|
+
return;
|
|
27598
|
+
const now = Date.now();
|
|
27599
|
+
r.lastAttempt = now;
|
|
27600
|
+
const sample = {
|
|
27601
|
+
at: now,
|
|
27602
|
+
finishedAt: now,
|
|
27603
|
+
reachable: null,
|
|
27604
|
+
interfaces: [],
|
|
27605
|
+
gaps: []
|
|
27606
|
+
};
|
|
27607
|
+
const events = [];
|
|
27608
|
+
if (getSafeModeManager(device).isActive)
|
|
27609
|
+
sample.gaps.push("Capture skipped: router is in Safe Mode.");
|
|
27610
|
+
else {
|
|
27611
|
+
try {
|
|
27612
|
+
const resource = parseSystemResource(await checkedRead("/system resource print", ctx));
|
|
27613
|
+
if (!resource || !Number.isFinite(resource.cpuLoad))
|
|
27614
|
+
throw new Error("No resource sample");
|
|
27615
|
+
sample.reachable = true;
|
|
27616
|
+
sample.cpu = resource.cpuLoad;
|
|
27617
|
+
if (resource.totalMemory !== undefined && resource.totalMemory > 0 && resource.freeMemory !== undefined)
|
|
27618
|
+
sample.memory = Math.round((1 - resource.freeMemory / resource.totalMemory) * 100);
|
|
27619
|
+
} catch {
|
|
27620
|
+
sample.reachable = false;
|
|
27621
|
+
sample.gaps.push("Management read failed; network outage is not established.");
|
|
27622
|
+
}
|
|
27623
|
+
if (sample.reachable) {
|
|
27624
|
+
try {
|
|
27625
|
+
const interfaces = await rows("/interface", "name,running,disabled,rx-byte,tx-byte", ctx);
|
|
27626
|
+
if (interfaces.length > 64)
|
|
27627
|
+
sample.gaps.push("Interface inventory capped at 64 entries.");
|
|
27628
|
+
sample.interfaces = interfaces.filter((i) => !["yes", "true"].includes(i.disabled) && !(i.flags ?? "").includes("X")).slice(0, 64).map((i) => ({
|
|
27629
|
+
name: (i.name ?? "unknown").slice(0, 100),
|
|
27630
|
+
running: ["yes", "true"].includes(i.running) || (i.flags ?? "").includes("R"),
|
|
27631
|
+
rx: numeric(i["rx-byte"]),
|
|
27632
|
+
tx: numeric(i["tx-byte"])
|
|
27633
|
+
}));
|
|
27634
|
+
} catch {
|
|
27635
|
+
sample.gaps.push("Interface state unavailable.");
|
|
27636
|
+
}
|
|
27637
|
+
try {
|
|
27638
|
+
const raw = await checkedRead(FLIGHT_LOG_COMMAND, ctx);
|
|
27639
|
+
const logs = raw.trim() ? raw.trim().split(/\r?\n/).map((line) => JSON.parse(line)) : [];
|
|
27640
|
+
if (logs.length > 50)
|
|
27641
|
+
throw new Error("Log cap exceeded");
|
|
27642
|
+
for (const row of logs) {
|
|
27643
|
+
const e = logEvidence(row, Date.now());
|
|
27644
|
+
if (!r.seenLogs.includes(e.id)) {
|
|
27645
|
+
events.push(e);
|
|
27646
|
+
r.seenLogs.push(e.id);
|
|
27647
|
+
}
|
|
27648
|
+
}
|
|
27649
|
+
if (logs.length === 50)
|
|
27650
|
+
sample.gaps.push("Only the newest 50 router log entries were checked; earlier entries may be missing.");
|
|
27651
|
+
} catch {
|
|
27652
|
+
sample.gaps.push("Router log collection unavailable or unsupported.");
|
|
27653
|
+
}
|
|
27654
|
+
}
|
|
27655
|
+
}
|
|
27656
|
+
sample.finishedAt = Date.now();
|
|
27657
|
+
r.samples.push(sample);
|
|
27658
|
+
r.events.push(...events);
|
|
27659
|
+
for (const incident of r.incidents.filter((i) => !i.complete && now <= i.until)) {
|
|
27660
|
+
incident.samples.push(sample);
|
|
27661
|
+
incident.events.push(...events);
|
|
27662
|
+
}
|
|
27663
|
+
const trigger = detectFlightIncident(r);
|
|
27664
|
+
if (trigger && now - (r.incidents.at(-1)?.at ?? 0) >= 300000)
|
|
27665
|
+
freezeFlight(r, trigger.title, trigger.trigger, now);
|
|
27666
|
+
r.error = sample.gaps.length ? sample.gaps.join(" ") : undefined;
|
|
27667
|
+
});
|
|
27668
|
+
}
|
|
27669
|
+
async function recordFlightTool(event) {
|
|
27670
|
+
if (!event.device || event.risk === "READ" && !event.isError)
|
|
27671
|
+
return;
|
|
27672
|
+
const device = access2(createContext(undefined, event.device), "get_flight_recorder");
|
|
27673
|
+
await edit(device, async (r) => {
|
|
27674
|
+
if (!r.enabled)
|
|
27675
|
+
return;
|
|
27676
|
+
const e = {
|
|
27677
|
+
id: `mcp:${event.id}`,
|
|
27678
|
+
at: Date.now(),
|
|
27679
|
+
source: "mcp",
|
|
27680
|
+
title: event.tool.slice(0, 100),
|
|
27681
|
+
risk: event.risk,
|
|
27682
|
+
failed: event.isError
|
|
27683
|
+
};
|
|
27684
|
+
r.events.push(e);
|
|
27685
|
+
for (const i of r.incidents.filter((i) => !i.complete && e.at <= i.until))
|
|
27686
|
+
i.events.push(e);
|
|
27687
|
+
});
|
|
27688
|
+
}
|
|
27689
|
+
var timer2;
|
|
27690
|
+
var unsubscribe;
|
|
27691
|
+
var ticking2 = false;
|
|
27692
|
+
function startFlightRecorder() {
|
|
27693
|
+
if (timer2)
|
|
27694
|
+
return;
|
|
27695
|
+
unsubscribe = subscribe((e) => {
|
|
27696
|
+
recordFlightTool(e).catch(() => {});
|
|
27697
|
+
});
|
|
27698
|
+
timer2 = setInterval(() => {
|
|
27699
|
+
flightTick().catch(() => {});
|
|
27700
|
+
}, 5000);
|
|
27701
|
+
timer2.unref();
|
|
27702
|
+
}
|
|
27703
|
+
function stopFlightRecorder() {
|
|
27704
|
+
if (timer2)
|
|
27705
|
+
clearInterval(timer2);
|
|
27706
|
+
timer2 = undefined;
|
|
27707
|
+
unsubscribe?.();
|
|
27708
|
+
unsubscribe = undefined;
|
|
27709
|
+
}
|
|
27710
|
+
async function flightTick() {
|
|
27711
|
+
if (ticking2)
|
|
27712
|
+
return;
|
|
27713
|
+
ticking2 = true;
|
|
27714
|
+
try {
|
|
27715
|
+
for (const device of Object.keys(getConfig().devices)) {
|
|
27716
|
+
try {
|
|
27717
|
+
const r = await record2(device);
|
|
27718
|
+
if (r.enabled)
|
|
27719
|
+
await sampleFlight(device);
|
|
27720
|
+
else if (r.samples.length + r.events.length + r.incidents.length > 0 && Date.now() - r.updatedAt > 60000)
|
|
27721
|
+
await edit(device, async () => {});
|
|
27722
|
+
} catch {}
|
|
27723
|
+
}
|
|
27724
|
+
} finally {
|
|
27725
|
+
ticking2 = false;
|
|
27726
|
+
}
|
|
27727
|
+
}
|
|
27728
|
+
|
|
27729
|
+
// src/tools/flight-recorder.ts
|
|
27730
|
+
var flightRecorderTools = [
|
|
27731
|
+
defineTool({
|
|
27732
|
+
name: "get_flight_recorder",
|
|
27733
|
+
title: "Read Network Flight Recorder",
|
|
27734
|
+
annotations: READ,
|
|
27735
|
+
description: "Read bounded persistent telemetry, off-router log metadata, capture gaps and frozen incidents for this router. No active probes. Times are host receipt times; correlation never proves cause, identity or a network outage.",
|
|
27736
|
+
inputSchema: {},
|
|
27737
|
+
async handler(_, ctx) {
|
|
27738
|
+
return JSON.stringify(await getFlight(ctx));
|
|
27739
|
+
}
|
|
27740
|
+
}),
|
|
27741
|
+
defineTool({
|
|
27742
|
+
name: "configure_flight_recorder",
|
|
27743
|
+
title: "Configure Network Flight Recorder",
|
|
27744
|
+
annotations: WRITE,
|
|
27745
|
+
description: "Explicitly enable/disable periodic read-only router collection and local retention. No router configuration writes. Stores bounded resources, interface state, classified log metadata and MCP write/failure metadata; no raw messages or credentials. Requires the MCP process to stay running. SSH polling can miss logs; not a lossless syslog service.",
|
|
27746
|
+
inputSchema: recorderInput.shape,
|
|
27747
|
+
async handler(a, ctx) {
|
|
27748
|
+
return JSON.stringify(await configureFlight(a, ctx));
|
|
27749
|
+
}
|
|
27750
|
+
}),
|
|
27751
|
+
defineTool({
|
|
27752
|
+
name: "freeze_network_incident",
|
|
27753
|
+
title: "Freeze Network Incident Evidence",
|
|
27754
|
+
annotations: WRITE,
|
|
27755
|
+
description: "Preserve this router's available rolling evidence plus two minutes of future samples when recording is enabled. Local operation only. Empty history stays empty; cannot recover past logs. Maximum 30 incidents, configured age retention.",
|
|
27756
|
+
inputSchema: { title: string2().trim().min(1).max(120) },
|
|
27757
|
+
async handler(a, ctx) {
|
|
27758
|
+
return JSON.stringify(await freezeIncident(a.title, ctx));
|
|
27759
|
+
}
|
|
27760
|
+
}),
|
|
27761
|
+
defineTool({
|
|
27762
|
+
name: "export_network_incident",
|
|
27763
|
+
title: "Export Network Incident Evidence",
|
|
27764
|
+
annotations: READ,
|
|
27765
|
+
description: "Export a device-scoped frozen incident with coverage gaps and separate router/receive timestamps. No raw logs or command bodies. Review device/interface names before sharing. Do not attribute an attack to a user based only on these observations.",
|
|
27766
|
+
inputSchema: { id: uuid2() },
|
|
27767
|
+
async handler(a, ctx) {
|
|
27768
|
+
return JSON.stringify(await exportIncident(a.id, ctx));
|
|
27769
|
+
}
|
|
27770
|
+
})
|
|
27771
|
+
];
|
|
27772
|
+
|
|
27773
|
+
// src/recovery-lab/model.ts
|
|
27774
|
+
import { createHash as createHash7 } from "crypto";
|
|
27775
|
+
var rosVersion = string2().regex(/^7\.\d+(?:\.\d+)?(?:beta\d+|rc\d+)?$/);
|
|
27776
|
+
var recoveryInput = object({
|
|
27777
|
+
snapshotId: string2().min(1).max(100),
|
|
27778
|
+
version: rosVersion,
|
|
27779
|
+
mode: _enum(["restore", "upgrade"]).default("restore")
|
|
27780
|
+
});
|
|
27781
|
+
var REQUIRED_CHECKS = [
|
|
27782
|
+
"authenticated-boot",
|
|
27783
|
+
"import",
|
|
27784
|
+
"configuration-readback",
|
|
27785
|
+
"reboot-persistence",
|
|
27786
|
+
"isolation"
|
|
27787
|
+
];
|
|
27788
|
+
var capabilitiesSchema = object({
|
|
27789
|
+
protocol: literal("mikrotik-recovery/v1"),
|
|
27790
|
+
runnerId: string2().regex(/^[a-zA-Z0-9_.-]{1,80}$/),
|
|
27791
|
+
isolated: literal(true),
|
|
27792
|
+
productionNetworkAccess: literal(false),
|
|
27793
|
+
disposable: literal(true),
|
|
27794
|
+
enforcesTtl: literal(true),
|
|
27795
|
+
versions: array(object({
|
|
27796
|
+
version: rosVersion,
|
|
27797
|
+
imageSha256: string2().regex(/^[a-f0-9]{64}$/),
|
|
27798
|
+
architecture: _enum(["x86_64", "aarch64"])
|
|
27799
|
+
})).min(1).max(30).refine((versions) => new Set(versions.map((v) => v.version)).size === versions.length, {
|
|
27800
|
+
message: "Each RouterOS version must identify one unambiguous pinned image."
|
|
27801
|
+
})
|
|
27802
|
+
});
|
|
27803
|
+
var resultSchema = object({
|
|
27804
|
+
protocol: literal("mikrotik-recovery/v1"),
|
|
27805
|
+
id: uuid2(),
|
|
27806
|
+
requestSha256: string2().regex(/^[a-f0-9]{64}$/),
|
|
27807
|
+
runnerId: string2().min(1).max(80),
|
|
27808
|
+
version: rosVersion,
|
|
27809
|
+
state: _enum(["running", "completed", "failed", "destroyed"]),
|
|
27810
|
+
isolated: literal(true),
|
|
27811
|
+
productionNetworkAccess: literal(false),
|
|
27812
|
+
checks: array(object({
|
|
27813
|
+
name: _enum(REQUIRED_CHECKS),
|
|
27814
|
+
state: _enum(["pass", "fail", "unsupported", "pending"]),
|
|
27815
|
+
detail: string2().max(500)
|
|
27816
|
+
})).max(5),
|
|
27817
|
+
elapsedMs: number2().int().min(0).max(3600000).optional(),
|
|
27818
|
+
cleanup: _enum(["pending", "destroyed", "failed"])
|
|
27819
|
+
});
|
|
27820
|
+
var sha256 = (value) => createHash7("sha256").update(value).digest("hex");
|
|
27821
|
+
var FIELDS = {
|
|
27822
|
+
"/interface/bridge": ["name", "protocol-mode", "vlan-filtering", "pvid", "disabled"],
|
|
27823
|
+
"/interface/vlan": ["name", "interface", "vlan-id", "disabled"],
|
|
27824
|
+
"/interface/bridge/port": [
|
|
27825
|
+
"bridge",
|
|
27826
|
+
"interface",
|
|
27827
|
+
"pvid",
|
|
27828
|
+
"ingress-filtering",
|
|
27829
|
+
"frame-types",
|
|
27830
|
+
"disabled"
|
|
27831
|
+
],
|
|
27832
|
+
"/interface/bridge/vlan": ["bridge", "tagged", "untagged", "vlan-ids", "disabled"],
|
|
27833
|
+
"/interface/list": ["name", "include", "exclude"],
|
|
27834
|
+
"/interface/list/member": ["list", "interface", "disabled"],
|
|
27835
|
+
"/ip/address": ["address", "interface", "network", "disabled"],
|
|
27836
|
+
"/ipv6/address": ["address", "interface", "advertise", "disabled"],
|
|
27837
|
+
"/ip/route": [
|
|
27838
|
+
"dst-address",
|
|
27839
|
+
"gateway",
|
|
27840
|
+
"distance",
|
|
27841
|
+
"routing-table",
|
|
27842
|
+
"scope",
|
|
27843
|
+
"target-scope",
|
|
27844
|
+
"disabled",
|
|
27845
|
+
"blackhole"
|
|
27846
|
+
],
|
|
27847
|
+
"/ipv6/route": [
|
|
27848
|
+
"dst-address",
|
|
27849
|
+
"gateway",
|
|
27850
|
+
"distance",
|
|
27851
|
+
"routing-table",
|
|
27852
|
+
"scope",
|
|
27853
|
+
"target-scope",
|
|
27854
|
+
"disabled",
|
|
27855
|
+
"blackhole"
|
|
27856
|
+
],
|
|
27857
|
+
"/routing/table": ["name", "fib", "disabled"],
|
|
27858
|
+
"/ip/firewall/filter": [
|
|
27859
|
+
"chain",
|
|
27860
|
+
"action",
|
|
27861
|
+
"protocol",
|
|
27862
|
+
"src-address",
|
|
27863
|
+
"dst-address",
|
|
27864
|
+
"src-port",
|
|
27865
|
+
"dst-port",
|
|
27866
|
+
"connection-state",
|
|
27867
|
+
"in-interface",
|
|
27868
|
+
"out-interface",
|
|
27869
|
+
"in-interface-list",
|
|
27870
|
+
"out-interface-list",
|
|
27871
|
+
"disabled"
|
|
27872
|
+
],
|
|
27873
|
+
"/ipv6/firewall/filter": [
|
|
27874
|
+
"chain",
|
|
27875
|
+
"action",
|
|
27876
|
+
"protocol",
|
|
27877
|
+
"src-address",
|
|
27878
|
+
"dst-address",
|
|
27879
|
+
"src-port",
|
|
27880
|
+
"dst-port",
|
|
27881
|
+
"connection-state",
|
|
27882
|
+
"in-interface",
|
|
27883
|
+
"out-interface",
|
|
27884
|
+
"in-interface-list",
|
|
27885
|
+
"out-interface-list",
|
|
27886
|
+
"disabled"
|
|
27887
|
+
]
|
|
27888
|
+
};
|
|
27889
|
+
function buildRecoverySubset(body) {
|
|
27890
|
+
if (body.length > 512000)
|
|
27891
|
+
throw new Error("Snapshot exceeds the 512 KB rehearsal limit.");
|
|
27892
|
+
const model = parseExport(body), commands = [], coverage = [];
|
|
27893
|
+
for (const section of model.sections) {
|
|
27894
|
+
const allowed = FIELDS[section.path];
|
|
27895
|
+
let included = 0, excluded = 0;
|
|
27896
|
+
for (const row of section.records) {
|
|
27897
|
+
const fields = Object.entries(row.fields).filter(([key]) => key !== "comment");
|
|
27898
|
+
if (!allowed || row.op !== "add" || /[$[\]{};\\\r\n]/.test(row.raw) || fields.some(([key, value]) => !allowed.includes(key) || value.length > 200) || fields.length === 0 || row.flags.length > 0) {
|
|
27899
|
+
excluded++;
|
|
27900
|
+
continue;
|
|
27901
|
+
}
|
|
27902
|
+
let cmd = new Cmd(`${section.path.replaceAll("/", " ").trimStart().replace(/^/, "/")} add`);
|
|
27903
|
+
for (const [key, value] of fields)
|
|
27904
|
+
cmd = cmd.set(key, value);
|
|
27905
|
+
commands.push(cmd.build());
|
|
27906
|
+
included++;
|
|
27907
|
+
}
|
|
27908
|
+
coverage.push({
|
|
27909
|
+
scope: section.path,
|
|
27910
|
+
included,
|
|
27911
|
+
excluded,
|
|
27912
|
+
reason: excluded ? "Unsupported scope, operation, field or expression: not sent to the lab." : undefined
|
|
27913
|
+
});
|
|
27914
|
+
}
|
|
27915
|
+
if (model.unparsed.length)
|
|
27916
|
+
coverage.push({
|
|
27917
|
+
scope: "unparsed lines",
|
|
27918
|
+
included: 0,
|
|
27919
|
+
excluded: model.unparsed.length,
|
|
27920
|
+
reason: "Unparsed text is never executed."
|
|
27921
|
+
});
|
|
27922
|
+
if (commands.length > 300)
|
|
27923
|
+
throw new Error("More than 300 portable records. Prepare a smaller reviewed snapshot.");
|
|
27924
|
+
return { commands, coverage };
|
|
27925
|
+
}
|
|
27926
|
+
function validateRunnerResult(input, run) {
|
|
27927
|
+
const result = resultSchema.parse(input);
|
|
27928
|
+
if (result.id !== run.id || result.runnerId !== run.runnerId || result.requestSha256 !== run.requestSha256 || result.version !== run.version)
|
|
27929
|
+
throw new Error("Runner evidence does not match this immutable rehearsal.");
|
|
27930
|
+
if (new Set(result.checks.map((c) => c.name)).size !== result.checks.length)
|
|
27931
|
+
throw new Error("Duplicate runner checks are not valid evidence.");
|
|
27932
|
+
if (result.state === "destroyed" && result.cleanup !== "destroyed")
|
|
27933
|
+
throw new Error("Destruction is not confirmed.");
|
|
27934
|
+
return result;
|
|
27935
|
+
}
|
|
27936
|
+
function resultState(result) {
|
|
27937
|
+
if (result.state === "destroyed")
|
|
27938
|
+
return "destroyed";
|
|
27939
|
+
if (result.state === "failed" || result.checks.some((c) => c.state === "fail"))
|
|
27940
|
+
return "failed";
|
|
27941
|
+
if (result.state === "running")
|
|
27942
|
+
return "running";
|
|
27943
|
+
return REQUIRED_CHECKS.every((name) => result.checks.some((c) => c.name === name && c.state === "pass")) ? "passed" : "uncertain";
|
|
27944
|
+
}
|
|
27945
|
+
|
|
27946
|
+
// src/recovery-lab/runner.ts
|
|
27947
|
+
function runnerConfig() {
|
|
27948
|
+
const value = process.env.MIKROTIK_RECOVERY_RUNNER_URL;
|
|
27949
|
+
const token = process.env.MIKROTIK_RECOVERY_RUNNER_TOKEN;
|
|
27950
|
+
if (!value && !token)
|
|
27951
|
+
return;
|
|
27952
|
+
if (!value || !token || token.length < 24 || /[\r\n]/.test(token))
|
|
27953
|
+
throw new Error("Recovery runner URL and a token of at least 24 characters must be configured by the administrator.");
|
|
27954
|
+
const url = new URL(value);
|
|
27955
|
+
if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || !(url.protocol === "https:" || url.protocol === "http:" && ["127.0.0.1", "[::1]"].includes(url.hostname)))
|
|
27956
|
+
throw new Error("Recovery runner needs an HTTPS origin (or explicit loopback HTTP), without path, query or URL credentials.");
|
|
27957
|
+
return { base: url.origin, token, binding: sha256(`${url.origin}
|
|
27958
|
+
${token}`) };
|
|
27959
|
+
}
|
|
27960
|
+
async function callRunner(method, path, body) {
|
|
27961
|
+
const cfg = runnerConfig();
|
|
27962
|
+
if (!cfg)
|
|
27963
|
+
throw new Error("No isolated recovery runner configured. Prepare and inspect locally; execution is unavailable.");
|
|
27964
|
+
if (!/^\/v1\/(capabilities|runs\/[a-f0-9-]{36})$/.test(path))
|
|
27965
|
+
throw new Error("Invalid runner operation.");
|
|
27966
|
+
if (method === "GET" && body !== undefined)
|
|
27967
|
+
throw new Error("Read-only runner operations cannot contain a request body.");
|
|
27968
|
+
const options = {
|
|
27969
|
+
method,
|
|
27970
|
+
headers: { authorization: `Bearer ${cfg.token}`, "content-type": "application/json" },
|
|
27971
|
+
redirect: "error",
|
|
27972
|
+
signal: AbortSignal.timeout(1e4)
|
|
27973
|
+
};
|
|
27974
|
+
if (method !== "GET" && body !== undefined)
|
|
27975
|
+
options.body = JSON.stringify(body);
|
|
27976
|
+
const response = await fetch(`${cfg.base}${path}`, options);
|
|
27977
|
+
if (!response.ok) {
|
|
27978
|
+
await response.body?.cancel();
|
|
27979
|
+
throw new Error(`Recovery runner returned HTTP ${response.status}; no automatic write retry.`);
|
|
27980
|
+
}
|
|
27981
|
+
const reader = response.body?.getReader();
|
|
27982
|
+
if (!reader)
|
|
27983
|
+
throw new Error("Runner returned no evidence.");
|
|
27984
|
+
const chunks = [];
|
|
27985
|
+
let size = 0;
|
|
27986
|
+
try {
|
|
27987
|
+
while (true) {
|
|
27988
|
+
const part = await reader.read();
|
|
27989
|
+
if (part.done)
|
|
27990
|
+
break;
|
|
27991
|
+
size += part.value.length;
|
|
27992
|
+
if (size > 65536)
|
|
27993
|
+
throw new Error("Runner evidence exceeds the 64 KB limit.");
|
|
27994
|
+
chunks.push(part.value);
|
|
27995
|
+
}
|
|
27996
|
+
} finally {
|
|
27997
|
+
await reader.cancel().catch(() => {});
|
|
27998
|
+
}
|
|
27999
|
+
const data = new Uint8Array(size);
|
|
28000
|
+
let offset = 0;
|
|
28001
|
+
for (const part of chunks) {
|
|
28002
|
+
data.set(part, offset);
|
|
28003
|
+
offset += part.length;
|
|
28004
|
+
}
|
|
28005
|
+
return JSON.parse(new TextDecoder().decode(data));
|
|
28006
|
+
}
|
|
28007
|
+
|
|
28008
|
+
// src/recovery-lab/service.ts
|
|
28009
|
+
var kind3 = "recovery-lab";
|
|
28010
|
+
function access3(ctx, tool, write = false) {
|
|
28011
|
+
const device = resolveDeviceName(ctx.device);
|
|
28012
|
+
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
28013
|
+
return device;
|
|
28014
|
+
}
|
|
28015
|
+
async function getRecovery(ctx) {
|
|
28016
|
+
const device = access3(ctx, "get_recovery_lab");
|
|
28017
|
+
let configured = false, configurationError;
|
|
28018
|
+
try {
|
|
28019
|
+
configured = !!runnerConfig();
|
|
28020
|
+
} catch {
|
|
28021
|
+
configurationError = "Runner configuration is invalid; ask the administrator to check the URL/token.";
|
|
28022
|
+
}
|
|
28023
|
+
return {
|
|
28024
|
+
runs: (await operationsStore()).list(kind3, device),
|
|
28025
|
+
configured,
|
|
28026
|
+
configurationError
|
|
28027
|
+
};
|
|
28028
|
+
}
|
|
28029
|
+
async function recoveryInventory(ctx) {
|
|
28030
|
+
const device = access3(ctx, "recovery_lab_inventory"), store = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
28031
|
+
try {
|
|
28032
|
+
const snapshots = store.list(device, 50).map((s) => ({ id: s.id, at: s.ts, label: s.label, version: s.rosVersion }));
|
|
28033
|
+
const cfg = runnerConfig();
|
|
28034
|
+
return {
|
|
28035
|
+
snapshots,
|
|
28036
|
+
runner: cfg ? capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities")) : null
|
|
28037
|
+
};
|
|
28038
|
+
} finally {
|
|
28039
|
+
store.close();
|
|
28040
|
+
}
|
|
28041
|
+
}
|
|
28042
|
+
async function prepareRecovery(input, ctx) {
|
|
28043
|
+
const device = access3(ctx, "prepare_recovery_lab", true), a = recoveryInput.parse(input);
|
|
28044
|
+
const snapshots = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
28045
|
+
try {
|
|
28046
|
+
const source = snapshots.get(a.snapshotId);
|
|
28047
|
+
if (!source || source.device !== device)
|
|
28048
|
+
throw new Error("Snapshot not found on this router.");
|
|
28049
|
+
const subset = buildRecoverySubset(source.body), cfg = runnerConfig();
|
|
28050
|
+
const caps = cfg ? capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities")) : undefined;
|
|
28051
|
+
if (caps && !caps.versions.some((v) => v.version === a.version))
|
|
28052
|
+
throw new Error("Target version is not available as a pinned runner image.");
|
|
28053
|
+
if (a.mode === "upgrade" && (!source.rosVersion || caps && !caps.versions.some((v) => v.version === source.rosVersion)))
|
|
28054
|
+
throw new Error("Upgrade rehearsal requires a known source version and pinned source/target images.");
|
|
28055
|
+
const now = Date.now();
|
|
28056
|
+
const run = {
|
|
28057
|
+
id: crypto.randomUUID(),
|
|
28058
|
+
device,
|
|
28059
|
+
updatedAt: now,
|
|
28060
|
+
preparedAt: now,
|
|
28061
|
+
snapshotId: source.id,
|
|
28062
|
+
snapshotSha: sha256(source.body),
|
|
28063
|
+
snapshotAt: source.ts,
|
|
28064
|
+
sourceVersion: source.rosVersion,
|
|
28065
|
+
version: a.version,
|
|
28066
|
+
mode: a.mode,
|
|
28067
|
+
...subset,
|
|
28068
|
+
commandSha256: sha256(subset.commands.join(`
|
|
28069
|
+
`)),
|
|
28070
|
+
state: "prepared",
|
|
28071
|
+
runnerId: caps?.runnerId,
|
|
28072
|
+
runnerBinding: cfg?.binding,
|
|
28073
|
+
capabilitiesSha: caps ? sha256(JSON.stringify(caps)) : undefined
|
|
28074
|
+
};
|
|
28075
|
+
const store = await operationsStore();
|
|
28076
|
+
if (store.list(kind3, device).length >= 100)
|
|
28077
|
+
throw new Error("100 rehearsal records reached. Archive/export old evidence before creating more.");
|
|
28078
|
+
store.put(kind3, run);
|
|
28079
|
+
return run;
|
|
28080
|
+
} finally {
|
|
28081
|
+
snapshots.close();
|
|
28082
|
+
}
|
|
28083
|
+
}
|
|
28084
|
+
async function editRun(id, device, work) {
|
|
28085
|
+
const store = await operationsStore(), owner = crypto.randomUUID();
|
|
28086
|
+
store.lock(`lab:${device}`, owner);
|
|
28087
|
+
try {
|
|
28088
|
+
const r = store.get(kind3, id, device);
|
|
28089
|
+
if (!r)
|
|
28090
|
+
throw new Error("Rehearsal not found on this router.");
|
|
28091
|
+
return await work(r);
|
|
28092
|
+
} finally {
|
|
28093
|
+
store.unlock(`lab:${device}`, owner);
|
|
28094
|
+
}
|
|
28095
|
+
}
|
|
28096
|
+
async function save2(run) {
|
|
28097
|
+
run.updatedAt = Date.now();
|
|
28098
|
+
(await operationsStore()).put(kind3, run);
|
|
28099
|
+
}
|
|
28100
|
+
function boundRunner(run) {
|
|
28101
|
+
const cfg = runnerConfig();
|
|
28102
|
+
if (!cfg || cfg.binding !== run.runnerBinding)
|
|
28103
|
+
throw new Error("Runner changed or is unavailable. Never send an existing rehearsal to a different destination.");
|
|
28104
|
+
}
|
|
28105
|
+
async function startRecovery(id, confirm, ctx) {
|
|
28106
|
+
const device = access3(ctx, "start_recovery_lab", true);
|
|
28107
|
+
if (!confirm)
|
|
28108
|
+
throw new Error("Explicit confirmation is required to send the reviewed subset to the configured isolated runner.");
|
|
28109
|
+
return editRun(id, device, async (run) => {
|
|
28110
|
+
if (run.state !== "prepared")
|
|
28111
|
+
throw new Error("Already submitted or uncertain. Poll its existing ID; do not replay the write.");
|
|
28112
|
+
if (Date.now() - run.preparedAt > 600000)
|
|
28113
|
+
throw new Error("Preview expired; prepare a fresh rehearsal.");
|
|
28114
|
+
if (!run.commands.length)
|
|
28115
|
+
throw new Error("There are no portable records to rehearse.");
|
|
28116
|
+
boundRunner(run);
|
|
28117
|
+
const caps = capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities"));
|
|
28118
|
+
if (sha256(JSON.stringify(caps)) !== run.capabilitiesSha)
|
|
28119
|
+
throw new Error("Runner capabilities changed; prepare again.");
|
|
28120
|
+
const snapshots = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
28121
|
+
try {
|
|
28122
|
+
const source = snapshots.get(run.snapshotId);
|
|
28123
|
+
if (!source || source.device !== device || sha256(source.body) !== run.snapshotSha)
|
|
28124
|
+
throw new Error("Source snapshot changed or was removed.");
|
|
28125
|
+
} finally {
|
|
28126
|
+
snapshots.close();
|
|
28127
|
+
}
|
|
28128
|
+
const request = {
|
|
28129
|
+
protocol: "mikrotik-recovery/v1",
|
|
28130
|
+
id: run.id,
|
|
28131
|
+
mode: run.mode,
|
|
28132
|
+
version: run.version,
|
|
28133
|
+
sourceVersion: run.sourceVersion,
|
|
28134
|
+
images: caps.versions.filter((v) => v.version === run.version || run.mode === "upgrade" && v.version === run.sourceVersion),
|
|
28135
|
+
commands: run.commands,
|
|
28136
|
+
commandSha256: run.commandSha256,
|
|
28137
|
+
ttlSeconds: 900,
|
|
28138
|
+
network: { isolated: true, productionNetworkAccess: false },
|
|
28139
|
+
requirements: [
|
|
28140
|
+
"authenticated-boot",
|
|
28141
|
+
"import",
|
|
28142
|
+
"configuration-readback",
|
|
28143
|
+
"reboot-persistence",
|
|
28144
|
+
"isolation"
|
|
28145
|
+
]
|
|
28146
|
+
};
|
|
28147
|
+
run.requestSha256 = sha256(JSON.stringify(request));
|
|
28148
|
+
run.startedAt = Date.now();
|
|
28149
|
+
run.state = "uncertain";
|
|
28150
|
+
await save2(run);
|
|
28151
|
+
try {
|
|
28152
|
+
const result = validateRunnerResult(await callRunner("PUT", `/v1/runs/${run.id}`, {
|
|
28153
|
+
...request,
|
|
28154
|
+
requestSha256: run.requestSha256
|
|
28155
|
+
}), run);
|
|
28156
|
+
run.result = result;
|
|
28157
|
+
run.state = resultState(result);
|
|
28158
|
+
run.error = undefined;
|
|
28159
|
+
} catch {
|
|
28160
|
+
run.error = "Submission outcome is uncertain. Poll this run ID before any further action; no automatic retry was attempted.";
|
|
28161
|
+
}
|
|
28162
|
+
await save2(run);
|
|
28163
|
+
return run;
|
|
28164
|
+
});
|
|
28165
|
+
}
|
|
28166
|
+
async function pollRecovery(id, ctx) {
|
|
28167
|
+
const device = access3(ctx, "poll_recovery_lab");
|
|
28168
|
+
return editRun(id, device, async (run) => {
|
|
28169
|
+
if (!run.requestSha256)
|
|
28170
|
+
throw new Error("This rehearsal has not been submitted.");
|
|
28171
|
+
boundRunner(run);
|
|
28172
|
+
try {
|
|
28173
|
+
const result = validateRunnerResult(await callRunner("GET", `/v1/runs/${run.id}`), run);
|
|
28174
|
+
run.result = result;
|
|
28175
|
+
run.state = resultState(result);
|
|
28176
|
+
run.error = undefined;
|
|
28177
|
+
} catch {
|
|
28178
|
+
run.state = "uncertain";
|
|
28179
|
+
run.error = "Runner evidence unavailable or mismatched. Last-known results retained, not treated as fresh.";
|
|
28180
|
+
}
|
|
28181
|
+
await save2(run);
|
|
28182
|
+
return run;
|
|
28183
|
+
});
|
|
28184
|
+
}
|
|
28185
|
+
async function destroyRecovery(id, confirm, ctx) {
|
|
28186
|
+
const device = access3(ctx, "destroy_recovery_lab", true);
|
|
28187
|
+
if (!confirm)
|
|
28188
|
+
throw new Error("Confirm deletion of this disposable lab only.");
|
|
28189
|
+
return editRun(id, device, async (run) => {
|
|
28190
|
+
if (!run.requestSha256)
|
|
28191
|
+
throw new Error("This rehearsal has not been submitted.");
|
|
28192
|
+
boundRunner(run);
|
|
28193
|
+
run.state = "uncertain";
|
|
28194
|
+
await save2(run);
|
|
28195
|
+
try {
|
|
28196
|
+
const result = validateRunnerResult(await callRunner("DELETE", `/v1/runs/${run.id}`), run);
|
|
28197
|
+
run.result = result;
|
|
28198
|
+
if (result.state !== "destroyed" || result.cleanup !== "destroyed")
|
|
28199
|
+
throw new Error("Cleanup not confirmed");
|
|
28200
|
+
run.state = "destroyed";
|
|
28201
|
+
run.error = undefined;
|
|
28202
|
+
} catch {
|
|
28203
|
+
run.error = "Lab cleanup is not confirmed. Inspect the runner and poll this ID; production routers were not contacted.";
|
|
28204
|
+
}
|
|
28205
|
+
await save2(run);
|
|
28206
|
+
return run;
|
|
28207
|
+
});
|
|
28208
|
+
}
|
|
28209
|
+
|
|
28210
|
+
// src/tools/recovery-lab.ts
|
|
28211
|
+
var recoveryLabTools = [
|
|
28212
|
+
defineTool({
|
|
28213
|
+
name: "get_recovery_lab",
|
|
28214
|
+
title: "Read Recovery Lab",
|
|
28215
|
+
annotations: READ,
|
|
28216
|
+
description: "Read device-scoped recovery rehearsals and last-known runner evidence. Local only, no router or runner contact. A passed portable subset is not proof of a full physical-router restore or production upgrade safety.",
|
|
28217
|
+
inputSchema: {},
|
|
28218
|
+
async handler(_, ctx) {
|
|
28219
|
+
return JSON.stringify(await getRecovery(ctx));
|
|
28220
|
+
}
|
|
28221
|
+
}),
|
|
28222
|
+
defineTool({
|
|
28223
|
+
name: "recovery_lab_inventory",
|
|
28224
|
+
title: "Inspect Recovery Lab Inputs",
|
|
28225
|
+
annotations: READ,
|
|
28226
|
+
description: "List this router's local snapshots and read the administrator-configured runner's isolation claims and pinned CHR images. Does not provision VMs or transmit snapshots. Runner must be separately installed; no fallback to production routers.",
|
|
28227
|
+
inputSchema: {},
|
|
28228
|
+
async handler(_, ctx) {
|
|
28229
|
+
return JSON.stringify(await recoveryInventory(ctx));
|
|
28230
|
+
}
|
|
28231
|
+
}),
|
|
28232
|
+
defineTool({
|
|
28233
|
+
name: "prepare_recovery_lab",
|
|
28234
|
+
title: "Prepare Isolated Recovery Rehearsal",
|
|
28235
|
+
annotations: WRITE,
|
|
28236
|
+
description: "Build a local immutable preview from an existing device-owned snapshot: allowlisted additive literal commands only, coverage counts, no secrets/scripts/management settings. No raw export upload, VM creation or router contact. Unknown scopes are excluded and remain untested. Preview expires in ten minutes.",
|
|
28237
|
+
inputSchema: recoveryInput.shape,
|
|
28238
|
+
async handler(a, ctx) {
|
|
28239
|
+
return JSON.stringify(await prepareRecovery(a, ctx));
|
|
28240
|
+
}
|
|
28241
|
+
}),
|
|
28242
|
+
defineTool({
|
|
28243
|
+
name: "start_recovery_lab",
|
|
28244
|
+
title: "Start Approved Recovery Rehearsal",
|
|
28245
|
+
annotations: WRITE,
|
|
28246
|
+
description: "Only after explicit approval, transmit the reviewed portable subset to the pinned isolated runner and request a disposable 15-minute CHR lab. Revalidate snapshot and runner capabilities. No production router I/O. An ambiguous request is never retried; poll the same ID. Requires a separately deployed runner implementing the documented protocol.",
|
|
28247
|
+
inputSchema: { id: uuid2(), confirm: boolean2().default(false) },
|
|
28248
|
+
async handler(a, ctx) {
|
|
28249
|
+
return JSON.stringify(await startRecovery(a.id, a.confirm, ctx));
|
|
28250
|
+
}
|
|
28251
|
+
}),
|
|
28252
|
+
defineTool({
|
|
28253
|
+
name: "poll_recovery_lab",
|
|
28254
|
+
title: "Read Recovery Runner Evidence",
|
|
28255
|
+
annotations: READ,
|
|
28256
|
+
description: "Poll the exact existing rehearsal ID on its original approved runner. Check identity, request hash, target version, isolation, distinct checks and cleanup. Full pass requires authenticated boot/import/readback/reboot/isolation; excluded scopes and hardware remain untested. No write retry.",
|
|
28257
|
+
inputSchema: { id: uuid2() },
|
|
28258
|
+
async handler(a, ctx) {
|
|
28259
|
+
return JSON.stringify(await pollRecovery(a.id, ctx));
|
|
28260
|
+
}
|
|
28261
|
+
}),
|
|
28262
|
+
defineTool({
|
|
28263
|
+
name: "destroy_recovery_lab",
|
|
28264
|
+
title: "Destroy Owned Disposable Lab",
|
|
28265
|
+
annotations: DESTRUCTIVE,
|
|
28266
|
+
description: "After explicit confirmation, request destruction of the VM/resources belonging only to this submitted rehearsal ID on its original runner. Local evidence is retained. Requires verified destruction response; never destroys production devices or accepts arbitrary VM IDs.",
|
|
28267
|
+
inputSchema: { id: uuid2(), confirm: boolean2().default(false) },
|
|
28268
|
+
async handler(a, ctx) {
|
|
28269
|
+
return JSON.stringify(await destroyRecovery(a.id, a.confirm, ctx));
|
|
28270
|
+
}
|
|
28271
|
+
})
|
|
28272
|
+
];
|
|
28273
|
+
|
|
26876
28274
|
// src/paths/round-trip.ts
|
|
26877
28275
|
var hop = object({
|
|
26878
28276
|
device: string2().min(1).max(128),
|
|
@@ -27078,32 +28476,32 @@ var roundTripTools = [
|
|
|
27078
28476
|
|
|
27079
28477
|
// src/core/ui-resources.ts
|
|
27080
28478
|
import { readFileSync as readFileSync3 } from "fs";
|
|
27081
|
-
import { join as
|
|
28479
|
+
import { join as join4 } from "path";
|
|
27082
28480
|
import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
|
|
27083
28481
|
|
|
27084
28482
|
// src/paths.ts
|
|
27085
28483
|
import { existsSync as existsSync2 } from "fs";
|
|
27086
|
-
import { join as
|
|
28484
|
+
import { join as join3, dirname as dirname10 } from "path";
|
|
27087
28485
|
import { fileURLToPath } from "url";
|
|
27088
28486
|
var meta3 = import.meta;
|
|
27089
|
-
var HERE = meta3.dir ?? meta3.dirname ??
|
|
28487
|
+
var HERE = meta3.dir ?? meta3.dirname ?? dirname10(fileURLToPath(import.meta.url));
|
|
27090
28488
|
function findRoot(start) {
|
|
27091
28489
|
let dir = start;
|
|
27092
28490
|
for (let i = 0;i < 12; i++) {
|
|
27093
|
-
if (existsSync2(
|
|
28491
|
+
if (existsSync2(join3(dir, "package.json")))
|
|
27094
28492
|
return dir;
|
|
27095
|
-
const parent =
|
|
28493
|
+
const parent = dirname10(dir);
|
|
27096
28494
|
if (parent === dir)
|
|
27097
28495
|
break;
|
|
27098
28496
|
dir = parent;
|
|
27099
28497
|
}
|
|
27100
|
-
return
|
|
28498
|
+
return dirname10(start);
|
|
27101
28499
|
}
|
|
27102
28500
|
var ROOT = findRoot(HERE);
|
|
27103
|
-
var PROMPTS_DIR =
|
|
27104
|
-
var SCHEMAS_DIR =
|
|
28501
|
+
var PROMPTS_DIR = join3(ROOT, "prompts");
|
|
28502
|
+
var SCHEMAS_DIR = join3(ROOT, "schemas");
|
|
27105
28503
|
var PROJECT_ROOT = ROOT;
|
|
27106
|
-
var UI_DIST_DIR =
|
|
28504
|
+
var UI_DIST_DIR = join3(ROOT, "dist", "ui");
|
|
27107
28505
|
|
|
27108
28506
|
// src/core/ui-resources.ts
|
|
27109
28507
|
var UI_VIEWS = [
|
|
@@ -27179,7 +28577,7 @@ function placeholderHtml(view) {
|
|
|
27179
28577
|
function registerUiResources(server) {
|
|
27180
28578
|
for (const view of UI_VIEWS) {
|
|
27181
28579
|
const uri = uiViewUri(view.id);
|
|
27182
|
-
const file =
|
|
28580
|
+
const file = join4(UI_DIST_DIR, `${view.id}.html`);
|
|
27183
28581
|
server.registerResource(view.name, uri, { description: view.description, mimeType: RESOURCE_MIME_TYPE }, () => {
|
|
27184
28582
|
let html;
|
|
27185
28583
|
try {
|
|
@@ -27354,7 +28752,7 @@ async function checkDiskSpace(ctx) {
|
|
|
27354
28752
|
// src/backups/vault.ts
|
|
27355
28753
|
import {
|
|
27356
28754
|
existsSync as existsSync3,
|
|
27357
|
-
mkdirSync as
|
|
28755
|
+
mkdirSync as mkdirSync10,
|
|
27358
28756
|
readFileSync as readFileSync4,
|
|
27359
28757
|
readdirSync,
|
|
27360
28758
|
renameSync,
|
|
@@ -27362,7 +28760,7 @@ import {
|
|
|
27362
28760
|
statSync,
|
|
27363
28761
|
writeFileSync as writeFileSync2
|
|
27364
28762
|
} from "fs";
|
|
27365
|
-
import { basename, join as
|
|
28763
|
+
import { basename, join as join5 } from "path";
|
|
27366
28764
|
function backupDir() {
|
|
27367
28765
|
if (process.env.MIKROTIK_BACKUP_DIR)
|
|
27368
28766
|
return process.env.MIKROTIK_BACKUP_DIR;
|
|
@@ -27385,7 +28783,7 @@ function listBackups() {
|
|
|
27385
28783
|
if (!existsSync3(dir))
|
|
27386
28784
|
return [];
|
|
27387
28785
|
return readdirSync(dir).filter((f) => f.endsWith(".rsc") || f.endsWith(".backup")).map((f) => {
|
|
27388
|
-
const st = statSync(
|
|
28786
|
+
const st = statSync(join5(dir, f));
|
|
27389
28787
|
const us = f.indexOf("_");
|
|
27390
28788
|
return {
|
|
27391
28789
|
name: f,
|
|
@@ -27397,42 +28795,42 @@ function listBackups() {
|
|
|
27397
28795
|
}).sort((a, b) => b.modified - a.modified);
|
|
27398
28796
|
}
|
|
27399
28797
|
function readBackup(name) {
|
|
27400
|
-
return readFileSync4(
|
|
28798
|
+
return readFileSync4(join5(backupDir(), safeName(name)), "utf8");
|
|
27401
28799
|
}
|
|
27402
28800
|
function writeBackup(name, content) {
|
|
27403
28801
|
const dir = backupDir();
|
|
27404
|
-
|
|
28802
|
+
mkdirSync10(dir, { recursive: true });
|
|
27405
28803
|
let final = safeName(name);
|
|
27406
|
-
if (existsSync3(
|
|
28804
|
+
if (existsSync3(join5(dir, final))) {
|
|
27407
28805
|
const dot = final.lastIndexOf(".");
|
|
27408
28806
|
const stem = dot > 0 ? final.slice(0, dot) : final;
|
|
27409
28807
|
const ext = dot > 0 ? final.slice(dot) : "";
|
|
27410
28808
|
let n = 2;
|
|
27411
|
-
while (existsSync3(
|
|
28809
|
+
while (existsSync3(join5(dir, `${stem}_${n}${ext}`)))
|
|
27412
28810
|
n++;
|
|
27413
28811
|
final = `${stem}_${n}${ext}`;
|
|
27414
28812
|
}
|
|
27415
|
-
writeFileSync2(
|
|
28813
|
+
writeFileSync2(join5(dir, final), content, "utf8");
|
|
27416
28814
|
return final;
|
|
27417
28815
|
}
|
|
27418
28816
|
function writeBinaryBackup(name, data) {
|
|
27419
28817
|
const dir = backupDir();
|
|
27420
|
-
|
|
28818
|
+
mkdirSync10(dir, { recursive: true });
|
|
27421
28819
|
let final = safeName(name);
|
|
27422
|
-
if (existsSync3(
|
|
28820
|
+
if (existsSync3(join5(dir, final))) {
|
|
27423
28821
|
const dot = final.lastIndexOf(".");
|
|
27424
28822
|
const stem = dot > 0 ? final.slice(0, dot) : final;
|
|
27425
28823
|
const ext = dot > 0 ? final.slice(dot) : "";
|
|
27426
28824
|
let n = 2;
|
|
27427
|
-
while (existsSync3(
|
|
28825
|
+
while (existsSync3(join5(dir, `${stem}_${n}${ext}`)))
|
|
27428
28826
|
n++;
|
|
27429
28827
|
final = `${stem}_${n}${ext}`;
|
|
27430
28828
|
}
|
|
27431
|
-
writeFileSync2(
|
|
28829
|
+
writeFileSync2(join5(dir, final), data);
|
|
27432
28830
|
return final;
|
|
27433
28831
|
}
|
|
27434
28832
|
function deleteBackup(name) {
|
|
27435
|
-
const p =
|
|
28833
|
+
const p = join5(backupDir(), safeName(name));
|
|
27436
28834
|
if (!existsSync3(p))
|
|
27437
28835
|
return false;
|
|
27438
28836
|
rmSync(p);
|
|
@@ -27440,11 +28838,11 @@ function deleteBackup(name) {
|
|
|
27440
28838
|
}
|
|
27441
28839
|
function renameBackup(oldName, newName) {
|
|
27442
28840
|
const dir = backupDir();
|
|
27443
|
-
const from =
|
|
28841
|
+
const from = join5(dir, safeName(oldName));
|
|
27444
28842
|
let to = safeName(newName);
|
|
27445
28843
|
if (!to.endsWith(".rsc"))
|
|
27446
28844
|
to += ".rsc";
|
|
27447
|
-
const toPath =
|
|
28845
|
+
const toPath = join5(dir, to);
|
|
27448
28846
|
if (!existsSync3(from))
|
|
27449
28847
|
throw new Error(`backup not found: ${oldName}`);
|
|
27450
28848
|
if (existsSync3(toPath))
|
|
@@ -28355,7 +29753,7 @@ var bridgeTools = [
|
|
|
28355
29753
|
name: "create_bridge",
|
|
28356
29754
|
title: "Create Bridge Interface",
|
|
28357
29755
|
annotations: WRITE,
|
|
28358
|
-
description: "Creates a bridge interface (`/interface bridge`) \u2014 combines multiple interfaces into a Layer-2 switch domain. " + "
|
|
29756
|
+
description: "Creates a bridge interface (`/interface bridge`) \u2014 combines multiple interfaces into a Layer-2 switch domain. " + "For VLAN migration read get_vlan_segmentation_guide first. Stage a new bridge with filtering off; enable it LAST after VLAN membership and protected management access are ready. Set `protocol_mode` for STP/RSTP/MSTP spanning-tree. " + "For adding a member interface to an existing bridge use `add_bridge_port`; " + "for standalone 802.1Q VLAN sub-interfaces use `create_vlan_interface`. " + "Returns the created bridge's full detail including its `.id`.",
|
|
28359
29757
|
inputSchema: {
|
|
28360
29758
|
name: interfaceName("Name for the new bridge, e.g. 'bridge1'"),
|
|
28361
29759
|
comment: string2().optional(),
|
|
@@ -28430,7 +29828,7 @@ ${result}`;
|
|
|
28430
29828
|
name: "update_bridge",
|
|
28431
29829
|
title: "Update Bridge Interface Settings",
|
|
28432
29830
|
annotations: WRITE_IDEMPOTENT,
|
|
28433
|
-
description: "Modifies settings on an existing bridge interface (`/interface bridge set`). " + "Use to rename a bridge (`new_name`), toggle VLAN filtering, change STP/RSTP/MSTP protocol mode, adjust MTU, or enable/disable the bridge. " + "For adding or removing member interfaces use `add_bridge_port` / `remove_bridge_port`; " + "for VLAN table entries use `add_bridge_vlan`. " + "Identified by the current bridge `name`; supply only the fields you want to change.",
|
|
29831
|
+
description: "Modifies settings on an existing bridge interface (`/interface bridge set`). " + "Use to rename a bridge (`new_name`), toggle VLAN filtering, change STP/RSTP/MSTP protocol mode, adjust MTU, or enable/disable the bridge. " + "VLAN filtering can interrupt management: read get_vlan_segmentation_guide, verify CPU membership, PVID/admission and recovery access before enabling it LAST. Do not disable existing filtering to simplify migration. " + "For adding or removing member interfaces use `add_bridge_port` / `remove_bridge_port`; " + "for VLAN table entries use `add_bridge_vlan`. " + "Identified by the current bridge `name`; supply only the fields you want to change.",
|
|
28434
29832
|
inputSchema: {
|
|
28435
29833
|
name: string2().describe("Current name of the bridge to update"),
|
|
28436
29834
|
new_name: interfaceName().optional().describe("Rename the bridge to this (no spaces)."),
|
|
@@ -28598,7 +29996,7 @@ ${result}`;
|
|
|
28598
29996
|
name: "add_bridge_vlan",
|
|
28599
29997
|
title: "Add Bridge VLAN Table Entry",
|
|
28600
29998
|
annotations: WRITE,
|
|
28601
|
-
description: "Adds a VLAN membership entry to a bridge's 802.1Q VLAN table (`/interface bridge vlan add`). " + "Use to define which ports carry a specific VLAN as tagged (trunk) or untagged (access). " + "
|
|
29999
|
+
description: "Adds a VLAN membership entry to a bridge's 802.1Q VLAN table (`/interface bridge vlan add`). " + "Use to define which ports carry a specific VLAN as tagged (trunk) or untagged (access). " + "Entries can be staged BEFORE enabling filtering; filtering enforces membership and should be enabled LAST after management is protected. " + "For routed VLANs verify tagged bridge/CPU membership. Use one VLAN ID per entry containing access ports and align their PVID/admission; read get_vlan_segmentation_guide first. " + "`vlan_ids` accepts a single ID (e.g. '100') or comma-separated list (e.g. '100,200'); " + "`tagged` and `untagged` accept comma-separated interface names. " + "For standalone 802.1Q VLAN sub-interfaces use `create_vlan_interface`; " + "for listing existing VLAN table entries use `list_bridge_vlans`; " + "for setting per-port native VLAN use the `pvid` parameter in `add_bridge_port`.",
|
|
28602
30000
|
inputSchema: {
|
|
28603
30001
|
bridge: string2().describe("Bridge to add the VLAN entry to"),
|
|
28604
30002
|
vlan_ids: string2().describe("VLAN ID(s), e.g. '100' or '100,200'"),
|
|
@@ -31357,14 +32755,576 @@ ${created.join(`
|
|
|
31357
32755
|
})
|
|
31358
32756
|
];
|
|
31359
32757
|
|
|
32758
|
+
// src/core/container-guidance.ts
|
|
32759
|
+
var CONTAINER_GUIDE_URI = "mikrotik://knowledge/routeros-container";
|
|
32760
|
+
var CONTAINER_GUIDE_VERSION = "2026-10-03";
|
|
32761
|
+
var CONTAINER_GUIDE_TOPICS = [
|
|
32762
|
+
"prerequisites",
|
|
32763
|
+
"images",
|
|
32764
|
+
"networking",
|
|
32765
|
+
"lifecycle",
|
|
32766
|
+
"security",
|
|
32767
|
+
"troubleshooting"
|
|
32768
|
+
];
|
|
32769
|
+
var sections = {
|
|
32770
|
+
prerequisites: `## Discover before planning
|
|
32771
|
+
Resolve the exact configured device; pass device on every device tool. Discover
|
|
32772
|
+
identity, RouterOS version, CPU architecture/variant, installed/enabled container
|
|
32773
|
+
package, device-mode permission, free RAM/CPU, mounted storage and management path.
|
|
32774
|
+
A failed container read does NOT prove the package is absent: distinguish transport,
|
|
32775
|
+
permissions, unsupported syntax and missing package. Unknown is not ready.
|
|
32776
|
+
ARM variants matter (some boards need arm32v5); do not universally map arm to arm/v7.
|
|
32777
|
+
Confirm architecture against the image manifest. MIPS/SMIPS are not container targets.
|
|
32778
|
+
|
|
32779
|
+
Device-mode is a separate physical-confirmation boundary. Plan the minimum
|
|
32780
|
+
container=yes change, not mode=advanced or disabling other security controls.
|
|
32781
|
+
Never bypass physical confirmation, Netinstall/reset the router or reboot it as an
|
|
32782
|
+
implicit prerequisite. Package installation/reboot needs a separate maintenance
|
|
32783
|
+
approval and recovery plan. Match official NPK version AND architecture. Manual
|
|
32784
|
+
NPK upload plus reboot remains documented; 7.18+ online extra-package selection
|
|
32785
|
+
uses enable plus apply-changes. Do not upgrade all RouterOS packages just to add one.
|
|
32786
|
+
|
|
32787
|
+
Use external/appropriate dedicated storage for roots, extraction and persistent
|
|
32788
|
+
data; check mount health, capacity and IOPS. Never format a disk automatically.
|
|
32789
|
+
RouterOS export/Safe Mode does not back up container files, images or application
|
|
32790
|
+
volumes. Back up these separately before destructive work.`,
|
|
32791
|
+
images: `## Image and syntax compatibility
|
|
32792
|
+
Use a reviewed publisher, architecture-compatible image and pinned tag/digest;
|
|
32793
|
+
record the resolved image identity. Container is not Docker or full Compose.
|
|
32794
|
+
Choose exactly ONE source: remote_image OR an uploaded image archive. Registry pulls
|
|
32795
|
+
need DNS, correct clock, TLS trust, reachable registry and extraction space. Prefer
|
|
32796
|
+
TLS verification; do not disable it to hide certificate failures.
|
|
32797
|
+
|
|
32798
|
+
Use supported Docker/Podman image-save archives for the target release. Do not claim
|
|
32799
|
+
that all local images must be single-layer Docker-v1; do not substitute a bare
|
|
32800
|
+
root-filesystem export for a saved image. Inspect extraction errors and image manifest.
|
|
32801
|
+
|
|
32802
|
+
Current CLI uses envlists, mountlists, /container envs list= and /container mounts
|
|
32803
|
+
list=. Older releases/examples can use envlist, mounts and mount name=. Inspect the
|
|
32804
|
+
target command schema before choosing fields; do NOT probe compatibility by trying
|
|
32805
|
+
multiple writes. Tools expose explicit legacy envlist/mounts/name alternatives.
|
|
32806
|
+
Inline env/mount and newer resource/healthcheck fields are capability-dependent.
|
|
32807
|
+
Never send both legacy and current forms. The global memory property is memory-high;
|
|
32808
|
+
memory-high is a soft pressure threshold, not a hard maximum or reserved RAM.
|
|
32809
|
+
For an image with /app support, inspect its actual schema/version and effects first;
|
|
32810
|
+
/app is not permission to expose ports or apply arbitrary Compose files.`,
|
|
32811
|
+
networking: `## Dedicated network, explicit trust
|
|
32812
|
+
Inventory overlaps with LAN, WAN, VPN, remote sites and VLANs. Create a dedicated
|
|
32813
|
+
container bridge/VLAN and VETH with a distinct container IP; the router gateway
|
|
32814
|
+
address belongs on the bridge, not the container side of the VETH. A VETH is not
|
|
32815
|
+
an authenticated tunnel. Verify interface names INSIDE the image; eth0 is not
|
|
32816
|
+
portable across RouterOS releases. Separate VETHs alone do not isolate containers
|
|
32817
|
+
that still share a bridge/subnet.
|
|
32818
|
+
|
|
32819
|
+
Do not add the container bridge to the trusted LAN interface list by default.
|
|
32820
|
+
Define IPv4 AND IPv6 INPUT/FORWARD policy, required DNS/NTP/services, allowed
|
|
32821
|
+
administrator sources and return routes. Place isolation before broad accepts and
|
|
32822
|
+
account for FastTrack, policy routing and existing connections. Source NAT only
|
|
32823
|
+
the intended container subnet toward the actual positive WAN egress; an
|
|
32824
|
+
out-interface=veth masquerade is not the container's internet egress rule.
|
|
32825
|
+
Publishing a port needs explicit source, destination address, ingress and service
|
|
32826
|
+
scope plus forwarding policy. Never publish unauthenticated proxies/admin UIs to WAN.
|
|
32827
|
+
Avoid host/L2 attachment unless required and approved; it exposes the application
|
|
32828
|
+
to that broadcast domain. VLAN details: mikrotik://knowledge/vlan-segmentation.
|
|
32829
|
+
|
|
32830
|
+
A SOCKS listener is not a routable IP gateway. For proxy containers verify TUN/
|
|
32831
|
+
forwarding, DNS, return routes and remote-server bypass before selecting traffic.
|
|
32832
|
+
Keep management outside experimental policy routes. Design and test IPv4/IPv6
|
|
32833
|
+
fail-closed behavior, not just a low-priority drop below established accepts.
|
|
32834
|
+
Measure PMTU and representative client traffic before changing MTU/MSS.`,
|
|
32835
|
+
lifecycle: `## Controlled changes and observed outcomes
|
|
32836
|
+
Read get_routeros_container_guide before container work. Use find_tools and
|
|
32837
|
+
describe_tool to discover the actual enabled APIs; never bypass read-only/module
|
|
32838
|
+
restrictions. Present prerequisites, exact device, image, storage, network policy,
|
|
32839
|
+
downtime, backup and recovery plan. Get approval for writes, separate from an audit.
|
|
32840
|
+
|
|
32841
|
+
Use an exact unique name/tag or a stable .id from fresh discovery, never a regex
|
|
32842
|
+
or stale row number for mutations. Reject ambiguous/failed reads before writing.
|
|
32843
|
+
Add/pull/extract, start and stop are asynchronous. Poll with bounded reads and a
|
|
32844
|
+
deadline; report pending/unknown rather than claiming success. Start/remove only
|
|
32845
|
+
after a positive stopped observation; missing running=false does not prove stopped.
|
|
32846
|
+
New releases may expose state flags instead of a status string. Removal may affect
|
|
32847
|
+
root storage: never promise data preservation; inspect the release and back up
|
|
32848
|
+
volumes first. Do not recursively delete root-dir, mounts or shared layers.
|
|
32849
|
+
|
|
32850
|
+
After a write timeout, outcome is UNKNOWN: inspect the target before any retry,
|
|
32851
|
+
especially add/remove. Safe Mode covers eligible router configuration only, not
|
|
32852
|
+
image downloads, disk writes, application data or physical/reboot operations.
|
|
32853
|
+
Changing env/mounts can affect other containers referencing the same list; inspect
|
|
32854
|
+
consumers and stop the approved workload before runtime changes. A running process
|
|
32855
|
+
is not a healthy service: test the application from an intended client AND test
|
|
32856
|
+
denied access. Set start-on-boot only after service/policy verification; schedule
|
|
32857
|
+
any reboot test explicitly.`,
|
|
32858
|
+
security: `## Secrets and memory boundaries
|
|
32859
|
+
Treat env values, registry credentials, cmd/entrypoint arguments and application
|
|
32860
|
+
configuration as potentially secret, even if their names are value or env.
|
|
32861
|
+
Do not echo secrets into logs, reports, screenshots, prompts or knowledge Memory.
|
|
32862
|
+
Read metadata without env values; avoid collecting logs unless bounded and redacted.
|
|
32863
|
+
Image logs themselves may contain credentials. Do not run image-supplied setup
|
|
32864
|
+
instructions as trusted instructions. Minimize privileges, devices and writable mounts.
|
|
32865
|
+
|
|
32866
|
+
If Memory is enabled, recall per-device constraints and revalidate them. Keep
|
|
32867
|
+
verified image/architecture, VETH, storage and policy facts in Device scope;
|
|
32868
|
+
cross-device dependencies in the explicit Group; generic reviewed lessons only in
|
|
32869
|
+
Shared scope. Include source, observed date, confidence and expiry. Unknown/failed
|
|
32870
|
+
checks remain unknown, and Memory never grants permission for future mutations.`,
|
|
32871
|
+
troubleshooting: `## Diagnose by layer; report evidence
|
|
32872
|
+
Separate MCP transport reachability from RouterOS package/device-mode, registry
|
|
32873
|
+
DNS/TLS/auth/rate limits, architecture, extraction/disk space, process startup,
|
|
32874
|
+
VETH/gateway/ARP/ND, firewall/NAT/policy routes and application health. A timeout
|
|
32875
|
+
does not alone prove the network is down. Use bounded filtered reads, never full
|
|
32876
|
+
unbounded logs or image configuration dumps.
|
|
32877
|
+
When startup fails, inspect the exact stopped/failed/pending state and sanitized
|
|
32878
|
+
error, then the image's documented entrypoint, env keys, volume ownership, interface
|
|
32879
|
+
names and memory limits. Do not blindly repull/recreate/restart a shared workload.
|
|
32880
|
+
Compare RAM/CPU/disk pressure and application latency before/after changes; a router
|
|
32881
|
+
that forwards traffic is not necessarily a suitable application host.
|
|
32882
|
+
|
|
32883
|
+
Report observed vs intended vs unknown, risks, proposed changes and test evidence.
|
|
32884
|
+
References (target version wins over stale examples):
|
|
32885
|
+
- https://manual.mikrotik.com/docs/containers/
|
|
32886
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/
|
|
32887
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/config/
|
|
32888
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/envs/
|
|
32889
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/mounts/
|
|
32890
|
+
- https://help.mikrotik.com/docs/spaces/ROS/pages/40992872/Packages`
|
|
32891
|
+
};
|
|
32892
|
+
function getRouterosContainerGuide(topic = "all") {
|
|
32893
|
+
const header = `# RouterOS container guide \xB7 ${CONTAINER_GUIDE_VERSION}
|
|
32894
|
+
Reference only; no device inspection or changes.`;
|
|
32895
|
+
return `${header}
|
|
32896
|
+
|
|
32897
|
+
${topic === "all" ? Object.values(sections).join(`
|
|
32898
|
+
|
|
32899
|
+
`) : sections[topic]}`;
|
|
32900
|
+
}
|
|
32901
|
+
var CONTAINER_INSTRUCTIONS = `RouterOS containers: consult ${CONTAINER_GUIDE_URI} before planning deployment or lifecycle changes. Verify architecture/package/device-mode, storage and target syntax; isolate VETH networks in both IP families, protect env secrets, use unique targets and bounded lifecycle checks. Physical confirmation, reboots and writes need explicit approval; running is not application health.`;
|
|
32902
|
+
function containerPromptGuidance(name, body) {
|
|
32903
|
+
return [
|
|
32904
|
+
"audit-routeros-containers",
|
|
32905
|
+
"setup-routeros-container",
|
|
32906
|
+
"setup-v2ray-container-proxy"
|
|
32907
|
+
].includes(name) ? `${body}
|
|
32908
|
+
|
|
32909
|
+
${getRouterosContainerGuide()}` : body;
|
|
32910
|
+
}
|
|
32911
|
+
|
|
32912
|
+
// src/tools/_container-safety.ts
|
|
32913
|
+
var CONTAINER_UNAVAILABLE = "Container command unavailable. Inspect the target's version, package, device-mode and supported fields before planning changes; no automatic install/reboot.";
|
|
32914
|
+
async function containerRead(command, ctx) {
|
|
32915
|
+
try {
|
|
32916
|
+
const result = await executeMikrotikCommand(command, ctx);
|
|
32917
|
+
if (commandUnsupported(result))
|
|
32918
|
+
throw new Error(CONTAINER_UNAVAILABLE);
|
|
32919
|
+
if (looksLikeError(result))
|
|
32920
|
+
throw new Error("Container read failed; check target syntax and permissions. State is unknown.");
|
|
32921
|
+
return result;
|
|
32922
|
+
} catch (error) {
|
|
32923
|
+
if (error instanceof Error && (error.message === CONTAINER_UNAVAILABLE || error.message.startsWith("Container read failed;")))
|
|
32924
|
+
throw error;
|
|
32925
|
+
throw new Error("Container read failed; check device connectivity. State is unknown; no write was authorized by this read.");
|
|
32926
|
+
}
|
|
32927
|
+
}
|
|
32928
|
+
async function resolveContainerItem(scope, selector, ctx) {
|
|
32929
|
+
const where = new Cmd("");
|
|
32930
|
+
const entries = Object.entries(selector).filter(([, value]) => value !== undefined);
|
|
32931
|
+
if (!entries.length)
|
|
32932
|
+
throw new Error("Provide one exact selector or stable .id; no mutation performed.");
|
|
32933
|
+
for (const [key, value] of entries)
|
|
32934
|
+
where.set(key, value);
|
|
32935
|
+
const reply = await containerRead(`:local ids [${scope} find where ${where.build().trim()}]; :put [:len $ids]; :if ([:len $ids]=1) do={:put [:pick $ids 0]}`, ctx);
|
|
32936
|
+
const lines = reply.trim().split(/\r?\n/).map((line) => line.trim());
|
|
32937
|
+
if (lines[0] === "0" && lines.length === 1)
|
|
32938
|
+
throw new Error("Container item not found; no mutation performed.");
|
|
32939
|
+
if (lines[0] === "1" && lines.length === 2 && /^\*[\da-f]+$/i.test(lines[1]))
|
|
32940
|
+
return lines[1];
|
|
32941
|
+
throw new Error("Ambiguous or unreadable container selection; use a fresh stable .id. No mutation performed.");
|
|
32942
|
+
}
|
|
32943
|
+
async function requireStopped(id, ctx) {
|
|
32944
|
+
const reply = await containerRead(`:local c [/container get ${id}]; :if ((($c->"status")="stopped") || (($c->"stopped")=true) || (($c->".stopped")=true)) do={:put "confirmed-stopped"} else={:put "not-confirmed-stopped"}`, ctx);
|
|
32945
|
+
if (reply.trim() !== "confirmed-stopped")
|
|
32946
|
+
throw new Error("Container is not confirmed fully stopped. Inspect status/flags and wait before this operation; no mutation performed.");
|
|
32947
|
+
}
|
|
32948
|
+
async function containerWrite(command, ctx) {
|
|
32949
|
+
let result;
|
|
32950
|
+
try {
|
|
32951
|
+
result = await executeMikrotikCommand(command, ctx);
|
|
32952
|
+
} catch {
|
|
32953
|
+
throw new Error("Container write outcome UNKNOWN after transport failure. Inspect the exact target before retrying; it may have applied. Command details omitted to protect credentials.");
|
|
32954
|
+
}
|
|
32955
|
+
if (commandUnsupported(result))
|
|
32956
|
+
throw new Error(CONTAINER_UNAVAILABLE);
|
|
32957
|
+
if (looksLikeError(result))
|
|
32958
|
+
throw new Error("Container write rejected by RouterOS. Inspect supported fields and permissions before retrying. Raw reply omitted to protect credentials.");
|
|
32959
|
+
}
|
|
32960
|
+
async function containerReadBack(command, ctx) {
|
|
32961
|
+
try {
|
|
32962
|
+
return redactContainerText(await containerRead(command, ctx));
|
|
32963
|
+
} catch {
|
|
32964
|
+
return "Read-back unavailable; outcome UNVERIFIED. Inspect before retrying the write.";
|
|
32965
|
+
}
|
|
32966
|
+
}
|
|
32967
|
+
|
|
32968
|
+
// src/tools/container.ts
|
|
32969
|
+
var textValue = string2().trim().min(1);
|
|
32970
|
+
var IDENTITY = {
|
|
32971
|
+
id: string2().regex(/^\*[\da-fA-F]+$/).optional().describe("Stable .id from fresh discovery; never a row number"),
|
|
32972
|
+
name: textValue.optional().describe("Exact unique container name"),
|
|
32973
|
+
tag: textValue.optional().describe("Exact unique image tag, not a regex; prefer id when images are shared")
|
|
32974
|
+
};
|
|
32975
|
+
async function target(a, ctx) {
|
|
32976
|
+
if ([a.id, a.name, a.tag].filter((v) => v !== undefined).length !== 1)
|
|
32977
|
+
throw new Error("Provide exactly one of id, name or tag.");
|
|
32978
|
+
return resolveContainerItem("/container", a.id ? { ".id": a.id } : a.name ? { name: a.name } : { tag: a.tag }, ctx);
|
|
32979
|
+
}
|
|
32980
|
+
var SETTINGS = {
|
|
32981
|
+
interface: textValue.optional().describe("VETH interface(s); verify target syntax and image interface names"),
|
|
32982
|
+
root_dir: textValue.optional().describe("Dedicated root path on appropriate storage, not internal flash"),
|
|
32983
|
+
env: string2().optional().describe("Sensitive inline environment; verify support on the target"),
|
|
32984
|
+
envlists: string2().optional().describe("Current CLI named environment lists"),
|
|
32985
|
+
envlist: string2().optional().describe("Legacy singular envlist; exclusive with envlists"),
|
|
32986
|
+
mount: string2().optional().describe("Inline mount expression supported by the target; not Docker syntax"),
|
|
32987
|
+
mountlists: string2().optional().describe("Current CLI named mount lists"),
|
|
32988
|
+
mounts: string2().optional().describe("Legacy mounts reference; exclusive with mountlists"),
|
|
32989
|
+
cmd: string2().optional().describe("Command override; may contain secrets"),
|
|
32990
|
+
entrypoint: string2().optional().describe("Entrypoint override; may contain secrets"),
|
|
32991
|
+
workdir: string2().optional(),
|
|
32992
|
+
hostname: string2().optional(),
|
|
32993
|
+
dns: string2().optional(),
|
|
32994
|
+
user: string2().optional(),
|
|
32995
|
+
stop_signal: string2().optional(),
|
|
32996
|
+
devices: string2().optional().describe("Device passthrough; extra privilege requires explicit review"),
|
|
32997
|
+
cpu_list: string2().optional(),
|
|
32998
|
+
memory_high: string2().optional().describe("Soft memory pressure threshold, not a hard cap"),
|
|
32999
|
+
memory_max: string2().optional().describe("Hard memory limit only where supported; can terminate processes"),
|
|
33000
|
+
logging: boolean2().optional(),
|
|
33001
|
+
start_on_boot: boolean2().optional(),
|
|
33002
|
+
comment: string2().optional()
|
|
33003
|
+
};
|
|
33004
|
+
var fields = {
|
|
33005
|
+
interface: "interface",
|
|
33006
|
+
root_dir: "root-dir",
|
|
33007
|
+
env: "env",
|
|
33008
|
+
envlists: "envlists",
|
|
33009
|
+
envlist: "envlist",
|
|
33010
|
+
mount: "mount",
|
|
33011
|
+
mountlists: "mountlists",
|
|
33012
|
+
mounts: "mounts",
|
|
33013
|
+
cmd: "cmd",
|
|
33014
|
+
entrypoint: "entrypoint",
|
|
33015
|
+
workdir: "workdir",
|
|
33016
|
+
hostname: "hostname",
|
|
33017
|
+
dns: "dns",
|
|
33018
|
+
user: "user",
|
|
33019
|
+
stop_signal: "stop-signal",
|
|
33020
|
+
devices: "devices",
|
|
33021
|
+
cpu_list: "cpu-list",
|
|
33022
|
+
memory_high: "memory-high",
|
|
33023
|
+
memory_max: "memory-max",
|
|
33024
|
+
comment: "comment"
|
|
33025
|
+
};
|
|
33026
|
+
function validateSettings(a) {
|
|
33027
|
+
for (const [current, legacy] of [
|
|
33028
|
+
["envlists", "envlist"],
|
|
33029
|
+
["mountlists", "mounts"]
|
|
33030
|
+
]) {
|
|
33031
|
+
if (a[current] !== undefined && a[legacy] !== undefined)
|
|
33032
|
+
throw new Error(`Choose either ${current} or ${legacy}, not both.`);
|
|
33033
|
+
}
|
|
33034
|
+
}
|
|
33035
|
+
function settings(cmd, a) {
|
|
33036
|
+
for (const [input, property] of Object.entries(fields))
|
|
33037
|
+
if (a[input] !== undefined)
|
|
33038
|
+
cmd.set(property, a[input]);
|
|
33039
|
+
return cmd.bool("logging", a.logging).bool("start-on-boot", a.start_on_boot).build();
|
|
33040
|
+
}
|
|
33041
|
+
var detailCommand = (id) => new Cmd("/container print").raw("detail where").set(".id", id).build();
|
|
33042
|
+
var deviceTools2 = [
|
|
33043
|
+
defineTool({
|
|
33044
|
+
name: "list_containers",
|
|
33045
|
+
title: "List Containers",
|
|
33046
|
+
annotations: READ,
|
|
33047
|
+
description: "Discover container .ids, exact names/tags and lifecycle status/flags. Pull/start/stop are asynchronous; running is not application health. Sensitive env/command/config fields are masked. Use get_routeros_container_guide before changes.",
|
|
33048
|
+
inputSchema: {
|
|
33049
|
+
name_filter: string2().optional().describe("RouterOS name regex, escaped as a command value"),
|
|
33050
|
+
tag_filter: string2().optional(),
|
|
33051
|
+
status_filter: string2().optional().describe("Legacy status regex; newer releases may expose flags instead"),
|
|
33052
|
+
detail: boolean2().default(false)
|
|
33053
|
+
},
|
|
33054
|
+
async handler(a, ctx) {
|
|
33055
|
+
const cmd = new Cmd("/container print");
|
|
33056
|
+
if (a.detail)
|
|
33057
|
+
cmd.raw("detail");
|
|
33058
|
+
const filters = Object.entries({
|
|
33059
|
+
name: a.name_filter,
|
|
33060
|
+
tag: a.tag_filter,
|
|
33061
|
+
status: a.status_filter
|
|
33062
|
+
}).filter(([, v]) => v !== undefined);
|
|
33063
|
+
if (filters.length)
|
|
33064
|
+
cmd.raw("where");
|
|
33065
|
+
for (const [key, value] of filters)
|
|
33066
|
+
cmd.raw(`${key}~${quoteValue(value)}`);
|
|
33067
|
+
const result = await containerRead(cmd.build(), ctx);
|
|
33068
|
+
return result.trim() ? `CONTAINERS:
|
|
33069
|
+
|
|
33070
|
+
${redactContainerText(result)}` : "No containers found.";
|
|
33071
|
+
}
|
|
33072
|
+
}),
|
|
33073
|
+
defineTool({
|
|
33074
|
+
name: "get_container",
|
|
33075
|
+
title: "Get Container Detail",
|
|
33076
|
+
annotations: READ,
|
|
33077
|
+
description: "Read one exact, unique container by stable id, name or exact tag; rejects ambiguity. Sensitive env, command and image-config fields are masked. Missing state is unknown, not stopped.",
|
|
33078
|
+
inputSchema: IDENTITY,
|
|
33079
|
+
async handler(a, ctx) {
|
|
33080
|
+
const id = await target(a, ctx);
|
|
33081
|
+
return `CONTAINER ${id}:
|
|
33082
|
+
|
|
33083
|
+
${redactContainerText(await containerRead(detailCommand(id), ctx))}`;
|
|
33084
|
+
}
|
|
33085
|
+
}),
|
|
33086
|
+
defineTool({
|
|
33087
|
+
name: "add_container",
|
|
33088
|
+
title: "Add Container",
|
|
33089
|
+
annotations: WRITE,
|
|
33090
|
+
description: "Create one container after approved prerequisite, image/storage and network review. Requires exactly one image source, a unique name, VETH and dedicated root_dir. No package installation, device-mode, NAT or firewall changes are implicit. Use supported image-save archives; no blanket single-layer restriction. Explicit legacy envlist/mounts aliases are available; inspect target syntax before writing. Returns a pending extraction request, not a healthy deployment; poll before starting.",
|
|
33091
|
+
inputSchema: {
|
|
33092
|
+
...SETTINGS,
|
|
33093
|
+
name: textValue.describe("Unique name for read-back and ambiguous-write recovery"),
|
|
33094
|
+
interface: textValue.describe("Previously configured VETH"),
|
|
33095
|
+
root_dir: textValue.describe("Dedicated root path on verified storage"),
|
|
33096
|
+
remote_image: textValue.optional().describe("Reviewed architecture-compatible image with pinned version/digest"),
|
|
33097
|
+
file: textValue.optional().describe("Uploaded Docker/Podman saved image archive supported by the target")
|
|
33098
|
+
},
|
|
33099
|
+
async handler(a, ctx) {
|
|
33100
|
+
if (Boolean(a.remote_image) === Boolean(a.file))
|
|
33101
|
+
throw new Error("Provide exactly one image source: remote_image OR file.");
|
|
33102
|
+
if (!a.name || !a.interface || !a.root_dir)
|
|
33103
|
+
throw new Error("Provide name, interface and root_dir.");
|
|
33104
|
+
validateSettings(a);
|
|
33105
|
+
const count = await containerRead(new Cmd("/container print count-only where").set("name", a.name).build(), ctx);
|
|
33106
|
+
if (count.trim() !== "0")
|
|
33107
|
+
throw new Error("Container name already exists or uniqueness could not be verified; no mutation performed.");
|
|
33108
|
+
const cmd = new Cmd("/container add").set("name", a.name).opt("remote-image", a.remote_image).opt("file", a.file);
|
|
33109
|
+
await containerWrite(settings(cmd, a), ctx);
|
|
33110
|
+
const readback = await containerReadBack(new Cmd("/container print detail where").set("name", a.name).build(), ctx);
|
|
33111
|
+
return `Container add accepted; extraction is asynchronous. Inspect the observed state before start; do not repeat add.
|
|
33112
|
+
|
|
33113
|
+
${readback}`;
|
|
33114
|
+
}
|
|
33115
|
+
}),
|
|
33116
|
+
defineTool({
|
|
33117
|
+
name: "update_container",
|
|
33118
|
+
title: "Update Container",
|
|
33119
|
+
annotations: WRITE_IDEMPOTENT,
|
|
33120
|
+
description: "Update exactly one container. Runtime settings require positive fully-stopped evidence; logging, comment and start_on_boot can change without stopping. Named env/mount lists can affect other consumers. Inspect target syntax; no automatic compatibility retries.",
|
|
33121
|
+
inputSchema: { ...IDENTITY, ...SETTINGS },
|
|
33122
|
+
async handler(a, ctx) {
|
|
33123
|
+
validateSettings(a);
|
|
33124
|
+
const changes = Object.keys(SETTINGS).filter((key) => a[key] !== undefined);
|
|
33125
|
+
if (!changes.length)
|
|
33126
|
+
return "No updates specified.";
|
|
33127
|
+
const id = await target(a, ctx);
|
|
33128
|
+
if (changes.some((key) => !["logging", "comment", "start_on_boot"].includes(key)))
|
|
33129
|
+
await requireStopped(id, ctx);
|
|
33130
|
+
await containerWrite(settings(new Cmd("/container set").set("numbers", id), a), ctx);
|
|
33131
|
+
return `Container update accepted. Observed read-back:
|
|
33132
|
+
|
|
33133
|
+
${await containerReadBack(detailCommand(id), ctx)}`;
|
|
33134
|
+
}
|
|
33135
|
+
}),
|
|
33136
|
+
...["start", "stop", "remove"].map((operation) => defineTool({
|
|
33137
|
+
name: `${operation}_container`,
|
|
33138
|
+
title: `${operation[0].toUpperCase()}${operation.slice(1)} Container`,
|
|
33139
|
+
annotations: operation === "remove" ? DESTRUCTIVE : WRITE,
|
|
33140
|
+
description: operation === "remove" ? "Remove exactly one container after a positive stopped check. Back up application data first; do not assume root-dir survives removal. Does not separately delete volumes/layers. Verify absence; never blindly retry an ambiguous write." : `${operation} exactly one container by stable id, exact unique name or tag. Start requires positive stopped evidence. Asynchronous: inspect state with bounded polling; accepted does not mean healthy/completed.`,
|
|
33141
|
+
inputSchema: IDENTITY,
|
|
33142
|
+
async handler(a, ctx) {
|
|
33143
|
+
const id = await target(a, ctx);
|
|
33144
|
+
if (operation !== "stop")
|
|
33145
|
+
await requireStopped(id, ctx);
|
|
33146
|
+
await containerWrite(new Cmd(`/container ${operation}`).set("numbers", id).build(), ctx);
|
|
33147
|
+
if (operation === "remove") {
|
|
33148
|
+
const count = await containerReadBack(new Cmd("/container print count-only where").set(".id", id).build(), ctx);
|
|
33149
|
+
return count.trim() === "0" ? `Container ${id} removal verified. Application-volume contents were not inspected.` : "Removal accepted but absence is UNVERIFIED/pending; inspect before retrying.";
|
|
33150
|
+
}
|
|
33151
|
+
return `Container ${operation} accepted; lifecycle may still be pending.
|
|
33152
|
+
|
|
33153
|
+
${await containerReadBack(detailCommand(id), ctx)}`;
|
|
33154
|
+
}
|
|
33155
|
+
})),
|
|
33156
|
+
defineTool({
|
|
33157
|
+
name: "get_container_config",
|
|
33158
|
+
title: "Get Container Global Config",
|
|
33159
|
+
annotations: READ,
|
|
33160
|
+
description: "Read registry, extraction storage and memory settings. Registry credentials are masked. Settings are router-wide and may affect every container.",
|
|
33161
|
+
async handler(_a, ctx) {
|
|
33162
|
+
return `CONTAINER CONFIG:
|
|
33163
|
+
|
|
33164
|
+
${redactContainerText(await containerRead("/container config print", ctx))}`;
|
|
33165
|
+
}
|
|
33166
|
+
}),
|
|
33167
|
+
defineTool({
|
|
33168
|
+
name: "set_container_config",
|
|
33169
|
+
title: "Set Container Global Config",
|
|
33170
|
+
annotations: WRITE_IDEMPOTENT,
|
|
33171
|
+
description: "Update router-wide registry/extraction/storage/memory settings and read back. Use verified storage and HTTPS registry; may affect other workloads. memory_high is a soft threshold. ram_high is a compatibility input alias for the same RouterOS memory-high property.",
|
|
33172
|
+
inputSchema: {
|
|
33173
|
+
registry_url: string2().optional(),
|
|
33174
|
+
tmpdir: string2().optional(),
|
|
33175
|
+
layer_dir: string2().optional(),
|
|
33176
|
+
memory_high: string2().optional(),
|
|
33177
|
+
ram_high: string2().optional().describe("Deprecated alias of memory_high; never sent as ram-high"),
|
|
33178
|
+
username: string2().optional(),
|
|
33179
|
+
password: string2().optional()
|
|
33180
|
+
},
|
|
33181
|
+
async handler(a, ctx) {
|
|
33182
|
+
if (a.memory_high !== undefined && a.ram_high !== undefined)
|
|
33183
|
+
throw new Error("Choose memory_high or its ram_high alias, not both.");
|
|
33184
|
+
const cmd = new Cmd("/container config set").opt("registry-url", a.registry_url).opt("tmpdir", a.tmpdir).opt("layer-dir", a.layer_dir).opt("memory-high", a.memory_high ?? a.ram_high).opt("username", a.username).opt("password", a.password).build();
|
|
33185
|
+
if (cmd === "/container config set")
|
|
33186
|
+
return "No updates specified.";
|
|
33187
|
+
await containerWrite(cmd, ctx);
|
|
33188
|
+
return `Container config update accepted.
|
|
33189
|
+
|
|
33190
|
+
${await containerReadBack("/container config print", ctx)}`;
|
|
33191
|
+
}
|
|
33192
|
+
}),
|
|
33193
|
+
defineTool({
|
|
33194
|
+
name: "list_container_envs",
|
|
33195
|
+
title: "List Container Env Metadata",
|
|
33196
|
+
annotations: READ,
|
|
33197
|
+
description: "List environment .ids, list names and keys WITHOUT retrieving values. Treat every value as potentially secret. Shared lists may have multiple container consumers.",
|
|
33198
|
+
inputSchema: { list_filter: string2().optional().describe("Exact list name") },
|
|
33199
|
+
async handler(a, ctx) {
|
|
33200
|
+
const cmd = new Cmd("/container envs print").raw("detail").set("proplist", ".id,list,key,disabled");
|
|
33201
|
+
if (a.list_filter !== undefined)
|
|
33202
|
+
cmd.raw("where").set("list", a.list_filter);
|
|
33203
|
+
return `CONTAINER ENV METADATA (values omitted):
|
|
33204
|
+
|
|
33205
|
+
${redactContainerText(await containerRead(cmd.build(), ctx))}`;
|
|
33206
|
+
}
|
|
33207
|
+
}),
|
|
33208
|
+
defineTool({
|
|
33209
|
+
name: "add_container_env",
|
|
33210
|
+
title: "Add Container Env Variable",
|
|
33211
|
+
annotations: WRITE,
|
|
33212
|
+
description: "Add a sensitive value to a named env list. Current CLI groups by list; check target syntax. Review all consumers before changing a shared list. Existing running containers may need an approved stop/start; no implicit restart.",
|
|
33213
|
+
inputSchema: { list: textValue, key: textValue, value: string2() },
|
|
33214
|
+
async handler(a, ctx) {
|
|
33215
|
+
const count = await containerRead(new Cmd("/container envs print count-only where").set("list", a.list).set("key", a.key).build(), ctx);
|
|
33216
|
+
if (count.trim() !== "0")
|
|
33217
|
+
throw new Error("Env entry exists or uniqueness is unknown; no mutation performed.");
|
|
33218
|
+
await containerWrite(new Cmd("/container envs add").set("list", a.list).set("key", a.key).set("value", a.value).build(), ctx);
|
|
33219
|
+
const countAfter = await containerReadBack(new Cmd("/container envs print count-only where").set("list", a.list).set("key", a.key).build(), ctx);
|
|
33220
|
+
return countAfter.trim() === "1" ? "Env entry creation verified; value omitted." : "Env add accepted; read-back UNVERIFIED. Inspect before retrying.";
|
|
33221
|
+
}
|
|
33222
|
+
}),
|
|
33223
|
+
defineTool({
|
|
33224
|
+
name: "remove_container_env",
|
|
33225
|
+
title: "Remove Container Env Variable",
|
|
33226
|
+
annotations: DESTRUCTIVE,
|
|
33227
|
+
description: "Remove one env entry by stable id OR exact list+key. Reject duplicates/unreadable selection. Review containers consuming this list first; no implicit restart.",
|
|
33228
|
+
inputSchema: { id: IDENTITY.id, list: textValue.optional(), key: textValue.optional() },
|
|
33229
|
+
async handler(a, ctx) {
|
|
33230
|
+
if (a.id ? a.list !== undefined || a.key !== undefined : !a.list || !a.key)
|
|
33231
|
+
throw new Error("Provide id OR both list and key.");
|
|
33232
|
+
const id = await resolveContainerItem("/container envs", a.id ? { ".id": a.id } : { list: a.list, key: a.key }, ctx);
|
|
33233
|
+
await containerWrite(new Cmd("/container envs remove").set("numbers", id).build(), ctx);
|
|
33234
|
+
const count = await containerReadBack(new Cmd("/container envs print count-only where").set(".id", id).build(), ctx);
|
|
33235
|
+
return count.trim() === "0" ? "Env removal verified." : "Env removal accepted; absence UNVERIFIED. Inspect before retrying.";
|
|
33236
|
+
}
|
|
33237
|
+
}),
|
|
33238
|
+
defineTool({
|
|
33239
|
+
name: "list_container_mounts",
|
|
33240
|
+
title: "List Container Mounts",
|
|
33241
|
+
annotations: READ,
|
|
33242
|
+
description: "Read mount metadata. Current CLI groups by list; legacy CLI may use name. No application files are read. A list can contain several mounts.",
|
|
33243
|
+
inputSchema: {
|
|
33244
|
+
list_filter: textValue.optional(),
|
|
33245
|
+
name_filter: textValue.optional().describe("Legacy exact name filter")
|
|
33246
|
+
},
|
|
33247
|
+
async handler(a, ctx) {
|
|
33248
|
+
if (a.list_filter !== undefined && a.name_filter !== undefined)
|
|
33249
|
+
throw new Error("Choose list_filter or legacy name_filter.");
|
|
33250
|
+
const cmd = new Cmd("/container mounts print detail");
|
|
33251
|
+
if (a.list_filter !== undefined)
|
|
33252
|
+
cmd.raw("where").set("list", a.list_filter);
|
|
33253
|
+
if (a.name_filter !== undefined)
|
|
33254
|
+
cmd.raw("where").set("name", a.name_filter);
|
|
33255
|
+
return `CONTAINER MOUNTS:
|
|
33256
|
+
|
|
33257
|
+
${redactContainerText(await containerRead(cmd.build(), ctx))}`;
|
|
33258
|
+
}
|
|
33259
|
+
}),
|
|
33260
|
+
defineTool({
|
|
33261
|
+
name: "add_container_mount",
|
|
33262
|
+
title: "Add Container Mount",
|
|
33263
|
+
annotations: WRITE,
|
|
33264
|
+
description: "Add a persistent mount using current list= OR legacy name=, never both. Verify target syntax first. Use appropriate storage; a missing source may be populated from the image. Review consumers; this neither formats storage nor restarts containers.",
|
|
33265
|
+
inputSchema: {
|
|
33266
|
+
list: textValue.optional().describe("Current CLI mount-list name"),
|
|
33267
|
+
name: textValue.optional().describe("Legacy CLI mount name; do not use for current list syntax"),
|
|
33268
|
+
src: textValue,
|
|
33269
|
+
dst: textValue
|
|
33270
|
+
},
|
|
33271
|
+
async handler(a, ctx) {
|
|
33272
|
+
if (Boolean(a.list) === Boolean(a.name))
|
|
33273
|
+
throw new Error("Provide list OR legacy name.");
|
|
33274
|
+
const selector = new Cmd("").opt("list", a.list).opt("name", a.name).set("src", a.src).set("dst", a.dst).build().trim();
|
|
33275
|
+
const count = await containerRead(`/container mounts print count-only where ${selector}`, ctx);
|
|
33276
|
+
if (count.trim() !== "0")
|
|
33277
|
+
throw new Error("Mount exists or uniqueness is unknown; no mutation performed.");
|
|
33278
|
+
await containerWrite(new Cmd("/container mounts add").opt("list", a.list).opt("name", a.name).set("src", a.src).set("dst", a.dst).build(), ctx);
|
|
33279
|
+
const countAfter = await containerReadBack(`/container mounts print count-only where ${selector}`, ctx);
|
|
33280
|
+
return countAfter.trim() === "1" ? "Mount creation verified; inspect application data separately." : "Mount add accepted; read-back UNVERIFIED. Inspect before retrying.";
|
|
33281
|
+
}
|
|
33282
|
+
}),
|
|
33283
|
+
defineTool({
|
|
33284
|
+
name: "remove_container_mount",
|
|
33285
|
+
title: "Remove Container Mount",
|
|
33286
|
+
annotations: DESTRUCTIVE,
|
|
33287
|
+
description: "Remove one mount definition by stable id or unique list/name, optionally narrowed by src/dst. Rejects multi-entry lists. Review shared consumers first; no host files are deleted by this tool.",
|
|
33288
|
+
inputSchema: {
|
|
33289
|
+
id: IDENTITY.id,
|
|
33290
|
+
list: textValue.optional(),
|
|
33291
|
+
name: textValue.optional(),
|
|
33292
|
+
src: textValue.optional(),
|
|
33293
|
+
dst: textValue.optional()
|
|
33294
|
+
},
|
|
33295
|
+
async handler(a, ctx) {
|
|
33296
|
+
if ([a.id, a.list, a.name].filter((v) => v !== undefined).length !== 1 || a.id && (a.src || a.dst))
|
|
33297
|
+
throw new Error("Provide id OR list/name with optional src/dst.");
|
|
33298
|
+
const id = await resolveContainerItem("/container mounts", a.id ? { ".id": a.id } : { list: a.list, name: a.name, src: a.src, dst: a.dst }, ctx);
|
|
33299
|
+
await containerWrite(new Cmd("/container mounts remove").set("numbers", id).build(), ctx);
|
|
33300
|
+
const count = await containerReadBack(new Cmd("/container mounts print count-only where").set(".id", id).build(), ctx);
|
|
33301
|
+
return count.trim() === "0" ? "Mount definition removal verified; host files were not touched." : "Mount removal accepted; absence UNVERIFIED. Inspect before retrying.";
|
|
33302
|
+
}
|
|
33303
|
+
})
|
|
33304
|
+
];
|
|
33305
|
+
var containerTools = [
|
|
33306
|
+
defineTool({
|
|
33307
|
+
name: "get_routeros_container_guide",
|
|
33308
|
+
title: "Get RouterOS Container Guide",
|
|
33309
|
+
description: "Read shared version-aware container knowledge: prerequisites, image compatibility, VETH isolation, lifecycle, secrets and troubleshooting. No device access. Use before auditing, deploying or changing containers.",
|
|
33310
|
+
annotations: READ,
|
|
33311
|
+
noDevice: true,
|
|
33312
|
+
inputSchema: { topic: _enum(["all", ...CONTAINER_GUIDE_TOPICS]).default("all") },
|
|
33313
|
+
async handler(a) {
|
|
33314
|
+
return getRouterosContainerGuide(a.topic);
|
|
33315
|
+
}
|
|
33316
|
+
}),
|
|
33317
|
+
...withRequires({ packages: ["container"], deviceMode: "container", minVersion: "7.0" }, deviceTools2)
|
|
33318
|
+
];
|
|
33319
|
+
|
|
31360
33320
|
// src/core/firewall-audit.ts
|
|
31361
|
-
import * as
|
|
33321
|
+
import * as ipaddr3 from "ipaddr.js";
|
|
31362
33322
|
|
|
31363
33323
|
// src/schedule/identity.ts
|
|
31364
|
-
import { createHash as
|
|
33324
|
+
import { createHash as createHash8 } from "crypto";
|
|
31365
33325
|
function stableId(prefix, parts) {
|
|
31366
33326
|
const material = parts.filter((p) => p !== undefined && p !== "").map((p) => String(p).trim().toLowerCase()).join(" | ");
|
|
31367
|
-
const digest =
|
|
33327
|
+
const digest = createHash8("sha256").update(material, "utf8").digest("hex").slice(0, 12);
|
|
31368
33328
|
return `${prefix}:${digest}`;
|
|
31369
33329
|
}
|
|
31370
33330
|
function ruleFingerprint(rule) {
|
|
@@ -31477,8 +33437,8 @@ function rulesFromRows(rows) {
|
|
|
31477
33437
|
function toCidr(value) {
|
|
31478
33438
|
try {
|
|
31479
33439
|
if (value.includes("/"))
|
|
31480
|
-
return
|
|
31481
|
-
const addr =
|
|
33440
|
+
return ipaddr3.parseCIDR(value);
|
|
33441
|
+
const addr = ipaddr3.parse(value);
|
|
31482
33442
|
return [addr, addr.kind() === "ipv6" ? 128 : 32];
|
|
31483
33443
|
} catch {
|
|
31484
33444
|
return null;
|
|
@@ -31945,395 +33905,8 @@ function tailLines(text, n) {
|
|
|
31945
33905
|
return lines.length <= n ? text : lines.slice(-n).join(`
|
|
31946
33906
|
`);
|
|
31947
33907
|
}
|
|
31948
|
-
// src/tools/container.ts
|
|
31949
|
-
var NOT_AVAILABLE = "Container support is not available on this device. Install the `container` package and enable " + "device-mode (`/system/device-mode/update container=yes`, then physically confirm).";
|
|
31950
|
-
function containerMatch(name, tag) {
|
|
31951
|
-
if (name)
|
|
31952
|
-
return `name=${quoteValue(name)}`;
|
|
31953
|
-
if (tag)
|
|
31954
|
-
return `tag~${quoteValue(tag)}`;
|
|
31955
|
-
return null;
|
|
31956
|
-
}
|
|
31957
|
-
var IDENTITY = {
|
|
31958
|
-
name: string2().optional().describe("Container name (set via add_container)"),
|
|
31959
|
-
tag: string2().optional().describe("Image tag to match (e.g. 'pihole') if no name")
|
|
31960
|
-
};
|
|
31961
|
-
var containerToolsDefs = [
|
|
31962
|
-
defineTool({
|
|
31963
|
-
name: "list_containers",
|
|
31964
|
-
title: "List Containers",
|
|
31965
|
-
annotations: READ,
|
|
31966
|
-
description: "List every OCI container on the device (`/container print`) with its status, image tag, name, VETH " + "interface and root-dir \u2014 the starting point for any container work and the way to POLL the lifecycle, " + "which is asynchronous: status moves extracting \u2192 stopped (ready to start) \u2192 running. Use this to find " + "the `name`/`tag` the other tools take, to confirm an add has finished extracting before start_container, " + "and to confirm a stop has completed before remove_container. Filter by partial `name_filter`, " + "`tag_filter`, or `status_filter` (e.g. 'running', 'stopped'); set `detail=true` for the full property " + "block. For one container use get_container. A container's stdout/stderr is in the system log " + '(`/log print where topics~"container"`) when it was created with logging=yes.',
|
|
31967
|
-
inputSchema: {
|
|
31968
|
-
name_filter: string2().optional().describe("Partial container name match"),
|
|
31969
|
-
tag_filter: string2().optional().describe("Partial image tag match"),
|
|
31970
|
-
status_filter: string2().optional().describe("e.g. 'running', 'stopped'"),
|
|
31971
|
-
detail: boolean2().default(false).describe("Show the full per-container property block")
|
|
31972
|
-
},
|
|
31973
|
-
async handler(a, ctx) {
|
|
31974
|
-
ctx.info("Listing containers");
|
|
31975
|
-
const filters = [];
|
|
31976
|
-
if (a.name_filter)
|
|
31977
|
-
filters.push(`name~"${a.name_filter}"`);
|
|
31978
|
-
if (a.tag_filter)
|
|
31979
|
-
filters.push(`tag~"${a.tag_filter}"`);
|
|
31980
|
-
if (a.status_filter)
|
|
31981
|
-
filters.push(`status~"${a.status_filter}"`);
|
|
31982
|
-
const result = await executeMikrotikCommand(`/container print${a.detail ? " detail" : ""}${whereClause(filters)}`, ctx);
|
|
31983
|
-
if (commandUnsupported(result))
|
|
31984
|
-
return NOT_AVAILABLE;
|
|
31985
|
-
return isEmpty(result) ? "No containers found matching the criteria." : `CONTAINERS:
|
|
31986
|
-
|
|
31987
|
-
${redactSecrets(result)}`;
|
|
31988
|
-
}
|
|
31989
|
-
}),
|
|
31990
|
-
defineTool({
|
|
31991
|
-
name: "get_container",
|
|
31992
|
-
title: "Get Container Detail",
|
|
31993
|
-
annotations: READ,
|
|
31994
|
-
description: "Full detail for one container (`/container print detail`) \u2014 status, image tag, interface, root-dir, " + "env/mounts, cmd/entrypoint, hostname/dns, logging and start-on-boot. Identify by `name` (preferred) or " + "`tag`. Use list_containers to discover identifiers.",
|
|
31995
|
-
inputSchema: { ...IDENTITY },
|
|
31996
|
-
async handler(a, ctx) {
|
|
31997
|
-
const match = containerMatch(a.name, a.tag);
|
|
31998
|
-
if (!match)
|
|
31999
|
-
return "Provide a container name or tag.";
|
|
32000
|
-
ctx.info(`Getting container detail: ${match}`);
|
|
32001
|
-
const result = await executeMikrotikCommand(`/container print detail where ${match}`, ctx);
|
|
32002
|
-
if (commandUnsupported(result))
|
|
32003
|
-
return NOT_AVAILABLE;
|
|
32004
|
-
return isEmpty(result) ? `Container (${match}) not found.` : `CONTAINER DETAILS:
|
|
32005
|
-
|
|
32006
|
-
${redactSecrets(result)}`;
|
|
32007
|
-
}
|
|
32008
|
-
}),
|
|
32009
|
-
defineTool({
|
|
32010
|
-
name: "add_container",
|
|
32011
|
-
title: "Add Container",
|
|
32012
|
-
annotations: WRITE,
|
|
32013
|
-
description: "Create an OCI container (`/container add`). " + "PREREQUISITES, in order: (1) the `container` package installed + device-mode `container=yes`; " + "(2) an external disk for storage (containers should never run on internal flash); " + "(3) for `remote_image`, a registry URL + on-disk `tmpdir` set via set_container_config; " + "(4) a VETH for networking \u2014 create it first with `/interface veth add name=veth1 " + "address=172.17.0.2/24 gateway=172.17.0.1`, then bridge it and add a srcnat masquerade rule for " + "internet (and a dst-nat to publish a port). " + "Then create the container: supply EITHER `remote_image` (registry pull, e.g. 'library/alpine:latest') " + "OR `file` (a local image tar on the device \u2014 must be a SINGLE-LAYER, UNCOMPRESSED Docker-v1 tar). " + "Set `interface` to the VETH and `root_dir` to a path on the external disk (e.g. 'disk1/myapp'). " + "Attach config via inline `env` ('K=v,K2=v2') / `mount` ('src=disk1/data,dst=/data'), or reference " + "named lists with `envlists`/`mountlists` (add_container_env / add_container_mount). Override " + "`cmd`/`entrypoint`/`workdir`; set `hostname`/`dns`; enable `logging`/`start_on_boot`; cap " + "`memory_high`/`cpu_list`. ALWAYS set `name` so the lifecycle tools can find it. " + "The image pull/extract is ASYNCHRONOUS: this returns immediately, then poll list_containers until " + "status becomes 'stopped' (extraction done) before calling start_container.",
|
|
32014
|
-
inputSchema: {
|
|
32015
|
-
name: string2().optional().describe("Container name (recommended for management)"),
|
|
32016
|
-
remote_image: string2().optional().describe("Registry image, e.g. 'library/alpine:latest'"),
|
|
32017
|
-
file: string2().optional().describe("Local Docker-v1 tar on the device (alternative to remote_image)"),
|
|
32018
|
-
interface: string2().optional().describe("VETH interface name"),
|
|
32019
|
-
root_dir: string2().optional().describe("Filesystem root, e.g. 'disk1/myapp'"),
|
|
32020
|
-
env: string2().optional().describe("Inline env vars: 'K=v,K2=v2' (7.21+)"),
|
|
32021
|
-
envlists: string2().optional().describe("Named env list name(s) (add_container_env)"),
|
|
32022
|
-
mount: string2().optional().describe("Inline mount: 'src=disk1/data,dst=/data' (7.21+)"),
|
|
32023
|
-
mountlists: string2().optional().describe("Named mount name(s) (add_container_mount)"),
|
|
32024
|
-
cmd: string2().optional().describe("Override container CMD"),
|
|
32025
|
-
entrypoint: string2().optional().describe("Override container ENTRYPOINT"),
|
|
32026
|
-
workdir: string2().optional().describe("Override working directory"),
|
|
32027
|
-
hostname: string2().optional(),
|
|
32028
|
-
dns: string2().optional().describe("DNS server for the container"),
|
|
32029
|
-
user: string2().optional(),
|
|
32030
|
-
stop_signal: string2().optional().describe("Signal used to stop the container"),
|
|
32031
|
-
devices: string2().optional().describe("Pass-through physical devices (7.20+)"),
|
|
32032
|
-
cpu_list: string2().optional().describe("CPU core affinity"),
|
|
32033
|
-
memory_high: string2().optional().describe("RAM limit, e.g. '256M'"),
|
|
32034
|
-
logging: boolean2().optional().describe("Send stdout/stderr to the RouterOS log"),
|
|
32035
|
-
start_on_boot: boolean2().optional().describe("Auto-start on device boot"),
|
|
32036
|
-
comment: string2().optional()
|
|
32037
|
-
},
|
|
32038
|
-
async handler(a, ctx) {
|
|
32039
|
-
if (!a.remote_image && !a.file)
|
|
32040
|
-
return "Provide remote_image (registry pull) or file (local tar).";
|
|
32041
|
-
ctx.info(`Adding container: ${a.name ?? a.remote_image ?? a.file}`);
|
|
32042
|
-
const cmd = new Cmd("/container add").opt("name", a.name).opt("remote-image", a.remote_image).opt("file", a.file).opt("interface", a.interface).opt("root-dir", a.root_dir).opt("env", a.env).opt("envlists", a.envlists).opt("mount", a.mount).opt("mountlists", a.mountlists).opt("cmd", a.cmd).opt("entrypoint", a.entrypoint).opt("workdir", a.workdir).opt("hostname", a.hostname).opt("dns", a.dns).opt("user", a.user).opt("stop-signal", a.stop_signal).opt("devices", a.devices).opt("cpu-list", a.cpu_list).opt("memory-high", a.memory_high).bool("logging", a.logging).bool("start-on-boot", a.start_on_boot).opt("comment", a.comment).build();
|
|
32043
|
-
const result = await executeMikrotikCommand(cmd, ctx);
|
|
32044
|
-
if (commandUnsupported(result))
|
|
32045
|
-
return NOT_AVAILABLE;
|
|
32046
|
-
if (looksLikeError(result))
|
|
32047
|
-
return `Failed to add container: ${redactSecrets(result)}`;
|
|
32048
|
-
return `Container added (image is pulling/extracting asynchronously \u2014 poll list_containers until status is ` + `'stopped', then start_container).
|
|
32049
|
-
|
|
32050
|
-
${redactSecrets(result)}`;
|
|
32051
|
-
}
|
|
32052
|
-
}),
|
|
32053
|
-
defineTool({
|
|
32054
|
-
name: "update_container",
|
|
32055
|
-
title: "Update Container",
|
|
32056
|
-
annotations: WRITE_IDEMPOTENT,
|
|
32057
|
-
description: "Modify an existing container's properties in place (`/container set [find \u2026]`) without recreating it \u2014 " + "change `start_on_boot`, `logging`, `cmd`/`entrypoint`/`workdir`, `hostname`/`dns`, `interface`, " + "`root_dir`, inline `env`/`mount` or `envlists`/`mountlists`, resource caps, or `comment`. Identify by " + "`name` or `tag`. Best practice: stop the container first (stop_container) before changing runtime " + "properties like interface, env, mounts or cmd \u2014 they take effect on the next start_container, not " + "live. To create a new container use add_container; to change the image, remove and re-add.",
|
|
32058
|
-
inputSchema: {
|
|
32059
|
-
...IDENTITY,
|
|
32060
|
-
interface: string2().optional(),
|
|
32061
|
-
root_dir: string2().optional(),
|
|
32062
|
-
env: string2().optional(),
|
|
32063
|
-
envlists: string2().optional(),
|
|
32064
|
-
mount: string2().optional(),
|
|
32065
|
-
mountlists: string2().optional(),
|
|
32066
|
-
cmd: string2().optional(),
|
|
32067
|
-
entrypoint: string2().optional(),
|
|
32068
|
-
workdir: string2().optional(),
|
|
32069
|
-
hostname: string2().optional(),
|
|
32070
|
-
dns: string2().optional(),
|
|
32071
|
-
cpu_list: string2().optional(),
|
|
32072
|
-
memory_high: string2().optional(),
|
|
32073
|
-
logging: boolean2().optional(),
|
|
32074
|
-
start_on_boot: boolean2().optional(),
|
|
32075
|
-
comment: string2().optional()
|
|
32076
|
-
},
|
|
32077
|
-
async handler(a, ctx) {
|
|
32078
|
-
const match = containerMatch(a.name, a.tag);
|
|
32079
|
-
if (!match)
|
|
32080
|
-
return "Provide a container name or tag.";
|
|
32081
|
-
ctx.info(`Updating container: ${match}`);
|
|
32082
|
-
const cmd = new Cmd(`/container set [find ${match}]`).opt("interface", a.interface).opt("root-dir", a.root_dir).opt("env", a.env).opt("envlists", a.envlists).opt("mount", a.mount).opt("mountlists", a.mountlists).opt("cmd", a.cmd).opt("entrypoint", a.entrypoint).opt("workdir", a.workdir).opt("hostname", a.hostname).opt("dns", a.dns).opt("cpu-list", a.cpu_list).opt("memory-high", a.memory_high).bool("logging", a.logging).bool("start-on-boot", a.start_on_boot).opt("comment", a.comment).build();
|
|
32083
|
-
if (cmd.endsWith("]"))
|
|
32084
|
-
return "No updates specified.";
|
|
32085
|
-
const result = await executeMikrotikCommand(cmd, ctx);
|
|
32086
|
-
if (commandUnsupported(result))
|
|
32087
|
-
return NOT_AVAILABLE;
|
|
32088
|
-
if (looksLikeError(result))
|
|
32089
|
-
return `Failed to update container: ${redactSecrets(result)}`;
|
|
32090
|
-
return `Container (${match}) updated.`;
|
|
32091
|
-
}
|
|
32092
|
-
}),
|
|
32093
|
-
defineTool({
|
|
32094
|
-
name: "start_container",
|
|
32095
|
-
title: "Start Container",
|
|
32096
|
-
annotations: WRITE,
|
|
32097
|
-
description: "Start a stopped container (`/container start [find \u2026]`). Identify by `name` or `tag`. The container " + "must have finished extracting (status 'stopped') first \u2014 check with list_containers. View its output " + "in the log when logging=yes. To stop it use stop_container.",
|
|
32098
|
-
inputSchema: { ...IDENTITY },
|
|
32099
|
-
async handler(a, ctx) {
|
|
32100
|
-
const match = containerMatch(a.name, a.tag);
|
|
32101
|
-
if (!match)
|
|
32102
|
-
return "Provide a container name or tag.";
|
|
32103
|
-
ctx.info(`Starting container: ${match}`);
|
|
32104
|
-
const count = await executeMikrotikCommand(`/container print count-only where ${match}`, ctx);
|
|
32105
|
-
if (commandUnsupported(count))
|
|
32106
|
-
return NOT_AVAILABLE;
|
|
32107
|
-
if (count.trim() === "0")
|
|
32108
|
-
return `Container (${match}) not found.`;
|
|
32109
|
-
const result = await executeMikrotikCommand(`/container start [find ${match}]`, ctx);
|
|
32110
|
-
if (looksLikeError(result))
|
|
32111
|
-
return `Failed to start container: ${result}`;
|
|
32112
|
-
return `Container (${match}) starting.`;
|
|
32113
|
-
}
|
|
32114
|
-
}),
|
|
32115
|
-
defineTool({
|
|
32116
|
-
name: "stop_container",
|
|
32117
|
-
title: "Stop Container",
|
|
32118
|
-
annotations: WRITE,
|
|
32119
|
-
description: "Stop a running container (`/container stop [find \u2026]`). Identify by `name` or `tag`. Stopping is " + "asynchronous \u2014 poll list_containers until status is 'stopped' before removing it. To start it again " + "use start_container.",
|
|
32120
|
-
inputSchema: { ...IDENTITY },
|
|
32121
|
-
async handler(a, ctx) {
|
|
32122
|
-
const match = containerMatch(a.name, a.tag);
|
|
32123
|
-
if (!match)
|
|
32124
|
-
return "Provide a container name or tag.";
|
|
32125
|
-
ctx.info(`Stopping container: ${match}`);
|
|
32126
|
-
const count = await executeMikrotikCommand(`/container print count-only where ${match}`, ctx);
|
|
32127
|
-
if (commandUnsupported(count))
|
|
32128
|
-
return NOT_AVAILABLE;
|
|
32129
|
-
if (count.trim() === "0")
|
|
32130
|
-
return `Container (${match}) not found.`;
|
|
32131
|
-
const result = await executeMikrotikCommand(`/container stop [find ${match}]`, ctx);
|
|
32132
|
-
if (looksLikeError(result))
|
|
32133
|
-
return `Failed to stop container: ${result}`;
|
|
32134
|
-
return `Container (${match}) stopping (poll list_containers for status 'stopped').`;
|
|
32135
|
-
}
|
|
32136
|
-
}),
|
|
32137
|
-
defineTool({
|
|
32138
|
-
name: "remove_container",
|
|
32139
|
-
title: "Remove Container",
|
|
32140
|
-
annotations: DESTRUCTIVE,
|
|
32141
|
-
description: "Permanently delete a container (`/container remove [find \u2026]`). The container must be FULLY STOPPED " + "first \u2014 RouterOS rejects removal while it is running or still stopping. If removal fails for that " + "reason, stop it (stop_container), wait until list_containers shows status 'stopped', then retry. " + "Identify by `name` or `tag`. This does not delete its root-dir data on disk.",
|
|
32142
|
-
inputSchema: { ...IDENTITY },
|
|
32143
|
-
async handler(a, ctx) {
|
|
32144
|
-
const match = containerMatch(a.name, a.tag);
|
|
32145
|
-
if (!match)
|
|
32146
|
-
return "Provide a container name or tag.";
|
|
32147
|
-
ctx.info(`Removing container: ${match}`);
|
|
32148
|
-
const count = await executeMikrotikCommand(`/container print count-only where ${match}`, ctx);
|
|
32149
|
-
if (commandUnsupported(count))
|
|
32150
|
-
return NOT_AVAILABLE;
|
|
32151
|
-
if (count.trim() === "0")
|
|
32152
|
-
return `Container (${match}) not found.`;
|
|
32153
|
-
const result = await executeMikrotikCommand(`/container remove [find ${match}]`, ctx);
|
|
32154
|
-
if (looksLikeError(result)) {
|
|
32155
|
-
return `Failed to remove container: ${result}
|
|
32156
|
-
|
|
32157
|
-
If it is still running/stopping, stop it first ` + `(stop_container), wait until list_containers shows status 'stopped', then retry.`;
|
|
32158
|
-
}
|
|
32159
|
-
return `Container (${match}) removed.`;
|
|
32160
|
-
}
|
|
32161
|
-
}),
|
|
32162
|
-
defineTool({
|
|
32163
|
-
name: "get_container_config",
|
|
32164
|
-
title: "Get Container Global Config",
|
|
32165
|
-
annotations: READ,
|
|
32166
|
-
description: "Read the global container configuration (`/container config print`) \u2014 the image registry URL, the " + "tmpdir used for pulls/extraction, the layer directory, and the RAM-high limit. Use to verify the " + "registry/tmpdir are set before pulling images. To change them use set_container_config.",
|
|
32167
|
-
async handler(_a, ctx) {
|
|
32168
|
-
ctx.info("Getting container config");
|
|
32169
|
-
const result = await executeMikrotikCommand("/container config print", ctx);
|
|
32170
|
-
if (commandUnsupported(result))
|
|
32171
|
-
return NOT_AVAILABLE;
|
|
32172
|
-
return isEmpty(result) ? "No container config found." : `CONTAINER CONFIG:
|
|
32173
|
-
|
|
32174
|
-
${redactSecrets(result)}`;
|
|
32175
|
-
}
|
|
32176
|
-
}),
|
|
32177
|
-
defineTool({
|
|
32178
|
-
name: "set_container_config",
|
|
32179
|
-
title: "Set Container Global Config",
|
|
32180
|
-
annotations: WRITE_IDEMPOTENT,
|
|
32181
|
-
description: "Configure the global container settings (`/container config set`) \u2014 the router-wide singleton that " + "MUST be set before pulling any `remote_image` with add_container. Set `registry_url` (Docker Hub is " + "'https://registry-1.docker.io') and `tmpdir` to a path on an EXTERNAL disk (e.g. 'disk1/pull') \u2014 pulls " + "and extraction need real space and IOPS, never internal flash. Optionally set `layer_dir`, a `ram_high` " + "cap, and `username`/`password` for a private registry (credentials are redacted from output). The " + "router also needs working DNS + internet to reach the registry. To read the current values use " + "get_container_config.",
|
|
32182
|
-
inputSchema: {
|
|
32183
|
-
registry_url: string2().optional().describe("Image registry URL"),
|
|
32184
|
-
tmpdir: string2().optional().describe("Pull/extract temp dir, e.g. 'disk1/pull'"),
|
|
32185
|
-
layer_dir: string2().optional().describe("Directory for extracted image layers"),
|
|
32186
|
-
ram_high: string2().optional().describe("RAM-high limit, e.g. '256M'"),
|
|
32187
|
-
username: string2().optional().describe("Registry username (private registries)"),
|
|
32188
|
-
password: string2().optional().describe("Registry password (private registries)")
|
|
32189
|
-
},
|
|
32190
|
-
async handler(a, ctx) {
|
|
32191
|
-
ctx.info("Setting container config");
|
|
32192
|
-
const cmd = new Cmd("/container config set").opt("registry-url", a.registry_url).opt("tmpdir", a.tmpdir).opt("layer-dir", a.layer_dir).opt("ram-high", a.ram_high).opt("username", a.username).opt("password", a.password).build();
|
|
32193
|
-
if (cmd === "/container config set")
|
|
32194
|
-
return "No updates specified.";
|
|
32195
|
-
const result = await executeMikrotikCommand(cmd, ctx);
|
|
32196
|
-
if (commandUnsupported(result))
|
|
32197
|
-
return NOT_AVAILABLE;
|
|
32198
|
-
if (looksLikeError(result))
|
|
32199
|
-
return `Failed to set container config: ${redactSecrets(result)}`;
|
|
32200
|
-
const detail = await executeMikrotikCommand("/container config print", ctx);
|
|
32201
|
-
return `Container config updated.
|
|
32202
|
-
|
|
32203
|
-
${redactSecrets(detail)}`;
|
|
32204
|
-
}
|
|
32205
|
-
}),
|
|
32206
|
-
defineTool({
|
|
32207
|
-
name: "list_container_envs",
|
|
32208
|
-
title: "List Container Env Variables",
|
|
32209
|
-
annotations: READ,
|
|
32210
|
-
description: "List named environment-variable entries (`/container envs print`) \u2014 each has a `list` (the group name " + "referenced by a container's envlists), a `key` and a `value`. Optionally filter by partial `list_filter`. " + "To add one use add_container_env; to delete use remove_container_env.",
|
|
32211
|
-
inputSchema: {
|
|
32212
|
-
list_filter: string2().optional().describe("Partial env-list (group) name match")
|
|
32213
|
-
},
|
|
32214
|
-
async handler(a, ctx) {
|
|
32215
|
-
ctx.info("Listing container envs");
|
|
32216
|
-
const filters = [];
|
|
32217
|
-
if (a.list_filter)
|
|
32218
|
-
filters.push(`list~"${a.list_filter}"`);
|
|
32219
|
-
const result = await executeMikrotikCommand(`/container envs print${whereClause(filters)}`, ctx);
|
|
32220
|
-
if (commandUnsupported(result))
|
|
32221
|
-
return NOT_AVAILABLE;
|
|
32222
|
-
return isEmpty(result) ? "No container env variables found." : `CONTAINER ENVS:
|
|
32223
|
-
|
|
32224
|
-
${redactSecrets(result)}`;
|
|
32225
|
-
}
|
|
32226
|
-
}),
|
|
32227
|
-
defineTool({
|
|
32228
|
-
name: "add_container_env",
|
|
32229
|
-
title: "Add Container Env Variable",
|
|
32230
|
-
annotations: WRITE,
|
|
32231
|
-
description: "Add an environment variable to a named list (`/container envs add list= key= value=`). Group related " + "variables under the same `list` name, then point a container at the group with `envlists=<list>` " + "(add_container or update_container) \u2014 a container that is already running must be restarted to pick up " + "env changes. Named lists are reusable across containers; for a one-off, self-contained setup the inline " + "`env` on add_container is simpler. The grouping `list=` property requires RouterOS 7.20+. Values may be " + "secrets and are redacted from output.",
|
|
32232
|
-
inputSchema: {
|
|
32233
|
-
list: string2().describe("Env-list (group) name, e.g. 'MYAPP'"),
|
|
32234
|
-
key: string2().describe("Variable name, e.g. 'TZ'"),
|
|
32235
|
-
value: string2().describe("Variable value")
|
|
32236
|
-
},
|
|
32237
|
-
async handler(a, ctx) {
|
|
32238
|
-
ctx.info(`Adding container env: list=${a.list} key=${a.key}`);
|
|
32239
|
-
const cmd = new Cmd("/container envs add").set("list", a.list).set("key", a.key).set("value", a.value).build();
|
|
32240
|
-
const result = await executeMikrotikCommand(cmd, ctx);
|
|
32241
|
-
if (commandUnsupported(result))
|
|
32242
|
-
return NOT_AVAILABLE;
|
|
32243
|
-
if (looksLikeError(result))
|
|
32244
|
-
return `Failed to add env variable: ${redactSecrets(result)}`;
|
|
32245
|
-
return `Env '${a.key}' added to list '${a.list}'.`;
|
|
32246
|
-
}
|
|
32247
|
-
}),
|
|
32248
|
-
defineTool({
|
|
32249
|
-
name: "remove_container_env",
|
|
32250
|
-
title: "Remove Container Env Variable",
|
|
32251
|
-
annotations: DESTRUCTIVE,
|
|
32252
|
-
description: "Delete an environment variable from a list (`/container envs remove [find list= key=]`). Supply the " + "`list` (group) name and the `key`. Verifies it exists first. To browse entries use list_container_envs.",
|
|
32253
|
-
inputSchema: {
|
|
32254
|
-
list: string2().describe("Env-list (group) name"),
|
|
32255
|
-
key: string2().describe("Variable name to remove")
|
|
32256
|
-
},
|
|
32257
|
-
async handler(a, ctx) {
|
|
32258
|
-
ctx.info(`Removing container env: list=${a.list} key=${a.key}`);
|
|
32259
|
-
const where = `list=${quoteValue(a.list)} key=${quoteValue(a.key)}`;
|
|
32260
|
-
const count = await executeMikrotikCommand(`/container envs print count-only where ${where}`, ctx);
|
|
32261
|
-
if (commandUnsupported(count))
|
|
32262
|
-
return NOT_AVAILABLE;
|
|
32263
|
-
if (count.trim() === "0")
|
|
32264
|
-
return `Env '${a.key}' in list '${a.list}' not found.`;
|
|
32265
|
-
const result = await executeMikrotikCommand(`/container envs remove [find ${where}]`, ctx);
|
|
32266
|
-
if (looksLikeError(result))
|
|
32267
|
-
return `Failed to remove env variable: ${result}`;
|
|
32268
|
-
return `Env '${a.key}' removed from list '${a.list}'.`;
|
|
32269
|
-
}
|
|
32270
|
-
}),
|
|
32271
|
-
defineTool({
|
|
32272
|
-
name: "list_container_mounts",
|
|
32273
|
-
title: "List Container Mounts",
|
|
32274
|
-
annotations: READ,
|
|
32275
|
-
description: "List named volume mounts (`/container mounts print`) \u2014 each has a `name` (referenced by a container's " + "mountlists), a host source `src` (e.g. 'disk1/appdata') and a container destination `dst` (e.g. " + "'/data'). Optionally filter by partial `name_filter`. To add one use add_container_mount; to delete use " + "remove_container_mount.",
|
|
32276
|
-
inputSchema: {
|
|
32277
|
-
name_filter: string2().optional().describe("Partial mount name match")
|
|
32278
|
-
},
|
|
32279
|
-
async handler(a, ctx) {
|
|
32280
|
-
ctx.info("Listing container mounts");
|
|
32281
|
-
const filters = [];
|
|
32282
|
-
if (a.name_filter)
|
|
32283
|
-
filters.push(`name~"${a.name_filter}"`);
|
|
32284
|
-
const result = await executeMikrotikCommand(`/container mounts print${whereClause(filters)}`, ctx);
|
|
32285
|
-
if (commandUnsupported(result))
|
|
32286
|
-
return NOT_AVAILABLE;
|
|
32287
|
-
return isEmpty(result) ? "No container mounts found." : `CONTAINER MOUNTS:
|
|
32288
|
-
|
|
32289
|
-
${result}`;
|
|
32290
|
-
}
|
|
32291
|
-
}),
|
|
32292
|
-
defineTool({
|
|
32293
|
-
name: "add_container_mount",
|
|
32294
|
-
title: "Add Container Mount",
|
|
32295
|
-
annotations: WRITE,
|
|
32296
|
-
description: "Create a named volume mount (`/container mounts add name= src= dst=`) \u2014 persists container data on the " + "host so it survives restarts/recreation. Maps a host source `src` (put it on an EXTERNAL disk, e.g. " + "'disk1/appdata', never internal flash) to a path `dst` inside the container (e.g. '/data'). Point a " + "container at it with `mountlists=<name>` (add_container or update_container); a running container must " + "be restarted to apply mount changes. For a one-off, the inline `mount` on add_container is simpler. " + "Named mounts and `mountlists` require RouterOS 7.21+.",
|
|
32297
|
-
inputSchema: {
|
|
32298
|
-
name: string2().describe("Mount name, e.g. 'appdata'"),
|
|
32299
|
-
src: string2().describe("Host source path, e.g. 'disk1/appdata'"),
|
|
32300
|
-
dst: string2().describe("Container destination path, e.g. '/data'")
|
|
32301
|
-
},
|
|
32302
|
-
async handler(a, ctx) {
|
|
32303
|
-
ctx.info(`Adding container mount: name=${a.name}`);
|
|
32304
|
-
const cmd = new Cmd("/container mounts add").set("name", a.name).set("src", a.src).set("dst", a.dst).build();
|
|
32305
|
-
const result = await executeMikrotikCommand(cmd, ctx);
|
|
32306
|
-
if (commandUnsupported(result))
|
|
32307
|
-
return NOT_AVAILABLE;
|
|
32308
|
-
if (looksLikeError(result))
|
|
32309
|
-
return `Failed to add mount: ${result}`;
|
|
32310
|
-
return `Mount '${a.name}' (${a.src} \u2192 ${a.dst}) added.`;
|
|
32311
|
-
}
|
|
32312
|
-
}),
|
|
32313
|
-
defineTool({
|
|
32314
|
-
name: "remove_container_mount",
|
|
32315
|
-
title: "Remove Container Mount",
|
|
32316
|
-
annotations: DESTRUCTIVE,
|
|
32317
|
-
description: "Delete a named volume mount (`/container mounts remove [find name=...]`). Verifies it exists first. " + "Does not delete the host data at `src`. To browse mounts use list_container_mounts.",
|
|
32318
|
-
inputSchema: { name: string2().describe("Mount name to remove") },
|
|
32319
|
-
async handler(a, ctx) {
|
|
32320
|
-
ctx.info(`Removing container mount: name=${a.name}`);
|
|
32321
|
-
const count = await executeMikrotikCommand(`/container mounts print count-only where name="${a.name}"`, ctx);
|
|
32322
|
-
if (commandUnsupported(count))
|
|
32323
|
-
return NOT_AVAILABLE;
|
|
32324
|
-
if (count.trim() === "0")
|
|
32325
|
-
return `Mount '${a.name}' not found.`;
|
|
32326
|
-
const result = await executeMikrotikCommand(`/container mounts remove [find name="${a.name}"]`, ctx);
|
|
32327
|
-
if (looksLikeError(result))
|
|
32328
|
-
return `Failed to remove mount: ${result}`;
|
|
32329
|
-
return `Mount '${a.name}' removed.`;
|
|
32330
|
-
}
|
|
32331
|
-
})
|
|
32332
|
-
];
|
|
32333
|
-
var containerTools = withRequires({ packages: ["container"], deviceMode: "container", minVersion: "7.0" }, containerToolsDefs);
|
|
32334
|
-
|
|
32335
33908
|
// src/tools/disk.ts
|
|
32336
|
-
var
|
|
33909
|
+
var NOT_AVAILABLE = "Disk management is not available on this device (no `/disk` support).";
|
|
32337
33910
|
var ADD_KEYS = new Set([
|
|
32338
33911
|
"type",
|
|
32339
33912
|
"slot",
|
|
@@ -32372,7 +33945,7 @@ var diskTools = [
|
|
|
32372
33945
|
filters.push(`interface~"${a.interface_filter}"`);
|
|
32373
33946
|
const result = await executeMikrotikCommand(`/disk print${a.detail ? " detail" : ""}${whereClause(filters)}`, ctx);
|
|
32374
33947
|
if (commandUnsupported(result))
|
|
32375
|
-
return
|
|
33948
|
+
return NOT_AVAILABLE;
|
|
32376
33949
|
return isEmpty(result) ? "No disks found matching the criteria." : `DISKS:
|
|
32377
33950
|
|
|
32378
33951
|
${result}`;
|
|
@@ -32388,7 +33961,7 @@ ${result}`;
|
|
|
32388
33961
|
ctx.info(`Getting disk details: slot=${a.slot}`);
|
|
32389
33962
|
const result = await executeMikrotikCommand(`/disk print detail where slot="${a.slot}"`, ctx);
|
|
32390
33963
|
if (commandUnsupported(result))
|
|
32391
|
-
return
|
|
33964
|
+
return NOT_AVAILABLE;
|
|
32392
33965
|
return isEmpty(result) ? `Disk '${a.slot}' not found.` : `DISK DETAILS:
|
|
32393
33966
|
|
|
32394
33967
|
${result}`;
|
|
@@ -32415,7 +33988,7 @@ ${result}`;
|
|
|
32415
33988
|
const cmd = new Cmd(`/disk format-drive ${quoteValue(a.slot)}`).opt("file-system", a.file_system).opt("label", a.label).opt("partition-size", a.partition_size).opt("encryption", a.encryption).opt("encryption-password", a.encryption_password).build();
|
|
32416
33989
|
const result = await executeMikrotikCommand(cmd, ctx);
|
|
32417
33990
|
if (commandUnsupported(result))
|
|
32418
|
-
return
|
|
33991
|
+
return NOT_AVAILABLE;
|
|
32419
33992
|
if (looksLikeError(result))
|
|
32420
33993
|
return `Failed to format disk: ${redactSecrets(result)}`;
|
|
32421
33994
|
return `Formatting disk '${a.slot}'\u2026
|
|
@@ -32443,7 +34016,7 @@ ${redactSecrets(result)}`;
|
|
|
32443
34016
|
return "No updates specified.";
|
|
32444
34017
|
const result = await executeMikrotikCommand(cmd, ctx);
|
|
32445
34018
|
if (commandUnsupported(result))
|
|
32446
|
-
return
|
|
34019
|
+
return NOT_AVAILABLE;
|
|
32447
34020
|
if (looksLikeError(result))
|
|
32448
34021
|
return `Failed to update disk: ${result}`;
|
|
32449
34022
|
const detail = await executeMikrotikCommand(`/disk print detail where slot="${a.slot}"`, ctx);
|
|
@@ -32471,7 +34044,7 @@ ${detail}`;
|
|
|
32471
34044
|
return "No sharing settings specified.";
|
|
32472
34045
|
const result = await executeMikrotikCommand(cmd, ctx);
|
|
32473
34046
|
if (commandUnsupported(result))
|
|
32474
|
-
return
|
|
34047
|
+
return NOT_AVAILABLE;
|
|
32475
34048
|
if (looksLikeError(result))
|
|
32476
34049
|
return `Failed to configure disk sharing: ${result}`;
|
|
32477
34050
|
const detail = await executeMikrotikCommand(`/disk print detail where slot="${a.slot}"`, ctx);
|
|
@@ -32504,7 +34077,7 @@ ${detail}`;
|
|
|
32504
34077
|
const built = cmd.build();
|
|
32505
34078
|
const result = await executeMikrotikCommand(built, ctx);
|
|
32506
34079
|
if (commandUnsupported(result))
|
|
32507
|
-
return
|
|
34080
|
+
return NOT_AVAILABLE;
|
|
32508
34081
|
if (looksLikeError(result))
|
|
32509
34082
|
return `Failed to add virtual disk: ${redactSecrets(result)}`;
|
|
32510
34083
|
return `Virtual disk (type=${a.type}) added.
|
|
@@ -32522,12 +34095,12 @@ ${redactSecrets(result)}`;
|
|
|
32522
34095
|
ctx.info(`Ejecting disk: slot=${a.slot}`);
|
|
32523
34096
|
const count = await executeMikrotikCommand(`/disk print count-only where slot="${a.slot}"`, ctx);
|
|
32524
34097
|
if (commandUnsupported(count))
|
|
32525
|
-
return
|
|
34098
|
+
return NOT_AVAILABLE;
|
|
32526
34099
|
if (count.trim() === "0")
|
|
32527
34100
|
return `Disk '${a.slot}' not found.`;
|
|
32528
34101
|
const result = await executeMikrotikCommand(`/disk eject [find slot="${a.slot}"]`, ctx);
|
|
32529
34102
|
if (commandUnsupported(result))
|
|
32530
|
-
return
|
|
34103
|
+
return NOT_AVAILABLE;
|
|
32531
34104
|
if (looksLikeError(result))
|
|
32532
34105
|
return `Failed to eject disk: ${result}`;
|
|
32533
34106
|
return `Disk '${a.slot}' ejected \u2014 safe to remove.`;
|
|
@@ -32543,7 +34116,7 @@ ${redactSecrets(result)}`;
|
|
|
32543
34116
|
ctx.info(`Removing virtual disk: slot=${a.slot}`);
|
|
32544
34117
|
const count = await executeMikrotikCommand(`/disk print count-only where slot="${a.slot}"`, ctx);
|
|
32545
34118
|
if (commandUnsupported(count))
|
|
32546
|
-
return
|
|
34119
|
+
return NOT_AVAILABLE;
|
|
32547
34120
|
if (count.trim() === "0")
|
|
32548
34121
|
return `Disk '${a.slot}' not found.`;
|
|
32549
34122
|
const result = await executeMikrotikCommand(`/disk remove [find slot="${a.slot}"]`, ctx);
|
|
@@ -32690,7 +34263,7 @@ var cache2 = null;
|
|
|
32690
34263
|
async function gateway() {
|
|
32691
34264
|
if (cache2)
|
|
32692
34265
|
return cache2;
|
|
32693
|
-
const { moduleCatalog } = await import("./shared/cli-
|
|
34266
|
+
const { moduleCatalog } = await import("./shared/cli-6wdstvdq.js");
|
|
32694
34267
|
const forIndex = [];
|
|
32695
34268
|
const byName = new Map;
|
|
32696
34269
|
for (const mod of moduleCatalog) {
|
|
@@ -34820,7 +36393,7 @@ function auditNetworkSegmentation(state) {
|
|
|
34820
36393
|
target: `/interface ${iface}`,
|
|
34821
36394
|
current: `subnets on one L2 domain: ${distinct.join(", ")}`,
|
|
34822
36395
|
proposed: "move server and client subnets onto separate VLANs / bridges",
|
|
34823
|
-
detail: "TOPOLOGY FACT (proven): these subnets share one physical interface with no VLAN/bridge object. " + `ISOLATION CLAIM (${isolationVerified ? "some inter-subnet filtering present \u2014 verify coverage" : "needs_live_verification"}): ` + "static config cannot fully prove no firewall enforces isolation between them. " + "
|
|
36396
|
+
detail: "TOPOLOGY FACT (proven): these subnets share one physical interface with no VLAN/bridge object. " + `ISOLATION CLAIM (${isolationVerified ? "some inter-subnet filtering present \u2014 verify coverage" : "needs_live_verification"}): ` + "static config cannot fully prove no firewall enforces isolation between them. " + "Read get_vlan_segmentation_guide before designing a migration. Confirm port roles, preserve " + `management access and plan separate L2 domains for client pools (${servedByDhcp.join(", ")}) ` + "and servers without assuming a native VLAN or example ID. Review bridge CPU/PVID membership, " + "IPv4/IPv6 INPUT and FORWARD policy, rule order and endpoint tests. NEVER auto-applied \u2014 " + "this is planned network work, not a bug fix."
|
|
34824
36397
|
});
|
|
34825
36398
|
}
|
|
34826
36399
|
return findings;
|
|
@@ -35650,7 +37223,7 @@ function evaluatePolicies(policies, model, opts = {}) {
|
|
|
35650
37223
|
|
|
35651
37224
|
// src/policy/load.ts
|
|
35652
37225
|
import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
|
|
35653
|
-
import { dirname as
|
|
37226
|
+
import { dirname as dirname11, isAbsolute, join as join6, resolve as resolve3 } from "path";
|
|
35654
37227
|
|
|
35655
37228
|
// src/policy/schema.ts
|
|
35656
37229
|
var MAX_REGEX_LENGTH = 200;
|
|
@@ -35773,18 +37346,18 @@ function validatePolicyText(text) {
|
|
|
35773
37346
|
var RULE_EXTENSIONS = [".yaml", ".yml", ".json"];
|
|
35774
37347
|
function expand(pattern, cwd) {
|
|
35775
37348
|
const absolute = isAbsolute(pattern) ? pattern : resolve3(cwd, pattern);
|
|
35776
|
-
const base =
|
|
37349
|
+
const base = dirname11(absolute);
|
|
35777
37350
|
const leaf = absolute.slice(base.length + 1);
|
|
35778
37351
|
if (!leaf.includes("*")) {
|
|
35779
37352
|
try {
|
|
35780
|
-
return statSync2(absolute).isDirectory() ? readdirSync2(absolute).filter((f) => RULE_EXTENSIONS.some((e) => f.endsWith(e))).map((f) =>
|
|
37353
|
+
return statSync2(absolute).isDirectory() ? readdirSync2(absolute).filter((f) => RULE_EXTENSIONS.some((e) => f.endsWith(e))).map((f) => join6(absolute, f)).sort() : [absolute];
|
|
35781
37354
|
} catch {
|
|
35782
37355
|
return [];
|
|
35783
37356
|
}
|
|
35784
37357
|
}
|
|
35785
37358
|
const suffix = leaf.replace(/^\*/, "");
|
|
35786
37359
|
try {
|
|
35787
|
-
return readdirSync2(base).filter((f) => suffix === "" ? true : f.endsWith(suffix)).map((f) =>
|
|
37360
|
+
return readdirSync2(base).filter((f) => suffix === "" ? true : f.endsWith(suffix)).map((f) => join6(base, f)).sort();
|
|
35788
37361
|
} catch {
|
|
35789
37362
|
return [];
|
|
35790
37363
|
}
|
|
@@ -35988,7 +37561,7 @@ function renderReport2(report, format, opts = {}) {
|
|
|
35988
37561
|
}
|
|
35989
37562
|
|
|
35990
37563
|
// src/policy/session.ts
|
|
35991
|
-
import { join as
|
|
37564
|
+
import { join as join7 } from "path";
|
|
35992
37565
|
var MAX_REPORTS = 25;
|
|
35993
37566
|
var reports = [];
|
|
35994
37567
|
function rememberReport(report) {
|
|
@@ -36003,7 +37576,7 @@ function recentReports() {
|
|
|
36003
37576
|
return reports;
|
|
36004
37577
|
}
|
|
36005
37578
|
function packagedPolicyPaths() {
|
|
36006
|
-
return [
|
|
37579
|
+
return [join7(PROJECT_ROOT, "policies")];
|
|
36007
37580
|
}
|
|
36008
37581
|
|
|
36009
37582
|
// src/tools/policy.ts
|
|
@@ -44335,7 +45908,7 @@ ${result}`;
|
|
|
44335
45908
|
];
|
|
44336
45909
|
|
|
44337
45910
|
// src/tools/ssh-test.ts
|
|
44338
|
-
async function
|
|
45911
|
+
async function probe2(opts, label, command) {
|
|
44339
45912
|
const client = new MikroTikSSHClient(opts);
|
|
44340
45913
|
const t0 = Date.now();
|
|
44341
45914
|
try {
|
|
@@ -44369,7 +45942,7 @@ var sshTestTools = [
|
|
|
44369
45942
|
return `'${name}' is a MAC-Telnet device (reached by MAC ${dc.mac}) \u2014 it has no SSH connection to test. Use a tool over MAC-Telnet instead.`;
|
|
44370
45943
|
}
|
|
44371
45944
|
ctx.info(`Testing SSH from MCP host to configured device '${name}' (${dc.host}:${dc.port})`);
|
|
44372
|
-
return
|
|
45945
|
+
return probe2({
|
|
44373
45946
|
...sshOptionsOf(dc),
|
|
44374
45947
|
jump: resolveJump(dc),
|
|
44375
45948
|
timeoutMs: Math.min(dc.timeoutMs ?? 1e4, 1e4)
|
|
@@ -44392,7 +45965,7 @@ var sshTestTools = [
|
|
|
44392
45965
|
},
|
|
44393
45966
|
async handler(a, ctx) {
|
|
44394
45967
|
ctx.info(`Testing SSH from MCP host to ${a.host}:${a.port} as ${a.username}`);
|
|
44395
|
-
return
|
|
45968
|
+
return probe2({
|
|
44396
45969
|
host: a.host,
|
|
44397
45970
|
port: a.port,
|
|
44398
45971
|
username: a.username,
|
|
@@ -52541,8 +54114,8 @@ function liveTxnUpdates() {
|
|
|
52541
54114
|
}
|
|
52542
54115
|
|
|
52543
54116
|
// src/txn/store.ts
|
|
52544
|
-
import { mkdirSync as
|
|
52545
|
-
import { dirname as
|
|
54117
|
+
import { mkdirSync as mkdirSync11 } from "fs";
|
|
54118
|
+
import { dirname as dirname12 } from "path";
|
|
52546
54119
|
function toRecord2(txn, ts, label) {
|
|
52547
54120
|
return {
|
|
52548
54121
|
id: txn.id,
|
|
@@ -52678,7 +54251,7 @@ class SqliteTxnStore {
|
|
|
52678
54251
|
async function openTxnStore(path) {
|
|
52679
54252
|
if (path !== ":memory:") {
|
|
52680
54253
|
try {
|
|
52681
|
-
|
|
54254
|
+
mkdirSync11(dirname12(path), { recursive: true });
|
|
52682
54255
|
} catch {}
|
|
52683
54256
|
}
|
|
52684
54257
|
const { Database } = await import("bun:sqlite");
|
|
@@ -53435,7 +55008,7 @@ var HISTORY_CAP = 60;
|
|
|
53435
55008
|
var statuses = new Map;
|
|
53436
55009
|
var histories = new Map;
|
|
53437
55010
|
var neighbors = new Map;
|
|
53438
|
-
var
|
|
55011
|
+
var timer3 = null;
|
|
53439
55012
|
var inFlight = false;
|
|
53440
55013
|
var UNKNOWN = { reachable: null, checkedAt: null, latencyMs: null };
|
|
53441
55014
|
function getDeviceStatus(name) {
|
|
@@ -53561,12 +55134,12 @@ async function probeAll() {
|
|
|
53561
55134
|
}
|
|
53562
55135
|
function startHealthChecks(intervalMs = 30000) {
|
|
53563
55136
|
probeAll();
|
|
53564
|
-
|
|
55137
|
+
timer3 = setInterval(() => void probeAll(), intervalMs);
|
|
53565
55138
|
}
|
|
53566
55139
|
function stopHealthChecks() {
|
|
53567
|
-
if (
|
|
53568
|
-
clearInterval(
|
|
53569
|
-
|
|
55140
|
+
if (timer3) {
|
|
55141
|
+
clearInterval(timer3);
|
|
55142
|
+
timer3 = null;
|
|
53570
55143
|
}
|
|
53571
55144
|
}
|
|
53572
55145
|
|
|
@@ -53742,8 +55315,8 @@ function createDeviceExecutor2(ctx, rolloutId) {
|
|
|
53742
55315
|
}
|
|
53743
55316
|
|
|
53744
55317
|
// src/rollout/store.ts
|
|
53745
|
-
import { mkdirSync as
|
|
53746
|
-
import { dirname as
|
|
55318
|
+
import { mkdirSync as mkdirSync12 } from "fs";
|
|
55319
|
+
import { dirname as dirname13 } from "path";
|
|
53747
55320
|
function toRecord3(rollout, ts, opts = {}) {
|
|
53748
55321
|
return {
|
|
53749
55322
|
id: rollout.id,
|
|
@@ -53876,7 +55449,7 @@ class SqliteRolloutStore {
|
|
|
53876
55449
|
async function openRolloutStore(path) {
|
|
53877
55450
|
if (path !== ":memory:") {
|
|
53878
55451
|
try {
|
|
53879
|
-
|
|
55452
|
+
mkdirSync12(dirname13(path), { recursive: true });
|
|
53880
55453
|
} catch {}
|
|
53881
55454
|
}
|
|
53882
55455
|
const { Database } = await import("bun:sqlite");
|
|
@@ -54336,7 +55909,7 @@ function rank(severity) {
|
|
|
54336
55909
|
const i = SEVERITY_ORDER4.indexOf(severity);
|
|
54337
55910
|
return i === -1 ? SEVERITY_ORDER4.length : i;
|
|
54338
55911
|
}
|
|
54339
|
-
var
|
|
55912
|
+
var FIELDS2 = [
|
|
54340
55913
|
{ min: 0, max: 59, name: "minute" },
|
|
54341
55914
|
{ min: 0, max: 23, name: "hour" },
|
|
54342
55915
|
{ min: 1, max: 31, name: "day-of-month" },
|
|
@@ -54403,11 +55976,11 @@ function parseCron(expression) {
|
|
|
54403
55976
|
}
|
|
54404
55977
|
const [minute, hour, dom, month, dow] = parts;
|
|
54405
55978
|
return {
|
|
54406
|
-
minutes: parseField(minute,
|
|
54407
|
-
hours: parseField(hour,
|
|
54408
|
-
daysOfMonth: parseField(dom,
|
|
54409
|
-
months: parseField(month,
|
|
54410
|
-
daysOfWeek: parseField(dow,
|
|
55979
|
+
minutes: parseField(minute, FIELDS2[0]),
|
|
55980
|
+
hours: parseField(hour, FIELDS2[1]),
|
|
55981
|
+
daysOfMonth: parseField(dom, FIELDS2[2]),
|
|
55982
|
+
months: parseField(month, FIELDS2[3]),
|
|
55983
|
+
daysOfWeek: parseField(dow, FIELDS2[4]),
|
|
54411
55984
|
domRestricted: dom !== "*",
|
|
54412
55985
|
dowRestricted: dow !== "*"
|
|
54413
55986
|
};
|
|
@@ -54592,8 +56165,8 @@ var JobSchema = object({
|
|
|
54592
56165
|
});
|
|
54593
56166
|
|
|
54594
56167
|
// src/schedule/store.ts
|
|
54595
|
-
import { mkdirSync as
|
|
54596
|
-
import { dirname as
|
|
56168
|
+
import { mkdirSync as mkdirSync13 } from "fs";
|
|
56169
|
+
import { dirname as dirname14 } from "path";
|
|
54597
56170
|
var SCHEMA3 = [
|
|
54598
56171
|
`CREATE TABLE IF NOT EXISTS schedule_jobs (
|
|
54599
56172
|
id TEXT PRIMARY KEY,
|
|
@@ -54735,7 +56308,7 @@ class SqliteScheduleStore {
|
|
|
54735
56308
|
async function openScheduleStore(path) {
|
|
54736
56309
|
if (path !== ":memory:") {
|
|
54737
56310
|
try {
|
|
54738
|
-
|
|
56311
|
+
mkdirSync13(dirname14(path), { recursive: true });
|
|
54739
56312
|
} catch {}
|
|
54740
56313
|
}
|
|
54741
56314
|
const { Database } = await import("bun:sqlite");
|
|
@@ -54937,7 +56510,7 @@ var riskByTool = null;
|
|
|
54937
56510
|
async function riskIndex() {
|
|
54938
56511
|
if (riskByTool)
|
|
54939
56512
|
return riskByTool;
|
|
54940
|
-
const { moduleCatalog } = await import("./shared/cli-
|
|
56513
|
+
const { moduleCatalog } = await import("./shared/cli-6wdstvdq.js");
|
|
54941
56514
|
const index = new Map;
|
|
54942
56515
|
for (const mod of moduleCatalog) {
|
|
54943
56516
|
for (const tool of mod.tools)
|
|
@@ -54997,10 +56570,10 @@ async function seedConfigJobs() {
|
|
|
54997
56570
|
}
|
|
54998
56571
|
return seeded;
|
|
54999
56572
|
}
|
|
55000
|
-
var
|
|
56573
|
+
var timer4 = null;
|
|
55001
56574
|
async function startScheduler() {
|
|
55002
56575
|
const cfg = getConfig().schedules;
|
|
55003
|
-
if (!cfg.enabled ||
|
|
56576
|
+
if (!cfg.enabled || timer4)
|
|
55004
56577
|
return;
|
|
55005
56578
|
await primeRiskIndex();
|
|
55006
56579
|
const seeded = await seedConfigJobs();
|
|
@@ -55010,7 +56583,7 @@ async function startScheduler() {
|
|
|
55010
56583
|
if (job.enabled)
|
|
55011
56584
|
armJob(job, now);
|
|
55012
56585
|
logger.info(`Scheduled audits enabled: ${jobs.length} job(s)${seeded ? ` (${seeded} seeded from config)` : ""}`);
|
|
55013
|
-
|
|
56586
|
+
timer4 = setInterval(() => {
|
|
55014
56587
|
(async () => {
|
|
55015
56588
|
try {
|
|
55016
56589
|
await tick(await listJobs(), liveExecutor(), runnerOptions());
|
|
@@ -55019,13 +56592,13 @@ async function startScheduler() {
|
|
|
55019
56592
|
}
|
|
55020
56593
|
})();
|
|
55021
56594
|
}, cfg.tickSeconds * 1000);
|
|
55022
|
-
|
|
56595
|
+
timer4.unref?.();
|
|
55023
56596
|
}
|
|
55024
56597
|
function stopScheduler() {
|
|
55025
|
-
if (!
|
|
56598
|
+
if (!timer4)
|
|
55026
56599
|
return;
|
|
55027
|
-
clearInterval(
|
|
55028
|
-
|
|
56600
|
+
clearInterval(timer4);
|
|
56601
|
+
timer4 = null;
|
|
55029
56602
|
}
|
|
55030
56603
|
|
|
55031
56604
|
// src/tools/schedule.ts
|
|
@@ -57159,7 +58732,7 @@ async function readScanList(ctx, list = "port-scanners") {
|
|
|
57159
58732
|
}
|
|
57160
58733
|
|
|
57161
58734
|
// src/attack/correlate.ts
|
|
57162
|
-
import { createHash as
|
|
58735
|
+
import { createHash as createHash9 } from "crypto";
|
|
57163
58736
|
var STAGE_ORDER = ["recon", "attempt", "breach", "persistence"];
|
|
57164
58737
|
var STAGE_OF = {
|
|
57165
58738
|
"port-scan": "recon",
|
|
@@ -57189,7 +58762,7 @@ var SEVERITY_RANK = {
|
|
|
57189
58762
|
info: 4
|
|
57190
58763
|
};
|
|
57191
58764
|
function incidentId(source, dayBucket) {
|
|
57192
|
-
const digest =
|
|
58765
|
+
const digest = createHash9("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
|
|
57193
58766
|
return `atk_${digest}`;
|
|
57194
58767
|
}
|
|
57195
58768
|
function worst(values) {
|
|
@@ -57279,7 +58852,7 @@ function mergeIncident(stored, fresh) {
|
|
|
57279
58852
|
var RECORD_START = /^\s*time=/;
|
|
57280
58853
|
var FIELD_RE = /([a-zA-Z][\w-]*)=(?:"((?:[^"\\]|\\.)*)"|(\S*))/g;
|
|
57281
58854
|
var TIME_WITH_CLOCK_RE = /time=(\S+)[ \t]+(\d{2}:\d{2}:\d{2}(?:\.\d+)?)/;
|
|
57282
|
-
function
|
|
58855
|
+
function fields2(text) {
|
|
57283
58856
|
const out = {};
|
|
57284
58857
|
for (const m of text.matchAll(FIELD_RE)) {
|
|
57285
58858
|
out[m[1]] = m[2] !== undefined ? m[2].replace(/\\(.)/g, "$1") : m[3] ?? "";
|
|
@@ -57301,7 +58874,7 @@ function parseLogRecords(text) {
|
|
|
57301
58874
|
return;
|
|
57302
58875
|
const raw = current.join(`
|
|
57303
58876
|
`);
|
|
57304
|
-
const f =
|
|
58877
|
+
const f = fields2(raw);
|
|
57305
58878
|
if (f.time === undefined || f.message === undefined) {
|
|
57306
58879
|
unparsed.push({ line: startLine, text: raw.trim().slice(0, 200) });
|
|
57307
58880
|
} else {
|
|
@@ -57411,8 +58984,8 @@ function dedupe(events, seen) {
|
|
|
57411
58984
|
}
|
|
57412
58985
|
|
|
57413
58986
|
// src/attack/store.ts
|
|
57414
|
-
import { mkdirSync as
|
|
57415
|
-
import { dirname as
|
|
58987
|
+
import { mkdirSync as mkdirSync14 } from "fs";
|
|
58988
|
+
import { dirname as dirname15 } from "path";
|
|
57416
58989
|
var SCHEMA4 = [
|
|
57417
58990
|
`CREATE TABLE IF NOT EXISTS attack_incidents (
|
|
57418
58991
|
id TEXT PRIMARY KEY,
|
|
@@ -57603,7 +59176,7 @@ class SqliteAttackStore {
|
|
|
57603
59176
|
async function openAttackStore(path) {
|
|
57604
59177
|
if (path !== ":memory:") {
|
|
57605
59178
|
try {
|
|
57606
|
-
|
|
59179
|
+
mkdirSync14(dirname15(path), { recursive: true });
|
|
57607
59180
|
} catch {}
|
|
57608
59181
|
}
|
|
57609
59182
|
const { Database } = await import("bun:sqlite");
|
|
@@ -57790,14 +59363,14 @@ async function sweep(options = {}) {
|
|
|
57790
59363
|
}
|
|
57791
59364
|
return { incidents, unavailable, devices: deviceResults, responses, skipped };
|
|
57792
59365
|
}
|
|
57793
|
-
var
|
|
59366
|
+
var timer5 = null;
|
|
57794
59367
|
var running2 = false;
|
|
57795
59368
|
function startAttackDetection() {
|
|
57796
59369
|
const cfg = getConfig().attacks;
|
|
57797
|
-
if (!cfg.enabled ||
|
|
59370
|
+
if (!cfg.enabled || timer5)
|
|
57798
59371
|
return;
|
|
57799
59372
|
logger.info(`Attack detection enabled: every ${cfg.pollSeconds}s over a ${cfg.windowMinutes}m window (mode=${cfg.mode})`);
|
|
57800
|
-
|
|
59373
|
+
timer5 = setInterval(() => {
|
|
57801
59374
|
if (running2) {
|
|
57802
59375
|
logger.warn("attack sweep still running; skipping this tick");
|
|
57803
59376
|
return;
|
|
@@ -57809,13 +59382,13 @@ function startAttackDetection() {
|
|
|
57809
59382
|
running2 = false;
|
|
57810
59383
|
});
|
|
57811
59384
|
}, cfg.pollSeconds * 1000);
|
|
57812
|
-
|
|
59385
|
+
timer5.unref?.();
|
|
57813
59386
|
}
|
|
57814
59387
|
function stopAttackDetection() {
|
|
57815
|
-
if (!
|
|
59388
|
+
if (!timer5)
|
|
57816
59389
|
return;
|
|
57817
|
-
clearInterval(
|
|
57818
|
-
|
|
59390
|
+
clearInterval(timer5);
|
|
59391
|
+
timer5 = null;
|
|
57819
59392
|
}
|
|
57820
59393
|
|
|
57821
59394
|
// src/tools/attack.ts
|
|
@@ -58304,14 +59877,14 @@ ${result}`;
|
|
|
58304
59877
|
];
|
|
58305
59878
|
|
|
58306
59879
|
// src/core/update-check.ts
|
|
58307
|
-
import { existsSync as existsSync4, mkdirSync as
|
|
59880
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync15, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
|
|
58308
59881
|
import { homedir as homedir2 } from "os";
|
|
58309
|
-
import { dirname as
|
|
59882
|
+
import { dirname as dirname16, join as join9 } from "path";
|
|
58310
59883
|
|
|
58311
59884
|
// src/version.ts
|
|
58312
59885
|
import { readFileSync as readFileSync7 } from "fs";
|
|
58313
|
-
import { join as
|
|
58314
|
-
var pkg = JSON.parse(readFileSync7(
|
|
59886
|
+
import { join as join8 } from "path";
|
|
59887
|
+
var pkg = JSON.parse(readFileSync7(join8(PROJECT_ROOT, "package.json"), "utf-8"));
|
|
58315
59888
|
var VERSION = pkg.version ?? "0.0.0";
|
|
58316
59889
|
var WEBSITE_URL = pkg.homepage ?? "";
|
|
58317
59890
|
var LOGO_URL = pkg.logoIcon ?? "";
|
|
@@ -58324,7 +59897,7 @@ var PKG_META = pkg;
|
|
|
58324
59897
|
var GITHUB_API = "https://api.github.com/repos/mikrotik-mcp/mikrotik-mcp/releases/latest";
|
|
58325
59898
|
var MEMORY_CACHE_TTL = 15 * 60 * 1000;
|
|
58326
59899
|
var FILE_CACHE_TTL = 6 * 60 * 60 * 1000;
|
|
58327
|
-
var CACHE_PATH =
|
|
59900
|
+
var CACHE_PATH = join9(homedir2(), ".mikrotik-mcp", "update-check.json");
|
|
58328
59901
|
function compareVersions2(a, b) {
|
|
58329
59902
|
const pa = a.replace(/^v/, "").split(".").map(Number);
|
|
58330
59903
|
const pb = b.replace(/^v/, "").split(".").map(Number);
|
|
@@ -58354,9 +59927,9 @@ function loadFileCacheSync() {
|
|
|
58354
59927
|
}
|
|
58355
59928
|
function saveFileCache(data) {
|
|
58356
59929
|
try {
|
|
58357
|
-
const dir =
|
|
59930
|
+
const dir = dirname16(CACHE_PATH);
|
|
58358
59931
|
if (!existsSync4(dir))
|
|
58359
|
-
|
|
59932
|
+
mkdirSync15(dir, { recursive: true });
|
|
58360
59933
|
writeFileSync3(CACHE_PATH, JSON.stringify({ data, fetchedAt: Date.now() }));
|
|
58361
59934
|
} catch {}
|
|
58362
59935
|
}
|
|
@@ -58572,13 +60145,27 @@ var serverPulseTools = [
|
|
|
58572
60145
|
];
|
|
58573
60146
|
|
|
58574
60147
|
// src/observability/config-admin.ts
|
|
58575
|
-
import { createHash as
|
|
58576
|
-
import { readFileSync as
|
|
60148
|
+
import { createHash as createHash10, randomUUID as randomUUID10 } from "crypto";
|
|
60149
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
58577
60150
|
|
|
58578
60151
|
// src/config-write.ts
|
|
58579
|
-
import { randomUUID as
|
|
58580
|
-
import {
|
|
58581
|
-
|
|
60152
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
60153
|
+
import {
|
|
60154
|
+
closeSync,
|
|
60155
|
+
constants,
|
|
60156
|
+
fchmodSync,
|
|
60157
|
+
fstatSync,
|
|
60158
|
+
fsyncSync,
|
|
60159
|
+
ftruncateSync,
|
|
60160
|
+
mkdirSync as mkdirSync16,
|
|
60161
|
+
openSync,
|
|
60162
|
+
readFileSync as readFileSync9,
|
|
60163
|
+
renameSync as renameSync2,
|
|
60164
|
+
rmSync as rmSync2,
|
|
60165
|
+
writeFileSync as writeFileSync4,
|
|
60166
|
+
writeSync
|
|
60167
|
+
} from "fs";
|
|
60168
|
+
import { dirname as dirname17 } from "path";
|
|
58582
60169
|
|
|
58583
60170
|
// src/config-device-draft.ts
|
|
58584
60171
|
var CREDENTIAL_SOURCE = "$credentialsFrom";
|
|
@@ -58651,15 +60238,55 @@ function backupName(path, ts) {
|
|
|
58651
60238
|
return `${path}.bak-${ts}`;
|
|
58652
60239
|
}
|
|
58653
60240
|
function atomicWrite(path, text) {
|
|
58654
|
-
|
|
58655
|
-
const tmp = `${path}.tmp-${
|
|
60241
|
+
mkdirSync16(dirname17(path), { recursive: true });
|
|
60242
|
+
const tmp = `${path}.tmp-${randomUUID9()}`;
|
|
58656
60243
|
try {
|
|
58657
|
-
writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
58658
|
-
|
|
60244
|
+
writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx", flush: true });
|
|
60245
|
+
try {
|
|
60246
|
+
renameSync2(tmp, path);
|
|
60247
|
+
} catch (error) {
|
|
60248
|
+
if (error.code !== "EBUSY")
|
|
60249
|
+
throw error;
|
|
60250
|
+
writeMountedFile(path, text);
|
|
60251
|
+
}
|
|
58659
60252
|
} finally {
|
|
58660
60253
|
rmSync2(tmp, { force: true });
|
|
58661
60254
|
}
|
|
58662
60255
|
}
|
|
60256
|
+
function replaceContents(fd, bytes) {
|
|
60257
|
+
let offset = 0;
|
|
60258
|
+
while (offset < bytes.length) {
|
|
60259
|
+
const written = writeSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
60260
|
+
if (written === 0)
|
|
60261
|
+
throw new Error("Configuration write made no progress.");
|
|
60262
|
+
offset += written;
|
|
60263
|
+
}
|
|
60264
|
+
ftruncateSync(fd, bytes.length);
|
|
60265
|
+
fsyncSync(fd);
|
|
60266
|
+
}
|
|
60267
|
+
function writeMountedFile(path, text) {
|
|
60268
|
+
const fd = openSync(path, constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
60269
|
+
try {
|
|
60270
|
+
if (!fstatSync(fd).isFile())
|
|
60271
|
+
throw new Error("Configuration target must be a regular file.");
|
|
60272
|
+
fchmodSync(fd, 384);
|
|
60273
|
+
const previous = readFileSync9(fd);
|
|
60274
|
+
const backup = `${path}.bak-mounted-${randomUUID9()}`;
|
|
60275
|
+
writeFileSync4(backup, previous, { mode: 384, flag: "wx", flush: true });
|
|
60276
|
+
try {
|
|
60277
|
+
replaceContents(fd, Buffer.from(text, "utf8"));
|
|
60278
|
+
} catch {
|
|
60279
|
+
try {
|
|
60280
|
+
replaceContents(fd, previous);
|
|
60281
|
+
} catch {
|
|
60282
|
+
throw new Error("Configuration write and recovery failed; restore the retained mounted-file backup.");
|
|
60283
|
+
}
|
|
60284
|
+
throw new Error("Configuration write failed; previous contents restored and backup retained.");
|
|
60285
|
+
}
|
|
60286
|
+
} finally {
|
|
60287
|
+
closeSync(fd);
|
|
60288
|
+
}
|
|
60289
|
+
}
|
|
58663
60290
|
|
|
58664
60291
|
// src/observability/config-admin.ts
|
|
58665
60292
|
function validateConfig(raw) {
|
|
@@ -58677,8 +60304,8 @@ function validateConfig(raw) {
|
|
|
58677
60304
|
function createConfigAdmin(deps) {
|
|
58678
60305
|
let pending = null;
|
|
58679
60306
|
let lastTimestamp = 0;
|
|
58680
|
-
const salt =
|
|
58681
|
-
const fingerprint = (config, source, contents) =>
|
|
60307
|
+
const salt = randomUUID10();
|
|
60308
|
+
const fingerprint = (config, source, contents) => createHash10("sha256").update(salt).update(JSON.stringify([config, source, contents])).digest("hex");
|
|
58682
60309
|
const revision = () => {
|
|
58683
60310
|
const source = deps.source();
|
|
58684
60311
|
return fingerprint(deps.getConfig(), source, deps.readFile(source.path));
|
|
@@ -58772,7 +60399,7 @@ function getConfigAdmin() {
|
|
|
58772
60399
|
source: getConfigSource2,
|
|
58773
60400
|
readFile: (path) => {
|
|
58774
60401
|
try {
|
|
58775
|
-
return
|
|
60402
|
+
return readFileSync10(path, "utf8");
|
|
58776
60403
|
} catch (error) {
|
|
58777
60404
|
if (error.code === "ENOENT")
|
|
58778
60405
|
return null;
|
|
@@ -58824,7 +60451,7 @@ var McpSettingsPendingSchema = object({
|
|
|
58824
60451
|
revision: string2().length(64).describe("Revision returned by update_mcp_settings or get_mcp_settings.")
|
|
58825
60452
|
}).strict();
|
|
58826
60453
|
var BOUNDARY = "Only the listed fields are editable. Devices, credentials, file paths, listeners, access, readOnly, tools and service probe allowlists remain operator-managed. No router is contacted.";
|
|
58827
|
-
function
|
|
60454
|
+
function settings2(cfg) {
|
|
58828
60455
|
return {
|
|
58829
60456
|
mcp: {
|
|
58830
60457
|
toolPageSize: cfg.mcp.toolPageSize,
|
|
@@ -58854,7 +60481,7 @@ function createMcpSettingsService(deps) {
|
|
|
58854
60481
|
const source = deps.source();
|
|
58855
60482
|
return {
|
|
58856
60483
|
revision: deps.admin.revision(),
|
|
58857
|
-
settings:
|
|
60484
|
+
settings: settings2(deps.getConfig()),
|
|
58858
60485
|
pending: id ? { id, owned: id === owned?.id, expiresAt: id === owned?.id ? owned.expiresAt : null } : null,
|
|
58859
60486
|
persistence: {
|
|
58860
60487
|
path: source.path,
|
|
@@ -58880,8 +60507,8 @@ function createMcpSettingsService(deps) {
|
|
|
58880
60507
|
});
|
|
58881
60508
|
if (changes.dashboard?.captureBody === true && !next.dashboard.redactInput)
|
|
58882
60509
|
throw new Error("Enabling body capture also requires dashboard.redactInput=true.");
|
|
58883
|
-
const before =
|
|
58884
|
-
const after =
|
|
60510
|
+
const before = settings2(current);
|
|
60511
|
+
const after = settings2(next);
|
|
58885
60512
|
const changedPaths = [];
|
|
58886
60513
|
for (const key of ["mcp", "ssh", "dashboard", "memory"]) {
|
|
58887
60514
|
for (const [field, value] of Object.entries(after[key])) {
|
|
@@ -59001,7 +60628,7 @@ var mcpSettingsTools = [
|
|
|
59001
60628
|
title: "Safely Update MCP Settings",
|
|
59002
60629
|
noDevice: true,
|
|
59003
60630
|
annotations: WRITE,
|
|
59004
|
-
description: "Apply explicitly user-approved MCP host settings, not RouterOS configuration. First get_mcp_settings_schema and preview_mcp_settings; supply that revision and confirm=true. Backs up the
|
|
60631
|
+
description: "Apply explicitly user-approved MCP host settings, not RouterOS configuration. First get_mcp_settings_schema and preview_mcp_settings; supply that revision and confirm=true. Backs up the source JSON, persists the full config and arms a 30\u2013600s in-process rollback (default 60s). Normal files use atomic replacement; a single-file Docker bind mount uses a backed-up in-place write that is not crash-atomic. Conflicts with another pending dashboard/tool edit are rejected. Verify configured values with get_mcp_settings, then confirm_mcp_settings before the deadline or rollback_mcp_settings. Never restart while pending: the rollback timer does not survive process exit. Restart-required settings are only fully activated after confirmation and a separate operator-controlled restart. Does not widen access scopes or change router addresses/credentials.",
|
|
59005
60632
|
inputSchema: McpSettingsUpdateSchema.shape,
|
|
59006
60633
|
handler: (args) => render(getMcpSettingsService().update(args))
|
|
59007
60634
|
}),
|
|
@@ -61047,7 +62674,7 @@ ${result}`;
|
|
|
61047
62674
|
];
|
|
61048
62675
|
|
|
61049
62676
|
// src/tools/user-manager.ts
|
|
61050
|
-
var
|
|
62677
|
+
var NOT_AVAILABLE2 = "User Manager is not available on this device (package not installed).";
|
|
61051
62678
|
var userManagerToolsDefs = [
|
|
61052
62679
|
defineTool({
|
|
61053
62680
|
name: "get_user_manager_settings",
|
|
@@ -61058,7 +62685,7 @@ var userManagerToolsDefs = [
|
|
|
61058
62685
|
ctx.info("Getting User Manager settings");
|
|
61059
62686
|
const result = await executeMikrotikCommand("/user-manager print", ctx);
|
|
61060
62687
|
if (commandUnsupported(result))
|
|
61061
|
-
return
|
|
62688
|
+
return NOT_AVAILABLE2;
|
|
61062
62689
|
return isEmpty(result) ? "No User Manager settings found." : `USER MANAGER SETTINGS:
|
|
61063
62690
|
|
|
61064
62691
|
${result}`;
|
|
@@ -61084,7 +62711,7 @@ ${result}`;
|
|
|
61084
62711
|
return "No updates specified.";
|
|
61085
62712
|
const result = await executeMikrotikCommand(cmd, ctx);
|
|
61086
62713
|
if (commandUnsupported(result))
|
|
61087
|
-
return
|
|
62714
|
+
return NOT_AVAILABLE2;
|
|
61088
62715
|
if (looksLikeError(result))
|
|
61089
62716
|
return `Failed to update User Manager settings: ${result}`;
|
|
61090
62717
|
const details = await executeMikrotikCommand("/user-manager print", ctx);
|
|
@@ -61114,7 +62741,7 @@ ${details}`;
|
|
|
61114
62741
|
const cmd = new Cmd("/user-manager user add").set("name", a.name).set("password", a.password).opt("group", a.group).opt("shared-users", a.shared_users).opt("attributes", a.attributes).opt("caller-id", a.caller_id).opt("otp-secret", a.otp_secret).opt("comment", a.comment).flag("disabled", a.disabled).build();
|
|
61115
62742
|
const result = await executeMikrotikCommand(cmd, ctx);
|
|
61116
62743
|
if (commandUnsupported(result))
|
|
61117
|
-
return
|
|
62744
|
+
return NOT_AVAILABLE2;
|
|
61118
62745
|
if (looksLikeError(result))
|
|
61119
62746
|
return `Failed to add User Manager user: ${result}`;
|
|
61120
62747
|
const details = await executeMikrotikCommand(`/user-manager user print detail where name="${a.name}"`, ctx);
|
|
@@ -61138,7 +62765,7 @@ ${redactSecrets(details)}` : "User Manager user creation completed but unable to
|
|
|
61138
62765
|
filters.push(`name~"${a.name_filter}"`);
|
|
61139
62766
|
const result = await executeMikrotikCommand(`/user-manager user print${whereClause(filters)}`, ctx);
|
|
61140
62767
|
if (commandUnsupported(result))
|
|
61141
|
-
return
|
|
62768
|
+
return NOT_AVAILABLE2;
|
|
61142
62769
|
return isEmpty(result) ? "No User Manager users found matching the criteria." : `USER MANAGER USERS:
|
|
61143
62770
|
|
|
61144
62771
|
${redactSecrets(result)}`;
|
|
@@ -61154,7 +62781,7 @@ ${redactSecrets(result)}`;
|
|
|
61154
62781
|
ctx.info(`Getting User Manager user details: name=${a.name}`);
|
|
61155
62782
|
const result = await executeMikrotikCommand(`/user-manager user print detail where name="${a.name}"`, ctx);
|
|
61156
62783
|
if (commandUnsupported(result))
|
|
61157
|
-
return
|
|
62784
|
+
return NOT_AVAILABLE2;
|
|
61158
62785
|
return isEmpty(result) ? `User Manager user '${a.name}' not found.` : `USER MANAGER USER DETAILS:
|
|
61159
62786
|
|
|
61160
62787
|
${redactSecrets(result)}`;
|
|
@@ -61184,7 +62811,7 @@ ${redactSecrets(result)}`;
|
|
|
61184
62811
|
return "No updates specified.";
|
|
61185
62812
|
const result = await executeMikrotikCommand(cmd, ctx);
|
|
61186
62813
|
if (commandUnsupported(result))
|
|
61187
|
-
return
|
|
62814
|
+
return NOT_AVAILABLE2;
|
|
61188
62815
|
if (looksLikeError(result))
|
|
61189
62816
|
return `Failed to update User Manager user: ${result}`;
|
|
61190
62817
|
const target = a.new_name ?? a.name;
|
|
@@ -61204,7 +62831,7 @@ ${redactSecrets(details)}`;
|
|
|
61204
62831
|
ctx.info(`Removing User Manager user: name=${a.name}`);
|
|
61205
62832
|
const count = await executeMikrotikCommand(`/user-manager user print count-only where name="${a.name}"`, ctx);
|
|
61206
62833
|
if (commandUnsupported(count))
|
|
61207
|
-
return
|
|
62834
|
+
return NOT_AVAILABLE2;
|
|
61208
62835
|
if (count.trim() === "0")
|
|
61209
62836
|
return `User Manager user '${a.name}' not found.`;
|
|
61210
62837
|
const result = await executeMikrotikCommand(`/user-manager user remove [find name="${a.name}"]`, ctx);
|
|
@@ -61232,7 +62859,7 @@ ${redactSecrets(details)}`;
|
|
|
61232
62859
|
const cmd = new Cmd("/user-manager profile add").set("name", a.name).opt("name-for-users", a.name_for_users).opt("validity", a.validity).opt("price", a.price).opt("starts-when", a.starts_when).opt("override-shared-users", a.override_shared_users).opt("comment", a.comment).build();
|
|
61233
62860
|
const result = await executeMikrotikCommand(cmd, ctx);
|
|
61234
62861
|
if (commandUnsupported(result))
|
|
61235
|
-
return
|
|
62862
|
+
return NOT_AVAILABLE2;
|
|
61236
62863
|
if (looksLikeError(result))
|
|
61237
62864
|
return `Failed to add User Manager profile: ${result}`;
|
|
61238
62865
|
const details = await executeMikrotikCommand(`/user-manager profile print detail where name="${a.name}"`, ctx);
|
|
@@ -61256,7 +62883,7 @@ ${details}` : "User Manager profile creation completed but unable to verify.";
|
|
|
61256
62883
|
filters.push(`name~"${a.name_filter}"`);
|
|
61257
62884
|
const result = await executeMikrotikCommand(`/user-manager profile print${whereClause(filters)}`, ctx);
|
|
61258
62885
|
if (commandUnsupported(result))
|
|
61259
|
-
return
|
|
62886
|
+
return NOT_AVAILABLE2;
|
|
61260
62887
|
return isEmpty(result) ? "No User Manager profiles found matching the criteria." : `USER MANAGER PROFILES:
|
|
61261
62888
|
|
|
61262
62889
|
${result}`;
|
|
@@ -61272,7 +62899,7 @@ ${result}`;
|
|
|
61272
62899
|
ctx.info(`Removing User Manager profile: name=${a.name}`);
|
|
61273
62900
|
const count = await executeMikrotikCommand(`/user-manager profile print count-only where name="${a.name}"`, ctx);
|
|
61274
62901
|
if (commandUnsupported(count))
|
|
61275
|
-
return
|
|
62902
|
+
return NOT_AVAILABLE2;
|
|
61276
62903
|
if (count.trim() === "0")
|
|
61277
62904
|
return `User Manager profile '${a.name}' not found.`;
|
|
61278
62905
|
const result = await executeMikrotikCommand(`/user-manager profile remove [find name="${a.name}"]`, ctx);
|
|
@@ -61295,7 +62922,7 @@ ${result}`;
|
|
|
61295
62922
|
const cmd = new Cmd("/user-manager user-profile add").set("user", a.user).set("profile", a.profile).build();
|
|
61296
62923
|
const result = await executeMikrotikCommand(cmd, ctx);
|
|
61297
62924
|
if (commandUnsupported(result))
|
|
61298
|
-
return
|
|
62925
|
+
return NOT_AVAILABLE2;
|
|
61299
62926
|
if (looksLikeError(result))
|
|
61300
62927
|
return `Failed to assign profile: ${result}`;
|
|
61301
62928
|
return `Assigned profile '${a.profile}' to user '${a.user}'.
|
|
@@ -61318,7 +62945,7 @@ ${result}`;
|
|
|
61318
62945
|
filters.push(`user~"${a.user_filter}"`);
|
|
61319
62946
|
const result = await executeMikrotikCommand(`/user-manager user-profile print${whereClause(filters)}`, ctx);
|
|
61320
62947
|
if (commandUnsupported(result))
|
|
61321
|
-
return
|
|
62948
|
+
return NOT_AVAILABLE2;
|
|
61322
62949
|
return isEmpty(result) ? "No User Manager user-profiles found matching the criteria." : `USER MANAGER USER-PROFILES:
|
|
61323
62950
|
|
|
61324
62951
|
${result}`;
|
|
@@ -61343,7 +62970,7 @@ ${result}`;
|
|
|
61343
62970
|
const cmd = new Cmd("/user-manager router add").set("name", a.name).set("address", a.address).set("shared-secret", a.shared_secret).opt("coa-port", a.coa_port).opt("protocol", a.protocol).opt("comment", a.comment).flag("disabled", a.disabled).build();
|
|
61344
62971
|
const result = await executeMikrotikCommand(cmd, ctx);
|
|
61345
62972
|
if (commandUnsupported(result))
|
|
61346
|
-
return
|
|
62973
|
+
return NOT_AVAILABLE2;
|
|
61347
62974
|
if (looksLikeError(result))
|
|
61348
62975
|
return `Failed to add User Manager router: ${result}`;
|
|
61349
62976
|
const details = await executeMikrotikCommand(`/user-manager router print detail where name="${a.name}"`, ctx);
|
|
@@ -61367,7 +62994,7 @@ ${redactSecrets(details)}` : "User Manager router creation completed but unable
|
|
|
61367
62994
|
filters.push(`name~"${a.name_filter}"`);
|
|
61368
62995
|
const result = await executeMikrotikCommand(`/user-manager router print${whereClause(filters)}`, ctx);
|
|
61369
62996
|
if (commandUnsupported(result))
|
|
61370
|
-
return
|
|
62997
|
+
return NOT_AVAILABLE2;
|
|
61371
62998
|
return isEmpty(result) ? "No User Manager routers found matching the criteria." : `USER MANAGER ROUTERS:
|
|
61372
62999
|
|
|
61373
63000
|
${redactSecrets(result)}`;
|
|
@@ -61383,7 +63010,7 @@ ${redactSecrets(result)}`;
|
|
|
61383
63010
|
ctx.info(`Removing User Manager router: name=${a.name}`);
|
|
61384
63011
|
const count = await executeMikrotikCommand(`/user-manager router print count-only where name="${a.name}"`, ctx);
|
|
61385
63012
|
if (commandUnsupported(count))
|
|
61386
|
-
return
|
|
63013
|
+
return NOT_AVAILABLE2;
|
|
61387
63014
|
if (count.trim() === "0")
|
|
61388
63015
|
return `User Manager router '${a.name}' not found.`;
|
|
61389
63016
|
const result = await executeMikrotikCommand(`/user-manager router remove [find name="${a.name}"]`, ctx);
|
|
@@ -61423,7 +63050,7 @@ ${redactSecrets(result)}`;
|
|
|
61423
63050
|
const cmd = new Cmd("/user-manager limitation add").set("name", a.name).opt("rate-limit-rx", a.rate_limit_rx).opt("rate-limit-tx", a.rate_limit_tx).opt("rate-limit-min-rx", a.rate_limit_min_rx).opt("rate-limit-min-tx", a.rate_limit_min_tx).opt("rate-limit-burst-rx", a.rate_limit_burst_rx).opt("rate-limit-burst-tx", a.rate_limit_burst_tx).opt("rate-limit-burst-threshold-rx", a.rate_limit_burst_threshold_rx).opt("rate-limit-burst-threshold-tx", a.rate_limit_burst_threshold_tx).opt("rate-limit-burst-time-rx", a.rate_limit_burst_time_rx).opt("rate-limit-burst-time-tx", a.rate_limit_burst_time_tx).opt("rate-limit-priority", a.rate_limit_priority).opt("download-limit", a.download_limit).opt("upload-limit", a.upload_limit).opt("transfer-limit", a.transfer_limit).opt("uptime-limit", a.uptime_limit).opt("reset-counters-interval", a.reset_counters_interval).opt("reset-counters-start-time", a.reset_counters_start_time).opt("comment", a.comment).build();
|
|
61424
63051
|
const result = await executeMikrotikCommand(cmd, ctx);
|
|
61425
63052
|
if (commandUnsupported(result))
|
|
61426
|
-
return
|
|
63053
|
+
return NOT_AVAILABLE2;
|
|
61427
63054
|
if (looksLikeError(result))
|
|
61428
63055
|
return `Failed to add User Manager limitation: ${result}`;
|
|
61429
63056
|
const details = await executeMikrotikCommand(`/user-manager limitation print detail where name="${a.name}"`, ctx);
|
|
@@ -61447,7 +63074,7 @@ ${details}` : "User Manager limitation creation completed but unable to verify."
|
|
|
61447
63074
|
filters.push(`name~"${a.name_filter}"`);
|
|
61448
63075
|
const result = await executeMikrotikCommand(`/user-manager limitation print${whereClause(filters)}`, ctx);
|
|
61449
63076
|
if (commandUnsupported(result))
|
|
61450
|
-
return
|
|
63077
|
+
return NOT_AVAILABLE2;
|
|
61451
63078
|
return isEmpty(result) ? "No User Manager limitations found matching the criteria." : `USER MANAGER LIMITATIONS:
|
|
61452
63079
|
|
|
61453
63080
|
${result}`;
|
|
@@ -61463,7 +63090,7 @@ ${result}`;
|
|
|
61463
63090
|
ctx.info(`Removing User Manager limitation: name=${a.name}`);
|
|
61464
63091
|
const count = await executeMikrotikCommand(`/user-manager limitation print count-only where name="${a.name}"`, ctx);
|
|
61465
63092
|
if (commandUnsupported(count))
|
|
61466
|
-
return
|
|
63093
|
+
return NOT_AVAILABLE2;
|
|
61467
63094
|
if (count.trim() === "0")
|
|
61468
63095
|
return `User Manager limitation '${a.name}' not found.`;
|
|
61469
63096
|
const result = await executeMikrotikCommand(`/user-manager limitation remove [find name="${a.name}"]`, ctx);
|
|
@@ -61490,7 +63117,7 @@ ${result}`;
|
|
|
61490
63117
|
filters.push("active=yes");
|
|
61491
63118
|
const result = await executeMikrotikCommand(`/user-manager session print${whereClause(filters)}`, ctx);
|
|
61492
63119
|
if (commandUnsupported(result))
|
|
61493
|
-
return
|
|
63120
|
+
return NOT_AVAILABLE2;
|
|
61494
63121
|
return isEmpty(result) ? "No User Manager sessions found matching the criteria." : `USER MANAGER SESSIONS:
|
|
61495
63122
|
|
|
61496
63123
|
${result}`;
|
|
@@ -61924,33 +63551,281 @@ ${result}`;
|
|
|
61924
63551
|
})
|
|
61925
63552
|
];
|
|
61926
63553
|
|
|
63554
|
+
// src/core/vlan-guidance.ts
|
|
63555
|
+
var VLAN_GUIDE_URI = "mikrotik://knowledge/vlan-segmentation";
|
|
63556
|
+
var VLAN_GUIDE_VERSION = "2026-10-03";
|
|
63557
|
+
var VLAN_GUIDE_TOPICS = [
|
|
63558
|
+
"overview",
|
|
63559
|
+
"discovery",
|
|
63560
|
+
"layer2",
|
|
63561
|
+
"policy",
|
|
63562
|
+
"migration",
|
|
63563
|
+
"verification"
|
|
63564
|
+
];
|
|
63565
|
+
var sections2 = {
|
|
63566
|
+
overview: `## Intent and boundaries
|
|
63567
|
+
Use this guide for homelab VLAN segmentation, guest Wi-Fi, IoT isolation and
|
|
63568
|
+
management networks. It is reference knowledge, NOT observed device state or
|
|
63569
|
+
authorization. Start read-only; use find_tools and describe_tool for the tools
|
|
63570
|
+
actually exposed in this session. Never bypass read-only mode or module restrictions.
|
|
63571
|
+
|
|
63572
|
+
Adapt the homelab-vlan-segmentation design to the actual requirements. Illustrative
|
|
63573
|
+
roles/IDs are Trusted 10, IoT 20, Servers 30 (only if needed), Guest 40 and Management
|
|
63574
|
+
99. IDs are examples, not reservations or defaults to apply. Preserve working
|
|
63575
|
+
subnets where possible; check overlap with WAN, VPN, remote sites and other VLANs.
|
|
63576
|
+
Trusted users are not automatically administrators. Agree a source/destination/
|
|
63577
|
+
service allow matrix, including router management, before proposing changes.
|
|
63578
|
+
|
|
63579
|
+
VLAN sub-interfaces alone do not provide isolation. Layer-2 membership, routed
|
|
63580
|
+
IPv4/IPv6 policy and actual endpoint tests are separate requirements. A VPS/CHR
|
|
63581
|
+
used only as a routed tunnel endpoint may need routes/policy, not local VLANs.
|
|
63582
|
+
Do not extend a broadcast domain across a WAN without an explicit L2 requirement.
|
|
63583
|
+
Segmentation is not a promise of lower latency or higher tunnel throughput.`,
|
|
63584
|
+
discovery: `## Read-only discovery and evidence
|
|
63585
|
+
Resolve each router by its exact configured device name and verify identity,
|
|
63586
|
+
RouterOS version, board, switch chip and installed Wi-Fi package. Recall constraints
|
|
63587
|
+
separately for each device if Memory is enabled; inspect conflicts and omitted
|
|
63588
|
+
constraints. Recalled facts may be stale. Never copy one router's addresses to another.
|
|
63589
|
+
|
|
63590
|
+
Discover interfaces, bridge settings/ports/VLAN table, VLAN sub-interfaces, interface
|
|
63591
|
+
lists, IP addresses, DHCP pools/networks/leases, DNS, IPv6 addresses/prefix delegation,
|
|
63592
|
+
ND/RA, IPv4 AND IPv6 filter/raw/NAT/mangle rules, routes/routing tables/rules,
|
|
63593
|
+
WireGuard allowed-addresses, queues, Wi-Fi/CAPsMAN/SSID datapaths and management
|
|
63594
|
+
services/MAC discovery. Use bounded, filtered reads; report unsupported, incomplete
|
|
63595
|
+
or timed-out reads as unknown, never empty or safe. Do not fetch credentials.
|
|
63596
|
+
|
|
63597
|
+
Build a physical port map: peer device, WAN/LAN/trunk/access role, bridge, PVID,
|
|
63598
|
+
tagged/untagged membership, link rate, hardware offload and management dependency.
|
|
63599
|
+
Do not infer a port's role from ether1, a comment, or a link-down snapshot. Resolve
|
|
63600
|
+
conflicting labels with the operator. Verify external switch/AP VLAN capability
|
|
63601
|
+
and its management/native VLAN before planning a trunk. Inventory scripts, netwatch,
|
|
63602
|
+
interface lists, NAT, policy-routing and queues that depend on the old interfaces.
|
|
63603
|
+
Distinguish proven observations, intended policy and unverified assumptions.`,
|
|
63604
|
+
layer2: `## Layer 2, CPU access and Wi-Fi
|
|
63605
|
+
For a NEW bridge, stage with vlan-filtering=no. For an existing production bridge,
|
|
63606
|
+
do not turn filtering off to simplify a migration: that can remove isolation.
|
|
63607
|
+
Enable VLAN filtering LAST when the VLAN table, port admission, management path,
|
|
63608
|
+
gateway and recovery plan are ready. A bridge reset can interrupt the session.
|
|
63609
|
+
|
|
63610
|
+
A routed VLAN interface normally belongs on the bridge, not on a physical port
|
|
63611
|
+
already enslaved to it. Include the bridge/CPU as tagged for VLANs terminated on
|
|
63612
|
+
that bridge and verify effective current-tagged membership (RouterOS may create
|
|
63613
|
+
dynamic entries). Do not expose CPU membership on VLANs that need only switching.
|
|
63614
|
+
Creating /interface vlan does not configure /interface bridge vlan or access ports.
|
|
63615
|
+
|
|
63616
|
+
On access ports: one intended untagged VLAN, matching PVID, ingress-filtering and
|
|
63617
|
+
admit-only-untagged-and-priority-tagged where supported. PVID classifies untagged
|
|
63618
|
+
ingress; it is not a tagged-traffic allowlist. Do not combine multiple VLAN IDs in
|
|
63619
|
+
a VLAN-table row containing access ports. On tagged-only trunks: explicit allowed
|
|
63620
|
+
VLAN membership, ingress-filtering and admit-only-vlan-tagged. Model hybrid/native
|
|
63621
|
+
ports explicitly; inspect dynamic VLAN 1/CPU membership for accidental access.
|
|
63622
|
+
Never add a WAN/ONT port to a LAN bridge merely because an example uses that number.
|
|
63623
|
+
|
|
63624
|
+
Map each SSID to a verified VLAN at the AP as well as its uplink. Inspect wireless,
|
|
63625
|
+
wifiwave2 or wifi and CAPsMAN local/manager forwarding. wifi-qcom and wifi-qcom-ac
|
|
63626
|
+
are not interchangeable: qcom-ac needs the appropriate bridge/PVID design rather
|
|
63627
|
+
than blindly copying CAPsMAN datapath vlan-id. Verify package-specific support.
|
|
63628
|
+
Guest client isolation within one SSID/VLAN is separate from inter-VLAN firewalling.
|
|
63629
|
+
Do not enable bridge use-ip-firewall just to filter traffic already routed by the
|
|
63630
|
+
CPU; inspect hardware-offload support and measure the performance impact.`,
|
|
63631
|
+
policy: `## Dual-stack policy and remote-site dependencies
|
|
63632
|
+
Design INPUT (to the router) and FORWARD (through the router) separately for both
|
|
63633
|
+
IPv4 and IPv6. Limit administration to the approved management sources/VPNs; allow
|
|
63634
|
+
only required DHCP/DNS/NTP and essential ICMP/ICMPv6 functions on client segments.
|
|
63635
|
+
Preserve neighbor discovery, router advertisements where intended and path-MTU
|
|
63636
|
+
discovery. Do not solve isolation by indiscriminately blocking all ICMPv6.
|
|
63637
|
+
|
|
63638
|
+
Evaluate first-match rule order, jumps, broad LAN/!WAN accepts, established flows,
|
|
63639
|
+
FastTrack and existing final drops. Place exact service exceptions before segment
|
|
63640
|
+
denies, and denies before broad accepts they must constrain. Appended drop rules
|
|
63641
|
+
may never match. Use current stable .ids, not saved row numbers. Preserve unrelated
|
|
63642
|
+
protections and allowlists. RFC1918-only drops miss local public IPv4, VPN/remote
|
|
63643
|
+
networks and all IPv6; enumerate actual protected destinations. Default-deny between
|
|
63644
|
+
zones with explicit exceptions is a design goal, not permission to rewrite a firewall.
|
|
63645
|
+
|
|
63646
|
+
NAT is not isolation or a routing policy. Reuse valid existing NAT; any new source
|
|
63647
|
+
NAT must be scoped to the intended egress, never every destination. SNAT may hide
|
|
63648
|
+
VLAN source identities from a remote router, so enforce segmentation locally unless
|
|
63649
|
+
an explicitly designed routed/no-NAT topology preserves them. Add new subnets to
|
|
63650
|
+
VPN allowed-addresses, return routes and remote policies only when required.
|
|
63651
|
+
|
|
63652
|
+
Each IPv6 SLAAC segment needs its own non-overlapping /64 from a valid routed or
|
|
63653
|
+
delegated prefix; do not reuse one /64 on separate L2 domains. Verify upstream
|
|
63654
|
+
reachability and return routing, not just a local address. If unavailable, report
|
|
63655
|
+
IPv6 as unconfigured/blocked by prerequisites, not working or isolated by IPv4.
|
|
63656
|
+
|
|
63657
|
+
Move policy-routing/interface-list/queue/automation dependencies before retiring
|
|
63658
|
+
legacy interfaces. FastTrack only eligible main-table traffic; policy-routed,
|
|
63659
|
+
queued or accounted traffic needs appropriate exclusions. Moving FastTrack above
|
|
63660
|
+
an established accept can change behavior beyond VLANs; never do it blindly.`,
|
|
63661
|
+
migration: `## Safe rollout and planner limits
|
|
63662
|
+
Deliver: (1) observed topology and unknowns; (2) proposed VLAN/subnet/IPv6/SSID/port
|
|
63663
|
+
map; (3) explicit allow/deny service matrix; (4) exact ordered per-device changes;
|
|
63664
|
+
(5) prerequisites, rollback triggers and acceptance tests. Ask only for missing
|
|
63665
|
+
choices that affect connectivity or policy. Do not invent interface or subnet roles.
|
|
63666
|
+
|
|
63667
|
+
Before writes, obtain approval for the exact scope, capture a host-side snapshot
|
|
63668
|
+
and follow the local-backup requirements. Confirm an independent console, rescue
|
|
63669
|
+
port or verified management path that does not depend on the bridge being changed.
|
|
63670
|
+
Do not assume a VPN is independent: it may traverse that same bridge/uplink.
|
|
63671
|
+
Use owned Safe Mode for suitable single-router changes; coordinated multi-router
|
|
63672
|
+
writes should use the transaction workflow when available and suitable. Transaction
|
|
63673
|
+
verification stages REAL changes, not an offline preview. Safe Mode is not a backup
|
|
63674
|
+
or a guarantee for all operations; ambiguous timeouts are not permission to retry.
|
|
63675
|
+
Preserve the old management path until the new one has been tested. Canary one
|
|
63676
|
+
port/SSID/client, then migrate the remainder; never reconfigure all access at once.
|
|
63677
|
+
|
|
63678
|
+
design_network_segment is only partial IPv4 scaffolding, not a full isolation
|
|
63679
|
+
engine. It does not configure bridge port PVID/admission, enable VLAN filtering,
|
|
63680
|
+
map SSIDs, build router INPUT or IPv6 policy, prove rule reachability, preserve
|
|
63681
|
+
remote routing, or roll back a partial apply. NAT needs explicit wan_interface;
|
|
63682
|
+
isolation drops need a current reviewed isolation_before rule .id. Non-/24 DHCP
|
|
63683
|
+
needs an explicit valid pool. Discover schemas before previewing; apply only after
|
|
63684
|
+
the surrounding approved configuration satisfies these prerequisites. Do not call
|
|
63685
|
+
it repeatedly to finish a partially applied plan; read back and reconcile first.
|
|
63686
|
+
For a complete migration, prefer an explicit reviewed plan with separate steps.`,
|
|
63687
|
+
verification: `## Verification, reporting and clean memory
|
|
63688
|
+
Read back bridge VLAN current-tagged/current-untagged, PVID/admission, gateway IPs,
|
|
63689
|
+
DHCP and IPv6 ND/RA, rules and counters, routing tables and VPN return routes.
|
|
63690
|
+
Then test from real representative wired AND wireless clients in each segment:
|
|
63691
|
+
address/lease, DNS, gateway, required internet/VPN services, allowed local services,
|
|
63692
|
+
denied cross-zone services, denied router management and guest peer isolation if
|
|
63693
|
+
requested. Test IPv4 and IPv6 independently, with fresh connections; existing
|
|
63694
|
+
tracked/FastTracked flows can conceal new policy. Never flush all connections as
|
|
63695
|
+
an unapproved test. Router-originated ping does not prove client FORWARD policy.
|
|
63696
|
+
|
|
63697
|
+
Record expected vs observed per test, sample time, source, address family and
|
|
63698
|
+
remaining unknowns. If no endpoint is available, mark client isolation unverified.
|
|
63699
|
+
For performance claims, compare the same path/client/workload before and after:
|
|
63700
|
+
link speed, CPU/offload, throughput, latency and loss. Ask before disruptive loads.
|
|
63701
|
+
Commit only an authorized, verified change; uncertain connectivity requires stop,
|
|
63702
|
+
read-back and the agreed rollback/recovery path, not speculative cleanup.
|
|
63703
|
+
|
|
63704
|
+
Only after successful validation, review stale objects and all references before
|
|
63705
|
+
proposing removals. Disabled is not proof unused. Preserve unrelated tunnels,
|
|
63706
|
+
WAN failover, management allowlists and domain-routing exceptions.
|
|
63707
|
+
Memory: store exact VLAN maps, addresses and evidence on each Device with source,
|
|
63708
|
+
verification time and expiry. Use a dedicated Group policy with explicit members
|
|
63709
|
+
for site-wide rules; Shared is only for intentionally reusable safeguards. Do not
|
|
63710
|
+
promote a device entity or store secrets/raw exports. Memory never grants new
|
|
63711
|
+
permission; generic guidance does not prove live facts.`
|
|
63712
|
+
};
|
|
63713
|
+
var sources2 = `## Authoritative references
|
|
63714
|
+
- Bridge VLAN table: https://help.mikrotik.com/docs/spaces/ROS/pages/28606465/Bridge+VLAN+Table
|
|
63715
|
+
- Wi-Fi packages and CAPsMAN: https://help.mikrotik.com/docs/spaces/ROS/pages/224559120/WiFi
|
|
63716
|
+
- IPv4/IPv6 firewall: https://help.mikrotik.com/docs/spaces/ROS/pages/328513/Building+Advanced+Firewall
|
|
63717
|
+
- Packet flow and FastTrack: https://help.mikrotik.com/docs/spaces/ROS/pages/328227/Packet+Flow+in+RouterOS
|
|
63718
|
+
Verify version-specific behavior against the current official manual before applying.
|
|
63719
|
+
Adapted from the homelab-vlan-segmentation skill with RouterOS-specific safety gates.`;
|
|
63720
|
+
function getVlanSegmentationGuide(topic = "all") {
|
|
63721
|
+
const selected = topic === "all" ? VLAN_GUIDE_TOPICS : [topic];
|
|
63722
|
+
return [
|
|
63723
|
+
`# RouterOS VLAN segmentation knowledge
|
|
63724
|
+
Guide version: ${VLAN_GUIDE_VERSION}
|
|
63725
|
+
Reference only; no device inspection or changes.`,
|
|
63726
|
+
...selected.map((key) => sections2[key]),
|
|
63727
|
+
sources2
|
|
63728
|
+
].join(`
|
|
63729
|
+
|
|
63730
|
+
`);
|
|
63731
|
+
}
|
|
63732
|
+
var VLAN_INSTRUCTIONS = `VLAN segmentation knowledge:
|
|
63733
|
+
Before VLAN/guest/IoT/management-network work, read ${VLAN_GUIDE_URI}.
|
|
63734
|
+
Begin with read-only discovery; never infer port roles from names or example IDs.
|
|
63735
|
+
Protect the management path, stage VLAN membership/PVID/CPU access before enabling
|
|
63736
|
+
filtering, and check BOTH IPv4 and IPv6 INPUT/FORWARD policy and remote return routes.
|
|
63737
|
+
design_network_segment is partial IPv4 scaffolding, NOT a complete isolation plan.
|
|
63738
|
+
Use only available tools; an audit or this guide never authorizes router changes.
|
|
63739
|
+
Verified device facts belong to Device memory; reusable safeguards may be Shared
|
|
63740
|
+
only with explicit intent. Do not treat shared memory as a live VLAN map.`;
|
|
63741
|
+
function vlanPromptGuidance(name, body) {
|
|
63742
|
+
if (!["setup-vlan-network", "setup-guest-wifi", "audit-vlan-segmentation"].includes(name)) {
|
|
63743
|
+
return body;
|
|
63744
|
+
}
|
|
63745
|
+
return `${body}
|
|
63746
|
+
|
|
63747
|
+
${getVlanSegmentationGuide()}`;
|
|
63748
|
+
}
|
|
63749
|
+
|
|
61927
63750
|
// src/tools/vlan-designer.ts
|
|
63751
|
+
var COVERAGE = "PARTIAL IPv4 scaffold only: no bridge port PVID/admission, VLAN filtering activation, SSID mapping, " + "router INPUT policy, IPv6 policy, remote return routes or automatic rollback. " + "Review existing rules, DNS, overlaps, interface roles and management recovery before apply. " + "Command completion does NOT prove isolation or internet access; verify from real clients. " + "Read get_vlan_segmentation_guide for the full workflow.";
|
|
63752
|
+
var portList = (text) => [
|
|
63753
|
+
...new Set((text ?? "").split(",").map((p) => p.trim()).filter(Boolean))
|
|
63754
|
+
];
|
|
61928
63755
|
function defaultRange2(subnet) {
|
|
61929
63756
|
const o = subnet.split("/")[0].split(".");
|
|
61930
63757
|
return `${o[0]}.${o[1]}.${o[2]}.10-${o[0]}.${o[1]}.${o[2]}.254`;
|
|
61931
63758
|
}
|
|
61932
63759
|
var vlanDesignerTools = [
|
|
63760
|
+
defineTool({
|
|
63761
|
+
name: "get_vlan_segmentation_guide",
|
|
63762
|
+
title: "Read VLAN Segmentation Knowledge",
|
|
63763
|
+
annotations: READ,
|
|
63764
|
+
noDevice: true,
|
|
63765
|
+
description: "Read the RouterOS homelab VLAN design guide before VLAN, guest Wi-Fi, IoT or management-network work. " + "Covers bridge CPU/tagged/untagged/PVID, dual-stack IPv4/IPv6 isolation, SSIDs/CAPsMAN, VPN return routing, " + "Safe Mode/rollback, validation and clean Device/Group/Shared memory. Reference only; no router contact, " + "live audit, memory write or authorization. Select a topic for concise guidance, or all for the full checklist.",
|
|
63766
|
+
inputSchema: {
|
|
63767
|
+
topic: _enum(["all", ...VLAN_GUIDE_TOPICS]).default("all")
|
|
63768
|
+
},
|
|
63769
|
+
handler: (a) => getVlanSegmentationGuide(a.topic)
|
|
63770
|
+
}),
|
|
61933
63771
|
defineTool({
|
|
61934
63772
|
name: "design_network_segment",
|
|
61935
|
-
title: "
|
|
63773
|
+
title: "Preview or Build Partial IPv4 VLAN Scaffolding",
|
|
61936
63774
|
annotations: DANGEROUS,
|
|
61937
|
-
description: "
|
|
63775
|
+
description: "Preview partial IPv4 VLAN interface/gateway/DHCP scaffolding (apply=false, no router I/O). " + "Read get_vlan_segmentation_guide first. Does NOT produce a complete isolated network. " + "Optional NAT requires explicit wan_interface; isolation drops require a reviewed isolation_before .id. " + "Bridge membership includes the CPU when ports are supplied, but port PVID/admission, filtering, Wi-Fi, " + "INPUT and IPv6 policies remain separate work. apply=true runs sequential non-idempotent writes only " + "after explicit approval, backup and a protected management/Safe Mode plan; failures may leave partial state. " + "Read back and test clients; never retry blindly or claim isolation from command success.",
|
|
61938
63776
|
inputSchema: {
|
|
61939
63777
|
vlan_id: number2().int().min(1).max(4094),
|
|
61940
63778
|
name: interfaceName("Name for the VLAN interface, e.g. 'guest'"),
|
|
61941
|
-
subnet:
|
|
61942
|
-
gateway:
|
|
63779
|
+
subnet: cidrv42().describe("Canonical IPv4 network CIDR, e.g. '192.168.30.0/24'"),
|
|
63780
|
+
gateway: ipv42().describe("Usable router address inside the subnet, excluded from the DHCP pool"),
|
|
61943
63781
|
bridge: string2().default("bridge").describe("Bridge to put the VLAN on"),
|
|
61944
|
-
tagged_ports: string2().optional().describe("Comma-separated
|
|
63782
|
+
tagged_ports: string2().optional().describe("Comma-separated verified tagged ports; the bridge/CPU is included once automatically"),
|
|
61945
63783
|
untagged_ports: string2().optional().describe("Comma-separated access/untagged ports"),
|
|
61946
63784
|
dhcp: boolean2().default(true).describe("Create a DHCP server + pool for the segment"),
|
|
61947
|
-
dhcp_range: string2().optional().describe("
|
|
61948
|
-
internet: boolean2().default(true).describe("
|
|
61949
|
-
|
|
63785
|
+
dhcp_range: string2().optional().describe("Single start-end IPv4 range excluding gateway/network/broadcast. Required outside /24; /24 defaults to .10\u2013.254"),
|
|
63786
|
+
internet: boolean2().default(true).describe("Add egress-scoped IPv4 masquerade (requires wan_interface); not a firewall allow. Set false to reuse existing NAT"),
|
|
63787
|
+
wan_interface: string2().trim().min(1).refine((value) => !value.startsWith("!"), "Choose one positive egress interface, not a negated matcher").optional().describe("Verified egress interface for new masquerade. Required when internet=true; never inferred"),
|
|
63788
|
+
isolate_from: array(cidrv42()).optional().describe("Subnets this segment must NOT reach, e.g. ['192.168.1.0/24']"),
|
|
63789
|
+
isolation_before: string2().regex(/^\*[0-9a-f]+$/i).optional().describe("Current enabled forward rule .id from a fresh read; insert drops before this reviewed rule, not after broad accepts. Required with isolate_from"),
|
|
61950
63790
|
apply: boolean2().default(false).describe("false = preview (default); true = build")
|
|
61951
63791
|
},
|
|
61952
63792
|
async handler(a, ctx) {
|
|
61953
|
-
const
|
|
63793
|
+
const subnet = parseCidr(a.subnet);
|
|
63794
|
+
const gateway = parseIp(a.gateway);
|
|
63795
|
+
if (!subnet || subnet.text !== a.subnet || subnet.prefix > 30 || gateway === null) {
|
|
63796
|
+
return "Error: use a canonical IPv4 network CIDR (/0\u2013/30) and valid gateway.";
|
|
63797
|
+
}
|
|
63798
|
+
const broadcast = subnet.network + 2 ** (32 - subnet.prefix) - 1;
|
|
63799
|
+
if (gateway <= subnet.network || gateway >= broadcast) {
|
|
63800
|
+
return "Error: gateway must be a usable host inside the segment subnet.";
|
|
63801
|
+
}
|
|
63802
|
+
if (a.internet && !a.wan_interface) {
|
|
63803
|
+
return "Error: internet=true requires wan_interface; unscoped masquerade is not safe. Set internet=false to reuse existing NAT.";
|
|
63804
|
+
}
|
|
63805
|
+
const isolate = [...new Set(a.isolate_from ?? [])];
|
|
63806
|
+
if (isolate.length && !a.isolation_before) {
|
|
63807
|
+
return "Error: isolate_from requires a reviewed isolation_before rule .id; blindly appending drops may not isolate anything.";
|
|
63808
|
+
}
|
|
63809
|
+
const tagged = portList(a.tagged_ports);
|
|
63810
|
+
const untagged = portList(a.untagged_ports);
|
|
63811
|
+
if (untagged.includes(a.bridge) || untagged.some((p) => tagged.includes(p))) {
|
|
63812
|
+
return "Error: this routed VLAN requires a tagged bridge/CPU and disjoint tagged/untagged ports.";
|
|
63813
|
+
}
|
|
63814
|
+
let range;
|
|
63815
|
+
if (a.dhcp) {
|
|
63816
|
+
if (!a.dhcp_range && subnet.prefix !== 24) {
|
|
63817
|
+
return "Error: non-/24 DHCP requires an explicit dhcp_range inside the subnet.";
|
|
63818
|
+
}
|
|
63819
|
+
const dhcpRange = a.dhcp_range ?? defaultRange2(a.subnet);
|
|
63820
|
+
range = dhcpRange;
|
|
63821
|
+
const parts = dhcpRange.split("-");
|
|
63822
|
+
const lo = parseIp(parts[0] ?? "");
|
|
63823
|
+
const hi = parseIp(parts[1] ?? "");
|
|
63824
|
+
if (parts.length !== 2 || lo === null || hi === null || lo > hi || lo <= subnet.network || hi >= broadcast || gateway >= lo && gateway <= hi) {
|
|
63825
|
+
return "Error: dhcp_range must be a single ordered start-end range inside the subnet, excluding network, broadcast and gateway.";
|
|
63826
|
+
}
|
|
63827
|
+
}
|
|
63828
|
+
const prefix = subnet.prefix;
|
|
61954
63829
|
const vlanIf = a.name;
|
|
61955
63830
|
const groups = [];
|
|
61956
63831
|
groups.push({
|
|
@@ -61960,11 +63835,11 @@ var vlanDesignerTools = [
|
|
|
61960
63835
|
new Cmd("/ip address add").set("address", `${a.gateway}/${prefix}`).set("interface", vlanIf).build()
|
|
61961
63836
|
]
|
|
61962
63837
|
});
|
|
61963
|
-
if (
|
|
63838
|
+
if (tagged.length || untagged.length) {
|
|
61964
63839
|
groups.push({
|
|
61965
63840
|
label: "Bridge VLAN tagging",
|
|
61966
63841
|
commands: [
|
|
61967
|
-
new Cmd("/interface bridge vlan add").set("bridge", a.bridge).set("vlan-ids", a.vlan_id).
|
|
63842
|
+
new Cmd("/interface bridge vlan add").set("bridge", a.bridge).set("vlan-ids", a.vlan_id).set("tagged", [...new Set([a.bridge, ...tagged])].join(",")).opt("untagged", untagged.length ? untagged.join(",") : undefined).build()
|
|
61968
63843
|
]
|
|
61969
63844
|
});
|
|
61970
63845
|
}
|
|
@@ -61973,7 +63848,7 @@ var vlanDesignerTools = [
|
|
|
61973
63848
|
groups.push({
|
|
61974
63849
|
label: "DHCP server",
|
|
61975
63850
|
commands: [
|
|
61976
|
-
new Cmd("/ip pool add").set("name", pool).set("ranges",
|
|
63851
|
+
new Cmd("/ip pool add").set("name", pool).set("ranges", range).build(),
|
|
61977
63852
|
new Cmd("/ip dhcp-server add").set("name", `${a.name}-dhcp`).set("interface", vlanIf).set("address-pool", pool).set("disabled", "no").build(),
|
|
61978
63853
|
new Cmd("/ip dhcp-server network add").set("address", a.subnet).set("gateway", a.gateway).set("dns-server", a.gateway).build()
|
|
61979
63854
|
]
|
|
@@ -61983,15 +63858,14 @@ var vlanDesignerTools = [
|
|
|
61983
63858
|
groups.push({
|
|
61984
63859
|
label: "Internet (srcnat masquerade)",
|
|
61985
63860
|
commands: [
|
|
61986
|
-
new Cmd("/ip firewall nat add").set("chain", "srcnat").set("src-address", a.subnet).set("action", "masquerade").set("comment", `vlan-${a.vlan_id} internet`).build()
|
|
63861
|
+
new Cmd("/ip firewall nat add").set("chain", "srcnat").set("src-address", a.subnet).set("out-interface", a.wan_interface).set("action", "masquerade").set("comment", `vlan-${a.vlan_id} internet`).build()
|
|
61987
63862
|
]
|
|
61988
63863
|
});
|
|
61989
63864
|
}
|
|
61990
|
-
const isolate = a.isolate_from ?? [];
|
|
61991
63865
|
if (isolate.length) {
|
|
61992
63866
|
groups.push({
|
|
61993
63867
|
label: "Inter-VLAN isolation",
|
|
61994
|
-
commands: isolate.map((dst) => new Cmd("/ip firewall filter add").set("chain", "forward").set("src-address", a.subnet).set("dst-address", dst).set("action", "drop").set("comment", `vlan-${a.vlan_id} isolate from ${dst}`).build())
|
|
63868
|
+
commands: isolate.map((dst) => new Cmd("/ip firewall filter add").set("chain", "forward").set("src-address", a.subnet).set("dst-address", dst).set("action", "drop").set("place-before", a.isolation_before).set("comment", `vlan-${a.vlan_id} isolate from ${dst}`).build())
|
|
61995
63869
|
});
|
|
61996
63870
|
}
|
|
61997
63871
|
const all = groups.flatMap((g) => g.commands);
|
|
@@ -62001,20 +63875,37 @@ ${g.commands.map((c) => ` ${c}`).join(`
|
|
|
62001
63875
|
`)}`).join(`
|
|
62002
63876
|
|
|
62003
63877
|
`);
|
|
62004
|
-
return `DRY RUN \u2014 VLAN ${a.vlan_id} '${a.name}' (${a.subnet}); ${all.length} command(s)
|
|
63878
|
+
return `DRY RUN \u2014 VLAN ${a.vlan_id} '${a.name}' (${a.subnet}); ${all.length} command(s):
|
|
62005
63879
|
|
|
62006
|
-
${
|
|
63880
|
+
${COVERAGE}
|
|
63881
|
+
|
|
63882
|
+
${preview}
|
|
63883
|
+
|
|
63884
|
+
Apply only within the complete approved migration plan.`;
|
|
63885
|
+
}
|
|
63886
|
+
if (isolate.length) {
|
|
63887
|
+
const anchor = await executeMikrotikCommand(new Cmd("/ip firewall filter print count-only where").set(".id", a.isolation_before).set("chain", "forward").set("disabled", "no").build(), ctx);
|
|
63888
|
+
if (anchor.trim() !== "1")
|
|
63889
|
+
return "Error: isolation_before is not a unique enabled forward rule. No changes applied; read rules again.";
|
|
62007
63890
|
}
|
|
62008
63891
|
const done = [];
|
|
62009
63892
|
for (const cmd of all) {
|
|
62010
|
-
|
|
63893
|
+
let result;
|
|
63894
|
+
try {
|
|
63895
|
+
result = await executeMikrotikCommand(cmd, ctx);
|
|
63896
|
+
} catch (error) {
|
|
63897
|
+
return `Error: VLAN apply stopped after ${done.length}/${all.length} acknowledged commands: ${String(error)}. The last command may already have applied. Read back partial state; do not retry blindly.
|
|
63898
|
+
${COVERAGE}`;
|
|
63899
|
+
}
|
|
62011
63900
|
if (looksLikeError(result)) {
|
|
62012
63901
|
return `Built ${done.length}/${all.length} commands, then FAILED: ${result}
|
|
62013
|
-
Review partial segment (the VLAN may exist without DHCP/firewall)
|
|
63902
|
+
Review partial segment (the VLAN may exist without DHCP/firewall). Do not retry blindly.
|
|
63903
|
+
${COVERAGE}`;
|
|
62014
63904
|
}
|
|
62015
63905
|
done.push(cmd);
|
|
62016
63906
|
}
|
|
62017
|
-
return `
|
|
63907
|
+
return `IPv4 scaffold '${a.name}' (id ${a.vlan_id}, ${a.subnet}): ${done.length} command(s) completed. Isolation and connectivity are UNVERIFIED.
|
|
63908
|
+
${COVERAGE}`;
|
|
62018
63909
|
}
|
|
62019
63910
|
})
|
|
62020
63911
|
];
|
|
@@ -62027,7 +63918,7 @@ var vlanTools = [
|
|
|
62027
63918
|
name: "create_vlan_interface",
|
|
62028
63919
|
title: "Create VLAN Interface",
|
|
62029
63920
|
annotations: WRITE,
|
|
62030
|
-
description: "Creates an 802.1Q VLAN sub-interface (`/interface vlan`) on a specified parent physical or bridge interface." + "
|
|
63921
|
+
description: "Creates an 802.1Q VLAN sub-interface (`/interface vlan`) on a specified parent physical or bridge interface." + " This creates only a VLAN sub-interface, NOT bridge port membership, PVID, firewall isolation or SSID mapping. For a bridge member use the bridge as routed parent; read get_vlan_segmentation_guide before migration. Set `use_service_tag=true` for 802.1ad QinQ double-tagging." + " For listing existing VLAN interfaces use `list_vlan_interfaces`; for editing an existing VLAN use `update_vlan_interface`." + " Returns the created interface's full detail including its name, which is the identifier accepted by `get_vlan_interface`, `update_vlan_interface`, and `remove_vlan_interface`." + " ARP mode accepts: enabled (default), disabled, proxy-arp, reply-only.",
|
|
62031
63922
|
inputSchema: {
|
|
62032
63923
|
name: interfaceName("Name for the new VLAN interface, e.g. 'vlan100'"),
|
|
62033
63924
|
vlan_id: number2().int().min(1).max(4094).describe("802.1Q VLAN ID (1-4094)"),
|
|
@@ -64594,6 +66485,27 @@ var moduleCatalog2 = [
|
|
|
64594
66485
|
description: "Administrator-approved DNS/TCP/TLS/HTTPS service checks, immutable contracts, history and fail-closed rollout gates with explicit MCP-host perspective.",
|
|
64595
66486
|
tools: serviceContractTools
|
|
64596
66487
|
},
|
|
66488
|
+
{
|
|
66489
|
+
label: "Service Routing",
|
|
66490
|
+
slug: "service-routing",
|
|
66491
|
+
group: "System & Ops",
|
|
66492
|
+
description: "Scoped dual-stack domain policies, router VRF service probes and explicitly authorized failover.",
|
|
66493
|
+
tools: serviceRoutingTools
|
|
66494
|
+
},
|
|
66495
|
+
{
|
|
66496
|
+
label: "Network Flight Recorder",
|
|
66497
|
+
slug: "flight-recorder",
|
|
66498
|
+
group: "System & Ops",
|
|
66499
|
+
description: "Durable bounded pre/post-incident telemetry, off-router log metadata and MCP change correlation.",
|
|
66500
|
+
tools: flightRecorderTools
|
|
66501
|
+
},
|
|
66502
|
+
{
|
|
66503
|
+
label: "Recovery Lab",
|
|
66504
|
+
slug: "recovery-lab",
|
|
66505
|
+
group: "System & Ops",
|
|
66506
|
+
description: "Isolated CHR rehearsal orchestration with immutable snapshot subsets, coverage and verified runner evidence.",
|
|
66507
|
+
tools: recoveryLabTools
|
|
66508
|
+
},
|
|
64597
66509
|
{
|
|
64598
66510
|
label: "Client Investigations",
|
|
64599
66511
|
slug: "investigations",
|
|
@@ -64668,7 +66580,7 @@ var moduleCatalog2 = [
|
|
|
64668
66580
|
label: "VLAN Designer",
|
|
64669
66581
|
slug: "vlan-designer",
|
|
64670
66582
|
group: "Interfaces",
|
|
64671
|
-
description: "
|
|
66583
|
+
description: "Read VLAN design/safety knowledge and preview partial IPv4 scaffolding; full L2, dual-stack " + "isolation and client verification remain explicit migration work.",
|
|
64672
66584
|
tools: vlanDesignerTools
|
|
64673
66585
|
},
|
|
64674
66586
|
{
|
|
@@ -65529,7 +67441,7 @@ var moduleCatalog2 = [
|
|
|
65529
67441
|
label: "Containers",
|
|
65530
67442
|
slug: "container",
|
|
65531
67443
|
group: "System & Ops",
|
|
65532
|
-
description: "
|
|
67444
|
+
description: "Shared container safety knowledge and exact-target OCI lifecycle (`/container`), global config " + "(registry/tmpdir/RAM), named env lists, and volume mounts.",
|
|
65533
67445
|
tools: containerTools
|
|
65534
67446
|
},
|
|
65535
67447
|
{
|
|
@@ -65616,9 +67528,9 @@ import { existsSync as existsSync6 } from "fs";
|
|
|
65616
67528
|
|
|
65617
67529
|
// src/observability/dashboard.ts
|
|
65618
67530
|
import { spawn } from "child_process";
|
|
65619
|
-
import { readFileSync as
|
|
67531
|
+
import { readFileSync as readFileSync14 } from "fs";
|
|
65620
67532
|
import { homedir as homedir6, networkInterfaces as networkInterfaces2 } from "os";
|
|
65621
|
-
import { dirname as
|
|
67533
|
+
import { dirname as dirname23, join as join16 } from "path";
|
|
65622
67534
|
var {serve } = globalThis.Bun;
|
|
65623
67535
|
|
|
65624
67536
|
// src/observability/modules.ts
|
|
@@ -65695,20 +67607,20 @@ function applyModuleToggle(filter, slug, enabled) {
|
|
|
65695
67607
|
}
|
|
65696
67608
|
|
|
65697
67609
|
// src/observability/ssh-key-inventory.ts
|
|
65698
|
-
import { createHash as
|
|
65699
|
-
import { constants } from "fs";
|
|
65700
|
-
import { access, lstat, open as open2, readdir } from "fs/promises";
|
|
67610
|
+
import { createHash as createHash11 } from "crypto";
|
|
67611
|
+
import { constants as constants2 } from "fs";
|
|
67612
|
+
import { access as access4, lstat, open as open2, readdir } from "fs/promises";
|
|
65701
67613
|
import { homedir as homedir3 } from "os";
|
|
65702
|
-
import { basename as basename2, join as
|
|
67614
|
+
import { basename as basename2, join as join10, resolve as resolve4 } from "path";
|
|
65703
67615
|
import { utils } from "ssh2";
|
|
65704
|
-
async function listSshKeys(configuredPaths, directory =
|
|
67616
|
+
async function listSshKeys(configuredPaths, directory = join10(homedir3(), ".ssh")) {
|
|
65705
67617
|
const paths = new Set(configuredPaths.filter(Boolean).map((path) => resolve4(path)));
|
|
65706
67618
|
let warning;
|
|
65707
67619
|
try {
|
|
65708
67620
|
const entries = await readdir(directory, { withFileTypes: true });
|
|
65709
67621
|
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
65710
67622
|
if (entry.isFile() && entry.name.endsWith(".pub"))
|
|
65711
|
-
paths.add(
|
|
67623
|
+
paths.add(join10(directory, entry.name.slice(0, -4)));
|
|
65712
67624
|
}
|
|
65713
67625
|
} catch (error) {
|
|
65714
67626
|
if (error.code !== "ENOENT")
|
|
@@ -65723,7 +67635,7 @@ async function listSshKeys(configuredPaths, directory = join9(homedir3(), ".ssh"
|
|
|
65723
67635
|
const pubPath = `${path}.pub`;
|
|
65724
67636
|
if (!(await lstat(pubPath)).isFile())
|
|
65725
67637
|
continue;
|
|
65726
|
-
file = await open2(pubPath,
|
|
67638
|
+
file = await open2(pubPath, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
|
|
65727
67639
|
const stat = await file.stat();
|
|
65728
67640
|
if (!stat.isFile() || stat.size > 16384)
|
|
65729
67641
|
continue;
|
|
@@ -65741,7 +67653,7 @@ async function listSshKeys(configuredPaths, directory = join9(homedir3(), ".ssh"
|
|
|
65741
67653
|
try {
|
|
65742
67654
|
const privateStat = await lstat(path);
|
|
65743
67655
|
if (privateStat.isFile() && privateStat.size > 0) {
|
|
65744
|
-
await
|
|
67656
|
+
await access4(path, constants2.R_OK);
|
|
65745
67657
|
usable = true;
|
|
65746
67658
|
}
|
|
65747
67659
|
} catch {}
|
|
@@ -65749,7 +67661,7 @@ async function listSshKeys(configuredPaths, directory = join9(homedir3(), ".ssh"
|
|
|
65749
67661
|
path,
|
|
65750
67662
|
name: basename2(path),
|
|
65751
67663
|
type: key.type,
|
|
65752
|
-
fingerprint: `SHA256:${
|
|
67664
|
+
fingerprint: `SHA256:${createHash11("sha256").update(key.getPublicSSH()).digest("base64").replace(/=+$/, "")}`,
|
|
65753
67665
|
publicKey: line,
|
|
65754
67666
|
usable
|
|
65755
67667
|
});
|
|
@@ -65906,15 +67818,15 @@ async function workspaceRoutes(req, url) {
|
|
|
65906
67818
|
}
|
|
65907
67819
|
|
|
65908
67820
|
// src/client-check/routes.ts
|
|
65909
|
-
import { readFileSync as
|
|
65910
|
-
import { join as
|
|
67821
|
+
import { readFileSync as readFileSync11 } from "fs";
|
|
67822
|
+
import { join as join11 } from "path";
|
|
65911
67823
|
import { randomBytes as randomBytes3 } from "crypto";
|
|
65912
67824
|
var MiB = 1048576;
|
|
65913
67825
|
var budgets = new Map;
|
|
65914
67826
|
async function clientCheckRoutes(req, url, peer = "unknown") {
|
|
65915
67827
|
if (url.pathname === "/client-check" && req.method === "GET") {
|
|
65916
67828
|
try {
|
|
65917
|
-
return new Response(
|
|
67829
|
+
return new Response(readFileSync11(join11(PROJECT_ROOT, "dist/ui/client-check.html"), "utf8"), {
|
|
65918
67830
|
headers: {
|
|
65919
67831
|
"content-type": "text/html;charset=utf-8",
|
|
65920
67832
|
"cache-control": "no-store",
|
|
@@ -66058,13 +67970,13 @@ async function clientCheckRoutes(req, url, peer = "unknown") {
|
|
|
66058
67970
|
|
|
66059
67971
|
// src/client-check/network.ts
|
|
66060
67972
|
import { networkInterfaces } from "os";
|
|
66061
|
-
import { isIP as
|
|
67973
|
+
import { isIP as isIP5 } from "net";
|
|
66062
67974
|
function clientCheckNetwork(host, port, interfaces = networkInterfaces()) {
|
|
66063
67975
|
const wildcard = host === "0.0.0.0" || host === "::";
|
|
66064
67976
|
const candidates = Object.entries(interfaces).flatMap(([name, addresses]) => (addresses ?? []).filter((a) => !a.internal && a.family === "IPv4" && (wildcard || a.address === host)).map((a) => ({ name, address: a.address, origin: `http://${a.address}:${port}` }))).sort((a, b) => Number(/^(utun|tun|wg|tailscale)/.test(a.name)) - Number(/^(utun|tun|wg|tailscale)/.test(b.name)));
|
|
66065
67977
|
if (!wildcard && !candidates.length) {
|
|
66066
67978
|
try {
|
|
66067
|
-
const origin = clientCheckOrigin(`http://${
|
|
67979
|
+
const origin = clientCheckOrigin(`http://${isIP5(host) === 6 ? `[${host}]` : host}:${port}`);
|
|
66068
67980
|
candidates.push({ name: "Bound address", address: host, origin });
|
|
66069
67981
|
} catch {}
|
|
66070
67982
|
}
|
|
@@ -66105,6 +68017,46 @@ async function serviceContractRoutes(req, url) {
|
|
|
66105
68017
|
}
|
|
66106
68018
|
}
|
|
66107
68019
|
|
|
68020
|
+
// src/observability/operations-routes.ts
|
|
68021
|
+
var routing = {
|
|
68022
|
+
"GET /api/recovery-lab": "get_recovery_lab",
|
|
68023
|
+
"GET /api/recovery-lab/inventory": "recovery_lab_inventory",
|
|
68024
|
+
"POST /api/recovery-lab/prepare": "prepare_recovery_lab",
|
|
68025
|
+
"POST /api/recovery-lab/start": "start_recovery_lab",
|
|
68026
|
+
"POST /api/recovery-lab/poll": "poll_recovery_lab",
|
|
68027
|
+
"POST /api/recovery-lab/destroy": "destroy_recovery_lab",
|
|
68028
|
+
"GET /api/flight-recorder": "get_flight_recorder",
|
|
68029
|
+
"POST /api/flight-recorder/configure": "configure_flight_recorder",
|
|
68030
|
+
"POST /api/flight-recorder/freeze": "freeze_network_incident",
|
|
68031
|
+
"POST /api/flight-recorder/export": "export_network_incident",
|
|
68032
|
+
"GET /api/service-routing": "list_service_routing",
|
|
68033
|
+
"GET /api/service-routing/inventory": "service_routing_inventory",
|
|
68034
|
+
"POST /api/service-routing": "create_service_routing",
|
|
68035
|
+
"POST /api/service-routing/probe": "probe_service_routing",
|
|
68036
|
+
"POST /api/service-routing/preview": "preview_service_routing",
|
|
68037
|
+
"POST /api/service-routing/apply": "apply_service_routing",
|
|
68038
|
+
"POST /api/service-routing/arm": "arm_service_routing"
|
|
68039
|
+
};
|
|
68040
|
+
async function operationsRoutes(req, url) {
|
|
68041
|
+
if (!["/api/service-routing", "/api/flight-recorder", "/api/recovery-lab"].some((p) => url.pathname.startsWith(p)))
|
|
68042
|
+
return null;
|
|
68043
|
+
const tool = [...serviceRoutingTools, ...flightRecorderTools, ...recoveryLabTools].find((t) => t.name === routing[`${req.method} ${url.pathname}`]);
|
|
68044
|
+
if (!tool)
|
|
68045
|
+
return Response.json({ error: "Unsupported workspace operation" }, { status: 405 });
|
|
68046
|
+
try {
|
|
68047
|
+
const input = req.method === "POST" ? JSON.parse(await readOperationBody(req)) : {};
|
|
68048
|
+
const device = url.searchParams.get("device");
|
|
68049
|
+
if (!device)
|
|
68050
|
+
throw new DashboardInputError(400, "Select an explicit router first.");
|
|
68051
|
+
const result = await tool.handler(object(tool.inputSchema).parse(input), createContext(undefined, device));
|
|
68052
|
+
return new Response(result, {
|
|
68053
|
+
headers: { "content-type": "application/json", "cache-control": "no-store" }
|
|
68054
|
+
});
|
|
68055
|
+
} catch (error) {
|
|
68056
|
+
return Response.json({ error: error instanceof Error ? error.message : "Workspace operation failed" }, { status: error instanceof DashboardInputError ? error.status : 400 });
|
|
68057
|
+
}
|
|
68058
|
+
}
|
|
68059
|
+
|
|
66108
68060
|
// src/observability/round-trip-routes.ts
|
|
66109
68061
|
async function roundTripRoutes(req, url) {
|
|
66110
68062
|
if (url.pathname === "/api/round-trip/options") {
|
|
@@ -66171,9 +68123,9 @@ async function roundTripRoutes(req, url) {
|
|
|
66171
68123
|
}
|
|
66172
68124
|
|
|
66173
68125
|
// src/observability/um-report-cache.ts
|
|
66174
|
-
import { createHash as
|
|
68126
|
+
import { createHash as createHash12, randomUUID as randomUUID11 } from "crypto";
|
|
66175
68127
|
import { mkdir, readFile, rename, stat, unlink, writeFile } from "fs/promises";
|
|
66176
|
-
import { dirname as
|
|
68128
|
+
import { dirname as dirname18, join as join12 } from "path";
|
|
66177
68129
|
var MAX_BYTES = 32 * 1024 * 1024;
|
|
66178
68130
|
var MAX_AGE = 24 * 60 * 60000;
|
|
66179
68131
|
var sourceSchema = object({
|
|
@@ -66201,8 +68153,8 @@ function umReportCachePath(device) {
|
|
|
66201
68153
|
chain.push([name, target]);
|
|
66202
68154
|
name = target?.jumpVia;
|
|
66203
68155
|
}
|
|
66204
|
-
const key =
|
|
66205
|
-
return
|
|
68156
|
+
const key = createHash12("sha256").update(JSON.stringify(chain)).digest("hex");
|
|
68157
|
+
return join12(`${config.dashboard.dbPath}.um-reports`, `${key}.json`);
|
|
66206
68158
|
}
|
|
66207
68159
|
async function loadUmReportCache(path, device, fields) {
|
|
66208
68160
|
if (!path)
|
|
@@ -66233,12 +68185,12 @@ async function loadUmReportCache(path, device, fields) {
|
|
|
66233
68185
|
async function saveUmReportCache(path, snapshot) {
|
|
66234
68186
|
if (!path || Object.values(snapshot.sources).some((source) => source.error))
|
|
66235
68187
|
return false;
|
|
66236
|
-
const temp = `${path}.${
|
|
68188
|
+
const temp = `${path}.${randomUUID11()}.tmp`;
|
|
66237
68189
|
try {
|
|
66238
68190
|
const text = JSON.stringify({ version: 1, snapshot });
|
|
66239
68191
|
if (Buffer.byteLength(text) > MAX_BYTES)
|
|
66240
68192
|
return false;
|
|
66241
|
-
await mkdir(
|
|
68193
|
+
await mkdir(dirname18(path), { recursive: true, mode: 448 });
|
|
66242
68194
|
await writeFile(temp, text, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
66243
68195
|
await rename(temp, path);
|
|
66244
68196
|
return true;
|
|
@@ -66802,14 +68754,14 @@ function buildUmReport(snapshot, query) {
|
|
|
66802
68754
|
// src/observability/config-history.ts
|
|
66803
68755
|
import {
|
|
66804
68756
|
existsSync as existsSync5,
|
|
66805
|
-
mkdirSync as
|
|
66806
|
-
readFileSync as
|
|
68757
|
+
mkdirSync as mkdirSync17,
|
|
68758
|
+
readFileSync as readFileSync12,
|
|
66807
68759
|
readdirSync as readdirSync3,
|
|
66808
68760
|
rmSync as rmSync3,
|
|
66809
68761
|
statSync as statSync3,
|
|
66810
68762
|
writeFileSync as writeFileSync5
|
|
66811
68763
|
} from "fs";
|
|
66812
|
-
import { join as
|
|
68764
|
+
import { join as join13 } from "path";
|
|
66813
68765
|
var AUTO_RETENTION = 50;
|
|
66814
68766
|
function historyDir() {
|
|
66815
68767
|
return process.env.MIKROTIK_CONFIG_HISTORY_DIR || DEFAULT_CONFIG_HISTORY_DIR2;
|
|
@@ -66828,7 +68780,7 @@ function listVersions() {
|
|
|
66828
68780
|
if (!/^v\d+\.json$/.test(f))
|
|
66829
68781
|
continue;
|
|
66830
68782
|
try {
|
|
66831
|
-
const raw =
|
|
68783
|
+
const raw = readFileSync12(join13(dir, f), "utf8");
|
|
66832
68784
|
const parsed = JSON.parse(raw);
|
|
66833
68785
|
out.push({
|
|
66834
68786
|
id: f.replace(/\.json$/, ""),
|
|
@@ -66842,11 +68794,11 @@ function listVersions() {
|
|
|
66842
68794
|
return out.sort((a, b) => b.ts - a.ts);
|
|
66843
68795
|
}
|
|
66844
68796
|
function readVersion(id) {
|
|
66845
|
-
const raw =
|
|
68797
|
+
const raw = readFileSync12(join13(historyDir(), idToFile(id)), "utf8");
|
|
66846
68798
|
return JSON.parse(raw);
|
|
66847
68799
|
}
|
|
66848
68800
|
function deleteVersion(id) {
|
|
66849
|
-
const p =
|
|
68801
|
+
const p = join13(historyDir(), idToFile(id));
|
|
66850
68802
|
if (!existsSync5(p))
|
|
66851
68803
|
return false;
|
|
66852
68804
|
rmSync3(p);
|
|
@@ -66854,12 +68806,12 @@ function deleteVersion(id) {
|
|
|
66854
68806
|
}
|
|
66855
68807
|
function recordVersion(config, kind, now, label) {
|
|
66856
68808
|
const dir = historyDir();
|
|
66857
|
-
|
|
68809
|
+
mkdirSync17(dir, { recursive: true });
|
|
66858
68810
|
let ts = now;
|
|
66859
|
-
while (existsSync5(
|
|
68811
|
+
while (existsSync5(join13(dir, `v${ts}.json`)))
|
|
66860
68812
|
ts++;
|
|
66861
68813
|
const body = { ts, kind, label, config };
|
|
66862
|
-
writeFileSync5(
|
|
68814
|
+
writeFileSync5(join13(dir, `v${ts}.json`), `${JSON.stringify(body, null, 2)}
|
|
66863
68815
|
`, "utf8");
|
|
66864
68816
|
pruneAuto(dir);
|
|
66865
68817
|
return {
|
|
@@ -66876,7 +68828,7 @@ function pruneAuto(dir) {
|
|
|
66876
68828
|
return;
|
|
66877
68829
|
for (const v of autos.slice(AUTO_RETENTION)) {
|
|
66878
68830
|
try {
|
|
66879
|
-
rmSync3(
|
|
68831
|
+
rmSync3(join13(dir, `${v.id}.json`));
|
|
66880
68832
|
} catch {}
|
|
66881
68833
|
}
|
|
66882
68834
|
}
|
|
@@ -66895,15 +68847,15 @@ function historyBytes() {
|
|
|
66895
68847
|
if (!/^v\d+\.json$/.test(f))
|
|
66896
68848
|
continue;
|
|
66897
68849
|
try {
|
|
66898
|
-
total += statSync3(
|
|
68850
|
+
total += statSync3(join13(dir, f)).size;
|
|
66899
68851
|
} catch {}
|
|
66900
68852
|
}
|
|
66901
68853
|
return total;
|
|
66902
68854
|
}
|
|
66903
68855
|
|
|
66904
68856
|
// src/prompts/index.ts
|
|
66905
|
-
import { readFileSync as
|
|
66906
|
-
import { join as
|
|
68857
|
+
import { readFileSync as readFileSync13, readdirSync as readdirSync4 } from "fs";
|
|
68858
|
+
import { join as join14 } from "path";
|
|
66907
68859
|
|
|
66908
68860
|
// src/txn/guidance.ts
|
|
66909
68861
|
var TRANSACTION_TOOL_NAMES = [
|
|
@@ -67030,7 +68982,7 @@ function parseFrontmatter(raw) {
|
|
|
67030
68982
|
title: meta.title ?? meta.name,
|
|
67031
68983
|
description: meta.description ?? "",
|
|
67032
68984
|
arguments: args,
|
|
67033
|
-
body: transactionPromptGuidance(meta.name, body.trim())
|
|
68985
|
+
body: containerPromptGuidance(meta.name, vlanPromptGuidance(meta.name, transactionPromptGuidance(meta.name, body.trim())))
|
|
67034
68986
|
};
|
|
67035
68987
|
}
|
|
67036
68988
|
function deviceArgDescription(directory) {
|
|
@@ -67053,7 +69005,7 @@ function listPrompts() {
|
|
|
67053
69005
|
const out = [];
|
|
67054
69006
|
for (const file of files) {
|
|
67055
69007
|
try {
|
|
67056
|
-
const parsed = parseFrontmatter(
|
|
69008
|
+
const parsed = parseFrontmatter(readFileSync13(join14(PROMPTS_DIR, file), "utf8"));
|
|
67057
69009
|
if (parsed) {
|
|
67058
69010
|
out.push({
|
|
67059
69011
|
name: parsed.name,
|
|
@@ -67080,7 +69032,7 @@ function registerPrompts(server, opts = {}) {
|
|
|
67080
69032
|
for (const file of files) {
|
|
67081
69033
|
let parsed;
|
|
67082
69034
|
try {
|
|
67083
|
-
parsed = parseFrontmatter(
|
|
69035
|
+
parsed = parseFrontmatter(readFileSync13(join14(PROMPTS_DIR, file), "utf8"));
|
|
67084
69036
|
} catch (e) {
|
|
67085
69037
|
logger.warn(`Skipping prompt ${file}: ${String(e)}`);
|
|
67086
69038
|
continue;
|
|
@@ -67098,17 +69050,27 @@ function registerPrompts(server, opts = {}) {
|
|
|
67098
69050
|
if (multiDevice && !hasOwnDevice) {
|
|
67099
69051
|
argsSchema.device = _enum(selectorNames).optional().describe(deviceArgDescription(opts.deviceDirectory));
|
|
67100
69052
|
}
|
|
67101
|
-
server.registerPrompt(parsed.name, { title: parsed.title, description: parsed.description, argsSchema }, (args) =>
|
|
67102
|
-
|
|
67103
|
-
|
|
67104
|
-
|
|
67105
|
-
|
|
67106
|
-
type: "text",
|
|
67107
|
-
text: substitutePrompt(parsed.body, args)
|
|
67108
|
-
}
|
|
69053
|
+
server.registerPrompt(parsed.name, { title: parsed.title, description: parsed.description, argsSchema }, (args) => {
|
|
69054
|
+
const values = { ...args };
|
|
69055
|
+
for (const arg of parsed.arguments) {
|
|
69056
|
+
if (!arg.required && (typeof values[arg.name] !== "string" || !String(values[arg.name]).trim())) {
|
|
69057
|
+
values[arg.name] = "(not specified; ask if needed)";
|
|
67109
69058
|
}
|
|
67110
|
-
|
|
67111
|
-
|
|
69059
|
+
}
|
|
69060
|
+
return {
|
|
69061
|
+
messages: [
|
|
69062
|
+
{
|
|
69063
|
+
role: "user",
|
|
69064
|
+
content: {
|
|
69065
|
+
type: "text",
|
|
69066
|
+
text: (multiDevice && !hasOwnDevice && typeof args.device === "string" ? `Target device (configured MCP key or label): ${JSON.stringify(args.device)}. Resolve this exact device; do not substitute the default.
|
|
69067
|
+
|
|
69068
|
+
` : "") + substitutePrompt(parsed.body, values)
|
|
69069
|
+
}
|
|
69070
|
+
}
|
|
69071
|
+
]
|
|
69072
|
+
};
|
|
69073
|
+
});
|
|
67112
69074
|
count++;
|
|
67113
69075
|
}
|
|
67114
69076
|
return count;
|
|
@@ -67176,7 +69138,7 @@ import { lookup } from "dns/promises";
|
|
|
67176
69138
|
var LOG_TAG2 = "mikrotik-mcp";
|
|
67177
69139
|
var cache4 = new Map;
|
|
67178
69140
|
var REFRESH_MS = 24 * 60 * 60000;
|
|
67179
|
-
var
|
|
69141
|
+
var timer6 = null;
|
|
67180
69142
|
var inFlight2 = false;
|
|
67181
69143
|
function getDeviceGeo(name) {
|
|
67182
69144
|
return cache4.get(name)?.geo ?? null;
|
|
@@ -67257,24 +69219,24 @@ async function refreshGeo() {
|
|
|
67257
69219
|
}
|
|
67258
69220
|
function startGeoLookups() {
|
|
67259
69221
|
refreshGeo();
|
|
67260
|
-
|
|
69222
|
+
timer6 = setInterval(() => void refreshGeo(), REFRESH_MS);
|
|
67261
69223
|
}
|
|
67262
69224
|
function stopGeoLookups() {
|
|
67263
|
-
if (
|
|
67264
|
-
clearInterval(
|
|
67265
|
-
|
|
69225
|
+
if (timer6) {
|
|
69226
|
+
clearInterval(timer6);
|
|
69227
|
+
timer6 = null;
|
|
67266
69228
|
}
|
|
67267
69229
|
}
|
|
67268
69230
|
|
|
67269
69231
|
// src/observability/flags.ts
|
|
67270
|
-
import { join as
|
|
69232
|
+
import { join as join15 } from "path";
|
|
67271
69233
|
import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
|
|
67272
69234
|
import { homedir as homedir4 } from "os";
|
|
67273
69235
|
var LOG_TAG3 = "mikrotik-mcp";
|
|
67274
69236
|
var CODE_RE = /^[a-z]{2}$/;
|
|
67275
69237
|
var sourceUrl = (code) => `https://hatscripts.github.io/circle-flags/flags/${code}.svg`;
|
|
67276
|
-
var VENDOR_DIR =
|
|
67277
|
-
var CACHE_DIR =
|
|
69238
|
+
var VENDOR_DIR = join15(PROJECT_ROOT, "assets", "flags");
|
|
69239
|
+
var CACHE_DIR = join15(homedir4(), ".mikrotik-mcp", "flags");
|
|
67278
69240
|
var mem = new Map;
|
|
67279
69241
|
async function flagSvg(code) {
|
|
67280
69242
|
const c = code.toLowerCase();
|
|
@@ -67283,7 +69245,7 @@ async function flagSvg(code) {
|
|
|
67283
69245
|
const cached = mem.get(c);
|
|
67284
69246
|
if (cached !== undefined)
|
|
67285
69247
|
return cached;
|
|
67286
|
-
for (const file of [
|
|
69248
|
+
for (const file of [join15(VENDOR_DIR, `${c}.svg`), join15(CACHE_DIR, `${c}.svg`)]) {
|
|
67287
69249
|
try {
|
|
67288
69250
|
const svg = await readFile2(file, "utf8");
|
|
67289
69251
|
mem.set(c, svg);
|
|
@@ -67299,7 +69261,7 @@ async function flagSvg(code) {
|
|
|
67299
69261
|
}
|
|
67300
69262
|
const svg = await res.text();
|
|
67301
69263
|
mem.set(c, svg);
|
|
67302
|
-
mkdir2(CACHE_DIR, { recursive: true }).then(() => writeFile2(
|
|
69264
|
+
mkdir2(CACHE_DIR, { recursive: true }).then(() => writeFile2(join15(CACHE_DIR, `${c}.svg`), svg)).catch(() => {});
|
|
67303
69265
|
return svg;
|
|
67304
69266
|
} catch (e) {
|
|
67305
69267
|
logger.warn(`[${LOG_TAG3}] flag fetch failed for '${c}': ${e instanceof Error ? e.message : String(e)}`);
|
|
@@ -67557,8 +69519,8 @@ data: ${JSON.stringify(sample)}
|
|
|
67557
69519
|
}
|
|
67558
69520
|
|
|
67559
69521
|
// src/observability/store.ts
|
|
67560
|
-
import { mkdirSync as
|
|
67561
|
-
import { dirname as
|
|
69522
|
+
import { mkdirSync as mkdirSync18 } from "fs";
|
|
69523
|
+
import { dirname as dirname19 } from "path";
|
|
67562
69524
|
function rowToEvent2(r) {
|
|
67563
69525
|
return {
|
|
67564
69526
|
id: r.id,
|
|
@@ -67736,7 +69698,7 @@ class SqliteEventStore {
|
|
|
67736
69698
|
async function openSqliteStore(path) {
|
|
67737
69699
|
if (path !== ":memory:") {
|
|
67738
69700
|
try {
|
|
67739
|
-
|
|
69701
|
+
mkdirSync18(dirname19(path), { recursive: true });
|
|
67740
69702
|
} catch {}
|
|
67741
69703
|
}
|
|
67742
69704
|
const { Database } = await import("bun:sqlite");
|
|
@@ -67745,8 +69707,8 @@ async function openSqliteStore(path) {
|
|
|
67745
69707
|
}
|
|
67746
69708
|
|
|
67747
69709
|
// src/observability/capsman-store.ts
|
|
67748
|
-
import { mkdirSync as
|
|
67749
|
-
import { dirname as
|
|
69710
|
+
import { mkdirSync as mkdirSync19 } from "fs";
|
|
69711
|
+
import { dirname as dirname20 } from "path";
|
|
67750
69712
|
function summariseRadioSamples(rows) {
|
|
67751
69713
|
const byRadio = new Map;
|
|
67752
69714
|
for (const r of rows) {
|
|
@@ -67836,7 +69798,7 @@ class SqliteCapsmanStore {
|
|
|
67836
69798
|
async function openCapsmanStore(path) {
|
|
67837
69799
|
if (path !== ":memory:") {
|
|
67838
69800
|
try {
|
|
67839
|
-
|
|
69801
|
+
mkdirSync19(dirname20(path), { recursive: true });
|
|
67840
69802
|
} catch {}
|
|
67841
69803
|
}
|
|
67842
69804
|
const { Database } = await import("bun:sqlite");
|
|
@@ -67850,7 +69812,7 @@ var CAPSMAN_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
|
67850
69812
|
var DEFAULT_CAPSMAN_INTERVAL_MS = 5 * 60000;
|
|
67851
69813
|
var MIN_CAPSMAN_INTERVAL_MS = 60000;
|
|
67852
69814
|
var MAX_CAPSMAN_INTERVAL_MS = 6 * 60 * 60000;
|
|
67853
|
-
var
|
|
69815
|
+
var timer7 = null;
|
|
67854
69816
|
var inFlight3 = false;
|
|
67855
69817
|
var noCapsman = new Set;
|
|
67856
69818
|
function clampInterval(ms) {
|
|
@@ -67905,18 +69867,18 @@ async function sampleCapsmanOnce(store) {
|
|
|
67905
69867
|
function startCapsmanSampler(store, intervalMs = DEFAULT_CAPSMAN_INTERVAL_MS) {
|
|
67906
69868
|
const ms = clampInterval(intervalMs);
|
|
67907
69869
|
sampleCapsmanOnce(store);
|
|
67908
|
-
|
|
69870
|
+
timer7 = setInterval(() => void sampleCapsmanOnce(store), ms);
|
|
67909
69871
|
}
|
|
67910
69872
|
function stopCapsmanSampler() {
|
|
67911
|
-
if (
|
|
67912
|
-
clearInterval(
|
|
67913
|
-
|
|
69873
|
+
if (timer7) {
|
|
69874
|
+
clearInterval(timer7);
|
|
69875
|
+
timer7 = null;
|
|
67914
69876
|
}
|
|
67915
69877
|
}
|
|
67916
69878
|
|
|
67917
69879
|
// src/observability/usage-store.ts
|
|
67918
|
-
import { mkdirSync as
|
|
67919
|
-
import { dirname as
|
|
69880
|
+
import { mkdirSync as mkdirSync20 } from "fs";
|
|
69881
|
+
import { dirname as dirname21 } from "path";
|
|
67920
69882
|
function dayOf(ts) {
|
|
67921
69883
|
return new Date(ts).toISOString().slice(0, 10);
|
|
67922
69884
|
}
|
|
@@ -68053,7 +70015,7 @@ class SqliteUsageStore {
|
|
|
68053
70015
|
async function openUsageStore(path) {
|
|
68054
70016
|
if (path !== ":memory:") {
|
|
68055
70017
|
try {
|
|
68056
|
-
|
|
70018
|
+
mkdirSync20(dirname21(path), { recursive: true });
|
|
68057
70019
|
} catch {}
|
|
68058
70020
|
}
|
|
68059
70021
|
const { Database } = await import("bun:sqlite");
|
|
@@ -68073,7 +70035,7 @@ var USAGE_RETENTION_MS = 93 * 24 * 60 * 60 * 1000;
|
|
|
68073
70035
|
var DEFAULT_USAGE_INTERVAL_MS = 60000;
|
|
68074
70036
|
var MIN_USAGE_INTERVAL_MS = 30000;
|
|
68075
70037
|
var MAX_USAGE_INTERVAL_MS = 6 * 60 * 60000;
|
|
68076
|
-
var
|
|
70038
|
+
var timer8 = null;
|
|
68077
70039
|
var inFlight4 = false;
|
|
68078
70040
|
var currentStore = null;
|
|
68079
70041
|
var currentIntervalMs = DEFAULT_USAGE_INTERVAL_MS;
|
|
@@ -68176,25 +70138,25 @@ function startUsageSampler(store, intervalMs = DEFAULT_USAGE_INTERVAL_MS) {
|
|
|
68176
70138
|
currentStore = store;
|
|
68177
70139
|
currentIntervalMs = clampInterval2(intervalMs);
|
|
68178
70140
|
sampleUsageOnce(store);
|
|
68179
|
-
|
|
70141
|
+
timer8 = setInterval(() => void sampleUsageOnce(store), currentIntervalMs);
|
|
68180
70142
|
}
|
|
68181
70143
|
function getUsageSamplerInterval() {
|
|
68182
70144
|
return currentIntervalMs;
|
|
68183
70145
|
}
|
|
68184
70146
|
function setUsageSamplerInterval(intervalMs) {
|
|
68185
70147
|
currentIntervalMs = clampInterval2(intervalMs);
|
|
68186
|
-
if (
|
|
68187
|
-
clearInterval(
|
|
70148
|
+
if (timer8)
|
|
70149
|
+
clearInterval(timer8);
|
|
68188
70150
|
if (currentStore) {
|
|
68189
70151
|
const store = currentStore;
|
|
68190
|
-
|
|
70152
|
+
timer8 = setInterval(() => void sampleUsageOnce(store), currentIntervalMs);
|
|
68191
70153
|
}
|
|
68192
70154
|
return currentIntervalMs;
|
|
68193
70155
|
}
|
|
68194
70156
|
function stopUsageSampler() {
|
|
68195
|
-
if (
|
|
68196
|
-
clearInterval(
|
|
68197
|
-
|
|
70157
|
+
if (timer8) {
|
|
70158
|
+
clearInterval(timer8);
|
|
70159
|
+
timer8 = null;
|
|
68198
70160
|
}
|
|
68199
70161
|
currentStore = null;
|
|
68200
70162
|
}
|
|
@@ -68487,7 +70449,7 @@ async function postureRoutes(req, url) {
|
|
|
68487
70449
|
}
|
|
68488
70450
|
|
|
68489
70451
|
// src/observability/access-settings.ts
|
|
68490
|
-
import { createHash as
|
|
70452
|
+
import { createHash as createHash13 } from "crypto";
|
|
68491
70453
|
var list2 = array(string2().trim().min(1).max(200)).max(200);
|
|
68492
70454
|
var accessSchema = AccessConfigSchema2.extend({
|
|
68493
70455
|
devices: list2,
|
|
@@ -68517,7 +70479,7 @@ function createAccessSettingsRoutes(admin, deps = {
|
|
|
68517
70479
|
}) {
|
|
68518
70480
|
let pending = null;
|
|
68519
70481
|
const tools = moduleCatalog2.flatMap((m) => m.tools.map((t) => ({ name: t.name, risk: riskOf(t.annotations), noDevice: !!t.noDevice })));
|
|
68520
|
-
const revision = () =>
|
|
70482
|
+
const revision = () => createHash13("sha256").update(JSON.stringify([deps.getConfig(), deps.getAccessPolicy()])).digest("hex");
|
|
68521
70483
|
const payload = () => {
|
|
68522
70484
|
const cfg = deps.getConfig();
|
|
68523
70485
|
const id = admin.pendingId();
|
|
@@ -68900,8 +70862,8 @@ async function rolloutRoutes(req, url) {
|
|
|
68900
70862
|
}
|
|
68901
70863
|
|
|
68902
70864
|
// src/policy/results.ts
|
|
68903
|
-
import { mkdirSync as
|
|
68904
|
-
import { dirname as
|
|
70865
|
+
import { mkdirSync as mkdirSync21 } from "fs";
|
|
70866
|
+
import { dirname as dirname22 } from "path";
|
|
68905
70867
|
var SCHEMA_STATEMENTS9 = [
|
|
68906
70868
|
`CREATE TABLE IF NOT EXISTS policy_results (
|
|
68907
70869
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -68961,7 +70923,7 @@ class SqlitePolicyResultStore {
|
|
|
68961
70923
|
async function openPolicyResultStore(path) {
|
|
68962
70924
|
if (path !== ":memory:") {
|
|
68963
70925
|
try {
|
|
68964
|
-
|
|
70926
|
+
mkdirSync21(dirname22(path), { recursive: true });
|
|
68965
70927
|
} catch {}
|
|
68966
70928
|
}
|
|
68967
70929
|
const { Database } = await import("bun:sqlite");
|
|
@@ -69823,9 +71785,9 @@ async function alertRoutes(req, url, db) {
|
|
|
69823
71785
|
}
|
|
69824
71786
|
|
|
69825
71787
|
// src/observability/memory-routes.ts
|
|
69826
|
-
var
|
|
71788
|
+
var name3 = string2().trim().min(1).max(200);
|
|
69827
71789
|
var content = string2().trim().min(1).max(8000);
|
|
69828
|
-
var relation = object({ from:
|
|
71790
|
+
var relation = object({ from: name3, to: name3, relationType: name3 }).strict();
|
|
69829
71791
|
var list3 = (schema) => array(schema).min(1).max(100);
|
|
69830
71792
|
var count2 = (value, fallback, max) => exports_coerce.number().int().min(0).max(max).parse(value ?? fallback);
|
|
69831
71793
|
var configuring = false;
|
|
@@ -69891,7 +71853,7 @@ async function memoryRoutes(req, url) {
|
|
|
69891
71853
|
return json14({ error: "Knowledge memory is disabled. Enable it in Memory settings." }, 503);
|
|
69892
71854
|
const store = await getMemoryStore();
|
|
69893
71855
|
if (p === "/api/memory/scope" && req.method === "GET")
|
|
69894
|
-
return json14(store.scope(
|
|
71856
|
+
return json14(store.scope(name3.parse(url.searchParams.get("entityName"))));
|
|
69895
71857
|
if (p === "/api/memory/scope" && req.method === "POST")
|
|
69896
71858
|
return json14(store.setScope(ScopeSchema.parse(await body(req))));
|
|
69897
71859
|
if (p === "/api/memory/summary" && req.method === "GET")
|
|
@@ -69926,14 +71888,14 @@ async function memoryRoutes(req, url) {
|
|
|
69926
71888
|
return json14(store.activity(count2(url.searchParams.get("limit"), 50, 100), url.searchParams.has("since") ? count2(url.searchParams.get("since"), 0, Number.MAX_SAFE_INTEGER) : undefined, url.searchParams.get("changesOnly") === "true"));
|
|
69927
71889
|
const entity = p.match(/^\/api\/memory\/entity\/(.+)$/);
|
|
69928
71890
|
if (entity && req.method === "GET") {
|
|
69929
|
-
const graph = store.openNodes([
|
|
71891
|
+
const graph = store.openNodes([name3.parse(decodeURIComponent(entity[1]))]);
|
|
69930
71892
|
return graph.entities.length ? json14({ entity: graph.entities[0], relations: graph.relations }) : json14({ error: "Entity not found" }, 404);
|
|
69931
71893
|
}
|
|
69932
71894
|
if (p === "/api/memory/entities" && req.method === "POST") {
|
|
69933
71895
|
const data = object({
|
|
69934
71896
|
entities: list3(object({
|
|
69935
|
-
name:
|
|
69936
|
-
entityType:
|
|
71897
|
+
name: name3,
|
|
71898
|
+
entityType: name3,
|
|
69937
71899
|
observations: array(content).max(100).optional()
|
|
69938
71900
|
}).strict())
|
|
69939
71901
|
}).strict().parse(await body(req));
|
|
@@ -69949,17 +71911,17 @@ async function memoryRoutes(req, url) {
|
|
|
69949
71911
|
}
|
|
69950
71912
|
if (p === "/api/memory/observations" && req.method === "POST") {
|
|
69951
71913
|
const data = object({
|
|
69952
|
-
observations: list3(object({ entityName:
|
|
71914
|
+
observations: list3(object({ entityName: name3, contents: list3(content) }).strict())
|
|
69953
71915
|
}).strict().parse(await body(req));
|
|
69954
71916
|
return json14({ results: store.addObservations(data.observations) });
|
|
69955
71917
|
}
|
|
69956
71918
|
if (p === "/api/memory/entities" && req.method === "DELETE") {
|
|
69957
|
-
const data = object({ names: list3(
|
|
71919
|
+
const data = object({ names: list3(name3) }).strict().parse(await body(req));
|
|
69958
71920
|
return json14({ removed: store.deleteEntities(data.names) });
|
|
69959
71921
|
}
|
|
69960
71922
|
if (p === "/api/memory/observations" && req.method === "DELETE") {
|
|
69961
71923
|
const data = object({
|
|
69962
|
-
deletions: list3(object({ entityName:
|
|
71924
|
+
deletions: list3(object({ entityName: name3, observations: list3(content) }).strict())
|
|
69963
71925
|
}).strict().parse(await body(req));
|
|
69964
71926
|
return json14({ removed: store.deleteObservations(data.deletions) });
|
|
69965
71927
|
}
|
|
@@ -70032,7 +71994,7 @@ spawn error: ${String(e)}` });
|
|
|
70032
71994
|
}
|
|
70033
71995
|
function dashboardHtml() {
|
|
70034
71996
|
try {
|
|
70035
|
-
return
|
|
71997
|
+
return readFileSync14(join16(UI_DIST_DIR, "observability.html"), "utf8");
|
|
70036
71998
|
} catch {
|
|
70037
71999
|
return `<!doctype html><meta charset=utf-8><body style="font:14px system-ui;padding:24px;background:#0b0d10;color:#e8eaed">
|
|
70038
72000
|
<h2>MikroTik MCP \u2014 Observability Dashboard</h2>
|
|
@@ -70966,7 +72928,7 @@ async function featureRoutes(req, url) {
|
|
|
70966
72928
|
const raw = b?.dir?.trim();
|
|
70967
72929
|
if (!raw)
|
|
70968
72930
|
return json15({ error: "dir required" }, 400);
|
|
70969
|
-
const dir = raw === "~" || raw.startsWith("~/") ?
|
|
72931
|
+
const dir = raw === "~" || raw.startsWith("~/") ? join16(homedir6(), raw.slice(1)) : raw;
|
|
70970
72932
|
const next = { ...getConfig(), backupDir: dir };
|
|
70971
72933
|
setConfig(next);
|
|
70972
72934
|
try {
|
|
@@ -71075,13 +73037,13 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
71075
73037
|
startHealthChecks(30000);
|
|
71076
73038
|
startGeoLookups();
|
|
71077
73039
|
try {
|
|
71078
|
-
usageStore = await openUsageStore(
|
|
73040
|
+
usageStore = await openUsageStore(join16(dirname23(cfg.dbPath), "usage.db"));
|
|
71079
73041
|
startUsageSampler(usageStore);
|
|
71080
73042
|
} catch (e) {
|
|
71081
73043
|
logger.warn(`[${SERVER_TAG3}] usage history disabled: ${String(e)}`);
|
|
71082
73044
|
}
|
|
71083
73045
|
try {
|
|
71084
|
-
capsmanStore = await openCapsmanStore(
|
|
73046
|
+
capsmanStore = await openCapsmanStore(join16(dirname23(cfg.dbPath), "capsman.db"));
|
|
71085
73047
|
startCapsmanSampler(capsmanStore);
|
|
71086
73048
|
} catch (e) {
|
|
71087
73049
|
logger.warn(`[${SERVER_TAG3}] capsman trends disabled: ${String(e)}`);
|
|
@@ -71149,6 +73111,9 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
71149
73111
|
const serviceContractResp = await serviceContractRoutes(req, url);
|
|
71150
73112
|
if (serviceContractResp)
|
|
71151
73113
|
return serviceContractResp;
|
|
73114
|
+
const operationsResp = await operationsRoutes(req, url);
|
|
73115
|
+
if (operationsResp)
|
|
73116
|
+
return operationsResp;
|
|
71152
73117
|
const roundTripResp = await roundTripRoutes(req, url);
|
|
71153
73118
|
if (roundTripResp)
|
|
71154
73119
|
return roundTripResp;
|
|
@@ -71504,7 +73469,7 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
71504
73469
|
}
|
|
71505
73470
|
|
|
71506
73471
|
// src/transport/http.ts
|
|
71507
|
-
import { randomUUID as
|
|
73472
|
+
import { randomUUID as randomUUID12 } from "crypto";
|
|
71508
73473
|
var {serve: serve2 } = globalThis.Bun;
|
|
71509
73474
|
|
|
71510
73475
|
// node_modules/content-type/index.js
|
|
@@ -78577,6 +80542,9 @@ class Protocol {
|
|
|
78577
80542
|
this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
|
|
78578
80543
|
const handleTaskResult = async () => {
|
|
78579
80544
|
const taskId = request.params.taskId;
|
|
80545
|
+
if (!await this._taskStore.getTask(taskId, extra.sessionId)) {
|
|
80546
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
|
|
80547
|
+
}
|
|
78580
80548
|
if (this._taskMessageQueue) {
|
|
78581
80549
|
let queuedMessage;
|
|
78582
80550
|
while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
|
|
@@ -78607,12 +80575,12 @@ class Protocol {
|
|
|
78607
80575
|
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
|
|
78608
80576
|
}
|
|
78609
80577
|
if (!isTerminal(task.status)) {
|
|
78610
|
-
await this._waitForTaskUpdate(taskId, extra.signal);
|
|
80578
|
+
await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
|
|
78611
80579
|
return await handleTaskResult();
|
|
78612
80580
|
}
|
|
78613
80581
|
if (isTerminal(task.status)) {
|
|
78614
80582
|
const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
|
|
78615
|
-
this._clearTaskQueue(taskId);
|
|
80583
|
+
this._clearTaskQueue(taskId, extra.sessionId);
|
|
78616
80584
|
return {
|
|
78617
80585
|
...result,
|
|
78618
80586
|
_meta: {
|
|
@@ -78649,7 +80617,7 @@ class Protocol {
|
|
|
78649
80617
|
throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
|
|
78650
80618
|
}
|
|
78651
80619
|
await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
|
|
78652
|
-
this._clearTaskQueue(request.params.taskId);
|
|
80620
|
+
this._clearTaskQueue(request.params.taskId, extra.sessionId);
|
|
78653
80621
|
const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
|
|
78654
80622
|
if (!cancelledTask) {
|
|
78655
80623
|
throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
|
|
@@ -78772,6 +80740,19 @@ class Protocol {
|
|
|
78772
80740
|
const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
|
|
78773
80741
|
const capturedTransport = this._transport;
|
|
78774
80742
|
const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
|
|
80743
|
+
const sessionId = capturedTransport?.sessionId;
|
|
80744
|
+
const store = this._taskStore;
|
|
80745
|
+
let relatedTaskFound = true;
|
|
80746
|
+
let relatedTaskLookup;
|
|
80747
|
+
if (relatedTaskId && store && this._taskMessageQueue && sessionId !== undefined) {
|
|
80748
|
+
relatedTaskFound = false;
|
|
80749
|
+
relatedTaskLookup = (async () => {
|
|
80750
|
+
if (!await store.getTask(relatedTaskId, sessionId)) {
|
|
80751
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`);
|
|
80752
|
+
}
|
|
80753
|
+
relatedTaskFound = true;
|
|
80754
|
+
})();
|
|
80755
|
+
}
|
|
78775
80756
|
if (handler === undefined) {
|
|
78776
80757
|
const errorResponse = {
|
|
78777
80758
|
jsonrpc: "2.0",
|
|
@@ -78781,7 +80762,10 @@ class Protocol {
|
|
|
78781
80762
|
message: "Method not found"
|
|
78782
80763
|
}
|
|
78783
80764
|
};
|
|
78784
|
-
if (relatedTaskId &&
|
|
80765
|
+
if (relatedTaskId && relatedTaskLookup) {
|
|
80766
|
+
const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() };
|
|
80767
|
+
relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
|
|
80768
|
+
} else if (relatedTaskId && this._taskMessageQueue) {
|
|
78785
80769
|
this._enqueueTaskMessage(relatedTaskId, {
|
|
78786
80770
|
type: "error",
|
|
78787
80771
|
message: errorResponse,
|
|
@@ -78832,7 +80816,10 @@ class Protocol {
|
|
|
78832
80816
|
closeSSEStream: extra?.closeSSEStream,
|
|
78833
80817
|
closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
|
|
78834
80818
|
};
|
|
78835
|
-
Promise.resolve().then(() => {
|
|
80819
|
+
(relatedTaskLookup ?? Promise.resolve()).then(() => {
|
|
80820
|
+
if (relatedTaskLookup && abortController.signal.aborted) {
|
|
80821
|
+
throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
|
|
80822
|
+
}
|
|
78836
80823
|
if (taskCreationParams) {
|
|
78837
80824
|
this.assertTaskHandlerCapability(request.method);
|
|
78838
80825
|
}
|
|
@@ -78867,7 +80854,7 @@ class Protocol {
|
|
|
78867
80854
|
...error["data"] !== undefined && { data: error["data"] }
|
|
78868
80855
|
}
|
|
78869
80856
|
};
|
|
78870
|
-
if (relatedTaskId && this._taskMessageQueue) {
|
|
80857
|
+
if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
|
|
78871
80858
|
await this._enqueueTaskMessage(relatedTaskId, {
|
|
78872
80859
|
type: "error",
|
|
78873
80860
|
message: errorResponse,
|
|
@@ -79255,7 +81242,7 @@ class Protocol {
|
|
|
79255
81242
|
throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
|
|
79256
81243
|
}
|
|
79257
81244
|
const maxQueueSize = this._options?.maxTaskQueueSize;
|
|
79258
|
-
await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
|
|
81245
|
+
await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
|
|
79259
81246
|
}
|
|
79260
81247
|
async _clearTaskQueue(taskId, sessionId) {
|
|
79261
81248
|
if (this._taskMessageQueue) {
|
|
@@ -79274,10 +81261,10 @@ class Protocol {
|
|
|
79274
81261
|
}
|
|
79275
81262
|
}
|
|
79276
81263
|
}
|
|
79277
|
-
async _waitForTaskUpdate(taskId, signal) {
|
|
81264
|
+
async _waitForTaskUpdate(taskId, signal, sessionId) {
|
|
79278
81265
|
let interval = this._options?.defaultTaskPollInterval ?? 1000;
|
|
79279
81266
|
try {
|
|
79280
|
-
const task = await this._taskStore?.getTask(taskId);
|
|
81267
|
+
const task = await this._taskStore?.getTask(taskId, sessionId);
|
|
79281
81268
|
if (task?.pollInterval) {
|
|
79282
81269
|
interval = task.pollInterval;
|
|
79283
81270
|
}
|
|
@@ -79945,6 +81932,43 @@ class ExperimentalMcpServerTasks {
|
|
|
79945
81932
|
}
|
|
79946
81933
|
|
|
79947
81934
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
|
|
81935
|
+
function toolInputElementCount(value, max) {
|
|
81936
|
+
let count = 0;
|
|
81937
|
+
const stack = [value];
|
|
81938
|
+
while (stack.length > 0) {
|
|
81939
|
+
const node = stack.pop();
|
|
81940
|
+
if (node === null || typeof node !== "object")
|
|
81941
|
+
continue;
|
|
81942
|
+
if (Array.isArray(node)) {
|
|
81943
|
+
for (const child of node) {
|
|
81944
|
+
if (++count > max)
|
|
81945
|
+
return count;
|
|
81946
|
+
if (child !== null && typeof child === "object")
|
|
81947
|
+
stack.push(child);
|
|
81948
|
+
}
|
|
81949
|
+
} else {
|
|
81950
|
+
for (const key in node) {
|
|
81951
|
+
if (!Object.prototype.hasOwnProperty.call(node, key))
|
|
81952
|
+
continue;
|
|
81953
|
+
if (++count > max)
|
|
81954
|
+
return count;
|
|
81955
|
+
const child = node[key];
|
|
81956
|
+
if (child !== null && typeof child === "object")
|
|
81957
|
+
stack.push(child);
|
|
81958
|
+
}
|
|
81959
|
+
}
|
|
81960
|
+
}
|
|
81961
|
+
return count;
|
|
81962
|
+
}
|
|
81963
|
+
function resolveMaxToolInputElements(value) {
|
|
81964
|
+
if (value === undefined || value === Infinity)
|
|
81965
|
+
return;
|
|
81966
|
+
if (typeof value !== "number" || Number.isNaN(value) || value < 1) {
|
|
81967
|
+
throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`);
|
|
81968
|
+
}
|
|
81969
|
+
return value;
|
|
81970
|
+
}
|
|
81971
|
+
|
|
79948
81972
|
class McpServer {
|
|
79949
81973
|
constructor(serverInfo, options) {
|
|
79950
81974
|
this._registeredResources = {};
|
|
@@ -79956,6 +81980,7 @@ class McpServer {
|
|
|
79956
81980
|
this._resourceHandlersInitialized = false;
|
|
79957
81981
|
this._promptHandlersInitialized = false;
|
|
79958
81982
|
this.server = new Server(serverInfo, options);
|
|
81983
|
+
this._maxToolInputElements = resolveMaxToolInputElements(options?.maxToolInputElements);
|
|
79959
81984
|
}
|
|
79960
81985
|
get experimental() {
|
|
79961
81986
|
if (!this._experimental) {
|
|
@@ -80062,12 +82087,15 @@ class McpServer {
|
|
|
80062
82087
|
};
|
|
80063
82088
|
}
|
|
80064
82089
|
async validateToolInput(tool, args, toolName) {
|
|
82090
|
+
if (this._maxToolInputElements !== undefined && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) {
|
|
82091
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);
|
|
82092
|
+
}
|
|
80065
82093
|
if (!tool.inputSchema) {
|
|
80066
82094
|
return;
|
|
80067
82095
|
}
|
|
80068
82096
|
const inputObj = normalizeObjectSchema(tool.inputSchema);
|
|
80069
82097
|
const schemaToParse = inputObj ?? tool.inputSchema;
|
|
80070
|
-
const parseResult = await safeParseAsync3(schemaToParse, args);
|
|
82098
|
+
const parseResult = await safeParseAsync3(schemaToParse, args ?? {});
|
|
80071
82099
|
if (!parseResult.success) {
|
|
80072
82100
|
const error = "error" in parseResult ? parseResult.error : "Unknown error";
|
|
80073
82101
|
const errorMessage = getParseErrorMessage(error);
|
|
@@ -80292,7 +82320,7 @@ class McpServer {
|
|
|
80292
82320
|
}
|
|
80293
82321
|
if (prompt.argsSchema) {
|
|
80294
82322
|
const argsObj = normalizeObjectSchema(prompt.argsSchema);
|
|
80295
|
-
const parseResult = await safeParseAsync3(argsObj, request.params.arguments);
|
|
82323
|
+
const parseResult = await safeParseAsync3(argsObj, request.params.arguments ?? {});
|
|
80296
82324
|
if (!parseResult.success) {
|
|
80297
82325
|
const error = "error" in parseResult ? parseResult.error : "Unknown error";
|
|
80298
82326
|
const errorMessage = getParseErrorMessage(error);
|
|
@@ -80670,6 +82698,28 @@ var EMPTY_COMPLETION_RESULT = {
|
|
|
80670
82698
|
}
|
|
80671
82699
|
};
|
|
80672
82700
|
|
|
82701
|
+
// src/core/vlan-resource.ts
|
|
82702
|
+
function registerVlanKnowledgeResource(server) {
|
|
82703
|
+
server.registerResource("vlan-segmentation-guide", VLAN_GUIDE_URI, {
|
|
82704
|
+
title: "RouterOS VLAN segmentation guide",
|
|
82705
|
+
description: "Read-only VLAN design, dual-stack isolation, management safety and validation guidance. No live device data.",
|
|
82706
|
+
mimeType: "text/markdown"
|
|
82707
|
+
}, (uri) => ({
|
|
82708
|
+
contents: [{ uri: uri.href, mimeType: "text/markdown", text: getVlanSegmentationGuide() }]
|
|
82709
|
+
}));
|
|
82710
|
+
}
|
|
82711
|
+
|
|
82712
|
+
// src/core/container-resource.ts
|
|
82713
|
+
function registerContainerKnowledgeResource(server) {
|
|
82714
|
+
server.registerResource("routeros-container-guide", CONTAINER_GUIDE_URI, {
|
|
82715
|
+
title: "RouterOS container operations guide",
|
|
82716
|
+
description: "Version-aware container discovery, deployment, isolation and lifecycle safety. Reference only, no live device data.",
|
|
82717
|
+
mimeType: "text/markdown"
|
|
82718
|
+
}, (uri) => ({
|
|
82719
|
+
contents: [{ uri: uri.href, mimeType: "text/markdown", text: getRouterosContainerGuide() }]
|
|
82720
|
+
}));
|
|
82721
|
+
}
|
|
82722
|
+
|
|
80673
82723
|
// src/server.ts
|
|
80674
82724
|
var INSTRUCTIONS = `MikroTik RouterOS management over SSH.
|
|
80675
82725
|
|
|
@@ -80694,10 +82744,12 @@ Tool discovery \u2014 MANDATORY workflow:
|
|
|
80694
82744
|
Safety model \u2014 tools are annotated by risk:
|
|
80695
82745
|
\u2022 readOnlyHint \u2192 inspection only, no changes
|
|
80696
82746
|
\u2022 destructiveHint \u2192 removes or replaces configuration
|
|
80697
|
-
Before a single-device batch of risky changes,
|
|
80698
|
-
|
|
80699
|
-
|
|
80700
|
-
|
|
82747
|
+
Before a single-device batch of risky changes, assess enable_safe_mode and an
|
|
82748
|
+
independent management recovery path. RouterOS can roll back eligible uncommitted
|
|
82749
|
+
changes after session loss, but Safe Mode has limits and is NOT a backup or a
|
|
82750
|
+
universal rollback guarantee. Use only your own session; inspect uncertain writes
|
|
82751
|
+
instead of replaying them. Commit only an approved, verified plan; otherwise use
|
|
82752
|
+
the agreed rollback/recovery path. Prefer filtered list_* reads to keep output small.
|
|
80701
82753
|
|
|
80702
82754
|
Change workflow \u2014 ALWAYS take a restore point before a plan. Before calling
|
|
80703
82755
|
plan_changes or apply_plan (or any batch of write/destructive tools), first call
|
|
@@ -80791,6 +82843,20 @@ function createServer(opts = {}) {
|
|
|
80791
82843
|
const toolModules = selectToolModules2(getConfig().tools);
|
|
80792
82844
|
const availableTools = new Set(toolModules.flatMap((mod) => mod.map((tool) => tool.name)));
|
|
80793
82845
|
let instructions = names.length > 1 ? INSTRUCTIONS + MULTI_DEVICE_INSTRUCTIONS.replace("{{names}}", names.join(", ")).replace("{{default}}", defaultDevice) : INSTRUCTIONS;
|
|
82846
|
+
instructions += `
|
|
82847
|
+
|
|
82848
|
+
${VLAN_INSTRUCTIONS}`;
|
|
82849
|
+
instructions += `
|
|
82850
|
+
|
|
82851
|
+
${CONTAINER_INSTRUCTIONS}`;
|
|
82852
|
+
if (availableTools.has("get_routeros_container_guide")) {
|
|
82853
|
+
instructions += `
|
|
82854
|
+
Container tool-only clients: discover get_routeros_container_guide with find_tools; this reference does not contact a router.`;
|
|
82855
|
+
}
|
|
82856
|
+
if (availableTools.has("get_vlan_segmentation_guide")) {
|
|
82857
|
+
instructions += `
|
|
82858
|
+
Tool-only clients: discover get_vlan_segmentation_guide with find_tools; topic=all returns the full guide without router I/O.`;
|
|
82859
|
+
}
|
|
80794
82860
|
const sshParticipants = names.filter((name) => !getConfig().devices[name]?.mac);
|
|
80795
82861
|
if (!readOnly && sshParticipants.length > 1 && TRANSACTION_TOOL_NAMES.every((name) => availableTools.has(name))) {
|
|
80796
82862
|
instructions += `
|
|
@@ -80862,6 +82928,8 @@ ${note}`;
|
|
|
80862
82928
|
deviceDirectory: deviceDirectory()
|
|
80863
82929
|
});
|
|
80864
82930
|
const uiViewCount = registerUiResources(server);
|
|
82931
|
+
registerVlanKnowledgeResource(server);
|
|
82932
|
+
registerContainerKnowledgeResource(server);
|
|
80865
82933
|
installToolPagination(server, getConfig().mcp.toolPageSize);
|
|
80866
82934
|
return { server, toolCount, promptCount, uiViewCount, readOnly };
|
|
80867
82935
|
}
|
|
@@ -80926,7 +82994,7 @@ async function runHttp(mcp) {
|
|
|
80926
82994
|
if (existing)
|
|
80927
82995
|
return existing;
|
|
80928
82996
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
80929
|
-
sessionIdGenerator: () =>
|
|
82997
|
+
sessionIdGenerator: () => randomUUID12(),
|
|
80930
82998
|
enableJsonResponse: true,
|
|
80931
82999
|
...security,
|
|
80932
83000
|
onsessioninitialized: (id) => {
|
|
@@ -81174,7 +83242,7 @@ async function printBanner() {
|
|
|
81174
83242
|
|
|
81175
83243
|
// src/alerts/sampler.ts
|
|
81176
83244
|
var DEFAULT_ALERT_SAMPLE_MS = 30000;
|
|
81177
|
-
var
|
|
83245
|
+
var timer9 = null;
|
|
81178
83246
|
var snapshotStorePromise2 = null;
|
|
81179
83247
|
function getSnapshotStore() {
|
|
81180
83248
|
snapshotStorePromise2 ??= openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
@@ -81252,18 +83320,18 @@ async function sampleAlertsOnce(now = Date.now()) {
|
|
|
81252
83320
|
}
|
|
81253
83321
|
function startAlertSampler(intervalMs = DEFAULT_ALERT_SAMPLE_MS) {
|
|
81254
83322
|
stopAlertSampler();
|
|
81255
|
-
|
|
83323
|
+
timer9 = setInterval(() => {
|
|
81256
83324
|
sampleAlertsOnce().catch((e) => {
|
|
81257
83325
|
logger.debug(`[alerts] sampler tick failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
81258
83326
|
});
|
|
81259
83327
|
}, intervalMs);
|
|
81260
|
-
|
|
83328
|
+
timer9.unref?.();
|
|
81261
83329
|
logger.debug(`[alerts] metric sampler started (${intervalMs}ms)`);
|
|
81262
83330
|
}
|
|
81263
83331
|
function stopAlertSampler() {
|
|
81264
|
-
if (
|
|
81265
|
-
clearInterval(
|
|
81266
|
-
|
|
83332
|
+
if (timer9)
|
|
83333
|
+
clearInterval(timer9);
|
|
83334
|
+
timer9 = null;
|
|
81267
83335
|
}
|
|
81268
83336
|
|
|
81269
83337
|
// src/cli.ts
|
|
@@ -81414,6 +83482,8 @@ async function main() {
|
|
|
81414
83482
|
}
|
|
81415
83483
|
const cfg = loadConfig2();
|
|
81416
83484
|
setConfig(cfg);
|
|
83485
|
+
startRoutingMonitor();
|
|
83486
|
+
startFlightRecorder();
|
|
81417
83487
|
await printBanner();
|
|
81418
83488
|
warnIfPlaintextPasswordInContainer(Object.values(cfg.devices).some((d) => !!d.password));
|
|
81419
83489
|
const deviceNames = Object.keys(cfg.devices);
|
|
@@ -81452,6 +83522,8 @@ async function main() {
|
|
|
81452
83522
|
stopAlertSampler();
|
|
81453
83523
|
stopScheduler();
|
|
81454
83524
|
stopAttackDetection();
|
|
83525
|
+
stopRoutingMonitor();
|
|
83526
|
+
stopFlightRecorder();
|
|
81455
83527
|
process.exit(0);
|
|
81456
83528
|
};
|
|
81457
83529
|
process.on("SIGINT", () => shutdown("SIGINT"));
|