@usex/mikrotik-mcp 6.14.0 → 6.15.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/index.d.ts CHANGED
@@ -77,6 +77,111 @@ interface ToolAccess {
77
77
  /** How a device command was actually carried. */
78
78
  type DeviceTransport = "ssh" | "rest" | "mac-telnet";
79
79
  type SendLog = (level: "info" | "error", message: string) => void;
80
+ import { ClientChannel } from "ssh2";
81
+ interface EndpointOptions {
82
+ /** Evaluated at connect time, not at client construction. */
83
+ hosts?: () => string[];
84
+ onAttempt?: (host: string, error?: string) => void;
85
+ onConnected?: (host: string) => () => void;
86
+ }
87
+ interface SSHClientOptions extends EndpointOptions {
88
+ host: string;
89
+ username: string;
90
+ password?: string;
91
+ port?: number;
92
+ keyFilename?: string;
93
+ privateKey?: string;
94
+ /** Passphrase for an encrypted private key. */
95
+ keyPassphrase?: string;
96
+ timeoutMs?: number;
97
+ /**
98
+ * Optional SSH jump host (bastion / ProxyJump). When set, `connect()` reaches
99
+ * `host:port` THROUGH this hop: it opens an SSH session to the hop, asks it to
100
+ * `forwardOut` a TCP channel to the target, then runs the real SSH session
101
+ * over that channel. So the target never needs a port exposed to the network —
102
+ * only the bastion is reachable. The hop is itself an SSH endpoint and may
103
+ * carry its own `jump` for a multi-hop chain (A → B → target).
104
+ */
105
+ jump?: SSHClientOptions;
106
+ /** Interval (ms) for SSH keepalive packets. 0 disables (default). */
107
+ keepAliveInterval?: number;
108
+ /** Max consecutive keepalive failures before disconnect. Default: 3. */
109
+ keepAliveCountMax?: number;
110
+ }
111
+ /** Options for one command. `onData` and `signal` serve a live terminal. */
112
+ interface RunOptions {
113
+ /** Stop the command after this long and return what it printed. */
114
+ maxMs?: number;
115
+ /** Receives stdout as it arrives. The full output is still returned. */
116
+ onData?: (text: string) => void;
117
+ /** Aborting stops the command and returns what it printed so far. */
118
+ signal?: AbortSignal;
119
+ }
120
+ declare class MikroTikSSHClient {
121
+ private client;
122
+ /**
123
+ * Open bastion connections, outermost-first, kept alive for the lifetime of
124
+ * the session (the target's transport rides a channel on the last one). Closed
125
+ * in reverse on `disconnect()`.
126
+ */
127
+ private bastions;
128
+ private releases;
129
+ private readonly opts;
130
+ /** Human-readable reason the last `connect()` failed, if it did. */
131
+ lastError?: string;
132
+ connectedHost?: string;
133
+ get isConnected(): boolean;
134
+ constructor(opts: SSHClientOptions);
135
+ /**
136
+ * Establish the SSH connection — directly, or through one or more jump hosts
137
+ * when `opts.jump` is set. Resolves `true` on success, `false` on failure
138
+ * (with the reason on `lastError`).
139
+ */
140
+ connect(): Promise<boolean>;
141
+ /** Retry addresses only during connection setup, never after dispatching a command. */
142
+ private connectEndpoint;
143
+ /**
144
+ * Open one ssh2 connection. When `sock` is given the connection rides that
145
+ * stream (a forwarded channel from a jump host) instead of dialling the
146
+ * network directly. Resolves the ready `Client`; rejects with a clear reason.
147
+ */
148
+ private openClient;
149
+ /**
150
+ * Ask a connected jump host to open a TCP channel to `host:port` and resolve
151
+ * the resulting stream (used as the next hop's transport `sock`).
152
+ *
153
+ * A RouterOS bastion with SSH TCP forwarding disabled (the default) often
154
+ * NEVER answers the channel-open request instead of rejecting it cleanly, so
155
+ * without a timeout this would hang the whole connection (the dashboard sits
156
+ * forever at "connecting…"). The `timeoutMs` guard turns that silent stall
157
+ * into a fast, actionable error; an explicit rejection gets the same hint.
158
+ */
159
+ private forwardOut;
160
+ /** Run a single command on a fresh SSH channel and return its decoded output. */
161
+ run(command: string, opts?: RunOptions): Promise<string>;
162
+ /**
163
+ * Upload a file's bytes to the device over SFTP — the file-transfer subsystem
164
+ * RouterOS exposes on its SSH server. `remotePath` is relative to the SFTP
165
+ * default directory (the flash root), so `config.rsc` lands at the root and
166
+ * appears in `/file`; a path like `disk1/config.rsc` targets external disk.
167
+ * Resolves on success; rejects with a clear reason on failure.
168
+ */
169
+ uploadFile(remotePath: string, data: Buffer): Promise<void>;
170
+ /**
171
+ * Download a file's bytes from the device over SFTP. `remotePath` is relative
172
+ * to the SFTP default directory (the flash root). Resolves with the raw file
173
+ * contents; rejects with a clear reason on failure.
174
+ */
175
+ downloadFile(remotePath: string): Promise<Buffer>;
176
+ /** Open a persistent interactive shell channel (used by Safe Mode). */
177
+ shell(opts?: {
178
+ term?: string;
179
+ cols?: number;
180
+ rows?: number;
181
+ }): Promise<ClientChannel>;
182
+ /** Close the SSH connection (and any jump hosts). Safe to call multiple times. */
183
+ disconnect(): void;
184
+ }
80
185
  /**
81
186
  * Execute a RouterOS command and return its raw text output.
82
187
  *
@@ -89,9 +194,7 @@ type SendLog = (level: "info" | "error", message: string) => void;
89
194
  * @param opts `maxMs` caps the one-shot read for interactive/streaming
90
195
  * commands (ping, bandwidth-test) so they can't hang the tool.
91
196
  */
92
- declare function executeMikrotikCommand(command: string, ctx: ToolContext, opts?: {
93
- maxMs?: number;
94
- }): Promise<string>;
197
+ declare function executeMikrotikCommand(command: string, ctx: ToolContext, opts?: RunOptions): Promise<string>;
95
198
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
96
199
  import { CallToolResult as CallToolResult2, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
97
200
  import { ZodRawShape } from "zod";
@@ -314,104 +417,6 @@ interface CreatedServer {
314
417
  declare function createServer(opts?: {
315
418
  sendLog?: SendLog;
316
419
  }): CreatedServer;
317
- import { ClientChannel } from "ssh2";
318
- interface EndpointOptions {
319
- /** Evaluated at connect time, not at client construction. */
320
- hosts?: () => string[];
321
- onAttempt?: (host: string, error?: string) => void;
322
- onConnected?: (host: string) => () => void;
323
- }
324
- interface SSHClientOptions extends EndpointOptions {
325
- host: string;
326
- username: string;
327
- password?: string;
328
- port?: number;
329
- keyFilename?: string;
330
- privateKey?: string;
331
- /** Passphrase for an encrypted private key. */
332
- keyPassphrase?: string;
333
- timeoutMs?: number;
334
- /**
335
- * Optional SSH jump host (bastion / ProxyJump). When set, `connect()` reaches
336
- * `host:port` THROUGH this hop: it opens an SSH session to the hop, asks it to
337
- * `forwardOut` a TCP channel to the target, then runs the real SSH session
338
- * over that channel. So the target never needs a port exposed to the network —
339
- * only the bastion is reachable. The hop is itself an SSH endpoint and may
340
- * carry its own `jump` for a multi-hop chain (A → B → target).
341
- */
342
- jump?: SSHClientOptions;
343
- /** Interval (ms) for SSH keepalive packets. 0 disables (default). */
344
- keepAliveInterval?: number;
345
- /** Max consecutive keepalive failures before disconnect. Default: 3. */
346
- keepAliveCountMax?: number;
347
- }
348
- declare class MikroTikSSHClient {
349
- private client;
350
- /**
351
- * Open bastion connections, outermost-first, kept alive for the lifetime of
352
- * the session (the target's transport rides a channel on the last one). Closed
353
- * in reverse on `disconnect()`.
354
- */
355
- private bastions;
356
- private releases;
357
- private readonly opts;
358
- /** Human-readable reason the last `connect()` failed, if it did. */
359
- lastError?: string;
360
- connectedHost?: string;
361
- get isConnected(): boolean;
362
- constructor(opts: SSHClientOptions);
363
- /**
364
- * Establish the SSH connection — directly, or through one or more jump hosts
365
- * when `opts.jump` is set. Resolves `true` on success, `false` on failure
366
- * (with the reason on `lastError`).
367
- */
368
- connect(): Promise<boolean>;
369
- /** Retry addresses only during connection setup, never after dispatching a command. */
370
- private connectEndpoint;
371
- /**
372
- * Open one ssh2 connection. When `sock` is given the connection rides that
373
- * stream (a forwarded channel from a jump host) instead of dialling the
374
- * network directly. Resolves the ready `Client`; rejects with a clear reason.
375
- */
376
- private openClient;
377
- /**
378
- * Ask a connected jump host to open a TCP channel to `host:port` and resolve
379
- * the resulting stream (used as the next hop's transport `sock`).
380
- *
381
- * A RouterOS bastion with SSH TCP forwarding disabled (the default) often
382
- * NEVER answers the channel-open request instead of rejecting it cleanly, so
383
- * without a timeout this would hang the whole connection (the dashboard sits
384
- * forever at "connecting…"). The `timeoutMs` guard turns that silent stall
385
- * into a fast, actionable error; an explicit rejection gets the same hint.
386
- */
387
- private forwardOut;
388
- /** Run a single command on a fresh SSH channel and return its decoded output. */
389
- run(command: string, opts?: {
390
- maxMs?: number;
391
- }): Promise<string>;
392
- /**
393
- * Upload a file's bytes to the device over SFTP — the file-transfer subsystem
394
- * RouterOS exposes on its SSH server. `remotePath` is relative to the SFTP
395
- * default directory (the flash root), so `config.rsc` lands at the root and
396
- * appears in `/file`; a path like `disk1/config.rsc` targets external disk.
397
- * Resolves on success; rejects with a clear reason on failure.
398
- */
399
- uploadFile(remotePath: string, data: Buffer): Promise<void>;
400
- /**
401
- * Download a file's bytes from the device over SFTP. `remotePath` is relative
402
- * to the SFTP default directory (the flash root). Resolves with the raw file
403
- * contents; rejects with a clear reason on failure.
404
- */
405
- downloadFile(remotePath: string): Promise<Buffer>;
406
- /** Open a persistent interactive shell channel (used by Safe Mode). */
407
- shell(opts?: {
408
- term?: string;
409
- cols?: number;
410
- rows?: number;
411
- }): Promise<ClientChannel>;
412
- /** Close the SSH connection (and any jump hosts). Safe to call multiple times. */
413
- disconnect(): void;
414
- }
415
420
  /**
416
421
  * Outcome of {@link SafeModeManager.commit}. `ok` is true ONLY when Safe Mode is
417
422
  * confirmed exited (changes persisted) — callers must check it before telling
package/dist/index.js CHANGED
@@ -70,7 +70,7 @@ import {
70
70
  updateSummaryLine,
71
71
  allToolModules2,
72
72
  selectToolModules2
73
- } from "./shared/library-2wd7mt3g.js";
73
+ } from "./shared/library-7qr2sc9x.js";
74
74
 
75
75
  // node_modules/ajv/dist/compile/codegen/code.js
76
76
  var require_code = __commonJS(function(exports) {
@@ -4,7 +4,7 @@ import {
4
4
  normalizeExport2,
5
5
  contentSha2,
6
6
  countLines2
7
- } from "./cli-1vn2bbpy.js";
7
+ } from "./cli-4n039739.js";
8
8
  export {
9
9
  contentSha2 as contentSha,
10
10
  countLines2 as countLines,
@@ -8500,6 +8500,7 @@ var McpServerSettingsSchema2 = object({
8500
8500
  allowedHosts: string().default(""),
8501
8501
  allowedOrigins: string().default(""),
8502
8502
  corsOrigins: string().default(""),
8503
+ sessionIdleTimeout: exports_coerce.number().int().positive().default(86400000),
8503
8504
  toolPageSize: exports_coerce.number().int().min(0).default(0),
8504
8505
  toolSurface: _enum(["full", "core"]).default("full"),
8505
8506
  coreTools: string().default(""),
@@ -8638,7 +8639,8 @@ var DashboardConfigSchema2 = object({
8638
8639
  redactInput: boolean().default(false),
8639
8640
  maxBodyBytes: exports_coerce.number().int().nonnegative().default(16384),
8640
8641
  token: string().optional(),
8641
- feedLimit: exports_coerce.number().int().positive().max(1e4).default(200)
8642
+ feedLimit: exports_coerce.number().int().positive().max(1e4).default(200),
8643
+ terminal: boolean().default(true)
8642
8644
  });
8643
8645
  var MemoryConfigSchema2 = object({
8644
8646
  enabled: boolean().default(true),
@@ -8692,7 +8694,7 @@ function env(...names) {
8692
8694
  }
8693
8695
  return;
8694
8696
  }
8695
- function parseFlags(argv) {
8697
+ function parseFlags2(argv) {
8696
8698
  const out = {};
8697
8699
  for (let i = 0;i < argv.length; i++) {
8698
8700
  const arg = argv[i];
@@ -8769,7 +8771,7 @@ function getConfigSource2() {
8769
8771
  return configSource;
8770
8772
  }
8771
8773
  function loadConfig2(argv = process.argv.slice(2)) {
8772
- const flags = parseFlags(argv);
8774
+ const flags = parseFlags2(argv);
8773
8775
  const pick = (flag, ...envNames) => flags[flag] ?? env(...envNames);
8774
8776
  const overlay = (file, over) => {
8775
8777
  const out = { ...file };
@@ -8864,6 +8866,7 @@ function loadConfig2(argv = process.argv.slice(2)) {
8864
8866
  allowedHosts: pick("mcp-allowed-hosts", "MIKROTIK_MCP__ALLOWED_HOSTS"),
8865
8867
  allowedOrigins: pick("mcp-allowed-origins", "MIKROTIK_MCP__ALLOWED_ORIGINS"),
8866
8868
  corsOrigins: pick("mcp-cors-origins", "MIKROTIK_MCP__CORS_ORIGINS"),
8869
+ sessionIdleTimeout: pick("mcp-session-idle-timeout", "MIKROTIK_MCP__SESSION_IDLE_TIMEOUT"),
8867
8870
  toolPageSize: pick("tool-page-size", "MIKROTIK_MCP__TOOL_PAGE_SIZE"),
8868
8871
  toolSurface: pick("tool-surface", "MIKROTIK_MCP__TOOL_SURFACE"),
8869
8872
  coreTools: pick("core-tools", "MIKROTIK_MCP__CORE_TOOLS"),
@@ -8893,7 +8896,8 @@ function loadConfig2(argv = process.argv.slice(2)) {
8893
8896
  redactInput: boolOpt(pick("dashboard-redact-input", "MIKROTIK_DASHBOARD__REDACT_INPUT")),
8894
8897
  maxBodyBytes: pick("dashboard-max-body-bytes", "MIKROTIK_DASHBOARD__MAX_BODY_BYTES"),
8895
8898
  token: pick("dashboard-token", "MIKROTIK_DASHBOARD__TOKEN"),
8896
- feedLimit: pick("dashboard-feed-limit", "MIKROTIK_DASHBOARD__FEED_LIMIT")
8899
+ feedLimit: pick("dashboard-feed-limit", "MIKROTIK_DASHBOARD__FEED_LIMIT"),
8900
+ terminal: boolOpt(pick("dashboard-terminal", "MIKROTIK_DASHBOARD__TERMINAL"))
8897
8901
  });
8898
8902
  const ssh = overlay(fileSsh, {
8899
8903
  keepAlive: boolOpt(pick("ssh-keep-alive", "MIKROTIK_SSH__KEEP_ALIVE")),
@@ -9397,6 +9401,37 @@ function decodeOutput(data) {
9397
9401
  }
9398
9402
  return new TextDecoder("utf-8").decode(data);
9399
9403
  }
9404
+ var watches = new WeakMap;
9405
+ function watchConnection(connection, waiter) {
9406
+ let watch = watches.get(connection);
9407
+ if (!watch) {
9408
+ const waiters = new Set;
9409
+ const notify = (lost) => {
9410
+ for (const each of Array.from(waiters))
9411
+ each(lost);
9412
+ };
9413
+ watch = {
9414
+ waiters,
9415
+ onError: (error) => notify(`SSH connection lost: ${error.message}.`),
9416
+ onClose: () => notify("SSH connection closed before command completion.")
9417
+ };
9418
+ watches.set(connection, watch);
9419
+ connection.on("error", watch.onError);
9420
+ connection.on("end", watch.onClose);
9421
+ connection.on("close", watch.onClose);
9422
+ }
9423
+ const current = watch;
9424
+ current.waiters.add(waiter);
9425
+ return () => {
9426
+ current.waiters.delete(waiter);
9427
+ if (current.waiters.size > 0 || watches.get(connection) !== current)
9428
+ return;
9429
+ watches.delete(connection);
9430
+ connection.off("error", current.onError);
9431
+ connection.off("end", current.onClose);
9432
+ connection.off("close", current.onClose);
9433
+ };
9434
+ }
9400
9435
 
9401
9436
  class MikroTikSSHClient {
9402
9437
  client = null;
@@ -9555,7 +9590,10 @@ class MikroTikSSHClient {
9555
9590
  let timer;
9556
9591
  let idleTimer;
9557
9592
  let hardTimer;
9593
+ let unwatch = () => {};
9594
+ const live = opts.onData ? new TextDecoder("utf-8") : undefined;
9558
9595
  const clearTimers = () => {
9596
+ opts.signal?.removeEventListener("abort", onAbort);
9559
9597
  if (openTimer)
9560
9598
  clearTimeout(openTimer);
9561
9599
  if (timer)
@@ -9564,9 +9602,7 @@ class MikroTikSSHClient {
9564
9602
  clearTimeout(idleTimer);
9565
9603
  if (hardTimer)
9566
9604
  clearTimeout(hardTimer);
9567
- connection.off("error", onConnectionError);
9568
- connection.off("end", onConnectionClose);
9569
- connection.off("close", onConnectionClose);
9605
+ unwatch();
9570
9606
  };
9571
9607
  const finish = () => {
9572
9608
  if (settled)
@@ -9591,15 +9627,7 @@ class MikroTikSSHClient {
9591
9627
  reject(e);
9592
9628
  };
9593
9629
  const uncertain = "Command outcome is unknown; do not retry a write blindly. Reconnect and read back the target state first.";
9594
- function onConnectionError(error) {
9595
- fail(new Error(`SSH connection lost: ${error.message}. ${uncertain}`));
9596
- }
9597
- function onConnectionClose() {
9598
- fail(new Error(`SSH connection closed before command completion. ${uncertain}`));
9599
- }
9600
- connection.on("error", onConnectionError);
9601
- connection.on("end", onConnectionClose);
9602
- connection.on("close", onConnectionClose);
9630
+ unwatch = watchConnection(connection, (lost) => fail(new Error(`${lost} ${uncertain}`)));
9603
9631
  openTimer = setTimeout(() => {
9604
9632
  fail(new Error(`SSH channel request timed out after ${this.opts.timeoutMs}ms. ${uncertain}`));
9605
9633
  if (this.client === connection)
@@ -9654,6 +9682,8 @@ class MikroTikSSHClient {
9654
9682
  if (settled)
9655
9683
  return;
9656
9684
  stdout.push(d);
9685
+ if (live)
9686
+ opts.onData?.(live.decode(d, { stream: true }));
9657
9687
  armIdle();
9658
9688
  }).stderr.on("data", (d) => {
9659
9689
  if (settled)
@@ -9662,6 +9692,19 @@ class MikroTikSSHClient {
9662
9692
  armIdle();
9663
9693
  });
9664
9694
  };
9695
+ function onAbort() {
9696
+ const channel = stream;
9697
+ finish();
9698
+ try {
9699
+ channel?.signal("INT");
9700
+ } catch {}
9701
+ try {
9702
+ channel?.close();
9703
+ } catch {}
9704
+ }
9705
+ if (opts.signal?.aborted)
9706
+ return onAbort();
9707
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
9665
9708
  try {
9666
9709
  openChannel(command, onChannel);
9667
9710
  } catch (error) {
@@ -22262,13 +22305,13 @@ async function undoMigration(id, confirm, selected) {
22262
22305
  throw new Error("Undo lost Safe Mode or exceeded its time budget.");
22263
22306
  await checkedRead(item.undo, createContext(undefined, device));
22264
22307
  }
22265
- const beforeTarget = (await import("./cli-w6km895r.js")).openSnapshotStore;
22266
- const db = await beforeTarget((await import("./cli-rcx7e9h4.js")).DEFAULT_SNAPSHOT_DB);
22308
+ const beforeTarget = (await import("./cli-57nggfz3.js")).openSnapshotStore;
22309
+ const db = await beforeTarget((await import("./cli-5hgbedxa.js")).DEFAULT_SNAPSHOT_DB);
22267
22310
  try {
22268
22311
  const original = db.get(p.snapshots.target);
22269
22312
  if (!original)
22270
22313
  throw new Error("Original target snapshot unavailable.");
22271
- const { normalizeExport } = await import("./cli-4xzq2n6j.js");
22314
+ const { normalizeExport } = await import("./cli-4aqtcr9k.js");
22272
22315
  if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
22273
22316
  throw new Error("Target differs from its backup. Undo verification failed.");
22274
22317
  } finally {
@@ -34448,7 +34491,7 @@ var cache3 = null;
34448
34491
  async function gateway() {
34449
34492
  if (cache3)
34450
34493
  return cache3;
34451
- const { moduleCatalog } = await import("./cli-r1ng5cjy.js");
34494
+ const { moduleCatalog } = await import("./cli-9x2ne7hp.js");
34452
34495
  const forIndex = [];
34453
34496
  const byName = new Map;
34454
34497
  for (const mod of moduleCatalog) {
@@ -60108,7 +60151,7 @@ var riskByTool = null;
60108
60151
  async function riskIndex() {
60109
60152
  if (riskByTool)
60110
60153
  return riskByTool;
60111
- const { moduleCatalog } = await import("./cli-r1ng5cjy.js");
60154
+ const { moduleCatalog } = await import("./cli-9x2ne7hp.js");
60112
60155
  const index = new Map;
60113
60156
  for (const mod of moduleCatalog) {
60114
60157
  for (const tool of mod.tools)
@@ -71294,4 +71337,4 @@ function selectToolModules2(filter = {}, catalog = moduleCatalog2) {
71294
71337
  }).map((m) => m.tools);
71295
71338
  }
71296
71339
 
71297
- export { __toESM, __commonJS, toJSONSchema, ZodError, string, ipv4, number, boolean, _null, unknown, array, object, looseObject, union, discriminatedUnion, intersection, record, _enum, literal, ZodOptional, optional, custom, preprocess, datetime, exports_coerce, DEFAULT_DASHBOARD_DB2, DEFAULT_SNAPSHOT_DB2, DEFAULT_BACKUP_DIR2, DEFAULT_CONFIG_HISTORY_DIR2, McpServerSettingsSchema2, DeviceConfigSchema2, DashboardConfigSchema2, MemoryConfigSchema2, SSHConfigSchema2, ToolFilterSchema2, AccessConfigSchema2, MikrotikConfigSchema2, getConfigSource2, loadConfig2, onConfigChanged, setConfig, getConfig, listDevices, deviceLabels, resolveDeviceName, deviceDirectory, getDevice, evaluateAccess, previewAccessPolicy, getAccessPolicy, hasSessionNarrowing, recentDenials, assertDeviceAccess, DeviceConnectionError, logger, deviceEndpoints, isMacTelnetDevice, createDeviceClient, describeTransport, isPoolEnabled, closeAll, closeDevice, poolStatus, getSafeModeManager, parseKeyValues, parseRouterosDate, parseSize, parseRecords, parseLeadingNumber, executeMikrotikCommand, executeMikrotikJson, riskOf, redact, createContext, Cmd, isEmpty, flattenLiveOutput, looksLikeError, commandUnsupported, objectFromShape, safeParse, safeParseAsync, getObjectShape, normalizeObjectSchema, getParseErrorMessage, getSchemaDescription, isSchemaOptional, getLiteralValue, toJsonSchemaCompat, getMethodLiteral, parseWithCompat, explainUnmet, serializeCapabilities, isYes, getCapabilities, peekCapabilities, invalidateCapabilities, ScopeSchema, RememberSchema, ReviseSchema, RecallSchema, BrowseSchema, openMemoryStore, getMemoryStore, closeMemoryStore, installMemoryStore, redactChannels, setMcpAlertSender, deliver, parseDuration, AlertRuleSchema, isEventTrigger, ruleWarnings, eventMet, initialState, step, isMuted, parseRules, AlertEngine, setAlertEngine, getAlertEngine, configureRecorder, getEventStore, subscribe, subscriberCount, registerTools, bandwidthServerTools, parseExportMeta2, normalizeExport2, contentSha2, countLines2, openSnapshotStore2, captureSnapshot, startRoutingMonitor, stopRoutingMonitor, startFlightRecorder, stopFlightRecorder, clientCheckOrigin, noteClientPresence, authorizedCheck, saveCheckRun, clientCheckTools, parseExport, routerMigrationTools, supportBundleTools, addressSetTools, fetchDevices, sampleDeviceTraffic, KID_CONTROL_COUNTERS_COMMAND, parseKidControlOutput, sampleAllTraffic, setDeviceLimits, blockDevice, allowDevice, makeDeviceStatic, setDeviceIp, setDeviceLabel, removeDeviceLease, devicesView, ipv6, getFlowCollector, topTalkers, conversations, protocolMix, timeline, summarize, flowStore, FlowPathError, investigationTools, homeInternetTools, buildModel, unreachableRules, tracePacket, diffTraces, listSuites, getSuite, saveSuite, serviceContractTools, serviceRoutingTools, flightRecorderTools, recoveryLabTools, roundTripTools, PROMPTS_DIR, PROJECT_ROOT, UI_DIST_DIR, registerUiResources, backupDir, listBackups, readBackup, writeBackup, deleteBackup, renameBackup, createLocalBackup, restoreLocalBackup, isS3Configured, getS3Client, presignExpiresIn, s3Target, splitCommands, buildChangePlan, renderPlan, diffLines, noteDriftResult, analyzeDrift, attributeChanges, CONTAINER_GUIDE_URI, getRouterosContainerGuide, CONTAINER_INSTRUCTIONS, containerPromptGuidance, applyWritesSafely, evaluatePolicies, validatePolicyText, renderReport, rememberReport, currentPolicySet, verificationSchema, verifyPolicy, buildFabricMap, collectFabric, ADVISORY_DATASET_DATE, ADVISORIES, matchAdvisories, collectDeviceFacts, getDeviceGeo, isPublicIpLiteral, sourceIpLiteral, getIpGeo, ipGeoRoute, startGeoLookups, stopGeoLookups, IpIntelligenceInput, lookupIpIntelligence, decodeTzsp, DEFAULT_TZSP_PORT, capture, OpenVpnOperationError, disconnectOpenVpnInput, listOpenVpnSessions, disconnectOpenVpnSession, AAA_ENTITIES, listAaaEntity, addAaaEntity, updateAaaEntity, removeAaaEntity, toggleAaaEntity, getRadiusIncoming, setRadiusIncoming, resetRadiusCounters, getUmSettings, setUmSettings, requestAbort, runTransaction, createDeviceExecutor, subscribeTxn, liveTxnUpdates, toRecord, getTxn, dropTxn, listTxns, txnStore, persistTxn, publishRollout, subscribeRollout, liveRolloutUpdates, requestHold, resume, requestAbort2, summarize2, buildTopology, getDeviceStatus, getDeviceNeighbors, getDeviceHistory, probeDevice, startHealthChecks, stopHealthChecks, runRollout, createDeviceExecutor2, toRecord2, getRollout, dropRollout, listRollouts, rolloutStore, persistRollout, auditAdapter, schedulableTools, nextRun, describeCron, diffFindings, describeDiff, worstSeverity, severityCounts, JobSchema, scheduleStore, runJob, armJob, nextRunOf, forgetJob, primeRiskIndex, liveExecutor, runnerOptions, startScheduler, stopScheduler, analyzeDevice, diffNarratives, renderDiff, topologyMermaid, NARRATIVE_SECTIONS, renderNarrative, isPlan, neverBlockSet, isNeverBlock, decide, executePlan, revokeBlock, attackStore, buildGuards, policyFromConfig, sweep, startAttackDetection, stopAttackDetection, VERSION, WEBSITE_URL, LOGO_URL, SERVER_TITLE, SERVER_DESCRIPTION, SERVER_NAME, PKG_META, loadFileCacheSync, fetchLatestRelease, checkForUpdate, updateSummaryLine, fetchAllReleases, scopeConfigDraft, mergeDeviceDraft, mergeConfigDraft, serializeConfig, atomicWrite, validateConfig, getConfigAdmin, VLAN_GUIDE_URI, getVlanSegmentationGuide, VLAN_INSTRUCTIONS, vlanPromptGuidance, buildChannelPlanCommands, reportWeakClients, runCapsmanAudit, steerAlreadyPresent, buildSteerCommands, loadBalancePlan, buildLoadBalanceCommands, buildFtCommands, buildHaCommands, haGuidance, capsmanOverview, fetchCapsmanState, moduleCatalog2, allToolModules2, ALWAYS_ON_MODULES2, selectToolModules2 };
71340
+ export { __toESM, __commonJS, toJSONSchema, ZodError, string, ipv4, number, boolean, _null, unknown, array, object, looseObject, union, discriminatedUnion, intersection, record, _enum, literal, ZodOptional, optional, custom, preprocess, datetime, exports_coerce, DEFAULT_DASHBOARD_DB2, DEFAULT_SNAPSHOT_DB2, DEFAULT_BACKUP_DIR2, DEFAULT_CONFIG_HISTORY_DIR2, McpServerSettingsSchema2, DeviceConfigSchema2, DashboardConfigSchema2, MemoryConfigSchema2, SSHConfigSchema2, ToolFilterSchema2, AccessConfigSchema2, MikrotikConfigSchema2, parseFlags2, getConfigSource2, loadConfig2, onConfigChanged, setConfig, getConfig, listDevices, deviceLabels, resolveDeviceName, deviceDirectory, getDevice, evaluateAccess, previewAccessPolicy, getAccessPolicy, hasSessionNarrowing, recentDenials, assertDeviceAccess, DeviceConnectionError, logger, deviceEndpoints, MikroTikSSHClient, isMacTelnetDevice, sshOptionsOf, resolveJump, createDeviceClient, describeTransport, isPoolEnabled, closeAll, closeDevice, poolStatus, getSafeModeManager, parseKeyValues, parseRouterosDate, parseSize, parseRecords, parseLeadingNumber, bypassesSafeMode, executeMikrotikCommand, executeMikrotikJson, riskOf, redact, createContext, quoteValue, Cmd, isEmpty, flattenLiveOutput, looksLikeError, commandUnsupported, objectFromShape, safeParse, safeParseAsync, getObjectShape, normalizeObjectSchema, getParseErrorMessage, getSchemaDescription, isSchemaOptional, getLiteralValue, toJsonSchemaCompat, getMethodLiteral, parseWithCompat, explainUnmet, serializeCapabilities, isYes, getCapabilities, peekCapabilities, invalidateCapabilities, ScopeSchema, RememberSchema, ReviseSchema, RecallSchema, BrowseSchema, openMemoryStore, getMemoryStore, closeMemoryStore, installMemoryStore, redactChannels, setMcpAlertSender, deliver, parseDuration, AlertRuleSchema, isEventTrigger, ruleWarnings, eventMet, initialState, step, isMuted, parseRules, AlertEngine, setAlertEngine, getAlertEngine, configureRecorder, getEventStore, subscribe, subscriberCount, recordToolCall, registerTools, bandwidthServerTools, parseExportMeta2, normalizeExport2, contentSha2, countLines2, openSnapshotStore2, captureSnapshot, startRoutingMonitor, stopRoutingMonitor, startFlightRecorder, stopFlightRecorder, clientCheckOrigin, noteClientPresence, authorizedCheck, saveCheckRun, clientCheckTools, parseExport, routerMigrationTools, supportBundleTools, addressSetTools, fetchDevices, sampleDeviceTraffic, KID_CONTROL_COUNTERS_COMMAND, parseKidControlOutput, sampleAllTraffic, setDeviceLimits, blockDevice, allowDevice, makeDeviceStatic, setDeviceIp, setDeviceLabel, removeDeviceLease, devicesView, ipv6, getFlowCollector, topTalkers, conversations, protocolMix, timeline, summarize, flowStore, FlowPathError, investigationTools, homeInternetTools, buildModel, unreachableRules, tracePacket, diffTraces, listSuites, getSuite, saveSuite, serviceContractTools, serviceRoutingTools, flightRecorderTools, recoveryLabTools, roundTripTools, PROMPTS_DIR, PROJECT_ROOT, UI_DIST_DIR, registerUiResources, backupDir, listBackups, readBackup, writeBackup, deleteBackup, renameBackup, createLocalBackup, restoreLocalBackup, isS3Configured, getS3Client, presignExpiresIn, s3Target, splitCommands, buildChangePlan, renderPlan, diffLines, noteDriftResult, analyzeDrift, attributeChanges, configSnapshotTools, CONTAINER_GUIDE_URI, getRouterosContainerGuide, CONTAINER_INSTRUCTIONS, containerPromptGuidance, applyWritesSafely, toolGatewayTools, evaluatePolicies, validatePolicyText, renderReport, rememberReport, currentPolicySet, verificationSchema, verifyPolicy, buildFabricMap, collectFabric, ADVISORY_DATASET_DATE, ADVISORIES, matchAdvisories, collectDeviceFacts, getDeviceGeo, isPublicIpLiteral, sourceIpLiteral, getIpGeo, ipGeoRoute, startGeoLookups, stopGeoLookups, IpIntelligenceInput, lookupIpIntelligence, decodeTzsp, DEFAULT_TZSP_PORT, capture, OpenVpnOperationError, disconnectOpenVpnInput, listOpenVpnSessions, disconnectOpenVpnSession, AAA_ENTITIES, listAaaEntity, addAaaEntity, updateAaaEntity, removeAaaEntity, toggleAaaEntity, getRadiusIncoming, setRadiusIncoming, resetRadiusCounters, getUmSettings, setUmSettings, requestAbort, runTransaction, createDeviceExecutor, subscribeTxn, liveTxnUpdates, toRecord, getTxn, dropTxn, listTxns, txnStore, persistTxn, publishRollout, subscribeRollout, liveRolloutUpdates, requestHold, resume, requestAbort2, summarize2, buildTopology, getDeviceStatus, getDeviceNeighbors, getDeviceHistory, probeDevice, startHealthChecks, stopHealthChecks, runRollout, createDeviceExecutor2, toRecord2, getRollout, dropRollout, listRollouts, rolloutStore, persistRollout, auditAdapter, schedulableTools, nextRun, describeCron, diffFindings, describeDiff, worstSeverity, severityCounts, JobSchema, scheduleStore, runJob, armJob, nextRunOf, forgetJob, primeRiskIndex, liveExecutor, runnerOptions, startScheduler, stopScheduler, analyzeDevice, diffNarratives, renderDiff, topologyMermaid, NARRATIVE_SECTIONS, renderNarrative, isPlan, neverBlockSet, isNeverBlock, decide, executePlan, revokeBlock, attackStore, buildGuards, policyFromConfig, sweep, startAttackDetection, stopAttackDetection, VERSION, WEBSITE_URL, LOGO_URL, SERVER_TITLE, SERVER_DESCRIPTION, SERVER_NAME, PKG_META, loadFileCacheSync, fetchLatestRelease, checkForUpdate, updateSummaryLine, fetchAllReleases, scopeConfigDraft, mergeDeviceDraft, mergeConfigDraft, serializeConfig, atomicWrite, validateConfig, getConfigAdmin, VLAN_GUIDE_URI, getVlanSegmentationGuide, VLAN_INSTRUCTIONS, vlanPromptGuidance, buildChannelPlanCommands, reportWeakClients, runCapsmanAudit, steerAlreadyPresent, buildSteerCommands, loadBalancePlan, buildLoadBalanceCommands, buildFtCommands, buildHaCommands, haGuidance, capsmanOverview, fetchCapsmanState, moduleCatalog2, allToolModules2, ALWAYS_ON_MODULES2, selectToolModules2 };
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  import {
3
3
  openSnapshotStore2
4
- } from "./cli-1vn2bbpy.js";
4
+ } from "./cli-4n039739.js";
5
5
  export {
6
6
  openSnapshotStore2 as openSnapshotStore
7
7
  };
@@ -12,9 +12,10 @@ import {
12
12
  ToolFilterSchema2,
13
13
  AccessConfigSchema2,
14
14
  MikrotikConfigSchema2,
15
+ parseFlags2,
15
16
  getConfigSource2,
16
17
  loadConfig2
17
- } from "./cli-1vn2bbpy.js";
18
+ } from "./cli-4n039739.js";
18
19
  export {
19
20
  AccessConfigSchema2 as AccessConfigSchema,
20
21
  DEFAULT_BACKUP_DIR2 as DEFAULT_BACKUP_DIR,
@@ -29,5 +30,6 @@ export {
29
30
  SSHConfigSchema2 as SSHConfigSchema,
30
31
  ToolFilterSchema2 as ToolFilterSchema,
31
32
  getConfigSource2 as getConfigSource,
32
- loadConfig2 as loadConfig
33
+ loadConfig2 as loadConfig,
34
+ parseFlags2 as parseFlags
33
35
  };
@@ -4,7 +4,7 @@ import {
4
4
  allToolModules2,
5
5
  ALWAYS_ON_MODULES2,
6
6
  selectToolModules2
7
- } from "./cli-1vn2bbpy.js";
7
+ } from "./cli-4n039739.js";
8
8
  export {
9
9
  ALWAYS_ON_MODULES2 as ALWAYS_ON_MODULES,
10
10
  allToolModules2 as allToolModules,
@@ -0,0 +1,109 @@
1
+ // @bun
2
+ import {
3
+ logger,
4
+ UI_DIST_DIR
5
+ } from "./cli-4n039739.js";
6
+
7
+ // src/observability/remote.ts
8
+ import { readFileSync } from "fs";
9
+ import { join } from "path";
10
+ var {serve } = globalThis.Bun;
11
+ function serverOrigin(server) {
12
+ let url;
13
+ try {
14
+ url = new URL(server);
15
+ } catch {
16
+ throw new Error(`--server must be a URL like http://192.168.1.10:9090 (got "${server}")`);
17
+ }
18
+ if (url.protocol !== "http:" && url.protocol !== "https:")
19
+ throw new Error(`--server must use http or https (got "${url.protocol}")`);
20
+ return url.origin;
21
+ }
22
+ function upstreamUrl(origin, pathAndQuery, ws = false) {
23
+ const url = new URL(pathAndQuery, origin);
24
+ if (ws)
25
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
26
+ return url.href;
27
+ }
28
+ function upstreamHeaders(incoming, token) {
29
+ const out = new Headers(incoming);
30
+ for (const name of ["host", "connection", "authorization", "accept-encoding"])
31
+ out.delete(name);
32
+ if (token)
33
+ out.set("authorization", `Bearer ${token}`);
34
+ return out;
35
+ }
36
+ function localPage(dir = UI_DIST_DIR) {
37
+ try {
38
+ return readFileSync(join(dir, "observability.html"), "utf8");
39
+ } catch {
40
+ return;
41
+ }
42
+ }
43
+ function runRemoteDashboard(options) {
44
+ const origin = serverOrigin(options.server);
45
+ const auth = options.token ? { authorization: `Bearer ${options.token}` } : undefined;
46
+ const server = serve({
47
+ hostname: options.host,
48
+ port: options.port,
49
+ idleTimeout: 0,
50
+ async fetch(req, srv) {
51
+ const url = new URL(req.url);
52
+ const path = url.pathname + url.search;
53
+ if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
54
+ const target = upstreamUrl(origin, path, true);
55
+ return srv.upgrade(req, { data: { target } }) ? undefined : new Response("WebSocket upgrade failed", { status: 400 });
56
+ }
57
+ if (req.method === "GET" && (url.pathname === "/" || url.pathname === "/index.html")) {
58
+ const page = localPage();
59
+ if (page !== undefined)
60
+ return new Response(page, { headers: { "content-type": "text/html; charset=utf-8" } });
61
+ }
62
+ try {
63
+ const res = await fetch(upstreamUrl(origin, path), {
64
+ method: req.method,
65
+ headers: upstreamHeaders(req.headers, options.token),
66
+ body: req.method === "GET" || req.method === "HEAD" ? undefined : req.body,
67
+ redirect: "manual",
68
+ signal: req.signal
69
+ });
70
+ const headers = new Headers(res.headers);
71
+ headers.delete("content-encoding");
72
+ headers.delete("content-length");
73
+ return new Response(res.body, { status: res.status, headers });
74
+ } catch (e) {
75
+ if (req.signal.aborted)
76
+ return new Response(null, { status: 499 });
77
+ const reason = e instanceof Error ? e.message : String(e);
78
+ return new Response(`Cannot reach the MikroTik MCP server at ${origin}: ${reason}`, {
79
+ status: 502
80
+ });
81
+ }
82
+ },
83
+ websocket: {
84
+ open(ws) {
85
+ const upstream = new WebSocket(ws.data.target, { headers: auth });
86
+ ws.data.upstream = upstream;
87
+ upstream.onmessage = (m) => ws.send(m.data);
88
+ upstream.onclose = () => ws.close();
89
+ upstream.onerror = () => ws.close();
90
+ },
91
+ message(ws, message) {
92
+ const upstream = ws.data.upstream;
93
+ if (upstream?.readyState === WebSocket.OPEN)
94
+ upstream.send(message);
95
+ },
96
+ close(ws) {
97
+ ws.data.upstream?.close();
98
+ }
99
+ }
100
+ });
101
+ logger.info(`Remote dashboard ready \u2014 open http://${options.host === "0.0.0.0" ? "localhost" : options.host}:${options.port} ` + `(server ${origin}${options.token ? ", token set" : ""}, page: ` + `${localPage() === undefined ? "the server's \u2014 no local build, run `bun run build:ui` to use this machine's UI" : "this machine's build"})`);
102
+ if (options.host !== "127.0.0.1" && options.host !== "localhost" && options.host !== "::1") {
103
+ logger.warn("The remote dashboard is reachable from other machines and asks for no token of its own: " + "anyone who can open it gets the server's dashboard, including its config editor. " + "Bind it to 127.0.0.1 unless that is intended.");
104
+ }
105
+ return { stop: () => server.stop(true) };
106
+ }
107
+ export {
108
+ runRemoteDashboard
109
+ };
@@ -4,7 +4,7 @@ import {
4
4
  normalizeExport2,
5
5
  contentSha2,
6
6
  countLines2
7
- } from "./library-2wd7mt3g.js";
7
+ } from "./library-7qr2sc9x.js";
8
8
  export {
9
9
  contentSha2 as contentSha,
10
10
  countLines2 as countLines,
@@ -11,7 +11,7 @@ import {
11
11
  MikrotikConfigSchema2,
12
12
  getConfigSource2,
13
13
  loadConfig2
14
- } from "./library-2wd7mt3g.js";
14
+ } from "./library-7qr2sc9x.js";
15
15
  export {
16
16
  DEFAULT_BACKUP_DIR2 as DEFAULT_BACKUP_DIR,
17
17
  DEFAULT_DASHBOARD_DB2 as DEFAULT_DASHBOARD_DB,