@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
|
@@ -14845,13 +14845,13 @@ async function undoMigration(id, confirm, selected) {
|
|
|
14845
14845
|
throw new Error("Undo lost Safe Mode or exceeded its time budget.");
|
|
14846
14846
|
await checkedRead(item.undo, createContext(undefined, device));
|
|
14847
14847
|
}
|
|
14848
|
-
const beforeTarget = (await import("./library-
|
|
14849
|
-
const db = await beforeTarget((await import("./library-
|
|
14848
|
+
const beforeTarget = (await import("./library-588vnctn.js")).openSnapshotStore;
|
|
14849
|
+
const db = await beforeTarget((await import("./library-k6m2bxjr.js")).DEFAULT_SNAPSHOT_DB);
|
|
14850
14850
|
try {
|
|
14851
14851
|
const original = db.get(p.snapshots.target);
|
|
14852
14852
|
if (!original)
|
|
14853
14853
|
throw new Error("Original target snapshot unavailable.");
|
|
14854
|
-
const { normalizeExport } = await import("./library-
|
|
14854
|
+
const { normalizeExport } = await import("./library-g8far2nz.js");
|
|
14855
14855
|
if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
|
|
14856
14856
|
throw new Error("Target differs from its backup. Undo verification failed.");
|
|
14857
14857
|
} finally {
|
|
@@ -19635,10 +19635,43 @@ var serviceContractTools = [
|
|
|
19635
19635
|
// src/service-routing/model.ts
|
|
19636
19636
|
import ipaddr2 from "ipaddr.js";
|
|
19637
19637
|
import { createHash as createHash5 } from "crypto";
|
|
19638
|
+
|
|
19639
|
+
// src/service-routing/domain.ts
|
|
19640
|
+
var routingDomain = string().trim().toLowerCase().max(253).refine((value) => {
|
|
19641
|
+
const base = value.startsWith("*.") ? value.slice(2) : value;
|
|
19642
|
+
const labels = base.split(".");
|
|
19643
|
+
return labels.length >= 2 && !/^\d+(?:\.\d+){3}$/.test(base) && labels.every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) && !/^\d+$/.test(labels.at(-1));
|
|
19644
|
+
}, "Enter a domain such as api.example.com or *.example.com; no URL, port, path or other wildcard.");
|
|
19645
|
+
var isWildcard = (domain) => domain.startsWith("*.");
|
|
19646
|
+
function domainMatches(domain, host) {
|
|
19647
|
+
const candidate = host.toLowerCase();
|
|
19648
|
+
return isWildcard(domain) ? candidate.endsWith(domain.slice(1)) && candidate.length > domain.length - 1 : candidate === domain;
|
|
19649
|
+
}
|
|
19650
|
+
function wildcardRegexp(domain) {
|
|
19651
|
+
const checked = routingDomain.parse(domain);
|
|
19652
|
+
if (!isWildcard(checked))
|
|
19653
|
+
throw new Error("A wildcard domain is required.");
|
|
19654
|
+
return `^([a-z0-9-]+[.])+${checked.slice(2).replaceAll(".", "[.]")}$`;
|
|
19655
|
+
}
|
|
19656
|
+
function wildcardRegexOverlaps(regexp, domain) {
|
|
19657
|
+
const prefix = "^([a-z0-9-]+[.])+";
|
|
19658
|
+
if (!regexp.startsWith(prefix) || !regexp.endsWith("$"))
|
|
19659
|
+
return true;
|
|
19660
|
+
const base = regexp.slice(prefix.length, -1).replaceAll("[.]", ".");
|
|
19661
|
+
if (!routingDomain.safeParse(base).success || wildcardRegexp(`*.${base}`) !== regexp)
|
|
19662
|
+
return true;
|
|
19663
|
+
const candidate = domain.slice(2);
|
|
19664
|
+
return candidate === base || candidate.endsWith(`.${base}`) || base.endsWith(`.${candidate}`);
|
|
19665
|
+
}
|
|
19666
|
+
|
|
19667
|
+
// src/service-routing/model.ts
|
|
19638
19668
|
var name2 = string().trim().min(1).max(64).regex(/^[a-zA-Z0-9_.-]+$/);
|
|
19639
19669
|
var routingInput = object({
|
|
19640
19670
|
name: string().trim().min(1).max(80),
|
|
19641
|
-
target: name2.describe("
|
|
19671
|
+
target: name2.optional().describe("Optional approved HTTPS probe alias; legacy drafts without domain route this alias's exact host"),
|
|
19672
|
+
domain: routingDomain.optional().describe("Exact domain or *.example.com (subdomains only, not the apex). Wildcards need client DNS through this router."),
|
|
19673
|
+
dnsLearningConfirmed: boolean().optional().describe("For wildcard only: confirms clients use this router DNS, shared-IP scope and FWD adlist bypass are understood. Does not enable or intercept DNS."),
|
|
19674
|
+
precedence: _enum(["before-existing"]).optional().describe("Explicitly allow this scoped policy before existing routing rules. Preview still binds their full configuration; FastTrack is never bypassed."),
|
|
19642
19675
|
family: _enum(["ipv4", "ipv6"]),
|
|
19643
19676
|
sources: array(string().refine((v) => ipaddr2.isValidCIDR(v), "Use an explicit client subnet CIDR")).min(1).max(8),
|
|
19644
19677
|
tables: array(name2).min(1).max(3),
|
|
@@ -19647,6 +19680,13 @@ var routingInput = object({
|
|
|
19647
19680
|
failuresBeforeSwitch: number().int().min(2).max(10).default(3),
|
|
19648
19681
|
cooldownSeconds: number().int().min(120).max(3600).default(300)
|
|
19649
19682
|
}).superRefine((v, ctx) => {
|
|
19683
|
+
if (!v.domain && !v.target)
|
|
19684
|
+
ctx.addIssue({ code: "custom", message: "Enter a domain or choose an approved service" });
|
|
19685
|
+
if (v.domain && isWildcard(v.domain) && !v.dnsLearningConfirmed)
|
|
19686
|
+
ctx.addIssue({
|
|
19687
|
+
code: "custom",
|
|
19688
|
+
message: "Confirm client DNS learning and its limitations for wildcard routing"
|
|
19689
|
+
});
|
|
19650
19690
|
if (!v.tables.includes(v.primary) || new Set(v.tables).size !== v.tables.length)
|
|
19651
19691
|
ctx.addIssue({ code: "custom", message: "Choose one unique candidate table as primary" });
|
|
19652
19692
|
for (const s of v.sources) {
|
|
@@ -19663,13 +19703,21 @@ var ownerTag = (id) => `mcp-sr-${id}`;
|
|
|
19663
19703
|
var selector = (tag) => `[find where comment=${quoteValue(tag)}]`;
|
|
19664
19704
|
var routingPath = (family) => family === "ipv4" ? "/ip firewall" : "/ipv6 firewall";
|
|
19665
19705
|
function fingerprint(facts) {
|
|
19666
|
-
return createHash5("sha256").update(JSON.stringify(
|
|
19706
|
+
return createHash5("sha256").update(JSON.stringify({
|
|
19707
|
+
...facts,
|
|
19708
|
+
addresses: facts.addresses.filter((r) => !(r.list?.startsWith("mcp-sr-") && r.list.endsWith("-dst") && (["yes", "true"].includes(r.dynamic) || (r.flags ?? "").includes("D"))))
|
|
19709
|
+
}, (key, value) => ["#", ".id", "bytes", "packets", "last-handshake", "expires-after"].includes(key) ? undefined : value)).digest("hex");
|
|
19667
19710
|
}
|
|
19668
19711
|
function planCommands(policy, table, facts, remove = false) {
|
|
19669
19712
|
const path = routingPath(policy.family), tag = ownerTag(policy.id), chain = `sr-${policy.id.slice(0, 12)}`;
|
|
19670
19713
|
if (policy.state === "uncertain")
|
|
19671
19714
|
throw new Error("Reconcile uncertain router state before another change.");
|
|
19672
19715
|
const owned = facts.mangle.filter((r) => r.comment === tag);
|
|
19716
|
+
const wildcard = isWildcard(policy.host);
|
|
19717
|
+
const dns = facts.dns ?? [];
|
|
19718
|
+
const ownedDns = dns.filter((r) => r.comment === tag);
|
|
19719
|
+
if (wildcard && dns.some((r) => r["address-list"] === `${tag}-dst` && r.comment !== tag))
|
|
19720
|
+
throw new Error("A foreign DNS entry uses the owned destination list; reconcile first.");
|
|
19673
19721
|
if (facts.mangle.some((r) => r.chain === chain && r.comment !== tag))
|
|
19674
19722
|
throw new Error("Private chain contains foreign rules; review it first.");
|
|
19675
19723
|
if (owned.some((r) => r.chain !== chain && r.chain !== "prerouting"))
|
|
@@ -19677,14 +19725,33 @@ function planCommands(policy, table, facts, remove = false) {
|
|
|
19677
19725
|
if (remove)
|
|
19678
19726
|
return [
|
|
19679
19727
|
new Cmd(`${path} mangle remove ${selector(tag)}`).build(),
|
|
19680
|
-
new Cmd(`${path} address-list remove ${selector(tag)}`).build()
|
|
19728
|
+
new Cmd(`${path} address-list remove ${selector(tag)}`).build(),
|
|
19729
|
+
...wildcard ? [
|
|
19730
|
+
new Cmd(`/ip dns static remove ${selector(tag)}`).build(),
|
|
19731
|
+
...["/ip firewall", "/ipv6 firewall"].map((base) => new Cmd(`${base} address-list remove [find where list=${quoteValue(`${tag}-dst`)} dynamic=yes]`).build())
|
|
19732
|
+
] : []
|
|
19681
19733
|
];
|
|
19734
|
+
if (wildcard) {
|
|
19735
|
+
const version = /^(\d+)\.(\d+)(?:\.(\d+))?(?:\s|$)/.exec(facts.version ?? "");
|
|
19736
|
+
if (!version || Number(version[1]) < 7 || Number(version[1]) === 7 && Number(version[2]) < 17)
|
|
19737
|
+
throw new Error("Wildcard workflow requires stable RouterOS 7.17 or newer; version could not be verified.");
|
|
19738
|
+
if (!facts.dnsRemoteRequests || !policy.dnsLearningConfirmed)
|
|
19739
|
+
throw new Error("Wildcard routing needs confirmed client DNS through this router and allow-remote-requests already enabled. MCP will not expose DNS automatically.");
|
|
19740
|
+
const base = policy.host.slice(2);
|
|
19741
|
+
if (dns.some((r) => enabled3(r) && r.comment !== tag && (r.regexp && wildcardRegexOverlaps(r.regexp, policy.host) || r.name === base || r.name?.endsWith(`.${base}`) || ["yes", "true"].includes(r["match-subdomain"]) && base.endsWith(`.${r.name}`))))
|
|
19742
|
+
throw new Error("Existing DNS entries may overlap this wildcard. Review them first; MCP will not replace them.");
|
|
19743
|
+
if (owned.length) {
|
|
19744
|
+
if (ownedDns.length !== 1 || !enabled3(ownedDns[0]) || ownedDns[0].type !== "FWD" || ownedDns[0].regexp !== wildcardRegexp(policy.host) || ownedDns[0]["address-list"] !== `${tag}-dst` || ownedDns[0]["forward-to"] || ownedDns[0].name)
|
|
19745
|
+
throw new Error("Owned DNS learning scope changed externally.");
|
|
19746
|
+
} else if (ownedDns.length)
|
|
19747
|
+
throw new Error("Owned DNS entry is partially present; reconcile first.");
|
|
19748
|
+
}
|
|
19682
19749
|
const listRows = facts.addresses.filter((r) => [`${tag}-src`, `${tag}-dst`].includes(r.list));
|
|
19683
19750
|
const staticRows = listRows.filter((r) => !["yes", "true"].includes(r.dynamic) && !(r.flags ?? "").includes("D"));
|
|
19684
19751
|
if (owned.length) {
|
|
19685
19752
|
const expectedLists = [
|
|
19686
19753
|
...policy.sources.map((address) => ({ list: `${tag}-src`, address })),
|
|
19687
|
-
{ list: `${tag}-dst`, address: policy.host }
|
|
19754
|
+
...!wildcard ? [{ list: `${tag}-dst`, address: policy.host }] : []
|
|
19688
19755
|
];
|
|
19689
19756
|
if (staticRows.length !== expectedLists.length || expectedLists.some((e) => !staticRows.some((r) => r.list === e.list && r.address === e.address && r.comment === tag && enabled3(r))))
|
|
19690
19757
|
throw new Error("Owned address-list scope changed externally.");
|
|
@@ -19698,11 +19765,11 @@ function planCommands(policy, table, facts, remove = false) {
|
|
|
19698
19765
|
if (!facts.tables.some((r) => r.name === table && enabled3(r) && ["yes", "true"].includes(r.fib)))
|
|
19699
19766
|
throw new Error("Exit needs an existing enabled FIB table.");
|
|
19700
19767
|
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.");
|
|
19768
|
+
if (!facts.routes.some((r) => r["routing-table"] === table && r["dst-address"] === dst && !!r.gateway && r.blackhole !== "yes" && r.blackhole !== "true" && !["blackhole", "unreachable", "prohibit"].includes(r.type) && enabled3(r) && (["yes", "true"].includes(r.active) || (r.flags ?? "").includes("A"))))
|
|
19769
|
+
throw new Error("Exit has no observed active forwarding default route for this family (discard routes are not exits).");
|
|
19703
19770
|
if (facts.filters.some((r) => enabled3(r) && r.action === "fasttrack-connection"))
|
|
19704
19771
|
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)))
|
|
19772
|
+
if (policy.precedence !== "before-existing" && facts.mangle.some((r) => enabled3(r) && r.comment !== tag && ["mark-routing", "jump", "route"].includes(r.action)))
|
|
19706
19773
|
throw new Error("Existing routing/jump rules need an administrator conflict review. They will not be overridden.");
|
|
19707
19774
|
const result = [];
|
|
19708
19775
|
if (owned.length) {
|
|
@@ -19711,7 +19778,8 @@ function planCommands(policy, table, facts, remove = false) {
|
|
|
19711
19778
|
const expected = planCommands({ ...policy, state: "draft" }, policy.activeTable, {
|
|
19712
19779
|
...facts,
|
|
19713
19780
|
mangle: facts.mangle.filter((r) => r.comment !== tag),
|
|
19714
|
-
addresses: facts.addresses.filter((r) => ![`${tag}-src`, `${tag}-dst`].includes(r.list))
|
|
19781
|
+
addresses: facts.addresses.filter((r) => ![`${tag}-src`, `${tag}-dst`].includes(r.list)),
|
|
19782
|
+
dns: facts.dns?.filter((r) => r.comment !== tag)
|
|
19715
19783
|
}).filter((command) => command.startsWith(`${path} mangle add`)).map((command) => parseRecords(`0 ${command}`).rows[0]);
|
|
19716
19784
|
if (owned.length !== expected.length || expected.some((e) => !e || !owned.some((r) => Object.entries(e).filter(([key]) => !["place-before", "#"].includes(key)).every(([key, value]) => r[key] === value) && enabled3(r))))
|
|
19717
19785
|
throw new Error("Owned rule scope changed externally. Automatic edits are blocked.");
|
|
@@ -19722,7 +19790,10 @@ function planCommands(policy, table, facts, remove = false) {
|
|
|
19722
19790
|
}
|
|
19723
19791
|
for (const address of policy.sources)
|
|
19724
19792
|
result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-src`).set("address", address).set("comment", tag).build());
|
|
19725
|
-
|
|
19793
|
+
if (wildcard)
|
|
19794
|
+
result.push(new Cmd("/ip dns static add").set("type", "FWD").set("regexp", wildcardRegexp(policy.host)).set("address-list", `${tag}-dst`).bool("disabled", false).set("comment", tag).build());
|
|
19795
|
+
else
|
|
19796
|
+
result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-dst`).set("address", policy.host).set("comment", tag).build());
|
|
19726
19797
|
const exclude = policy.family === "ipv4" ? [
|
|
19727
19798
|
"0.0.0.0/8",
|
|
19728
19799
|
"10.0.0.0/8",
|
|
@@ -19744,6 +19815,172 @@ function planCommands(policy, table, facts, remove = false) {
|
|
|
19744
19815
|
import { randomUUID as randomUUID8 } from "crypto";
|
|
19745
19816
|
import { isIP as isIP2 } from "net";
|
|
19746
19817
|
|
|
19818
|
+
// src/service-routing/read.ts
|
|
19819
|
+
var paths = new Set([
|
|
19820
|
+
"/ip dns static",
|
|
19821
|
+
"/routing table",
|
|
19822
|
+
"/routing rule",
|
|
19823
|
+
"/ip route",
|
|
19824
|
+
"/ipv6 route",
|
|
19825
|
+
"/ip vrf",
|
|
19826
|
+
"/ip firewall mangle",
|
|
19827
|
+
"/ipv6 firewall mangle",
|
|
19828
|
+
"/ip firewall filter",
|
|
19829
|
+
"/ipv6 firewall filter",
|
|
19830
|
+
"/ip firewall address-list",
|
|
19831
|
+
"/ipv6 firewall address-list"
|
|
19832
|
+
]);
|
|
19833
|
+
var ROUTING_ROW_LIMIT = 2000;
|
|
19834
|
+
function routingReadCommand(path, lists) {
|
|
19835
|
+
if (!paths.has(path))
|
|
19836
|
+
throw new Error("Unsupported routing inventory section.");
|
|
19837
|
+
const where = lists?.length ? `where ${lists.map((list) => `list=${quoteValue(list)}`).join(" or ")}` : "";
|
|
19838
|
+
const find = new Cmd(`${path} find`).raw(where).build();
|
|
19839
|
+
const print = new Cmd(`${path} print`).raw("detail as-value").raw(where).build();
|
|
19840
|
+
return `:if ([:len [${find}]] > ${ROUTING_ROW_LIMIT}) do={:put "MCP_ROUTING_ROW_LIMIT"} else={:put [:serialize to=json value=[${print}]]}`;
|
|
19841
|
+
}
|
|
19842
|
+
function parseRoutingRows(raw, fields) {
|
|
19843
|
+
if (raw.length > 1048576)
|
|
19844
|
+
throw new Error("Routing section exceeds the 1 MiB read limit.");
|
|
19845
|
+
if (raw.trim() === "MCP_ROUTING_ROW_LIMIT")
|
|
19846
|
+
throw new Error(`More than ${ROUTING_ROW_LIMIT} entries: this section was not loaded to protect the router. Use a filtered RouterOS read; the other routing sections are independent.`);
|
|
19847
|
+
if (looksLikeError(raw))
|
|
19848
|
+
throw new Error("Router rejected this read; check connectivity, permissions and RouterOS v7 support.");
|
|
19849
|
+
let data;
|
|
19850
|
+
try {
|
|
19851
|
+
data = JSON.parse(raw.trim());
|
|
19852
|
+
} catch {
|
|
19853
|
+
throw new Error("Router did not return valid structured routing data; no rows were accepted.");
|
|
19854
|
+
}
|
|
19855
|
+
if (!Array.isArray(data) || data.length > ROUTING_ROW_LIMIT || data.some((r) => !r || typeof r !== "object" || Array.isArray(r)))
|
|
19856
|
+
throw new Error("Router returned an incomplete or invalid routing section.");
|
|
19857
|
+
const keys = fields ? new Set(["#", ".id", "flags", ...fields.split(",")]) : undefined;
|
|
19858
|
+
return data.map((record, index) => {
|
|
19859
|
+
const row = { "#": String(index) };
|
|
19860
|
+
for (const [key, value] of Object.entries(record)) {
|
|
19861
|
+
if (keys && !keys.has(key))
|
|
19862
|
+
continue;
|
|
19863
|
+
if (typeof value === "boolean")
|
|
19864
|
+
row[key] = value ? "yes" : "no";
|
|
19865
|
+
else if (typeof value === "string" || typeof value === "number")
|
|
19866
|
+
row[key] = String(value);
|
|
19867
|
+
else if (Array.isArray(value) && value.every((v) => ["string", "number"].includes(typeof v)))
|
|
19868
|
+
row[key] = value.join(",");
|
|
19869
|
+
}
|
|
19870
|
+
return row;
|
|
19871
|
+
});
|
|
19872
|
+
}
|
|
19873
|
+
async function readRoutingRows(path, fields, ctx, lists) {
|
|
19874
|
+
const raw = await executeMikrotikCommand2(routingReadCommand(path, lists), ctx, { maxMs: 6000 });
|
|
19875
|
+
return parseRoutingRows(raw, fields);
|
|
19876
|
+
}
|
|
19877
|
+
async function readRoutingAddressPage(path, ctx, offset = 0) {
|
|
19878
|
+
if (!["/ip firewall address-list", "/ipv6 firewall address-list"].includes(path) || !Number.isSafeInteger(offset) || offset < 0 || offset > 1e6)
|
|
19879
|
+
throw new Error("Invalid address-list page.");
|
|
19880
|
+
const find = new Cmd(`${path} find`).build();
|
|
19881
|
+
const get = new Cmd(`${path} get`).raw("$srId").build();
|
|
19882
|
+
const command = `{ :local srIds [${find}]; :local srItems [:toarray ""]; :foreach srId in=[:pick $srIds ${offset} ${offset + 200}] do={ :local srRow [${get}]; :set ($srRow->".id") $srId; :set ($srItems->[:len $srItems]) $srRow; }; :put [:serialize to=json value={"rows"=$srItems;"total"=[:len $srIds]}]; }`;
|
|
19883
|
+
const raw = await executeMikrotikCommand2(command, ctx, { maxMs: 6000 });
|
|
19884
|
+
return parseRoutingAddressPage(raw, offset);
|
|
19885
|
+
}
|
|
19886
|
+
function parseRoutingAddressPage(raw, offset = 0) {
|
|
19887
|
+
if (looksLikeError(raw) || raw.length > 1048576)
|
|
19888
|
+
throw new Error("Address-list page could not be read safely.");
|
|
19889
|
+
let data;
|
|
19890
|
+
try {
|
|
19891
|
+
data = JSON.parse(raw.trim());
|
|
19892
|
+
} catch {
|
|
19893
|
+
throw new Error("Invalid structured address-list page.");
|
|
19894
|
+
}
|
|
19895
|
+
if (!data || !Array.isArray(data.rows) || !Number.isSafeInteger(data.total) || data.total < 0)
|
|
19896
|
+
throw new Error("Invalid address-list total.");
|
|
19897
|
+
const rows = parseRoutingRows(JSON.stringify(data.rows)).map((r, i) => ({
|
|
19898
|
+
...r,
|
|
19899
|
+
"#": String(offset + i)
|
|
19900
|
+
}));
|
|
19901
|
+
if (rows.length !== Math.min(200, Math.max(0, data.total - offset)) || rows.some((r) => !r[".id"]))
|
|
19902
|
+
throw new Error("Incomplete address-list page. Refresh if the router list changed while reading.");
|
|
19903
|
+
return {
|
|
19904
|
+
rows,
|
|
19905
|
+
total: data.total,
|
|
19906
|
+
nextOffset: offset + rows.length < data.total ? offset + rows.length : undefined
|
|
19907
|
+
};
|
|
19908
|
+
}
|
|
19909
|
+
|
|
19910
|
+
// src/service-routing/inventory.ts
|
|
19911
|
+
var routingSections = {
|
|
19912
|
+
tables: "/routing table",
|
|
19913
|
+
routes4: "/ip route",
|
|
19914
|
+
routes6: "/ipv6 route",
|
|
19915
|
+
mangle4: "/ip firewall mangle",
|
|
19916
|
+
mangle6: "/ipv6 firewall mangle",
|
|
19917
|
+
rules: "/routing rule",
|
|
19918
|
+
addresses4: "/ip firewall address-list",
|
|
19919
|
+
addresses6: "/ipv6 firewall address-list",
|
|
19920
|
+
vrfs: "/ip vrf",
|
|
19921
|
+
filters4: "/ip firewall filter",
|
|
19922
|
+
filters6: "/ipv6 firewall filter"
|
|
19923
|
+
};
|
|
19924
|
+
function createRoutingInventoryReader(read = readRoutingRows, addresses = readRoutingAddressPage) {
|
|
19925
|
+
const cache = new Map;
|
|
19926
|
+
const pending = new Map;
|
|
19927
|
+
let generation = 0;
|
|
19928
|
+
return {
|
|
19929
|
+
clear() {
|
|
19930
|
+
generation++;
|
|
19931
|
+
cache.clear();
|
|
19932
|
+
pending.clear();
|
|
19933
|
+
},
|
|
19934
|
+
async read(device, ctx) {
|
|
19935
|
+
const hit = cache.get(device);
|
|
19936
|
+
const ttl = hit && Object.values(hit.value.sections).every((s) => s.state === "ready") ? 20000 : 5000;
|
|
19937
|
+
if (hit && Date.now() - hit.at < ttl)
|
|
19938
|
+
return hit.value;
|
|
19939
|
+
if (pending.has(device))
|
|
19940
|
+
return pending.get(device);
|
|
19941
|
+
const current = generation;
|
|
19942
|
+
const work = (async () => {
|
|
19943
|
+
const sections = {};
|
|
19944
|
+
const deadline = Date.now() + 25000;
|
|
19945
|
+
const entries = Object.entries(routingSections);
|
|
19946
|
+
const worker = async () => {
|
|
19947
|
+
for (let entry = entries.shift();entry; entry = entries.shift()) {
|
|
19948
|
+
const [key, path] = entry;
|
|
19949
|
+
try {
|
|
19950
|
+
if (Date.now() >= deadline)
|
|
19951
|
+
throw new Error("Snapshot time budget reached. Refresh to retry this section.");
|
|
19952
|
+
const result = key.startsWith("addresses") ? await addresses(path, { ...ctx, device }) : { rows: await read(path, undefined, { ...ctx, device }) };
|
|
19953
|
+
sections[key] = { path, ...result, state: "ready", observedAt: Date.now() };
|
|
19954
|
+
} catch (e) {
|
|
19955
|
+
sections[key] = {
|
|
19956
|
+
path,
|
|
19957
|
+
rows: [],
|
|
19958
|
+
state: "error",
|
|
19959
|
+
observedAt: Date.now(),
|
|
19960
|
+
error: e instanceof Error ? e.message : "Routing section could not be read."
|
|
19961
|
+
};
|
|
19962
|
+
}
|
|
19963
|
+
}
|
|
19964
|
+
};
|
|
19965
|
+
await Promise.all([worker(), worker()]);
|
|
19966
|
+
const value = { device, sections, observedAt: Date.now() };
|
|
19967
|
+
if (generation === current)
|
|
19968
|
+
cache.set(device, { at: Date.now(), value });
|
|
19969
|
+
return value;
|
|
19970
|
+
})();
|
|
19971
|
+
pending.set(device, work);
|
|
19972
|
+
try {
|
|
19973
|
+
return await work;
|
|
19974
|
+
} finally {
|
|
19975
|
+
if (pending.get(device) === work)
|
|
19976
|
+
pending.delete(device);
|
|
19977
|
+
}
|
|
19978
|
+
}
|
|
19979
|
+
};
|
|
19980
|
+
}
|
|
19981
|
+
var routerRoutingInventory = createRoutingInventoryReader();
|
|
19982
|
+
onConfigChanged(() => routerRoutingInventory.clear());
|
|
19983
|
+
|
|
19747
19984
|
// src/operations/store.ts
|
|
19748
19985
|
import { mkdirSync as mkdirSync9, chmodSync } from "fs";
|
|
19749
19986
|
import { dirname as dirname9, join as join2 } from "path";
|
|
@@ -19798,6 +20035,76 @@ function operationsStore() {
|
|
|
19798
20035
|
return pending5;
|
|
19799
20036
|
}
|
|
19800
20037
|
|
|
20038
|
+
// src/service-routing/traffic.ts
|
|
20039
|
+
function trafficCommand(policy) {
|
|
20040
|
+
const path = `${routingPath(policy.family)} mangle`;
|
|
20041
|
+
const find = new Cmd(`${path} find`).raw(`where comment=${quoteValue(ownerTag(policy.id))} action=mark-routing`).build();
|
|
20042
|
+
const get = new Cmd(`${path} get`).raw("$srId").build();
|
|
20043
|
+
return `{ :local srIds [${find}]; :if ([:len $srIds] > 1) do={:error "Ambiguous service routing counters"}; :local srItems [:toarray ""]; :foreach srId in=$srIds do={ :local srRow [${get}]; :set ($srRow->".id") $srId; :set ($srRow->"bytes") [:tostr [${get} bytes]]; :set ($srRow->"packets") [:tostr [${get} packets]]; :set ($srItems->[:len $srItems]) $srRow; }; :put [:serialize to=json options=json.no-string-conversion value=$srItems]; }`;
|
|
20044
|
+
}
|
|
20045
|
+
function parsePolicyTraffic(policy, raw, at) {
|
|
20046
|
+
if (raw.length > 32768)
|
|
20047
|
+
throw new Error("Counter response exceeds the bounded read limit.");
|
|
20048
|
+
const rows = parseRoutingRows(raw);
|
|
20049
|
+
const row = rows[0];
|
|
20050
|
+
const base = { policyId: policy.id, device: policy.device, at };
|
|
20051
|
+
const encoded = JSON.parse(raw);
|
|
20052
|
+
if (rows.length !== 1 || !row || !row[".id"] || !enabled3(row) || row.comment !== ownerTag(policy.id) || row.action !== "mark-routing" || row.chain !== `sr-${policy.id.slice(0, 12)}` || row["new-routing-mark"] !== policy.activeTable || typeof encoded[0]?.bytes !== "string" || typeof encoded[0]?.packets !== "string" || !/^\d{1,20}$/.test(row.bytes ?? "") || !/^\d{1,20}$/.test(row.packets ?? "")) {
|
|
20053
|
+
return {
|
|
20054
|
+
...base,
|
|
20055
|
+
state: "unavailable",
|
|
20056
|
+
detail: "The active owned rule or its counters could not be verified. Inspect router configuration; missing data is not zero."
|
|
20057
|
+
};
|
|
20058
|
+
}
|
|
20059
|
+
return {
|
|
20060
|
+
...base,
|
|
20061
|
+
state: "ready",
|
|
20062
|
+
ruleId: row[".id"],
|
|
20063
|
+
table: row["new-routing-mark"],
|
|
20064
|
+
bytes: row.bytes,
|
|
20065
|
+
packets: row.packets,
|
|
20066
|
+
detail: "Client \u2192 service packets matched by this routing mark, since router counter reset. Excludes return/download traffic; not proof of delivery or billing totals."
|
|
20067
|
+
};
|
|
20068
|
+
}
|
|
20069
|
+
var cache2 = new Map;
|
|
20070
|
+
async function readPolicyTraffic(policy, ctx) {
|
|
20071
|
+
if (policy.state !== "active")
|
|
20072
|
+
return {
|
|
20073
|
+
policyId: policy.id,
|
|
20074
|
+
device: policy.device,
|
|
20075
|
+
at: Date.now(),
|
|
20076
|
+
state: "inactive",
|
|
20077
|
+
detail: "Apply and verify this policy before reading its router counters."
|
|
20078
|
+
};
|
|
20079
|
+
const key = JSON.stringify([policy.device, policy.id, policy.activeTable, policy.lastSwitchAt]);
|
|
20080
|
+
const cached = cache2.get(key);
|
|
20081
|
+
if (cached && cached.expires > Date.now())
|
|
20082
|
+
return cached.value;
|
|
20083
|
+
if (cache2.size >= 64)
|
|
20084
|
+
cache2.delete(cache2.keys().next().value);
|
|
20085
|
+
const value = (async () => {
|
|
20086
|
+
try {
|
|
20087
|
+
const raw = await executeMikrotikCommand2(trafficCommand(policy), ctx, { maxMs: 6000 });
|
|
20088
|
+
return parsePolicyTraffic(policy, raw, Date.now());
|
|
20089
|
+
} catch {
|
|
20090
|
+
return {
|
|
20091
|
+
policyId: policy.id,
|
|
20092
|
+
device: policy.device,
|
|
20093
|
+
at: Date.now(),
|
|
20094
|
+
state: "unavailable",
|
|
20095
|
+
detail: "Router counters could not be read. Check device connectivity and retry; no zero values were substituted."
|
|
20096
|
+
};
|
|
20097
|
+
}
|
|
20098
|
+
})();
|
|
20099
|
+
cache2.set(key, { value, expires: Date.now() + 1e4 });
|
|
20100
|
+
value.finally(() => {
|
|
20101
|
+
const entry = cache2.get(key);
|
|
20102
|
+
if (entry?.value === value)
|
|
20103
|
+
entry.expires = Date.now() + 4000;
|
|
20104
|
+
});
|
|
20105
|
+
return value;
|
|
20106
|
+
}
|
|
20107
|
+
|
|
19801
20108
|
// src/service-routing/service.ts
|
|
19802
20109
|
var kind = "service-routing";
|
|
19803
20110
|
function access(ctx, tool, write = false) {
|
|
@@ -19827,9 +20134,11 @@ function save(policy, message) {
|
|
|
19827
20134
|
return operationsStore().then((store) => store.put(kind, policy));
|
|
19828
20135
|
}
|
|
19829
20136
|
async function routingInventory(ctx) {
|
|
19830
|
-
access(ctx, "service_routing_inventory");
|
|
19831
|
-
const
|
|
20137
|
+
const device = access(ctx, "service_routing_inventory");
|
|
20138
|
+
const snapshot = await routerRoutingInventory.read(device, ctx);
|
|
20139
|
+
const tables = snapshot.sections.tables.rows;
|
|
19832
20140
|
return {
|
|
20141
|
+
...snapshot,
|
|
19833
20142
|
tables: tables.filter((r) => enabled3(r) && ["yes", "true"].includes(r.fib)).map((r) => r.name),
|
|
19834
20143
|
targets: Object.entries(getConfig2().serviceProbes.targets).filter(([, t]) => t.kind === "https").map(([alias, t]) => ({ alias, host: t.host }))
|
|
19835
20144
|
};
|
|
@@ -19838,11 +20147,25 @@ async function listRouting(ctx) {
|
|
|
19838
20147
|
const device = access(ctx, "list_service_routing");
|
|
19839
20148
|
return { policies: (await operationsStore()).list(kind, device) };
|
|
19840
20149
|
}
|
|
20150
|
+
async function routingAddressPage(family, offset, ctx) {
|
|
20151
|
+
const device = access(ctx, "service_routing_address_page");
|
|
20152
|
+
return {
|
|
20153
|
+
device,
|
|
20154
|
+
family,
|
|
20155
|
+
offset,
|
|
20156
|
+
...await readRoutingAddressPage(`${routingPath(family)} address-list`, { ...ctx, device }, offset)
|
|
20157
|
+
};
|
|
20158
|
+
}
|
|
19841
20159
|
async function createRouting(input, ctx) {
|
|
19842
20160
|
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")
|
|
20161
|
+
const target = a.target ? getConfig2().serviceProbes.targets[a.target] : undefined;
|
|
20162
|
+
if (a.target && (!target || target.kind !== "https"))
|
|
19845
20163
|
throw new Error("Select an administrator-approved HTTPS probe alias first.");
|
|
20164
|
+
const host = a.domain ?? target?.host.toLowerCase();
|
|
20165
|
+
if (!host)
|
|
20166
|
+
throw new Error("Enter a domain or choose an approved service.");
|
|
20167
|
+
if (target && !domainMatches(host, target.host))
|
|
20168
|
+
throw new Error("The approved probe hostname must match the exact domain or its wildcard subdomains.");
|
|
19846
20169
|
const store = await operationsStore();
|
|
19847
20170
|
if (store.list(kind, device).length >= 100)
|
|
19848
20171
|
throw new Error("Router policy limit reached (100).");
|
|
@@ -19850,7 +20173,8 @@ async function createRouting(input, ctx) {
|
|
|
19850
20173
|
...a,
|
|
19851
20174
|
id: randomUUID8(),
|
|
19852
20175
|
device,
|
|
19853
|
-
host
|
|
20176
|
+
host,
|
|
20177
|
+
probeHost: target?.host,
|
|
19854
20178
|
updatedAt: Date.now(),
|
|
19855
20179
|
state: "draft",
|
|
19856
20180
|
samples: [],
|
|
@@ -19859,29 +20183,41 @@ async function createRouting(input, ctx) {
|
|
|
19859
20183
|
await save(policy, "Draft saved. No router changes or probes yet.");
|
|
19860
20184
|
return policy;
|
|
19861
20185
|
}
|
|
20186
|
+
async function routingTraffic(id, ctx) {
|
|
20187
|
+
const device = access(ctx, "service_routing_traffic");
|
|
20188
|
+
return readPolicyTraffic(await routingPolicy(id, device), { ...ctx, device });
|
|
20189
|
+
}
|
|
19862
20190
|
async function facts(policy, ctx) {
|
|
19863
20191
|
const base = routingPath(policy.family);
|
|
19864
|
-
const tables = await
|
|
19865
|
-
const routes = await
|
|
19866
|
-
const mangle = await
|
|
19867
|
-
const filters = await
|
|
20192
|
+
const tables = await readRoutingRows("/routing table", "name,fib,disabled", ctx);
|
|
20193
|
+
const routes = await readRoutingRows(policy.family === "ipv4" ? "/ip route" : "/ipv6 route", "routing-table,dst-address,gateway,active,disabled,blackhole,type", ctx);
|
|
20194
|
+
const mangle = await readRoutingRows(`${base} mangle`, undefined, ctx);
|
|
20195
|
+
const filters = await readRoutingRows(`${base} filter`, "action,disabled", ctx);
|
|
19868
20196
|
if (policy.family === "ipv4") {
|
|
19869
20197
|
const active = (await checkedRead("/ip firewall connection print count-only where fasttrack=yes", ctx)).trim();
|
|
19870
20198
|
if (!/^\d+$/.test(active) || Number(active) > 0)
|
|
19871
20199
|
throw new Error("Active FastTrack connections must drain before routing can be changed.");
|
|
19872
20200
|
}
|
|
19873
|
-
const vrfs = await
|
|
19874
|
-
const addresses = await
|
|
19875
|
-
|
|
20201
|
+
const vrfs = await readRoutingRows("/ip vrf", "name,interfaces,disabled", ctx);
|
|
20202
|
+
const addresses = await readRoutingRows(`${base} address-list`, "list,address,comment,dynamic,disabled", ctx, [`${ownerTag(policy.id)}-src`, `${ownerTag(policy.id)}-dst`]);
|
|
20203
|
+
const result = { tables, routes, mangle, filters, vrfs, addresses };
|
|
20204
|
+
if (isWildcard(policy.host)) {
|
|
20205
|
+
result.dns = await readRoutingRows("/ip dns static", "name,regexp,type,address-list,match-subdomain,forward-to,disabled,comment", ctx);
|
|
20206
|
+
result.version = (await checkedRead(":put [/system resource get version]", ctx)).trim();
|
|
20207
|
+
result.dnsRemoteRequests = ["yes", "true"].includes((await checkedRead(":put [/ip dns get allow-remote-requests]", ctx)).trim());
|
|
20208
|
+
}
|
|
20209
|
+
return result;
|
|
19876
20210
|
}
|
|
19877
20211
|
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").
|
|
20212
|
+
return `:put [:serialize to=json value=[${new Cmd("/tool fetch").set("address", `${address}@${table}`).set("host", host).set("mode", "https").set("src-path", path).set("port", port).set("http-method", "head").set("check-certificate", "yes").set("http-max-redirect-count", 0).set("idle-timeout", "5s").set("duration", "5s").set("output", "none").raw("as-value").build()}]]`;
|
|
19879
20213
|
}
|
|
19880
20214
|
async function probe(policy, ctx) {
|
|
20215
|
+
if (!policy.target)
|
|
20216
|
+
throw new Error("This is a manual domain route. Add an approved HTTPS probe in a new policy to check exits or authorize failover.");
|
|
19881
20217
|
const target = getConfig2().serviceProbes.targets[policy.target];
|
|
19882
|
-
if (!target || target.kind !== "https" || target.host !== policy.host)
|
|
20218
|
+
if (!target || target.kind !== "https" || target.host !== (policy.probeHost ?? policy.host))
|
|
19883
20219
|
throw new Error("Probe approval changed. Create a new policy.");
|
|
19884
|
-
const vrfs = await
|
|
20220
|
+
const vrfs = await readRoutingRows("/ip vrf", "name,disabled", ctx);
|
|
19885
20221
|
let addresses = [];
|
|
19886
20222
|
try {
|
|
19887
20223
|
addresses = await nativeProbeIO.resolve(target.host, 3000);
|
|
@@ -19943,7 +20279,16 @@ async function preview(policy, table, remove, ctx) {
|
|
|
19943
20279
|
remove,
|
|
19944
20280
|
expiresAt: Date.now() + 120000,
|
|
19945
20281
|
fingerprint: fingerprint(snapshot),
|
|
19946
|
-
commands: planCommands(policy, table, snapshot, remove)
|
|
20282
|
+
commands: planCommands(policy, table, snapshot, remove),
|
|
20283
|
+
warnings: [
|
|
20284
|
+
"IP-based matching includes other services sharing the resolved IPs. Counters measure client-to-service matched packets, not successful delivery or download totals.",
|
|
20285
|
+
...isWildcard(policy.host) ? [
|
|
20286
|
+
"Subdomains only; apex excluded. Clients must query this router DNS. External DNS, client DoH/DoT and previously cached answers can bypass learning. FWD uses existing upstream DNS and bypasses router adlists for matching names, for all DNS clients; no DNS interception or exposure is added."
|
|
20287
|
+
] : [],
|
|
20288
|
+
...policy.precedence === "before-existing" ? [
|
|
20289
|
+
"This scoped policy is inserted before existing routing rules. On shared IPs it takes precedence; other rules are not rewritten. Existing connections may be interrupted."
|
|
20290
|
+
] : []
|
|
20291
|
+
]
|
|
19947
20292
|
};
|
|
19948
20293
|
await save(policy, "Preview created. Review scope and commands; valid for two minutes.");
|
|
19949
20294
|
return policy;
|
|
@@ -19982,6 +20327,8 @@ async function apply(policy, planId, ctx) {
|
|
|
19982
20327
|
if (plan.remove) {
|
|
19983
20328
|
if (after.addresses.some((r) => r.comment === ownerTag(policy.id)))
|
|
19984
20329
|
throw new Error("Owned address-list removal not confirmed.");
|
|
20330
|
+
if (after.dns?.some((r) => r.comment === ownerTag(policy.id)))
|
|
20331
|
+
throw new Error("Owned DNS entry removal not confirmed.");
|
|
19985
20332
|
} else {
|
|
19986
20333
|
planCommands({ ...policy, state: "active", activeTable: plan.table }, plan.table, after);
|
|
19987
20334
|
}
|
|
@@ -19996,7 +20343,9 @@ async function apply(policy, planId, ctx) {
|
|
|
19996
20343
|
policy.plan = undefined;
|
|
19997
20344
|
policy.error = undefined;
|
|
19998
20345
|
await save(policy, plan.remove ? "Owned routing policy removed." : `Routing read-back verified: ${plan.table}. Client delivery still requires a client check.`);
|
|
20346
|
+
routerRoutingInventory.clear();
|
|
19999
20347
|
} catch (error) {
|
|
20348
|
+
routerRoutingInventory.clear();
|
|
20000
20349
|
if (owned && !commitAttempted)
|
|
20001
20350
|
await safe.rollback().catch(() => {});
|
|
20002
20351
|
policy.error = error instanceof Error ? error.message : "Apply failed";
|
|
@@ -20020,6 +20369,8 @@ async function armRouting(id, minutes, confirm, ctx) {
|
|
|
20020
20369
|
return locked(device, async () => {
|
|
20021
20370
|
const policy = await routingPolicy(id, device);
|
|
20022
20371
|
if (minutes) {
|
|
20372
|
+
if (!policy.target)
|
|
20373
|
+
throw new Error("Automatic failover requires an approved HTTPS probe; this is a manual domain route.");
|
|
20023
20374
|
const other = (await operationsStore()).list(kind, device).some((p) => p.id !== id && (p.armedUntil ?? 0) > Date.now());
|
|
20024
20375
|
if (other)
|
|
20025
20376
|
throw new Error("Only one automatic service policy per router can be armed at a time.");
|
|
@@ -20049,19 +20400,42 @@ var serviceRoutingTools = [
|
|
|
20049
20400
|
}),
|
|
20050
20401
|
defineTool2({
|
|
20051
20402
|
name: "service_routing_inventory",
|
|
20052
|
-
title: "
|
|
20403
|
+
title: "Inspect Router Routing Configuration",
|
|
20053
20404
|
annotations: READ,
|
|
20054
|
-
description: "Read
|
|
20405
|
+
description: "Read live IPv4/IPv6 routes, ordered mangle and routing rules, address lists, tables, VRFs and filter rules independently of saved MCP policies. Includes dynamic/disabled entries, per-section failures and observation timestamps; bounded reads, 20-second cache. Missing data is not zero. Also lists enabled FIB exits and approved HTTPS aliases. Table presence is not path health; HTTPS exit probes require a matching VRF. No router changes.",
|
|
20055
20406
|
inputSchema: {},
|
|
20056
20407
|
async handler(_, ctx) {
|
|
20057
20408
|
return JSON.stringify(await routingInventory(ctx));
|
|
20058
20409
|
}
|
|
20059
20410
|
}),
|
|
20411
|
+
defineTool2({
|
|
20412
|
+
name: "service_routing_address_page",
|
|
20413
|
+
title: "Read Routing Address List Page",
|
|
20414
|
+
annotations: READ,
|
|
20415
|
+
description: "Read the next bounded page of this router's IPv4 or IPv6 address-list members. Use nextOffset from service_routing_inventory or the preceding page. At most 200 rows per request; live lists may change between pages. Read-only, no router changes.",
|
|
20416
|
+
inputSchema: {
|
|
20417
|
+
family: _enum(["ipv4", "ipv6"]),
|
|
20418
|
+
offset: number().int().min(0).max(1e6).default(0)
|
|
20419
|
+
},
|
|
20420
|
+
async handler(a, ctx) {
|
|
20421
|
+
return JSON.stringify(await routingAddressPage(a.family, a.offset, ctx));
|
|
20422
|
+
}
|
|
20423
|
+
}),
|
|
20424
|
+
defineTool2({
|
|
20425
|
+
name: "service_routing_traffic",
|
|
20426
|
+
title: "Read Service Routing Traffic",
|
|
20427
|
+
annotations: READ,
|
|
20428
|
+
description: "Read the exact active MCP-owned routing mark's client-to-service byte and packet counters for one saved policy. Decimal strings preserve 64-bit totals. Four-second cache; missing, disabled or modified rules are unavailable, not zero. Excludes return/download traffic and does not prove delivery, DNS coverage or billing usage. No reset or router change.",
|
|
20429
|
+
inputSchema: { id: uuid2() },
|
|
20430
|
+
async handler(a, ctx) {
|
|
20431
|
+
return JSON.stringify(await routingTraffic(a.id, ctx));
|
|
20432
|
+
}
|
|
20433
|
+
}),
|
|
20060
20434
|
defineTool2({
|
|
20061
20435
|
name: "create_service_routing",
|
|
20062
20436
|
title: "Create Service Routing Draft",
|
|
20063
20437
|
annotations: WRITE,
|
|
20064
|
-
description: "Save a single-family
|
|
20438
|
+
description: "Save a single-family exact domain or *.example.com route for explicit client subnets. The wildcard excludes the apex and requires client DNS through this router, existing remote DNS, RouterOS 7.17+ and dnsLearningConfirmed. Wildcard FWD bypasses adlists for matching DNS queries. HTTPS target is optional for manual routing, required for health probes/failover; when domain is absent use the approved target's host (legacy). Shared CDN IPs can affect other services. No router change until preview and explicit apply. Never infer authorization from a draft.",
|
|
20065
20439
|
inputSchema: routingInput.shape,
|
|
20066
20440
|
async handler(a, ctx) {
|
|
20067
20441
|
return JSON.stringify(await createRouting(a, ctx));
|
|
@@ -20081,7 +20455,7 @@ var serviceRoutingTools = [
|
|
|
20081
20455
|
name: "preview_service_routing",
|
|
20082
20456
|
title: "Preview Service Routing Change",
|
|
20083
20457
|
annotations: READ,
|
|
20084
|
-
description: "Read router state and save a two-minute
|
|
20458
|
+
description: "Read router state and save a two-minute state-bound preview for applying/switching or removing owned rules. Reject FastTrack, overlapping wildcard DNS and foreign routing conflicts unless before-existing precedence was explicitly selected. Wildcard plans add an owned DNS FWD learner, not DNS interception. Does not create exits, NAT or change the router until apply.",
|
|
20085
20459
|
inputSchema: {
|
|
20086
20460
|
id: uuid2(),
|
|
20087
20461
|
table: string().min(1).max(64),
|
|
@@ -26776,11 +27150,11 @@ function searchToolIndex(index, query, limit = 8) {
|
|
|
26776
27150
|
|
|
26777
27151
|
// src/tools/tool-gateway.ts
|
|
26778
27152
|
var META_NAMES = new Set(["find_tools", "describe_tool", "invoke_tool"]);
|
|
26779
|
-
var
|
|
27153
|
+
var cache3 = null;
|
|
26780
27154
|
async function gateway() {
|
|
26781
|
-
if (
|
|
26782
|
-
return
|
|
26783
|
-
const { moduleCatalog } = await import("./library-
|
|
27155
|
+
if (cache3)
|
|
27156
|
+
return cache3;
|
|
27157
|
+
const { moduleCatalog } = await import("./library-wj2xfx8h.js");
|
|
26784
27158
|
const forIndex = [];
|
|
26785
27159
|
const byName = new Map;
|
|
26786
27160
|
for (const mod of moduleCatalog) {
|
|
@@ -26798,8 +27172,8 @@ async function gateway() {
|
|
|
26798
27172
|
});
|
|
26799
27173
|
}
|
|
26800
27174
|
}
|
|
26801
|
-
|
|
26802
|
-
return
|
|
27175
|
+
cache3 = { index: buildToolIndex(forIndex), byName };
|
|
27176
|
+
return cache3;
|
|
26803
27177
|
}
|
|
26804
27178
|
function isOptional(field) {
|
|
26805
27179
|
return field.safeParse(undefined).success;
|
|
@@ -40029,8 +40403,235 @@ var wolTools = [
|
|
|
40029
40403
|
})
|
|
40030
40404
|
];
|
|
40031
40405
|
|
|
40406
|
+
// src/core/openvpn-sessions.ts
|
|
40407
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
40408
|
+
|
|
40409
|
+
// src/core/openvpn-sessions-model.ts
|
|
40410
|
+
function openVpnUptime(value) {
|
|
40411
|
+
const clock = /^(?:(\d+)w)?(?:(\d+)d)?(\d{1,3}):(\d{2}):(\d{2})(?:\.(\d+))?$/.exec(value);
|
|
40412
|
+
if (clock) {
|
|
40413
|
+
if (+clock[4] > 59 || +clock[5] > 59)
|
|
40414
|
+
return null;
|
|
40415
|
+
return +(clock[1] || 0) * 604800 + +(clock[2] || 0) * 86400 + +clock[3] * 3600 + +clock[4] * 60 + +clock[5];
|
|
40416
|
+
}
|
|
40417
|
+
if (!/^(?=\d)(?:\d+w)?(?:\d+d)?(?:\d+h)?(?:\d+m)?(?:\d+(?:\.\d+)?s)?$/.test(value))
|
|
40418
|
+
return null;
|
|
40419
|
+
const units = { w: 604800, d: 86400, h: 3600, m: 60, s: 1 };
|
|
40420
|
+
const seconds = [...value.matchAll(/(\d+(?:\.\d+)?)([wdhms])/g)].reduce((total, part) => total + +part[1] * units[part[2]], 0);
|
|
40421
|
+
return Number.isSafeInteger(Math.floor(seconds)) ? Math.floor(seconds) : null;
|
|
40422
|
+
}
|
|
40423
|
+
|
|
40424
|
+
// src/core/openvpn-sessions.ts
|
|
40425
|
+
var SESSION_LIMIT = 1000;
|
|
40426
|
+
var TICKET_TTL = 60000;
|
|
40427
|
+
var tickets = new Map;
|
|
40428
|
+
var cache4 = new Map;
|
|
40429
|
+
|
|
40430
|
+
class OpenVpnOperationError extends Error {
|
|
40431
|
+
status;
|
|
40432
|
+
constructor(status, message) {
|
|
40433
|
+
super(message);
|
|
40434
|
+
this.status = status;
|
|
40435
|
+
}
|
|
40436
|
+
}
|
|
40437
|
+
var disconnectOpenVpnInput = object({
|
|
40438
|
+
token: string().uuid().describe("Fresh disconnectToken from list_ovpn_sessions on this router; expires after 60 seconds and is single-use."),
|
|
40439
|
+
confirm: literal(true).describe("Explicit operator approval to terminate this one live connection. The client can reconnect.")
|
|
40440
|
+
});
|
|
40441
|
+
function access4(ctx, write = false) {
|
|
40442
|
+
if (!ctx.device)
|
|
40443
|
+
throw new OpenVpnOperationError(400, "Select an explicit router first.");
|
|
40444
|
+
let device;
|
|
40445
|
+
try {
|
|
40446
|
+
device = resolveDeviceName2(ctx.device);
|
|
40447
|
+
} catch {
|
|
40448
|
+
throw new OpenVpnOperationError(400, "Unknown router. Select an enabled router first.");
|
|
40449
|
+
}
|
|
40450
|
+
try {
|
|
40451
|
+
assertDeviceAccess([device], write ? "disconnect_ovpn_session" : "list_ovpn_sessions", write ? "DESTRUCTIVE" : "READ");
|
|
40452
|
+
} catch (e) {
|
|
40453
|
+
throw new OpenVpnOperationError(403, e instanceof Error ? e.message : "Device access denied.");
|
|
40454
|
+
}
|
|
40455
|
+
return device;
|
|
40456
|
+
}
|
|
40457
|
+
function openVpnSessionsCommand() {
|
|
40458
|
+
const find = new Cmd("/ppp active find where").set("service", "ovpn").build();
|
|
40459
|
+
const read = new Cmd("/ppp active print").raw("detail as-value").raw("where").set("service", "ovpn").build();
|
|
40460
|
+
return `{ :if ([:len [${find}]] > ${SESSION_LIMIT}) do={ :error "OpenVPN session limit exceeded" }; :local rows [:toarray ""]; :foreach row in=[${read}] do={ :set ($row->"uptime") [:tostr ($row->"uptime")]; :set ($row->"session-id") [:tostr ($row->"session-id")]; :set ($rows->[:len $rows]) $row }; :put [:serialize to=json options=json.no-string-conversion value=$rows] }`;
|
|
40461
|
+
}
|
|
40462
|
+
function parseOpenVpnSessions(output) {
|
|
40463
|
+
if (output.length > 1e6)
|
|
40464
|
+
throw new Error("OpenVPN session response is too large; no partial list is shown.");
|
|
40465
|
+
let rows;
|
|
40466
|
+
try {
|
|
40467
|
+
rows = JSON.parse(output.trim());
|
|
40468
|
+
} catch {
|
|
40469
|
+
throw new Error("Could not read OpenVPN sessions. Check router connectivity and RouterOS JSON support.");
|
|
40470
|
+
}
|
|
40471
|
+
if (!Array.isArray(rows) || rows.length > SESSION_LIMIT)
|
|
40472
|
+
throw new Error("Invalid OpenVPN session snapshot.");
|
|
40473
|
+
const ids = new Set;
|
|
40474
|
+
return rows.map((row) => {
|
|
40475
|
+
const r = object({
|
|
40476
|
+
".id": string().regex(/^\*[A-Fa-f0-9]+$/),
|
|
40477
|
+
name: string().min(1),
|
|
40478
|
+
service: literal("ovpn"),
|
|
40479
|
+
address: string().default(""),
|
|
40480
|
+
"caller-id": string().default(""),
|
|
40481
|
+
"session-id": string().default(""),
|
|
40482
|
+
uptime: string().default(""),
|
|
40483
|
+
encoding: string().default(""),
|
|
40484
|
+
radius: union([boolean(), string()]).optional()
|
|
40485
|
+
}).parse(row);
|
|
40486
|
+
if (ids.has(r[".id"]))
|
|
40487
|
+
throw new Error("Duplicate OpenVPN session identifier; refresh required.");
|
|
40488
|
+
ids.add(r[".id"]);
|
|
40489
|
+
return {
|
|
40490
|
+
id: r[".id"],
|
|
40491
|
+
name: r.name,
|
|
40492
|
+
address: r.address,
|
|
40493
|
+
callerId: r["caller-id"],
|
|
40494
|
+
sessionId: r["session-id"],
|
|
40495
|
+
encoding: r.encoding,
|
|
40496
|
+
radius: r.radius === true || r.radius === "yes" || r.radius === "true",
|
|
40497
|
+
uptime: r.uptime,
|
|
40498
|
+
uptimeSeconds: openVpnUptime(r.uptime)
|
|
40499
|
+
};
|
|
40500
|
+
});
|
|
40501
|
+
}
|
|
40502
|
+
async function read(ctx) {
|
|
40503
|
+
const output = await executeMikrotikCommand2(openVpnSessionsCommand(), ctx, { maxMs: 1e4 });
|
|
40504
|
+
return parseOpenVpnSessions(output);
|
|
40505
|
+
}
|
|
40506
|
+
async function listOpenVpnSessions(ctx) {
|
|
40507
|
+
const device = access4(ctx);
|
|
40508
|
+
let canDisconnect = true;
|
|
40509
|
+
try {
|
|
40510
|
+
access4(ctx, true);
|
|
40511
|
+
} catch {
|
|
40512
|
+
canDisconnect = false;
|
|
40513
|
+
}
|
|
40514
|
+
let entry = cache4.get(device);
|
|
40515
|
+
if (!entry || entry.expires < Date.now()) {
|
|
40516
|
+
if (cache4.size >= 64)
|
|
40517
|
+
cache4.delete(cache4.keys().next().value);
|
|
40518
|
+
const next = {
|
|
40519
|
+
expires: Infinity,
|
|
40520
|
+
promise: Promise.resolve(null)
|
|
40521
|
+
};
|
|
40522
|
+
next.promise = read(ctx).then((sessions) => {
|
|
40523
|
+
const at = Date.now();
|
|
40524
|
+
for (const [token, ticket] of tickets)
|
|
40525
|
+
if (at - ticket.at >= TICKET_TTL)
|
|
40526
|
+
tickets.delete(token);
|
|
40527
|
+
for (const session of sessions) {
|
|
40528
|
+
if (!session.sessionId || session.uptimeSeconds === null)
|
|
40529
|
+
continue;
|
|
40530
|
+
if (tickets.size >= 1e4)
|
|
40531
|
+
tickets.delete(tickets.keys().next().value);
|
|
40532
|
+
session.disconnectToken = randomUUID9();
|
|
40533
|
+
tickets.set(session.disconnectToken, { device, at, session });
|
|
40534
|
+
}
|
|
40535
|
+
next.expires = at + 2000;
|
|
40536
|
+
return { device, observedAt: at, sessions, canDisconnect: true };
|
|
40537
|
+
}).catch((error) => {
|
|
40538
|
+
if (cache4.get(device) === next)
|
|
40539
|
+
cache4.delete(device);
|
|
40540
|
+
throw error;
|
|
40541
|
+
});
|
|
40542
|
+
cache4.set(device, next);
|
|
40543
|
+
entry = next;
|
|
40544
|
+
}
|
|
40545
|
+
return { ...await entry.promise, canDisconnect };
|
|
40546
|
+
}
|
|
40547
|
+
function disconnectOpenVpnCommand(session) {
|
|
40548
|
+
const literal2 = (value) => {
|
|
40549
|
+
const quoted = quoteValue(value);
|
|
40550
|
+
return quoted.startsWith('"') ? quoted : `"${quoted}"`;
|
|
40551
|
+
};
|
|
40552
|
+
const find = new Cmd("/ppp active find where").raw(`.id=${quoteValue(session.id)}`).set("service", "ovpn").build();
|
|
40553
|
+
const checks = [
|
|
40554
|
+
["name", session.name],
|
|
40555
|
+
["address", session.address],
|
|
40556
|
+
["caller-id", session.callerId],
|
|
40557
|
+
["session-id", session.sessionId]
|
|
40558
|
+
].map(([field, value]) => `([:tostr [/ppp active get $id ${field}]] != ${literal2(value)})`).join(" || ");
|
|
40559
|
+
return `{ :local ids [${find}]; :if ([:len $ids] = 0) do={ :put "ovpn:gone" } else={ :if ([:len $ids] != 1) do={ :error "Ambiguous session" }; :local id [:pick $ids 0]; :if (${checks} || ([/ppp active get $id uptime] < [:totime ${literal2(session.uptime)}])) do={ :put "ovpn:changed" } else={ ${new Cmd("/ppp active remove").raw("$id").build()}; :put "ovpn:sent" } } }`;
|
|
40560
|
+
}
|
|
40561
|
+
async function disconnectOpenVpnSession(input, ctx) {
|
|
40562
|
+
const device = access4(ctx, true);
|
|
40563
|
+
const { token } = disconnectOpenVpnInput.parse(input);
|
|
40564
|
+
const ticket = tickets.get(token);
|
|
40565
|
+
if (!ticket || ticket.device !== device || Date.now() - ticket.at >= TICKET_TTL)
|
|
40566
|
+
throw new OpenVpnOperationError(409, "This session selection expired or belongs to another router. Refresh and select it again.");
|
|
40567
|
+
if (getSafeModeManager2(device).isActive)
|
|
40568
|
+
throw new OpenVpnOperationError(409, "Finish the current Safe Mode session first. Disconnecting a live connection cannot be rolled back.");
|
|
40569
|
+
tickets.delete(token);
|
|
40570
|
+
cache4.delete(device);
|
|
40571
|
+
const { session } = ticket;
|
|
40572
|
+
let output;
|
|
40573
|
+
try {
|
|
40574
|
+
output = (await executeMikrotikCommand2(disconnectOpenVpnCommand(session), ctx, { maxMs: 1e4 })).trim();
|
|
40575
|
+
} catch {
|
|
40576
|
+
return {
|
|
40577
|
+
status: "unverified",
|
|
40578
|
+
message: "The disconnect outcome is unknown. Refresh the sessions before any further action; do not retry this request."
|
|
40579
|
+
};
|
|
40580
|
+
}
|
|
40581
|
+
if (output === "ovpn:gone")
|
|
40582
|
+
return {
|
|
40583
|
+
status: "already-ended",
|
|
40584
|
+
message: "This connection has already ended. No other connection was changed."
|
|
40585
|
+
};
|
|
40586
|
+
if (output === "ovpn:changed")
|
|
40587
|
+
throw new OpenVpnOperationError(409, "The selected connection changed. Nothing was disconnected; refresh and select the current session.");
|
|
40588
|
+
if (output !== "ovpn:sent" || looksLikeError(output))
|
|
40589
|
+
return {
|
|
40590
|
+
status: "unverified",
|
|
40591
|
+
message: "The router did not confirm disconnection. Refresh to reconcile; this request will not be replayed."
|
|
40592
|
+
};
|
|
40593
|
+
try {
|
|
40594
|
+
const current = await read(ctx);
|
|
40595
|
+
if (current.some((s) => s.id === session.id && s.sessionId === session.sessionId))
|
|
40596
|
+
return {
|
|
40597
|
+
status: "unverified",
|
|
40598
|
+
message: "The disconnect was sent, but the selected session is still listed. Refresh before another action."
|
|
40599
|
+
};
|
|
40600
|
+
const reconnected = current.some((s) => s.name === session.name);
|
|
40601
|
+
return {
|
|
40602
|
+
status: "disconnected",
|
|
40603
|
+
message: reconnected ? "Selected connection ended. Another connection for this user is active; it was not touched." : "Selected connection ended. The account is unchanged and can reconnect."
|
|
40604
|
+
};
|
|
40605
|
+
} catch {
|
|
40606
|
+
return {
|
|
40607
|
+
status: "unverified",
|
|
40608
|
+
message: "Disconnect sent, but read-back failed. Refresh when the router is reachable; do not replay this request."
|
|
40609
|
+
};
|
|
40610
|
+
}
|
|
40611
|
+
}
|
|
40612
|
+
|
|
40032
40613
|
// src/tools/openvpn.ts
|
|
40033
40614
|
var openvpnTools = [
|
|
40615
|
+
defineTool2({
|
|
40616
|
+
name: "list_ovpn_sessions",
|
|
40617
|
+
title: "List Active OpenVPN Connections",
|
|
40618
|
+
annotations: READ,
|
|
40619
|
+
description: "Read currently connected OpenVPN users on an explicit router, including assigned IP, caller address, uptime, encoding and RADIUS status. Reads only /ppp active where service=ovpn; does not read secrets, historical sessions, or outbound clients. Returns structured JSON and short-lived disconnect tokens for individual sessions. A cached read is at most two seconds old; errors are not an empty list.",
|
|
40620
|
+
inputSchema: {},
|
|
40621
|
+
async handler(_a, ctx) {
|
|
40622
|
+
return JSON.stringify(await listOpenVpnSessions(ctx));
|
|
40623
|
+
}
|
|
40624
|
+
}),
|
|
40625
|
+
defineTool2({
|
|
40626
|
+
name: "disconnect_ovpn_session",
|
|
40627
|
+
title: "Disconnect One OpenVPN Connection",
|
|
40628
|
+
annotations: DESTRUCTIVE,
|
|
40629
|
+
description: "Disconnect exactly one observed OpenVPN connection after explicit operator approval. First list_ovpn_sessions on the same explicit router, then supply its fresh disconnectToken. Rechecks internal ID, session ID, username, addresses and uptime before removal, then verifies absence. Does not disable or delete the account; clients can reconnect and PPP on-down hooks may run. Can interrupt your own management tunnel. Unknown outcomes must be reconciled by reading again, never automatically retried. Not available during Safe Mode.",
|
|
40630
|
+
inputSchema: disconnectOpenVpnInput.shape,
|
|
40631
|
+
async handler(a, ctx) {
|
|
40632
|
+
return JSON.stringify(await disconnectOpenVpnSession(a, ctx));
|
|
40633
|
+
}
|
|
40634
|
+
}),
|
|
40034
40635
|
defineTool2({
|
|
40035
40636
|
name: "get_ovpn_server",
|
|
40036
40637
|
title: "Get OpenVPN Server Configuration",
|
|
@@ -48779,7 +49380,7 @@ var riskByTool = null;
|
|
|
48779
49380
|
async function riskIndex() {
|
|
48780
49381
|
if (riskByTool)
|
|
48781
49382
|
return riskByTool;
|
|
48782
|
-
const { moduleCatalog } = await import("./library-
|
|
49383
|
+
const { moduleCatalog } = await import("./library-wj2xfx8h.js");
|
|
48783
49384
|
const index = new Map;
|
|
48784
49385
|
for (const mod of moduleCatalog) {
|
|
48785
49386
|
for (const tool of mod.tools)
|
|
@@ -52289,11 +52890,11 @@ var serverPulseTools = [
|
|
|
52289
52890
|
];
|
|
52290
52891
|
|
|
52291
52892
|
// src/observability/config-admin.ts
|
|
52292
|
-
import { createHash as createHash9, randomUUID as
|
|
52893
|
+
import { createHash as createHash9, randomUUID as randomUUID11 } from "crypto";
|
|
52293
52894
|
import { readFileSync as readFileSync10 } from "fs";
|
|
52294
52895
|
|
|
52295
52896
|
// src/config-write.ts
|
|
52296
|
-
import { randomUUID as
|
|
52897
|
+
import { randomUUID as randomUUID10 } from "crypto";
|
|
52297
52898
|
import {
|
|
52298
52899
|
closeSync,
|
|
52299
52900
|
constants,
|
|
@@ -52322,7 +52923,7 @@ function backupName(path, ts) {
|
|
|
52322
52923
|
}
|
|
52323
52924
|
function atomicWrite(path, text) {
|
|
52324
52925
|
mkdirSync16(dirname17(path), { recursive: true });
|
|
52325
|
-
const tmp = `${path}.tmp-${
|
|
52926
|
+
const tmp = `${path}.tmp-${randomUUID10()}`;
|
|
52326
52927
|
try {
|
|
52327
52928
|
writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx", flush: true });
|
|
52328
52929
|
try {
|
|
@@ -52354,7 +52955,7 @@ function writeMountedFile(path, text) {
|
|
|
52354
52955
|
throw new Error("Configuration target must be a regular file.");
|
|
52355
52956
|
fchmodSync(fd, 384);
|
|
52356
52957
|
const previous = readFileSync9(fd);
|
|
52357
|
-
const backup = `${path}.bak-mounted-${
|
|
52958
|
+
const backup = `${path}.bak-mounted-${randomUUID10()}`;
|
|
52358
52959
|
writeFileSync4(backup, previous, { mode: 384, flag: "wx", flush: true });
|
|
52359
52960
|
try {
|
|
52360
52961
|
replaceContents(fd, Buffer.from(text, "utf8"));
|
|
@@ -52375,7 +52976,7 @@ function writeMountedFile(path, text) {
|
|
|
52375
52976
|
function createConfigAdmin(deps) {
|
|
52376
52977
|
let pending = null;
|
|
52377
52978
|
let lastTimestamp = 0;
|
|
52378
|
-
const salt =
|
|
52979
|
+
const salt = randomUUID11();
|
|
52379
52980
|
const fingerprint = (config, source, contents) => createHash9("sha256").update(salt).update(JSON.stringify([config, source, contents])).digest("hex");
|
|
52380
52981
|
const revision = () => {
|
|
52381
52982
|
const source = deps.source();
|