@usex/mikrotik-mcp 6.4.1 → 6.5.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/README.md +10 -4
- package/dist/cli.js +28 -4
- package/dist/index.js +1 -1
- package/dist/shared/{cli-6g4wtkj1.js → cli-0bdzn6kc.js} +1 -1
- package/dist/shared/{cli-71bbmd5h.js → cli-37e58eme.js} +1 -1
- package/dist/shared/{cli-wn4ybhq4.js → cli-704wwgnc.js} +1 -1
- package/dist/shared/{cli-y81nsdte.js → cli-89y0ykq1.js} +704 -67
- package/dist/shared/{cli-5jnc1v2w.js → cli-fvjmfzab.js} +1 -1
- package/dist/shared/{library-9ygb3vgn.js → library-3wpdmsen.js} +1 -1
- package/dist/shared/{library-4c9wrr75.js → library-9c5k05ge.js} +1 -1
- package/dist/shared/{library-rbaybv2t.js → library-djammhn2.js} +1 -1
- package/dist/shared/{library-kssnaqqr.js → library-e2gm3ta5.js} +911 -272
- package/dist/shared/{library-gcbk2m7w.js → library-ys83rjgm.js} +1 -1
- package/dist/ui/observability.html +82 -79
- package/package.json +2 -2
- package/schemas/README.md +1 -1
- package/schemas/devtools-manifest.json +87 -2
- package/schemas/tool-catalog.json +337 -2
- package/schemas/tools/apply_address_set.json +23 -0
- package/schemas/tools/compose_address_set.json +52 -0
- package/schemas/tools/create_address_set.json +52 -0
- package/schemas/tools/get_flow_collector_health.json +7 -0
- package/schemas/tools/list_address_sets.json +7 -0
- package/schemas/tools/preview_address_set.json +52 -0
- package/schemas/tools/verify_filter_policy.json +74 -0
|
@@ -16594,13 +16594,13 @@ async function undoMigration(id, confirm, selected) {
|
|
|
16594
16594
|
throw new Error("Undo lost Safe Mode or exceeded its time budget.");
|
|
16595
16595
|
await checkedRead(item.undo, createContext(undefined, device));
|
|
16596
16596
|
}
|
|
16597
|
-
const beforeTarget = (await import("./cli-
|
|
16598
|
-
const db = await beforeTarget((await import("./cli-
|
|
16597
|
+
const beforeTarget = (await import("./cli-37e58eme.js")).openSnapshotStore;
|
|
16598
|
+
const db = await beforeTarget((await import("./cli-704wwgnc.js")).DEFAULT_SNAPSHOT_DB);
|
|
16599
16599
|
try {
|
|
16600
16600
|
const original = db.get(p.snapshots.target);
|
|
16601
16601
|
if (!original)
|
|
16602
16602
|
throw new Error("Original target snapshot unavailable.");
|
|
16603
|
-
const { normalizeExport } = await import("./cli-
|
|
16603
|
+
const { normalizeExport } = await import("./cli-0bdzn6kc.js");
|
|
16604
16604
|
if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
|
|
16605
16605
|
throw new Error("Target differs from its backup. Undo verification failed.");
|
|
16606
16606
|
} finally {
|
|
@@ -17043,8 +17043,385 @@ ${result}`;
|
|
|
17043
17043
|
})
|
|
17044
17044
|
];
|
|
17045
17045
|
|
|
17046
|
-
// src/
|
|
17046
|
+
// src/address-sets/model.ts
|
|
17047
|
+
import { createHash as createHash6 } from "crypto";
|
|
17047
17048
|
import { isIP as isIP4 } from "net";
|
|
17049
|
+
import ipaddr3 from "ipaddr.js";
|
|
17050
|
+
var addressSetInput = object({
|
|
17051
|
+
name: string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,39}$/),
|
|
17052
|
+
family: _enum(["ipv4", "ipv6"]).default("ipv4"),
|
|
17053
|
+
operation: _enum(["union", "intersection", "difference"]).default("union"),
|
|
17054
|
+
left: array(string().max(80)).min(1).max(2048),
|
|
17055
|
+
right: array(string().max(80)).max(2048).default([]),
|
|
17056
|
+
source: string().trim().min(1).max(256).describe("Provenance label, not a URL to fetch"),
|
|
17057
|
+
parent: string().uuid().optional()
|
|
17058
|
+
});
|
|
17059
|
+
function merge2(spans) {
|
|
17060
|
+
const out = [];
|
|
17061
|
+
for (const [lo, hi] of spans.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)) {
|
|
17062
|
+
const previous = out.at(-1);
|
|
17063
|
+
if (previous && lo <= previous[1] + 1n)
|
|
17064
|
+
previous[1] = hi > previous[1] ? hi : previous[1];
|
|
17065
|
+
else
|
|
17066
|
+
out.push([lo, hi]);
|
|
17067
|
+
}
|
|
17068
|
+
return out;
|
|
17069
|
+
}
|
|
17070
|
+
function parse5(values, family) {
|
|
17071
|
+
const bits = family === "ipv4" ? 32 : 128;
|
|
17072
|
+
return merge2(values.map((value) => {
|
|
17073
|
+
const parts = value.trim().split("/");
|
|
17074
|
+
if (parts.length > 2 || isIP4(parts[0]) !== (bits === 32 ? 4 : 6) || parts[1] !== undefined && !/^\d+$/.test(parts[1]))
|
|
17075
|
+
throw new Error(`Invalid ${family} prefix: ${value}`);
|
|
17076
|
+
const prefix = parts[1] === undefined ? bits : Number(parts[1]);
|
|
17077
|
+
if (prefix < 0 || prefix > bits)
|
|
17078
|
+
throw new Error(`Invalid prefix length: ${value}`);
|
|
17079
|
+
const address = ipaddr3.parse(parts[0]).toByteArray().reduce((n, b) => n << 8n | BigInt(b), 0n);
|
|
17080
|
+
const size = 1n << BigInt(bits - prefix);
|
|
17081
|
+
const lo = address / size * size;
|
|
17082
|
+
return [lo, lo + size - 1n];
|
|
17083
|
+
}));
|
|
17084
|
+
}
|
|
17085
|
+
function subtract(a, b) {
|
|
17086
|
+
const out = [];
|
|
17087
|
+
for (const [lo, hi] of a) {
|
|
17088
|
+
let start = lo;
|
|
17089
|
+
for (const [bl, bh] of b) {
|
|
17090
|
+
if (bh < start)
|
|
17091
|
+
continue;
|
|
17092
|
+
if (bl > hi)
|
|
17093
|
+
break;
|
|
17094
|
+
if (bl > start)
|
|
17095
|
+
out.push([start, bl - 1n]);
|
|
17096
|
+
start = bh + 1n > start ? bh + 1n : start;
|
|
17097
|
+
if (start > hi)
|
|
17098
|
+
break;
|
|
17099
|
+
}
|
|
17100
|
+
if (start <= hi)
|
|
17101
|
+
out.push([start, hi]);
|
|
17102
|
+
}
|
|
17103
|
+
return out;
|
|
17104
|
+
}
|
|
17105
|
+
function cidrs(spans, family) {
|
|
17106
|
+
const bits = family === "ipv4" ? 32 : 128;
|
|
17107
|
+
const out = [];
|
|
17108
|
+
for (const [lo, hi] of spans) {
|
|
17109
|
+
let start = lo;
|
|
17110
|
+
while (start <= hi) {
|
|
17111
|
+
let hostBits = 0;
|
|
17112
|
+
while (hostBits < bits) {
|
|
17113
|
+
const next = 1n << BigInt(hostBits + 1);
|
|
17114
|
+
if (start % next !== 0n || start + next - 1n > hi)
|
|
17115
|
+
break;
|
|
17116
|
+
hostBits++;
|
|
17117
|
+
}
|
|
17118
|
+
const bytes = Array.from({ length: bits / 8 }, (_, i) => Number(start >> BigInt(bits - 8 - i * 8) & 255n));
|
|
17119
|
+
out.push(`${ipaddr3.fromByteArray(bytes).toString()}/${bits - hostBits}`);
|
|
17120
|
+
if (out.length > 4096)
|
|
17121
|
+
throw new Error("Result exceeds 4096 prefixes; narrow the input.");
|
|
17122
|
+
start += 1n << BigInt(hostBits);
|
|
17123
|
+
}
|
|
17124
|
+
}
|
|
17125
|
+
return out;
|
|
17126
|
+
}
|
|
17127
|
+
function composeAddressSet(input) {
|
|
17128
|
+
const a = addressSetInput.parse(input);
|
|
17129
|
+
return combinePrefixes(a);
|
|
17130
|
+
}
|
|
17131
|
+
function combinePrefixes(a) {
|
|
17132
|
+
if (a.left.length > 4096 || a.right.length > 4096)
|
|
17133
|
+
throw new Error("Operand exceeds 4096 prefixes.");
|
|
17134
|
+
const left = parse5(a.left, a.family), right = parse5(a.right, a.family);
|
|
17135
|
+
const spans = a.operation === "union" ? merge2([...left, ...right]) : a.operation === "difference" ? subtract(left, right) : subtract(left, subtract(left, right));
|
|
17136
|
+
const prefixes = cidrs(spans, a.family);
|
|
17137
|
+
return {
|
|
17138
|
+
prefixes,
|
|
17139
|
+
checksum: createHash6("sha256").update(`${a.family}
|
|
17140
|
+
${prefixes.join(`
|
|
17141
|
+
`)}`).digest("hex"),
|
|
17142
|
+
addresses: spans.reduce((n, [lo, hi]) => n + hi - lo + 1n, 0n).toString()
|
|
17143
|
+
};
|
|
17144
|
+
}
|
|
17145
|
+
var referenceSchema = object({
|
|
17146
|
+
table: _enum(["filter", "mangle"]),
|
|
17147
|
+
id: string().regex(/^\*[0-9A-Fa-f]+$/),
|
|
17148
|
+
field: _enum(["src-address-list", "dst-address-list"]),
|
|
17149
|
+
expected: string().min(1).max(128)
|
|
17150
|
+
});
|
|
17151
|
+
|
|
17152
|
+
// src/address-sets/service.ts
|
|
17153
|
+
import { createHash as createHash7, randomUUID as randomUUID5 } from "crypto";
|
|
17154
|
+
var KIND = "address-set";
|
|
17155
|
+
var hash2 = (value) => createHash7("sha256").update(JSON.stringify(value)).digest("hex");
|
|
17156
|
+
var pathFor = (r) => r.input.family === "ipv4" ? "/ip firewall" : "/ipv6 firewall";
|
|
17157
|
+
function access3(ctx, tool, write = false) {
|
|
17158
|
+
const device = resolveDeviceName(ctx.device);
|
|
17159
|
+
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
17160
|
+
return device;
|
|
17161
|
+
}
|
|
17162
|
+
async function revision(id, device) {
|
|
17163
|
+
const r = (await operationsStore()).get(KIND, id, device);
|
|
17164
|
+
if (!r)
|
|
17165
|
+
throw new Error("Address-set revision not found on this device.");
|
|
17166
|
+
return r;
|
|
17167
|
+
}
|
|
17168
|
+
async function save2(r) {
|
|
17169
|
+
r.updatedAt = Date.now();
|
|
17170
|
+
(await operationsStore()).put(KIND, r);
|
|
17171
|
+
return r;
|
|
17172
|
+
}
|
|
17173
|
+
async function listAddressSets(ctx) {
|
|
17174
|
+
const device = access3(ctx, "list_address_sets");
|
|
17175
|
+
return { revisions: (await operationsStore()).list(KIND, device) };
|
|
17176
|
+
}
|
|
17177
|
+
async function createAddressSet(input, ctx) {
|
|
17178
|
+
const device = access3(ctx, "create_address_set", true);
|
|
17179
|
+
const a = addressSetInput.parse(input), composition = composeAddressSet(a);
|
|
17180
|
+
if (!composition.prefixes.length)
|
|
17181
|
+
throw new Error("An empty set cannot be saved or published.");
|
|
17182
|
+
let delta;
|
|
17183
|
+
if (a.parent) {
|
|
17184
|
+
const parent = await revision(a.parent, device);
|
|
17185
|
+
if (parent.input.name !== a.name || parent.input.family !== a.family)
|
|
17186
|
+
throw new Error("Parent name/family differs; create a new set instead.");
|
|
17187
|
+
const added = combinePrefixes({
|
|
17188
|
+
...a,
|
|
17189
|
+
operation: "difference",
|
|
17190
|
+
left: composition.prefixes,
|
|
17191
|
+
right: parent.prefixes
|
|
17192
|
+
});
|
|
17193
|
+
const removed = combinePrefixes({
|
|
17194
|
+
...a,
|
|
17195
|
+
operation: "difference",
|
|
17196
|
+
left: parent.prefixes,
|
|
17197
|
+
right: composition.prefixes
|
|
17198
|
+
});
|
|
17199
|
+
delta = {
|
|
17200
|
+
added: added.prefixes,
|
|
17201
|
+
removed: removed.prefixes,
|
|
17202
|
+
addedAddresses: added.addresses,
|
|
17203
|
+
removedAddresses: removed.addresses,
|
|
17204
|
+
large: BigInt(added.addresses) * 2n > BigInt(parent.addresses) || BigInt(removed.addresses) * 2n > BigInt(parent.addresses)
|
|
17205
|
+
};
|
|
17206
|
+
}
|
|
17207
|
+
const id = randomUUID5();
|
|
17208
|
+
return save2({
|
|
17209
|
+
id,
|
|
17210
|
+
device,
|
|
17211
|
+
createdAt: Date.now(),
|
|
17212
|
+
updatedAt: Date.now(),
|
|
17213
|
+
input: a,
|
|
17214
|
+
...composition,
|
|
17215
|
+
list: `mcp-as-${id}`,
|
|
17216
|
+
state: "draft",
|
|
17217
|
+
delta
|
|
17218
|
+
});
|
|
17219
|
+
}
|
|
17220
|
+
async function facts2(r, refs, ctx) {
|
|
17221
|
+
const rules = [];
|
|
17222
|
+
for (const table of new Set(refs.map((ref) => ref.table))) {
|
|
17223
|
+
const rows = await readRoutingRows(`${pathFor(r)} ${table}`, undefined, ctx);
|
|
17224
|
+
for (const ref of refs.filter((item) => item.table === table)) {
|
|
17225
|
+
const rule = rows.find((row) => row[".id"] === ref.id);
|
|
17226
|
+
if (!rule)
|
|
17227
|
+
throw new Error(`Rule ${table} ${ref.id} no longer exists.`);
|
|
17228
|
+
const { "#": _position, ...stable } = rule;
|
|
17229
|
+
rules.push({ reference: ref, rule: stable });
|
|
17230
|
+
}
|
|
17231
|
+
}
|
|
17232
|
+
const entries = await readRoutingRows(`${pathFor(r)} address-list`, undefined, ctx, [r.list]);
|
|
17233
|
+
const names = [...new Set(refs.map((ref) => ref.expected.replace(/^!/, "")))];
|
|
17234
|
+
const originals = await readRoutingRows(`${pathFor(r)} address-list`, undefined, ctx, names);
|
|
17235
|
+
if (names.some((name) => !originals.some((entry) => entry.list === name)))
|
|
17236
|
+
throw new Error("An original list is empty or missing; refusing an unsafe reference change.");
|
|
17237
|
+
if (originals.some((entry) => ["yes", "true"].includes(entry.dynamic) || entry.timeout && entry.timeout !== "0s"))
|
|
17238
|
+
throw new Error("Dynamic original lists cannot be safely versioned by this workflow.");
|
|
17239
|
+
return { rules, entries, originals: originals.map(({ "#": _position, ...entry }) => entry) };
|
|
17240
|
+
}
|
|
17241
|
+
function targetList(r, ref, rollback) {
|
|
17242
|
+
return rollback ? ref.expected : `${ref.expected.startsWith("!") ? "!" : ""}${r.list}`;
|
|
17243
|
+
}
|
|
17244
|
+
function addressSetCommands(r, refs, rollback) {
|
|
17245
|
+
const path = pathFor(r);
|
|
17246
|
+
const commands = rollback ? [] : r.prefixes.map((address) => new Cmd(`${path} address-list add`).set("list", r.list).set("address", address).set("comment", `mcp-address-set:${r.id}`).build());
|
|
17247
|
+
for (const ref of refs)
|
|
17248
|
+
commands.push(new Cmd(`${path} ${ref.table} set`).raw(ref.id).set(ref.field, targetList(r, ref, rollback)).build());
|
|
17249
|
+
return commands;
|
|
17250
|
+
}
|
|
17251
|
+
function verifyEntries(r, entries) {
|
|
17252
|
+
if (entries.length !== r.prefixes.length || entries.some((e) => e.comment !== `mcp-address-set:${r.id}` || ["yes", "true"].includes(e.disabled) || ["yes", "true"].includes(e.dynamic) || e.timeout && e.timeout !== "0s"))
|
|
17253
|
+
throw new Error("Generation entries differ from the saved revision.");
|
|
17254
|
+
const actual = composeAddressSet({
|
|
17255
|
+
...r.input,
|
|
17256
|
+
operation: "union",
|
|
17257
|
+
left: entries.map((e) => e.address),
|
|
17258
|
+
right: []
|
|
17259
|
+
});
|
|
17260
|
+
if (actual.checksum !== r.checksum)
|
|
17261
|
+
throw new Error("Generation checksum does not match router read-back.");
|
|
17262
|
+
}
|
|
17263
|
+
async function previewAddressSet(id, references, rollback, ctx, allowLargeChange = false) {
|
|
17264
|
+
const device = access3(ctx, "preview_address_set");
|
|
17265
|
+
const r = await revision(id, device);
|
|
17266
|
+
if (!rollback && !allowLargeChange && (r.delta?.large || r.prefixes.some((p) => p.endsWith("/0"))))
|
|
17267
|
+
throw new Error("Broad coverage change (>50% of parent or /0) requires explicit allowLargeChange acknowledgement.");
|
|
17268
|
+
if (r.state !== (rollback ? "published" : "draft"))
|
|
17269
|
+
throw new Error("Revision state does not permit this operation; uncertain writes require reconciliation.");
|
|
17270
|
+
const refs = rollback ? r.references ?? [] : referenceSchema.array().min(1).max(8).parse(references);
|
|
17271
|
+
if (!refs.length || new Set(refs.map((v) => `${v.table}/${v.id}/${v.field}`)).size !== refs.length)
|
|
17272
|
+
throw new Error("Choose 1\u20138 unique rule references.");
|
|
17273
|
+
if (!rollback && r.prefixes.length > 64)
|
|
17274
|
+
throw new Error("This release publishes at most 64 compacted prefixes plus 8 rule references per Safe Mode transaction. The saved composition remains available.");
|
|
17275
|
+
const before = await facts2(r, refs, ctx);
|
|
17276
|
+
for (const { reference, rule } of before.rules) {
|
|
17277
|
+
if (rule[reference.field] !== (rollback ? targetList(r, reference, false) : reference.expected))
|
|
17278
|
+
throw new Error("Rule reference differs from the expected list. Refresh and review again.");
|
|
17279
|
+
}
|
|
17280
|
+
if (rollback) {
|
|
17281
|
+
verifyEntries(r, before.entries);
|
|
17282
|
+
if (hash2(before.originals) !== r.originalListsHash)
|
|
17283
|
+
throw new Error("Original list contents changed since publication; automatic rollback refused.");
|
|
17284
|
+
} else if (before.entries.length)
|
|
17285
|
+
throw new Error("Generation list already exists; refusing to adopt or overwrite it.");
|
|
17286
|
+
r.plan = {
|
|
17287
|
+
id: randomUUID5(),
|
|
17288
|
+
expiresAt: Date.now() + 120000,
|
|
17289
|
+
references: refs,
|
|
17290
|
+
fingerprint: hash2(before),
|
|
17291
|
+
rollback,
|
|
17292
|
+
commands: addressSetCommands(r, refs, rollback)
|
|
17293
|
+
};
|
|
17294
|
+
return save2(r);
|
|
17295
|
+
}
|
|
17296
|
+
async function applyAddressSet(id, planId, confirm, ctx) {
|
|
17297
|
+
const device = access3(ctx, "apply_address_set", true);
|
|
17298
|
+
if (!confirm)
|
|
17299
|
+
throw new Error("Explicit confirmation is required after reviewing the preview.");
|
|
17300
|
+
const store = await operationsStore(), owner = randomUUID5();
|
|
17301
|
+
store.lock(device, owner);
|
|
17302
|
+
try {
|
|
17303
|
+
const r = await revision(id, device), plan = r.plan;
|
|
17304
|
+
if (!plan || plan.id !== planId || plan.expiresAt < Date.now())
|
|
17305
|
+
throw new Error("Preview expired or changed; preview again.");
|
|
17306
|
+
if (r.state !== (plan.rollback ? "published" : "draft"))
|
|
17307
|
+
throw new Error("Revision requires reconciliation before another write.");
|
|
17308
|
+
const safe = getSafeModeManager(device);
|
|
17309
|
+
if (getDevice(device).mac || safe.isActive)
|
|
17310
|
+
throw new Error("Requires SSH and no existing Safe Mode session.");
|
|
17311
|
+
const before = await facts2(r, plan.references, ctx);
|
|
17312
|
+
if (hash2(before) !== plan.fingerprint)
|
|
17313
|
+
throw new Error("Router changed after preview.");
|
|
17314
|
+
if (!plan.rollback)
|
|
17315
|
+
r.originalListsHash = hash2(before.originals);
|
|
17316
|
+
r.snapshot = await captureSnapshot(ctx, `Before address set ${r.input.name}`, true);
|
|
17317
|
+
r.state = "uncertain";
|
|
17318
|
+
await save2(r);
|
|
17319
|
+
let owned = false, commitAttempted = false;
|
|
17320
|
+
try {
|
|
17321
|
+
if (!(await safe.enable()).startsWith("Safe mode ENABLED"))
|
|
17322
|
+
throw new Error("Could not acquire Safe Mode.");
|
|
17323
|
+
owned = true;
|
|
17324
|
+
const started = Date.now();
|
|
17325
|
+
if (plan.expiresAt < started)
|
|
17326
|
+
throw new Error("Preview expired while capturing the backup; preview again.");
|
|
17327
|
+
if (hash2(await facts2(r, plan.references, ctx)) !== plan.fingerprint)
|
|
17328
|
+
throw new Error("Router changed while entering Safe Mode.");
|
|
17329
|
+
for (const [index, command] of plan.commands.entries()) {
|
|
17330
|
+
if (Date.now() - started > 120000)
|
|
17331
|
+
throw new Error("Publication time budget exceeded; aborting.");
|
|
17332
|
+
if (!plan.rollback && index === r.prefixes.length)
|
|
17333
|
+
verifyEntries(r, (await facts2(r, plan.references, ctx)).entries);
|
|
17334
|
+
await checkedRead(command, ctx);
|
|
17335
|
+
}
|
|
17336
|
+
const after = await facts2(r, plan.references, ctx);
|
|
17337
|
+
verifyEntries(r, after.entries);
|
|
17338
|
+
if (after.rules.some(({ reference, rule }) => rule[reference.field] !== targetList(r, reference, plan.rollback)))
|
|
17339
|
+
throw new Error("Rule read-back did not match the approved plan.");
|
|
17340
|
+
await checkedRead("/system identity print", ctx);
|
|
17341
|
+
commitAttempted = true;
|
|
17342
|
+
if (!(await safe.commit()).ok)
|
|
17343
|
+
throw new Error("Commit uncertain; inspect router state before any retry.");
|
|
17344
|
+
owned = false;
|
|
17345
|
+
r.state = plan.rollback ? "rolled-back" : "published";
|
|
17346
|
+
r.references = plan.references;
|
|
17347
|
+
r.plan = undefined;
|
|
17348
|
+
r.error = undefined;
|
|
17349
|
+
return await save2(r);
|
|
17350
|
+
} catch (error) {
|
|
17351
|
+
if (owned && !commitAttempted)
|
|
17352
|
+
await safe.rollback().catch(() => {});
|
|
17353
|
+
r.state = "uncertain";
|
|
17354
|
+
r.error = error instanceof Error ? error.message : String(error);
|
|
17355
|
+
r.plan = undefined;
|
|
17356
|
+
await save2(r);
|
|
17357
|
+
throw error;
|
|
17358
|
+
}
|
|
17359
|
+
} finally {
|
|
17360
|
+
store.unlock(device, owner);
|
|
17361
|
+
}
|
|
17362
|
+
}
|
|
17363
|
+
|
|
17364
|
+
// src/tools/address-sets.ts
|
|
17365
|
+
var addressSetTools = [
|
|
17366
|
+
defineTool({
|
|
17367
|
+
name: "compose_address_set",
|
|
17368
|
+
title: "Compose an Address Set",
|
|
17369
|
+
annotations: READ,
|
|
17370
|
+
description: "Pure IPv4/IPv6 CIDR union, intersection or difference. Normalizes, deduplicates and compacts exact coverage; returns checksum and exact address count. Source is a provenance label, never fetched/executed. No router or disk I/O.",
|
|
17371
|
+
inputSchema: addressSetInput.shape,
|
|
17372
|
+
handler(a) {
|
|
17373
|
+
return JSON.stringify(composeAddressSet(a));
|
|
17374
|
+
}
|
|
17375
|
+
}),
|
|
17376
|
+
defineTool({
|
|
17377
|
+
name: "list_address_sets",
|
|
17378
|
+
title: "List Address Set Revisions",
|
|
17379
|
+
annotations: READ,
|
|
17380
|
+
description: "Read the newest 100 locally persisted address-set revisions for the selected device, including publication state and rollback references. No router I/O.",
|
|
17381
|
+
inputSchema: {},
|
|
17382
|
+
async handler(_, ctx) {
|
|
17383
|
+
return JSON.stringify(await listAddressSets(ctx));
|
|
17384
|
+
}
|
|
17385
|
+
}),
|
|
17386
|
+
defineTool({
|
|
17387
|
+
name: "create_address_set",
|
|
17388
|
+
title: "Save Address Set Revision",
|
|
17389
|
+
annotations: WRITE,
|
|
17390
|
+
description: "Save an immutable non-empty CIDR composition with checksum, provenance and optional parent revision. Local write only; never changes a router. Input at most 2048 prefixes per operand, output at most 4096. Publication currently capped at 64 compacted prefixes to preserve Safe Mode undo coverage.",
|
|
17391
|
+
inputSchema: addressSetInput.shape,
|
|
17392
|
+
async handler(a, ctx) {
|
|
17393
|
+
return JSON.stringify(await createAddressSet(a, ctx));
|
|
17394
|
+
}
|
|
17395
|
+
}),
|
|
17396
|
+
defineTool({
|
|
17397
|
+
name: "preview_address_set",
|
|
17398
|
+
title: "Preview Address Set Publication or Rollback",
|
|
17399
|
+
annotations: READ,
|
|
17400
|
+
description: "Read current rules and prepare a two-minute state-bound preview. Explicitly select 1\u20138 filter/mangle rule IDs, address-list fields and expected old list names. Creates a new generation without deleting old/manual entries. Rollback restores only these references, retaining generations. Never changes router configuration; use apply_address_set only after explicit review. Not an atomic packet-wide swap.",
|
|
17401
|
+
inputSchema: {
|
|
17402
|
+
id: uuid2(),
|
|
17403
|
+
references: referenceSchema.array().max(8).default([]),
|
|
17404
|
+
rollback: boolean().default(false),
|
|
17405
|
+
allowLargeChange: boolean().default(false).describe("Explicitly acknowledge /0 or coverage changing by more than 50% of the parent")
|
|
17406
|
+
},
|
|
17407
|
+
async handler(a, ctx) {
|
|
17408
|
+
return JSON.stringify(await previewAddressSet(a.id, a.references, a.rollback, ctx, a.allowLargeChange));
|
|
17409
|
+
}
|
|
17410
|
+
}),
|
|
17411
|
+
defineTool({
|
|
17412
|
+
name: "apply_address_set",
|
|
17413
|
+
title: "Apply Approved Address Set Preview",
|
|
17414
|
+
annotations: WRITE,
|
|
17415
|
+
description: "After explicit confirmation: capture a local backup, acquire exclusive Safe Mode, recheck preview fingerprint, create the generation, switch only selected references, verify exact contents and commit. Maximum 64 prefixes + 8 references, SSH only. Failure/ambiguous commit is uncertain and never automatically retried. Rollback previews preserve all lists. Requires fresh preview id and confirm=true.",
|
|
17416
|
+
inputSchema: { id: uuid2(), planId: uuid2(), confirm: boolean().default(false) },
|
|
17417
|
+
async handler(a, ctx) {
|
|
17418
|
+
return JSON.stringify(await applyAddressSet(a.id, a.planId, a.confirm, ctx));
|
|
17419
|
+
}
|
|
17420
|
+
})
|
|
17421
|
+
];
|
|
17422
|
+
|
|
17423
|
+
// src/tools/connected-devices.ts
|
|
17424
|
+
import { isIP as isIP5 } from "net";
|
|
17048
17425
|
var BLOCK_TAG = "mcp-blocked";
|
|
17049
17426
|
function normalizeMac(mac) {
|
|
17050
17427
|
return mac.trim().toUpperCase().replace(/-/g, ":");
|
|
@@ -17241,7 +17618,7 @@ function parseKidDevices(rows) {
|
|
|
17241
17618
|
return Number.isFinite(parsed) ? parsed : null;
|
|
17242
17619
|
};
|
|
17243
17620
|
for (const row of rows) {
|
|
17244
|
-
const addresses = (row["ip-address"] ?? "").split(/[,;]/).map((ip) => ip.trim()).filter((ip) =>
|
|
17621
|
+
const addresses = (row["ip-address"] ?? "").split(/[,;]/).map((ip) => ip.trim()).filter((ip) => isIP5(ip));
|
|
17245
17622
|
const rxBytes = number(row["bytes-down"], true);
|
|
17246
17623
|
const txBytes = number(row["bytes-up"], true);
|
|
17247
17624
|
if (rxBytes == null || txBytes == null)
|
|
@@ -17602,7 +17979,7 @@ ${isEmpty(arp) ? "(no arp entry)" : arp}`;
|
|
|
17602
17979
|
];
|
|
17603
17980
|
|
|
17604
17981
|
// src/investigations/collect.ts
|
|
17605
|
-
import { randomUUID as
|
|
17982
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
17606
17983
|
|
|
17607
17984
|
// src/tools/dr-drill.ts
|
|
17608
17985
|
function parsePingSummary(output) {
|
|
@@ -17773,7 +18150,7 @@ async function collectInvestigation(input, ctx, read = executeMikrotikCommand) {
|
|
|
17773
18150
|
const capture = async (source, command, parse) => {
|
|
17774
18151
|
const startedAt = Date.now();
|
|
17775
18152
|
const e = {
|
|
17776
|
-
id:
|
|
18153
|
+
id: randomUUID6(),
|
|
17777
18154
|
device: d,
|
|
17778
18155
|
source,
|
|
17779
18156
|
startedAt,
|
|
@@ -17849,7 +18226,7 @@ async function collectInvestigation(input, ctx, read = executeMikrotikCommand) {
|
|
|
17849
18226
|
}
|
|
17850
18227
|
assertDeviceAccess(devices, "create_investigation", "WRITE");
|
|
17851
18228
|
return {
|
|
17852
|
-
id:
|
|
18229
|
+
id: randomUUID6(),
|
|
17853
18230
|
createdAt,
|
|
17854
18231
|
finishedAt: Date.now(),
|
|
17855
18232
|
device,
|
|
@@ -18318,6 +18695,7 @@ class TemplateRegistry {
|
|
|
18318
18695
|
templates = new Map;
|
|
18319
18696
|
pending = [];
|
|
18320
18697
|
droppedPending = 0;
|
|
18698
|
+
changedTemplates = 0;
|
|
18321
18699
|
maxPending;
|
|
18322
18700
|
constructor(maxPending = DEFAULT_MAX_PENDING) {
|
|
18323
18701
|
this.maxPending = maxPending;
|
|
@@ -18326,6 +18704,10 @@ class TemplateRegistry {
|
|
|
18326
18704
|
return `${sourceId}/${templateId}`;
|
|
18327
18705
|
}
|
|
18328
18706
|
learn(template) {
|
|
18707
|
+
const previous = this.get(template.sourceId, template.templateId);
|
|
18708
|
+
if (previous && JSON.stringify(previous.fields) !== JSON.stringify(template.fields)) {
|
|
18709
|
+
this.changedTemplates++;
|
|
18710
|
+
}
|
|
18329
18711
|
this.templates.set(TemplateRegistry.key(template.sourceId, template.templateId), template);
|
|
18330
18712
|
}
|
|
18331
18713
|
get(sourceId, templateId) {
|
|
@@ -18361,6 +18743,9 @@ class TemplateRegistry {
|
|
|
18361
18743
|
get droppedCount() {
|
|
18362
18744
|
return this.droppedPending;
|
|
18363
18745
|
}
|
|
18746
|
+
get changedCount() {
|
|
18747
|
+
return this.changedTemplates;
|
|
18748
|
+
}
|
|
18364
18749
|
list() {
|
|
18365
18750
|
return [...this.templates.values()];
|
|
18366
18751
|
}
|
|
@@ -18368,15 +18753,23 @@ class TemplateRegistry {
|
|
|
18368
18753
|
this.templates.clear();
|
|
18369
18754
|
this.pending = [];
|
|
18370
18755
|
this.droppedPending = 0;
|
|
18756
|
+
this.changedTemplates = 0;
|
|
18371
18757
|
}
|
|
18372
18758
|
}
|
|
18373
18759
|
|
|
18374
18760
|
// src/flows/exporter-decoder.ts
|
|
18375
18761
|
class ExporterFlowDecoder {
|
|
18376
18762
|
registries = new Map;
|
|
18763
|
+
health = new Map;
|
|
18764
|
+
sequences = new Map;
|
|
18377
18765
|
decode(packet, exporter, now) {
|
|
18378
18766
|
const version = (packet[0] ?? 0) << 8 | (packet[1] ?? 0);
|
|
18379
|
-
const
|
|
18767
|
+
const headerSize = version === 5 ? 24 : version === 9 ? 20 : version === 10 ? 16 : 0;
|
|
18768
|
+
if (!headerSize || packet.length < headerSize)
|
|
18769
|
+
return decodeFlowPacket(packet, new TemplateRegistry, now);
|
|
18770
|
+
const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
|
|
18771
|
+
const domain = version === 9 ? view.getUint32(16) : version === 10 ? view.getUint32(12) : view.getUint16(20);
|
|
18772
|
+
const key = `${exporter}/${version}/${domain}`;
|
|
18380
18773
|
let registry = this.registries.get(key);
|
|
18381
18774
|
if (!registry) {
|
|
18382
18775
|
if (this.registries.size >= 128)
|
|
@@ -18390,17 +18783,59 @@ class ExporterFlowDecoder {
|
|
|
18390
18783
|
registry = new TemplateRegistry;
|
|
18391
18784
|
this.registries.set(key, registry);
|
|
18392
18785
|
}
|
|
18393
|
-
|
|
18786
|
+
const result = decodeFlowPacket(packet, registry, now);
|
|
18787
|
+
const state = this.health.get(key) ?? {
|
|
18788
|
+
exporter,
|
|
18789
|
+
version,
|
|
18790
|
+
domain,
|
|
18791
|
+
packets: 0,
|
|
18792
|
+
records: 0,
|
|
18793
|
+
errors: 0,
|
|
18794
|
+
lastSeen: now,
|
|
18795
|
+
sequenceGaps: 0,
|
|
18796
|
+
reordered: 0,
|
|
18797
|
+
templateChanges: 0,
|
|
18798
|
+
pending: 0,
|
|
18799
|
+
stale: false
|
|
18800
|
+
};
|
|
18801
|
+
state.packets++;
|
|
18802
|
+
state.records += result.records.length;
|
|
18803
|
+
state.errors += result.error ? 1 : 0;
|
|
18804
|
+
state.lastSeen = now;
|
|
18805
|
+
state.templateChanges = registry.changedCount;
|
|
18806
|
+
state.pending = registry.pendingCount;
|
|
18807
|
+
if (version === 9 && !result.error) {
|
|
18808
|
+
const sequence = view.getUint32(12);
|
|
18809
|
+
const previous = this.sequences.get(key);
|
|
18810
|
+
const delta = previous === undefined ? 1 : sequence - previous >>> 0;
|
|
18811
|
+
if (delta === 0 || delta >= 2147483648)
|
|
18812
|
+
state.reordered++;
|
|
18813
|
+
else {
|
|
18814
|
+
state.sequenceGaps += delta - 1;
|
|
18815
|
+
this.sequences.set(key, sequence);
|
|
18816
|
+
}
|
|
18817
|
+
}
|
|
18818
|
+
this.health.set(key, state);
|
|
18819
|
+
return result;
|
|
18394
18820
|
}
|
|
18395
18821
|
clear() {
|
|
18396
18822
|
this.registries.clear();
|
|
18823
|
+
this.health.clear();
|
|
18824
|
+
this.sequences.clear();
|
|
18397
18825
|
}
|
|
18398
|
-
stats() {
|
|
18399
|
-
|
|
18826
|
+
stats(now = Date.now()) {
|
|
18827
|
+
const totals = [...this.registries.values()].reduce((sum, r) => ({
|
|
18400
18828
|
templates: sum.templates + r.size,
|
|
18401
18829
|
templatesPending: sum.templatesPending + r.pendingCount,
|
|
18402
18830
|
templatesDropped: sum.templatesDropped + r.droppedCount
|
|
18403
18831
|
}), { templates: 0, templatesPending: 0, templatesDropped: 0 });
|
|
18832
|
+
return {
|
|
18833
|
+
...totals,
|
|
18834
|
+
exporterHealth: [...this.health.values()].map((state) => ({
|
|
18835
|
+
...state,
|
|
18836
|
+
stale: now - state.lastSeen > 300000
|
|
18837
|
+
}))
|
|
18838
|
+
};
|
|
18404
18839
|
}
|
|
18405
18840
|
}
|
|
18406
18841
|
|
|
@@ -18422,6 +18857,7 @@ class FlowCollector {
|
|
|
18422
18857
|
packets = 0;
|
|
18423
18858
|
flows = 0;
|
|
18424
18859
|
decodeErrors = 0;
|
|
18860
|
+
storageDropped = 0;
|
|
18425
18861
|
lastError;
|
|
18426
18862
|
exporters = new Map;
|
|
18427
18863
|
get running() {
|
|
@@ -18477,6 +18913,7 @@ class FlowCollector {
|
|
|
18477
18913
|
this.packets = 0;
|
|
18478
18914
|
this.flows = 0;
|
|
18479
18915
|
this.decodeErrors = 0;
|
|
18916
|
+
this.storageDropped = 0;
|
|
18480
18917
|
this.lastError = undefined;
|
|
18481
18918
|
this.exporters = new Map;
|
|
18482
18919
|
}
|
|
@@ -18508,6 +18945,7 @@ class FlowCollector {
|
|
|
18508
18945
|
try {
|
|
18509
18946
|
this.store.insert(batch);
|
|
18510
18947
|
} catch (e) {
|
|
18948
|
+
this.storageDropped += batch.length;
|
|
18511
18949
|
logger.error(`Flow store insert failed (${batch.length} records dropped): ${String(e)}`);
|
|
18512
18950
|
}
|
|
18513
18951
|
}
|
|
@@ -18534,7 +18972,8 @@ class FlowCollector {
|
|
|
18534
18972
|
lastError: this.lastError,
|
|
18535
18973
|
...this.decoder.stats(),
|
|
18536
18974
|
exporters: Object.fromEntries(this.exporters),
|
|
18537
|
-
queued: this.queue.length
|
|
18975
|
+
queued: this.queue.length,
|
|
18976
|
+
storageDropped: this.storageDropped
|
|
18538
18977
|
};
|
|
18539
18978
|
}
|
|
18540
18979
|
drain() {
|
|
@@ -19060,6 +19499,15 @@ function talkerTable(title, rows) {
|
|
|
19060
19499
|
`);
|
|
19061
19500
|
}
|
|
19062
19501
|
var trafficFlowTools = [
|
|
19502
|
+
defineTool({
|
|
19503
|
+
name: "get_flow_collector_health",
|
|
19504
|
+
title: "Inspect Flow Collector Health",
|
|
19505
|
+
annotations: READ,
|
|
19506
|
+
description: "Reads host collector health per exporter, protocol and observation domain: last receipt, " + "template changes, pending templates, decode errors and failed storage writes. NetFlow v9 " + "sequence gaps are observations, not proven packet loss (UDP can reorder). IPFIX loss is " + "not estimated. Silent >5m means no exports received, not proof the router is offline. " + "Counters reset when the collector restarts. No router changes.",
|
|
19507
|
+
handler() {
|
|
19508
|
+
return JSON.stringify(getFlowCollector().stats(), null, 2);
|
|
19509
|
+
}
|
|
19510
|
+
}),
|
|
19063
19511
|
defineTool({
|
|
19064
19512
|
name: "get_traffic_flow_settings",
|
|
19065
19513
|
title: "Get Traffic Flow Settings",
|
|
@@ -19558,7 +20006,7 @@ var investigationTools = [
|
|
|
19558
20006
|
];
|
|
19559
20007
|
|
|
19560
20008
|
// src/home/policies.ts
|
|
19561
|
-
import { createHash as
|
|
20009
|
+
import { createHash as createHash8, randomUUID as randomUUID7 } from "crypto";
|
|
19562
20010
|
|
|
19563
20011
|
// src/home/store.ts
|
|
19564
20012
|
import { mkdirSync as mkdirSync7 } from "fs";
|
|
@@ -19700,7 +20148,7 @@ function buildPolicy(id, input, facts) {
|
|
|
19700
20148
|
...generated,
|
|
19701
20149
|
warnings,
|
|
19702
20150
|
queueBefore,
|
|
19703
|
-
fingerprint:
|
|
20151
|
+
fingerprint: createHash8("sha256").update(stable).digest("hex")
|
|
19704
20152
|
};
|
|
19705
20153
|
}
|
|
19706
20154
|
async function policyFacts(ctx, read = executeMikrotikCommand) {
|
|
@@ -19736,7 +20184,7 @@ async function previewPolicy(input, ctx) {
|
|
|
19736
20184
|
a.mac = a.mac.toUpperCase();
|
|
19737
20185
|
assertDeviceAccess([device], "preview_home_policy", "WRITE");
|
|
19738
20186
|
return exclusive(device, async () => {
|
|
19739
|
-
const id =
|
|
20187
|
+
const id = randomUUID7();
|
|
19740
20188
|
const plan = {
|
|
19741
20189
|
id,
|
|
19742
20190
|
device,
|
|
@@ -20016,7 +20464,7 @@ var homeInternetTools = [
|
|
|
20016
20464
|
];
|
|
20017
20465
|
|
|
20018
20466
|
// src/tools/service-contracts.ts
|
|
20019
|
-
import { randomUUID as
|
|
20467
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
20020
20468
|
|
|
20021
20469
|
// src/service-contracts/store.ts
|
|
20022
20470
|
import { mkdirSync as mkdirSync8 } from "fs";
|
|
@@ -20062,7 +20510,7 @@ function contractStore() {
|
|
|
20062
20510
|
}
|
|
20063
20511
|
|
|
20064
20512
|
// src/service-contracts/run.ts
|
|
20065
|
-
import { randomUUID as
|
|
20513
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
20066
20514
|
|
|
20067
20515
|
// src/sim/ip.ts
|
|
20068
20516
|
var IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
|
|
@@ -21331,7 +21779,7 @@ async function evaluateContract(contract, io, simulationExport) {
|
|
|
21331
21779
|
}
|
|
21332
21780
|
}
|
|
21333
21781
|
return {
|
|
21334
|
-
id:
|
|
21782
|
+
id: randomUUID8(),
|
|
21335
21783
|
contractId: contract.id,
|
|
21336
21784
|
device: contract.device,
|
|
21337
21785
|
startedAt,
|
|
@@ -21456,7 +21904,7 @@ var serviceContractTools = [
|
|
|
21456
21904
|
const args = contractInput.parse(a);
|
|
21457
21905
|
if (args.checks.some((c) => !getConfig().serviceProbes.targets[c.target]))
|
|
21458
21906
|
throw new Error("Contract references an unapproved target. Ask the administrator to configure it.");
|
|
21459
|
-
const contract = { ...args, id:
|
|
21907
|
+
const contract = { ...args, id: randomUUID9(), device, createdAt: Date.now() };
|
|
21460
21908
|
(await contractStore()).save(contract);
|
|
21461
21909
|
return JSON.stringify(contract);
|
|
21462
21910
|
}
|
|
@@ -21650,7 +22098,7 @@ var flightRecorderTools = [
|
|
|
21650
22098
|
];
|
|
21651
22099
|
|
|
21652
22100
|
// src/recovery-lab/model.ts
|
|
21653
|
-
import { createHash as
|
|
22101
|
+
import { createHash as createHash9 } from "crypto";
|
|
21654
22102
|
var rosVersion = string().regex(/^7\.\d+(?:\.\d+)?(?:beta\d+|rc\d+)?$/);
|
|
21655
22103
|
var recoveryInput = object({
|
|
21656
22104
|
snapshotId: string().min(1).max(100),
|
|
@@ -21696,7 +22144,7 @@ var resultSchema = object({
|
|
|
21696
22144
|
elapsedMs: number().int().min(0).max(3600000).optional(),
|
|
21697
22145
|
cleanup: _enum(["pending", "destroyed", "failed"])
|
|
21698
22146
|
});
|
|
21699
|
-
var sha256 = (value) =>
|
|
22147
|
+
var sha256 = (value) => createHash9("sha256").update(value).digest("hex");
|
|
21700
22148
|
var FIELDS = {
|
|
21701
22149
|
"/interface/bridge": ["name", "protocol-mode", "vlan-filtering", "pvid", "disabled"],
|
|
21702
22150
|
"/interface/vlan": ["name", "interface", "vlan-id", "disabled"],
|
|
@@ -21886,13 +22334,13 @@ async function callRunner(method, path, body) {
|
|
|
21886
22334
|
|
|
21887
22335
|
// src/recovery-lab/service.ts
|
|
21888
22336
|
var kind3 = "recovery-lab";
|
|
21889
|
-
function
|
|
22337
|
+
function access4(ctx, tool, write = false) {
|
|
21890
22338
|
const device = resolveDeviceName(ctx.device);
|
|
21891
22339
|
assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
|
|
21892
22340
|
return device;
|
|
21893
22341
|
}
|
|
21894
22342
|
async function getRecovery(ctx) {
|
|
21895
|
-
const device =
|
|
22343
|
+
const device = access4(ctx, "get_recovery_lab");
|
|
21896
22344
|
let configured = false, configurationError;
|
|
21897
22345
|
try {
|
|
21898
22346
|
configured = !!runnerConfig();
|
|
@@ -21906,7 +22354,7 @@ async function getRecovery(ctx) {
|
|
|
21906
22354
|
};
|
|
21907
22355
|
}
|
|
21908
22356
|
async function recoveryInventory(ctx) {
|
|
21909
|
-
const device =
|
|
22357
|
+
const device = access4(ctx, "recovery_lab_inventory"), store = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
21910
22358
|
try {
|
|
21911
22359
|
const snapshots = store.list(device, 50).map((s) => ({ id: s.id, at: s.ts, label: s.label, version: s.rosVersion }));
|
|
21912
22360
|
const cfg = runnerConfig();
|
|
@@ -21919,7 +22367,7 @@ async function recoveryInventory(ctx) {
|
|
|
21919
22367
|
}
|
|
21920
22368
|
}
|
|
21921
22369
|
async function prepareRecovery(input, ctx) {
|
|
21922
|
-
const device =
|
|
22370
|
+
const device = access4(ctx, "prepare_recovery_lab", true), a = recoveryInput.parse(input);
|
|
21923
22371
|
const snapshots = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
|
|
21924
22372
|
try {
|
|
21925
22373
|
const source = snapshots.get(a.snapshotId);
|
|
@@ -21972,7 +22420,7 @@ async function editRun(id, device, work) {
|
|
|
21972
22420
|
store.unlock(`lab:${device}`, owner);
|
|
21973
22421
|
}
|
|
21974
22422
|
}
|
|
21975
|
-
async function
|
|
22423
|
+
async function save3(run) {
|
|
21976
22424
|
run.updatedAt = Date.now();
|
|
21977
22425
|
(await operationsStore()).put(kind3, run);
|
|
21978
22426
|
}
|
|
@@ -21982,7 +22430,7 @@ function boundRunner(run) {
|
|
|
21982
22430
|
throw new Error("Runner changed or is unavailable. Never send an existing rehearsal to a different destination.");
|
|
21983
22431
|
}
|
|
21984
22432
|
async function startRecovery(id, confirm, ctx) {
|
|
21985
|
-
const device =
|
|
22433
|
+
const device = access4(ctx, "start_recovery_lab", true);
|
|
21986
22434
|
if (!confirm)
|
|
21987
22435
|
throw new Error("Explicit confirmation is required to send the reviewed subset to the configured isolated runner.");
|
|
21988
22436
|
return editRun(id, device, async (run) => {
|
|
@@ -22026,7 +22474,7 @@ async function startRecovery(id, confirm, ctx) {
|
|
|
22026
22474
|
run.requestSha256 = sha256(JSON.stringify(request));
|
|
22027
22475
|
run.startedAt = Date.now();
|
|
22028
22476
|
run.state = "uncertain";
|
|
22029
|
-
await
|
|
22477
|
+
await save3(run);
|
|
22030
22478
|
try {
|
|
22031
22479
|
const result = validateRunnerResult(await callRunner("PUT", `/v1/runs/${run.id}`, {
|
|
22032
22480
|
...request,
|
|
@@ -22038,12 +22486,12 @@ async function startRecovery(id, confirm, ctx) {
|
|
|
22038
22486
|
} catch {
|
|
22039
22487
|
run.error = "Submission outcome is uncertain. Poll this run ID before any further action; no automatic retry was attempted.";
|
|
22040
22488
|
}
|
|
22041
|
-
await
|
|
22489
|
+
await save3(run);
|
|
22042
22490
|
return run;
|
|
22043
22491
|
});
|
|
22044
22492
|
}
|
|
22045
22493
|
async function pollRecovery(id, ctx) {
|
|
22046
|
-
const device =
|
|
22494
|
+
const device = access4(ctx, "poll_recovery_lab");
|
|
22047
22495
|
return editRun(id, device, async (run) => {
|
|
22048
22496
|
if (!run.requestSha256)
|
|
22049
22497
|
throw new Error("This rehearsal has not been submitted.");
|
|
@@ -22057,12 +22505,12 @@ async function pollRecovery(id, ctx) {
|
|
|
22057
22505
|
run.state = "uncertain";
|
|
22058
22506
|
run.error = "Runner evidence unavailable or mismatched. Last-known results retained, not treated as fresh.";
|
|
22059
22507
|
}
|
|
22060
|
-
await
|
|
22508
|
+
await save3(run);
|
|
22061
22509
|
return run;
|
|
22062
22510
|
});
|
|
22063
22511
|
}
|
|
22064
22512
|
async function destroyRecovery(id, confirm, ctx) {
|
|
22065
|
-
const device =
|
|
22513
|
+
const device = access4(ctx, "destroy_recovery_lab", true);
|
|
22066
22514
|
if (!confirm)
|
|
22067
22515
|
throw new Error("Confirm deletion of this disposable lab only.");
|
|
22068
22516
|
return editRun(id, device, async (run) => {
|
|
@@ -22070,7 +22518,7 @@ async function destroyRecovery(id, confirm, ctx) {
|
|
|
22070
22518
|
throw new Error("This rehearsal has not been submitted.");
|
|
22071
22519
|
boundRunner(run);
|
|
22072
22520
|
run.state = "uncertain";
|
|
22073
|
-
await
|
|
22521
|
+
await save3(run);
|
|
22074
22522
|
try {
|
|
22075
22523
|
const result = validateRunnerResult(await callRunner("DELETE", `/v1/runs/${run.id}`), run);
|
|
22076
22524
|
run.result = result;
|
|
@@ -22081,7 +22529,7 @@ async function destroyRecovery(id, confirm, ctx) {
|
|
|
22081
22529
|
} catch {
|
|
22082
22530
|
run.error = "Lab cleanup is not confirmed. Inspect the runner and poll this ID; production routers were not contacted.";
|
|
22083
22531
|
}
|
|
22084
|
-
await
|
|
22532
|
+
await save3(run);
|
|
22085
22533
|
return run;
|
|
22086
22534
|
});
|
|
22087
22535
|
}
|
|
@@ -27197,13 +27645,13 @@ var containerTools = [
|
|
|
27197
27645
|
];
|
|
27198
27646
|
|
|
27199
27647
|
// src/core/firewall-audit.ts
|
|
27200
|
-
import * as
|
|
27648
|
+
import * as ipaddr4 from "ipaddr.js";
|
|
27201
27649
|
|
|
27202
27650
|
// src/schedule/identity.ts
|
|
27203
|
-
import { createHash as
|
|
27651
|
+
import { createHash as createHash10 } from "crypto";
|
|
27204
27652
|
function stableId(prefix, parts) {
|
|
27205
27653
|
const material = parts.filter((p) => p !== undefined && p !== "").map((p) => String(p).trim().toLowerCase()).join(" | ");
|
|
27206
|
-
const digest =
|
|
27654
|
+
const digest = createHash10("sha256").update(material, "utf8").digest("hex").slice(0, 12);
|
|
27207
27655
|
return `${prefix}:${digest}`;
|
|
27208
27656
|
}
|
|
27209
27657
|
function ruleFingerprint(rule) {
|
|
@@ -27316,8 +27764,8 @@ function rulesFromRows(rows) {
|
|
|
27316
27764
|
function toCidr(value) {
|
|
27317
27765
|
try {
|
|
27318
27766
|
if (value.includes("/"))
|
|
27319
|
-
return
|
|
27320
|
-
const addr =
|
|
27767
|
+
return ipaddr4.parseCIDR(value);
|
|
27768
|
+
const addr = ipaddr4.parse(value);
|
|
27321
27769
|
return [addr, addr.kind() === "ipv6" ? 128 : 32];
|
|
27322
27770
|
} catch {
|
|
27323
27771
|
return null;
|
|
@@ -28153,7 +28601,7 @@ var cache3 = null;
|
|
|
28153
28601
|
async function gateway() {
|
|
28154
28602
|
if (cache3)
|
|
28155
28603
|
return cache3;
|
|
28156
|
-
const { moduleCatalog } = await import("./cli-
|
|
28604
|
+
const { moduleCatalog } = await import("./cli-fvjmfzab.js");
|
|
28157
28605
|
const forIndex = [];
|
|
28158
28606
|
const byName = new Map;
|
|
28159
28607
|
for (const mod of moduleCatalog) {
|
|
@@ -31698,6 +32146,178 @@ var policyTools = [
|
|
|
31698
32146
|
})
|
|
31699
32147
|
];
|
|
31700
32148
|
|
|
32149
|
+
// src/sim/verify.ts
|
|
32150
|
+
var verificationSchema = object({
|
|
32151
|
+
config_text: string().min(1).max(200000),
|
|
32152
|
+
source: string().max(64),
|
|
32153
|
+
destination: string().max(64),
|
|
32154
|
+
source_ports: string().max(64).default("0-65535"),
|
|
32155
|
+
destination_ports: string().max(64).default("0-65535"),
|
|
32156
|
+
protocol: _enum(["tcp", "udp"]).default("tcp"),
|
|
32157
|
+
chain: _enum(["input", "forward", "output"]).default("forward"),
|
|
32158
|
+
in_interface: string().max(128).default("bridge"),
|
|
32159
|
+
out_interface: string().max(128).default("ether1"),
|
|
32160
|
+
connection_state: _enum(["new", "established", "related", "invalid"]).default("new"),
|
|
32161
|
+
expect: _enum(["accept", "drop", "reject"]).default("drop")
|
|
32162
|
+
});
|
|
32163
|
+
var SCOPE = "IPv4 filter-chain entry only; declared interfaces/state; static export. Not end-to-end reachability or NAT/routing verification.";
|
|
32164
|
+
var MAX_CELLS = 4096;
|
|
32165
|
+
var ALLOWED = new Set([
|
|
32166
|
+
"chain",
|
|
32167
|
+
"action",
|
|
32168
|
+
"disabled",
|
|
32169
|
+
"comment",
|
|
32170
|
+
"log",
|
|
32171
|
+
"log-prefix",
|
|
32172
|
+
"jump-target",
|
|
32173
|
+
"reject-with",
|
|
32174
|
+
"src-address",
|
|
32175
|
+
"dst-address",
|
|
32176
|
+
"src-address-list",
|
|
32177
|
+
"dst-address-list",
|
|
32178
|
+
"src-port",
|
|
32179
|
+
"dst-port",
|
|
32180
|
+
"port",
|
|
32181
|
+
"protocol",
|
|
32182
|
+
"in-interface",
|
|
32183
|
+
"out-interface",
|
|
32184
|
+
"connection-state"
|
|
32185
|
+
]);
|
|
32186
|
+
function addressRange(text) {
|
|
32187
|
+
if (text.includes("-")) {
|
|
32188
|
+
const parts = text.split("-");
|
|
32189
|
+
const lo = parseIp(parts[0]);
|
|
32190
|
+
const hi = parseIp(parts[1] ?? "");
|
|
32191
|
+
if (parts.length === 2 && lo !== null && hi !== null && lo <= hi)
|
|
32192
|
+
return [lo, hi];
|
|
32193
|
+
} else if (/^\d+\.\d+\.\d+\.\d+(\/\d{1,2})?$/.test(text)) {
|
|
32194
|
+
const cidr = parseCidr(text);
|
|
32195
|
+
if (cidr)
|
|
32196
|
+
return [cidr.network, cidr.network + 2 ** (32 - cidr.prefix) - 1];
|
|
32197
|
+
}
|
|
32198
|
+
throw new Error(`Unsupported IPv4 address/range: ${text}`);
|
|
32199
|
+
}
|
|
32200
|
+
function portRange(text) {
|
|
32201
|
+
if (!/^\d+(?:-\d+)?$/.test(text))
|
|
32202
|
+
throw new Error(`Invalid port range: ${text}`);
|
|
32203
|
+
const [lo, end] = text.split("-").map(Number);
|
|
32204
|
+
const hi = end ?? lo;
|
|
32205
|
+
if (lo > hi || hi > 65535)
|
|
32206
|
+
throw new Error(`Invalid port range: ${text}`);
|
|
32207
|
+
return [lo, hi];
|
|
32208
|
+
}
|
|
32209
|
+
function representatives(scope, boundaries) {
|
|
32210
|
+
const points = new Set([scope[0]]);
|
|
32211
|
+
for (const [lo, hi] of boundaries) {
|
|
32212
|
+
if (lo > scope[0] && lo <= scope[1])
|
|
32213
|
+
points.add(lo);
|
|
32214
|
+
if (hi + 1 > scope[0] && hi + 1 <= scope[1])
|
|
32215
|
+
points.add(hi + 1);
|
|
32216
|
+
}
|
|
32217
|
+
return [...points].sort((a, b) => a - b);
|
|
32218
|
+
}
|
|
32219
|
+
function verifyPolicy(input) {
|
|
32220
|
+
const a = verificationSchema.parse(input);
|
|
32221
|
+
const result = {
|
|
32222
|
+
status: "unknown",
|
|
32223
|
+
scope: SCOPE,
|
|
32224
|
+
reason: "",
|
|
32225
|
+
cells: 0,
|
|
32226
|
+
checked: 0
|
|
32227
|
+
};
|
|
32228
|
+
try {
|
|
32229
|
+
const source = addressRange(a.source);
|
|
32230
|
+
const destination = addressRange(a.destination);
|
|
32231
|
+
const sourcePorts = portRange(a.source_ports);
|
|
32232
|
+
const destinationPorts = portRange(a.destination_ports);
|
|
32233
|
+
const parsed = parseExport(a.config_text);
|
|
32234
|
+
if (parsed.unparsed.length)
|
|
32235
|
+
throw new Error("Export contains unparsed lines.");
|
|
32236
|
+
const filter = recordsOf(parsed, "/ip/firewall/filter");
|
|
32237
|
+
if (!filter.length)
|
|
32238
|
+
throw new Error("No filter rules in supplied export; completeness cannot be established.");
|
|
32239
|
+
if (filter.length > 256)
|
|
32240
|
+
throw new Error("More than 256 filter rules; narrow the supplied model.");
|
|
32241
|
+
const model = buildModel(a.config_text);
|
|
32242
|
+
const lists = recordsOf(parsed, "/ip/firewall/address-list");
|
|
32243
|
+
const src = [], dst = [], sp = [], dp = [];
|
|
32244
|
+
for (const rule of filter) {
|
|
32245
|
+
if (rule.op !== "add")
|
|
32246
|
+
throw new Error(`Only exported add rules supported (line ${rule.line}).`);
|
|
32247
|
+
if (["yes", "true"].includes(rule.fields.disabled))
|
|
32248
|
+
continue;
|
|
32249
|
+
for (const [field, raw] of Object.entries(rule.fields)) {
|
|
32250
|
+
if (!ALLOWED.has(field))
|
|
32251
|
+
throw new Error(`Unsupported ${field} at line ${rule.line}.`);
|
|
32252
|
+
const value = raw.replace(/^!/, "");
|
|
32253
|
+
if (field === "action" && !["accept", "drop", "reject", "jump", "return", "log", "passthrough"].includes(value))
|
|
32254
|
+
throw new Error(`Unsupported action ${value} at line ${rule.line}.`);
|
|
32255
|
+
if (field === "src-address" || field === "dst-address")
|
|
32256
|
+
(field === "src-address" ? src : dst).push(addressRange(value));
|
|
32257
|
+
if (field === "src-address-list" || field === "dst-address-list") {
|
|
32258
|
+
const members = lists.filter((r) => r.fields.list === value);
|
|
32259
|
+
if (!members.length)
|
|
32260
|
+
throw new Error(`List ${value} is absent; dynamic membership cannot be proven.`);
|
|
32261
|
+
for (const member of members) {
|
|
32262
|
+
if (member.op !== "add" || member.fields.timeout || member.fields.dynamic)
|
|
32263
|
+
throw new Error(`List ${value} has non-static membership.`);
|
|
32264
|
+
(field === "src-address-list" ? src : dst).push(addressRange(member.fields.address ?? ""));
|
|
32265
|
+
}
|
|
32266
|
+
}
|
|
32267
|
+
if (["src-port", "dst-port", "port"].includes(field)) {
|
|
32268
|
+
const ranges = value.split(",").map(portRange);
|
|
32269
|
+
if (field !== "dst-port")
|
|
32270
|
+
sp.push(...ranges);
|
|
32271
|
+
if (field !== "src-port")
|
|
32272
|
+
dp.push(...ranges);
|
|
32273
|
+
}
|
|
32274
|
+
}
|
|
32275
|
+
}
|
|
32276
|
+
const axes = [
|
|
32277
|
+
representatives(source, src),
|
|
32278
|
+
representatives(destination, dst),
|
|
32279
|
+
representatives(sourcePorts, sp),
|
|
32280
|
+
representatives(destinationPorts, dp)
|
|
32281
|
+
];
|
|
32282
|
+
result.cells = axes.reduce((n, axis) => n * axis.length, 1);
|
|
32283
|
+
if (result.cells > MAX_CELLS)
|
|
32284
|
+
throw new Error(`Analysis requires ${result.cells} cells; limit is ${MAX_CELLS}. Narrow the scope.`);
|
|
32285
|
+
for (const s of axes[0])
|
|
32286
|
+
for (const d of axes[1])
|
|
32287
|
+
for (const p of axes[2])
|
|
32288
|
+
for (const q of axes[3]) {
|
|
32289
|
+
const packet = {
|
|
32290
|
+
srcAddress: formatIp(s),
|
|
32291
|
+
dstAddress: formatIp(d),
|
|
32292
|
+
srcPort: p,
|
|
32293
|
+
dstPort: q,
|
|
32294
|
+
protocol: a.protocol,
|
|
32295
|
+
inInterface: a.in_interface,
|
|
32296
|
+
outInterface: a.out_interface,
|
|
32297
|
+
connectionState: a.connection_state
|
|
32298
|
+
};
|
|
32299
|
+
const trace = traverseChain(model, model.filter, a.chain, packet);
|
|
32300
|
+
result.checked++;
|
|
32301
|
+
if (trace.verdict !== a.expect) {
|
|
32302
|
+
return {
|
|
32303
|
+
...result,
|
|
32304
|
+
status: trace.verdict === "unknown" ? "unknown" : "violated",
|
|
32305
|
+
reason: `Expected ${a.expect}; model returned ${trace.verdict}.`,
|
|
32306
|
+
witness: packet,
|
|
32307
|
+
trace: trace.steps
|
|
32308
|
+
};
|
|
32309
|
+
}
|
|
32310
|
+
}
|
|
32311
|
+
return {
|
|
32312
|
+
...result,
|
|
32313
|
+
status: "proved",
|
|
32314
|
+
reason: `All ${result.cells} equivalence cells satisfy ${a.expect} within the stated filter-only model.`
|
|
32315
|
+
};
|
|
32316
|
+
} catch (error) {
|
|
32317
|
+
return { ...result, reason: error instanceof Error ? error.message : String(error) };
|
|
32318
|
+
}
|
|
32319
|
+
}
|
|
32320
|
+
|
|
31701
32321
|
// src/tools/simulate.ts
|
|
31702
32322
|
var storePromise8 = null;
|
|
31703
32323
|
function snapshots4() {
|
|
@@ -31761,6 +32381,16 @@ A packet whose path crosses one of these is reported UNKNOWN.`;
|
|
|
31761
32381
|
}
|
|
31762
32382
|
var SCOPE_NOTE = " Models IPv4 filter/NAT/routing only: no raw table, no queues, no layer7, no IPv6, and no live " + "connection tracking (`connection_state` is declared by you, not inferred). Anything on the " + "path that is out of scope downgrades the verdict to UNKNOWN rather than guessing.";
|
|
31763
32383
|
var simulateTools = [
|
|
32384
|
+
defineTool({
|
|
32385
|
+
name: "verify_filter_policy",
|
|
32386
|
+
title: "Verify a Filter Policy over Address and Port Sets",
|
|
32387
|
+
annotations: READ,
|
|
32388
|
+
description: "Exhaustively checks IPv4 source/destination ranges and port ranges using equivalence partitions, not sampling. Returns proved, violated with a counterexample and rule trace, or unknown. Supplied static export only; packet fields are at filter-chain entry, AFTER any destination NAT. This is NOT routing/NAT/IPv6/conntrack verification and cannot prove no WAN leak. Unsupported constructs, dynamic lists or >4096 cells fail closed to unknown. No router I/O.",
|
|
32389
|
+
inputSchema: verificationSchema.shape,
|
|
32390
|
+
handler(a) {
|
|
32391
|
+
return JSON.stringify(verifyPolicy(a), null, 2);
|
|
32392
|
+
}
|
|
32393
|
+
}),
|
|
31764
32394
|
defineTool({
|
|
31765
32395
|
name: "simulate_packet",
|
|
31766
32396
|
title: "Simulate a Packet",
|
|
@@ -39803,12 +40433,12 @@ ${result}`;
|
|
|
39803
40433
|
];
|
|
39804
40434
|
|
|
39805
40435
|
// src/core/ip-intelligence.ts
|
|
39806
|
-
import { isIP as
|
|
39807
|
-
import
|
|
40436
|
+
import { isIP as isIP7 } from "net";
|
|
40437
|
+
import ipaddr5 from "ipaddr.js";
|
|
39808
40438
|
|
|
39809
40439
|
// src/observability/geo.ts
|
|
39810
40440
|
import { lookup } from "dns/promises";
|
|
39811
|
-
import { BlockList, isIP as
|
|
40441
|
+
import { BlockList, isIP as isIP6 } from "net";
|
|
39812
40442
|
// src/data/iran-asns.json
|
|
39813
40443
|
var iran_asns_default = {
|
|
39814
40444
|
source: "https://whois.ipip.net/iso/IR",
|
|
@@ -42209,10 +42839,10 @@ nonPublic.addSubnet("fc00::", 7, "ipv6");
|
|
|
42209
42839
|
nonPublic.addSubnet("fe80::", 10, "ipv6");
|
|
42210
42840
|
nonPublic.addSubnet("ff00::", 8, "ipv6");
|
|
42211
42841
|
function isIpLiteral(host) {
|
|
42212
|
-
return
|
|
42842
|
+
return isIP6(host) !== 0;
|
|
42213
42843
|
}
|
|
42214
42844
|
function isPublicIpLiteral(host) {
|
|
42215
|
-
const version =
|
|
42845
|
+
const version = isIP6(host);
|
|
42216
42846
|
return version !== 0 && !nonPublic.check(host, version === 6 ? "ipv6" : "ipv4");
|
|
42217
42847
|
}
|
|
42218
42848
|
async function publicIpOf(host) {
|
|
@@ -42382,7 +43012,7 @@ function stopGeoLookups() {
|
|
|
42382
43012
|
|
|
42383
43013
|
// src/core/ip-intelligence.ts
|
|
42384
43014
|
var IpIntelligenceInput = object({
|
|
42385
|
-
ip: string().trim().max(64).refine((ip) =>
|
|
43015
|
+
ip: string().trim().max(64).refine((ip) => isIP7(ip) !== 0, "Enter an IPv4 or IPv6 literal, not a hostname, URL, port or CIDR")
|
|
42386
43016
|
});
|
|
42387
43017
|
var cache5 = new Map;
|
|
42388
43018
|
var active3 = 0;
|
|
@@ -42439,10 +43069,10 @@ async function provider(url) {
|
|
|
42439
43069
|
}
|
|
42440
43070
|
async function lookupIpIntelligence(input) {
|
|
42441
43071
|
const { ip: literal } = IpIntelligenceInput.parse(input);
|
|
42442
|
-
const ip =
|
|
43072
|
+
const ip = ipaddr5.parse(literal).toString();
|
|
42443
43073
|
const base = {
|
|
42444
43074
|
ip,
|
|
42445
|
-
version:
|
|
43075
|
+
version: isIP7(ip),
|
|
42446
43076
|
public: isPublicIpLiteral(ip),
|
|
42447
43077
|
lookedUpAt: Date.now(),
|
|
42448
43078
|
cached: false,
|
|
@@ -44104,7 +44734,7 @@ var wolTools = [
|
|
|
44104
44734
|
];
|
|
44105
44735
|
|
|
44106
44736
|
// src/core/openvpn-sessions.ts
|
|
44107
|
-
import { randomUUID as
|
|
44737
|
+
import { randomUUID as randomUUID10 } from "crypto";
|
|
44108
44738
|
|
|
44109
44739
|
// src/core/openvpn-sessions-model.ts
|
|
44110
44740
|
function openVpnUptime(value) {
|
|
@@ -44138,7 +44768,7 @@ var disconnectOpenVpnInput = object({
|
|
|
44138
44768
|
token: string().uuid().describe("Fresh disconnectToken from list_ovpn_sessions on this router; expires after 60 seconds and is single-use."),
|
|
44139
44769
|
confirm: literal(true).describe("Explicit operator approval to terminate this one live connection. The client can reconnect.")
|
|
44140
44770
|
});
|
|
44141
|
-
function
|
|
44771
|
+
function access5(ctx, write = false) {
|
|
44142
44772
|
if (!ctx.device)
|
|
44143
44773
|
throw new OpenVpnOperationError(400, "Select an explicit router first.");
|
|
44144
44774
|
let device;
|
|
@@ -44204,10 +44834,10 @@ async function read(ctx) {
|
|
|
44204
44834
|
return parseOpenVpnSessions(output);
|
|
44205
44835
|
}
|
|
44206
44836
|
async function listOpenVpnSessions(ctx) {
|
|
44207
|
-
const device =
|
|
44837
|
+
const device = access5(ctx);
|
|
44208
44838
|
let canDisconnect = true;
|
|
44209
44839
|
try {
|
|
44210
|
-
|
|
44840
|
+
access5(ctx, true);
|
|
44211
44841
|
} catch {
|
|
44212
44842
|
canDisconnect = false;
|
|
44213
44843
|
}
|
|
@@ -44229,7 +44859,7 @@ async function listOpenVpnSessions(ctx) {
|
|
|
44229
44859
|
continue;
|
|
44230
44860
|
if (tickets.size >= 1e4)
|
|
44231
44861
|
tickets.delete(tickets.keys().next().value);
|
|
44232
|
-
session.disconnectToken =
|
|
44862
|
+
session.disconnectToken = randomUUID10();
|
|
44233
44863
|
tickets.set(session.disconnectToken, { device, at, session });
|
|
44234
44864
|
}
|
|
44235
44865
|
next.expires = at + 2000;
|
|
@@ -44259,7 +44889,7 @@ function disconnectOpenVpnCommand(session) {
|
|
|
44259
44889
|
return `{ :local ids [${find}]; :if ([:len $ids] = 0) do={ :put "ovpn:gone" } else={ :if ([:len $ids] != 1) do={ :error "Ambiguous session" }; :local id [:pick $ids 0]; :if (${checks} || ([/ppp active get $id uptime] < [:totime ${literal2(session.uptime)}])) do={ :put "ovpn:changed" } else={ ${new Cmd("/ppp active remove").raw("$id").build()}; :put "ovpn:sent" } } }`;
|
|
44260
44890
|
}
|
|
44261
44891
|
async function disconnectOpenVpnSession(input, ctx) {
|
|
44262
|
-
const device =
|
|
44892
|
+
const device = access5(ctx, true);
|
|
44263
44893
|
const { token } = disconnectOpenVpnInput.parse(input);
|
|
44264
44894
|
const ticket = tickets.get(token);
|
|
44265
44895
|
if (!ticket || ticket.device !== device || Date.now() - ticket.at >= TICKET_TTL)
|
|
@@ -53446,7 +54076,7 @@ var riskByTool = null;
|
|
|
53446
54076
|
async function riskIndex() {
|
|
53447
54077
|
if (riskByTool)
|
|
53448
54078
|
return riskByTool;
|
|
53449
|
-
const { moduleCatalog } = await import("./cli-
|
|
54079
|
+
const { moduleCatalog } = await import("./cli-fvjmfzab.js");
|
|
53450
54080
|
const index = new Map;
|
|
53451
54081
|
for (const mod of moduleCatalog) {
|
|
53452
54082
|
for (const tool of mod.tools)
|
|
@@ -55668,7 +56298,7 @@ async function readScanList(ctx, list = "port-scanners") {
|
|
|
55668
56298
|
}
|
|
55669
56299
|
|
|
55670
56300
|
// src/attack/correlate.ts
|
|
55671
|
-
import { createHash as
|
|
56301
|
+
import { createHash as createHash11 } from "crypto";
|
|
55672
56302
|
var STAGE_ORDER = ["recon", "attempt", "breach", "persistence"];
|
|
55673
56303
|
var STAGE_OF = {
|
|
55674
56304
|
"port-scan": "recon",
|
|
@@ -55698,7 +56328,7 @@ var SEVERITY_RANK = {
|
|
|
55698
56328
|
info: 4
|
|
55699
56329
|
};
|
|
55700
56330
|
function incidentId(source, dayBucket) {
|
|
55701
|
-
const digest =
|
|
56331
|
+
const digest = createHash11("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
|
|
55702
56332
|
return `atk_${digest}`;
|
|
55703
56333
|
}
|
|
55704
56334
|
function worst(values) {
|
|
@@ -57081,11 +57711,11 @@ var serverPulseTools = [
|
|
|
57081
57711
|
];
|
|
57082
57712
|
|
|
57083
57713
|
// src/observability/config-admin.ts
|
|
57084
|
-
import { createHash as
|
|
57714
|
+
import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
|
|
57085
57715
|
import { readFileSync as readFileSync10 } from "fs";
|
|
57086
57716
|
|
|
57087
57717
|
// src/config-write.ts
|
|
57088
|
-
import { randomUUID as
|
|
57718
|
+
import { randomUUID as randomUUID11 } from "crypto";
|
|
57089
57719
|
import {
|
|
57090
57720
|
closeSync,
|
|
57091
57721
|
constants,
|
|
@@ -57181,7 +57811,7 @@ function backupName(path, ts) {
|
|
|
57181
57811
|
}
|
|
57182
57812
|
function atomicWrite(path, text) {
|
|
57183
57813
|
mkdirSync16(dirname17(path), { recursive: true });
|
|
57184
|
-
const tmp = `${path}.tmp-${
|
|
57814
|
+
const tmp = `${path}.tmp-${randomUUID11()}`;
|
|
57185
57815
|
try {
|
|
57186
57816
|
writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx", flush: true });
|
|
57187
57817
|
try {
|
|
@@ -57213,7 +57843,7 @@ function writeMountedFile(path, text) {
|
|
|
57213
57843
|
throw new Error("Configuration target must be a regular file.");
|
|
57214
57844
|
fchmodSync(fd, 384);
|
|
57215
57845
|
const previous = readFileSync9(fd);
|
|
57216
|
-
const backup = `${path}.bak-mounted-${
|
|
57846
|
+
const backup = `${path}.bak-mounted-${randomUUID11()}`;
|
|
57217
57847
|
writeFileSync4(backup, previous, { mode: 384, flag: "wx", flush: true });
|
|
57218
57848
|
try {
|
|
57219
57849
|
replaceContents(fd, Buffer.from(text, "utf8"));
|
|
@@ -57246,8 +57876,8 @@ function validateConfig(raw) {
|
|
|
57246
57876
|
function createConfigAdmin(deps) {
|
|
57247
57877
|
let pending = null;
|
|
57248
57878
|
let lastTimestamp = 0;
|
|
57249
|
-
const salt =
|
|
57250
|
-
const fingerprint = (config, source, contents) =>
|
|
57879
|
+
const salt = randomUUID12();
|
|
57880
|
+
const fingerprint = (config, source, contents) => createHash12("sha256").update(salt).update(JSON.stringify([config, source, contents])).digest("hex");
|
|
57251
57881
|
const revision = () => {
|
|
57252
57882
|
const source = deps.source();
|
|
57253
57883
|
return fingerprint(deps.getConfig(), source, deps.readFile(source.path));
|
|
@@ -61603,7 +62233,7 @@ ${doomed}`;
|
|
|
61603
62233
|
];
|
|
61604
62234
|
|
|
61605
62235
|
// src/core/wifi-survey.ts
|
|
61606
|
-
import { randomUUID as
|
|
62236
|
+
import { randomUUID as randomUUID13 } from "crypto";
|
|
61607
62237
|
var DONE = "MCP-SURVEY-DONE";
|
|
61608
62238
|
var FAILED = "MCP-SURVEY-FAILED";
|
|
61609
62239
|
var PENDING = "MCP-SURVEY-PENDING";
|
|
@@ -61612,7 +62242,7 @@ function readFile(file) {
|
|
|
61612
62242
|
return `:local surveyFiles [${find}]; :if ([:len $surveyFiles] = 0) do={ :put "${PENDING}" } else={ ` + `:if ([/file get ($surveyFiles->0) size] > 60000) do={ :error "failure: survey exceeds safe contents read size" }; ` + `:put [/file get ($surveyFiles->0) contents] }`;
|
|
61613
62243
|
}
|
|
61614
62244
|
async function runWifiSurvey(path, iface, duration, ctx) {
|
|
61615
|
-
const base = `mcp-wifi-survey-${
|
|
62245
|
+
const base = `mcp-wifi-survey-${randomUUID13()}`;
|
|
61616
62246
|
const report = `${base}.txt`;
|
|
61617
62247
|
const status = `${base}-status.txt`;
|
|
61618
62248
|
const scan = new Cmd(`${path} frequency-scan`).raw(quoteValue(iface)).set("duration", `${duration}s`).set("save-file", report).build();
|
|
@@ -64018,6 +64648,13 @@ var moduleCatalog2 = [
|
|
|
64018
64648
|
description: "Firewall address-lists (`/ip firewall address-list`).",
|
|
64019
64649
|
tools: addressListTools
|
|
64020
64650
|
},
|
|
64651
|
+
{
|
|
64652
|
+
label: "Address Sets",
|
|
64653
|
+
slug: "address-sets",
|
|
64654
|
+
group: "Security",
|
|
64655
|
+
description: "Versioned CIDR algebra, publication previews and guarded rollback of selected rule references.",
|
|
64656
|
+
tools: addressSetTools
|
|
64657
|
+
},
|
|
64021
64658
|
{
|
|
64022
64659
|
label: "Connected Devices",
|
|
64023
64660
|
slug: "connected-devices",
|
|
@@ -64608,4 +65245,4 @@ function selectToolModules2(filter = {}, catalog = moduleCatalog2) {
|
|
|
64608
65245
|
}).map((m) => m.tools);
|
|
64609
65246
|
}
|
|
64610
65247
|
|
|
64611
|
-
export { __toESM, __commonJS, clone, normalizeParams, own, installLazyProp, $constructor, parse, parseAsync, safeParse, safeParseAsync, $ZodType, $ZodObject, toJSONSchema, ZodError, string, number, boolean, _null, unknown, array, object, looseObject, union, discriminatedUnion, intersection, record, _enum, literal, ZodOptional, optional, custom, preprocess, datetime, exports_coerce, DEFAULT_DASHBOARD_DB2, DEFAULT_SNAPSHOT_DB2, DEFAULT_BACKUP_DIR2, DEFAULT_CONFIG_HISTORY_DIR2, McpServerSettingsSchema2, DeviceConfigSchema2, DashboardConfigSchema2, MemoryConfigSchema2, SSHConfigSchema2, ToolFilterSchema2, AccessConfigSchema2, MikrotikConfigSchema2, getConfigSource2, loadConfig2, logger, deviceEndpoints, onConfigChanged, setConfig, getConfig, listDevices, deviceLabels, resolveDeviceName, deviceDirectory, DeviceConnectionError, isMacTelnetDevice, createDeviceClient, describeTransport, isPoolEnabled, closeAll, closeDevice, poolStatus, ScopeSchema, RememberSchema, ReviseSchema, RecallSchema, BrowseSchema, openMemoryStore, getMemoryStore, closeMemoryStore, installMemoryStore, Cmd, isEmpty, looksLikeError, commandUnsupported, createContext, evaluateAccess, previewAccessPolicy, getAccessPolicy, hasSessionNarrowing, recentDenials, assertDeviceAccess, getSafeModeManager, parseKeyValues, parseRouterosDate, parseSize, parseRecords, parseLeadingNumber, executeMikrotikCommand, isYes, parseExportMeta2, normalizeExport2, contentSha2, countLines2, openSnapshotStore2, captureSnapshot, startRoutingMonitor, stopRoutingMonitor, riskOf, redact, configureRecorder, getEventStore, subscribe, subscriberCount, startFlightRecorder, stopFlightRecorder, explainUnmet, serializeCapabilities, getCapabilities, peekCapabilities, invalidateCapabilities, redactChannels, setMcpAlertSender, deliver, parseDuration, AlertRuleSchema, isEventTrigger, ruleWarnings, eventMet, initialState, step, isMuted, parseRules, AlertEngine, setAlertEngine, getAlertEngine, registerTools, clientCheckOrigin, noteClientPresence, authorizedCheck, saveCheckRun, clientCheckTools, parseExport, routerMigrationTools, supportBundleTools, fetchDevices, sampleDeviceTraffic, KID_CONTROL_COUNTERS_COMMAND, parseKidControlOutput, sampleAllTraffic, setDeviceLimits, blockDevice, allowDevice, makeDeviceStatic, setDeviceIp, setDeviceLabel, removeDeviceLease, devicesView, getFlowCollector, topTalkers, conversations, protocolMix, timeline, summarize, flowStore, FlowPathError, investigationTools, homeInternetTools, buildModel, unreachableRules, tracePacket, diffTraces, listSuites, getSuite, saveSuite, serviceContractTools, serviceRoutingTools, flightRecorderTools, recoveryLabTools, roundTripTools, PROMPTS_DIR, PROJECT_ROOT, UI_DIST_DIR, registerUiResources, backupDir, listBackups, readBackup, writeBackup, deleteBackup, renameBackup, createLocalBackup, restoreLocalBackup, isS3Configured, getS3Client, presignExpiresIn, s3Target, splitCommands, buildChangePlan, renderPlan, diffLines, noteDriftResult, analyzeDrift, attributeChanges, CONTAINER_GUIDE_URI, getRouterosContainerGuide, CONTAINER_INSTRUCTIONS, containerPromptGuidance, applyWritesSafely, evaluatePolicies, validatePolicyText, renderReport, rememberReport, currentPolicySet, buildFabricMap, collectFabric, ADVISORY_DATASET_DATE, ADVISORIES, matchAdvisories, collectDeviceFacts, getDeviceGeo, sourceIpLiteral, getIpGeo, ipGeoRoute, startGeoLookups, stopGeoLookups, IpIntelligenceInput, lookupIpIntelligence, DEFAULT_TZSP_PORT, capture, OpenVpnOperationError, disconnectOpenVpnInput, listOpenVpnSessions, disconnectOpenVpnSession, AAA_ENTITIES, listAaaEntity, addAaaEntity, updateAaaEntity, removeAaaEntity, toggleAaaEntity, getRadiusIncoming, setRadiusIncoming, resetRadiusCounters, getUmSettings, setUmSettings, requestAbort, runTransaction, createDeviceExecutor, subscribeTxn, liveTxnUpdates, toRecord, getTxn, dropTxn, listTxns, txnStore, persistTxn, publishRollout, subscribeRollout, liveRolloutUpdates, requestHold, resume, requestAbort2, summarize2, buildTopology, getDeviceStatus, getDeviceNeighbors, getDeviceHistory, probeDevice, startHealthChecks, stopHealthChecks, runRollout, createDeviceExecutor2, toRecord2, getRollout, dropRollout, listRollouts, rolloutStore, persistRollout, auditAdapter, schedulableTools, nextRun, describeCron, diffFindings, describeDiff, worstSeverity, severityCounts, JobSchema, scheduleStore, runJob, armJob, nextRunOf, forgetJob, primeRiskIndex, liveExecutor, runnerOptions, startScheduler, stopScheduler, analyzeDevice, diffNarratives, renderDiff, topologyMermaid, NARRATIVE_SECTIONS, renderNarrative, isPlan, neverBlockSet, isNeverBlock, decide, executePlan, revokeBlock, attackStore, buildGuards, policyFromConfig, sweep, startAttackDetection, stopAttackDetection, VERSION, WEBSITE_URL, LOGO_URL, SERVER_TITLE, SERVER_DESCRIPTION, SERVER_NAME, PKG_META, loadFileCacheSync, fetchLatestRelease, checkForUpdate, updateSummaryLine, fetchAllReleases, scopeConfigDraft, mergeDeviceDraft, mergeConfigDraft, serializeConfig, atomicWrite, validateConfig, getConfigAdmin, VLAN_GUIDE_URI, getVlanSegmentationGuide, VLAN_INSTRUCTIONS, vlanPromptGuidance, buildChannelPlanCommands, reportWeakClients, runCapsmanAudit, steerAlreadyPresent, buildSteerCommands, loadBalancePlan, buildLoadBalanceCommands, buildFtCommands, buildHaCommands, haGuidance, capsmanOverview, fetchCapsmanState, moduleCatalog2, allToolModules2, ALWAYS_ON_MODULES2, selectToolModules2 };
|
|
65248
|
+
export { __toESM, __commonJS, clone, normalizeParams, own, installLazyProp, $constructor, parse, parseAsync, safeParse, safeParseAsync, $ZodType, $ZodObject, toJSONSchema, ZodError, string, number, boolean, _null, unknown, array, object, looseObject, union, discriminatedUnion, intersection, record, _enum, literal, ZodOptional, optional, custom, preprocess, datetime, exports_coerce, DEFAULT_DASHBOARD_DB2, DEFAULT_SNAPSHOT_DB2, DEFAULT_BACKUP_DIR2, DEFAULT_CONFIG_HISTORY_DIR2, McpServerSettingsSchema2, DeviceConfigSchema2, DashboardConfigSchema2, MemoryConfigSchema2, SSHConfigSchema2, ToolFilterSchema2, AccessConfigSchema2, MikrotikConfigSchema2, getConfigSource2, loadConfig2, logger, deviceEndpoints, onConfigChanged, setConfig, getConfig, listDevices, deviceLabels, resolveDeviceName, deviceDirectory, DeviceConnectionError, isMacTelnetDevice, createDeviceClient, describeTransport, isPoolEnabled, closeAll, closeDevice, poolStatus, ScopeSchema, RememberSchema, ReviseSchema, RecallSchema, BrowseSchema, openMemoryStore, getMemoryStore, closeMemoryStore, installMemoryStore, Cmd, isEmpty, looksLikeError, commandUnsupported, createContext, evaluateAccess, previewAccessPolicy, getAccessPolicy, hasSessionNarrowing, recentDenials, assertDeviceAccess, getSafeModeManager, parseKeyValues, parseRouterosDate, parseSize, parseRecords, parseLeadingNumber, executeMikrotikCommand, isYes, parseExportMeta2, normalizeExport2, contentSha2, countLines2, openSnapshotStore2, captureSnapshot, startRoutingMonitor, stopRoutingMonitor, riskOf, redact, configureRecorder, getEventStore, subscribe, subscriberCount, startFlightRecorder, stopFlightRecorder, explainUnmet, serializeCapabilities, getCapabilities, peekCapabilities, invalidateCapabilities, redactChannels, setMcpAlertSender, deliver, parseDuration, AlertRuleSchema, isEventTrigger, ruleWarnings, eventMet, initialState, step, isMuted, parseRules, AlertEngine, setAlertEngine, getAlertEngine, registerTools, clientCheckOrigin, noteClientPresence, authorizedCheck, saveCheckRun, clientCheckTools, parseExport, routerMigrationTools, supportBundleTools, addressSetTools, fetchDevices, sampleDeviceTraffic, KID_CONTROL_COUNTERS_COMMAND, parseKidControlOutput, sampleAllTraffic, setDeviceLimits, blockDevice, allowDevice, makeDeviceStatic, setDeviceIp, setDeviceLabel, removeDeviceLease, devicesView, getFlowCollector, topTalkers, conversations, protocolMix, timeline, summarize, flowStore, FlowPathError, investigationTools, homeInternetTools, buildModel, unreachableRules, tracePacket, diffTraces, listSuites, getSuite, saveSuite, serviceContractTools, serviceRoutingTools, flightRecorderTools, recoveryLabTools, roundTripTools, PROMPTS_DIR, PROJECT_ROOT, UI_DIST_DIR, registerUiResources, backupDir, listBackups, readBackup, writeBackup, deleteBackup, renameBackup, createLocalBackup, restoreLocalBackup, isS3Configured, getS3Client, presignExpiresIn, s3Target, splitCommands, buildChangePlan, renderPlan, diffLines, noteDriftResult, analyzeDrift, attributeChanges, CONTAINER_GUIDE_URI, getRouterosContainerGuide, CONTAINER_INSTRUCTIONS, containerPromptGuidance, applyWritesSafely, evaluatePolicies, validatePolicyText, renderReport, rememberReport, currentPolicySet, verificationSchema, verifyPolicy, buildFabricMap, collectFabric, ADVISORY_DATASET_DATE, ADVISORIES, matchAdvisories, collectDeviceFacts, getDeviceGeo, sourceIpLiteral, getIpGeo, ipGeoRoute, startGeoLookups, stopGeoLookups, IpIntelligenceInput, lookupIpIntelligence, DEFAULT_TZSP_PORT, capture, OpenVpnOperationError, disconnectOpenVpnInput, listOpenVpnSessions, disconnectOpenVpnSession, AAA_ENTITIES, listAaaEntity, addAaaEntity, updateAaaEntity, removeAaaEntity, toggleAaaEntity, getRadiusIncoming, setRadiusIncoming, resetRadiusCounters, getUmSettings, setUmSettings, requestAbort, runTransaction, createDeviceExecutor, subscribeTxn, liveTxnUpdates, toRecord, getTxn, dropTxn, listTxns, txnStore, persistTxn, publishRollout, subscribeRollout, liveRolloutUpdates, requestHold, resume, requestAbort2, summarize2, buildTopology, getDeviceStatus, getDeviceNeighbors, getDeviceHistory, probeDevice, startHealthChecks, stopHealthChecks, runRollout, createDeviceExecutor2, toRecord2, getRollout, dropRollout, listRollouts, rolloutStore, persistRollout, auditAdapter, schedulableTools, nextRun, describeCron, diffFindings, describeDiff, worstSeverity, severityCounts, JobSchema, scheduleStore, runJob, armJob, nextRunOf, forgetJob, primeRiskIndex, liveExecutor, runnerOptions, startScheduler, stopScheduler, analyzeDevice, diffNarratives, renderDiff, topologyMermaid, NARRATIVE_SECTIONS, renderNarrative, isPlan, neverBlockSet, isNeverBlock, decide, executePlan, revokeBlock, attackStore, buildGuards, policyFromConfig, sweep, startAttackDetection, stopAttackDetection, VERSION, WEBSITE_URL, LOGO_URL, SERVER_TITLE, SERVER_DESCRIPTION, SERVER_NAME, PKG_META, loadFileCacheSync, fetchLatestRelease, checkForUpdate, updateSummaryLine, fetchAllReleases, scopeConfigDraft, mergeDeviceDraft, mergeConfigDraft, serializeConfig, atomicWrite, validateConfig, getConfigAdmin, VLAN_GUIDE_URI, getVlanSegmentationGuide, VLAN_INSTRUCTIONS, vlanPromptGuidance, buildChannelPlanCommands, reportWeakClients, runCapsmanAudit, steerAlreadyPresent, buildSteerCommands, loadBalancePlan, buildLoadBalanceCommands, buildFtCommands, buildHaCommands, haGuidance, capsmanOverview, fetchCapsmanState, moduleCatalog2, allToolModules2, ALWAYS_ON_MODULES2, selectToolModules2 };
|