@usex/mikrotik-mcp 5.20.0 → 5.22.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/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-cvt06346.js")).openSnapshotStore;
21896
- const db = await beforeTarget((await import("./shared/cli-426pkqe9.js")).DEFAULT_SNAPSHOT_DB);
21895
+ const beforeTarget = (await import("./shared/cli-v5brt13c.js")).openSnapshotStore;
21896
+ const db = await beforeTarget((await import("./shared/cli-8tmbrnm5.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-z1kavk0z.js");
21901
+ const { normalizeExport } = await import("./shared/cli-a5tef6t8.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("Approved HTTPS alias in serviceProbes.targets; its exact hostname is routed"),
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(facts, (key, value) => ["#", ".id", "bytes", "packets", "last-handshake", "expires-after"].includes(key) ? undefined : value)).digest("hex");
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
- result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-dst`).set("address", policy.host).set("comment", tag).build());
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 tables = await rows("/routing table", "name,fib,disabled", ctx);
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: target.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 rows("/routing table", "name,fib,disabled", ctx);
27136
- const routes = await rows(policy.family === "ipv4" ? "/ip route" : "/ipv6 route", "routing-table,dst-address,gateway,active,disabled", ctx);
27137
- const mangle = await rows(`${base} mangle`, "chain,action,new-routing-mark,jump-target,src-address-list,dst-address-list,dst-address-type,dst-address,passthrough,disabled,comment", ctx);
27138
- const filters = await rows(`${base} filter`, "action,disabled", ctx);
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 rows("/ip vrf", "name,interfaces,disabled", ctx);
27145
- const addresses = await rows(`${base} address-list`, "list,address,comment,dynamic,disabled", ctx);
27146
- return { tables, routes, mangle, filters, vrfs, addresses };
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").flag("as-value", true).build()}]]`;
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 rows("/ip vrf", "name,disabled", ctx);
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: "Discover Service Routing Exits",
27724
+ title: "Inspect Router Routing Configuration",
27374
27725
  annotations: READ,
27375
- description: "Read enabled FIB tables and administrator-approved HTTPS target aliases. A table is not proof of a working path; HTTPS per-exit probes require a matching VRF.",
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 policy for one approved exact hostname and explicit client subnets. No router changes. Create separate IPv4/IPv6 policies. Shared CDN IPs can affect other services. Preview, then explicitly confirm apply; never infer authorization from a draft.",
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, state-bound preview for applying/switching or removing only owned rules. Reject FastTrack and foreign policy-routing conflicts. Does not create exits, NAT, DNS interception or change router configuration.",
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 cache2 = null;
34636
+ var cache3 = null;
34263
34637
  async function gateway() {
34264
- if (cache2)
34265
- return cache2;
34266
- const { moduleCatalog } = await import("./shared/cli-6wdstvdq.js");
34638
+ if (cache3)
34639
+ return cache3;
34640
+ const { moduleCatalog } = await import("./shared/cli-0v69rn38.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
- cache2 = { index: buildToolIndex(forIndex), byName };
34285
- return cache2;
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",
@@ -48976,6 +49577,109 @@ ${details}`;
48976
49577
  })
48977
49578
  ];
48978
49579
 
49580
+ // src/tools/um-user-profile.ts
49581
+ var assignmentSchema = array(object({
49582
+ ".id": string2().regex(/^\*[0-9a-f]+$/i),
49583
+ user: string2(),
49584
+ profile: string2(),
49585
+ state: _enum(["running-active", "running active", "running", "used"])
49586
+ })).max(1000);
49587
+ var active3 = (row) => row.state.replaceAll(" ", "-") === "running-active";
49588
+ async function assignments(ctx, user) {
49589
+ const query = new Cmd("/user-manager user-profile print").raw("as-value where").set("user", user).build();
49590
+ const output = await executeMikrotikCommand(`:put [:serialize to=json value=[${query}] options=json.no-string-conversion]`, ctx);
49591
+ if (output.length > 1e6)
49592
+ throw new Error("Assignment response too large");
49593
+ const rows = assignmentSchema.parse(JSON.parse(output));
49594
+ if (rows.some((row) => row.user !== user) || new Set(rows.map((row) => row[".id"])).size !== rows.length)
49595
+ throw new Error("Invalid assignment identities");
49596
+ return rows;
49597
+ }
49598
+ async function updateUmUserWithProfile(ctx, user, profile, pairs) {
49599
+ if (typeof profile !== "string" || !profile.trim() || !user.trim())
49600
+ return { ok: false, message: "A user name and a valid profile name are required." };
49601
+ const renamed = pairs.find(([key]) => key === "name")?.[1] ?? user;
49602
+ if (typeof renamed !== "string" || !renamed.trim())
49603
+ return { ok: false, message: "A valid user name is required." };
49604
+ let writeAttempted = false;
49605
+ try {
49606
+ for (const [menu, name] of [
49607
+ ["user", user],
49608
+ ["profile", profile]
49609
+ ]) {
49610
+ const count = await executeMikrotikCommand(new Cmd(`/user-manager ${menu} print count-only where`).set("name", name).build(), ctx);
49611
+ if (count.trim() !== "1")
49612
+ return {
49613
+ ok: false,
49614
+ message: `The selected ${menu} could not be verified on this device. Refresh before saving.`
49615
+ };
49616
+ }
49617
+ let rows = await assignments(ctx, user);
49618
+ if (rows.filter(active3).length > 1)
49619
+ return {
49620
+ ok: false,
49621
+ message: "Multiple active profiles were returned. Review Assignments before saving."
49622
+ };
49623
+ const eligible = rows.filter((row) => row.profile === profile && row.state !== "used");
49624
+ let target = eligible.find(active3) ?? (eligible.length === 1 ? eligible[0] : undefined);
49625
+ if (!target && eligible.length > 1)
49626
+ return {
49627
+ ok: false,
49628
+ message: "Multiple pending assignments use this profile. Review Assignments before saving."
49629
+ };
49630
+ const write = async (command) => {
49631
+ writeAttempted = true;
49632
+ const output = await executeMikrotikCommand(command, ctx);
49633
+ if (commandUnsupported(output) || looksLikeError(output))
49634
+ throw new Error("Router rejected update");
49635
+ };
49636
+ if (pairs.length) {
49637
+ const selector = new Cmd("find where").set("name", user).build();
49638
+ const command = new Cmd("/user-manager user set").raw(`[${selector}]`);
49639
+ for (const [key, value] of pairs)
49640
+ command.set(key, value);
49641
+ await write(command.build());
49642
+ }
49643
+ rows = await assignments(ctx, renamed);
49644
+ if (target) {
49645
+ const targetId = target[".id"];
49646
+ target = rows.find((row) => row[".id"] === targetId && row.profile === profile && row.state !== "used");
49647
+ if (!target)
49648
+ throw new Error("Assignment changed during save");
49649
+ } else {
49650
+ if (rows.some((row) => row.profile === profile && row.state !== "used"))
49651
+ throw new Error("Assignments changed during save");
49652
+ const previousIds = new Set(rows.map((row) => row[".id"]));
49653
+ await write(new Cmd("/user-manager user-profile add").set("user", renamed).set("profile", profile).build());
49654
+ rows = await assignments(ctx, renamed);
49655
+ const added = rows.filter((row) => !previousIds.has(row[".id"]) && row.profile === profile && row.state !== "used");
49656
+ if (added.length !== 1)
49657
+ throw new Error("New assignment could not be verified");
49658
+ target = added[0];
49659
+ }
49660
+ if (!active3(target)) {
49661
+ const selector = new Cmd("find where").set(".id", target[".id"]).set("user", renamed).set("profile", profile).build();
49662
+ await write(new Cmd("/user-manager user-profile activate-user-profile").raw(`[${selector}]`).build());
49663
+ }
49664
+ const current = (await assignments(ctx, renamed)).filter(active3);
49665
+ if (current.length !== 1 || current[0][".id"] !== target[".id"] || current[0].profile !== profile)
49666
+ throw new Error("Activation could not be verified");
49667
+ return {
49668
+ ok: true,
49669
+ message: `User saved. Active profile: ${profile}. Existing connections may need to reconnect for new limits.`
49670
+ };
49671
+ } catch {
49672
+ return writeAttempted ? {
49673
+ ok: false,
49674
+ reviewRequired: true,
49675
+ message: "Save could not be fully confirmed. User settings or profile assignments may have changed. Refresh Users and check Assignments before trying again; no automatic retry was made."
49676
+ } : {
49677
+ ok: false,
49678
+ message: "Could not verify this user's profile assignments. No changes were made. Check connectivity and refresh before saving."
49679
+ };
49680
+ }
49681
+ }
49682
+
48979
49683
  // src/tools/aaa-data.ts
48980
49684
  var UM_NOT_AVAILABLE = "User Manager is not available on this device (the user-manager package is not installed).";
48981
49685
  var SECRET_KEYS = new Set(["secret", "password", "shared-secret", "otp-secret"]);
@@ -49175,6 +49879,8 @@ async function updateAaaEntity(ctx, slug, id, fields) {
49175
49879
  if (entity.readonly)
49176
49880
  return { ok: false, message: `${slug} is read-only.` };
49177
49881
  const pairs = pickFields(entity, fields);
49882
+ if (slug === "um-users" && fields.profile !== undefined && fields.profile !== "")
49883
+ return updateUmUserWithProfile(ctx, id, fields.profile, pairs);
49178
49884
  if (pairs.length === 0)
49179
49885
  return { ok: false, message: "No updates supplied." };
49180
49886
  const cmd = applyFields(new Cmd(`/${entity.menu} set ${findClause(entity, id)}`), pairs).build();
@@ -56510,7 +57216,7 @@ var riskByTool = null;
56510
57216
  async function riskIndex() {
56511
57217
  if (riskByTool)
56512
57218
  return riskByTool;
56513
- const { moduleCatalog } = await import("./shared/cli-6wdstvdq.js");
57219
+ const { moduleCatalog } = await import("./shared/cli-0v69rn38.js");
56514
57220
  const index = new Map;
56515
57221
  for (const mod of moduleCatalog) {
56516
57222
  for (const tool of mod.tools)
@@ -60145,11 +60851,11 @@ var serverPulseTools = [
60145
60851
  ];
60146
60852
 
60147
60853
  // src/observability/config-admin.ts
60148
- import { createHash as createHash10, randomUUID as randomUUID10 } from "crypto";
60854
+ import { createHash as createHash10, randomUUID as randomUUID11 } from "crypto";
60149
60855
  import { readFileSync as readFileSync10 } from "fs";
60150
60856
 
60151
60857
  // src/config-write.ts
60152
- import { randomUUID as randomUUID9 } from "crypto";
60858
+ import { randomUUID as randomUUID10 } from "crypto";
60153
60859
  import {
60154
60860
  closeSync,
60155
60861
  constants,
@@ -60169,14 +60875,20 @@ import { dirname as dirname17 } from "path";
60169
60875
 
60170
60876
  // src/config-device-draft.ts
60171
60877
  var CREDENTIAL_SOURCE = "$credentialsFrom";
60878
+ function ownsConfigKey(key, scope) {
60879
+ if (scope === "serviceProbes")
60880
+ return key === "serviceProbes";
60881
+ const deviceKey = key === "devices" || key === "defaultDevice";
60882
+ return scope === "devices" ? deviceKey : !deviceKey;
60883
+ }
60172
60884
  function selectConfigScope(cfg, scope) {
60173
- return Object.fromEntries(Object.entries(cfg).filter(([key]) => scope === "devices" ? key === "devices" || key === "defaultDevice" : key !== "devices" && key !== "defaultDevice"));
60885
+ return Object.fromEntries(Object.entries(cfg).filter(([key]) => ownsConfigKey(key, scope)));
60174
60886
  }
60175
60887
  function scopeConfigDraft(raw, current, scope) {
60176
60888
  if (!raw || typeof raw !== "object" || Array.isArray(raw))
60177
60889
  return raw;
60178
60890
  return {
60179
- ...selectConfigScope(current, scope === "devices" ? "server" : "devices"),
60891
+ ...Object.fromEntries(Object.entries(current).filter(([key]) => !ownsConfigKey(key, scope))),
60180
60892
  ...selectConfigScope(raw, scope)
60181
60893
  };
60182
60894
  }
@@ -60239,7 +60951,7 @@ function backupName(path, ts) {
60239
60951
  }
60240
60952
  function atomicWrite(path, text) {
60241
60953
  mkdirSync16(dirname17(path), { recursive: true });
60242
- const tmp = `${path}.tmp-${randomUUID9()}`;
60954
+ const tmp = `${path}.tmp-${randomUUID10()}`;
60243
60955
  try {
60244
60956
  writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx", flush: true });
60245
60957
  try {
@@ -60271,7 +60983,7 @@ function writeMountedFile(path, text) {
60271
60983
  throw new Error("Configuration target must be a regular file.");
60272
60984
  fchmodSync(fd, 384);
60273
60985
  const previous = readFileSync9(fd);
60274
- const backup = `${path}.bak-mounted-${randomUUID9()}`;
60986
+ const backup = `${path}.bak-mounted-${randomUUID10()}`;
60275
60987
  writeFileSync4(backup, previous, { mode: 384, flag: "wx", flush: true });
60276
60988
  try {
60277
60989
  replaceContents(fd, Buffer.from(text, "utf8"));
@@ -60304,7 +61016,7 @@ function validateConfig(raw) {
60304
61016
  function createConfigAdmin(deps) {
60305
61017
  let pending = null;
60306
61018
  let lastTimestamp = 0;
60307
- const salt = randomUUID10();
61019
+ const salt = randomUUID11();
60308
61020
  const fingerprint = (config, source, contents) => createHash10("sha256").update(salt).update(JSON.stringify([config, source, contents])).digest("hex");
60309
61021
  const revision = () => {
60310
61022
  const source = deps.source();
@@ -67609,7 +68321,7 @@ function applyModuleToggle(filter, slug, enabled) {
67609
68321
  // src/observability/ssh-key-inventory.ts
67610
68322
  import { createHash as createHash11 } from "crypto";
67611
68323
  import { constants as constants2 } from "fs";
67612
- import { access as access4, lstat, open as open2, readdir } from "fs/promises";
68324
+ import { access as access5, lstat, open as open2, readdir } from "fs/promises";
67613
68325
  import { homedir as homedir3 } from "os";
67614
68326
  import { basename as basename2, join as join10, resolve as resolve4 } from "path";
67615
68327
  import { utils } from "ssh2";
@@ -67653,7 +68365,7 @@ async function listSshKeys(configuredPaths, directory = join10(homedir3(), ".ssh
67653
68365
  try {
67654
68366
  const privateStat = await lstat(path);
67655
68367
  if (privateStat.isFile() && privateStat.size > 0) {
67656
- await access4(path, constants2.R_OK);
68368
+ await access5(path, constants2.R_OK);
67657
68369
  usable = true;
67658
68370
  }
67659
68371
  } catch {}
@@ -68031,6 +68743,8 @@ var routing = {
68031
68743
  "POST /api/flight-recorder/export": "export_network_incident",
68032
68744
  "GET /api/service-routing": "list_service_routing",
68033
68745
  "GET /api/service-routing/inventory": "service_routing_inventory",
68746
+ "GET /api/service-routing/addresses": "service_routing_address_page",
68747
+ "GET /api/service-routing/traffic": "service_routing_traffic",
68034
68748
  "POST /api/service-routing": "create_service_routing",
68035
68749
  "POST /api/service-routing/probe": "probe_service_routing",
68036
68750
  "POST /api/service-routing/preview": "preview_service_routing",
@@ -68044,7 +68758,10 @@ async function operationsRoutes(req, url) {
68044
68758
  if (!tool)
68045
68759
  return Response.json({ error: "Unsupported workspace operation" }, { status: 405 });
68046
68760
  try {
68047
- const input = req.method === "POST" ? JSON.parse(await readOperationBody(req)) : {};
68761
+ const input = req.method === "POST" ? JSON.parse(await readOperationBody(req)) : url.pathname === "/api/service-routing/addresses" ? {
68762
+ family: url.searchParams.get("family"),
68763
+ offset: Number(url.searchParams.get("offset") ?? "0")
68764
+ } : url.pathname === "/api/service-routing/traffic" ? { id: url.searchParams.get("id") } : {};
68048
68765
  const device = url.searchParams.get("device");
68049
68766
  if (!device)
68050
68767
  throw new DashboardInputError(400, "Select an explicit router first.");
@@ -68057,6 +68774,73 @@ async function operationsRoutes(req, url) {
68057
68774
  }
68058
68775
  }
68059
68776
 
68777
+ // src/observability/http-error.ts
68778
+ import { homedir as homedir4 } from "os";
68779
+ var HOME = homedir4();
68780
+ var MAX_LEN = 300;
68781
+ function sanitizeMessage(raw, home, fallback) {
68782
+ const line = raw.split(`
68783
+ `, 1)[0].trim();
68784
+ const masked = home.length > 1 ? line.split(home).join("~") : line;
68785
+ if (!masked)
68786
+ return fallback;
68787
+ return masked.length > MAX_LEN ? `${masked.slice(0, MAX_LEN)}\u2026` : masked;
68788
+ }
68789
+ function clientError(e, fallback = "unknown error") {
68790
+ return sanitizeMessage(e instanceof Error ? e.message : String(e), HOME, fallback);
68791
+ }
68792
+ function errorResponse(e) {
68793
+ const connection = e instanceof DeviceConnectionError;
68794
+ return Response.json({
68795
+ error: clientError(e),
68796
+ ...connection && {
68797
+ code: "DEVICE_CONNECTION_FAILED",
68798
+ device: sanitizeMessage(e.device, HOME, "unknown device")
68799
+ }
68800
+ }, { status: connection ? 503 : 502 });
68801
+ }
68802
+ function logError(e) {
68803
+ if (e instanceof Error)
68804
+ return e.stack ?? e.message;
68805
+ return String(e);
68806
+ }
68807
+
68808
+ // src/observability/openvpn-routes.ts
68809
+ async function openVpnRoutes(req, url) {
68810
+ if (url.pathname !== "/api/openvpn/sessions" && url.pathname !== "/api/openvpn/disconnect")
68811
+ return null;
68812
+ try {
68813
+ const device = url.searchParams.get("device");
68814
+ if (!device?.trim())
68815
+ throw new DashboardInputError(400, "Select an explicit router first.");
68816
+ const ctx = createContext(undefined, device);
68817
+ let result;
68818
+ if (req.method === "GET" && url.pathname === "/api/openvpn/sessions")
68819
+ result = await listOpenVpnSessions(ctx);
68820
+ else if (req.method === "POST" && url.pathname === "/api/openvpn/disconnect") {
68821
+ const body = await readOperationBody(req);
68822
+ let input;
68823
+ try {
68824
+ input = JSON.parse(body);
68825
+ } catch {
68826
+ throw new DashboardInputError(400, "Provide a valid JSON request.");
68827
+ }
68828
+ const parsed = disconnectOpenVpnInput.safeParse(input);
68829
+ if (!parsed.success)
68830
+ throw new DashboardInputError(400, "A valid session token and explicit confirmation are required.");
68831
+ result = await disconnectOpenVpnSession(parsed.data, ctx);
68832
+ } else
68833
+ return Response.json({ error: "Method not allowed" }, { status: 405 });
68834
+ return Response.json(result, { headers: { "cache-control": "no-store" } });
68835
+ } catch (error) {
68836
+ if (error instanceof DashboardInputError || error instanceof OpenVpnOperationError)
68837
+ return Response.json({ error: clientError(error) }, { status: error.status, headers: { "cache-control": "no-store" } });
68838
+ const response = errorResponse(error);
68839
+ response.headers.set("cache-control", "no-store");
68840
+ return response;
68841
+ }
68842
+ }
68843
+
68060
68844
  // src/observability/round-trip-routes.ts
68061
68845
  async function roundTripRoutes(req, url) {
68062
68846
  if (url.pathname === "/api/round-trip/options") {
@@ -68123,7 +68907,7 @@ async function roundTripRoutes(req, url) {
68123
68907
  }
68124
68908
 
68125
68909
  // src/observability/um-report-cache.ts
68126
- import { createHash as createHash12, randomUUID as randomUUID11 } from "crypto";
68910
+ import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
68127
68911
  import { mkdir, readFile, rename, stat, unlink, writeFile } from "fs/promises";
68128
68912
  import { dirname as dirname18, join as join12 } from "path";
68129
68913
  var MAX_BYTES = 32 * 1024 * 1024;
@@ -68185,7 +68969,7 @@ async function loadUmReportCache(path, device, fields) {
68185
68969
  async function saveUmReportCache(path, snapshot) {
68186
68970
  if (!path || Object.values(snapshot.sources).some((source) => source.error))
68187
68971
  return false;
68188
- const temp = `${path}.${randomUUID11()}.tmp`;
68972
+ const temp = `${path}.${randomUUID12()}.tmp`;
68189
68973
  try {
68190
68974
  const text = JSON.stringify({ version: 1, snapshot });
68191
68975
  if (Buffer.byteLength(text) > MAX_BYTES)
@@ -68412,8 +69196,8 @@ async function collect(device, progress) {
68412
69196
  throw new Error("Configuration changed during report collection.");
68413
69197
  return { device, collectedAt: Date.now(), collectionMs: Date.now() - start, clock, sources };
68414
69198
  }
68415
- var cache3 = new Map;
68416
- onConfigChanged(() => cache3.clear());
69199
+ var cache5 = new Map;
69200
+ onConfigChanged(() => cache5.clear());
68417
69201
  var freshnessMs = (value) => Math.max(CACHE_MS, Math.min(900000, (value?.collectionMs ?? 0) * 5));
68418
69202
  async function getUmSnapshot(device, refresh = false, wait = true) {
68419
69203
  const name = resolveDeviceName(device);
@@ -68427,12 +69211,12 @@ async function getUmSnapshot(device, refresh = false, wait = true) {
68427
69211
  "get_user_manager_settings"
68428
69212
  ])
68429
69213
  assertDeviceAccess([name], tool, "READ");
68430
- let entry = cache3.get(name);
69214
+ let entry = cache5.get(name);
68431
69215
  const config = getConfig();
68432
69216
  const path = umReportCachePath(name);
68433
69217
  if (!entry) {
68434
69218
  entry = { retryAt: 0, progress: { source: "users", completed: 0, total: null } };
68435
- cache3.set(name, entry);
69219
+ cache5.set(name, entry);
68436
69220
  const target = entry;
68437
69221
  target.restored = loadUmReportCache(path, name, UM_REPORT_FIELDS).then((value) => {
68438
69222
  target.value = value;
@@ -69136,12 +69920,12 @@ async function setCapsmanManager(ctx, input) {
69136
69920
  // src/observability/geo.ts
69137
69921
  import { lookup } from "dns/promises";
69138
69922
  var LOG_TAG2 = "mikrotik-mcp";
69139
- var cache4 = new Map;
69923
+ var cache6 = new Map;
69140
69924
  var REFRESH_MS = 24 * 60 * 60000;
69141
69925
  var timer6 = null;
69142
69926
  var inFlight2 = false;
69143
69927
  function getDeviceGeo(name) {
69144
- return cache4.get(name)?.geo ?? null;
69928
+ return cache6.get(name)?.geo ?? null;
69145
69929
  }
69146
69930
  var IPV4_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/;
69147
69931
  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 +69983,7 @@ async function fetchGeo(ip) {
69199
69983
  async function resolveDevice(name, host) {
69200
69984
  const ip = host ? await publicIpOf(host) : null;
69201
69985
  const geo = ip ? await fetchGeo(ip) : null;
69202
- cache4.set(name, { geo, at: Date.now() });
69986
+ cache6.set(name, { geo, at: Date.now() });
69203
69987
  }
69204
69988
  async function refreshGeo() {
69205
69989
  if (inFlight2)
@@ -69208,7 +69992,7 @@ async function refreshGeo() {
69208
69992
  try {
69209
69993
  const now = Date.now();
69210
69994
  await Promise.all(Object.entries(getConfig().devices).map(([name, dc]) => {
69211
- const c = cache4.get(name);
69995
+ const c = cache6.get(name);
69212
69996
  if (c && now - c.at < REFRESH_MS)
69213
69997
  return Promise.resolve();
69214
69998
  return resolveDevice(name, dc.mac ? undefined : dc.host);
@@ -69231,12 +70015,12 @@ function stopGeoLookups() {
69231
70015
  // src/observability/flags.ts
69232
70016
  import { join as join15 } from "path";
69233
70017
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
69234
- import { homedir as homedir4 } from "os";
70018
+ import { homedir as homedir5 } from "os";
69235
70019
  var LOG_TAG3 = "mikrotik-mcp";
69236
70020
  var CODE_RE = /^[a-z]{2}$/;
69237
70021
  var sourceUrl = (code) => `https://hatscripts.github.io/circle-flags/flags/${code}.svg`;
69238
70022
  var VENDOR_DIR = join15(PROJECT_ROOT, "assets", "flags");
69239
- var CACHE_DIR = join15(homedir4(), ".mikrotik-mcp", "flags");
70023
+ var CACHE_DIR = join15(homedir5(), ".mikrotik-mcp", "flags");
69240
70024
  var mem = new Map;
69241
70025
  async function flagSvg(code) {
69242
70026
  const c = code.toLowerCase();
@@ -69330,37 +70114,6 @@ function readTrafficSample(device) {
69330
70114
  });
69331
70115
  }
69332
70116
 
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
70117
  // src/observability/interface-stats.ts
69365
70118
  var INTERVAL = 2000;
69366
70119
  var counter2 = (value) => {
@@ -72229,11 +72982,11 @@ function issues(error) {
72229
72982
  async function configRoutes(req, url, admin) {
72230
72983
  const p = url.pathname;
72231
72984
  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")
72985
+ if (req.method === "POST" && ["/api/config", "/api/config/validate", "/api/config/preview"].includes(p) && scope !== null && scope !== "devices" && scope !== "server" && scope !== "serviceProbes")
72233
72986
  return json15({ ok: false, error: "Unknown configuration scope" }, 400);
72234
72987
  const mergeDraft = (raw) => {
72235
72988
  const current = getConfig();
72236
- return mergeConfigDraft(scope === "devices" || scope === "server" ? scopeConfigDraft(raw, current, scope) : raw, current);
72989
+ return mergeConfigDraft(scope === "devices" || scope === "server" || scope === "serviceProbes" ? scopeConfigDraft(raw, current, scope) : raw, current);
72237
72990
  };
72238
72991
  if (p === "/api/config-schema" && req.method === "GET") {
72239
72992
  return json15(configSchemaJson());
@@ -73114,6 +73867,9 @@ async function runDashboard(cfg, transportLabel) {
73114
73867
  const operationsResp = await operationsRoutes(req, url);
73115
73868
  if (operationsResp)
73116
73869
  return operationsResp;
73870
+ const openVpnResp = await openVpnRoutes(req, url);
73871
+ if (openVpnResp)
73872
+ return openVpnResp;
73117
73873
  const roundTripResp = await roundTripRoutes(req, url);
73118
73874
  if (roundTripResp)
73119
73875
  return roundTripResp;
@@ -73469,7 +74225,7 @@ async function runDashboard(cfg, transportLabel) {
73469
74225
  }
73470
74226
 
73471
74227
  // src/transport/http.ts
73472
- import { randomUUID as randomUUID12 } from "crypto";
74228
+ import { randomUUID as randomUUID13 } from "crypto";
73473
74229
  var {serve: serve2 } = globalThis.Bun;
73474
74230
 
73475
74231
  // node_modules/content-type/index.js
@@ -82994,7 +83750,7 @@ async function runHttp(mcp) {
82994
83750
  if (existing)
82995
83751
  return existing;
82996
83752
  const transport = new WebStandardStreamableHTTPServerTransport({
82997
- sessionIdGenerator: () => randomUUID12(),
83753
+ sessionIdGenerator: () => randomUUID13(),
82998
83754
  enableJsonResponse: true,
82999
83755
  ...security,
83000
83756
  onsessioninitialized: (id) => {
@@ -83369,7 +84125,7 @@ TRANSPORT OPTIONS
83369
84125
  --transport stdio | sse | streamable-http (MIKROTIK_MCP__TRANSPORT)
83370
84126
  --mcp-host HTTP bind host (MIKROTIK_MCP__HOST)
83371
84127
  --mcp-port HTTP bind port (MIKROTIK_MCP__PORT)
83372
- --mcp-allowed-hosts Host header allow-list (DNS-rebinding protection)
84128
+ --mcp-allowed-hosts Host heaxder allow-list (DNS-rebinding protection)
83373
84129
 
83374
84130
  SSH CONNECTION POOLING (persistent connections, on by default)
83375
84131
  --ssh-keep-alive Enable/disable pooling (MIKROTIK_SSH__KEEP_ALIVE, default true)