@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/cli.js +1389 -445
- package/dist/index.d.ts +106 -101
- package/dist/index.js +1 -1
- package/dist/shared/{cli-4xzq2n6j.js → cli-4aqtcr9k.js} +1 -1
- package/dist/shared/{cli-1vn2bbpy.js → cli-4n039739.js} +65 -22
- package/dist/shared/{cli-w6km895r.js → cli-57nggfz3.js} +1 -1
- package/dist/shared/{cli-rcx7e9h4.js → cli-5hgbedxa.js} +4 -2
- package/dist/shared/{cli-r1ng5cjy.js → cli-9x2ne7hp.js} +1 -1
- package/dist/shared/cli-b7rbwm6j.js +109 -0
- package/dist/shared/{library-1nhmbsv0.js → library-1sy0ph9r.js} +1 -1
- package/dist/shared/{library-1swafsvq.js → library-28w0j1ny.js} +1 -1
- package/dist/shared/{library-2wd7mt3g.js → library-7qr2sc9x.js} +62 -19
- package/dist/shared/{library-0qn06vwr.js → library-nt9fygza.js} +1 -1
- package/dist/shared/{library-jpmbkkz7.js → library-twpgma2r.js} +1 -1
- package/dist/ui/observability.html +293 -90
- package/package.json +5 -1
- package/schemas/config.schema.json +16 -2
- package/schemas/devtools-manifest.json +1 -1
- package/schemas/tool-catalog.json +1 -1
- package/scripts/service.ts +240 -31
package/dist/cli.js
CHANGED
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
ToolFilterSchema2,
|
|
33
33
|
AccessConfigSchema2,
|
|
34
34
|
MikrotikConfigSchema2,
|
|
35
|
+
parseFlags2,
|
|
35
36
|
getConfigSource2,
|
|
36
37
|
loadConfig2,
|
|
37
38
|
onConfigChanged,
|
|
@@ -51,7 +52,10 @@ import {
|
|
|
51
52
|
DeviceConnectionError,
|
|
52
53
|
logger,
|
|
53
54
|
deviceEndpoints,
|
|
55
|
+
MikroTikSSHClient,
|
|
54
56
|
isMacTelnetDevice,
|
|
57
|
+
sshOptionsOf,
|
|
58
|
+
resolveJump,
|
|
55
59
|
createDeviceClient,
|
|
56
60
|
describeTransport,
|
|
57
61
|
isPoolEnabled,
|
|
@@ -64,11 +68,13 @@ import {
|
|
|
64
68
|
parseSize,
|
|
65
69
|
parseRecords,
|
|
66
70
|
parseLeadingNumber,
|
|
71
|
+
bypassesSafeMode,
|
|
67
72
|
executeMikrotikCommand,
|
|
68
73
|
executeMikrotikJson,
|
|
69
74
|
riskOf,
|
|
70
75
|
redact,
|
|
71
76
|
createContext,
|
|
77
|
+
quoteValue,
|
|
72
78
|
Cmd,
|
|
73
79
|
isEmpty,
|
|
74
80
|
flattenLiveOutput,
|
|
@@ -120,6 +126,7 @@ import {
|
|
|
120
126
|
getEventStore,
|
|
121
127
|
subscribe,
|
|
122
128
|
subscriberCount,
|
|
129
|
+
recordToolCall,
|
|
123
130
|
registerTools,
|
|
124
131
|
bandwidthServerTools,
|
|
125
132
|
normalizeExport2,
|
|
@@ -197,11 +204,13 @@ import {
|
|
|
197
204
|
noteDriftResult,
|
|
198
205
|
analyzeDrift,
|
|
199
206
|
attributeChanges,
|
|
207
|
+
configSnapshotTools,
|
|
200
208
|
CONTAINER_GUIDE_URI,
|
|
201
209
|
getRouterosContainerGuide,
|
|
202
210
|
CONTAINER_INSTRUCTIONS,
|
|
203
211
|
containerPromptGuidance,
|
|
204
212
|
applyWritesSafely,
|
|
213
|
+
toolGatewayTools,
|
|
205
214
|
evaluatePolicies,
|
|
206
215
|
validatePolicyText,
|
|
207
216
|
renderReport,
|
|
@@ -351,7 +360,7 @@ import {
|
|
|
351
360
|
allToolModules2,
|
|
352
361
|
ALWAYS_ON_MODULES2,
|
|
353
362
|
selectToolModules2
|
|
354
|
-
} from "./shared/cli-
|
|
363
|
+
} from "./shared/cli-4n039739.js";
|
|
355
364
|
|
|
356
365
|
// node_modules/ajv/dist/compile/codegen/code.js
|
|
357
366
|
var require_code = __commonJS(function(exports) {
|
|
@@ -7311,9 +7320,9 @@ import { existsSync as existsSync2 } from "fs";
|
|
|
7311
7320
|
|
|
7312
7321
|
// src/observability/dashboard.ts
|
|
7313
7322
|
import { spawn } from "child_process";
|
|
7314
|
-
import { readFileSync as
|
|
7323
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
7315
7324
|
import { homedir as homedir5, networkInterfaces as networkInterfaces2 } from "os";
|
|
7316
|
-
import { dirname as
|
|
7325
|
+
import { dirname as dirname11, join as join10 } from "path";
|
|
7317
7326
|
var {serve } = globalThis.Bun;
|
|
7318
7327
|
|
|
7319
7328
|
// src/observability/modules.ts
|
|
@@ -7644,6 +7653,847 @@ async function homeRoutes(req, url) {
|
|
|
7644
7653
|
}
|
|
7645
7654
|
}
|
|
7646
7655
|
|
|
7656
|
+
// src/observability/terminal-shell.ts
|
|
7657
|
+
import {
|
|
7658
|
+
createWriteStream,
|
|
7659
|
+
mkdirSync as mkdirSync2,
|
|
7660
|
+
readdirSync,
|
|
7661
|
+
readFileSync,
|
|
7662
|
+
statSync,
|
|
7663
|
+
unlinkSync
|
|
7664
|
+
} from "fs";
|
|
7665
|
+
import { join as join4 } from "path";
|
|
7666
|
+
var sessions = new Map;
|
|
7667
|
+
var recordingDir;
|
|
7668
|
+
var MAX_RECORDING_BYTES = 5 * 1024 * 1024;
|
|
7669
|
+
var MAX_RECORDINGS = 200;
|
|
7670
|
+
var RECORDING_ID = /^[\w.-]+\.cast$/;
|
|
7671
|
+
function setRecordingDir(dir) {
|
|
7672
|
+
recordingDir = dir;
|
|
7673
|
+
}
|
|
7674
|
+
function listRecordings() {
|
|
7675
|
+
if (!recordingDir)
|
|
7676
|
+
return [];
|
|
7677
|
+
let names;
|
|
7678
|
+
try {
|
|
7679
|
+
names = readdirSync(recordingDir).filter((name) => RECORDING_ID.test(name));
|
|
7680
|
+
} catch {
|
|
7681
|
+
return [];
|
|
7682
|
+
}
|
|
7683
|
+
const dir = recordingDir;
|
|
7684
|
+
return names.map((id) => {
|
|
7685
|
+
const [stamp = "0", ...rest] = id.replace(/\.cast$/, "").split("_");
|
|
7686
|
+
return {
|
|
7687
|
+
id,
|
|
7688
|
+
device: rest.slice(0, -1).join("_"),
|
|
7689
|
+
started: Number(stamp),
|
|
7690
|
+
bytes: statSync(join4(dir, id)).size
|
|
7691
|
+
};
|
|
7692
|
+
}).sort((a, b) => b.started - a.started);
|
|
7693
|
+
}
|
|
7694
|
+
function readRecording(id) {
|
|
7695
|
+
if (!recordingDir || !RECORDING_ID.test(id))
|
|
7696
|
+
return;
|
|
7697
|
+
try {
|
|
7698
|
+
return readFileSync(join4(recordingDir, id), "utf8");
|
|
7699
|
+
} catch {
|
|
7700
|
+
return;
|
|
7701
|
+
}
|
|
7702
|
+
}
|
|
7703
|
+
function deleteRecording(id) {
|
|
7704
|
+
if (!recordingDir || !RECORDING_ID.test(id))
|
|
7705
|
+
return false;
|
|
7706
|
+
try {
|
|
7707
|
+
unlinkSync(join4(recordingDir, id));
|
|
7708
|
+
return true;
|
|
7709
|
+
} catch {
|
|
7710
|
+
return false;
|
|
7711
|
+
}
|
|
7712
|
+
}
|
|
7713
|
+
function startRecording(device, cols, rows) {
|
|
7714
|
+
if (!recordingDir)
|
|
7715
|
+
return;
|
|
7716
|
+
let file;
|
|
7717
|
+
const started = Date.now();
|
|
7718
|
+
try {
|
|
7719
|
+
mkdirSync2(recordingDir, { recursive: true });
|
|
7720
|
+
for (const old of listRecordings().slice(MAX_RECORDINGS - 1))
|
|
7721
|
+
deleteRecording(old.id);
|
|
7722
|
+
const safe = device.replace(/[^\w.-]+/g, "-");
|
|
7723
|
+
file = createWriteStream(join4(recordingDir, `${started}_${safe}_${crypto.randomUUID().slice(0, 8)}.cast`));
|
|
7724
|
+
} catch {
|
|
7725
|
+
return;
|
|
7726
|
+
}
|
|
7727
|
+
file.on("error", () => {});
|
|
7728
|
+
file.write(`${JSON.stringify({ version: 2, width: cols, height: rows, timestamp: Math.floor(started / 1000), title: device })}
|
|
7729
|
+
`);
|
|
7730
|
+
const decoder = new TextDecoder("utf-8");
|
|
7731
|
+
let bytes = 0;
|
|
7732
|
+
return {
|
|
7733
|
+
write(data) {
|
|
7734
|
+
if (bytes > MAX_RECORDING_BYTES)
|
|
7735
|
+
return;
|
|
7736
|
+
bytes += data.length;
|
|
7737
|
+
const text = decoder.decode(data, { stream: true });
|
|
7738
|
+
if (text)
|
|
7739
|
+
file.write(`${JSON.stringify([(Date.now() - started) / 1000, "o", text])}
|
|
7740
|
+
`);
|
|
7741
|
+
},
|
|
7742
|
+
end: () => file.end()
|
|
7743
|
+
};
|
|
7744
|
+
}
|
|
7745
|
+
var MAX_SHELLS = 12;
|
|
7746
|
+
var IDLE_MS = 30 * 60000;
|
|
7747
|
+
var clampSize = (value, fallback, max) => {
|
|
7748
|
+
const n = Math.floor(Number(value));
|
|
7749
|
+
return Number.isFinite(n) && n >= 2 ? Math.min(n, max) : fallback;
|
|
7750
|
+
};
|
|
7751
|
+
async function openShell(device, size, signal) {
|
|
7752
|
+
const fail = (status, error) => Response.json({ error }, { status });
|
|
7753
|
+
if (sessions.size >= MAX_SHELLS)
|
|
7754
|
+
return fail(429, `Too many interactive shells are open (${MAX_SHELLS}). Close one first.`);
|
|
7755
|
+
const dc = getDevice(device);
|
|
7756
|
+
if (isMacTelnetDevice(dc))
|
|
7757
|
+
return fail(400, "The interactive shell needs SSH. This router is reached over MAC-Telnet.");
|
|
7758
|
+
const client = new MikroTikSSHClient({
|
|
7759
|
+
...sshOptionsOf(dc),
|
|
7760
|
+
jump: resolveJump(dc),
|
|
7761
|
+
keepAliveInterval: 15000,
|
|
7762
|
+
keepAliveCountMax: 3
|
|
7763
|
+
});
|
|
7764
|
+
if (!await client.connect())
|
|
7765
|
+
return fail(502, `Could not connect to ${device}: ${client.lastError ?? "unknown error"}`);
|
|
7766
|
+
let channel;
|
|
7767
|
+
try {
|
|
7768
|
+
channel = await client.shell({
|
|
7769
|
+
term: "xterm-256color",
|
|
7770
|
+
cols: clampSize(size.cols, 120, 500),
|
|
7771
|
+
rows: clampSize(size.rows, 30, 200)
|
|
7772
|
+
});
|
|
7773
|
+
} catch (e) {
|
|
7774
|
+
client.disconnect();
|
|
7775
|
+
return fail(502, `Could not open a shell on ${device}: ${e instanceof Error ? e.message : e}`);
|
|
7776
|
+
}
|
|
7777
|
+
const id = crypto.randomUUID();
|
|
7778
|
+
const opened = Date.now();
|
|
7779
|
+
const recording = startRecording(device, clampSize(size.cols, 120, 500), clampSize(size.rows, 30, 200));
|
|
7780
|
+
let controller;
|
|
7781
|
+
let closed = false;
|
|
7782
|
+
const close = (reason) => {
|
|
7783
|
+
if (closed)
|
|
7784
|
+
return;
|
|
7785
|
+
closed = true;
|
|
7786
|
+
const session = sessions.get(id);
|
|
7787
|
+
if (session?.idle)
|
|
7788
|
+
clearTimeout(session.idle);
|
|
7789
|
+
sessions.delete(id);
|
|
7790
|
+
try {
|
|
7791
|
+
channel.close();
|
|
7792
|
+
} catch {}
|
|
7793
|
+
client.disconnect();
|
|
7794
|
+
recording?.end();
|
|
7795
|
+
try {
|
|
7796
|
+
controller?.close();
|
|
7797
|
+
} catch {}
|
|
7798
|
+
logger.info(`Terminal shell ${id} on '${device}' closed (${reason}); ${sessions.size} open`);
|
|
7799
|
+
recordToolCall({
|
|
7800
|
+
tool: "dashboard_terminal",
|
|
7801
|
+
title: "Dashboard Terminal",
|
|
7802
|
+
risk: "WRITE",
|
|
7803
|
+
device,
|
|
7804
|
+
deviceTransport: "ssh",
|
|
7805
|
+
ts: opened,
|
|
7806
|
+
durationMs: Date.now() - opened,
|
|
7807
|
+
isError: false,
|
|
7808
|
+
args: { shell: "interactive session" },
|
|
7809
|
+
output: `Interactive shell closed (${reason}). ${recording ? "The router's output was recorded; typed keys are not." : "This session was not recorded."}`,
|
|
7810
|
+
hasStructured: false
|
|
7811
|
+
});
|
|
7812
|
+
};
|
|
7813
|
+
const touch = () => {
|
|
7814
|
+
const session = sessions.get(id);
|
|
7815
|
+
if (!session)
|
|
7816
|
+
return;
|
|
7817
|
+
if (session.idle)
|
|
7818
|
+
clearTimeout(session.idle);
|
|
7819
|
+
session.idle = setTimeout(() => close("idle for 30 minutes"), IDLE_MS);
|
|
7820
|
+
};
|
|
7821
|
+
sessions.set(id, { device, client, channel, opened, idle: undefined, close });
|
|
7822
|
+
touch();
|
|
7823
|
+
logger.info(`Terminal shell ${id} on '${device}' opened; ${sessions.size} open`);
|
|
7824
|
+
const body = new ReadableStream({
|
|
7825
|
+
start(streamController) {
|
|
7826
|
+
controller = streamController;
|
|
7827
|
+
const push = (data) => {
|
|
7828
|
+
if (closed)
|
|
7829
|
+
return;
|
|
7830
|
+
recording?.write(data);
|
|
7831
|
+
try {
|
|
7832
|
+
streamController.enqueue(new Uint8Array(data));
|
|
7833
|
+
} catch {
|
|
7834
|
+
close("viewer left");
|
|
7835
|
+
}
|
|
7836
|
+
};
|
|
7837
|
+
channel.on("data", push);
|
|
7838
|
+
channel.stderr.on("data", push);
|
|
7839
|
+
channel.on("close", () => close("router closed the session"));
|
|
7840
|
+
channel.on("error", () => close("channel error"));
|
|
7841
|
+
},
|
|
7842
|
+
cancel() {
|
|
7843
|
+
close("viewer left");
|
|
7844
|
+
}
|
|
7845
|
+
});
|
|
7846
|
+
signal.addEventListener("abort", () => close("viewer left"), { once: true });
|
|
7847
|
+
return new Response(body, {
|
|
7848
|
+
headers: {
|
|
7849
|
+
"content-type": "application/octet-stream",
|
|
7850
|
+
"cache-control": "no-store",
|
|
7851
|
+
"x-shell-id": id,
|
|
7852
|
+
"x-shell-host": client.connectedHost ?? ""
|
|
7853
|
+
}
|
|
7854
|
+
});
|
|
7855
|
+
}
|
|
7856
|
+
function shellInput(id, data) {
|
|
7857
|
+
const session = sessions.get(id);
|
|
7858
|
+
if (!session)
|
|
7859
|
+
return false;
|
|
7860
|
+
session.channel.write(data);
|
|
7861
|
+
if (session.idle)
|
|
7862
|
+
clearTimeout(session.idle);
|
|
7863
|
+
session.idle = setTimeout(() => session.close("idle for 30 minutes"), IDLE_MS);
|
|
7864
|
+
return true;
|
|
7865
|
+
}
|
|
7866
|
+
function shellResize(id, cols, rows) {
|
|
7867
|
+
const session = sessions.get(id);
|
|
7868
|
+
if (!session)
|
|
7869
|
+
return false;
|
|
7870
|
+
session.channel.setWindow(clampSize(rows, 30, 200), clampSize(cols, 120, 500), 0, 0);
|
|
7871
|
+
return true;
|
|
7872
|
+
}
|
|
7873
|
+
function closeShell(id) {
|
|
7874
|
+
const session = sessions.get(id);
|
|
7875
|
+
session?.close("closed by the viewer");
|
|
7876
|
+
return Boolean(session);
|
|
7877
|
+
}
|
|
7878
|
+
function closeAllShells() {
|
|
7879
|
+
for (const session of Array.from(sessions.values()))
|
|
7880
|
+
session.close("dashboard stopped");
|
|
7881
|
+
}
|
|
7882
|
+
|
|
7883
|
+
// src/observability/terminal-routes.ts
|
|
7884
|
+
var LOOPBACK = new Set(["127.0.0.1", "localhost", "::1"]);
|
|
7885
|
+
function terminalAccess(cfg) {
|
|
7886
|
+
if (cfg.terminal === false)
|
|
7887
|
+
return "The terminal is turned off (dashboard.terminal = false).";
|
|
7888
|
+
if (cfg.token || LOOPBACK.has(cfg.host))
|
|
7889
|
+
return null;
|
|
7890
|
+
return "The terminal runs any command on your routers, so it needs a protected dashboard. " + "Set a dashboard token (--dashboard-token) or bind the dashboard to 127.0.0.1 (--dashboard-host).";
|
|
7891
|
+
}
|
|
7892
|
+
var DEFAULT_MAX_MS = 30000;
|
|
7893
|
+
var DESTRUCTIVE_RE = /(?:^|[\s/;[{])(?:remove|reset-configuration|reset|reboot|shutdown|format|format-drive|downgrade|uninstall|wipe)(?:$|[\s;\]}])/;
|
|
7894
|
+
var DIAGNOSTIC_RE = /^\/?(?:ping|tool[\s/]+(?:ping|traceroute|trace)|console[\s/]+inspect)(?:\s|$)|^:put\s+[^[\]]*$/;
|
|
7895
|
+
function classifyCommand(command) {
|
|
7896
|
+
const text = command.trim();
|
|
7897
|
+
if (bypassesSafeMode(text.startsWith("/") ? text : `/${text}`, {}) || DIAGNOSTIC_RE.test(text))
|
|
7898
|
+
return "READ";
|
|
7899
|
+
return DESTRUCTIVE_RE.test(text) ? "DESTRUCTIVE" : "WRITE";
|
|
7900
|
+
}
|
|
7901
|
+
function parseHighlight(output) {
|
|
7902
|
+
const found = output.match(/highlight=([a-z0-9;-]*?);type=/i);
|
|
7903
|
+
return found?.[1] ? found[1].split(";") : [];
|
|
7904
|
+
}
|
|
7905
|
+
function parseCompletions(output) {
|
|
7906
|
+
const rows = [];
|
|
7907
|
+
for (const line of output.split(/\r?\n/)) {
|
|
7908
|
+
const cells = line.match(/^\s*completion\s+(\S*)\s+([a-z-]+)\s+(\d+)\s+(-?\d+)\s+(yes|no)/);
|
|
7909
|
+
if (!cells || !cells[1] || cells[5] !== "yes")
|
|
7910
|
+
continue;
|
|
7911
|
+
rows.push({
|
|
7912
|
+
completion: cells[1],
|
|
7913
|
+
style: cells[2] ?? "none",
|
|
7914
|
+
offset: Number(cells[3]),
|
|
7915
|
+
preference: Number(cells[4])
|
|
7916
|
+
});
|
|
7917
|
+
}
|
|
7918
|
+
return rows.sort((x, y) => y.preference - x.preference).map(({ completion, style, offset }) => ({ completion, style, offset }));
|
|
7919
|
+
}
|
|
7920
|
+
function parseSyntaxHelp(output) {
|
|
7921
|
+
const items = [];
|
|
7922
|
+
for (const record of output.trim().split(/;type=syntax(?:;|\s*$)/)) {
|
|
7923
|
+
const cells = record.match(/nested=(\d+);nonorm=\w+;symbol=(.*?);symbol-type=([\w-]+);text=(.*)$/s);
|
|
7924
|
+
if (!cells)
|
|
7925
|
+
continue;
|
|
7926
|
+
const symbol = cells[2] ?? "";
|
|
7927
|
+
const text = (cells[4] ?? "").trim();
|
|
7928
|
+
if (!symbol && !text)
|
|
7929
|
+
continue;
|
|
7930
|
+
items.push({ symbol, text, nested: Number(cells[1]) });
|
|
7931
|
+
}
|
|
7932
|
+
return items;
|
|
7933
|
+
}
|
|
7934
|
+
function rankCommands(question, commands, limit = 8) {
|
|
7935
|
+
const words = question.toLowerCase().split(/[^a-z0-9.-]+/).filter((word) => word.length > 1);
|
|
7936
|
+
if (!words.length)
|
|
7937
|
+
return [];
|
|
7938
|
+
const seen = new Set;
|
|
7939
|
+
return commands.filter((command) => !seen.has(command) && seen.add(command)).map((command) => {
|
|
7940
|
+
const text = command.toLowerCase();
|
|
7941
|
+
return { command, score: words.filter((word) => text.includes(word)).length };
|
|
7942
|
+
}).filter((item) => item.score > 0).sort((a, b) => b.score - a.score).slice(0, limit).map((item) => item.command);
|
|
7943
|
+
}
|
|
7944
|
+
function parseFoundTools(answer) {
|
|
7945
|
+
return Array.from(answer.matchAll(/^\d+\. (\S+)\s+\[[^\]]*\]\n\s+(.+?) \u2014 /gm), (match) => ({
|
|
7946
|
+
name: match[1] ?? "",
|
|
7947
|
+
title: match[2] ?? ""
|
|
7948
|
+
}));
|
|
7949
|
+
}
|
|
7950
|
+
var shares = new Map;
|
|
7951
|
+
var SHARE_TTL_MS = 24 * 3600000;
|
|
7952
|
+
var MAX_SHARES = 20;
|
|
7953
|
+
var MIN_SCHEDULE_MS = 60000;
|
|
7954
|
+
var MAX_SCHEDULES = 50;
|
|
7955
|
+
var schedulerTimer;
|
|
7956
|
+
function stopTerminalScheduler() {
|
|
7957
|
+
if (schedulerTimer)
|
|
7958
|
+
clearInterval(schedulerTimer);
|
|
7959
|
+
schedulerTimer = undefined;
|
|
7960
|
+
}
|
|
7961
|
+
async function runDueSchedules(store, now = Date.now()) {
|
|
7962
|
+
let ran = 0;
|
|
7963
|
+
for (const item of store.listSchedules()) {
|
|
7964
|
+
if (item.nextRun === null || item.nextRun > now)
|
|
7965
|
+
continue;
|
|
7966
|
+
ran++;
|
|
7967
|
+
const ctx = createContext(undefined, item.device);
|
|
7968
|
+
let output = "";
|
|
7969
|
+
let error;
|
|
7970
|
+
try {
|
|
7971
|
+
if (classifyCommand(item.command) !== "READ")
|
|
7972
|
+
throw new Error("Only reads may be scheduled.");
|
|
7973
|
+
output = await executeMikrotikCommand(item.command, ctx, { maxMs: DEFAULT_MAX_MS });
|
|
7974
|
+
if (looksLikeError(output))
|
|
7975
|
+
error = "RouterOS rejected the command.";
|
|
7976
|
+
} catch (e) {
|
|
7977
|
+
error = e instanceof Error ? e.message : String(e);
|
|
7978
|
+
}
|
|
7979
|
+
const ms = Date.now() - now;
|
|
7980
|
+
store.addHistory({
|
|
7981
|
+
ts: now,
|
|
7982
|
+
device: item.device,
|
|
7983
|
+
command: item.command,
|
|
7984
|
+
output,
|
|
7985
|
+
ok: !error,
|
|
7986
|
+
ms,
|
|
7987
|
+
error
|
|
7988
|
+
});
|
|
7989
|
+
recordToolCall({
|
|
7990
|
+
tool: "dashboard_terminal",
|
|
7991
|
+
title: "Dashboard Terminal",
|
|
7992
|
+
risk: "READ",
|
|
7993
|
+
device: item.device,
|
|
7994
|
+
deviceTransport: ctx.transport,
|
|
7995
|
+
ts: now,
|
|
7996
|
+
durationMs: ms,
|
|
7997
|
+
isError: Boolean(error),
|
|
7998
|
+
error,
|
|
7999
|
+
args: { command: item.command, scheduled: true },
|
|
8000
|
+
output,
|
|
8001
|
+
hasStructured: false
|
|
8002
|
+
});
|
|
8003
|
+
store.markScheduleRun(item.id, {
|
|
8004
|
+
at: now,
|
|
8005
|
+
ok: !error,
|
|
8006
|
+
note: error ?? `${output.split(/\r?\n/).filter(Boolean).length} lines`,
|
|
8007
|
+
next: item.everyMs > 0 ? now + item.everyMs : null
|
|
8008
|
+
});
|
|
8009
|
+
}
|
|
8010
|
+
return ran;
|
|
8011
|
+
}
|
|
8012
|
+
var noStore = { "cache-control": "no-store" };
|
|
8013
|
+
var json = (body, status = 200) => Response.json(body, { status, headers: noStore });
|
|
8014
|
+
var MAX_MAX_MS = 600000;
|
|
8015
|
+
async function snapshotTool(name, device, input) {
|
|
8016
|
+
const tool = configSnapshotTools.find((candidate) => candidate.name === name);
|
|
8017
|
+
if (!tool)
|
|
8018
|
+
throw new Error(`Snapshot tool ${name} is not available.`);
|
|
8019
|
+
const result = await tool.handler(object(tool.inputSchema).parse(input), createContext(undefined, device));
|
|
8020
|
+
return typeof result === "string" ? result : JSON.stringify(result);
|
|
8021
|
+
}
|
|
8022
|
+
function createTerminalRoutes(options) {
|
|
8023
|
+
if (options.denied === null && !schedulerTimer) {
|
|
8024
|
+
schedulerTimer = setInterval(() => {
|
|
8025
|
+
options.store().then((store) => runDueSchedules(store)).catch((e) => logger.warn(`Terminal schedules did not run: ${e instanceof Error ? e.message : e}`));
|
|
8026
|
+
}, 20000);
|
|
8027
|
+
schedulerTimer.unref?.();
|
|
8028
|
+
}
|
|
8029
|
+
function run(req, device, command, maxMs, snapshot) {
|
|
8030
|
+
const risk = classifyCommand(command);
|
|
8031
|
+
const encoder = new TextEncoder;
|
|
8032
|
+
const started = Date.now();
|
|
8033
|
+
const abort = new AbortController;
|
|
8034
|
+
req.signal.addEventListener("abort", () => abort.abort(), { once: true });
|
|
8035
|
+
const stream = new ReadableStream({
|
|
8036
|
+
async start(controller) {
|
|
8037
|
+
let open = true;
|
|
8038
|
+
const send = (message) => {
|
|
8039
|
+
if (!open)
|
|
8040
|
+
return;
|
|
8041
|
+
try {
|
|
8042
|
+
controller.enqueue(encoder.encode(`${JSON.stringify(message)}
|
|
8043
|
+
`));
|
|
8044
|
+
} catch {
|
|
8045
|
+
open = false;
|
|
8046
|
+
}
|
|
8047
|
+
};
|
|
8048
|
+
const ctx = createContext(undefined, device);
|
|
8049
|
+
const guarded = snapshot && risk !== "READ";
|
|
8050
|
+
send({ t: "start", ts: started, device, risk, snapshot: guarded });
|
|
8051
|
+
let streamed = false;
|
|
8052
|
+
let output = "";
|
|
8053
|
+
let error;
|
|
8054
|
+
let dispatched = true;
|
|
8055
|
+
let transportFailed = false;
|
|
8056
|
+
let snapshotFailed = false;
|
|
8057
|
+
try {
|
|
8058
|
+
if (guarded) {
|
|
8059
|
+
try {
|
|
8060
|
+
await snapshotTool("capture_config_snapshot", device, {
|
|
8061
|
+
label: `terminal: ${command.slice(0, 80)}`
|
|
8062
|
+
});
|
|
8063
|
+
} catch (e) {
|
|
8064
|
+
snapshotFailed = true;
|
|
8065
|
+
throw new Error(`The command was NOT run: the snapshot before it failed (${e instanceof Error ? e.message : String(e)}).`, { cause: e });
|
|
8066
|
+
}
|
|
8067
|
+
}
|
|
8068
|
+
output = await executeMikrotikCommand(command, ctx, {
|
|
8069
|
+
maxMs,
|
|
8070
|
+
signal: abort.signal,
|
|
8071
|
+
onData: (text) => {
|
|
8072
|
+
streamed = true;
|
|
8073
|
+
send({ t: "out", d: text });
|
|
8074
|
+
}
|
|
8075
|
+
});
|
|
8076
|
+
if (!streamed && output)
|
|
8077
|
+
send({ t: "out", d: output });
|
|
8078
|
+
if (!abort.signal.aborted && looksLikeError(output))
|
|
8079
|
+
error = "RouterOS rejected the command.";
|
|
8080
|
+
} catch (e) {
|
|
8081
|
+
error = e instanceof Error ? e.message : String(e);
|
|
8082
|
+
transportFailed = !snapshotFailed;
|
|
8083
|
+
dispatched = !snapshotFailed && !(e instanceof DeviceConnectionError);
|
|
8084
|
+
}
|
|
8085
|
+
const ms = Date.now() - started;
|
|
8086
|
+
const stopped = abort.signal.aborted;
|
|
8087
|
+
let historyId;
|
|
8088
|
+
try {
|
|
8089
|
+
historyId = (await options.store()).addHistory({
|
|
8090
|
+
ts: started,
|
|
8091
|
+
device,
|
|
8092
|
+
command,
|
|
8093
|
+
output,
|
|
8094
|
+
ok: !error,
|
|
8095
|
+
ms,
|
|
8096
|
+
error
|
|
8097
|
+
});
|
|
8098
|
+
} catch (e) {
|
|
8099
|
+
logger.warn(`Terminal history was not saved: ${e instanceof Error ? e.message : e}`);
|
|
8100
|
+
}
|
|
8101
|
+
recordToolCall({
|
|
8102
|
+
tool: "dashboard_terminal",
|
|
8103
|
+
title: "Dashboard Terminal",
|
|
8104
|
+
risk,
|
|
8105
|
+
device,
|
|
8106
|
+
deviceTransport: ctx.transport,
|
|
8107
|
+
restFallback: ctx.restFallback,
|
|
8108
|
+
ts: started,
|
|
8109
|
+
durationMs: ms,
|
|
8110
|
+
isError: Boolean(error),
|
|
8111
|
+
error,
|
|
8112
|
+
args: { command },
|
|
8113
|
+
output,
|
|
8114
|
+
hasStructured: false
|
|
8115
|
+
});
|
|
8116
|
+
send({
|
|
8117
|
+
t: "end",
|
|
8118
|
+
ok: !error,
|
|
8119
|
+
ms,
|
|
8120
|
+
error,
|
|
8121
|
+
stopped,
|
|
8122
|
+
historyId,
|
|
8123
|
+
snapshot: guarded && dispatched,
|
|
8124
|
+
transport: ctx.transport,
|
|
8125
|
+
retryable: transportFailed && (!dispatched || risk === "READ")
|
|
8126
|
+
});
|
|
8127
|
+
open = false;
|
|
8128
|
+
try {
|
|
8129
|
+
controller.close();
|
|
8130
|
+
} catch {}
|
|
8131
|
+
},
|
|
8132
|
+
cancel() {
|
|
8133
|
+
abort.abort();
|
|
8134
|
+
}
|
|
8135
|
+
});
|
|
8136
|
+
return new Response(stream, {
|
|
8137
|
+
headers: { "content-type": "application/x-ndjson; charset=utf-8", ...noStore }
|
|
8138
|
+
});
|
|
8139
|
+
}
|
|
8140
|
+
return async function terminalRoutes(req, url) {
|
|
8141
|
+
const path = url.pathname;
|
|
8142
|
+
if (!path.startsWith("/api/terminal"))
|
|
8143
|
+
return null;
|
|
8144
|
+
const key = `${req.method} ${path}`;
|
|
8145
|
+
if (key === "GET /api/terminal/state")
|
|
8146
|
+
return json({
|
|
8147
|
+
enabled: options.denied === null,
|
|
8148
|
+
reason: options.denied,
|
|
8149
|
+
readOnly: getConfig().readOnly
|
|
8150
|
+
});
|
|
8151
|
+
if (options.denied !== null)
|
|
8152
|
+
return json({ error: options.denied }, 403);
|
|
8153
|
+
try {
|
|
8154
|
+
if (key === "GET /api/terminal/history") {
|
|
8155
|
+
const store = await options.store();
|
|
8156
|
+
return json({
|
|
8157
|
+
entries: store.listHistory({
|
|
8158
|
+
device: url.searchParams.get("device") || undefined,
|
|
8159
|
+
q: url.searchParams.get("q") || undefined,
|
|
8160
|
+
limit: Number(url.searchParams.get("limit")) || undefined
|
|
8161
|
+
})
|
|
8162
|
+
});
|
|
8163
|
+
}
|
|
8164
|
+
if (key === "GET /api/terminal/recordings")
|
|
8165
|
+
return json({ recordings: listRecordings() });
|
|
8166
|
+
if (key === "GET /api/terminal/recording") {
|
|
8167
|
+
const cast = readRecording(url.searchParams.get("id") ?? "");
|
|
8168
|
+
if (cast === undefined)
|
|
8169
|
+
return json({ error: "No such recording." }, 404);
|
|
8170
|
+
return new Response(cast, {
|
|
8171
|
+
headers: { "content-type": "text/plain; charset=utf-8", ...noStore }
|
|
8172
|
+
});
|
|
8173
|
+
}
|
|
8174
|
+
if (key === "GET /api/terminal/shared") {
|
|
8175
|
+
const share = shares.get(url.searchParams.get("id") ?? "");
|
|
8176
|
+
if (!share || Date.now() - share.since > SHARE_TTL_MS)
|
|
8177
|
+
return json({ error: "This shared view does not exist or has ended." }, 404);
|
|
8178
|
+
const entries = (await options.store()).listHistory({ device: share.device, limit: 300 }).filter((entry) => entry.ts >= share.since).reverse();
|
|
8179
|
+
return json({ device: share.device, since: share.since, entries });
|
|
8180
|
+
}
|
|
8181
|
+
if (key === "GET /api/terminal/schedules")
|
|
8182
|
+
return json({ schedules: (await options.store()).listSchedules() });
|
|
8183
|
+
if (key === "GET /api/terminal/suggest") {
|
|
8184
|
+
const question = url.searchParams.get("q") ?? "";
|
|
8185
|
+
const store = await options.store();
|
|
8186
|
+
const known = [
|
|
8187
|
+
...store.listFavorites().map((favorite) => favorite.command),
|
|
8188
|
+
...store.listHistory({ limit: 1000 }).map((entry) => entry.command)
|
|
8189
|
+
];
|
|
8190
|
+
let tools = [];
|
|
8191
|
+
const finder = toolGatewayTools.find((tool) => tool.name === "find_tools");
|
|
8192
|
+
if (finder && question.trim()) {
|
|
8193
|
+
try {
|
|
8194
|
+
const answer = await finder.handler({ query: question, limit: 6 }, createContext());
|
|
8195
|
+
tools = parseFoundTools(typeof answer === "string" ? answer : "");
|
|
8196
|
+
} catch {}
|
|
8197
|
+
}
|
|
8198
|
+
return json({ commands: rankCommands(question, known), tools });
|
|
8199
|
+
}
|
|
8200
|
+
if (key === "GET /api/terminal/favorites")
|
|
8201
|
+
return json({ favorites: (await options.store()).listFavorites() });
|
|
8202
|
+
if (req.method !== "POST" && req.method !== "DELETE")
|
|
8203
|
+
return json({ error: "Unsupported terminal route" }, 405);
|
|
8204
|
+
const body = JSON.parse(await readOperationBody(req, 65536) || "{}");
|
|
8205
|
+
const text = (name) => typeof body[name] === "string" ? body[name] : "";
|
|
8206
|
+
if (key === "DELETE /api/terminal/history") {
|
|
8207
|
+
const id = typeof body.id === "number" ? body.id : undefined;
|
|
8208
|
+
const store = await options.store();
|
|
8209
|
+
return json({ removed: store.deleteHistory({ id, device: text("device") || undefined }) });
|
|
8210
|
+
}
|
|
8211
|
+
if (key === "POST /api/terminal/favorites") {
|
|
8212
|
+
const command = text("command").trim();
|
|
8213
|
+
if (!command)
|
|
8214
|
+
return json({ error: "A command is required." }, 400);
|
|
8215
|
+
const label = (text("label").trim() || command).slice(0, 120);
|
|
8216
|
+
return json({ favorite: (await options.store()).saveFavorite(command, label) });
|
|
8217
|
+
}
|
|
8218
|
+
if (key === "DELETE /api/terminal/schedules") {
|
|
8219
|
+
if (typeof body.id !== "number")
|
|
8220
|
+
return json({ error: "A schedule id is required." }, 400);
|
|
8221
|
+
return json({ removed: (await options.store()).deleteSchedule(body.id) });
|
|
8222
|
+
}
|
|
8223
|
+
if (key === "POST /api/terminal/schedules") {
|
|
8224
|
+
const command = text("command").trim();
|
|
8225
|
+
if (!command)
|
|
8226
|
+
return json({ error: "A command is required." }, 400);
|
|
8227
|
+
if (classifyCommand(command) !== "READ")
|
|
8228
|
+
return json({
|
|
8229
|
+
error: "Only commands that read (print, export, ping, traceroute) can be scheduled. A change must be run by a person."
|
|
8230
|
+
}, 400);
|
|
8231
|
+
const store = await options.store();
|
|
8232
|
+
if (store.listSchedules().length >= MAX_SCHEDULES)
|
|
8233
|
+
return json({ error: `At most ${MAX_SCHEDULES} schedules are kept.` }, 400);
|
|
8234
|
+
const everyMs = Math.max(0, Math.floor(Number(body.everyMs) || 0));
|
|
8235
|
+
if (everyMs > 0 && everyMs < MIN_SCHEDULE_MS)
|
|
8236
|
+
return json({ error: "The shortest repeat is one minute." }, 400);
|
|
8237
|
+
const at = Number(body.at);
|
|
8238
|
+
const nextRun = Number.isFinite(at) && at > Date.now() ? at : Date.now() + (everyMs || 0);
|
|
8239
|
+
const id = store.addSchedule({
|
|
8240
|
+
device: resolveDeviceName(text("device") || undefined),
|
|
8241
|
+
command,
|
|
8242
|
+
everyMs,
|
|
8243
|
+
nextRun
|
|
8244
|
+
});
|
|
8245
|
+
return json({ id, schedules: store.listSchedules() });
|
|
8246
|
+
}
|
|
8247
|
+
if (key === "DELETE /api/terminal/favorites") {
|
|
8248
|
+
if (typeof body.id !== "number")
|
|
8249
|
+
return json({ error: "A favourite id is required." }, 400);
|
|
8250
|
+
return json({ removed: (await options.store()).deleteFavorite(body.id) });
|
|
8251
|
+
}
|
|
8252
|
+
if (key === "POST /api/terminal/shell/input")
|
|
8253
|
+
return json({ ok: shellInput(text("id"), text("data")) });
|
|
8254
|
+
if (key === "POST /api/terminal/shell/resize")
|
|
8255
|
+
return json({ ok: shellResize(text("id"), body.cols, body.rows) });
|
|
8256
|
+
if (key === "POST /api/terminal/shell/close")
|
|
8257
|
+
return json({ ok: closeShell(text("id")) });
|
|
8258
|
+
const device = resolveDeviceName(text("device") || undefined);
|
|
8259
|
+
if (key === "POST /api/terminal/share") {
|
|
8260
|
+
for (const [id, share] of shares)
|
|
8261
|
+
if (Date.now() - share.since > SHARE_TTL_MS)
|
|
8262
|
+
shares.delete(id);
|
|
8263
|
+
if (shares.size >= MAX_SHARES)
|
|
8264
|
+
return json({ error: `At most ${MAX_SHARES} shared views are open.` }, 400);
|
|
8265
|
+
const id = crypto.randomUUID();
|
|
8266
|
+
shares.set(id, { device, since: Date.now() });
|
|
8267
|
+
return json({ id, device });
|
|
8268
|
+
}
|
|
8269
|
+
if (key === "DELETE /api/terminal/recordings")
|
|
8270
|
+
return json({ ok: deleteRecording(text("id")) });
|
|
8271
|
+
if (key === "POST /api/terminal/unshare")
|
|
8272
|
+
return json({ ok: shares.delete(text("id")) });
|
|
8273
|
+
if (key === "POST /api/terminal/shell/open") {
|
|
8274
|
+
if (getConfig().readOnly)
|
|
8275
|
+
return json({ error: "This server is in read-only mode: the interactive shell is not available." }, 403);
|
|
8276
|
+
return await openShell(device, { cols: body.cols, rows: body.rows }, req.signal);
|
|
8277
|
+
}
|
|
8278
|
+
const quick = (command) => {
|
|
8279
|
+
const ctx = createContext(undefined, device);
|
|
8280
|
+
return { ctx, result: executeMikrotikCommand(command, ctx, { maxMs: 8000 }) };
|
|
8281
|
+
};
|
|
8282
|
+
if (key === "POST /api/terminal/probe") {
|
|
8283
|
+
const started = performance.now();
|
|
8284
|
+
const { ctx, result } = quick(":put [/system identity get name]");
|
|
8285
|
+
try {
|
|
8286
|
+
const out = await result;
|
|
8287
|
+
return json({
|
|
8288
|
+
ok: true,
|
|
8289
|
+
ms: Math.round(performance.now() - started),
|
|
8290
|
+
identity: out.trim().split(/\r?\n/)[0] ?? "",
|
|
8291
|
+
safeMode: getSafeModeManager(device).isActive,
|
|
8292
|
+
transport: ctx.transport
|
|
8293
|
+
});
|
|
8294
|
+
} catch (e) {
|
|
8295
|
+
return json({
|
|
8296
|
+
ok: false,
|
|
8297
|
+
ms: Math.round(performance.now() - started),
|
|
8298
|
+
error: e instanceof Error ? e.message : String(e)
|
|
8299
|
+
});
|
|
8300
|
+
}
|
|
8301
|
+
}
|
|
8302
|
+
if (key === "POST /api/terminal/safe-mode") {
|
|
8303
|
+
if (getConfig().readOnly)
|
|
8304
|
+
return json({ error: "This server is in read-only mode: Safe Mode is not needed." }, 403);
|
|
8305
|
+
const manager = getSafeModeManager(device);
|
|
8306
|
+
const action = text("action");
|
|
8307
|
+
const started = Date.now();
|
|
8308
|
+
let message;
|
|
8309
|
+
let ok = true;
|
|
8310
|
+
if (action === "enable") {
|
|
8311
|
+
message = await manager.enable();
|
|
8312
|
+
ok = !message.startsWith("Error");
|
|
8313
|
+
} else if (action === "commit") {
|
|
8314
|
+
const result = await manager.commit();
|
|
8315
|
+
message = result.message;
|
|
8316
|
+
ok = result.ok;
|
|
8317
|
+
} else if (action === "rollback")
|
|
8318
|
+
message = await manager.rollback();
|
|
8319
|
+
else
|
|
8320
|
+
return json({ error: "action must be enable, commit or rollback." }, 400);
|
|
8321
|
+
recordToolCall({
|
|
8322
|
+
tool: "dashboard_terminal",
|
|
8323
|
+
title: "Dashboard Terminal",
|
|
8324
|
+
risk: "WRITE",
|
|
8325
|
+
device,
|
|
8326
|
+
deviceTransport: "ssh",
|
|
8327
|
+
ts: started,
|
|
8328
|
+
durationMs: Date.now() - started,
|
|
8329
|
+
isError: !ok,
|
|
8330
|
+
error: ok ? undefined : message,
|
|
8331
|
+
args: { safeMode: action },
|
|
8332
|
+
output: message,
|
|
8333
|
+
hasStructured: false
|
|
8334
|
+
});
|
|
8335
|
+
return json({ ok, message, active: manager.isActive });
|
|
8336
|
+
}
|
|
8337
|
+
if (key === "POST /api/terminal/highlight") {
|
|
8338
|
+
const input = text("input");
|
|
8339
|
+
if (!input.trim())
|
|
8340
|
+
return json({ tokens: [] });
|
|
8341
|
+
const command = `:put [/console/inspect request=highlight input=${quoteValue(input)} as-value]`;
|
|
8342
|
+
return json({ tokens: parseHighlight(await quick(command).result) });
|
|
8343
|
+
}
|
|
8344
|
+
if (key === "POST /api/terminal/syntax") {
|
|
8345
|
+
const command = `:put [/console/inspect request=syntax input=${quoteValue(text("input"))} as-value]`;
|
|
8346
|
+
return json({ items: parseSyntaxHelp(await quick(command).result).slice(0, 200) });
|
|
8347
|
+
}
|
|
8348
|
+
if (key === "POST /api/terminal/complete") {
|
|
8349
|
+
const command = `/console/inspect request=completion input=${quoteValue(text("input"))}`;
|
|
8350
|
+
return json({ completions: parseCompletions(await quick(command).result) });
|
|
8351
|
+
}
|
|
8352
|
+
if (key === "POST /api/terminal/run") {
|
|
8353
|
+
const command = text("command").trim();
|
|
8354
|
+
if (!command)
|
|
8355
|
+
return json({ error: "Type a command first." }, 400);
|
|
8356
|
+
if (getConfig().readOnly && classifyCommand(command) !== "READ")
|
|
8357
|
+
return json({
|
|
8358
|
+
error: "This server is in read-only mode: only print, export and diagnostic commands run here."
|
|
8359
|
+
}, 403);
|
|
8360
|
+
const asked = Number(body.maxMs);
|
|
8361
|
+
const maxMs = Number.isFinite(asked) && asked > 0 ? Math.min(asked, MAX_MAX_MS) : DEFAULT_MAX_MS;
|
|
8362
|
+
return run(req, device, command, maxMs, body.snapshot === true);
|
|
8363
|
+
}
|
|
8364
|
+
if (key === "POST /api/terminal/changes") {
|
|
8365
|
+
return json({
|
|
8366
|
+
text: await snapshotTool("diff_config_snapshots", device, { from: "latest", to: "live" })
|
|
8367
|
+
});
|
|
8368
|
+
}
|
|
8369
|
+
return json({ error: "Unsupported terminal route" }, 405);
|
|
8370
|
+
} catch (e) {
|
|
8371
|
+
if (e instanceof DashboardInputError)
|
|
8372
|
+
return json({ error: e.message }, e.status);
|
|
8373
|
+
if (e instanceof SyntaxError)
|
|
8374
|
+
return json({ error: "Invalid JSON body." }, 400);
|
|
8375
|
+
return json({ error: e instanceof Error ? e.message : "Terminal request failed." }, 400);
|
|
8376
|
+
}
|
|
8377
|
+
};
|
|
8378
|
+
}
|
|
8379
|
+
|
|
8380
|
+
// src/observability/terminal-store.ts
|
|
8381
|
+
import { mkdirSync as mkdirSync3 } from "fs";
|
|
8382
|
+
import { dirname as dirname3 } from "path";
|
|
8383
|
+
var MAX_OUTPUT_CHARS = 200000;
|
|
8384
|
+
var MAX_HISTORY_ROWS = 5000;
|
|
8385
|
+
|
|
8386
|
+
class TerminalStore {
|
|
8387
|
+
db;
|
|
8388
|
+
constructor(db) {
|
|
8389
|
+
this.db = db;
|
|
8390
|
+
db.run(`CREATE TABLE IF NOT EXISTS terminal_history (
|
|
8391
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
8392
|
+
ts INTEGER NOT NULL,
|
|
8393
|
+
device TEXT NOT NULL,
|
|
8394
|
+
command TEXT NOT NULL,
|
|
8395
|
+
output TEXT NOT NULL,
|
|
8396
|
+
ok INTEGER NOT NULL,
|
|
8397
|
+
ms INTEGER NOT NULL,
|
|
8398
|
+
error TEXT
|
|
8399
|
+
)`);
|
|
8400
|
+
db.run("CREATE INDEX IF NOT EXISTS terminal_history_device ON terminal_history(device, id)");
|
|
8401
|
+
db.run(`CREATE TABLE IF NOT EXISTS terminal_schedules (
|
|
8402
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
8403
|
+
device TEXT NOT NULL,
|
|
8404
|
+
command TEXT NOT NULL,
|
|
8405
|
+
every_ms INTEGER NOT NULL,
|
|
8406
|
+
next_run INTEGER,
|
|
8407
|
+
last_run INTEGER,
|
|
8408
|
+
last_ok INTEGER,
|
|
8409
|
+
last_note TEXT NOT NULL
|
|
8410
|
+
)`);
|
|
8411
|
+
db.run(`CREATE TABLE IF NOT EXISTS terminal_favorites (
|
|
8412
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
8413
|
+
ts INTEGER NOT NULL,
|
|
8414
|
+
label TEXT NOT NULL,
|
|
8415
|
+
command TEXT NOT NULL UNIQUE
|
|
8416
|
+
)`);
|
|
8417
|
+
}
|
|
8418
|
+
addHistory(entry) {
|
|
8419
|
+
const result = this.db.query("INSERT INTO terminal_history (ts, device, command, output, ok, ms, error) VALUES (?, ?, ?, ?, ?, ?, ?)").run(entry.ts, entry.device, entry.command, entry.output.slice(0, MAX_OUTPUT_CHARS), entry.ok ? 1 : 0, Math.round(entry.ms), entry.error ?? null);
|
|
8420
|
+
this.db.run("DELETE FROM terminal_history WHERE id <= (SELECT MAX(id) FROM terminal_history) - ?", [MAX_HISTORY_ROWS]);
|
|
8421
|
+
return Number(result.lastInsertRowid);
|
|
8422
|
+
}
|
|
8423
|
+
listHistory(filter = {}) {
|
|
8424
|
+
const where = [];
|
|
8425
|
+
const args = [];
|
|
8426
|
+
if (filter.device) {
|
|
8427
|
+
where.push("device = ?");
|
|
8428
|
+
args.push(filter.device);
|
|
8429
|
+
}
|
|
8430
|
+
if (filter.q) {
|
|
8431
|
+
where.push("instr(lower(command), lower(?)) > 0");
|
|
8432
|
+
args.push(filter.q);
|
|
8433
|
+
}
|
|
8434
|
+
args.push(Math.min(Math.max(filter.limit ?? 200, 1), 1000));
|
|
8435
|
+
const rows = this.db.query(`SELECT id, ts, device, command, output, ok, ms, error FROM terminal_history
|
|
8436
|
+
${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY id DESC LIMIT ?`).all(...args);
|
|
8437
|
+
return rows.map((row) => ({
|
|
8438
|
+
...row,
|
|
8439
|
+
ok: row.ok === 1,
|
|
8440
|
+
error: row.error ?? undefined
|
|
8441
|
+
}));
|
|
8442
|
+
}
|
|
8443
|
+
deleteHistory(target) {
|
|
8444
|
+
if (target.id !== undefined)
|
|
8445
|
+
return this.db.run("DELETE FROM terminal_history WHERE id = ?", [target.id]).changes;
|
|
8446
|
+
if (target.device)
|
|
8447
|
+
return this.db.run("DELETE FROM terminal_history WHERE device = ?", [target.device]).changes;
|
|
8448
|
+
return this.db.run("DELETE FROM terminal_history").changes;
|
|
8449
|
+
}
|
|
8450
|
+
listFavorites() {
|
|
8451
|
+
return this.db.query("SELECT id, ts, label, command FROM terminal_favorites ORDER BY label, id").all();
|
|
8452
|
+
}
|
|
8453
|
+
saveFavorite(command, label) {
|
|
8454
|
+
this.db.run(`INSERT INTO terminal_favorites (ts, label, command) VALUES (?, ?, ?)
|
|
8455
|
+
ON CONFLICT(command) DO UPDATE SET label = excluded.label`, [Date.now(), label, command]);
|
|
8456
|
+
return this.db.query("SELECT id, ts, label, command FROM terminal_favorites WHERE command = ?").get(command);
|
|
8457
|
+
}
|
|
8458
|
+
deleteFavorite(id) {
|
|
8459
|
+
return this.db.run("DELETE FROM terminal_favorites WHERE id = ?", [id]).changes;
|
|
8460
|
+
}
|
|
8461
|
+
listSchedules() {
|
|
8462
|
+
const rows = this.db.query(`SELECT id, device, command, every_ms AS everyMs, next_run AS nextRun,
|
|
8463
|
+
last_run AS lastRun, last_ok AS lastOk, last_note AS lastNote
|
|
8464
|
+
FROM terminal_schedules ORDER BY next_run IS NULL, next_run, id`).all();
|
|
8465
|
+
return rows.map((row) => ({ ...row, lastOk: row.lastOk === null ? null : row.lastOk === 1 }));
|
|
8466
|
+
}
|
|
8467
|
+
addSchedule(item) {
|
|
8468
|
+
const result = this.db.run("INSERT INTO terminal_schedules (device, command, every_ms, next_run, last_note) VALUES (?, ?, ?, ?, '')", [item.device, item.command, item.everyMs, item.nextRun]);
|
|
8469
|
+
return Number(result.lastInsertRowid);
|
|
8470
|
+
}
|
|
8471
|
+
deleteSchedule(id) {
|
|
8472
|
+
return this.db.run("DELETE FROM terminal_schedules WHERE id = ?", [id]).changes;
|
|
8473
|
+
}
|
|
8474
|
+
markScheduleRun(id, run) {
|
|
8475
|
+
this.db.run("UPDATE terminal_schedules SET last_run = ?, last_ok = ?, last_note = ?, next_run = ? WHERE id = ?", [run.at, run.ok ? 1 : 0, run.note.slice(0, 300), run.next, id]);
|
|
8476
|
+
}
|
|
8477
|
+
close() {
|
|
8478
|
+
this.db.close();
|
|
8479
|
+
}
|
|
8480
|
+
}
|
|
8481
|
+
async function openTerminalStore(path) {
|
|
8482
|
+
if (path !== ":memory:") {
|
|
8483
|
+
try {
|
|
8484
|
+
mkdirSync3(dirname3(path), { recursive: true });
|
|
8485
|
+
} catch {}
|
|
8486
|
+
}
|
|
8487
|
+
const { Database } = await import("bun:sqlite");
|
|
8488
|
+
const db = new Database(path, { create: true });
|
|
8489
|
+
try {
|
|
8490
|
+
return new TerminalStore(db);
|
|
8491
|
+
} catch (error) {
|
|
8492
|
+
db.close();
|
|
8493
|
+
throw error;
|
|
8494
|
+
}
|
|
8495
|
+
}
|
|
8496
|
+
|
|
7647
8497
|
// src/observability/workspace-routes.ts
|
|
7648
8498
|
var routes2 = {
|
|
7649
8499
|
"GET /api/client-checks": "list_client_checks",
|
|
@@ -7686,15 +8536,15 @@ async function workspaceRoutes(req, url) {
|
|
|
7686
8536
|
}
|
|
7687
8537
|
|
|
7688
8538
|
// src/client-check/routes.ts
|
|
7689
|
-
import { readFileSync } from "fs";
|
|
7690
|
-
import { join as
|
|
8539
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
8540
|
+
import { join as join5 } from "path";
|
|
7691
8541
|
import { randomBytes } from "crypto";
|
|
7692
8542
|
var MiB = 1048576;
|
|
7693
8543
|
var budgets = new Map;
|
|
7694
8544
|
async function clientCheckRoutes(req, url, peer = "unknown") {
|
|
7695
8545
|
if (url.pathname === "/client-check" && req.method === "GET") {
|
|
7696
8546
|
try {
|
|
7697
|
-
return new Response(
|
|
8547
|
+
return new Response(readFileSync2(join5(PROJECT_ROOT, "dist/ui/client-check.html"), "utf8"), {
|
|
7698
8548
|
headers: {
|
|
7699
8549
|
"content-type": "text/html;charset=utf-8",
|
|
7700
8550
|
"cache-control": "no-store",
|
|
@@ -8042,8 +8892,8 @@ async function openVpnRoutes(req, url, history) {
|
|
|
8042
8892
|
|
|
8043
8893
|
// src/observability/openvpn-history.ts
|
|
8044
8894
|
import { randomUUID } from "crypto";
|
|
8045
|
-
import { chmodSync, mkdirSync as
|
|
8046
|
-
import { dirname as
|
|
8895
|
+
import { chmodSync, mkdirSync as mkdirSync4 } from "fs";
|
|
8896
|
+
import { dirname as dirname4 } from "path";
|
|
8047
8897
|
var OPENVPN_HISTORY_INTERVAL = 15000;
|
|
8048
8898
|
function sameObservedSession(previous, session, at) {
|
|
8049
8899
|
if (previous.ended !== null)
|
|
@@ -8178,7 +9028,7 @@ class OpenVpnHistoryStore {
|
|
|
8178
9028
|
}
|
|
8179
9029
|
}
|
|
8180
9030
|
async function openOpenVpnHistory(path) {
|
|
8181
|
-
|
|
9031
|
+
mkdirSync4(dirname4(path), { recursive: true, mode: 448 });
|
|
8182
9032
|
const { Database } = await import("bun:sqlite");
|
|
8183
9033
|
const db = new Database(path, { create: true });
|
|
8184
9034
|
chmodSync(path, 384);
|
|
@@ -8242,8 +9092,8 @@ function startOpenVpnHistorySampler(store) {
|
|
|
8242
9092
|
}
|
|
8243
9093
|
|
|
8244
9094
|
// src/observability/site-activity.ts
|
|
8245
|
-
import { chmodSync as chmodSync2, mkdirSync as
|
|
8246
|
-
import { dirname as
|
|
9095
|
+
import { chmodSync as chmodSync2, mkdirSync as mkdirSync5 } from "fs";
|
|
9096
|
+
import { dirname as dirname5 } from "path";
|
|
8247
9097
|
import { isIP as isIP2 } from "net";
|
|
8248
9098
|
function validSiteHost(host) {
|
|
8249
9099
|
const normalized = host.toLowerCase().replace(/\.$/, "");
|
|
@@ -8510,7 +9360,7 @@ class SqliteSiteActivityStore {
|
|
|
8510
9360
|
}
|
|
8511
9361
|
async function openSiteActivityStore(path) {
|
|
8512
9362
|
if (path !== ":memory:")
|
|
8513
|
-
|
|
9363
|
+
mkdirSync5(dirname5(path), { recursive: true, mode: 448 });
|
|
8514
9364
|
const { Database } = await import("bun:sqlite");
|
|
8515
9365
|
const db = new Database(path, { create: true });
|
|
8516
9366
|
if (path !== ":memory:")
|
|
@@ -9019,7 +9869,7 @@ async function roundTripRoutes(req, url) {
|
|
|
9019
9869
|
// src/observability/um-report-cache.ts
|
|
9020
9870
|
import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
|
|
9021
9871
|
import { mkdir as mkdir2, readFile, rename, stat, unlink as unlink2, writeFile } from "fs/promises";
|
|
9022
|
-
import { dirname as
|
|
9872
|
+
import { dirname as dirname6, join as join6 } from "path";
|
|
9023
9873
|
var MAX_BYTES = 32 * 1024 * 1024;
|
|
9024
9874
|
var MAX_AGE = 24 * 60 * 60000;
|
|
9025
9875
|
var sourceSchema = object({
|
|
@@ -9048,7 +9898,7 @@ function umReportCachePath(device) {
|
|
|
9048
9898
|
name = target?.jumpVia;
|
|
9049
9899
|
}
|
|
9050
9900
|
const key = createHash4("sha256").update(JSON.stringify(chain)).digest("hex");
|
|
9051
|
-
return
|
|
9901
|
+
return join6(`${config.dashboard.dbPath}.um-reports`, `${key}.json`);
|
|
9052
9902
|
}
|
|
9053
9903
|
async function loadUmReportCache(path, device, fields) {
|
|
9054
9904
|
if (!path)
|
|
@@ -9084,7 +9934,7 @@ async function saveUmReportCache(path, snapshot) {
|
|
|
9084
9934
|
const text = JSON.stringify({ version: 1, snapshot });
|
|
9085
9935
|
if (Buffer.byteLength(text) > MAX_BYTES)
|
|
9086
9936
|
return false;
|
|
9087
|
-
await mkdir2(
|
|
9937
|
+
await mkdir2(dirname6(path), { recursive: true, mode: 448 });
|
|
9088
9938
|
await writeFile(temp, text, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
9089
9939
|
await rename(temp, path);
|
|
9090
9940
|
return true;
|
|
@@ -9807,14 +10657,14 @@ function buildUmReport(snapshot, query) {
|
|
|
9807
10657
|
// src/observability/config-history.ts
|
|
9808
10658
|
import {
|
|
9809
10659
|
existsSync,
|
|
9810
|
-
mkdirSync as
|
|
9811
|
-
readFileSync as
|
|
9812
|
-
readdirSync,
|
|
10660
|
+
mkdirSync as mkdirSync6,
|
|
10661
|
+
readFileSync as readFileSync3,
|
|
10662
|
+
readdirSync as readdirSync2,
|
|
9813
10663
|
rmSync,
|
|
9814
|
-
statSync,
|
|
10664
|
+
statSync as statSync2,
|
|
9815
10665
|
writeFileSync
|
|
9816
10666
|
} from "fs";
|
|
9817
|
-
import { join as
|
|
10667
|
+
import { join as join7 } from "path";
|
|
9818
10668
|
var AUTO_RETENTION = 50;
|
|
9819
10669
|
function historyDir() {
|
|
9820
10670
|
return process.env.MIKROTIK_CONFIG_HISTORY_DIR || DEFAULT_CONFIG_HISTORY_DIR2;
|
|
@@ -9829,11 +10679,11 @@ function listVersions() {
|
|
|
9829
10679
|
if (!existsSync(dir))
|
|
9830
10680
|
return [];
|
|
9831
10681
|
const out = [];
|
|
9832
|
-
for (const f of
|
|
10682
|
+
for (const f of readdirSync2(dir)) {
|
|
9833
10683
|
if (!/^v\d+\.json$/.test(f))
|
|
9834
10684
|
continue;
|
|
9835
10685
|
try {
|
|
9836
|
-
const raw =
|
|
10686
|
+
const raw = readFileSync3(join7(dir, f), "utf8");
|
|
9837
10687
|
const parsed = JSON.parse(raw);
|
|
9838
10688
|
out.push({
|
|
9839
10689
|
id: f.replace(/\.json$/, ""),
|
|
@@ -9847,11 +10697,11 @@ function listVersions() {
|
|
|
9847
10697
|
return out.sort((a, b) => b.ts - a.ts);
|
|
9848
10698
|
}
|
|
9849
10699
|
function readVersion(id) {
|
|
9850
|
-
const raw =
|
|
10700
|
+
const raw = readFileSync3(join7(historyDir(), idToFile(id)), "utf8");
|
|
9851
10701
|
return JSON.parse(raw);
|
|
9852
10702
|
}
|
|
9853
10703
|
function deleteVersion(id) {
|
|
9854
|
-
const p =
|
|
10704
|
+
const p = join7(historyDir(), idToFile(id));
|
|
9855
10705
|
if (!existsSync(p))
|
|
9856
10706
|
return false;
|
|
9857
10707
|
rmSync(p);
|
|
@@ -9859,12 +10709,12 @@ function deleteVersion(id) {
|
|
|
9859
10709
|
}
|
|
9860
10710
|
function recordVersion(config, kind, now, label) {
|
|
9861
10711
|
const dir = historyDir();
|
|
9862
|
-
|
|
10712
|
+
mkdirSync6(dir, { recursive: true });
|
|
9863
10713
|
let ts = now;
|
|
9864
|
-
while (existsSync(
|
|
10714
|
+
while (existsSync(join7(dir, `v${ts}.json`)))
|
|
9865
10715
|
ts++;
|
|
9866
10716
|
const body = { ts, kind, label, config };
|
|
9867
|
-
writeFileSync(
|
|
10717
|
+
writeFileSync(join7(dir, `v${ts}.json`), `${JSON.stringify(body, null, 2)}
|
|
9868
10718
|
`, "utf8");
|
|
9869
10719
|
pruneAuto(dir);
|
|
9870
10720
|
return {
|
|
@@ -9881,7 +10731,7 @@ function pruneAuto(dir) {
|
|
|
9881
10731
|
return;
|
|
9882
10732
|
for (const v of autos.slice(AUTO_RETENTION)) {
|
|
9883
10733
|
try {
|
|
9884
|
-
rmSync(
|
|
10734
|
+
rmSync(join7(dir, `${v.id}.json`));
|
|
9885
10735
|
} catch {}
|
|
9886
10736
|
}
|
|
9887
10737
|
}
|
|
@@ -9889,26 +10739,26 @@ function isEmpty2() {
|
|
|
9889
10739
|
const dir = historyDir();
|
|
9890
10740
|
if (!existsSync(dir))
|
|
9891
10741
|
return true;
|
|
9892
|
-
return !
|
|
10742
|
+
return !readdirSync2(dir).some((f) => /^v\d+\.json$/.test(f));
|
|
9893
10743
|
}
|
|
9894
10744
|
function historyBytes() {
|
|
9895
10745
|
const dir = historyDir();
|
|
9896
10746
|
if (!existsSync(dir))
|
|
9897
10747
|
return 0;
|
|
9898
10748
|
let total = 0;
|
|
9899
|
-
for (const f of
|
|
10749
|
+
for (const f of readdirSync2(dir)) {
|
|
9900
10750
|
if (!/^v\d+\.json$/.test(f))
|
|
9901
10751
|
continue;
|
|
9902
10752
|
try {
|
|
9903
|
-
total +=
|
|
10753
|
+
total += statSync2(join7(dir, f)).size;
|
|
9904
10754
|
} catch {}
|
|
9905
10755
|
}
|
|
9906
10756
|
return total;
|
|
9907
10757
|
}
|
|
9908
10758
|
|
|
9909
10759
|
// src/prompts/index.ts
|
|
9910
|
-
import { readFileSync as
|
|
9911
|
-
import { join as
|
|
10760
|
+
import { readFileSync as readFileSync4, readdirSync as readdirSync3 } from "fs";
|
|
10761
|
+
import { join as join8 } from "path";
|
|
9912
10762
|
|
|
9913
10763
|
// src/txn/guidance.ts
|
|
9914
10764
|
var TRANSACTION_TOOL_NAMES = [
|
|
@@ -10051,14 +10901,14 @@ function deviceArgDescription(directory) {
|
|
|
10051
10901
|
function listPrompts() {
|
|
10052
10902
|
let files;
|
|
10053
10903
|
try {
|
|
10054
|
-
files =
|
|
10904
|
+
files = readdirSync3(PROMPTS_DIR).filter((f) => f.endsWith(".md"));
|
|
10055
10905
|
} catch {
|
|
10056
10906
|
return [];
|
|
10057
10907
|
}
|
|
10058
10908
|
const out = [];
|
|
10059
10909
|
for (const file of files) {
|
|
10060
10910
|
try {
|
|
10061
|
-
const parsed = parseFrontmatter(
|
|
10911
|
+
const parsed = parseFrontmatter(readFileSync4(join8(PROMPTS_DIR, file), "utf8"));
|
|
10062
10912
|
if (parsed) {
|
|
10063
10913
|
out.push({
|
|
10064
10914
|
name: parsed.name,
|
|
@@ -10075,7 +10925,7 @@ function listPrompts() {
|
|
|
10075
10925
|
function registerPrompts(server, opts = {}) {
|
|
10076
10926
|
let files;
|
|
10077
10927
|
try {
|
|
10078
|
-
files =
|
|
10928
|
+
files = readdirSync3(PROMPTS_DIR).filter((f) => f.endsWith(".md"));
|
|
10079
10929
|
} catch {
|
|
10080
10930
|
return 0;
|
|
10081
10931
|
}
|
|
@@ -10085,7 +10935,7 @@ function registerPrompts(server, opts = {}) {
|
|
|
10085
10935
|
for (const file of files) {
|
|
10086
10936
|
let parsed;
|
|
10087
10937
|
try {
|
|
10088
|
-
parsed = parseFrontmatter(
|
|
10938
|
+
parsed = parseFrontmatter(readFileSync4(join8(PROMPTS_DIR, file), "utf8"));
|
|
10089
10939
|
} catch (e) {
|
|
10090
10940
|
logger.warn(`Skipping prompt ${file}: ${String(e)}`);
|
|
10091
10941
|
continue;
|
|
@@ -10187,14 +11037,14 @@ async function setCapsmanManager(ctx, input) {
|
|
|
10187
11037
|
}
|
|
10188
11038
|
|
|
10189
11039
|
// src/observability/flags.ts
|
|
10190
|
-
import { join as
|
|
11040
|
+
import { join as join9 } from "path";
|
|
10191
11041
|
import { mkdir as mkdir3, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
|
|
10192
11042
|
import { homedir as homedir4 } from "os";
|
|
10193
11043
|
var LOG_TAG = "mikrotik-mcp";
|
|
10194
11044
|
var CODE_RE = /^[a-z]{2}$/;
|
|
10195
11045
|
var sourceUrl = (code) => `https://hatscripts.github.io/circle-flags/flags/${code}.svg`;
|
|
10196
|
-
var VENDOR_DIR =
|
|
10197
|
-
var CACHE_DIR =
|
|
11046
|
+
var VENDOR_DIR = join9(PROJECT_ROOT, "assets", "flags");
|
|
11047
|
+
var CACHE_DIR = join9(homedir4(), ".mikrotik-mcp", "flags");
|
|
10198
11048
|
var mem = new Map;
|
|
10199
11049
|
async function flagSvg(code) {
|
|
10200
11050
|
const c = code.toLowerCase();
|
|
@@ -10203,7 +11053,7 @@ async function flagSvg(code) {
|
|
|
10203
11053
|
const cached = mem.get(c);
|
|
10204
11054
|
if (cached !== undefined)
|
|
10205
11055
|
return cached;
|
|
10206
|
-
for (const file of [
|
|
11056
|
+
for (const file of [join9(VENDOR_DIR, `${c}.svg`), join9(CACHE_DIR, `${c}.svg`)]) {
|
|
10207
11057
|
try {
|
|
10208
11058
|
const svg = await readFile2(file, "utf8");
|
|
10209
11059
|
mem.set(c, svg);
|
|
@@ -10219,7 +11069,7 @@ async function flagSvg(code) {
|
|
|
10219
11069
|
}
|
|
10220
11070
|
const svg = await res.text();
|
|
10221
11071
|
mem.set(c, svg);
|
|
10222
|
-
mkdir3(CACHE_DIR, { recursive: true }).then(() => writeFile2(
|
|
11072
|
+
mkdir3(CACHE_DIR, { recursive: true }).then(() => writeFile2(join9(CACHE_DIR, `${c}.svg`), svg)).catch(() => {});
|
|
10223
11073
|
return svg;
|
|
10224
11074
|
} catch (e) {
|
|
10225
11075
|
logger.warn(`[${LOG_TAG}] flag fetch failed for '${c}': ${e instanceof Error ? e.message : String(e)}`);
|
|
@@ -10446,8 +11296,8 @@ data: ${JSON.stringify(sample)}
|
|
|
10446
11296
|
}
|
|
10447
11297
|
|
|
10448
11298
|
// src/observability/store.ts
|
|
10449
|
-
import { mkdirSync as
|
|
10450
|
-
import { dirname as
|
|
11299
|
+
import { mkdirSync as mkdirSync7 } from "fs";
|
|
11300
|
+
import { dirname as dirname7 } from "path";
|
|
10451
11301
|
function rowToEvent(r) {
|
|
10452
11302
|
return {
|
|
10453
11303
|
id: r.id,
|
|
@@ -10633,7 +11483,7 @@ class SqliteEventStore {
|
|
|
10633
11483
|
async function openSqliteStore(path) {
|
|
10634
11484
|
if (path !== ":memory:") {
|
|
10635
11485
|
try {
|
|
10636
|
-
|
|
11486
|
+
mkdirSync7(dirname7(path), { recursive: true });
|
|
10637
11487
|
} catch {}
|
|
10638
11488
|
}
|
|
10639
11489
|
const { Database } = await import("bun:sqlite");
|
|
@@ -10642,8 +11492,8 @@ async function openSqliteStore(path) {
|
|
|
10642
11492
|
}
|
|
10643
11493
|
|
|
10644
11494
|
// src/observability/capsman-store.ts
|
|
10645
|
-
import { mkdirSync as
|
|
10646
|
-
import { dirname as
|
|
11495
|
+
import { mkdirSync as mkdirSync8 } from "fs";
|
|
11496
|
+
import { dirname as dirname8 } from "path";
|
|
10647
11497
|
function summariseRadioSamples(rows) {
|
|
10648
11498
|
const byRadio = new Map;
|
|
10649
11499
|
for (const r of rows) {
|
|
@@ -10733,7 +11583,7 @@ class SqliteCapsmanStore {
|
|
|
10733
11583
|
async function openCapsmanStore(path) {
|
|
10734
11584
|
if (path !== ":memory:") {
|
|
10735
11585
|
try {
|
|
10736
|
-
|
|
11586
|
+
mkdirSync8(dirname8(path), { recursive: true });
|
|
10737
11587
|
} catch {}
|
|
10738
11588
|
}
|
|
10739
11589
|
const { Database } = await import("bun:sqlite");
|
|
@@ -10812,8 +11662,8 @@ function stopCapsmanSampler() {
|
|
|
10812
11662
|
}
|
|
10813
11663
|
|
|
10814
11664
|
// src/observability/usage-store.ts
|
|
10815
|
-
import { mkdirSync as
|
|
10816
|
-
import { dirname as
|
|
11665
|
+
import { mkdirSync as mkdirSync9 } from "fs";
|
|
11666
|
+
import { dirname as dirname9 } from "path";
|
|
10817
11667
|
function dayOf(ts) {
|
|
10818
11668
|
return new Date(ts).toISOString().slice(0, 10);
|
|
10819
11669
|
}
|
|
@@ -10950,7 +11800,7 @@ class SqliteUsageStore {
|
|
|
10950
11800
|
async function openUsageStore(path) {
|
|
10951
11801
|
if (path !== ":memory:") {
|
|
10952
11802
|
try {
|
|
10953
|
-
|
|
11803
|
+
mkdirSync9(dirname9(path), { recursive: true });
|
|
10954
11804
|
} catch {}
|
|
10955
11805
|
}
|
|
10956
11806
|
const { Database } = await import("bun:sqlite");
|
|
@@ -11197,7 +12047,7 @@ function getStore() {
|
|
|
11197
12047
|
return storePromise2;
|
|
11198
12048
|
}
|
|
11199
12049
|
var JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
|
|
11200
|
-
function
|
|
12050
|
+
function json2(body, status = 200) {
|
|
11201
12051
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
|
|
11202
12052
|
}
|
|
11203
12053
|
async function bodyJson(req) {
|
|
@@ -11238,7 +12088,7 @@ async function driftRoutes(req, url) {
|
|
|
11238
12088
|
latestSnapshotTs: latest.ts
|
|
11239
12089
|
};
|
|
11240
12090
|
});
|
|
11241
|
-
return
|
|
12091
|
+
return json2({ devices });
|
|
11242
12092
|
}
|
|
11243
12093
|
if (p === "/api/drift/baselines" && req.method === "GET") {
|
|
11244
12094
|
const baselines = store.listBaselines();
|
|
@@ -11249,16 +12099,16 @@ async function driftRoutes(req, url) {
|
|
|
11249
12099
|
snapshot: snap ? { lines: snap.lines, bytes: snap.bytes, sha: snap.sha, rosVersion: snap.rosVersion } : null
|
|
11250
12100
|
};
|
|
11251
12101
|
});
|
|
11252
|
-
return
|
|
12102
|
+
return json2({ baselines: enriched });
|
|
11253
12103
|
}
|
|
11254
12104
|
const baselineMatch = p.match(/^\/api\/drift\/baseline\/(.+)$/);
|
|
11255
12105
|
if (baselineMatch && req.method === "GET") {
|
|
11256
12106
|
const device = decodeURIComponent(baselineMatch[1]);
|
|
11257
12107
|
const baseline = store.getBaseline(device);
|
|
11258
12108
|
if (!baseline)
|
|
11259
|
-
return
|
|
12109
|
+
return json2({ error: "no baseline set" }, 404);
|
|
11260
12110
|
const snap = store.get(baseline.snapshotId);
|
|
11261
|
-
return
|
|
12111
|
+
return json2({
|
|
11262
12112
|
...baseline,
|
|
11263
12113
|
snapshot: snap ? { lines: snap.lines, bytes: snap.bytes, sha: snap.sha, rosVersion: snap.rosVersion } : null
|
|
11264
12114
|
});
|
|
@@ -11266,25 +12116,25 @@ async function driftRoutes(req, url) {
|
|
|
11266
12116
|
if (p === "/api/drift/baseline" && req.method === "POST") {
|
|
11267
12117
|
const b = await bodyJson(req);
|
|
11268
12118
|
if (!b.device || !b.snapshotId) {
|
|
11269
|
-
return
|
|
12119
|
+
return json2({ error: "device and snapshotId are required" }, 400);
|
|
11270
12120
|
}
|
|
11271
12121
|
const snap = store.get(b.snapshotId);
|
|
11272
12122
|
if (!snap)
|
|
11273
|
-
return
|
|
12123
|
+
return json2({ error: `snapshot '${b.snapshotId}' not found` }, 404);
|
|
11274
12124
|
store.setBaseline(b.device, b.snapshotId, "dashboard", b.label, b.notes);
|
|
11275
|
-
return
|
|
12125
|
+
return json2({ ok: true, device: b.device, snapshotId: b.snapshotId });
|
|
11276
12126
|
}
|
|
11277
12127
|
if (baselineMatch && req.method === "DELETE") {
|
|
11278
12128
|
const device = decodeURIComponent(baselineMatch[1]);
|
|
11279
12129
|
const removed = store.removeBaseline(device);
|
|
11280
|
-
return
|
|
12130
|
+
return json2({ ok: removed, device });
|
|
11281
12131
|
}
|
|
11282
12132
|
const historyMatch = p.match(/^\/api\/drift\/history\/(.+)$/);
|
|
11283
12133
|
if (historyMatch && req.method === "GET") {
|
|
11284
12134
|
const device = decodeURIComponent(historyMatch[1]);
|
|
11285
12135
|
const limit = Number(url.searchParams.get("limit") ?? "20");
|
|
11286
12136
|
const snapshots = store.list(device, limit, false);
|
|
11287
|
-
return
|
|
12137
|
+
return json2({ device, snapshots });
|
|
11288
12138
|
}
|
|
11289
12139
|
const checkMatch = p.match(/^\/api\/drift\/check\/(.+)$/);
|
|
11290
12140
|
if (checkMatch && req.method === "GET") {
|
|
@@ -11293,20 +12143,20 @@ async function driftRoutes(req, url) {
|
|
|
11293
12143
|
try {
|
|
11294
12144
|
device = resolveDeviceName(deviceKey);
|
|
11295
12145
|
} catch {
|
|
11296
|
-
return
|
|
12146
|
+
return json2({ error: `unknown device '${deviceKey}'` }, 404);
|
|
11297
12147
|
}
|
|
11298
12148
|
const baseline = store.getBaseline(device);
|
|
11299
12149
|
if (!baseline)
|
|
11300
|
-
return
|
|
12150
|
+
return json2({ error: "no baseline set" }, 404);
|
|
11301
12151
|
const baselineSnap = store.get(baseline.snapshotId);
|
|
11302
12152
|
if (!baselineSnap)
|
|
11303
|
-
return
|
|
12153
|
+
return json2({ error: "baseline snapshot deleted" }, 404);
|
|
11304
12154
|
try {
|
|
11305
12155
|
const ctx = createContext(undefined, device);
|
|
11306
12156
|
const exportCmd = new Cmd("/export").raw("terse").build();
|
|
11307
12157
|
const liveBody = await executeMikrotikCommand(exportCmd, ctx);
|
|
11308
12158
|
if (isEmpty(liveBody) || looksLikeError(liveBody)) {
|
|
11309
|
-
return
|
|
12159
|
+
return json2({ error: `export failed: ${liveBody.trim() || "(empty)"}` }, 502);
|
|
11310
12160
|
}
|
|
11311
12161
|
const diff = diffLines(normalizeExport2(baselineSnap.body), normalizeExport2(liveBody), {
|
|
11312
12162
|
contextLines: 3,
|
|
@@ -11322,7 +12172,7 @@ async function driftRoutes(req, url) {
|
|
|
11322
12172
|
report.attributions = attributeChanges(report.sections, logText);
|
|
11323
12173
|
}
|
|
11324
12174
|
} catch {}
|
|
11325
|
-
return
|
|
12175
|
+
return json2(report);
|
|
11326
12176
|
} catch (e) {
|
|
11327
12177
|
return errorResponse(e);
|
|
11328
12178
|
}
|
|
@@ -11332,7 +12182,7 @@ async function driftRoutes(req, url) {
|
|
|
11332
12182
|
|
|
11333
12183
|
// src/observability/posture-routes.ts
|
|
11334
12184
|
var JSON_HEADERS2 = { "content-type": "application/json; charset=utf-8" };
|
|
11335
|
-
function
|
|
12185
|
+
function json3(body, status = 200) {
|
|
11336
12186
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS2 });
|
|
11337
12187
|
}
|
|
11338
12188
|
async function postureRoutes(req, url) {
|
|
@@ -11344,9 +12194,9 @@ async function postureRoutes(req, url) {
|
|
|
11344
12194
|
const ctx = createContext(undefined, device);
|
|
11345
12195
|
try {
|
|
11346
12196
|
const map = buildFabricMap(await collectFabric(device, ctx));
|
|
11347
|
-
return
|
|
12197
|
+
return json3(map);
|
|
11348
12198
|
} catch (e) {
|
|
11349
|
-
return
|
|
12199
|
+
return json3({ error: e instanceof Error ? e.message : String(e) }, 502);
|
|
11350
12200
|
}
|
|
11351
12201
|
}
|
|
11352
12202
|
if (p === "/api/advisories") {
|
|
@@ -11356,7 +12206,7 @@ async function postureRoutes(req, url) {
|
|
|
11356
12206
|
try {
|
|
11357
12207
|
const facts = await Promise.all(targets.map((d) => collectDeviceFacts(d)));
|
|
11358
12208
|
const report = matchAdvisories(facts);
|
|
11359
|
-
return
|
|
12209
|
+
return json3({
|
|
11360
12210
|
...report,
|
|
11361
12211
|
datasetDate: ADVISORY_DATASET_DATE,
|
|
11362
12212
|
datasetSize: ADVISORIES.length,
|
|
@@ -11369,12 +12219,12 @@ async function postureRoutes(req, url) {
|
|
|
11369
12219
|
}))
|
|
11370
12220
|
});
|
|
11371
12221
|
} catch (e) {
|
|
11372
|
-
return
|
|
12222
|
+
return json3({ error: e instanceof Error ? e.message : String(e) }, 502);
|
|
11373
12223
|
}
|
|
11374
12224
|
}
|
|
11375
12225
|
if (p === "/api/access") {
|
|
11376
12226
|
const policy = getAccessPolicy();
|
|
11377
|
-
return
|
|
12227
|
+
return json3({
|
|
11378
12228
|
enabled: policy.enabled,
|
|
11379
12229
|
scope: policy.scope,
|
|
11380
12230
|
denials: recentDenials(50)
|
|
@@ -11400,7 +12250,7 @@ var editSchema = object({
|
|
|
11400
12250
|
tool: string().optional()
|
|
11401
12251
|
}).strict();
|
|
11402
12252
|
var idSchema = object({ pendingId: string().min(1) }).strict();
|
|
11403
|
-
var
|
|
12253
|
+
var json4 = (body, status = 200) => Response.json(body, { status });
|
|
11404
12254
|
var policyFor = ({ enabled, ...scope }) => ({ enabled, scope });
|
|
11405
12255
|
function createAccessSettingsRoutes(admin, deps = {
|
|
11406
12256
|
getConfig,
|
|
@@ -11440,46 +12290,46 @@ function createAccessSettingsRoutes(admin, deps = {
|
|
|
11440
12290
|
if (!path.startsWith("/api/access/settings"))
|
|
11441
12291
|
return null;
|
|
11442
12292
|
if (path === "/api/access/settings" && req.method === "GET")
|
|
11443
|
-
return
|
|
12293
|
+
return json4(payload());
|
|
11444
12294
|
if (!["preview", "apply", "keep", "rollback"].some((s) => path === `/api/access/settings/${s}`))
|
|
11445
|
-
return
|
|
12295
|
+
return json4({ error: "Not found" }, 404);
|
|
11446
12296
|
if (req.method !== "POST")
|
|
11447
|
-
return
|
|
12297
|
+
return json4({ error: "Use POST" }, 405);
|
|
11448
12298
|
if (req.headers.get("sec-fetch-site") === "cross-site")
|
|
11449
|
-
return
|
|
12299
|
+
return json4({ error: "Cross-site access changes are not allowed" }, 403);
|
|
11450
12300
|
if (req.headers.get("content-type")?.split(";")[0].trim() !== "application/json")
|
|
11451
|
-
return
|
|
12301
|
+
return json4({ error: "Expected application/json" }, 415);
|
|
11452
12302
|
let body;
|
|
11453
12303
|
try {
|
|
11454
12304
|
const text = await req.text();
|
|
11455
12305
|
if (text.length > 65536)
|
|
11456
|
-
return
|
|
12306
|
+
return json4({ error: "Access settings are too large" }, 413);
|
|
11457
12307
|
body = JSON.parse(text);
|
|
11458
12308
|
} catch {
|
|
11459
|
-
return
|
|
12309
|
+
return json4({ error: "Invalid JSON" }, 400);
|
|
11460
12310
|
}
|
|
11461
12311
|
if (path.endsWith("/keep") || path.endsWith("/rollback")) {
|
|
11462
12312
|
const parsed = idSchema.safeParse(body);
|
|
11463
12313
|
if (!parsed.success)
|
|
11464
|
-
return
|
|
12314
|
+
return json4({ error: "A pending change ID is required" }, 400);
|
|
11465
12315
|
const id = parsed.data.pendingId;
|
|
11466
12316
|
if (pending?.id !== id || admin.pendingId() !== id)
|
|
11467
|
-
return
|
|
12317
|
+
return json4({ error: "This change expired or was replaced. Refresh the current policy." }, 409);
|
|
11468
12318
|
const keep = path.endsWith("/keep");
|
|
11469
12319
|
const ok = keep ? admin.keepConfig(id) : admin.rollback(id);
|
|
11470
12320
|
if (!ok)
|
|
11471
|
-
return
|
|
12321
|
+
return json4({ error: "This change is no longer pending" }, 409);
|
|
11472
12322
|
pending = null;
|
|
11473
12323
|
if (keep)
|
|
11474
12324
|
deps.recordVersion(deps.getConfig(), "auto", deps.now(), "access scope updated");
|
|
11475
|
-
return
|
|
12325
|
+
return json4({ ok: true, settings: payload() });
|
|
11476
12326
|
}
|
|
11477
12327
|
const parsed = editSchema.safeParse(body);
|
|
11478
12328
|
if (!parsed.success)
|
|
11479
|
-
return
|
|
12329
|
+
return json4({ error: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, 400);
|
|
11480
12330
|
const { access, tool } = parsed.data;
|
|
11481
12331
|
if (parsed.data.revision !== revision())
|
|
11482
|
-
return
|
|
12332
|
+
return json4({ error: "Configuration changed since you opened this editor. Refresh before applying." }, 409);
|
|
11483
12333
|
const cfg = deps.getConfig();
|
|
11484
12334
|
const device = parsed.data.device ? Object.keys(cfg.devices).find((key) => key.toLowerCase() === parsed.data.device.toLowerCase()) : cfg.defaultDevice;
|
|
11485
12335
|
const unknownDevice = [
|
|
@@ -11488,9 +12338,9 @@ function createAccessSettingsRoutes(admin, deps = {
|
|
|
11488
12338
|
...parsed.data.device ? [parsed.data.device] : []
|
|
11489
12339
|
].find((name) => !Object.keys(cfg.devices).some((key) => key.toLowerCase() === name.toLowerCase()));
|
|
11490
12340
|
if (unknownDevice)
|
|
11491
|
-
return
|
|
12341
|
+
return json4({ error: `Unknown device: ${unknownDevice}` }, 400);
|
|
11492
12342
|
if (tool && !tools.some((t) => t.name === tool))
|
|
11493
|
-
return
|
|
12343
|
+
return json4({ error: `Unknown tool: ${tool}` }, 400);
|
|
11494
12344
|
if (path.endsWith("/preview")) {
|
|
11495
12345
|
const effective = deps.previewAccessPolicy(policyFor(access));
|
|
11496
12346
|
const current = deps.getAccessPolicy();
|
|
@@ -11532,21 +12382,21 @@ function createAccessSettingsRoutes(admin, deps = {
|
|
|
11532
12382
|
if (tool === t.name)
|
|
11533
12383
|
result.check = next;
|
|
11534
12384
|
}
|
|
11535
|
-
return
|
|
12385
|
+
return json4({ ok: true, preview: result });
|
|
11536
12386
|
}
|
|
11537
12387
|
if (admin.pendingId())
|
|
11538
|
-
return
|
|
12388
|
+
return json4({
|
|
11539
12389
|
error: "Another configuration change is awaiting confirmation. Keep or revert it first."
|
|
11540
12390
|
}, 409);
|
|
11541
12391
|
const res = admin.applyConfig({ ...cfg, access }, 60000);
|
|
11542
12392
|
pending = { id: res.pendingId, expiresAt: deps.now() + res.rollbackMs };
|
|
11543
|
-
return
|
|
12393
|
+
return json4({ ok: true, settings: payload() });
|
|
11544
12394
|
};
|
|
11545
12395
|
}
|
|
11546
12396
|
|
|
11547
12397
|
// src/observability/txn-routes.ts
|
|
11548
12398
|
var JSON_HEADERS3 = { "content-type": "application/json; charset=utf-8" };
|
|
11549
|
-
function
|
|
12399
|
+
function json5(body, status = 200) {
|
|
11550
12400
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS3 });
|
|
11551
12401
|
}
|
|
11552
12402
|
function liveRecord(id) {
|
|
@@ -11573,16 +12423,16 @@ async function txnRoutes(req, url) {
|
|
|
11573
12423
|
for (const r of live)
|
|
11574
12424
|
byId.set(r.id, r);
|
|
11575
12425
|
const transactions = [...byId.values()].sort((a, b) => b.ts - a.ts).slice(0, limit);
|
|
11576
|
-
return
|
|
12426
|
+
return json5({ transactions, live: liveTxnUpdates(), error: storeError });
|
|
11577
12427
|
}
|
|
11578
12428
|
const parts = p.slice("/api/txn/".length).split("/").filter(Boolean);
|
|
11579
12429
|
if (parts.length === 0 || parts.length > 2)
|
|
11580
|
-
return
|
|
12430
|
+
return json5({ error: "not found" }, 404);
|
|
11581
12431
|
const id = decodeURIComponent(parts[0]);
|
|
11582
12432
|
if (parts[1] === "abort" && req.method === "POST") {
|
|
11583
12433
|
const entry = getTxn(id);
|
|
11584
12434
|
if (!entry)
|
|
11585
|
-
return
|
|
12435
|
+
return json5({ error: `no open transaction '${id}'` }, 404);
|
|
11586
12436
|
entry.txn = requestAbort(entry.txn, "aborted from the dashboard");
|
|
11587
12437
|
const run = await runTransaction({
|
|
11588
12438
|
txn: entry.txn,
|
|
@@ -11593,7 +12443,7 @@ async function txnRoutes(req, url) {
|
|
|
11593
12443
|
await persistTxn(entry);
|
|
11594
12444
|
if (run.state !== undefined)
|
|
11595
12445
|
dropTxn(id);
|
|
11596
|
-
return
|
|
12446
|
+
return json5({
|
|
11597
12447
|
state: run.state,
|
|
11598
12448
|
summary: run.summary,
|
|
11599
12449
|
transaction: toRecord(run.txn, entry.ts)
|
|
@@ -11602,15 +12452,15 @@ async function txnRoutes(req, url) {
|
|
|
11602
12452
|
if (parts.length === 1 && req.method === "GET") {
|
|
11603
12453
|
const record = liveRecord(id) ?? store?.get(id) ?? null;
|
|
11604
12454
|
if (!record)
|
|
11605
|
-
return
|
|
11606
|
-
return
|
|
12455
|
+
return json5({ error: `unknown transaction '${id}'` }, 404);
|
|
12456
|
+
return json5({ transaction: record, events: store?.events(id) ?? [] });
|
|
11607
12457
|
}
|
|
11608
|
-
return
|
|
12458
|
+
return json5({ error: "method not allowed" }, 405);
|
|
11609
12459
|
}
|
|
11610
12460
|
|
|
11611
12461
|
// src/observability/flow-routes.ts
|
|
11612
12462
|
var JSON_HEADERS4 = { "content-type": "application/json; charset=utf-8" };
|
|
11613
|
-
function
|
|
12463
|
+
function json6(body, status = 200) {
|
|
11614
12464
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS4 });
|
|
11615
12465
|
}
|
|
11616
12466
|
var WINDOWS = {
|
|
@@ -11631,14 +12481,14 @@ async function flowRoutes(req, url) {
|
|
|
11631
12481
|
if (!p.startsWith("/api/flows"))
|
|
11632
12482
|
return null;
|
|
11633
12483
|
if (req.method !== "GET")
|
|
11634
|
-
return
|
|
12484
|
+
return json6({ error: "method not allowed" }, 405);
|
|
11635
12485
|
const collector = getFlowCollector();
|
|
11636
12486
|
if (p === "/api/flows/health") {
|
|
11637
12487
|
let store = null;
|
|
11638
12488
|
try {
|
|
11639
12489
|
store = (await flowStore()).stats();
|
|
11640
12490
|
} catch {}
|
|
11641
|
-
return
|
|
12491
|
+
return json6({ collector: collector.stats(), store });
|
|
11642
12492
|
}
|
|
11643
12493
|
collector.drain();
|
|
11644
12494
|
let records;
|
|
@@ -11649,12 +12499,12 @@ async function flowRoutes(req, url) {
|
|
|
11649
12499
|
try {
|
|
11650
12500
|
records = (await flowStore()).query({ from, to, address, limit: 200000 });
|
|
11651
12501
|
} catch (e) {
|
|
11652
|
-
return
|
|
12502
|
+
return json6({ error: e instanceof Error ? e.message : String(e), records: [] }, 200);
|
|
11653
12503
|
}
|
|
11654
12504
|
if (p === "/api/flows/top") {
|
|
11655
12505
|
const dimension = url.searchParams.get("dimension") ?? "source";
|
|
11656
12506
|
const limit = Number(url.searchParams.get("limit") ?? 10);
|
|
11657
|
-
return
|
|
12507
|
+
return json6({
|
|
11658
12508
|
window: { from, to },
|
|
11659
12509
|
totals: summarize(records),
|
|
11660
12510
|
top: topTalkers(records, dimension, limit, true),
|
|
@@ -11664,7 +12514,7 @@ async function flowRoutes(req, url) {
|
|
|
11664
12514
|
}
|
|
11665
12515
|
if (p === "/api/flows/conversations") {
|
|
11666
12516
|
const limit = Number(url.searchParams.get("limit") ?? 20);
|
|
11667
|
-
return
|
|
12517
|
+
return json6({
|
|
11668
12518
|
window: { from, to },
|
|
11669
12519
|
conversations: conversations(records, limit)
|
|
11670
12520
|
});
|
|
@@ -11673,19 +12523,19 @@ async function flowRoutes(req, url) {
|
|
|
11673
12523
|
const dimension = url.searchParams.get("dimension") ?? "source";
|
|
11674
12524
|
const topN = Number(url.searchParams.get("topN") ?? 5);
|
|
11675
12525
|
const bucket = bucketFor(span);
|
|
11676
|
-
return
|
|
12526
|
+
return json6({
|
|
11677
12527
|
window: { from, to },
|
|
11678
12528
|
bucketMs: bucket,
|
|
11679
12529
|
keys: topTalkers(records, dimension, topN).map((t) => t.key),
|
|
11680
12530
|
buckets: timeline(records, from, to, bucket, dimension, topN)
|
|
11681
12531
|
});
|
|
11682
12532
|
}
|
|
11683
|
-
return
|
|
12533
|
+
return json6({ error: "not found" }, 404);
|
|
11684
12534
|
}
|
|
11685
12535
|
|
|
11686
12536
|
// src/observability/rollout-routes.ts
|
|
11687
12537
|
var JSON_HEADERS5 = { "content-type": "application/json; charset=utf-8" };
|
|
11688
|
-
function
|
|
12538
|
+
function json7(body, status = 200) {
|
|
11689
12539
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS5 });
|
|
11690
12540
|
}
|
|
11691
12541
|
function liveRecord2(id) {
|
|
@@ -11715,17 +12565,17 @@ async function rolloutRoutes(req, url) {
|
|
|
11715
12565
|
for (const r of live)
|
|
11716
12566
|
byId.set(r.id, r);
|
|
11717
12567
|
const rollouts = [...byId.values()].sort((a, b) => b.ts - a.ts).slice(0, limit);
|
|
11718
|
-
return
|
|
12568
|
+
return json7({ rollouts, live: liveRolloutUpdates(), error: storeError });
|
|
11719
12569
|
}
|
|
11720
12570
|
const parts = p.slice("/api/rollout/".length).split("/").filter(Boolean);
|
|
11721
12571
|
if (parts.length === 0 || parts.length > 2)
|
|
11722
|
-
return
|
|
12572
|
+
return json7({ error: "not found" }, 404);
|
|
11723
12573
|
const id = decodeURIComponent(parts[0]);
|
|
11724
12574
|
const verb = parts[1];
|
|
11725
12575
|
if (verb && req.method === "POST") {
|
|
11726
12576
|
const entry = getRollout(id);
|
|
11727
12577
|
if (!entry)
|
|
11728
|
-
return
|
|
12578
|
+
return json7({ error: `no active rollout '${id}'` }, 404);
|
|
11729
12579
|
switch (verb) {
|
|
11730
12580
|
case "hold": {
|
|
11731
12581
|
entry.state = requestHold(entry.state);
|
|
@@ -11740,7 +12590,7 @@ async function rolloutRoutes(req, url) {
|
|
|
11740
12590
|
devices: entry.state.devices,
|
|
11741
12591
|
gates: entry.state.gates
|
|
11742
12592
|
});
|
|
11743
|
-
return
|
|
12593
|
+
return json7({ held: true, summary: summarize2(entry.state) });
|
|
11744
12594
|
}
|
|
11745
12595
|
case "resume": {
|
|
11746
12596
|
entry.state = resume(entry.state);
|
|
@@ -11768,7 +12618,7 @@ async function rolloutRoutes(req, url) {
|
|
|
11768
12618
|
await persistRollout(entry);
|
|
11769
12619
|
if (run.outcome)
|
|
11770
12620
|
dropRollout(id);
|
|
11771
|
-
return
|
|
12621
|
+
return json7({ outcome: run.outcome, summary: run.summary });
|
|
11772
12622
|
}
|
|
11773
12623
|
case "abort": {
|
|
11774
12624
|
entry.state = requestAbort2(entry.state, "aborted from the dashboard");
|
|
@@ -11781,24 +12631,24 @@ async function rolloutRoutes(req, url) {
|
|
|
11781
12631
|
await persistRollout(entry);
|
|
11782
12632
|
if (run.outcome)
|
|
11783
12633
|
dropRollout(id);
|
|
11784
|
-
return
|
|
12634
|
+
return json7({ outcome: run.outcome, summary: run.summary });
|
|
11785
12635
|
}
|
|
11786
12636
|
default:
|
|
11787
|
-
return
|
|
12637
|
+
return json7({ error: `unknown action '${verb}'` }, 404);
|
|
11788
12638
|
}
|
|
11789
12639
|
}
|
|
11790
12640
|
if (parts.length === 1 && req.method === "GET") {
|
|
11791
12641
|
const record = liveRecord2(id) ?? store?.get(id) ?? null;
|
|
11792
12642
|
if (!record)
|
|
11793
|
-
return
|
|
11794
|
-
return
|
|
12643
|
+
return json7({ error: `unknown rollout '${id}'` }, 404);
|
|
12644
|
+
return json7({ rollout: record, events: store?.events(id) ?? [] });
|
|
11795
12645
|
}
|
|
11796
|
-
return
|
|
12646
|
+
return json7({ error: "method not allowed" }, 405);
|
|
11797
12647
|
}
|
|
11798
12648
|
|
|
11799
12649
|
// src/policy/results.ts
|
|
11800
|
-
import { mkdirSync as
|
|
11801
|
-
import { dirname as
|
|
12650
|
+
import { mkdirSync as mkdirSync10 } from "fs";
|
|
12651
|
+
import { dirname as dirname10 } from "path";
|
|
11802
12652
|
var SCHEMA_STATEMENTS4 = [
|
|
11803
12653
|
`CREATE TABLE IF NOT EXISTS policy_results (
|
|
11804
12654
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -11858,7 +12708,7 @@ class SqlitePolicyResultStore {
|
|
|
11858
12708
|
async function openPolicyResultStore(path) {
|
|
11859
12709
|
if (path !== ":memory:") {
|
|
11860
12710
|
try {
|
|
11861
|
-
|
|
12711
|
+
mkdirSync10(dirname10(path), { recursive: true });
|
|
11862
12712
|
} catch {}
|
|
11863
12713
|
}
|
|
11864
12714
|
const { Database } = await import("bun:sqlite");
|
|
@@ -11883,7 +12733,7 @@ async function policyResults(device, limit = 50) {
|
|
|
11883
12733
|
|
|
11884
12734
|
// src/observability/policy-routes.ts
|
|
11885
12735
|
var JSON_HEADERS6 = { "content-type": "application/json; charset=utf-8" };
|
|
11886
|
-
function
|
|
12736
|
+
function json8(body, status = 200) {
|
|
11887
12737
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS6 });
|
|
11888
12738
|
}
|
|
11889
12739
|
async function bodyJson2(req) {
|
|
@@ -11895,7 +12745,7 @@ async function policyRoutes(req, url) {
|
|
|
11895
12745
|
return null;
|
|
11896
12746
|
if (p === "/api/policies" && req.method === "GET") {
|
|
11897
12747
|
const set = currentPolicySet();
|
|
11898
|
-
return
|
|
12748
|
+
return json8({
|
|
11899
12749
|
files: set.files.map((f) => ({
|
|
11900
12750
|
path: f.path,
|
|
11901
12751
|
name: f.name,
|
|
@@ -11916,21 +12766,21 @@ async function policyRoutes(req, url) {
|
|
|
11916
12766
|
try {
|
|
11917
12767
|
results = await policyResults(device, limit);
|
|
11918
12768
|
} catch (e) {
|
|
11919
|
-
return
|
|
12769
|
+
return json8({ results: [], error: e instanceof Error ? e.message : String(e) });
|
|
11920
12770
|
}
|
|
11921
|
-
return
|
|
12771
|
+
return json8({ results });
|
|
11922
12772
|
}
|
|
11923
12773
|
if (p === "/api/policies/validate" && req.method === "POST") {
|
|
11924
12774
|
const body = await bodyJson2(req);
|
|
11925
12775
|
if (typeof body.content !== "string")
|
|
11926
|
-
return
|
|
11927
|
-
return
|
|
12776
|
+
return json8({ error: "content is required" }, 400);
|
|
12777
|
+
return json8(validatePolicyText(body.content));
|
|
11928
12778
|
}
|
|
11929
12779
|
if (p === "/api/policies/run" && req.method === "POST") {
|
|
11930
12780
|
const body = await bodyJson2(req);
|
|
11931
12781
|
const set = currentPolicySet();
|
|
11932
12782
|
if (set.policies.length === 0) {
|
|
11933
|
-
return
|
|
12783
|
+
return json8({ error: "no policy rules are loaded", reports: [] });
|
|
11934
12784
|
}
|
|
11935
12785
|
const cfg = getConfig();
|
|
11936
12786
|
const devices = body.devices && body.devices.length > 0 ? body.devices : Object.entries(cfg.devices).filter(([, d]) => !d.disabled).map(([name]) => name);
|
|
@@ -11959,14 +12809,14 @@ async function policyRoutes(req, url) {
|
|
|
11959
12809
|
reports.push({ device, error: e instanceof Error ? e.message : String(e) });
|
|
11960
12810
|
}
|
|
11961
12811
|
}
|
|
11962
|
-
return
|
|
12812
|
+
return json8({ reports });
|
|
11963
12813
|
}
|
|
11964
|
-
return
|
|
12814
|
+
return json8({ error: "not found" }, 404);
|
|
11965
12815
|
}
|
|
11966
12816
|
|
|
11967
12817
|
// src/observability/sim-routes.ts
|
|
11968
12818
|
var JSON_HEADERS7 = { "content-type": "application/json; charset=utf-8" };
|
|
11969
|
-
function
|
|
12819
|
+
function json9(body, status = 200) {
|
|
11970
12820
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS7 });
|
|
11971
12821
|
}
|
|
11972
12822
|
async function bodyJson3(req) {
|
|
@@ -12001,32 +12851,32 @@ async function simRoutes(req, url) {
|
|
|
12001
12851
|
if (p === "/api/sim/verify" && req.method === "POST") {
|
|
12002
12852
|
const parsed = verificationSchema.safeParse(await bodyJson3(req));
|
|
12003
12853
|
if (!parsed.success)
|
|
12004
|
-
return
|
|
12005
|
-
return
|
|
12854
|
+
return json9({ error: "Provide an export, valid scope and declared packet context." }, 400);
|
|
12855
|
+
return json9(verifyPolicy(parsed.data));
|
|
12006
12856
|
}
|
|
12007
12857
|
if (p === "/api/sim/suites" && req.method === "GET") {
|
|
12008
|
-
return
|
|
12858
|
+
return json9({ suites: await listSuites() });
|
|
12009
12859
|
}
|
|
12010
12860
|
if (p === "/api/sim/suites" && req.method === "POST") {
|
|
12011
12861
|
const body = await bodyJson3(req);
|
|
12012
12862
|
if (!body.name || !Array.isArray(body.packets) || body.packets.length === 0) {
|
|
12013
|
-
return
|
|
12863
|
+
return json9({ error: "name and a non-empty packets array are required" }, 400);
|
|
12014
12864
|
}
|
|
12015
12865
|
const saved = await saveSuite({
|
|
12016
12866
|
id: body.id,
|
|
12017
12867
|
name: body.name,
|
|
12018
12868
|
packets: body.packets
|
|
12019
12869
|
});
|
|
12020
|
-
return
|
|
12870
|
+
return json9({ suite: saved });
|
|
12021
12871
|
}
|
|
12022
12872
|
if (p === "/api/sim/packet" && req.method === "POST") {
|
|
12023
12873
|
const body = await bodyJson3(req);
|
|
12024
12874
|
const config = await configFor(body);
|
|
12025
12875
|
if ("error" in config)
|
|
12026
|
-
return
|
|
12876
|
+
return json9(config, 400);
|
|
12027
12877
|
const model = buildModel(config.text);
|
|
12028
12878
|
const result = tracePacket({ model, packet: body.packet });
|
|
12029
|
-
return
|
|
12879
|
+
return json9({
|
|
12030
12880
|
source: config.source,
|
|
12031
12881
|
result,
|
|
12032
12882
|
coverage: {
|
|
@@ -12040,16 +12890,16 @@ async function simRoutes(req, url) {
|
|
|
12040
12890
|
const body = await bodyJson3(req);
|
|
12041
12891
|
const config = await configFor(body);
|
|
12042
12892
|
if ("error" in config)
|
|
12043
|
-
return
|
|
12893
|
+
return json9(config, 400);
|
|
12044
12894
|
if (!body.changes || body.changes.trim() === "") {
|
|
12045
|
-
return
|
|
12895
|
+
return json9({ error: "changes are required" }, 400);
|
|
12046
12896
|
}
|
|
12047
12897
|
const before = tracePacket({ model: buildModel(config.text), packet: body.packet });
|
|
12048
12898
|
const afterModel = buildModel(`${config.text}
|
|
12049
12899
|
${body.changes}
|
|
12050
12900
|
`);
|
|
12051
12901
|
const after = tracePacket({ model: afterModel, packet: body.packet });
|
|
12052
|
-
return
|
|
12902
|
+
return json9({
|
|
12053
12903
|
source: config.source,
|
|
12054
12904
|
before,
|
|
12055
12905
|
after,
|
|
@@ -12064,10 +12914,10 @@ ${body.changes}
|
|
|
12064
12914
|
packet: {}
|
|
12065
12915
|
});
|
|
12066
12916
|
if ("error" in config)
|
|
12067
|
-
return
|
|
12917
|
+
return json9(config, 400);
|
|
12068
12918
|
const model = buildModel(config.text);
|
|
12069
12919
|
const dead = unreachableRules(model.filter);
|
|
12070
|
-
return
|
|
12920
|
+
return json9({
|
|
12071
12921
|
source: config.source,
|
|
12072
12922
|
rules: model.filter.map((r) => ({
|
|
12073
12923
|
chain: r.chain,
|
|
@@ -12088,11 +12938,11 @@ ${body.changes}
|
|
|
12088
12938
|
const id = decodeURIComponent(p.slice("/api/sim/suite/".length, -"/run".length));
|
|
12089
12939
|
const suite = await getSuite(id);
|
|
12090
12940
|
if (!suite)
|
|
12091
|
-
return
|
|
12941
|
+
return json9({ error: `no suite '${id}'` }, 404);
|
|
12092
12942
|
const body = await bodyJson3(req);
|
|
12093
12943
|
const config = await configFor({ ...body, packet: {} });
|
|
12094
12944
|
if ("error" in config)
|
|
12095
|
-
return
|
|
12945
|
+
return json9(config, 400);
|
|
12096
12946
|
const model = buildModel(config.text);
|
|
12097
12947
|
const results = suite.packets.map((entry) => {
|
|
12098
12948
|
const result = tracePacket({ model, packet: entry.packet });
|
|
@@ -12104,7 +12954,7 @@ ${body.changes}
|
|
|
12104
12954
|
summary: result.summary
|
|
12105
12955
|
};
|
|
12106
12956
|
});
|
|
12107
|
-
return
|
|
12957
|
+
return json9({
|
|
12108
12958
|
source: config.source,
|
|
12109
12959
|
suite: { id: suite.id, name: suite.name },
|
|
12110
12960
|
results,
|
|
@@ -12112,12 +12962,12 @@ ${body.changes}
|
|
|
12112
12962
|
total: results.length
|
|
12113
12963
|
});
|
|
12114
12964
|
}
|
|
12115
|
-
return
|
|
12965
|
+
return json9({ error: "not found" }, 404);
|
|
12116
12966
|
}
|
|
12117
12967
|
|
|
12118
12968
|
// src/observability/schedule-routes.ts
|
|
12119
12969
|
var JSON_HEADERS8 = { "content-type": "application/json; charset=utf-8" };
|
|
12120
|
-
function
|
|
12970
|
+
function json10(body, status = 200) {
|
|
12121
12971
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS8 });
|
|
12122
12972
|
}
|
|
12123
12973
|
function latestPerDevice(runs) {
|
|
@@ -12194,12 +13044,12 @@ async function scheduleRoutes(req, url) {
|
|
|
12194
13044
|
try {
|
|
12195
13045
|
store = await scheduleStore();
|
|
12196
13046
|
} catch (e) {
|
|
12197
|
-
return
|
|
13047
|
+
return json10({ error: e instanceof Error ? e.message : String(e), jobs: [] }, 503);
|
|
12198
13048
|
}
|
|
12199
13049
|
const now = Date.now();
|
|
12200
13050
|
if (p === "/api/schedules" && req.method === "GET") {
|
|
12201
13051
|
const jobs = store.listJobs().map((job) => jobRow(job, store.runs(job.id, 500), now));
|
|
12202
|
-
return
|
|
13052
|
+
return json10({
|
|
12203
13053
|
jobs,
|
|
12204
13054
|
schedulable: schedulableTools().map((a) => ({ tool: a.tool, summary: a.summary }))
|
|
12205
13055
|
});
|
|
@@ -12207,20 +13057,20 @@ async function scheduleRoutes(req, url) {
|
|
|
12207
13057
|
if (p === "/api/schedules" && req.method === "POST") {
|
|
12208
13058
|
const body = await req.json().catch(() => null);
|
|
12209
13059
|
if (!body)
|
|
12210
|
-
return
|
|
13060
|
+
return json10({ error: "invalid JSON body" }, 400);
|
|
12211
13061
|
const parsed = JobSchema.safeParse(body);
|
|
12212
13062
|
if (!parsed.success) {
|
|
12213
|
-
return
|
|
13063
|
+
return json10({
|
|
12214
13064
|
error: parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ")
|
|
12215
13065
|
}, 400);
|
|
12216
13066
|
}
|
|
12217
13067
|
if (!auditAdapter(parsed.data.tool)) {
|
|
12218
|
-
return
|
|
13068
|
+
return json10({ error: `'${parsed.data.tool}' is not a schedulable auditor` }, 400);
|
|
12219
13069
|
}
|
|
12220
13070
|
await primeRiskIndex();
|
|
12221
13071
|
const risk = liveExecutor().riskOf(parsed.data.tool);
|
|
12222
13072
|
if (risk !== "READ") {
|
|
12223
|
-
return
|
|
13073
|
+
return json10({ error: `'${parsed.data.tool}' is annotated ${risk}; only READ may be scheduled` }, 400);
|
|
12224
13074
|
}
|
|
12225
13075
|
const existing = store.getJob(parsed.data.id);
|
|
12226
13076
|
const job = { ...parsed.data, createdAt: existing?.createdAt ?? now };
|
|
@@ -12229,7 +13079,7 @@ async function scheduleRoutes(req, url) {
|
|
|
12229
13079
|
armJob(job, now);
|
|
12230
13080
|
else
|
|
12231
13081
|
forgetJob(job.id);
|
|
12232
|
-
return
|
|
13082
|
+
return json10({ job: jobRow(job, store.runs(job.id, 500), now), replaced: existing !== null });
|
|
12233
13083
|
}
|
|
12234
13084
|
if (p === "/api/schedules/timeline" && req.method === "GET") {
|
|
12235
13085
|
const jobId = url.searchParams.get("job") ?? undefined;
|
|
@@ -12237,7 +13087,7 @@ async function scheduleRoutes(req, url) {
|
|
|
12237
13087
|
const days = Number(url.searchParams.get("days") ?? 30);
|
|
12238
13088
|
const since = now - days * 86400000;
|
|
12239
13089
|
const runs = store.runs(jobId, 2000).filter((r) => r.startedAt >= since && (!device || r.device === device));
|
|
12240
|
-
return
|
|
13090
|
+
return json10({
|
|
12241
13091
|
points: runs.map((r) => ({
|
|
12242
13092
|
at: r.startedAt,
|
|
12243
13093
|
jobId: r.jobId,
|
|
@@ -12257,30 +13107,30 @@ async function scheduleRoutes(req, url) {
|
|
|
12257
13107
|
const limit = Number(url.searchParams.get("limit") ?? 50);
|
|
12258
13108
|
const jobs = jobId ? [jobId] : store.listJobs().map((j) => j.id);
|
|
12259
13109
|
const items = jobs.flatMap((id) => regressionsFor(store.runs(id, 500), id)).sort((a, b) => b.at - a.at).slice(0, limit);
|
|
12260
|
-
return
|
|
13110
|
+
return json10({ regressions: items });
|
|
12261
13111
|
}
|
|
12262
13112
|
const parts = p.slice("/api/schedules/".length).split("/").filter(Boolean);
|
|
12263
13113
|
if (parts.length === 0 || parts.length > 2)
|
|
12264
|
-
return
|
|
13114
|
+
return json10({ error: "not found" }, 404);
|
|
12265
13115
|
const id = decodeURIComponent(parts[0]);
|
|
12266
13116
|
const verb = parts[1];
|
|
12267
13117
|
if (!verb && req.method === "DELETE") {
|
|
12268
13118
|
const job = store.getJob(id);
|
|
12269
13119
|
if (!job)
|
|
12270
|
-
return
|
|
13120
|
+
return json10({ error: `no schedule '${id}'` }, 404);
|
|
12271
13121
|
const runCount = store.runs(id, 1e4).length;
|
|
12272
13122
|
store.removeJob(id);
|
|
12273
13123
|
forgetJob(id);
|
|
12274
|
-
return
|
|
13124
|
+
return json10({ removed: id, runsDiscarded: runCount });
|
|
12275
13125
|
}
|
|
12276
13126
|
if (verb === "run" && req.method === "POST") {
|
|
12277
13127
|
const job = store.getJob(id);
|
|
12278
13128
|
if (!job)
|
|
12279
|
-
return
|
|
13129
|
+
return json10({ error: `no schedule '${id}'` }, 404);
|
|
12280
13130
|
await primeRiskIndex();
|
|
12281
13131
|
logger.info(`schedule '${id}' run requested from the dashboard`);
|
|
12282
13132
|
const result = await runJob(job, liveExecutor(), runnerOptions());
|
|
12283
|
-
return
|
|
13133
|
+
return json10({
|
|
12284
13134
|
...result,
|
|
12285
13135
|
job: jobRow(job, store.runs(id, 500), Date.now())
|
|
12286
13136
|
});
|
|
@@ -12288,16 +13138,16 @@ async function scheduleRoutes(req, url) {
|
|
|
12288
13138
|
if (!verb && req.method === "GET") {
|
|
12289
13139
|
const job = store.getJob(id);
|
|
12290
13140
|
if (!job)
|
|
12291
|
-
return
|
|
13141
|
+
return json10({ error: `no schedule '${id}'` }, 404);
|
|
12292
13142
|
const runs = store.runs(id, 500);
|
|
12293
|
-
return
|
|
13143
|
+
return json10({ job: jobRow(job, runs, now), runs, regressions: regressionsFor(runs, id) });
|
|
12294
13144
|
}
|
|
12295
|
-
return
|
|
13145
|
+
return json10({ error: "not found" }, 404);
|
|
12296
13146
|
}
|
|
12297
13147
|
|
|
12298
13148
|
// src/observability/explain-routes.ts
|
|
12299
13149
|
var JSON_HEADERS9 = { "content-type": "application/json; charset=utf-8" };
|
|
12300
|
-
function
|
|
13150
|
+
function json11(body, status = 200) {
|
|
12301
13151
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS9 });
|
|
12302
13152
|
}
|
|
12303
13153
|
var storePromise5 = null;
|
|
@@ -12338,52 +13188,52 @@ async function explainRoutes(req, url) {
|
|
|
12338
13188
|
if (p === "/api/explain/diff" && req.method === "POST") {
|
|
12339
13189
|
const body = await req.json().catch(() => null);
|
|
12340
13190
|
if (!body)
|
|
12341
|
-
return
|
|
13191
|
+
return json11({ error: "invalid JSON body" }, 400);
|
|
12342
13192
|
if (!body.before && !body.beforeText) {
|
|
12343
|
-
return
|
|
13193
|
+
return json11({ error: "a diff needs a baseline: pass `before` (a snapshot id) or `beforeText`" }, 400);
|
|
12344
13194
|
}
|
|
12345
13195
|
const device = body.device ?? "";
|
|
12346
13196
|
const before = body.beforeText ? { text: body.beforeText, device, source: "supplied text" } : await configFor2(device, body.before ?? null);
|
|
12347
13197
|
if ("error" in before)
|
|
12348
|
-
return
|
|
13198
|
+
return json11({ error: `before: ${before.error}` }, before.status);
|
|
12349
13199
|
const after = body.afterText ? { text: body.afterText, device, source: "supplied text" } : await configFor2(device, body.after ?? null);
|
|
12350
13200
|
if ("error" in after)
|
|
12351
|
-
return
|
|
13201
|
+
return json11({ error: `after: ${after.error}` }, after.status);
|
|
12352
13202
|
const diff = diffNarratives(analyzeDevice(before.text, before.device), analyzeDevice(after.text, after.device));
|
|
12353
|
-
return
|
|
13203
|
+
return json11({ diff, markdown: renderDiff(diff), before: before.source, after: after.source });
|
|
12354
13204
|
}
|
|
12355
13205
|
const rest = p.slice("/api/explain/".length).split("/").filter(Boolean);
|
|
12356
13206
|
if (rest.length === 0)
|
|
12357
|
-
return
|
|
13207
|
+
return json11({ error: "not found" }, 404);
|
|
12358
13208
|
if (req.method !== "GET")
|
|
12359
|
-
return
|
|
13209
|
+
return json11({ error: "not found" }, 404);
|
|
12360
13210
|
const device = decodeURIComponent(rest[0]);
|
|
12361
13211
|
const snapshotId = url.searchParams.get("snapshot");
|
|
12362
13212
|
let config;
|
|
12363
13213
|
try {
|
|
12364
13214
|
config = await configFor2(device, snapshotId);
|
|
12365
13215
|
} catch (e) {
|
|
12366
|
-
return
|
|
13216
|
+
return json11({ error: e instanceof Error ? e.message : String(e) }, 502);
|
|
12367
13217
|
}
|
|
12368
13218
|
if ("error" in config)
|
|
12369
|
-
return
|
|
13219
|
+
return json11({ error: config.error }, config.status);
|
|
12370
13220
|
const narrative = { ...analyzeDevice(config.text, config.device), generatedAt: Date.now() };
|
|
12371
13221
|
if (rest.length === 1) {
|
|
12372
|
-
return
|
|
13222
|
+
return json11(payload(narrative, config.source, renderNarrative(narrative)));
|
|
12373
13223
|
}
|
|
12374
13224
|
if (rest[1] === "section" && rest[2]) {
|
|
12375
13225
|
const section = decodeURIComponent(rest[2]);
|
|
12376
13226
|
if (!NARRATIVE_SECTIONS.includes(section)) {
|
|
12377
|
-
return
|
|
13227
|
+
return json11({ error: `unknown section '${section}'. Known: ${NARRATIVE_SECTIONS.join(", ")}` }, 400);
|
|
12378
13228
|
}
|
|
12379
|
-
return
|
|
13229
|
+
return json11(payload(narrative, config.source, renderNarrative(narrative, { sections: [section] })));
|
|
12380
13230
|
}
|
|
12381
|
-
return
|
|
13231
|
+
return json11({ error: "not found" }, 404);
|
|
12382
13232
|
}
|
|
12383
13233
|
|
|
12384
13234
|
// src/observability/attack-routes.ts
|
|
12385
13235
|
var JSON_HEADERS10 = { "content-type": "application/json; charset=utf-8" };
|
|
12386
|
-
function
|
|
13236
|
+
function json12(body, status = 200) {
|
|
12387
13237
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS10 });
|
|
12388
13238
|
}
|
|
12389
13239
|
async function attackRoutes(req, url) {
|
|
@@ -12394,7 +13244,7 @@ async function attackRoutes(req, url) {
|
|
|
12394
13244
|
try {
|
|
12395
13245
|
store = await attackStore();
|
|
12396
13246
|
} catch (e) {
|
|
12397
|
-
return
|
|
13247
|
+
return json12({ error: e instanceof Error ? e.message : String(e), incidents: [] }, 503);
|
|
12398
13248
|
}
|
|
12399
13249
|
const cfg = getConfig().attacks;
|
|
12400
13250
|
const now = Date.now();
|
|
@@ -12406,7 +13256,7 @@ async function attackRoutes(req, url) {
|
|
|
12406
13256
|
});
|
|
12407
13257
|
const responses = store.listResponses({ active: true, limit: 500 });
|
|
12408
13258
|
const blocked = new Set(responses.map((r) => r.source));
|
|
12409
|
-
return
|
|
13259
|
+
return json12({
|
|
12410
13260
|
incidents: incidents.map((i) => ({ ...i, blocked: blocked.has(i.source) })),
|
|
12411
13261
|
responses,
|
|
12412
13262
|
posture: {
|
|
@@ -12446,7 +13296,7 @@ async function attackRoutes(req, url) {
|
|
|
12446
13296
|
}
|
|
12447
13297
|
}
|
|
12448
13298
|
const active = new Set(store.listResponses({ active: true, limit: 500 }).map((r) => r.source));
|
|
12449
|
-
return
|
|
13299
|
+
return json12({
|
|
12450
13300
|
sources: [...bySource.values()].map((s) => ({
|
|
12451
13301
|
source: s.source,
|
|
12452
13302
|
devices: [...s.devices].sort(),
|
|
@@ -12464,14 +13314,14 @@ async function attackRoutes(req, url) {
|
|
|
12464
13314
|
const guards = buildGuards();
|
|
12465
13315
|
const never = [...neverBlockSet(guards)].sort();
|
|
12466
13316
|
const check = url.searchParams.get("check");
|
|
12467
|
-
return
|
|
13317
|
+
return json12({
|
|
12468
13318
|
config: cfg,
|
|
12469
13319
|
neverBlock: never,
|
|
12470
13320
|
check: check ? { address: check, protected: isNeverBlock(check, new Set(never)) } : undefined
|
|
12471
13321
|
});
|
|
12472
13322
|
}
|
|
12473
13323
|
if (p === "/api/attacks/config" && req.method === "POST") {
|
|
12474
|
-
return
|
|
13324
|
+
return json12({
|
|
12475
13325
|
error: "edit the `attacks` block in Config \u2014 the policy has to survive a restart, so it is not held in memory here"
|
|
12476
13326
|
}, 501);
|
|
12477
13327
|
}
|
|
@@ -12484,7 +13334,7 @@ async function attackRoutes(req, url) {
|
|
|
12484
13334
|
onlineOnly: body.onlineOnly,
|
|
12485
13335
|
respond: false
|
|
12486
13336
|
});
|
|
12487
|
-
return
|
|
13337
|
+
return json12({
|
|
12488
13338
|
incidents: result.incidents,
|
|
12489
13339
|
unavailable: result.unavailable,
|
|
12490
13340
|
devices: result.devices,
|
|
@@ -12492,7 +13342,7 @@ async function attackRoutes(req, url) {
|
|
|
12492
13342
|
});
|
|
12493
13343
|
}
|
|
12494
13344
|
if (p === "/api/attacks/devices" && req.method === "GET") {
|
|
12495
|
-
return
|
|
13345
|
+
return json12({
|
|
12496
13346
|
devices: listDevices().names.map((name) => ({
|
|
12497
13347
|
name,
|
|
12498
13348
|
reachable: getDeviceStatus(name).reachable
|
|
@@ -12505,24 +13355,24 @@ async function attackRoutes(req, url) {
|
|
|
12505
13355
|
const response = store.responseFor(address);
|
|
12506
13356
|
const devices = response?.devices ?? [];
|
|
12507
13357
|
if (devices.length === 0)
|
|
12508
|
-
return
|
|
13358
|
+
return json12({ error: `no recorded block for ${address}` }, 404);
|
|
12509
13359
|
const results = await revokeBlock(address, devices, response?.list);
|
|
12510
13360
|
store.revokeResponse(address, now);
|
|
12511
|
-
return
|
|
13361
|
+
return json12({ address, results });
|
|
12512
13362
|
}
|
|
12513
13363
|
if (rest.length === 1 && req.method === "GET") {
|
|
12514
13364
|
const incident = store.getIncident(decodeURIComponent(rest[0]));
|
|
12515
13365
|
if (!incident)
|
|
12516
|
-
return
|
|
12517
|
-
return
|
|
13366
|
+
return json12({ error: "not found" }, 404);
|
|
13367
|
+
return json12({ incident, response: store.responseFor(incident.source) });
|
|
12518
13368
|
}
|
|
12519
13369
|
if (rest.length === 2 && rest[1] === "respond" && req.method === "POST") {
|
|
12520
13370
|
const incident = store.getIncident(decodeURIComponent(rest[0]));
|
|
12521
13371
|
if (!incident)
|
|
12522
|
-
return
|
|
13372
|
+
return json12({ error: "not found" }, 404);
|
|
12523
13373
|
const body = await req.json().catch(() => ({}));
|
|
12524
13374
|
if (body.action === "dismiss") {
|
|
12525
|
-
return
|
|
13375
|
+
return json12({ dismissed: incident.id });
|
|
12526
13376
|
}
|
|
12527
13377
|
const decision = decide({
|
|
12528
13378
|
incident,
|
|
@@ -12534,13 +13384,13 @@ async function attackRoutes(req, url) {
|
|
|
12534
13384
|
timeout: body.timeout
|
|
12535
13385
|
});
|
|
12536
13386
|
if (!isPlan(decision)) {
|
|
12537
|
-
return
|
|
13387
|
+
return json12({ refused: true, guard: decision.guard, reason: decision.reason }, 200);
|
|
12538
13388
|
}
|
|
12539
13389
|
if (decision.action === "escalate") {
|
|
12540
|
-
return
|
|
13390
|
+
return json12({ escalated: true, reason: decision.reason });
|
|
12541
13391
|
}
|
|
12542
13392
|
if (!body.confirm) {
|
|
12543
|
-
return
|
|
13393
|
+
return json12({ dryRun: true, plan: decision });
|
|
12544
13394
|
}
|
|
12545
13395
|
const applied = await executePlan(decision);
|
|
12546
13396
|
const ok = applied.some((r) => r.ok);
|
|
@@ -12556,14 +13406,14 @@ async function attackRoutes(req, url) {
|
|
|
12556
13406
|
ok,
|
|
12557
13407
|
error: ok ? undefined : applied.map((r) => r.detail).join("; ")
|
|
12558
13408
|
});
|
|
12559
|
-
return
|
|
13409
|
+
return json12({ applied, ok, plan: decision });
|
|
12560
13410
|
}
|
|
12561
|
-
return
|
|
13411
|
+
return json12({ error: "not found" }, 404);
|
|
12562
13412
|
}
|
|
12563
13413
|
|
|
12564
13414
|
// src/observability/alert-routes.ts
|
|
12565
13415
|
var JSON_HEADERS11 = { "content-type": "application/json; charset=utf-8" };
|
|
12566
|
-
function
|
|
13416
|
+
function json13(body, status = 200) {
|
|
12567
13417
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS11 });
|
|
12568
13418
|
}
|
|
12569
13419
|
function ruleRow(rule, subject, status, since) {
|
|
@@ -12618,11 +13468,11 @@ async function alertRoutes(req, url, db) {
|
|
|
12618
13468
|
const channels = getConfig().alerts?.channels;
|
|
12619
13469
|
if (p === "/api/alerts" && req.method === "GET") {
|
|
12620
13470
|
if (!engine) {
|
|
12621
|
-
return
|
|
13471
|
+
return json13({ configured: false, rules: [], active: [], channels: {} });
|
|
12622
13472
|
}
|
|
12623
13473
|
const now = Date.now();
|
|
12624
13474
|
const rows = engine.snapshot().map(({ rule, subject, state }) => ruleRow(rule, subject, isMuted(rule, now) ? "muted" : !rule.enabled ? "disabled" : state.status, state.since));
|
|
12625
|
-
return
|
|
13475
|
+
return json13({
|
|
12626
13476
|
configured: true,
|
|
12627
13477
|
rules: rows,
|
|
12628
13478
|
active: rows.filter((r) => r.status === "firing"),
|
|
@@ -12631,41 +13481,41 @@ async function alertRoutes(req, url, db) {
|
|
|
12631
13481
|
}
|
|
12632
13482
|
if (p === "/api/alerts/history" && req.method === "GET") {
|
|
12633
13483
|
if (!engine)
|
|
12634
|
-
return
|
|
13484
|
+
return json13({ history: [] });
|
|
12635
13485
|
const hours = Number(url.searchParams.get("hours") ?? 24);
|
|
12636
13486
|
const history = await engine.history({
|
|
12637
13487
|
sinceMs: Date.now() - hours * 3600000,
|
|
12638
13488
|
ruleId: url.searchParams.get("rule") ?? undefined,
|
|
12639
13489
|
limit: Number(url.searchParams.get("limit") ?? 200)
|
|
12640
13490
|
});
|
|
12641
|
-
return
|
|
13491
|
+
return json13({ history });
|
|
12642
13492
|
}
|
|
12643
13493
|
if (p === "/api/alerts/rules" && req.method === "POST") {
|
|
12644
13494
|
if (!engine)
|
|
12645
|
-
return
|
|
13495
|
+
return json13({ error: "alerting is not configured" }, 400);
|
|
12646
13496
|
const parsed = AlertRuleSchema.safeParse(await req.json());
|
|
12647
13497
|
if (!parsed.success) {
|
|
12648
|
-
return
|
|
13498
|
+
return json13({ error: parsed.error.issues.map((i) => i.message).join("; ") }, 400);
|
|
12649
13499
|
}
|
|
12650
13500
|
const rules = engine.configuredRules();
|
|
12651
13501
|
if (rules.some((r) => r.id === parsed.data.id)) {
|
|
12652
|
-
return
|
|
13502
|
+
return json13({ error: `rule '${parsed.data.id}' already exists` }, 409);
|
|
12653
13503
|
}
|
|
12654
13504
|
engine.setRules([...rules, parsed.data]);
|
|
12655
|
-
return
|
|
13505
|
+
return json13({ ok: true, id: parsed.data.id });
|
|
12656
13506
|
}
|
|
12657
13507
|
const idMatch = p.match(/^\/api\/alerts\/rules\/([^/]+)$/);
|
|
12658
13508
|
if (idMatch) {
|
|
12659
13509
|
if (!engine)
|
|
12660
|
-
return
|
|
13510
|
+
return json13({ error: "alerting is not configured" }, 400);
|
|
12661
13511
|
const id = decodeURIComponent(idMatch[1]);
|
|
12662
13512
|
const rules = engine.configuredRules();
|
|
12663
13513
|
const existing = rules.find((r) => r.id === id);
|
|
12664
13514
|
if (!existing)
|
|
12665
|
-
return
|
|
13515
|
+
return json13({ error: `unknown rule: ${id}` }, 404);
|
|
12666
13516
|
if (req.method === "DELETE") {
|
|
12667
13517
|
engine.setRules(rules.filter((r) => r.id !== id));
|
|
12668
|
-
return
|
|
13518
|
+
return json13({ ok: true });
|
|
12669
13519
|
}
|
|
12670
13520
|
if (req.method === "PATCH") {
|
|
12671
13521
|
const body = await req.json();
|
|
@@ -12673,22 +13523,22 @@ async function alertRoutes(req, url, db) {
|
|
|
12673
13523
|
if (typeof body.mute === "string") {
|
|
12674
13524
|
const ms = parseDuration(body.mute);
|
|
12675
13525
|
if (ms === null)
|
|
12676
|
-
return
|
|
13526
|
+
return json13({ error: `invalid duration: ${body.mute}` }, 400);
|
|
12677
13527
|
mutedUntil = ms === 0 ? undefined : Date.now() + ms;
|
|
12678
13528
|
delete body.mute;
|
|
12679
13529
|
}
|
|
12680
13530
|
const merged = AlertRuleSchema.safeParse({ ...existing, ...body, mutedUntil });
|
|
12681
13531
|
if (!merged.success) {
|
|
12682
|
-
return
|
|
13532
|
+
return json13({ error: merged.error.issues.map((i) => i.message).join("; ") }, 400);
|
|
12683
13533
|
}
|
|
12684
13534
|
engine.setRules(rules.map((r) => r.id === id ? merged.data : r));
|
|
12685
|
-
return
|
|
13535
|
+
return json13({ ok: true, rule: merged.data });
|
|
12686
13536
|
}
|
|
12687
13537
|
}
|
|
12688
13538
|
if (p === "/api/alerts/test" && req.method === "POST") {
|
|
12689
13539
|
const body = await req.json();
|
|
12690
13540
|
if (!channels || !body?.channel)
|
|
12691
|
-
return
|
|
13541
|
+
return json13({ error: "channel is required" }, 400);
|
|
12692
13542
|
try {
|
|
12693
13543
|
const result = await deliver(body.channel, channels, {
|
|
12694
13544
|
ruleId: "test",
|
|
@@ -12698,20 +13548,20 @@ async function alertRoutes(req, url, db) {
|
|
|
12698
13548
|
body: "If you can read this, this channel is configured correctly.",
|
|
12699
13549
|
at: Date.now()
|
|
12700
13550
|
});
|
|
12701
|
-
return
|
|
13551
|
+
return json13(result);
|
|
12702
13552
|
} catch (e) {
|
|
12703
13553
|
logger.error(`Alert channel test failed: ${logError(e)}`);
|
|
12704
|
-
return
|
|
13554
|
+
return json13({ error: clientError(e) }, 502);
|
|
12705
13555
|
}
|
|
12706
13556
|
}
|
|
12707
13557
|
if (p === "/api/alerts/preview" && req.method === "POST") {
|
|
12708
13558
|
const parsed = AlertRuleSchema.safeParse(await req.json());
|
|
12709
13559
|
if (!parsed.success) {
|
|
12710
|
-
return
|
|
13560
|
+
return json13({ error: parsed.error.issues.map((i) => i.message).join("; ") }, 400);
|
|
12711
13561
|
}
|
|
12712
13562
|
const hours = Number(url.searchParams.get("hours") ?? 24);
|
|
12713
13563
|
if (!db) {
|
|
12714
|
-
return
|
|
13564
|
+
return json13({ hours, sampled: 0, fires: 0, resolves: 0, matched: 0, noHistory: true });
|
|
12715
13565
|
}
|
|
12716
13566
|
const events = db.query({ since: Date.now() - hours * 3600000, limit: 5000 }).map((e) => ({
|
|
12717
13567
|
ts: e.ts,
|
|
@@ -12720,7 +13570,7 @@ async function alertRoutes(req, url, db) {
|
|
|
12720
13570
|
risk: e.risk,
|
|
12721
13571
|
isError: e.isError
|
|
12722
13572
|
}));
|
|
12723
|
-
return
|
|
13573
|
+
return json13({ hours, sampled: events.length, ...previewRule(parsed.data, events) });
|
|
12724
13574
|
}
|
|
12725
13575
|
return null;
|
|
12726
13576
|
}
|
|
@@ -12732,7 +13582,7 @@ var relation = object({ from: name, to: name, relationType: name }).strict();
|
|
|
12732
13582
|
var list2 = (schema) => array(schema).min(1).max(100);
|
|
12733
13583
|
var count2 = (value, fallback, max) => exports_coerce.number().int().min(0).max(max).parse(value ?? fallback);
|
|
12734
13584
|
var configuring = false;
|
|
12735
|
-
function
|
|
13585
|
+
function json14(body, status = 200) {
|
|
12736
13586
|
return Response.json(body, { status, headers: { "cache-control": "no-store" } });
|
|
12737
13587
|
}
|
|
12738
13588
|
async function body(req) {
|
|
@@ -12754,14 +13604,14 @@ async function memoryRoutes(req, url) {
|
|
|
12754
13604
|
stats = (await getMemoryStore()).stats();
|
|
12755
13605
|
} catch {}
|
|
12756
13606
|
}
|
|
12757
|
-
return
|
|
13607
|
+
return json14({
|
|
12758
13608
|
...cfg.memory,
|
|
12759
13609
|
stats
|
|
12760
13610
|
});
|
|
12761
13611
|
}
|
|
12762
13612
|
if (p === "/api/memory/config" && req.method === "POST") {
|
|
12763
13613
|
if (configuring)
|
|
12764
|
-
return
|
|
13614
|
+
return json14({ error: "Memory configuration is being saved. Retry shortly." }, 409);
|
|
12765
13615
|
const update = object({
|
|
12766
13616
|
dbPath: string().trim().min(1).max(4096).optional(),
|
|
12767
13617
|
enabled: boolean().optional()
|
|
@@ -12770,13 +13620,13 @@ async function memoryRoutes(req, url) {
|
|
|
12770
13620
|
try {
|
|
12771
13621
|
const next = { ...cfg, memory: { ...cfg.memory, ...update } };
|
|
12772
13622
|
if (next.memory.enabled === cfg.memory.enabled && next.memory.dbPath === cfg.memory.dbPath)
|
|
12773
|
-
return
|
|
13623
|
+
return json14({ ok: true, ...cfg.memory });
|
|
12774
13624
|
const prepared = next.memory.enabled ? await openMemoryStore(next.memory.dbPath) : null;
|
|
12775
13625
|
try {
|
|
12776
13626
|
atomicWrite(getConfigSource2().path, serializeConfig(next));
|
|
12777
13627
|
} catch {
|
|
12778
13628
|
prepared?.close();
|
|
12779
|
-
return
|
|
13629
|
+
return json14({
|
|
12780
13630
|
error: "Could not persist memory configuration; the previous configuration is still active."
|
|
12781
13631
|
}, 500);
|
|
12782
13632
|
}
|
|
@@ -12785,52 +13635,52 @@ async function memoryRoutes(req, url) {
|
|
|
12785
13635
|
installMemoryStore(prepared);
|
|
12786
13636
|
else
|
|
12787
13637
|
closeMemoryStore();
|
|
12788
|
-
return
|
|
13638
|
+
return json14({ ok: true, ...next.memory, stats: prepared?.stats() ?? null });
|
|
12789
13639
|
} finally {
|
|
12790
13640
|
configuring = false;
|
|
12791
13641
|
}
|
|
12792
13642
|
}
|
|
12793
13643
|
if (!cfg.memory.enabled)
|
|
12794
|
-
return
|
|
13644
|
+
return json14({ error: "Knowledge memory is disabled. Enable it in Memory settings." }, 503);
|
|
12795
13645
|
const store = await getMemoryStore();
|
|
12796
13646
|
if (p === "/api/memory/scope" && req.method === "GET")
|
|
12797
|
-
return
|
|
13647
|
+
return json14(store.scope(name.parse(url.searchParams.get("entityName"))));
|
|
12798
13648
|
if (p === "/api/memory/scope" && req.method === "POST")
|
|
12799
|
-
return
|
|
13649
|
+
return json14(store.setScope(ScopeSchema.parse(await body(req))));
|
|
12800
13650
|
if (p === "/api/memory/summary" && req.method === "GET")
|
|
12801
|
-
return
|
|
13651
|
+
return json14({ stats: store.stats(), health: store.health() });
|
|
12802
13652
|
if (p === "/api/memory/facts" && req.method === "GET") {
|
|
12803
13653
|
const values = Object.fromEntries(url.searchParams);
|
|
12804
13654
|
delete values.token;
|
|
12805
|
-
return
|
|
13655
|
+
return json14(store.facts(BrowseSchema.parse({
|
|
12806
13656
|
...values,
|
|
12807
13657
|
limit: count2(url.searchParams.get("limit"), 30, 100),
|
|
12808
13658
|
offset: count2(url.searchParams.get("offset"), 0, 1e6)
|
|
12809
13659
|
})));
|
|
12810
13660
|
}
|
|
12811
13661
|
if (p === "/api/memory/facts" && req.method === "POST")
|
|
12812
|
-
return
|
|
13662
|
+
return json14(store.remember(RememberSchema.parse(await body(req))));
|
|
12813
13663
|
if (p === "/api/memory/facts/revise" && req.method === "POST")
|
|
12814
|
-
return
|
|
13664
|
+
return json14(store.revise(ReviseSchema.parse(await body(req))));
|
|
12815
13665
|
if (p === "/api/memory/recall" && req.method === "POST")
|
|
12816
|
-
return
|
|
13666
|
+
return json14(store.recall(RecallSchema.parse(await body(req))));
|
|
12817
13667
|
const history = p.match(/^\/api\/memory\/facts\/(\d+)\/history$/);
|
|
12818
13668
|
if (history && req.method === "GET")
|
|
12819
|
-
return
|
|
13669
|
+
return json14(store.history(exports_coerce.number().int().positive().parse(history[1])));
|
|
12820
13670
|
if (p === "/api/memory/entities" && req.method === "GET")
|
|
12821
|
-
return
|
|
13671
|
+
return json14(store.listEntities(string().max(500).parse(url.searchParams.get("q") ?? ""), count2(url.searchParams.get("limit"), 100, 100), count2(url.searchParams.get("offset"), 0, 1e6)));
|
|
12822
13672
|
if (p === "/api/memory/graph" && req.method === "GET")
|
|
12823
|
-
return
|
|
13673
|
+
return json14(store.readGraph());
|
|
12824
13674
|
if (p === "/api/memory/stats" && req.method === "GET")
|
|
12825
|
-
return
|
|
13675
|
+
return json14(store.stats());
|
|
12826
13676
|
if (p === "/api/memory/search" && req.method === "GET")
|
|
12827
|
-
return
|
|
13677
|
+
return json14(store.searchNodes(string().max(500).parse(url.searchParams.get("q") ?? ""), count2(url.searchParams.get("limit"), 50, 100)));
|
|
12828
13678
|
if (p === "/api/memory/activity" && req.method === "GET")
|
|
12829
|
-
return
|
|
13679
|
+
return json14(store.activity(count2(url.searchParams.get("limit"), 50, 100), url.searchParams.has("since") ? count2(url.searchParams.get("since"), 0, Number.MAX_SAFE_INTEGER) : undefined, url.searchParams.get("changesOnly") === "true"));
|
|
12830
13680
|
const entity = p.match(/^\/api\/memory\/entity\/(.+)$/);
|
|
12831
13681
|
if (entity && req.method === "GET") {
|
|
12832
13682
|
const graph = store.openNodes([name.parse(decodeURIComponent(entity[1]))]);
|
|
12833
|
-
return graph.entities.length ?
|
|
13683
|
+
return graph.entities.length ? json14({ entity: graph.entities[0], relations: graph.relations }) : json14({ error: "Entity not found" }, 404);
|
|
12834
13684
|
}
|
|
12835
13685
|
if (p === "/api/memory/entities" && req.method === "POST") {
|
|
12836
13686
|
const data = object({
|
|
@@ -12841,45 +13691,45 @@ async function memoryRoutes(req, url) {
|
|
|
12841
13691
|
}).strict())
|
|
12842
13692
|
}).strict().parse(await body(req));
|
|
12843
13693
|
const created = store.createEntities(data.entities);
|
|
12844
|
-
return
|
|
13694
|
+
return json14({ created, count: created.length });
|
|
12845
13695
|
}
|
|
12846
13696
|
if (p === "/api/memory/relations" && (req.method === "POST" || req.method === "DELETE")) {
|
|
12847
13697
|
const data = object({ relations: list2(relation) }).strict().parse(await body(req));
|
|
12848
13698
|
if (req.method === "DELETE")
|
|
12849
|
-
return
|
|
13699
|
+
return json14({ removed: store.deleteRelations(data.relations) });
|
|
12850
13700
|
const created = store.createRelations(data.relations);
|
|
12851
|
-
return
|
|
13701
|
+
return json14({ created, count: created.length });
|
|
12852
13702
|
}
|
|
12853
13703
|
if (p === "/api/memory/observations" && req.method === "POST") {
|
|
12854
13704
|
const data = object({
|
|
12855
13705
|
observations: list2(object({ entityName: name, contents: list2(content) }).strict())
|
|
12856
13706
|
}).strict().parse(await body(req));
|
|
12857
|
-
return
|
|
13707
|
+
return json14({ results: store.addObservations(data.observations) });
|
|
12858
13708
|
}
|
|
12859
13709
|
if (p === "/api/memory/entities" && req.method === "DELETE") {
|
|
12860
13710
|
const data = object({ names: list2(name) }).strict().parse(await body(req));
|
|
12861
|
-
return
|
|
13711
|
+
return json14({ removed: store.deleteEntities(data.names) });
|
|
12862
13712
|
}
|
|
12863
13713
|
if (p === "/api/memory/observations" && req.method === "DELETE") {
|
|
12864
13714
|
const data = object({
|
|
12865
13715
|
deletions: list2(object({ entityName: name, observations: list2(content) }).strict())
|
|
12866
13716
|
}).strict().parse(await body(req));
|
|
12867
|
-
return
|
|
13717
|
+
return json14({ removed: store.deleteObservations(data.deletions) });
|
|
12868
13718
|
}
|
|
12869
|
-
return
|
|
13719
|
+
return json14({ error: "Unknown memory endpoint or method" }, 404);
|
|
12870
13720
|
} catch (error) {
|
|
12871
13721
|
if (error instanceof ZodError)
|
|
12872
|
-
return
|
|
13722
|
+
return json14({ error: error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, 400);
|
|
12873
13723
|
if (error instanceof SyntaxError || error instanceof URIError)
|
|
12874
|
-
return
|
|
13724
|
+
return json14({ error: "Invalid memory request" }, 400);
|
|
12875
13725
|
const message = error instanceof Error ? error.message : "Memory operation failed";
|
|
12876
13726
|
if (message.includes("UNIQUE constraint"))
|
|
12877
|
-
return
|
|
13727
|
+
return json14({ error: "This entity already has an identical memory. Edit the existing record." }, 409);
|
|
12878
13728
|
if (message.includes("changed since"))
|
|
12879
|
-
return
|
|
13729
|
+
return json14({ error: message }, 409);
|
|
12880
13730
|
if (/not found|credential vault|already exists|too large|Invalid scope/.test(message))
|
|
12881
|
-
return
|
|
12882
|
-
return
|
|
13731
|
+
return json14({ error: message }, 400);
|
|
13732
|
+
return json14({ error: "Memory storage is unavailable. Check its path and permissions, then retry." }, 503);
|
|
12883
13733
|
}
|
|
12884
13734
|
}
|
|
12885
13735
|
|
|
@@ -12906,7 +13756,7 @@ var dashboardSocketLifecycle = {
|
|
|
12906
13756
|
// src/observability/dashboard.ts
|
|
12907
13757
|
var SERVER_TAG3 = "mikrotik-mcp";
|
|
12908
13758
|
var JSON_HEADERS12 = { "content-type": "application/json; charset=utf-8" };
|
|
12909
|
-
function
|
|
13759
|
+
function json15(body, status = 200) {
|
|
12910
13760
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS12 });
|
|
12911
13761
|
}
|
|
12912
13762
|
function restartProcess() {
|
|
@@ -12955,7 +13805,7 @@ spawn error: ${String(e)}` });
|
|
|
12955
13805
|
}
|
|
12956
13806
|
function dashboardHtml() {
|
|
12957
13807
|
try {
|
|
12958
|
-
return
|
|
13808
|
+
return readFileSync5(join10(UI_DIST_DIR, "observability.html"), "utf8");
|
|
12959
13809
|
} catch {
|
|
12960
13810
|
return `<!doctype html><meta charset=utf-8><body style="font:14px system-ui;padding:24px;background:#0b0d10;color:#e8eaed">
|
|
12961
13811
|
<h2>MikroTik MCP \u2014 Observability Dashboard</h2>
|
|
@@ -13191,26 +14041,26 @@ async function configRoutes(req, url, admin) {
|
|
|
13191
14041
|
const p = url.pathname;
|
|
13192
14042
|
const scope = url.searchParams.get("scope");
|
|
13193
14043
|
if (req.method === "POST" && ["/api/config", "/api/config/validate", "/api/config/preview"].includes(p) && scope !== null && scope !== "devices" && scope !== "server" && scope !== "serviceProbes")
|
|
13194
|
-
return
|
|
14044
|
+
return json15({ ok: false, error: "Unknown configuration scope" }, 400);
|
|
13195
14045
|
const mergeDraft = (raw) => {
|
|
13196
14046
|
const current = getConfig();
|
|
13197
14047
|
return mergeConfigDraft(scope === "devices" || scope === "server" || scope === "serviceProbes" ? scopeConfigDraft(raw, current, scope) : raw, current);
|
|
13198
14048
|
};
|
|
13199
14049
|
if (p === "/api/config-schema" && req.method === "GET") {
|
|
13200
|
-
return
|
|
14050
|
+
return json15(configSchemaJson());
|
|
13201
14051
|
}
|
|
13202
14052
|
if (p === "/api/config/ssh-keys" && req.method === "POST")
|
|
13203
14053
|
return createSshKeyResponse(req);
|
|
13204
14054
|
if (p === "/api/config/ssh-keys" && req.method === "GET") {
|
|
13205
14055
|
const origin = req.headers.get("origin");
|
|
13206
14056
|
if (origin && origin !== url.origin || req.headers.get("sec-fetch-site") === "cross-site")
|
|
13207
|
-
return
|
|
14057
|
+
return json15({ error: "SSH key selection requires a same-origin dashboard request." }, 403);
|
|
13208
14058
|
const paths = Object.values(getConfig().devices).flatMap((device) => [device.keyFilename, device.jumpHost?.keyFilename].filter((p) => !!p));
|
|
13209
14059
|
return Response.json(await listSshKeys(paths), { headers: { "cache-control": "no-store" } });
|
|
13210
14060
|
}
|
|
13211
14061
|
if (p === "/api/config/validate" && req.method === "POST") {
|
|
13212
14062
|
const merged = mergeDraft(await readJson(req));
|
|
13213
|
-
return
|
|
14063
|
+
return json15(validateConfig(merged));
|
|
13214
14064
|
}
|
|
13215
14065
|
if (p === "/api/config/test-device" && req.method === "POST") {
|
|
13216
14066
|
const body = await readJson(req);
|
|
@@ -13218,33 +14068,33 @@ async function configRoutes(req, url, admin) {
|
|
|
13218
14068
|
const merged = mergeDeviceDraft(body?.config, name, getConfig().devices);
|
|
13219
14069
|
const target = merged;
|
|
13220
14070
|
if (![target?.host, target?.mac].some((value) => typeof value === "string" && value.trim().length > 0))
|
|
13221
|
-
return
|
|
14071
|
+
return json15({ ok: false, error: "Enter a Host / IP or MAC address before testing." }, 400);
|
|
13222
14072
|
const parsed = DeviceConfigSchema2.safeParse(merged);
|
|
13223
14073
|
if (!parsed.success)
|
|
13224
|
-
return
|
|
14074
|
+
return json15({ ok: false, errors: issues(parsed.error) }, 400);
|
|
13225
14075
|
let devices;
|
|
13226
14076
|
if (body.devices !== undefined) {
|
|
13227
14077
|
const draft = mergeConfigDraft({ devices: body.devices }, getConfig());
|
|
13228
14078
|
const inventory = record(string(), DeviceConfigSchema2).safeParse(draft.devices);
|
|
13229
14079
|
if (!inventory.success)
|
|
13230
|
-
return
|
|
14080
|
+
return json15({ ok: false, errors: issues(inventory.error) }, 400);
|
|
13231
14081
|
devices = { ...inventory.data, [name]: parsed.data };
|
|
13232
14082
|
}
|
|
13233
14083
|
const status = await probeDevice(`config-test:${name}`, parsed.data, devices);
|
|
13234
|
-
return
|
|
14084
|
+
return json15({ ok: true, status });
|
|
13235
14085
|
}
|
|
13236
14086
|
if (p === "/api/config/preview" && req.method === "POST") {
|
|
13237
14087
|
const before = JSON.stringify(redact(getConfig()), null, 2);
|
|
13238
14088
|
const after = JSON.stringify(redact(mergeDraft(await readJson(req))), null, 2);
|
|
13239
14089
|
const d = diffLines(before, after, { fromLabel: "current", toLabel: "edited" });
|
|
13240
|
-
return
|
|
14090
|
+
return json15({ summary: d.summary, unified: d.unified });
|
|
13241
14091
|
}
|
|
13242
14092
|
if (p === "/api/config" && req.method === "POST") {
|
|
13243
14093
|
const body = await readJson(req);
|
|
13244
14094
|
const merged = mergeDraft(body?.config);
|
|
13245
14095
|
const v = validateConfig(merged);
|
|
13246
14096
|
if (!v.ok || !v.value)
|
|
13247
|
-
return
|
|
14097
|
+
return json15({ ok: false, errors: v.errors }, 400);
|
|
13248
14098
|
const prev = getConfig();
|
|
13249
14099
|
const before = JSON.stringify(redact(prev), null, 2);
|
|
13250
14100
|
const after = JSON.stringify(redact(v.value), null, 2);
|
|
@@ -13253,7 +14103,7 @@ async function configRoutes(req, url, admin) {
|
|
|
13253
14103
|
const nextDevs = Object.keys(v.value.devices);
|
|
13254
14104
|
const devicesChanged = prevDevs.length !== nextDevs.length || prevDevs.some((d) => !nextDevs.includes(d));
|
|
13255
14105
|
const res = admin.applyConfig(v.value, clampRollback(body?.rollbackMs));
|
|
13256
|
-
return
|
|
14106
|
+
return json15({
|
|
13257
14107
|
ok: true,
|
|
13258
14108
|
...res,
|
|
13259
14109
|
config: redact(v.value),
|
|
@@ -13267,18 +14117,18 @@ async function configRoutes(req, url, admin) {
|
|
|
13267
14117
|
const kept = admin.keepConfig(String(body?.pendingId ?? ""));
|
|
13268
14118
|
if (kept)
|
|
13269
14119
|
recordVersion(getConfig(), "auto", Date.now());
|
|
13270
|
-
return
|
|
14120
|
+
return json15({ kept });
|
|
13271
14121
|
}
|
|
13272
14122
|
if (p === "/api/config/rollback" && req.method === "POST") {
|
|
13273
14123
|
const body = await readJson(req);
|
|
13274
14124
|
const rolledBack = admin.rollback(String(body?.pendingId ?? ""));
|
|
13275
|
-
return
|
|
14125
|
+
return json15({ rolledBack, config: redact(getConfig()) });
|
|
13276
14126
|
}
|
|
13277
14127
|
if (p === "/api/reload" && req.method === "POST") {
|
|
13278
14128
|
const body = await readJson(req);
|
|
13279
14129
|
if (body?.hard === true) {
|
|
13280
14130
|
const relaunched = restartProcess();
|
|
13281
|
-
return
|
|
14131
|
+
return json15({
|
|
13282
14132
|
ok: true,
|
|
13283
14133
|
mode: "restart",
|
|
13284
14134
|
note: relaunched ? "Restarting now \u2014 a fresh server process was launched and will bind the same port(s) in ~1.5s. Reconnect shortly." : "Could not self-relaunch; the process is exiting. It only comes back if a supervisor respawns it."
|
|
@@ -13289,10 +14139,10 @@ async function configRoutes(req, url, admin) {
|
|
|
13289
14139
|
setConfig(cfg);
|
|
13290
14140
|
const devices = Object.keys(cfg.devices);
|
|
13291
14141
|
logger.info(`Config reloaded from source \u2014 ${devices.length} device(s): ${devices.join(", ")}`);
|
|
13292
|
-
return
|
|
14142
|
+
return json15({ ok: true, mode: "config", count: devices.length, devices });
|
|
13293
14143
|
} catch (e) {
|
|
13294
14144
|
logger.error(`Config reload failed: ${logError(e)}`);
|
|
13295
|
-
return
|
|
14145
|
+
return json15({ ok: false, error: clientError(e) }, 500);
|
|
13296
14146
|
}
|
|
13297
14147
|
}
|
|
13298
14148
|
if (p === "/api/config/history" && req.method === "GET") {
|
|
@@ -13308,55 +14158,55 @@ async function configRoutes(req, url, admin) {
|
|
|
13308
14158
|
} catch {}
|
|
13309
14159
|
return { ...v, drift: { added, removed } };
|
|
13310
14160
|
});
|
|
13311
|
-
return
|
|
14161
|
+
return json15({ versions, bytes: historyBytes(), retention: AUTO_RETENTION });
|
|
13312
14162
|
}
|
|
13313
14163
|
if (p === "/api/config/history/get" && req.method === "GET") {
|
|
13314
14164
|
const id = url.searchParams.get("id");
|
|
13315
14165
|
if (!id)
|
|
13316
|
-
return
|
|
14166
|
+
return json15({ error: "id required" }, 400);
|
|
13317
14167
|
try {
|
|
13318
14168
|
const v = readVersion(id);
|
|
13319
|
-
return
|
|
14169
|
+
return json15({
|
|
13320
14170
|
ts: v.ts,
|
|
13321
14171
|
kind: v.kind,
|
|
13322
14172
|
label: v.label,
|
|
13323
14173
|
config: JSON.stringify(redact(v.config), null, 2)
|
|
13324
14174
|
});
|
|
13325
14175
|
} catch {
|
|
13326
|
-
return
|
|
14176
|
+
return json15({ error: "not found" }, 404);
|
|
13327
14177
|
}
|
|
13328
14178
|
}
|
|
13329
14179
|
if (p === "/api/config/history/diff" && req.method === "GET") {
|
|
13330
14180
|
const id = url.searchParams.get("id");
|
|
13331
14181
|
if (!id)
|
|
13332
|
-
return
|
|
14182
|
+
return json15({ error: "id required" }, 400);
|
|
13333
14183
|
try {
|
|
13334
14184
|
const before = JSON.stringify(redact(readVersion(id).config), null, 2);
|
|
13335
14185
|
const after = JSON.stringify(redact(getConfig()), null, 2);
|
|
13336
14186
|
const d = diffLines(before, after, { fromLabel: "this version", toLabel: "current" });
|
|
13337
|
-
return
|
|
14187
|
+
return json15({ summary: d.summary, unified: d.unified });
|
|
13338
14188
|
} catch {
|
|
13339
|
-
return
|
|
14189
|
+
return json15({ error: "not found" }, 404);
|
|
13340
14190
|
}
|
|
13341
14191
|
}
|
|
13342
14192
|
if (p === "/api/config/history/checkpoint" && req.method === "POST") {
|
|
13343
14193
|
const b = await readJson(req);
|
|
13344
14194
|
const label = b?.label?.trim() || "checkpoint";
|
|
13345
|
-
return
|
|
14195
|
+
return json15({ ok: true, version: recordVersion(getConfig(), "checkpoint", Date.now(), label) });
|
|
13346
14196
|
}
|
|
13347
14197
|
if (p === "/api/config/history/restore" && req.method === "POST") {
|
|
13348
14198
|
const b = await readJson(req);
|
|
13349
14199
|
if (!b?.id)
|
|
13350
|
-
return
|
|
14200
|
+
return json15({ error: "id required" }, 400);
|
|
13351
14201
|
let target;
|
|
13352
14202
|
try {
|
|
13353
14203
|
target = readVersion(b.id);
|
|
13354
14204
|
} catch {
|
|
13355
|
-
return
|
|
14205
|
+
return json15({ error: "not found" }, 404);
|
|
13356
14206
|
}
|
|
13357
14207
|
const v = validateConfig(target.config);
|
|
13358
14208
|
if (!v.ok || !v.value)
|
|
13359
|
-
return
|
|
14209
|
+
return json15({ ok: false, errors: v.errors }, 400);
|
|
13360
14210
|
recordVersion(getConfig(), "auto", Date.now(), "before restore");
|
|
13361
14211
|
setConfig(v.value);
|
|
13362
14212
|
let persisted = true;
|
|
@@ -13367,13 +14217,13 @@ async function configRoutes(req, url, admin) {
|
|
|
13367
14217
|
}
|
|
13368
14218
|
const label = target.label ? `restored "${target.label}"` : `restored ${b.id}`;
|
|
13369
14219
|
recordVersion(getConfig(), "auto", Date.now(), label);
|
|
13370
|
-
return
|
|
14220
|
+
return json15({ ok: true, persisted, restored: b.id, config: redact(getConfig()) });
|
|
13371
14221
|
}
|
|
13372
14222
|
if (p === "/api/config/history/delete" && req.method === "POST") {
|
|
13373
14223
|
const b = await readJson(req);
|
|
13374
14224
|
if (!b?.id)
|
|
13375
|
-
return
|
|
13376
|
-
return deleteVersion(b.id) ?
|
|
14225
|
+
return json15({ error: "id required" }, 400);
|
|
14226
|
+
return deleteVersion(b.id) ? json15({ ok: true }) : json15({ error: "not found" }, 404);
|
|
13377
14227
|
}
|
|
13378
14228
|
return null;
|
|
13379
14229
|
}
|
|
@@ -13384,7 +14234,7 @@ async function modulesRoutes(req, url) {
|
|
|
13384
14234
|
if (p === "/api/modules" && req.method === "GET") {
|
|
13385
14235
|
const cfg = getConfig();
|
|
13386
14236
|
const src = getConfigSource2();
|
|
13387
|
-
return
|
|
14237
|
+
return json15({
|
|
13388
14238
|
...moduleSurface(cfg.tools),
|
|
13389
14239
|
filter: cfg.tools,
|
|
13390
14240
|
source: src,
|
|
@@ -13394,11 +14244,11 @@ async function modulesRoutes(req, url) {
|
|
|
13394
14244
|
if (p === "/api/modules/toggle" && req.method === "POST") {
|
|
13395
14245
|
const b = await readJson(req);
|
|
13396
14246
|
if (typeof b?.slug !== "string" || typeof b?.enabled !== "boolean") {
|
|
13397
|
-
return
|
|
14247
|
+
return json15({ error: "slug (string) and enabled (boolean) are required" }, 400);
|
|
13398
14248
|
}
|
|
13399
14249
|
const mod = moduleCatalog2.find((m) => m.slug.toLowerCase() === b.slug.toLowerCase());
|
|
13400
14250
|
if (!mod)
|
|
13401
|
-
return
|
|
14251
|
+
return json15({ error: `unknown module: ${b.slug}` }, 404);
|
|
13402
14252
|
const cfg = getConfig();
|
|
13403
14253
|
const nextTools = ToolFilterSchema2.parse(applyModuleToggle(cfg.tools, mod.slug, b.enabled));
|
|
13404
14254
|
const next = { ...cfg, tools: nextTools };
|
|
@@ -13414,7 +14264,7 @@ async function modulesRoutes(req, url) {
|
|
|
13414
14264
|
if (persisted) {
|
|
13415
14265
|
recordVersion(getConfig(), "auto", Date.now(), `module ${b.enabled ? "enabled" : "disabled"}: ${mod.slug}`);
|
|
13416
14266
|
}
|
|
13417
|
-
return
|
|
14267
|
+
return json15({
|
|
13418
14268
|
ok: true,
|
|
13419
14269
|
persisted,
|
|
13420
14270
|
requiresReconnect: true,
|
|
@@ -13429,7 +14279,7 @@ async function modulesRoutes(req, url) {
|
|
|
13429
14279
|
if (p === "/api/modules/app-views" && req.method === "POST") {
|
|
13430
14280
|
const b = await readJson(req);
|
|
13431
14281
|
if (typeof b?.enabled !== "boolean") {
|
|
13432
|
-
return
|
|
14282
|
+
return json15({ error: "enabled (boolean) is required" }, 400);
|
|
13433
14283
|
}
|
|
13434
14284
|
const cfg = getConfig();
|
|
13435
14285
|
const next = { ...cfg, mcp: { ...cfg.mcp, appViews: b.enabled } };
|
|
@@ -13445,7 +14295,7 @@ async function modulesRoutes(req, url) {
|
|
|
13445
14295
|
if (persisted) {
|
|
13446
14296
|
recordVersion(getConfig(), "auto", Date.now(), `app views ${b.enabled ? "enabled" : "disabled"}`);
|
|
13447
14297
|
}
|
|
13448
|
-
return
|
|
14298
|
+
return json15({
|
|
13449
14299
|
ok: true,
|
|
13450
14300
|
persisted,
|
|
13451
14301
|
requiresReconnect: true,
|
|
@@ -13459,11 +14309,11 @@ async function modulesRoutes(req, url) {
|
|
|
13459
14309
|
async function captureRoutes(req, url) {
|
|
13460
14310
|
const p = url.pathname;
|
|
13461
14311
|
if (p === "/api/capture/status" && req.method === "GET") {
|
|
13462
|
-
return
|
|
14312
|
+
return json15(capture.stats());
|
|
13463
14313
|
}
|
|
13464
14314
|
if (p === "/api/capture/packets" && req.method === "GET") {
|
|
13465
14315
|
const limit = Number(url.searchParams.get("limit") ?? 200) || 200;
|
|
13466
|
-
return
|
|
14316
|
+
return json15({ packets: capture.recent(limit), stats: capture.stats() });
|
|
13467
14317
|
}
|
|
13468
14318
|
if (p === "/api/capture/pcap" && req.method === "GET") {
|
|
13469
14319
|
return new Response(capture.pcap(), {
|
|
@@ -13475,11 +14325,11 @@ async function captureRoutes(req, url) {
|
|
|
13475
14325
|
}
|
|
13476
14326
|
if (p === "/api/capture/start" && req.method === "POST") {
|
|
13477
14327
|
const body = await readJson(req);
|
|
13478
|
-
return
|
|
14328
|
+
return json15(await capture.start(typeof body?.port === "number" ? body.port : DEFAULT_TZSP_PORT));
|
|
13479
14329
|
}
|
|
13480
14330
|
if (p === "/api/capture/stop" && req.method === "POST") {
|
|
13481
14331
|
capture.stop();
|
|
13482
|
-
return
|
|
14332
|
+
return json15({ ok: true, ...capture.stats() });
|
|
13483
14333
|
}
|
|
13484
14334
|
return null;
|
|
13485
14335
|
}
|
|
@@ -13492,9 +14342,9 @@ async function capsmanRoutes(req, url) {
|
|
|
13492
14342
|
if (req.method === "GET") {
|
|
13493
14343
|
const requested = url.searchParams.get("device");
|
|
13494
14344
|
if (!requested)
|
|
13495
|
-
return
|
|
14345
|
+
return json15({ error: "Select a device first." }, 400);
|
|
13496
14346
|
const device = resolveDeviceName(requested);
|
|
13497
|
-
return
|
|
14347
|
+
return json15({
|
|
13498
14348
|
device,
|
|
13499
14349
|
managers: await readCapsmanManagers(createContext(undefined, device))
|
|
13500
14350
|
});
|
|
@@ -13502,33 +14352,33 @@ async function capsmanRoutes(req, url) {
|
|
|
13502
14352
|
if (req.method === "POST") {
|
|
13503
14353
|
const parsed = capsmanManagerChange.safeParse(await readJson(req));
|
|
13504
14354
|
if (!parsed.success)
|
|
13505
|
-
return
|
|
14355
|
+
return json15({ error: "A device, supported manager, boolean enabled and confirmation are required." }, 400);
|
|
13506
14356
|
const ctx = createContext(undefined, resolveDeviceName(parsed.data.device));
|
|
13507
|
-
return
|
|
14357
|
+
return json15(await setCapsmanManager(ctx, parsed.data));
|
|
13508
14358
|
}
|
|
13509
|
-
return
|
|
14359
|
+
return json15({ error: "Method not allowed" }, 405);
|
|
13510
14360
|
}
|
|
13511
14361
|
if (req.method === "GET") {
|
|
13512
14362
|
const ctx = createContext(undefined, url.searchParams.get("device") ?? undefined);
|
|
13513
14363
|
if (p === "/api/capsman/overview") {
|
|
13514
|
-
return
|
|
14364
|
+
return json15(capsmanOverview(await fetchCapsmanState(ctx)));
|
|
13515
14365
|
}
|
|
13516
14366
|
if (p === "/api/capsman/clients") {
|
|
13517
14367
|
const state = await fetchCapsmanState(ctx);
|
|
13518
14368
|
const weakDbm = Number.parseInt(url.searchParams.get("weak_dbm") ?? "", 10);
|
|
13519
14369
|
const weak = reportWeakClients(state, Number.isFinite(weakDbm) ? weakDbm : undefined);
|
|
13520
|
-
return
|
|
14370
|
+
return json15({ clients: state.clients, weak });
|
|
13521
14371
|
}
|
|
13522
14372
|
if (p === "/api/capsman/audit") {
|
|
13523
|
-
return
|
|
14373
|
+
return json15(runCapsmanAudit(await fetchCapsmanState(ctx)));
|
|
13524
14374
|
}
|
|
13525
14375
|
if (p === "/api/capsman/trends") {
|
|
13526
14376
|
if (!capsmanStore)
|
|
13527
|
-
return
|
|
14377
|
+
return json15({ error: "capsman store not active" }, 503);
|
|
13528
14378
|
const device = resolveDeviceName(url.searchParams.get("device") ?? undefined);
|
|
13529
14379
|
const days = daysParam(url, 7, 30);
|
|
13530
14380
|
const series = capsmanStore.radioSeries(device, Date.now() - days * 86400000);
|
|
13531
|
-
return
|
|
14381
|
+
return json15({ series, days });
|
|
13532
14382
|
}
|
|
13533
14383
|
return null;
|
|
13534
14384
|
}
|
|
@@ -13539,45 +14389,45 @@ async function capsmanRoutes(req, url) {
|
|
|
13539
14389
|
if (p === "/api/capsman/apply/steer") {
|
|
13540
14390
|
const client = state.clients.find((c) => c.mac.toLowerCase() === (body.mac ?? "").toLowerCase());
|
|
13541
14391
|
if (!client)
|
|
13542
|
-
return
|
|
14392
|
+
return json15({ ok: false, error: "client not associated" }, 400);
|
|
13543
14393
|
if (steerAlreadyPresent(state, body.mac ?? "")) {
|
|
13544
|
-
return
|
|
14394
|
+
return json15({ ok: true, message: "already steered (no-op)" });
|
|
13545
14395
|
}
|
|
13546
14396
|
const mode = body.mode === "soft" ? "soft" : "hard";
|
|
13547
14397
|
const commands = buildSteerCommands(state, body.mac ?? "", client.radioId, mode);
|
|
13548
14398
|
if (!body.confirm)
|
|
13549
|
-
return
|
|
13550
|
-
return
|
|
14399
|
+
return json15({ ok: true, preview: commands });
|
|
14400
|
+
return json15(await applyCapsmanWrites(ctx, commands, `pre-steer-${body.mac}`));
|
|
13551
14401
|
}
|
|
13552
14402
|
if (p === "/api/capsman/apply/load-balance") {
|
|
13553
14403
|
const plan = loadBalancePlan(state);
|
|
13554
14404
|
const commands = buildLoadBalanceCommands(state, plan);
|
|
13555
14405
|
if (!body.confirm)
|
|
13556
|
-
return
|
|
13557
|
-
return
|
|
14406
|
+
return json15({ ok: true, preview: commands, plan });
|
|
14407
|
+
return json15(await applyCapsmanWrites(ctx, commands, "pre-load-balance"));
|
|
13558
14408
|
}
|
|
13559
14409
|
if (p === "/api/capsman/apply/channel-plan") {
|
|
13560
14410
|
if (state.path === "/caps-man") {
|
|
13561
|
-
return
|
|
14411
|
+
return json15({ ok: false, error: "channel-plan apply is v7 /interface wifi only" }, 400);
|
|
13562
14412
|
}
|
|
13563
14413
|
const commands = buildChannelPlanCommands(state);
|
|
13564
14414
|
if (!body.confirm)
|
|
13565
|
-
return
|
|
13566
|
-
return
|
|
14415
|
+
return json15({ ok: true, preview: commands });
|
|
14416
|
+
return json15(await applyCapsmanWrites(ctx, commands, "pre-channel-plan"));
|
|
13567
14417
|
}
|
|
13568
14418
|
if (p === "/api/capsman/apply/ft") {
|
|
13569
14419
|
const commands = buildFtCommands(state);
|
|
13570
14420
|
if (!body.confirm)
|
|
13571
|
-
return
|
|
13572
|
-
return
|
|
14421
|
+
return json15({ ok: true, preview: commands });
|
|
14422
|
+
return json15(await applyCapsmanWrites(ctx, commands, "pre-ft"));
|
|
13573
14423
|
}
|
|
13574
14424
|
if (p === "/api/capsman/apply/ha") {
|
|
13575
14425
|
const commands = buildHaCommands(state);
|
|
13576
14426
|
const guidance = haGuidance(state);
|
|
13577
14427
|
if (!body.confirm)
|
|
13578
|
-
return
|
|
14428
|
+
return json15({ ok: true, preview: commands, guidance });
|
|
13579
14429
|
const res = await applyCapsmanWrites(ctx, commands, "pre-ha");
|
|
13580
|
-
return
|
|
14430
|
+
return json15({ ...res, guidance });
|
|
13581
14431
|
}
|
|
13582
14432
|
}
|
|
13583
14433
|
return null;
|
|
@@ -13603,31 +14453,31 @@ async function clientsRoutes(req, url) {
|
|
|
13603
14453
|
const deviceFromQuery = () => url.searchParams.get("device") ?? undefined;
|
|
13604
14454
|
if (p === "/api/clients" && req.method === "GET") {
|
|
13605
14455
|
const ctx = createContext(undefined, deviceFromQuery());
|
|
13606
|
-
return
|
|
14456
|
+
return json15(devicesView(await fetchDevices(ctx)));
|
|
13607
14457
|
}
|
|
13608
14458
|
if (p === "/api/clients/traffic" && req.method === "GET") {
|
|
13609
14459
|
const ip = url.searchParams.get("ip");
|
|
13610
14460
|
if (!ip)
|
|
13611
|
-
return
|
|
14461
|
+
return json15({ error: "ip required" }, 400);
|
|
13612
14462
|
const ctx = createContext(undefined, deviceFromQuery());
|
|
13613
|
-
return
|
|
14463
|
+
return json15(await sampleDeviceTraffic(ctx, ip));
|
|
13614
14464
|
}
|
|
13615
14465
|
if (p === "/api/clients/traffic-bulk" && req.method === "GET") {
|
|
13616
|
-
return
|
|
14466
|
+
return json15(await readTrafficSample(deviceFromQuery() ?? ""));
|
|
13617
14467
|
}
|
|
13618
14468
|
if (req.method === "POST") {
|
|
13619
14469
|
const b = await readJson(req);
|
|
13620
14470
|
const ctx = createContext(undefined, b?.device);
|
|
13621
14471
|
if (p === "/api/clients/limits") {
|
|
13622
14472
|
if (!b?.ip)
|
|
13623
|
-
return
|
|
13624
|
-
return
|
|
14473
|
+
return json15({ error: "ip required" }, 400);
|
|
14474
|
+
return json15(await setDeviceLimits(ctx, b.ip, { download: b.download, upload: b.upload }));
|
|
13625
14475
|
}
|
|
13626
14476
|
if (!b?.mac)
|
|
13627
|
-
return
|
|
14477
|
+
return json15({ error: "mac required" }, 400);
|
|
13628
14478
|
const run = async (op) => {
|
|
13629
14479
|
const r = await op;
|
|
13630
|
-
return
|
|
14480
|
+
return json15({ ...r, view: r.ok ? devicesView(await fetchDevices(ctx)) : undefined });
|
|
13631
14481
|
};
|
|
13632
14482
|
if (p === "/api/clients/block")
|
|
13633
14483
|
return run(blockDevice(ctx, b.mac, b.comment));
|
|
@@ -13639,12 +14489,12 @@ async function clientsRoutes(req, url) {
|
|
|
13639
14489
|
return run(removeDeviceLease(ctx, b.mac));
|
|
13640
14490
|
if (p === "/api/clients/set-ip") {
|
|
13641
14491
|
if (!b.ip)
|
|
13642
|
-
return
|
|
14492
|
+
return json15({ error: "ip required" }, 400);
|
|
13643
14493
|
return run(setDeviceIp(ctx, b.mac, b.ip));
|
|
13644
14494
|
}
|
|
13645
14495
|
if (p === "/api/clients/label") {
|
|
13646
14496
|
if (typeof b.label !== "string")
|
|
13647
|
-
return
|
|
14497
|
+
return json15({ error: "label required" }, 400);
|
|
13648
14498
|
return run(setDeviceLabel(ctx, b.mac, b.label));
|
|
13649
14499
|
}
|
|
13650
14500
|
}
|
|
@@ -13657,14 +14507,14 @@ async function aaaRoutes(req, url) {
|
|
|
13657
14507
|
const deviceFromQuery = () => url.searchParams.get("device") ?? undefined;
|
|
13658
14508
|
if (req.method === "GET") {
|
|
13659
14509
|
if (p === "/api/aaa/entities") {
|
|
13660
|
-
return
|
|
14510
|
+
return json15({ entities: AAA_ENTITIES });
|
|
13661
14511
|
}
|
|
13662
14512
|
if (p === "/api/aaa/reports") {
|
|
13663
14513
|
let filters;
|
|
13664
14514
|
try {
|
|
13665
14515
|
filters = parseUmReportQuery(url.searchParams);
|
|
13666
14516
|
} catch {
|
|
13667
|
-
return
|
|
14517
|
+
return json15({ error: "Invalid report filters" }, 400);
|
|
13668
14518
|
}
|
|
13669
14519
|
const snapshot = await getUmSnapshot(deviceFromQuery(), url.searchParams.get("refresh") === "true", false);
|
|
13670
14520
|
return Response.json("status" in snapshot ? snapshot : buildUmReport(snapshot, filters), {
|
|
@@ -13673,20 +14523,20 @@ async function aaaRoutes(req, url) {
|
|
|
13673
14523
|
});
|
|
13674
14524
|
}
|
|
13675
14525
|
if (p === "/api/aaa/user-counters") {
|
|
13676
|
-
return
|
|
14526
|
+
return json15(await getUmUserCounters(deviceFromQuery()));
|
|
13677
14527
|
}
|
|
13678
14528
|
if (p === "/api/aaa/radius-incoming") {
|
|
13679
|
-
return
|
|
14529
|
+
return json15(await getRadiusIncoming(createContext(undefined, deviceFromQuery())));
|
|
13680
14530
|
}
|
|
13681
14531
|
if (p === "/api/aaa/um-settings") {
|
|
13682
|
-
return
|
|
14532
|
+
return json15(await getUmSettings(createContext(undefined, deviceFromQuery())));
|
|
13683
14533
|
}
|
|
13684
14534
|
const listMatch = p.match(/^\/api\/aaa\/list\/([\w-]+)$/);
|
|
13685
14535
|
if (listMatch) {
|
|
13686
14536
|
const slug = listMatch[1];
|
|
13687
14537
|
if (!AAA_ENTITIES[slug])
|
|
13688
|
-
return
|
|
13689
|
-
return
|
|
14538
|
+
return json15({ error: "unknown entity" }, 404);
|
|
14539
|
+
return json15(await listAaaEntity(createContext(undefined, deviceFromQuery()), slug));
|
|
13690
14540
|
}
|
|
13691
14541
|
return null;
|
|
13692
14542
|
}
|
|
@@ -13694,30 +14544,30 @@ async function aaaRoutes(req, url) {
|
|
|
13694
14544
|
const body = await readJson(req);
|
|
13695
14545
|
const ctx = createContext(undefined, body?.device);
|
|
13696
14546
|
if (p === "/api/aaa/radius-incoming")
|
|
13697
|
-
return
|
|
14547
|
+
return json15(await setRadiusIncoming(ctx, body?.fields ?? {}));
|
|
13698
14548
|
if (p === "/api/aaa/um-settings")
|
|
13699
|
-
return
|
|
14549
|
+
return json15(await setUmSettings(ctx, body?.fields ?? {}));
|
|
13700
14550
|
if (p === "/api/aaa/radius-reset-counters")
|
|
13701
|
-
return
|
|
14551
|
+
return json15(await resetRadiusCounters(ctx));
|
|
13702
14552
|
const slug = body?.slug ?? "";
|
|
13703
14553
|
if (!AAA_ENTITIES[slug])
|
|
13704
|
-
return
|
|
14554
|
+
return json15({ error: "unknown entity" }, 404);
|
|
13705
14555
|
if (p === "/api/aaa/add")
|
|
13706
|
-
return
|
|
14556
|
+
return json15(await addAaaEntity(ctx, slug, body?.fields ?? {}));
|
|
13707
14557
|
if (p === "/api/aaa/update") {
|
|
13708
14558
|
if (!body?.id)
|
|
13709
|
-
return
|
|
13710
|
-
return
|
|
14559
|
+
return json15({ error: "id required" }, 400);
|
|
14560
|
+
return json15(await updateAaaEntity(ctx, slug, body.id, body?.fields ?? {}));
|
|
13711
14561
|
}
|
|
13712
14562
|
if (p === "/api/aaa/remove") {
|
|
13713
14563
|
if (!body?.id)
|
|
13714
|
-
return
|
|
13715
|
-
return
|
|
14564
|
+
return json15({ error: "id required" }, 400);
|
|
14565
|
+
return json15(await removeAaaEntity(ctx, slug, body.id));
|
|
13716
14566
|
}
|
|
13717
14567
|
if (p === "/api/aaa/toggle") {
|
|
13718
14568
|
if (!body?.id)
|
|
13719
|
-
return
|
|
13720
|
-
return
|
|
14569
|
+
return json15({ error: "id required" }, 400);
|
|
14570
|
+
return json15(await toggleAaaEntity(ctx, slug, body.id, body?.enable === true));
|
|
13721
14571
|
}
|
|
13722
14572
|
}
|
|
13723
14573
|
return null;
|
|
@@ -13733,43 +14583,43 @@ async function usageRoutes(req, url) {
|
|
|
13733
14583
|
return null;
|
|
13734
14584
|
if (p === "/api/usage/sampler") {
|
|
13735
14585
|
if (req.method === "GET")
|
|
13736
|
-
return
|
|
14586
|
+
return json15({ intervalMs: getUsageSamplerInterval() });
|
|
13737
14587
|
if (req.method === "POST") {
|
|
13738
14588
|
const b = await readJson(req);
|
|
13739
14589
|
const applied = setUsageSamplerInterval(Number(b?.intervalMs));
|
|
13740
|
-
return
|
|
14590
|
+
return json15({ intervalMs: applied });
|
|
13741
14591
|
}
|
|
13742
14592
|
return null;
|
|
13743
14593
|
}
|
|
13744
14594
|
if (req.method !== "GET")
|
|
13745
14595
|
return null;
|
|
13746
14596
|
if (!usageStore)
|
|
13747
|
-
return
|
|
14597
|
+
return json15({ error: "usage store not active" }, 503);
|
|
13748
14598
|
const device = resolveDeviceName(url.searchParams.get("device") ?? undefined);
|
|
13749
14599
|
const sinceTs = (days) => Date.now() - days * 86400000;
|
|
13750
14600
|
if (p === "/api/usage/um-users") {
|
|
13751
|
-
return
|
|
14601
|
+
return json15({ users: usageStore.umUsers(device) });
|
|
13752
14602
|
}
|
|
13753
14603
|
if (p === "/api/usage/client") {
|
|
13754
14604
|
const ip = url.searchParams.get("ip");
|
|
13755
14605
|
if (!ip)
|
|
13756
|
-
return
|
|
14606
|
+
return json15({ error: "ip required" }, 400);
|
|
13757
14607
|
const series = usageStore.clientDailyUsage(device, ip, sinceTs(daysParam(url, 90, 400)));
|
|
13758
|
-
return
|
|
14608
|
+
return json15(withTotals(series));
|
|
13759
14609
|
}
|
|
13760
14610
|
if (p === "/api/usage/um-user") {
|
|
13761
14611
|
const user = url.searchParams.get("user");
|
|
13762
14612
|
if (!user)
|
|
13763
|
-
return
|
|
14613
|
+
return json15({ error: "user required" }, 400);
|
|
13764
14614
|
const series = usageStore.umUserDailyUsage(device, user, sinceTs(daysParam(url, 90, 400)));
|
|
13765
|
-
return
|
|
14615
|
+
return json15(withTotals(series));
|
|
13766
14616
|
}
|
|
13767
14617
|
if (p === "/api/usage/heatmap") {
|
|
13768
14618
|
const user = url.searchParams.get("user");
|
|
13769
14619
|
const days = usageStore.heatmap(device, user || null, sinceTs(daysParam(url, 371, 400)));
|
|
13770
14620
|
const total = days.reduce((s, d) => s + d.count, 0);
|
|
13771
14621
|
const max = days.reduce((m, d) => Math.max(m, d.count), 0);
|
|
13772
|
-
return
|
|
14622
|
+
return json15({ days, total, max });
|
|
13773
14623
|
}
|
|
13774
14624
|
return null;
|
|
13775
14625
|
}
|
|
@@ -13793,13 +14643,13 @@ async function featureRoutes(req, url) {
|
|
|
13793
14643
|
const cfg = getConfig();
|
|
13794
14644
|
const all = Object.keys(cfg.devices).flatMap((d) => store.list(d, 200, false));
|
|
13795
14645
|
all.sort((a, b) => b.ts - a.ts);
|
|
13796
|
-
return
|
|
14646
|
+
return json15({ snapshots: all });
|
|
13797
14647
|
}
|
|
13798
14648
|
const snapMatch = p.match(/^\/api\/snapshot\/(.+)$/);
|
|
13799
14649
|
if (snapMatch && req.method === "GET") {
|
|
13800
14650
|
const store = await snapStore();
|
|
13801
14651
|
const s = store.get(decodeURIComponent(snapMatch[1]));
|
|
13802
|
-
return s ?
|
|
14652
|
+
return s ? json15(s) : json15({ error: "not found" }, 404);
|
|
13803
14653
|
}
|
|
13804
14654
|
if (p === "/api/snapshots/diff" && req.method === "POST") {
|
|
13805
14655
|
const store = await snapStore();
|
|
@@ -13807,13 +14657,13 @@ async function featureRoutes(req, url) {
|
|
|
13807
14657
|
const from = b?.from ? store.get(b.from) : null;
|
|
13808
14658
|
const to = b?.to ? store.get(b.to) : null;
|
|
13809
14659
|
if (!from || !to) {
|
|
13810
|
-
return
|
|
14660
|
+
return json15({ error: "both 'from' and 'to' snapshot ids are required" }, 400);
|
|
13811
14661
|
}
|
|
13812
14662
|
const diff = diffLines(normalizeExport2(from.body), normalizeExport2(to.body), {
|
|
13813
14663
|
fromLabel: from.label ?? from.id,
|
|
13814
14664
|
toLabel: to.label ?? to.id
|
|
13815
14665
|
});
|
|
13816
|
-
return
|
|
14666
|
+
return json15({
|
|
13817
14667
|
from: { id: from.id, label: from.label, ts: from.ts, device: from.device },
|
|
13818
14668
|
to: { id: to.id, label: to.label, ts: to.ts, device: to.device },
|
|
13819
14669
|
summary: diff.summary,
|
|
@@ -13827,16 +14677,16 @@ async function featureRoutes(req, url) {
|
|
|
13827
14677
|
...b?.script ? splitCommands(b.script) : []
|
|
13828
14678
|
];
|
|
13829
14679
|
if (commands.length === 0)
|
|
13830
|
-
return
|
|
14680
|
+
return json15({ error: "no commands provided" }, 400);
|
|
13831
14681
|
const plan = buildChangePlan(commands);
|
|
13832
|
-
return
|
|
14682
|
+
return json15({ plan, text: renderPlan(plan) });
|
|
13833
14683
|
}
|
|
13834
14684
|
if (p === "/api/s3" && req.method === "GET") {
|
|
13835
|
-
return
|
|
14685
|
+
return json15({ configured: isS3Configured(), target: isS3Configured() ? s3Target() : null });
|
|
13836
14686
|
}
|
|
13837
14687
|
if (p === "/api/s3/list" && req.method === "GET") {
|
|
13838
14688
|
if (!isS3Configured())
|
|
13839
|
-
return
|
|
14689
|
+
return json15({ configured: false, objects: [] });
|
|
13840
14690
|
const prefix = url.searchParams.get("prefix") ?? "";
|
|
13841
14691
|
try {
|
|
13842
14692
|
const res = await getS3Client().list({ prefix: prefix || undefined, maxKeys: 1000 });
|
|
@@ -13845,42 +14695,42 @@ async function featureRoutes(req, url) {
|
|
|
13845
14695
|
size: o.size ?? 0,
|
|
13846
14696
|
lastModified: o.lastModified ?? null
|
|
13847
14697
|
}));
|
|
13848
|
-
return
|
|
14698
|
+
return json15({ configured: true, target: s3Target(), objects, truncated: !!res.isTruncated });
|
|
13849
14699
|
} catch (e) {
|
|
13850
|
-
return
|
|
14700
|
+
return json15({ error: clientError(e) }, 502);
|
|
13851
14701
|
}
|
|
13852
14702
|
}
|
|
13853
14703
|
if (p === "/api/s3/presign" && req.method === "GET") {
|
|
13854
14704
|
if (!isS3Configured())
|
|
13855
|
-
return
|
|
14705
|
+
return json15({ error: "S3 not configured" }, 400);
|
|
13856
14706
|
const key = url.searchParams.get("key");
|
|
13857
14707
|
if (!key)
|
|
13858
|
-
return
|
|
14708
|
+
return json15({ error: "key required" }, 400);
|
|
13859
14709
|
try {
|
|
13860
14710
|
const link = getS3Client().presign(key, { expiresIn: presignExpiresIn(), method: "GET" });
|
|
13861
|
-
return
|
|
14711
|
+
return json15({ url: link });
|
|
13862
14712
|
} catch (e) {
|
|
13863
|
-
return
|
|
14713
|
+
return json15({ error: clientError(e) }, 502);
|
|
13864
14714
|
}
|
|
13865
14715
|
}
|
|
13866
14716
|
if (p === "/api/s3/delete" && req.method === "POST") {
|
|
13867
14717
|
if (!isS3Configured())
|
|
13868
|
-
return
|
|
14718
|
+
return json15({ error: "S3 not configured" }, 400);
|
|
13869
14719
|
const b = await readJson(req);
|
|
13870
14720
|
if (!b?.key)
|
|
13871
|
-
return
|
|
14721
|
+
return json15({ error: "key required" }, 400);
|
|
13872
14722
|
try {
|
|
13873
14723
|
const client = getS3Client();
|
|
13874
14724
|
if (!await client.exists(b.key))
|
|
13875
|
-
return
|
|
14725
|
+
return json15({ error: "not found" }, 404);
|
|
13876
14726
|
await client.delete(b.key);
|
|
13877
|
-
return
|
|
14727
|
+
return json15({ ok: true, key: b.key });
|
|
13878
14728
|
} catch (e) {
|
|
13879
|
-
return
|
|
14729
|
+
return json15({ error: clientError(e) }, 502);
|
|
13880
14730
|
}
|
|
13881
14731
|
}
|
|
13882
14732
|
if (p === "/api/backups" && req.method === "GET") {
|
|
13883
|
-
return
|
|
14733
|
+
return json15({
|
|
13884
14734
|
dir: backupDir(),
|
|
13885
14735
|
devices: Object.keys(getConfig().devices),
|
|
13886
14736
|
backups: listBackups()
|
|
@@ -13890,14 +14740,14 @@ async function featureRoutes(req, url) {
|
|
|
13890
14740
|
const b = await readJson(req);
|
|
13891
14741
|
const raw = b?.dir?.trim();
|
|
13892
14742
|
if (!raw)
|
|
13893
|
-
return
|
|
13894
|
-
const dir = raw === "~" || raw.startsWith("~/") ?
|
|
14743
|
+
return json15({ error: "dir required" }, 400);
|
|
14744
|
+
const dir = raw === "~" || raw.startsWith("~/") ? join10(homedir5(), raw.slice(1)) : raw;
|
|
13895
14745
|
const next = { ...getConfig(), backupDir: dir };
|
|
13896
14746
|
setConfig(next);
|
|
13897
14747
|
try {
|
|
13898
14748
|
atomicWrite(getConfigSource2().path, serializeConfig(next));
|
|
13899
14749
|
} catch (e) {
|
|
13900
|
-
return
|
|
14750
|
+
return json15({
|
|
13901
14751
|
ok: true,
|
|
13902
14752
|
dir: backupDir(),
|
|
13903
14753
|
persisted: false,
|
|
@@ -13905,16 +14755,16 @@ async function featureRoutes(req, url) {
|
|
|
13905
14755
|
});
|
|
13906
14756
|
}
|
|
13907
14757
|
recordVersion(getConfig(), "auto", Date.now(), "backup path changed");
|
|
13908
|
-
return
|
|
14758
|
+
return json15({ ok: true, dir: backupDir(), persisted: true });
|
|
13909
14759
|
}
|
|
13910
14760
|
if (p === "/api/backups/get" && req.method === "GET") {
|
|
13911
14761
|
const name = url.searchParams.get("name");
|
|
13912
14762
|
if (!name)
|
|
13913
|
-
return
|
|
14763
|
+
return json15({ error: "name required" }, 400);
|
|
13914
14764
|
try {
|
|
13915
|
-
return
|
|
14765
|
+
return json15({ name, content: readBackup(name) });
|
|
13916
14766
|
} catch {
|
|
13917
|
-
return
|
|
14767
|
+
return json15({ error: "not found" }, 404);
|
|
13918
14768
|
}
|
|
13919
14769
|
}
|
|
13920
14770
|
if (p === "/api/backups/raw" && req.method === "GET") {
|
|
@@ -13935,41 +14785,41 @@ async function featureRoutes(req, url) {
|
|
|
13935
14785
|
if (p === "/api/backups/upload" && req.method === "POST") {
|
|
13936
14786
|
const b = await readJson(req);
|
|
13937
14787
|
if (!b?.name || typeof b.content !== "string") {
|
|
13938
|
-
return
|
|
14788
|
+
return json15({ error: "name and content are required" }, 400);
|
|
13939
14789
|
}
|
|
13940
14790
|
try {
|
|
13941
14791
|
const safe = b.name.endsWith(".rsc") ? b.name : `${b.name}.rsc`;
|
|
13942
|
-
return
|
|
14792
|
+
return json15({ ok: true, name: writeBackup(safe, b.content) });
|
|
13943
14793
|
} catch (e) {
|
|
13944
|
-
return
|
|
14794
|
+
return json15({ error: clientError(e) }, 400);
|
|
13945
14795
|
}
|
|
13946
14796
|
}
|
|
13947
14797
|
if (p === "/api/backups/rename" && req.method === "POST") {
|
|
13948
14798
|
const b = await readJson(req);
|
|
13949
14799
|
if (!b?.name || !b?.new_name)
|
|
13950
|
-
return
|
|
14800
|
+
return json15({ error: "name and new_name are required" }, 400);
|
|
13951
14801
|
try {
|
|
13952
|
-
return
|
|
14802
|
+
return json15({ ok: true, name: renameBackup(b.name, b.new_name) });
|
|
13953
14803
|
} catch (e) {
|
|
13954
|
-
return
|
|
14804
|
+
return json15({ error: clientError(e) }, 400);
|
|
13955
14805
|
}
|
|
13956
14806
|
}
|
|
13957
14807
|
if (p === "/api/backups/delete" && req.method === "POST") {
|
|
13958
14808
|
const b = await readJson(req);
|
|
13959
14809
|
if (!b?.name)
|
|
13960
|
-
return
|
|
14810
|
+
return json15({ error: "name required" }, 400);
|
|
13961
14811
|
try {
|
|
13962
|
-
return deleteBackup(b.name) ?
|
|
14812
|
+
return deleteBackup(b.name) ? json15({ ok: true }) : json15({ error: "not found" }, 404);
|
|
13963
14813
|
} catch (e) {
|
|
13964
|
-
return
|
|
14814
|
+
return json15({ error: clientError(e) }, 400);
|
|
13965
14815
|
}
|
|
13966
14816
|
}
|
|
13967
14817
|
if (p === "/api/backups/restore" && req.method === "POST") {
|
|
13968
14818
|
const b = await readJson(req);
|
|
13969
14819
|
if (!b?.name)
|
|
13970
|
-
return
|
|
14820
|
+
return json15({ error: "name required" }, 400);
|
|
13971
14821
|
const device = resolveDeviceName(b.device);
|
|
13972
|
-
return
|
|
14822
|
+
return json15(await restoreLocalBackup(device, b.name, b.confirm === true));
|
|
13973
14823
|
}
|
|
13974
14824
|
if (p === "/api/backups/create" && req.method === "POST") {
|
|
13975
14825
|
const b = await readJson(req);
|
|
@@ -13981,7 +14831,7 @@ async function featureRoutes(req, url) {
|
|
|
13981
14831
|
compact: b?.compact === true,
|
|
13982
14832
|
terse: b?.terse === true
|
|
13983
14833
|
});
|
|
13984
|
-
return r.ok ?
|
|
14834
|
+
return r.ok ? json15(r) : json15({ error: r.error ?? "export failed" }, 502);
|
|
13985
14835
|
}
|
|
13986
14836
|
return null;
|
|
13987
14837
|
}
|
|
@@ -14002,7 +14852,7 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14002
14852
|
let openVpnHistory;
|
|
14003
14853
|
let stopOpenVpnHistory;
|
|
14004
14854
|
try {
|
|
14005
|
-
openVpnHistory = await openOpenVpnHistory(
|
|
14855
|
+
openVpnHistory = await openOpenVpnHistory(join10(dirname11(cfg.dbPath), "openvpn-history.db"));
|
|
14006
14856
|
stopOpenVpnHistory = startOpenVpnHistorySampler(openVpnHistory);
|
|
14007
14857
|
} catch (e) {
|
|
14008
14858
|
logger.warn(`[${SERVER_TAG3}] OpenVPN history disabled: ${String(e)}`);
|
|
@@ -14021,7 +14871,7 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14021
14871
|
}
|
|
14022
14872
|
}
|
|
14023
14873
|
try {
|
|
14024
|
-
siteActivity = await openSiteActivityStore(
|
|
14874
|
+
siteActivity = await openSiteActivityStore(join10(dirname11(cfg.dbPath), "site-activity.db"));
|
|
14025
14875
|
stopSiteActivity = await startSiteActivityCollector(siteActivity, openVpnHistory);
|
|
14026
14876
|
} catch (e) {
|
|
14027
14877
|
logger.warn(`[${SERVER_TAG3}] Site activity unavailable: ${String(e)}`);
|
|
@@ -14029,13 +14879,13 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14029
14879
|
siteActivity = undefined;
|
|
14030
14880
|
}
|
|
14031
14881
|
try {
|
|
14032
|
-
usageStore = await openUsageStore(
|
|
14882
|
+
usageStore = await openUsageStore(join10(dirname11(cfg.dbPath), "usage.db"));
|
|
14033
14883
|
startUsageSampler(usageStore);
|
|
14034
14884
|
} catch (e) {
|
|
14035
14885
|
logger.warn(`[${SERVER_TAG3}] usage history disabled: ${String(e)}`);
|
|
14036
14886
|
}
|
|
14037
14887
|
try {
|
|
14038
|
-
capsmanStore = await openCapsmanStore(
|
|
14888
|
+
capsmanStore = await openCapsmanStore(join10(dirname11(cfg.dbPath), "capsman.db"));
|
|
14039
14889
|
startCapsmanSampler(capsmanStore);
|
|
14040
14890
|
} catch (e) {
|
|
14041
14891
|
logger.warn(`[${SERVER_TAG3}] capsman trends disabled: ${String(e)}`);
|
|
@@ -14054,11 +14904,17 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14054
14904
|
return bearer === cfg.token || url.searchParams.get("token") === cfg.token;
|
|
14055
14905
|
};
|
|
14056
14906
|
const accessSettingsRoutes = createAccessSettingsRoutes(configAdmin);
|
|
14907
|
+
setRecordingDir(cfg.dbPath === ":memory:" ? undefined : join10(dirname11(cfg.dbPath), "terminal-recordings"));
|
|
14908
|
+
let terminalStore;
|
|
14909
|
+
const terminalRoutes = createTerminalRoutes({
|
|
14910
|
+
denied: terminalAccess(cfg),
|
|
14911
|
+
store: () => terminalStore ??= openTerminalStore(cfg.dbPath === ":memory:" ? ":memory:" : join10(dirname11(cfg.dbPath), "terminal.db"))
|
|
14912
|
+
});
|
|
14057
14913
|
async function dashboardRoute(req, url, srv, ca, tl) {
|
|
14058
14914
|
if (url.pathname === "/api/interfaces/stream" && req.method === "GET") {
|
|
14059
14915
|
const device = url.searchParams.get("device");
|
|
14060
14916
|
if (!device)
|
|
14061
|
-
return
|
|
14917
|
+
return json15({ error: "device required" }, 400);
|
|
14062
14918
|
return interfaceStatsResponse(req, device);
|
|
14063
14919
|
}
|
|
14064
14920
|
if (url.pathname === "/api/stream") {
|
|
@@ -14095,8 +14951,11 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14095
14951
|
const homeResp = await homeRoutes(req, url);
|
|
14096
14952
|
if (homeResp)
|
|
14097
14953
|
return homeResp;
|
|
14954
|
+
const terminalResp = await terminalRoutes(req, url);
|
|
14955
|
+
if (terminalResp)
|
|
14956
|
+
return terminalResp;
|
|
14098
14957
|
if (url.pathname === "/api/client-checks/network" && req.method === "GET")
|
|
14099
|
-
return
|
|
14958
|
+
return json15(clientCheckNetwork(cfg.host, srv.port ?? cfg.port));
|
|
14100
14959
|
const workspaceResp = await workspaceRoutes(req, url);
|
|
14101
14960
|
if (workspaceResp)
|
|
14102
14961
|
return workspaceResp;
|
|
@@ -14171,7 +15030,7 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14171
15030
|
return memoryResp;
|
|
14172
15031
|
const db = getEventStore();
|
|
14173
15032
|
if (!db)
|
|
14174
|
-
return
|
|
15033
|
+
return json15({ error: "recorder not active" }, 503);
|
|
14175
15034
|
if (url.pathname === "/api/events" && req.method === "DELETE") {
|
|
14176
15035
|
let body = {};
|
|
14177
15036
|
try {
|
|
@@ -14179,7 +15038,7 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14179
15038
|
} catch {}
|
|
14180
15039
|
const ids = Array.isArray(body.ids) ? body.ids.filter((x) => typeof x === "string") : [];
|
|
14181
15040
|
const removed = body.all === true ? db.clear() : db.delete(ids);
|
|
14182
|
-
return
|
|
15041
|
+
return json15({ removed, total: db.total() });
|
|
14183
15042
|
}
|
|
14184
15043
|
if (url.pathname === "/api/ssh-pool") {
|
|
14185
15044
|
const cfg = getConfig();
|
|
@@ -14188,7 +15047,7 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14188
15047
|
const totalInflight = ps.reduce((s, p) => s + p.inflight, 0);
|
|
14189
15048
|
const totalIdle = ps.filter((p) => p.idle).length;
|
|
14190
15049
|
const totalBusy = ps.filter((p) => p.inflight > 0).length;
|
|
14191
|
-
return
|
|
15050
|
+
return json15({
|
|
14192
15051
|
enabled,
|
|
14193
15052
|
config: {
|
|
14194
15053
|
keepAlive: cfg.ssh.keepAlive,
|
|
@@ -14217,26 +15076,26 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14217
15076
|
});
|
|
14218
15077
|
}
|
|
14219
15078
|
if (url.pathname === "/api/devices") {
|
|
14220
|
-
return
|
|
15079
|
+
return json15(devicesPayload(db));
|
|
14221
15080
|
}
|
|
14222
15081
|
if (url.pathname === "/api/capabilities") {
|
|
14223
15082
|
const devices = Object.keys(getConfig().devices).map((name) => ({
|
|
14224
15083
|
device: name,
|
|
14225
15084
|
capabilities: serializeCapabilities(peekCapabilities(name))
|
|
14226
15085
|
}));
|
|
14227
|
-
return
|
|
15086
|
+
return json15({ devices });
|
|
14228
15087
|
}
|
|
14229
15088
|
if (url.pathname === "/api/capabilities/refresh" && req.method === "POST") {
|
|
14230
15089
|
const b = await readJson(req);
|
|
14231
15090
|
if (typeof b?.device !== "string")
|
|
14232
|
-
return
|
|
15091
|
+
return json15({ error: "device (string) is required" }, 400);
|
|
14233
15092
|
if (!(b.device in getConfig().devices)) {
|
|
14234
|
-
return
|
|
15093
|
+
return json15({ error: `unknown device: ${b.device}` }, 404);
|
|
14235
15094
|
}
|
|
14236
15095
|
invalidateCapabilities(b.device);
|
|
14237
15096
|
try {
|
|
14238
15097
|
const caps = await getCapabilities(b.device);
|
|
14239
|
-
return
|
|
15098
|
+
return json15({ device: b.device, capabilities: serializeCapabilities(caps) });
|
|
14240
15099
|
} catch (e) {
|
|
14241
15100
|
logger.error(`Capability probe failed for '${b.device}': ${logError(e)}`);
|
|
14242
15101
|
return errorResponse(e);
|
|
@@ -14245,11 +15104,11 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14245
15104
|
if (url.pathname === "/api/devices/toggle" && req.method === "POST") {
|
|
14246
15105
|
const b = await readJson(req);
|
|
14247
15106
|
if (typeof b?.device !== "string" || typeof b?.disabled !== "boolean") {
|
|
14248
|
-
return
|
|
15107
|
+
return json15({ error: "device (string) and disabled (boolean) are required" }, 400);
|
|
14249
15108
|
}
|
|
14250
15109
|
const cfg = getConfig();
|
|
14251
15110
|
if (!(b.device in cfg.devices))
|
|
14252
|
-
return
|
|
15111
|
+
return json15({ error: `unknown device: ${b.device}` }, 404);
|
|
14253
15112
|
const dc = cfg.devices[b.device];
|
|
14254
15113
|
const next = {
|
|
14255
15114
|
...cfg,
|
|
@@ -14270,7 +15129,7 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14270
15129
|
if (persisted) {
|
|
14271
15130
|
recordVersion(getConfig(), "auto", Date.now(), `device ${b.disabled ? "disabled" : "enabled"}: ${b.device}`);
|
|
14272
15131
|
}
|
|
14273
|
-
return
|
|
15132
|
+
return json15({
|
|
14274
15133
|
ok: true,
|
|
14275
15134
|
persisted,
|
|
14276
15135
|
requiresReconnect: true,
|
|
@@ -14283,17 +15142,17 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14283
15142
|
const name = typeof b?.device === "string" ? b.device : "";
|
|
14284
15143
|
const cfg = getConfig();
|
|
14285
15144
|
if (!(name in cfg.devices))
|
|
14286
|
-
return
|
|
15145
|
+
return json15({ error: `unknown device: ${name}` }, 404);
|
|
14287
15146
|
if (url.pathname === "/api/devices/reconnect")
|
|
14288
15147
|
closeDevice(name);
|
|
14289
15148
|
const status = await probeDevice(name, cfg.devices[name]);
|
|
14290
|
-
return
|
|
15149
|
+
return json15({ ok: true, status, ...devicesPayload(db) });
|
|
14291
15150
|
}
|
|
14292
15151
|
if (url.pathname === "/api/topology") {
|
|
14293
|
-
return
|
|
15152
|
+
return json15(topologyPayload());
|
|
14294
15153
|
}
|
|
14295
15154
|
if (url.pathname === "/api/config") {
|
|
14296
|
-
return
|
|
15155
|
+
return json15(configPayload());
|
|
14297
15156
|
}
|
|
14298
15157
|
if (url.pathname === "/" || url.pathname === "/index.html") {
|
|
14299
15158
|
return new Response(dashboardHtml(), {
|
|
@@ -14302,9 +15161,9 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14302
15161
|
}
|
|
14303
15162
|
if (url.pathname === "/api/releases/latest") {
|
|
14304
15163
|
try {
|
|
14305
|
-
return
|
|
15164
|
+
return json15(await fetchLatestRelease());
|
|
14306
15165
|
} catch (e) {
|
|
14307
|
-
return
|
|
15166
|
+
return json15({ error: clientError(e, "fetch failed") }, 502);
|
|
14308
15167
|
}
|
|
14309
15168
|
}
|
|
14310
15169
|
if (url.pathname === "/api/catalog" && req.method === "GET") {
|
|
@@ -14323,7 +15182,7 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14323
15182
|
}));
|
|
14324
15183
|
const prompts = listPrompts();
|
|
14325
15184
|
const groups = [...new Set(modules.map((m) => m.group))].sort();
|
|
14326
|
-
return
|
|
15185
|
+
return json15({
|
|
14327
15186
|
modules,
|
|
14328
15187
|
prompts,
|
|
14329
15188
|
groups,
|
|
@@ -14338,27 +15197,27 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14338
15197
|
}
|
|
14339
15198
|
if (url.pathname === "/api/releases" && req.method === "GET") {
|
|
14340
15199
|
try {
|
|
14341
|
-
return
|
|
15200
|
+
return json15(await fetchAllReleases());
|
|
14342
15201
|
} catch (e) {
|
|
14343
|
-
return
|
|
15202
|
+
return json15({ error: clientError(e, "fetch failed") }, 502);
|
|
14344
15203
|
}
|
|
14345
15204
|
}
|
|
14346
15205
|
if (url.pathname === "/api/upgrade" && req.method === "POST") {
|
|
14347
15206
|
const body = await readJson(req);
|
|
14348
15207
|
if (body?.version != null && typeof body.version !== "string")
|
|
14349
|
-
return
|
|
15208
|
+
return json15({ ok: false, error: 'Version must be "latest" or an x.y.z string.' }, 400);
|
|
14350
15209
|
const version = body?.version ?? "latest";
|
|
14351
15210
|
if (version !== "latest" && !/^\d+\.\d+\.\d+$/.test(version)) {
|
|
14352
|
-
return
|
|
15211
|
+
return json15({ ok: false, error: `Invalid version "${version}" (use "latest" or x.y.z).` }, 400);
|
|
14353
15212
|
}
|
|
14354
15213
|
const spec = `@usex/mikrotik-mcp@${version}`;
|
|
14355
15214
|
logger.warn(`Dashboard requested upgrade: bun i -g ${spec}`);
|
|
14356
15215
|
const { ok, log } = await runUpgrade(spec);
|
|
14357
15216
|
if (!ok)
|
|
14358
|
-
return
|
|
15217
|
+
return json15({ ok: false, version, log }, 500);
|
|
14359
15218
|
const willRestart = body?.restart !== false;
|
|
14360
15219
|
const relaunched = willRestart ? restartProcess() : false;
|
|
14361
|
-
return
|
|
15220
|
+
return json15({
|
|
14362
15221
|
ok: true,
|
|
14363
15222
|
version,
|
|
14364
15223
|
log,
|
|
@@ -14368,7 +15227,7 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14368
15227
|
}
|
|
14369
15228
|
if (url.pathname === "/api/meta") {
|
|
14370
15229
|
const f = facets(db);
|
|
14371
|
-
return
|
|
15230
|
+
return json15({
|
|
14372
15231
|
...f,
|
|
14373
15232
|
version: VERSION,
|
|
14374
15233
|
risks: ["READ", "WRITE", "WRITE_IDEMPOTENT", "DESTRUCTIVE", "DANGEROUS"],
|
|
@@ -14379,19 +15238,19 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14379
15238
|
}
|
|
14380
15239
|
if (url.pathname === "/api/events") {
|
|
14381
15240
|
const filter = filterFromQuery(url);
|
|
14382
|
-
return
|
|
15241
|
+
return json15({ events: db.query(filter), total: db.total() });
|
|
14383
15242
|
}
|
|
14384
15243
|
const eventMatch = url.pathname.match(/^\/api\/event\/(.+)$/);
|
|
14385
15244
|
if (eventMatch) {
|
|
14386
15245
|
const e = db.get(decodeURIComponent(eventMatch[1]));
|
|
14387
|
-
return e ?
|
|
15246
|
+
return e ? json15(e) : json15({ error: "not found" }, 404);
|
|
14388
15247
|
}
|
|
14389
15248
|
if (url.pathname === "/api/stats") {
|
|
14390
15249
|
const now = Date.now();
|
|
14391
15250
|
const windowMs = Number(url.searchParams.get("window") ?? 3600000);
|
|
14392
15251
|
const buckets = Number(url.searchParams.get("buckets") ?? 60);
|
|
14393
15252
|
const events = db.query({ since: now - windowMs, limit: 5000 });
|
|
14394
|
-
return
|
|
15253
|
+
return json15(computeStats(events, { now, windowMs, buckets }));
|
|
14395
15254
|
}
|
|
14396
15255
|
return new Response("Not Found", { status: 404 });
|
|
14397
15256
|
}
|
|
@@ -14472,6 +15331,9 @@ async function runDashboard(cfg, transportLabel) {
|
|
|
14472
15331
|
store.close();
|
|
14473
15332
|
usageStore?.close();
|
|
14474
15333
|
usageStore = null;
|
|
15334
|
+
closeAllShells();
|
|
15335
|
+
stopTerminalScheduler();
|
|
15336
|
+
terminalStore?.then((opened) => opened.close()).catch(() => {});
|
|
14475
15337
|
capsmanStore?.close();
|
|
14476
15338
|
capsmanStore = null;
|
|
14477
15339
|
closeMemoryStore();
|
|
@@ -18681,10 +19543,11 @@ function buildSecurity(mcp) {
|
|
|
18681
19543
|
};
|
|
18682
19544
|
}
|
|
18683
19545
|
if (LOCALHOST.has(mcp.host) && mcp.host !== "0.0.0.0") {
|
|
19546
|
+
const names = ["127.0.0.1", "localhost", "[::1]"];
|
|
18684
19547
|
return {
|
|
18685
19548
|
enableDnsRebindingProtection: true,
|
|
18686
|
-
allowedHosts:
|
|
18687
|
-
allowedOrigins:
|
|
19549
|
+
allowedHosts: names.map((name) => `${name}:${mcp.port}`),
|
|
19550
|
+
allowedOrigins: names.map((name) => `http://${name}:${mcp.port}`)
|
|
18688
19551
|
};
|
|
18689
19552
|
}
|
|
18690
19553
|
logger.warn(`Serving HTTP on a non-localhost host (${mcp.host}) without an allow-list, so DNS-rebinding ` + "protection is disabled. Behind a reverse proxy, set --mcp-allowed-hosts to your domain.");
|
|
@@ -18693,27 +19556,77 @@ function buildSecurity(mcp) {
|
|
|
18693
19556
|
async function runHttp(mcp) {
|
|
18694
19557
|
const security = buildSecurity(mcp);
|
|
18695
19558
|
const { toolCount, promptCount, uiViewCount, readOnly } = createServer();
|
|
18696
|
-
const
|
|
18697
|
-
|
|
18698
|
-
|
|
18699
|
-
const
|
|
18700
|
-
if (
|
|
18701
|
-
return
|
|
19559
|
+
const sessions = new Map;
|
|
19560
|
+
const jsonError = (status, code, message, cors) => Response.json({ jsonrpc: "2.0", error: { code, message }, id: null }, { status, headers: cors });
|
|
19561
|
+
function evict(id, reason) {
|
|
19562
|
+
const session = sessions.get(id);
|
|
19563
|
+
if (!session)
|
|
19564
|
+
return;
|
|
19565
|
+
sessions.delete(id);
|
|
19566
|
+
logger.info(`MCP session ${id} evicted (${session.closeReason ?? reason}); ${sessions.size} open`);
|
|
19567
|
+
session.server.close().catch(() => {});
|
|
19568
|
+
session.transport.close().catch(() => {});
|
|
19569
|
+
}
|
|
19570
|
+
const sweep = setInterval(() => {
|
|
19571
|
+
const now = Date.now();
|
|
19572
|
+
for (const [id, session] of sessions) {
|
|
19573
|
+
const idle = now - session.lastSeen;
|
|
19574
|
+
if (idle >= mcp.sessionIdleTimeout)
|
|
19575
|
+
evict(id, `expired: idle ${Math.round(idle / 1000)}s`);
|
|
19576
|
+
}
|
|
19577
|
+
}, Math.min(mcp.sessionIdleTimeout, 60000));
|
|
19578
|
+
sweep.unref?.();
|
|
19579
|
+
async function openSession(req, body) {
|
|
19580
|
+
const { server } = createServer();
|
|
18702
19581
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
18703
19582
|
sessionIdGenerator: () => randomUUID3(),
|
|
18704
19583
|
enableJsonResponse: true,
|
|
18705
19584
|
...security,
|
|
18706
19585
|
onsessioninitialized: (id) => {
|
|
18707
|
-
|
|
19586
|
+
sessions.set(id, { transport, server, lastSeen: Date.now() });
|
|
19587
|
+
logger.info(`MCP session ${id} created; ${sessions.size} open`);
|
|
18708
19588
|
}
|
|
18709
19589
|
});
|
|
18710
19590
|
transport.onclose = () => {
|
|
18711
19591
|
if (transport.sessionId)
|
|
18712
|
-
|
|
19592
|
+
evict(transport.sessionId, "transport closed");
|
|
18713
19593
|
};
|
|
18714
|
-
|
|
18715
|
-
|
|
18716
|
-
|
|
19594
|
+
try {
|
|
19595
|
+
await server.connect(transport);
|
|
19596
|
+
const res = await transport.handleRequest(req, { parsedBody: body });
|
|
19597
|
+
if (!transport.sessionId || !sessions.has(transport.sessionId))
|
|
19598
|
+
server.close().catch(() => {});
|
|
19599
|
+
return res;
|
|
19600
|
+
} catch (error) {
|
|
19601
|
+
if (transport.sessionId)
|
|
19602
|
+
evict(transport.sessionId, "initialize failed");
|
|
19603
|
+
server.close().catch(() => {});
|
|
19604
|
+
throw error;
|
|
19605
|
+
}
|
|
19606
|
+
}
|
|
19607
|
+
async function handleMcp(req, cors) {
|
|
19608
|
+
const sid = req.headers.get("mcp-session-id");
|
|
19609
|
+
if (sid) {
|
|
19610
|
+
const session = sessions.get(sid);
|
|
19611
|
+
if (!session)
|
|
19612
|
+
return jsonError(404, -32001, "Session not found", cors);
|
|
19613
|
+
session.lastSeen = Date.now();
|
|
19614
|
+
if (req.method === "DELETE")
|
|
19615
|
+
session.closeReason = "deleted by client";
|
|
19616
|
+
return session.transport.handleRequest(req);
|
|
19617
|
+
}
|
|
19618
|
+
if (req.method !== "POST")
|
|
19619
|
+
return jsonError(400, -32000, "Bad Request: Mcp-Session-Id header is required", cors);
|
|
19620
|
+
let body;
|
|
19621
|
+
try {
|
|
19622
|
+
body = await req.json();
|
|
19623
|
+
} catch {
|
|
19624
|
+
return jsonError(400, -32700, "Parse error: Invalid JSON", cors);
|
|
19625
|
+
}
|
|
19626
|
+
const isInitialize = (Array.isArray(body) ? body : [body]).some((message) => message?.method === "initialize");
|
|
19627
|
+
if (!isInitialize)
|
|
19628
|
+
return jsonError(400, -32000, "Bad Request: Mcp-Session-Id header is required", cors);
|
|
19629
|
+
return openSession(req, body);
|
|
18717
19630
|
}
|
|
18718
19631
|
const mcpPath = "/mcp";
|
|
18719
19632
|
serve2({
|
|
@@ -18732,8 +19645,7 @@ async function runHttp(mcp) {
|
|
|
18732
19645
|
});
|
|
18733
19646
|
}
|
|
18734
19647
|
if (url.pathname === mcpPath || url.pathname === `${mcpPath}/`) {
|
|
18735
|
-
const
|
|
18736
|
-
const res = await transport.handleRequest(req);
|
|
19648
|
+
const res = await handleMcp(req, cors);
|
|
18737
19649
|
if (Object.keys(cors).length === 0)
|
|
18738
19650
|
return res;
|
|
18739
19651
|
const headers = new Headers(res.headers);
|
|
@@ -19048,6 +19960,10 @@ USAGE
|
|
|
19048
19960
|
|
|
19049
19961
|
COMMANDS
|
|
19050
19962
|
serve Start the MCP server (default)
|
|
19963
|
+
dashboard Open the dashboard of a server that runs somewhere else
|
|
19964
|
+
--server <url> that server's dashboard URL (http://host:9090)
|
|
19965
|
+
--server-token its --dashboard-token (MIKROTIK_DASHBOARD_SERVER_TOKEN)
|
|
19966
|
+
--host / --port where to serve it here (default 127.0.0.1:9090)
|
|
19051
19967
|
auth-check Connect over SSH to every configured device and probe it
|
|
19052
19968
|
devices List the configured devices (name \xB7 host \xB7 auth)
|
|
19053
19969
|
tools Print the full tool catalog (name \xB7 risk \xB7 title)
|
|
@@ -19078,6 +19994,8 @@ TRANSPORT OPTIONS
|
|
|
19078
19994
|
--tool-surface full | core tool list (MIKROTIK_MCP__TOOL_SURFACE)
|
|
19079
19995
|
--core-tools Extra tools listed in core mode (MIKROTIK_MCP__CORE_TOOLS)
|
|
19080
19996
|
--mcp-allowed-hosts Host heaxder allow-list (DNS-rebinding protection)
|
|
19997
|
+
--mcp-session-idle-timeout Close an HTTP session idle this long, ms (default 24h)
|
|
19998
|
+
(MIKROTIK_MCP__SESSION_IDLE_TIMEOUT)
|
|
19081
19999
|
|
|
19082
20000
|
SSH CONNECTION POOLING (persistent connections, on by default)
|
|
19083
20001
|
--ssh-keep-alive Enable/disable pooling (MIKROTIK_SSH__KEEP_ALIVE, default true)
|
|
@@ -19094,6 +20012,9 @@ OBSERVABILITY DASHBOARD (optional; real-time feed + analytics of every tool cal
|
|
|
19094
20012
|
--dashboard-capture-body Record redacted in/out bodies (MIKROTIK_DASHBOARD__CAPTURE_BODY)
|
|
19095
20013
|
--dashboard-token Bearer token to protect the dashboard
|
|
19096
20014
|
(MIKROTIK_DASHBOARD__TOKEN)
|
|
20015
|
+
--dashboard-terminal Serve the Terminal page (default true). It also needs
|
|
20016
|
+
a dashboard token or a loopback bind
|
|
20017
|
+
(MIKROTIK_DASHBOARD__TERMINAL)
|
|
19097
20018
|
`;
|
|
19098
20019
|
function warnIfPlaintextPasswordInContainer(anyPassword) {
|
|
19099
20020
|
const inContainer = existsSync2("/.dockerenv") || process.env.container === "docker";
|
|
@@ -19180,6 +20101,29 @@ async function main() {
|
|
|
19180
20101
|
listDevicesCli();
|
|
19181
20102
|
return;
|
|
19182
20103
|
}
|
|
20104
|
+
if (command === "dashboard") {
|
|
20105
|
+
const flags = parseFlags2(argv);
|
|
20106
|
+
const server = flags.server ?? process.env.MIKROTIK_DASHBOARD_SERVER;
|
|
20107
|
+
if (!server) {
|
|
20108
|
+
process.stderr.write(`Usage: mikrotik-mcp dashboard --server http://<server-ip>:9090 [--server-token <token>] [--port 9090]
|
|
20109
|
+
`);
|
|
20110
|
+
process.exit(2);
|
|
20111
|
+
}
|
|
20112
|
+
const { runRemoteDashboard } = await import("./shared/cli-b7rbwm6j.js");
|
|
20113
|
+
try {
|
|
20114
|
+
runRemoteDashboard({
|
|
20115
|
+
server,
|
|
20116
|
+
token: flags["server-token"] ?? process.env.MIKROTIK_DASHBOARD_SERVER_TOKEN,
|
|
20117
|
+
host: flags.host ?? "127.0.0.1",
|
|
20118
|
+
port: Number(flags.port ?? 9090)
|
|
20119
|
+
});
|
|
20120
|
+
} catch (e) {
|
|
20121
|
+
process.stderr.write(`${e instanceof Error ? e.message : String(e)}
|
|
20122
|
+
`);
|
|
20123
|
+
process.exit(2);
|
|
20124
|
+
}
|
|
20125
|
+
return;
|
|
20126
|
+
}
|
|
19183
20127
|
if (command === "auth-check") {
|
|
19184
20128
|
process.exit(await authCheck());
|
|
19185
20129
|
}
|
|
@@ -19195,7 +20139,7 @@ async function main() {
|
|
|
19195
20139
|
await printBanner();
|
|
19196
20140
|
warnIfPlaintextPasswordInContainer(Object.values(cfg.devices).some((d) => !!d.password));
|
|
19197
20141
|
const deviceNames = Object.keys(cfg.devices);
|
|
19198
|
-
logger.info(`Starting ${SERVER_NAME} v${VERSION} (transport=${cfg.mcp.transport},
|
|
20142
|
+
logger.info(`Starting ${SERVER_NAME} v${VERSION} (transport=${cfg.mcp.transport}, devices=${deviceNames.length === 1 ? deviceNames[0] : deviceNames.join("/")}, ssh-pool=${cfg.ssh.keepAlive ? "on" : "off"})`);
|
|
19199
20143
|
if (cfg.alerts?.enabled !== false && cfg.alerts) {
|
|
19200
20144
|
try {
|
|
19201
20145
|
const rules = parseRules(cfg.alerts.rules);
|
|
@@ -19245,7 +20189,7 @@ async function main() {
|
|
|
19245
20189
|
try {
|
|
19246
20190
|
await runDashboard(cfg.dashboard, cfg.mcp.transport);
|
|
19247
20191
|
} catch (e) {
|
|
19248
|
-
logger.error(`Failed to start observability dashboard: ${e instanceof Error ? e.message : String(e)}.
|
|
20192
|
+
logger.error(`Failed to start observability dashboard: ${e instanceof Error ? e.message : String(e)}. Continuing without it.`);
|
|
19249
20193
|
}
|
|
19250
20194
|
};
|
|
19251
20195
|
if (cfg.mcp.transport === "stdio") {
|