@usex/mikrotik-mcp 5.20.0 → 5.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -5
- package/dist/cli.js +748 -97
- package/dist/index.js +1 -1
- package/dist/shared/{library-81amv3az.js → library-588vnctn.js} +1 -1
- package/dist/shared/{library-73y8qdjr.js → library-6tvh3gq1.js} +645 -44
- package/dist/shared/{library-76naf20r.js → library-g8far2nz.js} +1 -1
- package/dist/shared/{library-y9tt30y1.js → library-k6m2bxjr.js} +1 -1
- package/dist/shared/{library-krajvnj9.js → library-wj2xfx8h.js} +1 -1
- package/dist/ui/observability.html +64 -62
- package/package.json +3 -2
- package/schemas/README.md +1 -1
- package/schemas/devtools-manifest.json +41 -1
- package/schemas/tool-catalog.json +122 -9
- package/schemas/tools/create_service_routing.json +16 -3
- package/schemas/tools/disconnect_ovpn_session.json +20 -0
- package/schemas/tools/list_ovpn_sessions.json +7 -0
- package/schemas/tools/service_routing_address_page.json +19 -0
- package/schemas/tools/service_routing_traffic.json +14 -0
- /package/dist/shared/{cli-426pkqe9.js → cli-h065ap70.js} +0 -0
- /package/dist/shared/{cli-cvt06346.js → cli-se3tgt7t.js} +0 -0
- /package/dist/shared/{cli-6wdstvdq.js → cli-t311px0m.js} +0 -0
- /package/dist/shared/{cli-z1kavk0z.js → cli-wf9a7qjm.js} +0 -0
package/dist/cli.js
CHANGED
|
@@ -21892,13 +21892,13 @@ async function undoMigration(id, confirm, selected) {
|
|
|
21892
21892
|
throw new Error("Undo lost Safe Mode or exceeded its time budget.");
|
|
21893
21893
|
await checkedRead(item.undo, createContext(undefined, device));
|
|
21894
21894
|
}
|
|
21895
|
-
const beforeTarget = (await import("./shared/cli-
|
|
21896
|
-
const db = await beforeTarget((await import("./shared/cli-
|
|
21895
|
+
const beforeTarget = (await import("./shared/cli-se3tgt7t.js")).openSnapshotStore;
|
|
21896
|
+
const db = await beforeTarget((await import("./shared/cli-h065ap70.js")).DEFAULT_SNAPSHOT_DB);
|
|
21897
21897
|
try {
|
|
21898
21898
|
const original = db.get(p.snapshots.target);
|
|
21899
21899
|
if (!original)
|
|
21900
21900
|
throw new Error("Original target snapshot unavailable.");
|
|
21901
|
-
const { normalizeExport } = await import("./shared/cli-
|
|
21901
|
+
const { normalizeExport } = await import("./shared/cli-wf9a7qjm.js");
|
|
21902
21902
|
if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
|
|
21903
21903
|
throw new Error("Target differs from its backup. Undo verification failed.");
|
|
21904
21904
|
} finally {
|
|
@@ -26897,10 +26897,43 @@ var serviceContractTools = [
|
|
|
26897
26897
|
// src/service-routing/model.ts
|
|
26898
26898
|
import ipaddr2 from "ipaddr.js";
|
|
26899
26899
|
import { createHash as createHash5 } from "crypto";
|
|
26900
|
+
|
|
26901
|
+
// src/service-routing/domain.ts
|
|
26902
|
+
var routingDomain = string2().trim().toLowerCase().max(253).refine((value) => {
|
|
26903
|
+
const base = value.startsWith("*.") ? value.slice(2) : value;
|
|
26904
|
+
const labels = base.split(".");
|
|
26905
|
+
return labels.length >= 2 && !/^\d+(?:\.\d+){3}$/.test(base) && labels.every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) && !/^\d+$/.test(labels.at(-1));
|
|
26906
|
+
}, "Enter a domain such as api.example.com or *.example.com; no URL, port, path or other wildcard.");
|
|
26907
|
+
var isWildcard = (domain) => domain.startsWith("*.");
|
|
26908
|
+
function domainMatches(domain, host) {
|
|
26909
|
+
const candidate = host.toLowerCase();
|
|
26910
|
+
return isWildcard(domain) ? candidate.endsWith(domain.slice(1)) && candidate.length > domain.length - 1 : candidate === domain;
|
|
26911
|
+
}
|
|
26912
|
+
function wildcardRegexp(domain) {
|
|
26913
|
+
const checked = routingDomain.parse(domain);
|
|
26914
|
+
if (!isWildcard(checked))
|
|
26915
|
+
throw new Error("A wildcard domain is required.");
|
|
26916
|
+
return `^([a-z0-9-]+[.])+${checked.slice(2).replaceAll(".", "[.]")}$`;
|
|
26917
|
+
}
|
|
26918
|
+
function wildcardRegexOverlaps(regexp, domain) {
|
|
26919
|
+
const prefix = "^([a-z0-9-]+[.])+";
|
|
26920
|
+
if (!regexp.startsWith(prefix) || !regexp.endsWith("$"))
|
|
26921
|
+
return true;
|
|
26922
|
+
const base = regexp.slice(prefix.length, -1).replaceAll("[.]", ".");
|
|
26923
|
+
if (!routingDomain.safeParse(base).success || wildcardRegexp(`*.${base}`) !== regexp)
|
|
26924
|
+
return true;
|
|
26925
|
+
const candidate = domain.slice(2);
|
|
26926
|
+
return candidate === base || candidate.endsWith(`.${base}`) || base.endsWith(`.${candidate}`);
|
|
26927
|
+
}
|
|
26928
|
+
|
|
26929
|
+
// src/service-routing/model.ts
|
|
26900
26930
|
var name2 = string2().trim().min(1).max(64).regex(/^[a-zA-Z0-9_.-]+$/);
|
|
26901
26931
|
var routingInput = object({
|
|
26902
26932
|
name: string2().trim().min(1).max(80),
|
|
26903
|
-
target: name2.describe("
|
|
26933
|
+
target: name2.optional().describe("Optional approved HTTPS probe alias; legacy drafts without domain route this alias's exact host"),
|
|
26934
|
+
domain: routingDomain.optional().describe("Exact domain or *.example.com (subdomains only, not the apex). Wildcards need client DNS through this router."),
|
|
26935
|
+
dnsLearningConfirmed: boolean2().optional().describe("For wildcard only: confirms clients use this router DNS, shared-IP scope and FWD adlist bypass are understood. Does not enable or intercept DNS."),
|
|
26936
|
+
precedence: _enum(["before-existing"]).optional().describe("Explicitly allow this scoped policy before existing routing rules. Preview still binds their full configuration; FastTrack is never bypassed."),
|
|
26904
26937
|
family: _enum(["ipv4", "ipv6"]),
|
|
26905
26938
|
sources: array(string2().refine((v) => ipaddr2.isValidCIDR(v), "Use an explicit client subnet CIDR")).min(1).max(8),
|
|
26906
26939
|
tables: array(name2).min(1).max(3),
|
|
@@ -26909,6 +26942,13 @@ var routingInput = object({
|
|
|
26909
26942
|
failuresBeforeSwitch: number2().int().min(2).max(10).default(3),
|
|
26910
26943
|
cooldownSeconds: number2().int().min(120).max(3600).default(300)
|
|
26911
26944
|
}).superRefine((v, ctx) => {
|
|
26945
|
+
if (!v.domain && !v.target)
|
|
26946
|
+
ctx.addIssue({ code: "custom", message: "Enter a domain or choose an approved service" });
|
|
26947
|
+
if (v.domain && isWildcard(v.domain) && !v.dnsLearningConfirmed)
|
|
26948
|
+
ctx.addIssue({
|
|
26949
|
+
code: "custom",
|
|
26950
|
+
message: "Confirm client DNS learning and its limitations for wildcard routing"
|
|
26951
|
+
});
|
|
26912
26952
|
if (!v.tables.includes(v.primary) || new Set(v.tables).size !== v.tables.length)
|
|
26913
26953
|
ctx.addIssue({ code: "custom", message: "Choose one unique candidate table as primary" });
|
|
26914
26954
|
for (const s of v.sources) {
|
|
@@ -26925,13 +26965,21 @@ var ownerTag = (id) => `mcp-sr-${id}`;
|
|
|
26925
26965
|
var selector = (tag) => `[find where comment=${quoteValue(tag)}]`;
|
|
26926
26966
|
var routingPath = (family) => family === "ipv4" ? "/ip firewall" : "/ipv6 firewall";
|
|
26927
26967
|
function fingerprint(facts) {
|
|
26928
|
-
return createHash5("sha256").update(JSON.stringify(
|
|
26968
|
+
return createHash5("sha256").update(JSON.stringify({
|
|
26969
|
+
...facts,
|
|
26970
|
+
addresses: facts.addresses.filter((r) => !(r.list?.startsWith("mcp-sr-") && r.list.endsWith("-dst") && (["yes", "true"].includes(r.dynamic) || (r.flags ?? "").includes("D"))))
|
|
26971
|
+
}, (key, value) => ["#", ".id", "bytes", "packets", "last-handshake", "expires-after"].includes(key) ? undefined : value)).digest("hex");
|
|
26929
26972
|
}
|
|
26930
26973
|
function planCommands(policy, table, facts, remove = false) {
|
|
26931
26974
|
const path = routingPath(policy.family), tag = ownerTag(policy.id), chain = `sr-${policy.id.slice(0, 12)}`;
|
|
26932
26975
|
if (policy.state === "uncertain")
|
|
26933
26976
|
throw new Error("Reconcile uncertain router state before another change.");
|
|
26934
26977
|
const owned = facts.mangle.filter((r) => r.comment === tag);
|
|
26978
|
+
const wildcard = isWildcard(policy.host);
|
|
26979
|
+
const dns = facts.dns ?? [];
|
|
26980
|
+
const ownedDns = dns.filter((r) => r.comment === tag);
|
|
26981
|
+
if (wildcard && dns.some((r) => r["address-list"] === `${tag}-dst` && r.comment !== tag))
|
|
26982
|
+
throw new Error("A foreign DNS entry uses the owned destination list; reconcile first.");
|
|
26935
26983
|
if (facts.mangle.some((r) => r.chain === chain && r.comment !== tag))
|
|
26936
26984
|
throw new Error("Private chain contains foreign rules; review it first.");
|
|
26937
26985
|
if (owned.some((r) => r.chain !== chain && r.chain !== "prerouting"))
|
|
@@ -26939,14 +26987,33 @@ function planCommands(policy, table, facts, remove = false) {
|
|
|
26939
26987
|
if (remove)
|
|
26940
26988
|
return [
|
|
26941
26989
|
new Cmd(`${path} mangle remove ${selector(tag)}`).build(),
|
|
26942
|
-
new Cmd(`${path} address-list remove ${selector(tag)}`).build()
|
|
26990
|
+
new Cmd(`${path} address-list remove ${selector(tag)}`).build(),
|
|
26991
|
+
...wildcard ? [
|
|
26992
|
+
new Cmd(`/ip dns static remove ${selector(tag)}`).build(),
|
|
26993
|
+
...["/ip firewall", "/ipv6 firewall"].map((base) => new Cmd(`${base} address-list remove [find where list=${quoteValue(`${tag}-dst`)} dynamic=yes]`).build())
|
|
26994
|
+
] : []
|
|
26943
26995
|
];
|
|
26996
|
+
if (wildcard) {
|
|
26997
|
+
const version = /^(\d+)\.(\d+)(?:\.(\d+))?(?:\s|$)/.exec(facts.version ?? "");
|
|
26998
|
+
if (!version || Number(version[1]) < 7 || Number(version[1]) === 7 && Number(version[2]) < 17)
|
|
26999
|
+
throw new Error("Wildcard workflow requires stable RouterOS 7.17 or newer; version could not be verified.");
|
|
27000
|
+
if (!facts.dnsRemoteRequests || !policy.dnsLearningConfirmed)
|
|
27001
|
+
throw new Error("Wildcard routing needs confirmed client DNS through this router and allow-remote-requests already enabled. MCP will not expose DNS automatically.");
|
|
27002
|
+
const base = policy.host.slice(2);
|
|
27003
|
+
if (dns.some((r) => enabled3(r) && r.comment !== tag && (r.regexp && wildcardRegexOverlaps(r.regexp, policy.host) || r.name === base || r.name?.endsWith(`.${base}`) || ["yes", "true"].includes(r["match-subdomain"]) && base.endsWith(`.${r.name}`))))
|
|
27004
|
+
throw new Error("Existing DNS entries may overlap this wildcard. Review them first; MCP will not replace them.");
|
|
27005
|
+
if (owned.length) {
|
|
27006
|
+
if (ownedDns.length !== 1 || !enabled3(ownedDns[0]) || ownedDns[0].type !== "FWD" || ownedDns[0].regexp !== wildcardRegexp(policy.host) || ownedDns[0]["address-list"] !== `${tag}-dst` || ownedDns[0]["forward-to"] || ownedDns[0].name)
|
|
27007
|
+
throw new Error("Owned DNS learning scope changed externally.");
|
|
27008
|
+
} else if (ownedDns.length)
|
|
27009
|
+
throw new Error("Owned DNS entry is partially present; reconcile first.");
|
|
27010
|
+
}
|
|
26944
27011
|
const listRows = facts.addresses.filter((r) => [`${tag}-src`, `${tag}-dst`].includes(r.list));
|
|
26945
27012
|
const staticRows = listRows.filter((r) => !["yes", "true"].includes(r.dynamic) && !(r.flags ?? "").includes("D"));
|
|
26946
27013
|
if (owned.length) {
|
|
26947
27014
|
const expectedLists = [
|
|
26948
27015
|
...policy.sources.map((address) => ({ list: `${tag}-src`, address })),
|
|
26949
|
-
{ list: `${tag}-dst`, address: policy.host }
|
|
27016
|
+
...!wildcard ? [{ list: `${tag}-dst`, address: policy.host }] : []
|
|
26950
27017
|
];
|
|
26951
27018
|
if (staticRows.length !== expectedLists.length || expectedLists.some((e) => !staticRows.some((r) => r.list === e.list && r.address === e.address && r.comment === tag && enabled3(r))))
|
|
26952
27019
|
throw new Error("Owned address-list scope changed externally.");
|
|
@@ -26960,11 +27027,11 @@ function planCommands(policy, table, facts, remove = false) {
|
|
|
26960
27027
|
if (!facts.tables.some((r) => r.name === table && enabled3(r) && ["yes", "true"].includes(r.fib)))
|
|
26961
27028
|
throw new Error("Exit needs an existing enabled FIB table.");
|
|
26962
27029
|
const dst = policy.family === "ipv4" ? "0.0.0.0/0" : "::/0";
|
|
26963
|
-
if (!facts.routes.some((r) => r["routing-table"] === table && r["dst-address"] === dst && enabled3(r) && (["yes", "true"].includes(r.active) || (r.flags ?? "").includes("A"))))
|
|
26964
|
-
throw new Error("Exit has no observed active default route for this family.");
|
|
27030
|
+
if (!facts.routes.some((r) => r["routing-table"] === table && r["dst-address"] === dst && !!r.gateway && r.blackhole !== "yes" && r.blackhole !== "true" && !["blackhole", "unreachable", "prohibit"].includes(r.type) && enabled3(r) && (["yes", "true"].includes(r.active) || (r.flags ?? "").includes("A"))))
|
|
27031
|
+
throw new Error("Exit has no observed active forwarding default route for this family (discard routes are not exits).");
|
|
26965
27032
|
if (facts.filters.some((r) => enabled3(r) && r.action === "fasttrack-connection"))
|
|
26966
27033
|
throw new Error("FastTrack may bypass this policy. Configure an explicit exclusion before applying.");
|
|
26967
|
-
if (facts.mangle.some((r) => enabled3(r) && r.comment !== tag && ["mark-routing", "jump", "route"].includes(r.action)))
|
|
27034
|
+
if (policy.precedence !== "before-existing" && facts.mangle.some((r) => enabled3(r) && r.comment !== tag && ["mark-routing", "jump", "route"].includes(r.action)))
|
|
26968
27035
|
throw new Error("Existing routing/jump rules need an administrator conflict review. They will not be overridden.");
|
|
26969
27036
|
const result = [];
|
|
26970
27037
|
if (owned.length) {
|
|
@@ -26973,7 +27040,8 @@ function planCommands(policy, table, facts, remove = false) {
|
|
|
26973
27040
|
const expected = planCommands({ ...policy, state: "draft" }, policy.activeTable, {
|
|
26974
27041
|
...facts,
|
|
26975
27042
|
mangle: facts.mangle.filter((r) => r.comment !== tag),
|
|
26976
|
-
addresses: facts.addresses.filter((r) => ![`${tag}-src`, `${tag}-dst`].includes(r.list))
|
|
27043
|
+
addresses: facts.addresses.filter((r) => ![`${tag}-src`, `${tag}-dst`].includes(r.list)),
|
|
27044
|
+
dns: facts.dns?.filter((r) => r.comment !== tag)
|
|
26977
27045
|
}).filter((command) => command.startsWith(`${path} mangle add`)).map((command) => parseRecords(`0 ${command}`).rows[0]);
|
|
26978
27046
|
if (owned.length !== expected.length || expected.some((e) => !e || !owned.some((r) => Object.entries(e).filter(([key]) => !["place-before", "#"].includes(key)).every(([key, value]) => r[key] === value) && enabled3(r))))
|
|
26979
27047
|
throw new Error("Owned rule scope changed externally. Automatic edits are blocked.");
|
|
@@ -26984,7 +27052,10 @@ function planCommands(policy, table, facts, remove = false) {
|
|
|
26984
27052
|
}
|
|
26985
27053
|
for (const address of policy.sources)
|
|
26986
27054
|
result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-src`).set("address", address).set("comment", tag).build());
|
|
26987
|
-
|
|
27055
|
+
if (wildcard)
|
|
27056
|
+
result.push(new Cmd("/ip dns static add").set("type", "FWD").set("regexp", wildcardRegexp(policy.host)).set("address-list", `${tag}-dst`).bool("disabled", false).set("comment", tag).build());
|
|
27057
|
+
else
|
|
27058
|
+
result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-dst`).set("address", policy.host).set("comment", tag).build());
|
|
26988
27059
|
const exclude = policy.family === "ipv4" ? [
|
|
26989
27060
|
"0.0.0.0/8",
|
|
26990
27061
|
"10.0.0.0/8",
|
|
@@ -27015,6 +27086,172 @@ function chooseExit(policy, now) {
|
|
|
27015
27086
|
import { randomUUID as randomUUID8 } from "crypto";
|
|
27016
27087
|
import { isIP as isIP4 } from "net";
|
|
27017
27088
|
|
|
27089
|
+
// src/service-routing/read.ts
|
|
27090
|
+
var paths = new Set([
|
|
27091
|
+
"/ip dns static",
|
|
27092
|
+
"/routing table",
|
|
27093
|
+
"/routing rule",
|
|
27094
|
+
"/ip route",
|
|
27095
|
+
"/ipv6 route",
|
|
27096
|
+
"/ip vrf",
|
|
27097
|
+
"/ip firewall mangle",
|
|
27098
|
+
"/ipv6 firewall mangle",
|
|
27099
|
+
"/ip firewall filter",
|
|
27100
|
+
"/ipv6 firewall filter",
|
|
27101
|
+
"/ip firewall address-list",
|
|
27102
|
+
"/ipv6 firewall address-list"
|
|
27103
|
+
]);
|
|
27104
|
+
var ROUTING_ROW_LIMIT = 2000;
|
|
27105
|
+
function routingReadCommand(path, lists) {
|
|
27106
|
+
if (!paths.has(path))
|
|
27107
|
+
throw new Error("Unsupported routing inventory section.");
|
|
27108
|
+
const where = lists?.length ? `where ${lists.map((list) => `list=${quoteValue(list)}`).join(" or ")}` : "";
|
|
27109
|
+
const find = new Cmd(`${path} find`).raw(where).build();
|
|
27110
|
+
const print = new Cmd(`${path} print`).raw("detail as-value").raw(where).build();
|
|
27111
|
+
return `:if ([:len [${find}]] > ${ROUTING_ROW_LIMIT}) do={:put "MCP_ROUTING_ROW_LIMIT"} else={:put [:serialize to=json value=[${print}]]}`;
|
|
27112
|
+
}
|
|
27113
|
+
function parseRoutingRows(raw, fields) {
|
|
27114
|
+
if (raw.length > 1048576)
|
|
27115
|
+
throw new Error("Routing section exceeds the 1 MiB read limit.");
|
|
27116
|
+
if (raw.trim() === "MCP_ROUTING_ROW_LIMIT")
|
|
27117
|
+
throw new Error(`More than ${ROUTING_ROW_LIMIT} entries: this section was not loaded to protect the router. Use a filtered RouterOS read; the other routing sections are independent.`);
|
|
27118
|
+
if (looksLikeError(raw))
|
|
27119
|
+
throw new Error("Router rejected this read; check connectivity, permissions and RouterOS v7 support.");
|
|
27120
|
+
let data;
|
|
27121
|
+
try {
|
|
27122
|
+
data = JSON.parse(raw.trim());
|
|
27123
|
+
} catch {
|
|
27124
|
+
throw new Error("Router did not return valid structured routing data; no rows were accepted.");
|
|
27125
|
+
}
|
|
27126
|
+
if (!Array.isArray(data) || data.length > ROUTING_ROW_LIMIT || data.some((r) => !r || typeof r !== "object" || Array.isArray(r)))
|
|
27127
|
+
throw new Error("Router returned an incomplete or invalid routing section.");
|
|
27128
|
+
const keys = fields ? new Set(["#", ".id", "flags", ...fields.split(",")]) : undefined;
|
|
27129
|
+
return data.map((record, index) => {
|
|
27130
|
+
const row = { "#": String(index) };
|
|
27131
|
+
for (const [key, value] of Object.entries(record)) {
|
|
27132
|
+
if (keys && !keys.has(key))
|
|
27133
|
+
continue;
|
|
27134
|
+
if (typeof value === "boolean")
|
|
27135
|
+
row[key] = value ? "yes" : "no";
|
|
27136
|
+
else if (typeof value === "string" || typeof value === "number")
|
|
27137
|
+
row[key] = String(value);
|
|
27138
|
+
else if (Array.isArray(value) && value.every((v) => ["string", "number"].includes(typeof v)))
|
|
27139
|
+
row[key] = value.join(",");
|
|
27140
|
+
}
|
|
27141
|
+
return row;
|
|
27142
|
+
});
|
|
27143
|
+
}
|
|
27144
|
+
async function readRoutingRows(path, fields, ctx, lists) {
|
|
27145
|
+
const raw = await executeMikrotikCommand(routingReadCommand(path, lists), ctx, { maxMs: 6000 });
|
|
27146
|
+
return parseRoutingRows(raw, fields);
|
|
27147
|
+
}
|
|
27148
|
+
async function readRoutingAddressPage(path, ctx, offset = 0) {
|
|
27149
|
+
if (!["/ip firewall address-list", "/ipv6 firewall address-list"].includes(path) || !Number.isSafeInteger(offset) || offset < 0 || offset > 1e6)
|
|
27150
|
+
throw new Error("Invalid address-list page.");
|
|
27151
|
+
const find = new Cmd(`${path} find`).build();
|
|
27152
|
+
const get = new Cmd(`${path} get`).raw("$srId").build();
|
|
27153
|
+
const command = `{ :local srIds [${find}]; :local srItems [:toarray ""]; :foreach srId in=[:pick $srIds ${offset} ${offset + 200}] do={ :local srRow [${get}]; :set ($srRow->".id") $srId; :set ($srItems->[:len $srItems]) $srRow; }; :put [:serialize to=json value={"rows"=$srItems;"total"=[:len $srIds]}]; }`;
|
|
27154
|
+
const raw = await executeMikrotikCommand(command, ctx, { maxMs: 6000 });
|
|
27155
|
+
return parseRoutingAddressPage(raw, offset);
|
|
27156
|
+
}
|
|
27157
|
+
function parseRoutingAddressPage(raw, offset = 0) {
|
|
27158
|
+
if (looksLikeError(raw) || raw.length > 1048576)
|
|
27159
|
+
throw new Error("Address-list page could not be read safely.");
|
|
27160
|
+
let data;
|
|
27161
|
+
try {
|
|
27162
|
+
data = JSON.parse(raw.trim());
|
|
27163
|
+
} catch {
|
|
27164
|
+
throw new Error("Invalid structured address-list page.");
|
|
27165
|
+
}
|
|
27166
|
+
if (!data || !Array.isArray(data.rows) || !Number.isSafeInteger(data.total) || data.total < 0)
|
|
27167
|
+
throw new Error("Invalid address-list total.");
|
|
27168
|
+
const rows = parseRoutingRows(JSON.stringify(data.rows)).map((r, i) => ({
|
|
27169
|
+
...r,
|
|
27170
|
+
"#": String(offset + i)
|
|
27171
|
+
}));
|
|
27172
|
+
if (rows.length !== Math.min(200, Math.max(0, data.total - offset)) || rows.some((r) => !r[".id"]))
|
|
27173
|
+
throw new Error("Incomplete address-list page. Refresh if the router list changed while reading.");
|
|
27174
|
+
return {
|
|
27175
|
+
rows,
|
|
27176
|
+
total: data.total,
|
|
27177
|
+
nextOffset: offset + rows.length < data.total ? offset + rows.length : undefined
|
|
27178
|
+
};
|
|
27179
|
+
}
|
|
27180
|
+
|
|
27181
|
+
// src/service-routing/inventory.ts
|
|
27182
|
+
var routingSections = {
|
|
27183
|
+
tables: "/routing table",
|
|
27184
|
+
routes4: "/ip route",
|
|
27185
|
+
routes6: "/ipv6 route",
|
|
27186
|
+
mangle4: "/ip firewall mangle",
|
|
27187
|
+
mangle6: "/ipv6 firewall mangle",
|
|
27188
|
+
rules: "/routing rule",
|
|
27189
|
+
addresses4: "/ip firewall address-list",
|
|
27190
|
+
addresses6: "/ipv6 firewall address-list",
|
|
27191
|
+
vrfs: "/ip vrf",
|
|
27192
|
+
filters4: "/ip firewall filter",
|
|
27193
|
+
filters6: "/ipv6 firewall filter"
|
|
27194
|
+
};
|
|
27195
|
+
function createRoutingInventoryReader(read = readRoutingRows, addresses = readRoutingAddressPage) {
|
|
27196
|
+
const cache = new Map;
|
|
27197
|
+
const pending = new Map;
|
|
27198
|
+
let generation = 0;
|
|
27199
|
+
return {
|
|
27200
|
+
clear() {
|
|
27201
|
+
generation++;
|
|
27202
|
+
cache.clear();
|
|
27203
|
+
pending.clear();
|
|
27204
|
+
},
|
|
27205
|
+
async read(device, ctx) {
|
|
27206
|
+
const hit = cache.get(device);
|
|
27207
|
+
const ttl = hit && Object.values(hit.value.sections).every((s) => s.state === "ready") ? 20000 : 5000;
|
|
27208
|
+
if (hit && Date.now() - hit.at < ttl)
|
|
27209
|
+
return hit.value;
|
|
27210
|
+
if (pending.has(device))
|
|
27211
|
+
return pending.get(device);
|
|
27212
|
+
const current = generation;
|
|
27213
|
+
const work = (async () => {
|
|
27214
|
+
const sections = {};
|
|
27215
|
+
const deadline = Date.now() + 25000;
|
|
27216
|
+
const entries = Object.entries(routingSections);
|
|
27217
|
+
const worker = async () => {
|
|
27218
|
+
for (let entry = entries.shift();entry; entry = entries.shift()) {
|
|
27219
|
+
const [key, path] = entry;
|
|
27220
|
+
try {
|
|
27221
|
+
if (Date.now() >= deadline)
|
|
27222
|
+
throw new Error("Snapshot time budget reached. Refresh to retry this section.");
|
|
27223
|
+
const result = key.startsWith("addresses") ? await addresses(path, { ...ctx, device }) : { rows: await read(path, undefined, { ...ctx, device }) };
|
|
27224
|
+
sections[key] = { path, ...result, state: "ready", observedAt: Date.now() };
|
|
27225
|
+
} catch (e) {
|
|
27226
|
+
sections[key] = {
|
|
27227
|
+
path,
|
|
27228
|
+
rows: [],
|
|
27229
|
+
state: "error",
|
|
27230
|
+
observedAt: Date.now(),
|
|
27231
|
+
error: e instanceof Error ? e.message : "Routing section could not be read."
|
|
27232
|
+
};
|
|
27233
|
+
}
|
|
27234
|
+
}
|
|
27235
|
+
};
|
|
27236
|
+
await Promise.all([worker(), worker()]);
|
|
27237
|
+
const value = { device, sections, observedAt: Date.now() };
|
|
27238
|
+
if (generation === current)
|
|
27239
|
+
cache.set(device, { at: Date.now(), value });
|
|
27240
|
+
return value;
|
|
27241
|
+
})();
|
|
27242
|
+
pending.set(device, work);
|
|
27243
|
+
try {
|
|
27244
|
+
return await work;
|
|
27245
|
+
} finally {
|
|
27246
|
+
if (pending.get(device) === work)
|
|
27247
|
+
pending.delete(device);
|
|
27248
|
+
}
|
|
27249
|
+
}
|
|
27250
|
+
};
|
|
27251
|
+
}
|
|
27252
|
+
var routerRoutingInventory = createRoutingInventoryReader();
|
|
27253
|
+
onConfigChanged(() => routerRoutingInventory.clear());
|
|
27254
|
+
|
|
27018
27255
|
// src/operations/store.ts
|
|
27019
27256
|
import { mkdirSync as mkdirSync9, chmodSync } from "fs";
|
|
27020
27257
|
import { dirname as dirname9, join as join2 } from "path";
|
|
@@ -27069,6 +27306,76 @@ function operationsStore() {
|
|
|
27069
27306
|
return pending5;
|
|
27070
27307
|
}
|
|
27071
27308
|
|
|
27309
|
+
// src/service-routing/traffic.ts
|
|
27310
|
+
function trafficCommand(policy) {
|
|
27311
|
+
const path = `${routingPath(policy.family)} mangle`;
|
|
27312
|
+
const find = new Cmd(`${path} find`).raw(`where comment=${quoteValue(ownerTag(policy.id))} action=mark-routing`).build();
|
|
27313
|
+
const get = new Cmd(`${path} get`).raw("$srId").build();
|
|
27314
|
+
return `{ :local srIds [${find}]; :if ([:len $srIds] > 1) do={:error "Ambiguous service routing counters"}; :local srItems [:toarray ""]; :foreach srId in=$srIds do={ :local srRow [${get}]; :set ($srRow->".id") $srId; :set ($srRow->"bytes") [:tostr [${get} bytes]]; :set ($srRow->"packets") [:tostr [${get} packets]]; :set ($srItems->[:len $srItems]) $srRow; }; :put [:serialize to=json options=json.no-string-conversion value=$srItems]; }`;
|
|
27315
|
+
}
|
|
27316
|
+
function parsePolicyTraffic(policy, raw, at) {
|
|
27317
|
+
if (raw.length > 32768)
|
|
27318
|
+
throw new Error("Counter response exceeds the bounded read limit.");
|
|
27319
|
+
const rows = parseRoutingRows(raw);
|
|
27320
|
+
const row = rows[0];
|
|
27321
|
+
const base = { policyId: policy.id, device: policy.device, at };
|
|
27322
|
+
const encoded = JSON.parse(raw);
|
|
27323
|
+
if (rows.length !== 1 || !row || !row[".id"] || !enabled3(row) || row.comment !== ownerTag(policy.id) || row.action !== "mark-routing" || row.chain !== `sr-${policy.id.slice(0, 12)}` || row["new-routing-mark"] !== policy.activeTable || typeof encoded[0]?.bytes !== "string" || typeof encoded[0]?.packets !== "string" || !/^\d{1,20}$/.test(row.bytes ?? "") || !/^\d{1,20}$/.test(row.packets ?? "")) {
|
|
27324
|
+
return {
|
|
27325
|
+
...base,
|
|
27326
|
+
state: "unavailable",
|
|
27327
|
+
detail: "The active owned rule or its counters could not be verified. Inspect router configuration; missing data is not zero."
|
|
27328
|
+
};
|
|
27329
|
+
}
|
|
27330
|
+
return {
|
|
27331
|
+
...base,
|
|
27332
|
+
state: "ready",
|
|
27333
|
+
ruleId: row[".id"],
|
|
27334
|
+
table: row["new-routing-mark"],
|
|
27335
|
+
bytes: row.bytes,
|
|
27336
|
+
packets: row.packets,
|
|
27337
|
+
detail: "Client \u2192 service packets matched by this routing mark, since router counter reset. Excludes return/download traffic; not proof of delivery or billing totals."
|
|
27338
|
+
};
|
|
27339
|
+
}
|
|
27340
|
+
var cache2 = new Map;
|
|
27341
|
+
async function readPolicyTraffic(policy, ctx) {
|
|
27342
|
+
if (policy.state !== "active")
|
|
27343
|
+
return {
|
|
27344
|
+
policyId: policy.id,
|
|
27345
|
+
device: policy.device,
|
|
27346
|
+
at: Date.now(),
|
|
27347
|
+
state: "inactive",
|
|
27348
|
+
detail: "Apply and verify this policy before reading its router counters."
|
|
27349
|
+
};
|
|
27350
|
+
const key = JSON.stringify([policy.device, policy.id, policy.activeTable, policy.lastSwitchAt]);
|
|
27351
|
+
const cached = cache2.get(key);
|
|
27352
|
+
if (cached && cached.expires > Date.now())
|
|
27353
|
+
return cached.value;
|
|
27354
|
+
if (cache2.size >= 64)
|
|
27355
|
+
cache2.delete(cache2.keys().next().value);
|
|
27356
|
+
const value = (async () => {
|
|
27357
|
+
try {
|
|
27358
|
+
const raw = await executeMikrotikCommand(trafficCommand(policy), ctx, { maxMs: 6000 });
|
|
27359
|
+
return parsePolicyTraffic(policy, raw, Date.now());
|
|
27360
|
+
} catch {
|
|
27361
|
+
return {
|
|
27362
|
+
policyId: policy.id,
|
|
27363
|
+
device: policy.device,
|
|
27364
|
+
at: Date.now(),
|
|
27365
|
+
state: "unavailable",
|
|
27366
|
+
detail: "Router counters could not be read. Check device connectivity and retry; no zero values were substituted."
|
|
27367
|
+
};
|
|
27368
|
+
}
|
|
27369
|
+
})();
|
|
27370
|
+
cache2.set(key, { value, expires: Date.now() + 1e4 });
|
|
27371
|
+
value.finally(() => {
|
|
27372
|
+
const entry = cache2.get(key);
|
|
27373
|
+
if (entry?.value === value)
|
|
27374
|
+
entry.expires = Date.now() + 4000;
|
|
27375
|
+
});
|
|
27376
|
+
return value;
|
|
27377
|
+
}
|
|
27378
|
+
|
|
27072
27379
|
// src/service-routing/service.ts
|
|
27073
27380
|
var kind = "service-routing";
|
|
27074
27381
|
function access(ctx, tool, write = false) {
|
|
@@ -27098,9 +27405,11 @@ function save(policy, message) {
|
|
|
27098
27405
|
return operationsStore().then((store) => store.put(kind, policy));
|
|
27099
27406
|
}
|
|
27100
27407
|
async function routingInventory(ctx) {
|
|
27101
|
-
access(ctx, "service_routing_inventory");
|
|
27102
|
-
const
|
|
27408
|
+
const device = access(ctx, "service_routing_inventory");
|
|
27409
|
+
const snapshot = await routerRoutingInventory.read(device, ctx);
|
|
27410
|
+
const tables = snapshot.sections.tables.rows;
|
|
27103
27411
|
return {
|
|
27412
|
+
...snapshot,
|
|
27104
27413
|
tables: tables.filter((r) => enabled3(r) && ["yes", "true"].includes(r.fib)).map((r) => r.name),
|
|
27105
27414
|
targets: Object.entries(getConfig().serviceProbes.targets).filter(([, t]) => t.kind === "https").map(([alias, t]) => ({ alias, host: t.host }))
|
|
27106
27415
|
};
|
|
@@ -27109,11 +27418,25 @@ async function listRouting(ctx) {
|
|
|
27109
27418
|
const device = access(ctx, "list_service_routing");
|
|
27110
27419
|
return { policies: (await operationsStore()).list(kind, device) };
|
|
27111
27420
|
}
|
|
27421
|
+
async function routingAddressPage(family, offset, ctx) {
|
|
27422
|
+
const device = access(ctx, "service_routing_address_page");
|
|
27423
|
+
return {
|
|
27424
|
+
device,
|
|
27425
|
+
family,
|
|
27426
|
+
offset,
|
|
27427
|
+
...await readRoutingAddressPage(`${routingPath(family)} address-list`, { ...ctx, device }, offset)
|
|
27428
|
+
};
|
|
27429
|
+
}
|
|
27112
27430
|
async function createRouting(input, ctx) {
|
|
27113
27431
|
const device = access(ctx, "create_service_routing", true), a = routingInput.parse(input);
|
|
27114
|
-
const target = getConfig().serviceProbes.targets[a.target];
|
|
27115
|
-
if (!target || target.kind !== "https")
|
|
27432
|
+
const target = a.target ? getConfig().serviceProbes.targets[a.target] : undefined;
|
|
27433
|
+
if (a.target && (!target || target.kind !== "https"))
|
|
27116
27434
|
throw new Error("Select an administrator-approved HTTPS probe alias first.");
|
|
27435
|
+
const host = a.domain ?? target?.host.toLowerCase();
|
|
27436
|
+
if (!host)
|
|
27437
|
+
throw new Error("Enter a domain or choose an approved service.");
|
|
27438
|
+
if (target && !domainMatches(host, target.host))
|
|
27439
|
+
throw new Error("The approved probe hostname must match the exact domain or its wildcard subdomains.");
|
|
27117
27440
|
const store = await operationsStore();
|
|
27118
27441
|
if (store.list(kind, device).length >= 100)
|
|
27119
27442
|
throw new Error("Router policy limit reached (100).");
|
|
@@ -27121,7 +27444,8 @@ async function createRouting(input, ctx) {
|
|
|
27121
27444
|
...a,
|
|
27122
27445
|
id: randomUUID8(),
|
|
27123
27446
|
device,
|
|
27124
|
-
host
|
|
27447
|
+
host,
|
|
27448
|
+
probeHost: target?.host,
|
|
27125
27449
|
updatedAt: Date.now(),
|
|
27126
27450
|
state: "draft",
|
|
27127
27451
|
samples: [],
|
|
@@ -27130,29 +27454,41 @@ async function createRouting(input, ctx) {
|
|
|
27130
27454
|
await save(policy, "Draft saved. No router changes or probes yet.");
|
|
27131
27455
|
return policy;
|
|
27132
27456
|
}
|
|
27457
|
+
async function routingTraffic(id, ctx) {
|
|
27458
|
+
const device = access(ctx, "service_routing_traffic");
|
|
27459
|
+
return readPolicyTraffic(await routingPolicy(id, device), { ...ctx, device });
|
|
27460
|
+
}
|
|
27133
27461
|
async function facts(policy, ctx) {
|
|
27134
27462
|
const base = routingPath(policy.family);
|
|
27135
|
-
const tables = await
|
|
27136
|
-
const routes = await
|
|
27137
|
-
const mangle = await
|
|
27138
|
-
const filters = await
|
|
27463
|
+
const tables = await readRoutingRows("/routing table", "name,fib,disabled", ctx);
|
|
27464
|
+
const routes = await readRoutingRows(policy.family === "ipv4" ? "/ip route" : "/ipv6 route", "routing-table,dst-address,gateway,active,disabled,blackhole,type", ctx);
|
|
27465
|
+
const mangle = await readRoutingRows(`${base} mangle`, undefined, ctx);
|
|
27466
|
+
const filters = await readRoutingRows(`${base} filter`, "action,disabled", ctx);
|
|
27139
27467
|
if (policy.family === "ipv4") {
|
|
27140
27468
|
const active = (await checkedRead("/ip firewall connection print count-only where fasttrack=yes", ctx)).trim();
|
|
27141
27469
|
if (!/^\d+$/.test(active) || Number(active) > 0)
|
|
27142
27470
|
throw new Error("Active FastTrack connections must drain before routing can be changed.");
|
|
27143
27471
|
}
|
|
27144
|
-
const vrfs = await
|
|
27145
|
-
const addresses = await
|
|
27146
|
-
|
|
27472
|
+
const vrfs = await readRoutingRows("/ip vrf", "name,interfaces,disabled", ctx);
|
|
27473
|
+
const addresses = await readRoutingRows(`${base} address-list`, "list,address,comment,dynamic,disabled", ctx, [`${ownerTag(policy.id)}-src`, `${ownerTag(policy.id)}-dst`]);
|
|
27474
|
+
const result = { tables, routes, mangle, filters, vrfs, addresses };
|
|
27475
|
+
if (isWildcard(policy.host)) {
|
|
27476
|
+
result.dns = await readRoutingRows("/ip dns static", "name,regexp,type,address-list,match-subdomain,forward-to,disabled,comment", ctx);
|
|
27477
|
+
result.version = (await checkedRead(":put [/system resource get version]", ctx)).trim();
|
|
27478
|
+
result.dnsRemoteRequests = ["yes", "true"].includes((await checkedRead(":put [/ip dns get allow-remote-requests]", ctx)).trim());
|
|
27479
|
+
}
|
|
27480
|
+
return result;
|
|
27147
27481
|
}
|
|
27148
27482
|
function fetchCommand(address, table, host, path, port) {
|
|
27149
|
-
return `:put [:serialize to=json value=[${new Cmd("/tool fetch").set("address", `${address}@${table}`).set("host", host).set("mode", "https").set("src-path", path).set("port", port).set("http-method", "head").set("check-certificate", "yes").set("http-max-redirect-count", 0).set("idle-timeout", "5s").set("output", "none").
|
|
27483
|
+
return `:put [:serialize to=json value=[${new Cmd("/tool fetch").set("address", `${address}@${table}`).set("host", host).set("mode", "https").set("src-path", path).set("port", port).set("http-method", "head").set("check-certificate", "yes").set("http-max-redirect-count", 0).set("idle-timeout", "5s").set("duration", "5s").set("output", "none").raw("as-value").build()}]]`;
|
|
27150
27484
|
}
|
|
27151
27485
|
async function probe(policy, ctx) {
|
|
27486
|
+
if (!policy.target)
|
|
27487
|
+
throw new Error("This is a manual domain route. Add an approved HTTPS probe in a new policy to check exits or authorize failover.");
|
|
27152
27488
|
const target = getConfig().serviceProbes.targets[policy.target];
|
|
27153
|
-
if (!target || target.kind !== "https" || target.host !== policy.host)
|
|
27489
|
+
if (!target || target.kind !== "https" || target.host !== (policy.probeHost ?? policy.host))
|
|
27154
27490
|
throw new Error("Probe approval changed. Create a new policy.");
|
|
27155
|
-
const vrfs = await
|
|
27491
|
+
const vrfs = await readRoutingRows("/ip vrf", "name,disabled", ctx);
|
|
27156
27492
|
let addresses = [];
|
|
27157
27493
|
try {
|
|
27158
27494
|
addresses = await nativeProbeIO.resolve(target.host, 3000);
|
|
@@ -27214,7 +27550,16 @@ async function preview(policy, table, remove, ctx) {
|
|
|
27214
27550
|
remove,
|
|
27215
27551
|
expiresAt: Date.now() + 120000,
|
|
27216
27552
|
fingerprint: fingerprint(snapshot),
|
|
27217
|
-
commands: planCommands(policy, table, snapshot, remove)
|
|
27553
|
+
commands: planCommands(policy, table, snapshot, remove),
|
|
27554
|
+
warnings: [
|
|
27555
|
+
"IP-based matching includes other services sharing the resolved IPs. Counters measure client-to-service matched packets, not successful delivery or download totals.",
|
|
27556
|
+
...isWildcard(policy.host) ? [
|
|
27557
|
+
"Subdomains only; apex excluded. Clients must query this router DNS. External DNS, client DoH/DoT and previously cached answers can bypass learning. FWD uses existing upstream DNS and bypasses router adlists for matching names, for all DNS clients; no DNS interception or exposure is added."
|
|
27558
|
+
] : [],
|
|
27559
|
+
...policy.precedence === "before-existing" ? [
|
|
27560
|
+
"This scoped policy is inserted before existing routing rules. On shared IPs it takes precedence; other rules are not rewritten. Existing connections may be interrupted."
|
|
27561
|
+
] : []
|
|
27562
|
+
]
|
|
27218
27563
|
};
|
|
27219
27564
|
await save(policy, "Preview created. Review scope and commands; valid for two minutes.");
|
|
27220
27565
|
return policy;
|
|
@@ -27253,6 +27598,8 @@ async function apply(policy, planId, ctx) {
|
|
|
27253
27598
|
if (plan.remove) {
|
|
27254
27599
|
if (after.addresses.some((r) => r.comment === ownerTag(policy.id)))
|
|
27255
27600
|
throw new Error("Owned address-list removal not confirmed.");
|
|
27601
|
+
if (after.dns?.some((r) => r.comment === ownerTag(policy.id)))
|
|
27602
|
+
throw new Error("Owned DNS entry removal not confirmed.");
|
|
27256
27603
|
} else {
|
|
27257
27604
|
planCommands({ ...policy, state: "active", activeTable: plan.table }, plan.table, after);
|
|
27258
27605
|
}
|
|
@@ -27267,7 +27614,9 @@ async function apply(policy, planId, ctx) {
|
|
|
27267
27614
|
policy.plan = undefined;
|
|
27268
27615
|
policy.error = undefined;
|
|
27269
27616
|
await save(policy, plan.remove ? "Owned routing policy removed." : `Routing read-back verified: ${plan.table}. Client delivery still requires a client check.`);
|
|
27617
|
+
routerRoutingInventory.clear();
|
|
27270
27618
|
} catch (error) {
|
|
27619
|
+
routerRoutingInventory.clear();
|
|
27271
27620
|
if (owned && !commitAttempted)
|
|
27272
27621
|
await safe.rollback().catch(() => {});
|
|
27273
27622
|
policy.error = error instanceof Error ? error.message : "Apply failed";
|
|
@@ -27291,6 +27640,8 @@ async function armRouting(id, minutes, confirm, ctx) {
|
|
|
27291
27640
|
return locked(device, async () => {
|
|
27292
27641
|
const policy = await routingPolicy(id, device);
|
|
27293
27642
|
if (minutes) {
|
|
27643
|
+
if (!policy.target)
|
|
27644
|
+
throw new Error("Automatic failover requires an approved HTTPS probe; this is a manual domain route.");
|
|
27294
27645
|
const other = (await operationsStore()).list(kind, device).some((p) => p.id !== id && (p.armedUntil ?? 0) > Date.now());
|
|
27295
27646
|
if (other)
|
|
27296
27647
|
throw new Error("Only one automatic service policy per router can be armed at a time.");
|
|
@@ -27370,19 +27721,42 @@ var serviceRoutingTools = [
|
|
|
27370
27721
|
}),
|
|
27371
27722
|
defineTool({
|
|
27372
27723
|
name: "service_routing_inventory",
|
|
27373
|
-
title: "
|
|
27724
|
+
title: "Inspect Router Routing Configuration",
|
|
27374
27725
|
annotations: READ,
|
|
27375
|
-
description: "Read
|
|
27726
|
+
description: "Read live IPv4/IPv6 routes, ordered mangle and routing rules, address lists, tables, VRFs and filter rules independently of saved MCP policies. Includes dynamic/disabled entries, per-section failures and observation timestamps; bounded reads, 20-second cache. Missing data is not zero. Also lists enabled FIB exits and approved HTTPS aliases. Table presence is not path health; HTTPS exit probes require a matching VRF. No router changes.",
|
|
27376
27727
|
inputSchema: {},
|
|
27377
27728
|
async handler(_, ctx) {
|
|
27378
27729
|
return JSON.stringify(await routingInventory(ctx));
|
|
27379
27730
|
}
|
|
27380
27731
|
}),
|
|
27732
|
+
defineTool({
|
|
27733
|
+
name: "service_routing_address_page",
|
|
27734
|
+
title: "Read Routing Address List Page",
|
|
27735
|
+
annotations: READ,
|
|
27736
|
+
description: "Read the next bounded page of this router's IPv4 or IPv6 address-list members. Use nextOffset from service_routing_inventory or the preceding page. At most 200 rows per request; live lists may change between pages. Read-only, no router changes.",
|
|
27737
|
+
inputSchema: {
|
|
27738
|
+
family: _enum(["ipv4", "ipv6"]),
|
|
27739
|
+
offset: number2().int().min(0).max(1e6).default(0)
|
|
27740
|
+
},
|
|
27741
|
+
async handler(a, ctx) {
|
|
27742
|
+
return JSON.stringify(await routingAddressPage(a.family, a.offset, ctx));
|
|
27743
|
+
}
|
|
27744
|
+
}),
|
|
27745
|
+
defineTool({
|
|
27746
|
+
name: "service_routing_traffic",
|
|
27747
|
+
title: "Read Service Routing Traffic",
|
|
27748
|
+
annotations: READ,
|
|
27749
|
+
description: "Read the exact active MCP-owned routing mark's client-to-service byte and packet counters for one saved policy. Decimal strings preserve 64-bit totals. Four-second cache; missing, disabled or modified rules are unavailable, not zero. Excludes return/download traffic and does not prove delivery, DNS coverage or billing usage. No reset or router change.",
|
|
27750
|
+
inputSchema: { id: uuid2() },
|
|
27751
|
+
async handler(a, ctx) {
|
|
27752
|
+
return JSON.stringify(await routingTraffic(a.id, ctx));
|
|
27753
|
+
}
|
|
27754
|
+
}),
|
|
27381
27755
|
defineTool({
|
|
27382
27756
|
name: "create_service_routing",
|
|
27383
27757
|
title: "Create Service Routing Draft",
|
|
27384
27758
|
annotations: WRITE,
|
|
27385
|
-
description: "Save a single-family
|
|
27759
|
+
description: "Save a single-family exact domain or *.example.com route for explicit client subnets. The wildcard excludes the apex and requires client DNS through this router, existing remote DNS, RouterOS 7.17+ and dnsLearningConfirmed. Wildcard FWD bypasses adlists for matching DNS queries. HTTPS target is optional for manual routing, required for health probes/failover; when domain is absent use the approved target's host (legacy). Shared CDN IPs can affect other services. No router change until preview and explicit apply. Never infer authorization from a draft.",
|
|
27386
27760
|
inputSchema: routingInput.shape,
|
|
27387
27761
|
async handler(a, ctx) {
|
|
27388
27762
|
return JSON.stringify(await createRouting(a, ctx));
|
|
@@ -27402,7 +27776,7 @@ var serviceRoutingTools = [
|
|
|
27402
27776
|
name: "preview_service_routing",
|
|
27403
27777
|
title: "Preview Service Routing Change",
|
|
27404
27778
|
annotations: READ,
|
|
27405
|
-
description: "Read router state and save a two-minute
|
|
27779
|
+
description: "Read router state and save a two-minute state-bound preview for applying/switching or removing owned rules. Reject FastTrack, overlapping wildcard DNS and foreign routing conflicts unless before-existing precedence was explicitly selected. Wildcard plans add an owned DNS FWD learner, not DNS interception. Does not create exits, NAT or change the router until apply.",
|
|
27406
27780
|
inputSchema: {
|
|
27407
27781
|
id: uuid2(),
|
|
27408
27782
|
table: string2().min(1).max(64),
|
|
@@ -34259,11 +34633,11 @@ function searchToolIndex(index, query, limit = 8) {
|
|
|
34259
34633
|
|
|
34260
34634
|
// src/tools/tool-gateway.ts
|
|
34261
34635
|
var META_NAMES = new Set(["find_tools", "describe_tool", "invoke_tool"]);
|
|
34262
|
-
var
|
|
34636
|
+
var cache3 = null;
|
|
34263
34637
|
async function gateway() {
|
|
34264
|
-
if (
|
|
34265
|
-
return
|
|
34266
|
-
const { moduleCatalog } = await import("./shared/cli-
|
|
34638
|
+
if (cache3)
|
|
34639
|
+
return cache3;
|
|
34640
|
+
const { moduleCatalog } = await import("./shared/cli-t311px0m.js");
|
|
34267
34641
|
const forIndex = [];
|
|
34268
34642
|
const byName = new Map;
|
|
34269
34643
|
for (const mod of moduleCatalog) {
|
|
@@ -34281,8 +34655,8 @@ async function gateway() {
|
|
|
34281
34655
|
});
|
|
34282
34656
|
}
|
|
34283
34657
|
}
|
|
34284
|
-
|
|
34285
|
-
return
|
|
34658
|
+
cache3 = { index: buildToolIndex(forIndex), byName };
|
|
34659
|
+
return cache3;
|
|
34286
34660
|
}
|
|
34287
34661
|
function isOptional(field) {
|
|
34288
34662
|
return field.safeParse(undefined).success;
|
|
@@ -47512,8 +47886,235 @@ var wolTools = [
|
|
|
47512
47886
|
})
|
|
47513
47887
|
];
|
|
47514
47888
|
|
|
47889
|
+
// src/core/openvpn-sessions.ts
|
|
47890
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
47891
|
+
|
|
47892
|
+
// src/core/openvpn-sessions-model.ts
|
|
47893
|
+
function openVpnUptime(value) {
|
|
47894
|
+
const clock = /^(?:(\d+)w)?(?:(\d+)d)?(\d{1,3}):(\d{2}):(\d{2})(?:\.(\d+))?$/.exec(value);
|
|
47895
|
+
if (clock) {
|
|
47896
|
+
if (+clock[4] > 59 || +clock[5] > 59)
|
|
47897
|
+
return null;
|
|
47898
|
+
return +(clock[1] || 0) * 604800 + +(clock[2] || 0) * 86400 + +clock[3] * 3600 + +clock[4] * 60 + +clock[5];
|
|
47899
|
+
}
|
|
47900
|
+
if (!/^(?=\d)(?:\d+w)?(?:\d+d)?(?:\d+h)?(?:\d+m)?(?:\d+(?:\.\d+)?s)?$/.test(value))
|
|
47901
|
+
return null;
|
|
47902
|
+
const units = { w: 604800, d: 86400, h: 3600, m: 60, s: 1 };
|
|
47903
|
+
const seconds = [...value.matchAll(/(\d+(?:\.\d+)?)([wdhms])/g)].reduce((total, part) => total + +part[1] * units[part[2]], 0);
|
|
47904
|
+
return Number.isSafeInteger(Math.floor(seconds)) ? Math.floor(seconds) : null;
|
|
47905
|
+
}
|
|
47906
|
+
|
|
47907
|
+
// src/core/openvpn-sessions.ts
|
|
47908
|
+
var SESSION_LIMIT = 1000;
|
|
47909
|
+
var TICKET_TTL = 60000;
|
|
47910
|
+
var tickets = new Map;
|
|
47911
|
+
var cache4 = new Map;
|
|
47912
|
+
|
|
47913
|
+
class OpenVpnOperationError extends Error {
|
|
47914
|
+
status;
|
|
47915
|
+
constructor(status, message) {
|
|
47916
|
+
super(message);
|
|
47917
|
+
this.status = status;
|
|
47918
|
+
}
|
|
47919
|
+
}
|
|
47920
|
+
var disconnectOpenVpnInput = object({
|
|
47921
|
+
token: string2().uuid().describe("Fresh disconnectToken from list_ovpn_sessions on this router; expires after 60 seconds and is single-use."),
|
|
47922
|
+
confirm: literal(true).describe("Explicit operator approval to terminate this one live connection. The client can reconnect.")
|
|
47923
|
+
});
|
|
47924
|
+
function access4(ctx, write = false) {
|
|
47925
|
+
if (!ctx.device)
|
|
47926
|
+
throw new OpenVpnOperationError(400, "Select an explicit router first.");
|
|
47927
|
+
let device;
|
|
47928
|
+
try {
|
|
47929
|
+
device = resolveDeviceName(ctx.device);
|
|
47930
|
+
} catch {
|
|
47931
|
+
throw new OpenVpnOperationError(400, "Unknown router. Select an enabled router first.");
|
|
47932
|
+
}
|
|
47933
|
+
try {
|
|
47934
|
+
assertDeviceAccess([device], write ? "disconnect_ovpn_session" : "list_ovpn_sessions", write ? "DESTRUCTIVE" : "READ");
|
|
47935
|
+
} catch (e) {
|
|
47936
|
+
throw new OpenVpnOperationError(403, e instanceof Error ? e.message : "Device access denied.");
|
|
47937
|
+
}
|
|
47938
|
+
return device;
|
|
47939
|
+
}
|
|
47940
|
+
function openVpnSessionsCommand() {
|
|
47941
|
+
const find = new Cmd("/ppp active find where").set("service", "ovpn").build();
|
|
47942
|
+
const read = new Cmd("/ppp active print").raw("detail as-value").raw("where").set("service", "ovpn").build();
|
|
47943
|
+
return `{ :if ([:len [${find}]] > ${SESSION_LIMIT}) do={ :error "OpenVPN session limit exceeded" }; :local rows [:toarray ""]; :foreach row in=[${read}] do={ :set ($row->"uptime") [:tostr ($row->"uptime")]; :set ($row->"session-id") [:tostr ($row->"session-id")]; :set ($rows->[:len $rows]) $row }; :put [:serialize to=json options=json.no-string-conversion value=$rows] }`;
|
|
47944
|
+
}
|
|
47945
|
+
function parseOpenVpnSessions(output) {
|
|
47946
|
+
if (output.length > 1e6)
|
|
47947
|
+
throw new Error("OpenVPN session response is too large; no partial list is shown.");
|
|
47948
|
+
let rows;
|
|
47949
|
+
try {
|
|
47950
|
+
rows = JSON.parse(output.trim());
|
|
47951
|
+
} catch {
|
|
47952
|
+
throw new Error("Could not read OpenVPN sessions. Check router connectivity and RouterOS JSON support.");
|
|
47953
|
+
}
|
|
47954
|
+
if (!Array.isArray(rows) || rows.length > SESSION_LIMIT)
|
|
47955
|
+
throw new Error("Invalid OpenVPN session snapshot.");
|
|
47956
|
+
const ids = new Set;
|
|
47957
|
+
return rows.map((row) => {
|
|
47958
|
+
const r = object({
|
|
47959
|
+
".id": string2().regex(/^\*[A-Fa-f0-9]+$/),
|
|
47960
|
+
name: string2().min(1),
|
|
47961
|
+
service: literal("ovpn"),
|
|
47962
|
+
address: string2().default(""),
|
|
47963
|
+
"caller-id": string2().default(""),
|
|
47964
|
+
"session-id": string2().default(""),
|
|
47965
|
+
uptime: string2().default(""),
|
|
47966
|
+
encoding: string2().default(""),
|
|
47967
|
+
radius: union([boolean2(), string2()]).optional()
|
|
47968
|
+
}).parse(row);
|
|
47969
|
+
if (ids.has(r[".id"]))
|
|
47970
|
+
throw new Error("Duplicate OpenVPN session identifier; refresh required.");
|
|
47971
|
+
ids.add(r[".id"]);
|
|
47972
|
+
return {
|
|
47973
|
+
id: r[".id"],
|
|
47974
|
+
name: r.name,
|
|
47975
|
+
address: r.address,
|
|
47976
|
+
callerId: r["caller-id"],
|
|
47977
|
+
sessionId: r["session-id"],
|
|
47978
|
+
encoding: r.encoding,
|
|
47979
|
+
radius: r.radius === true || r.radius === "yes" || r.radius === "true",
|
|
47980
|
+
uptime: r.uptime,
|
|
47981
|
+
uptimeSeconds: openVpnUptime(r.uptime)
|
|
47982
|
+
};
|
|
47983
|
+
});
|
|
47984
|
+
}
|
|
47985
|
+
async function read(ctx) {
|
|
47986
|
+
const output = await executeMikrotikCommand(openVpnSessionsCommand(), ctx, { maxMs: 1e4 });
|
|
47987
|
+
return parseOpenVpnSessions(output);
|
|
47988
|
+
}
|
|
47989
|
+
async function listOpenVpnSessions(ctx) {
|
|
47990
|
+
const device = access4(ctx);
|
|
47991
|
+
let canDisconnect = true;
|
|
47992
|
+
try {
|
|
47993
|
+
access4(ctx, true);
|
|
47994
|
+
} catch {
|
|
47995
|
+
canDisconnect = false;
|
|
47996
|
+
}
|
|
47997
|
+
let entry = cache4.get(device);
|
|
47998
|
+
if (!entry || entry.expires < Date.now()) {
|
|
47999
|
+
if (cache4.size >= 64)
|
|
48000
|
+
cache4.delete(cache4.keys().next().value);
|
|
48001
|
+
const next = {
|
|
48002
|
+
expires: Infinity,
|
|
48003
|
+
promise: Promise.resolve(null)
|
|
48004
|
+
};
|
|
48005
|
+
next.promise = read(ctx).then((sessions) => {
|
|
48006
|
+
const at = Date.now();
|
|
48007
|
+
for (const [token, ticket] of tickets)
|
|
48008
|
+
if (at - ticket.at >= TICKET_TTL)
|
|
48009
|
+
tickets.delete(token);
|
|
48010
|
+
for (const session of sessions) {
|
|
48011
|
+
if (!session.sessionId || session.uptimeSeconds === null)
|
|
48012
|
+
continue;
|
|
48013
|
+
if (tickets.size >= 1e4)
|
|
48014
|
+
tickets.delete(tickets.keys().next().value);
|
|
48015
|
+
session.disconnectToken = randomUUID9();
|
|
48016
|
+
tickets.set(session.disconnectToken, { device, at, session });
|
|
48017
|
+
}
|
|
48018
|
+
next.expires = at + 2000;
|
|
48019
|
+
return { device, observedAt: at, sessions, canDisconnect: true };
|
|
48020
|
+
}).catch((error) => {
|
|
48021
|
+
if (cache4.get(device) === next)
|
|
48022
|
+
cache4.delete(device);
|
|
48023
|
+
throw error;
|
|
48024
|
+
});
|
|
48025
|
+
cache4.set(device, next);
|
|
48026
|
+
entry = next;
|
|
48027
|
+
}
|
|
48028
|
+
return { ...await entry.promise, canDisconnect };
|
|
48029
|
+
}
|
|
48030
|
+
function disconnectOpenVpnCommand(session) {
|
|
48031
|
+
const literal2 = (value) => {
|
|
48032
|
+
const quoted = quoteValue(value);
|
|
48033
|
+
return quoted.startsWith('"') ? quoted : `"${quoted}"`;
|
|
48034
|
+
};
|
|
48035
|
+
const find = new Cmd("/ppp active find where").raw(`.id=${quoteValue(session.id)}`).set("service", "ovpn").build();
|
|
48036
|
+
const checks = [
|
|
48037
|
+
["name", session.name],
|
|
48038
|
+
["address", session.address],
|
|
48039
|
+
["caller-id", session.callerId],
|
|
48040
|
+
["session-id", session.sessionId]
|
|
48041
|
+
].map(([field, value]) => `([:tostr [/ppp active get $id ${field}]] != ${literal2(value)})`).join(" || ");
|
|
48042
|
+
return `{ :local ids [${find}]; :if ([:len $ids] = 0) do={ :put "ovpn:gone" } else={ :if ([:len $ids] != 1) do={ :error "Ambiguous session" }; :local id [:pick $ids 0]; :if (${checks} || ([/ppp active get $id uptime] < [:totime ${literal2(session.uptime)}])) do={ :put "ovpn:changed" } else={ ${new Cmd("/ppp active remove").raw("$id").build()}; :put "ovpn:sent" } } }`;
|
|
48043
|
+
}
|
|
48044
|
+
async function disconnectOpenVpnSession(input, ctx) {
|
|
48045
|
+
const device = access4(ctx, true);
|
|
48046
|
+
const { token } = disconnectOpenVpnInput.parse(input);
|
|
48047
|
+
const ticket = tickets.get(token);
|
|
48048
|
+
if (!ticket || ticket.device !== device || Date.now() - ticket.at >= TICKET_TTL)
|
|
48049
|
+
throw new OpenVpnOperationError(409, "This session selection expired or belongs to another router. Refresh and select it again.");
|
|
48050
|
+
if (getSafeModeManager(device).isActive)
|
|
48051
|
+
throw new OpenVpnOperationError(409, "Finish the current Safe Mode session first. Disconnecting a live connection cannot be rolled back.");
|
|
48052
|
+
tickets.delete(token);
|
|
48053
|
+
cache4.delete(device);
|
|
48054
|
+
const { session } = ticket;
|
|
48055
|
+
let output;
|
|
48056
|
+
try {
|
|
48057
|
+
output = (await executeMikrotikCommand(disconnectOpenVpnCommand(session), ctx, { maxMs: 1e4 })).trim();
|
|
48058
|
+
} catch {
|
|
48059
|
+
return {
|
|
48060
|
+
status: "unverified",
|
|
48061
|
+
message: "The disconnect outcome is unknown. Refresh the sessions before any further action; do not retry this request."
|
|
48062
|
+
};
|
|
48063
|
+
}
|
|
48064
|
+
if (output === "ovpn:gone")
|
|
48065
|
+
return {
|
|
48066
|
+
status: "already-ended",
|
|
48067
|
+
message: "This connection has already ended. No other connection was changed."
|
|
48068
|
+
};
|
|
48069
|
+
if (output === "ovpn:changed")
|
|
48070
|
+
throw new OpenVpnOperationError(409, "The selected connection changed. Nothing was disconnected; refresh and select the current session.");
|
|
48071
|
+
if (output !== "ovpn:sent" || looksLikeError(output))
|
|
48072
|
+
return {
|
|
48073
|
+
status: "unverified",
|
|
48074
|
+
message: "The router did not confirm disconnection. Refresh to reconcile; this request will not be replayed."
|
|
48075
|
+
};
|
|
48076
|
+
try {
|
|
48077
|
+
const current = await read(ctx);
|
|
48078
|
+
if (current.some((s) => s.id === session.id && s.sessionId === session.sessionId))
|
|
48079
|
+
return {
|
|
48080
|
+
status: "unverified",
|
|
48081
|
+
message: "The disconnect was sent, but the selected session is still listed. Refresh before another action."
|
|
48082
|
+
};
|
|
48083
|
+
const reconnected = current.some((s) => s.name === session.name);
|
|
48084
|
+
return {
|
|
48085
|
+
status: "disconnected",
|
|
48086
|
+
message: reconnected ? "Selected connection ended. Another connection for this user is active; it was not touched." : "Selected connection ended. The account is unchanged and can reconnect."
|
|
48087
|
+
};
|
|
48088
|
+
} catch {
|
|
48089
|
+
return {
|
|
48090
|
+
status: "unverified",
|
|
48091
|
+
message: "Disconnect sent, but read-back failed. Refresh when the router is reachable; do not replay this request."
|
|
48092
|
+
};
|
|
48093
|
+
}
|
|
48094
|
+
}
|
|
48095
|
+
|
|
47515
48096
|
// src/tools/openvpn.ts
|
|
47516
48097
|
var openvpnTools = [
|
|
48098
|
+
defineTool({
|
|
48099
|
+
name: "list_ovpn_sessions",
|
|
48100
|
+
title: "List Active OpenVPN Connections",
|
|
48101
|
+
annotations: READ,
|
|
48102
|
+
description: "Read currently connected OpenVPN users on an explicit router, including assigned IP, caller address, uptime, encoding and RADIUS status. Reads only /ppp active where service=ovpn; does not read secrets, historical sessions, or outbound clients. Returns structured JSON and short-lived disconnect tokens for individual sessions. A cached read is at most two seconds old; errors are not an empty list.",
|
|
48103
|
+
inputSchema: {},
|
|
48104
|
+
async handler(_a, ctx) {
|
|
48105
|
+
return JSON.stringify(await listOpenVpnSessions(ctx));
|
|
48106
|
+
}
|
|
48107
|
+
}),
|
|
48108
|
+
defineTool({
|
|
48109
|
+
name: "disconnect_ovpn_session",
|
|
48110
|
+
title: "Disconnect One OpenVPN Connection",
|
|
48111
|
+
annotations: DESTRUCTIVE,
|
|
48112
|
+
description: "Disconnect exactly one observed OpenVPN connection after explicit operator approval. First list_ovpn_sessions on the same explicit router, then supply its fresh disconnectToken. Rechecks internal ID, session ID, username, addresses and uptime before removal, then verifies absence. Does not disable or delete the account; clients can reconnect and PPP on-down hooks may run. Can interrupt your own management tunnel. Unknown outcomes must be reconciled by reading again, never automatically retried. Not available during Safe Mode.",
|
|
48113
|
+
inputSchema: disconnectOpenVpnInput.shape,
|
|
48114
|
+
async handler(a, ctx) {
|
|
48115
|
+
return JSON.stringify(await disconnectOpenVpnSession(a, ctx));
|
|
48116
|
+
}
|
|
48117
|
+
}),
|
|
47517
48118
|
defineTool({
|
|
47518
48119
|
name: "get_ovpn_server",
|
|
47519
48120
|
title: "Get OpenVPN Server Configuration",
|
|
@@ -56510,7 +57111,7 @@ var riskByTool = null;
|
|
|
56510
57111
|
async function riskIndex() {
|
|
56511
57112
|
if (riskByTool)
|
|
56512
57113
|
return riskByTool;
|
|
56513
|
-
const { moduleCatalog } = await import("./shared/cli-
|
|
57114
|
+
const { moduleCatalog } = await import("./shared/cli-t311px0m.js");
|
|
56514
57115
|
const index = new Map;
|
|
56515
57116
|
for (const mod of moduleCatalog) {
|
|
56516
57117
|
for (const tool of mod.tools)
|
|
@@ -60145,11 +60746,11 @@ var serverPulseTools = [
|
|
|
60145
60746
|
];
|
|
60146
60747
|
|
|
60147
60748
|
// src/observability/config-admin.ts
|
|
60148
|
-
import { createHash as createHash10, randomUUID as
|
|
60749
|
+
import { createHash as createHash10, randomUUID as randomUUID11 } from "crypto";
|
|
60149
60750
|
import { readFileSync as readFileSync10 } from "fs";
|
|
60150
60751
|
|
|
60151
60752
|
// src/config-write.ts
|
|
60152
|
-
import { randomUUID as
|
|
60753
|
+
import { randomUUID as randomUUID10 } from "crypto";
|
|
60153
60754
|
import {
|
|
60154
60755
|
closeSync,
|
|
60155
60756
|
constants,
|
|
@@ -60169,14 +60770,20 @@ import { dirname as dirname17 } from "path";
|
|
|
60169
60770
|
|
|
60170
60771
|
// src/config-device-draft.ts
|
|
60171
60772
|
var CREDENTIAL_SOURCE = "$credentialsFrom";
|
|
60773
|
+
function ownsConfigKey(key, scope) {
|
|
60774
|
+
if (scope === "serviceProbes")
|
|
60775
|
+
return key === "serviceProbes";
|
|
60776
|
+
const deviceKey = key === "devices" || key === "defaultDevice";
|
|
60777
|
+
return scope === "devices" ? deviceKey : !deviceKey;
|
|
60778
|
+
}
|
|
60172
60779
|
function selectConfigScope(cfg, scope) {
|
|
60173
|
-
return Object.fromEntries(Object.entries(cfg).filter(([key]) =>
|
|
60780
|
+
return Object.fromEntries(Object.entries(cfg).filter(([key]) => ownsConfigKey(key, scope)));
|
|
60174
60781
|
}
|
|
60175
60782
|
function scopeConfigDraft(raw, current, scope) {
|
|
60176
60783
|
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
60177
60784
|
return raw;
|
|
60178
60785
|
return {
|
|
60179
|
-
...
|
|
60786
|
+
...Object.fromEntries(Object.entries(current).filter(([key]) => !ownsConfigKey(key, scope))),
|
|
60180
60787
|
...selectConfigScope(raw, scope)
|
|
60181
60788
|
};
|
|
60182
60789
|
}
|
|
@@ -60239,7 +60846,7 @@ function backupName(path, ts) {
|
|
|
60239
60846
|
}
|
|
60240
60847
|
function atomicWrite(path, text) {
|
|
60241
60848
|
mkdirSync16(dirname17(path), { recursive: true });
|
|
60242
|
-
const tmp = `${path}.tmp-${
|
|
60849
|
+
const tmp = `${path}.tmp-${randomUUID10()}`;
|
|
60243
60850
|
try {
|
|
60244
60851
|
writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx", flush: true });
|
|
60245
60852
|
try {
|
|
@@ -60271,7 +60878,7 @@ function writeMountedFile(path, text) {
|
|
|
60271
60878
|
throw new Error("Configuration target must be a regular file.");
|
|
60272
60879
|
fchmodSync(fd, 384);
|
|
60273
60880
|
const previous = readFileSync9(fd);
|
|
60274
|
-
const backup = `${path}.bak-mounted-${
|
|
60881
|
+
const backup = `${path}.bak-mounted-${randomUUID10()}`;
|
|
60275
60882
|
writeFileSync4(backup, previous, { mode: 384, flag: "wx", flush: true });
|
|
60276
60883
|
try {
|
|
60277
60884
|
replaceContents(fd, Buffer.from(text, "utf8"));
|
|
@@ -60304,7 +60911,7 @@ function validateConfig(raw) {
|
|
|
60304
60911
|
function createConfigAdmin(deps) {
|
|
60305
60912
|
let pending = null;
|
|
60306
60913
|
let lastTimestamp = 0;
|
|
60307
|
-
const salt =
|
|
60914
|
+
const salt = randomUUID11();
|
|
60308
60915
|
const fingerprint = (config, source, contents) => createHash10("sha256").update(salt).update(JSON.stringify([config, source, contents])).digest("hex");
|
|
60309
60916
|
const revision = () => {
|
|
60310
60917
|
const source = deps.source();
|
|
@@ -67609,7 +68216,7 @@ function applyModuleToggle(filter, slug, enabled) {
|
|
|
67609
68216
|
// src/observability/ssh-key-inventory.ts
|
|
67610
68217
|
import { createHash as createHash11 } from "crypto";
|
|
67611
68218
|
import { constants as constants2 } from "fs";
|
|
67612
|
-
import { access as
|
|
68219
|
+
import { access as access5, lstat, open as open2, readdir } from "fs/promises";
|
|
67613
68220
|
import { homedir as homedir3 } from "os";
|
|
67614
68221
|
import { basename as basename2, join as join10, resolve as resolve4 } from "path";
|
|
67615
68222
|
import { utils } from "ssh2";
|
|
@@ -67653,7 +68260,7 @@ async function listSshKeys(configuredPaths, directory = join10(homedir3(), ".ssh
|
|
|
67653
68260
|
try {
|
|
67654
68261
|
const privateStat = await lstat(path);
|
|
67655
68262
|
if (privateStat.isFile() && privateStat.size > 0) {
|
|
67656
|
-
await
|
|
68263
|
+
await access5(path, constants2.R_OK);
|
|
67657
68264
|
usable = true;
|
|
67658
68265
|
}
|
|
67659
68266
|
} catch {}
|
|
@@ -68031,6 +68638,8 @@ var routing = {
|
|
|
68031
68638
|
"POST /api/flight-recorder/export": "export_network_incident",
|
|
68032
68639
|
"GET /api/service-routing": "list_service_routing",
|
|
68033
68640
|
"GET /api/service-routing/inventory": "service_routing_inventory",
|
|
68641
|
+
"GET /api/service-routing/addresses": "service_routing_address_page",
|
|
68642
|
+
"GET /api/service-routing/traffic": "service_routing_traffic",
|
|
68034
68643
|
"POST /api/service-routing": "create_service_routing",
|
|
68035
68644
|
"POST /api/service-routing/probe": "probe_service_routing",
|
|
68036
68645
|
"POST /api/service-routing/preview": "preview_service_routing",
|
|
@@ -68044,7 +68653,10 @@ async function operationsRoutes(req, url) {
|
|
|
68044
68653
|
if (!tool)
|
|
68045
68654
|
return Response.json({ error: "Unsupported workspace operation" }, { status: 405 });
|
|
68046
68655
|
try {
|
|
68047
|
-
const input = req.method === "POST" ? JSON.parse(await readOperationBody(req)) : {
|
|
68656
|
+
const input = req.method === "POST" ? JSON.parse(await readOperationBody(req)) : url.pathname === "/api/service-routing/addresses" ? {
|
|
68657
|
+
family: url.searchParams.get("family"),
|
|
68658
|
+
offset: Number(url.searchParams.get("offset") ?? "0")
|
|
68659
|
+
} : url.pathname === "/api/service-routing/traffic" ? { id: url.searchParams.get("id") } : {};
|
|
68048
68660
|
const device = url.searchParams.get("device");
|
|
68049
68661
|
if (!device)
|
|
68050
68662
|
throw new DashboardInputError(400, "Select an explicit router first.");
|
|
@@ -68057,6 +68669,73 @@ async function operationsRoutes(req, url) {
|
|
|
68057
68669
|
}
|
|
68058
68670
|
}
|
|
68059
68671
|
|
|
68672
|
+
// src/observability/http-error.ts
|
|
68673
|
+
import { homedir as homedir4 } from "os";
|
|
68674
|
+
var HOME = homedir4();
|
|
68675
|
+
var MAX_LEN = 300;
|
|
68676
|
+
function sanitizeMessage(raw, home, fallback) {
|
|
68677
|
+
const line = raw.split(`
|
|
68678
|
+
`, 1)[0].trim();
|
|
68679
|
+
const masked = home.length > 1 ? line.split(home).join("~") : line;
|
|
68680
|
+
if (!masked)
|
|
68681
|
+
return fallback;
|
|
68682
|
+
return masked.length > MAX_LEN ? `${masked.slice(0, MAX_LEN)}\u2026` : masked;
|
|
68683
|
+
}
|
|
68684
|
+
function clientError(e, fallback = "unknown error") {
|
|
68685
|
+
return sanitizeMessage(e instanceof Error ? e.message : String(e), HOME, fallback);
|
|
68686
|
+
}
|
|
68687
|
+
function errorResponse(e) {
|
|
68688
|
+
const connection = e instanceof DeviceConnectionError;
|
|
68689
|
+
return Response.json({
|
|
68690
|
+
error: clientError(e),
|
|
68691
|
+
...connection && {
|
|
68692
|
+
code: "DEVICE_CONNECTION_FAILED",
|
|
68693
|
+
device: sanitizeMessage(e.device, HOME, "unknown device")
|
|
68694
|
+
}
|
|
68695
|
+
}, { status: connection ? 503 : 502 });
|
|
68696
|
+
}
|
|
68697
|
+
function logError(e) {
|
|
68698
|
+
if (e instanceof Error)
|
|
68699
|
+
return e.stack ?? e.message;
|
|
68700
|
+
return String(e);
|
|
68701
|
+
}
|
|
68702
|
+
|
|
68703
|
+
// src/observability/openvpn-routes.ts
|
|
68704
|
+
async function openVpnRoutes(req, url) {
|
|
68705
|
+
if (url.pathname !== "/api/openvpn/sessions" && url.pathname !== "/api/openvpn/disconnect")
|
|
68706
|
+
return null;
|
|
68707
|
+
try {
|
|
68708
|
+
const device = url.searchParams.get("device");
|
|
68709
|
+
if (!device?.trim())
|
|
68710
|
+
throw new DashboardInputError(400, "Select an explicit router first.");
|
|
68711
|
+
const ctx = createContext(undefined, device);
|
|
68712
|
+
let result;
|
|
68713
|
+
if (req.method === "GET" && url.pathname === "/api/openvpn/sessions")
|
|
68714
|
+
result = await listOpenVpnSessions(ctx);
|
|
68715
|
+
else if (req.method === "POST" && url.pathname === "/api/openvpn/disconnect") {
|
|
68716
|
+
const body = await readOperationBody(req);
|
|
68717
|
+
let input;
|
|
68718
|
+
try {
|
|
68719
|
+
input = JSON.parse(body);
|
|
68720
|
+
} catch {
|
|
68721
|
+
throw new DashboardInputError(400, "Provide a valid JSON request.");
|
|
68722
|
+
}
|
|
68723
|
+
const parsed = disconnectOpenVpnInput.safeParse(input);
|
|
68724
|
+
if (!parsed.success)
|
|
68725
|
+
throw new DashboardInputError(400, "A valid session token and explicit confirmation are required.");
|
|
68726
|
+
result = await disconnectOpenVpnSession(parsed.data, ctx);
|
|
68727
|
+
} else
|
|
68728
|
+
return Response.json({ error: "Method not allowed" }, { status: 405 });
|
|
68729
|
+
return Response.json(result, { headers: { "cache-control": "no-store" } });
|
|
68730
|
+
} catch (error) {
|
|
68731
|
+
if (error instanceof DashboardInputError || error instanceof OpenVpnOperationError)
|
|
68732
|
+
return Response.json({ error: clientError(error) }, { status: error.status, headers: { "cache-control": "no-store" } });
|
|
68733
|
+
const response = errorResponse(error);
|
|
68734
|
+
response.headers.set("cache-control", "no-store");
|
|
68735
|
+
return response;
|
|
68736
|
+
}
|
|
68737
|
+
}
|
|
68738
|
+
|
|
68060
68739
|
// src/observability/round-trip-routes.ts
|
|
68061
68740
|
async function roundTripRoutes(req, url) {
|
|
68062
68741
|
if (url.pathname === "/api/round-trip/options") {
|
|
@@ -68123,7 +68802,7 @@ async function roundTripRoutes(req, url) {
|
|
|
68123
68802
|
}
|
|
68124
68803
|
|
|
68125
68804
|
// src/observability/um-report-cache.ts
|
|
68126
|
-
import { createHash as createHash12, randomUUID as
|
|
68805
|
+
import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
|
|
68127
68806
|
import { mkdir, readFile, rename, stat, unlink, writeFile } from "fs/promises";
|
|
68128
68807
|
import { dirname as dirname18, join as join12 } from "path";
|
|
68129
68808
|
var MAX_BYTES = 32 * 1024 * 1024;
|
|
@@ -68185,7 +68864,7 @@ async function loadUmReportCache(path, device, fields) {
|
|
|
68185
68864
|
async function saveUmReportCache(path, snapshot) {
|
|
68186
68865
|
if (!path || Object.values(snapshot.sources).some((source) => source.error))
|
|
68187
68866
|
return false;
|
|
68188
|
-
const temp = `${path}.${
|
|
68867
|
+
const temp = `${path}.${randomUUID12()}.tmp`;
|
|
68189
68868
|
try {
|
|
68190
68869
|
const text = JSON.stringify({ version: 1, snapshot });
|
|
68191
68870
|
if (Buffer.byteLength(text) > MAX_BYTES)
|
|
@@ -68412,8 +69091,8 @@ async function collect(device, progress) {
|
|
|
68412
69091
|
throw new Error("Configuration changed during report collection.");
|
|
68413
69092
|
return { device, collectedAt: Date.now(), collectionMs: Date.now() - start, clock, sources };
|
|
68414
69093
|
}
|
|
68415
|
-
var
|
|
68416
|
-
onConfigChanged(() =>
|
|
69094
|
+
var cache5 = new Map;
|
|
69095
|
+
onConfigChanged(() => cache5.clear());
|
|
68417
69096
|
var freshnessMs = (value) => Math.max(CACHE_MS, Math.min(900000, (value?.collectionMs ?? 0) * 5));
|
|
68418
69097
|
async function getUmSnapshot(device, refresh = false, wait = true) {
|
|
68419
69098
|
const name = resolveDeviceName(device);
|
|
@@ -68427,12 +69106,12 @@ async function getUmSnapshot(device, refresh = false, wait = true) {
|
|
|
68427
69106
|
"get_user_manager_settings"
|
|
68428
69107
|
])
|
|
68429
69108
|
assertDeviceAccess([name], tool, "READ");
|
|
68430
|
-
let entry =
|
|
69109
|
+
let entry = cache5.get(name);
|
|
68431
69110
|
const config = getConfig();
|
|
68432
69111
|
const path = umReportCachePath(name);
|
|
68433
69112
|
if (!entry) {
|
|
68434
69113
|
entry = { retryAt: 0, progress: { source: "users", completed: 0, total: null } };
|
|
68435
|
-
|
|
69114
|
+
cache5.set(name, entry);
|
|
68436
69115
|
const target = entry;
|
|
68437
69116
|
target.restored = loadUmReportCache(path, name, UM_REPORT_FIELDS).then((value) => {
|
|
68438
69117
|
target.value = value;
|
|
@@ -69136,12 +69815,12 @@ async function setCapsmanManager(ctx, input) {
|
|
|
69136
69815
|
// src/observability/geo.ts
|
|
69137
69816
|
import { lookup } from "dns/promises";
|
|
69138
69817
|
var LOG_TAG2 = "mikrotik-mcp";
|
|
69139
|
-
var
|
|
69818
|
+
var cache6 = new Map;
|
|
69140
69819
|
var REFRESH_MS = 24 * 60 * 60000;
|
|
69141
69820
|
var timer6 = null;
|
|
69142
69821
|
var inFlight2 = false;
|
|
69143
69822
|
function getDeviceGeo(name) {
|
|
69144
|
-
return
|
|
69823
|
+
return cache6.get(name)?.geo ?? null;
|
|
69145
69824
|
}
|
|
69146
69825
|
var IPV4_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/;
|
|
69147
69826
|
var PRIVATE_RE = /^(?:10\.|127\.|0\.|169\.254\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.|::1$|f[cd])/i;
|
|
@@ -69199,7 +69878,7 @@ async function fetchGeo(ip) {
|
|
|
69199
69878
|
async function resolveDevice(name, host) {
|
|
69200
69879
|
const ip = host ? await publicIpOf(host) : null;
|
|
69201
69880
|
const geo = ip ? await fetchGeo(ip) : null;
|
|
69202
|
-
|
|
69881
|
+
cache6.set(name, { geo, at: Date.now() });
|
|
69203
69882
|
}
|
|
69204
69883
|
async function refreshGeo() {
|
|
69205
69884
|
if (inFlight2)
|
|
@@ -69208,7 +69887,7 @@ async function refreshGeo() {
|
|
|
69208
69887
|
try {
|
|
69209
69888
|
const now = Date.now();
|
|
69210
69889
|
await Promise.all(Object.entries(getConfig().devices).map(([name, dc]) => {
|
|
69211
|
-
const c =
|
|
69890
|
+
const c = cache6.get(name);
|
|
69212
69891
|
if (c && now - c.at < REFRESH_MS)
|
|
69213
69892
|
return Promise.resolve();
|
|
69214
69893
|
return resolveDevice(name, dc.mac ? undefined : dc.host);
|
|
@@ -69231,12 +69910,12 @@ function stopGeoLookups() {
|
|
|
69231
69910
|
// src/observability/flags.ts
|
|
69232
69911
|
import { join as join15 } from "path";
|
|
69233
69912
|
import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
|
|
69234
|
-
import { homedir as
|
|
69913
|
+
import { homedir as homedir5 } from "os";
|
|
69235
69914
|
var LOG_TAG3 = "mikrotik-mcp";
|
|
69236
69915
|
var CODE_RE = /^[a-z]{2}$/;
|
|
69237
69916
|
var sourceUrl = (code) => `https://hatscripts.github.io/circle-flags/flags/${code}.svg`;
|
|
69238
69917
|
var VENDOR_DIR = join15(PROJECT_ROOT, "assets", "flags");
|
|
69239
|
-
var CACHE_DIR = join15(
|
|
69918
|
+
var CACHE_DIR = join15(homedir5(), ".mikrotik-mcp", "flags");
|
|
69240
69919
|
var mem = new Map;
|
|
69241
69920
|
async function flagSvg(code) {
|
|
69242
69921
|
const c = code.toLowerCase();
|
|
@@ -69330,37 +70009,6 @@ function readTrafficSample(device) {
|
|
|
69330
70009
|
});
|
|
69331
70010
|
}
|
|
69332
70011
|
|
|
69333
|
-
// src/observability/http-error.ts
|
|
69334
|
-
import { homedir as homedir5 } from "os";
|
|
69335
|
-
var HOME = homedir5();
|
|
69336
|
-
var MAX_LEN = 300;
|
|
69337
|
-
function sanitizeMessage(raw, home, fallback) {
|
|
69338
|
-
const line = raw.split(`
|
|
69339
|
-
`, 1)[0].trim();
|
|
69340
|
-
const masked = home.length > 1 ? line.split(home).join("~") : line;
|
|
69341
|
-
if (!masked)
|
|
69342
|
-
return fallback;
|
|
69343
|
-
return masked.length > MAX_LEN ? `${masked.slice(0, MAX_LEN)}\u2026` : masked;
|
|
69344
|
-
}
|
|
69345
|
-
function clientError(e, fallback = "unknown error") {
|
|
69346
|
-
return sanitizeMessage(e instanceof Error ? e.message : String(e), HOME, fallback);
|
|
69347
|
-
}
|
|
69348
|
-
function errorResponse(e) {
|
|
69349
|
-
const connection = e instanceof DeviceConnectionError;
|
|
69350
|
-
return Response.json({
|
|
69351
|
-
error: clientError(e),
|
|
69352
|
-
...connection && {
|
|
69353
|
-
code: "DEVICE_CONNECTION_FAILED",
|
|
69354
|
-
device: sanitizeMessage(e.device, HOME, "unknown device")
|
|
69355
|
-
}
|
|
69356
|
-
}, { status: connection ? 503 : 502 });
|
|
69357
|
-
}
|
|
69358
|
-
function logError(e) {
|
|
69359
|
-
if (e instanceof Error)
|
|
69360
|
-
return e.stack ?? e.message;
|
|
69361
|
-
return String(e);
|
|
69362
|
-
}
|
|
69363
|
-
|
|
69364
70012
|
// src/observability/interface-stats.ts
|
|
69365
70013
|
var INTERVAL = 2000;
|
|
69366
70014
|
var counter2 = (value) => {
|
|
@@ -72229,11 +72877,11 @@ function issues(error) {
|
|
|
72229
72877
|
async function configRoutes(req, url, admin) {
|
|
72230
72878
|
const p = url.pathname;
|
|
72231
72879
|
const scope = url.searchParams.get("scope");
|
|
72232
|
-
if (req.method === "POST" && ["/api/config", "/api/config/validate", "/api/config/preview"].includes(p) && scope !== null && scope !== "devices" && scope !== "server")
|
|
72880
|
+
if (req.method === "POST" && ["/api/config", "/api/config/validate", "/api/config/preview"].includes(p) && scope !== null && scope !== "devices" && scope !== "server" && scope !== "serviceProbes")
|
|
72233
72881
|
return json15({ ok: false, error: "Unknown configuration scope" }, 400);
|
|
72234
72882
|
const mergeDraft = (raw) => {
|
|
72235
72883
|
const current = getConfig();
|
|
72236
|
-
return mergeConfigDraft(scope === "devices" || scope === "server" ? scopeConfigDraft(raw, current, scope) : raw, current);
|
|
72884
|
+
return mergeConfigDraft(scope === "devices" || scope === "server" || scope === "serviceProbes" ? scopeConfigDraft(raw, current, scope) : raw, current);
|
|
72237
72885
|
};
|
|
72238
72886
|
if (p === "/api/config-schema" && req.method === "GET") {
|
|
72239
72887
|
return json15(configSchemaJson());
|
|
@@ -73114,6 +73762,9 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
73114
73762
|
const operationsResp = await operationsRoutes(req, url);
|
|
73115
73763
|
if (operationsResp)
|
|
73116
73764
|
return operationsResp;
|
|
73765
|
+
const openVpnResp = await openVpnRoutes(req, url);
|
|
73766
|
+
if (openVpnResp)
|
|
73767
|
+
return openVpnResp;
|
|
73117
73768
|
const roundTripResp = await roundTripRoutes(req, url);
|
|
73118
73769
|
if (roundTripResp)
|
|
73119
73770
|
return roundTripResp;
|
|
@@ -73469,7 +74120,7 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
73469
74120
|
}
|
|
73470
74121
|
|
|
73471
74122
|
// src/transport/http.ts
|
|
73472
|
-
import { randomUUID as
|
|
74123
|
+
import { randomUUID as randomUUID13 } from "crypto";
|
|
73473
74124
|
var {serve: serve2 } = globalThis.Bun;
|
|
73474
74125
|
|
|
73475
74126
|
// node_modules/content-type/index.js
|
|
@@ -82994,7 +83645,7 @@ async function runHttp(mcp) {
|
|
|
82994
83645
|
if (existing)
|
|
82995
83646
|
return existing;
|
|
82996
83647
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
82997
|
-
sessionIdGenerator: () =>
|
|
83648
|
+
sessionIdGenerator: () => randomUUID13(),
|
|
82998
83649
|
enableJsonResponse: true,
|
|
82999
83650
|
...security,
|
|
83000
83651
|
onsessioninitialized: (id) => {
|
|
@@ -83369,7 +84020,7 @@ TRANSPORT OPTIONS
|
|
|
83369
84020
|
--transport stdio | sse | streamable-http (MIKROTIK_MCP__TRANSPORT)
|
|
83370
84021
|
--mcp-host HTTP bind host (MIKROTIK_MCP__HOST)
|
|
83371
84022
|
--mcp-port HTTP bind port (MIKROTIK_MCP__PORT)
|
|
83372
|
-
--mcp-allowed-hosts Host
|
|
84023
|
+
--mcp-allowed-hosts Host heaxder allow-list (DNS-rebinding protection)
|
|
83373
84024
|
|
|
83374
84025
|
SSH CONNECTION POOLING (persistent connections, on by default)
|
|
83375
84026
|
--ssh-keep-alive Enable/disable pooling (MIKROTIK_SSH__KEEP_ALIVE, default true)
|