@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.
@@ -15512,13 +15512,13 @@ async function undoMigration(id, confirm, selected) {
15512
15512
  throw new Error("Undo lost Safe Mode or exceeded its time budget.");
15513
15513
  await checkedRead(item.undo, createContext(undefined, device));
15514
15514
  }
15515
- const beforeTarget = (await import("./library-rbaybv2t.js")).openSnapshotStore;
15516
- const db = await beforeTarget((await import("./library-4c9wrr75.js")).DEFAULT_SNAPSHOT_DB);
15515
+ const beforeTarget = (await import("./library-djammhn2.js")).openSnapshotStore;
15516
+ const db = await beforeTarget((await import("./library-9c5k05ge.js")).DEFAULT_SNAPSHOT_DB);
15517
15517
  try {
15518
15518
  const original = db.get(p.snapshots.target);
15519
15519
  if (!original)
15520
15520
  throw new Error("Original target snapshot unavailable.");
15521
- const { normalizeExport } = await import("./library-gcbk2m7w.js");
15521
+ const { normalizeExport } = await import("./library-ys83rjgm.js");
15522
15522
  if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
15523
15523
  throw new Error("Target differs from its backup. Undo verification failed.");
15524
15524
  } finally {
@@ -15961,6 +15961,531 @@ ${result}`;
15961
15961
  })
15962
15962
  ];
15963
15963
 
15964
+ // src/address-sets/model.ts
15965
+ import { createHash as createHash4 } from "crypto";
15966
+ import { isIP } from "net";
15967
+ import ipaddr2 from "ipaddr.js";
15968
+ var addressSetInput = object({
15969
+ name: string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,39}$/),
15970
+ family: _enum(["ipv4", "ipv6"]).default("ipv4"),
15971
+ operation: _enum(["union", "intersection", "difference"]).default("union"),
15972
+ left: array(string().max(80)).min(1).max(2048),
15973
+ right: array(string().max(80)).max(2048).default([]),
15974
+ source: string().trim().min(1).max(256).describe("Provenance label, not a URL to fetch"),
15975
+ parent: string().uuid().optional()
15976
+ });
15977
+ function merge2(spans) {
15978
+ const out = [];
15979
+ for (const [lo, hi] of spans.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)) {
15980
+ const previous = out.at(-1);
15981
+ if (previous && lo <= previous[1] + 1n)
15982
+ previous[1] = hi > previous[1] ? hi : previous[1];
15983
+ else
15984
+ out.push([lo, hi]);
15985
+ }
15986
+ return out;
15987
+ }
15988
+ function parse5(values, family) {
15989
+ const bits = family === "ipv4" ? 32 : 128;
15990
+ return merge2(values.map((value) => {
15991
+ const parts = value.trim().split("/");
15992
+ if (parts.length > 2 || isIP(parts[0]) !== (bits === 32 ? 4 : 6) || parts[1] !== undefined && !/^\d+$/.test(parts[1]))
15993
+ throw new Error(`Invalid ${family} prefix: ${value}`);
15994
+ const prefix = parts[1] === undefined ? bits : Number(parts[1]);
15995
+ if (prefix < 0 || prefix > bits)
15996
+ throw new Error(`Invalid prefix length: ${value}`);
15997
+ const address = ipaddr2.parse(parts[0]).toByteArray().reduce((n, b) => n << 8n | BigInt(b), 0n);
15998
+ const size = 1n << BigInt(bits - prefix);
15999
+ const lo = address / size * size;
16000
+ return [lo, lo + size - 1n];
16001
+ }));
16002
+ }
16003
+ function subtract(a, b) {
16004
+ const out = [];
16005
+ for (const [lo, hi] of a) {
16006
+ let start = lo;
16007
+ for (const [bl, bh] of b) {
16008
+ if (bh < start)
16009
+ continue;
16010
+ if (bl > hi)
16011
+ break;
16012
+ if (bl > start)
16013
+ out.push([start, bl - 1n]);
16014
+ start = bh + 1n > start ? bh + 1n : start;
16015
+ if (start > hi)
16016
+ break;
16017
+ }
16018
+ if (start <= hi)
16019
+ out.push([start, hi]);
16020
+ }
16021
+ return out;
16022
+ }
16023
+ function cidrs(spans, family) {
16024
+ const bits = family === "ipv4" ? 32 : 128;
16025
+ const out = [];
16026
+ for (const [lo, hi] of spans) {
16027
+ let start = lo;
16028
+ while (start <= hi) {
16029
+ let hostBits = 0;
16030
+ while (hostBits < bits) {
16031
+ const next = 1n << BigInt(hostBits + 1);
16032
+ if (start % next !== 0n || start + next - 1n > hi)
16033
+ break;
16034
+ hostBits++;
16035
+ }
16036
+ const bytes = Array.from({ length: bits / 8 }, (_, i) => Number(start >> BigInt(bits - 8 - i * 8) & 255n));
16037
+ out.push(`${ipaddr2.fromByteArray(bytes).toString()}/${bits - hostBits}`);
16038
+ if (out.length > 4096)
16039
+ throw new Error("Result exceeds 4096 prefixes; narrow the input.");
16040
+ start += 1n << BigInt(hostBits);
16041
+ }
16042
+ }
16043
+ return out;
16044
+ }
16045
+ function composeAddressSet(input) {
16046
+ const a = addressSetInput.parse(input);
16047
+ return combinePrefixes(a);
16048
+ }
16049
+ function combinePrefixes(a) {
16050
+ if (a.left.length > 4096 || a.right.length > 4096)
16051
+ throw new Error("Operand exceeds 4096 prefixes.");
16052
+ const left = parse5(a.left, a.family), right = parse5(a.right, a.family);
16053
+ const spans = a.operation === "union" ? merge2([...left, ...right]) : a.operation === "difference" ? subtract(left, right) : subtract(left, subtract(left, right));
16054
+ const prefixes = cidrs(spans, a.family);
16055
+ return {
16056
+ prefixes,
16057
+ checksum: createHash4("sha256").update(`${a.family}
16058
+ ${prefixes.join(`
16059
+ `)}`).digest("hex"),
16060
+ addresses: spans.reduce((n, [lo, hi]) => n + hi - lo + 1n, 0n).toString()
16061
+ };
16062
+ }
16063
+ var referenceSchema = object({
16064
+ table: _enum(["filter", "mangle"]),
16065
+ id: string().regex(/^\*[0-9A-Fa-f]+$/),
16066
+ field: _enum(["src-address-list", "dst-address-list"]),
16067
+ expected: string().min(1).max(128)
16068
+ });
16069
+
16070
+ // src/address-sets/service.ts
16071
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "crypto";
16072
+
16073
+ // src/operations/store.ts
16074
+ import { mkdirSync as mkdirSync6, chmodSync } from "fs";
16075
+ import { dirname as dirname7, join as join6 } from "path";
16076
+ class OperationsStore {
16077
+ db;
16078
+ constructor(db) {
16079
+ this.db = db;
16080
+ db.run("PRAGMA busy_timeout = 3000");
16081
+ db.run("CREATE TABLE IF NOT EXISTS workspace_records (kind TEXT, id TEXT, device TEXT, updated INTEGER, body TEXT, PRIMARY KEY(kind,id))");
16082
+ db.run("CREATE INDEX IF NOT EXISTS workspace_device ON workspace_records(kind,device,updated DESC)");
16083
+ db.run("CREATE TABLE IF NOT EXISTS workspace_locks (device TEXT PRIMARY KEY, owner TEXT NOT NULL)");
16084
+ }
16085
+ get(kind, id, device) {
16086
+ const row = this.db.query("SELECT body FROM workspace_records WHERE kind=? AND id=? AND device=?").get(kind, id, device);
16087
+ return row ? JSON.parse(row.body) : undefined;
16088
+ }
16089
+ list(kind, device, limit = 100) {
16090
+ return this.db.query("SELECT body FROM workspace_records WHERE kind=? AND device=? ORDER BY updated DESC LIMIT ?").all(kind, device, Math.min(500, limit)).map((r) => JSON.parse(r.body));
16091
+ }
16092
+ put(kind, record) {
16093
+ this.db.query("INSERT INTO workspace_records VALUES (?,?,?,?,?) ON CONFLICT(kind,id) DO UPDATE SET updated=excluded.updated,body=excluded.body WHERE device=excluded.device").run(kind, record.id, record.device, record.updatedAt, JSON.stringify(record));
16094
+ }
16095
+ delete(kind, id, device) {
16096
+ this.db.query("DELETE FROM workspace_records WHERE kind=? AND id=? AND device=?").run(kind, id, device);
16097
+ }
16098
+ prune(kind, device, before) {
16099
+ this.db.query("DELETE FROM workspace_records WHERE kind=? AND device=? AND updated<?").run(kind, device, before);
16100
+ }
16101
+ lock(device, owner) {
16102
+ const result = this.db.query("INSERT OR IGNORE INTO workspace_locks VALUES (?,?)").run(device, owner);
16103
+ if (!result.changes)
16104
+ throw new Error("Another workspace operation holds this router. An interrupted operation requires reconciliation before retrying.");
16105
+ }
16106
+ unlock(device, owner) {
16107
+ this.db.query("DELETE FROM workspace_locks WHERE device=? AND owner=?").run(device, owner);
16108
+ }
16109
+ }
16110
+ var pending3;
16111
+ function operationsStore() {
16112
+ pending3 ??= (async () => {
16113
+ const path = join6(dirname7(DEFAULT_SNAPSHOT_DB2), "operations.db");
16114
+ mkdirSync6(dirname7(path), { recursive: true, mode: 448 });
16115
+ const { Database } = await import("bun:sqlite");
16116
+ const db = new Database(path, { create: true });
16117
+ chmodSync(path, 384);
16118
+ db.run("PRAGMA journal_mode = WAL");
16119
+ return new OperationsStore(db);
16120
+ })().catch((error) => {
16121
+ pending3 = undefined;
16122
+ throw error;
16123
+ });
16124
+ return pending3;
16125
+ }
16126
+
16127
+ // src/service-routing/read.ts
16128
+ var paths = new Set([
16129
+ "/ip dns static",
16130
+ "/routing table",
16131
+ "/routing rule",
16132
+ "/ip route",
16133
+ "/ipv6 route",
16134
+ "/ip vrf",
16135
+ "/ip firewall mangle",
16136
+ "/ipv6 firewall mangle",
16137
+ "/ip firewall filter",
16138
+ "/ipv6 firewall filter",
16139
+ "/ip firewall address-list",
16140
+ "/ipv6 firewall address-list"
16141
+ ]);
16142
+ var ROUTING_ROW_LIMIT = 2000;
16143
+ function routingReadCommand(path, lists) {
16144
+ if (!paths.has(path))
16145
+ throw new Error("Unsupported routing inventory section.");
16146
+ const where = lists?.length ? `where ${lists.map((list) => `list=${quoteValue(list)}`).join(" or ")}` : "";
16147
+ const find = new Cmd(`${path} find`).raw(where).build();
16148
+ const print = new Cmd(`${path} print`).raw("detail as-value").raw(where).build();
16149
+ return `:if ([:len [${find}]] > ${ROUTING_ROW_LIMIT}) do={:put "MCP_ROUTING_ROW_LIMIT"} else={:put [:serialize to=json value=[${print}]]}`;
16150
+ }
16151
+ function parseRoutingRows(raw, fields) {
16152
+ if (raw.length > 1048576)
16153
+ throw new Error("Routing section exceeds the 1 MiB read limit.");
16154
+ if (raw.trim() === "MCP_ROUTING_ROW_LIMIT")
16155
+ throw new Error(`More than ${ROUTING_ROW_LIMIT} entries: this section was not loaded to protect the router. Use a filtered RouterOS read; the other routing sections are independent.`);
16156
+ if (looksLikeError(raw))
16157
+ throw new Error("Router rejected this read; check connectivity, permissions and RouterOS v7 support.");
16158
+ let data;
16159
+ try {
16160
+ data = JSON.parse(raw.trim());
16161
+ } catch {
16162
+ throw new Error("Router did not return valid structured routing data; no rows were accepted.");
16163
+ }
16164
+ if (!Array.isArray(data) || data.length > ROUTING_ROW_LIMIT || data.some((r) => !r || typeof r !== "object" || Array.isArray(r)))
16165
+ throw new Error("Router returned an incomplete or invalid routing section.");
16166
+ const keys = fields ? new Set(["#", ".id", "flags", ...fields.split(",")]) : undefined;
16167
+ return data.map((record, index) => {
16168
+ const row = { "#": String(index) };
16169
+ for (const [key, value] of Object.entries(record)) {
16170
+ if (keys && !keys.has(key))
16171
+ continue;
16172
+ if (typeof value === "boolean")
16173
+ row[key] = value ? "yes" : "no";
16174
+ else if (typeof value === "string" || typeof value === "number")
16175
+ row[key] = String(value);
16176
+ else if (Array.isArray(value) && value.every((v) => ["string", "number"].includes(typeof v)))
16177
+ row[key] = value.join(",");
16178
+ }
16179
+ return row;
16180
+ });
16181
+ }
16182
+ async function readRoutingRows(path, fields, ctx, lists) {
16183
+ const raw = await executeMikrotikCommand2(routingReadCommand(path, lists), ctx, { maxMs: 6000 });
16184
+ return parseRoutingRows(raw, fields);
16185
+ }
16186
+ async function readRoutingAddressPage(path, ctx, offset = 0) {
16187
+ if (!["/ip firewall address-list", "/ipv6 firewall address-list"].includes(path) || !Number.isSafeInteger(offset) || offset < 0 || offset > 1e6)
16188
+ throw new Error("Invalid address-list page.");
16189
+ const find = new Cmd(`${path} find`).build();
16190
+ const get = new Cmd(`${path} get`).raw("$srId").build();
16191
+ const command = `{ :local srIds [${find}]; :local srItems [:toarray ""]; :foreach srId in=[:pick $srIds ${offset} ${offset + 200}] do={ :local srRow [${get}]; :set ($srRow->".id") $srId; :set ($srItems->[:len $srItems]) $srRow; }; :put [:serialize to=json value={"rows"=$srItems;"total"=[:len $srIds]}]; }`;
16192
+ const raw = await executeMikrotikCommand2(command, ctx, { maxMs: 6000 });
16193
+ return parseRoutingAddressPage(raw, offset);
16194
+ }
16195
+ function parseRoutingAddressPage(raw, offset = 0) {
16196
+ if (looksLikeError(raw) || raw.length > 1048576)
16197
+ throw new Error("Address-list page could not be read safely.");
16198
+ let data;
16199
+ try {
16200
+ data = JSON.parse(raw.trim());
16201
+ } catch {
16202
+ throw new Error("Invalid structured address-list page.");
16203
+ }
16204
+ if (!data || !Array.isArray(data.rows) || !Number.isSafeInteger(data.total) || data.total < 0)
16205
+ throw new Error("Invalid address-list total.");
16206
+ const rows = parseRoutingRows(JSON.stringify(data.rows)).map((r, i) => ({
16207
+ ...r,
16208
+ "#": String(offset + i)
16209
+ }));
16210
+ if (rows.length !== Math.min(200, Math.max(0, data.total - offset)) || rows.some((r) => !r[".id"]))
16211
+ throw new Error("Incomplete address-list page. Refresh if the router list changed while reading.");
16212
+ return {
16213
+ rows,
16214
+ total: data.total,
16215
+ nextOffset: offset + rows.length < data.total ? offset + rows.length : undefined
16216
+ };
16217
+ }
16218
+
16219
+ // src/address-sets/service.ts
16220
+ var KIND = "address-set";
16221
+ var hash2 = (value) => createHash5("sha256").update(JSON.stringify(value)).digest("hex");
16222
+ var pathFor = (r) => r.input.family === "ipv4" ? "/ip firewall" : "/ipv6 firewall";
16223
+ function access(ctx, tool, write = false) {
16224
+ const device = resolveDeviceName2(ctx.device);
16225
+ assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
16226
+ return device;
16227
+ }
16228
+ async function revision(id, device) {
16229
+ const r = (await operationsStore()).get(KIND, id, device);
16230
+ if (!r)
16231
+ throw new Error("Address-set revision not found on this device.");
16232
+ return r;
16233
+ }
16234
+ async function save(r) {
16235
+ r.updatedAt = Date.now();
16236
+ (await operationsStore()).put(KIND, r);
16237
+ return r;
16238
+ }
16239
+ async function listAddressSets(ctx) {
16240
+ const device = access(ctx, "list_address_sets");
16241
+ return { revisions: (await operationsStore()).list(KIND, device) };
16242
+ }
16243
+ async function createAddressSet(input, ctx) {
16244
+ const device = access(ctx, "create_address_set", true);
16245
+ const a = addressSetInput.parse(input), composition = composeAddressSet(a);
16246
+ if (!composition.prefixes.length)
16247
+ throw new Error("An empty set cannot be saved or published.");
16248
+ let delta;
16249
+ if (a.parent) {
16250
+ const parent = await revision(a.parent, device);
16251
+ if (parent.input.name !== a.name || parent.input.family !== a.family)
16252
+ throw new Error("Parent name/family differs; create a new set instead.");
16253
+ const added = combinePrefixes({
16254
+ ...a,
16255
+ operation: "difference",
16256
+ left: composition.prefixes,
16257
+ right: parent.prefixes
16258
+ });
16259
+ const removed = combinePrefixes({
16260
+ ...a,
16261
+ operation: "difference",
16262
+ left: parent.prefixes,
16263
+ right: composition.prefixes
16264
+ });
16265
+ delta = {
16266
+ added: added.prefixes,
16267
+ removed: removed.prefixes,
16268
+ addedAddresses: added.addresses,
16269
+ removedAddresses: removed.addresses,
16270
+ large: BigInt(added.addresses) * 2n > BigInt(parent.addresses) || BigInt(removed.addresses) * 2n > BigInt(parent.addresses)
16271
+ };
16272
+ }
16273
+ const id = randomUUID4();
16274
+ return save({
16275
+ id,
16276
+ device,
16277
+ createdAt: Date.now(),
16278
+ updatedAt: Date.now(),
16279
+ input: a,
16280
+ ...composition,
16281
+ list: `mcp-as-${id}`,
16282
+ state: "draft",
16283
+ delta
16284
+ });
16285
+ }
16286
+ async function facts(r, refs, ctx) {
16287
+ const rules = [];
16288
+ for (const table of new Set(refs.map((ref) => ref.table))) {
16289
+ const rows = await readRoutingRows(`${pathFor(r)} ${table}`, undefined, ctx);
16290
+ for (const ref of refs.filter((item) => item.table === table)) {
16291
+ const rule = rows.find((row) => row[".id"] === ref.id);
16292
+ if (!rule)
16293
+ throw new Error(`Rule ${table} ${ref.id} no longer exists.`);
16294
+ const { "#": _position, ...stable } = rule;
16295
+ rules.push({ reference: ref, rule: stable });
16296
+ }
16297
+ }
16298
+ const entries = await readRoutingRows(`${pathFor(r)} address-list`, undefined, ctx, [r.list]);
16299
+ const names = [...new Set(refs.map((ref) => ref.expected.replace(/^!/, "")))];
16300
+ const originals = await readRoutingRows(`${pathFor(r)} address-list`, undefined, ctx, names);
16301
+ if (names.some((name) => !originals.some((entry) => entry.list === name)))
16302
+ throw new Error("An original list is empty or missing; refusing an unsafe reference change.");
16303
+ if (originals.some((entry) => ["yes", "true"].includes(entry.dynamic) || entry.timeout && entry.timeout !== "0s"))
16304
+ throw new Error("Dynamic original lists cannot be safely versioned by this workflow.");
16305
+ return { rules, entries, originals: originals.map(({ "#": _position, ...entry }) => entry) };
16306
+ }
16307
+ function targetList(r, ref, rollback) {
16308
+ return rollback ? ref.expected : `${ref.expected.startsWith("!") ? "!" : ""}${r.list}`;
16309
+ }
16310
+ function addressSetCommands(r, refs, rollback) {
16311
+ const path = pathFor(r);
16312
+ 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());
16313
+ for (const ref of refs)
16314
+ commands.push(new Cmd(`${path} ${ref.table} set`).raw(ref.id).set(ref.field, targetList(r, ref, rollback)).build());
16315
+ return commands;
16316
+ }
16317
+ function verifyEntries(r, entries) {
16318
+ 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"))
16319
+ throw new Error("Generation entries differ from the saved revision.");
16320
+ const actual = composeAddressSet({
16321
+ ...r.input,
16322
+ operation: "union",
16323
+ left: entries.map((e) => e.address),
16324
+ right: []
16325
+ });
16326
+ if (actual.checksum !== r.checksum)
16327
+ throw new Error("Generation checksum does not match router read-back.");
16328
+ }
16329
+ async function previewAddressSet(id, references, rollback, ctx, allowLargeChange = false) {
16330
+ const device = access(ctx, "preview_address_set");
16331
+ const r = await revision(id, device);
16332
+ if (!rollback && !allowLargeChange && (r.delta?.large || r.prefixes.some((p) => p.endsWith("/0"))))
16333
+ throw new Error("Broad coverage change (>50% of parent or /0) requires explicit allowLargeChange acknowledgement.");
16334
+ if (r.state !== (rollback ? "published" : "draft"))
16335
+ throw new Error("Revision state does not permit this operation; uncertain writes require reconciliation.");
16336
+ const refs = rollback ? r.references ?? [] : referenceSchema.array().min(1).max(8).parse(references);
16337
+ if (!refs.length || new Set(refs.map((v) => `${v.table}/${v.id}/${v.field}`)).size !== refs.length)
16338
+ throw new Error("Choose 1\u20138 unique rule references.");
16339
+ if (!rollback && r.prefixes.length > 64)
16340
+ throw new Error("This release publishes at most 64 compacted prefixes plus 8 rule references per Safe Mode transaction. The saved composition remains available.");
16341
+ const before = await facts(r, refs, ctx);
16342
+ for (const { reference, rule } of before.rules) {
16343
+ if (rule[reference.field] !== (rollback ? targetList(r, reference, false) : reference.expected))
16344
+ throw new Error("Rule reference differs from the expected list. Refresh and review again.");
16345
+ }
16346
+ if (rollback) {
16347
+ verifyEntries(r, before.entries);
16348
+ if (hash2(before.originals) !== r.originalListsHash)
16349
+ throw new Error("Original list contents changed since publication; automatic rollback refused.");
16350
+ } else if (before.entries.length)
16351
+ throw new Error("Generation list already exists; refusing to adopt or overwrite it.");
16352
+ r.plan = {
16353
+ id: randomUUID4(),
16354
+ expiresAt: Date.now() + 120000,
16355
+ references: refs,
16356
+ fingerprint: hash2(before),
16357
+ rollback,
16358
+ commands: addressSetCommands(r, refs, rollback)
16359
+ };
16360
+ return save(r);
16361
+ }
16362
+ async function applyAddressSet(id, planId, confirm, ctx) {
16363
+ const device = access(ctx, "apply_address_set", true);
16364
+ if (!confirm)
16365
+ throw new Error("Explicit confirmation is required after reviewing the preview.");
16366
+ const store = await operationsStore(), owner = randomUUID4();
16367
+ store.lock(device, owner);
16368
+ try {
16369
+ const r = await revision(id, device), plan = r.plan;
16370
+ if (!plan || plan.id !== planId || plan.expiresAt < Date.now())
16371
+ throw new Error("Preview expired or changed; preview again.");
16372
+ if (r.state !== (plan.rollback ? "published" : "draft"))
16373
+ throw new Error("Revision requires reconciliation before another write.");
16374
+ const safe = getSafeModeManager2(device);
16375
+ if (getDevice2(device).mac || safe.isActive)
16376
+ throw new Error("Requires SSH and no existing Safe Mode session.");
16377
+ const before = await facts(r, plan.references, ctx);
16378
+ if (hash2(before) !== plan.fingerprint)
16379
+ throw new Error("Router changed after preview.");
16380
+ if (!plan.rollback)
16381
+ r.originalListsHash = hash2(before.originals);
16382
+ r.snapshot = await captureSnapshot(ctx, `Before address set ${r.input.name}`, true);
16383
+ r.state = "uncertain";
16384
+ await save(r);
16385
+ let owned = false, commitAttempted = false;
16386
+ try {
16387
+ if (!(await safe.enable()).startsWith("Safe mode ENABLED"))
16388
+ throw new Error("Could not acquire Safe Mode.");
16389
+ owned = true;
16390
+ const started = Date.now();
16391
+ if (plan.expiresAt < started)
16392
+ throw new Error("Preview expired while capturing the backup; preview again.");
16393
+ if (hash2(await facts(r, plan.references, ctx)) !== plan.fingerprint)
16394
+ throw new Error("Router changed while entering Safe Mode.");
16395
+ for (const [index, command] of plan.commands.entries()) {
16396
+ if (Date.now() - started > 120000)
16397
+ throw new Error("Publication time budget exceeded; aborting.");
16398
+ if (!plan.rollback && index === r.prefixes.length)
16399
+ verifyEntries(r, (await facts(r, plan.references, ctx)).entries);
16400
+ await checkedRead(command, ctx);
16401
+ }
16402
+ const after = await facts(r, plan.references, ctx);
16403
+ verifyEntries(r, after.entries);
16404
+ if (after.rules.some(({ reference, rule }) => rule[reference.field] !== targetList(r, reference, plan.rollback)))
16405
+ throw new Error("Rule read-back did not match the approved plan.");
16406
+ await checkedRead("/system identity print", ctx);
16407
+ commitAttempted = true;
16408
+ if (!(await safe.commit()).ok)
16409
+ throw new Error("Commit uncertain; inspect router state before any retry.");
16410
+ owned = false;
16411
+ r.state = plan.rollback ? "rolled-back" : "published";
16412
+ r.references = plan.references;
16413
+ r.plan = undefined;
16414
+ r.error = undefined;
16415
+ return await save(r);
16416
+ } catch (error) {
16417
+ if (owned && !commitAttempted)
16418
+ await safe.rollback().catch(() => {});
16419
+ r.state = "uncertain";
16420
+ r.error = error instanceof Error ? error.message : String(error);
16421
+ r.plan = undefined;
16422
+ await save(r);
16423
+ throw error;
16424
+ }
16425
+ } finally {
16426
+ store.unlock(device, owner);
16427
+ }
16428
+ }
16429
+
16430
+ // src/tools/address-sets.ts
16431
+ var addressSetTools = [
16432
+ defineTool2({
16433
+ name: "compose_address_set",
16434
+ title: "Compose an Address Set",
16435
+ annotations: READ,
16436
+ 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.",
16437
+ inputSchema: addressSetInput.shape,
16438
+ handler(a) {
16439
+ return JSON.stringify(composeAddressSet(a));
16440
+ }
16441
+ }),
16442
+ defineTool2({
16443
+ name: "list_address_sets",
16444
+ title: "List Address Set Revisions",
16445
+ annotations: READ,
16446
+ description: "Read the newest 100 locally persisted address-set revisions for the selected device, including publication state and rollback references. No router I/O.",
16447
+ inputSchema: {},
16448
+ async handler(_, ctx) {
16449
+ return JSON.stringify(await listAddressSets(ctx));
16450
+ }
16451
+ }),
16452
+ defineTool2({
16453
+ name: "create_address_set",
16454
+ title: "Save Address Set Revision",
16455
+ annotations: WRITE,
16456
+ 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.",
16457
+ inputSchema: addressSetInput.shape,
16458
+ async handler(a, ctx) {
16459
+ return JSON.stringify(await createAddressSet(a, ctx));
16460
+ }
16461
+ }),
16462
+ defineTool2({
16463
+ name: "preview_address_set",
16464
+ title: "Preview Address Set Publication or Rollback",
16465
+ annotations: READ,
16466
+ 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.",
16467
+ inputSchema: {
16468
+ id: uuid2(),
16469
+ references: referenceSchema.array().max(8).default([]),
16470
+ rollback: boolean().default(false),
16471
+ allowLargeChange: boolean().default(false).describe("Explicitly acknowledge /0 or coverage changing by more than 50% of the parent")
16472
+ },
16473
+ async handler(a, ctx) {
16474
+ return JSON.stringify(await previewAddressSet(a.id, a.references, a.rollback, ctx, a.allowLargeChange));
16475
+ }
16476
+ }),
16477
+ defineTool2({
16478
+ name: "apply_address_set",
16479
+ title: "Apply Approved Address Set Preview",
16480
+ annotations: WRITE,
16481
+ 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.",
16482
+ inputSchema: { id: uuid2(), planId: uuid2(), confirm: boolean().default(false) },
16483
+ async handler(a, ctx) {
16484
+ return JSON.stringify(await applyAddressSet(a.id, a.planId, a.confirm, ctx));
16485
+ }
16486
+ })
16487
+ ];
16488
+
15964
16489
  // src/tools/connected-devices.ts
15965
16490
  var BLOCK_TAG = "mcp-blocked";
15966
16491
  function normalizeMac(mac) {
@@ -16354,7 +16879,7 @@ ${isEmpty(arp) ? "(no arp entry)" : arp}`;
16354
16879
  ];
16355
16880
 
16356
16881
  // src/investigations/collect.ts
16357
- import { randomUUID as randomUUID4 } from "crypto";
16882
+ import { randomUUID as randomUUID5 } from "crypto";
16358
16883
 
16359
16884
  // src/tools/dr-drill.ts
16360
16885
  function parsePingSummary(output) {
@@ -16525,7 +17050,7 @@ async function collectInvestigation(input, ctx, read = executeMikrotikCommand2)
16525
17050
  const capture = async (source, command, parse) => {
16526
17051
  const startedAt = Date.now();
16527
17052
  const e = {
16528
- id: randomUUID4(),
17053
+ id: randomUUID5(),
16529
17054
  device: d,
16530
17055
  source,
16531
17056
  startedAt,
@@ -16601,7 +17126,7 @@ async function collectInvestigation(input, ctx, read = executeMikrotikCommand2)
16601
17126
  }
16602
17127
  assertDeviceAccess(devices, "create_investigation", "WRITE");
16603
17128
  return {
16604
- id: randomUUID4(),
17129
+ id: randomUUID5(),
16605
17130
  createdAt,
16606
17131
  finishedAt: Date.now(),
16607
17132
  device,
@@ -17070,6 +17595,7 @@ class TemplateRegistry {
17070
17595
  templates = new Map;
17071
17596
  pending = [];
17072
17597
  droppedPending = 0;
17598
+ changedTemplates = 0;
17073
17599
  maxPending;
17074
17600
  constructor(maxPending = DEFAULT_MAX_PENDING) {
17075
17601
  this.maxPending = maxPending;
@@ -17078,6 +17604,10 @@ class TemplateRegistry {
17078
17604
  return `${sourceId}/${templateId}`;
17079
17605
  }
17080
17606
  learn(template) {
17607
+ const previous = this.get(template.sourceId, template.templateId);
17608
+ if (previous && JSON.stringify(previous.fields) !== JSON.stringify(template.fields)) {
17609
+ this.changedTemplates++;
17610
+ }
17081
17611
  this.templates.set(TemplateRegistry.key(template.sourceId, template.templateId), template);
17082
17612
  }
17083
17613
  get(sourceId, templateId) {
@@ -17113,6 +17643,9 @@ class TemplateRegistry {
17113
17643
  get droppedCount() {
17114
17644
  return this.droppedPending;
17115
17645
  }
17646
+ get changedCount() {
17647
+ return this.changedTemplates;
17648
+ }
17116
17649
  list() {
17117
17650
  return [...this.templates.values()];
17118
17651
  }
@@ -17120,15 +17653,23 @@ class TemplateRegistry {
17120
17653
  this.templates.clear();
17121
17654
  this.pending = [];
17122
17655
  this.droppedPending = 0;
17656
+ this.changedTemplates = 0;
17123
17657
  }
17124
17658
  }
17125
17659
 
17126
17660
  // src/flows/exporter-decoder.ts
17127
17661
  class ExporterFlowDecoder {
17128
17662
  registries = new Map;
17663
+ health = new Map;
17664
+ sequences = new Map;
17129
17665
  decode(packet, exporter, now) {
17130
17666
  const version = (packet[0] ?? 0) << 8 | (packet[1] ?? 0);
17131
- const key = `${exporter}/${version}`;
17667
+ const headerSize = version === 5 ? 24 : version === 9 ? 20 : version === 10 ? 16 : 0;
17668
+ if (!headerSize || packet.length < headerSize)
17669
+ return decodeFlowPacket(packet, new TemplateRegistry, now);
17670
+ const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
17671
+ const domain = version === 9 ? view.getUint32(16) : version === 10 ? view.getUint32(12) : view.getUint16(20);
17672
+ const key = `${exporter}/${version}/${domain}`;
17132
17673
  let registry = this.registries.get(key);
17133
17674
  if (!registry) {
17134
17675
  if (this.registries.size >= 128)
@@ -17142,17 +17683,59 @@ class ExporterFlowDecoder {
17142
17683
  registry = new TemplateRegistry;
17143
17684
  this.registries.set(key, registry);
17144
17685
  }
17145
- return decodeFlowPacket(packet, registry, now);
17686
+ const result = decodeFlowPacket(packet, registry, now);
17687
+ const state = this.health.get(key) ?? {
17688
+ exporter,
17689
+ version,
17690
+ domain,
17691
+ packets: 0,
17692
+ records: 0,
17693
+ errors: 0,
17694
+ lastSeen: now,
17695
+ sequenceGaps: 0,
17696
+ reordered: 0,
17697
+ templateChanges: 0,
17698
+ pending: 0,
17699
+ stale: false
17700
+ };
17701
+ state.packets++;
17702
+ state.records += result.records.length;
17703
+ state.errors += result.error ? 1 : 0;
17704
+ state.lastSeen = now;
17705
+ state.templateChanges = registry.changedCount;
17706
+ state.pending = registry.pendingCount;
17707
+ if (version === 9 && !result.error) {
17708
+ const sequence = view.getUint32(12);
17709
+ const previous = this.sequences.get(key);
17710
+ const delta = previous === undefined ? 1 : sequence - previous >>> 0;
17711
+ if (delta === 0 || delta >= 2147483648)
17712
+ state.reordered++;
17713
+ else {
17714
+ state.sequenceGaps += delta - 1;
17715
+ this.sequences.set(key, sequence);
17716
+ }
17717
+ }
17718
+ this.health.set(key, state);
17719
+ return result;
17146
17720
  }
17147
17721
  clear() {
17148
17722
  this.registries.clear();
17723
+ this.health.clear();
17724
+ this.sequences.clear();
17149
17725
  }
17150
- stats() {
17151
- return [...this.registries.values()].reduce((sum, r) => ({
17726
+ stats(now = Date.now()) {
17727
+ const totals = [...this.registries.values()].reduce((sum, r) => ({
17152
17728
  templates: sum.templates + r.size,
17153
17729
  templatesPending: sum.templatesPending + r.pendingCount,
17154
17730
  templatesDropped: sum.templatesDropped + r.droppedCount
17155
17731
  }), { templates: 0, templatesPending: 0, templatesDropped: 0 });
17732
+ return {
17733
+ ...totals,
17734
+ exporterHealth: [...this.health.values()].map((state) => ({
17735
+ ...state,
17736
+ stale: now - state.lastSeen > 300000
17737
+ }))
17738
+ };
17156
17739
  }
17157
17740
  }
17158
17741
 
@@ -17174,6 +17757,7 @@ class FlowCollector {
17174
17757
  packets = 0;
17175
17758
  flows = 0;
17176
17759
  decodeErrors = 0;
17760
+ storageDropped = 0;
17177
17761
  lastError;
17178
17762
  exporters = new Map;
17179
17763
  get running() {
@@ -17229,6 +17813,7 @@ class FlowCollector {
17229
17813
  this.packets = 0;
17230
17814
  this.flows = 0;
17231
17815
  this.decodeErrors = 0;
17816
+ this.storageDropped = 0;
17232
17817
  this.lastError = undefined;
17233
17818
  this.exporters = new Map;
17234
17819
  }
@@ -17260,6 +17845,7 @@ class FlowCollector {
17260
17845
  try {
17261
17846
  this.store.insert(batch);
17262
17847
  } catch (e) {
17848
+ this.storageDropped += batch.length;
17263
17849
  logger.error(`Flow store insert failed (${batch.length} records dropped): ${String(e)}`);
17264
17850
  }
17265
17851
  }
@@ -17286,7 +17872,8 @@ class FlowCollector {
17286
17872
  lastError: this.lastError,
17287
17873
  ...this.decoder.stats(),
17288
17874
  exporters: Object.fromEntries(this.exporters),
17289
- queued: this.queue.length
17875
+ queued: this.queue.length,
17876
+ storageDropped: this.storageDropped
17290
17877
  };
17291
17878
  }
17292
17879
  drain() {
@@ -17522,8 +18109,8 @@ function humanBytes(n) {
17522
18109
  }
17523
18110
 
17524
18111
  // src/flows/store.ts
17525
- import { mkdirSync as mkdirSync6 } from "fs";
17526
- import { dirname as dirname7 } from "path";
18112
+ import { mkdirSync as mkdirSync7 } from "fs";
18113
+ import { dirname as dirname8 } from "path";
17527
18114
  var SCHEMA_STATEMENTS3 = [
17528
18115
  `CREATE TABLE IF NOT EXISTS flows (
17529
18116
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -17721,7 +18308,7 @@ class SqliteFlowStore {
17721
18308
  async function openFlowStore(path, opts = {}) {
17722
18309
  if (path !== ":memory:") {
17723
18310
  try {
17724
- mkdirSync6(dirname7(path), { recursive: true });
18311
+ mkdirSync7(dirname8(path), { recursive: true });
17725
18312
  } catch {}
17726
18313
  }
17727
18314
  const { Database } = await import("bun:sqlite");
@@ -17785,6 +18372,15 @@ function talkerTable(title, rows) {
17785
18372
  `);
17786
18373
  }
17787
18374
  var trafficFlowTools = [
18375
+ defineTool2({
18376
+ name: "get_flow_collector_health",
18377
+ title: "Inspect Flow Collector Health",
18378
+ annotations: READ,
18379
+ 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.",
18380
+ handler() {
18381
+ return JSON.stringify(getFlowCollector().stats(), null, 2);
18382
+ }
18383
+ }),
17788
18384
  defineTool2({
17789
18385
  name: "get_traffic_flow_settings",
17790
18386
  title: "Get Traffic Flow Settings",
@@ -18283,11 +18879,11 @@ var investigationTools = [
18283
18879
  ];
18284
18880
 
18285
18881
  // src/home/policies.ts
18286
- import { createHash as createHash4, randomUUID as randomUUID5 } from "crypto";
18882
+ import { createHash as createHash6, randomUUID as randomUUID6 } from "crypto";
18287
18883
 
18288
18884
  // src/home/store.ts
18289
- import { mkdirSync as mkdirSync7 } from "fs";
18290
- import { dirname as dirname8 } from "path";
18885
+ import { mkdirSync as mkdirSync8 } from "fs";
18886
+ import { dirname as dirname9 } from "path";
18291
18887
  class HomeStore {
18292
18888
  db;
18293
18889
  constructor(db) {
@@ -18324,17 +18920,17 @@ class HomeStore {
18324
18920
  ].sort((a, b) => b.createdAt - a.createdAt);
18325
18921
  }
18326
18922
  }
18327
- var pending3;
18923
+ var pending4;
18328
18924
  function homeStore() {
18329
- return pending3 ??= (async () => {
18330
- mkdirSync7(dirname8(DEFAULT_SNAPSHOT_DB2), { recursive: true });
18925
+ return pending4 ??= (async () => {
18926
+ mkdirSync8(dirname9(DEFAULT_SNAPSHOT_DB2), { recursive: true });
18331
18927
  const { Database } = await import("bun:sqlite");
18332
18928
  const db = new Database(DEFAULT_SNAPSHOT_DB2, { create: true });
18333
18929
  db.run("PRAGMA journal_mode=WAL");
18334
18930
  db.run("PRAGMA busy_timeout=5000");
18335
18931
  return new HomeStore(db);
18336
18932
  })().catch((e) => {
18337
- pending3 = undefined;
18933
+ pending4 = undefined;
18338
18934
  throw e;
18339
18935
  });
18340
18936
  }
@@ -18425,7 +19021,7 @@ function buildPolicy(id, input, facts) {
18425
19021
  ...generated,
18426
19022
  warnings,
18427
19023
  queueBefore,
18428
- fingerprint: createHash4("sha256").update(stable).digest("hex")
19024
+ fingerprint: createHash6("sha256").update(stable).digest("hex")
18429
19025
  };
18430
19026
  }
18431
19027
  async function policyFacts(ctx, read = executeMikrotikCommand2) {
@@ -18461,7 +19057,7 @@ async function previewPolicy(input, ctx) {
18461
19057
  a.mac = a.mac.toUpperCase();
18462
19058
  assertDeviceAccess([device], "preview_home_policy", "WRITE");
18463
19059
  return exclusive(device, async () => {
18464
- const id = randomUUID5();
19060
+ const id = randomUUID6();
18465
19061
  const plan = {
18466
19062
  id,
18467
19063
  device,
@@ -18741,11 +19337,11 @@ var homeInternetTools = [
18741
19337
  ];
18742
19338
 
18743
19339
  // src/tools/service-contracts.ts
18744
- import { randomUUID as randomUUID7 } from "crypto";
19340
+ import { randomUUID as randomUUID8 } from "crypto";
18745
19341
 
18746
19342
  // src/service-contracts/store.ts
18747
- import { mkdirSync as mkdirSync8 } from "fs";
18748
- import { dirname as dirname9 } from "path";
19343
+ import { mkdirSync as mkdirSync9 } from "fs";
19344
+ import { dirname as dirname10 } from "path";
18749
19345
  class ContractStore {
18750
19346
  db;
18751
19347
  constructor(db) {
@@ -18771,23 +19367,23 @@ class ContractStore {
18771
19367
  return this.db.query("SELECT body FROM service_contract_runs WHERE contract_id = ? ORDER BY started_at DESC LIMIT 100").all(id).map((r) => JSON.parse(r.body));
18772
19368
  }
18773
19369
  }
18774
- var pending4;
19370
+ var pending5;
18775
19371
  function contractStore() {
18776
- pending4 ??= (async () => {
18777
- mkdirSync8(dirname9(DEFAULT_SNAPSHOT_DB2), { recursive: true });
19372
+ pending5 ??= (async () => {
19373
+ mkdirSync9(dirname10(DEFAULT_SNAPSHOT_DB2), { recursive: true });
18778
19374
  const { Database } = await import("bun:sqlite");
18779
19375
  const db = new Database(DEFAULT_SNAPSHOT_DB2, { create: true });
18780
19376
  db.run("PRAGMA journal_mode = WAL");
18781
19377
  return new ContractStore(db);
18782
19378
  })().catch((e) => {
18783
- pending4 = undefined;
19379
+ pending5 = undefined;
18784
19380
  throw e;
18785
19381
  });
18786
- return pending4;
19382
+ return pending5;
18787
19383
  }
18788
19384
 
18789
19385
  // src/service-contracts/run.ts
18790
- import { randomUUID as randomUUID6 } from "crypto";
19386
+ import { randomUUID as randomUUID7 } from "crypto";
18791
19387
 
18792
19388
  // src/sim/ip.ts
18793
19389
  var IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
@@ -19902,8 +20498,8 @@ function diffTraces(before, after) {
19902
20498
  }
19903
20499
 
19904
20500
  // src/sim/suites.ts
19905
- import { mkdirSync as mkdirSync9 } from "fs";
19906
- import { dirname as dirname10 } from "path";
20501
+ import { mkdirSync as mkdirSync10 } from "fs";
20502
+ import { dirname as dirname11 } from "path";
19907
20503
  var SCHEMA = [
19908
20504
  `CREATE TABLE IF NOT EXISTS sim_suites (
19909
20505
  id TEXT PRIMARY KEY,
@@ -19953,7 +20549,7 @@ var storePromise4 = null;
19953
20549
  async function store2() {
19954
20550
  storePromise4 ??= (async () => {
19955
20551
  try {
19956
- mkdirSync9(dirname10(DEFAULT_SNAPSHOT_DB2), { recursive: true });
20552
+ mkdirSync10(dirname11(DEFAULT_SNAPSHOT_DB2), { recursive: true });
19957
20553
  } catch {}
19958
20554
  const { Database } = await import("bun:sqlite");
19959
20555
  return new SqliteSuiteStore(new Database(DEFAULT_SNAPSHOT_DB2, { create: true }));
@@ -19970,11 +20566,11 @@ async function getSuite(id) {
19970
20566
 
19971
20567
  // src/service-contracts/probe.ts
19972
20568
  import { Resolver } from "dns/promises";
19973
- import { connect, isIP } from "net";
20569
+ import { connect, isIP as isIP2 } from "net";
19974
20570
  import { connect as connectTls } from "tls";
19975
20571
  import { request } from "https";
19976
20572
  async function resolve2(host, timeoutMs) {
19977
- if (isIP(host))
20573
+ if (isIP2(host))
19978
20574
  return [host];
19979
20575
  const resolver = new Resolver({ timeout: timeoutMs, tries: 1 });
19980
20576
  const timer = setTimeout(() => resolver.cancel(), timeoutMs);
@@ -20009,7 +20605,7 @@ function connectTarget(target, address, timeoutMs) {
20009
20605
  port: target.port,
20010
20606
  path: target.path,
20011
20607
  method: "GET",
20012
- servername: isIP(target.host) ? undefined : target.host,
20608
+ servername: isIP2(target.host) ? undefined : target.host,
20013
20609
  rejectUnauthorized: true,
20014
20610
  headers: {
20015
20611
  host: `${target.host}:${target.port}`,
@@ -20032,7 +20628,7 @@ function connectTarget(target, address, timeoutMs) {
20032
20628
  const socket = target.kind === "tls" ? connectTls({
20033
20629
  host: address,
20034
20630
  port: target.port,
20035
- servername: isIP(target.host) ? undefined : target.host,
20631
+ servername: isIP2(target.host) ? undefined : target.host,
20036
20632
  rejectUnauthorized: true
20037
20633
  }) : connect({ host: address, port: target.port });
20038
20634
  close = () => socket.destroy();
@@ -20130,7 +20726,7 @@ async function evaluateContract(contract, io, simulationExport) {
20130
20726
  }
20131
20727
  }
20132
20728
  return {
20133
- id: randomUUID6(),
20729
+ id: randomUUID7(),
20134
20730
  contractId: contract.id,
20135
20731
  device: contract.device,
20136
20732
  startedAt,
@@ -20255,7 +20851,7 @@ var serviceContractTools = [
20255
20851
  const args = contractInput.parse(a);
20256
20852
  if (args.checks.some((c) => !getConfig2().serviceProbes.targets[c.target]))
20257
20853
  throw new Error("Contract references an unapproved target. Ask the administrator to configure it.");
20258
- const contract = { ...args, id: randomUUID7(), device, createdAt: Date.now() };
20854
+ const contract = { ...args, id: randomUUID8(), device, createdAt: Date.now() };
20259
20855
  (await contractStore()).save(contract);
20260
20856
  return JSON.stringify(contract);
20261
20857
  }
@@ -20300,8 +20896,8 @@ var serviceContractTools = [
20300
20896
  ];
20301
20897
 
20302
20898
  // src/service-routing/model.ts
20303
- import ipaddr2 from "ipaddr.js";
20304
- import { createHash as createHash5 } from "crypto";
20899
+ import ipaddr3 from "ipaddr.js";
20900
+ import { createHash as createHash7 } from "crypto";
20305
20901
 
20306
20902
  // src/service-routing/domain.ts
20307
20903
  var routingDomain = string().trim().toLowerCase().max(253).refine((value) => {
@@ -20340,7 +20936,7 @@ var routingInput = object({
20340
20936
  dnsLearningConfirmed: boolean().optional().describe("For wildcard only: confirms clients use this router DNS, shared-IP scope and FWD adlist bypass are understood. Does not enable or intercept DNS."),
20341
20937
  precedence: _enum(["before-existing"]).optional().describe("Explicitly allow this scoped policy before existing routing rules. Preview still binds their full configuration; FastTrack is never bypassed."),
20342
20938
  family: _enum(["ipv4", "ipv6"]),
20343
- sources: array(string().refine((v) => ipaddr2.isValidCIDR(v), "Use an explicit client subnet CIDR")).min(1).max(8),
20939
+ sources: array(string().refine((v) => ipaddr3.isValidCIDR(v), "Use an explicit client subnet CIDR")).min(1).max(8),
20344
20940
  tables: array(name2).min(1).max(3),
20345
20941
  primary: name2,
20346
20942
  maxLatencyMs: number().int().min(100).max(15000).default(5000),
@@ -20357,7 +20953,7 @@ var routingInput = object({
20357
20953
  if (!v.tables.includes(v.primary) || new Set(v.tables).size !== v.tables.length)
20358
20954
  ctx.addIssue({ code: "custom", message: "Choose one unique candidate table as primary" });
20359
20955
  for (const s of v.sources) {
20360
- const [ip, bits] = ipaddr2.parseCIDR(s);
20956
+ const [ip, bits] = ipaddr3.parseCIDR(s);
20361
20957
  if (ip.kind() !== v.family || bits === 0)
20362
20958
  ctx.addIssue({
20363
20959
  code: "custom",
@@ -20370,7 +20966,7 @@ var ownerTag = (id) => `mcp-sr-${id}`;
20370
20966
  var selector = (tag) => `[find where comment=${quoteValue(tag)}]`;
20371
20967
  var routingPath = (family) => family === "ipv4" ? "/ip firewall" : "/ipv6 firewall";
20372
20968
  function fingerprint(facts) {
20373
- return createHash5("sha256").update(JSON.stringify({
20969
+ return createHash7("sha256").update(JSON.stringify({
20374
20970
  ...facts,
20375
20971
  addresses: facts.addresses.filter((r) => !(r.list?.startsWith("mcp-sr-") && r.list.endsWith("-dst") && (["yes", "true"].includes(r.dynamic) || (r.flags ?? "").includes("D"))))
20376
20972
  }, (key, value) => ["#", ".id", "bytes", "packets", "last-handshake", "expires-after"].includes(key) ? undefined : value)).digest("hex");
@@ -20479,100 +21075,8 @@ function planCommands(policy, table, facts, remove = false) {
20479
21075
  }
20480
21076
 
20481
21077
  // src/service-routing/service.ts
20482
- import { randomUUID as randomUUID8 } from "crypto";
20483
- import { isIP as isIP2 } from "net";
20484
-
20485
- // src/service-routing/read.ts
20486
- var paths = new Set([
20487
- "/ip dns static",
20488
- "/routing table",
20489
- "/routing rule",
20490
- "/ip route",
20491
- "/ipv6 route",
20492
- "/ip vrf",
20493
- "/ip firewall mangle",
20494
- "/ipv6 firewall mangle",
20495
- "/ip firewall filter",
20496
- "/ipv6 firewall filter",
20497
- "/ip firewall address-list",
20498
- "/ipv6 firewall address-list"
20499
- ]);
20500
- var ROUTING_ROW_LIMIT = 2000;
20501
- function routingReadCommand(path, lists) {
20502
- if (!paths.has(path))
20503
- throw new Error("Unsupported routing inventory section.");
20504
- const where = lists?.length ? `where ${lists.map((list) => `list=${quoteValue(list)}`).join(" or ")}` : "";
20505
- const find = new Cmd(`${path} find`).raw(where).build();
20506
- const print = new Cmd(`${path} print`).raw("detail as-value").raw(where).build();
20507
- return `:if ([:len [${find}]] > ${ROUTING_ROW_LIMIT}) do={:put "MCP_ROUTING_ROW_LIMIT"} else={:put [:serialize to=json value=[${print}]]}`;
20508
- }
20509
- function parseRoutingRows(raw, fields) {
20510
- if (raw.length > 1048576)
20511
- throw new Error("Routing section exceeds the 1 MiB read limit.");
20512
- if (raw.trim() === "MCP_ROUTING_ROW_LIMIT")
20513
- throw new Error(`More than ${ROUTING_ROW_LIMIT} entries: this section was not loaded to protect the router. Use a filtered RouterOS read; the other routing sections are independent.`);
20514
- if (looksLikeError(raw))
20515
- throw new Error("Router rejected this read; check connectivity, permissions and RouterOS v7 support.");
20516
- let data;
20517
- try {
20518
- data = JSON.parse(raw.trim());
20519
- } catch {
20520
- throw new Error("Router did not return valid structured routing data; no rows were accepted.");
20521
- }
20522
- if (!Array.isArray(data) || data.length > ROUTING_ROW_LIMIT || data.some((r) => !r || typeof r !== "object" || Array.isArray(r)))
20523
- throw new Error("Router returned an incomplete or invalid routing section.");
20524
- const keys = fields ? new Set(["#", ".id", "flags", ...fields.split(",")]) : undefined;
20525
- return data.map((record, index) => {
20526
- const row = { "#": String(index) };
20527
- for (const [key, value] of Object.entries(record)) {
20528
- if (keys && !keys.has(key))
20529
- continue;
20530
- if (typeof value === "boolean")
20531
- row[key] = value ? "yes" : "no";
20532
- else if (typeof value === "string" || typeof value === "number")
20533
- row[key] = String(value);
20534
- else if (Array.isArray(value) && value.every((v) => ["string", "number"].includes(typeof v)))
20535
- row[key] = value.join(",");
20536
- }
20537
- return row;
20538
- });
20539
- }
20540
- async function readRoutingRows(path, fields, ctx, lists) {
20541
- const raw = await executeMikrotikCommand2(routingReadCommand(path, lists), ctx, { maxMs: 6000 });
20542
- return parseRoutingRows(raw, fields);
20543
- }
20544
- async function readRoutingAddressPage(path, ctx, offset = 0) {
20545
- if (!["/ip firewall address-list", "/ipv6 firewall address-list"].includes(path) || !Number.isSafeInteger(offset) || offset < 0 || offset > 1e6)
20546
- throw new Error("Invalid address-list page.");
20547
- const find = new Cmd(`${path} find`).build();
20548
- const get = new Cmd(`${path} get`).raw("$srId").build();
20549
- const command = `{ :local srIds [${find}]; :local srItems [:toarray ""]; :foreach srId in=[:pick $srIds ${offset} ${offset + 200}] do={ :local srRow [${get}]; :set ($srRow->".id") $srId; :set ($srItems->[:len $srItems]) $srRow; }; :put [:serialize to=json value={"rows"=$srItems;"total"=[:len $srIds]}]; }`;
20550
- const raw = await executeMikrotikCommand2(command, ctx, { maxMs: 6000 });
20551
- return parseRoutingAddressPage(raw, offset);
20552
- }
20553
- function parseRoutingAddressPage(raw, offset = 0) {
20554
- if (looksLikeError(raw) || raw.length > 1048576)
20555
- throw new Error("Address-list page could not be read safely.");
20556
- let data;
20557
- try {
20558
- data = JSON.parse(raw.trim());
20559
- } catch {
20560
- throw new Error("Invalid structured address-list page.");
20561
- }
20562
- if (!data || !Array.isArray(data.rows) || !Number.isSafeInteger(data.total) || data.total < 0)
20563
- throw new Error("Invalid address-list total.");
20564
- const rows = parseRoutingRows(JSON.stringify(data.rows)).map((r, i) => ({
20565
- ...r,
20566
- "#": String(offset + i)
20567
- }));
20568
- if (rows.length !== Math.min(200, Math.max(0, data.total - offset)) || rows.some((r) => !r[".id"]))
20569
- throw new Error("Incomplete address-list page. Refresh if the router list changed while reading.");
20570
- return {
20571
- rows,
20572
- total: data.total,
20573
- nextOffset: offset + rows.length < data.total ? offset + rows.length : undefined
20574
- };
20575
- }
21078
+ import { randomUUID as randomUUID9 } from "crypto";
21079
+ import { isIP as isIP3 } from "net";
20576
21080
 
20577
21081
  // src/service-routing/inventory.ts
20578
21082
  var routingSections = {
@@ -20648,60 +21152,6 @@ function createRoutingInventoryReader(read = readRoutingRows, addresses = readRo
20648
21152
  var routerRoutingInventory = createRoutingInventoryReader();
20649
21153
  onConfigChanged(() => routerRoutingInventory.clear());
20650
21154
 
20651
- // src/operations/store.ts
20652
- import { mkdirSync as mkdirSync10, chmodSync } from "fs";
20653
- import { dirname as dirname11, join as join6 } from "path";
20654
- class OperationsStore {
20655
- db;
20656
- constructor(db) {
20657
- this.db = db;
20658
- db.run("PRAGMA busy_timeout = 3000");
20659
- db.run("CREATE TABLE IF NOT EXISTS workspace_records (kind TEXT, id TEXT, device TEXT, updated INTEGER, body TEXT, PRIMARY KEY(kind,id))");
20660
- db.run("CREATE INDEX IF NOT EXISTS workspace_device ON workspace_records(kind,device,updated DESC)");
20661
- db.run("CREATE TABLE IF NOT EXISTS workspace_locks (device TEXT PRIMARY KEY, owner TEXT NOT NULL)");
20662
- }
20663
- get(kind, id, device) {
20664
- const row = this.db.query("SELECT body FROM workspace_records WHERE kind=? AND id=? AND device=?").get(kind, id, device);
20665
- return row ? JSON.parse(row.body) : undefined;
20666
- }
20667
- list(kind, device, limit = 100) {
20668
- return this.db.query("SELECT body FROM workspace_records WHERE kind=? AND device=? ORDER BY updated DESC LIMIT ?").all(kind, device, Math.min(500, limit)).map((r) => JSON.parse(r.body));
20669
- }
20670
- put(kind, record) {
20671
- this.db.query("INSERT INTO workspace_records VALUES (?,?,?,?,?) ON CONFLICT(kind,id) DO UPDATE SET updated=excluded.updated,body=excluded.body WHERE device=excluded.device").run(kind, record.id, record.device, record.updatedAt, JSON.stringify(record));
20672
- }
20673
- delete(kind, id, device) {
20674
- this.db.query("DELETE FROM workspace_records WHERE kind=? AND id=? AND device=?").run(kind, id, device);
20675
- }
20676
- prune(kind, device, before) {
20677
- this.db.query("DELETE FROM workspace_records WHERE kind=? AND device=? AND updated<?").run(kind, device, before);
20678
- }
20679
- lock(device, owner) {
20680
- const result = this.db.query("INSERT OR IGNORE INTO workspace_locks VALUES (?,?)").run(device, owner);
20681
- if (!result.changes)
20682
- throw new Error("Another workspace operation holds this router. An interrupted operation requires reconciliation before retrying.");
20683
- }
20684
- unlock(device, owner) {
20685
- this.db.query("DELETE FROM workspace_locks WHERE device=? AND owner=?").run(device, owner);
20686
- }
20687
- }
20688
- var pending5;
20689
- function operationsStore() {
20690
- pending5 ??= (async () => {
20691
- const path = join6(dirname11(DEFAULT_SNAPSHOT_DB2), "operations.db");
20692
- mkdirSync10(dirname11(path), { recursive: true, mode: 448 });
20693
- const { Database } = await import("bun:sqlite");
20694
- const db = new Database(path, { create: true });
20695
- chmodSync(path, 384);
20696
- db.run("PRAGMA journal_mode = WAL");
20697
- return new OperationsStore(db);
20698
- })().catch((error) => {
20699
- pending5 = undefined;
20700
- throw error;
20701
- });
20702
- return pending5;
20703
- }
20704
-
20705
21155
  // src/service-routing/traffic.ts
20706
21156
  function trafficCommand(policy) {
20707
21157
  const path = `${routingPath(policy.family)} mangle`;
@@ -20774,13 +21224,13 @@ async function readPolicyTraffic(policy, ctx) {
20774
21224
 
20775
21225
  // src/service-routing/service.ts
20776
21226
  var kind = "service-routing";
20777
- function access(ctx, tool, write = false) {
21227
+ function access2(ctx, tool, write = false) {
20778
21228
  const device = resolveDeviceName2(ctx.device);
20779
21229
  assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
20780
21230
  return device;
20781
21231
  }
20782
21232
  async function locked(device, work) {
20783
- const store = await operationsStore(), owner = randomUUID8();
21233
+ const store = await operationsStore(), owner = randomUUID9();
20784
21234
  store.lock(device, owner);
20785
21235
  try {
20786
21236
  return await work();
@@ -20794,14 +21244,14 @@ async function routingPolicy(id, device) {
20794
21244
  throw new Error("Policy not found on the selected router.");
20795
21245
  return policy;
20796
21246
  }
20797
- function save(policy, message) {
21247
+ function save2(policy, message) {
20798
21248
  policy.updatedAt = Date.now();
20799
21249
  if (message)
20800
21250
  policy.history = [{ at: policy.updatedAt, message }, ...policy.history].slice(0, 100);
20801
21251
  return operationsStore().then((store) => store.put(kind, policy));
20802
21252
  }
20803
21253
  async function routingInventory(ctx) {
20804
- const device = access(ctx, "service_routing_inventory");
21254
+ const device = access2(ctx, "service_routing_inventory");
20805
21255
  const snapshot = await routerRoutingInventory.read(device, ctx);
20806
21256
  const tables = snapshot.sections.tables.rows;
20807
21257
  return {
@@ -20811,11 +21261,11 @@ async function routingInventory(ctx) {
20811
21261
  };
20812
21262
  }
20813
21263
  async function listRouting(ctx) {
20814
- const device = access(ctx, "list_service_routing");
21264
+ const device = access2(ctx, "list_service_routing");
20815
21265
  return { policies: (await operationsStore()).list(kind, device) };
20816
21266
  }
20817
21267
  async function routingAddressPage(family, offset, ctx) {
20818
- const device = access(ctx, "service_routing_address_page");
21268
+ const device = access2(ctx, "service_routing_address_page");
20819
21269
  return {
20820
21270
  device,
20821
21271
  family,
@@ -20824,7 +21274,7 @@ async function routingAddressPage(family, offset, ctx) {
20824
21274
  };
20825
21275
  }
20826
21276
  async function createRouting(input, ctx) {
20827
- const device = access(ctx, "create_service_routing", true), a = routingInput.parse(input);
21277
+ const device = access2(ctx, "create_service_routing", true), a = routingInput.parse(input);
20828
21278
  const target = a.target ? getConfig2().serviceProbes.targets[a.target] : undefined;
20829
21279
  if (a.target && (!target || target.kind !== "https"))
20830
21280
  throw new Error("Select an administrator-approved HTTPS probe alias first.");
@@ -20838,7 +21288,7 @@ async function createRouting(input, ctx) {
20838
21288
  throw new Error("Router policy limit reached (100).");
20839
21289
  const policy = {
20840
21290
  ...a,
20841
- id: randomUUID8(),
21291
+ id: randomUUID9(),
20842
21292
  device,
20843
21293
  host,
20844
21294
  probeHost: target?.host,
@@ -20847,14 +21297,14 @@ async function createRouting(input, ctx) {
20847
21297
  samples: [],
20848
21298
  history: []
20849
21299
  };
20850
- await save(policy, "Draft saved. No router changes or probes yet.");
21300
+ await save2(policy, "Draft saved. No router changes or probes yet.");
20851
21301
  return policy;
20852
21302
  }
20853
21303
  async function routingTraffic(id, ctx) {
20854
- const device = access(ctx, "service_routing_traffic");
21304
+ const device = access2(ctx, "service_routing_traffic");
20855
21305
  return readPolicyTraffic(await routingPolicy(id, device), { ...ctx, device });
20856
21306
  }
20857
- async function facts(policy, ctx) {
21307
+ async function facts2(policy, ctx) {
20858
21308
  const base = routingPath(policy.family);
20859
21309
  const tables = await readRoutingRows("/routing table", "name,fib,disabled", ctx);
20860
21310
  const routes = await readRoutingRows(policy.family === "ipv4" ? "/ip route" : "/ipv6 route", "routing-table,dst-address,gateway,active,disabled,blackhole,type", ctx);
@@ -20891,7 +21341,7 @@ async function probe(policy, ctx) {
20891
21341
  if (addresses.some((a) => !addressAllowed(a, target.addresses)))
20892
21342
  addresses = [];
20893
21343
  } catch {}
20894
- const address = addresses.find((a) => isIP2(a) === (policy.family === "ipv4" ? 4 : 6));
21344
+ const address = addresses.find((a) => isIP3(a) === (policy.family === "ipv4" ? 4 : 6));
20895
21345
  for (const table of policy.tables) {
20896
21346
  const sample = {
20897
21347
  table,
@@ -20928,10 +21378,10 @@ async function probe(policy, ctx) {
20928
21378
  policy.samples.push(sample);
20929
21379
  }
20930
21380
  policy.samples = policy.samples.slice(-180);
20931
- await save(policy);
21381
+ await save2(policy);
20932
21382
  }
20933
21383
  async function probeRouting(id, ctx) {
20934
- const device = access(ctx, "probe_service_routing");
21384
+ const device = access2(ctx, "probe_service_routing");
20935
21385
  return locked(device, async () => {
20936
21386
  const policy = await routingPolicy(id, device);
20937
21387
  await probe(policy, ctx);
@@ -20939,9 +21389,9 @@ async function probeRouting(id, ctx) {
20939
21389
  });
20940
21390
  }
20941
21391
  async function preview(policy, table, remove, ctx) {
20942
- const snapshot = await facts(policy, ctx);
21392
+ const snapshot = await facts2(policy, ctx);
20943
21393
  policy.plan = {
20944
- id: randomUUID8(),
21394
+ id: randomUUID9(),
20945
21395
  table,
20946
21396
  remove,
20947
21397
  expiresAt: Date.now() + 120000,
@@ -20957,19 +21407,19 @@ async function preview(policy, table, remove, ctx) {
20957
21407
  ] : []
20958
21408
  ]
20959
21409
  };
20960
- await save(policy, "Preview created. Review scope and commands; valid for two minutes.");
21410
+ await save2(policy, "Preview created. Review scope and commands; valid for two minutes.");
20961
21411
  return policy;
20962
21412
  }
20963
21413
  async function previewRouting(id, table, remove, ctx) {
20964
- const device = access(ctx, "preview_service_routing");
21414
+ const device = access2(ctx, "preview_service_routing");
20965
21415
  return locked(device, async () => preview(await routingPolicy(id, device), table, remove, ctx));
20966
21416
  }
20967
21417
  async function apply(policy, planId, ctx) {
20968
21418
  const plan = policy.plan;
20969
21419
  if (!plan || plan.id !== planId || plan.expiresAt < Date.now())
20970
21420
  throw new Error("Preview expired or changed. Preview again before confirming.");
20971
- access(ctx, "apply_service_routing", true);
20972
- if (fingerprint(await facts(policy, ctx)) !== plan.fingerprint)
21421
+ access2(ctx, "apply_service_routing", true);
21422
+ if (fingerprint(await facts2(policy, ctx)) !== plan.fingerprint)
20973
21423
  throw new Error("Router configuration changed after preview.");
20974
21424
  const safe = getSafeModeManager2(policy.device);
20975
21425
  if (safe.isActive)
@@ -20977,17 +21427,17 @@ async function apply(policy, planId, ctx) {
20977
21427
  policy.snapshot = await captureSnapshot(ctx, `Before service route ${policy.name}`, true);
20978
21428
  policy.state = "uncertain";
20979
21429
  policy.armedUntil = undefined;
20980
- await save(policy, "Apply started; outcome must be read back before being considered active.");
21430
+ await save2(policy, "Apply started; outcome must be read back before being considered active.");
20981
21431
  let owned = false, commitAttempted = false;
20982
21432
  try {
20983
21433
  if (!(await safe.enable()).startsWith("Safe mode ENABLED"))
20984
21434
  throw new Error("Could not acquire Safe Mode.");
20985
21435
  owned = true;
20986
- if (fingerprint(await facts(policy, ctx)) !== plan.fingerprint)
21436
+ if (fingerprint(await facts2(policy, ctx)) !== plan.fingerprint)
20987
21437
  throw new Error("Router changed while entering Safe Mode.");
20988
21438
  for (const command of plan.commands)
20989
21439
  await checkedRead(command, ctx);
20990
- const after = await facts(policy, ctx);
21440
+ const after = await facts2(policy, ctx);
20991
21441
  const matched = after.mangle.filter((r) => r.comment === ownerTag(policy.id));
20992
21442
  if (plan.remove ? matched.length !== 0 : matched.filter((r) => r.action === "mark-routing" && r["new-routing-mark"] === plan.table && enabled3(r)).length !== 1)
20993
21443
  throw new Error("Router read-back did not match this preview.");
@@ -21009,26 +21459,26 @@ async function apply(policy, planId, ctx) {
21009
21459
  policy.lastSwitchAt = Date.now();
21010
21460
  policy.plan = undefined;
21011
21461
  policy.error = undefined;
21012
- await save(policy, plan.remove ? "Owned routing policy removed." : `Routing read-back verified: ${plan.table}. Client delivery still requires a client check.`);
21462
+ await save2(policy, plan.remove ? "Owned routing policy removed." : `Routing read-back verified: ${plan.table}. Client delivery still requires a client check.`);
21013
21463
  routerRoutingInventory.clear();
21014
21464
  } catch (error) {
21015
21465
  routerRoutingInventory.clear();
21016
21466
  if (owned && !commitAttempted)
21017
21467
  await safe.rollback().catch(() => {});
21018
21468
  policy.error = error instanceof Error ? error.message : "Apply failed";
21019
- await save(policy, "Apply not confirmed; automation stopped. Inspect the saved backup and router state.");
21469
+ await save2(policy, "Apply not confirmed; automation stopped. Inspect the saved backup and router state.");
21020
21470
  throw error;
21021
21471
  }
21022
21472
  return policy;
21023
21473
  }
21024
21474
  async function applyRouting(id, planId, confirm, ctx) {
21025
- const device = access(ctx, "apply_service_routing", true);
21475
+ const device = access2(ctx, "apply_service_routing", true);
21026
21476
  if (!confirm)
21027
21477
  throw new Error("Explicit confirmation of the exact preview is required.");
21028
21478
  return locked(device, async () => apply(await routingPolicy(id, device), planId, ctx));
21029
21479
  }
21030
21480
  async function armRouting(id, minutes, confirm, ctx) {
21031
- const device = access(ctx, "arm_service_routing", true);
21481
+ const device = access2(ctx, "arm_service_routing", true);
21032
21482
  if (!confirm)
21033
21483
  throw new Error("Confirm the time-limited automatic failover authorization.");
21034
21484
  if (!Number.isInteger(minutes) || minutes < 0 || minutes > 60)
@@ -21048,7 +21498,7 @@ async function armRouting(id, minutes, confirm, ctx) {
21048
21498
  throw new Error("Every authorized exit needs a fresh passing VRF probe before arming.");
21049
21499
  }
21050
21500
  policy.armedUntil = minutes ? Date.now() + minutes * 60000 : undefined;
21051
- await save(policy, minutes ? `Automatic failover authorized for ${minutes} minutes, only between the saved exits.` : "Automatic failover paused; the current route stays in place.");
21501
+ await save2(policy, minutes ? `Automatic failover authorized for ${minutes} minutes, only between the saved exits.` : "Automatic failover paused; the current route stays in place.");
21052
21502
  return policy;
21053
21503
  });
21054
21504
  }
@@ -21212,7 +21662,7 @@ function freezeFlight(record, title, trigger, now) {
21212
21662
  // src/flight-recorder/service.ts
21213
21663
  var kind2 = "flight-recorder";
21214
21664
  var queues = new Map;
21215
- function access2(ctx, tool, write = false) {
21665
+ function access3(ctx, tool, write = false) {
21216
21666
  const device = resolveDeviceName2(ctx.device);
21217
21667
  assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
21218
21668
  return device;
@@ -21241,7 +21691,7 @@ async function edit(device, work) {
21241
21691
  }
21242
21692
  }
21243
21693
  async function getFlight(ctx) {
21244
- const device = access2(ctx, "get_flight_recorder");
21694
+ const device = access3(ctx, "get_flight_recorder");
21245
21695
  return {
21246
21696
  recorder: trimFlight(await record2(device), Date.now()),
21247
21697
  toolEventsAvailable: isRecording(),
@@ -21253,7 +21703,7 @@ async function getFlight(ctx) {
21253
21703
  };
21254
21704
  }
21255
21705
  async function configureFlight(input, ctx) {
21256
- const device = access2(ctx, "configure_flight_recorder", true), a = recorderInput.parse(input);
21706
+ const device = access3(ctx, "configure_flight_recorder", true), a = recorderInput.parse(input);
21257
21707
  await edit(device, async (r) => {
21258
21708
  Object.assign(r, a);
21259
21709
  r.error = undefined;
@@ -21261,7 +21711,7 @@ async function configureFlight(input, ctx) {
21261
21711
  return getFlight(ctx);
21262
21712
  }
21263
21713
  async function freezeIncident(title, ctx) {
21264
- const device = access2(ctx, "freeze_network_incident", true);
21714
+ const device = access3(ctx, "freeze_network_incident", true);
21265
21715
  if (!title.trim() || title.length > 120)
21266
21716
  throw new Error("Use a 1\u2013120 character incident title.");
21267
21717
  await edit(device, async (r) => {
@@ -21270,7 +21720,7 @@ async function freezeIncident(title, ctx) {
21270
21720
  return getFlight(ctx);
21271
21721
  }
21272
21722
  async function exportIncident(id, ctx) {
21273
- const device = access2(ctx, "export_network_incident"), r = await record2(device);
21723
+ const device = access3(ctx, "export_network_incident"), r = await record2(device);
21274
21724
  const incident = trimFlight(r, Date.now()).incidents.find((i) => i.id === id);
21275
21725
  if (!incident)
21276
21726
  throw new Error("Incident not found on the selected router or retention expired.");
@@ -21329,7 +21779,7 @@ var flightRecorderTools = [
21329
21779
  ];
21330
21780
 
21331
21781
  // src/recovery-lab/model.ts
21332
- import { createHash as createHash6 } from "crypto";
21782
+ import { createHash as createHash8 } from "crypto";
21333
21783
  var rosVersion = string().regex(/^7\.\d+(?:\.\d+)?(?:beta\d+|rc\d+)?$/);
21334
21784
  var recoveryInput = object({
21335
21785
  snapshotId: string().min(1).max(100),
@@ -21375,7 +21825,7 @@ var resultSchema = object({
21375
21825
  elapsedMs: number().int().min(0).max(3600000).optional(),
21376
21826
  cleanup: _enum(["pending", "destroyed", "failed"])
21377
21827
  });
21378
- var sha256 = (value) => createHash6("sha256").update(value).digest("hex");
21828
+ var sha256 = (value) => createHash8("sha256").update(value).digest("hex");
21379
21829
  var FIELDS = {
21380
21830
  "/interface/bridge": ["name", "protocol-mode", "vlan-filtering", "pvid", "disabled"],
21381
21831
  "/interface/vlan": ["name", "interface", "vlan-id", "disabled"],
@@ -21565,13 +22015,13 @@ async function callRunner(method, path, body) {
21565
22015
 
21566
22016
  // src/recovery-lab/service.ts
21567
22017
  var kind3 = "recovery-lab";
21568
- function access3(ctx, tool, write = false) {
22018
+ function access4(ctx, tool, write = false) {
21569
22019
  const device = resolveDeviceName2(ctx.device);
21570
22020
  assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
21571
22021
  return device;
21572
22022
  }
21573
22023
  async function getRecovery(ctx) {
21574
- const device = access3(ctx, "get_recovery_lab");
22024
+ const device = access4(ctx, "get_recovery_lab");
21575
22025
  let configured = false, configurationError;
21576
22026
  try {
21577
22027
  configured = !!runnerConfig();
@@ -21585,7 +22035,7 @@ async function getRecovery(ctx) {
21585
22035
  };
21586
22036
  }
21587
22037
  async function recoveryInventory(ctx) {
21588
- const device = access3(ctx, "recovery_lab_inventory"), store = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
22038
+ const device = access4(ctx, "recovery_lab_inventory"), store = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
21589
22039
  try {
21590
22040
  const snapshots = store.list(device, 50).map((s) => ({ id: s.id, at: s.ts, label: s.label, version: s.rosVersion }));
21591
22041
  const cfg = runnerConfig();
@@ -21598,7 +22048,7 @@ async function recoveryInventory(ctx) {
21598
22048
  }
21599
22049
  }
21600
22050
  async function prepareRecovery(input, ctx) {
21601
- const device = access3(ctx, "prepare_recovery_lab", true), a = recoveryInput.parse(input);
22051
+ const device = access4(ctx, "prepare_recovery_lab", true), a = recoveryInput.parse(input);
21602
22052
  const snapshots = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
21603
22053
  try {
21604
22054
  const source = snapshots.get(a.snapshotId);
@@ -21651,7 +22101,7 @@ async function editRun(id, device, work) {
21651
22101
  store.unlock(`lab:${device}`, owner);
21652
22102
  }
21653
22103
  }
21654
- async function save2(run) {
22104
+ async function save3(run) {
21655
22105
  run.updatedAt = Date.now();
21656
22106
  (await operationsStore()).put(kind3, run);
21657
22107
  }
@@ -21661,7 +22111,7 @@ function boundRunner(run) {
21661
22111
  throw new Error("Runner changed or is unavailable. Never send an existing rehearsal to a different destination.");
21662
22112
  }
21663
22113
  async function startRecovery(id, confirm, ctx) {
21664
- const device = access3(ctx, "start_recovery_lab", true);
22114
+ const device = access4(ctx, "start_recovery_lab", true);
21665
22115
  if (!confirm)
21666
22116
  throw new Error("Explicit confirmation is required to send the reviewed subset to the configured isolated runner.");
21667
22117
  return editRun(id, device, async (run) => {
@@ -21705,7 +22155,7 @@ async function startRecovery(id, confirm, ctx) {
21705
22155
  run.requestSha256 = sha256(JSON.stringify(request));
21706
22156
  run.startedAt = Date.now();
21707
22157
  run.state = "uncertain";
21708
- await save2(run);
22158
+ await save3(run);
21709
22159
  try {
21710
22160
  const result = validateRunnerResult(await callRunner("PUT", `/v1/runs/${run.id}`, {
21711
22161
  ...request,
@@ -21717,12 +22167,12 @@ async function startRecovery(id, confirm, ctx) {
21717
22167
  } catch {
21718
22168
  run.error = "Submission outcome is uncertain. Poll this run ID before any further action; no automatic retry was attempted.";
21719
22169
  }
21720
- await save2(run);
22170
+ await save3(run);
21721
22171
  return run;
21722
22172
  });
21723
22173
  }
21724
22174
  async function pollRecovery(id, ctx) {
21725
- const device = access3(ctx, "poll_recovery_lab");
22175
+ const device = access4(ctx, "poll_recovery_lab");
21726
22176
  return editRun(id, device, async (run) => {
21727
22177
  if (!run.requestSha256)
21728
22178
  throw new Error("This rehearsal has not been submitted.");
@@ -21736,12 +22186,12 @@ async function pollRecovery(id, ctx) {
21736
22186
  run.state = "uncertain";
21737
22187
  run.error = "Runner evidence unavailable or mismatched. Last-known results retained, not treated as fresh.";
21738
22188
  }
21739
- await save2(run);
22189
+ await save3(run);
21740
22190
  return run;
21741
22191
  });
21742
22192
  }
21743
22193
  async function destroyRecovery(id, confirm, ctx) {
21744
- const device = access3(ctx, "destroy_recovery_lab", true);
22194
+ const device = access4(ctx, "destroy_recovery_lab", true);
21745
22195
  if (!confirm)
21746
22196
  throw new Error("Confirm deletion of this disposable lab only.");
21747
22197
  return editRun(id, device, async (run) => {
@@ -21749,7 +22199,7 @@ async function destroyRecovery(id, confirm, ctx) {
21749
22199
  throw new Error("This rehearsal has not been submitted.");
21750
22200
  boundRunner(run);
21751
22201
  run.state = "uncertain";
21752
- await save2(run);
22202
+ await save3(run);
21753
22203
  try {
21754
22204
  const result = validateRunnerResult(await callRunner("DELETE", `/v1/runs/${run.id}`), run);
21755
22205
  run.result = result;
@@ -21760,7 +22210,7 @@ async function destroyRecovery(id, confirm, ctx) {
21760
22210
  } catch {
21761
22211
  run.error = "Lab cleanup is not confirmed. Inspect the runner and poll this ID; production routers were not contacted.";
21762
22212
  }
21763
- await save2(run);
22213
+ await save3(run);
21764
22214
  return run;
21765
22215
  });
21766
22216
  }
@@ -26605,13 +27055,13 @@ var containerTools = [
26605
27055
  ];
26606
27056
 
26607
27057
  // src/core/firewall-audit.ts
26608
- import * as ipaddr3 from "ipaddr.js";
27058
+ import * as ipaddr4 from "ipaddr.js";
26609
27059
 
26610
27060
  // src/schedule/identity.ts
26611
- import { createHash as createHash7 } from "crypto";
27061
+ import { createHash as createHash9 } from "crypto";
26612
27062
  function stableId(prefix, parts) {
26613
27063
  const material = parts.filter((p) => p !== undefined && p !== "").map((p) => String(p).trim().toLowerCase()).join(" | ");
26614
- const digest = createHash7("sha256").update(material, "utf8").digest("hex").slice(0, 12);
27064
+ const digest = createHash9("sha256").update(material, "utf8").digest("hex").slice(0, 12);
26615
27065
  return `${prefix}:${digest}`;
26616
27066
  }
26617
27067
  function ruleFingerprint(rule) {
@@ -26724,8 +27174,8 @@ function rulesFromRows(rows) {
26724
27174
  function toCidr(value) {
26725
27175
  try {
26726
27176
  if (value.includes("/"))
26727
- return ipaddr3.parseCIDR(value);
26728
- const addr = ipaddr3.parse(value);
27177
+ return ipaddr4.parseCIDR(value);
27178
+ const addr = ipaddr4.parse(value);
26729
27179
  return [addr, addr.kind() === "ipv6" ? 128 : 32];
26730
27180
  } catch {
26731
27181
  return null;
@@ -27561,7 +28011,7 @@ var cache3 = null;
27561
28011
  async function gateway() {
27562
28012
  if (cache3)
27563
28013
  return cache3;
27564
- const { moduleCatalog } = await import("./library-9ygb3vgn.js");
28014
+ const { moduleCatalog } = await import("./library-3wpdmsen.js");
27565
28015
  const forIndex = [];
27566
28016
  const byName = new Map;
27567
28017
  for (const mod of moduleCatalog) {
@@ -31106,6 +31556,178 @@ var policyTools = [
31106
31556
  })
31107
31557
  ];
31108
31558
 
31559
+ // src/sim/verify.ts
31560
+ var verificationSchema = object({
31561
+ config_text: string().min(1).max(200000),
31562
+ source: string().max(64),
31563
+ destination: string().max(64),
31564
+ source_ports: string().max(64).default("0-65535"),
31565
+ destination_ports: string().max(64).default("0-65535"),
31566
+ protocol: _enum(["tcp", "udp"]).default("tcp"),
31567
+ chain: _enum(["input", "forward", "output"]).default("forward"),
31568
+ in_interface: string().max(128).default("bridge"),
31569
+ out_interface: string().max(128).default("ether1"),
31570
+ connection_state: _enum(["new", "established", "related", "invalid"]).default("new"),
31571
+ expect: _enum(["accept", "drop", "reject"]).default("drop")
31572
+ });
31573
+ var SCOPE = "IPv4 filter-chain entry only; declared interfaces/state; static export. Not end-to-end reachability or NAT/routing verification.";
31574
+ var MAX_CELLS = 4096;
31575
+ var ALLOWED = new Set([
31576
+ "chain",
31577
+ "action",
31578
+ "disabled",
31579
+ "comment",
31580
+ "log",
31581
+ "log-prefix",
31582
+ "jump-target",
31583
+ "reject-with",
31584
+ "src-address",
31585
+ "dst-address",
31586
+ "src-address-list",
31587
+ "dst-address-list",
31588
+ "src-port",
31589
+ "dst-port",
31590
+ "port",
31591
+ "protocol",
31592
+ "in-interface",
31593
+ "out-interface",
31594
+ "connection-state"
31595
+ ]);
31596
+ function addressRange(text) {
31597
+ if (text.includes("-")) {
31598
+ const parts = text.split("-");
31599
+ const lo = parseIp(parts[0]);
31600
+ const hi = parseIp(parts[1] ?? "");
31601
+ if (parts.length === 2 && lo !== null && hi !== null && lo <= hi)
31602
+ return [lo, hi];
31603
+ } else if (/^\d+\.\d+\.\d+\.\d+(\/\d{1,2})?$/.test(text)) {
31604
+ const cidr = parseCidr(text);
31605
+ if (cidr)
31606
+ return [cidr.network, cidr.network + 2 ** (32 - cidr.prefix) - 1];
31607
+ }
31608
+ throw new Error(`Unsupported IPv4 address/range: ${text}`);
31609
+ }
31610
+ function portRange(text) {
31611
+ if (!/^\d+(?:-\d+)?$/.test(text))
31612
+ throw new Error(`Invalid port range: ${text}`);
31613
+ const [lo, end] = text.split("-").map(Number);
31614
+ const hi = end ?? lo;
31615
+ if (lo > hi || hi > 65535)
31616
+ throw new Error(`Invalid port range: ${text}`);
31617
+ return [lo, hi];
31618
+ }
31619
+ function representatives(scope, boundaries) {
31620
+ const points = new Set([scope[0]]);
31621
+ for (const [lo, hi] of boundaries) {
31622
+ if (lo > scope[0] && lo <= scope[1])
31623
+ points.add(lo);
31624
+ if (hi + 1 > scope[0] && hi + 1 <= scope[1])
31625
+ points.add(hi + 1);
31626
+ }
31627
+ return [...points].sort((a, b) => a - b);
31628
+ }
31629
+ function verifyPolicy(input) {
31630
+ const a = verificationSchema.parse(input);
31631
+ const result = {
31632
+ status: "unknown",
31633
+ scope: SCOPE,
31634
+ reason: "",
31635
+ cells: 0,
31636
+ checked: 0
31637
+ };
31638
+ try {
31639
+ const source = addressRange(a.source);
31640
+ const destination = addressRange(a.destination);
31641
+ const sourcePorts = portRange(a.source_ports);
31642
+ const destinationPorts = portRange(a.destination_ports);
31643
+ const parsed = parseExport(a.config_text);
31644
+ if (parsed.unparsed.length)
31645
+ throw new Error("Export contains unparsed lines.");
31646
+ const filter = recordsOf(parsed, "/ip/firewall/filter");
31647
+ if (!filter.length)
31648
+ throw new Error("No filter rules in supplied export; completeness cannot be established.");
31649
+ if (filter.length > 256)
31650
+ throw new Error("More than 256 filter rules; narrow the supplied model.");
31651
+ const model = buildModel(a.config_text);
31652
+ const lists = recordsOf(parsed, "/ip/firewall/address-list");
31653
+ const src = [], dst = [], sp = [], dp = [];
31654
+ for (const rule of filter) {
31655
+ if (rule.op !== "add")
31656
+ throw new Error(`Only exported add rules supported (line ${rule.line}).`);
31657
+ if (["yes", "true"].includes(rule.fields.disabled))
31658
+ continue;
31659
+ for (const [field, raw] of Object.entries(rule.fields)) {
31660
+ if (!ALLOWED.has(field))
31661
+ throw new Error(`Unsupported ${field} at line ${rule.line}.`);
31662
+ const value = raw.replace(/^!/, "");
31663
+ if (field === "action" && !["accept", "drop", "reject", "jump", "return", "log", "passthrough"].includes(value))
31664
+ throw new Error(`Unsupported action ${value} at line ${rule.line}.`);
31665
+ if (field === "src-address" || field === "dst-address")
31666
+ (field === "src-address" ? src : dst).push(addressRange(value));
31667
+ if (field === "src-address-list" || field === "dst-address-list") {
31668
+ const members = lists.filter((r) => r.fields.list === value);
31669
+ if (!members.length)
31670
+ throw new Error(`List ${value} is absent; dynamic membership cannot be proven.`);
31671
+ for (const member of members) {
31672
+ if (member.op !== "add" || member.fields.timeout || member.fields.dynamic)
31673
+ throw new Error(`List ${value} has non-static membership.`);
31674
+ (field === "src-address-list" ? src : dst).push(addressRange(member.fields.address ?? ""));
31675
+ }
31676
+ }
31677
+ if (["src-port", "dst-port", "port"].includes(field)) {
31678
+ const ranges = value.split(",").map(portRange);
31679
+ if (field !== "dst-port")
31680
+ sp.push(...ranges);
31681
+ if (field !== "src-port")
31682
+ dp.push(...ranges);
31683
+ }
31684
+ }
31685
+ }
31686
+ const axes = [
31687
+ representatives(source, src),
31688
+ representatives(destination, dst),
31689
+ representatives(sourcePorts, sp),
31690
+ representatives(destinationPorts, dp)
31691
+ ];
31692
+ result.cells = axes.reduce((n, axis) => n * axis.length, 1);
31693
+ if (result.cells > MAX_CELLS)
31694
+ throw new Error(`Analysis requires ${result.cells} cells; limit is ${MAX_CELLS}. Narrow the scope.`);
31695
+ for (const s of axes[0])
31696
+ for (const d of axes[1])
31697
+ for (const p of axes[2])
31698
+ for (const q of axes[3]) {
31699
+ const packet = {
31700
+ srcAddress: formatIp(s),
31701
+ dstAddress: formatIp(d),
31702
+ srcPort: p,
31703
+ dstPort: q,
31704
+ protocol: a.protocol,
31705
+ inInterface: a.in_interface,
31706
+ outInterface: a.out_interface,
31707
+ connectionState: a.connection_state
31708
+ };
31709
+ const trace = traverseChain(model, model.filter, a.chain, packet);
31710
+ result.checked++;
31711
+ if (trace.verdict !== a.expect) {
31712
+ return {
31713
+ ...result,
31714
+ status: trace.verdict === "unknown" ? "unknown" : "violated",
31715
+ reason: `Expected ${a.expect}; model returned ${trace.verdict}.`,
31716
+ witness: packet,
31717
+ trace: trace.steps
31718
+ };
31719
+ }
31720
+ }
31721
+ return {
31722
+ ...result,
31723
+ status: "proved",
31724
+ reason: `All ${result.cells} equivalence cells satisfy ${a.expect} within the stated filter-only model.`
31725
+ };
31726
+ } catch (error) {
31727
+ return { ...result, reason: error instanceof Error ? error.message : String(error) };
31728
+ }
31729
+ }
31730
+
31109
31731
  // src/tools/simulate.ts
31110
31732
  var storePromise8 = null;
31111
31733
  function snapshots4() {
@@ -31169,6 +31791,16 @@ A packet whose path crosses one of these is reported UNKNOWN.`;
31169
31791
  }
31170
31792
  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.";
31171
31793
  var simulateTools = [
31794
+ defineTool2({
31795
+ name: "verify_filter_policy",
31796
+ title: "Verify a Filter Policy over Address and Port Sets",
31797
+ annotations: READ,
31798
+ 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.",
31799
+ inputSchema: verificationSchema.shape,
31800
+ handler(a) {
31801
+ return JSON.stringify(verifyPolicy(a), null, 2);
31802
+ }
31803
+ }),
31172
31804
  defineTool2({
31173
31805
  name: "simulate_packet",
31174
31806
  title: "Simulate a Packet",
@@ -39211,11 +39843,11 @@ ${result}`;
39211
39843
  ];
39212
39844
 
39213
39845
  // src/core/ip-intelligence.ts
39214
- import { isIP as isIP4 } from "net";
39215
- import ipaddr4 from "ipaddr.js";
39846
+ import { isIP as isIP5 } from "net";
39847
+ import ipaddr5 from "ipaddr.js";
39216
39848
 
39217
39849
  // src/observability/geo.ts
39218
- import { BlockList, isIP as isIP3 } from "net";
39850
+ import { BlockList, isIP as isIP4 } from "net";
39219
39851
  // src/data/iran-asns.json
39220
39852
  var iran_asns_default = {
39221
39853
  source: "https://whois.ipip.net/iso/IR",
@@ -41602,14 +42234,14 @@ nonPublic.addSubnet("fc00::", 7, "ipv6");
41602
42234
  nonPublic.addSubnet("fe80::", 10, "ipv6");
41603
42235
  nonPublic.addSubnet("ff00::", 8, "ipv6");
41604
42236
  function isPublicIpLiteral(host) {
41605
- const version = isIP3(host);
42237
+ const version = isIP4(host);
41606
42238
  return version !== 0 && !nonPublic.check(host, version === 6 ? "ipv6" : "ipv4");
41607
42239
  }
41608
42240
  var ipCache = new Map;
41609
42241
 
41610
42242
  // src/core/ip-intelligence.ts
41611
42243
  var IpIntelligenceInput = object({
41612
- ip: string().trim().max(64).refine((ip) => isIP4(ip) !== 0, "Enter an IPv4 or IPv6 literal, not a hostname, URL, port or CIDR")
42244
+ ip: string().trim().max(64).refine((ip) => isIP5(ip) !== 0, "Enter an IPv4 or IPv6 literal, not a hostname, URL, port or CIDR")
41613
42245
  });
41614
42246
  var cache5 = new Map;
41615
42247
  var active3 = 0;
@@ -41666,10 +42298,10 @@ async function provider(url) {
41666
42298
  }
41667
42299
  async function lookupIpIntelligence(input) {
41668
42300
  const { ip: literal } = IpIntelligenceInput.parse(input);
41669
- const ip = ipaddr4.parse(literal).toString();
42301
+ const ip = ipaddr5.parse(literal).toString();
41670
42302
  const base = {
41671
42303
  ip,
41672
- version: isIP4(ip),
42304
+ version: isIP5(ip),
41673
42305
  public: isPublicIpLiteral(ip),
41674
42306
  lookedUpAt: Date.now(),
41675
42307
  cached: false,
@@ -43331,7 +43963,7 @@ var wolTools = [
43331
43963
  ];
43332
43964
 
43333
43965
  // src/core/openvpn-sessions.ts
43334
- import { randomUUID as randomUUID9 } from "crypto";
43966
+ import { randomUUID as randomUUID10 } from "crypto";
43335
43967
 
43336
43968
  // src/core/openvpn-sessions-model.ts
43337
43969
  function openVpnUptime(value) {
@@ -43365,7 +43997,7 @@ var disconnectOpenVpnInput = object({
43365
43997
  token: string().uuid().describe("Fresh disconnectToken from list_ovpn_sessions on this router; expires after 60 seconds and is single-use."),
43366
43998
  confirm: literal(true).describe("Explicit operator approval to terminate this one live connection. The client can reconnect.")
43367
43999
  });
43368
- function access4(ctx, write = false) {
44000
+ function access5(ctx, write = false) {
43369
44001
  if (!ctx.device)
43370
44002
  throw new OpenVpnOperationError(400, "Select an explicit router first.");
43371
44003
  let device;
@@ -43431,10 +44063,10 @@ async function read(ctx) {
43431
44063
  return parseOpenVpnSessions(output);
43432
44064
  }
43433
44065
  async function listOpenVpnSessions(ctx) {
43434
- const device = access4(ctx);
44066
+ const device = access5(ctx);
43435
44067
  let canDisconnect = true;
43436
44068
  try {
43437
- access4(ctx, true);
44069
+ access5(ctx, true);
43438
44070
  } catch {
43439
44071
  canDisconnect = false;
43440
44072
  }
@@ -43456,7 +44088,7 @@ async function listOpenVpnSessions(ctx) {
43456
44088
  continue;
43457
44089
  if (tickets.size >= 1e4)
43458
44090
  tickets.delete(tickets.keys().next().value);
43459
- session.disconnectToken = randomUUID9();
44091
+ session.disconnectToken = randomUUID10();
43460
44092
  tickets.set(session.disconnectToken, { device, at, session });
43461
44093
  }
43462
44094
  next.expires = at + 2000;
@@ -43486,7 +44118,7 @@ function disconnectOpenVpnCommand(session) {
43486
44118
  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" } } }`;
43487
44119
  }
43488
44120
  async function disconnectOpenVpnSession(input, ctx) {
43489
- const device = access4(ctx, true);
44121
+ const device = access5(ctx, true);
43490
44122
  const { token } = disconnectOpenVpnInput.parse(input);
43491
44123
  const ticket = tickets.get(token);
43492
44124
  if (!ticket || ticket.device !== device || Date.now() - ticket.at >= TICKET_TTL)
@@ -52425,7 +53057,7 @@ var riskByTool = null;
52425
53057
  async function riskIndex() {
52426
53058
  if (riskByTool)
52427
53059
  return riskByTool;
52428
- const { moduleCatalog } = await import("./library-9ygb3vgn.js");
53060
+ const { moduleCatalog } = await import("./library-3wpdmsen.js");
52429
53061
  const index = new Map;
52430
53062
  for (const mod of moduleCatalog) {
52431
53063
  for (const tool of mod.tools)
@@ -54589,7 +55221,7 @@ async function readScanList(ctx, list = "port-scanners") {
54589
55221
  }
54590
55222
 
54591
55223
  // src/attack/correlate.ts
54592
- import { createHash as createHash8 } from "crypto";
55224
+ import { createHash as createHash10 } from "crypto";
54593
55225
  var STAGE_ORDER = ["recon", "attempt", "breach", "persistence"];
54594
55226
  var STAGE_OF = {
54595
55227
  "port-scan": "recon",
@@ -54619,7 +55251,7 @@ var SEVERITY_RANK = {
54619
55251
  info: 4
54620
55252
  };
54621
55253
  function incidentId(source, dayBucket) {
54622
- const digest = createHash8("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
55254
+ const digest = createHash10("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
54623
55255
  return `atk_${digest}`;
54624
55256
  }
54625
55257
  function worst(values) {
@@ -55802,11 +56434,11 @@ var serverPulseTools = [
55802
56434
  ];
55803
56435
 
55804
56436
  // src/observability/config-admin.ts
55805
- import { createHash as createHash9, randomUUID as randomUUID11 } from "crypto";
56437
+ import { createHash as createHash11, randomUUID as randomUUID12 } from "crypto";
55806
56438
  import { readFileSync as readFileSync10 } from "fs";
55807
56439
 
55808
56440
  // src/config-write.ts
55809
- import { randomUUID as randomUUID10 } from "crypto";
56441
+ import { randomUUID as randomUUID11 } from "crypto";
55810
56442
  import {
55811
56443
  closeSync,
55812
56444
  constants,
@@ -55835,7 +56467,7 @@ function backupName(path, ts) {
55835
56467
  }
55836
56468
  function atomicWrite(path, text) {
55837
56469
  mkdirSync16(dirname17(path), { recursive: true });
55838
- const tmp = `${path}.tmp-${randomUUID10()}`;
56470
+ const tmp = `${path}.tmp-${randomUUID11()}`;
55839
56471
  try {
55840
56472
  writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx", flush: true });
55841
56473
  try {
@@ -55867,7 +56499,7 @@ function writeMountedFile(path, text) {
55867
56499
  throw new Error("Configuration target must be a regular file.");
55868
56500
  fchmodSync(fd, 384);
55869
56501
  const previous = readFileSync9(fd);
55870
- const backup = `${path}.bak-mounted-${randomUUID10()}`;
56502
+ const backup = `${path}.bak-mounted-${randomUUID11()}`;
55871
56503
  writeFileSync4(backup, previous, { mode: 384, flag: "wx", flush: true });
55872
56504
  try {
55873
56505
  replaceContents(fd, Buffer.from(text, "utf8"));
@@ -55888,8 +56520,8 @@ function writeMountedFile(path, text) {
55888
56520
  function createConfigAdmin(deps) {
55889
56521
  let pending = null;
55890
56522
  let lastTimestamp = 0;
55891
- const salt = randomUUID11();
55892
- const fingerprint = (config, source, contents) => createHash9("sha256").update(salt).update(JSON.stringify([config, source, contents])).digest("hex");
56523
+ const salt = randomUUID12();
56524
+ const fingerprint = (config, source, contents) => createHash11("sha256").update(salt).update(JSON.stringify([config, source, contents])).digest("hex");
55893
56525
  const revision = () => {
55894
56526
  const source = deps.source();
55895
56527
  return fingerprint(deps.getConfig(), source, deps.readFile(source.path));
@@ -60049,7 +60681,7 @@ ${doomed}`;
60049
60681
  ];
60050
60682
 
60051
60683
  // src/core/wifi-survey.ts
60052
- import { randomUUID as randomUUID12 } from "crypto";
60684
+ import { randomUUID as randomUUID13 } from "crypto";
60053
60685
  var DONE = "MCP-SURVEY-DONE";
60054
60686
  var FAILED = "MCP-SURVEY-FAILED";
60055
60687
  var PENDING = "MCP-SURVEY-PENDING";
@@ -60058,7 +60690,7 @@ function readFile(file) {
60058
60690
  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] }`;
60059
60691
  }
60060
60692
  async function runWifiSurvey(path, iface, duration, ctx) {
60061
- const base = `mcp-wifi-survey-${randomUUID12()}`;
60693
+ const base = `mcp-wifi-survey-${randomUUID13()}`;
60062
60694
  const report = `${base}.txt`;
60063
60695
  const status = `${base}-status.txt`;
60064
60696
  const scan = new Cmd(`${path} frequency-scan`).raw(quoteValue(iface)).set("duration", `${duration}s`).set("save-file", report).build();
@@ -62425,6 +63057,13 @@ var moduleCatalog2 = [
62425
63057
  description: "Firewall address-lists (`/ip firewall address-list`).",
62426
63058
  tools: addressListTools
62427
63059
  },
63060
+ {
63061
+ label: "Address Sets",
63062
+ slug: "address-sets",
63063
+ group: "Security",
63064
+ description: "Versioned CIDR algebra, publication previews and guarded rollback of selected rule references.",
63065
+ tools: addressSetTools
63066
+ },
62428
63067
  {
62429
63068
  label: "Connected Devices",
62430
63069
  slug: "connected-devices",