@usex/mikrotik-mcp 5.15.0 → 5.16.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
@@ -30981,7 +30981,7 @@ var cache2 = null;
30981
30981
  async function gateway() {
30982
30982
  if (cache2)
30983
30983
  return cache2;
30984
- const { moduleCatalog } = await import("./shared/cli-p8wka734.js");
30984
+ const { moduleCatalog } = await import("./shared/cli-gee7615j.js");
30985
30985
  const forIndex = [];
30986
30986
  const byName = new Map;
30987
30987
  for (const mod of moduleCatalog) {
@@ -53179,7 +53179,7 @@ var riskByTool = null;
53179
53179
  async function riskIndex() {
53180
53180
  if (riskByTool)
53181
53181
  return riskByTool;
53182
- const { moduleCatalog } = await import("./shared/cli-p8wka734.js");
53182
+ const { moduleCatalog } = await import("./shared/cli-gee7615j.js");
53183
53183
  const index = new Map;
53184
53184
  for (const mod of moduleCatalog) {
53185
53185
  for (const tool of mod.tools)
@@ -63387,6 +63387,11 @@ function applyModuleToggle(filter, slug, enabled) {
63387
63387
  // src/config-write.ts
63388
63388
  import { mkdirSync as mkdirSync14, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "fs";
63389
63389
  import { dirname as dirname15 } from "path";
63390
+
63391
+ // src/config-device-draft.ts
63392
+ var CREDENTIAL_SOURCE = "$credentialsFrom";
63393
+
63394
+ // src/config-write.ts
63390
63395
  var SCHEMA_REF = "./schemas/config.schema.json";
63391
63396
  function mergeSecrets(incoming, current) {
63392
63397
  if (incoming === REDACTED) {
@@ -63408,6 +63413,31 @@ function mergeSecrets(incoming, current) {
63408
63413
  }
63409
63414
  return incoming;
63410
63415
  }
63416
+ function mergeDeviceDraft(incoming, name, devices) {
63417
+ if (!incoming || typeof incoming !== "object" || Array.isArray(incoming))
63418
+ return incoming;
63419
+ const { [CREDENTIAL_SOURCE]: source, ...draft } = incoming;
63420
+ if (source !== undefined && (typeof source !== "string" || !Object.hasOwn(devices, source)))
63421
+ throw new Error("Credential source is unavailable. Reopen the editor or enter new credentials.");
63422
+ const key = typeof source === "string" ? source : name;
63423
+ return mergeSecrets(draft, Object.hasOwn(devices, key) ? devices[key] : undefined);
63424
+ }
63425
+ function mergeConfigDraft(incoming, current) {
63426
+ if (!incoming || typeof incoming !== "object" || Array.isArray(incoming))
63427
+ return incoming;
63428
+ const draft = incoming;
63429
+ if (!draft.devices || typeof draft.devices !== "object" || Array.isArray(draft.devices))
63430
+ return mergeSecrets(incoming, current);
63431
+ const { devices: _devices, ...rest } = draft;
63432
+ const currentDevices = current?.devices ?? {};
63433
+ return {
63434
+ ...mergeSecrets(rest, current),
63435
+ devices: Object.fromEntries(Object.entries(draft.devices).map(([name, device]) => [
63436
+ name,
63437
+ mergeDeviceDraft(device, name, currentDevices)
63438
+ ]))
63439
+ };
63440
+ }
63411
63441
  function serializeConfig(config) {
63412
63442
  const body = config && typeof config === "object" && !Array.isArray(config) ? config : {};
63413
63443
  const { $schema: _drop, ...rest } = body;
@@ -64171,6 +64201,184 @@ function subscribeTraffic(device, fn) {
64171
64201
  };
64172
64202
  }
64173
64203
 
64204
+ // src/observability/http-error.ts
64205
+ import { homedir as homedir4 } from "os";
64206
+ var HOME = homedir4();
64207
+ var MAX_LEN = 300;
64208
+ function sanitizeMessage(raw, home, fallback) {
64209
+ const line = raw.split(`
64210
+ `, 1)[0].trim();
64211
+ const masked = home.length > 1 ? line.split(home).join("~") : line;
64212
+ if (!masked)
64213
+ return fallback;
64214
+ return masked.length > MAX_LEN ? `${masked.slice(0, MAX_LEN)}\u2026` : masked;
64215
+ }
64216
+ function clientError(e, fallback = "unknown error") {
64217
+ return sanitizeMessage(e instanceof Error ? e.message : String(e), HOME, fallback);
64218
+ }
64219
+ function logError(e) {
64220
+ if (e instanceof Error)
64221
+ return e.stack ?? e.message;
64222
+ return String(e);
64223
+ }
64224
+
64225
+ // src/observability/interface-stats.ts
64226
+ var INTERVAL = 2000;
64227
+ var counter2 = (value) => {
64228
+ const n = parseSize(value);
64229
+ return n != null && Number.isFinite(n) && n >= 0 ? n : null;
64230
+ };
64231
+ function parseInterfaceStats(detail, stats) {
64232
+ const normalized = stats.replace(/((?:rx|tx|fp-rx|fp-tx)-(?:byte|packet|error|drop|queue-drop)=)(\d+(?:[ \t]+\d{3})*)(?=\s|$)/g, (_match, key, value) => key + value.replace(/[ \t]/g, ""));
64233
+ const counters = new Map(parseRecords(normalized).rows.map((r) => [r.name, r]));
64234
+ return parseRecords(detail).rows.filter((r) => r.name).map((r) => {
64235
+ const s = counters.get(r.name) ?? {};
64236
+ const flags = s.flags ?? r.flags ?? "";
64237
+ return {
64238
+ name: r.name,
64239
+ type: r.type || "unknown",
64240
+ comment: r.comment || "",
64241
+ running: isYes(r.running ?? "") || flags.includes("R"),
64242
+ disabled: isYes(r.disabled ?? "") || flags.includes("X"),
64243
+ dynamic: isYes(r.dynamic ?? "") || flags.includes("D"),
64244
+ mtu: counter2(r["actual-mtu"] ?? r.mtu),
64245
+ mac: r["mac-address"] || "",
64246
+ rxBytes: counter2(s["rx-byte"]),
64247
+ txBytes: counter2(s["tx-byte"]),
64248
+ rxPackets: counter2(s["rx-packet"]),
64249
+ txPackets: counter2(s["tx-packet"]),
64250
+ rxErrors: counter2(s["rx-error"]),
64251
+ txErrors: counter2(s["tx-error"]),
64252
+ rxDrops: counter2(s["rx-drop"]),
64253
+ txDrops: counter2(s["tx-drop"]),
64254
+ queueDrops: counter2(s["tx-queue-drop"]),
64255
+ linkDowns: counter2(s["link-downs"] ?? r["link-downs"]),
64256
+ rxRate: null,
64257
+ txRate: null,
64258
+ rxPps: null,
64259
+ txPps: null
64260
+ };
64261
+ });
64262
+ }
64263
+ function interfaceRates(current, previous) {
64264
+ if (!previous || previous.error || previous.device !== current.device)
64265
+ return current;
64266
+ const seconds = (current.ts - previous.ts) / 1000;
64267
+ if (seconds <= 0 || seconds > 30)
64268
+ return current;
64269
+ const old = new Map(previous.interfaces.map((row) => [row.name, row]));
64270
+ const rate = (a, b, multiplier = 1) => a != null && b != null && a >= b ? (a - b) * multiplier / seconds : null;
64271
+ return {
64272
+ ...current,
64273
+ interfaces: current.interfaces.map((row) => {
64274
+ const before = old.get(row.name);
64275
+ if (!before || before.type !== row.type || before.mac !== row.mac)
64276
+ return row;
64277
+ return {
64278
+ ...row,
64279
+ rxRate: rate(row.rxBytes, before.rxBytes, 8),
64280
+ txRate: rate(row.txBytes, before.txBytes, 8),
64281
+ rxPps: rate(row.rxPackets, before.rxPackets),
64282
+ txPps: rate(row.txPackets, before.txPackets)
64283
+ };
64284
+ })
64285
+ };
64286
+ }
64287
+ async function readInterfaces(device) {
64288
+ const ctx = createContext(undefined, device);
64289
+ const read = async (mode) => {
64290
+ const output = await executeMikrotikCommand(new Cmd("/interface print").raw(mode).raw("without-paging").build(), ctx);
64291
+ if (looksLikeError(output))
64292
+ throw new Error(output);
64293
+ return output;
64294
+ };
64295
+ const detail = await read("detail");
64296
+ const stats = await read("stats-detail");
64297
+ const interfaces = parseInterfaceStats(detail, stats);
64298
+ if (!interfaces.length && detail.trim())
64299
+ throw new Error("No readable interface records returned");
64300
+ return { device, ts: Date.now(), interfaces };
64301
+ }
64302
+ var hubs2 = new Map;
64303
+ function subscribeInterfaces(target, listener) {
64304
+ const device = resolveDeviceName(target);
64305
+ let hub = hubs2.get(device);
64306
+ if (!hub) {
64307
+ hub = { listeners: new Set };
64308
+ hubs2.set(device, hub);
64309
+ const active = hub;
64310
+ const poll = async () => {
64311
+ let sample;
64312
+ try {
64313
+ sample = interfaceRates(await readInterfaces(device), active.last);
64314
+ } catch (error) {
64315
+ sample = { device, ts: Date.now(), interfaces: [], error: clientError(error) };
64316
+ }
64317
+ if (hubs2.get(device) !== active)
64318
+ return;
64319
+ active.last = sample;
64320
+ for (const fn of active.listeners)
64321
+ fn(sample);
64322
+ active.timer = setTimeout(() => void poll(), INTERVAL);
64323
+ };
64324
+ poll();
64325
+ }
64326
+ hub.listeners.add(listener);
64327
+ if (hub.last)
64328
+ listener(hub.last);
64329
+ const active = hub;
64330
+ return () => {
64331
+ active.listeners.delete(listener);
64332
+ if (!active.listeners.size) {
64333
+ clearTimeout(active.timer);
64334
+ if (hubs2.get(device) === active)
64335
+ hubs2.delete(device);
64336
+ }
64337
+ };
64338
+ }
64339
+ function interfaceStatsResponse(req, target) {
64340
+ const device = resolveDeviceName(target);
64341
+ let unsubscribe;
64342
+ let heartbeat;
64343
+ const cleanup = () => {
64344
+ unsubscribe?.();
64345
+ clearInterval(heartbeat);
64346
+ req.signal.removeEventListener("abort", cleanup);
64347
+ };
64348
+ const stream = new ReadableStream({
64349
+ start(controller) {
64350
+ const encoder = new TextEncoder;
64351
+ const send = (text) => {
64352
+ try {
64353
+ controller.enqueue(encoder.encode(text));
64354
+ } catch {
64355
+ cleanup();
64356
+ }
64357
+ };
64358
+ if (req.signal.aborted) {
64359
+ controller.close();
64360
+ return;
64361
+ }
64362
+ unsubscribe = subscribeInterfaces(device, (sample) => send(`event: interfaces
64363
+ data: ${JSON.stringify(sample)}
64364
+
64365
+ `));
64366
+ heartbeat = setInterval(() => send(`: ping
64367
+
64368
+ `), 15000);
64369
+ req.signal.addEventListener("abort", cleanup, { once: true });
64370
+ },
64371
+ cancel: cleanup
64372
+ });
64373
+ return new Response(stream, {
64374
+ headers: {
64375
+ "content-type": "text/event-stream; charset=utf-8",
64376
+ "cache-control": "no-cache, no-transform",
64377
+ connection: "keep-alive"
64378
+ }
64379
+ });
64380
+ }
64381
+
64174
64382
  // src/observability/store.ts
64175
64383
  import { mkdirSync as mkdirSync16 } from "fs";
64176
64384
  import { dirname as dirname16 } from "path";
@@ -64900,27 +65108,6 @@ function computeStats(events, opts) {
64900
65108
  };
64901
65109
  }
64902
65110
 
64903
- // src/observability/http-error.ts
64904
- import { homedir as homedir4 } from "os";
64905
- var HOME = homedir4();
64906
- var MAX_LEN = 300;
64907
- function sanitizeMessage(raw, home, fallback) {
64908
- const line = raw.split(`
64909
- `, 1)[0].trim();
64910
- const masked = home.length > 1 ? line.split(home).join("~") : line;
64911
- if (!masked)
64912
- return fallback;
64913
- return masked.length > MAX_LEN ? `${masked.slice(0, MAX_LEN)}\u2026` : masked;
64914
- }
64915
- function clientError(e, fallback = "unknown error") {
64916
- return sanitizeMessage(e instanceof Error ? e.message : String(e), HOME, fallback);
64917
- }
64918
- function logError(e) {
64919
- if (e instanceof Error)
64920
- return e.stack ?? e.message;
64921
- return String(e);
64922
- }
64923
-
64924
65111
  // src/observability/drift-routes.ts
64925
65112
  var storePromise14 = null;
64926
65113
  function getStore() {
@@ -66863,14 +67050,16 @@ async function configRoutes(req, url, admin) {
66863
67050
  return json15(configSchemaJson());
66864
67051
  }
66865
67052
  if (p === "/api/config/validate" && req.method === "POST") {
66866
- const merged = mergeSecrets(await readJson(req), getConfig());
67053
+ const merged = mergeConfigDraft(await readJson(req), getConfig());
66867
67054
  return json15(validateConfig(merged));
66868
67055
  }
66869
67056
  if (p === "/api/config/test-device" && req.method === "POST") {
66870
67057
  const body = await readJson(req);
66871
67058
  const name = typeof body?.name === "string" ? body.name : "(unsaved)";
66872
- const currentDc = getConfig().devices[name];
66873
- const merged = mergeSecrets(body?.config, currentDc);
67059
+ const merged = mergeDeviceDraft(body?.config, name, getConfig().devices);
67060
+ const target = merged;
67061
+ if (![target?.host, target?.mac].some((value) => typeof value === "string" && value.trim().length > 0))
67062
+ return json15({ ok: false, error: "Enter a Host / IP or MAC address before testing." }, 400);
66874
67063
  const parsed = DeviceConfigSchema.safeParse(merged);
66875
67064
  if (!parsed.success)
66876
67065
  return json15({ ok: false, errors: issues(parsed.error) }, 400);
@@ -66879,13 +67068,13 @@ async function configRoutes(req, url, admin) {
66879
67068
  }
66880
67069
  if (p === "/api/config/preview" && req.method === "POST") {
66881
67070
  const before = JSON.stringify(redact(getConfig()), null, 2);
66882
- const after = JSON.stringify(await readJson(req) ?? {}, null, 2);
67071
+ const after = JSON.stringify(redact(mergeConfigDraft(await readJson(req), getConfig())), null, 2);
66883
67072
  const d = diffLines(before, after, { fromLabel: "current", toLabel: "edited" });
66884
67073
  return json15({ summary: d.summary, unified: d.unified });
66885
67074
  }
66886
67075
  if (p === "/api/config" && req.method === "POST") {
66887
67076
  const body = await readJson(req);
66888
- const merged = mergeSecrets(body?.config, getConfig());
67077
+ const merged = mergeConfigDraft(body?.config, getConfig());
66889
67078
  const v = validateConfig(merged);
66890
67079
  if (!v.ok || !v.value)
66891
67080
  return json15({ ok: false, errors: v.errors }, 400);
@@ -66897,7 +67086,14 @@ async function configRoutes(req, url, admin) {
66897
67086
  const nextDevs = Object.keys(v.value.devices);
66898
67087
  const devicesChanged = prevDevs.length !== nextDevs.length || prevDevs.some((d) => !nextDevs.includes(d));
66899
67088
  const res = admin.applyConfig(v.value, clampRollback(body?.rollbackMs));
66900
- return json15({ ok: true, ...res, devicesChanged, summary: diff.summary, unified: diff.unified });
67089
+ return json15({
67090
+ ok: true,
67091
+ ...res,
67092
+ config: redact(v.value),
67093
+ devicesChanged,
67094
+ summary: diff.summary,
67095
+ unified: diff.unified
67096
+ });
66901
67097
  }
66902
67098
  if (p === "/api/config/keep" && req.method === "POST") {
66903
67099
  const body = await readJson(req);
@@ -67646,6 +67842,12 @@ async function runDashboard(cfg, transportLabel) {
67646
67842
  };
67647
67843
  const accessSettingsRoutes = createAccessSettingsRoutes(configAdmin);
67648
67844
  async function dashboardRoute(req, url, srv, ca, tl) {
67845
+ if (url.pathname === "/api/interfaces/stream" && req.method === "GET") {
67846
+ const device = url.searchParams.get("device");
67847
+ if (!device)
67848
+ return json15({ error: "device required" }, 400);
67849
+ return interfaceStatsResponse(req, device);
67850
+ }
67649
67851
  if (url.pathname === "/api/stream") {
67650
67852
  const traffic = url.searchParams.has("traffic") ? url.searchParams.get("traffic") ?? "" : undefined;
67651
67853
  if (srv.upgrade(req, { data: { traffic } }))