@usex/mikrotik-mcp 5.19.0 → 5.21.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 +180 -8
- package/dist/cli.js +3452 -729
- package/dist/index.js +148 -27
- package/dist/shared/{library-ppnv0f07.js → library-588vnctn.js} +1 -1
- package/dist/shared/{library-7wcv2ckk.js → library-6tvh3gq1.js} +2837 -545
- package/dist/shared/{library-tqrvrykj.js → library-g8far2nz.js} +1 -1
- package/dist/shared/{library-f3be6g03.js → library-k6m2bxjr.js} +1 -1
- package/dist/shared/{library-z7qsdq88.js → library-wj2xfx8h.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 +66 -62
- 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 +24 -23
- 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 +327 -16
- package/schemas/tool-catalog.json +898 -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 +91 -0
- package/schemas/tools/design_network_segment.json +22 -6
- package/schemas/tools/destroy_recovery_lab.json +18 -0
- package/schemas/tools/disconnect_ovpn_session.json +20 -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_ovpn_sessions.json +7 -0
- 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_address_page.json +19 -0
- package/schemas/tools/service_routing_inventory.json +7 -0
- package/schemas/tools/service_routing_traffic.json +14 -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-h065ap70.js} +0 -0
- /package/dist/shared/{cli-s0rxncz4.js → cli-se3tgt7t.js} +0 -0
- /package/dist/shared/{cli-y00nwzxx.js → cli-t311px0m.js} +0 -0
- /package/dist/shared/{cli-gtq5bw8q.js → cli-wf9a7qjm.js} +0 -0
|
@@ -9066,6 +9066,27 @@ async function openSnapshotStore2(path) {
|
|
|
9066
9066
|
|
|
9067
9067
|
// src/logger.ts
|
|
9068
9068
|
import { stderr } from "process";
|
|
9069
|
+
|
|
9070
|
+
// src/utils/container-redaction.ts
|
|
9071
|
+
function redactContainerText(text) {
|
|
9072
|
+
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="***"');
|
|
9073
|
+
}
|
|
9074
|
+
function containerCommandForLog(command) {
|
|
9075
|
+
if (!/\/container(?:[\s/]|$)/.test(command))
|
|
9076
|
+
return command;
|
|
9077
|
+
const prefix = command.match(/^\[[^\]\r\n]+\] Executing (?:MikroTik command|\(safe mode\)): /)?.[0] ?? "";
|
|
9078
|
+
return `${prefix}${command.match(/\/container(?:[ /](?:config|envs|mounts))?[ /](?:[a-z-]+)/)?.[0] ?? "/container"} [arguments omitted]`;
|
|
9079
|
+
}
|
|
9080
|
+
function redactContainerInput(tool, args) {
|
|
9081
|
+
if (!/(?:^|_)container(?:_|$)/.test(tool) || !args || typeof args !== "object" || Array.isArray(args))
|
|
9082
|
+
return args;
|
|
9083
|
+
return Object.fromEntries(Object.entries(args).map(([key, value]) => [
|
|
9084
|
+
key,
|
|
9085
|
+
["env", "value", "cmd", "entrypoint", "password"].includes(key) && value != null && value !== "" ? "\xABredacted\xBB" : value
|
|
9086
|
+
]));
|
|
9087
|
+
}
|
|
9088
|
+
|
|
9089
|
+
// src/logger.ts
|
|
9069
9090
|
var LEVELS = {
|
|
9070
9091
|
debug: 10,
|
|
9071
9092
|
info: 20,
|
|
@@ -9083,7 +9104,7 @@ var COLORS = {
|
|
|
9083
9104
|
var RESET = "\x1B[0m";
|
|
9084
9105
|
var useColor = stderr.isTTY ?? false;
|
|
9085
9106
|
function formatLogMessage(message) {
|
|
9086
|
-
const compact = message.replace(/\bfrom=\*[\da-f]+(?:,\*[\da-f]+)+/gi, (list) => `from=<${list.split(",").length} IDs omitted>`);
|
|
9107
|
+
const compact = containerCommandForLog(message).replace(/\bfrom=\*[\da-f]+(?:,\*[\da-f]+)+/gi, (list) => `from=<${list.split(",").length} IDs omitted>`);
|
|
9087
9108
|
const maxLength = 1024;
|
|
9088
9109
|
return compact.length <= maxLength ? compact : `${compact.slice(0, maxLength)}\u2026 [${compact.length - maxLength} chars omitted]`;
|
|
9089
9110
|
}
|
|
@@ -11303,7 +11324,7 @@ function buildPrint(path, rest) {
|
|
|
11303
11324
|
const [k, v] = pair;
|
|
11304
11325
|
if (/[~<>!]/.test(k))
|
|
11305
11326
|
return null;
|
|
11306
|
-
query[k] = v;
|
|
11327
|
+
query[k === "proplist" ? ".proplist" : k] = v;
|
|
11307
11328
|
}
|
|
11308
11329
|
return { method: "GET", path, query, countOnly };
|
|
11309
11330
|
}
|
|
@@ -12106,11 +12127,11 @@ async function executeMikrotikCommand2(command, ctx, opts) {
|
|
|
12106
12127
|
const deviceName = resolveDeviceName2(ctx.device);
|
|
12107
12128
|
const safe = getSafeModeManager2(deviceName);
|
|
12108
12129
|
if (safe.isActive) {
|
|
12109
|
-
ctx.info(`[${deviceName}] Executing (safe mode): ${command}`);
|
|
12130
|
+
ctx.info(`[${deviceName}] Executing (safe mode): ${containerCommandForLog(command)}`);
|
|
12110
12131
|
ctx.transport = "ssh";
|
|
12111
12132
|
return safe.execute(command);
|
|
12112
12133
|
}
|
|
12113
|
-
ctx.info(`[${deviceName}] Executing MikroTik command: ${command}`);
|
|
12134
|
+
ctx.info(`[${deviceName}] Executing MikroTik command: ${containerCommandForLog(command)}`);
|
|
12114
12135
|
return runOnce(command, ctx.device, opts, ctx);
|
|
12115
12136
|
}
|
|
12116
12137
|
async function uploadFileToDevice(deviceName, remotePath, data) {
|
|
@@ -12338,7 +12359,7 @@ function buildEvent(raw, id, opts) {
|
|
|
12338
12359
|
let output = "";
|
|
12339
12360
|
let truncated = false;
|
|
12340
12361
|
if (opts.captureBody) {
|
|
12341
|
-
const args = opts.redactInput === false ? raw.args : redact(raw.args);
|
|
12362
|
+
const args = opts.redactInput === false ? raw.args : redact(redactContainerInput(raw.tool, raw.args));
|
|
12342
12363
|
const rin = truncate(JSON.stringify(args ?? {}), opts.maxBodyBytes);
|
|
12343
12364
|
const rout = truncate(raw.tool === "create_client_check" ? "Client check created. Private invitation omitted from activity history." : raw.output, opts.maxBodyBytes);
|
|
12344
12365
|
input = rin.text;
|
|
@@ -14824,13 +14845,13 @@ async function undoMigration(id, confirm, selected) {
|
|
|
14824
14845
|
throw new Error("Undo lost Safe Mode or exceeded its time budget.");
|
|
14825
14846
|
await checkedRead(item.undo, createContext(undefined, device));
|
|
14826
14847
|
}
|
|
14827
|
-
const beforeTarget = (await import("./library-
|
|
14828
|
-
const db = await beforeTarget((await import("./library-
|
|
14848
|
+
const beforeTarget = (await import("./library-588vnctn.js")).openSnapshotStore;
|
|
14849
|
+
const db = await beforeTarget((await import("./library-k6m2bxjr.js")).DEFAULT_SNAPSHOT_DB);
|
|
14829
14850
|
try {
|
|
14830
14851
|
const original = db.get(p.snapshots.target);
|
|
14831
14852
|
if (!original)
|
|
14832
14853
|
throw new Error("Original target snapshot unavailable.");
|
|
14833
|
-
const { normalizeExport } = await import("./library-
|
|
14854
|
+
const { normalizeExport } = await import("./library-g8far2nz.js");
|
|
14834
14855
|
if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
|
|
14835
14856
|
throw new Error("Target differs from its backup. Undo verification failed.");
|
|
14836
14857
|
} finally {
|
|
@@ -19611,6 +19632,1536 @@ var serviceContractTools = [
|
|
|
19611
19632
|
})
|
|
19612
19633
|
];
|
|
19613
19634
|
|
|
19635
|
+
// src/service-routing/model.ts
|
|
19636
|
+
import ipaddr2 from "ipaddr.js";
|
|
19637
|
+
import { createHash as createHash5 } from "crypto";
|
|
19638
|
+
|
|
19639
|
+
// src/service-routing/domain.ts
|
|
19640
|
+
var routingDomain = string().trim().toLowerCase().max(253).refine((value) => {
|
|
19641
|
+
const base = value.startsWith("*.") ? value.slice(2) : value;
|
|
19642
|
+
const labels = base.split(".");
|
|
19643
|
+
return labels.length >= 2 && !/^\d+(?:\.\d+){3}$/.test(base) && labels.every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) && !/^\d+$/.test(labels.at(-1));
|
|
19644
|
+
}, "Enter a domain such as api.example.com or *.example.com; no URL, port, path or other wildcard.");
|
|
19645
|
+
var isWildcard = (domain) => domain.startsWith("*.");
|
|
19646
|
+
function domainMatches(domain, host) {
|
|
19647
|
+
const candidate = host.toLowerCase();
|
|
19648
|
+
return isWildcard(domain) ? candidate.endsWith(domain.slice(1)) && candidate.length > domain.length - 1 : candidate === domain;
|
|
19649
|
+
}
|
|
19650
|
+
function wildcardRegexp(domain) {
|
|
19651
|
+
const checked = routingDomain.parse(domain);
|
|
19652
|
+
if (!isWildcard(checked))
|
|
19653
|
+
throw new Error("A wildcard domain is required.");
|
|
19654
|
+
return `^([a-z0-9-]+[.])+${checked.slice(2).replaceAll(".", "[.]")}$`;
|
|
19655
|
+
}
|
|
19656
|
+
function wildcardRegexOverlaps(regexp, domain) {
|
|
19657
|
+
const prefix = "^([a-z0-9-]+[.])+";
|
|
19658
|
+
if (!regexp.startsWith(prefix) || !regexp.endsWith("$"))
|
|
19659
|
+
return true;
|
|
19660
|
+
const base = regexp.slice(prefix.length, -1).replaceAll("[.]", ".");
|
|
19661
|
+
if (!routingDomain.safeParse(base).success || wildcardRegexp(`*.${base}`) !== regexp)
|
|
19662
|
+
return true;
|
|
19663
|
+
const candidate = domain.slice(2);
|
|
19664
|
+
return candidate === base || candidate.endsWith(`.${base}`) || base.endsWith(`.${candidate}`);
|
|
19665
|
+
}
|
|
19666
|
+
|
|
19667
|
+
// src/service-routing/model.ts
|
|
19668
|
+
var name2 = string().trim().min(1).max(64).regex(/^[a-zA-Z0-9_.-]+$/);
|
|
19669
|
+
var routingInput = object({
|
|
19670
|
+
name: string().trim().min(1).max(80),
|
|
19671
|
+
target: name2.optional().describe("Optional approved HTTPS probe alias; legacy drafts without domain route this alias's exact host"),
|
|
19672
|
+
domain: routingDomain.optional().describe("Exact domain or *.example.com (subdomains only, not the apex). Wildcards need client DNS through this router."),
|
|
19673
|
+
dnsLearningConfirmed: boolean().optional().describe("For wildcard only: confirms clients use this router DNS, shared-IP scope and FWD adlist bypass are understood. Does not enable or intercept DNS."),
|
|
19674
|
+
precedence: _enum(["before-existing"]).optional().describe("Explicitly allow this scoped policy before existing routing rules. Preview still binds their full configuration; FastTrack is never bypassed."),
|
|
19675
|
+
family: _enum(["ipv4", "ipv6"]),
|
|
19676
|
+
sources: array(string().refine((v) => ipaddr2.isValidCIDR(v), "Use an explicit client subnet CIDR")).min(1).max(8),
|
|
19677
|
+
tables: array(name2).min(1).max(3),
|
|
19678
|
+
primary: name2,
|
|
19679
|
+
maxLatencyMs: number().int().min(100).max(15000).default(5000),
|
|
19680
|
+
failuresBeforeSwitch: number().int().min(2).max(10).default(3),
|
|
19681
|
+
cooldownSeconds: number().int().min(120).max(3600).default(300)
|
|
19682
|
+
}).superRefine((v, ctx) => {
|
|
19683
|
+
if (!v.domain && !v.target)
|
|
19684
|
+
ctx.addIssue({ code: "custom", message: "Enter a domain or choose an approved service" });
|
|
19685
|
+
if (v.domain && isWildcard(v.domain) && !v.dnsLearningConfirmed)
|
|
19686
|
+
ctx.addIssue({
|
|
19687
|
+
code: "custom",
|
|
19688
|
+
message: "Confirm client DNS learning and its limitations for wildcard routing"
|
|
19689
|
+
});
|
|
19690
|
+
if (!v.tables.includes(v.primary) || new Set(v.tables).size !== v.tables.length)
|
|
19691
|
+
ctx.addIssue({ code: "custom", message: "Choose one unique candidate table as primary" });
|
|
19692
|
+
for (const s of v.sources) {
|
|
19693
|
+
const [ip, bits] = ipaddr2.parseCIDR(s);
|
|
19694
|
+
if (ip.kind() !== v.family || bits === 0)
|
|
19695
|
+
ctx.addIssue({
|
|
19696
|
+
code: "custom",
|
|
19697
|
+
message: "Sources must match the selected IP family and cannot be a default route"
|
|
19698
|
+
});
|
|
19699
|
+
}
|
|
19700
|
+
});
|
|
19701
|
+
var enabled3 = (r) => !["yes", "true"].includes(r.disabled) && !(r.flags ?? "").includes("X");
|
|
19702
|
+
var ownerTag = (id) => `mcp-sr-${id}`;
|
|
19703
|
+
var selector = (tag) => `[find where comment=${quoteValue(tag)}]`;
|
|
19704
|
+
var routingPath = (family) => family === "ipv4" ? "/ip firewall" : "/ipv6 firewall";
|
|
19705
|
+
function fingerprint(facts) {
|
|
19706
|
+
return createHash5("sha256").update(JSON.stringify({
|
|
19707
|
+
...facts,
|
|
19708
|
+
addresses: facts.addresses.filter((r) => !(r.list?.startsWith("mcp-sr-") && r.list.endsWith("-dst") && (["yes", "true"].includes(r.dynamic) || (r.flags ?? "").includes("D"))))
|
|
19709
|
+
}, (key, value) => ["#", ".id", "bytes", "packets", "last-handshake", "expires-after"].includes(key) ? undefined : value)).digest("hex");
|
|
19710
|
+
}
|
|
19711
|
+
function planCommands(policy, table, facts, remove = false) {
|
|
19712
|
+
const path = routingPath(policy.family), tag = ownerTag(policy.id), chain = `sr-${policy.id.slice(0, 12)}`;
|
|
19713
|
+
if (policy.state === "uncertain")
|
|
19714
|
+
throw new Error("Reconcile uncertain router state before another change.");
|
|
19715
|
+
const owned = facts.mangle.filter((r) => r.comment === tag);
|
|
19716
|
+
const wildcard = isWildcard(policy.host);
|
|
19717
|
+
const dns = facts.dns ?? [];
|
|
19718
|
+
const ownedDns = dns.filter((r) => r.comment === tag);
|
|
19719
|
+
if (wildcard && dns.some((r) => r["address-list"] === `${tag}-dst` && r.comment !== tag))
|
|
19720
|
+
throw new Error("A foreign DNS entry uses the owned destination list; reconcile first.");
|
|
19721
|
+
if (facts.mangle.some((r) => r.chain === chain && r.comment !== tag))
|
|
19722
|
+
throw new Error("Private chain contains foreign rules; review it first.");
|
|
19723
|
+
if (owned.some((r) => r.chain !== chain && r.chain !== "prerouting"))
|
|
19724
|
+
throw new Error("Owned rules were edited externally; review them first.");
|
|
19725
|
+
if (remove)
|
|
19726
|
+
return [
|
|
19727
|
+
new Cmd(`${path} mangle remove ${selector(tag)}`).build(),
|
|
19728
|
+
new Cmd(`${path} address-list remove ${selector(tag)}`).build(),
|
|
19729
|
+
...wildcard ? [
|
|
19730
|
+
new Cmd(`/ip dns static remove ${selector(tag)}`).build(),
|
|
19731
|
+
...["/ip firewall", "/ipv6 firewall"].map((base) => new Cmd(`${base} address-list remove [find where list=${quoteValue(`${tag}-dst`)} dynamic=yes]`).build())
|
|
19732
|
+
] : []
|
|
19733
|
+
];
|
|
19734
|
+
if (wildcard) {
|
|
19735
|
+
const version = /^(\d+)\.(\d+)(?:\.(\d+))?(?:\s|$)/.exec(facts.version ?? "");
|
|
19736
|
+
if (!version || Number(version[1]) < 7 || Number(version[1]) === 7 && Number(version[2]) < 17)
|
|
19737
|
+
throw new Error("Wildcard workflow requires stable RouterOS 7.17 or newer; version could not be verified.");
|
|
19738
|
+
if (!facts.dnsRemoteRequests || !policy.dnsLearningConfirmed)
|
|
19739
|
+
throw new Error("Wildcard routing needs confirmed client DNS through this router and allow-remote-requests already enabled. MCP will not expose DNS automatically.");
|
|
19740
|
+
const base = policy.host.slice(2);
|
|
19741
|
+
if (dns.some((r) => enabled3(r) && r.comment !== tag && (r.regexp && wildcardRegexOverlaps(r.regexp, policy.host) || r.name === base || r.name?.endsWith(`.${base}`) || ["yes", "true"].includes(r["match-subdomain"]) && base.endsWith(`.${r.name}`))))
|
|
19742
|
+
throw new Error("Existing DNS entries may overlap this wildcard. Review them first; MCP will not replace them.");
|
|
19743
|
+
if (owned.length) {
|
|
19744
|
+
if (ownedDns.length !== 1 || !enabled3(ownedDns[0]) || ownedDns[0].type !== "FWD" || ownedDns[0].regexp !== wildcardRegexp(policy.host) || ownedDns[0]["address-list"] !== `${tag}-dst` || ownedDns[0]["forward-to"] || ownedDns[0].name)
|
|
19745
|
+
throw new Error("Owned DNS learning scope changed externally.");
|
|
19746
|
+
} else if (ownedDns.length)
|
|
19747
|
+
throw new Error("Owned DNS entry is partially present; reconcile first.");
|
|
19748
|
+
}
|
|
19749
|
+
const listRows = facts.addresses.filter((r) => [`${tag}-src`, `${tag}-dst`].includes(r.list));
|
|
19750
|
+
const staticRows = listRows.filter((r) => !["yes", "true"].includes(r.dynamic) && !(r.flags ?? "").includes("D"));
|
|
19751
|
+
if (owned.length) {
|
|
19752
|
+
const expectedLists = [
|
|
19753
|
+
...policy.sources.map((address) => ({ list: `${tag}-src`, address })),
|
|
19754
|
+
...!wildcard ? [{ list: `${tag}-dst`, address: policy.host }] : []
|
|
19755
|
+
];
|
|
19756
|
+
if (staticRows.length !== expectedLists.length || expectedLists.some((e) => !staticRows.some((r) => r.list === e.list && r.address === e.address && r.comment === tag && enabled3(r))))
|
|
19757
|
+
throw new Error("Owned address-list scope changed externally.");
|
|
19758
|
+
if (listRows.some((r) => r.list === `${tag}-src` && !staticRows.includes(r)))
|
|
19759
|
+
throw new Error("Unexpected dynamic source scope.");
|
|
19760
|
+
} else if (policy.state === "active" || listRows.length) {
|
|
19761
|
+
throw new Error("Owned policy is missing or partially present; reconcile first.");
|
|
19762
|
+
}
|
|
19763
|
+
if (!policy.tables.includes(table))
|
|
19764
|
+
throw new Error("This exit is not approved by the policy.");
|
|
19765
|
+
if (!facts.tables.some((r) => r.name === table && enabled3(r) && ["yes", "true"].includes(r.fib)))
|
|
19766
|
+
throw new Error("Exit needs an existing enabled FIB table.");
|
|
19767
|
+
const dst = policy.family === "ipv4" ? "0.0.0.0/0" : "::/0";
|
|
19768
|
+
if (!facts.routes.some((r) => r["routing-table"] === table && r["dst-address"] === dst && !!r.gateway && r.blackhole !== "yes" && r.blackhole !== "true" && !["blackhole", "unreachable", "prohibit"].includes(r.type) && enabled3(r) && (["yes", "true"].includes(r.active) || (r.flags ?? "").includes("A"))))
|
|
19769
|
+
throw new Error("Exit has no observed active forwarding default route for this family (discard routes are not exits).");
|
|
19770
|
+
if (facts.filters.some((r) => enabled3(r) && r.action === "fasttrack-connection"))
|
|
19771
|
+
throw new Error("FastTrack may bypass this policy. Configure an explicit exclusion before applying.");
|
|
19772
|
+
if (policy.precedence !== "before-existing" && facts.mangle.some((r) => enabled3(r) && r.comment !== tag && ["mark-routing", "jump", "route"].includes(r.action)))
|
|
19773
|
+
throw new Error("Existing routing/jump rules need an administrator conflict review. They will not be overridden.");
|
|
19774
|
+
const result = [];
|
|
19775
|
+
if (owned.length) {
|
|
19776
|
+
if (policy.state !== "active" || !policy.activeTable)
|
|
19777
|
+
throw new Error("Unexpected owned rules exist. Reconcile the router before applying a draft.");
|
|
19778
|
+
const expected = planCommands({ ...policy, state: "draft" }, policy.activeTable, {
|
|
19779
|
+
...facts,
|
|
19780
|
+
mangle: facts.mangle.filter((r) => r.comment !== tag),
|
|
19781
|
+
addresses: facts.addresses.filter((r) => ![`${tag}-src`, `${tag}-dst`].includes(r.list)),
|
|
19782
|
+
dns: facts.dns?.filter((r) => r.comment !== tag)
|
|
19783
|
+
}).filter((command) => command.startsWith(`${path} mangle add`)).map((command) => parseRecords(`0 ${command}`).rows[0]);
|
|
19784
|
+
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))))
|
|
19785
|
+
throw new Error("Owned rule scope changed externally. Automatic edits are blocked.");
|
|
19786
|
+
if (owned.filter((r) => r.action === "mark-routing").length !== 1)
|
|
19787
|
+
throw new Error("Owned routing mark is missing or ambiguous.");
|
|
19788
|
+
result.push(new Cmd(`${path} mangle set [find where comment=${quoteValue(tag)} action=mark-routing]`).set("new-routing-mark", table).build());
|
|
19789
|
+
return result;
|
|
19790
|
+
}
|
|
19791
|
+
for (const address of policy.sources)
|
|
19792
|
+
result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-src`).set("address", address).set("comment", tag).build());
|
|
19793
|
+
if (wildcard)
|
|
19794
|
+
result.push(new Cmd("/ip dns static add").set("type", "FWD").set("regexp", wildcardRegexp(policy.host)).set("address-list", `${tag}-dst`).bool("disabled", false).set("comment", tag).build());
|
|
19795
|
+
else
|
|
19796
|
+
result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-dst`).set("address", policy.host).set("comment", tag).build());
|
|
19797
|
+
const exclude = policy.family === "ipv4" ? [
|
|
19798
|
+
"0.0.0.0/8",
|
|
19799
|
+
"10.0.0.0/8",
|
|
19800
|
+
"100.64.0.0/10",
|
|
19801
|
+
"127.0.0.0/8",
|
|
19802
|
+
"169.254.0.0/16",
|
|
19803
|
+
"172.16.0.0/12",
|
|
19804
|
+
"192.168.0.0/16",
|
|
19805
|
+
"224.0.0.0/3"
|
|
19806
|
+
] : ["::/128", "::1/128", "::ffff:0:0/96", "fc00::/7", "fe80::/10", "ff00::/8"];
|
|
19807
|
+
for (const subnet of exclude)
|
|
19808
|
+
result.push(new Cmd(`${path} mangle add`).set("chain", chain).set("dst-address", subnet).set("action", "return").set("comment", tag).build());
|
|
19809
|
+
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());
|
|
19810
|
+
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());
|
|
19811
|
+
return result;
|
|
19812
|
+
}
|
|
19813
|
+
|
|
19814
|
+
// src/service-routing/service.ts
|
|
19815
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
19816
|
+
import { isIP as isIP2 } from "net";
|
|
19817
|
+
|
|
19818
|
+
// src/service-routing/read.ts
|
|
19819
|
+
var paths = new Set([
|
|
19820
|
+
"/ip dns static",
|
|
19821
|
+
"/routing table",
|
|
19822
|
+
"/routing rule",
|
|
19823
|
+
"/ip route",
|
|
19824
|
+
"/ipv6 route",
|
|
19825
|
+
"/ip vrf",
|
|
19826
|
+
"/ip firewall mangle",
|
|
19827
|
+
"/ipv6 firewall mangle",
|
|
19828
|
+
"/ip firewall filter",
|
|
19829
|
+
"/ipv6 firewall filter",
|
|
19830
|
+
"/ip firewall address-list",
|
|
19831
|
+
"/ipv6 firewall address-list"
|
|
19832
|
+
]);
|
|
19833
|
+
var ROUTING_ROW_LIMIT = 2000;
|
|
19834
|
+
function routingReadCommand(path, lists) {
|
|
19835
|
+
if (!paths.has(path))
|
|
19836
|
+
throw new Error("Unsupported routing inventory section.");
|
|
19837
|
+
const where = lists?.length ? `where ${lists.map((list) => `list=${quoteValue(list)}`).join(" or ")}` : "";
|
|
19838
|
+
const find = new Cmd(`${path} find`).raw(where).build();
|
|
19839
|
+
const print = new Cmd(`${path} print`).raw("detail as-value").raw(where).build();
|
|
19840
|
+
return `:if ([:len [${find}]] > ${ROUTING_ROW_LIMIT}) do={:put "MCP_ROUTING_ROW_LIMIT"} else={:put [:serialize to=json value=[${print}]]}`;
|
|
19841
|
+
}
|
|
19842
|
+
function parseRoutingRows(raw, fields) {
|
|
19843
|
+
if (raw.length > 1048576)
|
|
19844
|
+
throw new Error("Routing section exceeds the 1 MiB read limit.");
|
|
19845
|
+
if (raw.trim() === "MCP_ROUTING_ROW_LIMIT")
|
|
19846
|
+
throw new Error(`More than ${ROUTING_ROW_LIMIT} entries: this section was not loaded to protect the router. Use a filtered RouterOS read; the other routing sections are independent.`);
|
|
19847
|
+
if (looksLikeError(raw))
|
|
19848
|
+
throw new Error("Router rejected this read; check connectivity, permissions and RouterOS v7 support.");
|
|
19849
|
+
let data;
|
|
19850
|
+
try {
|
|
19851
|
+
data = JSON.parse(raw.trim());
|
|
19852
|
+
} catch {
|
|
19853
|
+
throw new Error("Router did not return valid structured routing data; no rows were accepted.");
|
|
19854
|
+
}
|
|
19855
|
+
if (!Array.isArray(data) || data.length > ROUTING_ROW_LIMIT || data.some((r) => !r || typeof r !== "object" || Array.isArray(r)))
|
|
19856
|
+
throw new Error("Router returned an incomplete or invalid routing section.");
|
|
19857
|
+
const keys = fields ? new Set(["#", ".id", "flags", ...fields.split(",")]) : undefined;
|
|
19858
|
+
return data.map((record, index) => {
|
|
19859
|
+
const row = { "#": String(index) };
|
|
19860
|
+
for (const [key, value] of Object.entries(record)) {
|
|
19861
|
+
if (keys && !keys.has(key))
|
|
19862
|
+
continue;
|
|
19863
|
+
if (typeof value === "boolean")
|
|
19864
|
+
row[key] = value ? "yes" : "no";
|
|
19865
|
+
else if (typeof value === "string" || typeof value === "number")
|
|
19866
|
+
row[key] = String(value);
|
|
19867
|
+
else if (Array.isArray(value) && value.every((v) => ["string", "number"].includes(typeof v)))
|
|
19868
|
+
row[key] = value.join(",");
|
|
19869
|
+
}
|
|
19870
|
+
return row;
|
|
19871
|
+
});
|
|
19872
|
+
}
|
|
19873
|
+
async function readRoutingRows(path, fields, ctx, lists) {
|
|
19874
|
+
const raw = await executeMikrotikCommand2(routingReadCommand(path, lists), ctx, { maxMs: 6000 });
|
|
19875
|
+
return parseRoutingRows(raw, fields);
|
|
19876
|
+
}
|
|
19877
|
+
async function readRoutingAddressPage(path, ctx, offset = 0) {
|
|
19878
|
+
if (!["/ip firewall address-list", "/ipv6 firewall address-list"].includes(path) || !Number.isSafeInteger(offset) || offset < 0 || offset > 1e6)
|
|
19879
|
+
throw new Error("Invalid address-list page.");
|
|
19880
|
+
const find = new Cmd(`${path} find`).build();
|
|
19881
|
+
const get = new Cmd(`${path} get`).raw("$srId").build();
|
|
19882
|
+
const command = `{ :local srIds [${find}]; :local srItems [:toarray ""]; :foreach srId in=[:pick $srIds ${offset} ${offset + 200}] do={ :local srRow [${get}]; :set ($srRow->".id") $srId; :set ($srItems->[:len $srItems]) $srRow; }; :put [:serialize to=json value={"rows"=$srItems;"total"=[:len $srIds]}]; }`;
|
|
19883
|
+
const raw = await executeMikrotikCommand2(command, ctx, { maxMs: 6000 });
|
|
19884
|
+
return parseRoutingAddressPage(raw, offset);
|
|
19885
|
+
}
|
|
19886
|
+
function parseRoutingAddressPage(raw, offset = 0) {
|
|
19887
|
+
if (looksLikeError(raw) || raw.length > 1048576)
|
|
19888
|
+
throw new Error("Address-list page could not be read safely.");
|
|
19889
|
+
let data;
|
|
19890
|
+
try {
|
|
19891
|
+
data = JSON.parse(raw.trim());
|
|
19892
|
+
} catch {
|
|
19893
|
+
throw new Error("Invalid structured address-list page.");
|
|
19894
|
+
}
|
|
19895
|
+
if (!data || !Array.isArray(data.rows) || !Number.isSafeInteger(data.total) || data.total < 0)
|
|
19896
|
+
throw new Error("Invalid address-list total.");
|
|
19897
|
+
const rows = parseRoutingRows(JSON.stringify(data.rows)).map((r, i) => ({
|
|
19898
|
+
...r,
|
|
19899
|
+
"#": String(offset + i)
|
|
19900
|
+
}));
|
|
19901
|
+
if (rows.length !== Math.min(200, Math.max(0, data.total - offset)) || rows.some((r) => !r[".id"]))
|
|
19902
|
+
throw new Error("Incomplete address-list page. Refresh if the router list changed while reading.");
|
|
19903
|
+
return {
|
|
19904
|
+
rows,
|
|
19905
|
+
total: data.total,
|
|
19906
|
+
nextOffset: offset + rows.length < data.total ? offset + rows.length : undefined
|
|
19907
|
+
};
|
|
19908
|
+
}
|
|
19909
|
+
|
|
19910
|
+
// src/service-routing/inventory.ts
|
|
19911
|
+
var routingSections = {
|
|
19912
|
+
tables: "/routing table",
|
|
19913
|
+
routes4: "/ip route",
|
|
19914
|
+
routes6: "/ipv6 route",
|
|
19915
|
+
mangle4: "/ip firewall mangle",
|
|
19916
|
+
mangle6: "/ipv6 firewall mangle",
|
|
19917
|
+
rules: "/routing rule",
|
|
19918
|
+
addresses4: "/ip firewall address-list",
|
|
19919
|
+
addresses6: "/ipv6 firewall address-list",
|
|
19920
|
+
vrfs: "/ip vrf",
|
|
19921
|
+
filters4: "/ip firewall filter",
|
|
19922
|
+
filters6: "/ipv6 firewall filter"
|
|
19923
|
+
};
|
|
19924
|
+
function createRoutingInventoryReader(read = readRoutingRows, addresses = readRoutingAddressPage) {
|
|
19925
|
+
const cache = new Map;
|
|
19926
|
+
const pending = new Map;
|
|
19927
|
+
let generation = 0;
|
|
19928
|
+
return {
|
|
19929
|
+
clear() {
|
|
19930
|
+
generation++;
|
|
19931
|
+
cache.clear();
|
|
19932
|
+
pending.clear();
|
|
19933
|
+
},
|
|
19934
|
+
async read(device, ctx) {
|
|
19935
|
+
const hit = cache.get(device);
|
|
19936
|
+
const ttl = hit && Object.values(hit.value.sections).every((s) => s.state === "ready") ? 20000 : 5000;
|
|
19937
|
+
if (hit && Date.now() - hit.at < ttl)
|
|
19938
|
+
return hit.value;
|
|
19939
|
+
if (pending.has(device))
|
|
19940
|
+
return pending.get(device);
|
|
19941
|
+
const current = generation;
|
|
19942
|
+
const work = (async () => {
|
|
19943
|
+
const sections = {};
|
|
19944
|
+
const deadline = Date.now() + 25000;
|
|
19945
|
+
const entries = Object.entries(routingSections);
|
|
19946
|
+
const worker = async () => {
|
|
19947
|
+
for (let entry = entries.shift();entry; entry = entries.shift()) {
|
|
19948
|
+
const [key, path] = entry;
|
|
19949
|
+
try {
|
|
19950
|
+
if (Date.now() >= deadline)
|
|
19951
|
+
throw new Error("Snapshot time budget reached. Refresh to retry this section.");
|
|
19952
|
+
const result = key.startsWith("addresses") ? await addresses(path, { ...ctx, device }) : { rows: await read(path, undefined, { ...ctx, device }) };
|
|
19953
|
+
sections[key] = { path, ...result, state: "ready", observedAt: Date.now() };
|
|
19954
|
+
} catch (e) {
|
|
19955
|
+
sections[key] = {
|
|
19956
|
+
path,
|
|
19957
|
+
rows: [],
|
|
19958
|
+
state: "error",
|
|
19959
|
+
observedAt: Date.now(),
|
|
19960
|
+
error: e instanceof Error ? e.message : "Routing section could not be read."
|
|
19961
|
+
};
|
|
19962
|
+
}
|
|
19963
|
+
}
|
|
19964
|
+
};
|
|
19965
|
+
await Promise.all([worker(), worker()]);
|
|
19966
|
+
const value = { device, sections, observedAt: Date.now() };
|
|
19967
|
+
if (generation === current)
|
|
19968
|
+
cache.set(device, { at: Date.now(), value });
|
|
19969
|
+
return value;
|
|
19970
|
+
})();
|
|
19971
|
+
pending.set(device, work);
|
|
19972
|
+
try {
|
|
19973
|
+
return await work;
|
|
19974
|
+
} finally {
|
|
19975
|
+
if (pending.get(device) === work)
|
|
19976
|
+
pending.delete(device);
|
|
19977
|
+
}
|
|
19978
|
+
}
|
|
19979
|
+
};
|
|
19980
|
+
}
|
|
19981
|
+
var routerRoutingInventory = createRoutingInventoryReader();
|
|
19982
|
+
onConfigChanged(() => routerRoutingInventory.clear());
|
|
19983
|
+
|
|
19984
|
+
// src/operations/store.ts
|
|
19985
|
+
import { mkdirSync as mkdirSync9, chmodSync } from "fs";
|
|
19986
|
+
import { dirname as dirname9, join as join2 } from "path";
|
|
19987
|
+
class OperationsStore {
|
|
19988
|
+
db;
|
|
19989
|
+
constructor(db) {
|
|
19990
|
+
this.db = db;
|
|
19991
|
+
db.run("PRAGMA busy_timeout = 3000");
|
|
19992
|
+
db.run("CREATE TABLE IF NOT EXISTS workspace_records (kind TEXT, id TEXT, device TEXT, updated INTEGER, body TEXT, PRIMARY KEY(kind,id))");
|
|
19993
|
+
db.run("CREATE INDEX IF NOT EXISTS workspace_device ON workspace_records(kind,device,updated DESC)");
|
|
19994
|
+
db.run("CREATE TABLE IF NOT EXISTS workspace_locks (device TEXT PRIMARY KEY, owner TEXT NOT NULL)");
|
|
19995
|
+
}
|
|
19996
|
+
get(kind, id, device) {
|
|
19997
|
+
const row = this.db.query("SELECT body FROM workspace_records WHERE kind=? AND id=? AND device=?").get(kind, id, device);
|
|
19998
|
+
return row ? JSON.parse(row.body) : undefined;
|
|
19999
|
+
}
|
|
20000
|
+
list(kind, device, limit = 100) {
|
|
20001
|
+
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));
|
|
20002
|
+
}
|
|
20003
|
+
put(kind, record) {
|
|
20004
|
+
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));
|
|
20005
|
+
}
|
|
20006
|
+
delete(kind, id, device) {
|
|
20007
|
+
this.db.query("DELETE FROM workspace_records WHERE kind=? AND id=? AND device=?").run(kind, id, device);
|
|
20008
|
+
}
|
|
20009
|
+
prune(kind, device, before) {
|
|
20010
|
+
this.db.query("DELETE FROM workspace_records WHERE kind=? AND device=? AND updated<?").run(kind, device, before);
|
|
20011
|
+
}
|
|
20012
|
+
lock(device, owner) {
|
|
20013
|
+
const result = this.db.query("INSERT OR IGNORE INTO workspace_locks VALUES (?,?)").run(device, owner);
|
|
20014
|
+
if (!result.changes)
|
|
20015
|
+
throw new Error("Another workspace operation holds this router. An interrupted operation requires reconciliation before retrying.");
|
|
20016
|
+
}
|
|
20017
|
+
unlock(device, owner) {
|
|
20018
|
+
this.db.query("DELETE FROM workspace_locks WHERE device=? AND owner=?").run(device, owner);
|
|
20019
|
+
}
|
|
20020
|
+
}
|
|
20021
|
+
var pending5;
|
|
20022
|
+
function operationsStore() {
|
|
20023
|
+
pending5 ??= (async () => {
|
|
20024
|
+
const path = join2(dirname9(DEFAULT_SNAPSHOT_DB2), "operations.db");
|
|
20025
|
+
mkdirSync9(dirname9(path), { recursive: true, mode: 448 });
|
|
20026
|
+
const { Database } = await import("bun:sqlite");
|
|
20027
|
+
const db = new Database(path, { create: true });
|
|
20028
|
+
chmodSync(path, 384);
|
|
20029
|
+
db.run("PRAGMA journal_mode = WAL");
|
|
20030
|
+
return new OperationsStore(db);
|
|
20031
|
+
})().catch((error) => {
|
|
20032
|
+
pending5 = undefined;
|
|
20033
|
+
throw error;
|
|
20034
|
+
});
|
|
20035
|
+
return pending5;
|
|
20036
|
+
}
|
|
20037
|
+
|
|
20038
|
+
// src/service-routing/traffic.ts
|
|
20039
|
+
function trafficCommand(policy) {
|
|
20040
|
+
const path = `${routingPath(policy.family)} mangle`;
|
|
20041
|
+
const find = new Cmd(`${path} find`).raw(`where comment=${quoteValue(ownerTag(policy.id))} action=mark-routing`).build();
|
|
20042
|
+
const get = new Cmd(`${path} get`).raw("$srId").build();
|
|
20043
|
+
return `{ :local srIds [${find}]; :if ([:len $srIds] > 1) do={:error "Ambiguous service routing counters"}; :local srItems [:toarray ""]; :foreach srId in=$srIds do={ :local srRow [${get}]; :set ($srRow->".id") $srId; :set ($srRow->"bytes") [:tostr [${get} bytes]]; :set ($srRow->"packets") [:tostr [${get} packets]]; :set ($srItems->[:len $srItems]) $srRow; }; :put [:serialize to=json options=json.no-string-conversion value=$srItems]; }`;
|
|
20044
|
+
}
|
|
20045
|
+
function parsePolicyTraffic(policy, raw, at) {
|
|
20046
|
+
if (raw.length > 32768)
|
|
20047
|
+
throw new Error("Counter response exceeds the bounded read limit.");
|
|
20048
|
+
const rows = parseRoutingRows(raw);
|
|
20049
|
+
const row = rows[0];
|
|
20050
|
+
const base = { policyId: policy.id, device: policy.device, at };
|
|
20051
|
+
const encoded = JSON.parse(raw);
|
|
20052
|
+
if (rows.length !== 1 || !row || !row[".id"] || !enabled3(row) || row.comment !== ownerTag(policy.id) || row.action !== "mark-routing" || row.chain !== `sr-${policy.id.slice(0, 12)}` || row["new-routing-mark"] !== policy.activeTable || typeof encoded[0]?.bytes !== "string" || typeof encoded[0]?.packets !== "string" || !/^\d{1,20}$/.test(row.bytes ?? "") || !/^\d{1,20}$/.test(row.packets ?? "")) {
|
|
20053
|
+
return {
|
|
20054
|
+
...base,
|
|
20055
|
+
state: "unavailable",
|
|
20056
|
+
detail: "The active owned rule or its counters could not be verified. Inspect router configuration; missing data is not zero."
|
|
20057
|
+
};
|
|
20058
|
+
}
|
|
20059
|
+
return {
|
|
20060
|
+
...base,
|
|
20061
|
+
state: "ready",
|
|
20062
|
+
ruleId: row[".id"],
|
|
20063
|
+
table: row["new-routing-mark"],
|
|
20064
|
+
bytes: row.bytes,
|
|
20065
|
+
packets: row.packets,
|
|
20066
|
+
detail: "Client \u2192 service packets matched by this routing mark, since router counter reset. Excludes return/download traffic; not proof of delivery or billing totals."
|
|
20067
|
+
};
|
|
20068
|
+
}
|
|
20069
|
+
var cache2 = new Map;
|
|
20070
|
+
async function readPolicyTraffic(policy, ctx) {
|
|
20071
|
+
if (policy.state !== "active")
|
|
20072
|
+
return {
|
|
20073
|
+
policyId: policy.id,
|
|
20074
|
+
device: policy.device,
|
|
20075
|
+
at: Date.now(),
|
|
20076
|
+
state: "inactive",
|
|
20077
|
+
detail: "Apply and verify this policy before reading its router counters."
|
|
20078
|
+
};
|
|
20079
|
+
const key = JSON.stringify([policy.device, policy.id, policy.activeTable, policy.lastSwitchAt]);
|
|
20080
|
+
const cached = cache2.get(key);
|
|
20081
|
+
if (cached && cached.expires > Date.now())
|
|
20082
|
+
return cached.value;
|
|
20083
|
+
if (cache2.size >= 64)
|
|
20084
|
+
cache2.delete(cache2.keys().next().value);
|
|
20085
|
+
const value = (async () => {
|
|
20086
|
+
try {
|
|
20087
|
+
const raw = await executeMikrotikCommand2(trafficCommand(policy), ctx, { maxMs: 6000 });
|
|
20088
|
+
return parsePolicyTraffic(policy, raw, Date.now());
|
|
20089
|
+
} catch {
|
|
20090
|
+
return {
|
|
20091
|
+
policyId: policy.id,
|
|
20092
|
+
device: policy.device,
|
|
20093
|
+
at: Date.now(),
|
|
20094
|
+
state: "unavailable",
|
|
20095
|
+
detail: "Router counters could not be read. Check device connectivity and retry; no zero values were substituted."
|
|
20096
|
+
};
|
|
20097
|
+
}
|
|
20098
|
+
})();
|
|
20099
|
+
cache2.set(key, { value, expires: Date.now() + 1e4 });
|
|
20100
|
+
value.finally(() => {
|
|
20101
|
+
const entry = cache2.get(key);
|
|
20102
|
+
if (entry?.value === value)
|
|
20103
|
+
entry.expires = Date.now() + 4000;
|
|
20104
|
+
});
|
|
20105
|
+
return value;
|
|
20106
|
+
}
|
|
20107
|
+
|
|
20108
|
+
// src/service-routing/service.ts
|
|
20109
|
+
var kind = "service-routing";
|
|
20110
|
+
function access(ctx, tool, write = false) {
|
|
20111
|
+
const device = resolveDeviceName2(ctx.device);
|
|
20112
|
+
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
20113
|
+
return device;
|
|
20114
|
+
}
|
|
20115
|
+
async function locked(device, work) {
|
|
20116
|
+
const store = await operationsStore(), owner = randomUUID8();
|
|
20117
|
+
store.lock(device, owner);
|
|
20118
|
+
try {
|
|
20119
|
+
return await work();
|
|
20120
|
+
} finally {
|
|
20121
|
+
store.unlock(device, owner);
|
|
20122
|
+
}
|
|
20123
|
+
}
|
|
20124
|
+
async function routingPolicy(id, device) {
|
|
20125
|
+
const policy = (await operationsStore()).get(kind, id, device);
|
|
20126
|
+
if (!policy)
|
|
20127
|
+
throw new Error("Policy not found on the selected router.");
|
|
20128
|
+
return policy;
|
|
20129
|
+
}
|
|
20130
|
+
function save(policy, message) {
|
|
20131
|
+
policy.updatedAt = Date.now();
|
|
20132
|
+
if (message)
|
|
20133
|
+
policy.history = [{ at: policy.updatedAt, message }, ...policy.history].slice(0, 100);
|
|
20134
|
+
return operationsStore().then((store) => store.put(kind, policy));
|
|
20135
|
+
}
|
|
20136
|
+
async function routingInventory(ctx) {
|
|
20137
|
+
const device = access(ctx, "service_routing_inventory");
|
|
20138
|
+
const snapshot = await routerRoutingInventory.read(device, ctx);
|
|
20139
|
+
const tables = snapshot.sections.tables.rows;
|
|
20140
|
+
return {
|
|
20141
|
+
...snapshot,
|
|
20142
|
+
tables: tables.filter((r) => enabled3(r) && ["yes", "true"].includes(r.fib)).map((r) => r.name),
|
|
20143
|
+
targets: Object.entries(getConfig2().serviceProbes.targets).filter(([, t]) => t.kind === "https").map(([alias, t]) => ({ alias, host: t.host }))
|
|
20144
|
+
};
|
|
20145
|
+
}
|
|
20146
|
+
async function listRouting(ctx) {
|
|
20147
|
+
const device = access(ctx, "list_service_routing");
|
|
20148
|
+
return { policies: (await operationsStore()).list(kind, device) };
|
|
20149
|
+
}
|
|
20150
|
+
async function routingAddressPage(family, offset, ctx) {
|
|
20151
|
+
const device = access(ctx, "service_routing_address_page");
|
|
20152
|
+
return {
|
|
20153
|
+
device,
|
|
20154
|
+
family,
|
|
20155
|
+
offset,
|
|
20156
|
+
...await readRoutingAddressPage(`${routingPath(family)} address-list`, { ...ctx, device }, offset)
|
|
20157
|
+
};
|
|
20158
|
+
}
|
|
20159
|
+
async function createRouting(input, ctx) {
|
|
20160
|
+
const device = access(ctx, "create_service_routing", true), a = routingInput.parse(input);
|
|
20161
|
+
const target = a.target ? getConfig2().serviceProbes.targets[a.target] : undefined;
|
|
20162
|
+
if (a.target && (!target || target.kind !== "https"))
|
|
20163
|
+
throw new Error("Select an administrator-approved HTTPS probe alias first.");
|
|
20164
|
+
const host = a.domain ?? target?.host.toLowerCase();
|
|
20165
|
+
if (!host)
|
|
20166
|
+
throw new Error("Enter a domain or choose an approved service.");
|
|
20167
|
+
if (target && !domainMatches(host, target.host))
|
|
20168
|
+
throw new Error("The approved probe hostname must match the exact domain or its wildcard subdomains.");
|
|
20169
|
+
const store = await operationsStore();
|
|
20170
|
+
if (store.list(kind, device).length >= 100)
|
|
20171
|
+
throw new Error("Router policy limit reached (100).");
|
|
20172
|
+
const policy = {
|
|
20173
|
+
...a,
|
|
20174
|
+
id: randomUUID8(),
|
|
20175
|
+
device,
|
|
20176
|
+
host,
|
|
20177
|
+
probeHost: target?.host,
|
|
20178
|
+
updatedAt: Date.now(),
|
|
20179
|
+
state: "draft",
|
|
20180
|
+
samples: [],
|
|
20181
|
+
history: []
|
|
20182
|
+
};
|
|
20183
|
+
await save(policy, "Draft saved. No router changes or probes yet.");
|
|
20184
|
+
return policy;
|
|
20185
|
+
}
|
|
20186
|
+
async function routingTraffic(id, ctx) {
|
|
20187
|
+
const device = access(ctx, "service_routing_traffic");
|
|
20188
|
+
return readPolicyTraffic(await routingPolicy(id, device), { ...ctx, device });
|
|
20189
|
+
}
|
|
20190
|
+
async function facts(policy, ctx) {
|
|
20191
|
+
const base = routingPath(policy.family);
|
|
20192
|
+
const tables = await readRoutingRows("/routing table", "name,fib,disabled", ctx);
|
|
20193
|
+
const routes = await readRoutingRows(policy.family === "ipv4" ? "/ip route" : "/ipv6 route", "routing-table,dst-address,gateway,active,disabled,blackhole,type", ctx);
|
|
20194
|
+
const mangle = await readRoutingRows(`${base} mangle`, undefined, ctx);
|
|
20195
|
+
const filters = await readRoutingRows(`${base} filter`, "action,disabled", ctx);
|
|
20196
|
+
if (policy.family === "ipv4") {
|
|
20197
|
+
const active = (await checkedRead("/ip firewall connection print count-only where fasttrack=yes", ctx)).trim();
|
|
20198
|
+
if (!/^\d+$/.test(active) || Number(active) > 0)
|
|
20199
|
+
throw new Error("Active FastTrack connections must drain before routing can be changed.");
|
|
20200
|
+
}
|
|
20201
|
+
const vrfs = await readRoutingRows("/ip vrf", "name,interfaces,disabled", ctx);
|
|
20202
|
+
const addresses = await readRoutingRows(`${base} address-list`, "list,address,comment,dynamic,disabled", ctx, [`${ownerTag(policy.id)}-src`, `${ownerTag(policy.id)}-dst`]);
|
|
20203
|
+
const result = { tables, routes, mangle, filters, vrfs, addresses };
|
|
20204
|
+
if (isWildcard(policy.host)) {
|
|
20205
|
+
result.dns = await readRoutingRows("/ip dns static", "name,regexp,type,address-list,match-subdomain,forward-to,disabled,comment", ctx);
|
|
20206
|
+
result.version = (await checkedRead(":put [/system resource get version]", ctx)).trim();
|
|
20207
|
+
result.dnsRemoteRequests = ["yes", "true"].includes((await checkedRead(":put [/ip dns get allow-remote-requests]", ctx)).trim());
|
|
20208
|
+
}
|
|
20209
|
+
return result;
|
|
20210
|
+
}
|
|
20211
|
+
function fetchCommand(address, table, host, path, port) {
|
|
20212
|
+
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("duration", "5s").set("output", "none").raw("as-value").build()}]]`;
|
|
20213
|
+
}
|
|
20214
|
+
async function probe(policy, ctx) {
|
|
20215
|
+
if (!policy.target)
|
|
20216
|
+
throw new Error("This is a manual domain route. Add an approved HTTPS probe in a new policy to check exits or authorize failover.");
|
|
20217
|
+
const target = getConfig2().serviceProbes.targets[policy.target];
|
|
20218
|
+
if (!target || target.kind !== "https" || target.host !== (policy.probeHost ?? policy.host))
|
|
20219
|
+
throw new Error("Probe approval changed. Create a new policy.");
|
|
20220
|
+
const vrfs = await readRoutingRows("/ip vrf", "name,disabled", ctx);
|
|
20221
|
+
let addresses = [];
|
|
20222
|
+
try {
|
|
20223
|
+
addresses = await nativeProbeIO.resolve(target.host, 3000);
|
|
20224
|
+
if (addresses.some((a) => !addressAllowed(a, target.addresses)))
|
|
20225
|
+
addresses = [];
|
|
20226
|
+
} catch {}
|
|
20227
|
+
const address = addresses.find((a) => isIP2(a) === (policy.family === "ipv4" ? 4 : 6));
|
|
20228
|
+
for (const table of policy.tables) {
|
|
20229
|
+
const sample = {
|
|
20230
|
+
table,
|
|
20231
|
+
at: Date.now(),
|
|
20232
|
+
state: "unknown",
|
|
20233
|
+
detail: "No approved DNS answer for this IP family."
|
|
20234
|
+
};
|
|
20235
|
+
if (address) {
|
|
20236
|
+
sample.address = address;
|
|
20237
|
+
sample.detail = "This routing table is not a VRF. A table-only HTTPS path cannot be proved by fetch.";
|
|
20238
|
+
if (vrfs.some((v) => v.name === table && enabled3(v))) {
|
|
20239
|
+
const start = Date.now();
|
|
20240
|
+
try {
|
|
20241
|
+
const raw = await executeMikrotikCommand2(fetchCommand(address, table, target.host, target.path, target.port), ctx, { maxMs: 8000 });
|
|
20242
|
+
sample.elapsedMs = Date.now() - start;
|
|
20243
|
+
if (looksLikeError(raw)) {
|
|
20244
|
+
if (/failure:.*(?:fetch|SSL|connection|timeout|resolving|status)/i.test(raw)) {
|
|
20245
|
+
sample.state = "fail";
|
|
20246
|
+
sample.detail = "Router fetch reported an HTTP, TLS or connection failure.";
|
|
20247
|
+
} else
|
|
20248
|
+
sample.detail = "Router fetch was rejected or unsupported; path health is unknown.";
|
|
20249
|
+
} else {
|
|
20250
|
+
const result = JSON.parse(raw.trim());
|
|
20251
|
+
if (result.status === "finished" && (result.code === undefined || Number(result.code) >= 200 && Number(result.code) < 300)) {
|
|
20252
|
+
sample.state = sample.elapsedMs <= policy.maxLatencyMs ? "pass" : "fail";
|
|
20253
|
+
sample.detail = `HTTPS HEAD completed via VRF ${table}; elapsed includes SSH overhead. Not a client-path or throughput test.`;
|
|
20254
|
+
}
|
|
20255
|
+
}
|
|
20256
|
+
} catch {
|
|
20257
|
+
sample.detail = "Router query did not produce verified fetch evidence. Connection or capability may be unavailable.";
|
|
20258
|
+
}
|
|
20259
|
+
}
|
|
20260
|
+
}
|
|
20261
|
+
policy.samples.push(sample);
|
|
20262
|
+
}
|
|
20263
|
+
policy.samples = policy.samples.slice(-180);
|
|
20264
|
+
await save(policy);
|
|
20265
|
+
}
|
|
20266
|
+
async function probeRouting(id, ctx) {
|
|
20267
|
+
const device = access(ctx, "probe_service_routing");
|
|
20268
|
+
return locked(device, async () => {
|
|
20269
|
+
const policy = await routingPolicy(id, device);
|
|
20270
|
+
await probe(policy, ctx);
|
|
20271
|
+
return policy;
|
|
20272
|
+
});
|
|
20273
|
+
}
|
|
20274
|
+
async function preview(policy, table, remove, ctx) {
|
|
20275
|
+
const snapshot = await facts(policy, ctx);
|
|
20276
|
+
policy.plan = {
|
|
20277
|
+
id: randomUUID8(),
|
|
20278
|
+
table,
|
|
20279
|
+
remove,
|
|
20280
|
+
expiresAt: Date.now() + 120000,
|
|
20281
|
+
fingerprint: fingerprint(snapshot),
|
|
20282
|
+
commands: planCommands(policy, table, snapshot, remove),
|
|
20283
|
+
warnings: [
|
|
20284
|
+
"IP-based matching includes other services sharing the resolved IPs. Counters measure client-to-service matched packets, not successful delivery or download totals.",
|
|
20285
|
+
...isWildcard(policy.host) ? [
|
|
20286
|
+
"Subdomains only; apex excluded. Clients must query this router DNS. External DNS, client DoH/DoT and previously cached answers can bypass learning. FWD uses existing upstream DNS and bypasses router adlists for matching names, for all DNS clients; no DNS interception or exposure is added."
|
|
20287
|
+
] : [],
|
|
20288
|
+
...policy.precedence === "before-existing" ? [
|
|
20289
|
+
"This scoped policy is inserted before existing routing rules. On shared IPs it takes precedence; other rules are not rewritten. Existing connections may be interrupted."
|
|
20290
|
+
] : []
|
|
20291
|
+
]
|
|
20292
|
+
};
|
|
20293
|
+
await save(policy, "Preview created. Review scope and commands; valid for two minutes.");
|
|
20294
|
+
return policy;
|
|
20295
|
+
}
|
|
20296
|
+
async function previewRouting(id, table, remove, ctx) {
|
|
20297
|
+
const device = access(ctx, "preview_service_routing");
|
|
20298
|
+
return locked(device, async () => preview(await routingPolicy(id, device), table, remove, ctx));
|
|
20299
|
+
}
|
|
20300
|
+
async function apply(policy, planId, ctx) {
|
|
20301
|
+
const plan = policy.plan;
|
|
20302
|
+
if (!plan || plan.id !== planId || plan.expiresAt < Date.now())
|
|
20303
|
+
throw new Error("Preview expired or changed. Preview again before confirming.");
|
|
20304
|
+
access(ctx, "apply_service_routing", true);
|
|
20305
|
+
if (fingerprint(await facts(policy, ctx)) !== plan.fingerprint)
|
|
20306
|
+
throw new Error("Router configuration changed after preview.");
|
|
20307
|
+
const safe = getSafeModeManager2(policy.device);
|
|
20308
|
+
if (safe.isActive)
|
|
20309
|
+
throw new Error("Finish the existing Safe Mode session first.");
|
|
20310
|
+
policy.snapshot = await captureSnapshot(ctx, `Before service route ${policy.name}`, true);
|
|
20311
|
+
policy.state = "uncertain";
|
|
20312
|
+
policy.armedUntil = undefined;
|
|
20313
|
+
await save(policy, "Apply started; outcome must be read back before being considered active.");
|
|
20314
|
+
let owned = false, commitAttempted = false;
|
|
20315
|
+
try {
|
|
20316
|
+
if (!(await safe.enable()).startsWith("Safe mode ENABLED"))
|
|
20317
|
+
throw new Error("Could not acquire Safe Mode.");
|
|
20318
|
+
owned = true;
|
|
20319
|
+
if (fingerprint(await facts(policy, ctx)) !== plan.fingerprint)
|
|
20320
|
+
throw new Error("Router changed while entering Safe Mode.");
|
|
20321
|
+
for (const command of plan.commands)
|
|
20322
|
+
await checkedRead(command, ctx);
|
|
20323
|
+
const after = await facts(policy, ctx);
|
|
20324
|
+
const matched = after.mangle.filter((r) => r.comment === ownerTag(policy.id));
|
|
20325
|
+
if (plan.remove ? matched.length !== 0 : matched.filter((r) => r.action === "mark-routing" && r["new-routing-mark"] === plan.table && enabled3(r)).length !== 1)
|
|
20326
|
+
throw new Error("Router read-back did not match this preview.");
|
|
20327
|
+
if (plan.remove) {
|
|
20328
|
+
if (after.addresses.some((r) => r.comment === ownerTag(policy.id)))
|
|
20329
|
+
throw new Error("Owned address-list removal not confirmed.");
|
|
20330
|
+
if (after.dns?.some((r) => r.comment === ownerTag(policy.id)))
|
|
20331
|
+
throw new Error("Owned DNS entry removal not confirmed.");
|
|
20332
|
+
} else {
|
|
20333
|
+
planCommands({ ...policy, state: "active", activeTable: plan.table }, plan.table, after);
|
|
20334
|
+
}
|
|
20335
|
+
await checkedRead("/system identity print", ctx);
|
|
20336
|
+
commitAttempted = true;
|
|
20337
|
+
if (!(await safe.commit()).ok)
|
|
20338
|
+
throw new Error("Commit outcome uncertain. Do not replay the change.");
|
|
20339
|
+
owned = false;
|
|
20340
|
+
policy.state = plan.remove ? "removed" : "active";
|
|
20341
|
+
policy.activeTable = plan.remove ? undefined : plan.table;
|
|
20342
|
+
policy.lastSwitchAt = Date.now();
|
|
20343
|
+
policy.plan = undefined;
|
|
20344
|
+
policy.error = undefined;
|
|
20345
|
+
await save(policy, plan.remove ? "Owned routing policy removed." : `Routing read-back verified: ${plan.table}. Client delivery still requires a client check.`);
|
|
20346
|
+
routerRoutingInventory.clear();
|
|
20347
|
+
} catch (error) {
|
|
20348
|
+
routerRoutingInventory.clear();
|
|
20349
|
+
if (owned && !commitAttempted)
|
|
20350
|
+
await safe.rollback().catch(() => {});
|
|
20351
|
+
policy.error = error instanceof Error ? error.message : "Apply failed";
|
|
20352
|
+
await save(policy, "Apply not confirmed; automation stopped. Inspect the saved backup and router state.");
|
|
20353
|
+
throw error;
|
|
20354
|
+
}
|
|
20355
|
+
return policy;
|
|
20356
|
+
}
|
|
20357
|
+
async function applyRouting(id, planId, confirm, ctx) {
|
|
20358
|
+
const device = access(ctx, "apply_service_routing", true);
|
|
20359
|
+
if (!confirm)
|
|
20360
|
+
throw new Error("Explicit confirmation of the exact preview is required.");
|
|
20361
|
+
return locked(device, async () => apply(await routingPolicy(id, device), planId, ctx));
|
|
20362
|
+
}
|
|
20363
|
+
async function armRouting(id, minutes, confirm, ctx) {
|
|
20364
|
+
const device = access(ctx, "arm_service_routing", true);
|
|
20365
|
+
if (!confirm)
|
|
20366
|
+
throw new Error("Confirm the time-limited automatic failover authorization.");
|
|
20367
|
+
if (!Number.isInteger(minutes) || minutes < 0 || minutes > 60)
|
|
20368
|
+
throw new Error("Authorization must be 0\u201360 minutes.");
|
|
20369
|
+
return locked(device, async () => {
|
|
20370
|
+
const policy = await routingPolicy(id, device);
|
|
20371
|
+
if (minutes) {
|
|
20372
|
+
if (!policy.target)
|
|
20373
|
+
throw new Error("Automatic failover requires an approved HTTPS probe; this is a manual domain route.");
|
|
20374
|
+
const other = (await operationsStore()).list(kind, device).some((p) => p.id !== id && (p.armedUntil ?? 0) > Date.now());
|
|
20375
|
+
if (other)
|
|
20376
|
+
throw new Error("Only one automatic service policy per router can be armed at a time.");
|
|
20377
|
+
if (policy.state !== "active" || policy.tables.length < 2)
|
|
20378
|
+
throw new Error("Apply a policy with at least two exits first.");
|
|
20379
|
+
const now = Date.now();
|
|
20380
|
+
if (policy.tables.some((t) => !policy.samples.some((s) => s.table === t && s.state === "pass" && now - s.at < 120000)))
|
|
20381
|
+
throw new Error("Every authorized exit needs a fresh passing VRF probe before arming.");
|
|
20382
|
+
}
|
|
20383
|
+
policy.armedUntil = minutes ? Date.now() + minutes * 60000 : undefined;
|
|
20384
|
+
await save(policy, minutes ? `Automatic failover authorized for ${minutes} minutes, only between the saved exits.` : "Automatic failover paused; the current route stays in place.");
|
|
20385
|
+
return policy;
|
|
20386
|
+
});
|
|
20387
|
+
}
|
|
20388
|
+
|
|
20389
|
+
// src/tools/service-routing.ts
|
|
20390
|
+
var serviceRoutingTools = [
|
|
20391
|
+
defineTool2({
|
|
20392
|
+
name: "list_service_routing",
|
|
20393
|
+
title: "List Service Routing Policies",
|
|
20394
|
+
annotations: READ,
|
|
20395
|
+
description: "Read persistent domain routing policies, path evidence, primary exit, history and authorization expiry for this router. No probes or router changes.",
|
|
20396
|
+
inputSchema: {},
|
|
20397
|
+
async handler(_, ctx) {
|
|
20398
|
+
return JSON.stringify(await listRouting(ctx));
|
|
20399
|
+
}
|
|
20400
|
+
}),
|
|
20401
|
+
defineTool2({
|
|
20402
|
+
name: "service_routing_inventory",
|
|
20403
|
+
title: "Inspect Router Routing Configuration",
|
|
20404
|
+
annotations: READ,
|
|
20405
|
+
description: "Read live IPv4/IPv6 routes, ordered mangle and routing rules, address lists, tables, VRFs and filter rules independently of saved MCP policies. Includes dynamic/disabled entries, per-section failures and observation timestamps; bounded reads, 20-second cache. Missing data is not zero. Also lists enabled FIB exits and approved HTTPS aliases. Table presence is not path health; HTTPS exit probes require a matching VRF. No router changes.",
|
|
20406
|
+
inputSchema: {},
|
|
20407
|
+
async handler(_, ctx) {
|
|
20408
|
+
return JSON.stringify(await routingInventory(ctx));
|
|
20409
|
+
}
|
|
20410
|
+
}),
|
|
20411
|
+
defineTool2({
|
|
20412
|
+
name: "service_routing_address_page",
|
|
20413
|
+
title: "Read Routing Address List Page",
|
|
20414
|
+
annotations: READ,
|
|
20415
|
+
description: "Read the next bounded page of this router's IPv4 or IPv6 address-list members. Use nextOffset from service_routing_inventory or the preceding page. At most 200 rows per request; live lists may change between pages. Read-only, no router changes.",
|
|
20416
|
+
inputSchema: {
|
|
20417
|
+
family: _enum(["ipv4", "ipv6"]),
|
|
20418
|
+
offset: number().int().min(0).max(1e6).default(0)
|
|
20419
|
+
},
|
|
20420
|
+
async handler(a, ctx) {
|
|
20421
|
+
return JSON.stringify(await routingAddressPage(a.family, a.offset, ctx));
|
|
20422
|
+
}
|
|
20423
|
+
}),
|
|
20424
|
+
defineTool2({
|
|
20425
|
+
name: "service_routing_traffic",
|
|
20426
|
+
title: "Read Service Routing Traffic",
|
|
20427
|
+
annotations: READ,
|
|
20428
|
+
description: "Read the exact active MCP-owned routing mark's client-to-service byte and packet counters for one saved policy. Decimal strings preserve 64-bit totals. Four-second cache; missing, disabled or modified rules are unavailable, not zero. Excludes return/download traffic and does not prove delivery, DNS coverage or billing usage. No reset or router change.",
|
|
20429
|
+
inputSchema: { id: uuid2() },
|
|
20430
|
+
async handler(a, ctx) {
|
|
20431
|
+
return JSON.stringify(await routingTraffic(a.id, ctx));
|
|
20432
|
+
}
|
|
20433
|
+
}),
|
|
20434
|
+
defineTool2({
|
|
20435
|
+
name: "create_service_routing",
|
|
20436
|
+
title: "Create Service Routing Draft",
|
|
20437
|
+
annotations: WRITE,
|
|
20438
|
+
description: "Save a single-family exact domain or *.example.com route for explicit client subnets. The wildcard excludes the apex and requires client DNS through this router, existing remote DNS, RouterOS 7.17+ and dnsLearningConfirmed. Wildcard FWD bypasses adlists for matching DNS queries. HTTPS target is optional for manual routing, required for health probes/failover; when domain is absent use the approved target's host (legacy). Shared CDN IPs can affect other services. No router change until preview and explicit apply. Never infer authorization from a draft.",
|
|
20439
|
+
inputSchema: routingInput.shape,
|
|
20440
|
+
async handler(a, ctx) {
|
|
20441
|
+
return JSON.stringify(await createRouting(a, ctx));
|
|
20442
|
+
}
|
|
20443
|
+
}),
|
|
20444
|
+
defineTool2({
|
|
20445
|
+
name: "probe_service_routing",
|
|
20446
|
+
title: "Probe Service Exits",
|
|
20447
|
+
annotations: READ,
|
|
20448
|
+
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.",
|
|
20449
|
+
inputSchema: { id: uuid2() },
|
|
20450
|
+
async handler(a, ctx) {
|
|
20451
|
+
return JSON.stringify(await probeRouting(a.id, ctx));
|
|
20452
|
+
}
|
|
20453
|
+
}),
|
|
20454
|
+
defineTool2({
|
|
20455
|
+
name: "preview_service_routing",
|
|
20456
|
+
title: "Preview Service Routing Change",
|
|
20457
|
+
annotations: READ,
|
|
20458
|
+
description: "Read router state and save a two-minute state-bound preview for applying/switching or removing owned rules. Reject FastTrack, overlapping wildcard DNS and foreign routing conflicts unless before-existing precedence was explicitly selected. Wildcard plans add an owned DNS FWD learner, not DNS interception. Does not create exits, NAT or change the router until apply.",
|
|
20459
|
+
inputSchema: {
|
|
20460
|
+
id: uuid2(),
|
|
20461
|
+
table: string().min(1).max(64),
|
|
20462
|
+
remove: boolean().default(false)
|
|
20463
|
+
},
|
|
20464
|
+
async handler(a, ctx) {
|
|
20465
|
+
return JSON.stringify(await previewRouting(a.id, a.table, a.remove, ctx));
|
|
20466
|
+
}
|
|
20467
|
+
}),
|
|
20468
|
+
defineTool2({
|
|
20469
|
+
name: "apply_service_routing",
|
|
20470
|
+
title: "Apply Approved Service Routing Preview",
|
|
20471
|
+
annotations: WRITE,
|
|
20472
|
+
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.",
|
|
20473
|
+
inputSchema: { id: uuid2(), planId: uuid2(), confirm: boolean().default(false) },
|
|
20474
|
+
async handler(a, ctx) {
|
|
20475
|
+
return JSON.stringify(await applyRouting(a.id, a.planId, a.confirm, ctx));
|
|
20476
|
+
}
|
|
20477
|
+
}),
|
|
20478
|
+
defineTool2({
|
|
20479
|
+
name: "arm_service_routing",
|
|
20480
|
+
title: "Authorize Time-Limited Service Failover",
|
|
20481
|
+
annotations: WRITE,
|
|
20482
|
+
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.",
|
|
20483
|
+
inputSchema: {
|
|
20484
|
+
id: uuid2(),
|
|
20485
|
+
minutes: number().int().min(0).max(60),
|
|
20486
|
+
confirm: boolean().default(false)
|
|
20487
|
+
},
|
|
20488
|
+
async handler(a, ctx) {
|
|
20489
|
+
return JSON.stringify(await armRouting(a.id, a.minutes, a.confirm, ctx));
|
|
20490
|
+
}
|
|
20491
|
+
})
|
|
20492
|
+
];
|
|
20493
|
+
|
|
20494
|
+
// src/flight-recorder/model.ts
|
|
20495
|
+
var recorderInput = object({
|
|
20496
|
+
enabled: boolean(),
|
|
20497
|
+
intervalSeconds: number().int().min(30).max(300).default(60),
|
|
20498
|
+
windowMinutes: number().int().min(15).max(360).default(60),
|
|
20499
|
+
retentionDays: number().int().min(1).max(30).default(7)
|
|
20500
|
+
});
|
|
20501
|
+
function blankFlight(device, now) {
|
|
20502
|
+
return {
|
|
20503
|
+
id: device,
|
|
20504
|
+
device,
|
|
20505
|
+
updatedAt: now,
|
|
20506
|
+
enabled: false,
|
|
20507
|
+
intervalSeconds: 60,
|
|
20508
|
+
windowMinutes: 60,
|
|
20509
|
+
retentionDays: 7,
|
|
20510
|
+
samples: [],
|
|
20511
|
+
events: [],
|
|
20512
|
+
incidents: [],
|
|
20513
|
+
seenLogs: []
|
|
20514
|
+
};
|
|
20515
|
+
}
|
|
20516
|
+
function trimFlight(record, now) {
|
|
20517
|
+
const since = now - record.windowMinutes * 60000;
|
|
20518
|
+
record.samples = record.samples.filter((s) => s.at >= since).slice(-720);
|
|
20519
|
+
record.events = record.events.filter((s) => s.at >= since).slice(-500);
|
|
20520
|
+
record.seenLogs = record.seenLogs.slice(-500);
|
|
20521
|
+
record.incidents = record.incidents.filter((i) => i.at >= now - record.retentionDays * 86400000).slice(-30);
|
|
20522
|
+
for (const i of record.incidents) {
|
|
20523
|
+
i.samples = i.samples.slice(-720);
|
|
20524
|
+
i.events = i.events.slice(-500);
|
|
20525
|
+
i.complete = now >= i.until || !record.enabled;
|
|
20526
|
+
}
|
|
20527
|
+
record.updatedAt = now;
|
|
20528
|
+
return record;
|
|
20529
|
+
}
|
|
20530
|
+
function freezeFlight(record, title, trigger, now) {
|
|
20531
|
+
const incident = {
|
|
20532
|
+
id: crypto.randomUUID(),
|
|
20533
|
+
at: now,
|
|
20534
|
+
until: record.enabled ? now + 120000 : now,
|
|
20535
|
+
title,
|
|
20536
|
+
trigger,
|
|
20537
|
+
samples: structuredClone(record.samples),
|
|
20538
|
+
events: structuredClone(record.events),
|
|
20539
|
+
complete: !record.enabled
|
|
20540
|
+
};
|
|
20541
|
+
record.incidents.push(incident);
|
|
20542
|
+
return incident;
|
|
20543
|
+
}
|
|
20544
|
+
|
|
20545
|
+
// src/flight-recorder/service.ts
|
|
20546
|
+
var kind2 = "flight-recorder";
|
|
20547
|
+
var queues = new Map;
|
|
20548
|
+
function access2(ctx, tool, write = false) {
|
|
20549
|
+
const device = resolveDeviceName2(ctx.device);
|
|
20550
|
+
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
20551
|
+
return device;
|
|
20552
|
+
}
|
|
20553
|
+
async function record2(device) {
|
|
20554
|
+
return (await operationsStore()).get(kind2, device, device) ?? blankFlight(device, Date.now());
|
|
20555
|
+
}
|
|
20556
|
+
async function edit(device, work) {
|
|
20557
|
+
const task = (queues.get(device) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
|
20558
|
+
const store = await operationsStore(), owner = crypto.randomUUID(), key = `flight:${device}`;
|
|
20559
|
+
store.lock(key, owner);
|
|
20560
|
+
try {
|
|
20561
|
+
const r = await record2(device), result = await work(r);
|
|
20562
|
+
store.put(kind2, trimFlight(r, Date.now()));
|
|
20563
|
+
return result;
|
|
20564
|
+
} finally {
|
|
20565
|
+
store.unlock(key, owner);
|
|
20566
|
+
}
|
|
20567
|
+
});
|
|
20568
|
+
queues.set(device, task);
|
|
20569
|
+
try {
|
|
20570
|
+
return await task;
|
|
20571
|
+
} finally {
|
|
20572
|
+
if (queues.get(device) === task)
|
|
20573
|
+
queues.delete(device);
|
|
20574
|
+
}
|
|
20575
|
+
}
|
|
20576
|
+
async function getFlight(ctx) {
|
|
20577
|
+
const device = access2(ctx, "get_flight_recorder");
|
|
20578
|
+
return {
|
|
20579
|
+
recorder: trimFlight(await record2(device), Date.now()),
|
|
20580
|
+
toolEventsAvailable: isRecording(),
|
|
20581
|
+
limitations: [
|
|
20582
|
+
"SSH-polled log metadata, not a lossless syslog receiver.",
|
|
20583
|
+
"Receive-time correlation is not proof of cause or actor identity.",
|
|
20584
|
+
"No capture while MCP is stopped; missing observations are not healthy samples."
|
|
20585
|
+
]
|
|
20586
|
+
};
|
|
20587
|
+
}
|
|
20588
|
+
async function configureFlight(input, ctx) {
|
|
20589
|
+
const device = access2(ctx, "configure_flight_recorder", true), a = recorderInput.parse(input);
|
|
20590
|
+
await edit(device, async (r) => {
|
|
20591
|
+
Object.assign(r, a);
|
|
20592
|
+
r.error = undefined;
|
|
20593
|
+
});
|
|
20594
|
+
return getFlight(ctx);
|
|
20595
|
+
}
|
|
20596
|
+
async function freezeIncident(title, ctx) {
|
|
20597
|
+
const device = access2(ctx, "freeze_network_incident", true);
|
|
20598
|
+
if (!title.trim() || title.length > 120)
|
|
20599
|
+
throw new Error("Use a 1\u2013120 character incident title.");
|
|
20600
|
+
await edit(device, async (r) => {
|
|
20601
|
+
freezeFlight(r, title.trim(), "manual", Date.now());
|
|
20602
|
+
});
|
|
20603
|
+
return getFlight(ctx);
|
|
20604
|
+
}
|
|
20605
|
+
async function exportIncident(id, ctx) {
|
|
20606
|
+
const device = access2(ctx, "export_network_incident"), r = await record2(device);
|
|
20607
|
+
const incident = trimFlight(r, Date.now()).incidents.find((i) => i.id === id);
|
|
20608
|
+
if (!incident)
|
|
20609
|
+
throw new Error("Incident not found on the selected router or retention expired.");
|
|
20610
|
+
return {
|
|
20611
|
+
format: "mikrotik-flight-recorder/v1",
|
|
20612
|
+
device,
|
|
20613
|
+
exportedAt: Date.now(),
|
|
20614
|
+
incident,
|
|
20615
|
+
privacy: "Review device/interface names before sharing. Raw logs, commands, arguments and credentials are excluded.",
|
|
20616
|
+
interpretation: "Chronology is receipt time on the MCP host. Correlation is not causation; routerTime is untrusted, uncorrected router text."
|
|
20617
|
+
};
|
|
20618
|
+
}
|
|
20619
|
+
|
|
20620
|
+
// src/tools/flight-recorder.ts
|
|
20621
|
+
var flightRecorderTools = [
|
|
20622
|
+
defineTool2({
|
|
20623
|
+
name: "get_flight_recorder",
|
|
20624
|
+
title: "Read Network Flight Recorder",
|
|
20625
|
+
annotations: READ,
|
|
20626
|
+
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.",
|
|
20627
|
+
inputSchema: {},
|
|
20628
|
+
async handler(_, ctx) {
|
|
20629
|
+
return JSON.stringify(await getFlight(ctx));
|
|
20630
|
+
}
|
|
20631
|
+
}),
|
|
20632
|
+
defineTool2({
|
|
20633
|
+
name: "configure_flight_recorder",
|
|
20634
|
+
title: "Configure Network Flight Recorder",
|
|
20635
|
+
annotations: WRITE,
|
|
20636
|
+
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.",
|
|
20637
|
+
inputSchema: recorderInput.shape,
|
|
20638
|
+
async handler(a, ctx) {
|
|
20639
|
+
return JSON.stringify(await configureFlight(a, ctx));
|
|
20640
|
+
}
|
|
20641
|
+
}),
|
|
20642
|
+
defineTool2({
|
|
20643
|
+
name: "freeze_network_incident",
|
|
20644
|
+
title: "Freeze Network Incident Evidence",
|
|
20645
|
+
annotations: WRITE,
|
|
20646
|
+
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.",
|
|
20647
|
+
inputSchema: { title: string().trim().min(1).max(120) },
|
|
20648
|
+
async handler(a, ctx) {
|
|
20649
|
+
return JSON.stringify(await freezeIncident(a.title, ctx));
|
|
20650
|
+
}
|
|
20651
|
+
}),
|
|
20652
|
+
defineTool2({
|
|
20653
|
+
name: "export_network_incident",
|
|
20654
|
+
title: "Export Network Incident Evidence",
|
|
20655
|
+
annotations: READ,
|
|
20656
|
+
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.",
|
|
20657
|
+
inputSchema: { id: uuid2() },
|
|
20658
|
+
async handler(a, ctx) {
|
|
20659
|
+
return JSON.stringify(await exportIncident(a.id, ctx));
|
|
20660
|
+
}
|
|
20661
|
+
})
|
|
20662
|
+
];
|
|
20663
|
+
|
|
20664
|
+
// src/recovery-lab/model.ts
|
|
20665
|
+
import { createHash as createHash6 } from "crypto";
|
|
20666
|
+
var rosVersion = string().regex(/^7\.\d+(?:\.\d+)?(?:beta\d+|rc\d+)?$/);
|
|
20667
|
+
var recoveryInput = object({
|
|
20668
|
+
snapshotId: string().min(1).max(100),
|
|
20669
|
+
version: rosVersion,
|
|
20670
|
+
mode: _enum(["restore", "upgrade"]).default("restore")
|
|
20671
|
+
});
|
|
20672
|
+
var REQUIRED_CHECKS = [
|
|
20673
|
+
"authenticated-boot",
|
|
20674
|
+
"import",
|
|
20675
|
+
"configuration-readback",
|
|
20676
|
+
"reboot-persistence",
|
|
20677
|
+
"isolation"
|
|
20678
|
+
];
|
|
20679
|
+
var capabilitiesSchema = object({
|
|
20680
|
+
protocol: literal("mikrotik-recovery/v1"),
|
|
20681
|
+
runnerId: string().regex(/^[a-zA-Z0-9_.-]{1,80}$/),
|
|
20682
|
+
isolated: literal(true),
|
|
20683
|
+
productionNetworkAccess: literal(false),
|
|
20684
|
+
disposable: literal(true),
|
|
20685
|
+
enforcesTtl: literal(true),
|
|
20686
|
+
versions: array(object({
|
|
20687
|
+
version: rosVersion,
|
|
20688
|
+
imageSha256: string().regex(/^[a-f0-9]{64}$/),
|
|
20689
|
+
architecture: _enum(["x86_64", "aarch64"])
|
|
20690
|
+
})).min(1).max(30).refine((versions) => new Set(versions.map((v) => v.version)).size === versions.length, {
|
|
20691
|
+
message: "Each RouterOS version must identify one unambiguous pinned image."
|
|
20692
|
+
})
|
|
20693
|
+
});
|
|
20694
|
+
var resultSchema = object({
|
|
20695
|
+
protocol: literal("mikrotik-recovery/v1"),
|
|
20696
|
+
id: uuid2(),
|
|
20697
|
+
requestSha256: string().regex(/^[a-f0-9]{64}$/),
|
|
20698
|
+
runnerId: string().min(1).max(80),
|
|
20699
|
+
version: rosVersion,
|
|
20700
|
+
state: _enum(["running", "completed", "failed", "destroyed"]),
|
|
20701
|
+
isolated: literal(true),
|
|
20702
|
+
productionNetworkAccess: literal(false),
|
|
20703
|
+
checks: array(object({
|
|
20704
|
+
name: _enum(REQUIRED_CHECKS),
|
|
20705
|
+
state: _enum(["pass", "fail", "unsupported", "pending"]),
|
|
20706
|
+
detail: string().max(500)
|
|
20707
|
+
})).max(5),
|
|
20708
|
+
elapsedMs: number().int().min(0).max(3600000).optional(),
|
|
20709
|
+
cleanup: _enum(["pending", "destroyed", "failed"])
|
|
20710
|
+
});
|
|
20711
|
+
var sha256 = (value) => createHash6("sha256").update(value).digest("hex");
|
|
20712
|
+
var FIELDS = {
|
|
20713
|
+
"/interface/bridge": ["name", "protocol-mode", "vlan-filtering", "pvid", "disabled"],
|
|
20714
|
+
"/interface/vlan": ["name", "interface", "vlan-id", "disabled"],
|
|
20715
|
+
"/interface/bridge/port": [
|
|
20716
|
+
"bridge",
|
|
20717
|
+
"interface",
|
|
20718
|
+
"pvid",
|
|
20719
|
+
"ingress-filtering",
|
|
20720
|
+
"frame-types",
|
|
20721
|
+
"disabled"
|
|
20722
|
+
],
|
|
20723
|
+
"/interface/bridge/vlan": ["bridge", "tagged", "untagged", "vlan-ids", "disabled"],
|
|
20724
|
+
"/interface/list": ["name", "include", "exclude"],
|
|
20725
|
+
"/interface/list/member": ["list", "interface", "disabled"],
|
|
20726
|
+
"/ip/address": ["address", "interface", "network", "disabled"],
|
|
20727
|
+
"/ipv6/address": ["address", "interface", "advertise", "disabled"],
|
|
20728
|
+
"/ip/route": [
|
|
20729
|
+
"dst-address",
|
|
20730
|
+
"gateway",
|
|
20731
|
+
"distance",
|
|
20732
|
+
"routing-table",
|
|
20733
|
+
"scope",
|
|
20734
|
+
"target-scope",
|
|
20735
|
+
"disabled",
|
|
20736
|
+
"blackhole"
|
|
20737
|
+
],
|
|
20738
|
+
"/ipv6/route": [
|
|
20739
|
+
"dst-address",
|
|
20740
|
+
"gateway",
|
|
20741
|
+
"distance",
|
|
20742
|
+
"routing-table",
|
|
20743
|
+
"scope",
|
|
20744
|
+
"target-scope",
|
|
20745
|
+
"disabled",
|
|
20746
|
+
"blackhole"
|
|
20747
|
+
],
|
|
20748
|
+
"/routing/table": ["name", "fib", "disabled"],
|
|
20749
|
+
"/ip/firewall/filter": [
|
|
20750
|
+
"chain",
|
|
20751
|
+
"action",
|
|
20752
|
+
"protocol",
|
|
20753
|
+
"src-address",
|
|
20754
|
+
"dst-address",
|
|
20755
|
+
"src-port",
|
|
20756
|
+
"dst-port",
|
|
20757
|
+
"connection-state",
|
|
20758
|
+
"in-interface",
|
|
20759
|
+
"out-interface",
|
|
20760
|
+
"in-interface-list",
|
|
20761
|
+
"out-interface-list",
|
|
20762
|
+
"disabled"
|
|
20763
|
+
],
|
|
20764
|
+
"/ipv6/firewall/filter": [
|
|
20765
|
+
"chain",
|
|
20766
|
+
"action",
|
|
20767
|
+
"protocol",
|
|
20768
|
+
"src-address",
|
|
20769
|
+
"dst-address",
|
|
20770
|
+
"src-port",
|
|
20771
|
+
"dst-port",
|
|
20772
|
+
"connection-state",
|
|
20773
|
+
"in-interface",
|
|
20774
|
+
"out-interface",
|
|
20775
|
+
"in-interface-list",
|
|
20776
|
+
"out-interface-list",
|
|
20777
|
+
"disabled"
|
|
20778
|
+
]
|
|
20779
|
+
};
|
|
20780
|
+
function buildRecoverySubset(body) {
|
|
20781
|
+
if (body.length > 512000)
|
|
20782
|
+
throw new Error("Snapshot exceeds the 512 KB rehearsal limit.");
|
|
20783
|
+
const model = parseExport(body), commands = [], coverage = [];
|
|
20784
|
+
for (const section of model.sections) {
|
|
20785
|
+
const allowed = FIELDS[section.path];
|
|
20786
|
+
let included = 0, excluded = 0;
|
|
20787
|
+
for (const row of section.records) {
|
|
20788
|
+
const fields = Object.entries(row.fields).filter(([key]) => key !== "comment");
|
|
20789
|
+
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) {
|
|
20790
|
+
excluded++;
|
|
20791
|
+
continue;
|
|
20792
|
+
}
|
|
20793
|
+
let cmd = new Cmd(`${section.path.replaceAll("/", " ").trimStart().replace(/^/, "/")} add`);
|
|
20794
|
+
for (const [key, value] of fields)
|
|
20795
|
+
cmd = cmd.set(key, value);
|
|
20796
|
+
commands.push(cmd.build());
|
|
20797
|
+
included++;
|
|
20798
|
+
}
|
|
20799
|
+
coverage.push({
|
|
20800
|
+
scope: section.path,
|
|
20801
|
+
included,
|
|
20802
|
+
excluded,
|
|
20803
|
+
reason: excluded ? "Unsupported scope, operation, field or expression: not sent to the lab." : undefined
|
|
20804
|
+
});
|
|
20805
|
+
}
|
|
20806
|
+
if (model.unparsed.length)
|
|
20807
|
+
coverage.push({
|
|
20808
|
+
scope: "unparsed lines",
|
|
20809
|
+
included: 0,
|
|
20810
|
+
excluded: model.unparsed.length,
|
|
20811
|
+
reason: "Unparsed text is never executed."
|
|
20812
|
+
});
|
|
20813
|
+
if (commands.length > 300)
|
|
20814
|
+
throw new Error("More than 300 portable records. Prepare a smaller reviewed snapshot.");
|
|
20815
|
+
return { commands, coverage };
|
|
20816
|
+
}
|
|
20817
|
+
function validateRunnerResult(input, run) {
|
|
20818
|
+
const result = resultSchema.parse(input);
|
|
20819
|
+
if (result.id !== run.id || result.runnerId !== run.runnerId || result.requestSha256 !== run.requestSha256 || result.version !== run.version)
|
|
20820
|
+
throw new Error("Runner evidence does not match this immutable rehearsal.");
|
|
20821
|
+
if (new Set(result.checks.map((c) => c.name)).size !== result.checks.length)
|
|
20822
|
+
throw new Error("Duplicate runner checks are not valid evidence.");
|
|
20823
|
+
if (result.state === "destroyed" && result.cleanup !== "destroyed")
|
|
20824
|
+
throw new Error("Destruction is not confirmed.");
|
|
20825
|
+
return result;
|
|
20826
|
+
}
|
|
20827
|
+
function resultState(result) {
|
|
20828
|
+
if (result.state === "destroyed")
|
|
20829
|
+
return "destroyed";
|
|
20830
|
+
if (result.state === "failed" || result.checks.some((c) => c.state === "fail"))
|
|
20831
|
+
return "failed";
|
|
20832
|
+
if (result.state === "running")
|
|
20833
|
+
return "running";
|
|
20834
|
+
return REQUIRED_CHECKS.every((name) => result.checks.some((c) => c.name === name && c.state === "pass")) ? "passed" : "uncertain";
|
|
20835
|
+
}
|
|
20836
|
+
|
|
20837
|
+
// src/recovery-lab/runner.ts
|
|
20838
|
+
function runnerConfig() {
|
|
20839
|
+
const value = process.env.MIKROTIK_RECOVERY_RUNNER_URL;
|
|
20840
|
+
const token = process.env.MIKROTIK_RECOVERY_RUNNER_TOKEN;
|
|
20841
|
+
if (!value && !token)
|
|
20842
|
+
return;
|
|
20843
|
+
if (!value || !token || token.length < 24 || /[\r\n]/.test(token))
|
|
20844
|
+
throw new Error("Recovery runner URL and a token of at least 24 characters must be configured by the administrator.");
|
|
20845
|
+
const url = new URL(value);
|
|
20846
|
+
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)))
|
|
20847
|
+
throw new Error("Recovery runner needs an HTTPS origin (or explicit loopback HTTP), without path, query or URL credentials.");
|
|
20848
|
+
return { base: url.origin, token, binding: sha256(`${url.origin}
|
|
20849
|
+
${token}`) };
|
|
20850
|
+
}
|
|
20851
|
+
async function callRunner(method, path, body) {
|
|
20852
|
+
const cfg = runnerConfig();
|
|
20853
|
+
if (!cfg)
|
|
20854
|
+
throw new Error("No isolated recovery runner configured. Prepare and inspect locally; execution is unavailable.");
|
|
20855
|
+
if (!/^\/v1\/(capabilities|runs\/[a-f0-9-]{36})$/.test(path))
|
|
20856
|
+
throw new Error("Invalid runner operation.");
|
|
20857
|
+
if (method === "GET" && body !== undefined)
|
|
20858
|
+
throw new Error("Read-only runner operations cannot contain a request body.");
|
|
20859
|
+
const options = {
|
|
20860
|
+
method,
|
|
20861
|
+
headers: { authorization: `Bearer ${cfg.token}`, "content-type": "application/json" },
|
|
20862
|
+
redirect: "error",
|
|
20863
|
+
signal: AbortSignal.timeout(1e4)
|
|
20864
|
+
};
|
|
20865
|
+
if (method !== "GET" && body !== undefined)
|
|
20866
|
+
options.body = JSON.stringify(body);
|
|
20867
|
+
const response = await fetch(`${cfg.base}${path}`, options);
|
|
20868
|
+
if (!response.ok) {
|
|
20869
|
+
await response.body?.cancel();
|
|
20870
|
+
throw new Error(`Recovery runner returned HTTP ${response.status}; no automatic write retry.`);
|
|
20871
|
+
}
|
|
20872
|
+
const reader = response.body?.getReader();
|
|
20873
|
+
if (!reader)
|
|
20874
|
+
throw new Error("Runner returned no evidence.");
|
|
20875
|
+
const chunks = [];
|
|
20876
|
+
let size = 0;
|
|
20877
|
+
try {
|
|
20878
|
+
while (true) {
|
|
20879
|
+
const part = await reader.read();
|
|
20880
|
+
if (part.done)
|
|
20881
|
+
break;
|
|
20882
|
+
size += part.value.length;
|
|
20883
|
+
if (size > 65536)
|
|
20884
|
+
throw new Error("Runner evidence exceeds the 64 KB limit.");
|
|
20885
|
+
chunks.push(part.value);
|
|
20886
|
+
}
|
|
20887
|
+
} finally {
|
|
20888
|
+
await reader.cancel().catch(() => {});
|
|
20889
|
+
}
|
|
20890
|
+
const data = new Uint8Array(size);
|
|
20891
|
+
let offset = 0;
|
|
20892
|
+
for (const part of chunks) {
|
|
20893
|
+
data.set(part, offset);
|
|
20894
|
+
offset += part.length;
|
|
20895
|
+
}
|
|
20896
|
+
return JSON.parse(new TextDecoder().decode(data));
|
|
20897
|
+
}
|
|
20898
|
+
|
|
20899
|
+
// src/recovery-lab/service.ts
|
|
20900
|
+
var kind3 = "recovery-lab";
|
|
20901
|
+
function access3(ctx, tool, write = false) {
|
|
20902
|
+
const device = resolveDeviceName2(ctx.device);
|
|
20903
|
+
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
20904
|
+
return device;
|
|
20905
|
+
}
|
|
20906
|
+
async function getRecovery(ctx) {
|
|
20907
|
+
const device = access3(ctx, "get_recovery_lab");
|
|
20908
|
+
let configured = false, configurationError;
|
|
20909
|
+
try {
|
|
20910
|
+
configured = !!runnerConfig();
|
|
20911
|
+
} catch {
|
|
20912
|
+
configurationError = "Runner configuration is invalid; ask the administrator to check the URL/token.";
|
|
20913
|
+
}
|
|
20914
|
+
return {
|
|
20915
|
+
runs: (await operationsStore()).list(kind3, device),
|
|
20916
|
+
configured,
|
|
20917
|
+
configurationError
|
|
20918
|
+
};
|
|
20919
|
+
}
|
|
20920
|
+
async function recoveryInventory(ctx) {
|
|
20921
|
+
const device = access3(ctx, "recovery_lab_inventory"), store = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
20922
|
+
try {
|
|
20923
|
+
const snapshots = store.list(device, 50).map((s) => ({ id: s.id, at: s.ts, label: s.label, version: s.rosVersion }));
|
|
20924
|
+
const cfg = runnerConfig();
|
|
20925
|
+
return {
|
|
20926
|
+
snapshots,
|
|
20927
|
+
runner: cfg ? capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities")) : null
|
|
20928
|
+
};
|
|
20929
|
+
} finally {
|
|
20930
|
+
store.close();
|
|
20931
|
+
}
|
|
20932
|
+
}
|
|
20933
|
+
async function prepareRecovery(input, ctx) {
|
|
20934
|
+
const device = access3(ctx, "prepare_recovery_lab", true), a = recoveryInput.parse(input);
|
|
20935
|
+
const snapshots = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
20936
|
+
try {
|
|
20937
|
+
const source = snapshots.get(a.snapshotId);
|
|
20938
|
+
if (!source || source.device !== device)
|
|
20939
|
+
throw new Error("Snapshot not found on this router.");
|
|
20940
|
+
const subset = buildRecoverySubset(source.body), cfg = runnerConfig();
|
|
20941
|
+
const caps = cfg ? capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities")) : undefined;
|
|
20942
|
+
if (caps && !caps.versions.some((v) => v.version === a.version))
|
|
20943
|
+
throw new Error("Target version is not available as a pinned runner image.");
|
|
20944
|
+
if (a.mode === "upgrade" && (!source.rosVersion || caps && !caps.versions.some((v) => v.version === source.rosVersion)))
|
|
20945
|
+
throw new Error("Upgrade rehearsal requires a known source version and pinned source/target images.");
|
|
20946
|
+
const now = Date.now();
|
|
20947
|
+
const run = {
|
|
20948
|
+
id: crypto.randomUUID(),
|
|
20949
|
+
device,
|
|
20950
|
+
updatedAt: now,
|
|
20951
|
+
preparedAt: now,
|
|
20952
|
+
snapshotId: source.id,
|
|
20953
|
+
snapshotSha: sha256(source.body),
|
|
20954
|
+
snapshotAt: source.ts,
|
|
20955
|
+
sourceVersion: source.rosVersion,
|
|
20956
|
+
version: a.version,
|
|
20957
|
+
mode: a.mode,
|
|
20958
|
+
...subset,
|
|
20959
|
+
commandSha256: sha256(subset.commands.join(`
|
|
20960
|
+
`)),
|
|
20961
|
+
state: "prepared",
|
|
20962
|
+
runnerId: caps?.runnerId,
|
|
20963
|
+
runnerBinding: cfg?.binding,
|
|
20964
|
+
capabilitiesSha: caps ? sha256(JSON.stringify(caps)) : undefined
|
|
20965
|
+
};
|
|
20966
|
+
const store = await operationsStore();
|
|
20967
|
+
if (store.list(kind3, device).length >= 100)
|
|
20968
|
+
throw new Error("100 rehearsal records reached. Archive/export old evidence before creating more.");
|
|
20969
|
+
store.put(kind3, run);
|
|
20970
|
+
return run;
|
|
20971
|
+
} finally {
|
|
20972
|
+
snapshots.close();
|
|
20973
|
+
}
|
|
20974
|
+
}
|
|
20975
|
+
async function editRun(id, device, work) {
|
|
20976
|
+
const store = await operationsStore(), owner = crypto.randomUUID();
|
|
20977
|
+
store.lock(`lab:${device}`, owner);
|
|
20978
|
+
try {
|
|
20979
|
+
const r = store.get(kind3, id, device);
|
|
20980
|
+
if (!r)
|
|
20981
|
+
throw new Error("Rehearsal not found on this router.");
|
|
20982
|
+
return await work(r);
|
|
20983
|
+
} finally {
|
|
20984
|
+
store.unlock(`lab:${device}`, owner);
|
|
20985
|
+
}
|
|
20986
|
+
}
|
|
20987
|
+
async function save2(run) {
|
|
20988
|
+
run.updatedAt = Date.now();
|
|
20989
|
+
(await operationsStore()).put(kind3, run);
|
|
20990
|
+
}
|
|
20991
|
+
function boundRunner(run) {
|
|
20992
|
+
const cfg = runnerConfig();
|
|
20993
|
+
if (!cfg || cfg.binding !== run.runnerBinding)
|
|
20994
|
+
throw new Error("Runner changed or is unavailable. Never send an existing rehearsal to a different destination.");
|
|
20995
|
+
}
|
|
20996
|
+
async function startRecovery(id, confirm, ctx) {
|
|
20997
|
+
const device = access3(ctx, "start_recovery_lab", true);
|
|
20998
|
+
if (!confirm)
|
|
20999
|
+
throw new Error("Explicit confirmation is required to send the reviewed subset to the configured isolated runner.");
|
|
21000
|
+
return editRun(id, device, async (run) => {
|
|
21001
|
+
if (run.state !== "prepared")
|
|
21002
|
+
throw new Error("Already submitted or uncertain. Poll its existing ID; do not replay the write.");
|
|
21003
|
+
if (Date.now() - run.preparedAt > 600000)
|
|
21004
|
+
throw new Error("Preview expired; prepare a fresh rehearsal.");
|
|
21005
|
+
if (!run.commands.length)
|
|
21006
|
+
throw new Error("There are no portable records to rehearse.");
|
|
21007
|
+
boundRunner(run);
|
|
21008
|
+
const caps = capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities"));
|
|
21009
|
+
if (sha256(JSON.stringify(caps)) !== run.capabilitiesSha)
|
|
21010
|
+
throw new Error("Runner capabilities changed; prepare again.");
|
|
21011
|
+
const snapshots = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
21012
|
+
try {
|
|
21013
|
+
const source = snapshots.get(run.snapshotId);
|
|
21014
|
+
if (!source || source.device !== device || sha256(source.body) !== run.snapshotSha)
|
|
21015
|
+
throw new Error("Source snapshot changed or was removed.");
|
|
21016
|
+
} finally {
|
|
21017
|
+
snapshots.close();
|
|
21018
|
+
}
|
|
21019
|
+
const request = {
|
|
21020
|
+
protocol: "mikrotik-recovery/v1",
|
|
21021
|
+
id: run.id,
|
|
21022
|
+
mode: run.mode,
|
|
21023
|
+
version: run.version,
|
|
21024
|
+
sourceVersion: run.sourceVersion,
|
|
21025
|
+
images: caps.versions.filter((v) => v.version === run.version || run.mode === "upgrade" && v.version === run.sourceVersion),
|
|
21026
|
+
commands: run.commands,
|
|
21027
|
+
commandSha256: run.commandSha256,
|
|
21028
|
+
ttlSeconds: 900,
|
|
21029
|
+
network: { isolated: true, productionNetworkAccess: false },
|
|
21030
|
+
requirements: [
|
|
21031
|
+
"authenticated-boot",
|
|
21032
|
+
"import",
|
|
21033
|
+
"configuration-readback",
|
|
21034
|
+
"reboot-persistence",
|
|
21035
|
+
"isolation"
|
|
21036
|
+
]
|
|
21037
|
+
};
|
|
21038
|
+
run.requestSha256 = sha256(JSON.stringify(request));
|
|
21039
|
+
run.startedAt = Date.now();
|
|
21040
|
+
run.state = "uncertain";
|
|
21041
|
+
await save2(run);
|
|
21042
|
+
try {
|
|
21043
|
+
const result = validateRunnerResult(await callRunner("PUT", `/v1/runs/${run.id}`, {
|
|
21044
|
+
...request,
|
|
21045
|
+
requestSha256: run.requestSha256
|
|
21046
|
+
}), run);
|
|
21047
|
+
run.result = result;
|
|
21048
|
+
run.state = resultState(result);
|
|
21049
|
+
run.error = undefined;
|
|
21050
|
+
} catch {
|
|
21051
|
+
run.error = "Submission outcome is uncertain. Poll this run ID before any further action; no automatic retry was attempted.";
|
|
21052
|
+
}
|
|
21053
|
+
await save2(run);
|
|
21054
|
+
return run;
|
|
21055
|
+
});
|
|
21056
|
+
}
|
|
21057
|
+
async function pollRecovery(id, ctx) {
|
|
21058
|
+
const device = access3(ctx, "poll_recovery_lab");
|
|
21059
|
+
return editRun(id, device, async (run) => {
|
|
21060
|
+
if (!run.requestSha256)
|
|
21061
|
+
throw new Error("This rehearsal has not been submitted.");
|
|
21062
|
+
boundRunner(run);
|
|
21063
|
+
try {
|
|
21064
|
+
const result = validateRunnerResult(await callRunner("GET", `/v1/runs/${run.id}`), run);
|
|
21065
|
+
run.result = result;
|
|
21066
|
+
run.state = resultState(result);
|
|
21067
|
+
run.error = undefined;
|
|
21068
|
+
} catch {
|
|
21069
|
+
run.state = "uncertain";
|
|
21070
|
+
run.error = "Runner evidence unavailable or mismatched. Last-known results retained, not treated as fresh.";
|
|
21071
|
+
}
|
|
21072
|
+
await save2(run);
|
|
21073
|
+
return run;
|
|
21074
|
+
});
|
|
21075
|
+
}
|
|
21076
|
+
async function destroyRecovery(id, confirm, ctx) {
|
|
21077
|
+
const device = access3(ctx, "destroy_recovery_lab", true);
|
|
21078
|
+
if (!confirm)
|
|
21079
|
+
throw new Error("Confirm deletion of this disposable lab only.");
|
|
21080
|
+
return editRun(id, device, async (run) => {
|
|
21081
|
+
if (!run.requestSha256)
|
|
21082
|
+
throw new Error("This rehearsal has not been submitted.");
|
|
21083
|
+
boundRunner(run);
|
|
21084
|
+
run.state = "uncertain";
|
|
21085
|
+
await save2(run);
|
|
21086
|
+
try {
|
|
21087
|
+
const result = validateRunnerResult(await callRunner("DELETE", `/v1/runs/${run.id}`), run);
|
|
21088
|
+
run.result = result;
|
|
21089
|
+
if (result.state !== "destroyed" || result.cleanup !== "destroyed")
|
|
21090
|
+
throw new Error("Cleanup not confirmed");
|
|
21091
|
+
run.state = "destroyed";
|
|
21092
|
+
run.error = undefined;
|
|
21093
|
+
} catch {
|
|
21094
|
+
run.error = "Lab cleanup is not confirmed. Inspect the runner and poll this ID; production routers were not contacted.";
|
|
21095
|
+
}
|
|
21096
|
+
await save2(run);
|
|
21097
|
+
return run;
|
|
21098
|
+
});
|
|
21099
|
+
}
|
|
21100
|
+
|
|
21101
|
+
// src/tools/recovery-lab.ts
|
|
21102
|
+
var recoveryLabTools = [
|
|
21103
|
+
defineTool2({
|
|
21104
|
+
name: "get_recovery_lab",
|
|
21105
|
+
title: "Read Recovery Lab",
|
|
21106
|
+
annotations: READ,
|
|
21107
|
+
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.",
|
|
21108
|
+
inputSchema: {},
|
|
21109
|
+
async handler(_, ctx) {
|
|
21110
|
+
return JSON.stringify(await getRecovery(ctx));
|
|
21111
|
+
}
|
|
21112
|
+
}),
|
|
21113
|
+
defineTool2({
|
|
21114
|
+
name: "recovery_lab_inventory",
|
|
21115
|
+
title: "Inspect Recovery Lab Inputs",
|
|
21116
|
+
annotations: READ,
|
|
21117
|
+
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.",
|
|
21118
|
+
inputSchema: {},
|
|
21119
|
+
async handler(_, ctx) {
|
|
21120
|
+
return JSON.stringify(await recoveryInventory(ctx));
|
|
21121
|
+
}
|
|
21122
|
+
}),
|
|
21123
|
+
defineTool2({
|
|
21124
|
+
name: "prepare_recovery_lab",
|
|
21125
|
+
title: "Prepare Isolated Recovery Rehearsal",
|
|
21126
|
+
annotations: WRITE,
|
|
21127
|
+
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.",
|
|
21128
|
+
inputSchema: recoveryInput.shape,
|
|
21129
|
+
async handler(a, ctx) {
|
|
21130
|
+
return JSON.stringify(await prepareRecovery(a, ctx));
|
|
21131
|
+
}
|
|
21132
|
+
}),
|
|
21133
|
+
defineTool2({
|
|
21134
|
+
name: "start_recovery_lab",
|
|
21135
|
+
title: "Start Approved Recovery Rehearsal",
|
|
21136
|
+
annotations: WRITE,
|
|
21137
|
+
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.",
|
|
21138
|
+
inputSchema: { id: uuid2(), confirm: boolean().default(false) },
|
|
21139
|
+
async handler(a, ctx) {
|
|
21140
|
+
return JSON.stringify(await startRecovery(a.id, a.confirm, ctx));
|
|
21141
|
+
}
|
|
21142
|
+
}),
|
|
21143
|
+
defineTool2({
|
|
21144
|
+
name: "poll_recovery_lab",
|
|
21145
|
+
title: "Read Recovery Runner Evidence",
|
|
21146
|
+
annotations: READ,
|
|
21147
|
+
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.",
|
|
21148
|
+
inputSchema: { id: uuid2() },
|
|
21149
|
+
async handler(a, ctx) {
|
|
21150
|
+
return JSON.stringify(await pollRecovery(a.id, ctx));
|
|
21151
|
+
}
|
|
21152
|
+
}),
|
|
21153
|
+
defineTool2({
|
|
21154
|
+
name: "destroy_recovery_lab",
|
|
21155
|
+
title: "Destroy Owned Disposable Lab",
|
|
21156
|
+
annotations: DESTRUCTIVE,
|
|
21157
|
+
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.",
|
|
21158
|
+
inputSchema: { id: uuid2(), confirm: boolean().default(false) },
|
|
21159
|
+
async handler(a, ctx) {
|
|
21160
|
+
return JSON.stringify(await destroyRecovery(a.id, a.confirm, ctx));
|
|
21161
|
+
}
|
|
21162
|
+
})
|
|
21163
|
+
];
|
|
21164
|
+
|
|
19614
21165
|
// src/paths/round-trip.ts
|
|
19615
21166
|
var hop = object({
|
|
19616
21167
|
device: string().min(1).max(128),
|
|
@@ -19816,32 +21367,32 @@ var roundTripTools = [
|
|
|
19816
21367
|
|
|
19817
21368
|
// src/core/ui-resources.ts
|
|
19818
21369
|
import { readFileSync as readFileSync3 } from "fs";
|
|
19819
|
-
import { join as
|
|
21370
|
+
import { join as join4 } from "path";
|
|
19820
21371
|
import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
|
|
19821
21372
|
|
|
19822
21373
|
// src/paths.ts
|
|
19823
21374
|
import { existsSync as existsSync2 } from "fs";
|
|
19824
|
-
import { join as
|
|
21375
|
+
import { join as join3, dirname as dirname10 } from "path";
|
|
19825
21376
|
import { fileURLToPath } from "url";
|
|
19826
21377
|
var meta3 = import.meta;
|
|
19827
|
-
var HERE = meta3.dir ?? meta3.dirname ??
|
|
21378
|
+
var HERE = meta3.dir ?? meta3.dirname ?? dirname10(fileURLToPath(import.meta.url));
|
|
19828
21379
|
function findRoot(start) {
|
|
19829
21380
|
let dir = start;
|
|
19830
21381
|
for (let i = 0;i < 12; i++) {
|
|
19831
|
-
if (existsSync2(
|
|
21382
|
+
if (existsSync2(join3(dir, "package.json")))
|
|
19832
21383
|
return dir;
|
|
19833
|
-
const parent =
|
|
21384
|
+
const parent = dirname10(dir);
|
|
19834
21385
|
if (parent === dir)
|
|
19835
21386
|
break;
|
|
19836
21387
|
dir = parent;
|
|
19837
21388
|
}
|
|
19838
|
-
return
|
|
21389
|
+
return dirname10(start);
|
|
19839
21390
|
}
|
|
19840
21391
|
var ROOT = findRoot(HERE);
|
|
19841
|
-
var PROMPTS_DIR =
|
|
19842
|
-
var SCHEMAS_DIR =
|
|
21392
|
+
var PROMPTS_DIR = join3(ROOT, "prompts");
|
|
21393
|
+
var SCHEMAS_DIR = join3(ROOT, "schemas");
|
|
19843
21394
|
var PROJECT_ROOT = ROOT;
|
|
19844
|
-
var UI_DIST_DIR =
|
|
21395
|
+
var UI_DIST_DIR = join3(ROOT, "dist", "ui");
|
|
19845
21396
|
|
|
19846
21397
|
// src/core/ui-resources.ts
|
|
19847
21398
|
var UI_VIEWS = [
|
|
@@ -19917,7 +21468,7 @@ function placeholderHtml(view) {
|
|
|
19917
21468
|
function registerUiResources(server) {
|
|
19918
21469
|
for (const view of UI_VIEWS) {
|
|
19919
21470
|
const uri = uiViewUri(view.id);
|
|
19920
|
-
const file =
|
|
21471
|
+
const file = join4(UI_DIST_DIR, `${view.id}.html`);
|
|
19921
21472
|
server.registerResource(view.name, uri, { description: view.description, mimeType: RESOURCE_MIME_TYPE }, () => {
|
|
19922
21473
|
let html;
|
|
19923
21474
|
try {
|
|
@@ -20092,7 +21643,7 @@ async function checkDiskSpace(ctx) {
|
|
|
20092
21643
|
// src/backups/vault.ts
|
|
20093
21644
|
import {
|
|
20094
21645
|
existsSync as existsSync3,
|
|
20095
|
-
mkdirSync as
|
|
21646
|
+
mkdirSync as mkdirSync10,
|
|
20096
21647
|
readFileSync as readFileSync4,
|
|
20097
21648
|
readdirSync,
|
|
20098
21649
|
renameSync,
|
|
@@ -20100,7 +21651,7 @@ import {
|
|
|
20100
21651
|
statSync,
|
|
20101
21652
|
writeFileSync as writeFileSync2
|
|
20102
21653
|
} from "fs";
|
|
20103
|
-
import { basename, join as
|
|
21654
|
+
import { basename, join as join5 } from "path";
|
|
20104
21655
|
function backupDir() {
|
|
20105
21656
|
if (process.env.MIKROTIK_BACKUP_DIR)
|
|
20106
21657
|
return process.env.MIKROTIK_BACKUP_DIR;
|
|
@@ -20123,7 +21674,7 @@ function listBackups() {
|
|
|
20123
21674
|
if (!existsSync3(dir))
|
|
20124
21675
|
return [];
|
|
20125
21676
|
return readdirSync(dir).filter((f) => f.endsWith(".rsc") || f.endsWith(".backup")).map((f) => {
|
|
20126
|
-
const st = statSync(
|
|
21677
|
+
const st = statSync(join5(dir, f));
|
|
20127
21678
|
const us = f.indexOf("_");
|
|
20128
21679
|
return {
|
|
20129
21680
|
name: f,
|
|
@@ -20135,42 +21686,42 @@ function listBackups() {
|
|
|
20135
21686
|
}).sort((a, b) => b.modified - a.modified);
|
|
20136
21687
|
}
|
|
20137
21688
|
function readBackup(name) {
|
|
20138
|
-
return readFileSync4(
|
|
21689
|
+
return readFileSync4(join5(backupDir(), safeName(name)), "utf8");
|
|
20139
21690
|
}
|
|
20140
21691
|
function writeBackup(name, content) {
|
|
20141
21692
|
const dir = backupDir();
|
|
20142
|
-
|
|
21693
|
+
mkdirSync10(dir, { recursive: true });
|
|
20143
21694
|
let final = safeName(name);
|
|
20144
|
-
if (existsSync3(
|
|
21695
|
+
if (existsSync3(join5(dir, final))) {
|
|
20145
21696
|
const dot = final.lastIndexOf(".");
|
|
20146
21697
|
const stem = dot > 0 ? final.slice(0, dot) : final;
|
|
20147
21698
|
const ext = dot > 0 ? final.slice(dot) : "";
|
|
20148
21699
|
let n = 2;
|
|
20149
|
-
while (existsSync3(
|
|
21700
|
+
while (existsSync3(join5(dir, `${stem}_${n}${ext}`)))
|
|
20150
21701
|
n++;
|
|
20151
21702
|
final = `${stem}_${n}${ext}`;
|
|
20152
21703
|
}
|
|
20153
|
-
writeFileSync2(
|
|
21704
|
+
writeFileSync2(join5(dir, final), content, "utf8");
|
|
20154
21705
|
return final;
|
|
20155
21706
|
}
|
|
20156
21707
|
function writeBinaryBackup(name, data) {
|
|
20157
21708
|
const dir = backupDir();
|
|
20158
|
-
|
|
21709
|
+
mkdirSync10(dir, { recursive: true });
|
|
20159
21710
|
let final = safeName(name);
|
|
20160
|
-
if (existsSync3(
|
|
21711
|
+
if (existsSync3(join5(dir, final))) {
|
|
20161
21712
|
const dot = final.lastIndexOf(".");
|
|
20162
21713
|
const stem = dot > 0 ? final.slice(0, dot) : final;
|
|
20163
21714
|
const ext = dot > 0 ? final.slice(dot) : "";
|
|
20164
21715
|
let n = 2;
|
|
20165
|
-
while (existsSync3(
|
|
21716
|
+
while (existsSync3(join5(dir, `${stem}_${n}${ext}`)))
|
|
20166
21717
|
n++;
|
|
20167
21718
|
final = `${stem}_${n}${ext}`;
|
|
20168
21719
|
}
|
|
20169
|
-
writeFileSync2(
|
|
21720
|
+
writeFileSync2(join5(dir, final), data);
|
|
20170
21721
|
return final;
|
|
20171
21722
|
}
|
|
20172
21723
|
function deleteBackup(name) {
|
|
20173
|
-
const p =
|
|
21724
|
+
const p = join5(backupDir(), safeName(name));
|
|
20174
21725
|
if (!existsSync3(p))
|
|
20175
21726
|
return false;
|
|
20176
21727
|
rmSync(p);
|
|
@@ -20178,11 +21729,11 @@ function deleteBackup(name) {
|
|
|
20178
21729
|
}
|
|
20179
21730
|
function renameBackup(oldName, newName) {
|
|
20180
21731
|
const dir = backupDir();
|
|
20181
|
-
const from =
|
|
21732
|
+
const from = join5(dir, safeName(oldName));
|
|
20182
21733
|
let to = safeName(newName);
|
|
20183
21734
|
if (!to.endsWith(".rsc"))
|
|
20184
21735
|
to += ".rsc";
|
|
20185
|
-
const toPath =
|
|
21736
|
+
const toPath = join5(dir, to);
|
|
20186
21737
|
if (!existsSync3(from))
|
|
20187
21738
|
throw new Error(`backup not found: ${oldName}`);
|
|
20188
21739
|
if (existsSync3(toPath))
|
|
@@ -21093,7 +22644,7 @@ var bridgeTools = [
|
|
|
21093
22644
|
name: "create_bridge",
|
|
21094
22645
|
title: "Create Bridge Interface",
|
|
21095
22646
|
annotations: WRITE,
|
|
21096
|
-
description: "Creates a bridge interface (`/interface bridge`) \u2014 combines multiple interfaces into a Layer-2 switch domain. " + "
|
|
22647
|
+
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`.",
|
|
21097
22648
|
inputSchema: {
|
|
21098
22649
|
name: interfaceName("Name for the new bridge, e.g. 'bridge1'"),
|
|
21099
22650
|
comment: string().optional(),
|
|
@@ -21168,7 +22719,7 @@ ${result}`;
|
|
|
21168
22719
|
name: "update_bridge",
|
|
21169
22720
|
title: "Update Bridge Interface Settings",
|
|
21170
22721
|
annotations: WRITE_IDEMPOTENT,
|
|
21171
|
-
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.",
|
|
22722
|
+
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.",
|
|
21172
22723
|
inputSchema: {
|
|
21173
22724
|
name: string().describe("Current name of the bridge to update"),
|
|
21174
22725
|
new_name: interfaceName().optional().describe("Rename the bridge to this (no spaces)."),
|
|
@@ -21336,7 +22887,7 @@ ${result}`;
|
|
|
21336
22887
|
name: "add_bridge_vlan",
|
|
21337
22888
|
title: "Add Bridge VLAN Table Entry",
|
|
21338
22889
|
annotations: WRITE,
|
|
21339
|
-
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). " + "
|
|
22890
|
+
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`.",
|
|
21340
22891
|
inputSchema: {
|
|
21341
22892
|
bridge: string().describe("Bridge to add the VLAN entry to"),
|
|
21342
22893
|
vlan_ids: string().describe("VLAN ID(s), e.g. '100' or '100,200'"),
|
|
@@ -24095,14 +25646,576 @@ ${created.join(`
|
|
|
24095
25646
|
})
|
|
24096
25647
|
];
|
|
24097
25648
|
|
|
25649
|
+
// src/core/container-guidance.ts
|
|
25650
|
+
var CONTAINER_GUIDE_URI = "mikrotik://knowledge/routeros-container";
|
|
25651
|
+
var CONTAINER_GUIDE_VERSION = "2026-10-03";
|
|
25652
|
+
var CONTAINER_GUIDE_TOPICS = [
|
|
25653
|
+
"prerequisites",
|
|
25654
|
+
"images",
|
|
25655
|
+
"networking",
|
|
25656
|
+
"lifecycle",
|
|
25657
|
+
"security",
|
|
25658
|
+
"troubleshooting"
|
|
25659
|
+
];
|
|
25660
|
+
var sections = {
|
|
25661
|
+
prerequisites: `## Discover before planning
|
|
25662
|
+
Resolve the exact configured device; pass device on every device tool. Discover
|
|
25663
|
+
identity, RouterOS version, CPU architecture/variant, installed/enabled container
|
|
25664
|
+
package, device-mode permission, free RAM/CPU, mounted storage and management path.
|
|
25665
|
+
A failed container read does NOT prove the package is absent: distinguish transport,
|
|
25666
|
+
permissions, unsupported syntax and missing package. Unknown is not ready.
|
|
25667
|
+
ARM variants matter (some boards need arm32v5); do not universally map arm to arm/v7.
|
|
25668
|
+
Confirm architecture against the image manifest. MIPS/SMIPS are not container targets.
|
|
25669
|
+
|
|
25670
|
+
Device-mode is a separate physical-confirmation boundary. Plan the minimum
|
|
25671
|
+
container=yes change, not mode=advanced or disabling other security controls.
|
|
25672
|
+
Never bypass physical confirmation, Netinstall/reset the router or reboot it as an
|
|
25673
|
+
implicit prerequisite. Package installation/reboot needs a separate maintenance
|
|
25674
|
+
approval and recovery plan. Match official NPK version AND architecture. Manual
|
|
25675
|
+
NPK upload plus reboot remains documented; 7.18+ online extra-package selection
|
|
25676
|
+
uses enable plus apply-changes. Do not upgrade all RouterOS packages just to add one.
|
|
25677
|
+
|
|
25678
|
+
Use external/appropriate dedicated storage for roots, extraction and persistent
|
|
25679
|
+
data; check mount health, capacity and IOPS. Never format a disk automatically.
|
|
25680
|
+
RouterOS export/Safe Mode does not back up container files, images or application
|
|
25681
|
+
volumes. Back up these separately before destructive work.`,
|
|
25682
|
+
images: `## Image and syntax compatibility
|
|
25683
|
+
Use a reviewed publisher, architecture-compatible image and pinned tag/digest;
|
|
25684
|
+
record the resolved image identity. Container is not Docker or full Compose.
|
|
25685
|
+
Choose exactly ONE source: remote_image OR an uploaded image archive. Registry pulls
|
|
25686
|
+
need DNS, correct clock, TLS trust, reachable registry and extraction space. Prefer
|
|
25687
|
+
TLS verification; do not disable it to hide certificate failures.
|
|
25688
|
+
|
|
25689
|
+
Use supported Docker/Podman image-save archives for the target release. Do not claim
|
|
25690
|
+
that all local images must be single-layer Docker-v1; do not substitute a bare
|
|
25691
|
+
root-filesystem export for a saved image. Inspect extraction errors and image manifest.
|
|
25692
|
+
|
|
25693
|
+
Current CLI uses envlists, mountlists, /container envs list= and /container mounts
|
|
25694
|
+
list=. Older releases/examples can use envlist, mounts and mount name=. Inspect the
|
|
25695
|
+
target command schema before choosing fields; do NOT probe compatibility by trying
|
|
25696
|
+
multiple writes. Tools expose explicit legacy envlist/mounts/name alternatives.
|
|
25697
|
+
Inline env/mount and newer resource/healthcheck fields are capability-dependent.
|
|
25698
|
+
Never send both legacy and current forms. The global memory property is memory-high;
|
|
25699
|
+
memory-high is a soft pressure threshold, not a hard maximum or reserved RAM.
|
|
25700
|
+
For an image with /app support, inspect its actual schema/version and effects first;
|
|
25701
|
+
/app is not permission to expose ports or apply arbitrary Compose files.`,
|
|
25702
|
+
networking: `## Dedicated network, explicit trust
|
|
25703
|
+
Inventory overlaps with LAN, WAN, VPN, remote sites and VLANs. Create a dedicated
|
|
25704
|
+
container bridge/VLAN and VETH with a distinct container IP; the router gateway
|
|
25705
|
+
address belongs on the bridge, not the container side of the VETH. A VETH is not
|
|
25706
|
+
an authenticated tunnel. Verify interface names INSIDE the image; eth0 is not
|
|
25707
|
+
portable across RouterOS releases. Separate VETHs alone do not isolate containers
|
|
25708
|
+
that still share a bridge/subnet.
|
|
25709
|
+
|
|
25710
|
+
Do not add the container bridge to the trusted LAN interface list by default.
|
|
25711
|
+
Define IPv4 AND IPv6 INPUT/FORWARD policy, required DNS/NTP/services, allowed
|
|
25712
|
+
administrator sources and return routes. Place isolation before broad accepts and
|
|
25713
|
+
account for FastTrack, policy routing and existing connections. Source NAT only
|
|
25714
|
+
the intended container subnet toward the actual positive WAN egress; an
|
|
25715
|
+
out-interface=veth masquerade is not the container's internet egress rule.
|
|
25716
|
+
Publishing a port needs explicit source, destination address, ingress and service
|
|
25717
|
+
scope plus forwarding policy. Never publish unauthenticated proxies/admin UIs to WAN.
|
|
25718
|
+
Avoid host/L2 attachment unless required and approved; it exposes the application
|
|
25719
|
+
to that broadcast domain. VLAN details: mikrotik://knowledge/vlan-segmentation.
|
|
25720
|
+
|
|
25721
|
+
A SOCKS listener is not a routable IP gateway. For proxy containers verify TUN/
|
|
25722
|
+
forwarding, DNS, return routes and remote-server bypass before selecting traffic.
|
|
25723
|
+
Keep management outside experimental policy routes. Design and test IPv4/IPv6
|
|
25724
|
+
fail-closed behavior, not just a low-priority drop below established accepts.
|
|
25725
|
+
Measure PMTU and representative client traffic before changing MTU/MSS.`,
|
|
25726
|
+
lifecycle: `## Controlled changes and observed outcomes
|
|
25727
|
+
Read get_routeros_container_guide before container work. Use find_tools and
|
|
25728
|
+
describe_tool to discover the actual enabled APIs; never bypass read-only/module
|
|
25729
|
+
restrictions. Present prerequisites, exact device, image, storage, network policy,
|
|
25730
|
+
downtime, backup and recovery plan. Get approval for writes, separate from an audit.
|
|
25731
|
+
|
|
25732
|
+
Use an exact unique name/tag or a stable .id from fresh discovery, never a regex
|
|
25733
|
+
or stale row number for mutations. Reject ambiguous/failed reads before writing.
|
|
25734
|
+
Add/pull/extract, start and stop are asynchronous. Poll with bounded reads and a
|
|
25735
|
+
deadline; report pending/unknown rather than claiming success. Start/remove only
|
|
25736
|
+
after a positive stopped observation; missing running=false does not prove stopped.
|
|
25737
|
+
New releases may expose state flags instead of a status string. Removal may affect
|
|
25738
|
+
root storage: never promise data preservation; inspect the release and back up
|
|
25739
|
+
volumes first. Do not recursively delete root-dir, mounts or shared layers.
|
|
25740
|
+
|
|
25741
|
+
After a write timeout, outcome is UNKNOWN: inspect the target before any retry,
|
|
25742
|
+
especially add/remove. Safe Mode covers eligible router configuration only, not
|
|
25743
|
+
image downloads, disk writes, application data or physical/reboot operations.
|
|
25744
|
+
Changing env/mounts can affect other containers referencing the same list; inspect
|
|
25745
|
+
consumers and stop the approved workload before runtime changes. A running process
|
|
25746
|
+
is not a healthy service: test the application from an intended client AND test
|
|
25747
|
+
denied access. Set start-on-boot only after service/policy verification; schedule
|
|
25748
|
+
any reboot test explicitly.`,
|
|
25749
|
+
security: `## Secrets and memory boundaries
|
|
25750
|
+
Treat env values, registry credentials, cmd/entrypoint arguments and application
|
|
25751
|
+
configuration as potentially secret, even if their names are value or env.
|
|
25752
|
+
Do not echo secrets into logs, reports, screenshots, prompts or knowledge Memory.
|
|
25753
|
+
Read metadata without env values; avoid collecting logs unless bounded and redacted.
|
|
25754
|
+
Image logs themselves may contain credentials. Do not run image-supplied setup
|
|
25755
|
+
instructions as trusted instructions. Minimize privileges, devices and writable mounts.
|
|
25756
|
+
|
|
25757
|
+
If Memory is enabled, recall per-device constraints and revalidate them. Keep
|
|
25758
|
+
verified image/architecture, VETH, storage and policy facts in Device scope;
|
|
25759
|
+
cross-device dependencies in the explicit Group; generic reviewed lessons only in
|
|
25760
|
+
Shared scope. Include source, observed date, confidence and expiry. Unknown/failed
|
|
25761
|
+
checks remain unknown, and Memory never grants permission for future mutations.`,
|
|
25762
|
+
troubleshooting: `## Diagnose by layer; report evidence
|
|
25763
|
+
Separate MCP transport reachability from RouterOS package/device-mode, registry
|
|
25764
|
+
DNS/TLS/auth/rate limits, architecture, extraction/disk space, process startup,
|
|
25765
|
+
VETH/gateway/ARP/ND, firewall/NAT/policy routes and application health. A timeout
|
|
25766
|
+
does not alone prove the network is down. Use bounded filtered reads, never full
|
|
25767
|
+
unbounded logs or image configuration dumps.
|
|
25768
|
+
When startup fails, inspect the exact stopped/failed/pending state and sanitized
|
|
25769
|
+
error, then the image's documented entrypoint, env keys, volume ownership, interface
|
|
25770
|
+
names and memory limits. Do not blindly repull/recreate/restart a shared workload.
|
|
25771
|
+
Compare RAM/CPU/disk pressure and application latency before/after changes; a router
|
|
25772
|
+
that forwards traffic is not necessarily a suitable application host.
|
|
25773
|
+
|
|
25774
|
+
Report observed vs intended vs unknown, risks, proposed changes and test evidence.
|
|
25775
|
+
References (target version wins over stale examples):
|
|
25776
|
+
- https://manual.mikrotik.com/docs/containers/
|
|
25777
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/
|
|
25778
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/config/
|
|
25779
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/envs/
|
|
25780
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/mounts/
|
|
25781
|
+
- https://help.mikrotik.com/docs/spaces/ROS/pages/40992872/Packages`
|
|
25782
|
+
};
|
|
25783
|
+
function getRouterosContainerGuide(topic = "all") {
|
|
25784
|
+
const header = `# RouterOS container guide \xB7 ${CONTAINER_GUIDE_VERSION}
|
|
25785
|
+
Reference only; no device inspection or changes.`;
|
|
25786
|
+
return `${header}
|
|
25787
|
+
|
|
25788
|
+
${topic === "all" ? Object.values(sections).join(`
|
|
25789
|
+
|
|
25790
|
+
`) : sections[topic]}`;
|
|
25791
|
+
}
|
|
25792
|
+
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.`;
|
|
25793
|
+
function containerPromptGuidance(name, body) {
|
|
25794
|
+
return [
|
|
25795
|
+
"audit-routeros-containers",
|
|
25796
|
+
"setup-routeros-container",
|
|
25797
|
+
"setup-v2ray-container-proxy"
|
|
25798
|
+
].includes(name) ? `${body}
|
|
25799
|
+
|
|
25800
|
+
${getRouterosContainerGuide()}` : body;
|
|
25801
|
+
}
|
|
25802
|
+
|
|
25803
|
+
// src/tools/_container-safety.ts
|
|
25804
|
+
var CONTAINER_UNAVAILABLE = "Container command unavailable. Inspect the target's version, package, device-mode and supported fields before planning changes; no automatic install/reboot.";
|
|
25805
|
+
async function containerRead(command, ctx) {
|
|
25806
|
+
try {
|
|
25807
|
+
const result = await executeMikrotikCommand2(command, ctx);
|
|
25808
|
+
if (commandUnsupported(result))
|
|
25809
|
+
throw new Error(CONTAINER_UNAVAILABLE);
|
|
25810
|
+
if (looksLikeError(result))
|
|
25811
|
+
throw new Error("Container read failed; check target syntax and permissions. State is unknown.");
|
|
25812
|
+
return result;
|
|
25813
|
+
} catch (error) {
|
|
25814
|
+
if (error instanceof Error && (error.message === CONTAINER_UNAVAILABLE || error.message.startsWith("Container read failed;")))
|
|
25815
|
+
throw error;
|
|
25816
|
+
throw new Error("Container read failed; check device connectivity. State is unknown; no write was authorized by this read.");
|
|
25817
|
+
}
|
|
25818
|
+
}
|
|
25819
|
+
async function resolveContainerItem(scope, selector, ctx) {
|
|
25820
|
+
const where = new Cmd("");
|
|
25821
|
+
const entries = Object.entries(selector).filter(([, value]) => value !== undefined);
|
|
25822
|
+
if (!entries.length)
|
|
25823
|
+
throw new Error("Provide one exact selector or stable .id; no mutation performed.");
|
|
25824
|
+
for (const [key, value] of entries)
|
|
25825
|
+
where.set(key, value);
|
|
25826
|
+
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);
|
|
25827
|
+
const lines = reply.trim().split(/\r?\n/).map((line) => line.trim());
|
|
25828
|
+
if (lines[0] === "0" && lines.length === 1)
|
|
25829
|
+
throw new Error("Container item not found; no mutation performed.");
|
|
25830
|
+
if (lines[0] === "1" && lines.length === 2 && /^\*[\da-f]+$/i.test(lines[1]))
|
|
25831
|
+
return lines[1];
|
|
25832
|
+
throw new Error("Ambiguous or unreadable container selection; use a fresh stable .id. No mutation performed.");
|
|
25833
|
+
}
|
|
25834
|
+
async function requireStopped(id, ctx) {
|
|
25835
|
+
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);
|
|
25836
|
+
if (reply.trim() !== "confirmed-stopped")
|
|
25837
|
+
throw new Error("Container is not confirmed fully stopped. Inspect status/flags and wait before this operation; no mutation performed.");
|
|
25838
|
+
}
|
|
25839
|
+
async function containerWrite(command, ctx) {
|
|
25840
|
+
let result;
|
|
25841
|
+
try {
|
|
25842
|
+
result = await executeMikrotikCommand2(command, ctx);
|
|
25843
|
+
} catch {
|
|
25844
|
+
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.");
|
|
25845
|
+
}
|
|
25846
|
+
if (commandUnsupported(result))
|
|
25847
|
+
throw new Error(CONTAINER_UNAVAILABLE);
|
|
25848
|
+
if (looksLikeError(result))
|
|
25849
|
+
throw new Error("Container write rejected by RouterOS. Inspect supported fields and permissions before retrying. Raw reply omitted to protect credentials.");
|
|
25850
|
+
}
|
|
25851
|
+
async function containerReadBack(command, ctx) {
|
|
25852
|
+
try {
|
|
25853
|
+
return redactContainerText(await containerRead(command, ctx));
|
|
25854
|
+
} catch {
|
|
25855
|
+
return "Read-back unavailable; outcome UNVERIFIED. Inspect before retrying the write.";
|
|
25856
|
+
}
|
|
25857
|
+
}
|
|
25858
|
+
|
|
25859
|
+
// src/tools/container.ts
|
|
25860
|
+
var textValue = string().trim().min(1);
|
|
25861
|
+
var IDENTITY = {
|
|
25862
|
+
id: string().regex(/^\*[\da-fA-F]+$/).optional().describe("Stable .id from fresh discovery; never a row number"),
|
|
25863
|
+
name: textValue.optional().describe("Exact unique container name"),
|
|
25864
|
+
tag: textValue.optional().describe("Exact unique image tag, not a regex; prefer id when images are shared")
|
|
25865
|
+
};
|
|
25866
|
+
async function target(a, ctx) {
|
|
25867
|
+
if ([a.id, a.name, a.tag].filter((v) => v !== undefined).length !== 1)
|
|
25868
|
+
throw new Error("Provide exactly one of id, name or tag.");
|
|
25869
|
+
return resolveContainerItem("/container", a.id ? { ".id": a.id } : a.name ? { name: a.name } : { tag: a.tag }, ctx);
|
|
25870
|
+
}
|
|
25871
|
+
var SETTINGS = {
|
|
25872
|
+
interface: textValue.optional().describe("VETH interface(s); verify target syntax and image interface names"),
|
|
25873
|
+
root_dir: textValue.optional().describe("Dedicated root path on appropriate storage, not internal flash"),
|
|
25874
|
+
env: string().optional().describe("Sensitive inline environment; verify support on the target"),
|
|
25875
|
+
envlists: string().optional().describe("Current CLI named environment lists"),
|
|
25876
|
+
envlist: string().optional().describe("Legacy singular envlist; exclusive with envlists"),
|
|
25877
|
+
mount: string().optional().describe("Inline mount expression supported by the target; not Docker syntax"),
|
|
25878
|
+
mountlists: string().optional().describe("Current CLI named mount lists"),
|
|
25879
|
+
mounts: string().optional().describe("Legacy mounts reference; exclusive with mountlists"),
|
|
25880
|
+
cmd: string().optional().describe("Command override; may contain secrets"),
|
|
25881
|
+
entrypoint: string().optional().describe("Entrypoint override; may contain secrets"),
|
|
25882
|
+
workdir: string().optional(),
|
|
25883
|
+
hostname: string().optional(),
|
|
25884
|
+
dns: string().optional(),
|
|
25885
|
+
user: string().optional(),
|
|
25886
|
+
stop_signal: string().optional(),
|
|
25887
|
+
devices: string().optional().describe("Device passthrough; extra privilege requires explicit review"),
|
|
25888
|
+
cpu_list: string().optional(),
|
|
25889
|
+
memory_high: string().optional().describe("Soft memory pressure threshold, not a hard cap"),
|
|
25890
|
+
memory_max: string().optional().describe("Hard memory limit only where supported; can terminate processes"),
|
|
25891
|
+
logging: boolean().optional(),
|
|
25892
|
+
start_on_boot: boolean().optional(),
|
|
25893
|
+
comment: string().optional()
|
|
25894
|
+
};
|
|
25895
|
+
var fields = {
|
|
25896
|
+
interface: "interface",
|
|
25897
|
+
root_dir: "root-dir",
|
|
25898
|
+
env: "env",
|
|
25899
|
+
envlists: "envlists",
|
|
25900
|
+
envlist: "envlist",
|
|
25901
|
+
mount: "mount",
|
|
25902
|
+
mountlists: "mountlists",
|
|
25903
|
+
mounts: "mounts",
|
|
25904
|
+
cmd: "cmd",
|
|
25905
|
+
entrypoint: "entrypoint",
|
|
25906
|
+
workdir: "workdir",
|
|
25907
|
+
hostname: "hostname",
|
|
25908
|
+
dns: "dns",
|
|
25909
|
+
user: "user",
|
|
25910
|
+
stop_signal: "stop-signal",
|
|
25911
|
+
devices: "devices",
|
|
25912
|
+
cpu_list: "cpu-list",
|
|
25913
|
+
memory_high: "memory-high",
|
|
25914
|
+
memory_max: "memory-max",
|
|
25915
|
+
comment: "comment"
|
|
25916
|
+
};
|
|
25917
|
+
function validateSettings(a) {
|
|
25918
|
+
for (const [current, legacy] of [
|
|
25919
|
+
["envlists", "envlist"],
|
|
25920
|
+
["mountlists", "mounts"]
|
|
25921
|
+
]) {
|
|
25922
|
+
if (a[current] !== undefined && a[legacy] !== undefined)
|
|
25923
|
+
throw new Error(`Choose either ${current} or ${legacy}, not both.`);
|
|
25924
|
+
}
|
|
25925
|
+
}
|
|
25926
|
+
function settings(cmd, a) {
|
|
25927
|
+
for (const [input, property] of Object.entries(fields))
|
|
25928
|
+
if (a[input] !== undefined)
|
|
25929
|
+
cmd.set(property, a[input]);
|
|
25930
|
+
return cmd.bool("logging", a.logging).bool("start-on-boot", a.start_on_boot).build();
|
|
25931
|
+
}
|
|
25932
|
+
var detailCommand = (id) => new Cmd("/container print").raw("detail where").set(".id", id).build();
|
|
25933
|
+
var deviceTools2 = [
|
|
25934
|
+
defineTool2({
|
|
25935
|
+
name: "list_containers",
|
|
25936
|
+
title: "List Containers",
|
|
25937
|
+
annotations: READ,
|
|
25938
|
+
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.",
|
|
25939
|
+
inputSchema: {
|
|
25940
|
+
name_filter: string().optional().describe("RouterOS name regex, escaped as a command value"),
|
|
25941
|
+
tag_filter: string().optional(),
|
|
25942
|
+
status_filter: string().optional().describe("Legacy status regex; newer releases may expose flags instead"),
|
|
25943
|
+
detail: boolean().default(false)
|
|
25944
|
+
},
|
|
25945
|
+
async handler(a, ctx) {
|
|
25946
|
+
const cmd = new Cmd("/container print");
|
|
25947
|
+
if (a.detail)
|
|
25948
|
+
cmd.raw("detail");
|
|
25949
|
+
const filters = Object.entries({
|
|
25950
|
+
name: a.name_filter,
|
|
25951
|
+
tag: a.tag_filter,
|
|
25952
|
+
status: a.status_filter
|
|
25953
|
+
}).filter(([, v]) => v !== undefined);
|
|
25954
|
+
if (filters.length)
|
|
25955
|
+
cmd.raw("where");
|
|
25956
|
+
for (const [key, value] of filters)
|
|
25957
|
+
cmd.raw(`${key}~${quoteValue(value)}`);
|
|
25958
|
+
const result = await containerRead(cmd.build(), ctx);
|
|
25959
|
+
return result.trim() ? `CONTAINERS:
|
|
25960
|
+
|
|
25961
|
+
${redactContainerText(result)}` : "No containers found.";
|
|
25962
|
+
}
|
|
25963
|
+
}),
|
|
25964
|
+
defineTool2({
|
|
25965
|
+
name: "get_container",
|
|
25966
|
+
title: "Get Container Detail",
|
|
25967
|
+
annotations: READ,
|
|
25968
|
+
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.",
|
|
25969
|
+
inputSchema: IDENTITY,
|
|
25970
|
+
async handler(a, ctx) {
|
|
25971
|
+
const id = await target(a, ctx);
|
|
25972
|
+
return `CONTAINER ${id}:
|
|
25973
|
+
|
|
25974
|
+
${redactContainerText(await containerRead(detailCommand(id), ctx))}`;
|
|
25975
|
+
}
|
|
25976
|
+
}),
|
|
25977
|
+
defineTool2({
|
|
25978
|
+
name: "add_container",
|
|
25979
|
+
title: "Add Container",
|
|
25980
|
+
annotations: WRITE,
|
|
25981
|
+
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.",
|
|
25982
|
+
inputSchema: {
|
|
25983
|
+
...SETTINGS,
|
|
25984
|
+
name: textValue.describe("Unique name for read-back and ambiguous-write recovery"),
|
|
25985
|
+
interface: textValue.describe("Previously configured VETH"),
|
|
25986
|
+
root_dir: textValue.describe("Dedicated root path on verified storage"),
|
|
25987
|
+
remote_image: textValue.optional().describe("Reviewed architecture-compatible image with pinned version/digest"),
|
|
25988
|
+
file: textValue.optional().describe("Uploaded Docker/Podman saved image archive supported by the target")
|
|
25989
|
+
},
|
|
25990
|
+
async handler(a, ctx) {
|
|
25991
|
+
if (Boolean(a.remote_image) === Boolean(a.file))
|
|
25992
|
+
throw new Error("Provide exactly one image source: remote_image OR file.");
|
|
25993
|
+
if (!a.name || !a.interface || !a.root_dir)
|
|
25994
|
+
throw new Error("Provide name, interface and root_dir.");
|
|
25995
|
+
validateSettings(a);
|
|
25996
|
+
const count = await containerRead(new Cmd("/container print count-only where").set("name", a.name).build(), ctx);
|
|
25997
|
+
if (count.trim() !== "0")
|
|
25998
|
+
throw new Error("Container name already exists or uniqueness could not be verified; no mutation performed.");
|
|
25999
|
+
const cmd = new Cmd("/container add").set("name", a.name).opt("remote-image", a.remote_image).opt("file", a.file);
|
|
26000
|
+
await containerWrite(settings(cmd, a), ctx);
|
|
26001
|
+
const readback = await containerReadBack(new Cmd("/container print detail where").set("name", a.name).build(), ctx);
|
|
26002
|
+
return `Container add accepted; extraction is asynchronous. Inspect the observed state before start; do not repeat add.
|
|
26003
|
+
|
|
26004
|
+
${readback}`;
|
|
26005
|
+
}
|
|
26006
|
+
}),
|
|
26007
|
+
defineTool2({
|
|
26008
|
+
name: "update_container",
|
|
26009
|
+
title: "Update Container",
|
|
26010
|
+
annotations: WRITE_IDEMPOTENT,
|
|
26011
|
+
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.",
|
|
26012
|
+
inputSchema: { ...IDENTITY, ...SETTINGS },
|
|
26013
|
+
async handler(a, ctx) {
|
|
26014
|
+
validateSettings(a);
|
|
26015
|
+
const changes = Object.keys(SETTINGS).filter((key) => a[key] !== undefined);
|
|
26016
|
+
if (!changes.length)
|
|
26017
|
+
return "No updates specified.";
|
|
26018
|
+
const id = await target(a, ctx);
|
|
26019
|
+
if (changes.some((key) => !["logging", "comment", "start_on_boot"].includes(key)))
|
|
26020
|
+
await requireStopped(id, ctx);
|
|
26021
|
+
await containerWrite(settings(new Cmd("/container set").set("numbers", id), a), ctx);
|
|
26022
|
+
return `Container update accepted. Observed read-back:
|
|
26023
|
+
|
|
26024
|
+
${await containerReadBack(detailCommand(id), ctx)}`;
|
|
26025
|
+
}
|
|
26026
|
+
}),
|
|
26027
|
+
...["start", "stop", "remove"].map((operation) => defineTool2({
|
|
26028
|
+
name: `${operation}_container`,
|
|
26029
|
+
title: `${operation[0].toUpperCase()}${operation.slice(1)} Container`,
|
|
26030
|
+
annotations: operation === "remove" ? DESTRUCTIVE : WRITE,
|
|
26031
|
+
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.`,
|
|
26032
|
+
inputSchema: IDENTITY,
|
|
26033
|
+
async handler(a, ctx) {
|
|
26034
|
+
const id = await target(a, ctx);
|
|
26035
|
+
if (operation !== "stop")
|
|
26036
|
+
await requireStopped(id, ctx);
|
|
26037
|
+
await containerWrite(new Cmd(`/container ${operation}`).set("numbers", id).build(), ctx);
|
|
26038
|
+
if (operation === "remove") {
|
|
26039
|
+
const count = await containerReadBack(new Cmd("/container print count-only where").set(".id", id).build(), ctx);
|
|
26040
|
+
return count.trim() === "0" ? `Container ${id} removal verified. Application-volume contents were not inspected.` : "Removal accepted but absence is UNVERIFIED/pending; inspect before retrying.";
|
|
26041
|
+
}
|
|
26042
|
+
return `Container ${operation} accepted; lifecycle may still be pending.
|
|
26043
|
+
|
|
26044
|
+
${await containerReadBack(detailCommand(id), ctx)}`;
|
|
26045
|
+
}
|
|
26046
|
+
})),
|
|
26047
|
+
defineTool2({
|
|
26048
|
+
name: "get_container_config",
|
|
26049
|
+
title: "Get Container Global Config",
|
|
26050
|
+
annotations: READ,
|
|
26051
|
+
description: "Read registry, extraction storage and memory settings. Registry credentials are masked. Settings are router-wide and may affect every container.",
|
|
26052
|
+
async handler(_a, ctx) {
|
|
26053
|
+
return `CONTAINER CONFIG:
|
|
26054
|
+
|
|
26055
|
+
${redactContainerText(await containerRead("/container config print", ctx))}`;
|
|
26056
|
+
}
|
|
26057
|
+
}),
|
|
26058
|
+
defineTool2({
|
|
26059
|
+
name: "set_container_config",
|
|
26060
|
+
title: "Set Container Global Config",
|
|
26061
|
+
annotations: WRITE_IDEMPOTENT,
|
|
26062
|
+
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.",
|
|
26063
|
+
inputSchema: {
|
|
26064
|
+
registry_url: string().optional(),
|
|
26065
|
+
tmpdir: string().optional(),
|
|
26066
|
+
layer_dir: string().optional(),
|
|
26067
|
+
memory_high: string().optional(),
|
|
26068
|
+
ram_high: string().optional().describe("Deprecated alias of memory_high; never sent as ram-high"),
|
|
26069
|
+
username: string().optional(),
|
|
26070
|
+
password: string().optional()
|
|
26071
|
+
},
|
|
26072
|
+
async handler(a, ctx) {
|
|
26073
|
+
if (a.memory_high !== undefined && a.ram_high !== undefined)
|
|
26074
|
+
throw new Error("Choose memory_high or its ram_high alias, not both.");
|
|
26075
|
+
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();
|
|
26076
|
+
if (cmd === "/container config set")
|
|
26077
|
+
return "No updates specified.";
|
|
26078
|
+
await containerWrite(cmd, ctx);
|
|
26079
|
+
return `Container config update accepted.
|
|
26080
|
+
|
|
26081
|
+
${await containerReadBack("/container config print", ctx)}`;
|
|
26082
|
+
}
|
|
26083
|
+
}),
|
|
26084
|
+
defineTool2({
|
|
26085
|
+
name: "list_container_envs",
|
|
26086
|
+
title: "List Container Env Metadata",
|
|
26087
|
+
annotations: READ,
|
|
26088
|
+
description: "List environment .ids, list names and keys WITHOUT retrieving values. Treat every value as potentially secret. Shared lists may have multiple container consumers.",
|
|
26089
|
+
inputSchema: { list_filter: string().optional().describe("Exact list name") },
|
|
26090
|
+
async handler(a, ctx) {
|
|
26091
|
+
const cmd = new Cmd("/container envs print").raw("detail").set("proplist", ".id,list,key,disabled");
|
|
26092
|
+
if (a.list_filter !== undefined)
|
|
26093
|
+
cmd.raw("where").set("list", a.list_filter);
|
|
26094
|
+
return `CONTAINER ENV METADATA (values omitted):
|
|
26095
|
+
|
|
26096
|
+
${redactContainerText(await containerRead(cmd.build(), ctx))}`;
|
|
26097
|
+
}
|
|
26098
|
+
}),
|
|
26099
|
+
defineTool2({
|
|
26100
|
+
name: "add_container_env",
|
|
26101
|
+
title: "Add Container Env Variable",
|
|
26102
|
+
annotations: WRITE,
|
|
26103
|
+
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.",
|
|
26104
|
+
inputSchema: { list: textValue, key: textValue, value: string() },
|
|
26105
|
+
async handler(a, ctx) {
|
|
26106
|
+
const count = await containerRead(new Cmd("/container envs print count-only where").set("list", a.list).set("key", a.key).build(), ctx);
|
|
26107
|
+
if (count.trim() !== "0")
|
|
26108
|
+
throw new Error("Env entry exists or uniqueness is unknown; no mutation performed.");
|
|
26109
|
+
await containerWrite(new Cmd("/container envs add").set("list", a.list).set("key", a.key).set("value", a.value).build(), ctx);
|
|
26110
|
+
const countAfter = await containerReadBack(new Cmd("/container envs print count-only where").set("list", a.list).set("key", a.key).build(), ctx);
|
|
26111
|
+
return countAfter.trim() === "1" ? "Env entry creation verified; value omitted." : "Env add accepted; read-back UNVERIFIED. Inspect before retrying.";
|
|
26112
|
+
}
|
|
26113
|
+
}),
|
|
26114
|
+
defineTool2({
|
|
26115
|
+
name: "remove_container_env",
|
|
26116
|
+
title: "Remove Container Env Variable",
|
|
26117
|
+
annotations: DESTRUCTIVE,
|
|
26118
|
+
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.",
|
|
26119
|
+
inputSchema: { id: IDENTITY.id, list: textValue.optional(), key: textValue.optional() },
|
|
26120
|
+
async handler(a, ctx) {
|
|
26121
|
+
if (a.id ? a.list !== undefined || a.key !== undefined : !a.list || !a.key)
|
|
26122
|
+
throw new Error("Provide id OR both list and key.");
|
|
26123
|
+
const id = await resolveContainerItem("/container envs", a.id ? { ".id": a.id } : { list: a.list, key: a.key }, ctx);
|
|
26124
|
+
await containerWrite(new Cmd("/container envs remove").set("numbers", id).build(), ctx);
|
|
26125
|
+
const count = await containerReadBack(new Cmd("/container envs print count-only where").set(".id", id).build(), ctx);
|
|
26126
|
+
return count.trim() === "0" ? "Env removal verified." : "Env removal accepted; absence UNVERIFIED. Inspect before retrying.";
|
|
26127
|
+
}
|
|
26128
|
+
}),
|
|
26129
|
+
defineTool2({
|
|
26130
|
+
name: "list_container_mounts",
|
|
26131
|
+
title: "List Container Mounts",
|
|
26132
|
+
annotations: READ,
|
|
26133
|
+
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.",
|
|
26134
|
+
inputSchema: {
|
|
26135
|
+
list_filter: textValue.optional(),
|
|
26136
|
+
name_filter: textValue.optional().describe("Legacy exact name filter")
|
|
26137
|
+
},
|
|
26138
|
+
async handler(a, ctx) {
|
|
26139
|
+
if (a.list_filter !== undefined && a.name_filter !== undefined)
|
|
26140
|
+
throw new Error("Choose list_filter or legacy name_filter.");
|
|
26141
|
+
const cmd = new Cmd("/container mounts print detail");
|
|
26142
|
+
if (a.list_filter !== undefined)
|
|
26143
|
+
cmd.raw("where").set("list", a.list_filter);
|
|
26144
|
+
if (a.name_filter !== undefined)
|
|
26145
|
+
cmd.raw("where").set("name", a.name_filter);
|
|
26146
|
+
return `CONTAINER MOUNTS:
|
|
26147
|
+
|
|
26148
|
+
${redactContainerText(await containerRead(cmd.build(), ctx))}`;
|
|
26149
|
+
}
|
|
26150
|
+
}),
|
|
26151
|
+
defineTool2({
|
|
26152
|
+
name: "add_container_mount",
|
|
26153
|
+
title: "Add Container Mount",
|
|
26154
|
+
annotations: WRITE,
|
|
26155
|
+
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.",
|
|
26156
|
+
inputSchema: {
|
|
26157
|
+
list: textValue.optional().describe("Current CLI mount-list name"),
|
|
26158
|
+
name: textValue.optional().describe("Legacy CLI mount name; do not use for current list syntax"),
|
|
26159
|
+
src: textValue,
|
|
26160
|
+
dst: textValue
|
|
26161
|
+
},
|
|
26162
|
+
async handler(a, ctx) {
|
|
26163
|
+
if (Boolean(a.list) === Boolean(a.name))
|
|
26164
|
+
throw new Error("Provide list OR legacy name.");
|
|
26165
|
+
const selector = new Cmd("").opt("list", a.list).opt("name", a.name).set("src", a.src).set("dst", a.dst).build().trim();
|
|
26166
|
+
const count = await containerRead(`/container mounts print count-only where ${selector}`, ctx);
|
|
26167
|
+
if (count.trim() !== "0")
|
|
26168
|
+
throw new Error("Mount exists or uniqueness is unknown; no mutation performed.");
|
|
26169
|
+
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);
|
|
26170
|
+
const countAfter = await containerReadBack(`/container mounts print count-only where ${selector}`, ctx);
|
|
26171
|
+
return countAfter.trim() === "1" ? "Mount creation verified; inspect application data separately." : "Mount add accepted; read-back UNVERIFIED. Inspect before retrying.";
|
|
26172
|
+
}
|
|
26173
|
+
}),
|
|
26174
|
+
defineTool2({
|
|
26175
|
+
name: "remove_container_mount",
|
|
26176
|
+
title: "Remove Container Mount",
|
|
26177
|
+
annotations: DESTRUCTIVE,
|
|
26178
|
+
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.",
|
|
26179
|
+
inputSchema: {
|
|
26180
|
+
id: IDENTITY.id,
|
|
26181
|
+
list: textValue.optional(),
|
|
26182
|
+
name: textValue.optional(),
|
|
26183
|
+
src: textValue.optional(),
|
|
26184
|
+
dst: textValue.optional()
|
|
26185
|
+
},
|
|
26186
|
+
async handler(a, ctx) {
|
|
26187
|
+
if ([a.id, a.list, a.name].filter((v) => v !== undefined).length !== 1 || a.id && (a.src || a.dst))
|
|
26188
|
+
throw new Error("Provide id OR list/name with optional src/dst.");
|
|
26189
|
+
const id = await resolveContainerItem("/container mounts", a.id ? { ".id": a.id } : { list: a.list, name: a.name, src: a.src, dst: a.dst }, ctx);
|
|
26190
|
+
await containerWrite(new Cmd("/container mounts remove").set("numbers", id).build(), ctx);
|
|
26191
|
+
const count = await containerReadBack(new Cmd("/container mounts print count-only where").set(".id", id).build(), ctx);
|
|
26192
|
+
return count.trim() === "0" ? "Mount definition removal verified; host files were not touched." : "Mount removal accepted; absence UNVERIFIED. Inspect before retrying.";
|
|
26193
|
+
}
|
|
26194
|
+
})
|
|
26195
|
+
];
|
|
26196
|
+
var containerTools = [
|
|
26197
|
+
defineTool2({
|
|
26198
|
+
name: "get_routeros_container_guide",
|
|
26199
|
+
title: "Get RouterOS Container Guide",
|
|
26200
|
+
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.",
|
|
26201
|
+
annotations: READ,
|
|
26202
|
+
noDevice: true,
|
|
26203
|
+
inputSchema: { topic: _enum(["all", ...CONTAINER_GUIDE_TOPICS]).default("all") },
|
|
26204
|
+
async handler(a) {
|
|
26205
|
+
return getRouterosContainerGuide(a.topic);
|
|
26206
|
+
}
|
|
26207
|
+
}),
|
|
26208
|
+
...withRequires({ packages: ["container"], deviceMode: "container", minVersion: "7.0" }, deviceTools2)
|
|
26209
|
+
];
|
|
26210
|
+
|
|
24098
26211
|
// src/core/firewall-audit.ts
|
|
24099
|
-
import * as
|
|
26212
|
+
import * as ipaddr3 from "ipaddr.js";
|
|
24100
26213
|
|
|
24101
26214
|
// src/schedule/identity.ts
|
|
24102
|
-
import { createHash as
|
|
26215
|
+
import { createHash as createHash7 } from "crypto";
|
|
24103
26216
|
function stableId(prefix, parts) {
|
|
24104
26217
|
const material = parts.filter((p) => p !== undefined && p !== "").map((p) => String(p).trim().toLowerCase()).join(" | ");
|
|
24105
|
-
const digest =
|
|
26218
|
+
const digest = createHash7("sha256").update(material, "utf8").digest("hex").slice(0, 12);
|
|
24106
26219
|
return `${prefix}:${digest}`;
|
|
24107
26220
|
}
|
|
24108
26221
|
function ruleFingerprint(rule) {
|
|
@@ -24215,8 +26328,8 @@ function rulesFromRows(rows) {
|
|
|
24215
26328
|
function toCidr(value) {
|
|
24216
26329
|
try {
|
|
24217
26330
|
if (value.includes("/"))
|
|
24218
|
-
return
|
|
24219
|
-
const addr =
|
|
26331
|
+
return ipaddr3.parseCIDR(value);
|
|
26332
|
+
const addr = ipaddr3.parse(value);
|
|
24220
26333
|
return [addr, addr.kind() === "ipv6" ? 128 : 32];
|
|
24221
26334
|
} catch {
|
|
24222
26335
|
return null;
|
|
@@ -24683,395 +26796,8 @@ function tailLines(text, n) {
|
|
|
24683
26796
|
return lines.length <= n ? text : lines.slice(-n).join(`
|
|
24684
26797
|
`);
|
|
24685
26798
|
}
|
|
24686
|
-
// src/tools/container.ts
|
|
24687
|
-
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).";
|
|
24688
|
-
function containerMatch(name, tag) {
|
|
24689
|
-
if (name)
|
|
24690
|
-
return `name=${quoteValue(name)}`;
|
|
24691
|
-
if (tag)
|
|
24692
|
-
return `tag~${quoteValue(tag)}`;
|
|
24693
|
-
return null;
|
|
24694
|
-
}
|
|
24695
|
-
var IDENTITY = {
|
|
24696
|
-
name: string().optional().describe("Container name (set via add_container)"),
|
|
24697
|
-
tag: string().optional().describe("Image tag to match (e.g. 'pihole') if no name")
|
|
24698
|
-
};
|
|
24699
|
-
var containerToolsDefs = [
|
|
24700
|
-
defineTool2({
|
|
24701
|
-
name: "list_containers",
|
|
24702
|
-
title: "List Containers",
|
|
24703
|
-
annotations: READ,
|
|
24704
|
-
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.',
|
|
24705
|
-
inputSchema: {
|
|
24706
|
-
name_filter: string().optional().describe("Partial container name match"),
|
|
24707
|
-
tag_filter: string().optional().describe("Partial image tag match"),
|
|
24708
|
-
status_filter: string().optional().describe("e.g. 'running', 'stopped'"),
|
|
24709
|
-
detail: boolean().default(false).describe("Show the full per-container property block")
|
|
24710
|
-
},
|
|
24711
|
-
async handler(a, ctx) {
|
|
24712
|
-
ctx.info("Listing containers");
|
|
24713
|
-
const filters = [];
|
|
24714
|
-
if (a.name_filter)
|
|
24715
|
-
filters.push(`name~"${a.name_filter}"`);
|
|
24716
|
-
if (a.tag_filter)
|
|
24717
|
-
filters.push(`tag~"${a.tag_filter}"`);
|
|
24718
|
-
if (a.status_filter)
|
|
24719
|
-
filters.push(`status~"${a.status_filter}"`);
|
|
24720
|
-
const result = await executeMikrotikCommand2(`/container print${a.detail ? " detail" : ""}${whereClause(filters)}`, ctx);
|
|
24721
|
-
if (commandUnsupported(result))
|
|
24722
|
-
return NOT_AVAILABLE;
|
|
24723
|
-
return isEmpty(result) ? "No containers found matching the criteria." : `CONTAINERS:
|
|
24724
|
-
|
|
24725
|
-
${redactSecrets(result)}`;
|
|
24726
|
-
}
|
|
24727
|
-
}),
|
|
24728
|
-
defineTool2({
|
|
24729
|
-
name: "get_container",
|
|
24730
|
-
title: "Get Container Detail",
|
|
24731
|
-
annotations: READ,
|
|
24732
|
-
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.",
|
|
24733
|
-
inputSchema: { ...IDENTITY },
|
|
24734
|
-
async handler(a, ctx) {
|
|
24735
|
-
const match = containerMatch(a.name, a.tag);
|
|
24736
|
-
if (!match)
|
|
24737
|
-
return "Provide a container name or tag.";
|
|
24738
|
-
ctx.info(`Getting container detail: ${match}`);
|
|
24739
|
-
const result = await executeMikrotikCommand2(`/container print detail where ${match}`, ctx);
|
|
24740
|
-
if (commandUnsupported(result))
|
|
24741
|
-
return NOT_AVAILABLE;
|
|
24742
|
-
return isEmpty(result) ? `Container (${match}) not found.` : `CONTAINER DETAILS:
|
|
24743
|
-
|
|
24744
|
-
${redactSecrets(result)}`;
|
|
24745
|
-
}
|
|
24746
|
-
}),
|
|
24747
|
-
defineTool2({
|
|
24748
|
-
name: "add_container",
|
|
24749
|
-
title: "Add Container",
|
|
24750
|
-
annotations: WRITE,
|
|
24751
|
-
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.",
|
|
24752
|
-
inputSchema: {
|
|
24753
|
-
name: string().optional().describe("Container name (recommended for management)"),
|
|
24754
|
-
remote_image: string().optional().describe("Registry image, e.g. 'library/alpine:latest'"),
|
|
24755
|
-
file: string().optional().describe("Local Docker-v1 tar on the device (alternative to remote_image)"),
|
|
24756
|
-
interface: string().optional().describe("VETH interface name"),
|
|
24757
|
-
root_dir: string().optional().describe("Filesystem root, e.g. 'disk1/myapp'"),
|
|
24758
|
-
env: string().optional().describe("Inline env vars: 'K=v,K2=v2' (7.21+)"),
|
|
24759
|
-
envlists: string().optional().describe("Named env list name(s) (add_container_env)"),
|
|
24760
|
-
mount: string().optional().describe("Inline mount: 'src=disk1/data,dst=/data' (7.21+)"),
|
|
24761
|
-
mountlists: string().optional().describe("Named mount name(s) (add_container_mount)"),
|
|
24762
|
-
cmd: string().optional().describe("Override container CMD"),
|
|
24763
|
-
entrypoint: string().optional().describe("Override container ENTRYPOINT"),
|
|
24764
|
-
workdir: string().optional().describe("Override working directory"),
|
|
24765
|
-
hostname: string().optional(),
|
|
24766
|
-
dns: string().optional().describe("DNS server for the container"),
|
|
24767
|
-
user: string().optional(),
|
|
24768
|
-
stop_signal: string().optional().describe("Signal used to stop the container"),
|
|
24769
|
-
devices: string().optional().describe("Pass-through physical devices (7.20+)"),
|
|
24770
|
-
cpu_list: string().optional().describe("CPU core affinity"),
|
|
24771
|
-
memory_high: string().optional().describe("RAM limit, e.g. '256M'"),
|
|
24772
|
-
logging: boolean().optional().describe("Send stdout/stderr to the RouterOS log"),
|
|
24773
|
-
start_on_boot: boolean().optional().describe("Auto-start on device boot"),
|
|
24774
|
-
comment: string().optional()
|
|
24775
|
-
},
|
|
24776
|
-
async handler(a, ctx) {
|
|
24777
|
-
if (!a.remote_image && !a.file)
|
|
24778
|
-
return "Provide remote_image (registry pull) or file (local tar).";
|
|
24779
|
-
ctx.info(`Adding container: ${a.name ?? a.remote_image ?? a.file}`);
|
|
24780
|
-
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();
|
|
24781
|
-
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
24782
|
-
if (commandUnsupported(result))
|
|
24783
|
-
return NOT_AVAILABLE;
|
|
24784
|
-
if (looksLikeError(result))
|
|
24785
|
-
return `Failed to add container: ${redactSecrets(result)}`;
|
|
24786
|
-
return `Container added (image is pulling/extracting asynchronously \u2014 poll list_containers until status is ` + `'stopped', then start_container).
|
|
24787
|
-
|
|
24788
|
-
${redactSecrets(result)}`;
|
|
24789
|
-
}
|
|
24790
|
-
}),
|
|
24791
|
-
defineTool2({
|
|
24792
|
-
name: "update_container",
|
|
24793
|
-
title: "Update Container",
|
|
24794
|
-
annotations: WRITE_IDEMPOTENT,
|
|
24795
|
-
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.",
|
|
24796
|
-
inputSchema: {
|
|
24797
|
-
...IDENTITY,
|
|
24798
|
-
interface: string().optional(),
|
|
24799
|
-
root_dir: string().optional(),
|
|
24800
|
-
env: string().optional(),
|
|
24801
|
-
envlists: string().optional(),
|
|
24802
|
-
mount: string().optional(),
|
|
24803
|
-
mountlists: string().optional(),
|
|
24804
|
-
cmd: string().optional(),
|
|
24805
|
-
entrypoint: string().optional(),
|
|
24806
|
-
workdir: string().optional(),
|
|
24807
|
-
hostname: string().optional(),
|
|
24808
|
-
dns: string().optional(),
|
|
24809
|
-
cpu_list: string().optional(),
|
|
24810
|
-
memory_high: string().optional(),
|
|
24811
|
-
logging: boolean().optional(),
|
|
24812
|
-
start_on_boot: boolean().optional(),
|
|
24813
|
-
comment: string().optional()
|
|
24814
|
-
},
|
|
24815
|
-
async handler(a, ctx) {
|
|
24816
|
-
const match = containerMatch(a.name, a.tag);
|
|
24817
|
-
if (!match)
|
|
24818
|
-
return "Provide a container name or tag.";
|
|
24819
|
-
ctx.info(`Updating container: ${match}`);
|
|
24820
|
-
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();
|
|
24821
|
-
if (cmd.endsWith("]"))
|
|
24822
|
-
return "No updates specified.";
|
|
24823
|
-
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
24824
|
-
if (commandUnsupported(result))
|
|
24825
|
-
return NOT_AVAILABLE;
|
|
24826
|
-
if (looksLikeError(result))
|
|
24827
|
-
return `Failed to update container: ${redactSecrets(result)}`;
|
|
24828
|
-
return `Container (${match}) updated.`;
|
|
24829
|
-
}
|
|
24830
|
-
}),
|
|
24831
|
-
defineTool2({
|
|
24832
|
-
name: "start_container",
|
|
24833
|
-
title: "Start Container",
|
|
24834
|
-
annotations: WRITE,
|
|
24835
|
-
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.",
|
|
24836
|
-
inputSchema: { ...IDENTITY },
|
|
24837
|
-
async handler(a, ctx) {
|
|
24838
|
-
const match = containerMatch(a.name, a.tag);
|
|
24839
|
-
if (!match)
|
|
24840
|
-
return "Provide a container name or tag.";
|
|
24841
|
-
ctx.info(`Starting container: ${match}`);
|
|
24842
|
-
const count = await executeMikrotikCommand2(`/container print count-only where ${match}`, ctx);
|
|
24843
|
-
if (commandUnsupported(count))
|
|
24844
|
-
return NOT_AVAILABLE;
|
|
24845
|
-
if (count.trim() === "0")
|
|
24846
|
-
return `Container (${match}) not found.`;
|
|
24847
|
-
const result = await executeMikrotikCommand2(`/container start [find ${match}]`, ctx);
|
|
24848
|
-
if (looksLikeError(result))
|
|
24849
|
-
return `Failed to start container: ${result}`;
|
|
24850
|
-
return `Container (${match}) starting.`;
|
|
24851
|
-
}
|
|
24852
|
-
}),
|
|
24853
|
-
defineTool2({
|
|
24854
|
-
name: "stop_container",
|
|
24855
|
-
title: "Stop Container",
|
|
24856
|
-
annotations: WRITE,
|
|
24857
|
-
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.",
|
|
24858
|
-
inputSchema: { ...IDENTITY },
|
|
24859
|
-
async handler(a, ctx) {
|
|
24860
|
-
const match = containerMatch(a.name, a.tag);
|
|
24861
|
-
if (!match)
|
|
24862
|
-
return "Provide a container name or tag.";
|
|
24863
|
-
ctx.info(`Stopping container: ${match}`);
|
|
24864
|
-
const count = await executeMikrotikCommand2(`/container print count-only where ${match}`, ctx);
|
|
24865
|
-
if (commandUnsupported(count))
|
|
24866
|
-
return NOT_AVAILABLE;
|
|
24867
|
-
if (count.trim() === "0")
|
|
24868
|
-
return `Container (${match}) not found.`;
|
|
24869
|
-
const result = await executeMikrotikCommand2(`/container stop [find ${match}]`, ctx);
|
|
24870
|
-
if (looksLikeError(result))
|
|
24871
|
-
return `Failed to stop container: ${result}`;
|
|
24872
|
-
return `Container (${match}) stopping (poll list_containers for status 'stopped').`;
|
|
24873
|
-
}
|
|
24874
|
-
}),
|
|
24875
|
-
defineTool2({
|
|
24876
|
-
name: "remove_container",
|
|
24877
|
-
title: "Remove Container",
|
|
24878
|
-
annotations: DESTRUCTIVE,
|
|
24879
|
-
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.",
|
|
24880
|
-
inputSchema: { ...IDENTITY },
|
|
24881
|
-
async handler(a, ctx) {
|
|
24882
|
-
const match = containerMatch(a.name, a.tag);
|
|
24883
|
-
if (!match)
|
|
24884
|
-
return "Provide a container name or tag.";
|
|
24885
|
-
ctx.info(`Removing container: ${match}`);
|
|
24886
|
-
const count = await executeMikrotikCommand2(`/container print count-only where ${match}`, ctx);
|
|
24887
|
-
if (commandUnsupported(count))
|
|
24888
|
-
return NOT_AVAILABLE;
|
|
24889
|
-
if (count.trim() === "0")
|
|
24890
|
-
return `Container (${match}) not found.`;
|
|
24891
|
-
const result = await executeMikrotikCommand2(`/container remove [find ${match}]`, ctx);
|
|
24892
|
-
if (looksLikeError(result)) {
|
|
24893
|
-
return `Failed to remove container: ${result}
|
|
24894
|
-
|
|
24895
|
-
If it is still running/stopping, stop it first ` + `(stop_container), wait until list_containers shows status 'stopped', then retry.`;
|
|
24896
|
-
}
|
|
24897
|
-
return `Container (${match}) removed.`;
|
|
24898
|
-
}
|
|
24899
|
-
}),
|
|
24900
|
-
defineTool2({
|
|
24901
|
-
name: "get_container_config",
|
|
24902
|
-
title: "Get Container Global Config",
|
|
24903
|
-
annotations: READ,
|
|
24904
|
-
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.",
|
|
24905
|
-
async handler(_a, ctx) {
|
|
24906
|
-
ctx.info("Getting container config");
|
|
24907
|
-
const result = await executeMikrotikCommand2("/container config print", ctx);
|
|
24908
|
-
if (commandUnsupported(result))
|
|
24909
|
-
return NOT_AVAILABLE;
|
|
24910
|
-
return isEmpty(result) ? "No container config found." : `CONTAINER CONFIG:
|
|
24911
|
-
|
|
24912
|
-
${redactSecrets(result)}`;
|
|
24913
|
-
}
|
|
24914
|
-
}),
|
|
24915
|
-
defineTool2({
|
|
24916
|
-
name: "set_container_config",
|
|
24917
|
-
title: "Set Container Global Config",
|
|
24918
|
-
annotations: WRITE_IDEMPOTENT,
|
|
24919
|
-
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.",
|
|
24920
|
-
inputSchema: {
|
|
24921
|
-
registry_url: string().optional().describe("Image registry URL"),
|
|
24922
|
-
tmpdir: string().optional().describe("Pull/extract temp dir, e.g. 'disk1/pull'"),
|
|
24923
|
-
layer_dir: string().optional().describe("Directory for extracted image layers"),
|
|
24924
|
-
ram_high: string().optional().describe("RAM-high limit, e.g. '256M'"),
|
|
24925
|
-
username: string().optional().describe("Registry username (private registries)"),
|
|
24926
|
-
password: string().optional().describe("Registry password (private registries)")
|
|
24927
|
-
},
|
|
24928
|
-
async handler(a, ctx) {
|
|
24929
|
-
ctx.info("Setting container config");
|
|
24930
|
-
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();
|
|
24931
|
-
if (cmd === "/container config set")
|
|
24932
|
-
return "No updates specified.";
|
|
24933
|
-
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
24934
|
-
if (commandUnsupported(result))
|
|
24935
|
-
return NOT_AVAILABLE;
|
|
24936
|
-
if (looksLikeError(result))
|
|
24937
|
-
return `Failed to set container config: ${redactSecrets(result)}`;
|
|
24938
|
-
const detail = await executeMikrotikCommand2("/container config print", ctx);
|
|
24939
|
-
return `Container config updated.
|
|
24940
|
-
|
|
24941
|
-
${redactSecrets(detail)}`;
|
|
24942
|
-
}
|
|
24943
|
-
}),
|
|
24944
|
-
defineTool2({
|
|
24945
|
-
name: "list_container_envs",
|
|
24946
|
-
title: "List Container Env Variables",
|
|
24947
|
-
annotations: READ,
|
|
24948
|
-
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.",
|
|
24949
|
-
inputSchema: {
|
|
24950
|
-
list_filter: string().optional().describe("Partial env-list (group) name match")
|
|
24951
|
-
},
|
|
24952
|
-
async handler(a, ctx) {
|
|
24953
|
-
ctx.info("Listing container envs");
|
|
24954
|
-
const filters = [];
|
|
24955
|
-
if (a.list_filter)
|
|
24956
|
-
filters.push(`list~"${a.list_filter}"`);
|
|
24957
|
-
const result = await executeMikrotikCommand2(`/container envs print${whereClause(filters)}`, ctx);
|
|
24958
|
-
if (commandUnsupported(result))
|
|
24959
|
-
return NOT_AVAILABLE;
|
|
24960
|
-
return isEmpty(result) ? "No container env variables found." : `CONTAINER ENVS:
|
|
24961
|
-
|
|
24962
|
-
${redactSecrets(result)}`;
|
|
24963
|
-
}
|
|
24964
|
-
}),
|
|
24965
|
-
defineTool2({
|
|
24966
|
-
name: "add_container_env",
|
|
24967
|
-
title: "Add Container Env Variable",
|
|
24968
|
-
annotations: WRITE,
|
|
24969
|
-
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.",
|
|
24970
|
-
inputSchema: {
|
|
24971
|
-
list: string().describe("Env-list (group) name, e.g. 'MYAPP'"),
|
|
24972
|
-
key: string().describe("Variable name, e.g. 'TZ'"),
|
|
24973
|
-
value: string().describe("Variable value")
|
|
24974
|
-
},
|
|
24975
|
-
async handler(a, ctx) {
|
|
24976
|
-
ctx.info(`Adding container env: list=${a.list} key=${a.key}`);
|
|
24977
|
-
const cmd = new Cmd("/container envs add").set("list", a.list).set("key", a.key).set("value", a.value).build();
|
|
24978
|
-
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
24979
|
-
if (commandUnsupported(result))
|
|
24980
|
-
return NOT_AVAILABLE;
|
|
24981
|
-
if (looksLikeError(result))
|
|
24982
|
-
return `Failed to add env variable: ${redactSecrets(result)}`;
|
|
24983
|
-
return `Env '${a.key}' added to list '${a.list}'.`;
|
|
24984
|
-
}
|
|
24985
|
-
}),
|
|
24986
|
-
defineTool2({
|
|
24987
|
-
name: "remove_container_env",
|
|
24988
|
-
title: "Remove Container Env Variable",
|
|
24989
|
-
annotations: DESTRUCTIVE,
|
|
24990
|
-
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.",
|
|
24991
|
-
inputSchema: {
|
|
24992
|
-
list: string().describe("Env-list (group) name"),
|
|
24993
|
-
key: string().describe("Variable name to remove")
|
|
24994
|
-
},
|
|
24995
|
-
async handler(a, ctx) {
|
|
24996
|
-
ctx.info(`Removing container env: list=${a.list} key=${a.key}`);
|
|
24997
|
-
const where = `list=${quoteValue(a.list)} key=${quoteValue(a.key)}`;
|
|
24998
|
-
const count = await executeMikrotikCommand2(`/container envs print count-only where ${where}`, ctx);
|
|
24999
|
-
if (commandUnsupported(count))
|
|
25000
|
-
return NOT_AVAILABLE;
|
|
25001
|
-
if (count.trim() === "0")
|
|
25002
|
-
return `Env '${a.key}' in list '${a.list}' not found.`;
|
|
25003
|
-
const result = await executeMikrotikCommand2(`/container envs remove [find ${where}]`, ctx);
|
|
25004
|
-
if (looksLikeError(result))
|
|
25005
|
-
return `Failed to remove env variable: ${result}`;
|
|
25006
|
-
return `Env '${a.key}' removed from list '${a.list}'.`;
|
|
25007
|
-
}
|
|
25008
|
-
}),
|
|
25009
|
-
defineTool2({
|
|
25010
|
-
name: "list_container_mounts",
|
|
25011
|
-
title: "List Container Mounts",
|
|
25012
|
-
annotations: READ,
|
|
25013
|
-
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.",
|
|
25014
|
-
inputSchema: {
|
|
25015
|
-
name_filter: string().optional().describe("Partial mount name match")
|
|
25016
|
-
},
|
|
25017
|
-
async handler(a, ctx) {
|
|
25018
|
-
ctx.info("Listing container mounts");
|
|
25019
|
-
const filters = [];
|
|
25020
|
-
if (a.name_filter)
|
|
25021
|
-
filters.push(`name~"${a.name_filter}"`);
|
|
25022
|
-
const result = await executeMikrotikCommand2(`/container mounts print${whereClause(filters)}`, ctx);
|
|
25023
|
-
if (commandUnsupported(result))
|
|
25024
|
-
return NOT_AVAILABLE;
|
|
25025
|
-
return isEmpty(result) ? "No container mounts found." : `CONTAINER MOUNTS:
|
|
25026
|
-
|
|
25027
|
-
${result}`;
|
|
25028
|
-
}
|
|
25029
|
-
}),
|
|
25030
|
-
defineTool2({
|
|
25031
|
-
name: "add_container_mount",
|
|
25032
|
-
title: "Add Container Mount",
|
|
25033
|
-
annotations: WRITE,
|
|
25034
|
-
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+.",
|
|
25035
|
-
inputSchema: {
|
|
25036
|
-
name: string().describe("Mount name, e.g. 'appdata'"),
|
|
25037
|
-
src: string().describe("Host source path, e.g. 'disk1/appdata'"),
|
|
25038
|
-
dst: string().describe("Container destination path, e.g. '/data'")
|
|
25039
|
-
},
|
|
25040
|
-
async handler(a, ctx) {
|
|
25041
|
-
ctx.info(`Adding container mount: name=${a.name}`);
|
|
25042
|
-
const cmd = new Cmd("/container mounts add").set("name", a.name).set("src", a.src).set("dst", a.dst).build();
|
|
25043
|
-
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
25044
|
-
if (commandUnsupported(result))
|
|
25045
|
-
return NOT_AVAILABLE;
|
|
25046
|
-
if (looksLikeError(result))
|
|
25047
|
-
return `Failed to add mount: ${result}`;
|
|
25048
|
-
return `Mount '${a.name}' (${a.src} \u2192 ${a.dst}) added.`;
|
|
25049
|
-
}
|
|
25050
|
-
}),
|
|
25051
|
-
defineTool2({
|
|
25052
|
-
name: "remove_container_mount",
|
|
25053
|
-
title: "Remove Container Mount",
|
|
25054
|
-
annotations: DESTRUCTIVE,
|
|
25055
|
-
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.",
|
|
25056
|
-
inputSchema: { name: string().describe("Mount name to remove") },
|
|
25057
|
-
async handler(a, ctx) {
|
|
25058
|
-
ctx.info(`Removing container mount: name=${a.name}`);
|
|
25059
|
-
const count = await executeMikrotikCommand2(`/container mounts print count-only where name="${a.name}"`, ctx);
|
|
25060
|
-
if (commandUnsupported(count))
|
|
25061
|
-
return NOT_AVAILABLE;
|
|
25062
|
-
if (count.trim() === "0")
|
|
25063
|
-
return `Mount '${a.name}' not found.`;
|
|
25064
|
-
const result = await executeMikrotikCommand2(`/container mounts remove [find name="${a.name}"]`, ctx);
|
|
25065
|
-
if (looksLikeError(result))
|
|
25066
|
-
return `Failed to remove mount: ${result}`;
|
|
25067
|
-
return `Mount '${a.name}' removed.`;
|
|
25068
|
-
}
|
|
25069
|
-
})
|
|
25070
|
-
];
|
|
25071
|
-
var containerTools = withRequires({ packages: ["container"], deviceMode: "container", minVersion: "7.0" }, containerToolsDefs);
|
|
25072
|
-
|
|
25073
26799
|
// src/tools/disk.ts
|
|
25074
|
-
var
|
|
26800
|
+
var NOT_AVAILABLE = "Disk management is not available on this device (no `/disk` support).";
|
|
25075
26801
|
var ADD_KEYS = new Set([
|
|
25076
26802
|
"type",
|
|
25077
26803
|
"slot",
|
|
@@ -25110,7 +26836,7 @@ var diskTools = [
|
|
|
25110
26836
|
filters.push(`interface~"${a.interface_filter}"`);
|
|
25111
26837
|
const result = await executeMikrotikCommand2(`/disk print${a.detail ? " detail" : ""}${whereClause(filters)}`, ctx);
|
|
25112
26838
|
if (commandUnsupported(result))
|
|
25113
|
-
return
|
|
26839
|
+
return NOT_AVAILABLE;
|
|
25114
26840
|
return isEmpty(result) ? "No disks found matching the criteria." : `DISKS:
|
|
25115
26841
|
|
|
25116
26842
|
${result}`;
|
|
@@ -25126,7 +26852,7 @@ ${result}`;
|
|
|
25126
26852
|
ctx.info(`Getting disk details: slot=${a.slot}`);
|
|
25127
26853
|
const result = await executeMikrotikCommand2(`/disk print detail where slot="${a.slot}"`, ctx);
|
|
25128
26854
|
if (commandUnsupported(result))
|
|
25129
|
-
return
|
|
26855
|
+
return NOT_AVAILABLE;
|
|
25130
26856
|
return isEmpty(result) ? `Disk '${a.slot}' not found.` : `DISK DETAILS:
|
|
25131
26857
|
|
|
25132
26858
|
${result}`;
|
|
@@ -25153,7 +26879,7 @@ ${result}`;
|
|
|
25153
26879
|
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();
|
|
25154
26880
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
25155
26881
|
if (commandUnsupported(result))
|
|
25156
|
-
return
|
|
26882
|
+
return NOT_AVAILABLE;
|
|
25157
26883
|
if (looksLikeError(result))
|
|
25158
26884
|
return `Failed to format disk: ${redactSecrets(result)}`;
|
|
25159
26885
|
return `Formatting disk '${a.slot}'\u2026
|
|
@@ -25181,7 +26907,7 @@ ${redactSecrets(result)}`;
|
|
|
25181
26907
|
return "No updates specified.";
|
|
25182
26908
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
25183
26909
|
if (commandUnsupported(result))
|
|
25184
|
-
return
|
|
26910
|
+
return NOT_AVAILABLE;
|
|
25185
26911
|
if (looksLikeError(result))
|
|
25186
26912
|
return `Failed to update disk: ${result}`;
|
|
25187
26913
|
const detail = await executeMikrotikCommand2(`/disk print detail where slot="${a.slot}"`, ctx);
|
|
@@ -25209,7 +26935,7 @@ ${detail}`;
|
|
|
25209
26935
|
return "No sharing settings specified.";
|
|
25210
26936
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
25211
26937
|
if (commandUnsupported(result))
|
|
25212
|
-
return
|
|
26938
|
+
return NOT_AVAILABLE;
|
|
25213
26939
|
if (looksLikeError(result))
|
|
25214
26940
|
return `Failed to configure disk sharing: ${result}`;
|
|
25215
26941
|
const detail = await executeMikrotikCommand2(`/disk print detail where slot="${a.slot}"`, ctx);
|
|
@@ -25242,7 +26968,7 @@ ${detail}`;
|
|
|
25242
26968
|
const built = cmd.build();
|
|
25243
26969
|
const result = await executeMikrotikCommand2(built, ctx);
|
|
25244
26970
|
if (commandUnsupported(result))
|
|
25245
|
-
return
|
|
26971
|
+
return NOT_AVAILABLE;
|
|
25246
26972
|
if (looksLikeError(result))
|
|
25247
26973
|
return `Failed to add virtual disk: ${redactSecrets(result)}`;
|
|
25248
26974
|
return `Virtual disk (type=${a.type}) added.
|
|
@@ -25260,12 +26986,12 @@ ${redactSecrets(result)}`;
|
|
|
25260
26986
|
ctx.info(`Ejecting disk: slot=${a.slot}`);
|
|
25261
26987
|
const count = await executeMikrotikCommand2(`/disk print count-only where slot="${a.slot}"`, ctx);
|
|
25262
26988
|
if (commandUnsupported(count))
|
|
25263
|
-
return
|
|
26989
|
+
return NOT_AVAILABLE;
|
|
25264
26990
|
if (count.trim() === "0")
|
|
25265
26991
|
return `Disk '${a.slot}' not found.`;
|
|
25266
26992
|
const result = await executeMikrotikCommand2(`/disk eject [find slot="${a.slot}"]`, ctx);
|
|
25267
26993
|
if (commandUnsupported(result))
|
|
25268
|
-
return
|
|
26994
|
+
return NOT_AVAILABLE;
|
|
25269
26995
|
if (looksLikeError(result))
|
|
25270
26996
|
return `Failed to eject disk: ${result}`;
|
|
25271
26997
|
return `Disk '${a.slot}' ejected \u2014 safe to remove.`;
|
|
@@ -25281,7 +27007,7 @@ ${redactSecrets(result)}`;
|
|
|
25281
27007
|
ctx.info(`Removing virtual disk: slot=${a.slot}`);
|
|
25282
27008
|
const count = await executeMikrotikCommand2(`/disk print count-only where slot="${a.slot}"`, ctx);
|
|
25283
27009
|
if (commandUnsupported(count))
|
|
25284
|
-
return
|
|
27010
|
+
return NOT_AVAILABLE;
|
|
25285
27011
|
if (count.trim() === "0")
|
|
25286
27012
|
return `Disk '${a.slot}' not found.`;
|
|
25287
27013
|
const result = await executeMikrotikCommand2(`/disk remove [find slot="${a.slot}"]`, ctx);
|
|
@@ -25424,11 +27150,11 @@ function searchToolIndex(index, query, limit = 8) {
|
|
|
25424
27150
|
|
|
25425
27151
|
// src/tools/tool-gateway.ts
|
|
25426
27152
|
var META_NAMES = new Set(["find_tools", "describe_tool", "invoke_tool"]);
|
|
25427
|
-
var
|
|
27153
|
+
var cache3 = null;
|
|
25428
27154
|
async function gateway() {
|
|
25429
|
-
if (
|
|
25430
|
-
return
|
|
25431
|
-
const { moduleCatalog } = await import("./library-
|
|
27155
|
+
if (cache3)
|
|
27156
|
+
return cache3;
|
|
27157
|
+
const { moduleCatalog } = await import("./library-wj2xfx8h.js");
|
|
25432
27158
|
const forIndex = [];
|
|
25433
27159
|
const byName = new Map;
|
|
25434
27160
|
for (const mod of moduleCatalog) {
|
|
@@ -25446,8 +27172,8 @@ async function gateway() {
|
|
|
25446
27172
|
});
|
|
25447
27173
|
}
|
|
25448
27174
|
}
|
|
25449
|
-
|
|
25450
|
-
return
|
|
27175
|
+
cache3 = { index: buildToolIndex(forIndex), byName };
|
|
27176
|
+
return cache3;
|
|
25451
27177
|
}
|
|
25452
27178
|
function isOptional(field) {
|
|
25453
27179
|
return field.safeParse(undefined).success;
|
|
@@ -27558,7 +29284,7 @@ function auditNetworkSegmentation(state) {
|
|
|
27558
29284
|
target: `/interface ${iface}`,
|
|
27559
29285
|
current: `subnets on one L2 domain: ${distinct.join(", ")}`,
|
|
27560
29286
|
proposed: "move server and client subnets onto separate VLANs / bridges",
|
|
27561
|
-
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. " + "
|
|
29287
|
+
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."
|
|
27562
29288
|
});
|
|
27563
29289
|
}
|
|
27564
29290
|
return findings;
|
|
@@ -28388,7 +30114,7 @@ function evaluatePolicies(policies, model, opts = {}) {
|
|
|
28388
30114
|
|
|
28389
30115
|
// src/policy/load.ts
|
|
28390
30116
|
import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
|
|
28391
|
-
import { dirname as
|
|
30117
|
+
import { dirname as dirname11, isAbsolute, join as join6, resolve as resolve3 } from "path";
|
|
28392
30118
|
|
|
28393
30119
|
// src/policy/schema.ts
|
|
28394
30120
|
var MAX_REGEX_LENGTH = 200;
|
|
@@ -28511,18 +30237,18 @@ function validatePolicyText(text) {
|
|
|
28511
30237
|
var RULE_EXTENSIONS = [".yaml", ".yml", ".json"];
|
|
28512
30238
|
function expand(pattern, cwd) {
|
|
28513
30239
|
const absolute = isAbsolute(pattern) ? pattern : resolve3(cwd, pattern);
|
|
28514
|
-
const base =
|
|
30240
|
+
const base = dirname11(absolute);
|
|
28515
30241
|
const leaf = absolute.slice(base.length + 1);
|
|
28516
30242
|
if (!leaf.includes("*")) {
|
|
28517
30243
|
try {
|
|
28518
|
-
return statSync2(absolute).isDirectory() ? readdirSync2(absolute).filter((f) => RULE_EXTENSIONS.some((e) => f.endsWith(e))).map((f) =>
|
|
30244
|
+
return statSync2(absolute).isDirectory() ? readdirSync2(absolute).filter((f) => RULE_EXTENSIONS.some((e) => f.endsWith(e))).map((f) => join6(absolute, f)).sort() : [absolute];
|
|
28519
30245
|
} catch {
|
|
28520
30246
|
return [];
|
|
28521
30247
|
}
|
|
28522
30248
|
}
|
|
28523
30249
|
const suffix = leaf.replace(/^\*/, "");
|
|
28524
30250
|
try {
|
|
28525
|
-
return readdirSync2(base).filter((f) => suffix === "" ? true : f.endsWith(suffix)).map((f) =>
|
|
30251
|
+
return readdirSync2(base).filter((f) => suffix === "" ? true : f.endsWith(suffix)).map((f) => join6(base, f)).sort();
|
|
28526
30252
|
} catch {
|
|
28527
30253
|
return [];
|
|
28528
30254
|
}
|
|
@@ -28726,7 +30452,7 @@ function renderReport2(report, format, opts = {}) {
|
|
|
28726
30452
|
}
|
|
28727
30453
|
|
|
28728
30454
|
// src/policy/session.ts
|
|
28729
|
-
import { join as
|
|
30455
|
+
import { join as join7 } from "path";
|
|
28730
30456
|
var MAX_REPORTS = 25;
|
|
28731
30457
|
var reports = [];
|
|
28732
30458
|
function rememberReport(report) {
|
|
@@ -28741,7 +30467,7 @@ function recentReports() {
|
|
|
28741
30467
|
return reports;
|
|
28742
30468
|
}
|
|
28743
30469
|
function packagedPolicyPaths() {
|
|
28744
|
-
return [
|
|
30470
|
+
return [join7(PROJECT_ROOT, "policies")];
|
|
28745
30471
|
}
|
|
28746
30472
|
|
|
28747
30473
|
// src/tools/policy.ts
|
|
@@ -37073,7 +38799,7 @@ ${result}`;
|
|
|
37073
38799
|
];
|
|
37074
38800
|
|
|
37075
38801
|
// src/tools/ssh-test.ts
|
|
37076
|
-
async function
|
|
38802
|
+
async function probe2(opts, label, command) {
|
|
37077
38803
|
const client = new MikroTikSSHClient2(opts);
|
|
37078
38804
|
const t0 = Date.now();
|
|
37079
38805
|
try {
|
|
@@ -37107,7 +38833,7 @@ var sshTestTools = [
|
|
|
37107
38833
|
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.`;
|
|
37108
38834
|
}
|
|
37109
38835
|
ctx.info(`Testing SSH from MCP host to configured device '${name}' (${dc.host}:${dc.port})`);
|
|
37110
|
-
return
|
|
38836
|
+
return probe2({
|
|
37111
38837
|
...sshOptionsOf(dc),
|
|
37112
38838
|
jump: resolveJump(dc),
|
|
37113
38839
|
timeoutMs: Math.min(dc.timeoutMs ?? 1e4, 1e4)
|
|
@@ -37130,7 +38856,7 @@ var sshTestTools = [
|
|
|
37130
38856
|
},
|
|
37131
38857
|
async handler(a, ctx) {
|
|
37132
38858
|
ctx.info(`Testing SSH from MCP host to ${a.host}:${a.port} as ${a.username}`);
|
|
37133
|
-
return
|
|
38859
|
+
return probe2({
|
|
37134
38860
|
host: a.host,
|
|
37135
38861
|
port: a.port,
|
|
37136
38862
|
username: a.username,
|
|
@@ -38677,8 +40403,235 @@ var wolTools = [
|
|
|
38677
40403
|
})
|
|
38678
40404
|
];
|
|
38679
40405
|
|
|
40406
|
+
// src/core/openvpn-sessions.ts
|
|
40407
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
40408
|
+
|
|
40409
|
+
// src/core/openvpn-sessions-model.ts
|
|
40410
|
+
function openVpnUptime(value) {
|
|
40411
|
+
const clock = /^(?:(\d+)w)?(?:(\d+)d)?(\d{1,3}):(\d{2}):(\d{2})(?:\.(\d+))?$/.exec(value);
|
|
40412
|
+
if (clock) {
|
|
40413
|
+
if (+clock[4] > 59 || +clock[5] > 59)
|
|
40414
|
+
return null;
|
|
40415
|
+
return +(clock[1] || 0) * 604800 + +(clock[2] || 0) * 86400 + +clock[3] * 3600 + +clock[4] * 60 + +clock[5];
|
|
40416
|
+
}
|
|
40417
|
+
if (!/^(?=\d)(?:\d+w)?(?:\d+d)?(?:\d+h)?(?:\d+m)?(?:\d+(?:\.\d+)?s)?$/.test(value))
|
|
40418
|
+
return null;
|
|
40419
|
+
const units = { w: 604800, d: 86400, h: 3600, m: 60, s: 1 };
|
|
40420
|
+
const seconds = [...value.matchAll(/(\d+(?:\.\d+)?)([wdhms])/g)].reduce((total, part) => total + +part[1] * units[part[2]], 0);
|
|
40421
|
+
return Number.isSafeInteger(Math.floor(seconds)) ? Math.floor(seconds) : null;
|
|
40422
|
+
}
|
|
40423
|
+
|
|
40424
|
+
// src/core/openvpn-sessions.ts
|
|
40425
|
+
var SESSION_LIMIT = 1000;
|
|
40426
|
+
var TICKET_TTL = 60000;
|
|
40427
|
+
var tickets = new Map;
|
|
40428
|
+
var cache4 = new Map;
|
|
40429
|
+
|
|
40430
|
+
class OpenVpnOperationError extends Error {
|
|
40431
|
+
status;
|
|
40432
|
+
constructor(status, message) {
|
|
40433
|
+
super(message);
|
|
40434
|
+
this.status = status;
|
|
40435
|
+
}
|
|
40436
|
+
}
|
|
40437
|
+
var disconnectOpenVpnInput = object({
|
|
40438
|
+
token: string().uuid().describe("Fresh disconnectToken from list_ovpn_sessions on this router; expires after 60 seconds and is single-use."),
|
|
40439
|
+
confirm: literal(true).describe("Explicit operator approval to terminate this one live connection. The client can reconnect.")
|
|
40440
|
+
});
|
|
40441
|
+
function access4(ctx, write = false) {
|
|
40442
|
+
if (!ctx.device)
|
|
40443
|
+
throw new OpenVpnOperationError(400, "Select an explicit router first.");
|
|
40444
|
+
let device;
|
|
40445
|
+
try {
|
|
40446
|
+
device = resolveDeviceName2(ctx.device);
|
|
40447
|
+
} catch {
|
|
40448
|
+
throw new OpenVpnOperationError(400, "Unknown router. Select an enabled router first.");
|
|
40449
|
+
}
|
|
40450
|
+
try {
|
|
40451
|
+
assertDeviceAccess([device], write ? "disconnect_ovpn_session" : "list_ovpn_sessions", write ? "DESTRUCTIVE" : "READ");
|
|
40452
|
+
} catch (e) {
|
|
40453
|
+
throw new OpenVpnOperationError(403, e instanceof Error ? e.message : "Device access denied.");
|
|
40454
|
+
}
|
|
40455
|
+
return device;
|
|
40456
|
+
}
|
|
40457
|
+
function openVpnSessionsCommand() {
|
|
40458
|
+
const find = new Cmd("/ppp active find where").set("service", "ovpn").build();
|
|
40459
|
+
const read = new Cmd("/ppp active print").raw("detail as-value").raw("where").set("service", "ovpn").build();
|
|
40460
|
+
return `{ :if ([:len [${find}]] > ${SESSION_LIMIT}) do={ :error "OpenVPN session limit exceeded" }; :local rows [:toarray ""]; :foreach row in=[${read}] do={ :set ($row->"uptime") [:tostr ($row->"uptime")]; :set ($row->"session-id") [:tostr ($row->"session-id")]; :set ($rows->[:len $rows]) $row }; :put [:serialize to=json options=json.no-string-conversion value=$rows] }`;
|
|
40461
|
+
}
|
|
40462
|
+
function parseOpenVpnSessions(output) {
|
|
40463
|
+
if (output.length > 1e6)
|
|
40464
|
+
throw new Error("OpenVPN session response is too large; no partial list is shown.");
|
|
40465
|
+
let rows;
|
|
40466
|
+
try {
|
|
40467
|
+
rows = JSON.parse(output.trim());
|
|
40468
|
+
} catch {
|
|
40469
|
+
throw new Error("Could not read OpenVPN sessions. Check router connectivity and RouterOS JSON support.");
|
|
40470
|
+
}
|
|
40471
|
+
if (!Array.isArray(rows) || rows.length > SESSION_LIMIT)
|
|
40472
|
+
throw new Error("Invalid OpenVPN session snapshot.");
|
|
40473
|
+
const ids = new Set;
|
|
40474
|
+
return rows.map((row) => {
|
|
40475
|
+
const r = object({
|
|
40476
|
+
".id": string().regex(/^\*[A-Fa-f0-9]+$/),
|
|
40477
|
+
name: string().min(1),
|
|
40478
|
+
service: literal("ovpn"),
|
|
40479
|
+
address: string().default(""),
|
|
40480
|
+
"caller-id": string().default(""),
|
|
40481
|
+
"session-id": string().default(""),
|
|
40482
|
+
uptime: string().default(""),
|
|
40483
|
+
encoding: string().default(""),
|
|
40484
|
+
radius: union([boolean(), string()]).optional()
|
|
40485
|
+
}).parse(row);
|
|
40486
|
+
if (ids.has(r[".id"]))
|
|
40487
|
+
throw new Error("Duplicate OpenVPN session identifier; refresh required.");
|
|
40488
|
+
ids.add(r[".id"]);
|
|
40489
|
+
return {
|
|
40490
|
+
id: r[".id"],
|
|
40491
|
+
name: r.name,
|
|
40492
|
+
address: r.address,
|
|
40493
|
+
callerId: r["caller-id"],
|
|
40494
|
+
sessionId: r["session-id"],
|
|
40495
|
+
encoding: r.encoding,
|
|
40496
|
+
radius: r.radius === true || r.radius === "yes" || r.radius === "true",
|
|
40497
|
+
uptime: r.uptime,
|
|
40498
|
+
uptimeSeconds: openVpnUptime(r.uptime)
|
|
40499
|
+
};
|
|
40500
|
+
});
|
|
40501
|
+
}
|
|
40502
|
+
async function read(ctx) {
|
|
40503
|
+
const output = await executeMikrotikCommand2(openVpnSessionsCommand(), ctx, { maxMs: 1e4 });
|
|
40504
|
+
return parseOpenVpnSessions(output);
|
|
40505
|
+
}
|
|
40506
|
+
async function listOpenVpnSessions(ctx) {
|
|
40507
|
+
const device = access4(ctx);
|
|
40508
|
+
let canDisconnect = true;
|
|
40509
|
+
try {
|
|
40510
|
+
access4(ctx, true);
|
|
40511
|
+
} catch {
|
|
40512
|
+
canDisconnect = false;
|
|
40513
|
+
}
|
|
40514
|
+
let entry = cache4.get(device);
|
|
40515
|
+
if (!entry || entry.expires < Date.now()) {
|
|
40516
|
+
if (cache4.size >= 64)
|
|
40517
|
+
cache4.delete(cache4.keys().next().value);
|
|
40518
|
+
const next = {
|
|
40519
|
+
expires: Infinity,
|
|
40520
|
+
promise: Promise.resolve(null)
|
|
40521
|
+
};
|
|
40522
|
+
next.promise = read(ctx).then((sessions) => {
|
|
40523
|
+
const at = Date.now();
|
|
40524
|
+
for (const [token, ticket] of tickets)
|
|
40525
|
+
if (at - ticket.at >= TICKET_TTL)
|
|
40526
|
+
tickets.delete(token);
|
|
40527
|
+
for (const session of sessions) {
|
|
40528
|
+
if (!session.sessionId || session.uptimeSeconds === null)
|
|
40529
|
+
continue;
|
|
40530
|
+
if (tickets.size >= 1e4)
|
|
40531
|
+
tickets.delete(tickets.keys().next().value);
|
|
40532
|
+
session.disconnectToken = randomUUID9();
|
|
40533
|
+
tickets.set(session.disconnectToken, { device, at, session });
|
|
40534
|
+
}
|
|
40535
|
+
next.expires = at + 2000;
|
|
40536
|
+
return { device, observedAt: at, sessions, canDisconnect: true };
|
|
40537
|
+
}).catch((error) => {
|
|
40538
|
+
if (cache4.get(device) === next)
|
|
40539
|
+
cache4.delete(device);
|
|
40540
|
+
throw error;
|
|
40541
|
+
});
|
|
40542
|
+
cache4.set(device, next);
|
|
40543
|
+
entry = next;
|
|
40544
|
+
}
|
|
40545
|
+
return { ...await entry.promise, canDisconnect };
|
|
40546
|
+
}
|
|
40547
|
+
function disconnectOpenVpnCommand(session) {
|
|
40548
|
+
const literal2 = (value) => {
|
|
40549
|
+
const quoted = quoteValue(value);
|
|
40550
|
+
return quoted.startsWith('"') ? quoted : `"${quoted}"`;
|
|
40551
|
+
};
|
|
40552
|
+
const find = new Cmd("/ppp active find where").raw(`.id=${quoteValue(session.id)}`).set("service", "ovpn").build();
|
|
40553
|
+
const checks = [
|
|
40554
|
+
["name", session.name],
|
|
40555
|
+
["address", session.address],
|
|
40556
|
+
["caller-id", session.callerId],
|
|
40557
|
+
["session-id", session.sessionId]
|
|
40558
|
+
].map(([field, value]) => `([:tostr [/ppp active get $id ${field}]] != ${literal2(value)})`).join(" || ");
|
|
40559
|
+
return `{ :local ids [${find}]; :if ([:len $ids] = 0) do={ :put "ovpn:gone" } else={ :if ([:len $ids] != 1) do={ :error "Ambiguous session" }; :local id [:pick $ids 0]; :if (${checks} || ([/ppp active get $id uptime] < [:totime ${literal2(session.uptime)}])) do={ :put "ovpn:changed" } else={ ${new Cmd("/ppp active remove").raw("$id").build()}; :put "ovpn:sent" } } }`;
|
|
40560
|
+
}
|
|
40561
|
+
async function disconnectOpenVpnSession(input, ctx) {
|
|
40562
|
+
const device = access4(ctx, true);
|
|
40563
|
+
const { token } = disconnectOpenVpnInput.parse(input);
|
|
40564
|
+
const ticket = tickets.get(token);
|
|
40565
|
+
if (!ticket || ticket.device !== device || Date.now() - ticket.at >= TICKET_TTL)
|
|
40566
|
+
throw new OpenVpnOperationError(409, "This session selection expired or belongs to another router. Refresh and select it again.");
|
|
40567
|
+
if (getSafeModeManager2(device).isActive)
|
|
40568
|
+
throw new OpenVpnOperationError(409, "Finish the current Safe Mode session first. Disconnecting a live connection cannot be rolled back.");
|
|
40569
|
+
tickets.delete(token);
|
|
40570
|
+
cache4.delete(device);
|
|
40571
|
+
const { session } = ticket;
|
|
40572
|
+
let output;
|
|
40573
|
+
try {
|
|
40574
|
+
output = (await executeMikrotikCommand2(disconnectOpenVpnCommand(session), ctx, { maxMs: 1e4 })).trim();
|
|
40575
|
+
} catch {
|
|
40576
|
+
return {
|
|
40577
|
+
status: "unverified",
|
|
40578
|
+
message: "The disconnect outcome is unknown. Refresh the sessions before any further action; do not retry this request."
|
|
40579
|
+
};
|
|
40580
|
+
}
|
|
40581
|
+
if (output === "ovpn:gone")
|
|
40582
|
+
return {
|
|
40583
|
+
status: "already-ended",
|
|
40584
|
+
message: "This connection has already ended. No other connection was changed."
|
|
40585
|
+
};
|
|
40586
|
+
if (output === "ovpn:changed")
|
|
40587
|
+
throw new OpenVpnOperationError(409, "The selected connection changed. Nothing was disconnected; refresh and select the current session.");
|
|
40588
|
+
if (output !== "ovpn:sent" || looksLikeError(output))
|
|
40589
|
+
return {
|
|
40590
|
+
status: "unverified",
|
|
40591
|
+
message: "The router did not confirm disconnection. Refresh to reconcile; this request will not be replayed."
|
|
40592
|
+
};
|
|
40593
|
+
try {
|
|
40594
|
+
const current = await read(ctx);
|
|
40595
|
+
if (current.some((s) => s.id === session.id && s.sessionId === session.sessionId))
|
|
40596
|
+
return {
|
|
40597
|
+
status: "unverified",
|
|
40598
|
+
message: "The disconnect was sent, but the selected session is still listed. Refresh before another action."
|
|
40599
|
+
};
|
|
40600
|
+
const reconnected = current.some((s) => s.name === session.name);
|
|
40601
|
+
return {
|
|
40602
|
+
status: "disconnected",
|
|
40603
|
+
message: reconnected ? "Selected connection ended. Another connection for this user is active; it was not touched." : "Selected connection ended. The account is unchanged and can reconnect."
|
|
40604
|
+
};
|
|
40605
|
+
} catch {
|
|
40606
|
+
return {
|
|
40607
|
+
status: "unverified",
|
|
40608
|
+
message: "Disconnect sent, but read-back failed. Refresh when the router is reachable; do not replay this request."
|
|
40609
|
+
};
|
|
40610
|
+
}
|
|
40611
|
+
}
|
|
40612
|
+
|
|
38680
40613
|
// src/tools/openvpn.ts
|
|
38681
40614
|
var openvpnTools = [
|
|
40615
|
+
defineTool2({
|
|
40616
|
+
name: "list_ovpn_sessions",
|
|
40617
|
+
title: "List Active OpenVPN Connections",
|
|
40618
|
+
annotations: READ,
|
|
40619
|
+
description: "Read currently connected OpenVPN users on an explicit router, including assigned IP, caller address, uptime, encoding and RADIUS status. Reads only /ppp active where service=ovpn; does not read secrets, historical sessions, or outbound clients. Returns structured JSON and short-lived disconnect tokens for individual sessions. A cached read is at most two seconds old; errors are not an empty list.",
|
|
40620
|
+
inputSchema: {},
|
|
40621
|
+
async handler(_a, ctx) {
|
|
40622
|
+
return JSON.stringify(await listOpenVpnSessions(ctx));
|
|
40623
|
+
}
|
|
40624
|
+
}),
|
|
40625
|
+
defineTool2({
|
|
40626
|
+
name: "disconnect_ovpn_session",
|
|
40627
|
+
title: "Disconnect One OpenVPN Connection",
|
|
40628
|
+
annotations: DESTRUCTIVE,
|
|
40629
|
+
description: "Disconnect exactly one observed OpenVPN connection after explicit operator approval. First list_ovpn_sessions on the same explicit router, then supply its fresh disconnectToken. Rechecks internal ID, session ID, username, addresses and uptime before removal, then verifies absence. Does not disable or delete the account; clients can reconnect and PPP on-down hooks may run. Can interrupt your own management tunnel. Unknown outcomes must be reconciled by reading again, never automatically retried. Not available during Safe Mode.",
|
|
40630
|
+
inputSchema: disconnectOpenVpnInput.shape,
|
|
40631
|
+
async handler(a, ctx) {
|
|
40632
|
+
return JSON.stringify(await disconnectOpenVpnSession(a, ctx));
|
|
40633
|
+
}
|
|
40634
|
+
}),
|
|
38682
40635
|
defineTool2({
|
|
38683
40636
|
name: "get_ovpn_server",
|
|
38684
40637
|
title: "Get OpenVPN Server Configuration",
|
|
@@ -45267,8 +47220,8 @@ function publishTxn(update) {
|
|
|
45267
47220
|
}
|
|
45268
47221
|
|
|
45269
47222
|
// src/txn/store.ts
|
|
45270
|
-
import { mkdirSync as
|
|
45271
|
-
import { dirname as
|
|
47223
|
+
import { mkdirSync as mkdirSync11 } from "fs";
|
|
47224
|
+
import { dirname as dirname12 } from "path";
|
|
45272
47225
|
function toRecord(txn, ts, label) {
|
|
45273
47226
|
return {
|
|
45274
47227
|
id: txn.id,
|
|
@@ -45404,7 +47357,7 @@ class SqliteTxnStore {
|
|
|
45404
47357
|
async function openTxnStore(path) {
|
|
45405
47358
|
if (path !== ":memory:") {
|
|
45406
47359
|
try {
|
|
45407
|
-
|
|
47360
|
+
mkdirSync11(dirname12(path), { recursive: true });
|
|
45408
47361
|
} catch {}
|
|
45409
47362
|
}
|
|
45410
47363
|
const { Database } = await import("bun:sqlite");
|
|
@@ -46272,8 +48225,8 @@ function createDeviceExecutor2(ctx, rolloutId) {
|
|
|
46272
48225
|
}
|
|
46273
48226
|
|
|
46274
48227
|
// src/rollout/store.ts
|
|
46275
|
-
import { mkdirSync as
|
|
46276
|
-
import { dirname as
|
|
48228
|
+
import { mkdirSync as mkdirSync12 } from "fs";
|
|
48229
|
+
import { dirname as dirname13 } from "path";
|
|
46277
48230
|
function toRecord2(rollout, ts, opts = {}) {
|
|
46278
48231
|
return {
|
|
46279
48232
|
id: rollout.id,
|
|
@@ -46406,7 +48359,7 @@ class SqliteRolloutStore {
|
|
|
46406
48359
|
async function openRolloutStore(path) {
|
|
46407
48360
|
if (path !== ":memory:") {
|
|
46408
48361
|
try {
|
|
46409
|
-
|
|
48362
|
+
mkdirSync12(dirname13(path), { recursive: true });
|
|
46410
48363
|
} catch {}
|
|
46411
48364
|
}
|
|
46412
48365
|
const { Database } = await import("bun:sqlite");
|
|
@@ -46866,7 +48819,7 @@ function rank(severity) {
|
|
|
46866
48819
|
const i = SEVERITY_ORDER4.indexOf(severity);
|
|
46867
48820
|
return i === -1 ? SEVERITY_ORDER4.length : i;
|
|
46868
48821
|
}
|
|
46869
|
-
var
|
|
48822
|
+
var FIELDS2 = [
|
|
46870
48823
|
{ min: 0, max: 59, name: "minute" },
|
|
46871
48824
|
{ min: 0, max: 23, name: "hour" },
|
|
46872
48825
|
{ min: 1, max: 31, name: "day-of-month" },
|
|
@@ -46933,11 +48886,11 @@ function parseCron(expression) {
|
|
|
46933
48886
|
}
|
|
46934
48887
|
const [minute, hour, dom, month, dow] = parts;
|
|
46935
48888
|
return {
|
|
46936
|
-
minutes: parseField(minute,
|
|
46937
|
-
hours: parseField(hour,
|
|
46938
|
-
daysOfMonth: parseField(dom,
|
|
46939
|
-
months: parseField(month,
|
|
46940
|
-
daysOfWeek: parseField(dow,
|
|
48889
|
+
minutes: parseField(minute, FIELDS2[0]),
|
|
48890
|
+
hours: parseField(hour, FIELDS2[1]),
|
|
48891
|
+
daysOfMonth: parseField(dom, FIELDS2[2]),
|
|
48892
|
+
months: parseField(month, FIELDS2[3]),
|
|
48893
|
+
daysOfWeek: parseField(dow, FIELDS2[4]),
|
|
46941
48894
|
domRestricted: dom !== "*",
|
|
46942
48895
|
dowRestricted: dow !== "*"
|
|
46943
48896
|
};
|
|
@@ -47122,8 +49075,8 @@ var JobSchema = object({
|
|
|
47122
49075
|
});
|
|
47123
49076
|
|
|
47124
49077
|
// src/schedule/store.ts
|
|
47125
|
-
import { mkdirSync as
|
|
47126
|
-
import { dirname as
|
|
49078
|
+
import { mkdirSync as mkdirSync13 } from "fs";
|
|
49079
|
+
import { dirname as dirname14 } from "path";
|
|
47127
49080
|
var SCHEMA2 = [
|
|
47128
49081
|
`CREATE TABLE IF NOT EXISTS schedule_jobs (
|
|
47129
49082
|
id TEXT PRIMARY KEY,
|
|
@@ -47265,7 +49218,7 @@ class SqliteScheduleStore {
|
|
|
47265
49218
|
async function openScheduleStore(path) {
|
|
47266
49219
|
if (path !== ":memory:") {
|
|
47267
49220
|
try {
|
|
47268
|
-
|
|
49221
|
+
mkdirSync13(dirname14(path), { recursive: true });
|
|
47269
49222
|
} catch {}
|
|
47270
49223
|
}
|
|
47271
49224
|
const { Database } = await import("bun:sqlite");
|
|
@@ -47427,7 +49380,7 @@ var riskByTool = null;
|
|
|
47427
49380
|
async function riskIndex() {
|
|
47428
49381
|
if (riskByTool)
|
|
47429
49382
|
return riskByTool;
|
|
47430
|
-
const { moduleCatalog } = await import("./library-
|
|
49383
|
+
const { moduleCatalog } = await import("./library-wj2xfx8h.js");
|
|
47431
49384
|
const index = new Map;
|
|
47432
49385
|
for (const mod of moduleCatalog) {
|
|
47433
49386
|
for (const tool of mod.tools)
|
|
@@ -49591,7 +51544,7 @@ async function readScanList(ctx, list = "port-scanners") {
|
|
|
49591
51544
|
}
|
|
49592
51545
|
|
|
49593
51546
|
// src/attack/correlate.ts
|
|
49594
|
-
import { createHash as
|
|
51547
|
+
import { createHash as createHash8 } from "crypto";
|
|
49595
51548
|
var STAGE_ORDER = ["recon", "attempt", "breach", "persistence"];
|
|
49596
51549
|
var STAGE_OF = {
|
|
49597
51550
|
"port-scan": "recon",
|
|
@@ -49621,7 +51574,7 @@ var SEVERITY_RANK = {
|
|
|
49621
51574
|
info: 4
|
|
49622
51575
|
};
|
|
49623
51576
|
function incidentId(source, dayBucket) {
|
|
49624
|
-
const digest =
|
|
51577
|
+
const digest = createHash8("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
|
|
49625
51578
|
return `atk_${digest}`;
|
|
49626
51579
|
}
|
|
49627
51580
|
function worst(values) {
|
|
@@ -49711,7 +51664,7 @@ function mergeIncident(stored, fresh) {
|
|
|
49711
51664
|
var RECORD_START = /^\s*time=/;
|
|
49712
51665
|
var FIELD_RE = /([a-zA-Z][\w-]*)=(?:"((?:[^"\\]|\\.)*)"|(\S*))/g;
|
|
49713
51666
|
var TIME_WITH_CLOCK_RE = /time=(\S+)[ \t]+(\d{2}:\d{2}:\d{2}(?:\.\d+)?)/;
|
|
49714
|
-
function
|
|
51667
|
+
function fields2(text) {
|
|
49715
51668
|
const out = {};
|
|
49716
51669
|
for (const m of text.matchAll(FIELD_RE)) {
|
|
49717
51670
|
out[m[1]] = m[2] !== undefined ? m[2].replace(/\\(.)/g, "$1") : m[3] ?? "";
|
|
@@ -49733,7 +51686,7 @@ function parseLogRecords(text) {
|
|
|
49733
51686
|
return;
|
|
49734
51687
|
const raw = current.join(`
|
|
49735
51688
|
`);
|
|
49736
|
-
const f =
|
|
51689
|
+
const f = fields2(raw);
|
|
49737
51690
|
if (f.time === undefined || f.message === undefined) {
|
|
49738
51691
|
unparsed.push({ line: startLine, text: raw.trim().slice(0, 200) });
|
|
49739
51692
|
} else {
|
|
@@ -49843,8 +51796,8 @@ function dedupe(events, seen) {
|
|
|
49843
51796
|
}
|
|
49844
51797
|
|
|
49845
51798
|
// src/attack/store.ts
|
|
49846
|
-
import { mkdirSync as
|
|
49847
|
-
import { dirname as
|
|
51799
|
+
import { mkdirSync as mkdirSync14 } from "fs";
|
|
51800
|
+
import { dirname as dirname15 } from "path";
|
|
49848
51801
|
var SCHEMA3 = [
|
|
49849
51802
|
`CREATE TABLE IF NOT EXISTS attack_incidents (
|
|
49850
51803
|
id TEXT PRIMARY KEY,
|
|
@@ -50035,7 +51988,7 @@ class SqliteAttackStore {
|
|
|
50035
51988
|
async function openAttackStore(path) {
|
|
50036
51989
|
if (path !== ":memory:") {
|
|
50037
51990
|
try {
|
|
50038
|
-
|
|
51991
|
+
mkdirSync14(dirname15(path), { recursive: true });
|
|
50039
51992
|
} catch {}
|
|
50040
51993
|
}
|
|
50041
51994
|
const { Database } = await import("bun:sqlite");
|
|
@@ -50709,14 +52662,14 @@ ${result}`;
|
|
|
50709
52662
|
];
|
|
50710
52663
|
|
|
50711
52664
|
// src/core/update-check.ts
|
|
50712
|
-
import { existsSync as existsSync4, mkdirSync as
|
|
52665
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync15, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
|
|
50713
52666
|
import { homedir as homedir2 } from "os";
|
|
50714
|
-
import { dirname as
|
|
52667
|
+
import { dirname as dirname16, join as join9 } from "path";
|
|
50715
52668
|
|
|
50716
52669
|
// src/version.ts
|
|
50717
52670
|
import { readFileSync as readFileSync7 } from "fs";
|
|
50718
|
-
import { join as
|
|
50719
|
-
var pkg = JSON.parse(readFileSync7(
|
|
52671
|
+
import { join as join8 } from "path";
|
|
52672
|
+
var pkg = JSON.parse(readFileSync7(join8(PROJECT_ROOT, "package.json"), "utf-8"));
|
|
50720
52673
|
var VERSION2 = pkg.version ?? "0.0.0";
|
|
50721
52674
|
var WEBSITE_URL = pkg.homepage ?? "";
|
|
50722
52675
|
var LOGO_URL = pkg.logoIcon ?? "";
|
|
@@ -50728,7 +52681,7 @@ var SERVER_NAME2 = "mikrotik-mcp";
|
|
|
50728
52681
|
var GITHUB_API = "https://api.github.com/repos/mikrotik-mcp/mikrotik-mcp/releases/latest";
|
|
50729
52682
|
var MEMORY_CACHE_TTL = 15 * 60 * 1000;
|
|
50730
52683
|
var FILE_CACHE_TTL = 6 * 60 * 60 * 1000;
|
|
50731
|
-
var CACHE_PATH =
|
|
52684
|
+
var CACHE_PATH = join9(homedir2(), ".mikrotik-mcp", "update-check.json");
|
|
50732
52685
|
function compareVersions2(a, b) {
|
|
50733
52686
|
const pa = a.replace(/^v/, "").split(".").map(Number);
|
|
50734
52687
|
const pb = b.replace(/^v/, "").split(".").map(Number);
|
|
@@ -50758,9 +52711,9 @@ function loadFileCacheSync() {
|
|
|
50758
52711
|
}
|
|
50759
52712
|
function saveFileCache(data) {
|
|
50760
52713
|
try {
|
|
50761
|
-
const dir =
|
|
52714
|
+
const dir = dirname16(CACHE_PATH);
|
|
50762
52715
|
if (!existsSync4(dir))
|
|
50763
|
-
|
|
52716
|
+
mkdirSync15(dir, { recursive: true });
|
|
50764
52717
|
writeFileSync3(CACHE_PATH, JSON.stringify({ data, fetchedAt: Date.now() }));
|
|
50765
52718
|
} catch {}
|
|
50766
52719
|
}
|
|
@@ -50937,13 +52890,27 @@ var serverPulseTools = [
|
|
|
50937
52890
|
];
|
|
50938
52891
|
|
|
50939
52892
|
// src/observability/config-admin.ts
|
|
50940
|
-
import { createHash as
|
|
50941
|
-
import { readFileSync as
|
|
52893
|
+
import { createHash as createHash9, randomUUID as randomUUID11 } from "crypto";
|
|
52894
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
50942
52895
|
|
|
50943
52896
|
// src/config-write.ts
|
|
50944
|
-
import { randomUUID as
|
|
50945
|
-
import {
|
|
50946
|
-
|
|
52897
|
+
import { randomUUID as randomUUID10 } from "crypto";
|
|
52898
|
+
import {
|
|
52899
|
+
closeSync,
|
|
52900
|
+
constants,
|
|
52901
|
+
fchmodSync,
|
|
52902
|
+
fstatSync,
|
|
52903
|
+
fsyncSync,
|
|
52904
|
+
ftruncateSync,
|
|
52905
|
+
mkdirSync as mkdirSync16,
|
|
52906
|
+
openSync,
|
|
52907
|
+
readFileSync as readFileSync9,
|
|
52908
|
+
renameSync as renameSync2,
|
|
52909
|
+
rmSync as rmSync2,
|
|
52910
|
+
writeFileSync as writeFileSync4,
|
|
52911
|
+
writeSync
|
|
52912
|
+
} from "fs";
|
|
52913
|
+
import { dirname as dirname17 } from "path";
|
|
50947
52914
|
var SCHEMA_REF = "./schemas/config.schema.json";
|
|
50948
52915
|
function serializeConfig(config) {
|
|
50949
52916
|
const body = config && typeof config === "object" && !Array.isArray(config) ? config : {};
|
|
@@ -50955,22 +52922,62 @@ function backupName(path, ts) {
|
|
|
50955
52922
|
return `${path}.bak-${ts}`;
|
|
50956
52923
|
}
|
|
50957
52924
|
function atomicWrite(path, text) {
|
|
50958
|
-
|
|
50959
|
-
const tmp = `${path}.tmp-${
|
|
52925
|
+
mkdirSync16(dirname17(path), { recursive: true });
|
|
52926
|
+
const tmp = `${path}.tmp-${randomUUID10()}`;
|
|
50960
52927
|
try {
|
|
50961
|
-
writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
50962
|
-
|
|
52928
|
+
writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx", flush: true });
|
|
52929
|
+
try {
|
|
52930
|
+
renameSync2(tmp, path);
|
|
52931
|
+
} catch (error) {
|
|
52932
|
+
if (error.code !== "EBUSY")
|
|
52933
|
+
throw error;
|
|
52934
|
+
writeMountedFile(path, text);
|
|
52935
|
+
}
|
|
50963
52936
|
} finally {
|
|
50964
52937
|
rmSync2(tmp, { force: true });
|
|
50965
52938
|
}
|
|
50966
52939
|
}
|
|
52940
|
+
function replaceContents(fd, bytes) {
|
|
52941
|
+
let offset = 0;
|
|
52942
|
+
while (offset < bytes.length) {
|
|
52943
|
+
const written = writeSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
52944
|
+
if (written === 0)
|
|
52945
|
+
throw new Error("Configuration write made no progress.");
|
|
52946
|
+
offset += written;
|
|
52947
|
+
}
|
|
52948
|
+
ftruncateSync(fd, bytes.length);
|
|
52949
|
+
fsyncSync(fd);
|
|
52950
|
+
}
|
|
52951
|
+
function writeMountedFile(path, text) {
|
|
52952
|
+
const fd = openSync(path, constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
52953
|
+
try {
|
|
52954
|
+
if (!fstatSync(fd).isFile())
|
|
52955
|
+
throw new Error("Configuration target must be a regular file.");
|
|
52956
|
+
fchmodSync(fd, 384);
|
|
52957
|
+
const previous = readFileSync9(fd);
|
|
52958
|
+
const backup = `${path}.bak-mounted-${randomUUID10()}`;
|
|
52959
|
+
writeFileSync4(backup, previous, { mode: 384, flag: "wx", flush: true });
|
|
52960
|
+
try {
|
|
52961
|
+
replaceContents(fd, Buffer.from(text, "utf8"));
|
|
52962
|
+
} catch {
|
|
52963
|
+
try {
|
|
52964
|
+
replaceContents(fd, previous);
|
|
52965
|
+
} catch {
|
|
52966
|
+
throw new Error("Configuration write and recovery failed; restore the retained mounted-file backup.");
|
|
52967
|
+
}
|
|
52968
|
+
throw new Error("Configuration write failed; previous contents restored and backup retained.");
|
|
52969
|
+
}
|
|
52970
|
+
} finally {
|
|
52971
|
+
closeSync(fd);
|
|
52972
|
+
}
|
|
52973
|
+
}
|
|
50967
52974
|
|
|
50968
52975
|
// src/observability/config-admin.ts
|
|
50969
52976
|
function createConfigAdmin(deps) {
|
|
50970
52977
|
let pending = null;
|
|
50971
52978
|
let lastTimestamp = 0;
|
|
50972
|
-
const salt =
|
|
50973
|
-
const fingerprint = (config, source, contents) =>
|
|
52979
|
+
const salt = randomUUID11();
|
|
52980
|
+
const fingerprint = (config, source, contents) => createHash9("sha256").update(salt).update(JSON.stringify([config, source, contents])).digest("hex");
|
|
50974
52981
|
const revision = () => {
|
|
50975
52982
|
const source = deps.source();
|
|
50976
52983
|
return fingerprint(deps.getConfig(), source, deps.readFile(source.path));
|
|
@@ -51064,7 +53071,7 @@ function getConfigAdmin() {
|
|
|
51064
53071
|
source: getConfigSource2,
|
|
51065
53072
|
readFile: (path) => {
|
|
51066
53073
|
try {
|
|
51067
|
-
return
|
|
53074
|
+
return readFileSync10(path, "utf8");
|
|
51068
53075
|
} catch (error) {
|
|
51069
53076
|
if (error.code === "ENOENT")
|
|
51070
53077
|
return null;
|
|
@@ -51116,7 +53123,7 @@ var McpSettingsPendingSchema = object({
|
|
|
51116
53123
|
revision: string().length(64).describe("Revision returned by update_mcp_settings or get_mcp_settings.")
|
|
51117
53124
|
}).strict();
|
|
51118
53125
|
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.";
|
|
51119
|
-
function
|
|
53126
|
+
function settings2(cfg) {
|
|
51120
53127
|
return {
|
|
51121
53128
|
mcp: {
|
|
51122
53129
|
toolPageSize: cfg.mcp.toolPageSize,
|
|
@@ -51146,7 +53153,7 @@ function createMcpSettingsService(deps) {
|
|
|
51146
53153
|
const source = deps.source();
|
|
51147
53154
|
return {
|
|
51148
53155
|
revision: deps.admin.revision(),
|
|
51149
|
-
settings:
|
|
53156
|
+
settings: settings2(deps.getConfig()),
|
|
51150
53157
|
pending: id ? { id, owned: id === owned?.id, expiresAt: id === owned?.id ? owned.expiresAt : null } : null,
|
|
51151
53158
|
persistence: {
|
|
51152
53159
|
path: source.path,
|
|
@@ -51172,8 +53179,8 @@ function createMcpSettingsService(deps) {
|
|
|
51172
53179
|
});
|
|
51173
53180
|
if (changes.dashboard?.captureBody === true && !next.dashboard.redactInput)
|
|
51174
53181
|
throw new Error("Enabling body capture also requires dashboard.redactInput=true.");
|
|
51175
|
-
const before =
|
|
51176
|
-
const after =
|
|
53182
|
+
const before = settings2(current);
|
|
53183
|
+
const after = settings2(next);
|
|
51177
53184
|
const changedPaths = [];
|
|
51178
53185
|
for (const key of ["mcp", "ssh", "dashboard", "memory"]) {
|
|
51179
53186
|
for (const [field, value] of Object.entries(after[key])) {
|
|
@@ -51293,7 +53300,7 @@ var mcpSettingsTools = [
|
|
|
51293
53300
|
title: "Safely Update MCP Settings",
|
|
51294
53301
|
noDevice: true,
|
|
51295
53302
|
annotations: WRITE,
|
|
51296
|
-
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
|
|
53303
|
+
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.",
|
|
51297
53304
|
inputSchema: McpSettingsUpdateSchema.shape,
|
|
51298
53305
|
handler: (args) => render(getMcpSettingsService().update(args))
|
|
51299
53306
|
}),
|
|
@@ -53339,7 +55346,7 @@ ${result}`;
|
|
|
53339
55346
|
];
|
|
53340
55347
|
|
|
53341
55348
|
// src/tools/user-manager.ts
|
|
53342
|
-
var
|
|
55349
|
+
var NOT_AVAILABLE2 = "User Manager is not available on this device (package not installed).";
|
|
53343
55350
|
var userManagerToolsDefs = [
|
|
53344
55351
|
defineTool2({
|
|
53345
55352
|
name: "get_user_manager_settings",
|
|
@@ -53350,7 +55357,7 @@ var userManagerToolsDefs = [
|
|
|
53350
55357
|
ctx.info("Getting User Manager settings");
|
|
53351
55358
|
const result = await executeMikrotikCommand2("/user-manager print", ctx);
|
|
53352
55359
|
if (commandUnsupported(result))
|
|
53353
|
-
return
|
|
55360
|
+
return NOT_AVAILABLE2;
|
|
53354
55361
|
return isEmpty(result) ? "No User Manager settings found." : `USER MANAGER SETTINGS:
|
|
53355
55362
|
|
|
53356
55363
|
${result}`;
|
|
@@ -53376,7 +55383,7 @@ ${result}`;
|
|
|
53376
55383
|
return "No updates specified.";
|
|
53377
55384
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53378
55385
|
if (commandUnsupported(result))
|
|
53379
|
-
return
|
|
55386
|
+
return NOT_AVAILABLE2;
|
|
53380
55387
|
if (looksLikeError(result))
|
|
53381
55388
|
return `Failed to update User Manager settings: ${result}`;
|
|
53382
55389
|
const details = await executeMikrotikCommand2("/user-manager print", ctx);
|
|
@@ -53406,7 +55413,7 @@ ${details}`;
|
|
|
53406
55413
|
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();
|
|
53407
55414
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53408
55415
|
if (commandUnsupported(result))
|
|
53409
|
-
return
|
|
55416
|
+
return NOT_AVAILABLE2;
|
|
53410
55417
|
if (looksLikeError(result))
|
|
53411
55418
|
return `Failed to add User Manager user: ${result}`;
|
|
53412
55419
|
const details = await executeMikrotikCommand2(`/user-manager user print detail where name="${a.name}"`, ctx);
|
|
@@ -53430,7 +55437,7 @@ ${redactSecrets(details)}` : "User Manager user creation completed but unable to
|
|
|
53430
55437
|
filters.push(`name~"${a.name_filter}"`);
|
|
53431
55438
|
const result = await executeMikrotikCommand2(`/user-manager user print${whereClause(filters)}`, ctx);
|
|
53432
55439
|
if (commandUnsupported(result))
|
|
53433
|
-
return
|
|
55440
|
+
return NOT_AVAILABLE2;
|
|
53434
55441
|
return isEmpty(result) ? "No User Manager users found matching the criteria." : `USER MANAGER USERS:
|
|
53435
55442
|
|
|
53436
55443
|
${redactSecrets(result)}`;
|
|
@@ -53446,7 +55453,7 @@ ${redactSecrets(result)}`;
|
|
|
53446
55453
|
ctx.info(`Getting User Manager user details: name=${a.name}`);
|
|
53447
55454
|
const result = await executeMikrotikCommand2(`/user-manager user print detail where name="${a.name}"`, ctx);
|
|
53448
55455
|
if (commandUnsupported(result))
|
|
53449
|
-
return
|
|
55456
|
+
return NOT_AVAILABLE2;
|
|
53450
55457
|
return isEmpty(result) ? `User Manager user '${a.name}' not found.` : `USER MANAGER USER DETAILS:
|
|
53451
55458
|
|
|
53452
55459
|
${redactSecrets(result)}`;
|
|
@@ -53476,7 +55483,7 @@ ${redactSecrets(result)}`;
|
|
|
53476
55483
|
return "No updates specified.";
|
|
53477
55484
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53478
55485
|
if (commandUnsupported(result))
|
|
53479
|
-
return
|
|
55486
|
+
return NOT_AVAILABLE2;
|
|
53480
55487
|
if (looksLikeError(result))
|
|
53481
55488
|
return `Failed to update User Manager user: ${result}`;
|
|
53482
55489
|
const target = a.new_name ?? a.name;
|
|
@@ -53496,7 +55503,7 @@ ${redactSecrets(details)}`;
|
|
|
53496
55503
|
ctx.info(`Removing User Manager user: name=${a.name}`);
|
|
53497
55504
|
const count = await executeMikrotikCommand2(`/user-manager user print count-only where name="${a.name}"`, ctx);
|
|
53498
55505
|
if (commandUnsupported(count))
|
|
53499
|
-
return
|
|
55506
|
+
return NOT_AVAILABLE2;
|
|
53500
55507
|
if (count.trim() === "0")
|
|
53501
55508
|
return `User Manager user '${a.name}' not found.`;
|
|
53502
55509
|
const result = await executeMikrotikCommand2(`/user-manager user remove [find name="${a.name}"]`, ctx);
|
|
@@ -53524,7 +55531,7 @@ ${redactSecrets(details)}`;
|
|
|
53524
55531
|
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();
|
|
53525
55532
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53526
55533
|
if (commandUnsupported(result))
|
|
53527
|
-
return
|
|
55534
|
+
return NOT_AVAILABLE2;
|
|
53528
55535
|
if (looksLikeError(result))
|
|
53529
55536
|
return `Failed to add User Manager profile: ${result}`;
|
|
53530
55537
|
const details = await executeMikrotikCommand2(`/user-manager profile print detail where name="${a.name}"`, ctx);
|
|
@@ -53548,7 +55555,7 @@ ${details}` : "User Manager profile creation completed but unable to verify.";
|
|
|
53548
55555
|
filters.push(`name~"${a.name_filter}"`);
|
|
53549
55556
|
const result = await executeMikrotikCommand2(`/user-manager profile print${whereClause(filters)}`, ctx);
|
|
53550
55557
|
if (commandUnsupported(result))
|
|
53551
|
-
return
|
|
55558
|
+
return NOT_AVAILABLE2;
|
|
53552
55559
|
return isEmpty(result) ? "No User Manager profiles found matching the criteria." : `USER MANAGER PROFILES:
|
|
53553
55560
|
|
|
53554
55561
|
${result}`;
|
|
@@ -53564,7 +55571,7 @@ ${result}`;
|
|
|
53564
55571
|
ctx.info(`Removing User Manager profile: name=${a.name}`);
|
|
53565
55572
|
const count = await executeMikrotikCommand2(`/user-manager profile print count-only where name="${a.name}"`, ctx);
|
|
53566
55573
|
if (commandUnsupported(count))
|
|
53567
|
-
return
|
|
55574
|
+
return NOT_AVAILABLE2;
|
|
53568
55575
|
if (count.trim() === "0")
|
|
53569
55576
|
return `User Manager profile '${a.name}' not found.`;
|
|
53570
55577
|
const result = await executeMikrotikCommand2(`/user-manager profile remove [find name="${a.name}"]`, ctx);
|
|
@@ -53587,7 +55594,7 @@ ${result}`;
|
|
|
53587
55594
|
const cmd = new Cmd("/user-manager user-profile add").set("user", a.user).set("profile", a.profile).build();
|
|
53588
55595
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53589
55596
|
if (commandUnsupported(result))
|
|
53590
|
-
return
|
|
55597
|
+
return NOT_AVAILABLE2;
|
|
53591
55598
|
if (looksLikeError(result))
|
|
53592
55599
|
return `Failed to assign profile: ${result}`;
|
|
53593
55600
|
return `Assigned profile '${a.profile}' to user '${a.user}'.
|
|
@@ -53610,7 +55617,7 @@ ${result}`;
|
|
|
53610
55617
|
filters.push(`user~"${a.user_filter}"`);
|
|
53611
55618
|
const result = await executeMikrotikCommand2(`/user-manager user-profile print${whereClause(filters)}`, ctx);
|
|
53612
55619
|
if (commandUnsupported(result))
|
|
53613
|
-
return
|
|
55620
|
+
return NOT_AVAILABLE2;
|
|
53614
55621
|
return isEmpty(result) ? "No User Manager user-profiles found matching the criteria." : `USER MANAGER USER-PROFILES:
|
|
53615
55622
|
|
|
53616
55623
|
${result}`;
|
|
@@ -53635,7 +55642,7 @@ ${result}`;
|
|
|
53635
55642
|
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();
|
|
53636
55643
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53637
55644
|
if (commandUnsupported(result))
|
|
53638
|
-
return
|
|
55645
|
+
return NOT_AVAILABLE2;
|
|
53639
55646
|
if (looksLikeError(result))
|
|
53640
55647
|
return `Failed to add User Manager router: ${result}`;
|
|
53641
55648
|
const details = await executeMikrotikCommand2(`/user-manager router print detail where name="${a.name}"`, ctx);
|
|
@@ -53659,7 +55666,7 @@ ${redactSecrets(details)}` : "User Manager router creation completed but unable
|
|
|
53659
55666
|
filters.push(`name~"${a.name_filter}"`);
|
|
53660
55667
|
const result = await executeMikrotikCommand2(`/user-manager router print${whereClause(filters)}`, ctx);
|
|
53661
55668
|
if (commandUnsupported(result))
|
|
53662
|
-
return
|
|
55669
|
+
return NOT_AVAILABLE2;
|
|
53663
55670
|
return isEmpty(result) ? "No User Manager routers found matching the criteria." : `USER MANAGER ROUTERS:
|
|
53664
55671
|
|
|
53665
55672
|
${redactSecrets(result)}`;
|
|
@@ -53675,7 +55682,7 @@ ${redactSecrets(result)}`;
|
|
|
53675
55682
|
ctx.info(`Removing User Manager router: name=${a.name}`);
|
|
53676
55683
|
const count = await executeMikrotikCommand2(`/user-manager router print count-only where name="${a.name}"`, ctx);
|
|
53677
55684
|
if (commandUnsupported(count))
|
|
53678
|
-
return
|
|
55685
|
+
return NOT_AVAILABLE2;
|
|
53679
55686
|
if (count.trim() === "0")
|
|
53680
55687
|
return `User Manager router '${a.name}' not found.`;
|
|
53681
55688
|
const result = await executeMikrotikCommand2(`/user-manager router remove [find name="${a.name}"]`, ctx);
|
|
@@ -53715,7 +55722,7 @@ ${redactSecrets(result)}`;
|
|
|
53715
55722
|
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();
|
|
53716
55723
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53717
55724
|
if (commandUnsupported(result))
|
|
53718
|
-
return
|
|
55725
|
+
return NOT_AVAILABLE2;
|
|
53719
55726
|
if (looksLikeError(result))
|
|
53720
55727
|
return `Failed to add User Manager limitation: ${result}`;
|
|
53721
55728
|
const details = await executeMikrotikCommand2(`/user-manager limitation print detail where name="${a.name}"`, ctx);
|
|
@@ -53739,7 +55746,7 @@ ${details}` : "User Manager limitation creation completed but unable to verify."
|
|
|
53739
55746
|
filters.push(`name~"${a.name_filter}"`);
|
|
53740
55747
|
const result = await executeMikrotikCommand2(`/user-manager limitation print${whereClause(filters)}`, ctx);
|
|
53741
55748
|
if (commandUnsupported(result))
|
|
53742
|
-
return
|
|
55749
|
+
return NOT_AVAILABLE2;
|
|
53743
55750
|
return isEmpty(result) ? "No User Manager limitations found matching the criteria." : `USER MANAGER LIMITATIONS:
|
|
53744
55751
|
|
|
53745
55752
|
${result}`;
|
|
@@ -53755,7 +55762,7 @@ ${result}`;
|
|
|
53755
55762
|
ctx.info(`Removing User Manager limitation: name=${a.name}`);
|
|
53756
55763
|
const count = await executeMikrotikCommand2(`/user-manager limitation print count-only where name="${a.name}"`, ctx);
|
|
53757
55764
|
if (commandUnsupported(count))
|
|
53758
|
-
return
|
|
55765
|
+
return NOT_AVAILABLE2;
|
|
53759
55766
|
if (count.trim() === "0")
|
|
53760
55767
|
return `User Manager limitation '${a.name}' not found.`;
|
|
53761
55768
|
const result = await executeMikrotikCommand2(`/user-manager limitation remove [find name="${a.name}"]`, ctx);
|
|
@@ -53782,7 +55789,7 @@ ${result}`;
|
|
|
53782
55789
|
filters.push("active=yes");
|
|
53783
55790
|
const result = await executeMikrotikCommand2(`/user-manager session print${whereClause(filters)}`, ctx);
|
|
53784
55791
|
if (commandUnsupported(result))
|
|
53785
|
-
return
|
|
55792
|
+
return NOT_AVAILABLE2;
|
|
53786
55793
|
return isEmpty(result) ? "No User Manager sessions found matching the criteria." : `USER MANAGER SESSIONS:
|
|
53787
55794
|
|
|
53788
55795
|
${result}`;
|
|
@@ -54216,33 +56223,281 @@ ${result}`;
|
|
|
54216
56223
|
})
|
|
54217
56224
|
];
|
|
54218
56225
|
|
|
56226
|
+
// src/core/vlan-guidance.ts
|
|
56227
|
+
var VLAN_GUIDE_URI = "mikrotik://knowledge/vlan-segmentation";
|
|
56228
|
+
var VLAN_GUIDE_VERSION = "2026-10-03";
|
|
56229
|
+
var VLAN_GUIDE_TOPICS = [
|
|
56230
|
+
"overview",
|
|
56231
|
+
"discovery",
|
|
56232
|
+
"layer2",
|
|
56233
|
+
"policy",
|
|
56234
|
+
"migration",
|
|
56235
|
+
"verification"
|
|
56236
|
+
];
|
|
56237
|
+
var sections2 = {
|
|
56238
|
+
overview: `## Intent and boundaries
|
|
56239
|
+
Use this guide for homelab VLAN segmentation, guest Wi-Fi, IoT isolation and
|
|
56240
|
+
management networks. It is reference knowledge, NOT observed device state or
|
|
56241
|
+
authorization. Start read-only; use find_tools and describe_tool for the tools
|
|
56242
|
+
actually exposed in this session. Never bypass read-only mode or module restrictions.
|
|
56243
|
+
|
|
56244
|
+
Adapt the homelab-vlan-segmentation design to the actual requirements. Illustrative
|
|
56245
|
+
roles/IDs are Trusted 10, IoT 20, Servers 30 (only if needed), Guest 40 and Management
|
|
56246
|
+
99. IDs are examples, not reservations or defaults to apply. Preserve working
|
|
56247
|
+
subnets where possible; check overlap with WAN, VPN, remote sites and other VLANs.
|
|
56248
|
+
Trusted users are not automatically administrators. Agree a source/destination/
|
|
56249
|
+
service allow matrix, including router management, before proposing changes.
|
|
56250
|
+
|
|
56251
|
+
VLAN sub-interfaces alone do not provide isolation. Layer-2 membership, routed
|
|
56252
|
+
IPv4/IPv6 policy and actual endpoint tests are separate requirements. A VPS/CHR
|
|
56253
|
+
used only as a routed tunnel endpoint may need routes/policy, not local VLANs.
|
|
56254
|
+
Do not extend a broadcast domain across a WAN without an explicit L2 requirement.
|
|
56255
|
+
Segmentation is not a promise of lower latency or higher tunnel throughput.`,
|
|
56256
|
+
discovery: `## Read-only discovery and evidence
|
|
56257
|
+
Resolve each router by its exact configured device name and verify identity,
|
|
56258
|
+
RouterOS version, board, switch chip and installed Wi-Fi package. Recall constraints
|
|
56259
|
+
separately for each device if Memory is enabled; inspect conflicts and omitted
|
|
56260
|
+
constraints. Recalled facts may be stale. Never copy one router's addresses to another.
|
|
56261
|
+
|
|
56262
|
+
Discover interfaces, bridge settings/ports/VLAN table, VLAN sub-interfaces, interface
|
|
56263
|
+
lists, IP addresses, DHCP pools/networks/leases, DNS, IPv6 addresses/prefix delegation,
|
|
56264
|
+
ND/RA, IPv4 AND IPv6 filter/raw/NAT/mangle rules, routes/routing tables/rules,
|
|
56265
|
+
WireGuard allowed-addresses, queues, Wi-Fi/CAPsMAN/SSID datapaths and management
|
|
56266
|
+
services/MAC discovery. Use bounded, filtered reads; report unsupported, incomplete
|
|
56267
|
+
or timed-out reads as unknown, never empty or safe. Do not fetch credentials.
|
|
56268
|
+
|
|
56269
|
+
Build a physical port map: peer device, WAN/LAN/trunk/access role, bridge, PVID,
|
|
56270
|
+
tagged/untagged membership, link rate, hardware offload and management dependency.
|
|
56271
|
+
Do not infer a port's role from ether1, a comment, or a link-down snapshot. Resolve
|
|
56272
|
+
conflicting labels with the operator. Verify external switch/AP VLAN capability
|
|
56273
|
+
and its management/native VLAN before planning a trunk. Inventory scripts, netwatch,
|
|
56274
|
+
interface lists, NAT, policy-routing and queues that depend on the old interfaces.
|
|
56275
|
+
Distinguish proven observations, intended policy and unverified assumptions.`,
|
|
56276
|
+
layer2: `## Layer 2, CPU access and Wi-Fi
|
|
56277
|
+
For a NEW bridge, stage with vlan-filtering=no. For an existing production bridge,
|
|
56278
|
+
do not turn filtering off to simplify a migration: that can remove isolation.
|
|
56279
|
+
Enable VLAN filtering LAST when the VLAN table, port admission, management path,
|
|
56280
|
+
gateway and recovery plan are ready. A bridge reset can interrupt the session.
|
|
56281
|
+
|
|
56282
|
+
A routed VLAN interface normally belongs on the bridge, not on a physical port
|
|
56283
|
+
already enslaved to it. Include the bridge/CPU as tagged for VLANs terminated on
|
|
56284
|
+
that bridge and verify effective current-tagged membership (RouterOS may create
|
|
56285
|
+
dynamic entries). Do not expose CPU membership on VLANs that need only switching.
|
|
56286
|
+
Creating /interface vlan does not configure /interface bridge vlan or access ports.
|
|
56287
|
+
|
|
56288
|
+
On access ports: one intended untagged VLAN, matching PVID, ingress-filtering and
|
|
56289
|
+
admit-only-untagged-and-priority-tagged where supported. PVID classifies untagged
|
|
56290
|
+
ingress; it is not a tagged-traffic allowlist. Do not combine multiple VLAN IDs in
|
|
56291
|
+
a VLAN-table row containing access ports. On tagged-only trunks: explicit allowed
|
|
56292
|
+
VLAN membership, ingress-filtering and admit-only-vlan-tagged. Model hybrid/native
|
|
56293
|
+
ports explicitly; inspect dynamic VLAN 1/CPU membership for accidental access.
|
|
56294
|
+
Never add a WAN/ONT port to a LAN bridge merely because an example uses that number.
|
|
56295
|
+
|
|
56296
|
+
Map each SSID to a verified VLAN at the AP as well as its uplink. Inspect wireless,
|
|
56297
|
+
wifiwave2 or wifi and CAPsMAN local/manager forwarding. wifi-qcom and wifi-qcom-ac
|
|
56298
|
+
are not interchangeable: qcom-ac needs the appropriate bridge/PVID design rather
|
|
56299
|
+
than blindly copying CAPsMAN datapath vlan-id. Verify package-specific support.
|
|
56300
|
+
Guest client isolation within one SSID/VLAN is separate from inter-VLAN firewalling.
|
|
56301
|
+
Do not enable bridge use-ip-firewall just to filter traffic already routed by the
|
|
56302
|
+
CPU; inspect hardware-offload support and measure the performance impact.`,
|
|
56303
|
+
policy: `## Dual-stack policy and remote-site dependencies
|
|
56304
|
+
Design INPUT (to the router) and FORWARD (through the router) separately for both
|
|
56305
|
+
IPv4 and IPv6. Limit administration to the approved management sources/VPNs; allow
|
|
56306
|
+
only required DHCP/DNS/NTP and essential ICMP/ICMPv6 functions on client segments.
|
|
56307
|
+
Preserve neighbor discovery, router advertisements where intended and path-MTU
|
|
56308
|
+
discovery. Do not solve isolation by indiscriminately blocking all ICMPv6.
|
|
56309
|
+
|
|
56310
|
+
Evaluate first-match rule order, jumps, broad LAN/!WAN accepts, established flows,
|
|
56311
|
+
FastTrack and existing final drops. Place exact service exceptions before segment
|
|
56312
|
+
denies, and denies before broad accepts they must constrain. Appended drop rules
|
|
56313
|
+
may never match. Use current stable .ids, not saved row numbers. Preserve unrelated
|
|
56314
|
+
protections and allowlists. RFC1918-only drops miss local public IPv4, VPN/remote
|
|
56315
|
+
networks and all IPv6; enumerate actual protected destinations. Default-deny between
|
|
56316
|
+
zones with explicit exceptions is a design goal, not permission to rewrite a firewall.
|
|
56317
|
+
|
|
56318
|
+
NAT is not isolation or a routing policy. Reuse valid existing NAT; any new source
|
|
56319
|
+
NAT must be scoped to the intended egress, never every destination. SNAT may hide
|
|
56320
|
+
VLAN source identities from a remote router, so enforce segmentation locally unless
|
|
56321
|
+
an explicitly designed routed/no-NAT topology preserves them. Add new subnets to
|
|
56322
|
+
VPN allowed-addresses, return routes and remote policies only when required.
|
|
56323
|
+
|
|
56324
|
+
Each IPv6 SLAAC segment needs its own non-overlapping /64 from a valid routed or
|
|
56325
|
+
delegated prefix; do not reuse one /64 on separate L2 domains. Verify upstream
|
|
56326
|
+
reachability and return routing, not just a local address. If unavailable, report
|
|
56327
|
+
IPv6 as unconfigured/blocked by prerequisites, not working or isolated by IPv4.
|
|
56328
|
+
|
|
56329
|
+
Move policy-routing/interface-list/queue/automation dependencies before retiring
|
|
56330
|
+
legacy interfaces. FastTrack only eligible main-table traffic; policy-routed,
|
|
56331
|
+
queued or accounted traffic needs appropriate exclusions. Moving FastTrack above
|
|
56332
|
+
an established accept can change behavior beyond VLANs; never do it blindly.`,
|
|
56333
|
+
migration: `## Safe rollout and planner limits
|
|
56334
|
+
Deliver: (1) observed topology and unknowns; (2) proposed VLAN/subnet/IPv6/SSID/port
|
|
56335
|
+
map; (3) explicit allow/deny service matrix; (4) exact ordered per-device changes;
|
|
56336
|
+
(5) prerequisites, rollback triggers and acceptance tests. Ask only for missing
|
|
56337
|
+
choices that affect connectivity or policy. Do not invent interface or subnet roles.
|
|
56338
|
+
|
|
56339
|
+
Before writes, obtain approval for the exact scope, capture a host-side snapshot
|
|
56340
|
+
and follow the local-backup requirements. Confirm an independent console, rescue
|
|
56341
|
+
port or verified management path that does not depend on the bridge being changed.
|
|
56342
|
+
Do not assume a VPN is independent: it may traverse that same bridge/uplink.
|
|
56343
|
+
Use owned Safe Mode for suitable single-router changes; coordinated multi-router
|
|
56344
|
+
writes should use the transaction workflow when available and suitable. Transaction
|
|
56345
|
+
verification stages REAL changes, not an offline preview. Safe Mode is not a backup
|
|
56346
|
+
or a guarantee for all operations; ambiguous timeouts are not permission to retry.
|
|
56347
|
+
Preserve the old management path until the new one has been tested. Canary one
|
|
56348
|
+
port/SSID/client, then migrate the remainder; never reconfigure all access at once.
|
|
56349
|
+
|
|
56350
|
+
design_network_segment is only partial IPv4 scaffolding, not a full isolation
|
|
56351
|
+
engine. It does not configure bridge port PVID/admission, enable VLAN filtering,
|
|
56352
|
+
map SSIDs, build router INPUT or IPv6 policy, prove rule reachability, preserve
|
|
56353
|
+
remote routing, or roll back a partial apply. NAT needs explicit wan_interface;
|
|
56354
|
+
isolation drops need a current reviewed isolation_before rule .id. Non-/24 DHCP
|
|
56355
|
+
needs an explicit valid pool. Discover schemas before previewing; apply only after
|
|
56356
|
+
the surrounding approved configuration satisfies these prerequisites. Do not call
|
|
56357
|
+
it repeatedly to finish a partially applied plan; read back and reconcile first.
|
|
56358
|
+
For a complete migration, prefer an explicit reviewed plan with separate steps.`,
|
|
56359
|
+
verification: `## Verification, reporting and clean memory
|
|
56360
|
+
Read back bridge VLAN current-tagged/current-untagged, PVID/admission, gateway IPs,
|
|
56361
|
+
DHCP and IPv6 ND/RA, rules and counters, routing tables and VPN return routes.
|
|
56362
|
+
Then test from real representative wired AND wireless clients in each segment:
|
|
56363
|
+
address/lease, DNS, gateway, required internet/VPN services, allowed local services,
|
|
56364
|
+
denied cross-zone services, denied router management and guest peer isolation if
|
|
56365
|
+
requested. Test IPv4 and IPv6 independently, with fresh connections; existing
|
|
56366
|
+
tracked/FastTracked flows can conceal new policy. Never flush all connections as
|
|
56367
|
+
an unapproved test. Router-originated ping does not prove client FORWARD policy.
|
|
56368
|
+
|
|
56369
|
+
Record expected vs observed per test, sample time, source, address family and
|
|
56370
|
+
remaining unknowns. If no endpoint is available, mark client isolation unverified.
|
|
56371
|
+
For performance claims, compare the same path/client/workload before and after:
|
|
56372
|
+
link speed, CPU/offload, throughput, latency and loss. Ask before disruptive loads.
|
|
56373
|
+
Commit only an authorized, verified change; uncertain connectivity requires stop,
|
|
56374
|
+
read-back and the agreed rollback/recovery path, not speculative cleanup.
|
|
56375
|
+
|
|
56376
|
+
Only after successful validation, review stale objects and all references before
|
|
56377
|
+
proposing removals. Disabled is not proof unused. Preserve unrelated tunnels,
|
|
56378
|
+
WAN failover, management allowlists and domain-routing exceptions.
|
|
56379
|
+
Memory: store exact VLAN maps, addresses and evidence on each Device with source,
|
|
56380
|
+
verification time and expiry. Use a dedicated Group policy with explicit members
|
|
56381
|
+
for site-wide rules; Shared is only for intentionally reusable safeguards. Do not
|
|
56382
|
+
promote a device entity or store secrets/raw exports. Memory never grants new
|
|
56383
|
+
permission; generic guidance does not prove live facts.`
|
|
56384
|
+
};
|
|
56385
|
+
var sources2 = `## Authoritative references
|
|
56386
|
+
- Bridge VLAN table: https://help.mikrotik.com/docs/spaces/ROS/pages/28606465/Bridge+VLAN+Table
|
|
56387
|
+
- Wi-Fi packages and CAPsMAN: https://help.mikrotik.com/docs/spaces/ROS/pages/224559120/WiFi
|
|
56388
|
+
- IPv4/IPv6 firewall: https://help.mikrotik.com/docs/spaces/ROS/pages/328513/Building+Advanced+Firewall
|
|
56389
|
+
- Packet flow and FastTrack: https://help.mikrotik.com/docs/spaces/ROS/pages/328227/Packet+Flow+in+RouterOS
|
|
56390
|
+
Verify version-specific behavior against the current official manual before applying.
|
|
56391
|
+
Adapted from the homelab-vlan-segmentation skill with RouterOS-specific safety gates.`;
|
|
56392
|
+
function getVlanSegmentationGuide(topic = "all") {
|
|
56393
|
+
const selected = topic === "all" ? VLAN_GUIDE_TOPICS : [topic];
|
|
56394
|
+
return [
|
|
56395
|
+
`# RouterOS VLAN segmentation knowledge
|
|
56396
|
+
Guide version: ${VLAN_GUIDE_VERSION}
|
|
56397
|
+
Reference only; no device inspection or changes.`,
|
|
56398
|
+
...selected.map((key) => sections2[key]),
|
|
56399
|
+
sources2
|
|
56400
|
+
].join(`
|
|
56401
|
+
|
|
56402
|
+
`);
|
|
56403
|
+
}
|
|
56404
|
+
var VLAN_INSTRUCTIONS = `VLAN segmentation knowledge:
|
|
56405
|
+
Before VLAN/guest/IoT/management-network work, read ${VLAN_GUIDE_URI}.
|
|
56406
|
+
Begin with read-only discovery; never infer port roles from names or example IDs.
|
|
56407
|
+
Protect the management path, stage VLAN membership/PVID/CPU access before enabling
|
|
56408
|
+
filtering, and check BOTH IPv4 and IPv6 INPUT/FORWARD policy and remote return routes.
|
|
56409
|
+
design_network_segment is partial IPv4 scaffolding, NOT a complete isolation plan.
|
|
56410
|
+
Use only available tools; an audit or this guide never authorizes router changes.
|
|
56411
|
+
Verified device facts belong to Device memory; reusable safeguards may be Shared
|
|
56412
|
+
only with explicit intent. Do not treat shared memory as a live VLAN map.`;
|
|
56413
|
+
function vlanPromptGuidance(name, body) {
|
|
56414
|
+
if (!["setup-vlan-network", "setup-guest-wifi", "audit-vlan-segmentation"].includes(name)) {
|
|
56415
|
+
return body;
|
|
56416
|
+
}
|
|
56417
|
+
return `${body}
|
|
56418
|
+
|
|
56419
|
+
${getVlanSegmentationGuide()}`;
|
|
56420
|
+
}
|
|
56421
|
+
|
|
54219
56422
|
// src/tools/vlan-designer.ts
|
|
56423
|
+
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.";
|
|
56424
|
+
var portList = (text) => [
|
|
56425
|
+
...new Set((text ?? "").split(",").map((p) => p.trim()).filter(Boolean))
|
|
56426
|
+
];
|
|
54220
56427
|
function defaultRange2(subnet) {
|
|
54221
56428
|
const o = subnet.split("/")[0].split(".");
|
|
54222
56429
|
return `${o[0]}.${o[1]}.${o[2]}.10-${o[0]}.${o[1]}.${o[2]}.254`;
|
|
54223
56430
|
}
|
|
54224
56431
|
var vlanDesignerTools = [
|
|
56432
|
+
defineTool2({
|
|
56433
|
+
name: "get_vlan_segmentation_guide",
|
|
56434
|
+
title: "Read VLAN Segmentation Knowledge",
|
|
56435
|
+
annotations: READ,
|
|
56436
|
+
noDevice: true,
|
|
56437
|
+
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.",
|
|
56438
|
+
inputSchema: {
|
|
56439
|
+
topic: _enum(["all", ...VLAN_GUIDE_TOPICS]).default("all")
|
|
56440
|
+
},
|
|
56441
|
+
handler: (a) => getVlanSegmentationGuide(a.topic)
|
|
56442
|
+
}),
|
|
54225
56443
|
defineTool2({
|
|
54226
56444
|
name: "design_network_segment",
|
|
54227
|
-
title: "
|
|
56445
|
+
title: "Preview or Build Partial IPv4 VLAN Scaffolding",
|
|
54228
56446
|
annotations: DANGEROUS,
|
|
54229
|
-
description: "
|
|
56447
|
+
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.",
|
|
54230
56448
|
inputSchema: {
|
|
54231
56449
|
vlan_id: number().int().min(1).max(4094),
|
|
54232
56450
|
name: interfaceName("Name for the VLAN interface, e.g. 'guest'"),
|
|
54233
|
-
subnet:
|
|
54234
|
-
gateway:
|
|
56451
|
+
subnet: cidrv42().describe("Canonical IPv4 network CIDR, e.g. '192.168.30.0/24'"),
|
|
56452
|
+
gateway: ipv42().describe("Usable router address inside the subnet, excluded from the DHCP pool"),
|
|
54235
56453
|
bridge: string().default("bridge").describe("Bridge to put the VLAN on"),
|
|
54236
|
-
tagged_ports: string().optional().describe("Comma-separated
|
|
56454
|
+
tagged_ports: string().optional().describe("Comma-separated verified tagged ports; the bridge/CPU is included once automatically"),
|
|
54237
56455
|
untagged_ports: string().optional().describe("Comma-separated access/untagged ports"),
|
|
54238
56456
|
dhcp: boolean().default(true).describe("Create a DHCP server + pool for the segment"),
|
|
54239
|
-
dhcp_range: string().optional().describe("
|
|
54240
|
-
internet: boolean().default(true).describe("
|
|
54241
|
-
|
|
56457
|
+
dhcp_range: string().optional().describe("Single start-end IPv4 range excluding gateway/network/broadcast. Required outside /24; /24 defaults to .10\u2013.254"),
|
|
56458
|
+
internet: boolean().default(true).describe("Add egress-scoped IPv4 masquerade (requires wan_interface); not a firewall allow. Set false to reuse existing NAT"),
|
|
56459
|
+
wan_interface: string().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"),
|
|
56460
|
+
isolate_from: array(cidrv42()).optional().describe("Subnets this segment must NOT reach, e.g. ['192.168.1.0/24']"),
|
|
56461
|
+
isolation_before: string().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"),
|
|
54242
56462
|
apply: boolean().default(false).describe("false = preview (default); true = build")
|
|
54243
56463
|
},
|
|
54244
56464
|
async handler(a, ctx) {
|
|
54245
|
-
const
|
|
56465
|
+
const subnet = parseCidr(a.subnet);
|
|
56466
|
+
const gateway = parseIp(a.gateway);
|
|
56467
|
+
if (!subnet || subnet.text !== a.subnet || subnet.prefix > 30 || gateway === null) {
|
|
56468
|
+
return "Error: use a canonical IPv4 network CIDR (/0\u2013/30) and valid gateway.";
|
|
56469
|
+
}
|
|
56470
|
+
const broadcast = subnet.network + 2 ** (32 - subnet.prefix) - 1;
|
|
56471
|
+
if (gateway <= subnet.network || gateway >= broadcast) {
|
|
56472
|
+
return "Error: gateway must be a usable host inside the segment subnet.";
|
|
56473
|
+
}
|
|
56474
|
+
if (a.internet && !a.wan_interface) {
|
|
56475
|
+
return "Error: internet=true requires wan_interface; unscoped masquerade is not safe. Set internet=false to reuse existing NAT.";
|
|
56476
|
+
}
|
|
56477
|
+
const isolate = [...new Set(a.isolate_from ?? [])];
|
|
56478
|
+
if (isolate.length && !a.isolation_before) {
|
|
56479
|
+
return "Error: isolate_from requires a reviewed isolation_before rule .id; blindly appending drops may not isolate anything.";
|
|
56480
|
+
}
|
|
56481
|
+
const tagged = portList(a.tagged_ports);
|
|
56482
|
+
const untagged = portList(a.untagged_ports);
|
|
56483
|
+
if (untagged.includes(a.bridge) || untagged.some((p) => tagged.includes(p))) {
|
|
56484
|
+
return "Error: this routed VLAN requires a tagged bridge/CPU and disjoint tagged/untagged ports.";
|
|
56485
|
+
}
|
|
56486
|
+
let range;
|
|
56487
|
+
if (a.dhcp) {
|
|
56488
|
+
if (!a.dhcp_range && subnet.prefix !== 24) {
|
|
56489
|
+
return "Error: non-/24 DHCP requires an explicit dhcp_range inside the subnet.";
|
|
56490
|
+
}
|
|
56491
|
+
const dhcpRange = a.dhcp_range ?? defaultRange2(a.subnet);
|
|
56492
|
+
range = dhcpRange;
|
|
56493
|
+
const parts = dhcpRange.split("-");
|
|
56494
|
+
const lo = parseIp(parts[0] ?? "");
|
|
56495
|
+
const hi = parseIp(parts[1] ?? "");
|
|
56496
|
+
if (parts.length !== 2 || lo === null || hi === null || lo > hi || lo <= subnet.network || hi >= broadcast || gateway >= lo && gateway <= hi) {
|
|
56497
|
+
return "Error: dhcp_range must be a single ordered start-end range inside the subnet, excluding network, broadcast and gateway.";
|
|
56498
|
+
}
|
|
56499
|
+
}
|
|
56500
|
+
const prefix = subnet.prefix;
|
|
54246
56501
|
const vlanIf = a.name;
|
|
54247
56502
|
const groups = [];
|
|
54248
56503
|
groups.push({
|
|
@@ -54252,11 +56507,11 @@ var vlanDesignerTools = [
|
|
|
54252
56507
|
new Cmd("/ip address add").set("address", `${a.gateway}/${prefix}`).set("interface", vlanIf).build()
|
|
54253
56508
|
]
|
|
54254
56509
|
});
|
|
54255
|
-
if (
|
|
56510
|
+
if (tagged.length || untagged.length) {
|
|
54256
56511
|
groups.push({
|
|
54257
56512
|
label: "Bridge VLAN tagging",
|
|
54258
56513
|
commands: [
|
|
54259
|
-
new Cmd("/interface bridge vlan add").set("bridge", a.bridge).set("vlan-ids", a.vlan_id).
|
|
56514
|
+
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()
|
|
54260
56515
|
]
|
|
54261
56516
|
});
|
|
54262
56517
|
}
|
|
@@ -54265,7 +56520,7 @@ var vlanDesignerTools = [
|
|
|
54265
56520
|
groups.push({
|
|
54266
56521
|
label: "DHCP server",
|
|
54267
56522
|
commands: [
|
|
54268
|
-
new Cmd("/ip pool add").set("name", pool).set("ranges",
|
|
56523
|
+
new Cmd("/ip pool add").set("name", pool).set("ranges", range).build(),
|
|
54269
56524
|
new Cmd("/ip dhcp-server add").set("name", `${a.name}-dhcp`).set("interface", vlanIf).set("address-pool", pool).set("disabled", "no").build(),
|
|
54270
56525
|
new Cmd("/ip dhcp-server network add").set("address", a.subnet).set("gateway", a.gateway).set("dns-server", a.gateway).build()
|
|
54271
56526
|
]
|
|
@@ -54275,15 +56530,14 @@ var vlanDesignerTools = [
|
|
|
54275
56530
|
groups.push({
|
|
54276
56531
|
label: "Internet (srcnat masquerade)",
|
|
54277
56532
|
commands: [
|
|
54278
|
-
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()
|
|
56533
|
+
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()
|
|
54279
56534
|
]
|
|
54280
56535
|
});
|
|
54281
56536
|
}
|
|
54282
|
-
const isolate = a.isolate_from ?? [];
|
|
54283
56537
|
if (isolate.length) {
|
|
54284
56538
|
groups.push({
|
|
54285
56539
|
label: "Inter-VLAN isolation",
|
|
54286
|
-
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())
|
|
56540
|
+
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())
|
|
54287
56541
|
});
|
|
54288
56542
|
}
|
|
54289
56543
|
const all = groups.flatMap((g) => g.commands);
|
|
@@ -54293,20 +56547,37 @@ ${g.commands.map((c) => ` ${c}`).join(`
|
|
|
54293
56547
|
`)}`).join(`
|
|
54294
56548
|
|
|
54295
56549
|
`);
|
|
54296
|
-
return `DRY RUN \u2014 VLAN ${a.vlan_id} '${a.name}' (${a.subnet}); ${all.length} command(s)
|
|
56550
|
+
return `DRY RUN \u2014 VLAN ${a.vlan_id} '${a.name}' (${a.subnet}); ${all.length} command(s):
|
|
54297
56551
|
|
|
54298
|
-
${
|
|
56552
|
+
${COVERAGE}
|
|
56553
|
+
|
|
56554
|
+
${preview}
|
|
56555
|
+
|
|
56556
|
+
Apply only within the complete approved migration plan.`;
|
|
56557
|
+
}
|
|
56558
|
+
if (isolate.length) {
|
|
56559
|
+
const anchor = await executeMikrotikCommand2(new Cmd("/ip firewall filter print count-only where").set(".id", a.isolation_before).set("chain", "forward").set("disabled", "no").build(), ctx);
|
|
56560
|
+
if (anchor.trim() !== "1")
|
|
56561
|
+
return "Error: isolation_before is not a unique enabled forward rule. No changes applied; read rules again.";
|
|
54299
56562
|
}
|
|
54300
56563
|
const done = [];
|
|
54301
56564
|
for (const cmd of all) {
|
|
54302
|
-
|
|
56565
|
+
let result;
|
|
56566
|
+
try {
|
|
56567
|
+
result = await executeMikrotikCommand2(cmd, ctx);
|
|
56568
|
+
} catch (error) {
|
|
56569
|
+
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.
|
|
56570
|
+
${COVERAGE}`;
|
|
56571
|
+
}
|
|
54303
56572
|
if (looksLikeError(result)) {
|
|
54304
56573
|
return `Built ${done.length}/${all.length} commands, then FAILED: ${result}
|
|
54305
|
-
Review partial segment (the VLAN may exist without DHCP/firewall)
|
|
56574
|
+
Review partial segment (the VLAN may exist without DHCP/firewall). Do not retry blindly.
|
|
56575
|
+
${COVERAGE}`;
|
|
54306
56576
|
}
|
|
54307
56577
|
done.push(cmd);
|
|
54308
56578
|
}
|
|
54309
|
-
return `
|
|
56579
|
+
return `IPv4 scaffold '${a.name}' (id ${a.vlan_id}, ${a.subnet}): ${done.length} command(s) completed. Isolation and connectivity are UNVERIFIED.
|
|
56580
|
+
${COVERAGE}`;
|
|
54310
56581
|
}
|
|
54311
56582
|
})
|
|
54312
56583
|
];
|
|
@@ -54319,7 +56590,7 @@ var vlanTools = [
|
|
|
54319
56590
|
name: "create_vlan_interface",
|
|
54320
56591
|
title: "Create VLAN Interface",
|
|
54321
56592
|
annotations: WRITE,
|
|
54322
|
-
description: "Creates an 802.1Q VLAN sub-interface (`/interface vlan`) on a specified parent physical or bridge interface." + "
|
|
56593
|
+
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.",
|
|
54323
56594
|
inputSchema: {
|
|
54324
56595
|
name: interfaceName("Name for the new VLAN interface, e.g. 'vlan100'"),
|
|
54325
56596
|
vlan_id: number().int().min(1).max(4094).describe("802.1Q VLAN ID (1-4094)"),
|
|
@@ -56847,6 +59118,27 @@ var moduleCatalog2 = [
|
|
|
56847
59118
|
description: "Administrator-approved DNS/TCP/TLS/HTTPS service checks, immutable contracts, history and fail-closed rollout gates with explicit MCP-host perspective.",
|
|
56848
59119
|
tools: serviceContractTools
|
|
56849
59120
|
},
|
|
59121
|
+
{
|
|
59122
|
+
label: "Service Routing",
|
|
59123
|
+
slug: "service-routing",
|
|
59124
|
+
group: "System & Ops",
|
|
59125
|
+
description: "Scoped dual-stack domain policies, router VRF service probes and explicitly authorized failover.",
|
|
59126
|
+
tools: serviceRoutingTools
|
|
59127
|
+
},
|
|
59128
|
+
{
|
|
59129
|
+
label: "Network Flight Recorder",
|
|
59130
|
+
slug: "flight-recorder",
|
|
59131
|
+
group: "System & Ops",
|
|
59132
|
+
description: "Durable bounded pre/post-incident telemetry, off-router log metadata and MCP change correlation.",
|
|
59133
|
+
tools: flightRecorderTools
|
|
59134
|
+
},
|
|
59135
|
+
{
|
|
59136
|
+
label: "Recovery Lab",
|
|
59137
|
+
slug: "recovery-lab",
|
|
59138
|
+
group: "System & Ops",
|
|
59139
|
+
description: "Isolated CHR rehearsal orchestration with immutable snapshot subsets, coverage and verified runner evidence.",
|
|
59140
|
+
tools: recoveryLabTools
|
|
59141
|
+
},
|
|
56850
59142
|
{
|
|
56851
59143
|
label: "Client Investigations",
|
|
56852
59144
|
slug: "investigations",
|
|
@@ -56921,7 +59213,7 @@ var moduleCatalog2 = [
|
|
|
56921
59213
|
label: "VLAN Designer",
|
|
56922
59214
|
slug: "vlan-designer",
|
|
56923
59215
|
group: "Interfaces",
|
|
56924
|
-
description: "
|
|
59216
|
+
description: "Read VLAN design/safety knowledge and preview partial IPv4 scaffolding; full L2, dual-stack " + "isolation and client verification remain explicit migration work.",
|
|
56925
59217
|
tools: vlanDesignerTools
|
|
56926
59218
|
},
|
|
56927
59219
|
{
|
|
@@ -57782,7 +60074,7 @@ var moduleCatalog2 = [
|
|
|
57782
60074
|
label: "Containers",
|
|
57783
60075
|
slug: "container",
|
|
57784
60076
|
group: "System & Ops",
|
|
57785
|
-
description: "
|
|
60077
|
+
description: "Shared container safety knowledge and exact-target OCI lifecycle (`/container`), global config " + "(registry/tmpdir/RAM), named env lists, and volume mounts.",
|
|
57786
60078
|
tools: containerTools
|
|
57787
60079
|
},
|
|
57788
60080
|
{
|
|
@@ -57864,4 +60156,4 @@ function selectToolModules2(filter = {}, catalog = moduleCatalog2) {
|
|
|
57864
60156
|
}).map((m) => m.tools);
|
|
57865
60157
|
}
|
|
57866
60158
|
|
|
57867
|
-
export { __toESM, __commonJS, clone, normalizeParams, own, installLazyProp, $constructor, parse, parseAsync, safeParse, safeParseAsync, $ZodType, $ZodObject, toJSONSchema, string, number, boolean, _null, unknown, array, object, looseObject, union, discriminatedUnion, intersection, record, _enum, literal, ZodOptional, optional, custom, preprocess, datetime, DEFAULT_DASHBOARD_DB2, DEFAULT_SNAPSHOT_DB2, DEFAULT_BACKUP_DIR2, McpServerSettingsSchema2, DeviceConfigSchema2, DashboardConfigSchema2, MemoryConfigSchema2, SSHConfigSchema2, MikrotikConfigSchema2, getConfigSource2, loadConfig2, logger, MikroTikSSHClient2, setConfig2, getConfig2, listDevices2, deviceLabels, resolveDeviceName2, deviceDirectory, getDevice2, SafeModeManager2, getSafeModeManager2, executeMikrotikCommand2, defineTool2, registerTools2, PROMPTS_DIR, registerUiResources, VERSION2, WEBSITE_URL, LOGO_URL, SERVER_TITLE, SERVER_DESCRIPTION, SERVER_NAME2, loadFileCacheSync, updateSummaryLine, parseExportMeta2, normalizeExport2, contentSha2, countLines2, openSnapshotStore2, moduleCatalog2, allToolModules2, selectToolModules2 };
|
|
60159
|
+
export { __toESM, __commonJS, clone, normalizeParams, own, installLazyProp, $constructor, parse, parseAsync, safeParse, safeParseAsync, $ZodType, $ZodObject, toJSONSchema, string, number, boolean, _null, unknown, array, object, looseObject, union, discriminatedUnion, intersection, record, _enum, literal, ZodOptional, optional, custom, preprocess, datetime, DEFAULT_DASHBOARD_DB2, DEFAULT_SNAPSHOT_DB2, DEFAULT_BACKUP_DIR2, McpServerSettingsSchema2, DeviceConfigSchema2, DashboardConfigSchema2, MemoryConfigSchema2, SSHConfigSchema2, MikrotikConfigSchema2, getConfigSource2, loadConfig2, logger, MikroTikSSHClient2, setConfig2, getConfig2, listDevices2, deviceLabels, resolveDeviceName2, deviceDirectory, getDevice2, SafeModeManager2, getSafeModeManager2, executeMikrotikCommand2, defineTool2, registerTools2, PROMPTS_DIR, registerUiResources, VLAN_GUIDE_URI, getVlanSegmentationGuide, VLAN_INSTRUCTIONS, vlanPromptGuidance, CONTAINER_GUIDE_URI, getRouterosContainerGuide, CONTAINER_INSTRUCTIONS, containerPromptGuidance, VERSION2, WEBSITE_URL, LOGO_URL, SERVER_TITLE, SERVER_DESCRIPTION, SERVER_NAME2, loadFileCacheSync, updateSummaryLine, parseExportMeta2, normalizeExport2, contentSha2, countLines2, openSnapshotStore2, moduleCatalog2, allToolModules2, selectToolModules2 };
|