@usex/mikrotik-mcp 5.19.0 → 5.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +172 -8
- package/dist/cli.js +2751 -679
- package/dist/index.js +148 -27
- package/dist/shared/{library-7wcv2ckk.js → library-73y8qdjr.js} +2231 -540
- package/dist/shared/{library-tqrvrykj.js → library-76naf20r.js} +1 -1
- package/dist/shared/{library-ppnv0f07.js → library-81amv3az.js} +1 -1
- package/dist/shared/{library-z7qsdq88.js → library-krajvnj9.js} +1 -1
- package/dist/shared/{library-f3be6g03.js → library-y9tt30y1.js} +1 -1
- package/dist/ui/aaa.html +8 -8
- package/dist/ui/connected-devices.html +8 -8
- package/dist/ui/dashboard.html +16 -16
- package/dist/ui/fabric.html +11 -11
- package/dist/ui/firewall-audit.html +8 -8
- package/dist/ui/firewall.html +9 -9
- package/dist/ui/interfaces.html +8 -8
- package/dist/ui/investigations.html +11 -11
- package/dist/ui/observability.html +63 -61
- package/dist/ui/operations.html +11 -11
- package/dist/ui/records.html +12 -12
- package/dist/ui/reports.html +11 -11
- package/dist/ui/round-trip.html +11 -11
- package/dist/ui/service-health.html +11 -11
- package/package.json +22 -22
- package/prompts/audit-routeros-containers.md +27 -0
- package/prompts/audit-vlan-segmentation.md +31 -0
- package/prompts/setup-guest-wifi.md +23 -24
- package/prompts/setup-routeros-container.md +36 -0
- package/prompts/setup-v2ray-container-proxy.md +68 -194
- package/prompts/setup-vlan-network.md +27 -33
- package/schemas/README.md +1 -1
- package/schemas/devtools-manifest.json +287 -16
- package/schemas/tool-catalog.json +785 -109
- package/schemas/tools/add_container.json +42 -30
- package/schemas/tools/add_container_env.json +3 -4
- package/schemas/tools/add_container_mount.json +10 -4
- package/schemas/tools/apply_service_routing.json +23 -0
- package/schemas/tools/arm_service_routing.json +23 -0
- package/schemas/tools/configure_flight_recorder.json +30 -0
- package/schemas/tools/create_service_routing.json +78 -0
- package/schemas/tools/design_network_segment.json +22 -6
- package/schemas/tools/destroy_recovery_lab.json +18 -0
- package/schemas/tools/export_network_incident.json +14 -0
- package/schemas/tools/freeze_network_incident.json +14 -0
- package/schemas/tools/get_container.json +11 -4
- package/schemas/tools/get_flight_recorder.json +7 -0
- package/schemas/tools/get_recovery_lab.json +7 -0
- package/schemas/tools/get_routeros_container_guide.json +22 -0
- package/schemas/tools/get_vlan_segmentation_guide.json +14 -0
- package/schemas/tools/list_container_envs.json +1 -1
- package/schemas/tools/list_container_mounts.json +7 -2
- package/schemas/tools/list_containers.json +2 -4
- package/schemas/tools/list_service_routing.json +7 -0
- package/schemas/tools/poll_recovery_lab.json +14 -0
- package/schemas/tools/prepare_recovery_lab.json +23 -0
- package/schemas/tools/preview_service_routing.json +23 -0
- package/schemas/tools/probe_service_routing.json +14 -0
- package/schemas/tools/recovery_lab_inventory.json +7 -0
- package/schemas/tools/remove_container.json +11 -4
- package/schemas/tools/remove_container_env.json +7 -3
- package/schemas/tools/remove_container_mount.json +18 -2
- package/schemas/tools/service_routing_inventory.json +7 -0
- package/schemas/tools/set_container_config.json +4 -6
- package/schemas/tools/start_container.json +11 -4
- package/schemas/tools/start_recovery_lab.json +18 -0
- package/schemas/tools/stop_container.json +11 -4
- package/schemas/tools/update_container.json +46 -6
- /package/dist/shared/{cli-j07tbrke.js → cli-426pkqe9.js} +0 -0
- /package/dist/shared/{cli-y00nwzxx.js → cli-6wdstvdq.js} +0 -0
- /package/dist/shared/{cli-s0rxncz4.js → cli-cvt06346.js} +0 -0
- /package/dist/shared/{cli-gtq5bw8q.js → cli-z1kavk0z.js} +0 -0
|
@@ -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-81amv3az.js")).openSnapshotStore;
|
|
14849
|
+
const db = await beforeTarget((await import("./library-y9tt30y1.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-76naf20r.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,1162 @@ 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
|
+
var name2 = string().trim().min(1).max(64).regex(/^[a-zA-Z0-9_.-]+$/);
|
|
19639
|
+
var routingInput = object({
|
|
19640
|
+
name: string().trim().min(1).max(80),
|
|
19641
|
+
target: name2.describe("Approved HTTPS alias in serviceProbes.targets; its exact hostname is routed"),
|
|
19642
|
+
family: _enum(["ipv4", "ipv6"]),
|
|
19643
|
+
sources: array(string().refine((v) => ipaddr2.isValidCIDR(v), "Use an explicit client subnet CIDR")).min(1).max(8),
|
|
19644
|
+
tables: array(name2).min(1).max(3),
|
|
19645
|
+
primary: name2,
|
|
19646
|
+
maxLatencyMs: number().int().min(100).max(15000).default(5000),
|
|
19647
|
+
failuresBeforeSwitch: number().int().min(2).max(10).default(3),
|
|
19648
|
+
cooldownSeconds: number().int().min(120).max(3600).default(300)
|
|
19649
|
+
}).superRefine((v, ctx) => {
|
|
19650
|
+
if (!v.tables.includes(v.primary) || new Set(v.tables).size !== v.tables.length)
|
|
19651
|
+
ctx.addIssue({ code: "custom", message: "Choose one unique candidate table as primary" });
|
|
19652
|
+
for (const s of v.sources) {
|
|
19653
|
+
const [ip, bits] = ipaddr2.parseCIDR(s);
|
|
19654
|
+
if (ip.kind() !== v.family || bits === 0)
|
|
19655
|
+
ctx.addIssue({
|
|
19656
|
+
code: "custom",
|
|
19657
|
+
message: "Sources must match the selected IP family and cannot be a default route"
|
|
19658
|
+
});
|
|
19659
|
+
}
|
|
19660
|
+
});
|
|
19661
|
+
var enabled3 = (r) => !["yes", "true"].includes(r.disabled) && !(r.flags ?? "").includes("X");
|
|
19662
|
+
var ownerTag = (id) => `mcp-sr-${id}`;
|
|
19663
|
+
var selector = (tag) => `[find where comment=${quoteValue(tag)}]`;
|
|
19664
|
+
var routingPath = (family) => family === "ipv4" ? "/ip firewall" : "/ipv6 firewall";
|
|
19665
|
+
function fingerprint(facts) {
|
|
19666
|
+
return createHash5("sha256").update(JSON.stringify(facts, (key, value) => ["#", ".id", "bytes", "packets", "last-handshake", "expires-after"].includes(key) ? undefined : value)).digest("hex");
|
|
19667
|
+
}
|
|
19668
|
+
function planCommands(policy, table, facts, remove = false) {
|
|
19669
|
+
const path = routingPath(policy.family), tag = ownerTag(policy.id), chain = `sr-${policy.id.slice(0, 12)}`;
|
|
19670
|
+
if (policy.state === "uncertain")
|
|
19671
|
+
throw new Error("Reconcile uncertain router state before another change.");
|
|
19672
|
+
const owned = facts.mangle.filter((r) => r.comment === tag);
|
|
19673
|
+
if (facts.mangle.some((r) => r.chain === chain && r.comment !== tag))
|
|
19674
|
+
throw new Error("Private chain contains foreign rules; review it first.");
|
|
19675
|
+
if (owned.some((r) => r.chain !== chain && r.chain !== "prerouting"))
|
|
19676
|
+
throw new Error("Owned rules were edited externally; review them first.");
|
|
19677
|
+
if (remove)
|
|
19678
|
+
return [
|
|
19679
|
+
new Cmd(`${path} mangle remove ${selector(tag)}`).build(),
|
|
19680
|
+
new Cmd(`${path} address-list remove ${selector(tag)}`).build()
|
|
19681
|
+
];
|
|
19682
|
+
const listRows = facts.addresses.filter((r) => [`${tag}-src`, `${tag}-dst`].includes(r.list));
|
|
19683
|
+
const staticRows = listRows.filter((r) => !["yes", "true"].includes(r.dynamic) && !(r.flags ?? "").includes("D"));
|
|
19684
|
+
if (owned.length) {
|
|
19685
|
+
const expectedLists = [
|
|
19686
|
+
...policy.sources.map((address) => ({ list: `${tag}-src`, address })),
|
|
19687
|
+
{ list: `${tag}-dst`, address: policy.host }
|
|
19688
|
+
];
|
|
19689
|
+
if (staticRows.length !== expectedLists.length || expectedLists.some((e) => !staticRows.some((r) => r.list === e.list && r.address === e.address && r.comment === tag && enabled3(r))))
|
|
19690
|
+
throw new Error("Owned address-list scope changed externally.");
|
|
19691
|
+
if (listRows.some((r) => r.list === `${tag}-src` && !staticRows.includes(r)))
|
|
19692
|
+
throw new Error("Unexpected dynamic source scope.");
|
|
19693
|
+
} else if (policy.state === "active" || listRows.length) {
|
|
19694
|
+
throw new Error("Owned policy is missing or partially present; reconcile first.");
|
|
19695
|
+
}
|
|
19696
|
+
if (!policy.tables.includes(table))
|
|
19697
|
+
throw new Error("This exit is not approved by the policy.");
|
|
19698
|
+
if (!facts.tables.some((r) => r.name === table && enabled3(r) && ["yes", "true"].includes(r.fib)))
|
|
19699
|
+
throw new Error("Exit needs an existing enabled FIB table.");
|
|
19700
|
+
const dst = policy.family === "ipv4" ? "0.0.0.0/0" : "::/0";
|
|
19701
|
+
if (!facts.routes.some((r) => r["routing-table"] === table && r["dst-address"] === dst && enabled3(r) && (["yes", "true"].includes(r.active) || (r.flags ?? "").includes("A"))))
|
|
19702
|
+
throw new Error("Exit has no observed active default route for this family.");
|
|
19703
|
+
if (facts.filters.some((r) => enabled3(r) && r.action === "fasttrack-connection"))
|
|
19704
|
+
throw new Error("FastTrack may bypass this policy. Configure an explicit exclusion before applying.");
|
|
19705
|
+
if (facts.mangle.some((r) => enabled3(r) && r.comment !== tag && ["mark-routing", "jump", "route"].includes(r.action)))
|
|
19706
|
+
throw new Error("Existing routing/jump rules need an administrator conflict review. They will not be overridden.");
|
|
19707
|
+
const result = [];
|
|
19708
|
+
if (owned.length) {
|
|
19709
|
+
if (policy.state !== "active" || !policy.activeTable)
|
|
19710
|
+
throw new Error("Unexpected owned rules exist. Reconcile the router before applying a draft.");
|
|
19711
|
+
const expected = planCommands({ ...policy, state: "draft" }, policy.activeTable, {
|
|
19712
|
+
...facts,
|
|
19713
|
+
mangle: facts.mangle.filter((r) => r.comment !== tag),
|
|
19714
|
+
addresses: facts.addresses.filter((r) => ![`${tag}-src`, `${tag}-dst`].includes(r.list))
|
|
19715
|
+
}).filter((command) => command.startsWith(`${path} mangle add`)).map((command) => parseRecords(`0 ${command}`).rows[0]);
|
|
19716
|
+
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))))
|
|
19717
|
+
throw new Error("Owned rule scope changed externally. Automatic edits are blocked.");
|
|
19718
|
+
if (owned.filter((r) => r.action === "mark-routing").length !== 1)
|
|
19719
|
+
throw new Error("Owned routing mark is missing or ambiguous.");
|
|
19720
|
+
result.push(new Cmd(`${path} mangle set [find where comment=${quoteValue(tag)} action=mark-routing]`).set("new-routing-mark", table).build());
|
|
19721
|
+
return result;
|
|
19722
|
+
}
|
|
19723
|
+
for (const address of policy.sources)
|
|
19724
|
+
result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-src`).set("address", address).set("comment", tag).build());
|
|
19725
|
+
result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-dst`).set("address", policy.host).set("comment", tag).build());
|
|
19726
|
+
const exclude = policy.family === "ipv4" ? [
|
|
19727
|
+
"0.0.0.0/8",
|
|
19728
|
+
"10.0.0.0/8",
|
|
19729
|
+
"100.64.0.0/10",
|
|
19730
|
+
"127.0.0.0/8",
|
|
19731
|
+
"169.254.0.0/16",
|
|
19732
|
+
"172.16.0.0/12",
|
|
19733
|
+
"192.168.0.0/16",
|
|
19734
|
+
"224.0.0.0/3"
|
|
19735
|
+
] : ["::/128", "::1/128", "::ffff:0:0/96", "fc00::/7", "fe80::/10", "ff00::/8"];
|
|
19736
|
+
for (const subnet of exclude)
|
|
19737
|
+
result.push(new Cmd(`${path} mangle add`).set("chain", chain).set("dst-address", subnet).set("action", "return").set("comment", tag).build());
|
|
19738
|
+
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());
|
|
19739
|
+
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());
|
|
19740
|
+
return result;
|
|
19741
|
+
}
|
|
19742
|
+
|
|
19743
|
+
// src/service-routing/service.ts
|
|
19744
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
19745
|
+
import { isIP as isIP2 } from "net";
|
|
19746
|
+
|
|
19747
|
+
// src/operations/store.ts
|
|
19748
|
+
import { mkdirSync as mkdirSync9, chmodSync } from "fs";
|
|
19749
|
+
import { dirname as dirname9, join as join2 } from "path";
|
|
19750
|
+
class OperationsStore {
|
|
19751
|
+
db;
|
|
19752
|
+
constructor(db) {
|
|
19753
|
+
this.db = db;
|
|
19754
|
+
db.run("PRAGMA busy_timeout = 3000");
|
|
19755
|
+
db.run("CREATE TABLE IF NOT EXISTS workspace_records (kind TEXT, id TEXT, device TEXT, updated INTEGER, body TEXT, PRIMARY KEY(kind,id))");
|
|
19756
|
+
db.run("CREATE INDEX IF NOT EXISTS workspace_device ON workspace_records(kind,device,updated DESC)");
|
|
19757
|
+
db.run("CREATE TABLE IF NOT EXISTS workspace_locks (device TEXT PRIMARY KEY, owner TEXT NOT NULL)");
|
|
19758
|
+
}
|
|
19759
|
+
get(kind, id, device) {
|
|
19760
|
+
const row = this.db.query("SELECT body FROM workspace_records WHERE kind=? AND id=? AND device=?").get(kind, id, device);
|
|
19761
|
+
return row ? JSON.parse(row.body) : undefined;
|
|
19762
|
+
}
|
|
19763
|
+
list(kind, device, limit = 100) {
|
|
19764
|
+
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));
|
|
19765
|
+
}
|
|
19766
|
+
put(kind, record) {
|
|
19767
|
+
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));
|
|
19768
|
+
}
|
|
19769
|
+
delete(kind, id, device) {
|
|
19770
|
+
this.db.query("DELETE FROM workspace_records WHERE kind=? AND id=? AND device=?").run(kind, id, device);
|
|
19771
|
+
}
|
|
19772
|
+
prune(kind, device, before) {
|
|
19773
|
+
this.db.query("DELETE FROM workspace_records WHERE kind=? AND device=? AND updated<?").run(kind, device, before);
|
|
19774
|
+
}
|
|
19775
|
+
lock(device, owner) {
|
|
19776
|
+
const result = this.db.query("INSERT OR IGNORE INTO workspace_locks VALUES (?,?)").run(device, owner);
|
|
19777
|
+
if (!result.changes)
|
|
19778
|
+
throw new Error("Another workspace operation holds this router. An interrupted operation requires reconciliation before retrying.");
|
|
19779
|
+
}
|
|
19780
|
+
unlock(device, owner) {
|
|
19781
|
+
this.db.query("DELETE FROM workspace_locks WHERE device=? AND owner=?").run(device, owner);
|
|
19782
|
+
}
|
|
19783
|
+
}
|
|
19784
|
+
var pending5;
|
|
19785
|
+
function operationsStore() {
|
|
19786
|
+
pending5 ??= (async () => {
|
|
19787
|
+
const path = join2(dirname9(DEFAULT_SNAPSHOT_DB2), "operations.db");
|
|
19788
|
+
mkdirSync9(dirname9(path), { recursive: true, mode: 448 });
|
|
19789
|
+
const { Database } = await import("bun:sqlite");
|
|
19790
|
+
const db = new Database(path, { create: true });
|
|
19791
|
+
chmodSync(path, 384);
|
|
19792
|
+
db.run("PRAGMA journal_mode = WAL");
|
|
19793
|
+
return new OperationsStore(db);
|
|
19794
|
+
})().catch((error) => {
|
|
19795
|
+
pending5 = undefined;
|
|
19796
|
+
throw error;
|
|
19797
|
+
});
|
|
19798
|
+
return pending5;
|
|
19799
|
+
}
|
|
19800
|
+
|
|
19801
|
+
// src/service-routing/service.ts
|
|
19802
|
+
var kind = "service-routing";
|
|
19803
|
+
function access(ctx, tool, write = false) {
|
|
19804
|
+
const device = resolveDeviceName2(ctx.device);
|
|
19805
|
+
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
19806
|
+
return device;
|
|
19807
|
+
}
|
|
19808
|
+
async function locked(device, work) {
|
|
19809
|
+
const store = await operationsStore(), owner = randomUUID8();
|
|
19810
|
+
store.lock(device, owner);
|
|
19811
|
+
try {
|
|
19812
|
+
return await work();
|
|
19813
|
+
} finally {
|
|
19814
|
+
store.unlock(device, owner);
|
|
19815
|
+
}
|
|
19816
|
+
}
|
|
19817
|
+
async function routingPolicy(id, device) {
|
|
19818
|
+
const policy = (await operationsStore()).get(kind, id, device);
|
|
19819
|
+
if (!policy)
|
|
19820
|
+
throw new Error("Policy not found on the selected router.");
|
|
19821
|
+
return policy;
|
|
19822
|
+
}
|
|
19823
|
+
function save(policy, message) {
|
|
19824
|
+
policy.updatedAt = Date.now();
|
|
19825
|
+
if (message)
|
|
19826
|
+
policy.history = [{ at: policy.updatedAt, message }, ...policy.history].slice(0, 100);
|
|
19827
|
+
return operationsStore().then((store) => store.put(kind, policy));
|
|
19828
|
+
}
|
|
19829
|
+
async function routingInventory(ctx) {
|
|
19830
|
+
access(ctx, "service_routing_inventory");
|
|
19831
|
+
const tables = await rows("/routing table", "name,fib,disabled", ctx);
|
|
19832
|
+
return {
|
|
19833
|
+
tables: tables.filter((r) => enabled3(r) && ["yes", "true"].includes(r.fib)).map((r) => r.name),
|
|
19834
|
+
targets: Object.entries(getConfig2().serviceProbes.targets).filter(([, t]) => t.kind === "https").map(([alias, t]) => ({ alias, host: t.host }))
|
|
19835
|
+
};
|
|
19836
|
+
}
|
|
19837
|
+
async function listRouting(ctx) {
|
|
19838
|
+
const device = access(ctx, "list_service_routing");
|
|
19839
|
+
return { policies: (await operationsStore()).list(kind, device) };
|
|
19840
|
+
}
|
|
19841
|
+
async function createRouting(input, ctx) {
|
|
19842
|
+
const device = access(ctx, "create_service_routing", true), a = routingInput.parse(input);
|
|
19843
|
+
const target = getConfig2().serviceProbes.targets[a.target];
|
|
19844
|
+
if (!target || target.kind !== "https")
|
|
19845
|
+
throw new Error("Select an administrator-approved HTTPS probe alias first.");
|
|
19846
|
+
const store = await operationsStore();
|
|
19847
|
+
if (store.list(kind, device).length >= 100)
|
|
19848
|
+
throw new Error("Router policy limit reached (100).");
|
|
19849
|
+
const policy = {
|
|
19850
|
+
...a,
|
|
19851
|
+
id: randomUUID8(),
|
|
19852
|
+
device,
|
|
19853
|
+
host: target.host,
|
|
19854
|
+
updatedAt: Date.now(),
|
|
19855
|
+
state: "draft",
|
|
19856
|
+
samples: [],
|
|
19857
|
+
history: []
|
|
19858
|
+
};
|
|
19859
|
+
await save(policy, "Draft saved. No router changes or probes yet.");
|
|
19860
|
+
return policy;
|
|
19861
|
+
}
|
|
19862
|
+
async function facts(policy, ctx) {
|
|
19863
|
+
const base = routingPath(policy.family);
|
|
19864
|
+
const tables = await rows("/routing table", "name,fib,disabled", ctx);
|
|
19865
|
+
const routes = await rows(policy.family === "ipv4" ? "/ip route" : "/ipv6 route", "routing-table,dst-address,gateway,active,disabled", ctx);
|
|
19866
|
+
const mangle = await rows(`${base} mangle`, "chain,action,new-routing-mark,jump-target,src-address-list,dst-address-list,dst-address-type,dst-address,passthrough,disabled,comment", ctx);
|
|
19867
|
+
const filters = await rows(`${base} filter`, "action,disabled", ctx);
|
|
19868
|
+
if (policy.family === "ipv4") {
|
|
19869
|
+
const active = (await checkedRead("/ip firewall connection print count-only where fasttrack=yes", ctx)).trim();
|
|
19870
|
+
if (!/^\d+$/.test(active) || Number(active) > 0)
|
|
19871
|
+
throw new Error("Active FastTrack connections must drain before routing can be changed.");
|
|
19872
|
+
}
|
|
19873
|
+
const vrfs = await rows("/ip vrf", "name,interfaces,disabled", ctx);
|
|
19874
|
+
const addresses = await rows(`${base} address-list`, "list,address,comment,dynamic,disabled", ctx);
|
|
19875
|
+
return { tables, routes, mangle, filters, vrfs, addresses };
|
|
19876
|
+
}
|
|
19877
|
+
function fetchCommand(address, table, host, path, port) {
|
|
19878
|
+
return `:put [:serialize to=json value=[${new Cmd("/tool fetch").set("address", `${address}@${table}`).set("host", host).set("mode", "https").set("src-path", path).set("port", port).set("http-method", "head").set("check-certificate", "yes").set("http-max-redirect-count", 0).set("idle-timeout", "5s").set("output", "none").flag("as-value", true).build()}]]`;
|
|
19879
|
+
}
|
|
19880
|
+
async function probe(policy, ctx) {
|
|
19881
|
+
const target = getConfig2().serviceProbes.targets[policy.target];
|
|
19882
|
+
if (!target || target.kind !== "https" || target.host !== policy.host)
|
|
19883
|
+
throw new Error("Probe approval changed. Create a new policy.");
|
|
19884
|
+
const vrfs = await rows("/ip vrf", "name,disabled", ctx);
|
|
19885
|
+
let addresses = [];
|
|
19886
|
+
try {
|
|
19887
|
+
addresses = await nativeProbeIO.resolve(target.host, 3000);
|
|
19888
|
+
if (addresses.some((a) => !addressAllowed(a, target.addresses)))
|
|
19889
|
+
addresses = [];
|
|
19890
|
+
} catch {}
|
|
19891
|
+
const address = addresses.find((a) => isIP2(a) === (policy.family === "ipv4" ? 4 : 6));
|
|
19892
|
+
for (const table of policy.tables) {
|
|
19893
|
+
const sample = {
|
|
19894
|
+
table,
|
|
19895
|
+
at: Date.now(),
|
|
19896
|
+
state: "unknown",
|
|
19897
|
+
detail: "No approved DNS answer for this IP family."
|
|
19898
|
+
};
|
|
19899
|
+
if (address) {
|
|
19900
|
+
sample.address = address;
|
|
19901
|
+
sample.detail = "This routing table is not a VRF. A table-only HTTPS path cannot be proved by fetch.";
|
|
19902
|
+
if (vrfs.some((v) => v.name === table && enabled3(v))) {
|
|
19903
|
+
const start = Date.now();
|
|
19904
|
+
try {
|
|
19905
|
+
const raw = await executeMikrotikCommand2(fetchCommand(address, table, target.host, target.path, target.port), ctx, { maxMs: 8000 });
|
|
19906
|
+
sample.elapsedMs = Date.now() - start;
|
|
19907
|
+
if (looksLikeError(raw)) {
|
|
19908
|
+
if (/failure:.*(?:fetch|SSL|connection|timeout|resolving|status)/i.test(raw)) {
|
|
19909
|
+
sample.state = "fail";
|
|
19910
|
+
sample.detail = "Router fetch reported an HTTP, TLS or connection failure.";
|
|
19911
|
+
} else
|
|
19912
|
+
sample.detail = "Router fetch was rejected or unsupported; path health is unknown.";
|
|
19913
|
+
} else {
|
|
19914
|
+
const result = JSON.parse(raw.trim());
|
|
19915
|
+
if (result.status === "finished" && (result.code === undefined || Number(result.code) >= 200 && Number(result.code) < 300)) {
|
|
19916
|
+
sample.state = sample.elapsedMs <= policy.maxLatencyMs ? "pass" : "fail";
|
|
19917
|
+
sample.detail = `HTTPS HEAD completed via VRF ${table}; elapsed includes SSH overhead. Not a client-path or throughput test.`;
|
|
19918
|
+
}
|
|
19919
|
+
}
|
|
19920
|
+
} catch {
|
|
19921
|
+
sample.detail = "Router query did not produce verified fetch evidence. Connection or capability may be unavailable.";
|
|
19922
|
+
}
|
|
19923
|
+
}
|
|
19924
|
+
}
|
|
19925
|
+
policy.samples.push(sample);
|
|
19926
|
+
}
|
|
19927
|
+
policy.samples = policy.samples.slice(-180);
|
|
19928
|
+
await save(policy);
|
|
19929
|
+
}
|
|
19930
|
+
async function probeRouting(id, ctx) {
|
|
19931
|
+
const device = access(ctx, "probe_service_routing");
|
|
19932
|
+
return locked(device, async () => {
|
|
19933
|
+
const policy = await routingPolicy(id, device);
|
|
19934
|
+
await probe(policy, ctx);
|
|
19935
|
+
return policy;
|
|
19936
|
+
});
|
|
19937
|
+
}
|
|
19938
|
+
async function preview(policy, table, remove, ctx) {
|
|
19939
|
+
const snapshot = await facts(policy, ctx);
|
|
19940
|
+
policy.plan = {
|
|
19941
|
+
id: randomUUID8(),
|
|
19942
|
+
table,
|
|
19943
|
+
remove,
|
|
19944
|
+
expiresAt: Date.now() + 120000,
|
|
19945
|
+
fingerprint: fingerprint(snapshot),
|
|
19946
|
+
commands: planCommands(policy, table, snapshot, remove)
|
|
19947
|
+
};
|
|
19948
|
+
await save(policy, "Preview created. Review scope and commands; valid for two minutes.");
|
|
19949
|
+
return policy;
|
|
19950
|
+
}
|
|
19951
|
+
async function previewRouting(id, table, remove, ctx) {
|
|
19952
|
+
const device = access(ctx, "preview_service_routing");
|
|
19953
|
+
return locked(device, async () => preview(await routingPolicy(id, device), table, remove, ctx));
|
|
19954
|
+
}
|
|
19955
|
+
async function apply(policy, planId, ctx) {
|
|
19956
|
+
const plan = policy.plan;
|
|
19957
|
+
if (!plan || plan.id !== planId || plan.expiresAt < Date.now())
|
|
19958
|
+
throw new Error("Preview expired or changed. Preview again before confirming.");
|
|
19959
|
+
access(ctx, "apply_service_routing", true);
|
|
19960
|
+
if (fingerprint(await facts(policy, ctx)) !== plan.fingerprint)
|
|
19961
|
+
throw new Error("Router configuration changed after preview.");
|
|
19962
|
+
const safe = getSafeModeManager2(policy.device);
|
|
19963
|
+
if (safe.isActive)
|
|
19964
|
+
throw new Error("Finish the existing Safe Mode session first.");
|
|
19965
|
+
policy.snapshot = await captureSnapshot(ctx, `Before service route ${policy.name}`, true);
|
|
19966
|
+
policy.state = "uncertain";
|
|
19967
|
+
policy.armedUntil = undefined;
|
|
19968
|
+
await save(policy, "Apply started; outcome must be read back before being considered active.");
|
|
19969
|
+
let owned = false, commitAttempted = false;
|
|
19970
|
+
try {
|
|
19971
|
+
if (!(await safe.enable()).startsWith("Safe mode ENABLED"))
|
|
19972
|
+
throw new Error("Could not acquire Safe Mode.");
|
|
19973
|
+
owned = true;
|
|
19974
|
+
if (fingerprint(await facts(policy, ctx)) !== plan.fingerprint)
|
|
19975
|
+
throw new Error("Router changed while entering Safe Mode.");
|
|
19976
|
+
for (const command of plan.commands)
|
|
19977
|
+
await checkedRead(command, ctx);
|
|
19978
|
+
const after = await facts(policy, ctx);
|
|
19979
|
+
const matched = after.mangle.filter((r) => r.comment === ownerTag(policy.id));
|
|
19980
|
+
if (plan.remove ? matched.length !== 0 : matched.filter((r) => r.action === "mark-routing" && r["new-routing-mark"] === plan.table && enabled3(r)).length !== 1)
|
|
19981
|
+
throw new Error("Router read-back did not match this preview.");
|
|
19982
|
+
if (plan.remove) {
|
|
19983
|
+
if (after.addresses.some((r) => r.comment === ownerTag(policy.id)))
|
|
19984
|
+
throw new Error("Owned address-list removal not confirmed.");
|
|
19985
|
+
} else {
|
|
19986
|
+
planCommands({ ...policy, state: "active", activeTable: plan.table }, plan.table, after);
|
|
19987
|
+
}
|
|
19988
|
+
await checkedRead("/system identity print", ctx);
|
|
19989
|
+
commitAttempted = true;
|
|
19990
|
+
if (!(await safe.commit()).ok)
|
|
19991
|
+
throw new Error("Commit outcome uncertain. Do not replay the change.");
|
|
19992
|
+
owned = false;
|
|
19993
|
+
policy.state = plan.remove ? "removed" : "active";
|
|
19994
|
+
policy.activeTable = plan.remove ? undefined : plan.table;
|
|
19995
|
+
policy.lastSwitchAt = Date.now();
|
|
19996
|
+
policy.plan = undefined;
|
|
19997
|
+
policy.error = undefined;
|
|
19998
|
+
await save(policy, plan.remove ? "Owned routing policy removed." : `Routing read-back verified: ${plan.table}. Client delivery still requires a client check.`);
|
|
19999
|
+
} catch (error) {
|
|
20000
|
+
if (owned && !commitAttempted)
|
|
20001
|
+
await safe.rollback().catch(() => {});
|
|
20002
|
+
policy.error = error instanceof Error ? error.message : "Apply failed";
|
|
20003
|
+
await save(policy, "Apply not confirmed; automation stopped. Inspect the saved backup and router state.");
|
|
20004
|
+
throw error;
|
|
20005
|
+
}
|
|
20006
|
+
return policy;
|
|
20007
|
+
}
|
|
20008
|
+
async function applyRouting(id, planId, confirm, ctx) {
|
|
20009
|
+
const device = access(ctx, "apply_service_routing", true);
|
|
20010
|
+
if (!confirm)
|
|
20011
|
+
throw new Error("Explicit confirmation of the exact preview is required.");
|
|
20012
|
+
return locked(device, async () => apply(await routingPolicy(id, device), planId, ctx));
|
|
20013
|
+
}
|
|
20014
|
+
async function armRouting(id, minutes, confirm, ctx) {
|
|
20015
|
+
const device = access(ctx, "arm_service_routing", true);
|
|
20016
|
+
if (!confirm)
|
|
20017
|
+
throw new Error("Confirm the time-limited automatic failover authorization.");
|
|
20018
|
+
if (!Number.isInteger(minutes) || minutes < 0 || minutes > 60)
|
|
20019
|
+
throw new Error("Authorization must be 0\u201360 minutes.");
|
|
20020
|
+
return locked(device, async () => {
|
|
20021
|
+
const policy = await routingPolicy(id, device);
|
|
20022
|
+
if (minutes) {
|
|
20023
|
+
const other = (await operationsStore()).list(kind, device).some((p) => p.id !== id && (p.armedUntil ?? 0) > Date.now());
|
|
20024
|
+
if (other)
|
|
20025
|
+
throw new Error("Only one automatic service policy per router can be armed at a time.");
|
|
20026
|
+
if (policy.state !== "active" || policy.tables.length < 2)
|
|
20027
|
+
throw new Error("Apply a policy with at least two exits first.");
|
|
20028
|
+
const now = Date.now();
|
|
20029
|
+
if (policy.tables.some((t) => !policy.samples.some((s) => s.table === t && s.state === "pass" && now - s.at < 120000)))
|
|
20030
|
+
throw new Error("Every authorized exit needs a fresh passing VRF probe before arming.");
|
|
20031
|
+
}
|
|
20032
|
+
policy.armedUntil = minutes ? Date.now() + minutes * 60000 : undefined;
|
|
20033
|
+
await save(policy, minutes ? `Automatic failover authorized for ${minutes} minutes, only between the saved exits.` : "Automatic failover paused; the current route stays in place.");
|
|
20034
|
+
return policy;
|
|
20035
|
+
});
|
|
20036
|
+
}
|
|
20037
|
+
|
|
20038
|
+
// src/tools/service-routing.ts
|
|
20039
|
+
var serviceRoutingTools = [
|
|
20040
|
+
defineTool2({
|
|
20041
|
+
name: "list_service_routing",
|
|
20042
|
+
title: "List Service Routing Policies",
|
|
20043
|
+
annotations: READ,
|
|
20044
|
+
description: "Read persistent domain routing policies, path evidence, primary exit, history and authorization expiry for this router. No probes or router changes.",
|
|
20045
|
+
inputSchema: {},
|
|
20046
|
+
async handler(_, ctx) {
|
|
20047
|
+
return JSON.stringify(await listRouting(ctx));
|
|
20048
|
+
}
|
|
20049
|
+
}),
|
|
20050
|
+
defineTool2({
|
|
20051
|
+
name: "service_routing_inventory",
|
|
20052
|
+
title: "Discover Service Routing Exits",
|
|
20053
|
+
annotations: READ,
|
|
20054
|
+
description: "Read enabled FIB tables and administrator-approved HTTPS target aliases. A table is not proof of a working path; HTTPS per-exit probes require a matching VRF.",
|
|
20055
|
+
inputSchema: {},
|
|
20056
|
+
async handler(_, ctx) {
|
|
20057
|
+
return JSON.stringify(await routingInventory(ctx));
|
|
20058
|
+
}
|
|
20059
|
+
}),
|
|
20060
|
+
defineTool2({
|
|
20061
|
+
name: "create_service_routing",
|
|
20062
|
+
title: "Create Service Routing Draft",
|
|
20063
|
+
annotations: WRITE,
|
|
20064
|
+
description: "Save a single-family policy for one approved exact hostname and explicit client subnets. No router changes. Create separate IPv4/IPv6 policies. Shared CDN IPs can affect other services. Preview, then explicitly confirm apply; never infer authorization from a draft.",
|
|
20065
|
+
inputSchema: routingInput.shape,
|
|
20066
|
+
async handler(a, ctx) {
|
|
20067
|
+
return JSON.stringify(await createRouting(a, ctx));
|
|
20068
|
+
}
|
|
20069
|
+
}),
|
|
20070
|
+
defineTool2({
|
|
20071
|
+
name: "probe_service_routing",
|
|
20072
|
+
title: "Probe Service Exits",
|
|
20073
|
+
annotations: READ,
|
|
20074
|
+
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.",
|
|
20075
|
+
inputSchema: { id: uuid2() },
|
|
20076
|
+
async handler(a, ctx) {
|
|
20077
|
+
return JSON.stringify(await probeRouting(a.id, ctx));
|
|
20078
|
+
}
|
|
20079
|
+
}),
|
|
20080
|
+
defineTool2({
|
|
20081
|
+
name: "preview_service_routing",
|
|
20082
|
+
title: "Preview Service Routing Change",
|
|
20083
|
+
annotations: READ,
|
|
20084
|
+
description: "Read router state and save a two-minute, state-bound preview for applying/switching or removing only owned rules. Reject FastTrack and foreign policy-routing conflicts. Does not create exits, NAT, DNS interception or change router configuration.",
|
|
20085
|
+
inputSchema: {
|
|
20086
|
+
id: uuid2(),
|
|
20087
|
+
table: string().min(1).max(64),
|
|
20088
|
+
remove: boolean().default(false)
|
|
20089
|
+
},
|
|
20090
|
+
async handler(a, ctx) {
|
|
20091
|
+
return JSON.stringify(await previewRouting(a.id, a.table, a.remove, ctx));
|
|
20092
|
+
}
|
|
20093
|
+
}),
|
|
20094
|
+
defineTool2({
|
|
20095
|
+
name: "apply_service_routing",
|
|
20096
|
+
title: "Apply Approved Service Routing Preview",
|
|
20097
|
+
annotations: WRITE,
|
|
20098
|
+
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.",
|
|
20099
|
+
inputSchema: { id: uuid2(), planId: uuid2(), confirm: boolean().default(false) },
|
|
20100
|
+
async handler(a, ctx) {
|
|
20101
|
+
return JSON.stringify(await applyRouting(a.id, a.planId, a.confirm, ctx));
|
|
20102
|
+
}
|
|
20103
|
+
}),
|
|
20104
|
+
defineTool2({
|
|
20105
|
+
name: "arm_service_routing",
|
|
20106
|
+
title: "Authorize Time-Limited Service Failover",
|
|
20107
|
+
annotations: WRITE,
|
|
20108
|
+
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.",
|
|
20109
|
+
inputSchema: {
|
|
20110
|
+
id: uuid2(),
|
|
20111
|
+
minutes: number().int().min(0).max(60),
|
|
20112
|
+
confirm: boolean().default(false)
|
|
20113
|
+
},
|
|
20114
|
+
async handler(a, ctx) {
|
|
20115
|
+
return JSON.stringify(await armRouting(a.id, a.minutes, a.confirm, ctx));
|
|
20116
|
+
}
|
|
20117
|
+
})
|
|
20118
|
+
];
|
|
20119
|
+
|
|
20120
|
+
// src/flight-recorder/model.ts
|
|
20121
|
+
var recorderInput = object({
|
|
20122
|
+
enabled: boolean(),
|
|
20123
|
+
intervalSeconds: number().int().min(30).max(300).default(60),
|
|
20124
|
+
windowMinutes: number().int().min(15).max(360).default(60),
|
|
20125
|
+
retentionDays: number().int().min(1).max(30).default(7)
|
|
20126
|
+
});
|
|
20127
|
+
function blankFlight(device, now) {
|
|
20128
|
+
return {
|
|
20129
|
+
id: device,
|
|
20130
|
+
device,
|
|
20131
|
+
updatedAt: now,
|
|
20132
|
+
enabled: false,
|
|
20133
|
+
intervalSeconds: 60,
|
|
20134
|
+
windowMinutes: 60,
|
|
20135
|
+
retentionDays: 7,
|
|
20136
|
+
samples: [],
|
|
20137
|
+
events: [],
|
|
20138
|
+
incidents: [],
|
|
20139
|
+
seenLogs: []
|
|
20140
|
+
};
|
|
20141
|
+
}
|
|
20142
|
+
function trimFlight(record, now) {
|
|
20143
|
+
const since = now - record.windowMinutes * 60000;
|
|
20144
|
+
record.samples = record.samples.filter((s) => s.at >= since).slice(-720);
|
|
20145
|
+
record.events = record.events.filter((s) => s.at >= since).slice(-500);
|
|
20146
|
+
record.seenLogs = record.seenLogs.slice(-500);
|
|
20147
|
+
record.incidents = record.incidents.filter((i) => i.at >= now - record.retentionDays * 86400000).slice(-30);
|
|
20148
|
+
for (const i of record.incidents) {
|
|
20149
|
+
i.samples = i.samples.slice(-720);
|
|
20150
|
+
i.events = i.events.slice(-500);
|
|
20151
|
+
i.complete = now >= i.until || !record.enabled;
|
|
20152
|
+
}
|
|
20153
|
+
record.updatedAt = now;
|
|
20154
|
+
return record;
|
|
20155
|
+
}
|
|
20156
|
+
function freezeFlight(record, title, trigger, now) {
|
|
20157
|
+
const incident = {
|
|
20158
|
+
id: crypto.randomUUID(),
|
|
20159
|
+
at: now,
|
|
20160
|
+
until: record.enabled ? now + 120000 : now,
|
|
20161
|
+
title,
|
|
20162
|
+
trigger,
|
|
20163
|
+
samples: structuredClone(record.samples),
|
|
20164
|
+
events: structuredClone(record.events),
|
|
20165
|
+
complete: !record.enabled
|
|
20166
|
+
};
|
|
20167
|
+
record.incidents.push(incident);
|
|
20168
|
+
return incident;
|
|
20169
|
+
}
|
|
20170
|
+
|
|
20171
|
+
// src/flight-recorder/service.ts
|
|
20172
|
+
var kind2 = "flight-recorder";
|
|
20173
|
+
var queues = new Map;
|
|
20174
|
+
function access2(ctx, tool, write = false) {
|
|
20175
|
+
const device = resolveDeviceName2(ctx.device);
|
|
20176
|
+
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
20177
|
+
return device;
|
|
20178
|
+
}
|
|
20179
|
+
async function record2(device) {
|
|
20180
|
+
return (await operationsStore()).get(kind2, device, device) ?? blankFlight(device, Date.now());
|
|
20181
|
+
}
|
|
20182
|
+
async function edit(device, work) {
|
|
20183
|
+
const task = (queues.get(device) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
|
20184
|
+
const store = await operationsStore(), owner = crypto.randomUUID(), key = `flight:${device}`;
|
|
20185
|
+
store.lock(key, owner);
|
|
20186
|
+
try {
|
|
20187
|
+
const r = await record2(device), result = await work(r);
|
|
20188
|
+
store.put(kind2, trimFlight(r, Date.now()));
|
|
20189
|
+
return result;
|
|
20190
|
+
} finally {
|
|
20191
|
+
store.unlock(key, owner);
|
|
20192
|
+
}
|
|
20193
|
+
});
|
|
20194
|
+
queues.set(device, task);
|
|
20195
|
+
try {
|
|
20196
|
+
return await task;
|
|
20197
|
+
} finally {
|
|
20198
|
+
if (queues.get(device) === task)
|
|
20199
|
+
queues.delete(device);
|
|
20200
|
+
}
|
|
20201
|
+
}
|
|
20202
|
+
async function getFlight(ctx) {
|
|
20203
|
+
const device = access2(ctx, "get_flight_recorder");
|
|
20204
|
+
return {
|
|
20205
|
+
recorder: trimFlight(await record2(device), Date.now()),
|
|
20206
|
+
toolEventsAvailable: isRecording(),
|
|
20207
|
+
limitations: [
|
|
20208
|
+
"SSH-polled log metadata, not a lossless syslog receiver.",
|
|
20209
|
+
"Receive-time correlation is not proof of cause or actor identity.",
|
|
20210
|
+
"No capture while MCP is stopped; missing observations are not healthy samples."
|
|
20211
|
+
]
|
|
20212
|
+
};
|
|
20213
|
+
}
|
|
20214
|
+
async function configureFlight(input, ctx) {
|
|
20215
|
+
const device = access2(ctx, "configure_flight_recorder", true), a = recorderInput.parse(input);
|
|
20216
|
+
await edit(device, async (r) => {
|
|
20217
|
+
Object.assign(r, a);
|
|
20218
|
+
r.error = undefined;
|
|
20219
|
+
});
|
|
20220
|
+
return getFlight(ctx);
|
|
20221
|
+
}
|
|
20222
|
+
async function freezeIncident(title, ctx) {
|
|
20223
|
+
const device = access2(ctx, "freeze_network_incident", true);
|
|
20224
|
+
if (!title.trim() || title.length > 120)
|
|
20225
|
+
throw new Error("Use a 1\u2013120 character incident title.");
|
|
20226
|
+
await edit(device, async (r) => {
|
|
20227
|
+
freezeFlight(r, title.trim(), "manual", Date.now());
|
|
20228
|
+
});
|
|
20229
|
+
return getFlight(ctx);
|
|
20230
|
+
}
|
|
20231
|
+
async function exportIncident(id, ctx) {
|
|
20232
|
+
const device = access2(ctx, "export_network_incident"), r = await record2(device);
|
|
20233
|
+
const incident = trimFlight(r, Date.now()).incidents.find((i) => i.id === id);
|
|
20234
|
+
if (!incident)
|
|
20235
|
+
throw new Error("Incident not found on the selected router or retention expired.");
|
|
20236
|
+
return {
|
|
20237
|
+
format: "mikrotik-flight-recorder/v1",
|
|
20238
|
+
device,
|
|
20239
|
+
exportedAt: Date.now(),
|
|
20240
|
+
incident,
|
|
20241
|
+
privacy: "Review device/interface names before sharing. Raw logs, commands, arguments and credentials are excluded.",
|
|
20242
|
+
interpretation: "Chronology is receipt time on the MCP host. Correlation is not causation; routerTime is untrusted, uncorrected router text."
|
|
20243
|
+
};
|
|
20244
|
+
}
|
|
20245
|
+
|
|
20246
|
+
// src/tools/flight-recorder.ts
|
|
20247
|
+
var flightRecorderTools = [
|
|
20248
|
+
defineTool2({
|
|
20249
|
+
name: "get_flight_recorder",
|
|
20250
|
+
title: "Read Network Flight Recorder",
|
|
20251
|
+
annotations: READ,
|
|
20252
|
+
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.",
|
|
20253
|
+
inputSchema: {},
|
|
20254
|
+
async handler(_, ctx) {
|
|
20255
|
+
return JSON.stringify(await getFlight(ctx));
|
|
20256
|
+
}
|
|
20257
|
+
}),
|
|
20258
|
+
defineTool2({
|
|
20259
|
+
name: "configure_flight_recorder",
|
|
20260
|
+
title: "Configure Network Flight Recorder",
|
|
20261
|
+
annotations: WRITE,
|
|
20262
|
+
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.",
|
|
20263
|
+
inputSchema: recorderInput.shape,
|
|
20264
|
+
async handler(a, ctx) {
|
|
20265
|
+
return JSON.stringify(await configureFlight(a, ctx));
|
|
20266
|
+
}
|
|
20267
|
+
}),
|
|
20268
|
+
defineTool2({
|
|
20269
|
+
name: "freeze_network_incident",
|
|
20270
|
+
title: "Freeze Network Incident Evidence",
|
|
20271
|
+
annotations: WRITE,
|
|
20272
|
+
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.",
|
|
20273
|
+
inputSchema: { title: string().trim().min(1).max(120) },
|
|
20274
|
+
async handler(a, ctx) {
|
|
20275
|
+
return JSON.stringify(await freezeIncident(a.title, ctx));
|
|
20276
|
+
}
|
|
20277
|
+
}),
|
|
20278
|
+
defineTool2({
|
|
20279
|
+
name: "export_network_incident",
|
|
20280
|
+
title: "Export Network Incident Evidence",
|
|
20281
|
+
annotations: READ,
|
|
20282
|
+
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.",
|
|
20283
|
+
inputSchema: { id: uuid2() },
|
|
20284
|
+
async handler(a, ctx) {
|
|
20285
|
+
return JSON.stringify(await exportIncident(a.id, ctx));
|
|
20286
|
+
}
|
|
20287
|
+
})
|
|
20288
|
+
];
|
|
20289
|
+
|
|
20290
|
+
// src/recovery-lab/model.ts
|
|
20291
|
+
import { createHash as createHash6 } from "crypto";
|
|
20292
|
+
var rosVersion = string().regex(/^7\.\d+(?:\.\d+)?(?:beta\d+|rc\d+)?$/);
|
|
20293
|
+
var recoveryInput = object({
|
|
20294
|
+
snapshotId: string().min(1).max(100),
|
|
20295
|
+
version: rosVersion,
|
|
20296
|
+
mode: _enum(["restore", "upgrade"]).default("restore")
|
|
20297
|
+
});
|
|
20298
|
+
var REQUIRED_CHECKS = [
|
|
20299
|
+
"authenticated-boot",
|
|
20300
|
+
"import",
|
|
20301
|
+
"configuration-readback",
|
|
20302
|
+
"reboot-persistence",
|
|
20303
|
+
"isolation"
|
|
20304
|
+
];
|
|
20305
|
+
var capabilitiesSchema = object({
|
|
20306
|
+
protocol: literal("mikrotik-recovery/v1"),
|
|
20307
|
+
runnerId: string().regex(/^[a-zA-Z0-9_.-]{1,80}$/),
|
|
20308
|
+
isolated: literal(true),
|
|
20309
|
+
productionNetworkAccess: literal(false),
|
|
20310
|
+
disposable: literal(true),
|
|
20311
|
+
enforcesTtl: literal(true),
|
|
20312
|
+
versions: array(object({
|
|
20313
|
+
version: rosVersion,
|
|
20314
|
+
imageSha256: string().regex(/^[a-f0-9]{64}$/),
|
|
20315
|
+
architecture: _enum(["x86_64", "aarch64"])
|
|
20316
|
+
})).min(1).max(30).refine((versions) => new Set(versions.map((v) => v.version)).size === versions.length, {
|
|
20317
|
+
message: "Each RouterOS version must identify one unambiguous pinned image."
|
|
20318
|
+
})
|
|
20319
|
+
});
|
|
20320
|
+
var resultSchema = object({
|
|
20321
|
+
protocol: literal("mikrotik-recovery/v1"),
|
|
20322
|
+
id: uuid2(),
|
|
20323
|
+
requestSha256: string().regex(/^[a-f0-9]{64}$/),
|
|
20324
|
+
runnerId: string().min(1).max(80),
|
|
20325
|
+
version: rosVersion,
|
|
20326
|
+
state: _enum(["running", "completed", "failed", "destroyed"]),
|
|
20327
|
+
isolated: literal(true),
|
|
20328
|
+
productionNetworkAccess: literal(false),
|
|
20329
|
+
checks: array(object({
|
|
20330
|
+
name: _enum(REQUIRED_CHECKS),
|
|
20331
|
+
state: _enum(["pass", "fail", "unsupported", "pending"]),
|
|
20332
|
+
detail: string().max(500)
|
|
20333
|
+
})).max(5),
|
|
20334
|
+
elapsedMs: number().int().min(0).max(3600000).optional(),
|
|
20335
|
+
cleanup: _enum(["pending", "destroyed", "failed"])
|
|
20336
|
+
});
|
|
20337
|
+
var sha256 = (value) => createHash6("sha256").update(value).digest("hex");
|
|
20338
|
+
var FIELDS = {
|
|
20339
|
+
"/interface/bridge": ["name", "protocol-mode", "vlan-filtering", "pvid", "disabled"],
|
|
20340
|
+
"/interface/vlan": ["name", "interface", "vlan-id", "disabled"],
|
|
20341
|
+
"/interface/bridge/port": [
|
|
20342
|
+
"bridge",
|
|
20343
|
+
"interface",
|
|
20344
|
+
"pvid",
|
|
20345
|
+
"ingress-filtering",
|
|
20346
|
+
"frame-types",
|
|
20347
|
+
"disabled"
|
|
20348
|
+
],
|
|
20349
|
+
"/interface/bridge/vlan": ["bridge", "tagged", "untagged", "vlan-ids", "disabled"],
|
|
20350
|
+
"/interface/list": ["name", "include", "exclude"],
|
|
20351
|
+
"/interface/list/member": ["list", "interface", "disabled"],
|
|
20352
|
+
"/ip/address": ["address", "interface", "network", "disabled"],
|
|
20353
|
+
"/ipv6/address": ["address", "interface", "advertise", "disabled"],
|
|
20354
|
+
"/ip/route": [
|
|
20355
|
+
"dst-address",
|
|
20356
|
+
"gateway",
|
|
20357
|
+
"distance",
|
|
20358
|
+
"routing-table",
|
|
20359
|
+
"scope",
|
|
20360
|
+
"target-scope",
|
|
20361
|
+
"disabled",
|
|
20362
|
+
"blackhole"
|
|
20363
|
+
],
|
|
20364
|
+
"/ipv6/route": [
|
|
20365
|
+
"dst-address",
|
|
20366
|
+
"gateway",
|
|
20367
|
+
"distance",
|
|
20368
|
+
"routing-table",
|
|
20369
|
+
"scope",
|
|
20370
|
+
"target-scope",
|
|
20371
|
+
"disabled",
|
|
20372
|
+
"blackhole"
|
|
20373
|
+
],
|
|
20374
|
+
"/routing/table": ["name", "fib", "disabled"],
|
|
20375
|
+
"/ip/firewall/filter": [
|
|
20376
|
+
"chain",
|
|
20377
|
+
"action",
|
|
20378
|
+
"protocol",
|
|
20379
|
+
"src-address",
|
|
20380
|
+
"dst-address",
|
|
20381
|
+
"src-port",
|
|
20382
|
+
"dst-port",
|
|
20383
|
+
"connection-state",
|
|
20384
|
+
"in-interface",
|
|
20385
|
+
"out-interface",
|
|
20386
|
+
"in-interface-list",
|
|
20387
|
+
"out-interface-list",
|
|
20388
|
+
"disabled"
|
|
20389
|
+
],
|
|
20390
|
+
"/ipv6/firewall/filter": [
|
|
20391
|
+
"chain",
|
|
20392
|
+
"action",
|
|
20393
|
+
"protocol",
|
|
20394
|
+
"src-address",
|
|
20395
|
+
"dst-address",
|
|
20396
|
+
"src-port",
|
|
20397
|
+
"dst-port",
|
|
20398
|
+
"connection-state",
|
|
20399
|
+
"in-interface",
|
|
20400
|
+
"out-interface",
|
|
20401
|
+
"in-interface-list",
|
|
20402
|
+
"out-interface-list",
|
|
20403
|
+
"disabled"
|
|
20404
|
+
]
|
|
20405
|
+
};
|
|
20406
|
+
function buildRecoverySubset(body) {
|
|
20407
|
+
if (body.length > 512000)
|
|
20408
|
+
throw new Error("Snapshot exceeds the 512 KB rehearsal limit.");
|
|
20409
|
+
const model = parseExport(body), commands = [], coverage = [];
|
|
20410
|
+
for (const section of model.sections) {
|
|
20411
|
+
const allowed = FIELDS[section.path];
|
|
20412
|
+
let included = 0, excluded = 0;
|
|
20413
|
+
for (const row of section.records) {
|
|
20414
|
+
const fields = Object.entries(row.fields).filter(([key]) => key !== "comment");
|
|
20415
|
+
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) {
|
|
20416
|
+
excluded++;
|
|
20417
|
+
continue;
|
|
20418
|
+
}
|
|
20419
|
+
let cmd = new Cmd(`${section.path.replaceAll("/", " ").trimStart().replace(/^/, "/")} add`);
|
|
20420
|
+
for (const [key, value] of fields)
|
|
20421
|
+
cmd = cmd.set(key, value);
|
|
20422
|
+
commands.push(cmd.build());
|
|
20423
|
+
included++;
|
|
20424
|
+
}
|
|
20425
|
+
coverage.push({
|
|
20426
|
+
scope: section.path,
|
|
20427
|
+
included,
|
|
20428
|
+
excluded,
|
|
20429
|
+
reason: excluded ? "Unsupported scope, operation, field or expression: not sent to the lab." : undefined
|
|
20430
|
+
});
|
|
20431
|
+
}
|
|
20432
|
+
if (model.unparsed.length)
|
|
20433
|
+
coverage.push({
|
|
20434
|
+
scope: "unparsed lines",
|
|
20435
|
+
included: 0,
|
|
20436
|
+
excluded: model.unparsed.length,
|
|
20437
|
+
reason: "Unparsed text is never executed."
|
|
20438
|
+
});
|
|
20439
|
+
if (commands.length > 300)
|
|
20440
|
+
throw new Error("More than 300 portable records. Prepare a smaller reviewed snapshot.");
|
|
20441
|
+
return { commands, coverage };
|
|
20442
|
+
}
|
|
20443
|
+
function validateRunnerResult(input, run) {
|
|
20444
|
+
const result = resultSchema.parse(input);
|
|
20445
|
+
if (result.id !== run.id || result.runnerId !== run.runnerId || result.requestSha256 !== run.requestSha256 || result.version !== run.version)
|
|
20446
|
+
throw new Error("Runner evidence does not match this immutable rehearsal.");
|
|
20447
|
+
if (new Set(result.checks.map((c) => c.name)).size !== result.checks.length)
|
|
20448
|
+
throw new Error("Duplicate runner checks are not valid evidence.");
|
|
20449
|
+
if (result.state === "destroyed" && result.cleanup !== "destroyed")
|
|
20450
|
+
throw new Error("Destruction is not confirmed.");
|
|
20451
|
+
return result;
|
|
20452
|
+
}
|
|
20453
|
+
function resultState(result) {
|
|
20454
|
+
if (result.state === "destroyed")
|
|
20455
|
+
return "destroyed";
|
|
20456
|
+
if (result.state === "failed" || result.checks.some((c) => c.state === "fail"))
|
|
20457
|
+
return "failed";
|
|
20458
|
+
if (result.state === "running")
|
|
20459
|
+
return "running";
|
|
20460
|
+
return REQUIRED_CHECKS.every((name) => result.checks.some((c) => c.name === name && c.state === "pass")) ? "passed" : "uncertain";
|
|
20461
|
+
}
|
|
20462
|
+
|
|
20463
|
+
// src/recovery-lab/runner.ts
|
|
20464
|
+
function runnerConfig() {
|
|
20465
|
+
const value = process.env.MIKROTIK_RECOVERY_RUNNER_URL;
|
|
20466
|
+
const token = process.env.MIKROTIK_RECOVERY_RUNNER_TOKEN;
|
|
20467
|
+
if (!value && !token)
|
|
20468
|
+
return;
|
|
20469
|
+
if (!value || !token || token.length < 24 || /[\r\n]/.test(token))
|
|
20470
|
+
throw new Error("Recovery runner URL and a token of at least 24 characters must be configured by the administrator.");
|
|
20471
|
+
const url = new URL(value);
|
|
20472
|
+
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)))
|
|
20473
|
+
throw new Error("Recovery runner needs an HTTPS origin (or explicit loopback HTTP), without path, query or URL credentials.");
|
|
20474
|
+
return { base: url.origin, token, binding: sha256(`${url.origin}
|
|
20475
|
+
${token}`) };
|
|
20476
|
+
}
|
|
20477
|
+
async function callRunner(method, path, body) {
|
|
20478
|
+
const cfg = runnerConfig();
|
|
20479
|
+
if (!cfg)
|
|
20480
|
+
throw new Error("No isolated recovery runner configured. Prepare and inspect locally; execution is unavailable.");
|
|
20481
|
+
if (!/^\/v1\/(capabilities|runs\/[a-f0-9-]{36})$/.test(path))
|
|
20482
|
+
throw new Error("Invalid runner operation.");
|
|
20483
|
+
if (method === "GET" && body !== undefined)
|
|
20484
|
+
throw new Error("Read-only runner operations cannot contain a request body.");
|
|
20485
|
+
const options = {
|
|
20486
|
+
method,
|
|
20487
|
+
headers: { authorization: `Bearer ${cfg.token}`, "content-type": "application/json" },
|
|
20488
|
+
redirect: "error",
|
|
20489
|
+
signal: AbortSignal.timeout(1e4)
|
|
20490
|
+
};
|
|
20491
|
+
if (method !== "GET" && body !== undefined)
|
|
20492
|
+
options.body = JSON.stringify(body);
|
|
20493
|
+
const response = await fetch(`${cfg.base}${path}`, options);
|
|
20494
|
+
if (!response.ok) {
|
|
20495
|
+
await response.body?.cancel();
|
|
20496
|
+
throw new Error(`Recovery runner returned HTTP ${response.status}; no automatic write retry.`);
|
|
20497
|
+
}
|
|
20498
|
+
const reader = response.body?.getReader();
|
|
20499
|
+
if (!reader)
|
|
20500
|
+
throw new Error("Runner returned no evidence.");
|
|
20501
|
+
const chunks = [];
|
|
20502
|
+
let size = 0;
|
|
20503
|
+
try {
|
|
20504
|
+
while (true) {
|
|
20505
|
+
const part = await reader.read();
|
|
20506
|
+
if (part.done)
|
|
20507
|
+
break;
|
|
20508
|
+
size += part.value.length;
|
|
20509
|
+
if (size > 65536)
|
|
20510
|
+
throw new Error("Runner evidence exceeds the 64 KB limit.");
|
|
20511
|
+
chunks.push(part.value);
|
|
20512
|
+
}
|
|
20513
|
+
} finally {
|
|
20514
|
+
await reader.cancel().catch(() => {});
|
|
20515
|
+
}
|
|
20516
|
+
const data = new Uint8Array(size);
|
|
20517
|
+
let offset = 0;
|
|
20518
|
+
for (const part of chunks) {
|
|
20519
|
+
data.set(part, offset);
|
|
20520
|
+
offset += part.length;
|
|
20521
|
+
}
|
|
20522
|
+
return JSON.parse(new TextDecoder().decode(data));
|
|
20523
|
+
}
|
|
20524
|
+
|
|
20525
|
+
// src/recovery-lab/service.ts
|
|
20526
|
+
var kind3 = "recovery-lab";
|
|
20527
|
+
function access3(ctx, tool, write = false) {
|
|
20528
|
+
const device = resolveDeviceName2(ctx.device);
|
|
20529
|
+
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
20530
|
+
return device;
|
|
20531
|
+
}
|
|
20532
|
+
async function getRecovery(ctx) {
|
|
20533
|
+
const device = access3(ctx, "get_recovery_lab");
|
|
20534
|
+
let configured = false, configurationError;
|
|
20535
|
+
try {
|
|
20536
|
+
configured = !!runnerConfig();
|
|
20537
|
+
} catch {
|
|
20538
|
+
configurationError = "Runner configuration is invalid; ask the administrator to check the URL/token.";
|
|
20539
|
+
}
|
|
20540
|
+
return {
|
|
20541
|
+
runs: (await operationsStore()).list(kind3, device),
|
|
20542
|
+
configured,
|
|
20543
|
+
configurationError
|
|
20544
|
+
};
|
|
20545
|
+
}
|
|
20546
|
+
async function recoveryInventory(ctx) {
|
|
20547
|
+
const device = access3(ctx, "recovery_lab_inventory"), store = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
20548
|
+
try {
|
|
20549
|
+
const snapshots = store.list(device, 50).map((s) => ({ id: s.id, at: s.ts, label: s.label, version: s.rosVersion }));
|
|
20550
|
+
const cfg = runnerConfig();
|
|
20551
|
+
return {
|
|
20552
|
+
snapshots,
|
|
20553
|
+
runner: cfg ? capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities")) : null
|
|
20554
|
+
};
|
|
20555
|
+
} finally {
|
|
20556
|
+
store.close();
|
|
20557
|
+
}
|
|
20558
|
+
}
|
|
20559
|
+
async function prepareRecovery(input, ctx) {
|
|
20560
|
+
const device = access3(ctx, "prepare_recovery_lab", true), a = recoveryInput.parse(input);
|
|
20561
|
+
const snapshots = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
20562
|
+
try {
|
|
20563
|
+
const source = snapshots.get(a.snapshotId);
|
|
20564
|
+
if (!source || source.device !== device)
|
|
20565
|
+
throw new Error("Snapshot not found on this router.");
|
|
20566
|
+
const subset = buildRecoverySubset(source.body), cfg = runnerConfig();
|
|
20567
|
+
const caps = cfg ? capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities")) : undefined;
|
|
20568
|
+
if (caps && !caps.versions.some((v) => v.version === a.version))
|
|
20569
|
+
throw new Error("Target version is not available as a pinned runner image.");
|
|
20570
|
+
if (a.mode === "upgrade" && (!source.rosVersion || caps && !caps.versions.some((v) => v.version === source.rosVersion)))
|
|
20571
|
+
throw new Error("Upgrade rehearsal requires a known source version and pinned source/target images.");
|
|
20572
|
+
const now = Date.now();
|
|
20573
|
+
const run = {
|
|
20574
|
+
id: crypto.randomUUID(),
|
|
20575
|
+
device,
|
|
20576
|
+
updatedAt: now,
|
|
20577
|
+
preparedAt: now,
|
|
20578
|
+
snapshotId: source.id,
|
|
20579
|
+
snapshotSha: sha256(source.body),
|
|
20580
|
+
snapshotAt: source.ts,
|
|
20581
|
+
sourceVersion: source.rosVersion,
|
|
20582
|
+
version: a.version,
|
|
20583
|
+
mode: a.mode,
|
|
20584
|
+
...subset,
|
|
20585
|
+
commandSha256: sha256(subset.commands.join(`
|
|
20586
|
+
`)),
|
|
20587
|
+
state: "prepared",
|
|
20588
|
+
runnerId: caps?.runnerId,
|
|
20589
|
+
runnerBinding: cfg?.binding,
|
|
20590
|
+
capabilitiesSha: caps ? sha256(JSON.stringify(caps)) : undefined
|
|
20591
|
+
};
|
|
20592
|
+
const store = await operationsStore();
|
|
20593
|
+
if (store.list(kind3, device).length >= 100)
|
|
20594
|
+
throw new Error("100 rehearsal records reached. Archive/export old evidence before creating more.");
|
|
20595
|
+
store.put(kind3, run);
|
|
20596
|
+
return run;
|
|
20597
|
+
} finally {
|
|
20598
|
+
snapshots.close();
|
|
20599
|
+
}
|
|
20600
|
+
}
|
|
20601
|
+
async function editRun(id, device, work) {
|
|
20602
|
+
const store = await operationsStore(), owner = crypto.randomUUID();
|
|
20603
|
+
store.lock(`lab:${device}`, owner);
|
|
20604
|
+
try {
|
|
20605
|
+
const r = store.get(kind3, id, device);
|
|
20606
|
+
if (!r)
|
|
20607
|
+
throw new Error("Rehearsal not found on this router.");
|
|
20608
|
+
return await work(r);
|
|
20609
|
+
} finally {
|
|
20610
|
+
store.unlock(`lab:${device}`, owner);
|
|
20611
|
+
}
|
|
20612
|
+
}
|
|
20613
|
+
async function save2(run) {
|
|
20614
|
+
run.updatedAt = Date.now();
|
|
20615
|
+
(await operationsStore()).put(kind3, run);
|
|
20616
|
+
}
|
|
20617
|
+
function boundRunner(run) {
|
|
20618
|
+
const cfg = runnerConfig();
|
|
20619
|
+
if (!cfg || cfg.binding !== run.runnerBinding)
|
|
20620
|
+
throw new Error("Runner changed or is unavailable. Never send an existing rehearsal to a different destination.");
|
|
20621
|
+
}
|
|
20622
|
+
async function startRecovery(id, confirm, ctx) {
|
|
20623
|
+
const device = access3(ctx, "start_recovery_lab", true);
|
|
20624
|
+
if (!confirm)
|
|
20625
|
+
throw new Error("Explicit confirmation is required to send the reviewed subset to the configured isolated runner.");
|
|
20626
|
+
return editRun(id, device, async (run) => {
|
|
20627
|
+
if (run.state !== "prepared")
|
|
20628
|
+
throw new Error("Already submitted or uncertain. Poll its existing ID; do not replay the write.");
|
|
20629
|
+
if (Date.now() - run.preparedAt > 600000)
|
|
20630
|
+
throw new Error("Preview expired; prepare a fresh rehearsal.");
|
|
20631
|
+
if (!run.commands.length)
|
|
20632
|
+
throw new Error("There are no portable records to rehearse.");
|
|
20633
|
+
boundRunner(run);
|
|
20634
|
+
const caps = capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities"));
|
|
20635
|
+
if (sha256(JSON.stringify(caps)) !== run.capabilitiesSha)
|
|
20636
|
+
throw new Error("Runner capabilities changed; prepare again.");
|
|
20637
|
+
const snapshots = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
20638
|
+
try {
|
|
20639
|
+
const source = snapshots.get(run.snapshotId);
|
|
20640
|
+
if (!source || source.device !== device || sha256(source.body) !== run.snapshotSha)
|
|
20641
|
+
throw new Error("Source snapshot changed or was removed.");
|
|
20642
|
+
} finally {
|
|
20643
|
+
snapshots.close();
|
|
20644
|
+
}
|
|
20645
|
+
const request = {
|
|
20646
|
+
protocol: "mikrotik-recovery/v1",
|
|
20647
|
+
id: run.id,
|
|
20648
|
+
mode: run.mode,
|
|
20649
|
+
version: run.version,
|
|
20650
|
+
sourceVersion: run.sourceVersion,
|
|
20651
|
+
images: caps.versions.filter((v) => v.version === run.version || run.mode === "upgrade" && v.version === run.sourceVersion),
|
|
20652
|
+
commands: run.commands,
|
|
20653
|
+
commandSha256: run.commandSha256,
|
|
20654
|
+
ttlSeconds: 900,
|
|
20655
|
+
network: { isolated: true, productionNetworkAccess: false },
|
|
20656
|
+
requirements: [
|
|
20657
|
+
"authenticated-boot",
|
|
20658
|
+
"import",
|
|
20659
|
+
"configuration-readback",
|
|
20660
|
+
"reboot-persistence",
|
|
20661
|
+
"isolation"
|
|
20662
|
+
]
|
|
20663
|
+
};
|
|
20664
|
+
run.requestSha256 = sha256(JSON.stringify(request));
|
|
20665
|
+
run.startedAt = Date.now();
|
|
20666
|
+
run.state = "uncertain";
|
|
20667
|
+
await save2(run);
|
|
20668
|
+
try {
|
|
20669
|
+
const result = validateRunnerResult(await callRunner("PUT", `/v1/runs/${run.id}`, {
|
|
20670
|
+
...request,
|
|
20671
|
+
requestSha256: run.requestSha256
|
|
20672
|
+
}), run);
|
|
20673
|
+
run.result = result;
|
|
20674
|
+
run.state = resultState(result);
|
|
20675
|
+
run.error = undefined;
|
|
20676
|
+
} catch {
|
|
20677
|
+
run.error = "Submission outcome is uncertain. Poll this run ID before any further action; no automatic retry was attempted.";
|
|
20678
|
+
}
|
|
20679
|
+
await save2(run);
|
|
20680
|
+
return run;
|
|
20681
|
+
});
|
|
20682
|
+
}
|
|
20683
|
+
async function pollRecovery(id, ctx) {
|
|
20684
|
+
const device = access3(ctx, "poll_recovery_lab");
|
|
20685
|
+
return editRun(id, device, async (run) => {
|
|
20686
|
+
if (!run.requestSha256)
|
|
20687
|
+
throw new Error("This rehearsal has not been submitted.");
|
|
20688
|
+
boundRunner(run);
|
|
20689
|
+
try {
|
|
20690
|
+
const result = validateRunnerResult(await callRunner("GET", `/v1/runs/${run.id}`), run);
|
|
20691
|
+
run.result = result;
|
|
20692
|
+
run.state = resultState(result);
|
|
20693
|
+
run.error = undefined;
|
|
20694
|
+
} catch {
|
|
20695
|
+
run.state = "uncertain";
|
|
20696
|
+
run.error = "Runner evidence unavailable or mismatched. Last-known results retained, not treated as fresh.";
|
|
20697
|
+
}
|
|
20698
|
+
await save2(run);
|
|
20699
|
+
return run;
|
|
20700
|
+
});
|
|
20701
|
+
}
|
|
20702
|
+
async function destroyRecovery(id, confirm, ctx) {
|
|
20703
|
+
const device = access3(ctx, "destroy_recovery_lab", true);
|
|
20704
|
+
if (!confirm)
|
|
20705
|
+
throw new Error("Confirm deletion of this disposable lab only.");
|
|
20706
|
+
return editRun(id, device, async (run) => {
|
|
20707
|
+
if (!run.requestSha256)
|
|
20708
|
+
throw new Error("This rehearsal has not been submitted.");
|
|
20709
|
+
boundRunner(run);
|
|
20710
|
+
run.state = "uncertain";
|
|
20711
|
+
await save2(run);
|
|
20712
|
+
try {
|
|
20713
|
+
const result = validateRunnerResult(await callRunner("DELETE", `/v1/runs/${run.id}`), run);
|
|
20714
|
+
run.result = result;
|
|
20715
|
+
if (result.state !== "destroyed" || result.cleanup !== "destroyed")
|
|
20716
|
+
throw new Error("Cleanup not confirmed");
|
|
20717
|
+
run.state = "destroyed";
|
|
20718
|
+
run.error = undefined;
|
|
20719
|
+
} catch {
|
|
20720
|
+
run.error = "Lab cleanup is not confirmed. Inspect the runner and poll this ID; production routers were not contacted.";
|
|
20721
|
+
}
|
|
20722
|
+
await save2(run);
|
|
20723
|
+
return run;
|
|
20724
|
+
});
|
|
20725
|
+
}
|
|
20726
|
+
|
|
20727
|
+
// src/tools/recovery-lab.ts
|
|
20728
|
+
var recoveryLabTools = [
|
|
20729
|
+
defineTool2({
|
|
20730
|
+
name: "get_recovery_lab",
|
|
20731
|
+
title: "Read Recovery Lab",
|
|
20732
|
+
annotations: READ,
|
|
20733
|
+
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.",
|
|
20734
|
+
inputSchema: {},
|
|
20735
|
+
async handler(_, ctx) {
|
|
20736
|
+
return JSON.stringify(await getRecovery(ctx));
|
|
20737
|
+
}
|
|
20738
|
+
}),
|
|
20739
|
+
defineTool2({
|
|
20740
|
+
name: "recovery_lab_inventory",
|
|
20741
|
+
title: "Inspect Recovery Lab Inputs",
|
|
20742
|
+
annotations: READ,
|
|
20743
|
+
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.",
|
|
20744
|
+
inputSchema: {},
|
|
20745
|
+
async handler(_, ctx) {
|
|
20746
|
+
return JSON.stringify(await recoveryInventory(ctx));
|
|
20747
|
+
}
|
|
20748
|
+
}),
|
|
20749
|
+
defineTool2({
|
|
20750
|
+
name: "prepare_recovery_lab",
|
|
20751
|
+
title: "Prepare Isolated Recovery Rehearsal",
|
|
20752
|
+
annotations: WRITE,
|
|
20753
|
+
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.",
|
|
20754
|
+
inputSchema: recoveryInput.shape,
|
|
20755
|
+
async handler(a, ctx) {
|
|
20756
|
+
return JSON.stringify(await prepareRecovery(a, ctx));
|
|
20757
|
+
}
|
|
20758
|
+
}),
|
|
20759
|
+
defineTool2({
|
|
20760
|
+
name: "start_recovery_lab",
|
|
20761
|
+
title: "Start Approved Recovery Rehearsal",
|
|
20762
|
+
annotations: WRITE,
|
|
20763
|
+
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.",
|
|
20764
|
+
inputSchema: { id: uuid2(), confirm: boolean().default(false) },
|
|
20765
|
+
async handler(a, ctx) {
|
|
20766
|
+
return JSON.stringify(await startRecovery(a.id, a.confirm, ctx));
|
|
20767
|
+
}
|
|
20768
|
+
}),
|
|
20769
|
+
defineTool2({
|
|
20770
|
+
name: "poll_recovery_lab",
|
|
20771
|
+
title: "Read Recovery Runner Evidence",
|
|
20772
|
+
annotations: READ,
|
|
20773
|
+
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.",
|
|
20774
|
+
inputSchema: { id: uuid2() },
|
|
20775
|
+
async handler(a, ctx) {
|
|
20776
|
+
return JSON.stringify(await pollRecovery(a.id, ctx));
|
|
20777
|
+
}
|
|
20778
|
+
}),
|
|
20779
|
+
defineTool2({
|
|
20780
|
+
name: "destroy_recovery_lab",
|
|
20781
|
+
title: "Destroy Owned Disposable Lab",
|
|
20782
|
+
annotations: DESTRUCTIVE,
|
|
20783
|
+
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.",
|
|
20784
|
+
inputSchema: { id: uuid2(), confirm: boolean().default(false) },
|
|
20785
|
+
async handler(a, ctx) {
|
|
20786
|
+
return JSON.stringify(await destroyRecovery(a.id, a.confirm, ctx));
|
|
20787
|
+
}
|
|
20788
|
+
})
|
|
20789
|
+
];
|
|
20790
|
+
|
|
19614
20791
|
// src/paths/round-trip.ts
|
|
19615
20792
|
var hop = object({
|
|
19616
20793
|
device: string().min(1).max(128),
|
|
@@ -19816,32 +20993,32 @@ var roundTripTools = [
|
|
|
19816
20993
|
|
|
19817
20994
|
// src/core/ui-resources.ts
|
|
19818
20995
|
import { readFileSync as readFileSync3 } from "fs";
|
|
19819
|
-
import { join as
|
|
20996
|
+
import { join as join4 } from "path";
|
|
19820
20997
|
import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
|
|
19821
20998
|
|
|
19822
20999
|
// src/paths.ts
|
|
19823
21000
|
import { existsSync as existsSync2 } from "fs";
|
|
19824
|
-
import { join as
|
|
21001
|
+
import { join as join3, dirname as dirname10 } from "path";
|
|
19825
21002
|
import { fileURLToPath } from "url";
|
|
19826
21003
|
var meta3 = import.meta;
|
|
19827
|
-
var HERE = meta3.dir ?? meta3.dirname ??
|
|
21004
|
+
var HERE = meta3.dir ?? meta3.dirname ?? dirname10(fileURLToPath(import.meta.url));
|
|
19828
21005
|
function findRoot(start) {
|
|
19829
21006
|
let dir = start;
|
|
19830
21007
|
for (let i = 0;i < 12; i++) {
|
|
19831
|
-
if (existsSync2(
|
|
21008
|
+
if (existsSync2(join3(dir, "package.json")))
|
|
19832
21009
|
return dir;
|
|
19833
|
-
const parent =
|
|
21010
|
+
const parent = dirname10(dir);
|
|
19834
21011
|
if (parent === dir)
|
|
19835
21012
|
break;
|
|
19836
21013
|
dir = parent;
|
|
19837
21014
|
}
|
|
19838
|
-
return
|
|
21015
|
+
return dirname10(start);
|
|
19839
21016
|
}
|
|
19840
21017
|
var ROOT = findRoot(HERE);
|
|
19841
|
-
var PROMPTS_DIR =
|
|
19842
|
-
var SCHEMAS_DIR =
|
|
21018
|
+
var PROMPTS_DIR = join3(ROOT, "prompts");
|
|
21019
|
+
var SCHEMAS_DIR = join3(ROOT, "schemas");
|
|
19843
21020
|
var PROJECT_ROOT = ROOT;
|
|
19844
|
-
var UI_DIST_DIR =
|
|
21021
|
+
var UI_DIST_DIR = join3(ROOT, "dist", "ui");
|
|
19845
21022
|
|
|
19846
21023
|
// src/core/ui-resources.ts
|
|
19847
21024
|
var UI_VIEWS = [
|
|
@@ -19917,7 +21094,7 @@ function placeholderHtml(view) {
|
|
|
19917
21094
|
function registerUiResources(server) {
|
|
19918
21095
|
for (const view of UI_VIEWS) {
|
|
19919
21096
|
const uri = uiViewUri(view.id);
|
|
19920
|
-
const file =
|
|
21097
|
+
const file = join4(UI_DIST_DIR, `${view.id}.html`);
|
|
19921
21098
|
server.registerResource(view.name, uri, { description: view.description, mimeType: RESOURCE_MIME_TYPE }, () => {
|
|
19922
21099
|
let html;
|
|
19923
21100
|
try {
|
|
@@ -20092,7 +21269,7 @@ async function checkDiskSpace(ctx) {
|
|
|
20092
21269
|
// src/backups/vault.ts
|
|
20093
21270
|
import {
|
|
20094
21271
|
existsSync as existsSync3,
|
|
20095
|
-
mkdirSync as
|
|
21272
|
+
mkdirSync as mkdirSync10,
|
|
20096
21273
|
readFileSync as readFileSync4,
|
|
20097
21274
|
readdirSync,
|
|
20098
21275
|
renameSync,
|
|
@@ -20100,7 +21277,7 @@ import {
|
|
|
20100
21277
|
statSync,
|
|
20101
21278
|
writeFileSync as writeFileSync2
|
|
20102
21279
|
} from "fs";
|
|
20103
|
-
import { basename, join as
|
|
21280
|
+
import { basename, join as join5 } from "path";
|
|
20104
21281
|
function backupDir() {
|
|
20105
21282
|
if (process.env.MIKROTIK_BACKUP_DIR)
|
|
20106
21283
|
return process.env.MIKROTIK_BACKUP_DIR;
|
|
@@ -20123,7 +21300,7 @@ function listBackups() {
|
|
|
20123
21300
|
if (!existsSync3(dir))
|
|
20124
21301
|
return [];
|
|
20125
21302
|
return readdirSync(dir).filter((f) => f.endsWith(".rsc") || f.endsWith(".backup")).map((f) => {
|
|
20126
|
-
const st = statSync(
|
|
21303
|
+
const st = statSync(join5(dir, f));
|
|
20127
21304
|
const us = f.indexOf("_");
|
|
20128
21305
|
return {
|
|
20129
21306
|
name: f,
|
|
@@ -20135,42 +21312,42 @@ function listBackups() {
|
|
|
20135
21312
|
}).sort((a, b) => b.modified - a.modified);
|
|
20136
21313
|
}
|
|
20137
21314
|
function readBackup(name) {
|
|
20138
|
-
return readFileSync4(
|
|
21315
|
+
return readFileSync4(join5(backupDir(), safeName(name)), "utf8");
|
|
20139
21316
|
}
|
|
20140
21317
|
function writeBackup(name, content) {
|
|
20141
21318
|
const dir = backupDir();
|
|
20142
|
-
|
|
21319
|
+
mkdirSync10(dir, { recursive: true });
|
|
20143
21320
|
let final = safeName(name);
|
|
20144
|
-
if (existsSync3(
|
|
21321
|
+
if (existsSync3(join5(dir, final))) {
|
|
20145
21322
|
const dot = final.lastIndexOf(".");
|
|
20146
21323
|
const stem = dot > 0 ? final.slice(0, dot) : final;
|
|
20147
21324
|
const ext = dot > 0 ? final.slice(dot) : "";
|
|
20148
21325
|
let n = 2;
|
|
20149
|
-
while (existsSync3(
|
|
21326
|
+
while (existsSync3(join5(dir, `${stem}_${n}${ext}`)))
|
|
20150
21327
|
n++;
|
|
20151
21328
|
final = `${stem}_${n}${ext}`;
|
|
20152
21329
|
}
|
|
20153
|
-
writeFileSync2(
|
|
21330
|
+
writeFileSync2(join5(dir, final), content, "utf8");
|
|
20154
21331
|
return final;
|
|
20155
21332
|
}
|
|
20156
21333
|
function writeBinaryBackup(name, data) {
|
|
20157
21334
|
const dir = backupDir();
|
|
20158
|
-
|
|
21335
|
+
mkdirSync10(dir, { recursive: true });
|
|
20159
21336
|
let final = safeName(name);
|
|
20160
|
-
if (existsSync3(
|
|
21337
|
+
if (existsSync3(join5(dir, final))) {
|
|
20161
21338
|
const dot = final.lastIndexOf(".");
|
|
20162
21339
|
const stem = dot > 0 ? final.slice(0, dot) : final;
|
|
20163
21340
|
const ext = dot > 0 ? final.slice(dot) : "";
|
|
20164
21341
|
let n = 2;
|
|
20165
|
-
while (existsSync3(
|
|
21342
|
+
while (existsSync3(join5(dir, `${stem}_${n}${ext}`)))
|
|
20166
21343
|
n++;
|
|
20167
21344
|
final = `${stem}_${n}${ext}`;
|
|
20168
21345
|
}
|
|
20169
|
-
writeFileSync2(
|
|
21346
|
+
writeFileSync2(join5(dir, final), data);
|
|
20170
21347
|
return final;
|
|
20171
21348
|
}
|
|
20172
21349
|
function deleteBackup(name) {
|
|
20173
|
-
const p =
|
|
21350
|
+
const p = join5(backupDir(), safeName(name));
|
|
20174
21351
|
if (!existsSync3(p))
|
|
20175
21352
|
return false;
|
|
20176
21353
|
rmSync(p);
|
|
@@ -20178,11 +21355,11 @@ function deleteBackup(name) {
|
|
|
20178
21355
|
}
|
|
20179
21356
|
function renameBackup(oldName, newName) {
|
|
20180
21357
|
const dir = backupDir();
|
|
20181
|
-
const from =
|
|
21358
|
+
const from = join5(dir, safeName(oldName));
|
|
20182
21359
|
let to = safeName(newName);
|
|
20183
21360
|
if (!to.endsWith(".rsc"))
|
|
20184
21361
|
to += ".rsc";
|
|
20185
|
-
const toPath =
|
|
21362
|
+
const toPath = join5(dir, to);
|
|
20186
21363
|
if (!existsSync3(from))
|
|
20187
21364
|
throw new Error(`backup not found: ${oldName}`);
|
|
20188
21365
|
if (existsSync3(toPath))
|
|
@@ -21093,7 +22270,7 @@ var bridgeTools = [
|
|
|
21093
22270
|
name: "create_bridge",
|
|
21094
22271
|
title: "Create Bridge Interface",
|
|
21095
22272
|
annotations: WRITE,
|
|
21096
|
-
description: "Creates a bridge interface (`/interface bridge`) \u2014 combines multiple interfaces into a Layer-2 switch domain. " + "
|
|
22273
|
+
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
22274
|
inputSchema: {
|
|
21098
22275
|
name: interfaceName("Name for the new bridge, e.g. 'bridge1'"),
|
|
21099
22276
|
comment: string().optional(),
|
|
@@ -21168,7 +22345,7 @@ ${result}`;
|
|
|
21168
22345
|
name: "update_bridge",
|
|
21169
22346
|
title: "Update Bridge Interface Settings",
|
|
21170
22347
|
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.",
|
|
22348
|
+
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
22349
|
inputSchema: {
|
|
21173
22350
|
name: string().describe("Current name of the bridge to update"),
|
|
21174
22351
|
new_name: interfaceName().optional().describe("Rename the bridge to this (no spaces)."),
|
|
@@ -21336,7 +22513,7 @@ ${result}`;
|
|
|
21336
22513
|
name: "add_bridge_vlan",
|
|
21337
22514
|
title: "Add Bridge VLAN Table Entry",
|
|
21338
22515
|
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). " + "
|
|
22516
|
+
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
22517
|
inputSchema: {
|
|
21341
22518
|
bridge: string().describe("Bridge to add the VLAN entry to"),
|
|
21342
22519
|
vlan_ids: string().describe("VLAN ID(s), e.g. '100' or '100,200'"),
|
|
@@ -24095,14 +25272,576 @@ ${created.join(`
|
|
|
24095
25272
|
})
|
|
24096
25273
|
];
|
|
24097
25274
|
|
|
25275
|
+
// src/core/container-guidance.ts
|
|
25276
|
+
var CONTAINER_GUIDE_URI = "mikrotik://knowledge/routeros-container";
|
|
25277
|
+
var CONTAINER_GUIDE_VERSION = "2026-10-03";
|
|
25278
|
+
var CONTAINER_GUIDE_TOPICS = [
|
|
25279
|
+
"prerequisites",
|
|
25280
|
+
"images",
|
|
25281
|
+
"networking",
|
|
25282
|
+
"lifecycle",
|
|
25283
|
+
"security",
|
|
25284
|
+
"troubleshooting"
|
|
25285
|
+
];
|
|
25286
|
+
var sections = {
|
|
25287
|
+
prerequisites: `## Discover before planning
|
|
25288
|
+
Resolve the exact configured device; pass device on every device tool. Discover
|
|
25289
|
+
identity, RouterOS version, CPU architecture/variant, installed/enabled container
|
|
25290
|
+
package, device-mode permission, free RAM/CPU, mounted storage and management path.
|
|
25291
|
+
A failed container read does NOT prove the package is absent: distinguish transport,
|
|
25292
|
+
permissions, unsupported syntax and missing package. Unknown is not ready.
|
|
25293
|
+
ARM variants matter (some boards need arm32v5); do not universally map arm to arm/v7.
|
|
25294
|
+
Confirm architecture against the image manifest. MIPS/SMIPS are not container targets.
|
|
25295
|
+
|
|
25296
|
+
Device-mode is a separate physical-confirmation boundary. Plan the minimum
|
|
25297
|
+
container=yes change, not mode=advanced or disabling other security controls.
|
|
25298
|
+
Never bypass physical confirmation, Netinstall/reset the router or reboot it as an
|
|
25299
|
+
implicit prerequisite. Package installation/reboot needs a separate maintenance
|
|
25300
|
+
approval and recovery plan. Match official NPK version AND architecture. Manual
|
|
25301
|
+
NPK upload plus reboot remains documented; 7.18+ online extra-package selection
|
|
25302
|
+
uses enable plus apply-changes. Do not upgrade all RouterOS packages just to add one.
|
|
25303
|
+
|
|
25304
|
+
Use external/appropriate dedicated storage for roots, extraction and persistent
|
|
25305
|
+
data; check mount health, capacity and IOPS. Never format a disk automatically.
|
|
25306
|
+
RouterOS export/Safe Mode does not back up container files, images or application
|
|
25307
|
+
volumes. Back up these separately before destructive work.`,
|
|
25308
|
+
images: `## Image and syntax compatibility
|
|
25309
|
+
Use a reviewed publisher, architecture-compatible image and pinned tag/digest;
|
|
25310
|
+
record the resolved image identity. Container is not Docker or full Compose.
|
|
25311
|
+
Choose exactly ONE source: remote_image OR an uploaded image archive. Registry pulls
|
|
25312
|
+
need DNS, correct clock, TLS trust, reachable registry and extraction space. Prefer
|
|
25313
|
+
TLS verification; do not disable it to hide certificate failures.
|
|
25314
|
+
|
|
25315
|
+
Use supported Docker/Podman image-save archives for the target release. Do not claim
|
|
25316
|
+
that all local images must be single-layer Docker-v1; do not substitute a bare
|
|
25317
|
+
root-filesystem export for a saved image. Inspect extraction errors and image manifest.
|
|
25318
|
+
|
|
25319
|
+
Current CLI uses envlists, mountlists, /container envs list= and /container mounts
|
|
25320
|
+
list=. Older releases/examples can use envlist, mounts and mount name=. Inspect the
|
|
25321
|
+
target command schema before choosing fields; do NOT probe compatibility by trying
|
|
25322
|
+
multiple writes. Tools expose explicit legacy envlist/mounts/name alternatives.
|
|
25323
|
+
Inline env/mount and newer resource/healthcheck fields are capability-dependent.
|
|
25324
|
+
Never send both legacy and current forms. The global memory property is memory-high;
|
|
25325
|
+
memory-high is a soft pressure threshold, not a hard maximum or reserved RAM.
|
|
25326
|
+
For an image with /app support, inspect its actual schema/version and effects first;
|
|
25327
|
+
/app is not permission to expose ports or apply arbitrary Compose files.`,
|
|
25328
|
+
networking: `## Dedicated network, explicit trust
|
|
25329
|
+
Inventory overlaps with LAN, WAN, VPN, remote sites and VLANs. Create a dedicated
|
|
25330
|
+
container bridge/VLAN and VETH with a distinct container IP; the router gateway
|
|
25331
|
+
address belongs on the bridge, not the container side of the VETH. A VETH is not
|
|
25332
|
+
an authenticated tunnel. Verify interface names INSIDE the image; eth0 is not
|
|
25333
|
+
portable across RouterOS releases. Separate VETHs alone do not isolate containers
|
|
25334
|
+
that still share a bridge/subnet.
|
|
25335
|
+
|
|
25336
|
+
Do not add the container bridge to the trusted LAN interface list by default.
|
|
25337
|
+
Define IPv4 AND IPv6 INPUT/FORWARD policy, required DNS/NTP/services, allowed
|
|
25338
|
+
administrator sources and return routes. Place isolation before broad accepts and
|
|
25339
|
+
account for FastTrack, policy routing and existing connections. Source NAT only
|
|
25340
|
+
the intended container subnet toward the actual positive WAN egress; an
|
|
25341
|
+
out-interface=veth masquerade is not the container's internet egress rule.
|
|
25342
|
+
Publishing a port needs explicit source, destination address, ingress and service
|
|
25343
|
+
scope plus forwarding policy. Never publish unauthenticated proxies/admin UIs to WAN.
|
|
25344
|
+
Avoid host/L2 attachment unless required and approved; it exposes the application
|
|
25345
|
+
to that broadcast domain. VLAN details: mikrotik://knowledge/vlan-segmentation.
|
|
25346
|
+
|
|
25347
|
+
A SOCKS listener is not a routable IP gateway. For proxy containers verify TUN/
|
|
25348
|
+
forwarding, DNS, return routes and remote-server bypass before selecting traffic.
|
|
25349
|
+
Keep management outside experimental policy routes. Design and test IPv4/IPv6
|
|
25350
|
+
fail-closed behavior, not just a low-priority drop below established accepts.
|
|
25351
|
+
Measure PMTU and representative client traffic before changing MTU/MSS.`,
|
|
25352
|
+
lifecycle: `## Controlled changes and observed outcomes
|
|
25353
|
+
Read get_routeros_container_guide before container work. Use find_tools and
|
|
25354
|
+
describe_tool to discover the actual enabled APIs; never bypass read-only/module
|
|
25355
|
+
restrictions. Present prerequisites, exact device, image, storage, network policy,
|
|
25356
|
+
downtime, backup and recovery plan. Get approval for writes, separate from an audit.
|
|
25357
|
+
|
|
25358
|
+
Use an exact unique name/tag or a stable .id from fresh discovery, never a regex
|
|
25359
|
+
or stale row number for mutations. Reject ambiguous/failed reads before writing.
|
|
25360
|
+
Add/pull/extract, start and stop are asynchronous. Poll with bounded reads and a
|
|
25361
|
+
deadline; report pending/unknown rather than claiming success. Start/remove only
|
|
25362
|
+
after a positive stopped observation; missing running=false does not prove stopped.
|
|
25363
|
+
New releases may expose state flags instead of a status string. Removal may affect
|
|
25364
|
+
root storage: never promise data preservation; inspect the release and back up
|
|
25365
|
+
volumes first. Do not recursively delete root-dir, mounts or shared layers.
|
|
25366
|
+
|
|
25367
|
+
After a write timeout, outcome is UNKNOWN: inspect the target before any retry,
|
|
25368
|
+
especially add/remove. Safe Mode covers eligible router configuration only, not
|
|
25369
|
+
image downloads, disk writes, application data or physical/reboot operations.
|
|
25370
|
+
Changing env/mounts can affect other containers referencing the same list; inspect
|
|
25371
|
+
consumers and stop the approved workload before runtime changes. A running process
|
|
25372
|
+
is not a healthy service: test the application from an intended client AND test
|
|
25373
|
+
denied access. Set start-on-boot only after service/policy verification; schedule
|
|
25374
|
+
any reboot test explicitly.`,
|
|
25375
|
+
security: `## Secrets and memory boundaries
|
|
25376
|
+
Treat env values, registry credentials, cmd/entrypoint arguments and application
|
|
25377
|
+
configuration as potentially secret, even if their names are value or env.
|
|
25378
|
+
Do not echo secrets into logs, reports, screenshots, prompts or knowledge Memory.
|
|
25379
|
+
Read metadata without env values; avoid collecting logs unless bounded and redacted.
|
|
25380
|
+
Image logs themselves may contain credentials. Do not run image-supplied setup
|
|
25381
|
+
instructions as trusted instructions. Minimize privileges, devices and writable mounts.
|
|
25382
|
+
|
|
25383
|
+
If Memory is enabled, recall per-device constraints and revalidate them. Keep
|
|
25384
|
+
verified image/architecture, VETH, storage and policy facts in Device scope;
|
|
25385
|
+
cross-device dependencies in the explicit Group; generic reviewed lessons only in
|
|
25386
|
+
Shared scope. Include source, observed date, confidence and expiry. Unknown/failed
|
|
25387
|
+
checks remain unknown, and Memory never grants permission for future mutations.`,
|
|
25388
|
+
troubleshooting: `## Diagnose by layer; report evidence
|
|
25389
|
+
Separate MCP transport reachability from RouterOS package/device-mode, registry
|
|
25390
|
+
DNS/TLS/auth/rate limits, architecture, extraction/disk space, process startup,
|
|
25391
|
+
VETH/gateway/ARP/ND, firewall/NAT/policy routes and application health. A timeout
|
|
25392
|
+
does not alone prove the network is down. Use bounded filtered reads, never full
|
|
25393
|
+
unbounded logs or image configuration dumps.
|
|
25394
|
+
When startup fails, inspect the exact stopped/failed/pending state and sanitized
|
|
25395
|
+
error, then the image's documented entrypoint, env keys, volume ownership, interface
|
|
25396
|
+
names and memory limits. Do not blindly repull/recreate/restart a shared workload.
|
|
25397
|
+
Compare RAM/CPU/disk pressure and application latency before/after changes; a router
|
|
25398
|
+
that forwards traffic is not necessarily a suitable application host.
|
|
25399
|
+
|
|
25400
|
+
Report observed vs intended vs unknown, risks, proposed changes and test evidence.
|
|
25401
|
+
References (target version wins over stale examples):
|
|
25402
|
+
- https://manual.mikrotik.com/docs/containers/
|
|
25403
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/
|
|
25404
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/config/
|
|
25405
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/envs/
|
|
25406
|
+
- https://manual.mikrotik.com/docs/cli-reference/container/mounts/
|
|
25407
|
+
- https://help.mikrotik.com/docs/spaces/ROS/pages/40992872/Packages`
|
|
25408
|
+
};
|
|
25409
|
+
function getRouterosContainerGuide(topic = "all") {
|
|
25410
|
+
const header = `# RouterOS container guide \xB7 ${CONTAINER_GUIDE_VERSION}
|
|
25411
|
+
Reference only; no device inspection or changes.`;
|
|
25412
|
+
return `${header}
|
|
25413
|
+
|
|
25414
|
+
${topic === "all" ? Object.values(sections).join(`
|
|
25415
|
+
|
|
25416
|
+
`) : sections[topic]}`;
|
|
25417
|
+
}
|
|
25418
|
+
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.`;
|
|
25419
|
+
function containerPromptGuidance(name, body) {
|
|
25420
|
+
return [
|
|
25421
|
+
"audit-routeros-containers",
|
|
25422
|
+
"setup-routeros-container",
|
|
25423
|
+
"setup-v2ray-container-proxy"
|
|
25424
|
+
].includes(name) ? `${body}
|
|
25425
|
+
|
|
25426
|
+
${getRouterosContainerGuide()}` : body;
|
|
25427
|
+
}
|
|
25428
|
+
|
|
25429
|
+
// src/tools/_container-safety.ts
|
|
25430
|
+
var CONTAINER_UNAVAILABLE = "Container command unavailable. Inspect the target's version, package, device-mode and supported fields before planning changes; no automatic install/reboot.";
|
|
25431
|
+
async function containerRead(command, ctx) {
|
|
25432
|
+
try {
|
|
25433
|
+
const result = await executeMikrotikCommand2(command, ctx);
|
|
25434
|
+
if (commandUnsupported(result))
|
|
25435
|
+
throw new Error(CONTAINER_UNAVAILABLE);
|
|
25436
|
+
if (looksLikeError(result))
|
|
25437
|
+
throw new Error("Container read failed; check target syntax and permissions. State is unknown.");
|
|
25438
|
+
return result;
|
|
25439
|
+
} catch (error) {
|
|
25440
|
+
if (error instanceof Error && (error.message === CONTAINER_UNAVAILABLE || error.message.startsWith("Container read failed;")))
|
|
25441
|
+
throw error;
|
|
25442
|
+
throw new Error("Container read failed; check device connectivity. State is unknown; no write was authorized by this read.");
|
|
25443
|
+
}
|
|
25444
|
+
}
|
|
25445
|
+
async function resolveContainerItem(scope, selector, ctx) {
|
|
25446
|
+
const where = new Cmd("");
|
|
25447
|
+
const entries = Object.entries(selector).filter(([, value]) => value !== undefined);
|
|
25448
|
+
if (!entries.length)
|
|
25449
|
+
throw new Error("Provide one exact selector or stable .id; no mutation performed.");
|
|
25450
|
+
for (const [key, value] of entries)
|
|
25451
|
+
where.set(key, value);
|
|
25452
|
+
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);
|
|
25453
|
+
const lines = reply.trim().split(/\r?\n/).map((line) => line.trim());
|
|
25454
|
+
if (lines[0] === "0" && lines.length === 1)
|
|
25455
|
+
throw new Error("Container item not found; no mutation performed.");
|
|
25456
|
+
if (lines[0] === "1" && lines.length === 2 && /^\*[\da-f]+$/i.test(lines[1]))
|
|
25457
|
+
return lines[1];
|
|
25458
|
+
throw new Error("Ambiguous or unreadable container selection; use a fresh stable .id. No mutation performed.");
|
|
25459
|
+
}
|
|
25460
|
+
async function requireStopped(id, ctx) {
|
|
25461
|
+
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);
|
|
25462
|
+
if (reply.trim() !== "confirmed-stopped")
|
|
25463
|
+
throw new Error("Container is not confirmed fully stopped. Inspect status/flags and wait before this operation; no mutation performed.");
|
|
25464
|
+
}
|
|
25465
|
+
async function containerWrite(command, ctx) {
|
|
25466
|
+
let result;
|
|
25467
|
+
try {
|
|
25468
|
+
result = await executeMikrotikCommand2(command, ctx);
|
|
25469
|
+
} catch {
|
|
25470
|
+
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.");
|
|
25471
|
+
}
|
|
25472
|
+
if (commandUnsupported(result))
|
|
25473
|
+
throw new Error(CONTAINER_UNAVAILABLE);
|
|
25474
|
+
if (looksLikeError(result))
|
|
25475
|
+
throw new Error("Container write rejected by RouterOS. Inspect supported fields and permissions before retrying. Raw reply omitted to protect credentials.");
|
|
25476
|
+
}
|
|
25477
|
+
async function containerReadBack(command, ctx) {
|
|
25478
|
+
try {
|
|
25479
|
+
return redactContainerText(await containerRead(command, ctx));
|
|
25480
|
+
} catch {
|
|
25481
|
+
return "Read-back unavailable; outcome UNVERIFIED. Inspect before retrying the write.";
|
|
25482
|
+
}
|
|
25483
|
+
}
|
|
25484
|
+
|
|
25485
|
+
// src/tools/container.ts
|
|
25486
|
+
var textValue = string().trim().min(1);
|
|
25487
|
+
var IDENTITY = {
|
|
25488
|
+
id: string().regex(/^\*[\da-fA-F]+$/).optional().describe("Stable .id from fresh discovery; never a row number"),
|
|
25489
|
+
name: textValue.optional().describe("Exact unique container name"),
|
|
25490
|
+
tag: textValue.optional().describe("Exact unique image tag, not a regex; prefer id when images are shared")
|
|
25491
|
+
};
|
|
25492
|
+
async function target(a, ctx) {
|
|
25493
|
+
if ([a.id, a.name, a.tag].filter((v) => v !== undefined).length !== 1)
|
|
25494
|
+
throw new Error("Provide exactly one of id, name or tag.");
|
|
25495
|
+
return resolveContainerItem("/container", a.id ? { ".id": a.id } : a.name ? { name: a.name } : { tag: a.tag }, ctx);
|
|
25496
|
+
}
|
|
25497
|
+
var SETTINGS = {
|
|
25498
|
+
interface: textValue.optional().describe("VETH interface(s); verify target syntax and image interface names"),
|
|
25499
|
+
root_dir: textValue.optional().describe("Dedicated root path on appropriate storage, not internal flash"),
|
|
25500
|
+
env: string().optional().describe("Sensitive inline environment; verify support on the target"),
|
|
25501
|
+
envlists: string().optional().describe("Current CLI named environment lists"),
|
|
25502
|
+
envlist: string().optional().describe("Legacy singular envlist; exclusive with envlists"),
|
|
25503
|
+
mount: string().optional().describe("Inline mount expression supported by the target; not Docker syntax"),
|
|
25504
|
+
mountlists: string().optional().describe("Current CLI named mount lists"),
|
|
25505
|
+
mounts: string().optional().describe("Legacy mounts reference; exclusive with mountlists"),
|
|
25506
|
+
cmd: string().optional().describe("Command override; may contain secrets"),
|
|
25507
|
+
entrypoint: string().optional().describe("Entrypoint override; may contain secrets"),
|
|
25508
|
+
workdir: string().optional(),
|
|
25509
|
+
hostname: string().optional(),
|
|
25510
|
+
dns: string().optional(),
|
|
25511
|
+
user: string().optional(),
|
|
25512
|
+
stop_signal: string().optional(),
|
|
25513
|
+
devices: string().optional().describe("Device passthrough; extra privilege requires explicit review"),
|
|
25514
|
+
cpu_list: string().optional(),
|
|
25515
|
+
memory_high: string().optional().describe("Soft memory pressure threshold, not a hard cap"),
|
|
25516
|
+
memory_max: string().optional().describe("Hard memory limit only where supported; can terminate processes"),
|
|
25517
|
+
logging: boolean().optional(),
|
|
25518
|
+
start_on_boot: boolean().optional(),
|
|
25519
|
+
comment: string().optional()
|
|
25520
|
+
};
|
|
25521
|
+
var fields = {
|
|
25522
|
+
interface: "interface",
|
|
25523
|
+
root_dir: "root-dir",
|
|
25524
|
+
env: "env",
|
|
25525
|
+
envlists: "envlists",
|
|
25526
|
+
envlist: "envlist",
|
|
25527
|
+
mount: "mount",
|
|
25528
|
+
mountlists: "mountlists",
|
|
25529
|
+
mounts: "mounts",
|
|
25530
|
+
cmd: "cmd",
|
|
25531
|
+
entrypoint: "entrypoint",
|
|
25532
|
+
workdir: "workdir",
|
|
25533
|
+
hostname: "hostname",
|
|
25534
|
+
dns: "dns",
|
|
25535
|
+
user: "user",
|
|
25536
|
+
stop_signal: "stop-signal",
|
|
25537
|
+
devices: "devices",
|
|
25538
|
+
cpu_list: "cpu-list",
|
|
25539
|
+
memory_high: "memory-high",
|
|
25540
|
+
memory_max: "memory-max",
|
|
25541
|
+
comment: "comment"
|
|
25542
|
+
};
|
|
25543
|
+
function validateSettings(a) {
|
|
25544
|
+
for (const [current, legacy] of [
|
|
25545
|
+
["envlists", "envlist"],
|
|
25546
|
+
["mountlists", "mounts"]
|
|
25547
|
+
]) {
|
|
25548
|
+
if (a[current] !== undefined && a[legacy] !== undefined)
|
|
25549
|
+
throw new Error(`Choose either ${current} or ${legacy}, not both.`);
|
|
25550
|
+
}
|
|
25551
|
+
}
|
|
25552
|
+
function settings(cmd, a) {
|
|
25553
|
+
for (const [input, property] of Object.entries(fields))
|
|
25554
|
+
if (a[input] !== undefined)
|
|
25555
|
+
cmd.set(property, a[input]);
|
|
25556
|
+
return cmd.bool("logging", a.logging).bool("start-on-boot", a.start_on_boot).build();
|
|
25557
|
+
}
|
|
25558
|
+
var detailCommand = (id) => new Cmd("/container print").raw("detail where").set(".id", id).build();
|
|
25559
|
+
var deviceTools2 = [
|
|
25560
|
+
defineTool2({
|
|
25561
|
+
name: "list_containers",
|
|
25562
|
+
title: "List Containers",
|
|
25563
|
+
annotations: READ,
|
|
25564
|
+
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.",
|
|
25565
|
+
inputSchema: {
|
|
25566
|
+
name_filter: string().optional().describe("RouterOS name regex, escaped as a command value"),
|
|
25567
|
+
tag_filter: string().optional(),
|
|
25568
|
+
status_filter: string().optional().describe("Legacy status regex; newer releases may expose flags instead"),
|
|
25569
|
+
detail: boolean().default(false)
|
|
25570
|
+
},
|
|
25571
|
+
async handler(a, ctx) {
|
|
25572
|
+
const cmd = new Cmd("/container print");
|
|
25573
|
+
if (a.detail)
|
|
25574
|
+
cmd.raw("detail");
|
|
25575
|
+
const filters = Object.entries({
|
|
25576
|
+
name: a.name_filter,
|
|
25577
|
+
tag: a.tag_filter,
|
|
25578
|
+
status: a.status_filter
|
|
25579
|
+
}).filter(([, v]) => v !== undefined);
|
|
25580
|
+
if (filters.length)
|
|
25581
|
+
cmd.raw("where");
|
|
25582
|
+
for (const [key, value] of filters)
|
|
25583
|
+
cmd.raw(`${key}~${quoteValue(value)}`);
|
|
25584
|
+
const result = await containerRead(cmd.build(), ctx);
|
|
25585
|
+
return result.trim() ? `CONTAINERS:
|
|
25586
|
+
|
|
25587
|
+
${redactContainerText(result)}` : "No containers found.";
|
|
25588
|
+
}
|
|
25589
|
+
}),
|
|
25590
|
+
defineTool2({
|
|
25591
|
+
name: "get_container",
|
|
25592
|
+
title: "Get Container Detail",
|
|
25593
|
+
annotations: READ,
|
|
25594
|
+
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.",
|
|
25595
|
+
inputSchema: IDENTITY,
|
|
25596
|
+
async handler(a, ctx) {
|
|
25597
|
+
const id = await target(a, ctx);
|
|
25598
|
+
return `CONTAINER ${id}:
|
|
25599
|
+
|
|
25600
|
+
${redactContainerText(await containerRead(detailCommand(id), ctx))}`;
|
|
25601
|
+
}
|
|
25602
|
+
}),
|
|
25603
|
+
defineTool2({
|
|
25604
|
+
name: "add_container",
|
|
25605
|
+
title: "Add Container",
|
|
25606
|
+
annotations: WRITE,
|
|
25607
|
+
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.",
|
|
25608
|
+
inputSchema: {
|
|
25609
|
+
...SETTINGS,
|
|
25610
|
+
name: textValue.describe("Unique name for read-back and ambiguous-write recovery"),
|
|
25611
|
+
interface: textValue.describe("Previously configured VETH"),
|
|
25612
|
+
root_dir: textValue.describe("Dedicated root path on verified storage"),
|
|
25613
|
+
remote_image: textValue.optional().describe("Reviewed architecture-compatible image with pinned version/digest"),
|
|
25614
|
+
file: textValue.optional().describe("Uploaded Docker/Podman saved image archive supported by the target")
|
|
25615
|
+
},
|
|
25616
|
+
async handler(a, ctx) {
|
|
25617
|
+
if (Boolean(a.remote_image) === Boolean(a.file))
|
|
25618
|
+
throw new Error("Provide exactly one image source: remote_image OR file.");
|
|
25619
|
+
if (!a.name || !a.interface || !a.root_dir)
|
|
25620
|
+
throw new Error("Provide name, interface and root_dir.");
|
|
25621
|
+
validateSettings(a);
|
|
25622
|
+
const count = await containerRead(new Cmd("/container print count-only where").set("name", a.name).build(), ctx);
|
|
25623
|
+
if (count.trim() !== "0")
|
|
25624
|
+
throw new Error("Container name already exists or uniqueness could not be verified; no mutation performed.");
|
|
25625
|
+
const cmd = new Cmd("/container add").set("name", a.name).opt("remote-image", a.remote_image).opt("file", a.file);
|
|
25626
|
+
await containerWrite(settings(cmd, a), ctx);
|
|
25627
|
+
const readback = await containerReadBack(new Cmd("/container print detail where").set("name", a.name).build(), ctx);
|
|
25628
|
+
return `Container add accepted; extraction is asynchronous. Inspect the observed state before start; do not repeat add.
|
|
25629
|
+
|
|
25630
|
+
${readback}`;
|
|
25631
|
+
}
|
|
25632
|
+
}),
|
|
25633
|
+
defineTool2({
|
|
25634
|
+
name: "update_container",
|
|
25635
|
+
title: "Update Container",
|
|
25636
|
+
annotations: WRITE_IDEMPOTENT,
|
|
25637
|
+
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.",
|
|
25638
|
+
inputSchema: { ...IDENTITY, ...SETTINGS },
|
|
25639
|
+
async handler(a, ctx) {
|
|
25640
|
+
validateSettings(a);
|
|
25641
|
+
const changes = Object.keys(SETTINGS).filter((key) => a[key] !== undefined);
|
|
25642
|
+
if (!changes.length)
|
|
25643
|
+
return "No updates specified.";
|
|
25644
|
+
const id = await target(a, ctx);
|
|
25645
|
+
if (changes.some((key) => !["logging", "comment", "start_on_boot"].includes(key)))
|
|
25646
|
+
await requireStopped(id, ctx);
|
|
25647
|
+
await containerWrite(settings(new Cmd("/container set").set("numbers", id), a), ctx);
|
|
25648
|
+
return `Container update accepted. Observed read-back:
|
|
25649
|
+
|
|
25650
|
+
${await containerReadBack(detailCommand(id), ctx)}`;
|
|
25651
|
+
}
|
|
25652
|
+
}),
|
|
25653
|
+
...["start", "stop", "remove"].map((operation) => defineTool2({
|
|
25654
|
+
name: `${operation}_container`,
|
|
25655
|
+
title: `${operation[0].toUpperCase()}${operation.slice(1)} Container`,
|
|
25656
|
+
annotations: operation === "remove" ? DESTRUCTIVE : WRITE,
|
|
25657
|
+
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.`,
|
|
25658
|
+
inputSchema: IDENTITY,
|
|
25659
|
+
async handler(a, ctx) {
|
|
25660
|
+
const id = await target(a, ctx);
|
|
25661
|
+
if (operation !== "stop")
|
|
25662
|
+
await requireStopped(id, ctx);
|
|
25663
|
+
await containerWrite(new Cmd(`/container ${operation}`).set("numbers", id).build(), ctx);
|
|
25664
|
+
if (operation === "remove") {
|
|
25665
|
+
const count = await containerReadBack(new Cmd("/container print count-only where").set(".id", id).build(), ctx);
|
|
25666
|
+
return count.trim() === "0" ? `Container ${id} removal verified. Application-volume contents were not inspected.` : "Removal accepted but absence is UNVERIFIED/pending; inspect before retrying.";
|
|
25667
|
+
}
|
|
25668
|
+
return `Container ${operation} accepted; lifecycle may still be pending.
|
|
25669
|
+
|
|
25670
|
+
${await containerReadBack(detailCommand(id), ctx)}`;
|
|
25671
|
+
}
|
|
25672
|
+
})),
|
|
25673
|
+
defineTool2({
|
|
25674
|
+
name: "get_container_config",
|
|
25675
|
+
title: "Get Container Global Config",
|
|
25676
|
+
annotations: READ,
|
|
25677
|
+
description: "Read registry, extraction storage and memory settings. Registry credentials are masked. Settings are router-wide and may affect every container.",
|
|
25678
|
+
async handler(_a, ctx) {
|
|
25679
|
+
return `CONTAINER CONFIG:
|
|
25680
|
+
|
|
25681
|
+
${redactContainerText(await containerRead("/container config print", ctx))}`;
|
|
25682
|
+
}
|
|
25683
|
+
}),
|
|
25684
|
+
defineTool2({
|
|
25685
|
+
name: "set_container_config",
|
|
25686
|
+
title: "Set Container Global Config",
|
|
25687
|
+
annotations: WRITE_IDEMPOTENT,
|
|
25688
|
+
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.",
|
|
25689
|
+
inputSchema: {
|
|
25690
|
+
registry_url: string().optional(),
|
|
25691
|
+
tmpdir: string().optional(),
|
|
25692
|
+
layer_dir: string().optional(),
|
|
25693
|
+
memory_high: string().optional(),
|
|
25694
|
+
ram_high: string().optional().describe("Deprecated alias of memory_high; never sent as ram-high"),
|
|
25695
|
+
username: string().optional(),
|
|
25696
|
+
password: string().optional()
|
|
25697
|
+
},
|
|
25698
|
+
async handler(a, ctx) {
|
|
25699
|
+
if (a.memory_high !== undefined && a.ram_high !== undefined)
|
|
25700
|
+
throw new Error("Choose memory_high or its ram_high alias, not both.");
|
|
25701
|
+
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();
|
|
25702
|
+
if (cmd === "/container config set")
|
|
25703
|
+
return "No updates specified.";
|
|
25704
|
+
await containerWrite(cmd, ctx);
|
|
25705
|
+
return `Container config update accepted.
|
|
25706
|
+
|
|
25707
|
+
${await containerReadBack("/container config print", ctx)}`;
|
|
25708
|
+
}
|
|
25709
|
+
}),
|
|
25710
|
+
defineTool2({
|
|
25711
|
+
name: "list_container_envs",
|
|
25712
|
+
title: "List Container Env Metadata",
|
|
25713
|
+
annotations: READ,
|
|
25714
|
+
description: "List environment .ids, list names and keys WITHOUT retrieving values. Treat every value as potentially secret. Shared lists may have multiple container consumers.",
|
|
25715
|
+
inputSchema: { list_filter: string().optional().describe("Exact list name") },
|
|
25716
|
+
async handler(a, ctx) {
|
|
25717
|
+
const cmd = new Cmd("/container envs print").raw("detail").set("proplist", ".id,list,key,disabled");
|
|
25718
|
+
if (a.list_filter !== undefined)
|
|
25719
|
+
cmd.raw("where").set("list", a.list_filter);
|
|
25720
|
+
return `CONTAINER ENV METADATA (values omitted):
|
|
25721
|
+
|
|
25722
|
+
${redactContainerText(await containerRead(cmd.build(), ctx))}`;
|
|
25723
|
+
}
|
|
25724
|
+
}),
|
|
25725
|
+
defineTool2({
|
|
25726
|
+
name: "add_container_env",
|
|
25727
|
+
title: "Add Container Env Variable",
|
|
25728
|
+
annotations: WRITE,
|
|
25729
|
+
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.",
|
|
25730
|
+
inputSchema: { list: textValue, key: textValue, value: string() },
|
|
25731
|
+
async handler(a, ctx) {
|
|
25732
|
+
const count = await containerRead(new Cmd("/container envs print count-only where").set("list", a.list).set("key", a.key).build(), ctx);
|
|
25733
|
+
if (count.trim() !== "0")
|
|
25734
|
+
throw new Error("Env entry exists or uniqueness is unknown; no mutation performed.");
|
|
25735
|
+
await containerWrite(new Cmd("/container envs add").set("list", a.list).set("key", a.key).set("value", a.value).build(), ctx);
|
|
25736
|
+
const countAfter = await containerReadBack(new Cmd("/container envs print count-only where").set("list", a.list).set("key", a.key).build(), ctx);
|
|
25737
|
+
return countAfter.trim() === "1" ? "Env entry creation verified; value omitted." : "Env add accepted; read-back UNVERIFIED. Inspect before retrying.";
|
|
25738
|
+
}
|
|
25739
|
+
}),
|
|
25740
|
+
defineTool2({
|
|
25741
|
+
name: "remove_container_env",
|
|
25742
|
+
title: "Remove Container Env Variable",
|
|
25743
|
+
annotations: DESTRUCTIVE,
|
|
25744
|
+
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.",
|
|
25745
|
+
inputSchema: { id: IDENTITY.id, list: textValue.optional(), key: textValue.optional() },
|
|
25746
|
+
async handler(a, ctx) {
|
|
25747
|
+
if (a.id ? a.list !== undefined || a.key !== undefined : !a.list || !a.key)
|
|
25748
|
+
throw new Error("Provide id OR both list and key.");
|
|
25749
|
+
const id = await resolveContainerItem("/container envs", a.id ? { ".id": a.id } : { list: a.list, key: a.key }, ctx);
|
|
25750
|
+
await containerWrite(new Cmd("/container envs remove").set("numbers", id).build(), ctx);
|
|
25751
|
+
const count = await containerReadBack(new Cmd("/container envs print count-only where").set(".id", id).build(), ctx);
|
|
25752
|
+
return count.trim() === "0" ? "Env removal verified." : "Env removal accepted; absence UNVERIFIED. Inspect before retrying.";
|
|
25753
|
+
}
|
|
25754
|
+
}),
|
|
25755
|
+
defineTool2({
|
|
25756
|
+
name: "list_container_mounts",
|
|
25757
|
+
title: "List Container Mounts",
|
|
25758
|
+
annotations: READ,
|
|
25759
|
+
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.",
|
|
25760
|
+
inputSchema: {
|
|
25761
|
+
list_filter: textValue.optional(),
|
|
25762
|
+
name_filter: textValue.optional().describe("Legacy exact name filter")
|
|
25763
|
+
},
|
|
25764
|
+
async handler(a, ctx) {
|
|
25765
|
+
if (a.list_filter !== undefined && a.name_filter !== undefined)
|
|
25766
|
+
throw new Error("Choose list_filter or legacy name_filter.");
|
|
25767
|
+
const cmd = new Cmd("/container mounts print detail");
|
|
25768
|
+
if (a.list_filter !== undefined)
|
|
25769
|
+
cmd.raw("where").set("list", a.list_filter);
|
|
25770
|
+
if (a.name_filter !== undefined)
|
|
25771
|
+
cmd.raw("where").set("name", a.name_filter);
|
|
25772
|
+
return `CONTAINER MOUNTS:
|
|
25773
|
+
|
|
25774
|
+
${redactContainerText(await containerRead(cmd.build(), ctx))}`;
|
|
25775
|
+
}
|
|
25776
|
+
}),
|
|
25777
|
+
defineTool2({
|
|
25778
|
+
name: "add_container_mount",
|
|
25779
|
+
title: "Add Container Mount",
|
|
25780
|
+
annotations: WRITE,
|
|
25781
|
+
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.",
|
|
25782
|
+
inputSchema: {
|
|
25783
|
+
list: textValue.optional().describe("Current CLI mount-list name"),
|
|
25784
|
+
name: textValue.optional().describe("Legacy CLI mount name; do not use for current list syntax"),
|
|
25785
|
+
src: textValue,
|
|
25786
|
+
dst: textValue
|
|
25787
|
+
},
|
|
25788
|
+
async handler(a, ctx) {
|
|
25789
|
+
if (Boolean(a.list) === Boolean(a.name))
|
|
25790
|
+
throw new Error("Provide list OR legacy name.");
|
|
25791
|
+
const selector = new Cmd("").opt("list", a.list).opt("name", a.name).set("src", a.src).set("dst", a.dst).build().trim();
|
|
25792
|
+
const count = await containerRead(`/container mounts print count-only where ${selector}`, ctx);
|
|
25793
|
+
if (count.trim() !== "0")
|
|
25794
|
+
throw new Error("Mount exists or uniqueness is unknown; no mutation performed.");
|
|
25795
|
+
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);
|
|
25796
|
+
const countAfter = await containerReadBack(`/container mounts print count-only where ${selector}`, ctx);
|
|
25797
|
+
return countAfter.trim() === "1" ? "Mount creation verified; inspect application data separately." : "Mount add accepted; read-back UNVERIFIED. Inspect before retrying.";
|
|
25798
|
+
}
|
|
25799
|
+
}),
|
|
25800
|
+
defineTool2({
|
|
25801
|
+
name: "remove_container_mount",
|
|
25802
|
+
title: "Remove Container Mount",
|
|
25803
|
+
annotations: DESTRUCTIVE,
|
|
25804
|
+
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.",
|
|
25805
|
+
inputSchema: {
|
|
25806
|
+
id: IDENTITY.id,
|
|
25807
|
+
list: textValue.optional(),
|
|
25808
|
+
name: textValue.optional(),
|
|
25809
|
+
src: textValue.optional(),
|
|
25810
|
+
dst: textValue.optional()
|
|
25811
|
+
},
|
|
25812
|
+
async handler(a, ctx) {
|
|
25813
|
+
if ([a.id, a.list, a.name].filter((v) => v !== undefined).length !== 1 || a.id && (a.src || a.dst))
|
|
25814
|
+
throw new Error("Provide id OR list/name with optional src/dst.");
|
|
25815
|
+
const id = await resolveContainerItem("/container mounts", a.id ? { ".id": a.id } : { list: a.list, name: a.name, src: a.src, dst: a.dst }, ctx);
|
|
25816
|
+
await containerWrite(new Cmd("/container mounts remove").set("numbers", id).build(), ctx);
|
|
25817
|
+
const count = await containerReadBack(new Cmd("/container mounts print count-only where").set(".id", id).build(), ctx);
|
|
25818
|
+
return count.trim() === "0" ? "Mount definition removal verified; host files were not touched." : "Mount removal accepted; absence UNVERIFIED. Inspect before retrying.";
|
|
25819
|
+
}
|
|
25820
|
+
})
|
|
25821
|
+
];
|
|
25822
|
+
var containerTools = [
|
|
25823
|
+
defineTool2({
|
|
25824
|
+
name: "get_routeros_container_guide",
|
|
25825
|
+
title: "Get RouterOS Container Guide",
|
|
25826
|
+
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.",
|
|
25827
|
+
annotations: READ,
|
|
25828
|
+
noDevice: true,
|
|
25829
|
+
inputSchema: { topic: _enum(["all", ...CONTAINER_GUIDE_TOPICS]).default("all") },
|
|
25830
|
+
async handler(a) {
|
|
25831
|
+
return getRouterosContainerGuide(a.topic);
|
|
25832
|
+
}
|
|
25833
|
+
}),
|
|
25834
|
+
...withRequires({ packages: ["container"], deviceMode: "container", minVersion: "7.0" }, deviceTools2)
|
|
25835
|
+
];
|
|
25836
|
+
|
|
24098
25837
|
// src/core/firewall-audit.ts
|
|
24099
|
-
import * as
|
|
25838
|
+
import * as ipaddr3 from "ipaddr.js";
|
|
24100
25839
|
|
|
24101
25840
|
// src/schedule/identity.ts
|
|
24102
|
-
import { createHash as
|
|
25841
|
+
import { createHash as createHash7 } from "crypto";
|
|
24103
25842
|
function stableId(prefix, parts) {
|
|
24104
25843
|
const material = parts.filter((p) => p !== undefined && p !== "").map((p) => String(p).trim().toLowerCase()).join(" | ");
|
|
24105
|
-
const digest =
|
|
25844
|
+
const digest = createHash7("sha256").update(material, "utf8").digest("hex").slice(0, 12);
|
|
24106
25845
|
return `${prefix}:${digest}`;
|
|
24107
25846
|
}
|
|
24108
25847
|
function ruleFingerprint(rule) {
|
|
@@ -24215,8 +25954,8 @@ function rulesFromRows(rows) {
|
|
|
24215
25954
|
function toCidr(value) {
|
|
24216
25955
|
try {
|
|
24217
25956
|
if (value.includes("/"))
|
|
24218
|
-
return
|
|
24219
|
-
const addr =
|
|
25957
|
+
return ipaddr3.parseCIDR(value);
|
|
25958
|
+
const addr = ipaddr3.parse(value);
|
|
24220
25959
|
return [addr, addr.kind() === "ipv6" ? 128 : 32];
|
|
24221
25960
|
} catch {
|
|
24222
25961
|
return null;
|
|
@@ -24683,395 +26422,8 @@ function tailLines(text, n) {
|
|
|
24683
26422
|
return lines.length <= n ? text : lines.slice(-n).join(`
|
|
24684
26423
|
`);
|
|
24685
26424
|
}
|
|
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
26425
|
// src/tools/disk.ts
|
|
25074
|
-
var
|
|
26426
|
+
var NOT_AVAILABLE = "Disk management is not available on this device (no `/disk` support).";
|
|
25075
26427
|
var ADD_KEYS = new Set([
|
|
25076
26428
|
"type",
|
|
25077
26429
|
"slot",
|
|
@@ -25110,7 +26462,7 @@ var diskTools = [
|
|
|
25110
26462
|
filters.push(`interface~"${a.interface_filter}"`);
|
|
25111
26463
|
const result = await executeMikrotikCommand2(`/disk print${a.detail ? " detail" : ""}${whereClause(filters)}`, ctx);
|
|
25112
26464
|
if (commandUnsupported(result))
|
|
25113
|
-
return
|
|
26465
|
+
return NOT_AVAILABLE;
|
|
25114
26466
|
return isEmpty(result) ? "No disks found matching the criteria." : `DISKS:
|
|
25115
26467
|
|
|
25116
26468
|
${result}`;
|
|
@@ -25126,7 +26478,7 @@ ${result}`;
|
|
|
25126
26478
|
ctx.info(`Getting disk details: slot=${a.slot}`);
|
|
25127
26479
|
const result = await executeMikrotikCommand2(`/disk print detail where slot="${a.slot}"`, ctx);
|
|
25128
26480
|
if (commandUnsupported(result))
|
|
25129
|
-
return
|
|
26481
|
+
return NOT_AVAILABLE;
|
|
25130
26482
|
return isEmpty(result) ? `Disk '${a.slot}' not found.` : `DISK DETAILS:
|
|
25131
26483
|
|
|
25132
26484
|
${result}`;
|
|
@@ -25153,7 +26505,7 @@ ${result}`;
|
|
|
25153
26505
|
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
26506
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
25155
26507
|
if (commandUnsupported(result))
|
|
25156
|
-
return
|
|
26508
|
+
return NOT_AVAILABLE;
|
|
25157
26509
|
if (looksLikeError(result))
|
|
25158
26510
|
return `Failed to format disk: ${redactSecrets(result)}`;
|
|
25159
26511
|
return `Formatting disk '${a.slot}'\u2026
|
|
@@ -25181,7 +26533,7 @@ ${redactSecrets(result)}`;
|
|
|
25181
26533
|
return "No updates specified.";
|
|
25182
26534
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
25183
26535
|
if (commandUnsupported(result))
|
|
25184
|
-
return
|
|
26536
|
+
return NOT_AVAILABLE;
|
|
25185
26537
|
if (looksLikeError(result))
|
|
25186
26538
|
return `Failed to update disk: ${result}`;
|
|
25187
26539
|
const detail = await executeMikrotikCommand2(`/disk print detail where slot="${a.slot}"`, ctx);
|
|
@@ -25209,7 +26561,7 @@ ${detail}`;
|
|
|
25209
26561
|
return "No sharing settings specified.";
|
|
25210
26562
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
25211
26563
|
if (commandUnsupported(result))
|
|
25212
|
-
return
|
|
26564
|
+
return NOT_AVAILABLE;
|
|
25213
26565
|
if (looksLikeError(result))
|
|
25214
26566
|
return `Failed to configure disk sharing: ${result}`;
|
|
25215
26567
|
const detail = await executeMikrotikCommand2(`/disk print detail where slot="${a.slot}"`, ctx);
|
|
@@ -25242,7 +26594,7 @@ ${detail}`;
|
|
|
25242
26594
|
const built = cmd.build();
|
|
25243
26595
|
const result = await executeMikrotikCommand2(built, ctx);
|
|
25244
26596
|
if (commandUnsupported(result))
|
|
25245
|
-
return
|
|
26597
|
+
return NOT_AVAILABLE;
|
|
25246
26598
|
if (looksLikeError(result))
|
|
25247
26599
|
return `Failed to add virtual disk: ${redactSecrets(result)}`;
|
|
25248
26600
|
return `Virtual disk (type=${a.type}) added.
|
|
@@ -25260,12 +26612,12 @@ ${redactSecrets(result)}`;
|
|
|
25260
26612
|
ctx.info(`Ejecting disk: slot=${a.slot}`);
|
|
25261
26613
|
const count = await executeMikrotikCommand2(`/disk print count-only where slot="${a.slot}"`, ctx);
|
|
25262
26614
|
if (commandUnsupported(count))
|
|
25263
|
-
return
|
|
26615
|
+
return NOT_AVAILABLE;
|
|
25264
26616
|
if (count.trim() === "0")
|
|
25265
26617
|
return `Disk '${a.slot}' not found.`;
|
|
25266
26618
|
const result = await executeMikrotikCommand2(`/disk eject [find slot="${a.slot}"]`, ctx);
|
|
25267
26619
|
if (commandUnsupported(result))
|
|
25268
|
-
return
|
|
26620
|
+
return NOT_AVAILABLE;
|
|
25269
26621
|
if (looksLikeError(result))
|
|
25270
26622
|
return `Failed to eject disk: ${result}`;
|
|
25271
26623
|
return `Disk '${a.slot}' ejected \u2014 safe to remove.`;
|
|
@@ -25281,7 +26633,7 @@ ${redactSecrets(result)}`;
|
|
|
25281
26633
|
ctx.info(`Removing virtual disk: slot=${a.slot}`);
|
|
25282
26634
|
const count = await executeMikrotikCommand2(`/disk print count-only where slot="${a.slot}"`, ctx);
|
|
25283
26635
|
if (commandUnsupported(count))
|
|
25284
|
-
return
|
|
26636
|
+
return NOT_AVAILABLE;
|
|
25285
26637
|
if (count.trim() === "0")
|
|
25286
26638
|
return `Disk '${a.slot}' not found.`;
|
|
25287
26639
|
const result = await executeMikrotikCommand2(`/disk remove [find slot="${a.slot}"]`, ctx);
|
|
@@ -25428,7 +26780,7 @@ var cache2 = null;
|
|
|
25428
26780
|
async function gateway() {
|
|
25429
26781
|
if (cache2)
|
|
25430
26782
|
return cache2;
|
|
25431
|
-
const { moduleCatalog } = await import("./library-
|
|
26783
|
+
const { moduleCatalog } = await import("./library-krajvnj9.js");
|
|
25432
26784
|
const forIndex = [];
|
|
25433
26785
|
const byName = new Map;
|
|
25434
26786
|
for (const mod of moduleCatalog) {
|
|
@@ -27558,7 +28910,7 @@ function auditNetworkSegmentation(state) {
|
|
|
27558
28910
|
target: `/interface ${iface}`,
|
|
27559
28911
|
current: `subnets on one L2 domain: ${distinct.join(", ")}`,
|
|
27560
28912
|
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. " + "
|
|
28913
|
+
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
28914
|
});
|
|
27563
28915
|
}
|
|
27564
28916
|
return findings;
|
|
@@ -28388,7 +29740,7 @@ function evaluatePolicies(policies, model, opts = {}) {
|
|
|
28388
29740
|
|
|
28389
29741
|
// src/policy/load.ts
|
|
28390
29742
|
import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
|
|
28391
|
-
import { dirname as
|
|
29743
|
+
import { dirname as dirname11, isAbsolute, join as join6, resolve as resolve3 } from "path";
|
|
28392
29744
|
|
|
28393
29745
|
// src/policy/schema.ts
|
|
28394
29746
|
var MAX_REGEX_LENGTH = 200;
|
|
@@ -28511,18 +29863,18 @@ function validatePolicyText(text) {
|
|
|
28511
29863
|
var RULE_EXTENSIONS = [".yaml", ".yml", ".json"];
|
|
28512
29864
|
function expand(pattern, cwd) {
|
|
28513
29865
|
const absolute = isAbsolute(pattern) ? pattern : resolve3(cwd, pattern);
|
|
28514
|
-
const base =
|
|
29866
|
+
const base = dirname11(absolute);
|
|
28515
29867
|
const leaf = absolute.slice(base.length + 1);
|
|
28516
29868
|
if (!leaf.includes("*")) {
|
|
28517
29869
|
try {
|
|
28518
|
-
return statSync2(absolute).isDirectory() ? readdirSync2(absolute).filter((f) => RULE_EXTENSIONS.some((e) => f.endsWith(e))).map((f) =>
|
|
29870
|
+
return statSync2(absolute).isDirectory() ? readdirSync2(absolute).filter((f) => RULE_EXTENSIONS.some((e) => f.endsWith(e))).map((f) => join6(absolute, f)).sort() : [absolute];
|
|
28519
29871
|
} catch {
|
|
28520
29872
|
return [];
|
|
28521
29873
|
}
|
|
28522
29874
|
}
|
|
28523
29875
|
const suffix = leaf.replace(/^\*/, "");
|
|
28524
29876
|
try {
|
|
28525
|
-
return readdirSync2(base).filter((f) => suffix === "" ? true : f.endsWith(suffix)).map((f) =>
|
|
29877
|
+
return readdirSync2(base).filter((f) => suffix === "" ? true : f.endsWith(suffix)).map((f) => join6(base, f)).sort();
|
|
28526
29878
|
} catch {
|
|
28527
29879
|
return [];
|
|
28528
29880
|
}
|
|
@@ -28726,7 +30078,7 @@ function renderReport2(report, format, opts = {}) {
|
|
|
28726
30078
|
}
|
|
28727
30079
|
|
|
28728
30080
|
// src/policy/session.ts
|
|
28729
|
-
import { join as
|
|
30081
|
+
import { join as join7 } from "path";
|
|
28730
30082
|
var MAX_REPORTS = 25;
|
|
28731
30083
|
var reports = [];
|
|
28732
30084
|
function rememberReport(report) {
|
|
@@ -28741,7 +30093,7 @@ function recentReports() {
|
|
|
28741
30093
|
return reports;
|
|
28742
30094
|
}
|
|
28743
30095
|
function packagedPolicyPaths() {
|
|
28744
|
-
return [
|
|
30096
|
+
return [join7(PROJECT_ROOT, "policies")];
|
|
28745
30097
|
}
|
|
28746
30098
|
|
|
28747
30099
|
// src/tools/policy.ts
|
|
@@ -37073,7 +38425,7 @@ ${result}`;
|
|
|
37073
38425
|
];
|
|
37074
38426
|
|
|
37075
38427
|
// src/tools/ssh-test.ts
|
|
37076
|
-
async function
|
|
38428
|
+
async function probe2(opts, label, command) {
|
|
37077
38429
|
const client = new MikroTikSSHClient2(opts);
|
|
37078
38430
|
const t0 = Date.now();
|
|
37079
38431
|
try {
|
|
@@ -37107,7 +38459,7 @@ var sshTestTools = [
|
|
|
37107
38459
|
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
38460
|
}
|
|
37109
38461
|
ctx.info(`Testing SSH from MCP host to configured device '${name}' (${dc.host}:${dc.port})`);
|
|
37110
|
-
return
|
|
38462
|
+
return probe2({
|
|
37111
38463
|
...sshOptionsOf(dc),
|
|
37112
38464
|
jump: resolveJump(dc),
|
|
37113
38465
|
timeoutMs: Math.min(dc.timeoutMs ?? 1e4, 1e4)
|
|
@@ -37130,7 +38482,7 @@ var sshTestTools = [
|
|
|
37130
38482
|
},
|
|
37131
38483
|
async handler(a, ctx) {
|
|
37132
38484
|
ctx.info(`Testing SSH from MCP host to ${a.host}:${a.port} as ${a.username}`);
|
|
37133
|
-
return
|
|
38485
|
+
return probe2({
|
|
37134
38486
|
host: a.host,
|
|
37135
38487
|
port: a.port,
|
|
37136
38488
|
username: a.username,
|
|
@@ -45267,8 +46619,8 @@ function publishTxn(update) {
|
|
|
45267
46619
|
}
|
|
45268
46620
|
|
|
45269
46621
|
// src/txn/store.ts
|
|
45270
|
-
import { mkdirSync as
|
|
45271
|
-
import { dirname as
|
|
46622
|
+
import { mkdirSync as mkdirSync11 } from "fs";
|
|
46623
|
+
import { dirname as dirname12 } from "path";
|
|
45272
46624
|
function toRecord(txn, ts, label) {
|
|
45273
46625
|
return {
|
|
45274
46626
|
id: txn.id,
|
|
@@ -45404,7 +46756,7 @@ class SqliteTxnStore {
|
|
|
45404
46756
|
async function openTxnStore(path) {
|
|
45405
46757
|
if (path !== ":memory:") {
|
|
45406
46758
|
try {
|
|
45407
|
-
|
|
46759
|
+
mkdirSync11(dirname12(path), { recursive: true });
|
|
45408
46760
|
} catch {}
|
|
45409
46761
|
}
|
|
45410
46762
|
const { Database } = await import("bun:sqlite");
|
|
@@ -46272,8 +47624,8 @@ function createDeviceExecutor2(ctx, rolloutId) {
|
|
|
46272
47624
|
}
|
|
46273
47625
|
|
|
46274
47626
|
// src/rollout/store.ts
|
|
46275
|
-
import { mkdirSync as
|
|
46276
|
-
import { dirname as
|
|
47627
|
+
import { mkdirSync as mkdirSync12 } from "fs";
|
|
47628
|
+
import { dirname as dirname13 } from "path";
|
|
46277
47629
|
function toRecord2(rollout, ts, opts = {}) {
|
|
46278
47630
|
return {
|
|
46279
47631
|
id: rollout.id,
|
|
@@ -46406,7 +47758,7 @@ class SqliteRolloutStore {
|
|
|
46406
47758
|
async function openRolloutStore(path) {
|
|
46407
47759
|
if (path !== ":memory:") {
|
|
46408
47760
|
try {
|
|
46409
|
-
|
|
47761
|
+
mkdirSync12(dirname13(path), { recursive: true });
|
|
46410
47762
|
} catch {}
|
|
46411
47763
|
}
|
|
46412
47764
|
const { Database } = await import("bun:sqlite");
|
|
@@ -46866,7 +48218,7 @@ function rank(severity) {
|
|
|
46866
48218
|
const i = SEVERITY_ORDER4.indexOf(severity);
|
|
46867
48219
|
return i === -1 ? SEVERITY_ORDER4.length : i;
|
|
46868
48220
|
}
|
|
46869
|
-
var
|
|
48221
|
+
var FIELDS2 = [
|
|
46870
48222
|
{ min: 0, max: 59, name: "minute" },
|
|
46871
48223
|
{ min: 0, max: 23, name: "hour" },
|
|
46872
48224
|
{ min: 1, max: 31, name: "day-of-month" },
|
|
@@ -46933,11 +48285,11 @@ function parseCron(expression) {
|
|
|
46933
48285
|
}
|
|
46934
48286
|
const [minute, hour, dom, month, dow] = parts;
|
|
46935
48287
|
return {
|
|
46936
|
-
minutes: parseField(minute,
|
|
46937
|
-
hours: parseField(hour,
|
|
46938
|
-
daysOfMonth: parseField(dom,
|
|
46939
|
-
months: parseField(month,
|
|
46940
|
-
daysOfWeek: parseField(dow,
|
|
48288
|
+
minutes: parseField(minute, FIELDS2[0]),
|
|
48289
|
+
hours: parseField(hour, FIELDS2[1]),
|
|
48290
|
+
daysOfMonth: parseField(dom, FIELDS2[2]),
|
|
48291
|
+
months: parseField(month, FIELDS2[3]),
|
|
48292
|
+
daysOfWeek: parseField(dow, FIELDS2[4]),
|
|
46941
48293
|
domRestricted: dom !== "*",
|
|
46942
48294
|
dowRestricted: dow !== "*"
|
|
46943
48295
|
};
|
|
@@ -47122,8 +48474,8 @@ var JobSchema = object({
|
|
|
47122
48474
|
});
|
|
47123
48475
|
|
|
47124
48476
|
// src/schedule/store.ts
|
|
47125
|
-
import { mkdirSync as
|
|
47126
|
-
import { dirname as
|
|
48477
|
+
import { mkdirSync as mkdirSync13 } from "fs";
|
|
48478
|
+
import { dirname as dirname14 } from "path";
|
|
47127
48479
|
var SCHEMA2 = [
|
|
47128
48480
|
`CREATE TABLE IF NOT EXISTS schedule_jobs (
|
|
47129
48481
|
id TEXT PRIMARY KEY,
|
|
@@ -47265,7 +48617,7 @@ class SqliteScheduleStore {
|
|
|
47265
48617
|
async function openScheduleStore(path) {
|
|
47266
48618
|
if (path !== ":memory:") {
|
|
47267
48619
|
try {
|
|
47268
|
-
|
|
48620
|
+
mkdirSync13(dirname14(path), { recursive: true });
|
|
47269
48621
|
} catch {}
|
|
47270
48622
|
}
|
|
47271
48623
|
const { Database } = await import("bun:sqlite");
|
|
@@ -47427,7 +48779,7 @@ var riskByTool = null;
|
|
|
47427
48779
|
async function riskIndex() {
|
|
47428
48780
|
if (riskByTool)
|
|
47429
48781
|
return riskByTool;
|
|
47430
|
-
const { moduleCatalog } = await import("./library-
|
|
48782
|
+
const { moduleCatalog } = await import("./library-krajvnj9.js");
|
|
47431
48783
|
const index = new Map;
|
|
47432
48784
|
for (const mod of moduleCatalog) {
|
|
47433
48785
|
for (const tool of mod.tools)
|
|
@@ -49591,7 +50943,7 @@ async function readScanList(ctx, list = "port-scanners") {
|
|
|
49591
50943
|
}
|
|
49592
50944
|
|
|
49593
50945
|
// src/attack/correlate.ts
|
|
49594
|
-
import { createHash as
|
|
50946
|
+
import { createHash as createHash8 } from "crypto";
|
|
49595
50947
|
var STAGE_ORDER = ["recon", "attempt", "breach", "persistence"];
|
|
49596
50948
|
var STAGE_OF = {
|
|
49597
50949
|
"port-scan": "recon",
|
|
@@ -49621,7 +50973,7 @@ var SEVERITY_RANK = {
|
|
|
49621
50973
|
info: 4
|
|
49622
50974
|
};
|
|
49623
50975
|
function incidentId(source, dayBucket) {
|
|
49624
|
-
const digest =
|
|
50976
|
+
const digest = createHash8("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
|
|
49625
50977
|
return `atk_${digest}`;
|
|
49626
50978
|
}
|
|
49627
50979
|
function worst(values) {
|
|
@@ -49711,7 +51063,7 @@ function mergeIncident(stored, fresh) {
|
|
|
49711
51063
|
var RECORD_START = /^\s*time=/;
|
|
49712
51064
|
var FIELD_RE = /([a-zA-Z][\w-]*)=(?:"((?:[^"\\]|\\.)*)"|(\S*))/g;
|
|
49713
51065
|
var TIME_WITH_CLOCK_RE = /time=(\S+)[ \t]+(\d{2}:\d{2}:\d{2}(?:\.\d+)?)/;
|
|
49714
|
-
function
|
|
51066
|
+
function fields2(text) {
|
|
49715
51067
|
const out = {};
|
|
49716
51068
|
for (const m of text.matchAll(FIELD_RE)) {
|
|
49717
51069
|
out[m[1]] = m[2] !== undefined ? m[2].replace(/\\(.)/g, "$1") : m[3] ?? "";
|
|
@@ -49733,7 +51085,7 @@ function parseLogRecords(text) {
|
|
|
49733
51085
|
return;
|
|
49734
51086
|
const raw = current.join(`
|
|
49735
51087
|
`);
|
|
49736
|
-
const f =
|
|
51088
|
+
const f = fields2(raw);
|
|
49737
51089
|
if (f.time === undefined || f.message === undefined) {
|
|
49738
51090
|
unparsed.push({ line: startLine, text: raw.trim().slice(0, 200) });
|
|
49739
51091
|
} else {
|
|
@@ -49843,8 +51195,8 @@ function dedupe(events, seen) {
|
|
|
49843
51195
|
}
|
|
49844
51196
|
|
|
49845
51197
|
// src/attack/store.ts
|
|
49846
|
-
import { mkdirSync as
|
|
49847
|
-
import { dirname as
|
|
51198
|
+
import { mkdirSync as mkdirSync14 } from "fs";
|
|
51199
|
+
import { dirname as dirname15 } from "path";
|
|
49848
51200
|
var SCHEMA3 = [
|
|
49849
51201
|
`CREATE TABLE IF NOT EXISTS attack_incidents (
|
|
49850
51202
|
id TEXT PRIMARY KEY,
|
|
@@ -50035,7 +51387,7 @@ class SqliteAttackStore {
|
|
|
50035
51387
|
async function openAttackStore(path) {
|
|
50036
51388
|
if (path !== ":memory:") {
|
|
50037
51389
|
try {
|
|
50038
|
-
|
|
51390
|
+
mkdirSync14(dirname15(path), { recursive: true });
|
|
50039
51391
|
} catch {}
|
|
50040
51392
|
}
|
|
50041
51393
|
const { Database } = await import("bun:sqlite");
|
|
@@ -50709,14 +52061,14 @@ ${result}`;
|
|
|
50709
52061
|
];
|
|
50710
52062
|
|
|
50711
52063
|
// src/core/update-check.ts
|
|
50712
|
-
import { existsSync as existsSync4, mkdirSync as
|
|
52064
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync15, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
|
|
50713
52065
|
import { homedir as homedir2 } from "os";
|
|
50714
|
-
import { dirname as
|
|
52066
|
+
import { dirname as dirname16, join as join9 } from "path";
|
|
50715
52067
|
|
|
50716
52068
|
// src/version.ts
|
|
50717
52069
|
import { readFileSync as readFileSync7 } from "fs";
|
|
50718
|
-
import { join as
|
|
50719
|
-
var pkg = JSON.parse(readFileSync7(
|
|
52070
|
+
import { join as join8 } from "path";
|
|
52071
|
+
var pkg = JSON.parse(readFileSync7(join8(PROJECT_ROOT, "package.json"), "utf-8"));
|
|
50720
52072
|
var VERSION2 = pkg.version ?? "0.0.0";
|
|
50721
52073
|
var WEBSITE_URL = pkg.homepage ?? "";
|
|
50722
52074
|
var LOGO_URL = pkg.logoIcon ?? "";
|
|
@@ -50728,7 +52080,7 @@ var SERVER_NAME2 = "mikrotik-mcp";
|
|
|
50728
52080
|
var GITHUB_API = "https://api.github.com/repos/mikrotik-mcp/mikrotik-mcp/releases/latest";
|
|
50729
52081
|
var MEMORY_CACHE_TTL = 15 * 60 * 1000;
|
|
50730
52082
|
var FILE_CACHE_TTL = 6 * 60 * 60 * 1000;
|
|
50731
|
-
var CACHE_PATH =
|
|
52083
|
+
var CACHE_PATH = join9(homedir2(), ".mikrotik-mcp", "update-check.json");
|
|
50732
52084
|
function compareVersions2(a, b) {
|
|
50733
52085
|
const pa = a.replace(/^v/, "").split(".").map(Number);
|
|
50734
52086
|
const pb = b.replace(/^v/, "").split(".").map(Number);
|
|
@@ -50758,9 +52110,9 @@ function loadFileCacheSync() {
|
|
|
50758
52110
|
}
|
|
50759
52111
|
function saveFileCache(data) {
|
|
50760
52112
|
try {
|
|
50761
|
-
const dir =
|
|
52113
|
+
const dir = dirname16(CACHE_PATH);
|
|
50762
52114
|
if (!existsSync4(dir))
|
|
50763
|
-
|
|
52115
|
+
mkdirSync15(dir, { recursive: true });
|
|
50764
52116
|
writeFileSync3(CACHE_PATH, JSON.stringify({ data, fetchedAt: Date.now() }));
|
|
50765
52117
|
} catch {}
|
|
50766
52118
|
}
|
|
@@ -50937,13 +52289,27 @@ var serverPulseTools = [
|
|
|
50937
52289
|
];
|
|
50938
52290
|
|
|
50939
52291
|
// src/observability/config-admin.ts
|
|
50940
|
-
import { createHash as
|
|
50941
|
-
import { readFileSync as
|
|
52292
|
+
import { createHash as createHash9, randomUUID as randomUUID10 } from "crypto";
|
|
52293
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
50942
52294
|
|
|
50943
52295
|
// src/config-write.ts
|
|
50944
|
-
import { randomUUID as
|
|
50945
|
-
import {
|
|
50946
|
-
|
|
52296
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
52297
|
+
import {
|
|
52298
|
+
closeSync,
|
|
52299
|
+
constants,
|
|
52300
|
+
fchmodSync,
|
|
52301
|
+
fstatSync,
|
|
52302
|
+
fsyncSync,
|
|
52303
|
+
ftruncateSync,
|
|
52304
|
+
mkdirSync as mkdirSync16,
|
|
52305
|
+
openSync,
|
|
52306
|
+
readFileSync as readFileSync9,
|
|
52307
|
+
renameSync as renameSync2,
|
|
52308
|
+
rmSync as rmSync2,
|
|
52309
|
+
writeFileSync as writeFileSync4,
|
|
52310
|
+
writeSync
|
|
52311
|
+
} from "fs";
|
|
52312
|
+
import { dirname as dirname17 } from "path";
|
|
50947
52313
|
var SCHEMA_REF = "./schemas/config.schema.json";
|
|
50948
52314
|
function serializeConfig(config) {
|
|
50949
52315
|
const body = config && typeof config === "object" && !Array.isArray(config) ? config : {};
|
|
@@ -50955,22 +52321,62 @@ function backupName(path, ts) {
|
|
|
50955
52321
|
return `${path}.bak-${ts}`;
|
|
50956
52322
|
}
|
|
50957
52323
|
function atomicWrite(path, text) {
|
|
50958
|
-
|
|
50959
|
-
const tmp = `${path}.tmp-${
|
|
52324
|
+
mkdirSync16(dirname17(path), { recursive: true });
|
|
52325
|
+
const tmp = `${path}.tmp-${randomUUID9()}`;
|
|
50960
52326
|
try {
|
|
50961
|
-
writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
50962
|
-
|
|
52327
|
+
writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx", flush: true });
|
|
52328
|
+
try {
|
|
52329
|
+
renameSync2(tmp, path);
|
|
52330
|
+
} catch (error) {
|
|
52331
|
+
if (error.code !== "EBUSY")
|
|
52332
|
+
throw error;
|
|
52333
|
+
writeMountedFile(path, text);
|
|
52334
|
+
}
|
|
50963
52335
|
} finally {
|
|
50964
52336
|
rmSync2(tmp, { force: true });
|
|
50965
52337
|
}
|
|
50966
52338
|
}
|
|
52339
|
+
function replaceContents(fd, bytes) {
|
|
52340
|
+
let offset = 0;
|
|
52341
|
+
while (offset < bytes.length) {
|
|
52342
|
+
const written = writeSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
52343
|
+
if (written === 0)
|
|
52344
|
+
throw new Error("Configuration write made no progress.");
|
|
52345
|
+
offset += written;
|
|
52346
|
+
}
|
|
52347
|
+
ftruncateSync(fd, bytes.length);
|
|
52348
|
+
fsyncSync(fd);
|
|
52349
|
+
}
|
|
52350
|
+
function writeMountedFile(path, text) {
|
|
52351
|
+
const fd = openSync(path, constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
52352
|
+
try {
|
|
52353
|
+
if (!fstatSync(fd).isFile())
|
|
52354
|
+
throw new Error("Configuration target must be a regular file.");
|
|
52355
|
+
fchmodSync(fd, 384);
|
|
52356
|
+
const previous = readFileSync9(fd);
|
|
52357
|
+
const backup = `${path}.bak-mounted-${randomUUID9()}`;
|
|
52358
|
+
writeFileSync4(backup, previous, { mode: 384, flag: "wx", flush: true });
|
|
52359
|
+
try {
|
|
52360
|
+
replaceContents(fd, Buffer.from(text, "utf8"));
|
|
52361
|
+
} catch {
|
|
52362
|
+
try {
|
|
52363
|
+
replaceContents(fd, previous);
|
|
52364
|
+
} catch {
|
|
52365
|
+
throw new Error("Configuration write and recovery failed; restore the retained mounted-file backup.");
|
|
52366
|
+
}
|
|
52367
|
+
throw new Error("Configuration write failed; previous contents restored and backup retained.");
|
|
52368
|
+
}
|
|
52369
|
+
} finally {
|
|
52370
|
+
closeSync(fd);
|
|
52371
|
+
}
|
|
52372
|
+
}
|
|
50967
52373
|
|
|
50968
52374
|
// src/observability/config-admin.ts
|
|
50969
52375
|
function createConfigAdmin(deps) {
|
|
50970
52376
|
let pending = null;
|
|
50971
52377
|
let lastTimestamp = 0;
|
|
50972
|
-
const salt =
|
|
50973
|
-
const fingerprint = (config, source, contents) =>
|
|
52378
|
+
const salt = randomUUID10();
|
|
52379
|
+
const fingerprint = (config, source, contents) => createHash9("sha256").update(salt).update(JSON.stringify([config, source, contents])).digest("hex");
|
|
50974
52380
|
const revision = () => {
|
|
50975
52381
|
const source = deps.source();
|
|
50976
52382
|
return fingerprint(deps.getConfig(), source, deps.readFile(source.path));
|
|
@@ -51064,7 +52470,7 @@ function getConfigAdmin() {
|
|
|
51064
52470
|
source: getConfigSource2,
|
|
51065
52471
|
readFile: (path) => {
|
|
51066
52472
|
try {
|
|
51067
|
-
return
|
|
52473
|
+
return readFileSync10(path, "utf8");
|
|
51068
52474
|
} catch (error) {
|
|
51069
52475
|
if (error.code === "ENOENT")
|
|
51070
52476
|
return null;
|
|
@@ -51116,7 +52522,7 @@ var McpSettingsPendingSchema = object({
|
|
|
51116
52522
|
revision: string().length(64).describe("Revision returned by update_mcp_settings or get_mcp_settings.")
|
|
51117
52523
|
}).strict();
|
|
51118
52524
|
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
|
|
52525
|
+
function settings2(cfg) {
|
|
51120
52526
|
return {
|
|
51121
52527
|
mcp: {
|
|
51122
52528
|
toolPageSize: cfg.mcp.toolPageSize,
|
|
@@ -51146,7 +52552,7 @@ function createMcpSettingsService(deps) {
|
|
|
51146
52552
|
const source = deps.source();
|
|
51147
52553
|
return {
|
|
51148
52554
|
revision: deps.admin.revision(),
|
|
51149
|
-
settings:
|
|
52555
|
+
settings: settings2(deps.getConfig()),
|
|
51150
52556
|
pending: id ? { id, owned: id === owned?.id, expiresAt: id === owned?.id ? owned.expiresAt : null } : null,
|
|
51151
52557
|
persistence: {
|
|
51152
52558
|
path: source.path,
|
|
@@ -51172,8 +52578,8 @@ function createMcpSettingsService(deps) {
|
|
|
51172
52578
|
});
|
|
51173
52579
|
if (changes.dashboard?.captureBody === true && !next.dashboard.redactInput)
|
|
51174
52580
|
throw new Error("Enabling body capture also requires dashboard.redactInput=true.");
|
|
51175
|
-
const before =
|
|
51176
|
-
const after =
|
|
52581
|
+
const before = settings2(current);
|
|
52582
|
+
const after = settings2(next);
|
|
51177
52583
|
const changedPaths = [];
|
|
51178
52584
|
for (const key of ["mcp", "ssh", "dashboard", "memory"]) {
|
|
51179
52585
|
for (const [field, value] of Object.entries(after[key])) {
|
|
@@ -51293,7 +52699,7 @@ var mcpSettingsTools = [
|
|
|
51293
52699
|
title: "Safely Update MCP Settings",
|
|
51294
52700
|
noDevice: true,
|
|
51295
52701
|
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
|
|
52702
|
+
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
52703
|
inputSchema: McpSettingsUpdateSchema.shape,
|
|
51298
52704
|
handler: (args) => render(getMcpSettingsService().update(args))
|
|
51299
52705
|
}),
|
|
@@ -53339,7 +54745,7 @@ ${result}`;
|
|
|
53339
54745
|
];
|
|
53340
54746
|
|
|
53341
54747
|
// src/tools/user-manager.ts
|
|
53342
|
-
var
|
|
54748
|
+
var NOT_AVAILABLE2 = "User Manager is not available on this device (package not installed).";
|
|
53343
54749
|
var userManagerToolsDefs = [
|
|
53344
54750
|
defineTool2({
|
|
53345
54751
|
name: "get_user_manager_settings",
|
|
@@ -53350,7 +54756,7 @@ var userManagerToolsDefs = [
|
|
|
53350
54756
|
ctx.info("Getting User Manager settings");
|
|
53351
54757
|
const result = await executeMikrotikCommand2("/user-manager print", ctx);
|
|
53352
54758
|
if (commandUnsupported(result))
|
|
53353
|
-
return
|
|
54759
|
+
return NOT_AVAILABLE2;
|
|
53354
54760
|
return isEmpty(result) ? "No User Manager settings found." : `USER MANAGER SETTINGS:
|
|
53355
54761
|
|
|
53356
54762
|
${result}`;
|
|
@@ -53376,7 +54782,7 @@ ${result}`;
|
|
|
53376
54782
|
return "No updates specified.";
|
|
53377
54783
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53378
54784
|
if (commandUnsupported(result))
|
|
53379
|
-
return
|
|
54785
|
+
return NOT_AVAILABLE2;
|
|
53380
54786
|
if (looksLikeError(result))
|
|
53381
54787
|
return `Failed to update User Manager settings: ${result}`;
|
|
53382
54788
|
const details = await executeMikrotikCommand2("/user-manager print", ctx);
|
|
@@ -53406,7 +54812,7 @@ ${details}`;
|
|
|
53406
54812
|
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
54813
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53408
54814
|
if (commandUnsupported(result))
|
|
53409
|
-
return
|
|
54815
|
+
return NOT_AVAILABLE2;
|
|
53410
54816
|
if (looksLikeError(result))
|
|
53411
54817
|
return `Failed to add User Manager user: ${result}`;
|
|
53412
54818
|
const details = await executeMikrotikCommand2(`/user-manager user print detail where name="${a.name}"`, ctx);
|
|
@@ -53430,7 +54836,7 @@ ${redactSecrets(details)}` : "User Manager user creation completed but unable to
|
|
|
53430
54836
|
filters.push(`name~"${a.name_filter}"`);
|
|
53431
54837
|
const result = await executeMikrotikCommand2(`/user-manager user print${whereClause(filters)}`, ctx);
|
|
53432
54838
|
if (commandUnsupported(result))
|
|
53433
|
-
return
|
|
54839
|
+
return NOT_AVAILABLE2;
|
|
53434
54840
|
return isEmpty(result) ? "No User Manager users found matching the criteria." : `USER MANAGER USERS:
|
|
53435
54841
|
|
|
53436
54842
|
${redactSecrets(result)}`;
|
|
@@ -53446,7 +54852,7 @@ ${redactSecrets(result)}`;
|
|
|
53446
54852
|
ctx.info(`Getting User Manager user details: name=${a.name}`);
|
|
53447
54853
|
const result = await executeMikrotikCommand2(`/user-manager user print detail where name="${a.name}"`, ctx);
|
|
53448
54854
|
if (commandUnsupported(result))
|
|
53449
|
-
return
|
|
54855
|
+
return NOT_AVAILABLE2;
|
|
53450
54856
|
return isEmpty(result) ? `User Manager user '${a.name}' not found.` : `USER MANAGER USER DETAILS:
|
|
53451
54857
|
|
|
53452
54858
|
${redactSecrets(result)}`;
|
|
@@ -53476,7 +54882,7 @@ ${redactSecrets(result)}`;
|
|
|
53476
54882
|
return "No updates specified.";
|
|
53477
54883
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53478
54884
|
if (commandUnsupported(result))
|
|
53479
|
-
return
|
|
54885
|
+
return NOT_AVAILABLE2;
|
|
53480
54886
|
if (looksLikeError(result))
|
|
53481
54887
|
return `Failed to update User Manager user: ${result}`;
|
|
53482
54888
|
const target = a.new_name ?? a.name;
|
|
@@ -53496,7 +54902,7 @@ ${redactSecrets(details)}`;
|
|
|
53496
54902
|
ctx.info(`Removing User Manager user: name=${a.name}`);
|
|
53497
54903
|
const count = await executeMikrotikCommand2(`/user-manager user print count-only where name="${a.name}"`, ctx);
|
|
53498
54904
|
if (commandUnsupported(count))
|
|
53499
|
-
return
|
|
54905
|
+
return NOT_AVAILABLE2;
|
|
53500
54906
|
if (count.trim() === "0")
|
|
53501
54907
|
return `User Manager user '${a.name}' not found.`;
|
|
53502
54908
|
const result = await executeMikrotikCommand2(`/user-manager user remove [find name="${a.name}"]`, ctx);
|
|
@@ -53524,7 +54930,7 @@ ${redactSecrets(details)}`;
|
|
|
53524
54930
|
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
54931
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53526
54932
|
if (commandUnsupported(result))
|
|
53527
|
-
return
|
|
54933
|
+
return NOT_AVAILABLE2;
|
|
53528
54934
|
if (looksLikeError(result))
|
|
53529
54935
|
return `Failed to add User Manager profile: ${result}`;
|
|
53530
54936
|
const details = await executeMikrotikCommand2(`/user-manager profile print detail where name="${a.name}"`, ctx);
|
|
@@ -53548,7 +54954,7 @@ ${details}` : "User Manager profile creation completed but unable to verify.";
|
|
|
53548
54954
|
filters.push(`name~"${a.name_filter}"`);
|
|
53549
54955
|
const result = await executeMikrotikCommand2(`/user-manager profile print${whereClause(filters)}`, ctx);
|
|
53550
54956
|
if (commandUnsupported(result))
|
|
53551
|
-
return
|
|
54957
|
+
return NOT_AVAILABLE2;
|
|
53552
54958
|
return isEmpty(result) ? "No User Manager profiles found matching the criteria." : `USER MANAGER PROFILES:
|
|
53553
54959
|
|
|
53554
54960
|
${result}`;
|
|
@@ -53564,7 +54970,7 @@ ${result}`;
|
|
|
53564
54970
|
ctx.info(`Removing User Manager profile: name=${a.name}`);
|
|
53565
54971
|
const count = await executeMikrotikCommand2(`/user-manager profile print count-only where name="${a.name}"`, ctx);
|
|
53566
54972
|
if (commandUnsupported(count))
|
|
53567
|
-
return
|
|
54973
|
+
return NOT_AVAILABLE2;
|
|
53568
54974
|
if (count.trim() === "0")
|
|
53569
54975
|
return `User Manager profile '${a.name}' not found.`;
|
|
53570
54976
|
const result = await executeMikrotikCommand2(`/user-manager profile remove [find name="${a.name}"]`, ctx);
|
|
@@ -53587,7 +54993,7 @@ ${result}`;
|
|
|
53587
54993
|
const cmd = new Cmd("/user-manager user-profile add").set("user", a.user).set("profile", a.profile).build();
|
|
53588
54994
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53589
54995
|
if (commandUnsupported(result))
|
|
53590
|
-
return
|
|
54996
|
+
return NOT_AVAILABLE2;
|
|
53591
54997
|
if (looksLikeError(result))
|
|
53592
54998
|
return `Failed to assign profile: ${result}`;
|
|
53593
54999
|
return `Assigned profile '${a.profile}' to user '${a.user}'.
|
|
@@ -53610,7 +55016,7 @@ ${result}`;
|
|
|
53610
55016
|
filters.push(`user~"${a.user_filter}"`);
|
|
53611
55017
|
const result = await executeMikrotikCommand2(`/user-manager user-profile print${whereClause(filters)}`, ctx);
|
|
53612
55018
|
if (commandUnsupported(result))
|
|
53613
|
-
return
|
|
55019
|
+
return NOT_AVAILABLE2;
|
|
53614
55020
|
return isEmpty(result) ? "No User Manager user-profiles found matching the criteria." : `USER MANAGER USER-PROFILES:
|
|
53615
55021
|
|
|
53616
55022
|
${result}`;
|
|
@@ -53635,7 +55041,7 @@ ${result}`;
|
|
|
53635
55041
|
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
55042
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53637
55043
|
if (commandUnsupported(result))
|
|
53638
|
-
return
|
|
55044
|
+
return NOT_AVAILABLE2;
|
|
53639
55045
|
if (looksLikeError(result))
|
|
53640
55046
|
return `Failed to add User Manager router: ${result}`;
|
|
53641
55047
|
const details = await executeMikrotikCommand2(`/user-manager router print detail where name="${a.name}"`, ctx);
|
|
@@ -53659,7 +55065,7 @@ ${redactSecrets(details)}` : "User Manager router creation completed but unable
|
|
|
53659
55065
|
filters.push(`name~"${a.name_filter}"`);
|
|
53660
55066
|
const result = await executeMikrotikCommand2(`/user-manager router print${whereClause(filters)}`, ctx);
|
|
53661
55067
|
if (commandUnsupported(result))
|
|
53662
|
-
return
|
|
55068
|
+
return NOT_AVAILABLE2;
|
|
53663
55069
|
return isEmpty(result) ? "No User Manager routers found matching the criteria." : `USER MANAGER ROUTERS:
|
|
53664
55070
|
|
|
53665
55071
|
${redactSecrets(result)}`;
|
|
@@ -53675,7 +55081,7 @@ ${redactSecrets(result)}`;
|
|
|
53675
55081
|
ctx.info(`Removing User Manager router: name=${a.name}`);
|
|
53676
55082
|
const count = await executeMikrotikCommand2(`/user-manager router print count-only where name="${a.name}"`, ctx);
|
|
53677
55083
|
if (commandUnsupported(count))
|
|
53678
|
-
return
|
|
55084
|
+
return NOT_AVAILABLE2;
|
|
53679
55085
|
if (count.trim() === "0")
|
|
53680
55086
|
return `User Manager router '${a.name}' not found.`;
|
|
53681
55087
|
const result = await executeMikrotikCommand2(`/user-manager router remove [find name="${a.name}"]`, ctx);
|
|
@@ -53715,7 +55121,7 @@ ${redactSecrets(result)}`;
|
|
|
53715
55121
|
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
55122
|
const result = await executeMikrotikCommand2(cmd, ctx);
|
|
53717
55123
|
if (commandUnsupported(result))
|
|
53718
|
-
return
|
|
55124
|
+
return NOT_AVAILABLE2;
|
|
53719
55125
|
if (looksLikeError(result))
|
|
53720
55126
|
return `Failed to add User Manager limitation: ${result}`;
|
|
53721
55127
|
const details = await executeMikrotikCommand2(`/user-manager limitation print detail where name="${a.name}"`, ctx);
|
|
@@ -53739,7 +55145,7 @@ ${details}` : "User Manager limitation creation completed but unable to verify."
|
|
|
53739
55145
|
filters.push(`name~"${a.name_filter}"`);
|
|
53740
55146
|
const result = await executeMikrotikCommand2(`/user-manager limitation print${whereClause(filters)}`, ctx);
|
|
53741
55147
|
if (commandUnsupported(result))
|
|
53742
|
-
return
|
|
55148
|
+
return NOT_AVAILABLE2;
|
|
53743
55149
|
return isEmpty(result) ? "No User Manager limitations found matching the criteria." : `USER MANAGER LIMITATIONS:
|
|
53744
55150
|
|
|
53745
55151
|
${result}`;
|
|
@@ -53755,7 +55161,7 @@ ${result}`;
|
|
|
53755
55161
|
ctx.info(`Removing User Manager limitation: name=${a.name}`);
|
|
53756
55162
|
const count = await executeMikrotikCommand2(`/user-manager limitation print count-only where name="${a.name}"`, ctx);
|
|
53757
55163
|
if (commandUnsupported(count))
|
|
53758
|
-
return
|
|
55164
|
+
return NOT_AVAILABLE2;
|
|
53759
55165
|
if (count.trim() === "0")
|
|
53760
55166
|
return `User Manager limitation '${a.name}' not found.`;
|
|
53761
55167
|
const result = await executeMikrotikCommand2(`/user-manager limitation remove [find name="${a.name}"]`, ctx);
|
|
@@ -53782,7 +55188,7 @@ ${result}`;
|
|
|
53782
55188
|
filters.push("active=yes");
|
|
53783
55189
|
const result = await executeMikrotikCommand2(`/user-manager session print${whereClause(filters)}`, ctx);
|
|
53784
55190
|
if (commandUnsupported(result))
|
|
53785
|
-
return
|
|
55191
|
+
return NOT_AVAILABLE2;
|
|
53786
55192
|
return isEmpty(result) ? "No User Manager sessions found matching the criteria." : `USER MANAGER SESSIONS:
|
|
53787
55193
|
|
|
53788
55194
|
${result}`;
|
|
@@ -54216,33 +55622,281 @@ ${result}`;
|
|
|
54216
55622
|
})
|
|
54217
55623
|
];
|
|
54218
55624
|
|
|
55625
|
+
// src/core/vlan-guidance.ts
|
|
55626
|
+
var VLAN_GUIDE_URI = "mikrotik://knowledge/vlan-segmentation";
|
|
55627
|
+
var VLAN_GUIDE_VERSION = "2026-10-03";
|
|
55628
|
+
var VLAN_GUIDE_TOPICS = [
|
|
55629
|
+
"overview",
|
|
55630
|
+
"discovery",
|
|
55631
|
+
"layer2",
|
|
55632
|
+
"policy",
|
|
55633
|
+
"migration",
|
|
55634
|
+
"verification"
|
|
55635
|
+
];
|
|
55636
|
+
var sections2 = {
|
|
55637
|
+
overview: `## Intent and boundaries
|
|
55638
|
+
Use this guide for homelab VLAN segmentation, guest Wi-Fi, IoT isolation and
|
|
55639
|
+
management networks. It is reference knowledge, NOT observed device state or
|
|
55640
|
+
authorization. Start read-only; use find_tools and describe_tool for the tools
|
|
55641
|
+
actually exposed in this session. Never bypass read-only mode or module restrictions.
|
|
55642
|
+
|
|
55643
|
+
Adapt the homelab-vlan-segmentation design to the actual requirements. Illustrative
|
|
55644
|
+
roles/IDs are Trusted 10, IoT 20, Servers 30 (only if needed), Guest 40 and Management
|
|
55645
|
+
99. IDs are examples, not reservations or defaults to apply. Preserve working
|
|
55646
|
+
subnets where possible; check overlap with WAN, VPN, remote sites and other VLANs.
|
|
55647
|
+
Trusted users are not automatically administrators. Agree a source/destination/
|
|
55648
|
+
service allow matrix, including router management, before proposing changes.
|
|
55649
|
+
|
|
55650
|
+
VLAN sub-interfaces alone do not provide isolation. Layer-2 membership, routed
|
|
55651
|
+
IPv4/IPv6 policy and actual endpoint tests are separate requirements. A VPS/CHR
|
|
55652
|
+
used only as a routed tunnel endpoint may need routes/policy, not local VLANs.
|
|
55653
|
+
Do not extend a broadcast domain across a WAN without an explicit L2 requirement.
|
|
55654
|
+
Segmentation is not a promise of lower latency or higher tunnel throughput.`,
|
|
55655
|
+
discovery: `## Read-only discovery and evidence
|
|
55656
|
+
Resolve each router by its exact configured device name and verify identity,
|
|
55657
|
+
RouterOS version, board, switch chip and installed Wi-Fi package. Recall constraints
|
|
55658
|
+
separately for each device if Memory is enabled; inspect conflicts and omitted
|
|
55659
|
+
constraints. Recalled facts may be stale. Never copy one router's addresses to another.
|
|
55660
|
+
|
|
55661
|
+
Discover interfaces, bridge settings/ports/VLAN table, VLAN sub-interfaces, interface
|
|
55662
|
+
lists, IP addresses, DHCP pools/networks/leases, DNS, IPv6 addresses/prefix delegation,
|
|
55663
|
+
ND/RA, IPv4 AND IPv6 filter/raw/NAT/mangle rules, routes/routing tables/rules,
|
|
55664
|
+
WireGuard allowed-addresses, queues, Wi-Fi/CAPsMAN/SSID datapaths and management
|
|
55665
|
+
services/MAC discovery. Use bounded, filtered reads; report unsupported, incomplete
|
|
55666
|
+
or timed-out reads as unknown, never empty or safe. Do not fetch credentials.
|
|
55667
|
+
|
|
55668
|
+
Build a physical port map: peer device, WAN/LAN/trunk/access role, bridge, PVID,
|
|
55669
|
+
tagged/untagged membership, link rate, hardware offload and management dependency.
|
|
55670
|
+
Do not infer a port's role from ether1, a comment, or a link-down snapshot. Resolve
|
|
55671
|
+
conflicting labels with the operator. Verify external switch/AP VLAN capability
|
|
55672
|
+
and its management/native VLAN before planning a trunk. Inventory scripts, netwatch,
|
|
55673
|
+
interface lists, NAT, policy-routing and queues that depend on the old interfaces.
|
|
55674
|
+
Distinguish proven observations, intended policy and unverified assumptions.`,
|
|
55675
|
+
layer2: `## Layer 2, CPU access and Wi-Fi
|
|
55676
|
+
For a NEW bridge, stage with vlan-filtering=no. For an existing production bridge,
|
|
55677
|
+
do not turn filtering off to simplify a migration: that can remove isolation.
|
|
55678
|
+
Enable VLAN filtering LAST when the VLAN table, port admission, management path,
|
|
55679
|
+
gateway and recovery plan are ready. A bridge reset can interrupt the session.
|
|
55680
|
+
|
|
55681
|
+
A routed VLAN interface normally belongs on the bridge, not on a physical port
|
|
55682
|
+
already enslaved to it. Include the bridge/CPU as tagged for VLANs terminated on
|
|
55683
|
+
that bridge and verify effective current-tagged membership (RouterOS may create
|
|
55684
|
+
dynamic entries). Do not expose CPU membership on VLANs that need only switching.
|
|
55685
|
+
Creating /interface vlan does not configure /interface bridge vlan or access ports.
|
|
55686
|
+
|
|
55687
|
+
On access ports: one intended untagged VLAN, matching PVID, ingress-filtering and
|
|
55688
|
+
admit-only-untagged-and-priority-tagged where supported. PVID classifies untagged
|
|
55689
|
+
ingress; it is not a tagged-traffic allowlist. Do not combine multiple VLAN IDs in
|
|
55690
|
+
a VLAN-table row containing access ports. On tagged-only trunks: explicit allowed
|
|
55691
|
+
VLAN membership, ingress-filtering and admit-only-vlan-tagged. Model hybrid/native
|
|
55692
|
+
ports explicitly; inspect dynamic VLAN 1/CPU membership for accidental access.
|
|
55693
|
+
Never add a WAN/ONT port to a LAN bridge merely because an example uses that number.
|
|
55694
|
+
|
|
55695
|
+
Map each SSID to a verified VLAN at the AP as well as its uplink. Inspect wireless,
|
|
55696
|
+
wifiwave2 or wifi and CAPsMAN local/manager forwarding. wifi-qcom and wifi-qcom-ac
|
|
55697
|
+
are not interchangeable: qcom-ac needs the appropriate bridge/PVID design rather
|
|
55698
|
+
than blindly copying CAPsMAN datapath vlan-id. Verify package-specific support.
|
|
55699
|
+
Guest client isolation within one SSID/VLAN is separate from inter-VLAN firewalling.
|
|
55700
|
+
Do not enable bridge use-ip-firewall just to filter traffic already routed by the
|
|
55701
|
+
CPU; inspect hardware-offload support and measure the performance impact.`,
|
|
55702
|
+
policy: `## Dual-stack policy and remote-site dependencies
|
|
55703
|
+
Design INPUT (to the router) and FORWARD (through the router) separately for both
|
|
55704
|
+
IPv4 and IPv6. Limit administration to the approved management sources/VPNs; allow
|
|
55705
|
+
only required DHCP/DNS/NTP and essential ICMP/ICMPv6 functions on client segments.
|
|
55706
|
+
Preserve neighbor discovery, router advertisements where intended and path-MTU
|
|
55707
|
+
discovery. Do not solve isolation by indiscriminately blocking all ICMPv6.
|
|
55708
|
+
|
|
55709
|
+
Evaluate first-match rule order, jumps, broad LAN/!WAN accepts, established flows,
|
|
55710
|
+
FastTrack and existing final drops. Place exact service exceptions before segment
|
|
55711
|
+
denies, and denies before broad accepts they must constrain. Appended drop rules
|
|
55712
|
+
may never match. Use current stable .ids, not saved row numbers. Preserve unrelated
|
|
55713
|
+
protections and allowlists. RFC1918-only drops miss local public IPv4, VPN/remote
|
|
55714
|
+
networks and all IPv6; enumerate actual protected destinations. Default-deny between
|
|
55715
|
+
zones with explicit exceptions is a design goal, not permission to rewrite a firewall.
|
|
55716
|
+
|
|
55717
|
+
NAT is not isolation or a routing policy. Reuse valid existing NAT; any new source
|
|
55718
|
+
NAT must be scoped to the intended egress, never every destination. SNAT may hide
|
|
55719
|
+
VLAN source identities from a remote router, so enforce segmentation locally unless
|
|
55720
|
+
an explicitly designed routed/no-NAT topology preserves them. Add new subnets to
|
|
55721
|
+
VPN allowed-addresses, return routes and remote policies only when required.
|
|
55722
|
+
|
|
55723
|
+
Each IPv6 SLAAC segment needs its own non-overlapping /64 from a valid routed or
|
|
55724
|
+
delegated prefix; do not reuse one /64 on separate L2 domains. Verify upstream
|
|
55725
|
+
reachability and return routing, not just a local address. If unavailable, report
|
|
55726
|
+
IPv6 as unconfigured/blocked by prerequisites, not working or isolated by IPv4.
|
|
55727
|
+
|
|
55728
|
+
Move policy-routing/interface-list/queue/automation dependencies before retiring
|
|
55729
|
+
legacy interfaces. FastTrack only eligible main-table traffic; policy-routed,
|
|
55730
|
+
queued or accounted traffic needs appropriate exclusions. Moving FastTrack above
|
|
55731
|
+
an established accept can change behavior beyond VLANs; never do it blindly.`,
|
|
55732
|
+
migration: `## Safe rollout and planner limits
|
|
55733
|
+
Deliver: (1) observed topology and unknowns; (2) proposed VLAN/subnet/IPv6/SSID/port
|
|
55734
|
+
map; (3) explicit allow/deny service matrix; (4) exact ordered per-device changes;
|
|
55735
|
+
(5) prerequisites, rollback triggers and acceptance tests. Ask only for missing
|
|
55736
|
+
choices that affect connectivity or policy. Do not invent interface or subnet roles.
|
|
55737
|
+
|
|
55738
|
+
Before writes, obtain approval for the exact scope, capture a host-side snapshot
|
|
55739
|
+
and follow the local-backup requirements. Confirm an independent console, rescue
|
|
55740
|
+
port or verified management path that does not depend on the bridge being changed.
|
|
55741
|
+
Do not assume a VPN is independent: it may traverse that same bridge/uplink.
|
|
55742
|
+
Use owned Safe Mode for suitable single-router changes; coordinated multi-router
|
|
55743
|
+
writes should use the transaction workflow when available and suitable. Transaction
|
|
55744
|
+
verification stages REAL changes, not an offline preview. Safe Mode is not a backup
|
|
55745
|
+
or a guarantee for all operations; ambiguous timeouts are not permission to retry.
|
|
55746
|
+
Preserve the old management path until the new one has been tested. Canary one
|
|
55747
|
+
port/SSID/client, then migrate the remainder; never reconfigure all access at once.
|
|
55748
|
+
|
|
55749
|
+
design_network_segment is only partial IPv4 scaffolding, not a full isolation
|
|
55750
|
+
engine. It does not configure bridge port PVID/admission, enable VLAN filtering,
|
|
55751
|
+
map SSIDs, build router INPUT or IPv6 policy, prove rule reachability, preserve
|
|
55752
|
+
remote routing, or roll back a partial apply. NAT needs explicit wan_interface;
|
|
55753
|
+
isolation drops need a current reviewed isolation_before rule .id. Non-/24 DHCP
|
|
55754
|
+
needs an explicit valid pool. Discover schemas before previewing; apply only after
|
|
55755
|
+
the surrounding approved configuration satisfies these prerequisites. Do not call
|
|
55756
|
+
it repeatedly to finish a partially applied plan; read back and reconcile first.
|
|
55757
|
+
For a complete migration, prefer an explicit reviewed plan with separate steps.`,
|
|
55758
|
+
verification: `## Verification, reporting and clean memory
|
|
55759
|
+
Read back bridge VLAN current-tagged/current-untagged, PVID/admission, gateway IPs,
|
|
55760
|
+
DHCP and IPv6 ND/RA, rules and counters, routing tables and VPN return routes.
|
|
55761
|
+
Then test from real representative wired AND wireless clients in each segment:
|
|
55762
|
+
address/lease, DNS, gateway, required internet/VPN services, allowed local services,
|
|
55763
|
+
denied cross-zone services, denied router management and guest peer isolation if
|
|
55764
|
+
requested. Test IPv4 and IPv6 independently, with fresh connections; existing
|
|
55765
|
+
tracked/FastTracked flows can conceal new policy. Never flush all connections as
|
|
55766
|
+
an unapproved test. Router-originated ping does not prove client FORWARD policy.
|
|
55767
|
+
|
|
55768
|
+
Record expected vs observed per test, sample time, source, address family and
|
|
55769
|
+
remaining unknowns. If no endpoint is available, mark client isolation unverified.
|
|
55770
|
+
For performance claims, compare the same path/client/workload before and after:
|
|
55771
|
+
link speed, CPU/offload, throughput, latency and loss. Ask before disruptive loads.
|
|
55772
|
+
Commit only an authorized, verified change; uncertain connectivity requires stop,
|
|
55773
|
+
read-back and the agreed rollback/recovery path, not speculative cleanup.
|
|
55774
|
+
|
|
55775
|
+
Only after successful validation, review stale objects and all references before
|
|
55776
|
+
proposing removals. Disabled is not proof unused. Preserve unrelated tunnels,
|
|
55777
|
+
WAN failover, management allowlists and domain-routing exceptions.
|
|
55778
|
+
Memory: store exact VLAN maps, addresses and evidence on each Device with source,
|
|
55779
|
+
verification time and expiry. Use a dedicated Group policy with explicit members
|
|
55780
|
+
for site-wide rules; Shared is only for intentionally reusable safeguards. Do not
|
|
55781
|
+
promote a device entity or store secrets/raw exports. Memory never grants new
|
|
55782
|
+
permission; generic guidance does not prove live facts.`
|
|
55783
|
+
};
|
|
55784
|
+
var sources2 = `## Authoritative references
|
|
55785
|
+
- Bridge VLAN table: https://help.mikrotik.com/docs/spaces/ROS/pages/28606465/Bridge+VLAN+Table
|
|
55786
|
+
- Wi-Fi packages and CAPsMAN: https://help.mikrotik.com/docs/spaces/ROS/pages/224559120/WiFi
|
|
55787
|
+
- IPv4/IPv6 firewall: https://help.mikrotik.com/docs/spaces/ROS/pages/328513/Building+Advanced+Firewall
|
|
55788
|
+
- Packet flow and FastTrack: https://help.mikrotik.com/docs/spaces/ROS/pages/328227/Packet+Flow+in+RouterOS
|
|
55789
|
+
Verify version-specific behavior against the current official manual before applying.
|
|
55790
|
+
Adapted from the homelab-vlan-segmentation skill with RouterOS-specific safety gates.`;
|
|
55791
|
+
function getVlanSegmentationGuide(topic = "all") {
|
|
55792
|
+
const selected = topic === "all" ? VLAN_GUIDE_TOPICS : [topic];
|
|
55793
|
+
return [
|
|
55794
|
+
`# RouterOS VLAN segmentation knowledge
|
|
55795
|
+
Guide version: ${VLAN_GUIDE_VERSION}
|
|
55796
|
+
Reference only; no device inspection or changes.`,
|
|
55797
|
+
...selected.map((key) => sections2[key]),
|
|
55798
|
+
sources2
|
|
55799
|
+
].join(`
|
|
55800
|
+
|
|
55801
|
+
`);
|
|
55802
|
+
}
|
|
55803
|
+
var VLAN_INSTRUCTIONS = `VLAN segmentation knowledge:
|
|
55804
|
+
Before VLAN/guest/IoT/management-network work, read ${VLAN_GUIDE_URI}.
|
|
55805
|
+
Begin with read-only discovery; never infer port roles from names or example IDs.
|
|
55806
|
+
Protect the management path, stage VLAN membership/PVID/CPU access before enabling
|
|
55807
|
+
filtering, and check BOTH IPv4 and IPv6 INPUT/FORWARD policy and remote return routes.
|
|
55808
|
+
design_network_segment is partial IPv4 scaffolding, NOT a complete isolation plan.
|
|
55809
|
+
Use only available tools; an audit or this guide never authorizes router changes.
|
|
55810
|
+
Verified device facts belong to Device memory; reusable safeguards may be Shared
|
|
55811
|
+
only with explicit intent. Do not treat shared memory as a live VLAN map.`;
|
|
55812
|
+
function vlanPromptGuidance(name, body) {
|
|
55813
|
+
if (!["setup-vlan-network", "setup-guest-wifi", "audit-vlan-segmentation"].includes(name)) {
|
|
55814
|
+
return body;
|
|
55815
|
+
}
|
|
55816
|
+
return `${body}
|
|
55817
|
+
|
|
55818
|
+
${getVlanSegmentationGuide()}`;
|
|
55819
|
+
}
|
|
55820
|
+
|
|
54219
55821
|
// src/tools/vlan-designer.ts
|
|
55822
|
+
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.";
|
|
55823
|
+
var portList = (text) => [
|
|
55824
|
+
...new Set((text ?? "").split(",").map((p) => p.trim()).filter(Boolean))
|
|
55825
|
+
];
|
|
54220
55826
|
function defaultRange2(subnet) {
|
|
54221
55827
|
const o = subnet.split("/")[0].split(".");
|
|
54222
55828
|
return `${o[0]}.${o[1]}.${o[2]}.10-${o[0]}.${o[1]}.${o[2]}.254`;
|
|
54223
55829
|
}
|
|
54224
55830
|
var vlanDesignerTools = [
|
|
55831
|
+
defineTool2({
|
|
55832
|
+
name: "get_vlan_segmentation_guide",
|
|
55833
|
+
title: "Read VLAN Segmentation Knowledge",
|
|
55834
|
+
annotations: READ,
|
|
55835
|
+
noDevice: true,
|
|
55836
|
+
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.",
|
|
55837
|
+
inputSchema: {
|
|
55838
|
+
topic: _enum(["all", ...VLAN_GUIDE_TOPICS]).default("all")
|
|
55839
|
+
},
|
|
55840
|
+
handler: (a) => getVlanSegmentationGuide(a.topic)
|
|
55841
|
+
}),
|
|
54225
55842
|
defineTool2({
|
|
54226
55843
|
name: "design_network_segment",
|
|
54227
|
-
title: "
|
|
55844
|
+
title: "Preview or Build Partial IPv4 VLAN Scaffolding",
|
|
54228
55845
|
annotations: DANGEROUS,
|
|
54229
|
-
description: "
|
|
55846
|
+
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
55847
|
inputSchema: {
|
|
54231
55848
|
vlan_id: number().int().min(1).max(4094),
|
|
54232
55849
|
name: interfaceName("Name for the VLAN interface, e.g. 'guest'"),
|
|
54233
|
-
subnet:
|
|
54234
|
-
gateway:
|
|
55850
|
+
subnet: cidrv42().describe("Canonical IPv4 network CIDR, e.g. '192.168.30.0/24'"),
|
|
55851
|
+
gateway: ipv42().describe("Usable router address inside the subnet, excluded from the DHCP pool"),
|
|
54235
55852
|
bridge: string().default("bridge").describe("Bridge to put the VLAN on"),
|
|
54236
|
-
tagged_ports: string().optional().describe("Comma-separated
|
|
55853
|
+
tagged_ports: string().optional().describe("Comma-separated verified tagged ports; the bridge/CPU is included once automatically"),
|
|
54237
55854
|
untagged_ports: string().optional().describe("Comma-separated access/untagged ports"),
|
|
54238
55855
|
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
|
-
|
|
55856
|
+
dhcp_range: string().optional().describe("Single start-end IPv4 range excluding gateway/network/broadcast. Required outside /24; /24 defaults to .10\u2013.254"),
|
|
55857
|
+
internet: boolean().default(true).describe("Add egress-scoped IPv4 masquerade (requires wan_interface); not a firewall allow. Set false to reuse existing NAT"),
|
|
55858
|
+
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"),
|
|
55859
|
+
isolate_from: array(cidrv42()).optional().describe("Subnets this segment must NOT reach, e.g. ['192.168.1.0/24']"),
|
|
55860
|
+
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
55861
|
apply: boolean().default(false).describe("false = preview (default); true = build")
|
|
54243
55862
|
},
|
|
54244
55863
|
async handler(a, ctx) {
|
|
54245
|
-
const
|
|
55864
|
+
const subnet = parseCidr(a.subnet);
|
|
55865
|
+
const gateway = parseIp(a.gateway);
|
|
55866
|
+
if (!subnet || subnet.text !== a.subnet || subnet.prefix > 30 || gateway === null) {
|
|
55867
|
+
return "Error: use a canonical IPv4 network CIDR (/0\u2013/30) and valid gateway.";
|
|
55868
|
+
}
|
|
55869
|
+
const broadcast = subnet.network + 2 ** (32 - subnet.prefix) - 1;
|
|
55870
|
+
if (gateway <= subnet.network || gateway >= broadcast) {
|
|
55871
|
+
return "Error: gateway must be a usable host inside the segment subnet.";
|
|
55872
|
+
}
|
|
55873
|
+
if (a.internet && !a.wan_interface) {
|
|
55874
|
+
return "Error: internet=true requires wan_interface; unscoped masquerade is not safe. Set internet=false to reuse existing NAT.";
|
|
55875
|
+
}
|
|
55876
|
+
const isolate = [...new Set(a.isolate_from ?? [])];
|
|
55877
|
+
if (isolate.length && !a.isolation_before) {
|
|
55878
|
+
return "Error: isolate_from requires a reviewed isolation_before rule .id; blindly appending drops may not isolate anything.";
|
|
55879
|
+
}
|
|
55880
|
+
const tagged = portList(a.tagged_ports);
|
|
55881
|
+
const untagged = portList(a.untagged_ports);
|
|
55882
|
+
if (untagged.includes(a.bridge) || untagged.some((p) => tagged.includes(p))) {
|
|
55883
|
+
return "Error: this routed VLAN requires a tagged bridge/CPU and disjoint tagged/untagged ports.";
|
|
55884
|
+
}
|
|
55885
|
+
let range;
|
|
55886
|
+
if (a.dhcp) {
|
|
55887
|
+
if (!a.dhcp_range && subnet.prefix !== 24) {
|
|
55888
|
+
return "Error: non-/24 DHCP requires an explicit dhcp_range inside the subnet.";
|
|
55889
|
+
}
|
|
55890
|
+
const dhcpRange = a.dhcp_range ?? defaultRange2(a.subnet);
|
|
55891
|
+
range = dhcpRange;
|
|
55892
|
+
const parts = dhcpRange.split("-");
|
|
55893
|
+
const lo = parseIp(parts[0] ?? "");
|
|
55894
|
+
const hi = parseIp(parts[1] ?? "");
|
|
55895
|
+
if (parts.length !== 2 || lo === null || hi === null || lo > hi || lo <= subnet.network || hi >= broadcast || gateway >= lo && gateway <= hi) {
|
|
55896
|
+
return "Error: dhcp_range must be a single ordered start-end range inside the subnet, excluding network, broadcast and gateway.";
|
|
55897
|
+
}
|
|
55898
|
+
}
|
|
55899
|
+
const prefix = subnet.prefix;
|
|
54246
55900
|
const vlanIf = a.name;
|
|
54247
55901
|
const groups = [];
|
|
54248
55902
|
groups.push({
|
|
@@ -54252,11 +55906,11 @@ var vlanDesignerTools = [
|
|
|
54252
55906
|
new Cmd("/ip address add").set("address", `${a.gateway}/${prefix}`).set("interface", vlanIf).build()
|
|
54253
55907
|
]
|
|
54254
55908
|
});
|
|
54255
|
-
if (
|
|
55909
|
+
if (tagged.length || untagged.length) {
|
|
54256
55910
|
groups.push({
|
|
54257
55911
|
label: "Bridge VLAN tagging",
|
|
54258
55912
|
commands: [
|
|
54259
|
-
new Cmd("/interface bridge vlan add").set("bridge", a.bridge).set("vlan-ids", a.vlan_id).
|
|
55913
|
+
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
55914
|
]
|
|
54261
55915
|
});
|
|
54262
55916
|
}
|
|
@@ -54265,7 +55919,7 @@ var vlanDesignerTools = [
|
|
|
54265
55919
|
groups.push({
|
|
54266
55920
|
label: "DHCP server",
|
|
54267
55921
|
commands: [
|
|
54268
|
-
new Cmd("/ip pool add").set("name", pool).set("ranges",
|
|
55922
|
+
new Cmd("/ip pool add").set("name", pool).set("ranges", range).build(),
|
|
54269
55923
|
new Cmd("/ip dhcp-server add").set("name", `${a.name}-dhcp`).set("interface", vlanIf).set("address-pool", pool).set("disabled", "no").build(),
|
|
54270
55924
|
new Cmd("/ip dhcp-server network add").set("address", a.subnet).set("gateway", a.gateway).set("dns-server", a.gateway).build()
|
|
54271
55925
|
]
|
|
@@ -54275,15 +55929,14 @@ var vlanDesignerTools = [
|
|
|
54275
55929
|
groups.push({
|
|
54276
55930
|
label: "Internet (srcnat masquerade)",
|
|
54277
55931
|
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()
|
|
55932
|
+
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
55933
|
]
|
|
54280
55934
|
});
|
|
54281
55935
|
}
|
|
54282
|
-
const isolate = a.isolate_from ?? [];
|
|
54283
55936
|
if (isolate.length) {
|
|
54284
55937
|
groups.push({
|
|
54285
55938
|
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())
|
|
55939
|
+
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
55940
|
});
|
|
54288
55941
|
}
|
|
54289
55942
|
const all = groups.flatMap((g) => g.commands);
|
|
@@ -54293,20 +55946,37 @@ ${g.commands.map((c) => ` ${c}`).join(`
|
|
|
54293
55946
|
`)}`).join(`
|
|
54294
55947
|
|
|
54295
55948
|
`);
|
|
54296
|
-
return `DRY RUN \u2014 VLAN ${a.vlan_id} '${a.name}' (${a.subnet}); ${all.length} command(s)
|
|
55949
|
+
return `DRY RUN \u2014 VLAN ${a.vlan_id} '${a.name}' (${a.subnet}); ${all.length} command(s):
|
|
54297
55950
|
|
|
54298
|
-
${
|
|
55951
|
+
${COVERAGE}
|
|
55952
|
+
|
|
55953
|
+
${preview}
|
|
55954
|
+
|
|
55955
|
+
Apply only within the complete approved migration plan.`;
|
|
55956
|
+
}
|
|
55957
|
+
if (isolate.length) {
|
|
55958
|
+
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);
|
|
55959
|
+
if (anchor.trim() !== "1")
|
|
55960
|
+
return "Error: isolation_before is not a unique enabled forward rule. No changes applied; read rules again.";
|
|
54299
55961
|
}
|
|
54300
55962
|
const done = [];
|
|
54301
55963
|
for (const cmd of all) {
|
|
54302
|
-
|
|
55964
|
+
let result;
|
|
55965
|
+
try {
|
|
55966
|
+
result = await executeMikrotikCommand2(cmd, ctx);
|
|
55967
|
+
} catch (error) {
|
|
55968
|
+
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.
|
|
55969
|
+
${COVERAGE}`;
|
|
55970
|
+
}
|
|
54303
55971
|
if (looksLikeError(result)) {
|
|
54304
55972
|
return `Built ${done.length}/${all.length} commands, then FAILED: ${result}
|
|
54305
|
-
Review partial segment (the VLAN may exist without DHCP/firewall)
|
|
55973
|
+
Review partial segment (the VLAN may exist without DHCP/firewall). Do not retry blindly.
|
|
55974
|
+
${COVERAGE}`;
|
|
54306
55975
|
}
|
|
54307
55976
|
done.push(cmd);
|
|
54308
55977
|
}
|
|
54309
|
-
return `
|
|
55978
|
+
return `IPv4 scaffold '${a.name}' (id ${a.vlan_id}, ${a.subnet}): ${done.length} command(s) completed. Isolation and connectivity are UNVERIFIED.
|
|
55979
|
+
${COVERAGE}`;
|
|
54310
55980
|
}
|
|
54311
55981
|
})
|
|
54312
55982
|
];
|
|
@@ -54319,7 +55989,7 @@ var vlanTools = [
|
|
|
54319
55989
|
name: "create_vlan_interface",
|
|
54320
55990
|
title: "Create VLAN Interface",
|
|
54321
55991
|
annotations: WRITE,
|
|
54322
|
-
description: "Creates an 802.1Q VLAN sub-interface (`/interface vlan`) on a specified parent physical or bridge interface." + "
|
|
55992
|
+
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
55993
|
inputSchema: {
|
|
54324
55994
|
name: interfaceName("Name for the new VLAN interface, e.g. 'vlan100'"),
|
|
54325
55995
|
vlan_id: number().int().min(1).max(4094).describe("802.1Q VLAN ID (1-4094)"),
|
|
@@ -56847,6 +58517,27 @@ var moduleCatalog2 = [
|
|
|
56847
58517
|
description: "Administrator-approved DNS/TCP/TLS/HTTPS service checks, immutable contracts, history and fail-closed rollout gates with explicit MCP-host perspective.",
|
|
56848
58518
|
tools: serviceContractTools
|
|
56849
58519
|
},
|
|
58520
|
+
{
|
|
58521
|
+
label: "Service Routing",
|
|
58522
|
+
slug: "service-routing",
|
|
58523
|
+
group: "System & Ops",
|
|
58524
|
+
description: "Scoped dual-stack domain policies, router VRF service probes and explicitly authorized failover.",
|
|
58525
|
+
tools: serviceRoutingTools
|
|
58526
|
+
},
|
|
58527
|
+
{
|
|
58528
|
+
label: "Network Flight Recorder",
|
|
58529
|
+
slug: "flight-recorder",
|
|
58530
|
+
group: "System & Ops",
|
|
58531
|
+
description: "Durable bounded pre/post-incident telemetry, off-router log metadata and MCP change correlation.",
|
|
58532
|
+
tools: flightRecorderTools
|
|
58533
|
+
},
|
|
58534
|
+
{
|
|
58535
|
+
label: "Recovery Lab",
|
|
58536
|
+
slug: "recovery-lab",
|
|
58537
|
+
group: "System & Ops",
|
|
58538
|
+
description: "Isolated CHR rehearsal orchestration with immutable snapshot subsets, coverage and verified runner evidence.",
|
|
58539
|
+
tools: recoveryLabTools
|
|
58540
|
+
},
|
|
56850
58541
|
{
|
|
56851
58542
|
label: "Client Investigations",
|
|
56852
58543
|
slug: "investigations",
|
|
@@ -56921,7 +58612,7 @@ var moduleCatalog2 = [
|
|
|
56921
58612
|
label: "VLAN Designer",
|
|
56922
58613
|
slug: "vlan-designer",
|
|
56923
58614
|
group: "Interfaces",
|
|
56924
|
-
description: "
|
|
58615
|
+
description: "Read VLAN design/safety knowledge and preview partial IPv4 scaffolding; full L2, dual-stack " + "isolation and client verification remain explicit migration work.",
|
|
56925
58616
|
tools: vlanDesignerTools
|
|
56926
58617
|
},
|
|
56927
58618
|
{
|
|
@@ -57782,7 +59473,7 @@ var moduleCatalog2 = [
|
|
|
57782
59473
|
label: "Containers",
|
|
57783
59474
|
slug: "container",
|
|
57784
59475
|
group: "System & Ops",
|
|
57785
|
-
description: "
|
|
59476
|
+
description: "Shared container safety knowledge and exact-target OCI lifecycle (`/container`), global config " + "(registry/tmpdir/RAM), named env lists, and volume mounts.",
|
|
57786
59477
|
tools: containerTools
|
|
57787
59478
|
},
|
|
57788
59479
|
{
|
|
@@ -57864,4 +59555,4 @@ function selectToolModules2(filter = {}, catalog = moduleCatalog2) {
|
|
|
57864
59555
|
}).map((m) => m.tools);
|
|
57865
59556
|
}
|
|
57866
59557
|
|
|
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 };
|
|
59558
|
+
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 };
|