@usex/mikrotik-mcp 6.2.0 → 6.4.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
@@ -18413,12 +18413,25 @@ class SafeModeManager {
18413
18413
  uncertain = false;
18414
18414
  probeSequence = 0;
18415
18415
  queue = Promise.resolve();
18416
+ commandTimeoutMs = HARD_CAP_MS;
18417
+ idleTimeoutMs = IDLE_TIMEOUT_MS;
18418
+ setTimeouts(commandTimeoutMs, idleTimeoutMs) {
18419
+ if (!Number.isInteger(commandTimeoutMs) || commandTimeoutMs < 1000 || commandTimeoutMs > 600000 || !Number.isInteger(idleTimeoutMs) || idleTimeoutMs < 1000 || idleTimeoutMs > commandTimeoutMs) {
18420
+ throw new Error("Timeouts must be integer milliseconds: 1000 <= idleTimeoutMs <= commandTimeoutMs <= 600000.");
18421
+ }
18422
+ this.commandTimeoutMs = commandTimeoutMs;
18423
+ this.idleTimeoutMs = idleTimeoutMs;
18424
+ return `Safe Mode command timeout: ${commandTimeoutMs}ms; idle timeout: ${idleTimeoutMs}ms. Applies to subsequent commands only; does not change RouterOS rollback timing or clear an uncertain session.`;
18425
+ }
18416
18426
  constructor(deviceName) {
18417
18427
  this.deviceName = deviceName;
18418
18428
  }
18419
18429
  get isActive() {
18420
18430
  return this.active;
18421
18431
  }
18432
+ get requiresRecovery() {
18433
+ return this.droppedUnexpectedly || this.uncertain;
18434
+ }
18422
18435
  lock(fn) {
18423
18436
  const run = this.queue.then(fn, fn);
18424
18437
  this.queue = run.then(() => {
@@ -18459,20 +18472,20 @@ class SafeModeManager {
18459
18472
  return `Error: Safe mode did not activate. Response: ${JSON.stringify(response.slice(0, 300))}`;
18460
18473
  }
18461
18474
  this.active = true;
18462
- return "Safe mode ENABLED. All changes are temporary \u2014 they will be reverted " + "automatically if the connection drops or you call rollback_safe_mode. " + "Call commit_safe_mode to make changes permanent.";
18475
+ return "Safe mode ENABLED. RouterOS tracks reversible changes while protection remains active. " + "Keep a backup; disconnect requests rollback but does not prove restoration. " + "Call commit_safe_mode after verification.";
18463
18476
  });
18464
18477
  }
18465
18478
  execute(command) {
18466
18479
  return this.lock(async () => {
18467
18480
  if (this.droppedUnexpectedly) {
18468
- throw new Error("Safe Mode session dropped \u2014 RouterOS auto-reverted every staged change; nothing " + "was saved. Re-enable Safe Mode and re-apply, or apply the change directly.");
18481
+ throw new Error("Safe Mode session dropped. Rollback is unverified; inspect device state against the backup before retrying writes.");
18469
18482
  }
18470
18483
  if (!this.active || !this.channel) {
18471
18484
  throw new Error("Safe mode session is not active.");
18472
18485
  }
18473
18486
  if (this.uncertain)
18474
18487
  throw new Error(UNCERTAIN_SESSION);
18475
- const response = this.readUntilPrompt(IDLE_TIMEOUT_MS, undefined, HARD_CAP_MS, true);
18488
+ const response = this.readUntilPrompt(this.idleTimeoutMs, undefined, this.commandTimeoutMs, true);
18476
18489
  this.channel.write(`${command}
18477
18490
  `);
18478
18491
  const { text, timedOut } = await response;
@@ -18480,16 +18493,19 @@ class SafeModeManager {
18480
18493
  this.uncertain = true;
18481
18494
  throw new Error(`Safe Mode command did not return a recognized prompt before the timeout (command: ${command}). ` + `Execution may have occurred; do not retry the write blindly. ${UNCERTAIN_SESSION}`);
18482
18495
  }
18496
+ if (classifyPrompt(text) !== "safe") {
18497
+ this.uncertain = true;
18498
+ throw new Error(`Safe Mode protection was lost or could not be confirmed. Changes may already be permanent. ${UNCERTAIN_SESSION}`);
18499
+ }
18483
18500
  return this.extractOutput(text, command);
18484
18501
  });
18485
18502
  }
18486
18503
  commit() {
18487
18504
  return this.lock(async () => {
18488
18505
  if (this.droppedUnexpectedly) {
18489
- this.droppedUnexpectedly = false;
18490
18506
  return {
18491
18507
  ok: false,
18492
- message: "Commit FAILED \u2014 the Safe Mode session dropped before this commit, so RouterOS " + "automatically reverted ALL staged changes and NOTHING was saved. Re-enable Safe Mode " + "and re-apply the changes (or apply them directly and verify each with a read)."
18508
+ message: "Commit FAILED \u2014 the Safe Mode session dropped. Rollback is unverified; compare device state with the backup before retrying."
18493
18509
  };
18494
18510
  }
18495
18511
  if (!this.active || !this.channel) {
@@ -18499,16 +18515,16 @@ class SafeModeManager {
18499
18515
  return { ok: false, message: UNCERTAIN_SESSION };
18500
18516
  const before = await this.probeMode();
18501
18517
  if (before === "released") {
18502
- this.cleanup();
18518
+ this.uncertain = true;
18503
18519
  return {
18504
- ok: true,
18505
- message: "Safe mode already exited \u2014 your changes are committed. Safe mode DISABLED."
18520
+ ok: false,
18521
+ message: "Safe Mode exited before commit was requested. Changes may be permanent; verify device state against the backup."
18506
18522
  };
18507
18523
  }
18508
18524
  if (before === "unknown") {
18509
18525
  return {
18510
18526
  ok: false,
18511
- message: "Could not read a prompt to determine Safe Mode state. The session is left open so " + "nothing is reverted \u2014 call get_safe_mode_status, retry commit_safe_mode, or rollback_safe_mode."
18527
+ message: "Could not determine Safe Mode state. Session left open; outcome unverified. " + "Call safe_mode_status or rollback_safe_mode and inspect device state."
18512
18528
  };
18513
18529
  }
18514
18530
  this.channel.write(CTRL_X);
@@ -18525,7 +18541,7 @@ class SafeModeManager {
18525
18541
  default:
18526
18542
  return {
18527
18543
  ok: false,
18528
- message: "Commit status unclear \u2014 no prompt seen after the commit. The session is left open so " + "nothing is reverted; verify with get_safe_mode_status or retry commit_safe_mode."
18544
+ message: "Commit status unclear \u2014 no prompt seen after commit. Session left open; outcome unverified. " + "Inspect device state before retrying."
18529
18545
  };
18530
18546
  }
18531
18547
  });
@@ -18534,21 +18550,21 @@ class SafeModeManager {
18534
18550
  return this.lock(async () => {
18535
18551
  if (this.droppedUnexpectedly) {
18536
18552
  this.droppedUnexpectedly = false;
18537
- return "Safe Mode session had already dropped \u2014 RouterOS auto-reverted all staged changes; " + "nothing was left to roll back.";
18553
+ return "Safe Mode session had already dropped. Rollback is unverified; compare device state with the backup. Do not blindly reapply writes.";
18538
18554
  }
18539
18555
  if (!this.active)
18540
18556
  return "Safe mode is not active. Nothing to roll back.";
18541
18557
  this.cleanup();
18542
- return "Safe mode session closed. MikroTik has reverted all uncommitted changes automatically.";
18558
+ return "Safe mode session closed to request automatic rollback. Rollback is unverified and may be delayed; compare device state with the backup before retrying writes.";
18543
18559
  });
18544
18560
  }
18545
18561
  status() {
18546
18562
  if (this.droppedUnexpectedly) {
18547
- return "Safe mode session DROPPED unexpectedly \u2014 RouterOS auto-reverted all staged changes; they " + "were NOT saved. Re-enable Safe Mode and re-apply, or apply changes directly (verify each with a read).";
18563
+ return "Safe mode session DROPPED unexpectedly. Rollback is unverified; inspect device state against the backup before retrying writes.";
18548
18564
  }
18549
18565
  if (this.uncertain && this.active)
18550
18566
  return UNCERTAIN_SESSION;
18551
- return this.active ? "Safe mode is ACTIVE. Changes are pending \u2014 they are NOT yet persisted. " + "Call commit_safe_mode to persist or rollback_safe_mode to revert." : "Safe mode is NOT active. Changes take effect and persist immediately.";
18567
+ return this.active ? `Safe mode is ACTIVE (last observed). Command timeout: ${this.commandTimeoutMs}ms; idle timeout: ${this.idleTimeoutMs}ms. ` + "Call commit_safe_mode to persist or rollback_safe_mode to revert." : "Safe mode is NOT active. Changes take effect and persist immediately.";
18552
18568
  }
18553
18569
  handleUnexpectedDrop = () => {
18554
18570
  if (!this.active)
@@ -18564,6 +18580,7 @@ class SafeModeManager {
18564
18580
  let buf = "";
18565
18581
  let idleTimer;
18566
18582
  const hardTimer = setTimeout(() => finish(stripAnsi(buf), true), hardCapMs);
18583
+ const onClose = () => finish(stripAnsi(buf), true);
18567
18584
  function armIdle() {
18568
18585
  clearTimeout(idleTimer);
18569
18586
  idleTimer = setTimeout(() => finish(stripAnsi(buf), true), idleMs);
@@ -18586,10 +18603,14 @@ class SafeModeManager {
18586
18603
  clearTimeout(idleTimer);
18587
18604
  clearTimeout(hardTimer);
18588
18605
  channel.removeListener("data", onData);
18606
+ channel.removeListener("close", onClose);
18607
+ channel.removeListener("error", onClose);
18589
18608
  resolve({ text: result, timedOut });
18590
18609
  }
18591
18610
  armIdle();
18592
18611
  channel.on("data", onData);
18612
+ channel.once("close", onClose);
18613
+ channel.once("error", onClose);
18593
18614
  });
18594
18615
  }
18595
18616
  async probeMode() {
@@ -18724,7 +18745,7 @@ async function runOnce(command, deviceName, opts, ctx) {
18724
18745
  async function executeMikrotikCommand(command, ctx, opts) {
18725
18746
  const deviceName = resolveDeviceName(ctx.device);
18726
18747
  const safe = getSafeModeManager(deviceName);
18727
- if (safe.isActive) {
18748
+ if (safe.isActive || safe.requiresRecovery) {
18728
18749
  ctx.info(`[${deviceName}] Executing (safe mode): ${containerCommandForLog(command)}`);
18729
18750
  ctx.transport = "ssh";
18730
18751
  return safe.execute(command);
@@ -21892,13 +21913,13 @@ async function undoMigration(id, confirm, selected) {
21892
21913
  throw new Error("Undo lost Safe Mode or exceeded its time budget.");
21893
21914
  await checkedRead(item.undo, createContext(undefined, device));
21894
21915
  }
21895
- const beforeTarget = (await import("./shared/cli-5qqtzj1z.js")).openSnapshotStore;
21896
- const db = await beforeTarget((await import("./shared/cli-fjzymtm7.js")).DEFAULT_SNAPSHOT_DB);
21916
+ const beforeTarget = (await import("./shared/cli-j9nrx9mk.js")).openSnapshotStore;
21917
+ const db = await beforeTarget((await import("./shared/cli-pmy050a0.js")).DEFAULT_SNAPSHOT_DB);
21897
21918
  try {
21898
21919
  const original = db.get(p.snapshots.target);
21899
21920
  if (!original)
21900
21921
  throw new Error("Original target snapshot unavailable.");
21901
- const { normalizeExport } = await import("./shared/cli-76mdhx9m.js");
21922
+ const { normalizeExport } = await import("./shared/cli-qc7ckbhk.js");
21902
21923
  if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
21903
21924
  throw new Error("Target differs from its backup. Undo verification failed.");
21904
21925
  } finally {
@@ -34263,23 +34284,13 @@ async function applyWritesSafely(ctx, deviceName, commands, opts = {}) {
34263
34284
  await mgr.rollback().catch(() => {
34264
34285
  return;
34265
34286
  });
34266
- if (!fallback)
34267
- return {
34268
- applied,
34269
- total,
34270
- safeMode: `rolled back (a write failed: ${wedged})`,
34271
- committed: false,
34272
- error: wedged,
34273
- fellBack: false
34274
- };
34275
- const r = await applyCommandsDirect(ctx, commands);
34276
34287
  return {
34277
- applied: r.applied,
34288
+ applied,
34278
34289
  total,
34279
- safeMode: `Safe Mode wedged (${wedged}) \u2014 rolled back and re-applied directly (snapshot is the rollback point)`,
34280
- committed: !r.error,
34281
- error: r.error,
34282
- fellBack: true
34290
+ safeMode: `rollback requested, unverified (a write failed: ${wedged}); inspect the snapshot before retrying`,
34291
+ committed: false,
34292
+ error: wedged,
34293
+ fellBack: false
34283
34294
  };
34284
34295
  }
34285
34296
  const c = await mgr.commit();
@@ -34658,7 +34669,7 @@ var cache3 = null;
34658
34669
  async function gateway() {
34659
34670
  if (cache3)
34660
34671
  return cache3;
34661
- const { moduleCatalog } = await import("./shared/cli-j0jhy663.js");
34672
+ const { moduleCatalog } = await import("./shared/cli-wpshhzhr.js");
34662
34673
  const forIndex = [];
34663
34674
  const byName = new Map;
34664
34675
  for (const mod of moduleCatalog) {
@@ -57101,6 +57112,19 @@ ${details}`;
57101
57112
 
57102
57113
  // src/tools/safe-mode.ts
57103
57114
  var safeModeTools = [
57115
+ defineTool({
57116
+ name: "set_safe_mode_timeout",
57117
+ title: "Set Safe Mode Command Timeouts",
57118
+ annotations: WRITE,
57119
+ description: "Set per-device MCP Safe Mode command deadlines before or during a session. Applies only to subsequent commands. Increase for slow exports, decrease for faster failure detection. Does not change RouterOS rollback timing, MCP client deadlines, or unblock an uncertain session. Settings are in-memory and reset on MCP restart. Defaults: command 120000ms, idle 15000ms.",
57120
+ inputSchema: {
57121
+ commandTimeoutMs: number2().int().min(1000).max(600000).describe("Absolute command deadline in milliseconds."),
57122
+ idleTimeoutMs: number2().int().min(1000).max(600000).describe("Maximum silence in milliseconds; must not exceed commandTimeoutMs.")
57123
+ },
57124
+ handler(a, ctx) {
57125
+ return getSafeModeManager(resolveDeviceName(ctx.device)).setTimeouts(a.commandTimeoutMs, a.idleTimeoutMs);
57126
+ }
57127
+ }),
57104
57128
  defineTool({
57105
57129
  name: "safe_mode_status",
57106
57130
  title: "Get Safe Mode Session Status",
@@ -57116,7 +57140,7 @@ var safeModeTools = [
57116
57140
  name: "enable_safe_mode",
57117
57141
  title: "Enable Safe Mode Session",
57118
57142
  annotations: WRITE,
57119
- description: "Opens a Safe Mode SSH session on the targeted device (RouterOS Ctrl+X equivalent) \u2014 all subsequent configuration changes are staged in memory and auto-reverted if the SSH connection drops before an explicit commit." + " Use this to make reversible, transactional configuration changes without risk of permanent misconfiguration." + " Safe Mode is SSH-only and is not supported over MAC-Telnet connections." + " Check current state first with safe_mode_status; persist staged changes with commit_safe_mode; discard staged changes without saving with rollback_safe_mode.",
57143
+ description: "Opens a Safe Mode SSH session on the targeted device (RouterOS Ctrl+X equivalent) \u2014 all subsequent configuration changes are staged in memory and auto-reverted if the SSH connection drops before an explicit commit." + " Take a backup first: protection may be lost and disconnect is not proof of rollback. Use set_safe_mode_timeout to tune subsequent command deadlines." + " Safe Mode is SSH-only and is not supported over MAC-Telnet connections." + " Check current state first with safe_mode_status; persist staged changes with commit_safe_mode; discard staged changes without saving with rollback_safe_mode.",
57120
57144
  async handler(_a, ctx) {
57121
57145
  const device = resolveDeviceName(ctx.device);
57122
57146
  ctx.info(`[${device}] Enabling MikroTik safe mode`);
@@ -57138,7 +57162,7 @@ var safeModeTools = [
57138
57162
  name: "rollback_safe_mode",
57139
57163
  title: "Roll Back Safe Mode Changes",
57140
57164
  annotations: WRITE,
57141
- description: "Discards all pending Safe Mode changes on the targeted device by closing the SSH session, triggering RouterOS's automatic revert \u2014 all configuration changes staged since enable_safe_mode was called are undone as if they were never applied." + " Use this when staged changes are incorrect or need to be abandoned without saving." + " To persist staged changes instead, use commit_safe_mode." + " Check current Safe Mode state with safe_mode_status.",
57165
+ description: "Closes the targeted Safe Mode SSH session to request RouterOS automatic rollback. Completion is unverified and may be delayed; compare live configuration against a backup before retrying writes." + " Use this when staged changes are incorrect or need to be abandoned without saving." + " To persist staged changes instead, use commit_safe_mode." + " Check current Safe Mode state with safe_mode_status.",
57142
57166
  async handler(_a, ctx) {
57143
57167
  const device = resolveDeviceName(ctx.device);
57144
57168
  ctx.info(`[${device}] Rolling back safe mode changes`);
@@ -59938,7 +59962,7 @@ var riskByTool = null;
59938
59962
  async function riskIndex() {
59939
59963
  if (riskByTool)
59940
59964
  return riskByTool;
59941
- const { moduleCatalog } = await import("./shared/cli-j0jhy663.js");
59965
+ const { moduleCatalog } = await import("./shared/cli-wpshhzhr.js");
59942
59966
  const index = new Map;
59943
59967
  for (const mod of moduleCatalog) {
59944
59968
  for (const tool of mod.tools)
@@ -71044,7 +71068,7 @@ import { existsSync as existsSync6 } from "fs";
71044
71068
  import { spawn } from "child_process";
71045
71069
  import { readFileSync as readFileSync14 } from "fs";
71046
71070
  import { homedir as homedir6, networkInterfaces as networkInterfaces2 } from "os";
71047
- import { dirname as dirname23, join as join16 } from "path";
71071
+ import { dirname as dirname24, join as join16 } from "path";
71048
71072
  var {serve } = globalThis.Bun;
71049
71073
 
71050
71074
  // src/observability/modules.ts
@@ -71608,8 +71632,8 @@ function logError(e) {
71608
71632
  }
71609
71633
 
71610
71634
  // src/observability/openvpn-routes.ts
71611
- async function openVpnRoutes(req, url) {
71612
- if (url.pathname !== "/api/openvpn/sessions" && url.pathname !== "/api/openvpn/disconnect")
71635
+ async function openVpnRoutes(req, url, history) {
71636
+ if (!["/api/openvpn/sessions", "/api/openvpn/disconnect", "/api/openvpn/history"].includes(url.pathname))
71613
71637
  return null;
71614
71638
  try {
71615
71639
  const device = url.searchParams.get("device");
@@ -71617,7 +71641,28 @@ async function openVpnRoutes(req, url) {
71617
71641
  throw new DashboardInputError(400, "Select an explicit router first.");
71618
71642
  const ctx = createContext(undefined, device);
71619
71643
  let result;
71620
- if (req.method === "GET" && url.pathname === "/api/openvpn/sessions") {
71644
+ if (req.method === "GET" && url.pathname === "/api/openvpn/history") {
71645
+ let resolved;
71646
+ try {
71647
+ resolved = resolveDeviceName(device);
71648
+ } catch {
71649
+ throw new DashboardInputError(400, "Unknown router.");
71650
+ }
71651
+ try {
71652
+ assertDeviceAccess([resolved], "list_ovpn_sessions", "READ");
71653
+ } catch {
71654
+ throw new DashboardInputError(403, "Device access denied.");
71655
+ }
71656
+ if (!history)
71657
+ return Response.json({ error: "OpenVPN history storage is unavailable." }, { status: 503 });
71658
+ const user = url.searchParams.get("user") ?? "";
71659
+ const from = Number(url.searchParams.get("from") ?? 0);
71660
+ const to = Number(url.searchParams.get("to") ?? 8640000000000000);
71661
+ const offset = Number(url.searchParams.get("offset") ?? 0);
71662
+ if (user.length > 256 || ![from, to, offset].every(Number.isSafeInteger) || from < 0 || to < from || to > 8640000000000000 || offset < 0 || offset > 1e6)
71663
+ throw new DashboardInputError(400, "Provide a valid user, date range and page.");
71664
+ result = history.report({ device: resolved, user, from, to, offset });
71665
+ } else if (req.method === "GET" && url.pathname === "/api/openvpn/sessions") {
71621
71666
  const snapshot = await listOpenVpnSessions(ctx);
71622
71667
  result = {
71623
71668
  ...snapshot,
@@ -71650,6 +71695,203 @@ async function openVpnRoutes(req, url) {
71650
71695
  }
71651
71696
  }
71652
71697
 
71698
+ // src/observability/openvpn-history.ts
71699
+ import { randomUUID as randomUUID12 } from "crypto";
71700
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync17 } from "fs";
71701
+ import { dirname as dirname18 } from "path";
71702
+ var OPENVPN_HISTORY_INTERVAL = 15000;
71703
+ function sameObservedSession(previous, session, at) {
71704
+ if (previous.ended !== null)
71705
+ return false;
71706
+ if (session.uptimeSeconds === null || previous.uptime === null)
71707
+ return at - previous.lastSeen <= OPENVPN_HISTORY_INTERVAL * 3;
71708
+ return session.uptimeSeconds >= previous.uptime && Math.abs(at - session.uptimeSeconds * 1000 - previous.started) <= 20000;
71709
+ }
71710
+
71711
+ class OpenVpnHistoryStore {
71712
+ db;
71713
+ cache = new Map;
71714
+ constructor(db) {
71715
+ this.db = db;
71716
+ db.run("PRAGMA journal_mode=WAL");
71717
+ db.run("PRAGMA busy_timeout=5000");
71718
+ db.run(`CREATE TABLE IF NOT EXISTS ovpn_history (
71719
+ id TEXT PRIMARY KEY, device TEXT NOT NULL, user TEXT NOT NULL, identity TEXT NOT NULL,
71720
+ ip TEXT NOT NULL, tunnel TEXT NOT NULL, started INTEGER NOT NULL, firstSeen INTEGER NOT NULL,
71721
+ lastSeen INTEGER NOT NULL, ended INTEGER, uptime INTEGER, uncertain INTEGER NOT NULL,
71722
+ country TEXT NOT NULL, countryCode TEXT NOT NULL, asn TEXT NOT NULL, organization TEXT NOT NULL,
71723
+ geoStatus TEXT NOT NULL)`);
71724
+ db.run("CREATE INDEX IF NOT EXISTS ovpn_history_geo ON ovpn_history(ip,lastSeen) WHERE geoStatus='pending'");
71725
+ db.run("CREATE INDEX IF NOT EXISTS ovpn_history_user ON ovpn_history(device,user,started)");
71726
+ db.run("CREATE INDEX IF NOT EXISTS ovpn_history_time ON ovpn_history(device,started)");
71727
+ db.run("CREATE INDEX IF NOT EXISTS ovpn_history_ip ON ovpn_history(ip)");
71728
+ db.run("CREATE INDEX IF NOT EXISTS ovpn_history_active ON ovpn_history(device) WHERE ended IS NULL");
71729
+ db.run(`CREATE TABLE IF NOT EXISTS ovpn_coverage (
71730
+ device TEXT PRIMARY KEY, first INTEGER NOT NULL, last INTEGER NOT NULL,
71731
+ gaps INTEGER NOT NULL DEFAULT 0, failures INTEGER NOT NULL DEFAULT 0)`);
71732
+ }
71733
+ ingest(snapshot) {
71734
+ const { device, observedAt: at, sessions } = snapshot;
71735
+ this.db.transaction(() => {
71736
+ const coverage = this.db.query("SELECT last FROM ovpn_coverage WHERE device=?").get(device);
71737
+ if (coverage && at <= coverage.last)
71738
+ return;
71739
+ const gap = !!coverage && at - coverage.last > OPENVPN_HISTORY_INTERVAL * 3;
71740
+ const previous = this.db.query("SELECT * FROM ovpn_history WHERE device=? AND ended IS NULL").all(device);
71741
+ const active = new Map(previous.map((row) => [row.identity, row]));
71742
+ for (const session of sessions) {
71743
+ const identity = JSON.stringify([
71744
+ session.id,
71745
+ session.sessionId,
71746
+ session.name,
71747
+ session.callerId,
71748
+ session.address
71749
+ ]);
71750
+ const old = active.get(identity);
71751
+ const geo = session.sourceGeo;
71752
+ if (old && sameObservedSession(old, session, at)) {
71753
+ this.db.query(`UPDATE ovpn_history SET lastSeen=?,
71754
+ started=CASE WHEN uptime IS NULL AND ? IS NOT NULL THEN ? ELSE started END,
71755
+ uptime=COALESCE(?,uptime),uncertain=MAX(uncertain,?),
71756
+ country=CASE WHEN ?='' THEN country ELSE ? END,
71757
+ countryCode=CASE WHEN ?='' THEN countryCode ELSE ? END,
71758
+ asn=CASE WHEN ?='' THEN asn ELSE ? END,
71759
+ organization=CASE WHEN ?='' THEN organization ELSE ? END,
71760
+ geoStatus=CASE WHEN countryCode='' THEN ? ELSE geoStatus END WHERE id=?`).run(at, session.uptimeSeconds, at - (session.uptimeSeconds ?? 0) * 1000, session.uptimeSeconds, Number(gap || session.uptimeSeconds === null), geo?.country ?? "", geo?.country ?? "", geo?.countryCode ?? "", geo?.countryCode ?? "", geo?.asn ?? "", geo?.asn ?? "", geo?.asnOrganization ?? "", geo?.asnOrganization ?? "", geo?.status ?? "pending", old.id);
71761
+ active.delete(identity);
71762
+ } else {
71763
+ this.db.query("INSERT INTO ovpn_history VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(randomUUID12(), device, session.name, identity, session.callerId, session.address, at - (session.uptimeSeconds ?? 0) * 1000, at, at, null, session.uptimeSeconds, Number(gap || session.uptimeSeconds === null), geo?.country ?? "", geo?.countryCode ?? "", geo?.asn ?? "", geo?.asnOrganization ?? "", geo?.status ?? "pending");
71764
+ }
71765
+ }
71766
+ for (const row of active.values())
71767
+ this.db.query("UPDATE ovpn_history SET ended=?,uncertain=MAX(uncertain,?) WHERE id=?").run(at, Number(gap), row.id);
71768
+ this.db.query(`INSERT INTO ovpn_coverage(device,first,last) VALUES (?,?,?)
71769
+ ON CONFLICT(device) DO UPDATE SET last=excluded.last,gaps=gaps+?`).run(device, at, at, Number(gap));
71770
+ })();
71771
+ }
71772
+ failure(device) {
71773
+ this.db.query("UPDATE ovpn_coverage SET failures=failures+1 WHERE device=?").run(device);
71774
+ }
71775
+ enrich(lookup) {
71776
+ const pending = this.db.query("SELECT ip FROM ovpn_history WHERE geoStatus='pending' GROUP BY ip ORDER BY MAX(lastSeen) DESC LIMIT 100").all();
71777
+ for (const { ip } of pending) {
71778
+ const geo = lookup(ip);
71779
+ if (!geo || geo.status === "pending")
71780
+ continue;
71781
+ this.db.query("UPDATE ovpn_history SET country=?,countryCode=?,asn=?,organization=?,geoStatus=? WHERE ip=? AND geoStatus='pending'").run(geo.country ?? "", geo.countryCode ?? "", geo.asn ?? "", geo.asnOrganization ?? "", geo.status, ip);
71782
+ }
71783
+ }
71784
+ report(filter, now = Date.now()) {
71785
+ const key = JSON.stringify(filter);
71786
+ const cached = this.cache.get(key);
71787
+ if (cached && cached.expires > now)
71788
+ return cached.report;
71789
+ const { device, user, from, to, offset } = filter;
71790
+ const where = "device=? AND (?='' OR user=?) AND started>=? AND started<=?";
71791
+ const args = [device, user, user, from, to];
71792
+ const totals = this.db.query(`SELECT
71793
+ COUNT(*) connections,COUNT(DISTINCT user) users,COUNT(DISTINCT NULLIF(ip,'')) ips,
71794
+ COUNT(DISTINCT NULLIF(countryCode,'')) countries,COUNT(DISTINCT NULLIF(asn,'')) networks,
71795
+ COALESCE(SUM(uptime),0) seconds FROM ovpn_history WHERE ${where}`).get(...args);
71796
+ const groups = (label, detail) => this.db.query(`SELECT ${label} label,${detail} detail,COUNT(*) count FROM ovpn_history WHERE ${where}
71797
+ GROUP BY label ORDER BY count DESC,label LIMIT 20`).all(...args);
71798
+ const dayMs = 86400000;
71799
+ const lastDay = Math.floor(Math.min(to, now) / dayMs) * dayMs;
71800
+ const firstDay = Math.max(Math.floor(from / dayMs) * dayMs, lastDay - 89 * dayMs);
71801
+ const daily = new Map(this.db.query(`SELECT strftime('%Y-%m-%d',started/1000,'unixepoch') day,COUNT(*) count FROM ovpn_history WHERE ${where} AND started>=? GROUP BY day`).all(...args, firstDay).map((row) => [row.day, row.count]));
71802
+ const timeline = [];
71803
+ for (let at = firstDay;at <= lastDay; at += dayMs) {
71804
+ const day = new Date(at).toISOString().slice(0, 10);
71805
+ timeline.push({ day, count: daily.get(day) ?? 0 });
71806
+ }
71807
+ const report = {
71808
+ generatedAt: now,
71809
+ coverage: this.db.query("SELECT first,last,gaps,failures FROM ovpn_coverage WHERE device=?").get(device),
71810
+ users: this.db.query("SELECT DISTINCT user FROM ovpn_history WHERE device=? ORDER BY user LIMIT 10000").all(device).map((r) => r.user),
71811
+ allTime: this.db.query("SELECT COUNT(*) n FROM ovpn_history WHERE device=? AND (?='' OR user=?)").get(device, user, user).n,
71812
+ totals,
71813
+ timeline,
71814
+ ips: groups("COALESCE(NULLIF(ip,''),'Unknown IP')", "MAX(organization)"),
71815
+ networks: groups("COALESCE(NULLIF(asn,''),'Unknown ASN')", "MAX(organization)"),
71816
+ countries: groups("COALESCE(NULLIF(country,''),'Unknown country')", "MAX(countryCode)"),
71817
+ sessions: this.db.query(`SELECT * FROM ovpn_history WHERE ${where} ORDER BY started DESC,id LIMIT 50 OFFSET ?`).all(...args, offset),
71818
+ offset,
71819
+ limit: 50
71820
+ };
71821
+ if (this.cache.size >= 128)
71822
+ this.cache.delete(this.cache.keys().next().value);
71823
+ this.cache.set(key, { expires: now + 30000, report });
71824
+ return report;
71825
+ }
71826
+ close() {
71827
+ this.cache.clear();
71828
+ this.db.close();
71829
+ }
71830
+ }
71831
+ async function openOpenVpnHistory(path) {
71832
+ mkdirSync17(dirname18(path), { recursive: true, mode: 448 });
71833
+ const { Database } = await import("bun:sqlite");
71834
+ const db = new Database(path, { create: true });
71835
+ chmodSync2(path, 384);
71836
+ try {
71837
+ return new OpenVpnHistoryStore(db);
71838
+ } catch (error) {
71839
+ db.close();
71840
+ throw error;
71841
+ }
71842
+ }
71843
+
71844
+ // src/observability/openvpn-history-sampler.ts
71845
+ function startOpenVpnHistorySampler(store) {
71846
+ let stopped = false;
71847
+ let timer;
71848
+ const retries = new Map;
71849
+ async function sample() {
71850
+ for (const [device, config] of Object.entries(getConfig().devices)) {
71851
+ if (stopped)
71852
+ return;
71853
+ if (config.disabled || config.mac || getSafeModeManager(device).isActive)
71854
+ continue;
71855
+ if ((retries.get(device)?.at ?? 0) > Date.now())
71856
+ continue;
71857
+ try {
71858
+ const snapshot = await listOpenVpnSessions(createContext(undefined, device));
71859
+ if (stopped)
71860
+ return;
71861
+ store.ingest({
71862
+ ...snapshot,
71863
+ sessions: snapshot.sessions.map((s) => ({
71864
+ ...s,
71865
+ callerId: sourceIpLiteral(s.callerId) ?? s.callerId,
71866
+ sourceGeo: getIpGeo(s.callerId)
71867
+ }))
71868
+ });
71869
+ retries.delete(device);
71870
+ } catch {
71871
+ const delay = Math.min(300000, (retries.get(device)?.delay ?? 15000) * 2);
71872
+ retries.set(device, { at: Date.now() + delay, delay });
71873
+ if (!stopped) {
71874
+ try {
71875
+ store.failure(device);
71876
+ } catch {}
71877
+ }
71878
+ }
71879
+ }
71880
+ if (!stopped) {
71881
+ try {
71882
+ store.enrich(getIpGeo);
71883
+ } catch {}
71884
+ }
71885
+ if (!stopped)
71886
+ timer = setTimeout(() => void sample(), OPENVPN_HISTORY_INTERVAL);
71887
+ }
71888
+ sample();
71889
+ return () => {
71890
+ stopped = true;
71891
+ clearTimeout(timer);
71892
+ };
71893
+ }
71894
+
71653
71895
  // src/observability/ip-intelligence-routes.ts
71654
71896
  async function ipIntelligenceRoutes(req, url) {
71655
71897
  if (url.pathname !== "/api/ip-intelligence")
@@ -71742,9 +71984,9 @@ async function roundTripRoutes(req, url) {
71742
71984
  }
71743
71985
 
71744
71986
  // src/observability/um-report-cache.ts
71745
- import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
71987
+ import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
71746
71988
  import { mkdir, readFile, rename, stat, unlink, writeFile } from "fs/promises";
71747
- import { dirname as dirname18, join as join12 } from "path";
71989
+ import { dirname as dirname19, join as join12 } from "path";
71748
71990
  var MAX_BYTES = 32 * 1024 * 1024;
71749
71991
  var MAX_AGE = 24 * 60 * 60000;
71750
71992
  var sourceSchema = object({
@@ -71804,12 +72046,12 @@ async function loadUmReportCache(path, device, fields) {
71804
72046
  async function saveUmReportCache(path, snapshot) {
71805
72047
  if (!path || Object.values(snapshot.sources).some((source) => source.error))
71806
72048
  return false;
71807
- const temp = `${path}.${randomUUID12()}.tmp`;
72049
+ const temp = `${path}.${randomUUID13()}.tmp`;
71808
72050
  try {
71809
72051
  const text = JSON.stringify({ version: 1, snapshot });
71810
72052
  if (Buffer.byteLength(text) > MAX_BYTES)
71811
72053
  return false;
71812
- await mkdir(dirname18(path), { recursive: true, mode: 448 });
72054
+ await mkdir(dirname19(path), { recursive: true, mode: 448 });
71813
72055
  await writeFile(temp, text, { encoding: "utf8", mode: 384, flag: "wx" });
71814
72056
  await rename(temp, path);
71815
72057
  return true;
@@ -71822,8 +72064,32 @@ async function saveUmReportCache(path, snapshot) {
71822
72064
 
71823
72065
  // src/observability/um-last-connections.ts
71824
72066
  var CACHE_MS = 30000;
71825
- var SESSION_QUERY = new Cmd("/user-manager session print").raw("as-value").build();
71826
- var COMMAND = `:if ([/user-manager session print count-only] > 100000) do={ :error "Session limit exceeded" }; :local latest [:toarray ""]; :foreach row in=[${SESSION_QUERY}] do={ :local user ($row->"user"); :local started ($row->"started"); :if ([:len [:tostr $user]] > 0 && [:len [:tostr $started]] > 0) do={ :local previous ($latest->$user); :if ([:typeof $previous] = "nil") do={ :set ($latest->$user) $started } else={ :if ($started > $previous) do={ :set ($latest->$user) $started } } } }; :put [:serialize to=json value=$latest options=json.no-string-conversion]`;
72067
+ var RESCAN_MS = 15 * 60000;
72068
+ var COLLECTION_MS = 180000;
72069
+ var FIELDS3 = { sessions: [".id", "user", "started"] };
72070
+ var SESSION_IDS = ":put [:serialize to=json value=[/user-manager session find] options=json.no-string-conversion]";
72071
+ function sessionRows(rows) {
72072
+ if (!Array.isArray(rows))
72073
+ throw new Error("Invalid session page");
72074
+ const result = new Map;
72075
+ for (const row of rows) {
72076
+ if (!row || typeof row !== "object" || Array.isArray(row))
72077
+ throw new Error("Invalid session row");
72078
+ const { ".id": id, user, started } = row;
72079
+ if (typeof id !== "string" || !/^\*[0-9a-f]+$/i.test(id) || typeof user !== "string" || result.has(id))
72080
+ throw new Error("Invalid session identity");
72081
+ result.set(id, { user, started: umConnectionDate(started) });
72082
+ }
72083
+ return result;
72084
+ }
72085
+ function latestDates(sessions) {
72086
+ const values = new Map;
72087
+ for (const { user, started } of sessions.values()) {
72088
+ if (user && started && started > (values.get(user) ?? ""))
72089
+ values.set(user, started);
72090
+ }
72091
+ return values;
72092
+ }
71827
72093
  function umConnectionDate(value) {
71828
72094
  if (typeof value !== "string")
71829
72095
  return null;
@@ -71855,30 +72121,78 @@ function getUmLastConnections(device) {
71855
72121
  const config = getConfig();
71856
72122
  let entry = cache7.get(device);
71857
72123
  if (!entry || entry.config !== config) {
71858
- entry = { config, values: new Map, retryAt: 0, failed: false };
72124
+ entry = {
72125
+ config,
72126
+ values: new Map,
72127
+ sessions: new Map,
72128
+ scannedAt: 0,
72129
+ restored: false,
72130
+ retryAt: 0,
72131
+ failed: false
72132
+ };
71859
72133
  cache7.set(device, entry);
71860
72134
  }
71861
72135
  const target = entry;
71862
72136
  if (!target.pending && Date.now() >= target.retryAt) {
71863
72137
  target.pending = (async () => {
71864
- const raw = await executeMikrotikCommand(COMMAND, createContext(undefined, device), {
71865
- maxMs: 15000
71866
- });
71867
- if (looksLikeError(raw) || raw.length > 2 * 1024 * 1024)
71868
- throw new Error("Invalid last connection response");
71869
- const result = JSON.parse(raw);
71870
- if (!result || typeof result !== "object" || Array.isArray(result) && result.length)
71871
- throw new Error("Invalid last connection response");
71872
- const values = new Map;
71873
- for (const [user, value] of Object.entries(result)) {
71874
- const date = umConnectionDate(value);
71875
- if (date)
71876
- values.set(user, date);
72138
+ if (!target.restored) {
72139
+ target.restored = true;
72140
+ const snapshot = await loadUmReportCache(umReportCachePath(device), device, FIELDS3);
72141
+ if (getConfig() !== config)
72142
+ return;
72143
+ if (snapshot?.sources.sessions.available) {
72144
+ try {
72145
+ target.sessions = sessionRows(snapshot.sources.sessions.rows);
72146
+ target.values = latestDates(target.sessions);
72147
+ target.collectedAt = snapshot.collectedAt;
72148
+ target.scannedAt = snapshot.collectedAt;
72149
+ } catch {}
72150
+ }
72151
+ }
72152
+ const deadline = Date.now() + COLLECTION_MS;
72153
+ const ctx = createContext(undefined, device);
72154
+ const run = async (command) => {
72155
+ if (getConfig() !== config)
72156
+ throw new Error("Configuration changed");
72157
+ const remaining = deadline - Date.now();
72158
+ if (remaining <= 0)
72159
+ throw new Error("Last connection read deadline exceeded");
72160
+ const raw = await executeMikrotikCommand(command, ctx, {
72161
+ maxMs: Math.min(60000, remaining)
72162
+ });
72163
+ if (looksLikeError(raw) || raw.length > 2 * 1024 * 1024)
72164
+ throw new Error("Invalid last connection response");
72165
+ return raw;
72166
+ };
72167
+ const ids = JSON.parse(await run(SESSION_IDS));
72168
+ if (!Array.isArray(ids) || ids.length > 1e5 || !ids.every((id) => typeof id === "string" && /^\*[0-9a-f]+$/i.test(id)) || new Set(ids).size !== ids.length)
72169
+ throw new Error("Invalid session identities");
72170
+ const full = !target.scannedAt || Date.now() - target.scannedAt >= RESCAN_MS;
72171
+ const sessions = new Map;
72172
+ const missing = [];
72173
+ for (const id of ids) {
72174
+ const known = full ? undefined : target.sessions.get(id);
72175
+ if (known?.started)
72176
+ sessions.set(id, known);
72177
+ else
72178
+ missing.push(id);
72179
+ }
72180
+ for (let offset = 0;offset < missing.length; offset += 2000) {
72181
+ const batch = missing.slice(offset, offset + 2000);
72182
+ const query = new Cmd("/user-manager session print").raw("as-value").set("from", batch.join(",")).build();
72183
+ const page = sessionRows(JSON.parse(await run(`:put [:serialize to=json value=[${query}] options=json.no-string-conversion]`)));
72184
+ if (page.size !== batch.length || !batch.every((id) => page.has(id)))
72185
+ throw new Error("Incomplete session page");
72186
+ for (const [id, session] of page)
72187
+ sessions.set(id, session);
71877
72188
  }
71878
72189
  if (getConfig() !== config)
71879
72190
  return;
71880
- target.values = values;
72191
+ target.sessions = sessions;
72192
+ target.values = latestDates(sessions);
71881
72193
  target.collectedAt = Date.now();
72194
+ if (full)
72195
+ target.scannedAt = target.collectedAt;
71882
72196
  target.failed = false;
71883
72197
  })().catch(() => {
71884
72198
  target.failed = true;
@@ -71898,7 +72212,7 @@ function getUmLastConnections(device) {
71898
72212
  var DAY = 86400000;
71899
72213
  var CACHE_MS2 = 60000;
71900
72214
  var RETRY_MS = 30000;
71901
- var COLLECTION_MS = 180000;
72215
+ var COLLECTION_MS2 = 180000;
71902
72216
  var count = (v) => Math.max(0, Number(v) || 0);
71903
72217
  var size = (v) => Math.max(0, parseSize(v) ?? 0);
71904
72218
  var UM_REPORT_FIELDS = {
@@ -72004,7 +72318,7 @@ var menus = {
72004
72318
  routers: "router",
72005
72319
  groups: "user group"
72006
72320
  };
72007
- async function readSource(ctx, source, deadline = Date.now() + COLLECTION_MS, progress) {
72321
+ async function readSource(ctx, source, deadline = Date.now() + COLLECTION_MS2, progress) {
72008
72322
  let receivedBytes = 0;
72009
72323
  const run = (command) => {
72010
72324
  const remaining = deadline - Date.now();
@@ -72062,7 +72376,7 @@ async function readSource(ctx, source, deadline = Date.now() + COLLECTION_MS, pr
72062
72376
  }
72063
72377
  async function collect(device, progress) {
72064
72378
  const start = Date.now();
72065
- const deadline = start + COLLECTION_MS;
72379
+ const deadline = start + COLLECTION_MS2;
72066
72380
  const config = getConfig();
72067
72381
  const ctx = createContext(undefined, device);
72068
72382
  const sources = Object.fromEntries(Object.keys(UM_REPORT_FIELDS).map((key) => [key, { available: false, rows: [] }]));
@@ -72460,7 +72774,7 @@ function buildUmReport(snapshot, query) {
72460
72774
  // src/observability/config-history.ts
72461
72775
  import {
72462
72776
  existsSync as existsSync5,
72463
- mkdirSync as mkdirSync17,
72777
+ mkdirSync as mkdirSync18,
72464
72778
  readFileSync as readFileSync12,
72465
72779
  readdirSync as readdirSync3,
72466
72780
  rmSync as rmSync3,
@@ -72512,7 +72826,7 @@ function deleteVersion(id) {
72512
72826
  }
72513
72827
  function recordVersion(config, kind, now, label) {
72514
72828
  const dir = historyDir();
72515
- mkdirSync17(dir, { recursive: true });
72829
+ mkdirSync18(dir, { recursive: true });
72516
72830
  let ts = now;
72517
72831
  while (existsSync5(join13(dir, `v${ts}.json`)))
72518
72832
  ts++;
@@ -73099,8 +73413,8 @@ data: ${JSON.stringify(sample)}
73099
73413
  }
73100
73414
 
73101
73415
  // src/observability/store.ts
73102
- import { mkdirSync as mkdirSync18 } from "fs";
73103
- import { dirname as dirname19 } from "path";
73416
+ import { mkdirSync as mkdirSync19 } from "fs";
73417
+ import { dirname as dirname20 } from "path";
73104
73418
  function rowToEvent2(r) {
73105
73419
  return {
73106
73420
  id: r.id,
@@ -73278,7 +73592,7 @@ class SqliteEventStore {
73278
73592
  async function openSqliteStore(path) {
73279
73593
  if (path !== ":memory:") {
73280
73594
  try {
73281
- mkdirSync18(dirname19(path), { recursive: true });
73595
+ mkdirSync19(dirname20(path), { recursive: true });
73282
73596
  } catch {}
73283
73597
  }
73284
73598
  const { Database } = await import("bun:sqlite");
@@ -73287,8 +73601,8 @@ async function openSqliteStore(path) {
73287
73601
  }
73288
73602
 
73289
73603
  // src/observability/capsman-store.ts
73290
- import { mkdirSync as mkdirSync19 } from "fs";
73291
- import { dirname as dirname20 } from "path";
73604
+ import { mkdirSync as mkdirSync20 } from "fs";
73605
+ import { dirname as dirname21 } from "path";
73292
73606
  function summariseRadioSamples(rows) {
73293
73607
  const byRadio = new Map;
73294
73608
  for (const r of rows) {
@@ -73378,7 +73692,7 @@ class SqliteCapsmanStore {
73378
73692
  async function openCapsmanStore(path) {
73379
73693
  if (path !== ":memory:") {
73380
73694
  try {
73381
- mkdirSync19(dirname20(path), { recursive: true });
73695
+ mkdirSync20(dirname21(path), { recursive: true });
73382
73696
  } catch {}
73383
73697
  }
73384
73698
  const { Database } = await import("bun:sqlite");
@@ -73457,8 +73771,8 @@ function stopCapsmanSampler() {
73457
73771
  }
73458
73772
 
73459
73773
  // src/observability/usage-store.ts
73460
- import { mkdirSync as mkdirSync20 } from "fs";
73461
- import { dirname as dirname21 } from "path";
73774
+ import { mkdirSync as mkdirSync21 } from "fs";
73775
+ import { dirname as dirname22 } from "path";
73462
73776
  function dayOf(ts) {
73463
73777
  return new Date(ts).toISOString().slice(0, 10);
73464
73778
  }
@@ -73595,7 +73909,7 @@ class SqliteUsageStore {
73595
73909
  async function openUsageStore(path) {
73596
73910
  if (path !== ":memory:") {
73597
73911
  try {
73598
- mkdirSync20(dirname21(path), { recursive: true });
73912
+ mkdirSync21(dirname22(path), { recursive: true });
73599
73913
  } catch {}
73600
73914
  }
73601
73915
  const { Database } = await import("bun:sqlite");
@@ -74442,8 +74756,8 @@ async function rolloutRoutes(req, url) {
74442
74756
  }
74443
74757
 
74444
74758
  // src/policy/results.ts
74445
- import { mkdirSync as mkdirSync21 } from "fs";
74446
- import { dirname as dirname22 } from "path";
74759
+ import { mkdirSync as mkdirSync22 } from "fs";
74760
+ import { dirname as dirname23 } from "path";
74447
74761
  var SCHEMA_STATEMENTS9 = [
74448
74762
  `CREATE TABLE IF NOT EXISTS policy_results (
74449
74763
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -74503,7 +74817,7 @@ class SqlitePolicyResultStore {
74503
74817
  async function openPolicyResultStore(path) {
74504
74818
  if (path !== ":memory:") {
74505
74819
  try {
74506
- mkdirSync21(dirname22(path), { recursive: true });
74820
+ mkdirSync22(dirname23(path), { recursive: true });
74507
74821
  } catch {}
74508
74822
  }
74509
74823
  const { Database } = await import("bun:sqlite");
@@ -76616,14 +76930,22 @@ async function runDashboard(cfg, transportLabel) {
76616
76930
  });
76617
76931
  startHealthChecks(30000);
76618
76932
  startGeoLookups();
76933
+ let openVpnHistory;
76934
+ let stopOpenVpnHistory;
76935
+ try {
76936
+ openVpnHistory = await openOpenVpnHistory(join16(dirname24(cfg.dbPath), "openvpn-history.db"));
76937
+ stopOpenVpnHistory = startOpenVpnHistorySampler(openVpnHistory);
76938
+ } catch (e) {
76939
+ logger.warn(`[${SERVER_TAG3}] OpenVPN history disabled: ${String(e)}`);
76940
+ }
76619
76941
  try {
76620
- usageStore = await openUsageStore(join16(dirname23(cfg.dbPath), "usage.db"));
76942
+ usageStore = await openUsageStore(join16(dirname24(cfg.dbPath), "usage.db"));
76621
76943
  startUsageSampler(usageStore);
76622
76944
  } catch (e) {
76623
76945
  logger.warn(`[${SERVER_TAG3}] usage history disabled: ${String(e)}`);
76624
76946
  }
76625
76947
  try {
76626
- capsmanStore = await openCapsmanStore(join16(dirname23(cfg.dbPath), "capsman.db"));
76948
+ capsmanStore = await openCapsmanStore(join16(dirname24(cfg.dbPath), "capsman.db"));
76627
76949
  startCapsmanSampler(capsmanStore);
76628
76950
  } catch (e) {
76629
76951
  logger.warn(`[${SERVER_TAG3}] capsman trends disabled: ${String(e)}`);
@@ -76694,7 +77016,7 @@ async function runDashboard(cfg, transportLabel) {
76694
77016
  const operationsResp = await operationsRoutes(req, url);
76695
77017
  if (operationsResp)
76696
77018
  return operationsResp;
76697
- const openVpnResp = await openVpnRoutes(req, url);
77019
+ const openVpnResp = await openVpnRoutes(req, url, openVpnHistory);
76698
77020
  if (openVpnResp)
76699
77021
  return openVpnResp;
76700
77022
  const ipNetworkResp = ipGeoRoute(req, url);
@@ -77042,6 +77364,8 @@ async function runDashboard(cfg, transportLabel) {
77042
77364
  server,
77043
77365
  store,
77044
77366
  stop() {
77367
+ stopOpenVpnHistory?.();
77368
+ openVpnHistory?.close();
77045
77369
  stopHealthChecks();
77046
77370
  stopGeoLookups();
77047
77371
  stopUsageSampler();
@@ -77058,7 +77382,7 @@ async function runDashboard(cfg, transportLabel) {
77058
77382
  }
77059
77383
 
77060
77384
  // src/transport/http.ts
77061
- import { randomUUID as randomUUID13 } from "crypto";
77385
+ import { randomUUID as randomUUID14 } from "crypto";
77062
77386
  var {serve: serve2 } = globalThis.Bun;
77063
77387
 
77064
77388
  // node_modules/content-type/index.js
@@ -86583,7 +86907,7 @@ async function runHttp(mcp) {
86583
86907
  if (existing)
86584
86908
  return existing;
86585
86909
  const transport = new WebStandardStreamableHTTPServerTransport({
86586
- sessionIdGenerator: () => randomUUID13(),
86910
+ sessionIdGenerator: () => randomUUID14(),
86587
86911
  enableJsonResponse: true,
86588
86912
  ...security,
86589
86913
  onsessioninitialized: (id) => {